From 803109530820e43efd6a697478bfc025d00a3867 Mon Sep 17 00:00:00 2001 From: Rishi Balakrishnan Date: Thu, 17 Sep 2026 12:07:39 -0400 Subject: [PATCH] fix(pagination): adopt upstream enumeration and quote safeguards --- eslint-suppressions.json | 4 +- package.json | 2 +- src/lib/api/feed/custom.test.ts | 50 +++++++ src/lib/api/feed/custom.ts | 6 +- src/lib/api/feed/likes.ts | 4 +- src/lib/api/feed/merge.test.ts | 125 ++++++++++++++++++ src/lib/api/feed/merge.ts | 24 +++- .../__tests__/enumeration-pagination.test.ts | 51 +++++++ .../__tests__/post-quotes-pagination.test.tsx | 58 ++++++++ src/state/queries/list-members.ts | 13 +- src/state/queries/notifications/feed.ts | 82 +----------- src/state/queries/pagination.ts | 16 +++ src/state/queries/post-feed.ts | 58 ++------ src/state/queries/post-quotes.ts | 7 +- src/state/queries/profile-follows.ts | 4 +- src/state/queries/util.test.tsx | 100 ++++++++++++++ src/state/queries/util.ts | 77 +++++++++++ src/view/com/feeds/ProfileFeedgens.tsx | 2 +- src/view/com/lists/ListMembers.tsx | 20 +-- src/view/com/lists/ProfileLists.tsx | 2 +- src/view/com/profile/ProfileFollows.tsx | 6 +- .../screens/ModerationBlockedAccounts.tsx | 2 +- src/view/screens/ModerationMutedAccounts.tsx | 2 +- 23 files changed, 552 insertions(+), 163 deletions(-) create mode 100644 src/lib/api/feed/custom.test.ts create mode 100644 src/lib/api/feed/merge.test.ts create mode 100644 src/state/queries/__tests__/enumeration-pagination.test.ts create mode 100644 src/state/queries/__tests__/post-quotes-pagination.test.tsx create mode 100644 src/state/queries/pagination.ts create mode 100644 src/state/queries/util.test.tsx diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 09de57aee..e300a6dd4 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -1796,7 +1796,7 @@ "count": 2 }, "@typescript-eslint/no-floating-promises": { - "count": 2 + "count": 1 }, "@typescript-eslint/no-unsafe-member-access": { "count": 2 @@ -1834,7 +1834,7 @@ "count": 3 }, "@typescript-eslint/no-floating-promises": { - "count": 3 + "count": 2 }, "@typescript-eslint/no-unsafe-member-access": { "count": 3 diff --git a/package.json b/package.json index 49341309a..59a9adbe3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "blacksky.community", - "version": "1.130.1", + "version": "1.130.2", "private": true, "packageManager": "pnpm@11.7.0", "engines": { diff --git a/src/lib/api/feed/custom.test.ts b/src/lib/api/feed/custom.test.ts new file mode 100644 index 000000000..c75628333 --- /dev/null +++ b/src/lib/api/feed/custom.test.ts @@ -0,0 +1,50 @@ +import {type AtpAgent} from '@atproto/api' + +import {CustomFeedAPI} from './custom' + +jest.mock('@atproto/api', () => ({ + ...jest.requireActual('@atproto/api'), + jsonStringToLex: JSON.parse, +})) + +jest.mock('#/state/preferences/languages', () => ({ + getAppLanguageAsContentLanguage: () => '', + getContentLanguages: () => [], +})) + +jest.mock('#/lib/api/community-feed', () => ({ + fetchCommunityFeedConfigStrict: jest.fn().mockResolvedValue(null), + isSpaceBackedFeed: () => false, +})) + +jest.mock('./utils', () => ({ + createBskyTopicsHeader: () => ({}), + isBlueskyOwnedFeed: () => false, +})) + +describe('CustomFeedAPI', () => { + it('preserves the cursor from an empty logged-out fallback page', async () => { + const originalFetch = global.fetch + const fetchMock: jest.MockedFunction = jest + .fn() + .mockResolvedValueOnce(Response.json({feed: []})) + .mockResolvedValueOnce(Response.json({feed: [], cursor: 'next'})) + global.fetch = fetchMock + const api = new CustomFeedAPI({ + agent: {did: undefined} as unknown as AtpAgent, + feedParams: { + feed: 'at://did:example:feed/app.bsky.feed.generator/test', + }, + }) + + try { + await expect(api.fetch({cursor: undefined, limit: 10})).resolves.toEqual({ + cursor: 'next', + feed: [], + }) + expect(fetchMock).toHaveBeenCalledTimes(2) + } finally { + global.fetch = originalFetch + } + }) +}) diff --git a/src/lib/api/feed/custom.ts b/src/lib/api/feed/custom.ts index 00065bc6f..669a78b47 100644 --- a/src/lib/api/feed/custom.ts +++ b/src/lib/api/feed/custom.ts @@ -119,7 +119,7 @@ export class CustomFeedAPI implements FeedAPI { if (!this.agent.did) throw signInRequiredError() const page = await fetchSpaceFeed(this.agent, spaceFeed, {cursor, limit}) return { - cursor: page.feed.length ? page.cursor : undefined, + cursor: page.cursor, feed: page.feed, } } @@ -159,7 +159,7 @@ export class CustomFeedAPI implements FeedAPI { res.data.feed = res.data.feed.slice(0, limit) } return { - cursor: res.data.feed.length ? res.data.cursor : undefined, + cursor: res.data.cursor, feed: res.data.feed, } } @@ -227,7 +227,7 @@ async function loggedOutFetch({ data = res.ok ? (jsonStringToLex(await res.text()) as GetCustomFeed.OutputSchema) : null - if (data?.feed?.length) { + if (data) { return { success: true, data, diff --git a/src/lib/api/feed/likes.ts b/src/lib/api/feed/likes.ts index 1511dc833..0581e6445 100644 --- a/src/lib/api/feed/likes.ts +++ b/src/lib/api/feed/likes.ts @@ -42,10 +42,8 @@ export class LikesFeedAPI implements FeedAPI { limit, }) if (res.success) { - // HACKFIX: the API incorrectly returns a cursor when there are no items -sfn - const isEmptyPage = res.data.feed.length === 0 return { - cursor: isEmptyPage ? undefined : res.data.cursor, + cursor: res.data.cursor, feed: res.data.feed, } } diff --git a/src/lib/api/feed/merge.test.ts b/src/lib/api/feed/merge.test.ts new file mode 100644 index 000000000..46d90d768 --- /dev/null +++ b/src/lib/api/feed/merge.test.ts @@ -0,0 +1,125 @@ +import {type AppBskyFeedDefs, type AtpAgent} from '@atproto/api' + +import {MergeFeedAPI} from './merge' + +const post = {} as AppBskyFeedDefs.FeedViewPost + +describe('MergeFeedAPI', () => { + it('drains a terminal following queue without restarting the source', async () => { + const api = new MergeFeedAPI({ + agent: {} as AtpAgent, + feedParams: {}, + feedTuners: [], + }) + api.reset() + api.following.queue = [post, post, post] + api.following.hasMore = false + + const first = await api.fetch({cursor: 'started', limit: 2}) + const second = await api.fetch({cursor: first.cursor, limit: 2}) + + expect(first.feed).toHaveLength(2) + expect(first.cursor).toBeDefined() + expect(second.feed).toHaveLength(1) + expect(second.cursor).toBeUndefined() + }) + + it('stops when the following source repeats its cursor', async () => { + const call = jest + .fn() + .mockResolvedValueOnce({feed: [], cursor: 'a'}) + .mockResolvedValueOnce({feed: [], cursor: 'a'}) + const api = new MergeFeedAPI({ + agent: { + getTimeline: async (...args: unknown[]) => ({ + success: true, + data: await call(...args), + }), + } as unknown as AtpAgent, + feedParams: {}, + feedTuners: [], + }) + + const first = await api.fetch({cursor: undefined, limit: 1}) + const second = await api.fetch({cursor: first.cursor, limit: 1}) + + expect(first.cursor).toBeDefined() + expect(second.cursor).toBeUndefined() + expect(call).toHaveBeenCalledTimes(2) + }) + + it('stops when the following source returns an empty cursor', async () => { + const call = jest.fn().mockResolvedValue({feed: [], cursor: ''}) + const api = new MergeFeedAPI({ + agent: { + getTimeline: async (...args: unknown[]) => ({ + success: true, + data: await call(...args), + }), + } as unknown as AtpAgent, + feedParams: {}, + feedTuners: [], + }) + + const result = await api.fetch({cursor: undefined, limit: 1}) + + expect(result.cursor).toBeUndefined() + expect(call).toHaveBeenCalledTimes(1) + }) + + it('stops when the following source cycles to an earlier cursor', async () => { + const call = jest + .fn() + .mockResolvedValueOnce({feed: [], cursor: 'a'}) + .mockResolvedValueOnce({feed: [], cursor: 'b'}) + .mockResolvedValueOnce({feed: [], cursor: 'a'}) + const api = new MergeFeedAPI({ + agent: { + getTimeline: async (...args: unknown[]) => ({ + success: true, + data: await call(...args), + }), + } as unknown as AtpAgent, + feedParams: {}, + feedTuners: [], + }) + + const first = await api.fetch({cursor: undefined, limit: 1}) + const second = await api.fetch({cursor: first.cursor, limit: 1}) + const third = await api.fetch({cursor: second.cursor, limit: 1}) + + expect(third.cursor).toBeUndefined() + expect(call).toHaveBeenCalledTimes(3) + }) + + it('drains a terminal custom-feed queue without restarting the source', async () => { + const call = jest.fn() + const api = new MergeFeedAPI({ + agent: { + getTimeline: async (...args: unknown[]) => ({ + success: true, + data: await call(...args), + }), + } as unknown as AtpAgent, + feedParams: { + mergeFeedEnabled: true, + mergeFeedSources: [ + 'at://did:example:feed/app.bsky.feed.generator/test', + ], + }, + feedTuners: [], + }) + api.reset() + api.following.hasMore = false + api.customFeeds[0].queue = [post, post, post] + api.customFeeds[0].hasMore = false + + const first = await api.fetch({cursor: 'started', limit: 2}) + const second = await api.fetch({cursor: first.cursor, limit: 2}) + + expect(first.feed).toHaveLength(2) + expect(second.feed).toHaveLength(1) + expect(second.cursor).toBeUndefined() + expect(call).not.toHaveBeenCalled() + }) +}) diff --git a/src/lib/api/feed/merge.ts b/src/lib/api/feed/merge.ts index d5e013e18..2dc03994a 100644 --- a/src/lib/api/feed/merge.ts +++ b/src/lib/api/feed/merge.ts @@ -104,8 +104,8 @@ export class MergeFeedAPI implements FeedAPI { const promises = [] - // always keep following topped up - if (this.following.numReady < limit) { + // always keep following topped up while the source has another page + if (this.following.hasMore && this.following.numReady < limit) { await this.following.fetchNext(60) } @@ -121,7 +121,7 @@ export class MergeFeedAPI implements FeedAPI { !this.following.hasMore && this.following.numReady < limit if (this.params.mergeFeedEnabled || outOfFollows) { for (const feed of feeds) { - if (feed.numReady < 5) { + if (feed.hasMore && feed.numReady < 5) { promises.push(feed.fetchNext(10)) } } @@ -141,8 +141,12 @@ export class MergeFeedAPI implements FeedAPI { } } + const hasMore = + this.following.hasMore || + this.following.numReady > 0 || + this.customFeeds.some(feed => feed.hasMore || feed.numReady > 0) return { - cursor: String(this.itemCursor), + cursor: hasMore ? String(this.itemCursor) : undefined, feed: posts, } } @@ -151,8 +155,8 @@ export class MergeFeedAPI implements FeedAPI { const i = this.itemCursor++ const candidateFeeds = this.customFeeds.filter(f => f.numReady > 0) const canSample = candidateFeeds.length > 0 - const hasFollows = this.following.hasMore const hasFollowsReady = this.following.numReady > 0 + const hasFollows = this.following.hasMore || hasFollowsReady // this condition establishes the frequency that custom feeds are woven into follows const shouldSample = @@ -183,6 +187,7 @@ class MergeFeedSource { feedTuners: FeedTunerFn[] sourceInfo: ReasonFeedSource | undefined cursor: string | undefined = undefined + seenCursors = new Set() queue: AppBskyFeedDefs.FeedViewPost[] = [] hasMore = true @@ -217,11 +222,16 @@ class MergeFeedSource { const res = await this._getFeed(this.cursor, n) if (res.success) { this.cursor = res.data.cursor - if (res.data.feed.length) { - this.queue = this.queue.concat(res.data.feed) + const cursor = this.cursor + if (cursor) { + this.hasMore = !this.seenCursors.has(cursor) + this.seenCursors.add(cursor) } else { this.hasMore = false } + if (res.data.feed.length) { + this.queue = this.queue.concat(res.data.feed) + } } else { this.hasMore = false } diff --git a/src/state/queries/__tests__/enumeration-pagination.test.ts b/src/state/queries/__tests__/enumeration-pagination.test.ts new file mode 100644 index 000000000..017d0c582 --- /dev/null +++ b/src/state/queries/__tests__/enumeration-pagination.test.ts @@ -0,0 +1,51 @@ +import {type AppBskyGraphDefs, type AtpAgent} from '@atproto/api' + +jest.mock('#/state/session', () => ({useAgent: jest.fn()})) + +import {getAllListMembers} from '#/state/queries/list-members' +import {dedupeBy, getNextCursor} from '#/state/queries/pagination' + +function listItem(did: string): AppBskyGraphDefs.ListItemView { + return {subject: {did}} as AppBskyGraphDefs.ListItemView +} + +describe('enumeration pagination', () => { + it('rejects a cursor that has already been requested', () => { + expect(getNextCursor('cursor-b', [undefined, 'cursor-a'])).toBe('cursor-b') + expect(getNextCursor('cursor-a', [undefined, 'cursor-a'])).toBeUndefined() + }) + + it('keeps the first occurrence of each account in server order', () => { + const items = [ + listItem('did:plc:first'), + listItem('did:plc:jason'), + listItem('did:plc:jason'), + ] + + expect(dedupeBy(items, item => item.subject.did)).toEqual(items.slice(0, 2)) + }) + + it('stops and deduplicates when list pagination repeats its cursor', async () => { + const first = listItem('did:plc:first') + const repeated = listItem('did:plc:jason') + const getList = jest + .fn() + .mockResolvedValueOnce({ + data: {items: [first, repeated], cursor: 'stuck-cursor'}, + }) + .mockResolvedValue({ + data: {items: [repeated], cursor: 'stuck-cursor'}, + }) + const agent = { + app: {bsky: {graph: {getList}}}, + } as unknown as AtpAgent + + const items = await getAllListMembers(agent, 'at://did:plc:test/list/1') + + expect(items.map(item => item.subject.did)).toEqual([ + 'did:plc:first', + 'did:plc:jason', + ]) + expect(getList).toHaveBeenCalledTimes(2) + }) +}) diff --git a/src/state/queries/__tests__/post-quotes-pagination.test.tsx b/src/state/queries/__tests__/post-quotes-pagination.test.tsx new file mode 100644 index 000000000..031464a74 --- /dev/null +++ b/src/state/queries/__tests__/post-quotes-pagination.test.tsx @@ -0,0 +1,58 @@ +import {type ReactNode} from 'react' +import {type AppBskyFeedDefs} from '@atproto/api' +import {QueryClient, QueryClientProvider} from '@tanstack/react-query' +import {act, renderHook, waitFor} from '@testing-library/react-native' + +import {usePostQuotesQuery} from '#/state/queries/post-quotes' +import {useAgent} from '#/state/session' + +jest.mock('#/state/session', () => ({useAgent: jest.fn()})) +jest.mock('#/lib/api/community', () => ({getSpacePostQuotes: jest.fn()})) + +const subject = 'at://did:plc:subject/app.bsky.feed.post/subject' +const quote = (id: string) => + ({ + uri: `at://did:plc:author/app.bsky.feed.post/${id}`, + }) as AppBskyFeedDefs.PostView + +it('stops the repeated quote cursor and displays each post once', async () => { + const first = quote('first') + const tail = quote('tail') + const getQuotes = jest + .fn() + .mockResolvedValueOnce({ + data: {posts: [first, tail], cursor: 'tail-cursor'}, + }) + .mockResolvedValue({data: {posts: [tail], cursor: 'tail-cursor'}}) + jest.mocked(useAgent).mockReturnValue({ + api: {app: {bsky: {feed: {getQuotes}}}}, + } as unknown as ReturnType) + const client = new QueryClient({defaultOptions: {queries: {retry: false}}}) + const wrapper = ({children}: {children: ReactNode}) => ( + {children} + ) + const {result, unmount} = renderHook(() => usePostQuotesQuery(subject), { + wrapper, + }) + try { + await waitFor(() => expect(result.current.isSuccess).toBe(true)) + expect(result.current.hasNextPage).toBe(true) + await act(async () => { + await result.current.fetchNextPage() + }) + await waitFor(() => expect(result.current.hasNextPage).toBe(false)) + expect(result.current.data?.pages.flatMap(page => page.posts)).toEqual([ + first, + tail, + ]) + expect(getQuotes).toHaveBeenCalledTimes(2) + expect(getQuotes).toHaveBeenLastCalledWith({ + uri: subject, + limit: 30, + cursor: 'tail-cursor', + }) + } finally { + unmount() + client.clear() + } +}) diff --git a/src/state/queries/list-members.ts b/src/state/queries/list-members.ts index c43c7bb98..5484e67a7 100644 --- a/src/state/queries/list-members.ts +++ b/src/state/queries/list-members.ts @@ -13,6 +13,7 @@ import { } from '@tanstack/react-query' import {STALE} from '#/state/queries' +import {dedupeBy, getNextCursor} from '#/state/queries/pagination' import {useAgent} from '#/state/session' const PAGE_SIZE = 30 @@ -43,7 +44,8 @@ export function useListMembersQuery(uri?: string, limit: number = PAGE_SIZE) { return res.data }, initialPageParam: undefined, - getNextPageParam: lastPage => lastPage.cursor, + getNextPageParam: (lastPage, _allPages, _lastPageParam, allPageParams) => + getNextCursor(lastPage.cursor, allPageParams), enabled: Boolean(uri), }) } @@ -64,6 +66,7 @@ export async function getAllListMembers(agent: AtpAgent, uri: string) { let hasMore = true let cursor: string | undefined const listItems: AppBskyGraphDefs.ListItemView[] = [] + const pageParams: RQPageParam[] = [] // We want to cap this at 6 pages, just for anything weird happening with the api let i = 0 while (hasMore && i < 6) { @@ -73,11 +76,13 @@ export async function getAllListMembers(agent: AtpAgent, uri: string) { cursor, }) listItems.push(...res.data.items) - hasMore = Boolean(res.data.cursor) - cursor = res.data.cursor + pageParams.push(cursor) + const nextCursor = getNextCursor(res.data.cursor, pageParams) + hasMore = Boolean(nextCursor) + cursor = nextCursor i++ } - return listItems + return dedupeBy(listItems, item => item.subject.did) } export async function invalidateListMembersQuery({ diff --git a/src/state/queries/notifications/feed.ts b/src/state/queries/notifications/feed.ts index 745e61081..889da5ef6 100644 --- a/src/state/queries/notifications/feed.ts +++ b/src/state/queries/notifications/feed.ts @@ -16,7 +16,7 @@ * 3. Don't call this query's `refetch()` if you're trying to sync latest; call `checkUnread()` instead. */ -import {useCallback, useEffect, useMemo, useRef} from 'react' +import {useCallback, useMemo, useRef} from 'react' import {AppBskyFeedDefs, AppBskyFeedPost, moderatePost} from '@atproto/api' import { type InfiniteData, @@ -36,8 +36,8 @@ import { embedViewRecordToPostView, getEmbeddedPost, makeUriMatcher, + useAutoPagination, } from '../util' -import {nextAutoPaginationAttemptCount, shouldAutoPaginate} from './pagination' import {type FeedPage} from './types' import {useUnreadNotificationsApi} from './unread' import {fetchPage} from './util' @@ -220,81 +220,9 @@ export function useNotificationFeedQuery(opts: { ), }) - // The server may end up returning an empty page, a page with too few items, - // or a page with items that end up getting filtered out. When we fetch pages, - // we'll keep track of how many items we actually hope to see. If the server - // doesn't return enough items, we're going to continue asking for more items. - const lastItemCount = useRef(0) - const wantedItemCount = useRef(0) - const autoPaginationAttemptCount = useRef(0) - useEffect(() => { - const {data, isLoading, isRefetching, isFetchingNextPage, hasNextPage} = - query - // Count the items that we already have. - let itemCount = 0 - for (const page of data?.pages || []) { - itemCount += page.items.length - } - - // If items got truncated, reset the state we're tracking below. - if (itemCount !== lastItemCount.current) { - if (itemCount < lastItemCount.current) { - wantedItemCount.current = itemCount - } - lastItemCount.current = itemCount - } - - // Now track how many items we really want, and fetch more if needed. - if (isLoading || isRefetching) { - // During the initial fetch, we want to get an entire page's worth of items. - wantedItemCount.current = PAGE_SIZE - autoPaginationAttemptCount.current = nextAutoPaginationAttemptCount({ - attemptCount: autoPaginationAttemptCount.current, - hasNextPage: !!hasNextPage, - isLoading, - isRefetching, - requestNextPage: false, - }) - } else if (isFetchingNextPage) { - if (itemCount > wantedItemCount.current) { - // We have more items than wantedItemCount, so wantedItemCount must be out of date. - // Some other code must have called fetchNextPage(), for example, from onEndReached. - // Adjust the wantedItemCount to reflect that we want one more full page of items. - wantedItemCount.current = itemCount + PAGE_SIZE - } - } else if (hasNextPage) { - // At this point we're not fetching anymore, so it's time to make a decision. - // If we didn't receive enough items from the server, paginate again until we do. - if (itemCount < wantedItemCount.current) { - const requestNextPage = shouldAutoPaginate({ - hasNextPage, - itemCount, - wantedItemCount: wantedItemCount.current, - attemptCount: autoPaginationAttemptCount.current, - }) - autoPaginationAttemptCount.current = nextAutoPaginationAttemptCount({ - attemptCount: autoPaginationAttemptCount.current, - hasNextPage, - isLoading, - isRefetching, - requestNextPage, - }) - if (requestNextPage) { - query.fetchNextPage() - } - } else { - autoPaginationAttemptCount.current = 0 - } - } else { - autoPaginationAttemptCount.current = nextAutoPaginationAttemptCount({ - attemptCount: autoPaginationAttemptCount.current, - hasNextPage: false, - isLoading, - isRefetching, - requestNextPage: false, - }) - } - }, [query]) + const itemCount = + query.data?.pages.reduce((count, page) => count + page.items.length, 0) ?? 0 + useAutoPagination(query, itemCount, PAGE_SIZE) return query } diff --git a/src/state/queries/pagination.ts b/src/state/queries/pagination.ts new file mode 100644 index 000000000..399d821fe --- /dev/null +++ b/src/state/queries/pagination.ts @@ -0,0 +1,16 @@ +export function getNextCursor( + cursor: string | undefined, + pageParams: readonly (string | undefined)[], +) { + return cursor && !pageParams.includes(cursor) ? cursor : undefined +} + +export function dedupeBy(items: readonly T[], getKey: (item: T) => string) { + const seen = new Set() + return items.filter(item => { + const key = getKey(item) + if (seen.has(key)) return false + seen.add(key) + return true + }) +} diff --git a/src/state/queries/post-feed.ts b/src/state/queries/post-feed.ts index f7163ea76..585bb5646 100644 --- a/src/state/queries/post-feed.ts +++ b/src/state/queries/post-feed.ts @@ -1,4 +1,4 @@ -import {useCallback, useEffect, useMemo, useRef} from 'react' +import {useCallback, useMemo, useRef} from 'react' import {AppState} from 'react-native' import { type AppBskyActorDefs, @@ -42,6 +42,7 @@ import { embedViewRecordToPostView, getEmbeddedPost, makeUriMatcher, + useAutoPagination, } from './util' type ActorDid = string @@ -362,56 +363,13 @@ export function usePostFeedQuery( ), }) - // The server may end up returning an empty page, a page with too few items, - // or a page with items that end up getting filtered out. When we fetch pages, - // we'll keep track of how many items we actually hope to see. If the server - // doesn't return enough items, we're going to continue asking for more items. - const lastItemCount = useRef(0) - const wantedItemCount = useRef(0) - const autoPaginationAttemptCount = useRef(0) - useEffect(() => { - const {data, isLoading, isRefetching, isFetchingNextPage, hasNextPage} = - query - // Count the items that we already have. - let itemCount = 0 - for (const page of data?.pages || []) { - for (const slice of page.slices) { - itemCount += slice.items.length - } - } - - // If items got truncated, reset the state we're tracking below. - if (itemCount !== lastItemCount.current) { - if (itemCount < lastItemCount.current) { - wantedItemCount.current = itemCount - } - lastItemCount.current = itemCount + let itemCount = 0 + for (const page of query.data?.pages || []) { + for (const slice of page.slices) { + itemCount += slice.items.length } - - // Now track how many items we really want, and fetch more if needed. - if (isLoading || isRefetching) { - // During the initial fetch, we want to get an entire page's worth of items. - wantedItemCount.current = MIN_POSTS - } else if (isFetchingNextPage) { - if (itemCount > wantedItemCount.current) { - // We have more items than wantedItemCount, so wantedItemCount must be out of date. - // Some other code must have called fetchNextPage(), for example, from onEndReached. - // Adjust the wantedItemCount to reflect that we want one more full page of items. - wantedItemCount.current = itemCount + MIN_POSTS - } - } else if (hasNextPage) { - // At this point we're not fetching anymore, so it's time to make a decision. - // If we didn't receive enough items from the server, paginate again until we do. - if (itemCount < wantedItemCount.current) { - autoPaginationAttemptCount.current++ - if (autoPaginationAttemptCount.current < 50 /* failsafe */) { - query.fetchNextPage() - } - } else { - autoPaginationAttemptCount.current = 0 - } - } - }, [query]) + } + useAutoPagination(query, itemCount, MIN_POSTS) return query } diff --git a/src/state/queries/post-quotes.ts b/src/state/queries/post-quotes.ts index 633b79f50..2b3b1161c 100644 --- a/src/state/queries/post-quotes.ts +++ b/src/state/queries/post-quotes.ts @@ -14,6 +14,7 @@ import { import {getSpacePostQuotes} from '#/lib/api/community' import {isSpaceRecordUri} from '#/lib/api/space-uri' +import {getNextCursor} from '#/state/queries/pagination' import {useAgent} from '#/state/session' import { embedViewRecordToPostView, @@ -61,9 +62,11 @@ export function usePostQuotesQuery(resolvedUri: string | undefined) { return fetchPostQuotesPage(agent, resolvedUri || '', pageParam) }, initialPageParam: undefined, - getNextPageParam: lastPage => lastPage.cursor, + getNextPageParam: (lastPage, _allPages, _lastPageParam, allPageParams) => + getNextCursor(lastPage.cursor, allPageParams), enabled: !!resolvedUri, select: data => { + const seen = new Set() return { ...data, pages: data.pages.map(page => { @@ -75,6 +78,8 @@ export function usePostQuotesQuery(resolvedUri: string | undefined) { return false } } + if (seen.has(post.uri)) return false + seen.add(post.uri) return true }), } diff --git a/src/state/queries/profile-follows.ts b/src/state/queries/profile-follows.ts index 1b154793d..60bd0de70 100644 --- a/src/state/queries/profile-follows.ts +++ b/src/state/queries/profile-follows.ts @@ -7,6 +7,7 @@ import { } from '@tanstack/react-query' import {STALE} from '#/state/queries' +import {getNextCursor} from '#/state/queries/pagination' import {useAgent} from '#/state/session' const PAGE_SIZE = 30 @@ -45,7 +46,8 @@ export function useProfileFollowsQuery( return res.data }, initialPageParam: undefined, - getNextPageParam: lastPage => lastPage.cursor, + getNextPageParam: (lastPage, _allPages, _lastPageParam, allPageParams) => + getNextCursor(lastPage.cursor, allPageParams), enabled: !!did, }) } diff --git a/src/state/queries/util.test.tsx b/src/state/queries/util.test.tsx new file mode 100644 index 000000000..695ada069 --- /dev/null +++ b/src/state/queries/util.test.tsx @@ -0,0 +1,100 @@ +import {renderHook} from '@testing-library/react-native' + +import {useAutoPagination} from './util' + +function query(overrides: Record = {}) { + return { + data: {pageParams: [undefined]}, + isLoading: false, + isRefetching: false, + isFetchingNextPage: false, + hasNextPage: true, + fetchNextPage: jest.fn().mockResolvedValue(undefined), + ...overrides, + } +} + +describe('useAutoPagination', () => { + it('fetches another page when visible items are missing', () => { + const value = query() + + renderHook(() => useAutoPagination(value, 0, 10)) + + expect(value.fetchNextPage).toHaveBeenCalledTimes(1) + }) + + it('stops when the requested number of items is visible', () => { + const value = query() + + renderHook(() => useAutoPagination(value, 10, 10)) + + expect(value.fetchNextPage).not.toHaveBeenCalled() + }) + + it('stops when the server repeats a cursor', () => { + const value = query({data: {pageParams: [undefined, 'a', 'a']}}) + + renderHook(() => useAutoPagination(value, 0, 10)) + + expect(value.fetchNextPage).not.toHaveBeenCalled() + }) + + it('stops when structured page params repeat a cursor', () => { + const value = query({ + data: {pageParams: [undefined, {cursor: 'a'}, {cursor: 'a'}]}, + }) + + renderHook(() => useAutoPagination(value, 0, 10)) + + expect(value.fetchNextPage).not.toHaveBeenCalled() + }) + + it('stops when a cursor repeats non-adjacently', () => { + const value = query({data: {pageParams: [undefined, 'a', 'b', 'a']}}) + + renderHook(() => useAutoPagination(value, 0, 10)) + + expect(value.fetchNextPage).not.toHaveBeenCalled() + }) + + it('fills one page after switching to a smaller cached query', () => { + const first = query({hasNextPage: false}) + const second = query() + let value = first + let itemCount = 10 + const {rerender} = renderHook(() => useAutoPagination(value, itemCount, 10)) + + value = second + itemCount = 5 + rerender(undefined) + + expect(second.fetchNextPage).toHaveBeenCalledTimes(1) + }) + + it('resets the attempt limit after switching to cached data with the same item count', () => { + const fetchNextPage = jest.fn().mockResolvedValue(undefined) + const data = {pageParams: [undefined]} + let value = query({fetchNextPage, data}) + const itemCount = 0 + const {rerender} = renderHook(() => useAutoPagination(value, itemCount, 10)) + + for (let i = 1; i < 50; i++) { + value = query({ + fetchNextPage, + data, + }) + rerender(undefined) + } + expect(fetchNextPage).toHaveBeenCalledTimes(49) + + const second = query({ + data: { + pageParams: Array.from({length: 51}, (_, i) => `new-cursor-${i}`), + }, + }) + value = second + rerender(undefined) + + expect(second.fetchNextPage).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/state/queries/util.ts b/src/state/queries/util.ts index 90c0520d1..1c240ac27 100644 --- a/src/state/queries/util.ts +++ b/src/state/queries/util.ts @@ -1,3 +1,4 @@ +import {useEffect, useRef} from 'react' import { type AppBskyActorDefs, AppBskyEmbedRecord, @@ -15,6 +16,82 @@ import { import {isSpaceRecordUri} from '#/lib/api/space-uri' import * as bsky from '#/types/bsky' +type AutoPaginationQuery = { + data?: {pageParams: unknown[]} + isLoading: boolean + isRefetching: boolean + isFetchingNextPage: boolean + hasNextPage: boolean + fetchNextPage: () => Promise +} + +export function useAutoPagination( + query: AutoPaginationQuery, + itemCount: number, + pageSize: number, +) { + const lastItemCount = useRef(0) + const lastPageParams = useRef(query.data?.pageParams) + const wantedItemCount = useRef(pageSize) + const attemptCount = useRef(0) + + useEffect(() => { + const cursorOf = (param: unknown) => + param && typeof param === 'object' && 'cursor' in param + ? param.cursor + : param + const pageParams = query.data?.pageParams + const previousPageParams = lastPageParams.current + const continuedPagination = + pageParams && + previousPageParams && + pageParams.length > previousPageParams.length && + previousPageParams.every((param, index) => + Object.is(cursorOf(param), cursorOf(pageParams[index])), + ) + if ( + pageParams !== previousPageParams && + previousPageParams && + !continuedPagination + ) { + wantedItemCount.current = pageSize + attemptCount.current = 0 + } + lastPageParams.current = pageParams + + if (itemCount !== lastItemCount.current) { + attemptCount.current = 0 + if (itemCount < lastItemCount.current) { + wantedItemCount.current = Math.max(itemCount, pageSize) + } + lastItemCount.current = itemCount + } + + if (query.isLoading || query.isRefetching) { + wantedItemCount.current = pageSize + attemptCount.current = 0 + } else if (query.isFetchingNextPage) { + if (itemCount > wantedItemCount.current) { + wantedItemCount.current = itemCount + pageSize + } + } else if (query.hasNextPage) { + if (itemCount < wantedItemCount.current) { + const currentCursor = cursorOf(pageParams?.at(-1)) + const repeatedCursor = pageParams + ?.slice(0, -1) + .some(param => Object.is(cursorOf(param), currentCursor)) + if (repeatedCursor) return + attemptCount.current++ + if (attemptCount.current < 50) { + void query.fetchNextPage() + } + } else { + attemptCount.current = 0 + } + } + }, [itemCount, pageSize, query]) +} + export type StructuredQueryKey> = readonly [ string, T, diff --git a/src/view/com/feeds/ProfileFeedgens.tsx b/src/view/com/feeds/ProfileFeedgens.tsx index 6eedcd862..2b1e7b19b 100644 --- a/src/view/com/feeds/ProfileFeedgens.tsx +++ b/src/view/com/feeds/ProfileFeedgens.tsx @@ -79,7 +79,7 @@ export function ProfileFeedgens({ error, refetch, } = useProfileFeedgensQuery(did, opts) - const isEmpty = !isPending && !data?.pages[0]?.feeds.length + const isEmpty = !isPending && !data?.pages.some(page => page.feeds.length) const {data: preferences} = usePreferencesQuery() const navigation = useNavigation() const {currentAccount} = useSession() diff --git a/src/view/com/lists/ListMembers.tsx b/src/view/com/lists/ListMembers.tsx index 04876eefb..a80a6cfbb 100644 --- a/src/view/com/lists/ListMembers.tsx +++ b/src/view/com/lists/ListMembers.tsx @@ -15,6 +15,7 @@ import {cleanError} from '#/lib/strings/errors' import {logger} from '#/logger' import {useModerationOpts} from '#/state/preferences/moderation-opts' import {useListMembersQuery} from '#/state/queries/list-members' +import {dedupeBy} from '#/state/queries/pagination' import {useSession} from '#/state/session' import {ErrorMessage} from '#/view/com/util/error/ErrorMessage' import {List, type ListRef} from '#/view/com/util/List' @@ -90,7 +91,7 @@ export function ListMembers({ hasNextPage, isFetchingNextPage, } = useListMembersQuery(list) - const isEmpty = !isFetching && !data?.pages[0].items.length + const isEmpty = !isFetching && !data?.pages.some(page => page.items.length) const isOwner = currentAccount && data?.pages[0].list.creator.did === currentAccount.did @@ -103,14 +104,15 @@ export function ListMembers({ if (isEmpty) { items.push(EMPTY_ITEM) } else if (data) { - for (const page of data.pages) { - items.push( - ...page.items.map(item => ({ - kind: 'list_item' as const, - listItem: item, - })), - ) - } + items.push( + ...dedupeBy( + data.pages.flatMap(page => page.items), + item => item.subject.did, + ).map(item => ({ + kind: 'list_item' as const, + listItem: item, + })), + ) } if (!isEmpty && isError) { items.push(LOAD_MORE_ERROR_ITEM) diff --git a/src/view/com/lists/ProfileLists.tsx b/src/view/com/lists/ProfileLists.tsx index c17579362..817f38123 100644 --- a/src/view/com/lists/ProfileLists.tsx +++ b/src/view/com/lists/ProfileLists.tsx @@ -79,7 +79,7 @@ export function ProfileLists({ error, refetch, } = useProfileListsQuery(did, opts) - const isEmpty = !isPending && !data?.pages[0]?.lists.length + const isEmpty = !isPending && !data?.pages.some(page => page.lists.length) const {data: preferences} = usePreferencesQuery() const navigation = useNavigation() const {currentAccount} = useSession() diff --git a/src/view/com/profile/ProfileFollows.tsx b/src/view/com/profile/ProfileFollows.tsx index b2c190867..b1e56b97b 100644 --- a/src/view/com/profile/ProfileFollows.tsx +++ b/src/view/com/profile/ProfileFollows.tsx @@ -8,6 +8,7 @@ import {useInitialNumToRender} from '#/lib/hooks/useInitialNumToRender' import {type NavigationProp} from '#/lib/routes/types' import {cleanError} from '#/lib/strings/errors' import {logger} from '#/logger' +import {dedupeBy} from '#/state/queries/pagination' import {useProfileFollowsQuery} from '#/state/queries/profile-follows' import {useResolveDidQuery} from '#/state/queries/resolve-uri' import {useSession} from '#/state/session' @@ -80,7 +81,10 @@ export function ProfileFollows({name}: {name: string}) { const follows = useMemo(() => { if (data?.pages) { - return data.pages.flatMap(page => page.follows) + return dedupeBy( + data.pages.flatMap(page => page.follows), + profile => profile.did, + ) } return [] }, [data]) diff --git a/src/view/screens/ModerationBlockedAccounts.tsx b/src/view/screens/ModerationBlockedAccounts.tsx index 258a3c9b5..1e5adb097 100644 --- a/src/view/screens/ModerationBlockedAccounts.tsx +++ b/src/view/screens/ModerationBlockedAccounts.tsx @@ -36,7 +36,7 @@ export function ModerationBlockedAccounts({}: Props) { fetchNextPage, isFetchingNextPage, } = useMyBlockedAccountsQuery() - const isEmpty = !isFetching && !data?.pages[0]?.blocks.length + const isEmpty = !isFetching && !data?.pages.some(page => page.blocks.length) const profiles = useMemo(() => { if (data?.pages) { return data.pages.flatMap(page => page.blocks) diff --git a/src/view/screens/ModerationMutedAccounts.tsx b/src/view/screens/ModerationMutedAccounts.tsx index 122464d30..160eaad1a 100644 --- a/src/view/screens/ModerationMutedAccounts.tsx +++ b/src/view/screens/ModerationMutedAccounts.tsx @@ -36,7 +36,7 @@ export function ModerationMutedAccounts({}: Props) { fetchNextPage, isFetchingNextPage, } = useMyMutedAccountsQuery() - const isEmpty = !isFetching && !data?.pages[0]?.mutes.length + const isEmpty = !isFetching && !data?.pages.some(page => page.mutes.length) const profiles = useMemo(() => { if (data?.pages) { return data.pages.flatMap(page => page.mutes) -- knotmirror 0.0.1