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

cursor-pagination.integration.test.ts

483 lines17.0 KB

1import { QueryClient } from '@tanstack/query-core'
2import {
3 BasicIndex,
4 createCollection,
5 createLiveQueryCollection,
6} from '@tanstack/db'
7import { describe, expect, it, vi } from 'vitest'
8import fc from 'fast-check'
9import { oraclePropertyOptions } from '../../db/tests/oracle-config.js'
10import { createDeferred } from '../../db/src/deferred.js'
11import { createLiveQueryWindowController } from '../../db/src/live-query-window-controller.js'
12import { createCursorPager, queryCollectionOptions } from '../src/index.js'
13import { createBackend } from './cursor-pagination/backend.js'
14import { expectedWindow } from './cursor-pagination/model.js'
15import type { Row, Scope } from './cursor-pagination/model.js'
16​
17/**
18 * # Does opaque pagination refine a real live-query window?
19 *
20 * This is the end-to-end path: QueryClient -> QueryCollection -> query graph ->
21 * shared window controller. The visible window and `hasNextPage` must match the
22 * independent full-relation model through growth, offset, ties, filtering,
23 * cancellation, replacement, and cache reuse.
24 *
25 * The fixture endpoint supports prefix and rank-equality tie requests. Other
26 * predicates reject rather than silently dropping IR. The fixture validates
27 * cursor expressions, then chooses the explicit offset for its local reader.
28 * Each tie filter has its own opaque backend sequence, just like the prefix.
29 */
30function createFixture(
31 rows: Array<Row>,
32 scope: Scope,
33 backendSize: number,
34 holdFirst = false,
35) {
36 const backend = { calls: [] as Array<string | undefined> }
37 const gate = createDeferred<void>()
38 let received = 0
39 const client = new QueryClient({
40 defaultOptions: {
41 queries: { retry: false, staleTime: Infinity, gcTime: Infinity },
42 },
43 })
44 const makePager = (rank?: number) => {
45 const makeBackend = () =>
46 createBackend(
47 rank === undefined ? rows : rows.filter((row) => row.rank === rank),
48 scope,
49 backendSize,
50 )
51 let transport = makeBackend()
52 return createCursorPager({
53 queryClient: client,
54 queryKey: [`cursor-experiment`, scope, `opaque-pages`, rank ?? null],
55 fetchPage: async (cursor, signal) => {
56 if (cursor === undefined) transport = makeBackend()
57 if (rank === undefined) backend.calls.push(cursor)
58 const page = await transport.fetchPage(cursor, signal)
59 if (++received === 1 && holdFirst) await gate.promise
60 return page
61 },
62 })
63 }
64 const pager = makePager()
65 const ties = new Map<number, ReturnType<typeof makePager>>()
66 const requests: Array<{ offset: number; limit: number | undefined }> = []
67 let cursorRequestCount = 0
68 const direction = scope.descending ? `desc` : `asc`
69 const source = createCollection(
70 queryCollectionOptions<Row>({
71 queryClient: client,
72 queryKey: [`cursor-experiment`, scope, `rows`],
73 syncMode: `on-demand`,
74 autoIndex: `eager`,
75 defaultIndexType: BasicIndex,
76 getKey: (row) => row.id,
77 queryFn: async (ctx) => {
78 const options = ctx.meta?.loadSubsetOptions
79 let reader = pager
80 const where = options?.where
81 if (where !== undefined) {
82 if (
83 where.type !== `func` ||
84 where.name !== `eq` ||
85 where.args.length !== 2 ||
86 where.args[0]?.type !== `ref` ||
87 where.args[0].path.length !== 1 ||
88 where.args[0].path[0] !== `rank` ||
89 where.args[1]?.type !== `val` ||
90 typeof where.args[1].value !== `number`
91 ) {
92 throw new Error(`Unsupported fixture predicate`)
93 }
94 const rank = where.args[1].value
95 let tie = ties.get(rank)
96 if (!tie) {
97 tie = makePager(rank)
98 ties.set(rank, tie)
99 }
100 reader = tie
101 }
102 if (options?.cursor) {
103 cursorRequestCount++
104 expect(options.cursor.whereCurrent).toMatchObject({
105 type: `func`,
106 name: `eq`,
107 args: [
108 { type: `ref`, path: [`rank`] },
109 { type: `val`, value: expect.any(Number) },
110 ],
111 })
112 expect(options.cursor.whereFrom).toMatchObject({
113 type: `func`,
114 name: scope.descending ? `lt` : `gt`,
115 args: [
116 { type: `ref`, path: [`rank`] },
117 { type: `val`, value: expect.any(Number) },
118 ],
119 })
120 }
121 if (options?.orderBy) {
122 expect(options.orderBy).toMatchObject([
123 { expression: { path: [`rank`] }, compareOptions: { direction } },
124 { expression: { path: [`id`] }, compareOptions: { direction } },
125 ])
126 }
127 const window = { offset: options?.offset ?? 0, limit: options?.limit }
128 requests.push(window)
129 return reader.read(window, ctx.signal)
130 },
131 }),
132 )
133 const live = createLiveQueryCollection((q) =>
134 q
135 .from({ row: source })
136 .orderBy(({ row }) => row.rank, direction)
137 .orderBy(({ row }) => row.id, direction)
138 .limit(1),
139 )
140 return {
141 backend,
142 gate,
143 requests,
144 cursorRequestCount: () => cursorRequestCount,
145 live,
146 source,
147 refresh: () =>
148 client.invalidateQueries(
149 { queryKey: [`cursor-experiment`, scope] },
150 { throwOnError: true },
151 ),
152 received: () => received,
153 async cleanup() {
154 gate.resolve()
155 await live.cleanup()
156 await source.cleanup()
157 client.clear()
158 },
159 }
161​
162const matrix = [0, 1, 9, 20].flatMap((count) =>
163 [2, 5].flatMap((backendSize) =>
164 [3, 7].flatMap((pageSize) =>
165 [false, true].map((descending) => ({
166 count,
167 backendSize,
168 pageSize,
169 descending,
170 })),
171 ),
172 ),
174​
175// This oracle checks all user row fields and their order. Virtual Collection
176// fields ($key/$origin/etc.) are outside the cursor adapter's responsibility.
177const observeRows = (rows: ReadonlyArray<Row>) =>
178 rows.map(({ id, rank, group }) => ({ id, rank, group }))
179​
180describe(`cursor adapter through production pagination`, () => {
181 it.each([
182 { wrapped: false, nested: false },
183 { wrapped: false, nested: true },
184 { wrapped: true, nested: false },
185 ])(
186 `manual writes preserve cache shapes: $wrapped/$nested`,
187 async ({ wrapped, nested }) => {
188 await fc.assert(
189 fc.asyncProperty(
190 fc.array(
191 fc.record({
192 kind: fc.constantFrom(`insert`, `update`, `delete`),
193 position: fc.nat({ max: 10 }),
194 }),
195 { minLength: 1, maxLength: 8 },
196 ),
197 fc.integer({ min: 2, max: 6 }),
198 async (operations, count) => {
199 const client = new QueryClient({
200 defaultOptions: {
201 queries: {
202 retry: false,
203 staleTime: Infinity,
204 gcTime: Infinity,
205 },
206 },
207 })
208 const rows = Array.from({ length: count }, (_, id) => ({
209 id,
210 rank: id,
211 group: 0,
212 }))
213 const pageKey = [`manual`, `pages`]
214 const rowKey = nested ? [`manual`] : [`manual`, `rows`]
215 const pager = createCursorPager({
216 queryClient: client,
217 queryKey: pageKey,
218 fetchPage: () => Promise.resolve({ rows, nextCursor: null }),
219 })
220 const common = {
221 queryClient: client,
222 queryKey: rowKey,
223 getKey: (row: Row) => row.id,
224 }
225 const source = createCollection(
226 wrapped
227 ? queryCollectionOptions({
228 ...common,
229 queryFn: async () => ({
230 items: await pager.read({}),
231 label: `keep`,
232 }),
233 select: (response) => response.items,
234 })
235 : queryCollectionOptions({
236 ...common,
237 queryFn: () => pager.read({}),
238 }),
239 )
240 try {
241 await source.preload()
242 // Raw row caches with no data must still be seeded by manual writes.
243 const emptyKey = [...rowKey, `unloaded`]
244 if (!wrapped)
245 client.getQueryCache().build(client, { queryKey: emptyKey })
246 const expected = rows.map((row) => ({ ...row }))
247 let nextId = count
248 for (const [step, operation] of operations.entries()) {
249 await client.invalidateQueries({
250 queryKey: pageKey,
251 exact: true,
252 refetchType: `none`,
253 })
254 const previous = client.getQueryState(pageKey)
255 const position =
256 operation.position % Math.max(1, expected.length)
257 if (operation.kind === `insert` || !expected.length) {
258 const row = { id: nextId, rank: nextId++, group: 0 }
259 source.utils.writeInsert({ ...row })
260 expected.push(row)
261 } else if (operation.kind === `update`) {
262 source.utils.writeUpdate({
263 id: expected[position]!.id,
264 group: step + 1,
265 })
266 expected[position]!.group = step + 1
267 } else {
268 source.utils.writeDelete(expected[position]!.id)
269 expected.splice(position, 1)
270 }
271 expect(observeRows([...source.values()])).toEqual(expected)
272 expect(client.getQueryData(rowKey)).toEqual(
273 wrapped ? { items: expected, label: `keep` } : expected,
274 )
275 if (!wrapped)
276 expect(client.getQueryData(emptyKey)).toEqual(expected)
277 // Preserving the object alone is insufficient: a no-op setQueryData
278 // also clears invalidation and marks an unrelated sequence fresh.
279 expect(
280 client.getQueryState(pageKey),
281 `manual writes must not touch page state`,
282 ).toBe(previous)
283 expect(await pager.read({})).toEqual(rows)
284 }
285 } finally {
286 await source.cleanup()
287 client.clear()
288 }
289 },
290 ),
291 oraclePropertyOptions(50, `cursor-pagination.manual-write`),
292 )
293 },
294 )
295 it.each(
296 [false, true].flatMap((descending) =>
297 [2, 5].map((backendSize) => ({ descending, backendSize })),
298 ),
299 )(
300 `refreshes changed backend rows before growing the window $descending/$backendSize`,
301 async ({ descending, backendSize }) => {
302 const rows = Array.from({ length: 3 }, (_, id) => ({
303 id,
304 rank: 0,
305 group: 0,
306 }))
307 const scope = { group: undefined, descending }
308 const fixture = createFixture(rows, scope, backendSize)
309 const controller = createLiveQueryWindowController(fixture.live, {
310 pageSize: 3,
311 })
312 const stop = controller.subscribe(() => {})
313 try {
314 await controller.preload()
315 expect(observeRows(controller.getSnapshot().data)).toEqual(
316 expectedWindow(rows, scope, 3).rows,
317 )
318 expect(controller.getSnapshot().hasNextPage).toBe(false)
319 for (const count of [9, 2, 0, 7]) {
320 const previous = observeRows(controller.getSnapshot().data)
321 const calls = fixture.backend.calls.length
322 rows.splice(
323 0,
324 rows.length,
325 ...Array.from({ length: count }, (_, id) => ({
326 id,
327 rank: Math.floor(id / 6),
328 group: count,
329 })),
330 )
331 // Refreshing only the outer row query still allows its fresh page
332 // cache. Prefix invalidation is the explicit two-cache refresh path.
333 await fixture.source.utils.refetch({ throwOnError: true })
334 expect(observeRows(controller.getSnapshot().data)).toEqual(previous)
335 expect(fixture.backend.calls).toHaveLength(calls)
336 await fixture.refresh()
337 const expected = expectedWindow(rows, scope, 3)
338 await vi.waitFor(() => {
339 expect(observeRows(controller.getSnapshot().data)).toEqual(
340 expected.rows,
341 )
342 expect(controller.getSnapshot().hasNextPage).toBe(
343 expected.hasNextPage,
344 )
345 })
346 }
347 await controller.fetchNextPage()
348 expect(observeRows(controller.getSnapshot().data)).toEqual(
349 expectedWindow(rows, scope, 6).rows,
350 )
351 expect(controller.getSnapshot().hasNextPage).toBe(true)
352 } finally {
353 stop()
354 controller.dispose()
355 await fixture.cleanup()
356 }
357 },
358 )
359​
360 it.each(matrix)(
361 `publishes exact pages and exhaustion $count/$backendSize/$pageSize/$descending`,
362 async ({ count, backendSize, pageSize, descending }) => {
363 const rows = Array.from({ length: count }, (_, id) => ({
364 id,
365 rank: Math.floor(id / 6),
366 group: id % 2,
367 }))
368 const scope = { group: undefined, descending }
369 const fixture = createFixture(rows, scope, backendSize)
370 const controller = createLiveQueryWindowController(fixture.live, {
371 pageSize,
372 })
373 const publications: Array<{
374 rows: Array<Row>
375 pages: number
376 more: boolean
377 ready: boolean
378 }> = []
379 const unsubscribe = controller.subscribe(() => {
380 const snapshot = controller.getSnapshot()
381 publications.push({
382 rows: observeRows(snapshot.data),
383 pages: snapshot.pageParams.length,
384 more: snapshot.hasNextPage,
385 ready: snapshot.isReady,
386 })
387 })
388 try {
389 await controller.preload()
390 for (let page = 1; page <= Math.ceil(count / pageSize) + 1; page++) {
391 const expected = expectedWindow(rows, scope, page * pageSize)
392 const snapshot = controller.getSnapshot()
393 expect(observeRows(snapshot.data)).toEqual(expected.rows)
394 expect(snapshot.hasNextPage).toBe(expected.hasNextPage)
395 expect(observeRows(snapshot.pages.flat())).toEqual(expected.rows)
396 if (!expected.hasNextPage) break
397 await controller.fetchNextPage()
398 }
399 expect(publications.length).toBeGreaterThan(0)
400 expect(publications.some((published) => published.ready)).toBe(true)
401 for (const published of publications) {
402 if (published.ready) {
403 const expected = expectedWindow(
404 rows,
405 scope,
406 published.pages * pageSize,
407 )
408 expect(published.rows).toEqual(expected.rows)
409 expect(published.more).toBe(expected.hasNextPage)
410 }
411 }
412 expect(fixture.requests.length).toBeGreaterThan(0)
413 expect(fixture.requests[0]?.limit).toBe(pageSize + 1)
414 if (count > pageSize) {
415 expect(fixture.cursorRequestCount()).toBeGreaterThan(0)
416 }
417 expect(fixture.backend.calls).toHaveLength(
418 Math.max(1, Math.ceil(count / backendSize)),
419 )
420 } finally {
421 unsubscribe()
422 controller.dispose()
423 await fixture.cleanup()
424 }
425 },
426 )
427​
428 it(`holds real response delivery and preserves a shallower peer after deep exhaustion`, async () => {
429 const rows = Array.from({ length: 9 }, (_, id) => ({
430 id,
431 rank: Math.floor(id / 6),
432 group: 0,
433 }))
434 const scope = { group: undefined, descending: false }
435 const fixture = createFixture(rows, scope, 2, true)
436 const shallow = createLiveQueryWindowController(fixture.live, {
437 pageSize: 3,
438 })
439 const deep = createLiveQueryWindowController(fixture.live, { pageSize: 10 })
440 const publications: Array<Array<number>> = []
441 const stopShallow = shallow.subscribe(() =>
442 publications.push(shallow.getSnapshot().data.map((row) => row.id)),
443 )
444 const stopDeep = deep.subscribe(() => {})
445 let settled = 0
446 const pending = Promise.allSettled(
447 [shallow.preload(), deep.preload()].map((promise) =>
448 promise.then(() => {
449 settled++
450 }),
451 ),
452 )
453 try {
454 await vi.waitFor(() => expect(fixture.received()).toBe(1))
455 expect(settled).toBe(0)
456 expect(shallow.getSnapshot().data).toEqual([])
457 expect(publications.every((batch) => batch.length === 0)).toBe(true)
458 fixture.gate.resolve()
459 expect((await pending).map((result) => result.status)).toEqual([
460 `fulfilled`,
461 `fulfilled`,
462 ])
463 expect(shallow.getSnapshot().hasNextPage).toBe(true)
464 expect(deep.getSnapshot().hasNextPage).toBe(false)
465 stopDeep()
466 deep.dispose()
467 await shallow.preload()
468 expect(observeRows(shallow.getSnapshot().data)).toEqual(rows.slice(0, 3))
469 expect(shallow.getSnapshot().hasNextPage).toBe(true)
470 await shallow.fetchNextPage()
471 expect(observeRows(shallow.getSnapshot().data)).toEqual(rows.slice(0, 6))
472 expect(fixture.backend.calls).toHaveLength(5)
473 } finally {
474 fixture.gate.resolve()
475 await pending
476 stopShallow()
477 stopDeep()
478 shallow.dispose()
479 deep.dispose()
480 await fixture.cleanup()
481 }
482 })
483})