refactor(p0-5): 收敛热度相关注释

背景叙述与历史取舍已写进 `docs/design/hot-ranking.md`,从源码删除。
只保留不变式与安全约束:`clientFoundRows` 禁令、唯一索引判重、
成员补零的排序约定、快照用 `RENAMENX` 只建一次、`EXPIRE` 失败即删键。

`video_service.go` 的 `NewVideoService` 注释原本复述已删方法的来历,一并收敛。
`zset.go` 的 `ZUnionStore` 与 `RenameNX` 注释各压到四行以内。

验证:go build ./... 通过。
验证:go vet ./... 通过。
验证:go test -count=1 ./... 全绿(本机无 cgo,未跑 -race)。
验证:go test -tags integration -p 1 -count=1 ./internal/feed/ ./internal/video/ ./internal/worker/ 全绿。
This commit is contained in:
2026-11-01 16:47:31 +08:00
parent 006ec5f196
commit d782ccbb53
16 changed files with 74 additions and 132 deletions

View File

@@ -23,9 +23,10 @@ func (r *CommentRepository) CreateComment(ctx context.Context, comment *Comment)
return r.db.WithContext(ctx).Create(comment).Error
}
// CreateIdempotentWithPopularity 由 uk_comments_author_key 判重。
// 热度增量与插入必须同事务,只在 created=true 时执行。
// 注意:DSN 不能开 clientFoundRows,否则 RowsAffected 恒为 1,判重失效。
// CreateIdempotentWithPopularity 由 uk_comments_author_key 判重,
// 热度增量与插入同事务,只在 created=true 时执行。
//
// DSN 不能开 clientFoundRows,否则 RowsAffected 恒为 1,判重失效。
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 {
@@ -52,11 +53,8 @@ func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context,
// DeleteWithPopularity 删除评论,并在同一事务里把所属视频的 popularity 减 1。
//
// 返回被删的那一行:调用方要它的 created_at 把热榜分数减回评论发布那一刻的
// 分钟桶,还要它的 video_id 定位视频。这两个值都从库里取,比事件里的快照
// 更可信——事件到达时行可能已经被别的路径删掉了。
//
// deleted=false 表示没有这一行(重复投递的删除),此时不能再减热度。
// 返回被删的行:调用方要它的 created_at 落桶、要 video_id 定位视频,
// 这两个值从库里取比从事件里取可信。
func (r *CommentRepository) DeleteWithPopularity(ctx context.Context, id uint) (*Comment, bool, error) {
if id == 0 {
return nil, false, nil

View File

@@ -42,10 +42,7 @@ func NewCommentService(store CommentStore, videos videoExister, cache *rediscach
}
}
// Publish 先入队,入队失败才直写。
//
// 热度不再单独发布:它只由"这次插入是否真的落库"驱动,所以两条轨不会
// 各自成功一半。
// Publish 先入队,入队失败才直写;热度只由"这次插入是否真的落库"驱动。
func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
if comment == nil {
return errors.New("comment is nil")
@@ -69,7 +66,7 @@ func (s *CommentService) Publish(ctx context.Context, comment *Comment) error {
return fmt.Errorf("%w: video not found", apierror.ErrValidation)
}
// 行时间只在"直写"分支用到;worker 分支用它自己消息里的 occurred_at。
// 行时间只在直写分支用到;worker 用消息里的 occurred_at。
comment.CreatedAt = time.Now().UTC()
commentEnqueued := false

View File

@@ -14,14 +14,13 @@ type Mention struct {
}
type CommentStore interface {
// CreateIdempotentWithPopularity 在同一事务内插入评论并给热度加 delta。
// CreateIdempotentWithPopularity 同事务插入评论并给热度加 delta;
// created=false 表示该意图已落库,调用方不得再加热度。
CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (created bool, err error)
GetByID(ctx context.Context, id uint) (*Comment, error)
// DeleteWithPopularity 在同一事务内删除评论并向热度 -1。
// 返回被删的行(拿 created_at 落桶);deleted=false 表示空操作。
// DeleteWithPopularity 同事务删除评论并给热度 -1,返回被删的行。
DeleteWithPopularity(ctx context.Context, id uint) (row *Comment, deleted bool, err error)
GetAllComments(ctx context.Context, videoID uint) ([]Comment, error)

View File

@@ -12,11 +12,8 @@ func NewCounterReconciler(db *gorm.DB) *CounterReconciler { return &CounterRecon
// Reconcile 找出计数与源行不一致的视频,逐条重算。
//
// 为什么先 SELECT ... FOR UPDATE 再 COUNT:点赞/评论事务的顺序都是
// "插行 → UPDATE videos",而 UPDATE videos 会拿 videos 的行锁。因此只要
// 我们先锁住这一行,就不可能有新的业务行在 COUNT 期间提交(它提交不了
// 的 UPDATE 被我们挡住),COUNT 得到的是一个稳定值;随后我们把计数写成
// 这个值,等锁释放后业务事务再在正确值上 +1。
// 先 SELECT ... FOR UPDATE 再 COUNT:业务事务的顺序是"插行 → UPDATE videos",
// 后者会拿行锁,所以锁住这一行就能让 COUNT 读到稳定值。
func (r *CounterReconciler) Reconcile(ctx context.Context, limit int) (checked, fixed int, err error) {
const q = `
SELECT v.id FROM videos v

View File

@@ -10,42 +10,30 @@ import (
)
const (
// HotWindowMinutes 是热榜窗口覆盖的分钟桶数。读侧按 60 个桶求并集。
// HotWindowMinutes 是热榜窗口覆盖的分钟桶数。
HotWindowMinutes = 60
// HotWindowTTL 是单个分钟桶的寿命。
//
// 它必须大于读窗口(60 分钟):读侧只合并最近 60 个桶,但迟到增量可以
// 落在更早的桶里,桶在窗口滑出之前都不该被驱逐。
// HotWindowTTL 必须大于读窗口:迟到增量会落在窗口内的旧桶上,
// 桶在滑出窗口之前不能被驱逐。
HotWindowTTL = 2 * time.Hour
// hotOpTimeout 只约束 ZINCRBY / EXPIRE 两次往返。
hotOpTimeout = 100 * time.Millisecond
)
// HotBucket 把一个时刻折算成分钟桶名(UTC)。
//
// 桶名就是那一分钟的起始时刻,落下标一律用行自己的 created_at,
// 而不是消费时刻——worker 积压时两者能差几分钟。
// HotBucket 返回时刻所属的分钟桶名(UTC)。
func HotBucket(t time.Time) string {
return t.UTC().Truncate(time.Minute).Format("200601021504")
}
// HotMember 是视频在桶里的成员名。
//
// 补零到 12 位:ZSET 同分成员按字典序返回,补零后字典序与数值序一致,
// 才能和 MySQL 路径的 "ORDER BY score DESC, video_id DESC" 对上。
// HotMember 补零到 12 位:ZSET 同分按字典序返回,补零后字典序等于数值序,
// 才能与 MySQL 的 "ORDER BY score DESC, video_id DESC" 给出同一个顺序。
func HotMember(videoID uint) string {
return fmt.Sprintf("%012d", videoID)
}
// ApplyHotDelta 把一次互动的增量写进它所属分钟桶。
// ApplyHotDelta 把一次互动写进 occurredAt 所属的分钟桶。
//
// occurredAt 是这条互动落库那一行的 created_at:增量必须记在事件发生的
// 分钟,不能记在消费者看到它的分钟(否则积压会伪造尖峰)。
//
// 这里只写派生缓存,失败不回滚任何东西:DB 计数是事实,桶可以由
// cmd/reconcile 按 DB 重建。
// 只写派生缓存:失败不回滚任何东西,DB 计数是事实,桶可由 cmd/reconcile 重建。
func ApplyHotDelta(ctx context.Context, cache *rediscache.Client, videoID uint, delta int64, occurredAt time.Time) error {
if cache == nil || videoID == 0 || delta == 0 {
return nil
@@ -53,20 +41,18 @@ func ApplyHotDelta(ctx context.Context, cache *rediscache.Client, videoID uint,
now := time.Now().UTC()
if occurredAt.IsZero() {
// 兼容不带 occurred_at 的旧消息:这时只能按当前时刻落桶。
// 兼容不带 occurred_at 的旧消息。
occurredAt = now
}
if occurredAt.After(now) {
// 未来时间戳会落进未来的桶,读窗口永远看不到它。
// 未来的桶读窗口永远覆盖不到。
occurredAt = now
}
if now.Sub(occurredAt) > HotWindowTTL {
// 超过桶寿命的增量落下去也马上过期,静默丢弃。
return nil
}
// 缓存失效是 best-effort,不进 opCtx 的预算:详情页的热度数字变了,
// 但它不该拖慢写路径。
// 缓存失效是 best-effort,不占 opCtx 预算。
_ = cache.Del(context.Background(), cache.Key("video:detail:id=%d", videoID))
_ = cache.Del(context.Background(), cache.Key("video:entity:%d", videoID))

View File

@@ -22,8 +22,7 @@ func NewHotWindowAdmin(db *gorm.DB, cache *rediscache.Client) *HotWindowAdmin {
return &HotWindowAdmin{db: db, cache: cache}
}
// hotCountRow 是本包自己的扫描目标:feed 包里的 HotWindowRow 属于另一个包,
// 不要为了复用结构体在包之间引依赖。
// hotCountRow 是本包自己的扫描目标,不复用 feed 包的结构体以免跨包依赖。
type hotCountRow struct {
VideoID uint `gorm:"column:video_id"`
Score int64 `gorm:"column:score"`
@@ -81,8 +80,8 @@ func (a *HotWindowAdmin) Verify(ctx context.Context, from, to time.Time) (bucket
// Rebuild 用 DB 重写一个区间内的分钟桶。
//
// 与并发增量有竞态:Del 之后、ZAdd 之前到达的增量会被覆盖。因此不自动跑,
// 只在确认窗口已经冷却(或停写)之后手工执行,跑完再用 Verify 复核。
// 与并发增量有竞态:Del 之后、ZAdd 之前到达的增量会被覆盖,
// 所以只在窗口冷却后手工执行,跑完用 Verify 复核。
func (a *HotWindowAdmin) Rebuild(ctx context.Context, from, to time.Time) (buckets, members int, err error) {
for m := from.UTC().Truncate(time.Minute); m.Before(to); m = m.Add(time.Minute) {
buckets++

View File

@@ -16,13 +16,12 @@ func NewLikeRepository(db *gorm.DB) *LikeRepository {
return &LikeRepository{db: db}
}
// ApplyLike 插入点赞行,并在同一事务里给 likes_count 与 popularity 各 +1。
// ApplyLike 插入点赞行,同一事务里给 likes_count 与 popularity 各 +1。
//
// created=false 表示这一行本来就在(唯一索引 idx_like_video_account 判重),
// 此时计数与热榜都不能再动:重复投递只能算一次。判重交给数据库,不做
// "先查再插"——那样并发下必然漏判。
// 判重交给唯一索引,不做"先查再插":并发下必然漏判。
// created=false 表示行本来就存在,此时两个计数都不能再动。
//
// 注意:DSN 不能开 clientFoundRows,否则 RowsAffected 恒为 1,判重失效。
// DSN 不能开 clientFoundRows,否则 RowsAffected 恒为 1,判重失效。
func (r *LikeRepository) ApplyLike(ctx context.Context, like *Like) (created bool, err error) {
if like == nil || like.VideoID == 0 || like.AccountID == 0 {
return false, nil
@@ -50,11 +49,10 @@ func (r *LikeRepository) ApplyLike(ctx context.Context, like *Like) (created boo
return created, nil
}
// ApplyUnlike 删除点赞行,并在同一事务里把两个计数各 -1。
// ApplyUnlike 删除点赞行并把两个计数各 -1,返回被删的那一行。
//
// 返回被删的那一行:它的 created_at 是热榜回退时要用的时间。取消点赞必须
// 把分数减回点赞那一刻的桶,所以这个值必须来自库里,而不是调用方此刻的钟。
// deleted=false 表示没有这一行(重复投递),此时什么都不改。
// created_at 必须来自库里:取消点赞要把分数减回点赞那一刻的桶,
// 用调用方此刻的钟会留下一个永远偏高的旧桶。
func (r *LikeRepository) ApplyUnlike(ctx context.Context, videoID, accountID uint) (like *Like, deleted bool, err error) {
if videoID == 0 || accountID == 0 {
return nil, false, nil

View File

@@ -48,8 +48,7 @@ func (s *LikeService) Like(ctx context.Context, like *Like) error {
like.CreatedAt = time.Now()
// 意图键只用于日志关联(LikeEvent.EventID),不再参与去重:
// 判重由 likes 的唯一索引在事务里做,重复投递不会重复计数。
// 意图键只用于日志关联,不参与去重:判重由唯一索引在事务里做。
intentKey, err := NewIntentKey()
if err != nil {
return err

View File

@@ -20,9 +20,7 @@ type VideoService struct {
}
// NewVideoService 不涉及热度写入:likes_count / popularity 只由点赞与评论的
// 业务事务维护(LikeRepository.ApplyLike、CommentRepository.CreateIdempotentWithPopularity、
// DeleteWithPopularity),视频服务从来不直接改热度。原来这里挂着一个没人调用的
// UpdatePopularity,它是热度写入的第三份实现,且漏删 video:entity 缓存(P0-4 的 N3)。
// 业务事务维护。
func NewVideoService(repo *VideoRepository, cache *rediscache.Client) *VideoService {
return &VideoService{repo: repo, cache: cache, cacheTTL: 5 * time.Minute}
}