feat(video): 热度写入单轨化,点赞兜底不再重复插入

热度有两个写入者(PopularityWorker 与兜底直写)和三份实现,其中
VideoService.UpdatePopularity 是死代码且漏删 video:entity 缓存。这里
收敛成一条轨,并让"加过分"这件事可以判重。

- popularity_cache: UpdatePopularityCache 改成 5 参数并返回 error,
  用 redis SETNX 占位 hot:applied:<意图键> 实现幂等;ZINCRBY 失败必须
  撤销占位再上抛(占位留在失败路径上会让增量被永久跳过);三次 Del 是
  best-effort,不受 opCtx 约束。返回 error 同时修掉 P0-3 的 N2——
  原来三条路径全返回 nil,消费端的 Nack/重试/sleep 全是死代码。
- popularityMQ.Update / likeMQ.Like/Unlike 增加 intentKey 入参,写进
  event_id,让点赞事件与热度事件共享一次判重身份。
- like_service: 兜底拆成两个独立的 if(!likeEnqueued 写 DB、
  !popEnqueued 写热榜)。旧代码"两个都成功才 return"会在"点赞已入队 +
  热度发布失败"时再插一次 likes,撞唯一索引返回 500,而点赞其实成功了。
- 删除 VideoService.UpdatePopularity 及其 popularityMQ 字段与构造参数
  (router.go 是唯一调用点)。

行为变更:点赞在热度发布失败时不再返回 500。热度是展示数据,失败只降级
记日志,不回滚已经成立的点赞。
This commit is contained in:
2026-10-30 13:25:48 +08:00
parent d734cc9e43
commit 90a7feb6d3
9 changed files with 312 additions and 87 deletions

View File

@@ -0,0 +1,151 @@
package video
import (
"context"
"errors"
"strconv"
"strings"
"testing"
"time"
rediscache "feedsystem_video_go/internal/middleware/redis"
"github.com/alicebob/miniredis/v2"
goredis "github.com/redis/go-redis/v9"
)
func newTestCache(t *testing.T) (*rediscache.Client, *miniredis.Miniredis) {
t.Helper()
mr := miniredis.RunT(t)
rdb := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
t.Cleanup(func() { _ = rdb.Close() })
return rediscache.NewClient(rdb, "test:"), mr
}
// hotScore 汇总所有分钟窗口里某个视频的分数。
//
// 不直接构造 windowKey:那会把测试和"窗口按分钟切分"这一实现细节绑死,
// 而我们要断言的是"这条意图到底加了几次分"。
func hotScore(t *testing.T, mr *miniredis.Miniredis, id uint) float64 {
t.Helper()
member := strconv.FormatUint(uint64(id), 10)
var sum float64
for _, key := range mr.Keys() {
if !strings.Contains(key, "hot:video:1m:") {
continue
}
if !mr.Exists(key) {
continue
}
if v, err := mr.ZScore(key, member); err == nil {
sum += v
}
}
return sum
}
// 同一条意图重复调用只能加一次分:这是"双倍热度"的直接对手。
func TestUpdatePopularityCache_SecondCallIsNoop(t *testing.T) {
cache, mr := newTestCache(t)
ctx := context.Background()
key := "intent-heat-1"
for i := 0; i < 3; i++ {
if err := UpdatePopularityCache(ctx, cache, 42, 1, key); err != nil {
t.Fatalf("第 %d 次调用: %v", i+1, err)
}
}
if got := hotScore(t, mr, 42); got != 1 {
t.Fatalf("热度 = %v, want 1(同一意图键只能生效一次)", got)
}
}
// 没有意图键时必须每次都生效:这是点赞兜底路径,调用方已经确保
// "只有发不出去才走到这里",在这里再去重会把真实增量吞掉。
func TestUpdatePopularityCache_EmptyKeyAppliesEveryTime(t *testing.T) {
cache, mr := newTestCache(t)
ctx := context.Background()
for i := 0; i < 2; i++ {
if err := UpdatePopularityCache(ctx, cache, 43, 1, ""); err != nil {
t.Fatalf("第 %d 次调用: %v", i+1, err)
}
}
if got := hotScore(t, mr, 43); got != 2 {
t.Fatalf("热度 = %v, want 2(无意图键不参与去重)", got)
}
}
// 占位必须与"加分成功"同生共死:加分失败却留下占位,会让这次增量被
// 永久跳过——比重复加分更难发现(用户只会觉得"热度不动了")。
type failZincrByHook struct {
fail bool
}
func (h *failZincrByHook) DialHook(next goredis.DialHook) goredis.DialHook { return next }
func (h *failZincrByHook) ProcessHook(next goredis.ProcessHook) goredis.ProcessHook {
return func(ctx context.Context, cmd goredis.Cmder) error {
if h.fail && strings.EqualFold(cmd.Name(), "zincrby") {
return errors.New("injected zincrby failure")
}
return next(ctx, cmd)
}
}
func (h *failZincrByHook) ProcessPipelineHook(next goredis.ProcessPipelineHook) goredis.ProcessPipelineHook {
return next
}
func TestUpdatePopularityCache_MarkerRevokedOnFailure(t *testing.T) {
mr := miniredis.RunT(t)
rdb := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
t.Cleanup(func() { _ = rdb.Close() })
hook := &failZincrByHook{fail: true}
rdb.AddHook(hook)
cache := rediscache.NewClient(rdb, "test:")
ctx := context.Background()
key := "intent-heat-2"
if err := UpdatePopularityCache(ctx, cache, 44, 1, key); err == nil {
t.Fatal("ZINCRBY 失败时 UpdatePopularityCache 必须返回 error(否则消费端无法重试)")
}
// 故障恢复后重试同一条意图:占位已被撤销,这次必须真的加上。
hook.fail = false
if err := UpdatePopularityCache(ctx, cache, 44, 1, key); err != nil {
t.Fatalf("故障恢复后重试: %v", err)
}
if got := hotScore(t, mr, 44); got != 1 {
t.Fatalf("热度 = %v, want 1(失败后占位必须被撤销)", got)
}
}
// 降级路径:没有 cache(Redis 未启用)时不得报错,否则热度事件会被
// 无限重投直到停泊——一个"本来就没有热榜"的部署会凭空产生死信。
func TestUpdatePopularityCache_NilCacheIsNoop(t *testing.T) {
if err := UpdatePopularityCache(context.Background(), nil, 45, 1, "k"); err != nil {
t.Fatalf("nil cache 不应返回错误: %v", err)
}
}
// 缓存失效是 best-effort:它不在 opCtx 的预算里,也不阻塞主流程。
func TestUpdatePopularityCache_InvalidatesDetailAndEntityKeys(t *testing.T) {
cache, mr := newTestCache(t)
ctx := context.Background()
detail := cache.Key("video:detail:id=%d", 46)
entity := cache.Key("video:entity:%d", 46)
if err := cache.SetBytes(ctx, detail, []byte("x"), time.Hour); err != nil {
t.Fatalf("seed detail: %v", err)
}
if err := cache.SetBytes(ctx, entity, []byte("y"), time.Hour); err != nil {
t.Fatalf("seed entity: %v", err)
}
if err := UpdatePopularityCache(ctx, cache, 46, 1, "intent-heat-3"); err != nil {
t.Fatalf("UpdatePopularityCache: %v", err)
}
if mr.Exists(detail) || mr.Exists(entity) {
t.Fatalf("详情/实体缓存必须被失效")
}
}