点赞与评论的计数只由业务事务写。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 ./... 全绿。
296 lines
9.1 KiB
Go
296 lines
9.1 KiB
Go
//go:build integration
|
||
|
||
package video
|
||
|
||
import (
|
||
"context"
|
||
"os"
|
||
"strings"
|
||
"sync"
|
||
"testing"
|
||
|
||
"feedsystem_video_go/internal/notification"
|
||
|
||
"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{}, &Like{}, ¬ification.Notification{}, &testAccount{}); err != nil {
|
||
t.Fatalf("drop tables: %v", err)
|
||
}
|
||
if err := db.AutoMigrate(&testAccount{}, &Video{}, &Comment{}, &Like{}, ¬ification.Notification{}); 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 []notification.Notification
|
||
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)
|
||
}
|
||
}
|
||
|
||
// 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)
|
||
}
|
||
}
|