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

@@ -2,6 +2,7 @@ package video
import (
"context"
"errors"
"time"
"feedsystem_video_go/internal/notification"
@@ -49,20 +50,46 @@ func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context,
return created, nil
}
func (r *CommentRepository) DeleteComment(ctx context.Context, comment *Comment) error {
return r.db.WithContext(ctx).Delete(comment).Error
}
// DeleteByID 返回是否真的删除了一行,供调用方门控热度回退。
func (r *CommentRepository) DeleteByID(ctx context.Context, id uint) (bool, error) {
// DeleteWithPopularity 删除评论,并在同一事务里把所属视频的 popularity 减 1。
//
// 返回被删的那一行:调用方要它的 created_at 把热榜分数减回评论发布那一刻的
// 分钟桶,还要它的 video_id 定位视频。这两个值都从库里取,比事件里的快照
// 更可信——事件到达时行可能已经被别的路径删掉了。
//
// deleted=false 表示没有这一行(重复投递的删除),此时不能再减热度。
func (r *CommentRepository) DeleteWithPopularity(ctx context.Context, id uint) (*Comment, bool, error) {
if id == 0 {
return false, nil
return nil, false, nil
}
res := r.db.WithContext(ctx).Delete(&Comment{}, id)
if res.Error != nil {
return false, res.Error
var deleted *Comment
ok := false
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var row Comment
if err := tx.First(&row, id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil
}
return err
}
res := tx.Delete(&Comment{}, row.ID)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
return nil
}
deleted = &row
ok = true
return tx.Model(&Video{}).
Where("id = ?", row.VideoID).
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity - 1, 0)")).Error
})
if err != nil {
return nil, false, err
}
return res.RowsAffected > 0, nil
return deleted, ok, nil
}
func (r *CommentRepository) GetAllComments(ctx context.Context, videoID uint) ([]Comment, error) {