Files
VLoop/backend/internal/video/comment_service_test.go
huanghaosheng 953b609970 feat(video): 评论写路径按意图键幂等,HTTP 回显 request_id
同一条用户意图(同 author_id + request_id)在 comments 上只落一行:
唯一索引 uk_comments_author_key 是唯一的判重点,API 与 Worker 共用
同一个键,因此「MQ 假失败后兜底直写」与「消息稍后被消费」不再双写。

- comment_service: 引入 CommentStore/CommentPublisher/PopularityPublisher
  三个最小接口;Publish 先解析意图键,再把同一个键喂给评论事件、热度事件
  与兜底直写。只有评论事件没入队时才直写(闸 1),热度兜底独立门控。
- comment_repo: CreateIdempotentWithPopularity 在单事务内插入评论并按
  created 门控 videos.popularity;CreateMentions 显式补 CreatedAt 并按
  dedupe_key 去重;FindAccountIDs 一次 username IN ? 批量解析。
- commentworker: applyPublish 用 event_id 作幂等键并交给同一个事务,
  !created 记 dedupe=hit;applyDelete 改 DeleteByID,重复删除是空操作。
- comment_handler: 接收 request_id、响应回显,不返回评论 ID(MQ 路径上
  评论此刻可能尚未落库)。
- 提及通知带上绑定到意图键的 dedupe_key,重复投递只写一条。

验证:go test ./... 全绿;-tags integration 下 3 个用例在真实 MySQL 上
通过(重复事件 1 行评论 + 热度只加 1、空 event_id 落 NULL 键、重复删除)
2026-10-30 13:29:08 +08:00

241 lines
7.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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)
}
}