2026-11-01 15:15:36 +08:00
|
|
|
|
package video
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"context"
|
|
|
|
|
|
|
|
|
|
|
|
"gorm.io/gorm"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
type CounterReconciler struct{ db *gorm.DB }
|
|
|
|
|
|
|
|
|
|
|
|
func NewCounterReconciler(db *gorm.DB) *CounterReconciler { return &CounterReconciler{db: db} }
|
|
|
|
|
|
|
|
|
|
|
|
// Reconcile 找出计数与源行不一致的视频,逐条重算。
|
|
|
|
|
|
//
|
2026-11-01 16:47:31 +08:00
|
|
|
|
// 先 SELECT ... FOR UPDATE 再 COUNT:业务事务的顺序是"插行 → UPDATE videos",
|
|
|
|
|
|
// 后者会拿行锁,所以锁住这一行就能让 COUNT 读到稳定值。
|
2026-11-01 15:15:36 +08:00
|
|
|
|
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
|
|
|
|
|
|
}
|