feat(reconcile): 新增计数重算与热榜核对重建命令
三个动作分开放,因为风险不同。 Reconcile 重算 likes_count 与 popularity。它先锁 videos 行再 COUNT,可安全重跑。 Verify 逐桶比对 ZSET 与 DB。它只读,可以高频跑。 Rebuild 用 DB 重写分钟桶。Del 与 ZAdd 会与并发增量竞态,因此只能手工跑。 新增 cmd/reconcile,旗标为 -counters、-verify、-rebuild-hot、-from、-to、-limit。 发现漂移或修正了行时以退出码 1 结束。cron 可据此告警。 验证:go build -buildvcs=false ./... 通过。
This commit is contained in:
148
backend/cmd/reconcile/main.go
Normal file
148
backend/cmd/reconcile/main.go
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
// Command reconcile 是热度相关派生数据的运维入口:重算计数器、核对热榜、
|
||||||
|
// 重建热榜分钟桶。
|
||||||
|
//
|
||||||
|
// 三个动作分开放,因为风险不同:Reconcile 是行锁 + 重算,可重入;Verify 只读,
|
||||||
|
// 可以高频跑;Rebuild 的 Del+ZAdd 与并发增量有竞态,只能人工确认后执行。
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"flag"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"feedsystem_video_go/internal/config"
|
||||||
|
"feedsystem_video_go/internal/db"
|
||||||
|
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||||
|
"feedsystem_video_go/internal/video"
|
||||||
|
|
||||||
|
"github.com/joho/godotenv"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
counters := flag.Bool("counters", false, "重算 videos.likes_count / videos.popularity(写操作)")
|
||||||
|
verify := flag.Bool("verify", false, "逐桶核对热榜窗口与 DB 计数")
|
||||||
|
rebuild := flag.Bool("rebuild-hot", false, "用 DB 重写热榜分钟桶(会与并发增量竞态)")
|
||||||
|
from := flag.String("from", "", "窗口起点 RFC3339(默认 now-60m)")
|
||||||
|
to := flag.String("to", "", "窗口终点 RFC3339,开区间(默认本分钟起点,即含上一个闭合分钟)")
|
||||||
|
limit := flag.Int("limit", 200, "counters 每轮修正的视频数")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
if !*counters && !*verify && !*rebuild {
|
||||||
|
flag.Usage()
|
||||||
|
os.Exit(2)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
gormDB := mustDB(ctx)
|
||||||
|
// Redis 只在核对与重建时需要:counters 是纯 DB 操作。
|
||||||
|
var cache *rediscache.Client
|
||||||
|
if *verify || *rebuild {
|
||||||
|
cache = mustCache(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
fromT, toT := resolveWindow(*from, *to, time.Now())
|
||||||
|
failed := false
|
||||||
|
|
||||||
|
if *counters {
|
||||||
|
checked, fixed, err := video.NewCounterReconciler(gormDB).Reconcile(ctx, *limit)
|
||||||
|
log.Printf("reconcile: checked=%d fixed=%d err=%v", checked, fixed, err)
|
||||||
|
if err != nil || fixed > 0 {
|
||||||
|
failed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if *verify || *rebuild {
|
||||||
|
admin := video.NewHotWindowAdmin(gormDB, cache)
|
||||||
|
if *verify {
|
||||||
|
buckets, drift, err := admin.Verify(ctx, fromT, toT)
|
||||||
|
log.Printf("verify: buckets=%d drift=%d err=%v", buckets, drift, err)
|
||||||
|
if err != nil || drift > 0 {
|
||||||
|
failed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if *rebuild {
|
||||||
|
buckets, members, err := admin.Rebuild(ctx, fromT, toT)
|
||||||
|
log.Printf("rebuild: buckets=%d members=%d err=%v", buckets, members, err)
|
||||||
|
if err != nil {
|
||||||
|
failed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if failed {
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveWindow 解析 [from, to) 窗口。空串取默认值:最近 60 分钟,
|
||||||
|
// 右端是本分钟起点——这一分钟还在增长,不能当桶(N6)。
|
||||||
|
func resolveWindow(from, to string, now time.Time) (fromT, toT time.Time) {
|
||||||
|
now = now.UTC()
|
||||||
|
fromT = now.Truncate(time.Minute).Add(-time.Duration(video.HotWindowMinutes) * time.Minute)
|
||||||
|
toT = now.Truncate(time.Minute)
|
||||||
|
|
||||||
|
if from != "" {
|
||||||
|
if t, err := time.Parse(time.RFC3339, from); err == nil {
|
||||||
|
fromT = t.UTC()
|
||||||
|
} else {
|
||||||
|
log.Fatalf("invalid -from %q: %v", from, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if to != "" {
|
||||||
|
if t, err := time.Parse(time.RFC3339, to); err == nil {
|
||||||
|
toT = t.UTC()
|
||||||
|
} else {
|
||||||
|
log.Fatalf("invalid -to %q: %v", to, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !toT.After(fromT) {
|
||||||
|
log.Fatalf("empty window: from=%s to=%s", fromT.Format(time.RFC3339), toT.Format(time.RFC3339))
|
||||||
|
}
|
||||||
|
return fromT, toT
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustDB(ctx context.Context) *gorm.DB {
|
||||||
|
if err := godotenv.Load(); err != nil {
|
||||||
|
log.Println(".env not found; continuing")
|
||||||
|
}
|
||||||
|
configPath := os.Getenv("CONFIG_PATH")
|
||||||
|
if configPath == "" {
|
||||||
|
configPath = "configs/config.yaml"
|
||||||
|
}
|
||||||
|
cfg, usedDefault, err := config.LoadLocalDev(configPath)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to load config: %v", err)
|
||||||
|
}
|
||||||
|
if usedDefault {
|
||||||
|
log.Printf("Config file %s not found, using default local config", configPath)
|
||||||
|
}
|
||||||
|
gormDB, err := db.NewDB(cfg.Database)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to connect MySQL: %v", err)
|
||||||
|
}
|
||||||
|
return gormDB
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustCache(ctx context.Context) *rediscache.Client {
|
||||||
|
configPath := os.Getenv("CONFIG_PATH")
|
||||||
|
if configPath == "" {
|
||||||
|
configPath = "configs/config.yaml"
|
||||||
|
}
|
||||||
|
cfg, _, err := config.LoadLocalDev(configPath)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to load config: %v", err)
|
||||||
|
}
|
||||||
|
cache, err := rediscache.NewFromEnv(&cfg.Redis)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Failed to connect Redis: %v", err)
|
||||||
|
}
|
||||||
|
pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := cache.Ping(pingCtx); err != nil {
|
||||||
|
log.Fatalf("Redis not available: %v", err)
|
||||||
|
}
|
||||||
|
return cache
|
||||||
|
}
|
||||||
74
backend/internal/video/counters_reconcile.go
Normal file
74
backend/internal/video/counters_reconcile.go
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
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",而 UPDATE videos 会拿 videos 的行锁。因此只要
|
||||||
|
// 我们先锁住这一行,就不可能有新的业务行在 COUNT 期间提交(它提交不了
|
||||||
|
// 的 UPDATE 被我们挡住),COUNT 得到的是一个稳定值;随后我们把计数写成
|
||||||
|
// 这个值,等锁释放后业务事务再在正确值上 +1。
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package video
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 派生计数没有对账就只能靠"写路径永远正确"来保证,而写路径会崩、
|
||||||
|
// 会被手工改库、会在回滚期间落后。这个用例先用直插行制造漂移,
|
||||||
|
// 再断言 Reconcile 把两列拉回 COUNT,并且可以安全重跑。
|
||||||
|
func TestReconcile_FixesDrift(t *testing.T) {
|
||||||
|
db := newTestDB(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
v := seedVideo(t, db, 0) // likes_count=0, popularity=0,行数为 0
|
||||||
|
|
||||||
|
now := time.Now().UTC()
|
||||||
|
for _, account := range []uint{1, 2} {
|
||||||
|
if err := db.Create(&Like{VideoID: v.ID, AccountID: account, CreatedAt: now}).Error; err != nil {
|
||||||
|
t.Fatalf("seed like %d: %v", account, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := db.Create(&Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x", CreatedAt: now}).Error; err != nil {
|
||||||
|
t.Fatalf("seed comment: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
checked, fixed, err := NewCounterReconciler(db).Reconcile(ctx, 10)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Reconcile: %v", err)
|
||||||
|
}
|
||||||
|
if checked != 1 || fixed != 1 {
|
||||||
|
t.Fatalf("checked=%d fixed=%d, want 1/1(这条视频的两个计数都偏了)", checked, fixed)
|
||||||
|
}
|
||||||
|
|
||||||
|
var got Video
|
||||||
|
if err := db.First(&got, v.ID).Error; err != nil {
|
||||||
|
t.Fatalf("reload video: %v", err)
|
||||||
|
}
|
||||||
|
if got.LikesCount != 2 || got.Popularity != 3 {
|
||||||
|
t.Fatalf("likes_count=%d popularity=%d, want 2/3(点赞 2 + 评论 1)", got.LikesCount, got.Popularity)
|
||||||
|
}
|
||||||
|
|
||||||
|
// fixOne 是"锁行 + 重算",可以安全重跑:修好之后再跑不应再发现漂移。
|
||||||
|
checked, fixed, err = NewCounterReconciler(db).Reconcile(ctx, 10)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("第二次 Reconcile: %v", err)
|
||||||
|
}
|
||||||
|
if checked != 0 || fixed != 0 {
|
||||||
|
t.Fatalf("第二次 checked=%d fixed=%d, want 0/0", checked, fixed)
|
||||||
|
}
|
||||||
|
}
|
||||||
113
backend/internal/video/hot_window_admin.go
Normal file
113
backend/internal/video/hot_window_admin.go
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
package video
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||||
|
|
||||||
|
goredis "github.com/redis/go-redis/v9"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type HotWindowAdmin struct {
|
||||||
|
db *gorm.DB
|
||||||
|
cache *rediscache.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHotWindowAdmin(db *gorm.DB, cache *rediscache.Client) *HotWindowAdmin {
|
||||||
|
return &HotWindowAdmin{db: db, cache: cache}
|
||||||
|
}
|
||||||
|
|
||||||
|
// hotCountRow 是本包自己的扫描目标:feed 包里的 HotWindowRow 属于另一个包,
|
||||||
|
// 不要为了复用结构体在包之间引依赖。
|
||||||
|
type hotCountRow struct {
|
||||||
|
VideoID uint `gorm:"column:video_id"`
|
||||||
|
Score int64 `gorm:"column:score"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// counts 返回某分钟内每个视频的互动数,与 ApplyHotDelta 落桶的口径一致。
|
||||||
|
func (a *HotWindowAdmin) counts(ctx context.Context, from, to time.Time) (map[uint]int64, error) {
|
||||||
|
const q = `
|
||||||
|
SELECT video_id, CAST(SUM(cnt) AS SIGNED) AS score FROM (
|
||||||
|
SELECT video_id, COUNT(*) AS cnt FROM likes
|
||||||
|
WHERE created_at >= ? AND created_at < ? GROUP BY video_id
|
||||||
|
UNION ALL
|
||||||
|
SELECT video_id, COUNT(*) AS cnt FROM comments
|
||||||
|
WHERE created_at >= ? AND created_at < ? GROUP BY video_id
|
||||||
|
) t GROUP BY video_id`
|
||||||
|
var rows []hotCountRow
|
||||||
|
if err := a.db.WithContext(ctx).Raw(q, from, to, from, to).Scan(&rows).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make(map[uint]int64, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
out[r.VideoID] = r.Score
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify 逐桶比对 ZSET 与 DB。只读,可以随时跑。
|
||||||
|
func (a *HotWindowAdmin) Verify(ctx context.Context, from, to time.Time) (buckets, drift int, err error) {
|
||||||
|
for m := from.UTC().Truncate(time.Minute); m.Before(to); m = m.Add(time.Minute) {
|
||||||
|
buckets++
|
||||||
|
want, err := a.counts(ctx, m, m.Add(time.Minute))
|
||||||
|
if err != nil {
|
||||||
|
return buckets, drift, err
|
||||||
|
}
|
||||||
|
key := a.cache.Key("hot:video:1m:%s", HotBucket(m))
|
||||||
|
zs, err := a.cache.ZRangeWithScores(ctx, key, 0, -1)
|
||||||
|
if err != nil {
|
||||||
|
return buckets, drift, err
|
||||||
|
}
|
||||||
|
for _, z := range zs {
|
||||||
|
id, _ := strconv.ParseUint(fmt.Sprint(z.Member), 10, 64)
|
||||||
|
if want[uint(id)] != int64(z.Score) {
|
||||||
|
drift++
|
||||||
|
log.Printf("hot verify: bucket=%s video=%d redis=%v db=%d", HotBucket(m), id, z.Score, want[uint(id)])
|
||||||
|
}
|
||||||
|
delete(want, uint(id))
|
||||||
|
}
|
||||||
|
for id, c := range want {
|
||||||
|
drift++
|
||||||
|
log.Printf("hot verify: bucket=%s video=%d redis=missing db=%d", HotBucket(m), id, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return buckets, drift, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebuild 用 DB 重写一个区间内的分钟桶。
|
||||||
|
//
|
||||||
|
// 与并发增量有竞态: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++
|
||||||
|
want, err := a.counts(ctx, m, m.Add(time.Minute))
|
||||||
|
if err != nil {
|
||||||
|
return buckets, members, err
|
||||||
|
}
|
||||||
|
key := a.cache.Key("hot:video:1m:%s", HotBucket(m))
|
||||||
|
if err := a.cache.Del(ctx, key); err != nil {
|
||||||
|
return buckets, members, err
|
||||||
|
}
|
||||||
|
if len(want) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
zs := make([]goredis.Z, 0, len(want))
|
||||||
|
for id, c := range want {
|
||||||
|
zs = append(zs, goredis.Z{Score: float64(c), Member: HotMember(id)})
|
||||||
|
members++
|
||||||
|
}
|
||||||
|
if err := a.cache.ZAdd(ctx, key, zs...); err != nil {
|
||||||
|
return buckets, members, err
|
||||||
|
}
|
||||||
|
if err := a.cache.Expire(ctx, key, HotWindowTTL); err != nil {
|
||||||
|
log.Printf("hot rebuild: expire %s failed: %v", key, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return buckets, members, nil
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user