68 lines
2.0 KiB
Go
68 lines
2.0 KiB
Go
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
|
||
}
|