Files
msgexchange-v2/src/main/kotlin/com/gzzn/omms/msgexchange/processing/BackfillService.kt
T

75 lines
3.3 KiB
Kotlin
Raw Normal View History

package com.gzzn.omms.msgexchange.processing
import com.gzzn.omms.msgexchange.config.MailboxProps
import com.gzzn.omms.msgexchange.config.PipelineProps
import com.gzzn.omms.msgexchange.infra.persistence.CminmsgInboxRepository
import com.gzzn.omms.msgexchange.infra.persistence.ProcStateRepository
import jakarta.inject.Singleton
import java.time.Clock
import java.time.Duration
import java.time.Instant
/**
* 信箱处理标记回填(docs/message-lifecycle.md §3/§4/§5.2)。
*
* 回填意图(`BACKFILL_NEXT_AT`)由处理器在终态事务内登记,与业务写入同提交同回滚,
* 因此不存在"业务已提交、待办未记"的窗口;本服务只做两件事:
* 1. [attempt]:终态提交后立即尝试一次(低延迟,失败静默留给扫描);
* 2. [sweep]:到期或已达超期期限 R 的记录批量补写(§5.2),指数退避 30s 起步、封顶 15 分钟。
*
* 回填失败绝不重放业务变更,也绝不回改终态(§11);写入侧只把空标写为已处理,
* 重复执行无副作用。
*/
@Singleton
class BackfillService(
private val procState: ProcStateRepository,
private val mailbox: CminmsgInboxRepository,
private val mailboxProps: MailboxProps,
private val props: PipelineProps,
private val clock: Clock,
) {
private val log = org.slf4j.LoggerFactory.getLogger(BackfillService::class.java)
companion object {
private val INITIAL_BACKOFF: Duration = Duration.ofSeconds(30)
private val MAX_BACKOFF: Duration = Duration.ofMinutes(15)
fun backoffDelayFor(attempts: Int): Duration {
val shift = (attempts - 1).coerceIn(0, 20)
return INITIAL_BACKOFF.multipliedBy(1L shl shift).coerceAtMost(MAX_BACKOFF)
}
}
/** 单条最佳努力回填;失败只登记退避(异常不外抛,不阻塞提交后的处理路径)。 */
fun attempt(msgId: Long, now: Instant = clock.instant()) {
record(msgId, attempts = 0, now = now)?.let {
log.warn("backfill failed msgId={} error={} (sweep will retry)", msgId, it)
}
}
/**
* 批量补写(JobRunner 每 30s 触发;重启即继续,不依赖内存状态)。
* @return 本批检查条数
*/
fun sweep(now: Instant = clock.instant()): Int {
val due = procState.findBackfillDue(now, now.minus(props.pipeline.overdueBackfill), props.pipeline.backfillBatch)
due.forEach { record(it.msgId, it.attempts, now) }
return due.size
}
/** @return 失败原因;null = 已确认标记(含"已被其他路径标记"的幂等成功) */
private fun record(msgId: Long, attempts: Int, now: Instant): String? =
try {
// 影响 0 行 = 已有标记;按幂等成功处理(§11 标记单调:不回撤、不覆盖)
mailbox.markProcessedIfUnmarked(msgId, mailboxProps.processedValue)
procState.markBackfilled(msgId, now)
null
} catch (e: Exception) {
val reason = e.message ?: e.javaClass.simpleName
runCatching {
procState.recordBackfillFailure(msgId, reason, attempts + 1, now.plus(backoffDelayFor(attempts + 1)), now)
}.onFailure { log.error("record backfill failure failed msgId={}", msgId, it) }
reason
}
}