背景叙述与历史取舍已写进 `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/ 全绿。
72 lines
2.0 KiB
Go
72 lines
2.0 KiB
Go
package video
|
||
|
||
import (
|
||
"context"
|
||
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
type CounterReconciler struct{ db *gorm.DB }
|
||
|
||
func NewCounterReconciler(db *gorm.DB) *CounterReconciler { return &CounterReconciler{db: db} }
|
||
|
||
// Reconcile 找出计数与源行不一致的视频,逐条重算。
|
||
//
|
||
// 先 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
|
||
LEFT JOIN (SELECT video_id, COUNT(*) c FROM likes GROUP BY video_id) l ON l.video_id = v.id
|
||
LEFT JOIN (SELECT video_id, COUNT(*) c FROM comments GROUP BY video_id) c ON c.video_id = v.id
|
||
WHERE v.likes_count <> COALESCE(l.c, 0)
|
||
OR v.popularity <> COALESCE(l.c, 0) + COALESCE(c.c, 0)
|
||
ORDER BY v.id
|
||
LIMIT ?`
|
||
var ids []uint
|
||
if err := r.db.WithContext(ctx).Raw(q, limit).Scan(&ids).Error; err != nil {
|
||
return 0, 0, err
|
||
}
|
||
for _, id := range ids {
|
||
checked++
|
||
ok, err := r.fixOne(ctx, id)
|
||
if err != nil {
|
||
return checked, fixed, err
|
||
}
|
||
if ok {
|
||
fixed++
|
||
}
|
||
}
|
||
return checked, fixed, nil
|
||
}
|
||
|
||
func (r *CounterReconciler) fixOne(ctx context.Context, id uint) (bool, error) {
|
||
fixed := false
|
||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||
var locked uint
|
||
if err := tx.Raw("SELECT id FROM videos WHERE id = ? FOR UPDATE", id).Scan(&locked).Error; err != nil {
|
||
return err
|
||
}
|
||
if locked == 0 {
|
||
return nil // 视频在这期间被删了
|
||
}
|
||
var likes, comments int64
|
||
if err := tx.Model(&Like{}).Where("video_id = ?", id).Count(&likes).Error; err != nil {
|
||
return err
|
||
}
|
||
if err := tx.Model(&Comment{}).Where("video_id = ?", id).Count(&comments).Error; err != nil {
|
||
return err
|
||
}
|
||
res := tx.Model(&Video{}).Where("id = ?", id).UpdateColumns(map[string]any{
|
||
"likes_count": likes,
|
||
"popularity": likes + comments,
|
||
})
|
||
if res.Error != nil {
|
||
return res.Error
|
||
}
|
||
fixed = res.RowsAffected > 0
|
||
return nil
|
||
})
|
||
return fixed, err
|
||
}
|