Files
VLoop/backend/internal/video/popularity_cache.go
huanghaosheng c210e75996 style(backend): 清理幂等写入路径的注释
注释只保留一行级约束。
长段理由移入设计文档。
验证:go test -count=1 ./... 全绿。
2026-10-31 00:03:53 +08:00

68 lines
2.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package video
import (
"context"
"fmt"
"log"
"strconv"
"time"
rediscache "feedsystem_video_go/internal/middleware/redis"
)
const (
// hotAppliedTTL 覆盖同一次意图的重复投递窗口。
hotAppliedTTL = 2 * time.Hour
hotWindowTTL = 2 * time.Hour
// hotOpTimeout 只约束 SetNX / ZINCRBY / EXPIRE 三次往返。
hotOpTimeout = 100 * time.Millisecond
)
// UpdatePopularityCache 给视频的分钟窗口热度加 change。
//
// 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
}
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,不计入 opCtx 预算。
_ = cache.Del(context.Background(), cache.Key("video:detail:id=%d", id))
_ = cache.Del(context.Background(), cache.Key("video:entity:%d", id))
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 {
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)
}
if err := cache.Expire(opCtx, windowKey, hotWindowTTL); err != nil {
log.Printf("hot cache: expire %s failed (non-fatal): %v", windowKey, err)
}
return nil
}