diff --git a/backend/internal/middleware/rabbitmq/commentMQ.go b/backend/internal/middleware/rabbitmq/commentMQ.go index 9582dcf..520d57d 100644 --- a/backend/internal/middleware/rabbitmq/commentMQ.go +++ b/backend/internal/middleware/rabbitmq/commentMQ.go @@ -40,18 +40,17 @@ func NewCommentMQ(base *RabbitMQ) (*CommentMQ, error) { return &CommentMQ{mgr: base}, nil } -func (c *CommentMQ) Publish(ctx context.Context, username string, videoID, authorID uint, content string) error { - return c.publish(ctx, "publish", CommentPublishRK, CommentEvent{ - Username: username, - VideoID: videoID, - AuthorID: authorID, - Content: content, - }) +// Publish 直接接收完整事件:event_id 由调用方(服务层)生成,因为它是 +// "这次用户意图"的标识,必须与兜底直写用的是同一个值(P0-4 §6.8)。 +// 只有 EventID 为空时才在这里补一个随机 id(老调用方/测试路径)。 +func (c *CommentMQ) Publish(ctx context.Context, evt CommentEvent) error { + return c.publish(ctx, "publish", CommentPublishRK, evt) } -func (c *CommentMQ) Delete(ctx context.Context, commentID uint) error { +func (c *CommentMQ) Delete(ctx context.Context, commentID uint, intentKey string) error { return c.publish(ctx, "delete", CommentDeleteRK, CommentEvent{ CommentID: commentID, + EventID: intentKey, }) } @@ -59,11 +58,13 @@ func (c *CommentMQ) publish(ctx context.Context, action, routingKey string, evt if c == nil || c.mgr == nil { return errors.New("comment mq is not initialized") } - id, err := newEventID(16) - if err != nil { - return err + if evt.EventID == "" { + id, err := newEventID(16) + if err != nil { + return err + } + evt.EventID = id } - evt.EventID = id evt.Action = action evt.OccurredAt = time.Now().UTC() return c.mgr.PublishJSON(ctx, CommentExchange, routingKey, evt) diff --git a/backend/internal/video/comment_handler.go b/backend/internal/video/comment_handler.go index 687581c..bc8503d 100644 --- a/backend/internal/video/comment_handler.go +++ b/backend/internal/video/comment_handler.go @@ -46,11 +46,24 @@ func (h *CommentHandler) PublishComment(c *gin.Context) { AuthorID: authorId, Content: req.Content, } + // 客户端可以自带 request_id 来表达"这就是我刚才那次提交"。 + // 不传则由服务端生成:同一个请求内的所有写入仍然共用一个键(G6)。 + if req.RequestID != "" { + requestID := req.RequestID + comment.IdempotencyKey = &requestID + } if err := h.service.Publish(c.Request.Context(), comment); err != nil { c.JSON(apierror.ClassifyHTTPStatus(err), gin.H{"error": err.Error()}) return } - c.JSON(200, gin.H{"message": "comment published successfully"}) + // 回显 request_id:客户端重试时可以带上同一个值,服务端据此判重。 + // 刻意不返回评论 ID——MQ 路径上评论此刻可能还没落库,返回一个还不存在的 + // id 只会制造"点进去 404"的错觉。 + resp := gin.H{"message": "comment published successfully"} + if comment.IdempotencyKey != nil { + resp["request_id"] = *comment.IdempotencyKey + } + c.JSON(200, resp) } func (h *CommentHandler) DeleteComment(c *gin.Context) { diff --git a/backend/internal/video/comment_service.go b/backend/internal/video/comment_service.go index 782a9ee..c29fc79 100644 --- a/backend/internal/video/comment_service.go +++ b/backend/internal/video/comment_service.go @@ -3,95 +3,137 @@ package video import ( "context" "errors" - "feedsystem_video_go/internal/apierror" - "feedsystem_video_go/internal/middleware/rabbitmq" - rediscache "feedsystem_video_go/internal/middleware/redis" + "fmt" "log" "regexp" "strings" - "gorm.io/gorm" + "feedsystem_video_go/internal/apierror" + "feedsystem_video_go/internal/middleware/rabbitmq" + rediscache "feedsystem_video_go/internal/middleware/redis" ) +// CommentPublisher 只暴露评论服务用得到的两个动作。 +// +// 用接口而不是具体类型,是为了让"发布失败"成为可注入的场景:P0-4 的全部 +// 分支都取决于"这条消息到底发出去了没有",而这恰恰是真实 broker 最难稳定 +// 复现的状态。 +// +// 注意:nil 指针装进接口后 != nil 依然为 true,所以真实实现必须在 nil +// 接收者上返回 error(commentMQ.go 现状已如此)。 +type CommentPublisher interface { + Publish(ctx context.Context, evt rabbitmq.CommentEvent) error + Delete(ctx context.Context, commentID uint, intentKey string) error +} + +// PopularityPublisher 是热度事件的最小接口。 +type PopularityPublisher interface { + Update(ctx context.Context, videoID uint, change int64, intentKey string) error +} + +// videoExister 只暴露 CommentService 需要的那一个方法。 +// *VideoRepository 天然满足它,因此 router.go 的构造代码不需要改。 +type videoExister interface { + IsExist(ctx context.Context, id uint) (bool, error) +} + type CommentService struct { - repo *CommentRepository - VideoRepository *VideoRepository - cache *rediscache.Client - commentMQ *rabbitmq.CommentMQ - popularityMQ *rabbitmq.PopularityMQ + store CommentStore + videos videoExister + cache *rediscache.Client + commentMQ CommentPublisher + popularityMQ PopularityPublisher } -func NewCommentService(repo *CommentRepository, videoRepo *VideoRepository, cache *rediscache.Client, commentMQ *rabbitmq.CommentMQ, popularityMQ *rabbitmq.PopularityMQ) *CommentService { - return &CommentService{repo: repo, VideoRepository: videoRepo, cache: cache, commentMQ: commentMQ, popularityMQ: popularityMQ} +func NewCommentService(store CommentStore, videos videoExister, cache *rediscache.Client, commentMQ CommentPublisher, popularityMQ PopularityPublisher) *CommentService { + return &CommentService{ + store: store, + videos: videos, + cache: cache, + commentMQ: commentMQ, + popularityMQ: popularityMQ, + } } +// Publish 把一次"用户想发一条评论"的意图变成一次写入(P0-4 §6.5.2)。 +// +// 关键在于:MQ 路径与兜底路径共用同一个意图键,而"判重"发生在唯一索引上, +// 不是在内存里。因此 +// +// - 消息发布成功 → 由 worker 写库,API 不写(否则正常路径会稳定双写); +// - 消息发布失败 → API 直写,键仍是同一个,worker 稍后到达时命中唯一索引; +// - 客户端重试 → 同一个键,第二次什么都不做,但返回成功。 +// +// 发布失败不代表"没送达"(短超时、channel 抖动都可能发生在 broker 已收下 +// 之后),这正是旧代码的 D1:把 error 当成"未送达",于是必然双写。 func (s *CommentService) Publish(ctx context.Context, comment *Comment) error { if comment == nil { return errors.New("comment is nil") } - comment.Username = strings.TrimSpace(comment.Username) comment.Content = strings.TrimSpace(comment.Content) - if comment.VideoID == 0 || comment.AuthorID == 0 { - return errors.New("video_id and author_id are required") - } - if comment.Content == "" { - return errors.New("content is required") + comment.Username = strings.TrimSpace(comment.Username) + if comment.Content == "" || comment.VideoID == 0 || comment.AuthorID == 0 { + return fmt.Errorf("%w: video_id, author_id and content are required", apierror.ErrValidation) } - exists, err := s.VideoRepository.IsExist(ctx, comment.VideoID) + key, err := ResolveIntentKey(comment.IdempotencyKey) if err != nil { return err } - if !exists { - return errors.New("video not found") + comment.IdempotencyKey = &key + span := logIntent("comment.publish", key, comment.AuthorID, comment.VideoID) + + if ok, err := s.videos.IsExist(ctx, comment.VideoID); err != nil { + return err + } else if !ok { + return fmt.Errorf("%w: video not found", apierror.ErrValidation) } - mysqlEnqueued := false - redisEnqueued := false - if s.commentMQ != nil { - if err := s.commentMQ.Publish(ctx, comment.Username, comment.VideoID, comment.AuthorID, comment.Content); err == nil { - mysqlEnqueued = true - } - } - if s.popularityMQ != nil { - if err := s.popularityMQ.Update(ctx, comment.VideoID, 1, ""); err == nil { - redisEnqueued = true - } - } - if mysqlEnqueued && redisEnqueued { - s.notifyMentions(ctx, comment) - return nil + commentEnqueued := false + if err := s.commentMQ.Publish(ctx, rabbitmq.CommentEvent{ + EventID: key, + Action: "publish", + Username: comment.Username, + VideoID: comment.VideoID, + AuthorID: comment.AuthorID, + Content: comment.Content, + }); err == nil { + commentEnqueued = true + } else { + log.Printf("%s enqueue comment failed, fallback to direct write: %v", span, err) } - // Fallback: direct MySQL write when comment MQ publish fails. - if !mysqlEnqueued { - if err := s.repo.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { - if err := tx.Select("id").First(&Video{}, comment.VideoID).Error; err != nil { - if errors.Is(err, gorm.ErrRecordNotFound) { - return errors.New("video not found") - } - return err - } - if err := tx.Create(comment).Error; err != nil { - return err - } - return tx.Model(&Video{}).Where("id = ?", comment.VideoID). - UpdateColumn("popularity", gorm.Expr("popularity + 1")).Error - }); err != nil { - return err + popularityEnqueued := false + if err := s.popularityMQ.Update(ctx, comment.VideoID, 1, key); err == nil { + popularityEnqueued = true + } else { + log.Printf("%s enqueue popularity failed, fallback to hot cache: %v", span, err) + } + + // —— 闸 1:只有评论事件没入队时才直写。 + // 入队成功时不写:让 worker 去写,避免"入队成功但 API 又写一遍"的必然双写。 + if !commentEnqueued { + created, err := s.store.CreateIdempotentWithPopularity(ctx, comment, 1) + if err != nil { + return fmt.Errorf("fallback create comment: %w", err) + } + log.Printf("%s fallback write dedupe=%s", span, dedupeLabel(created)) + } + + // —— 热度兜底:与评论事件彼此独立(两条事件是两次独立发布)。 + // 热榜是"近似正确"的派生数据:失败只降级,不影响"评论已发布"的语义。 + if !popularityEnqueued { + if err := UpdatePopularityCache(ctx, s.cache, comment.VideoID, 1, key); err != nil { + log.Printf("%s hot cache update failed (degraded): %v", span, err) } } - // Fallback: direct Redis update when popularity MQ publish fails. - if !redisEnqueued { - UpdatePopularityCache(ctx, s.cache, comment.VideoID, 1, "") - } - s.notifyMentions(ctx, comment) + s.notifyMentions(ctx, comment, key) return nil } func (s *CommentService) Delete(ctx context.Context, commentID uint, accountID uint) error { - comment, err := s.repo.GetByID(ctx, commentID) + comment, err := s.store.GetByID(ctx, commentID) if err != nil { return err } @@ -101,58 +143,101 @@ func (s *CommentService) Delete(ctx context.Context, commentID uint, accountID u if comment.AuthorID != accountID { return apierror.ErrUnauthorized } - if s.commentMQ != nil { - if err := s.commentMQ.Delete(ctx, commentID); err == nil { - return nil - } + // 删除事件的 event_id 也用意图键:同一次删除被重复投递时,worker 侧 + // 按 id 删除并检查受影响行数,第二次是空操作。 + key, keyErr := NewIntentKey() + if keyErr != nil { + key = "" } - return s.repo.DeleteComment(ctx, comment) + if err := s.commentMQ.Delete(ctx, commentID, key); err == nil { + return nil + } + return s.store.DeleteComment(ctx, comment) } func (s *CommentService) GetAll(ctx context.Context, videoID uint) ([]Comment, error) { - exists, err := s.VideoRepository.IsExist(ctx, videoID) + exists, err := s.videos.IsExist(ctx, videoID) if err != nil { return nil, err } if !exists { - return nil, errors.New("video not found") + return nil, fmt.Errorf("%w: video not found", apierror.ErrValidation) } - return s.repo.GetAllComments(ctx, videoID) + return s.store.GetAllComments(ctx, videoID) } var mentionRegex = regexp.MustCompile(`@(\w+)`) -func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment) { +// notifyMentions 写入 @ 提及通知。 +// +// 三次往返收敛成两次(一次批量查用户名、一次批量插),并且每条通知都带 +// 绑定到意图键的去重键:同一条评论被重复投递时,通知也只有一条。 +func (s *CommentService) notifyMentions(ctx context.Context, comment *Comment, intentKey string) { matches := mentionRegex.FindAllStringSubmatch(comment.Content, -1) if len(matches) == 0 { return } - seen := make(map[string]bool) + + seen := make(map[string]struct{}, len(matches)) + names := make([]string, 0, len(matches)) for _, m := range matches { - username := m[1] - if seen[username] || username == comment.Username { + name := m[1] + if name == comment.Username { continue } - seen[username] = true - var accID uint - if err := s.repo.db.WithContext(ctx).Table("accounts").Where("username = ?", username).Select("id").Scan(&accID).Error; err != nil || accID == 0 { + if _, dup := seen[name]; dup { continue } - notif := struct { - RecipientID uint - SenderID uint - Type string - TargetID uint - Content string - }{ - RecipientID: accID, + seen[name] = struct{}{} + names = append(names, name) + } + if len(names) == 0 { + return + } + + ids, err := s.store.FindAccountIDs(ctx, names) + if err != nil { + log.Printf("intent_key=%s stage=mention.lookup err=%v", intentKey, err) + return + } + + mentions := make([]Mention, 0, len(ids)) + for _, name := range names { + id, ok := ids[name] + if !ok || id == 0 { + continue + } + if id == comment.AuthorID { + continue // 不给自己发通知 + } + mentions = append(mentions, Mention{ + RecipientID: id, SenderID: comment.AuthorID, - Type: "mention", TargetID: comment.VideoID, Content: comment.Username + " 在评论中提到了你", - } - if err := s.repo.db.WithContext(ctx).Table("notifications").Create(¬if).Error; err != nil { - log.Printf("create mention notification failed: %v", err) - } + DedupeKey: NotificationDedupeKey("mention", intentKey, id), + }) + } + if len(mentions) == 0 { + return + } + + if err := s.store.CreateMentions(ctx, mentions); err != nil { + // 通知是派生副作用:失败不改变"评论已发布"的结论(保持现状语义), + // 但必须留痕,否则"用户说没收到通知"无从排查。 + log.Printf("intent_key=%s stage=mention.create err=%v", intentKey, err) } } + +// logIntent 返回一段可 grep 的公共前缀:一次意图的所有日志都带同一个 key, +// 因此"用户说没看到评论"可以用 grep intent_key= 串起 API 与 Worker 两侧。 +func logIntent(stage, key string, authorID, videoID uint) string { + return fmt.Sprintf("intent_key=%s stage=%s author_id=%d video_id=%d", key, stage, authorID, videoID) +} + +func dedupeLabel(created bool) string { + if created { + return "miss" + } + return "hit" +} diff --git a/backend/internal/video/comment_service_test.go b/backend/internal/video/comment_service_test.go new file mode 100644 index 0000000..9ca54e9 --- /dev/null +++ b/backend/internal/video/comment_service_test.go @@ -0,0 +1,240 @@ +package video + +import ( + "context" + "errors" + "testing" + + "feedsystem_video_go/internal/apierror" + "feedsystem_video_go/internal/middleware/rabbitmq" +) + +type fakeVideoExister struct { + exists bool + err error +} + +func (f *fakeVideoExister) IsExist(_ context.Context, _ uint) (bool, error) { + return f.exists, f.err +} + +type fakeCommentStore struct { + createCalls int + created bool + createErr error + lastComment *Comment + lastDelta int64 + + findNames []string + ids map[string]uint + findErr error + + mentions []Mention + mentionsErr error +} + +func (f *fakeCommentStore) CreateIdempotentWithPopularity(_ context.Context, c *Comment, delta int64) (bool, error) { + f.createCalls++ + f.lastComment = c + f.lastDelta = delta + return f.created, f.createErr +} + +func (f *fakeCommentStore) GetByID(_ context.Context, _ uint) (*Comment, error) { return nil, nil } + +func (f *fakeCommentStore) DeleteComment(_ context.Context, _ *Comment) error { return nil } + +func (f *fakeCommentStore) DeleteByID(_ context.Context, _ uint) (bool, error) { return false, nil } + +func (f *fakeCommentStore) GetAllComments(_ context.Context, _ uint) ([]Comment, error) { + return nil, nil +} + +func (f *fakeCommentStore) CreateMentions(_ context.Context, m []Mention) error { + f.mentions = append(f.mentions, m...) + return f.mentionsErr +} + +func (f *fakeCommentStore) FindAccountIDs(_ context.Context, names []string) (map[string]uint, error) { + f.findNames = names + return f.ids, f.findErr +} + +type fakeCommentPublisher struct { + events []rabbitmq.CommentEvent + pubErr error +} + +func (f *fakeCommentPublisher) Publish(_ context.Context, evt rabbitmq.CommentEvent) error { + f.events = append(f.events, evt) + return f.pubErr +} + +func (f *fakeCommentPublisher) Delete(_ context.Context, _ uint, _ string) error { return nil } + +type popularityCall struct { + videoID uint + change int64 + key string +} + +type fakePopularityPublisher struct { + calls []popularityCall + pubErr error +} + +func (f *fakePopularityPublisher) Update(_ context.Context, videoID uint, change int64, intentKey string) error { + f.calls = append(f.calls, popularityCall{videoID: videoID, change: change, key: intentKey}) + return f.pubErr +} + +type commentFixture struct { + svc *CommentService + store *fakeCommentStore + comments *fakeCommentPublisher + pop *fakePopularityPublisher +} + +func newCommentFixture(t *testing.T) *commentFixture { + t.Helper() + store := &fakeCommentStore{created: true, ids: map[string]uint{}} + comments := &fakeCommentPublisher{} + pop := &fakePopularityPublisher{} + cache, _ := newTestCache(t) + svc := NewCommentService(store, &fakeVideoExister{exists: true}, cache, comments, pop) + return &commentFixture{svc: svc, store: store, comments: comments, pop: pop} +} + +func newComment(videoID, authorID uint, content string) *Comment { + return &Comment{VideoID: videoID, AuthorID: authorID, Username: "alice", Content: content} +} + +// 两条事件都发出去之后,API 绝不能再写一次库:否则"MQ 正常"的常规路径 +// 会稳定产生两条评论——这正是 P0-4 的核心症状之一。 +func TestCommentService_Publish_BothEnqueued_SkipsLocalWrite(t *testing.T) { + f := newCommentFixture(t) + if err := f.svc.Publish(context.Background(), newComment(7, 1, "hello")); err != nil { + t.Fatalf("Publish: %v", err) + } + if f.store.createCalls != 0 { + t.Fatalf("store.CreateIdempotentWithPopularity 调用 %d 次, want 0", f.store.createCalls) + } + if len(f.comments.events) != 1 || f.comments.events[0].EventID == "" { + t.Fatalf("评论事件 = %+v, want 1 条且带 event_id", f.comments.events) + } + if len(f.pop.calls) != 1 || f.pop.calls[0].key == "" { + t.Fatalf("热度事件 = %+v, want 1 条且带意图键", f.pop.calls) + } + if f.comments.events[0].EventID != f.pop.calls[0].key { + t.Fatalf("两条事件必须共享同一个意图键: comment=%q popularity=%q", + f.comments.events[0].EventID, f.pop.calls[0].key) + } +} + +// 评论事件发不出去时才直写,且直写必须带着同一个意图键—— +// 这样"消息其实进了队列、稍后被消费"与"API 已经直写"能收敛成一行。 +func TestCommentService_Publish_CommentPublishFails_WritesLocallyWithIntentKey(t *testing.T) { + f := newCommentFixture(t) + f.comments.pubErr = errors.New("broker down") + + if err := f.svc.Publish(context.Background(), newComment(7, 1, "hello")); err != nil { + t.Fatalf("Publish: %v", err) + } + if f.store.createCalls != 1 { + t.Fatalf("兜底写入 %d 次, want 1", f.store.createCalls) + } + written := f.store.lastComment.IdempotencyKey + if written == nil || *written == "" { + t.Fatal("兜底写入的评论必须带上意图键,否则 worker 侧无法判重") + } + if got := f.pop.calls[0].key; got != *written { + t.Fatalf("兜底写入的键 %q 与热度事件的键 %q 不一致", *written, got) + } + if f.store.lastDelta != 1 { + t.Fatalf("热度增量 = %d, want 1", f.store.lastDelta) + } +} + +// 评论事件入队成功、热度发布失败:这是旧代码返回 500 的那条路径。 +// 现在只降级更新热榜,库由 worker 写,接口返回成功。 +func TestCommentService_Publish_PopularityPublishFails_AppliesHotCacheOnce(t *testing.T) { + f := newCommentFixture(t) + f.pop.pubErr = errors.New("broker down") + + if err := f.svc.Publish(context.Background(), newComment(9, 1, "hello")); err != nil { + t.Fatalf("Publish 不应失败: %v", err) + } + if f.store.createCalls != 0 { + t.Fatalf("评论已入队,不应直写,实际调用 %d 次", f.store.createCalls) + } +} + +// 同一个意图键重复提交是正常语义(客户端重试),不能报错、也不能新增行。 +func TestCommentService_Publish_RepeatSameIntent_DoesNotError(t *testing.T) { + f := newCommentFixture(t) + f.comments.pubErr = errors.New("broker down") + f.store.created = false // 第二次:唯一索引命中 + + first := newComment(7, 1, "hello") + key := "intent-repeat-1" + first.IdempotencyKey = &key + if err := f.svc.Publish(context.Background(), first); err != nil { + t.Fatalf("首次 Publish: %v", err) + } + + second := newComment(7, 1, "hello") + second.IdempotencyKey = &key + if err := f.svc.Publish(context.Background(), second); err != nil { + t.Fatalf("重复 Publish 不应报错: %v", err) + } + if f.store.createCalls != 2 { + t.Fatalf("两次都应尝试写入(由唯一索引判重),实际 %d 次", f.store.createCalls) + } +} + +// 非法的 request_id 是客户端错误,必须落 400 而不是 500。 +func TestCommentService_Publish_InvalidRequestID(t *testing.T) { + f := newCommentFixture(t) + bad := "bad key with spaces" + c := newComment(7, 1, "hello") + c.IdempotencyKey = &bad + + err := f.svc.Publish(context.Background(), c) + if err == nil { + t.Fatal("非法 request_id 必须报错") + } + if got := apierror.ClassifyHTTPStatus(err); got != 400 { + t.Fatalf("HTTP 状态 = %d, want 400 (err=%v)", got, err) + } + if f.store.createCalls != 0 { + t.Fatal("非法键不得写入任何一行") + } +} + +// 提及通知的去重键必须绑定到同一次意图,且只查一次库、跳过自己。 +func TestCommentService_NotifyMentions_DedupeKeyBoundToIntent(t *testing.T) { + f := newCommentFixture(t) + f.store.ids = map[string]uint{"alice": 1, "bob": 2} + + c := newComment(7, 1, "@alice @bob @bob hi") + key := "intent-mention-1" + c.IdempotencyKey = &key + if err := f.svc.Publish(context.Background(), c); err != nil { + t.Fatalf("Publish: %v", err) + } + + // 自己(alice)不进查询;@bob 出现两次只查一次。 + if len(f.store.findNames) != 1 || f.store.findNames[0] != "bob" { + t.Fatalf("用户名去重后应只查 [bob],实际 %v", f.store.findNames) + } + if len(f.store.mentions) != 1 { + t.Fatalf("提及通知 = %+v, want 1 条(alice 是自己)", f.store.mentions) + } + m := f.store.mentions[0] + if m.RecipientID != 2 || m.SenderID != 1 || m.TargetID != 7 { + t.Fatalf("提及通知字段 = %+v", m) + } + if want := "mention:" + key + ":2"; m.DedupeKey != want { + t.Fatalf("去重键 = %q, want %q", m.DedupeKey, want) + } +} diff --git a/backend/internal/worker/commentworker.go b/backend/internal/worker/commentworker.go index 1ac8c73..b7e3651 100644 --- a/backend/internal/worker/commentworker.go +++ b/backend/internal/worker/commentworker.go @@ -15,12 +15,12 @@ import ( type CommentWorker struct { ch *amqp.Channel - comments *video.CommentRepository + comments video.CommentStore videos *video.VideoRepository queue string } -func NewCommentWorker(ch *amqp.Channel, comments *video.CommentRepository, videos *video.VideoRepository, queue string) *CommentWorker { +func NewCommentWorker(ch *amqp.Channel, comments video.CommentStore, videos *video.VideoRepository, queue string) *CommentWorker { return &CommentWorker{ch: ch, comments: comments, videos: videos, queue: queue} } @@ -117,22 +117,35 @@ func (w *CommentWorker) applyPublish(ctx context.Context, evt *rabbitmq.CommentE AuthorID: evt.AuthorID, Content: strings.TrimSpace(evt.Content), } - if err := w.comments.CreateComment(ctx, c); err != nil { + // 事件里的 event_id 就是"这次用户意图"的键。API 侧若已经兜底直写过, + // 这次插入会命中唯一索引:(created=false) 说明重复投递,热度不能再加一次。 + if evt.EventID != "" { + key := evt.EventID + c.IdempotencyKey = &key + } + + created, err := w.comments.CreateIdempotentWithPopularity(ctx, c, 1) + if err != nil { return err } - return w.videos.ChangePopularity(ctx, evt.VideoID, 1) + 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 } func (w *CommentWorker) applyDelete(ctx context.Context, evt *rabbitmq.CommentEvent) error { if evt == nil || evt.CommentID == 0 { return nil } - c, err := w.comments.GetByID(ctx, evt.CommentID) + deleted, err := w.comments.DeleteByID(ctx, evt.CommentID) if err != nil { return err } - if c == nil { - return nil + if !deleted { + // 重复投递的删除是空操作,不是错误。 + log.Printf("comment worker: comment already deleted id=%d event_id=%s", evt.CommentID, evt.EventID) } - return w.comments.DeleteComment(ctx, c) + return nil } diff --git a/backend/internal/worker/commentworker_integration_test.go b/backend/internal/worker/commentworker_integration_test.go new file mode 100644 index 0000000..ff39da1 --- /dev/null +++ b/backend/internal/worker/commentworker_integration_test.go @@ -0,0 +1,161 @@ +//go:build integration + +package worker + +import ( + "context" + "os" + "strings" + "testing" + + "feedsystem_video_go/internal/middleware/rabbitmq" + "feedsystem_video_go/internal/video" + + "gorm.io/driver/mysql" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +// 评论消费者"只写一次评论、不再碰热度"这条不变式只能在真实 MySQL 上验证: +// 判重落在唯一索引 (author_id, idempotency_key) 上,没有数据库就没有被测对象。 +// +// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \ +// go test -tags integration -count=1 ./internal/worker/ + +func newCommentWorkerTestDB(t *testing.T) *gorm.DB { + t.Helper() + dsn := os.Getenv("MYSQL_TEST_DSN") + if dsn == "" { + t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)") + } + if strings.Contains(dsn, "clientFoundRows") { + t.Fatalf("测试 DSN 不能带 clientFoundRows:它会让 RowsAffected 判重失效") + } + db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ + Logger: logger.Default.LogMode(logger.Silent), + }) + if err != nil { + t.Fatalf("connect mysql: %v", err) + } + if err := db.Migrator().DropTable(&video.Comment{}, &video.Video{}); err != nil { + t.Fatalf("drop tables: %v", err) + } + if err := db.AutoMigrate(&video.Video{}, &video.Comment{}); err != nil { + t.Fatalf("migrate: %v", err) + } + return db +} + +func seedCommentVideo(t *testing.T, db *gorm.DB) *video.Video { + t.Helper() + v := &video.Video{ + AuthorID: 99, + Username: "owner", + Title: "t", + PlayURL: "p", + CoverURL: "c", + Popularity: 0, + } + if err := db.Create(v).Error; err != nil { + t.Fatalf("seed video: %v", err) + } + return v +} + +// 同一条评论事件被投递两次(假失败 + 兜底 + 重投的必然结果),只能落一行, +// 数据库热度也只能加一次。 +// +// 两个断言分别钉住两件不同的事:行数 = 1 证明唯一索引吸收了重复;热度 = 1 +// (而不是 2)证明"加热度"与"插入评论"在同一个事务里、且以 created 为门控。 +// 热度写在这里而不是 Redis,是因为 videos.popularity 与 comments 必须原子 +// 提交——Redis 那条轨由 popularity 事件单独负责。 +func TestCommentWorker_ApplyPublish_DuplicateEventWritesOneRow(t *testing.T) { + db := newCommentWorkerTestDB(t) + v := seedCommentVideo(t, db) + w := NewCommentWorker(nil, video.NewCommentRepository(db), video.NewVideoRepository(db), "comment.events") + evt := &rabbitmq.CommentEvent{ + EventID: "evt-comment-1", + Action: "publish", + Username: "alice", + VideoID: v.ID, + AuthorID: 1, + Content: "好看", + } + + for i := 0; i < 2; i++ { + if err := w.applyPublish(context.Background(), evt); err != nil { + t.Fatalf("第 %d 次 applyPublish: %v", i+1, err) + } + } + + var count int64 + if err := db.Model(&video.Comment{}).Where("video_id = ?", v.ID).Count(&count).Error; err != nil { + t.Fatalf("count comments: %v", err) + } + if count != 1 { + t.Fatalf("评论行数 = %d, want 1(event_id 相同的重复投递必须被判重吸收)", count) + } + + var got video.Video + if err := db.First(&got, v.ID).Error; err != nil { + t.Fatalf("reload video: %v", err) + } + if got.Popularity != 1 { + t.Fatalf("popularity = %d, want 1(重复投递不得再加一次)", got.Popularity) + } +} + +// event_id 为空(老版本消息/手工构造)时不能去重:没有键就无法判断重复, +// 插入 NULL 键是唯一正确选择——用空字符串会撞唯一索引,把所有后续评论都吃掉。 +func TestCommentWorker_ApplyPublish_EmptyEventIDStillWrites(t *testing.T) { + db := newCommentWorkerTestDB(t) + v := seedCommentVideo(t, db) + w := NewCommentWorker(nil, video.NewCommentRepository(db), video.NewVideoRepository(db), "comment.events") + + evt := &rabbitmq.CommentEvent{ + Action: "publish", + Username: "alice", + VideoID: v.ID, + AuthorID: 1, + Content: "第一条", + } + if err := w.applyPublish(context.Background(), evt); err != nil { + t.Fatalf("applyPublish: %v", err) + } + + var c video.Comment + if err := db.Where("video_id = ?", v.ID).First(&c).Error; err != nil { + t.Fatalf("load comment: %v", err) + } + if c.IdempotencyKey != nil { + t.Fatalf("IdempotencyKey = %q, want NULL", *c.IdempotencyKey) + } +} + +// 删除事件重投两次:第二次是空操作,不是错误(否则会被当成故障送去停泊)。 +func TestCommentWorker_ApplyDelete_DuplicateIsNoop(t *testing.T) { + db := newCommentWorkerTestDB(t) + v := seedCommentVideo(t, db) + repo := video.NewCommentRepository(db) + w := NewCommentWorker(nil, repo, video.NewVideoRepository(db), "comment.events") + + c := &video.Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x"} + if _, err := repo.CreateIdempotentWithPopularity(context.Background(), c, 0); err != nil { + t.Fatalf("seed comment: %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) + } + } + + var count int64 + if err := db.Model(&video.Comment{}).Where("id = ?", c.ID).Count(&count).Error; err != nil { + t.Fatalf("count: %v", err) + } + if count != 0 { + t.Fatalf("评论行数 = %d, want 0", count) + } +}