style(backend): 清理幂等写入路径的注释

注释只保留一行级约束。
长段理由移入设计文档。
验证:go test -count=1 ./... 全绿。
This commit is contained in:
2026-10-31 00:03:53 +08:00
parent c0ab69118a
commit c210e75996
13 changed files with 50 additions and 239 deletions

View File

@@ -11,36 +11,18 @@ import (
)
const (
// hotAppliedTTL 是"这条意图已经加过分"占位的存活时间。
// 它只需要覆盖"同一事件的重复投递窗口"(重试 + 停泊重放 + 客户端重试),
// 2 小时远大于该窗口,同时又把键的数量限制在一个可估算的量级上。
// hotAppliedTTL 覆盖同一次意图的重复投递窗口。
hotAppliedTTL = 2 * time.Hour
// hotWindowTTL 是分钟窗口 ZSET 的存活时间。热榜只需要最近若干个窗口,
// 留 2 小时是为了让"跨窗口查询"和事后核对仍然可读。
hotWindowTTL = 2 * time.Hour
// hotOpTimeout 约束三次"计数往返":SetNX / ZINCRBY / EXPIRE。
// 三次 Del 是 best-effort 的缓存失效,用 context.Background(),不受它约束
// ——把删缓存也算进预算,Redis 一抖动就会让整条热度消息失败并触发重投。
hotWindowTTL = 2 * time.Hour
// hotOpTimeout 只约束 SetNX / ZINCRBY / EXPIRE 三次往返。
hotOpTimeout = 100 * time.Millisecond
)
// UpdatePopularityCache 在热榜上给某个视频加一次分(P0-4 §6.10)。
// UpdatePopularityCache 给视频的分钟窗口热度加 change。
//
// 返回值是这个函数与它前任最大的区别:原来所有错误都被 `_ =` 吞掉,导致
// 消费端的 Nack/重试分支全是死代码(P0-3 的 N2)。现在"加分失败"必须
// 上抛,让 ConsumeLoop 决定重投还是停泊——热度不是可选装饰,它是热榜的
// 唯一数据来源。
//
// 幂等由 redis 的 SETNX 占位实现,键为 hot:applied:<意图键>:
//
// - intentKey 非空时,先抢占位;抢不到说明这条意图已经加过分,直接返回
// 成功(去重是正常语义,不是错误)。
// - intentKey 为空时不去重:调用方(点赞兜底)已经保证"只有事件发不出去
// 才走到这里",在这里再去重会把真实增量吞掉。
//
// 占位必须与"加分成功"同生共死:ZINCRBY 失败而占位留下,这条增量就会被
// 永久跳过——用户只会觉得"热度不动了",比重复加分更难发现。所以失败分支
// 必须撤销占位,且撤销本身也用不受 opCtx 约束的 ctx。
// intentKey 非空时先抢 hot:applied:<intentKey> 占位,抢不到说明该意图
// 已生效,直接返回 nil。ZINCRBY 失败必须撤销占位,否则这次增量会被
// 永久跳过。
func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uint, change int64, intentKey string) error {
if cache == nil || id == 0 || change == 0 {
return nil
@@ -57,13 +39,11 @@ func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uin
return fmt.Errorf("hot cache: claim intent %q: %w", intentKey, err)
}
if !claimed {
// 这条意图已经生效过:不重复加分,也不重复失效缓存。
return nil
}
}
// 缓存失效是 best-effort:失败最多让详情页多陈旧 5 分钟(缓存 TTL),
// 不值得让整条消息重投。
// 缓存失效是 best-effort,不计入 opCtx 预算。
_ = cache.Del(context.Background(), cache.Key("video:detail:id=%d", id))
_ = cache.Del(context.Background(), cache.Key("video:entity:%d", id))
@@ -74,8 +54,6 @@ func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uin
if err := cache.ZincrBy(opCtx, windowKey, member, float64(change)); err != nil {
if marker != "" {
if delErr := cache.Del(context.Background(), marker); delErr != nil {
// 撤销失败:这条增量会被跳过。宁可留下一条明确的日志,
// 也不要假装成功——人工可以按 hot:applied:<K> 清理。
log.Printf("hot cache: revoke intent marker %s failed: %v", marker, delErr)
}
}
@@ -83,7 +61,6 @@ func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uin
}
if err := cache.Expire(opCtx, windowKey, hotWindowTTL); err != nil {
// 窗口已经写好,缺过期时间只是键长期驻留,不影响正确性。
log.Printf("hot cache: expire %s failed (non-fatal): %v", windowKey, err)
}
return nil