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:
2026-11-01 15:15:31 +08:00
parent 1b47c9f027
commit 85995f9f73
8 changed files with 746 additions and 145 deletions

View File

@@ -60,22 +60,28 @@ type ListByFollowingResponse struct {
}
type ListByPopularityRequest struct {
Limit int `json:"limit"`
AsOf int64 `json:"as_of"` // 服务器返回的分钟时间戳;第一页传0
Offset int `json:"offset"` // 下一页从这里开始;第一页传0
LatestIDBefore *uint `json:"latest_id_before,omitempty"`
// DB fallback 用(可选)
LatestPopularity int64 `json:"latest_popularity"`
LatestBefore time.Time `json:"latest_before"`
Limit int `json:"limit"`
AsOf int64 `json:"as_of"` // 0 表示"上一个闭合分钟";只接受更早且不超过 hotSnapshotTTL 的值
Offset int `json:"offset"` // 下一页从这里开始;第一页传 0
}
type ListByPopularityResponse struct {
VideoList []FeedVideoItem `json:"video_list"`
AsOf int64 `json:"as_of"`
AsOf int64 `json:"as_of"` // 本次快照的标识(分钟右端,必为已闭合分钟)
NextOffset int `json:"next_offset"`
HasMore bool `json:"has_more"`
// RankingSource 让客户端知道这一页来自哪里。它同时是一个**重置信号**:
// "hot" Redis 点时快照(正常)
// "hot_db" MySQL 重算同一窗口(Redis 缺席;没有快照,翻页只是近似稳定)
// "latest" 窗口内无互动,返回最新视频(终结页,HasMore 恒为 false)
// 与上一页不同,说明榜换了,offset 不再有意义,客户端应当从 0 重来。
RankingSource string `json:"ranking_source"`
// SnapshotRebuilt 为 true 表示服务端刚重建过快照(原来的过期或被驱逐),
// 这一页可能与上一页重叠:客户端应当从 offset 0 重来。
SnapshotRebuilt bool `json:"snapshot_rebuilt"`
// Deprecated: 旧版用 DB 的 (popularity, create_time, id) 游标继续翻页。
// 那套游标与 ZSET 的排名无关(N7),服务端已不再读取,字段仅为兼容保留。
NextLatestPopularity *int64 `json:"next_latest_popularity,omitempty"`
NextLatestBefore *time.Time `json:"next_latest_before,omitempty"`
NextLatestIDBefore *uint `json:"next_latest_id_before,omitempty"`

View File

@@ -131,34 +131,12 @@ func (f *FeedHandler) ListByPopularity(c *gin.Context) {
viewerAccountID = 0
}
var latestPopularity int64
var latestBefore time.Time
var latestIDBefore uint
if req.LatestPopularity < 0 {
c.JSON(400, gin.H{"error": "latest_popularity must be >= 0"})
return
}
anyCursor := !req.LatestBefore.IsZero() || req.LatestIDBefore != nil
if anyCursor {
if req.LatestBefore.IsZero() || req.LatestIDBefore == nil || *req.LatestIDBefore == 0 {
c.JSON(400, gin.H{"error": "latest_before and latest_id_before must be provided together"})
return
}
latestPopularity = req.LatestPopularity
latestBefore = req.LatestBefore
latestIDBefore = *req.LatestIDBefore
}
resp, err := f.service.ListByPopularity(
c.Request.Context(),
req.Limit,
req.AsOf,
req.Offset,
viewerAccountID,
latestPopularity,
latestBefore,
latestIDBefore,
)
if err != nil {
c.JSON(500, gin.H{"error": err.Error()})

View File

@@ -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) {

View File

@@ -0,0 +1,121 @@
//go:build integration
package feed
import (
"context"
"os"
"strings"
"testing"
"time"
"feedsystem_video_go/internal/video"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// 这些用例需要真实 MySQL:ListHotWindow 的排序定义(分数降序、同分按 id 降序)
// 必须与 Redis 路径逐字一致,而 SQL 的 GROUP BY / CAST / ORDER BY 语义
// 用替身验证等于什么都没验证。
//
// docker compose up -d mysql
// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \
// go test -tags integration -count=1 ./internal/feed/
func newFeedTestDB(t *testing.T) *gorm.DB {
t.Helper()
dsn := os.Getenv("MYSQL_TEST_DSN")
if dsn == "" {
t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)")
}
if strings.Contains(dsn, "clientFoundRows") {
t.Fatalf("测试 DSN 不能带 clientFoundRows:它会破坏 RowsAffected 判重")
}
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})
if err != nil {
t.Fatalf("connect mysql: %v", err)
}
if err := db.Migrator().DropTable(&video.Video{}, &video.Like{}, &video.Comment{}); err != nil {
t.Fatalf("drop tables: %v", err)
}
if err := db.AutoMigrate(&video.Video{}, &video.Like{}, &video.Comment{}); err != nil {
t.Fatalf("migrate: %v", err)
}
return db
}
func seedFeedVideo(t *testing.T, db *gorm.DB) *video.Video {
t.Helper()
v := &video.Video{
AuthorID: 1, Username: "author", Title: "t",
PlayURL: "p", CoverURL: "c",
}
if err := db.Create(v).Error; err != nil {
t.Fatalf("seed video: %v", err)
}
return v
}
func seedLikeAt(t *testing.T, db *gorm.DB, videoID, accountID uint, at time.Time) {
t.Helper()
if err := db.Create(&video.Like{VideoID: videoID, AccountID: accountID, CreatedAt: at}).Error; err != nil {
t.Fatalf("seed like: %v", err)
}
}
func seedCommentAt(t *testing.T, db *gorm.DB, videoID uint, at time.Time) {
t.Helper()
c := &video.Comment{Username: "alice", VideoID: videoID, AuthorID: 1, Content: "x", CreatedAt: at}
if err := db.Create(c).Error; err != nil {
t.Fatalf("seed comment: %v", err)
}
}
// Redis 路径用补零 member,同分时按 member 字符串降序 —— 也就是 id 降序。
// DB 回退必须复刻同一个顺序,否则同一次请求在两条路径上看到两个榜。
func TestListHotWindow_OrdersByScoreThenIDDesc(t *testing.T) {
db := newFeedTestDB(t)
repo := NewFeedRepository(db)
ctx := context.Background()
low := seedFeedVideo(t, db)
highA := seedFeedVideo(t, db)
highB := seedFeedVideo(t, db)
asOf := time.Now().UTC().Truncate(time.Minute).Add(-time.Minute)
at := asOf.Add(-5 * time.Minute)
to := asOf.Add(time.Minute)
// 分数:highA = highB = 3(同分,按 id DESC 应 highB 在前),low = 1。
for i := uint(1); i <= 3; i++ {
seedLikeAt(t, db, highA.ID, i, at)
}
seedLikeAt(t, db, highB.ID, 1, at)
seedCommentAt(t, db, highB.ID, at)
seedCommentAt(t, db, highB.ID, at.Add(time.Second))
seedLikeAt(t, db, low.ID, 1, at)
// 窗口外的互动不得进入结果。
seedLikeAt(t, db, low.ID, 2, to)
rows, err := repo.ListHotWindow(ctx, asOf.Add(-59*time.Minute), to, 10, 0)
if err != nil {
t.Fatalf("ListHotWindow: %v", err)
}
wantIDs := []uint{highB.ID, highA.ID, low.ID}
if len(rows) != len(wantIDs) {
t.Fatalf("rows = %+v, want %d 行", rows, len(wantIDs))
}
for i, want := range wantIDs {
if rows[i].VideoID != want {
t.Fatalf("第 %d 行 video_id = %d, want %d(分数降序,同分 id 降序)", i, rows[i].VideoID, want)
}
}
if rows[0].Score != 3 || rows[2].Score != 1 {
t.Fatalf("分数 = %d/%d, want 3/1", rows[0].Score, rows[2].Score)
}
}

