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

pagination.ts

332 lines10.5 KB

1import { paginationDemand } from './pagination-demand'
2import { subscribeQuery } from './subscription'
3import type { LoadSubsetOptions } from '@tanstack/db'
4import type { ConvexQueryOrder } from './paginated-options'
5import type { ConvexCollectionClient, ConvexSubscription } from './subscription'
6import type {
7 FunctionArgs,
8 FunctionReference,
9 PaginationResult,
10} from 'convex/server'
11​
12type Page<T> = {
13 cursor: string | null
14 endCursor?: string
15 subscription?: ConvexSubscription<PaginationResult<T>>
17​
18/**
19 * Each bounded subscription owns (cursor, endCursor]. A changing page cannot
20 * move its neighbour's boundary. Unbounded tails are sealed before continuing;
21 * split hints replace a range with its two disjoint halves. Only a complete
22 * chain can replace the Collection's authoritative snapshot: eager mode needs
23 * exhaustion; on-demand mode needs every active scope and its complete tie.
24 */
25export function subscribePages<TQuery extends FunctionReference<`query`>, TRow>(
26 client: ConvexCollectionClient,
27 query: TQuery,
28 args: Omit<FunctionArgs<TQuery>, `paginationOpts`>,
29 pageSize: number,
30 maxRows: number,
31 receive: (rows: ReadonlyArray<TRow>) => void,
32 fail: (error: unknown) => void,
33 queryOrder?: ConvexQueryOrder<TRow>,
34): ConvexSubscription<ReadonlyArray<TRow>> {
35 if (!Number.isSafeInteger(pageSize) || pageSize <= 0) {
36 throw new RangeError(`Convex pageSize must be a positive safe integer.`)
37 }
38 if (!Number.isSafeInteger(maxRows) || maxRows <= 0) {
39 throw new RangeError(`Convex maxRows must be a positive safe integer.`)
40 }
41 let active = true
42 let scheduled = false
43 let flushing = false
44 let result: ReadonlyArray<TRow> | undefined
45 let error: unknown
46 const waiters = new Set<{
47 resolve: () => void
48 reject: (reason: unknown) => void
49 }>()
50 const demands = new Map<
51 LoadSubsetOptions,
52 {
53 complete: ReturnType<typeof paginationDemand<TRow>>
54 promise: Promise<void>
55 resolve: () => void
56 reject: (reason: unknown) => void
57 cancel: () => void
58 pending: boolean
59 }
60 >()
61 let publishedPages = new Set<Page<TRow>>()
62 const pages: Array<Page<TRow>> = []
63 const boundaries = new Set<string>()
64 const reject = (reason: unknown): void => {
65 if (!active) return
66 error = reason
67 result = undefined
68 for (const demand of demands.values())
69 if (demand.pending) {
70 demand.pending = false
71 demand.reject(reason)
72 }
73 for (const waiter of waiters) waiter.reject(reason)
74 waiters.clear()
75 fail(reason)
76 }
77 const schedule = (): void => {
78 if (!active || scheduled) return
79 scheduled = true
80 queueMicrotask(() => {
81 scheduled = false
82 flush()
83 })
84 }
85 const createPage = (
86 cursor: string | null,
87 endCursor?: string,
88 ): Page<TRow> => {
89 const page: Page<TRow> = { cursor, endCursor }
90 const paginationOpts = {
91 cursor,
92 numItems: pageSize,
93 ...(endCursor === undefined ? {} : { endCursor }),
94 }
95 page.subscription = subscribeQuery(
96 client,
97 query,
98 { ...args, paginationOpts } as FunctionArgs<TQuery>,
99 () => {
100 // Pending tail acquisition leaves prior applied shallow coverage usable.
101 // An update to a published range invalidates that cache until a new
102 // coherent prefix establishes every still-active served scope.
103 if (publishedPages.has(page)) result = undefined
104 schedule()
105 },
106 reject,
107 ) as ConvexSubscription<PaginationResult<TRow>>
108 return page
109 }
110 const replace = (
111 index: number,
112 page: Page<TRow>,
113 boundary: string,
114 continueTail = true,
115 endCursor = page.endCursor,
116 ): void => {
117 if (
118 boundary === page.cursor ||
119 boundary === page.endCursor ||
120 boundaries.has(boundary)
121 ) {
122 throw new Error(
123 `Convex pagination returned a boundary that makes no progress.`,
124 )
125 }
126 const left = createPage(page.cursor, boundary)
127 let right: Page<TRow> | undefined
128 try {
129 if (continueTail) right = createPage(boundary, endCursor)
130 } catch (cause) {
131 left.subscription?.unsubscribe()
132 throw cause
133 }
134 boundaries.add(boundary)
135 pages.splice(index, 1, left, ...(right ? [right] : []))
136 page.subscription?.unsubscribe()
137 schedule()
138 }
139 function flush(): void {
140 if (!active || flushing || (queryOrder && demands.size === 0)) return
141 flushing = true
142 try {
143 const completePages: Array<Array<TRow>> = []
144 let rowCount = 0
145 for (let index = 0; index < pages.length; index++) {
146 const page = pages[index]!
147 const value = page.subscription!.getCurrentValue()
148 if (value === undefined) return
149 if (
150 !Array.isArray(value.page) ||
151 typeof value.isDone !== `boolean` ||
152 typeof value.continueCursor !== `string`
153 ) {
154 throw new TypeError(
155 `Convex paginated queries must return PaginationResult.`,
156 )
157 }
158 rowCount += value.page.length
159 if (rowCount > maxRows) {
160 throw new RangeError(
161 `Convex eager mirror exceeds maxRows (${maxRows}).`,
162 )
163 }
164 const split =
165 value.pageStatus === `SplitRequired` ||
166 value.pageStatus === `SplitRecommended`
167 if (split) {
168 if (!value.splitCursor)
169 throw new Error(
170 `Convex requested a page split without a splitCursor.`,
171 )
172 // Convex defines split children inside (cursor, continueCursor].
173 // An unbounded right child would also start an unrelated successor.
174 replace(
175 index,
176 page,
177 value.splitCursor,
178 true,
179 page.endCursor ?? value.continueCursor,
180 )
181 return
182 }
183 completePages.push(value.page)
184 if (page.endCursor === undefined && !value.isDone) {
185 const needTail =
186 !queryOrder ||
187 [...demands.values()].some(
188 (demand) => !demand.complete(completePages.flat(), false),
189 )
190 // Sealing keeps the returned range stable without speculatively
191 // opening its unrelated successor. Future growth resumes from here.
192 replace(index, page, value.continueCursor, needTail)
193 return
194 }
195 }
196 // Acquisition can add many ranges. Materialize rows only once every
197 // range is available, rather than copying each incomplete prefix.
198 const rows = completePages.flat()
199 const tail = pages.at(-1)
200 const exhausted =
201 tail?.endCursor === undefined &&
202 tail?.subscription?.getCurrentValue()?.isDone === true
203 if (
204 queryOrder
205 ? [...demands.values()].some(
206 (demand) => !demand.complete(rows, exhausted),
207 )
208 : !exhausted
209 ) {
210 if (tail?.endCursor !== undefined) {
211 pages.push(createPage(tail.endCursor))
212 schedule()
213 }
214 return
215 }
216 error = undefined
217 result = rows
218 publishedPages = new Set(pages)
219 receive(rows)
220 for (const demand of demands.values())
221 if (demand.pending) {
222 demand.pending = false
223 demand.resolve()
224 }
225 for (const waiter of waiters) waiter.resolve()
226 waiters.clear()
227 } catch (cause) {
228 reject(cause)
229 } finally {
230 flushing = false
231 }
232 }
233 try {
234 if (!queryOrder) pages.push(createPage(null))
235 schedule()
236 } catch (cause) {
237 for (const page of pages) page.subscription?.unsubscribe()
238 throw cause
239 }
240 const abortError = (): Error =>
241 Object.assign(new Error(`Convex subset was canceled.`), {
242 name: `AbortError`,
243 })
244 return {
245 ...(queryOrder
246 ? {
247 loadSubset: (request: LoadSubsetOptions): true | Promise<void> => {
248 if (!active || request.signal?.aborted)
249 return Promise.reject(abortError())
250 const existing = demands.get(request)
251 if (existing?.pending) return existing.promise
252 existing?.cancel()
253 const complete = paginationDemand(request, queryOrder)
254 let resolve!: () => void
255 let rejectWaiter!: (error: unknown) => void
256 const pending = new Promise<void>((yes, no) => {
257 resolve = yes
258 rejectWaiter = no
259 })
260 const cancel = (): void => {
261 const demand = demands.get(request)
262 if (!demand) return
263 request.signal?.removeEventListener(`abort`, cancel)
264 demands.delete(request)
265 if (demand.pending) {
266 demand.pending = false
267 demand.reject(abortError())
268 }
269 }
270 const demand = {
271 complete,
272 promise: pending,
273 resolve,
274 reject: rejectWaiter,
275 cancel,
276 pending: true,
277 }
278 demands.set(request, demand)
279 request.signal?.addEventListener(`abort`, cancel, { once: true })
280 if (complete([], false)) {
281 demand.pending = false
282 resolve()
283 return pending
284 }
285 if (request.refetch) result = undefined
286 flush()
287 if (
288 result !== undefined &&
289 complete(
290 result,
291 pages.at(-1)?.endCursor === undefined &&
292 pages.at(-1)?.subscription?.getCurrentValue()?.isDone ===
293 true,
294 )
295 ) {
296 demand.pending = false
297 resolve()
298 return pending
299 }
300 if (!pages.length) pages.push(createPage(null))
301 schedule()
302 return pending
303 },
304 unloadSubset: (request: LoadSubsetOptions): void => {
305 demands.get(request)?.cancel()
306 },
307 }
308 : {}),
309 getCurrentValue: () => {
310 flush()
311 return result
312 },
313 waitForCurrent: () => {
314 flush()
315 if (error !== undefined) return Promise.reject(error)
316 if (result !== undefined || (queryOrder && demands.size === 0))
317 return Promise.resolve()
318 return new Promise<void>((resolve, rejectWaiter) => {
319 waiters.add({ resolve, reject: rejectWaiter })
320 })
321 },
322 unsubscribe: () => {
323 active = false
324 for (const demand of [...demands.values()]) demand.cancel()
325 for (const page of pages) page.subscription?.unsubscribe()
326 const cause = new Error(`Convex pagination was cleaned up.`)
327 cause.name = `AbortError`
328 for (const waiter of waiters) waiter.reject(cause)
329 waiters.clear()
330 },
331 }