Files
VLoop/backend/internal/video/comment_repo_integration_test.go
huanghaosheng a9c0340733 feat(video): 评论幂等写入与提及通知去重
P0-4 的写层基础:给每次"用户想发一条评论"一个稳定的意图键,并让判重
与写入成为同一条 SQL 的同一个事务。

- comments 加 idempotency_key,与 author_id 组成唯一索引
  uk_comments_author_key。用 *string 而不是 string:MySQL 不约束 NULL,
  多条无键评论才能共存;空串会互相撞键。
- CreateIdempotentWithPopularity 在一个事务里完成"插入评论 + 首次插入时
  视频热度 +1"。重复写入静默返回 created=false,不报错、不覆盖、不再加
  热度。判重交给数据库唯一索引,因此不存在"先 SELECT 再 INSERT"的窗口
  ——那个窗口正是 MQ 假失败后兜底直写与 worker 稍后消费的交错点。
- DeleteByID 汇报是否真的删掉了一行,作为删除侧热度回退的门控点
  (P2-20)。删除事件的重复投递与新增同样会把热度减两次。
- CreateMentions 按 dedupe_key 幂等写入提及通知,并显式写 CreatedAt
  (P2-16 ①);FindAccountIDs 用一次 username IN (?) 替换逐个查询。
- CommentStore 接口把"判重与写入必须同事务"这条约束变成显式的名字。

集成测试(-tags integration,需要 MYSQL_TEST_DSN)覆盖:重复插入报告 0
行且热度只加一次、8 并发只有 1 个 created、多条 NULL 键共存、提及通知
去重且 CreatedAt 非零、用户名批量解析。
2026-10-30 13:21:09 +08:00

