feat(feed): 热榜读路径收口到闭合分钟的只建一次快照
窗口右端改为上一个已闭合分钟。当前分钟仍在增长,不能当右端。 一个 as_of 的快照只建一次。ZUNIONSTORE 先写临时键,再用 RENAMENX 原子占位,抢不到的人读赢家。 空并集不再发布成快照。否则这个 as_of 在 TTL 内每次都会命中一张空表,却报告 snapshot_rebuilt=false。 快照 TTL 改为 1 小时。EXPIRE 失败时删掉 dest,避免它继承临时键的 1 分钟寿命而永远翻不到第 2 页。 NextOffset 按 len(members) 推进。视频被删除后 member 仍在,按存活视频数推进会重复读到已跳过的位置。 DB 回退改用 ListHotWindow 重算同一窗口。排序为 score DESC, video_id DESC,与 ZSET 一致。 窗口内无互动时返回 latest。这一支是终结页,NextOffset 为 0。 ZUnionStore 返回并集基数,供调用方判空。新增 RenameNX 包装方法。 删除旧游标字段与 latest_* 配对校验。请求只剩 limit、as_of、offset。 验证:go build -buildvcs=false ./... 通过。go test -buildvcs=false -count=1 ./... 全绿。
This commit is contained in:
@@ -72,26 +72,33 @@ func (repo *FeedRepository) ListByFollowing(ctx context.Context, limit int, view
|
||||
return videos, nil
|
||||
}
|
||||
|
||||
// 查询热门视频. limit: 查询数量 popularityBefore: 查询热度低于此值的视频 timeBefore: 查询早于此时间的视频 idBefore: 查询ID小于此值的视频
|
||||
func (repo *FeedRepository) ListByPopularity(ctx context.Context, limit int, popularityBefore int64, timeBefore time.Time, idBefore uint) ([]*video.Video, error) {
|
||||
var videos []*video.Video
|
||||
query := repo.db.WithContext(ctx).Model(&video.Video{}).
|
||||
Order("popularity DESC, create_time DESC, id DESC")
|
||||
type HotWindowRow struct {
|
||||
VideoID uint `gorm:"column:video_id"`
|
||||
Score int64 `gorm:"column:score"`
|
||||
}
|
||||
|
||||
// 只有当游标完整提供时才加过滤(popularity 允许为 0)
|
||||
if !timeBefore.IsZero() && idBefore > 0 {
|
||||
query = query.Where(
|
||||
"(popularity < ?) OR (popularity = ? AND create_time < ?) OR (popularity = ? AND create_time = ? AND id < ?)",
|
||||
popularityBefore,
|
||||
popularityBefore, timeBefore,
|
||||
popularityBefore, timeBefore, idBefore,
|
||||
)
|
||||
}
|
||||
|
||||
if err := query.Limit(limit).Find(&videos).Error; err != nil {
|
||||
// ListHotWindow 在 MySQL 上重算热榜窗口,排序定义必须与 Redis 路径一致:
|
||||
// 分数降序,同分按视频 ID 降序(ZSET member 补零后就是同一个顺序)。
|
||||
//
|
||||
// 两个子查询各扫一个 (created_at, video_id) 覆盖索引;UNION ALL 之后再
|
||||
// GROUP BY,避免把两张大表 JOIN 起来。
|
||||
func (repo *FeedRepository) ListHotWindow(ctx context.Context, from, to time.Time, limit, offset int) ([]HotWindowRow, 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
|
||||
ORDER BY score DESC, video_id DESC
|
||||
LIMIT ? OFFSET ?`
|
||||
var rows []HotWindowRow
|
||||
if err := repo.db.WithContext(ctx).Raw(q, from, to, from, to, limit, offset).Scan(&rows).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return videos, nil
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
func (repo *FeedRepository) GetByIDs(ctx context.Context, ids []uint) ([]*video.Video, error) {
|
||||
|
||||
Reference in New Issue
Block a user