refactor(video): 计数改由业务事务维护并删除热度第二条写路径

点赞与评论的计数只由业务事务写。ApplyLike、ApplyUnlike、CreateIdempotentWithPopularity 与 DeleteWithPopularity 各自在单事务内完成插行与计数。
热榜增量改为提交后的 best-effort 写。ApplyHotDelta 按行的 created_at 落分钟桶,写失败只记日志,DB 计数仍然正确。
删除 PopularityMQ 与 PopularityWorker。同一次互动因此只有一个写者,不再有两个门闩各自放行。
删除 hot:applied 占位键。判重改由 likes 的唯一索引与 uk_comments_author_key 负责。
DeleteWithPopularity 先读行再删行。评论删除因此回退热度,重复投递不再多减一次。
likes 与 comments 各加 (created_at, video_id) 覆盖索引,服务热榜窗口查询。
验证:go build -buildvcs=false ./... 通过。go test -buildvcs=false -count=1 ./... 全绿。
This commit is contained in:
2026-11-01 15:15:15 +08:00
parent c0210b61ba
commit 1b47c9f027
26 changed files with 924 additions and 626 deletions

View File

@@ -51,10 +51,10 @@ func newTestDB(t *testing.T) *gorm.DB {
if err != nil {
t.Fatalf("connect mysql: %v", err)
}
if err := db.Migrator().DropTable(&Comment{}, &Video{}, &notification.Notification{}, &testAccount{}); err != nil {
if err := db.Migrator().DropTable(&Comment{}, &Video{}, &Like{}, &notification.Notification{}, &testAccount{}); err != nil {
t.Fatalf("drop tables: %v", err)
}
if err := db.AutoMigrate(&testAccount{}, &Video{}, &Comment{}, &notification.Notification{}); err != nil {
if err := db.AutoMigrate(&testAccount{}, &Video{}, &Comment{}, &Like{}, &notification.Notification{}); err != nil {
t.Fatalf("migrate: %v", err)
}
return db
@@ -245,3 +245,51 @@ func TestFindAccountIDs_BatchResolve(t *testing.T) {
t.Fatalf("解析结果异常: %+v", ids)
}
}
// P2-20:删除评论必须回退热度,且只能回退一次。
//
// 旧实现只删行(DeleteByID),popularity 永远停在原值。这里双击一次判重:
// 第一次返回 deleted=true 并减 1,第二次读不到行、deleted=false,不得再减。
func TestDeleteWithPopularity_DecrementsOnce(t *testing.T) {
db := newTestDB(t)
repo := NewCommentRepository(db)
ctx := context.Background()
v := seedVideo(t, db, 5)
c := &Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x"}
if _, err := repo.CreateIdempotentWithPopularity(ctx, c, 1); err != nil {
t.Fatalf("seed comment: %v", err)
}
row, deleted, err := repo.DeleteWithPopularity(ctx, c.ID)
if err != nil {
t.Fatalf("DeleteWithPopularity: %v", err)
}
if !deleted {
t.Fatal("首次删除必须报告 deleted=true")
}
if row == nil || row.VideoID != v.ID {
t.Fatalf("返回行 = %+v, want video_id=%d(热度减到哪个视频必须由行决定)", row, v.ID)
}
if row.CreatedAt.IsZero() {
t.Fatal("返回行必须带原始 created_at:热榜 -1 要落回创建那一分钟")
}
var got Video
if err := db.First(&got, v.ID).Error; err != nil {
t.Fatalf("reload video: %v", err)
}
if got.Popularity != 5 {
t.Fatalf("popularity = %d, want 5(5+1-1,删除只减一次)", got.Popularity)
}
if _, deleted, err := repo.DeleteWithPopularity(ctx, c.ID); err != nil || deleted {
t.Fatalf("重复删除 = deleted:%v err:%v, want false/nil", deleted, err)
}
if err := db.First(&got, v.ID).Error; err != nil {
t.Fatalf("reload video: %v", err)
}
if got.Popularity != 5 {
t.Fatalf("重复删除后 popularity = %d, want 5(空操作不能再减)", got.Popularity)
}
}