Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

cursor-pagination.ts

241 lines8.5 KB

1import { InfiniteQueryObserver, isCancelledError } from '@tanstack/query-core'
2import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/query-core'
3​
4/** One backend page. Only null means the ordered result is exhausted. */
5export interface CursorPage<T> {
6 rows: ReadonlyArray<T>
7 nextCursor: string | null
8}
9​
10export interface CursorPagerOptions<T> {
11 queryClient: QueryClient
12 /** Dedicated infinite-query key: include the source, filters and order, not the window. */
13 queryKey: QueryKey
14 fetchPage: (
15 cursor: string | undefined,
16 signal: AbortSignal,
17 ) => Promise<CursorPage<T>>
18 /** Query's freshness interval. Defaults to the QueryClient's setting. */
19 staleTime?: number
20 /** Query's inactive cache lifetime. Defaults to the QueryClient's setting. */
21 gcTime?: number
23​
24export interface CursorPager<T> {
25 read: (
26 window: { offset?: number; limit?: number },
27 signal?: AbortSignal,
28 ) => Promise<Array<T>>
29 /** Remove this key's cached pages and invalidate this pager's queued reads. */
30 reset: () => void
32​
33/**
34 * Fulfill offset/limit windows using opaque backend cursors. Query owns the
35 * pages, freshness, invalidation and garbage collection. Use one dedicated key
36 * per filtered, totally ordered source. Loading more reuses fresh pages; refreshing
37 * stale data rebuilds the loaded sequence from its first page.
38 *
39 * The key must not also be used for ordinary QueryCollection row arrays.
40 * Use sibling row/page prefixes under one resource prefix, not pages beneath
41 * the row prefix (manual writes update that whole prefix). For a forced refresh,
42 * cancel the resource prefix before invalidating it. A positive staleTime avoids
43 * refreshing on every read.
44 *
45 * Reads on one pager serialize; separate pagers share Query's cache and fetches.
46 * Aborting a reader discards its answer, not shared cached
47 * pages. Cancel the query through QueryClient to cancel its transport. Neither
48 * cancellation nor a TTL can repair a backend's inconsistent cursor sequence.
49 */
50export function createCursorPager<T>({
51 queryClient,
52 queryKey,
53 fetchPage,
54 staleTime,
55 gcTime,
56}: CursorPagerOptions<T>): CursorPager<T> {
57 let cursorSequenceGeneration = 0
58 let tail = Promise.resolve()
59 const sequences = new WeakMap<AbortSignal, Set<string | undefined>>()
60 type Pages = InfiniteData<CursorPage<T>, string | undefined>
61 const nextCursor = (page: CursorPage<T>) => {
62 if (
63 !Array.isArray(page.rows) ||
64 (page.nextCursor !== null && typeof page.nextCursor !== `string`)
65 )
66 throw new TypeError(
67 `Invalid cursor page: expected rows and a string or null nextCursor`,
68 )
69 return page.nextCursor
70 }
71 const options = {
72 queryKey,
73 // Offsets address the complete sequence, never a selected or evicted prefix.
74 maxPages: 0,
75 select: undefined,
76 enabled: true,
77 ...(staleTime === undefined ? {} : { staleTime }),
78 ...(gcTime === undefined ? {} : { gcTime }),
79 initialPageParam: undefined as string | undefined,
80 queryFn: async ({
81 pageParam,
82 signal,
83 }: {
84 pageParam: string | undefined
85 signal: AbortSignal
86 }) => {
87 let params = sequences.get(signal)
88 if (pageParam === undefined || !params) {
89 // Refresh starts a new sequence; growth extends the validated cache.
90 // Query gives every page/retry in an acquisition the same signal.
91 params = new Set(
92 pageParam === undefined
93 ? []
94 : queryClient.getQueryData<
95 InfiniteData<CursorPage<T>, string | undefined>
96 >(queryKey)?.pageParams,
97 )
98 sequences.set(signal, params)
99 }
100 params.add(pageParam)
101 const page = await fetchPage(pageParam, signal)
102 // Validate even the final response, before Query publishes success or
103 // resolves shared waiters. getNextPageParam runs too late for that.
104 const next = nextCursor(page)
105 if (next !== null && params.has(next)) {
106 throw new Error(`Backend repeated a continuation cursor`)
107 }
108 return page
109 },
110 getNextPageParam: nextCursor,
111 }
112​
113 const abortError = () =>
114 new DOMException(`Cursor acquisition was canceled`, `AbortError`)
115 const abortable = <TResult>(
116 request: Promise<TResult>,
117 signal?: AbortSignal,
118 ) => {
119 if (!signal) return request
120 return new Promise<TResult>((resolve, reject) => {
121 const abort = () => reject(signal.reason ?? abortError())
122 const cleanup = () => signal.removeEventListener(`abort`, abort)
123 request.then(
124 (value) => {
125 cleanup()
126 resolve(value)
127 },
128 (error) => {
129 cleanup()
130 reject(error)
131 },
132 )
133 if (signal.aborted) abort()
134 else signal.addEventListener(`abort`, abort, { once: true })
135 })
136 }
137​
138 return {
139 read({ offset = 0, limit }, signal) {
140 const requestedCursorSequenceGeneration = cursorSequenceGeneration
141 const checkCurrent = () => {
142 if (signal?.aborted) throw signal.reason ?? abortError()
143 if (requestedCursorSequenceGeneration !== cursorSequenceGeneration) {
144 throw new DOMException(`Cursor sequence was reset`, `AbortError`)
145 }
146 }
147 const run = async () => {
148 checkCurrent()
149 const end = limit === undefined ? Infinity : offset + limit
150 if (
151 !Number.isSafeInteger(offset) ||
152 offset < 0 ||
153 (limit !== undefined &&
154 (!Number.isSafeInteger(limit) ||
155 limit < 0 ||
156 !Number.isSafeInteger(end)))
157 )
158 throw new RangeError(`Expected a nonnegative finite integer window`)
159 if (limit === 0) return []
160 try {
161 const defaults = queryClient.defaultQueryOptions(options)
162 // Match imperative fetchQuery defaults in browsers as well as Node.
163 defaults.retry ??= false
164 const observer = new InfiniteQueryObserver<
165 CursorPage<T>,
166 Error,
167 Pages,
168 QueryKey,
169 string | undefined
170 >(queryClient, { ...options, retry: defaults.retry })
171 const query = observer.getCurrentQuery()
172 const acquire = async (next: boolean): Promise<Pages> => {
173 let request = (
174 next
175 ? observer.fetchNextPage({
176 throwOnError: true,
177 cancelRefetch: false,
178 })
179 : observer.refetch({ throwOnError: true, cancelRefetch: false })
180 ).then((result) => result.data!)
181 let acquisition = query.promise!
182 for (;;) {
183 try {
184 const [data] = await Promise.all([request, acquisition])
185 return data
186 } catch (error) {
187 if (!isCancelledError(error)) throw error
188 if (!error.silent || query.promise === acquisition)
189 throw abortError()
190 // A cancelling refetch supersedes the old transport. Follow
191 // its replacement, but never leak Query's control error into
192 // an enclosing row query as though that query was canceled.
193 acquisition = query.promise!
194 request = acquisition
195 }
196 }
197 }
198 const current = observer.getCurrentResult()
199 let data =
200 current.data && !current.isStale
201 ? current.data
202 : await acquire(false)
203 checkCurrent()
204 if (!data.pages.length)
205 throw new TypeError(`Invalid cursor page: empty cached sequence`)
206 while (
207 data.pages.reduce((count, page) => count + page.rows.length, 0) <
208 end &&
209 data.pages[data.pages.length - 1]?.nextCursor !== null
210 ) {
211 data = await acquire(true)
212 checkCurrent()
213 }
214 const rows: Array<T> = []
215 let start = 0
216 for (const page of data.pages) {
217 if (start >= end) break
218 const stop = Math.min(page.rows.length, end - start)
219 for (let index = Math.max(0, offset - start); index < stop; index++)
220 rows.push(page.rows[index]!)
221 start += page.rows.length
222 }
223 return rows
224 } catch (error) {
225 checkCurrent()
226 throw error
227 }
228 }
229 const result = tail.then(() => abortable(run(), signal))
230 tail = result.then(
231 () => {},
232 () => {},
233 )
234 return abortable(result, signal)
235 },
236 reset() {
237 cursorSequenceGeneration++
238 queryClient.removeQueries({ queryKey, exact: true })
239 },
240 }