View File

@@ -438,118 +438,236 @@ func (f *FeedService) ListByFollowing(ctx context.Context, limit int, latestBefo
return resp, nil
}
func (f *FeedService) ListByPopularity(ctx context.Context, limit int, reqAsOf int64, offset int, viewerAccountID uint, latestPopularity int64, latestBefore time.Time, latestIDBefore uint) (ListByPopularityResponse, error) {
// Redis 热榜(稳定分页:as_of + offset)
// hotSnapshotTTL 是一个 as_of 的快照寿命。
//
// 它要覆盖一次浏览会话,也要覆盖被驱逐后的重建窗口。1 小时与
// video.HotWindowTTL 同量级:任何时刻最多 60 个不同的 as_of 活着,
// 因此内存上界可算。
const hotSnapshotTTL = time.Hour
// lastClosedMinute 返回上一个已闭合的分钟(UTC)。
//
// 当前这一分钟仍在增长,永远不能当窗口右端:否则同一个 as_of 的榜会
// 在用户翻页的过程中自己变大,分页随之错位(N6)。
func lastClosedMinute(now time.Time) time.Time {
return now.UTC().Truncate(time.Minute).Add(-time.Minute)
}
// hotWindowBounds 返回 [asOf-59m, asOf+1m),正好覆盖 60 个分钟桶。
func hotWindowBounds(asOf time.Time) (from, to time.Time) {
from = asOf.Add(-time.Duration(video.HotWindowMinutes-1) * time.Minute)
to = asOf.Add(time.Minute)
return
}
func (f *FeedService) ListByPopularity(ctx context.Context, limit int, reqAsOf int64, offset int, viewerAccountID uint) (ListByPopularityResponse, error) {
asOf := lastClosedMinute(time.Now())
if reqAsOf > 0 {
want := time.Unix(reqAsOf, 0).UTC().Truncate(time.Minute)
// 只接受"比当前分钟更早、且还在快照 TTL 内"的 as_of:
// - 未来或当前分钟:窗口还在增长(N6);
// - 比 TTL 更老:快照早已过期,重建出来是另一个榜,不能再用同一个
// as_of 交回去(客户端据响应 as_of 的变化重置分页)。
if want.Before(asOf) && time.Since(want) <= hotSnapshotTTL {
asOf = want
}
}
if f.rediscache != nil {
// 将 as_of 截断到分钟级
asOf := time.Now().UTC().Truncate(time.Minute)
if reqAsOf > 0 {
asOf = time.Unix(reqAsOf, 0).UTC().Truncate(time.Minute)
resp, ok, err := f.listByHotWindowRedis(ctx, limit, offset, asOf, viewerAccountID)
if err != nil {
return ListByPopularityResponse{}, err
}
// 创建时间窗口,获取过去 60 分钟的 ZSET
const win = 60
keys := make([]string, 0, win)
for i := 0; i < win; i++ {
keys = append(keys, f.rediscache.Key("hot:video:1m:%s", asOf.Add(-time.Duration(i)*time.Minute).Format("200601021504")))
if ok {
return resp, nil
}
}
return f.listByHotWindowDB(ctx, limit, offset, asOf, viewerAccountID)
}
// 创建快照key:同一个as_of页内复用
dest := f.rediscache.Key("hot:video:merge:1m:%s", asOf.Format("200601021504"))
opCtx, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
defer cancel()
func (f *FeedService) listByHotWindowRedis(ctx context.Context, limit, offset int, asOf time.Time, viewer uint) (ListByPopularityResponse, bool, error) {
from, _ := hotWindowBounds(asOf)
keys := make([]string, 0, video.HotWindowMinutes)
for t := from; !t.After(asOf); t = t.Add(time.Minute) {
keys = append(keys, f.rediscache.Key("hot:video:1m:%s", video.HotBucket(t)))
}
dest := f.rediscache.Key("hot:video:merge:1m:%s", video.HotBucket(asOf))
exists, _ := f.rediscache.Exists(opCtx, dest) // 检查合并快照是否已存在
if !exists {
_ = f.rediscache.ZUnionStore(opCtx, dest, keys, "SUM")
_ = f.rediscache.Expire(opCtx, dest, 2*time.Minute) // 给翻页留时间
// 120ms 覆盖下面 5 次往返(含 ZUNIONSTORE 60 个键)。它比写入侧的
// hotOpTimeout 宽,但按读 P99 标定:超时一律落 DB 回退,而那条路是最贵的
// 查询,所以超时率要能观测。
opCtx, cancel := context.WithTimeout(ctx, 120*time.Millisecond)
defer cancel()
exists, err := f.rediscache.Exists(opCtx, dest)
if err != nil {
return ListByPopularityResponse{}, false, nil // Redis 抖动:交给 DB 窗口
}
if !exists {
// 快照只建一次。直接 ZUnionStore 到 dest 会覆盖已有内容:并发两个请求
// 时,后到的那个会把先到的快照换掉,"同一会话同一个榜"就没了。
// 先算到临时键,再用 RENAMENX 原子占位:抢到的人赢,没抢到的人丢掉
// 临时键,继续读已经存在的 dest。
tmp := dest + ":build:" + strconv.FormatInt(time.Now().UnixNano(), 36)
n, err := f.rediscache.ZUnionStore(opCtx, tmp, keys, "SUM")
if err != nil {
return ListByPopularityResponse{}, false, nil
}
start := int64(offset)
stop := start + int64(limit) - 1
members, err := f.rediscache.ZRevRange(opCtx, dest, start, stop)
if err == nil && len(members) == 0 {
if offset > 0 {
return ListByPopularityResponse{
VideoList: []FeedVideoItem{},
AsOf: asOf.Unix(),
NextOffset: offset,
HasMore: false,
}, nil
}
if n == 0 {
// ZUNIONSTORE 在没有成员时仍会创建一张空表。若把它发布成快照,
// 这个 as_of 在 hotSnapshotTTL 内每次都会命中"存在的空快照",
// 于是每次都落 DB,却又报告 snapshot_rebuilt=false——
// "真的空榜"与"快照丢了"从此分不开。丢掉临时键,交给 DB 路径判定。
_ = f.rediscache.Del(opCtx, tmp)
return ListByPopularityResponse{}, false, nil
}
if err == nil && len(members) > 0 {
// 将字符串 ID 转换为 uint
ids := make([]uint, 0, len(members))
for _, m := range members {
u, err := strconv.ParseUint(m, 10, 64)
if err == nil && u > 0 {
ids = append(ids, uint(u))
}
}
// 根据 ID 批量获取视频信息
videos, err := f.repo.GetByIDs(ctx, ids)
if err == nil {
byID := make(map[uint]*video.Video, len(videos))
for _, v := range videos {
byID[v.ID] = v
}
ordered := make([]*video.Video, 0, len(ids))
for _, id := range ids { // 按 Redis 返回的顺序重新排列
if v := byID[id]; v != nil {
ordered = append(ordered, v)
}
}
items, err := f.buildFeedVideos(ctx, ordered, viewerAccountID)
if err != nil {
return ListByPopularityResponse{}, err
}
resp := ListByPopularityResponse{
VideoList: items,
AsOf: asOf.Unix(),
NextOffset: offset + len(items),
HasMore: len(items) == limit,
}
if len(ordered) > 0 { // 准备最后一条视频的游标信息,供 DB fallback 使用
last := ordered[len(ordered)-1]
nextPopularity := last.Popularity
nextBefore := last.CreateTime
nextID := last.ID
resp.NextLatestPopularity = &nextPopularity
resp.NextLatestBefore = &nextBefore
resp.NextLatestIDBefore = &nextID
}
return resp, nil
}
// 临时键也给一个短 TTL:进程若在 ZUnionStore 与 RENAMENX 之间崩溃,
// 没有 TTL 的 tmp 会永久留下。RENAMENX 会把 TTL 一起带给 dest,
// 下一行的 Expire 再把它改成快照寿命。
if err := f.rediscache.Expire(opCtx, tmp, time.Minute); err != nil {
log.Printf("feed: expire hot snapshot tmp %s failed (non-fatal): %v", tmp, err)
}
won, err := f.rediscache.RenameNX(opCtx, tmp, dest)
if err != nil {
return ListByPopularityResponse{}, false, nil
}
if !won {
_ = f.rediscache.Del(opCtx, tmp) // 别人先建好了,用他的
} else if err := f.rediscache.Expire(opCtx, dest, hotSnapshotTTL); err != nil {
// RENAMENX 把 tmp 的 1 分钟 TTL 一起带给了 dest。若这里没改成
// 快照寿命,dest 会在一分钟后消失:第 2 页因此重建快照、
// snapshot_rebuilt=true、客户端重置到第 1 页——而重建的快照又只
// 活 1 分钟,于是永远翻不到第 2 页。宁可删掉让下一次请求干净重建。
log.Printf("feed: expire hot snapshot %s failed, dropping it: %v", dest, err)
_ = f.rediscache.Del(opCtx, dest)
}
}
// DB fallback(游标分页:latestPopularity + latestBefore + latestIDBefore)
videos, err := f.repo.ListByPopularity(ctx, limit, latestPopularity, latestBefore, latestIDBefore)
// 只要分数 > 0 的成员:加一次再减一次会把 member 留在桶里、分数归 0,
// 这类视频此刻没有任何互动,不应出现在榜上。DB 路径天然只返回"窗口内
// 有行"的视频,两者因此一致。
members, err := f.rediscache.ZRevRangeByScore(opCtx, dest, "+inf", "(0", int64(offset), int64(limit))
if err != nil {
return ListByPopularityResponse{}, false, nil
}
if len(members) == 0 {
if offset > 0 {
return ListByPopularityResponse{
VideoList: []FeedVideoItem{},
AsOf: asOf.Unix(),
NextOffset: offset,
HasMore: false,
RankingSource: "hot",
SnapshotRebuilt: !exists,
}, true, nil
}
// 空榜:可能是真的空,也可能是丢桶。都交给 DB 窗口判一次。
return ListByPopularityResponse{}, false, nil
}
ids := parseHotMembers(members)
videos, err := f.repo.GetByIDs(ctx, ids)
if err != nil {
return ListByPopularityResponse{}, false, err
}
byID := make(map[uint]*video.Video, len(videos))
for _, v := range videos {
byID[v.ID] = v
}
ordered := make([]*video.Video, 0, len(ids))
for _, id := range ids {
if v := byID[id]; v != nil {
ordered = append(ordered, v)
}
}
items, err := f.buildFeedVideos(ctx, ordered, viewer)
if err != nil {
return ListByPopularityResponse{}, false, err
}
return ListByPopularityResponse{
VideoList: items,
AsOf: asOf.Unix(),
// 按 ZSET 返回的 member 数推进:视频被删后 member 仍在,
// 按存活视频数推进会重复读到已经跳过的位置。
NextOffset: offset + len(members),
HasMore: len(members) == limit,
RankingSource: "hot",
SnapshotRebuilt: !exists && offset > 0,
}, true, nil
}
func parseHotMembers(members []string) []uint {
ids := make([]uint, 0, len(members))
for _, m := range members {
u, err := strconv.ParseUint(m, 10, 64) // 兼容补零与旧格式
if err == nil && u > 0 {
ids = append(ids, uint(u))
}
}
return ids
}
func (f *FeedService) listByHotWindowDB(ctx context.Context, limit, offset int, asOf time.Time, viewer uint) (ListByPopularityResponse, error) {
from, to := hotWindowBounds(asOf)
rows, err := f.repo.ListHotWindow(ctx, from, to, limit, offset)
if err != nil {
return ListByPopularityResponse{}, err
}
items, err := f.buildFeedVideos(ctx, videos, viewerAccountID)
if len(rows) == 0 && offset > 0 {
return ListByPopularityResponse{
VideoList: []FeedVideoItem{},
AsOf: asOf.Unix(),
NextOffset: offset,
HasMore: false,
RankingSource: "hot_db",
}, nil
}
if len(rows) == 0 {
// 窗口内没有任何互动:给"最新",而不是给一个空页面。
latest, err := f.repo.ListLatest(ctx, limit, time.Time{})
if err != nil {
return ListByPopularityResponse{}, err
}
items, err := f.buildFeedVideos(ctx, latest, viewer)
if err != nil {
return ListByPopularityResponse{}, err
}
return ListByPopularityResponse{
VideoList: items, AsOf: asOf.Unix(),
// 这一支是"兜底给点东西看",不是可分页的列表:ListLatest 不收 offset,
// 若这里回一个 next_offset,第 2 页会落到 ListHotWindow 的空结果上并返回空页。
NextOffset: 0, HasMore: false, RankingSource: "latest",
}, nil
}
ids := make([]uint, 0, len(rows))
for _, r := range rows {
ids = append(ids, r.VideoID)
}
videos, err := f.repo.GetByIDs(ctx, ids)
if err != nil {
return ListByPopularityResponse{}, err
}
resp := ListByPopularityResponse{
VideoList: items,
AsOf: 0,
NextOffset: 0,
HasMore: len(items) == limit,
byID := make(map[uint]*video.Video, len(videos))
for _, v := range videos {
byID[v.ID] = v
}
if len(videos) > 0 {
last := videos[len(videos)-1]
nextPopularity := last.Popularity
nextBefore := last.CreateTime
nextID := last.ID
resp.NextLatestPopularity = &nextPopularity
resp.NextLatestBefore = &nextBefore
resp.NextLatestIDBefore = &nextID
ordered := make([]*video.Video, 0, len(ids))
for _, id := range ids {
if v := byID[id]; v != nil {
ordered = append(ordered, v)
}
}
return resp, nil
items, err := f.buildFeedVideos(ctx, ordered, viewer)
if err != nil {
return ListByPopularityResponse{}, err
}
return ListByPopularityResponse{
VideoList: items, AsOf: asOf.Unix(),
NextOffset: offset + len(rows),
HasMore: len(rows) == limit,
RankingSource: "hot_db",
}, nil
}
// 将 Video 列表转换为 FeedVideoItem 列表,并批量查询填充当前用户对所有视频的点赞状态

View File

@@ -0,0 +1,270 @@
//go:build integration
package feed
import (
"context"
"errors"
"strings"
"testing"
"time"
rediscache "feedsystem_video_go/internal/middleware/redis"
"feedsystem_video_go/internal/video"
"github.com/alicebob/miniredis/v2"
goredis "github.com/redis/go-redis/v9"
"gorm.io/gorm"
)
type feedFixture struct {
svc *FeedService
db *gorm.DB
cache *rediscache.Client
mr *miniredis.Miniredis
asOf time.Time
at time.Time // 窗口内的互动时间
}
func newFeedFixture(t *testing.T, opts ...goredis.Hook) *feedFixture {
t.Helper()
db := newFeedTestDB(t)
mr := miniredis.RunT(t)
rdb := goredis.NewClient(&goredis.Options{Addr: mr.Addr()})
t.Cleanup(func() { _ = rdb.Close() })
for _, h := range opts {
rdb.AddHook(h)
}
cache := rediscache.NewClient(rdb, "test:")
svc := NewFeedService(NewFeedRepository(db), video.NewLikeRepository(db), cache)
asOf := lastClosedMinute(time.Now())
return &feedFixture{svc: svc, db: db, cache: cache, mr: mr, asOf: asOf, at: asOf.Add(-5 * time.Minute)}
}
func (f *feedFixture) seedHot(t *testing.T, likes int) *video.Video {
t.Helper()
v := seedFeedVideo(t, f.db)
for i := 1; i <= likes; i++ {
seedLikeAt(t, f.db, v.ID, uint(i), f.at)
}
// DB 行与热榜桶必须成对出现:桶是行的物化视图,只插行会让读侧
// 只剩 DB 回退路径,快照/并集相关的断言就失去被测对象。
if err := video.ApplyHotDelta(context.Background(), f.cache, v.ID, int64(likes), f.at); err != nil {
t.Fatalf("seed hot: %v", err)
}
return v
}
func ids(items []FeedVideoItem) []uint {
out := make([]uint, 0, len(items))
for _, it := range items {
out = append(out, it.ID)
}
return out
}
func (f *feedFixture) snapshotKey() string {
return f.cache.Key("hot:video:merge:1m:%s", video.HotBucket(f.asOf))
}
// 翻页不得重复:旧实现用 offset+len(items) 推进,视频被删后 items 比 members 短,
// 下一次请求会从已经返回过的位置开始。
func TestListByPopularity_PaginatesWithoutOverlap(t *testing.T) {
f := newFeedFixture(t)
ctx := context.Background()
f.seedHot(t, 3)
f.seedHot(t, 2)
f.seedHot(t, 1)
page1, err := f.svc.ListByPopularity(ctx, 2, f.asOf.Unix(), 0, 0)
if err != nil {
t.Fatalf("page1: %v", err)
}
if page1.RankingSource != "hot" {
t.Fatalf("page1 ranking_source = %q, want hot", page1.RankingSource)
}
if len(page1.VideoList) != 2 || !page1.HasMore || page1.NextOffset != 2 {
t.Fatalf("page1 = %d 条 has_more=%v next=%d, want 2 条/true/2",
len(page1.VideoList), page1.HasMore, page1.NextOffset)
}
page2, err := f.svc.ListByPopularity(ctx, 2, f.asOf.Unix(), page1.NextOffset, 0)
if err != nil {
t.Fatalf("page2: %v", err)
}
if len(page2.VideoList) != 1 || page2.HasMore {
t.Fatalf("page2 = %d 条 has_more=%v, want 1 条/false", len(page2.VideoList), page2.HasMore)
}
seen := make(map[uint]bool)
for _, id := range append(ids(page1.VideoList), ids(page2.VideoList)...) {
if seen[id] {
t.Fatalf("视频 %d 在两页里重复出现", id)
}
seen[id] = true
}
}
// 快照只建一次:第一个请求算出并原子发布,之后的请求读同一份副本。
func TestListByPopularity_SnapshotIsBuiltOnce(t *testing.T) {
f := newFeedFixture(t)
ctx := context.Background()
f.seedHot(t, 2)
f.seedHot(t, 1)
first, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
if err != nil {
t.Fatalf("first: %v", err)
}
if first.SnapshotRebuilt {
t.Fatal("首次请求是建快照,不是重建")
}
dest := f.snapshotKey()
if !f.mr.Exists(dest) {
t.Fatalf("快照键 %s 不存在", dest)
}
if ttl := f.mr.TTL(dest); ttl != hotSnapshotTTL {
t.Fatalf("快照 TTL = %v, want %v(继承临时键的 1 分钟 TTL 会让第 2 页永远翻不到)",
ttl, hotSnapshotTTL)
}
second, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
if err != nil {
t.Fatalf("second: %v", err)
}
if second.SnapshotRebuilt {
t.Fatal("快照已存在,第二次不得报告重建")
}
if got, want := ids(second.VideoList), ids(first.VideoList); len(got) != len(want) || got[0] != want[0] {
t.Fatalf("第二次结果 = %v, want %v", got, want)
}
}
// 迟到增量会改写仍在窗口内的桶,但已发布的快照不得重算:
// 同一个 as_of 在快照活着的时候是同一个榜。
func TestListByPopularity_LateDeltaDoesNotChangeSnapshot(t *testing.T) {
f := newFeedFixture(t)
ctx := context.Background()
top := f.seedHot(t, 2)
bottom := f.seedHot(t, 1)
first, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
if err != nil {
t.Fatalf("first: %v", err)
}
if got := ids(first.VideoList); len(got) != 2 || got[0] != top.ID {
t.Fatalf("首屏顺序 = %v, want [%d %d]", got, top.ID, bottom.ID)
}
// 往窗口内的桶补写,把 bottom 顶到第一。
bucketKey := f.cache.Key("hot:video:1m:%s", video.HotBucket(f.at))
if err := f.cache.ZincrBy(ctx, bucketKey, video.HotMember(bottom.ID), 10); err != nil {
t.Fatalf("zincrby: %v", err)
}
second, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
if err != nil {
t.Fatalf("second: %v", err)
}
if got := ids(second.VideoList); len(got) != 2 || got[0] != top.ID {
t.Fatalf("迟到增量改写了快照:顺序 = %v, want [%d %d]", got, top.ID, bottom.ID)
}
}
// Redis 缺席或丢键时退回 DB 重算同一窗口,并明确告诉客户端来源不同。
func TestListByPopularity_FallsBackToDBWindow(t *testing.T) {
f := newFeedFixture(t)
ctx := context.Background()
f.seedHot(t, 2)
f.mr.FlushAll() // 桶与快照一起丢:模拟 Redis 被清空
resp, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
if err != nil {
t.Fatalf("ListByPopularity: %v", err)
}
if resp.RankingSource != "hot_db" {
t.Fatalf("ranking_source = %q, want hot_db", resp.RankingSource)
}
if len(resp.VideoList) != 1 {
t.Fatalf("video_list = %d 条, want 1", len(resp.VideoList))
}
}
// 窗口内没有任何互动时给"最新",且这一支是终结页:不回 next_offset,
// 否则第 2 页会落到 ListHotWindow 的空结果上返回空页。
func TestListByPopularity_LatestBranchIsTerminal(t *testing.T) {
f := newFeedFixture(t)
ctx := context.Background()
seedFeedVideo(t, f.db) // 有视频,但窗口内没有互动
resp, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0)
if err != nil {
t.Fatalf("ListByPopularity: %v", err)
}
if resp.RankingSource != "latest" {
t.Fatalf("ranking_source = %q, want latest", resp.RankingSource)
}
if resp.NextOffset != 0 || resp.HasMore {
t.Fatalf("next_offset=%d has_more=%v, want 0/false(latest 是终结页)", resp.NextOffset, resp.HasMore)
}
if len(resp.VideoList) != 1 {
t.Fatalf("video_list = %d 条, want 1", len(resp.VideoList))
}
}
// 60 个空桶的并集是"空表",不能把它发布成快照:否则这个 as_of 在 TTL 内
// 每次都会命中"存在的空快照","真的空榜"与"快照丢了"从此分不开。
func TestListByPopularity_EmptyUnionIsNotPublished(t *testing.T) {
f := newFeedFixture(t)
ctx := context.Background()
resp, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 10, 0)
if err != nil {
t.Fatalf("ListByPopularity: %v", err)
}
if resp.NextOffset != 10 || resp.HasMore {
t.Fatalf("next_offset=%d has_more=%v, want 10/false", resp.NextOffset, resp.HasMore)
}
if f.mr.Exists(f.snapshotKey()) {
t.Fatal("空并集不得发布成快照")
}
}
// EXPIRE 失败时 dest 会继承临时键的 1 分钟 TTL:第 2 页因此重建快照、
// 客户端重置。宁可删掉让下一次请求干净重建。
type failExpireOnPrefixHook struct {
prefix string
}
func (h *failExpireOnPrefixHook) DialHook(next goredis.DialHook) goredis.DialHook { return next }
func (h *failExpireOnPrefixHook) ProcessHook(next goredis.ProcessHook) goredis.ProcessHook {
return func(ctx context.Context, cmd goredis.Cmder) error {
if strings.EqualFold(cmd.Name(), "expire") && len(cmd.Args()) >= 2 {
if key, ok := cmd.Args()[1].(string); ok && strings.HasPrefix(key, h.prefix) {
return errors.New("injected expire failure")
}
}
return next(ctx, cmd)
}
}
func (h *failExpireOnPrefixHook) ProcessPipelineHook(next goredis.ProcessPipelineHook) goredis.ProcessPipelineHook {
return next
}
func TestListByPopularity_SnapshotExpireFailureDropsKey(t *testing.T) {
f := newFeedFixture(t, &failExpireOnPrefixHook{
prefix: rediscache.NewClient(nil, "test:").Key("hot:video:merge:1m:"),
})
ctx := context.Background()
f.seedHot(t, 1)
if _, err := f.svc.ListByPopularity(ctx, 10, f.asOf.Unix(), 0, 0); err != nil {
t.Fatalf("ListByPopularity: %v", err)
}
if f.mr.Exists(f.snapshotKey()) {
t.Fatal("EXPIRE 失败必须删除快照键:留着它只活 1 分钟,客户端永远翻不到第 2 页")
}
}

View File

@@ -0,0 +1,85 @@
package feed
import (
"testing"
"time"
)
// 窗口右端必须是"已闭合的分钟":当前这一分钟还在增长,拿它当右端
// 会让同一个 as_of 的榜在翻页过程中自己变大(N6)。
func TestLastClosedMinute_NeverReturnsOpenMinute(t *testing.T) {
cases := []struct {
name string
now time.Time
want string
}{
{
name: "分钟内",
now: time.Date(2026, 3, 4, 5, 6, 7, 900_000_000, time.FixedZone("UTC+8", 8*3600)),
want: "2026-03-03T21:05:00Z",
},
{
name: "整分边界",
now: time.Date(2026, 3, 4, 12, 0, 0, 0, time.UTC),
want: "2026-03-04T11:59:00Z",
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := lastClosedMinute(c.now)
if want := mustParse(t, c.want); !got.Equal(want) {
t.Fatalf("lastClosedMinute(%v) = %v, want %v", c.now, got.Format(time.RFC3339), c.want)
}
if got.Location() != time.UTC {
t.Fatalf("location = %v, want UTC(桶名按 UTC 编码)", got.Location())
}
if !got.Before(c.now.UTC().Truncate(time.Minute)) {
t.Fatalf("返回值 %v 不早于当前分钟:开放分钟不能当窗口右端", got)
}
})
}
}
// 窗口必须正好覆盖 60 个分钟桶:少一个就漏掉最老的桶,多一个就跨出滑窗。
func TestHotWindowBounds_Covers60Buckets(t *testing.T) {
asOf := mustParse(t, "2026-03-04T12:05:00Z")
from, to := hotWindowBounds(asOf)
if !to.Equal(asOf.Add(time.Minute)) {
t.Fatalf("to = %v, want asOf+1m(右端开区间)", to)
}
if !from.Equal(asOf.Add(-59 * time.Minute)) {
t.Fatalf("from = %v, want asOf-59m", from)
}
var buckets int
for m := from; m.Before(to); m = m.Add(time.Minute) {
buckets++
}
if buckets != 60 {
t.Fatalf("窗口内分钟桶 = %d, want 60", buckets)
}
}
// 补零的 member 与旧实现的十进制 member 都要能读:上线时旧键还在。
func TestParseHotMembers_TolerantToPaddingAndGarbage(t *testing.T) {
got := parseHotMembers([]string{"000000000007", "42", "0", "abc", "", "-1"})
want := []uint{7, 42}
if len(got) != len(want) {
t.Fatalf("parseHotMembers = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("parseHotMembers = %v, want %v", got, want)
}
}
}
func mustParse(t *testing.T, s string) time.Time {
t.Helper()
parsed, err := time.Parse(time.RFC3339, s)
if err != nil {
t.Fatalf("parse %q: %v", s, err)
}
return parsed
}