246 lines
7.4 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 video
import (
"context"
"os"
"strings"
"sync"
"testing"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// 这些用例需要真实 MySQL:本仓库没有 DB mock,而"判重与写入是同一条 SQL"
// 这个性质的正确性完全取决于 MySQL 的 ON DUPLICATE KEY 语义与 RowsAffected,
// 用内存替身验证等于什么都没验证。
//
// docker compose up -d mysql
// 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/video/
// testAccount 只是 comments 提及解析的目标表投影(FindAccountIDs 查 accounts)。
type testAccount struct {
ID uint `gorm:"primaryKey"`
Username string `gorm:"column:username;type:varchar(255);not null;uniqueIndex"`
}
func (testAccount) TableName() string { return "accounts" }
func newTestDB(t *testing.T) *gorm.DB {
t.Helper()
dsn := os.Getenv("MYSQL_TEST_DSN")
if dsn == "" {
t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)")
}
// clientFoundRows 会让"行未变化"的 UPDATE 也返回 1 行受影响,
// 从而把"重复插入"误判成"插入成功",去重静默失效。生产 DSN
// (internal/db/db.go)同样不能打开它,那里另有单测钉住。
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(&Comment{}, &Video{}, &NotificationRow{}, &testAccount{}); err != nil {
t.Fatalf("drop tables: %v", err)
}
if err := db.AutoMigrate(&testAccount{}, &Video{}, &Comment{}, &NotificationRow{}); err != nil {
t.Fatalf("migrate: %v", err)
}
return db
}
func seedVideo(t *testing.T, db *gorm.DB, popularity int64) *Video {
t.Helper()
v := &Video{
AuthorID: 1, Username: "author", Title: "t",
PlayURL: "p", CoverURL: "c", Popularity: popularity,
}
if err := db.Create(v).Error; err != nil {
t.Fatalf("seed video: %v", err)
}
return v
}
func intPtr(s string) *string { return &s }
// 同一意图键第二次写入必须报告 created=false,并且不得再次加热度。
// 这条断言同时是 DSN 护栏:若 clientFoundRows 被打开,第二次插入会
// 报告 1 行受影响,热度变成 +2。
func TestP0_4_DuplicateInsertReportsZeroRows(t *testing.T) {
db := newTestDB(t)
repo := NewCommentRepository(db)
ctx := context.Background()
v := seedVideo(t, db, 0)
first := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "好看", IdempotencyKey: intPtr("intent-0001")}
created, err := repo.CreateIdempotentWithPopularity(ctx, first, 1)
if err != nil {
t.Fatalf("第一次写入: %v", err)
}
if !created {
t.Fatal("第一次写入必须返回 created=true")
}
second := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "好看", IdempotencyKey: intPtr("intent-0001")}
created, err = repo.CreateIdempotentWithPopularity(ctx, second, 1)
if err != nil {
t.Fatalf("第二次写入应静默去重而不是报错: %v", err)
}
if created {
t.Fatal("同一意图键的第二次写入必须返回 created=false(否则热度会 +2)")
}
var count int64
db.Model(&Comment{}).Count(&count)
if count != 1 {
t.Fatalf("comments 行数 = %d, want 1", count)
}
var got 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)
}
}
// 并发下"先 SELECT 再 INSERT"必然漏判;本用例保证判重确实是数据库唯一索引
// 在做,而不是应用层的检查。同时钉住:并发里只有一个执行者加热度。
func TestP0_4_ConcurrentInsertSingleRow(t *testing.T) {
db := newTestDB(t)
repo := NewCommentRepository(db)
ctx := context.Background()
v := seedVideo(t, db, 0)
const workers = 8
var wg sync.WaitGroup
var mu sync.Mutex
createdCount := 0
errs := make([]error, 0, workers)
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
c := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "并发", IdempotencyKey: intPtr("intent-0002")}
created, err := repo.CreateIdempotentWithPopularity(ctx, c, 1)
mu.Lock()
defer mu.Unlock()
if err != nil {
errs = append(errs, err)
return
}
if created {
createdCount++
}
}()
}
wg.Wait()
if len(errs) > 0 {
t.Fatalf("并发写入出现错误: %v", errs)
}
if createdCount != 1 {
t.Fatalf("created 次数 = %d, want 1", createdCount)
}
var count int64
db.Model(&Comment{}).Count(&count)
if count != 1 {
t.Fatalf("comments 行数 = %d, want 1", count)
}
var got 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)
}
}
// 存量行与旧 Worker 写入的行 idempotency_key 为 NULL,多个 NULL 必须共存,
// 否则迁移一上线,第二条无键评论就会撞唯一索引。
func TestP0_4_LegacyNullKeysCoexist(t *testing.T) {
db := newTestDB(t)
repo := NewCommentRepository(db)
ctx := context.Background()
v := seedVideo(t, db, 0)
for i := 0; i < 3; i++ {
c := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "同一条内容"}
created, err := repo.CreateIdempotentWithPopularity(ctx, c, 1)
if err != nil {
t.Fatalf("第 %d 条无键评论写入失败: %v", i+1, err)
}
if !created {
t.Fatalf("第 %d 条无键评论应被插入(NULL 不参与判重)", i+1)
}
}
var count int64
db.Model(&Comment{}).Count(&count)
if count != 3 {
t.Fatalf("comments 行数 = %d, want 3", count)
}
}
// 提及通知必须带 CreatedAt,且重复投递不得产生第二行。
func TestP0_4_MentionNotificationDedupe(t *testing.T) {
db := newTestDB(t)
repo := NewCommentRepository(db)
ctx := context.Background()
mention := Mention{
RecipientID: 2, SenderID: 1, TargetID: 9,
Content: "@b 在评论中提到了你",
DedupeKey: NotificationDedupeKey("mention", "intent-0003", 2),
}
for i := 0; i < 2; i++ {
if err := repo.CreateMentions(ctx, []Mention{mention}); err != nil {
t.Fatalf("第 %d 次写入提及通知: %v", i+1, err)
}
}
var rows []NotificationRow
if err := db.Find(&rows).Error; err != nil {
t.Fatalf("查询 notifications: %v", err)
}
if len(rows) != 1 {
t.Fatalf("notifications 行数 = %d, want 1(去重键生效)", len(rows))
}
if rows[0].CreatedAt.IsZero() {
t.Fatal("CreatedAt 必须被显式写入(P2-16 ①)")
}
}
func TestFindAccountIDs_BatchResolve(t *testing.T) {
db := newTestDB(t)
repo := NewCommentRepository(db)
ctx := context.Background()
if err := db.Create(&testAccount{Username: "alice"}).Error; err != nil {
t.Fatalf("seed alice: %v", err)
}
if err := db.Create(&testAccount{Username: "bob"}).Error; err != nil {
t.Fatalf("seed bob: %v", err)
}
ids, err := repo.FindAccountIDs(ctx, []string{"alice", "bob", "nobody"})
if err != nil {
t.Fatalf("FindAccountIDs: %v", err)
}
if len(ids) != 2 {
t.Fatalf("解析到 %d 个账号, want 2(不存在的用户名不应出现)", len(ids))
}
if ids["alice"] == 0 || ids["bob"] == 0 || ids["alice"] == ids["bob"] {
t.Fatalf("解析结果异常: %+v", ids)
}
}