Files
VLoop/backend/internal/worker/commentworker_integration_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

162 lines
5.2 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.
//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)
}
}