Files
VLoop/backend/internal/feed/service_integration_test.go
huanghaosheng 85995f9f73 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 ./... 全绿。
2026-11-01 15:15:31 +08:00

271 lines
8.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//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 页")
}
}