refactor(video): 计数改由业务事务维护并删除热度第二条写路径
点赞与评论的计数只由业务事务写。ApplyLike、ApplyUnlike、CreateIdempotentWithPopularity 与 DeleteWithPopularity 各自在单事务内完成插行与计数。 热榜增量改为提交后的 best-effort 写。ApplyHotDelta 按行的 created_at 落分钟桶,写失败只记日志,DB 计数仍然正确。 删除 PopularityMQ 与 PopularityWorker。同一次互动因此只有一个写者,不再有两个门闩各自放行。 删除 hot:applied 占位键。判重改由 likes 的唯一索引与 uk_comments_author_key 负责。 DeleteWithPopularity 先读行再删行。评论删除因此回退热度,重复投递不再多减一次。 likes 与 comments 各加 (created_at, video_id) 覆盖索引,服务热榜窗口查询。 验证:go build -buildvcs=false ./... 通过。go test -buildvcs=false -count=1 ./... 全绿。
This commit is contained in:
@@ -25,12 +25,6 @@ func (failingCommentPublisher) Delete(context.Context, uint, string) error {
|
||||
return errors.New("mq publish failed")
|
||||
}
|
||||
|
||||
type failingPopularityPublisher struct{}
|
||||
|
||||
func (failingPopularityPublisher) Update(context.Context, uint, int64, string) error {
|
||||
return errors.New("mq publish failed")
|
||||
}
|
||||
|
||||
// P0-4 的原始缺陷是"兜底直写一次 + 消费者再写一次",结果是两条评论、双倍热度。
|
||||
// 这个用例把两条路径接起来跑:先让服务层兜底写入,再让同一个意图键的事件到达
|
||||
// worker。断言收敛到一行评论、热度恰为 1。
|
||||
@@ -45,10 +39,8 @@ func TestP0_4_FallbackAndWorkerConvergeToOneComment(t *testing.T) {
|
||||
|
||||
commentRepo := video.NewCommentRepository(db)
|
||||
videoRepo := video.NewVideoRepository(db)
|
||||
svc := video.NewCommentService(
|
||||
commentRepo, videoRepo, nil,
|
||||
failingCommentPublisher{}, failingPopularityPublisher{},
|
||||
)
|
||||
// cache 传 nil:热榜是 best-effort 派生数据,本用例只断言 DB 侧的收敛。
|
||||
svc := video.NewCommentService(commentRepo, videoRepo, nil, failingCommentPublisher{})
|
||||
|
||||
intentKey := "converge-intent-0001"
|
||||
comment := &video.Comment{
|
||||
@@ -66,7 +58,7 @@ func TestP0_4_FallbackAndWorkerConvergeToOneComment(t *testing.T) {
|
||||
}
|
||||
|
||||
// 消息其实已到 broker,稍后由消费者处理同一个意图键。
|
||||
w := NewCommentWorker(nil, nil, commentRepo, videoRepo, rabbitmq.CommentQueue)
|
||||
w := NewCommentWorker(nil, nil, commentRepo, videoRepo, nil, rabbitmq.CommentQueue)
|
||||
evt := &rabbitmq.CommentEvent{
|
||||
EventID: intentKey,
|
||||
Action: "publish",
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
@@ -19,11 +20,12 @@ type CommentWorker struct {
|
||||
parker rabbitmq.Parker
|
||||
comments video.CommentStore
|
||||
videos *video.VideoRepository
|
||||
cache *rediscache.Client
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewCommentWorker(ch *amqp.Channel, parker rabbitmq.Parker, comments video.CommentStore, videos *video.VideoRepository, queue string) *CommentWorker {
|
||||
return &CommentWorker{ch: ch, parker: parker, comments: comments, videos: videos, queue: queue}
|
||||
func NewCommentWorker(ch *amqp.Channel, parker rabbitmq.Parker, comments video.CommentStore, videos *video.VideoRepository, cache *rediscache.Client, queue string) *CommentWorker {
|
||||
return &CommentWorker{ch: ch, parker: parker, comments: comments, videos: videos, cache: cache, queue: queue}
|
||||
}
|
||||
|
||||
func (w *CommentWorker) Run(ctx context.Context) error {
|
||||
@@ -71,6 +73,10 @@ func (w *CommentWorker) applyPublish(ctx context.Context, evt *rabbitmq.CommentE
|
||||
VideoID: evt.VideoID,
|
||||
AuthorID: evt.AuthorID,
|
||||
Content: strings.TrimSpace(evt.Content),
|
||||
// 行时间来自事件:桶必须落在评论发生的那一分钟。
|
||||
// 事件没带时间时保持零值,由 GORM 的 autoCreateTime 补当前时刻,
|
||||
// 并回填到这个字段,因此下面的落桶仍与行一致。
|
||||
CreatedAt: evt.OccurredAt,
|
||||
}
|
||||
// event_id 即意图键:API 已直写时这里会命中唯一索引。
|
||||
if evt.EventID != "" {
|
||||
@@ -85,6 +91,11 @@ func (w *CommentWorker) applyPublish(ctx context.Context, evt *rabbitmq.CommentE
|
||||
if !created {
|
||||
log.Printf("comment worker: dedupe=hit event_id=%s video_id=%d author_id=%d",
|
||||
evt.EventID, evt.VideoID, evt.AuthorID)
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, c.VideoID, 1, c.CreatedAt); err != nil {
|
||||
log.Printf("comment worker: hot window update failed video=%d: %v", c.VideoID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -93,13 +104,18 @@ func (w *CommentWorker) applyDelete(ctx context.Context, evt *rabbitmq.CommentEv
|
||||
if evt == nil || evt.CommentID == 0 {
|
||||
return rabbitmq.Permanent(errors.New("comment worker: invalid delete event: comment_id is required"))
|
||||
}
|
||||
deleted, err := w.comments.DeleteByID(ctx, evt.CommentID)
|
||||
deleted, ok, err := w.comments.DeleteWithPopularity(ctx, evt.CommentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !deleted {
|
||||
// 重复投递的删除是空操作,不是错误。
|
||||
if !ok {
|
||||
// 重复投递的删除是空操作,不是错误;热度也不能再减一次。
|
||||
log.Printf("comment worker: comment already deleted id=%d event_id=%s", evt.CommentID, evt.EventID)
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, deleted.VideoID, -1, deleted.CreatedAt); err != nil {
|
||||
log.Printf("comment worker: hot window update failed comment_id=%d: %v", evt.CommentID, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// 评论消费者"只写一次评论、不再碰热度"这条不变式只能在真实 MySQL 上验证:
|
||||
// 评论消费者"只写一次评论、热度跟着事务走"这条不变式只能在真实 MySQL 上验证:
|
||||
// 判重落在唯一索引 (author_id, idempotency_key) 上,没有数据库就没有被测对象。
|
||||
//
|
||||
// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \
|
||||
@@ -37,10 +37,10 @@ func newCommentWorkerTestDB(t *testing.T) *gorm.DB {
|
||||
if err != nil {
|
||||
t.Fatalf("connect mysql: %v", err)
|
||||
}
|
||||
if err := db.Migrator().DropTable(&video.Comment{}, &video.Video{}); err != nil {
|
||||
if err := db.Migrator().DropTable(&video.Comment{}, &video.Like{}, &video.Video{}); err != nil {
|
||||
t.Fatalf("drop tables: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&video.Video{}, &video.Comment{}); err != nil {
|
||||
if err := db.AutoMigrate(&video.Video{}, &video.Comment{}, &video.Like{}); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
return db
|
||||
@@ -67,12 +67,11 @@ func seedCommentVideo(t *testing.T, db *gorm.DB) *video.Video {
|
||||
//
|
||||
// 两个断言分别钉住两件不同的事:行数 = 1 证明唯一索引吸收了重复;热度 = 1
|
||||
// (而不是 2)证明"加热度"与"插入评论"在同一个事务里、且以 created 为门控。
|
||||
// 热度写在这里而不是 Redis,是因为 videos.popularity 与 comments 必须原子
|
||||
// 提交——Redis 那条轨由 popularity 事件单独负责。
|
||||
// 热度写在这里而不是 Redis,是因为 videos.popularity 是事实,热榜只是它的滑窗副本。
|
||||
func TestCommentWorker_ApplyPublish_DuplicateEventWritesOneRow(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), "comment.events")
|
||||
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), nil, "comment.events")
|
||||
evt := &rabbitmq.CommentEvent{
|
||||
EventID: "evt-comment-1",
|
||||
Action: "publish",
|
||||
@@ -110,7 +109,7 @@ func TestCommentWorker_ApplyPublish_DuplicateEventWritesOneRow(t *testing.T) {
|
||||
func TestCommentWorker_ApplyPublish_EmptyEventIDStillWrites(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), "comment.events")
|
||||
w := NewCommentWorker(nil, nil, video.NewCommentRepository(db), video.NewVideoRepository(db), nil, "comment.events")
|
||||
|
||||
evt := &rabbitmq.CommentEvent{
|
||||
Action: "publish",
|
||||
@@ -137,10 +136,10 @@ func TestCommentWorker_ApplyDelete_DuplicateIsNoop(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
repo := video.NewCommentRepository(db)
|
||||
w := NewCommentWorker(nil, nil, repo, video.NewVideoRepository(db), "comment.events")
|
||||
w := NewCommentWorker(nil, nil, repo, video.NewVideoRepository(db), nil, "comment.events")
|
||||
|
||||
c := &video.Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x"}
|
||||
if _, err := repo.CreateIdempotentWithPopularity(context.Background(), c, 0); err != nil {
|
||||
if _, err := repo.CreateIdempotentWithPopularity(context.Background(), c, 1); err != nil {
|
||||
t.Fatalf("seed comment: %v", err)
|
||||
}
|
||||
|
||||
@@ -158,4 +157,12 @@ func TestCommentWorker_ApplyDelete_DuplicateIsNoop(t *testing.T) {
|
||||
if count != 0 {
|
||||
t.Fatalf("评论行数 = %d, want 0", count)
|
||||
}
|
||||
// P2-20:删除必须回退热度,且只回退一次(第二次删除是空操作)。
|
||||
var got video.Video
|
||||
if err := db.First(&got, v.ID).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
if got.Popularity != 0 {
|
||||
t.Fatalf("popularity = %d, want 0(删除要回退热度,重复删除不得再减)", got.Popularity)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
@@ -18,11 +20,12 @@ type LikeWorker struct {
|
||||
parker rabbitmq.Parker
|
||||
likes *video.LikeRepository
|
||||
videos *video.VideoRepository
|
||||
cache *rediscache.Client
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewLikeWorker(ch *amqp.Channel, parker rabbitmq.Parker, likes *video.LikeRepository, videos *video.VideoRepository, queue string) *LikeWorker {
|
||||
return &LikeWorker{ch: ch, parker: parker, likes: likes, videos: videos, queue: queue}
|
||||
func NewLikeWorker(ch *amqp.Channel, parker rabbitmq.Parker, likes *video.LikeRepository, videos *video.VideoRepository, cache *rediscache.Client, queue string) *LikeWorker {
|
||||
return &LikeWorker{ch: ch, parker: parker, likes: likes, videos: videos, cache: cache, queue: queue}
|
||||
}
|
||||
|
||||
func (w *LikeWorker) Run(ctx context.Context) error {
|
||||
@@ -48,16 +51,16 @@ func (w *LikeWorker) process(ctx context.Context, d amqp.Delivery) error {
|
||||
|
||||
switch evt.Action {
|
||||
case "like":
|
||||
return w.applyLike(ctx, evt.UserID, evt.VideoID)
|
||||
return w.applyLike(ctx, evt)
|
||||
case "unlike":
|
||||
return w.applyUnlike(ctx, evt.UserID, evt.VideoID)
|
||||
return w.applyUnlike(ctx, evt)
|
||||
default:
|
||||
return rabbitmq.Permanent(fmt.Errorf("like worker: unknown action %q", evt.Action))
|
||||
}
|
||||
}
|
||||
|
||||
func (w *LikeWorker) applyLike(ctx context.Context, userID, videoID uint) error {
|
||||
ok, err := w.videos.IsExist(ctx, videoID)
|
||||
func (w *LikeWorker) applyLike(ctx context.Context, evt rabbitmq.LikeEvent) error {
|
||||
ok, err := w.videos.IsExist(ctx, evt.VideoID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -66,27 +69,37 @@ func (w *LikeWorker) applyLike(ctx context.Context, userID, videoID uint) error
|
||||
return nil
|
||||
}
|
||||
|
||||
created, err := w.likes.LikeIgnoreDuplicate(ctx, &video.Like{
|
||||
VideoID: videoID,
|
||||
AccountID: userID,
|
||||
CreatedAt: time.Now(),
|
||||
// 行时间来自消息:积压的 worker 必须把增量记在事件发生的那一分钟,
|
||||
// 不能记在它被消费的那一分钟。旧的告警消息没有 occurred_at,退回当前时刻。
|
||||
at := evt.OccurredAt
|
||||
if at.IsZero() {
|
||||
at = time.Now()
|
||||
}
|
||||
|
||||
// 插行与两个计数在同一个事务里,不再有"点赞成功、计数少 1"的中间态。
|
||||
created, err := w.likes.ApplyLike(ctx, &video.Like{
|
||||
VideoID: evt.VideoID,
|
||||
AccountID: evt.UserID,
|
||||
CreatedAt: at,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !created {
|
||||
// 重复投递:点赞已存在,计数不能再加。
|
||||
// 重复投递:点赞已存在,计数与热榜都不能再加。
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := w.videos.ChangeLikesCount(ctx, videoID, 1); err != nil {
|
||||
return err
|
||||
// 热榜是派生数据。写失败不回滚点赞(I1 只看 DB),只留痕:
|
||||
// -verify 能发现这个桶偏少,-rebuild-hot 能把它建回来。
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, evt.VideoID, 1, at); err != nil {
|
||||
log.Printf("like worker: hot window update failed video=%d: %v", evt.VideoID, err)
|
||||
}
|
||||
return w.videos.ChangePopularity(ctx, videoID, 1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *LikeWorker) applyUnlike(ctx context.Context, userID, videoID uint) error {
|
||||
ok, err := w.videos.IsExist(ctx, videoID)
|
||||
func (w *LikeWorker) applyUnlike(ctx context.Context, evt rabbitmq.LikeEvent) error {
|
||||
ok, err := w.videos.IsExist(ctx, evt.VideoID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -94,16 +107,18 @@ func (w *LikeWorker) applyUnlike(ctx context.Context, userID, videoID uint) erro
|
||||
return nil
|
||||
}
|
||||
|
||||
deleted, err := w.likes.DeleteByVideoAndAccount(ctx, videoID, userID)
|
||||
row, deleted, err := w.likes.ApplyUnlike(ctx, evt.VideoID, evt.UserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !deleted {
|
||||
// 重复投递:行已经不在了,热度也不能再减。
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := w.videos.ChangeLikesCount(ctx, videoID, -1); err != nil {
|
||||
return err
|
||||
// 减回点赞那一刻的桶:热榜是滑窗,按消费时刻减会留下一个永远偏高的旧桶。
|
||||
if err := video.ApplyHotDelta(ctx, w.cache, evt.VideoID, -1, row.CreatedAt); err != nil {
|
||||
log.Printf("like worker: hot window update failed video=%d: %v", evt.VideoID, err)
|
||||
}
|
||||
return w.videos.ChangePopularity(ctx, videoID, -1)
|
||||
return nil
|
||||
}
|
||||
|
||||
133
backend/internal/worker/likeworker_integration_test.go
Normal file
133
backend/internal/worker/likeworker_integration_test.go
Normal file
@@ -0,0 +1,133 @@
|
||||
//go:build integration
|
||||
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
"github.com/alicebob/miniredis/v2"
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 热榜增量必须由"事务是否真的插入"驱动,而不是由消息驱动:
|
||||
// 重投一次不能再加一次分,否则同一次点赞会在榜上加两次。
|
||||
func newLikeWorkerCache(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
|
||||
}
|
||||
|
||||
func hotScore(t *testing.T, cache *rediscache.Client, mr *miniredis.Miniredis, videoID uint, at time.Time) float64 {
|
||||
t.Helper()
|
||||
score, err := mr.ZScore(cache.Key("hot:video:1m:%s", video.HotBucket(at)), video.HotMember(videoID))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
func reloadVideo(t *testing.T, db *gorm.DB, id uint) video.Video {
|
||||
t.Helper()
|
||||
var v video.Video
|
||||
if err := db.First(&v, id).Error; err != nil {
|
||||
t.Fatalf("reload video: %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func TestLikeWorker_ReplayDoesNotDoubleHot(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
cache, mr := newLikeWorkerCache(t)
|
||||
w := NewLikeWorker(nil, nil, video.NewLikeRepository(db), video.NewVideoRepository(db), cache, "like.events")
|
||||
|
||||
// 10 分钟前发生的点赞,10 分钟后才被消费:桶要按 OccurredAt 落。
|
||||
at := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Second)
|
||||
evt := &rabbitmq.LikeEvent{EventID: "evt-like-1", Action: "like", UserID: 7, VideoID: v.ID, OccurredAt: at}
|
||||
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := w.applyLike(context.Background(), *evt); err != nil {
|
||||
t.Fatalf("第 %d 次 applyLike: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
got := reloadVideo(t, db, v.ID)
|
||||
if got.LikesCount != 1 || got.Popularity != 1 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 1/1(重投不得再计数)", got.LikesCount, got.Popularity)
|
||||
}
|
||||
if score := hotScore(t, cache, mr, v.ID, at); score != 1 {
|
||||
t.Fatalf("热榜分数 = %v, want 1(重投不得再加一次分)", score)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLikeWorker_UnlikeRevertsOriginalBucket(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
cache, mr := newLikeWorkerCache(t)
|
||||
w := NewLikeWorker(nil, nil, video.NewLikeRepository(db), video.NewVideoRepository(db), cache, "like.events")
|
||||
|
||||
at := time.Now().UTC().Add(-20 * time.Minute).Truncate(time.Second)
|
||||
if err := w.applyLike(context.Background(), rabbitmq.LikeEvent{EventID: "e1", Action: "like", UserID: 7, VideoID: v.ID, OccurredAt: at}); err != nil {
|
||||
t.Fatalf("applyLike: %v", err)
|
||||
}
|
||||
|
||||
// 取消事件的重投也要是空操作,且 -1 落回点赞那一分钟。
|
||||
unlike := &rabbitmq.LikeEvent{EventID: "e2", Action: "unlike", UserID: 7, VideoID: v.ID}
|
||||
if err := w.applyUnlike(context.Background(), *unlike); err != nil {
|
||||
t.Fatalf("applyUnlike: %v", err)
|
||||
}
|
||||
if err := w.applyUnlike(context.Background(), *unlike); err != nil {
|
||||
t.Fatalf("重复 applyUnlike: %v", err)
|
||||
}
|
||||
|
||||
got := reloadVideo(t, db, v.ID)
|
||||
if got.LikesCount != 0 || got.Popularity != 0 {
|
||||
t.Fatalf("likes_count=%d popularity=%d, want 0/0", got.LikesCount, got.Popularity)
|
||||
}
|
||||
if score := hotScore(t, cache, mr, v.ID, at); score != 0 {
|
||||
t.Fatalf("原桶分数 = %v, want 0(+1 与 -1 落在同一分钟)", score)
|
||||
}
|
||||
}
|
||||
|
||||
// P2-20:删除评论时必须把热度 -1 记回评论创建的那一分钟。
|
||||
func TestCommentWorker_DeleteRevertsHot(t *testing.T) {
|
||||
db := newCommentWorkerTestDB(t)
|
||||
v := seedCommentVideo(t, db)
|
||||
cache, mr := newLikeWorkerCache(t)
|
||||
repo := video.NewCommentRepository(db)
|
||||
w := NewCommentWorker(nil, nil, repo, video.NewVideoRepository(db), cache, "comment.events")
|
||||
|
||||
createdAt := time.Now().UTC().Add(-15 * time.Minute).Truncate(time.Second)
|
||||
c := &video.Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x", CreatedAt: createdAt}
|
||||
if created, err := repo.CreateIdempotentWithPopularity(context.Background(), c, 1); err != nil || !created {
|
||||
t.Fatalf("seed comment = created:%v err:%v", created, err)
|
||||
}
|
||||
// 用真实行时间模拟"发布时已经加过一分"。
|
||||
if err := video.ApplyHotDelta(context.Background(), cache, v.ID, 1, createdAt); err != nil {
|
||||
t.Fatalf("seed hot delta: %v", err)
|
||||
}
|
||||
|
||||
evt := &rabbitmq.CommentEvent{EventID: "evt-del-1", Action: "delete", CommentID: c.ID}
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := w.applyDelete(context.Background(), evt); err != nil {
|
||||
t.Fatalf("第 %d 次 applyDelete: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
got := reloadVideo(t, db, v.ID)
|
||||
if got.Popularity != 0 {
|
||||
t.Fatalf("popularity = %d, want 0(删除回退一次,重投不再减)", got.Popularity)
|
||||
}
|
||||
if score := hotScore(t, cache, mr, v.ID, createdAt); score != 0 {
|
||||
t.Fatalf("原桶分数 = %v, want 0(-1 必须落回创建那一分钟)", score)
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"feedsystem_video_go/internal/middleware/rabbitmq"
|
||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||
"feedsystem_video_go/internal/video"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
type PopularityWorker struct {
|
||||
ch *amqp.Channel
|
||||
parker rabbitmq.Parker
|
||||
cache *rediscache.Client
|
||||
queue string
|
||||
}
|
||||
|
||||
func NewPopularityWorker(ch *amqp.Channel, parker rabbitmq.Parker, cache *rediscache.Client, queue string) *PopularityWorker {
|
||||
return &PopularityWorker{ch: ch, parker: parker, cache: cache, queue: queue}
|
||||
}
|
||||
|
||||
func (w *PopularityWorker) Run(ctx context.Context) error {
|
||||
if w == nil || w.ch == nil {
|
||||
return errors.New("popularity worker is not initialized")
|
||||
}
|
||||
if w.queue == "" {
|
||||
return errors.New("queue is required")
|
||||
}
|
||||
return rabbitmq.ConsumeLoop(ctx, w.ch, w.parker, w.queue, rabbitmq.MaxAttempts, w.process)
|
||||
}
|
||||
|
||||
func (w *PopularityWorker) process(ctx context.Context, d amqp.Delivery) error {
|
||||
var evt rabbitmq.PopularityEvent
|
||||
if err := json.Unmarshal(d.Body, &evt); err != nil {
|
||||
return rabbitmq.Permanent(fmt.Errorf("popularity worker: decode event: %w", err))
|
||||
}
|
||||
if evt.VideoID == 0 || evt.Change == 0 {
|
||||
return rabbitmq.Permanent(fmt.Errorf("popularity worker: invalid event video_id=%d change=%d", evt.VideoID, evt.Change))
|
||||
}
|
||||
// 必须把错误上抛,否则重试分支是死代码。
|
||||
return video.UpdatePopularityCache(ctx, w.cache, evt.VideoID, evt.Change, evt.EventID)
|
||||
}
|
||||
Reference in New Issue
Block a user