Files
VLoop/backend/internal/feed/service_integration_test.go

452 lines
15 KiB
Go
Raw Normal View History

//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))
}
}
// 视频被硬删后互动行还在(DeleteVideo 不级联),整页都被 GetByIDs 过滤掉时
// 不能直接回空页,游标必须越过被跳过的行继续取。
func TestListByPopularity_DBWindowSkipsDeletedVideos(t *testing.T) {
f := newFeedFixture(t)
ctx := context.Background()
alive := f.seedHot(t, 1)
for _, likes := range []int{5, 4} {
gone := f.seedHot(t, likes)
if err := f.db.Delete(&video.Video{}, gone.ID).Error; err != nil {
t.Fatalf("硬删视频 %d: %v", gone.ID, err)
}
}
f.mr.FlushAll() // 桶与快照一起丢:强制走 DB 窗口
resp, err := f.svc.ListByPopularity(ctx, 2, f.asOf.Unix(), 0, 0)
if err != nil {
t.Fatalf("ListByPopularity: %v", err)
}
if got := ids(resp.VideoList); len(got) != 1 || got[0] != alive.ID {
t.Fatalf("首屏 = %v, want [%d](整页已删视频不能吃掉分页位置)", got, alive.ID)
}
if resp.HasMore {
t.Fatalf("has_more = true(next_offset=%d):跳过已删视频后窗口已经到底", resp.NextOffset)
}
if resp.NextOffset != 3 {
t.Fatalf("next_offset = %d, want 3(游标要越过被跳过的 2 行,否则第 2 页重复读)", resp.NextOffset)
}
}
// 按客户端方式翻到底:整页已删视频后不重不漏,并且能终止。
func TestListByPopularity_DBWindowPaginatesPastDeletedVideos(t *testing.T) {
f := newFeedFixture(t)
ctx := context.Background()
// 分数严格递减:4 个高分视频(会被删)排在 2 个存活视频之前。
want := map[uint]bool{}
for i := 0; i < 2; i++ {
want[f.seedHot(t, 2).ID] = true
}
for i := 0; i < 4; i++ {
gone := f.seedHot(t, 10+i)
if err := f.db.Delete(&video.Video{}, gone.ID).Error; err != nil {
t.Fatalf("硬删视频 %d: %v", gone.ID, err)
}
}
f.mr.FlushAll()
got := map[uint]bool{}
offset := 0
for page := 0; page < 10; page++ {
resp, err := f.svc.ListByPopularity(ctx, 2, f.asOf.Unix(), offset, 0)
if err != nil {
t.Fatalf("第 %d 页: %v", page+1, err)
}
for _, id := range ids(resp.VideoList) {
if got[id] {
t.Fatalf("第 %d 页重复返回视频 %d(offset=%d)", page+1, id, offset)
}
got[id] = true
}
if !resp.HasMore {
break
}
if resp.NextOffset <= offset {
t.Fatalf("has_more=true 但 next_offset(%d) 没前进(offset=%d):翻页会死循环", resp.NextOffset, offset)
}
offset = resp.NextOffset
}
if len(got) != len(want) {
t.Fatalf("翻完拿到 %v, want %v(漏了存活视频)", got, want)
}
for id := range want {
if !got[id] {
t.Fatalf("翻完没拿到存活视频 %d", id)
}
}
}
// 连续 hotDBMaxSweep 批都只剩已删视频时收尾,更靠后的视频留到下一次 as_of。
func TestListByPopularity_DBWindowStopsAfterSweepLimit(t *testing.T) {
f := newFeedFixture(t)
ctx := context.Background()
alive := f.seedHot(t, 1) // 分数最低,排在最后
for i := 0; i < 12; i++ {
gone := f.seedHot(t, 10+i) // 分数 10..21,全部排在前面
if err := f.db.Delete(&video.Video{}, gone.ID).Error; err != nil {
t.Fatalf("硬删视频 %d: %v", gone.ID, err)
}
}
f.mr.FlushAll()
// limit=2 → 5 批只够越过 10 行,第 11、12 行与存活的 alive 都还在后面。
resp, err := f.svc.ListByPopularity(ctx, 2, f.asOf.Unix(), 0, 0)
if err != nil {
t.Fatalf("ListByPopularity: %v", err)
}
if len(resp.VideoList) != 0 || resp.HasMore {
t.Fatalf("视频列表 = %v has_more=%v, want 空/false(撞到扫批上限后收尾)",
ids(resp.VideoList), resp.HasMore)
}
if want := 2 * hotDBMaxSweep; resp.NextOffset != want {
t.Fatalf("next_offset = %d, want %d(游标只越过 5 批 rows,alive=%d 留到下一个 as_of)",
resp.NextOffset, want, alive.ID)
}
}
// 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 页")
}
}
// 过期的 as_of 与未来的 as_of 都不能被采纳。
//
// 前者:快照已过 TTL,重建出来是另一个榜,交回同一个 as_of 会让客户端
// 以为还能续页。后者:那一分钟还没闭合,窗口仍在增长。
func TestListByPopularity_StaleAsOfIsReplaced(t *testing.T) {
f := newFeedFixture(t)
ctx := context.Background()
f.seedHot(t, 1)
cases := []struct {
name string
asOf int64
}{
{name: "超出快照 TTL", asOf: f.asOf.Add(-3 * time.Hour).Unix()},
{name: "未来分钟", asOf: time.Now().UTC().Add(10 * time.Minute).Unix()},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
resp, err := f.svc.ListByPopularity(ctx, 10, c.asOf, 0, 0)
if err != nil {
t.Fatalf("ListByPopularity: %v", err)
}
if want := f.asOf.Unix(); resp.AsOf != want {
t.Fatalf("as_of = %d, want %d(不可采纳的 as_of 必须换成上一个闭合分钟)", resp.AsOf, want)
}
})
}
}
// 非整分钟的 as_of 不是非法输入:截断到整分钟再采纳,由客户端按返回的 as_of 重置。
func TestListByPopularity_NonWholeMinuteAsOfIsTruncated(t *testing.T) {
f := newFeedFixture(t)
ctx := context.Background()
f.seedHot(t, 1)
requested := f.asOf.Add(-5*time.Minute + 30*time.Second)
resp, err := f.svc.ListByPopularity(ctx, 10, requested.Unix(), 0, 0)
if err != nil {
t.Fatalf("ListByPopularity: %v", err)
}
if want := f.asOf.Add(-5 * time.Minute).Unix(); resp.AsOf != want {
t.Fatalf("as_of = %d, want %d(非整分钟必须先截断再采纳,不是退回默认值)",
resp.AsOf, want)
}
}
// 负 offset 是非法游标,必须在读路径入口夹到 0。
//
// 不夹的话它一路走到 SQL:GORM 把 -1 绑成 OFFSET 的参数,MySQL 抛
// Error 1690(signed integer value is out of range in 'mysqld_stmt_execute'),
// 接口从"翻到头了"变成 500。
func TestListByPopularity_NegativeOffsetIsClamped(t *testing.T) {
f := newFeedFixture(t)
f.seedHot(t, 2)
// cache 为 nil:强制走 DB 窗口,offset 直接进 SQL,不经过 Redis 分页。
svc := NewFeedService(NewFeedRepository(f.db), video.NewLikeRepository(f.db), nil)
ctx := context.Background()
first, err := svc.ListByPopularity(ctx, 10, 0, 0, 0)
if err != nil {
t.Fatalf("offset=0: %v", err)
}
got, err := svc.ListByPopularity(ctx, 10, 0, -1, 0)
if err != nil {
t.Fatalf("offset=-1 应当夹到 0,却返回错误: %v", err)
}
if len(got.VideoList) != len(first.VideoList) {
t.Fatalf("offset=-1 返回 %d 条,offset=0 返回 %d 条:负游标没有被夹到 0",
len(got.VideoList), len(first.VideoList))
}
}