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

@@ -54,7 +54,7 @@ func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
}
}
if s.popularityMQ != nil {
if err := s.popularityMQ.Update(ctx, comment.VideoID, 1); err == nil {
if err := s.popularityMQ.Update(ctx, comment.VideoID, 1, ""); err == nil {
redisEnqueued = true
}
}
@@ -84,7 +84,7 @@ func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
// Fallback: direct Redis update when popularity MQ publish fails.
if !redisEnqueued {
UpdatePopularityCache(ctx, s.cache, comment.VideoID, 1)
UpdatePopularityCache(ctx, s.cache, comment.VideoID, 1, "")
}
s.notifyMentions(ctx, comment)
return nil

View File

@@ -5,6 +5,7 @@ import (
"errors"
"feedsystem_video_go/internal/middleware/rabbitmq"
rediscache "feedsystem_video_go/internal/middleware/redis"
"log"
"time"
"github.com/go-sql-driver/mysql"
@@ -55,24 +56,35 @@ func (s *LikeService) Like(ctx context.Context, like *Like) error {
}
like.CreatedAt = time.Now()
mysqlEnqueued := false
redisEnqueued := false
// 一条意图键同时喂给"点赞事件"和"热度事件":两条消息若都重复投递,
// 各自的消费端会用同一个键去重(点赞走唯一索引,热度走 redis 占位)。
intentKey, err := NewIntentKey()
if err != nil {
return err
}
likeEnqueued := false
popEnqueued := false
if s.likeMQ != nil {
if err := s.likeMQ.Like(ctx, like.AccountID, like.VideoID); err == nil {
mysqlEnqueued = true
if err := s.likeMQ.Like(ctx, like.AccountID, like.VideoID, intentKey); err == nil {
likeEnqueued = true
}
}
if s.popularityMQ != nil {
if err := s.popularityMQ.Update(ctx, like.VideoID, 1); err == nil {
redisEnqueued = true
if err := s.popularityMQ.Update(ctx, like.VideoID, 1, intentKey); err == nil {
popEnqueued = true
}
}
if mysqlEnqueued && redisEnqueued {
return nil
}
// Fallback: direct MySQL write when like MQ publish fails.
if !mysqlEnqueued {
// 两条轨各自独立降级(P0-4 §6.10.4)。
//
// 这里【不能】写成 `if !likeEnqueued && !popEnqueued` 之外的任何"合并判断":
// 旧代码是"两个都成功才 return,否则无条件进兜底",于是"点赞已入队 +
// 热度发布失败"会再插一次 likes → 撞 idx_like_video_account 1062 →
// 接口返回 500,而用户其实点赞成功了。热度归热度,点赞归点赞。
if !likeEnqueued {
// Fallback: direct MySQL write when like MQ publish fails.
err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Select("id").First(&Video{}, like.VideoID).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -99,8 +111,11 @@ func (s *LikeService) Like(ctx context.Context, like *Like) error {
}
// Fallback: direct Redis update when popularity MQ publish fails.
if !redisEnqueued {
UpdatePopularityCache(ctx, s.cache, like.VideoID, 1)
// 热度是"尽力而为"的展示数据,写失败只降级记日志,不回滚已经成立的点赞。
if !popEnqueued {
if err := UpdatePopularityCache(ctx, s.cache, like.VideoID, 1, intentKey); err != nil {
log.Printf("like: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err)
}
}
return nil
}
@@ -131,24 +146,27 @@ func (s *LikeService) Unlike(ctx context.Context, like *Like) error {
return errors.New("user has not liked this video")
}
mysqlEnqueued := false
redisEnqueued := false
intentKey, err := NewIntentKey()
if err != nil {
return err
}
likeEnqueued := false
popEnqueued := false
if s.likeMQ != nil {
if err := s.likeMQ.Unlike(ctx, like.AccountID, like.VideoID); err == nil {
mysqlEnqueued = true
if err := s.likeMQ.Unlike(ctx, like.AccountID, like.VideoID, intentKey); err == nil {
likeEnqueued = true
}
}
if s.popularityMQ != nil {
if err := s.popularityMQ.Update(ctx, like.VideoID, -1); err == nil {
redisEnqueued = true
if err := s.popularityMQ.Update(ctx, like.VideoID, -1, intentKey); err == nil {
popEnqueued = true
}
}
if mysqlEnqueued && redisEnqueued {
return nil
}
// Fallback: direct MySQL write when like MQ publish fails.
if !mysqlEnqueued {
// 与 Like 对称:两条轨各自降级,不做合并判断。
if !likeEnqueued {
// Fallback: direct MySQL write when like MQ publish fails.
err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
del := tx.Where("video_id = ? AND account_id = ?", like.VideoID, like.AccountID).Delete(&Like{})
if del.Error != nil {
@@ -171,8 +189,10 @@ func (s *LikeService) Unlike(ctx context.Context, like *Like) error {
}
// Fallback: direct Redis update when popularity MQ publish fails.
if !redisEnqueued {
UpdatePopularityCache(ctx, s.cache, like.VideoID, -1)
if !popEnqueued {
if err := UpdatePopularityCache(ctx, s.cache, like.VideoID, -1, intentKey); err != nil {
log.Printf("unlike: 热榜更新失败(已降级)video=%d: %v", like.VideoID, err)
}
}
return nil
}

View File

@@ -2,18 +2,68 @@ package video
import (
"context"
"fmt"
"log"
"strconv"
"time"
rediscache "feedsystem_video_go/internal/middleware/redis"
)
// 更新视频流行度缓存
func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uint, change int64) {
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 {
if cache == nil || id == 0 || change == 0 {
return
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:失败最多让详情页多陈旧 5 分钟(缓存 TTL),
// 不值得让整条消息重投。
_ = cache.Del(context.Background(), cache.Key("video:detail:id=%d", id))
_ = cache.Del(context.Background(), cache.Key("video:entity:%d", id))
@@ -21,9 +71,20 @@ func UpdatePopularityCache(ctx context.Context, cache *rediscache.Client, id uin
windowKey := cache.Key("hot:video:1m:%s", now.Format("200601021504"))
member := strconv.FormatUint(uint64(id), 10)
opCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
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)
}
_ = cache.ZincrBy(opCtx, windowKey, member, float64(change))
_ = cache.Expire(opCtx, windowKey, 2*time.Hour)
if err := cache.Expire(opCtx, windowKey, hotWindowTTL); err != nil {
// 窗口已经写好,缺过期时间只是键长期驻留,不影响正确性。
log.Printf("hot cache: expire %s failed (non-fatal): %v", windowKey, err)
}
return nil
}

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("详情/实体缓存必须被失效")
}
}

View File

@@ -4,26 +4,27 @@ import (
"context"
"encoding/json"
"errors"
"strconv"
"strings"
"time"
"feedsystem_video_go/internal/apierror"
"feedsystem_video_go/internal/middleware/rabbitmq"
rediscache "feedsystem_video_go/internal/middleware/redis"
"gorm.io/gorm"
)
type VideoService struct {
repo *VideoRepository
cache *rediscache.Client
cacheTTL time.Duration
popularityMQ *rabbitmq.PopularityMQ
repo *VideoRepository
cache *rediscache.Client
cacheTTL time.Duration
}
func NewVideoService(repo *VideoRepository, cache *rediscache.Client, popularityMQ *rabbitmq.PopularityMQ) *VideoService {
return &VideoService{repo: repo, cache: cache, cacheTTL: 5 * time.Minute, popularityMQ: popularityMQ}
// NewVideoService 不再接收 popularityMQ:热度写入只有两个入口——
// PopularityWorker(异步)与 LikeService/CommentService 的兜底路径,
// 视频服务从来不直接改热度。原来这里挂着一个没人调用的 UpdatePopularity,
// 它是热度写入的第三份实现,且漏删 video:entity 缓存(P0-4 的 N3)。
func NewVideoService(repo *VideoRepository, cache *rediscache.Client) *VideoService {
return &VideoService{repo: repo, cache: cache, cacheTTL: 5 * time.Minute}
}
func (vs *VideoService) Publish(ctx context.Context, video *Video) error {
@@ -199,32 +200,3 @@ func (vs *VideoService) UpdateLikesCount(ctx context.Context, id uint, likesCoun
}
return nil
}
func (vs *VideoService) UpdatePopularity(ctx context.Context, id uint, change int64) error {
if err := vs.repo.UpdatePopularity(ctx, id, change); err != nil {
return err
}
if vs.popularityMQ != nil {
if err := vs.popularityMQ.Update(ctx, id, change); err == nil {
return nil
}
}
if vs.cache != nil {
// 1) 详情缓存:直接失效(最简单靠谱)
_ = vs.cache.Del(context.Background(), vs.cache.Key("video:detail:id=%d", id))
// 2) 热榜:写到“时间窗ZSET”,不要用 detail key
now := time.Now().UTC().Truncate(time.Minute)
windowKey := vs.cache.Key("hot:video:1m:%s", now.Format("200601021504"))
member := strconv.FormatUint(uint64(id), 10)
opCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
_ = vs.cache.ZincrBy(opCtx, windowKey, member, float64(change))
_ = vs.cache.Expire(opCtx, windowKey, 2*time.Hour)
}
return nil
}