mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 08:05:12 +00:00
Merge pull request #9221 from debug-zhang/fix/7867-user-last-used-query
perf(user): fetch latest usage timestamp with an index-backed lateral probe
This commit is contained in:
3 files changed
+181
-4
No files matched your search
@@ -732,11 +732,23 @@ func (r *userRepository) GetLatestUsedAtByUserIDs(ctx context.Context, userIDs [
|
||||
return nil, fmt.Errorf("sql executor is not configured")
|
||||
}
|
||||
|
||||
// Resolve each user's latest usage timestamp with an index-backed LATERAL
|
||||
// probe instead of aggregating every historical usage_logs row. With the
|
||||
// idx_usage_logs_user_created(user_id, created_at) index, the inner
|
||||
// ORDER BY created_at DESC LIMIT 1 is a single backward index scan per user,
|
||||
// so the cost is O(page size * log n) rather than O(history size).
|
||||
// The inner join keeps the previous semantics: users without usage rows are
|
||||
// absent from the result map.
|
||||
const query = `
|
||||
SELECT user_id, MAX(created_at) AS last_used_at
|
||||
FROM usage_logs
|
||||
WHERE user_id = ANY($1)
|
||||
GROUP BY user_id
|
||||
SELECT u.user_id, latest.created_at
|
||||
FROM unnest($1::bigint[]) AS u(user_id)
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT created_at
|
||||
FROM usage_logs
|
||||
WHERE user_id = u.user_id
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1
|
||||
) AS latest
|
||||
`
|
||||
|
||||
rows, err := r.sql.QueryContext(ctx, query, pq.Array(userIDs))
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"github.com/lib/pq"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// The previous implementation aggregated every historical usage_logs row per
|
||||
// user with MAX(created_at) ... GROUP BY user_id, so its cost grew with the
|
||||
// whole history. The replacement must probe only the newest row per user so
|
||||
// that idx_usage_logs_user_created(user_id, created_at) can serve each lookup
|
||||
// as a single backward index scan.
|
||||
const latestUsedAtLateralQueryPattern = `(?s)SELECT u\.user_id, latest\.created_at\s+` +
|
||||
`FROM unnest\(\$1::bigint\[\]\) AS u\(user_id\)\s+` +
|
||||
`CROSS JOIN LATERAL \(\s+` +
|
||||
`SELECT created_at\s+` +
|
||||
`FROM usage_logs\s+` +
|
||||
`WHERE user_id = u\.user_id\s+` +
|
||||
`ORDER BY created_at DESC\s+` +
|
||||
`LIMIT 1\s+` +
|
||||
`\) AS latest`
|
||||
|
||||
func TestUserRepositoryGetLatestUsedAtByUserIDsUsesLateralProbe(t *testing.T) {
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newUserRepositoryWithSQL(nil, db)
|
||||
|
||||
newestFor7 := time.Date(2026, 5, 4, 3, 2, 1, 0, time.FixedZone("UTC+8", 8*60*60))
|
||||
newestFor8 := time.Date(2026, 5, 3, 1, 0, 0, 0, time.UTC)
|
||||
|
||||
// User 9 has no usage rows, so it is absent from the result set.
|
||||
mock.ExpectQuery(latestUsedAtLateralQueryPattern).
|
||||
WithArgs(pq.Array([]int64{7, 8, 9})).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"user_id", "created_at"}).
|
||||
AddRow(int64(7), newestFor7).
|
||||
AddRow(int64(8), newestFor8))
|
||||
|
||||
got, err := repo.GetLatestUsedAtByUserIDs(context.Background(), []int64{7, 8, 9})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, got, 2)
|
||||
require.NotContains(t, got, int64(9))
|
||||
require.NotNil(t, got[7])
|
||||
require.NotNil(t, got[8])
|
||||
require.True(t, got[7].Equal(newestFor7))
|
||||
require.True(t, got[8].Equal(newestFor8))
|
||||
require.Equal(t, time.UTC, got[7].Location(), "timestamps must be normalized to UTC")
|
||||
require.Equal(t, time.UTC, got[8].Location())
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestUserRepositoryGetLatestUsedAtByUserIDsEmptyInputSkipsQuery(t *testing.T) {
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newUserRepositoryWithSQL(nil, db)
|
||||
|
||||
for _, ids := range [][]int64{nil, {}} {
|
||||
got, err := repo.GetLatestUsedAtByUserIDs(context.Background(), ids)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got)
|
||||
require.Empty(t, got)
|
||||
}
|
||||
|
||||
// No query is expected or allowed for an empty ID list.
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestUserRepositoryGetLatestUsedAtByUserIDsNoUsageRows(t *testing.T) {
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newUserRepositoryWithSQL(nil, db)
|
||||
|
||||
mock.ExpectQuery(latestUsedAtLateralQueryPattern).
|
||||
WithArgs(pq.Array([]int64{42})).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"user_id", "created_at"}))
|
||||
|
||||
got, err := repo.GetLatestUsedAtByUserIDs(context.Background(), []int64{42})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got)
|
||||
require.Empty(t, got)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestUserRepositoryGetLatestUsedAtByUserIDReusesBatchQuery(t *testing.T) {
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newUserRepositoryWithSQL(nil, db)
|
||||
|
||||
newest := time.Date(2026, 5, 5, 4, 3, 2, 0, time.UTC)
|
||||
mock.ExpectQuery(latestUsedAtLateralQueryPattern).
|
||||
WithArgs(pq.Array([]int64{7})).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"user_id", "created_at"}).AddRow(int64(7), newest))
|
||||
|
||||
got, err := repo.GetLatestUsedAtByUserID(context.Background(), 7)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got)
|
||||
require.True(t, got.Equal(newest))
|
||||
|
||||
mock.ExpectQuery(latestUsedAtLateralQueryPattern).
|
||||
WithArgs(pq.Array([]int64{8})).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"user_id", "created_at"}))
|
||||
missing, err := repo.GetLatestUsedAtByUserID(context.Background(), 8)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, missing)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestUserRepositoryGetLatestUsedAtByUserIDsPropagatesQueryError(t *testing.T) {
|
||||
db, mock := newSQLMock(t)
|
||||
repo := newUserRepositoryWithSQL(nil, db)
|
||||
|
||||
mock.ExpectQuery(latestUsedAtLateralQueryPattern).
|
||||
WithArgs(pq.Array([]int64{7})).
|
||||
WillReturnError(context.DeadlineExceeded)
|
||||
|
||||
got, err := repo.GetLatestUsedAtByUserIDs(context.Background(), []int64{7})
|
||||
require.ErrorIs(t, err, context.DeadlineExceeded)
|
||||
require.Nil(t, got)
|
||||
require.NoError(t, mock.ExpectationsWereMet())
|
||||
}
|
||||
@@ -133,6 +133,51 @@ func (s *UserRepoSuite) TestGetLatestUsedAtByUserIDs_UsesUsageLogs() {
|
||||
s.Require().True(got[userWithUsage.ID].Equal(newer))
|
||||
}
|
||||
|
||||
// The latest usage lookup must return each user's newest row even when older
|
||||
// rows are inserted after it and must never widen the result set with users
|
||||
// that have no usage history.
|
||||
func (s *UserRepoSuite) TestGetLatestUsedAtByUserIDs_PicksLatestPerUserRegardlessOfInsertOrder() {
|
||||
oldest := time.Now().Add(-48 * time.Hour).UTC().Truncate(time.Second)
|
||||
middle := time.Now().Add(-24 * time.Hour).UTC().Truncate(time.Second)
|
||||
newest := time.Now().Add(-time.Hour).UTC().Truncate(time.Second)
|
||||
|
||||
userA := s.mustCreateUser(&service.User{Email: "latest-a@example.com"})
|
||||
userB := s.mustCreateUser(&service.User{Email: "latest-b@example.com"})
|
||||
userWithoutUsage := s.mustCreateUser(&service.User{Email: "latest-none@example.com"})
|
||||
|
||||
// Insert A out of chronological order, then B with a single row.
|
||||
s.mustInsertUsageLog(userA.ID, middle)
|
||||
s.mustInsertUsageLog(userA.ID, newest)
|
||||
s.mustInsertUsageLog(userA.ID, oldest)
|
||||
s.mustInsertUsageLog(userB.ID, oldest)
|
||||
|
||||
got, err := s.repo.GetLatestUsedAtByUserIDs(s.ctx, []int64{userA.ID, userB.ID, userWithoutUsage.ID})
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(got, 2)
|
||||
s.Require().Contains(got, userA.ID)
|
||||
s.Require().Contains(got, userB.ID)
|
||||
s.Require().NotContains(got, userWithoutUsage.ID)
|
||||
s.Require().True(got[userA.ID].Equal(newest))
|
||||
s.Require().True(got[userB.ID].Equal(oldest))
|
||||
|
||||
single, err := s.repo.GetLatestUsedAtByUserID(s.ctx, userA.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotNil(single)
|
||||
s.Require().True(single.Equal(newest))
|
||||
}
|
||||
|
||||
func (s *UserRepoSuite) TestGetLatestUsedAtByUserIDs_EmptyInputReturnsEmptyMap() {
|
||||
got, err := s.repo.GetLatestUsedAtByUserIDs(s.ctx, nil)
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotNil(got)
|
||||
s.Require().Empty(got)
|
||||
|
||||
got, err = s.repo.GetLatestUsedAtByUserIDs(s.ctx, []int64{})
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotNil(got)
|
||||
s.Require().Empty(got)
|
||||
}
|
||||
|
||||
func (s *UserRepoSuite) TestListWithFilters_SortByLastUsedAtDesc_UsesUsageLogsNotLastActiveAt() {
|
||||
lastUsedOlder := time.Now().Add(-6 * time.Hour).UTC().Truncate(time.Second)
|
||||
lastUsedNewer := time.Now().Add(-2 * time.Hour).UTC().Truncate(time.Second)
|
||||
|
||||
Reference in new issue
Block a user