From a9c034073362b228e8f6a6f892b8ecd88d95c04c Mon Sep 17 00:00:00 2001 From: huanghaosheng <386998068@qq.com> Date: Fri, 30 Oct 2026 13:21:09 +0800 Subject: [PATCH] =?UTF-8?q?feat(video):=20=E8=AF=84=E8=AE=BA=E5=B9=82?= =?UTF-8?q?=E7=AD=89=E5=86=99=E5=85=A5=E4=B8=8E=E6=8F=90=E5=8F=8A=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E5=8E=BB=E9=87=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 非零、用户名批量解析。 --- backend/internal/video/comment_entity.go | 23 +- backend/internal/video/comment_repo.go | 117 +++++++++ .../video/comment_repo_integration_test.go | 245 ++++++++++++++++++ backend/internal/video/comment_store.go | 79 ++++++ 4 files changed, 463 insertions(+), 1 deletion(-) create mode 100644 backend/internal/video/comment_repo_integration_test.go create mode 100644 backend/internal/video/comment_store.go diff --git a/backend/internal/video/comment_entity.go b/backend/internal/video/comment_entity.go index c0cd55e..35ff422 100644 --- a/backend/internal/video/comment_entity.go +++ b/backend/internal/video/comment_entity.go @@ -6,14 +6,35 @@ type Comment struct { ID uint `gorm:"primaryKey" json:"id"` Username string `gorm:"index" json:"username"` VideoID uint `gorm:"index" json:"video_id"` - AuthorID uint `gorm:"index" json:"author_id"` + AuthorID uint `gorm:"index;uniqueIndex:uk_comments_author_key,priority:1" json:"author_id"` Content string `gorm:"type:text" json:"content"` CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` + + // IdempotencyKey 是"这次发评论的意图"的稳定标识(P0-4)。 + // + // 与 AuthorID 组成唯一索引 uk_comments_author_key:同一次用户意图 + // 无论被写入几次(MQ 假失败后的 DB 兜底、worker 重复投递、客户端 + // 重试),在数据库里都只会留下一行。 + // + // 必须是指针:MySQL 的唯一索引不约束 NULL,多个 NULL 可以共存。 + // 若用 string + 空串,存量行与"没带 request_id"的行会全部撞在 + // 同一个 '' 上,第二条无键评论就会被判成重复。 + // + // json:"-" 让它不出现在任何 API 响应里:它是去重机制的内部标识, + // 不是用户可见的数据。 + IdempotencyKey *string `gorm:"column:idempotency_key;type:varchar(64);uniqueIndex:uk_comments_author_key,priority:2" json:"-"` } type PublishCommentRequest struct { VideoID uint `json:"video_id"` Content string `json:"content"` + + // RequestID 由客户端为"一次发送动作"生成,重试时复用同一个值。 + // + // 为空时服务端会生成一个(单次请求内仍然幂等,但客户端重试无法被识别)。 + // 校验规则见 idempotency.go:8–64 个 [0-9a-zA-Z_-] 字符,非法值返回 400 + // 而不是静默截断或忽略。 + RequestID string `json:"request_id"` } type DeleteCommentRequest struct { diff --git a/backend/internal/video/comment_repo.go b/backend/internal/video/comment_repo.go index d64882e..1ad12fa 100644 --- a/backend/internal/video/comment_repo.go +++ b/backend/internal/video/comment_repo.go @@ -2,8 +2,10 @@ package video import ( "context" + "time" "gorm.io/gorm" + "gorm.io/gorm/clause" ) type CommentRepository struct { @@ -18,10 +20,71 @@ func (r *CommentRepository) CreateComment(ctx context.Context, comment *Comment) return r.db.WithContext(ctx).Create(comment).Error } +// CreateIdempotentWithPopularity 是 P0-4 的核心写入口。 +// +// 它把两件必须同生共死的事放进同一个事务: +// +// 1. 插入评论——由 uk_comments_author_key(author_id, idempotency_key) 判重, +// 重复时静默返回 created=false,不报错、不覆盖。 +// 2. 视频热度 +delta——只在真的插入了这一行时才执行。 +// +// 为什么判重不能靠"先 SELECT 再 INSERT":两个 goroutine 之间永远有窗口, +// 而这条窗口正好是 P0-4 的场景(MQ 假失败后兜底直写 + worker 稍后消费)。 +// 让数据库的唯一索引来裁决,判重与写入就变成同一个原子动作,没有窗口。 +// +// 为什么不用 1062 判重:报错与去重是两种不同的语义,用报错表达去重会让 +// 每一条正常路径都经过一次 error 分支,也难以区分"真冲突"与"别的 1062"。 +// OnConflict DoNothing 直接给出 RowsAffected——它就是"我是否真的插入了"。 +// +// 注意:本项目 DSN(internal/db/db.go)刻意没有 clientFoundRows。若有人 +// 加上它,MySQL 会在"行未变化"时也报告 1 行受影响,本函数就会把重复写入 +// 当成首次写入,热度变成 +2——判重静默失效。db 包与集成测试各有护栏。 +func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (bool, error) { + var created bool + err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(c) + if res.Error != nil { + return res.Error + } + if res.RowsAffected == 0 { + // 这条意图已经落过库:不是错误,也不再加热度。 + return nil + } + created = true + if delta == 0 { + return nil + } + // 与插入同一个事务:要么"评论与热度"一起生效,要么都不生效。 + // GREATEST(...,0) 防止热度被回滚到负数(与点赞侧一致)。 + return tx.Model(&Video{}). + Where("id = ?", c.VideoID). + UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + ?, 0)", delta)).Error + }) + if err != nil { + return false, err + } + return created, nil +} + func (r *CommentRepository) DeleteComment(ctx context.Context, comment *Comment) error { return r.db.WithContext(ctx).Delete(comment).Error } +// DeleteByID 汇报"这次调用是否真的删掉了一行"。 +// +// 删除的重复投递与新增的重复投递同样致命:把热度回退当成无条件动作, +// 同一条删除事件投递两次就会把热度减两次(P2-20 的门控点就是这个返回值)。 +func (r *CommentRepository) DeleteByID(ctx context.Context, id uint) (bool, error) { + if id == 0 { + return false, nil + } + res := r.db.WithContext(ctx).Delete(&Comment{}, id) + if res.Error != nil { + return false, res.Error + } + return res.RowsAffected > 0, nil +} + func (r *CommentRepository) GetAllComments(ctx context.Context, videoID uint) ([]Comment, error) { var comments []Comment err := r.db.WithContext(ctx). @@ -53,3 +116,57 @@ func (r *CommentRepository) GetByID(ctx context.Context, id uint) (*Comment, err } return &comment, nil } + +// CreateMentions 幂等写入提及通知:DedupeKey 相同则静默跳过。 +// +// 显式写 CreatedAt 而不依赖 autoCreateTime:这条路径写的是"列投影"而不是 +// worker 包的实体,autoCreateTime 只在 GORM 认为字段是零值时才生效——一旦 +// 有人在调用前给 CreatedAt 赋了零值以外的值,两种来源就会打架(P2-16 ①)。 +func (r *CommentRepository) CreateMentions(ctx context.Context, mentions []Mention) error { + if len(mentions) == 0 { + return nil + } + now := time.Now() + rows := make([]NotificationRow, 0, len(mentions)) + for _, m := range mentions { + rows = append(rows, NotificationRow{ + RecipientID: m.RecipientID, + SenderID: m.SenderID, + Type: "mention", + TargetID: m.TargetID, + Content: m.Content, + CreatedAt: now, + DedupeKey: nilIfEmpty(m.DedupeKey), + }) + } + return r.db.WithContext(ctx). + Clauses(clause.OnConflict{DoNothing: true}). + Create(&rows).Error +} + +// FindAccountIDs 一次查询解析一批用户名。 +// +// 逐个 SELECT 会让"一条评论里 @ 了 5 个人"变成 5 次往返,而这段代码跑在 +// 用户请求路径上(P0-4 §6.5)。不存在的用户名不出现在结果里,调用方按 +// map 的不存在分支跳过即可。 +func (r *CommentRepository) FindAccountIDs(ctx context.Context, usernames []string) (map[string]uint, error) { + out := make(map[string]uint, len(usernames)) + if len(usernames) == 0 { + return out, nil + } + var rows []struct { + ID uint + Username string + } + if err := r.db.WithContext(ctx). + Table("accounts"). + Select("id, username"). + Where("username IN ?", usernames). + Scan(&rows).Error; err != nil { + return nil, err + } + for _, row := range rows { + out[row.Username] = row.ID + } + return out, nil +} diff --git a/backend/internal/video/comment_repo_integration_test.go b/backend/internal/video/comment_repo_integration_test.go new file mode 100644 index 0000000..8dedb63 --- /dev/null +++ b/backend/internal/video/comment_repo_integration_test.go @@ -0,0 +1,245 @@ +//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) + } +} diff --git a/backend/internal/video/comment_store.go b/backend/internal/video/comment_store.go new file mode 100644 index 0000000..58e87fa --- /dev/null +++ b/backend/internal/video/comment_store.go @@ -0,0 +1,79 @@ +package video + +import ( + "context" + "time" +) + +// Mention 是一条"提及通知"的写入意图。 +// +// DedupeKey 由 NotificationDedupeKey(notifType, intentKey, recipientID) 生成, +// 落到 notifications 表的唯一索引 uk_notifications_dedupe 上。它让"同一次 +// 评论意图产生的提及通知"无论被写几次都只有一行——与评论本身用的是同一个 +// 意图键,所以两侧的判重是同一个语义,而不是两套各自为政的计数器。 +type Mention struct { + RecipientID uint + SenderID uint + TargetID uint + Content string + DedupeKey string +} + +// NotificationRow 是 notifications 表在 video 包里的投影。 +// +// 为什么不直接 import worker.Notification:worker 包 import 了 video +// (CommentWorker 依赖 CommentStore),反向 import 会成环。这张投影只需要 +// "写一行通知"所需的字段,schema 的权威定义仍在 worker.Notification, +// 因此下面每个列标签都必须与它逐字一致——不一致时 AutoMigrate 会试图改动 +// 生产列类型,那是本方案最不希望引入的意外。 +type NotificationRow struct { + ID uint `gorm:"primaryKey"` + RecipientID uint `gorm:"index;not null"` + SenderID uint `gorm:"not null"` + Type string `gorm:"type:varchar(50);not null"` + TargetID uint `gorm:"column:target_id"` + Content string `gorm:"type:varchar(255)"` + IsRead bool `gorm:"default:false"` + CreatedAt time.Time `gorm:"autoCreateTime"` + + // DedupeKey 与 worker.Notification.DedupeKey 指向同一个唯一索引 + // uk_notifications_dedupe。为 nil 时不参与判重(MySQL 不约束 NULL), + // 这正是"没有意图键的旧路径"仍然能写入的原因。 + DedupeKey *string `gorm:"column:dedupe_key;type:varchar(128);uniqueIndex:uk_notifications_dedupe"` +} + +func (NotificationRow) TableName() string { return "notifications" } + +// CommentStore 是 CommentService 与 CommentWorker 依赖的窄接口。 +// +// 抽接口不是为了"面向接口编程",而是为了给"判重与写入必须发生在同一条 SQL +// 的同一个事务里"这条约束一个显式的名字:任何实现都必须提供 +// CreateIdempotentWithPopularity,而不是先 Create 再补一条热度 UPDATE—— +// 后者在两条语句之间崩溃就会留下"评论在、热度不在"的半成品。 +type CommentStore interface { + // CreateIdempotentWithPopularity 在同一个事务里完成 + // "插入评论(幂等)" + "热度增量(仅首次插入时)"。 + // created=false 表示这条意图已经落过库,调用方不得再加热度。 + CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (created bool, err error) + + GetByID(ctx context.Context, id uint) (*Comment, error) + DeleteComment(ctx context.Context, comment *Comment) error + DeleteByID(ctx context.Context, id uint) (deleted bool, err error) + GetAllComments(ctx context.Context, videoID uint) ([]Comment, error) + + // CreateMentions 按 DedupeKey 幂等写入提及通知。 + CreateMentions(ctx context.Context, mentions []Mention) error + // FindAccountIDs 一次查询把用户名批量解析成账号 ID。 + FindAccountIDs(ctx context.Context, usernames []string) (map[string]uint, error) +} + +// nilIfEmpty 把空串转成 NULL。 +// +// 用于 idempotency_key / dedupe_key 这类"可空唯一列":空串是一个真实的值, +// 多条空串会互相撞唯一索引;NULL 才是"没有这个键"。 +func nilIfEmpty(s string) *string { + if s == "" { + return nil + } + return &s +}