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/ 全绿
This commit is contained in:
2026-11-01 16:25:11 +08:00
parent eda8237c36
commit 9d9fdb91e5
2 changed files with 34 additions and 0 deletions

View File

@@ -461,6 +461,13 @@ func hotWindowBounds(asOf time.Time) (from, to time.Time) {
} }
func (f *FeedService) ListByPopularity(ctx context.Context, limit int, reqAsOf int64, offset int, viewerAccountID uint) (ListByPopularityResponse, error) { func (f *FeedService) ListByPopularity(ctx context.Context, limit int, reqAsOf int64, offset int, viewerAccountID uint) (ListByPopularityResponse, error) {
// offset 是榜内位置,负数没有意义。夹在入口而不是只夹在 handler:
// 它同时喂给 Redis 的 LIMIT 与 SQL 的 OFFSET,而后者拿到 -1 会直接
// 报错(Error 1690),把一个"翻到头了"的请求变成 500。
if offset < 0 {
offset = 0
}
asOf := lastClosedMinute(time.Now()) asOf := lastClosedMinute(time.Now())
if reqAsOf > 0 { if reqAsOf > 0 {
want := time.Unix(reqAsOf, 0).UTC().Truncate(time.Minute) want := time.Unix(reqAsOf, 0).UTC().Truncate(time.Minute)

View File

@@ -297,3 +297,30 @@ func TestListByPopularity_StaleAsOfIsReplaced(t *testing.T) {
}) })
} }
} }
// 负 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))
}
}