Files
VLoop/backend/internal/video/popularity_cache.go

91 lines
3.8 KiB
Go
Raw Normal View History

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