diff --git a/backend/internal/feed/service.go b/backend/internal/feed/service.go index d4e6fab..0071de3 100644 --- a/backend/internal/feed/service.go +++ b/backend/internal/feed/service.go @@ -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) { + // offset 是榜内位置,负数没有意义。夹在入口而不是只夹在 handler: + // 它同时喂给 Redis 的 LIMIT 与 SQL 的 OFFSET,而后者拿到 -1 会直接 + // 报错(Error 1690),把一个"翻到头了"的请求变成 500。 + if offset < 0 { + offset = 0 + } + asOf := lastClosedMinute(time.Now()) if reqAsOf > 0 { want := time.Unix(reqAsOf, 0).UTC().Truncate(time.Minute) diff --git a/backend/internal/feed/service_integration_test.go b/backend/internal/feed/service_integration_test.go index cc25dc1..b7a8fb6 100644 --- a/backend/internal/feed/service_integration_test.go +++ b/backend/internal/feed/service_integration_test.go @@ -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)) + } +}