Files
VLoop/backend/internal/feed/service_integration_test.go
huanghaosheng 9d9fdb91e5 fix(feed): 把负 offset 夹到 0
负 offset 是非法游标。它一路走到 SQL 的 OFFSET 参数。
MySQL 抛 Error 1690,一次翻页请求变成 500。
入口夹一次就够:这个值同时喂给 Redis 的 LIMIT 与 SQL 的 OFFSET。
不放 handler 是因为 handler 只规整 limit,夹在服务层才能挡住所有调用方。

验证:go test -tags integration -p 1 -count=1 ./internal/feed/ 全绿
2026-11-01 16:25:11 +08:00

327 lines
10 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 页")
}
}
// 过期的 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)
}
})
}
}
// 负 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))
}
}