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

cursor-pagination.boundary.test.ts

177 lines5.6 KB

1// @vitest-environment jsdom
2// Ordinary tests for cursor Query fetch boundaries: a fresh hit beside a same-turn
3// cancellation, retry policy, AbortSignal compatibility, invalid continuations,
4// and hash work. The cursor boundary law (nested cancellation and reader abort)
5// is owned by cursor-pagination.boundary-oracle.test.ts.
6import { QueryClient, hashKey } from '@tanstack/query-core'
7import { describe, expect, it, vi } from 'vitest'
8import { createDeferred } from '../../db/src/deferred.js'
9import { createCursorPager } from '../src/index.js'
10import { makeClient, rowsFor } from './cursor-pagination-boundary-support.js'
11​
12describe(`cursor Query fetch boundaries`, () => {
13 it(`a fresh hit does not inherit another Query fetch's same-turn cancellation`, async () => {
14 const client = makeClient(),
15 entered = createDeferred<void>(),
16 release = createDeferred<void>()
17 const key = [`hit`],
18 rows = rowsFor(1)
19 const options = {
20 queryClient: client,
21 queryKey: key,
22 fetchPage: async (cursor: string | undefined) => {
23 if (cursor) {
24 entered.resolve()
25 await release.promise
26 }
27 return {
28 rows: [rows[cursor ? 1 : 0]!],
29 nextCursor: cursor ? null : `next`,
30 }
31 },
32 }
33 await createCursorPager(options).read({ limit: 1 })
34 const pending = createCursorPager(options)
35 .read({})
36 .catch(() => {})
37 try {
38 await entered.promise
39 const hit = createCursorPager(options).read({ limit: 1 })
40 void client.cancelQueries(
41 { queryKey: key, exact: true },
42 { revert: false },
43 )
44 expect(await hit).toEqual(rows.slice(0, 1))
45 } finally {
46 release.resolve()
47 await pending
48 client.clear()
49 }
50 })
51​
52 it.each([undefined, false, 1] as const)(
53 `browser retry policy is the same across Query fetch phases: %s`,
54 async (retry) => {
55 for (const phase of [`initial`, `growth`] as const) {
56 const client = new QueryClient({
57 defaultOptions: {
58 queries: { gcTime: Infinity, staleTime: Infinity, retryDelay: 0 },
59 },
60 })
61 if (retry !== undefined) client.setQueryDefaults([`retry`], { retry })
62 let calls = 0
63 const error = new Error(`page failed`)
64 const pager = createCursorPager({
65 queryClient: client,
66 queryKey: [`retry`],
67 fetchPage: (cursor) => {
68 if (phase === `initial` || cursor !== undefined) {
69 calls++
70 return Promise.reject(error)
71 }
72 return Promise.resolve({ rows: [{ id: 0 }], nextCursor: `next` })
73 },
74 })
75 try {
76 await expect(pager.read({})).rejects.toBe(error)
77 expect(calls).toBe(retry === 1 ? 2 : 1)
78 } finally {
79 client.clear()
80 }
81 }
82 },
83 )
84​
85 it(`supports an AbortSignal without throwIfAborted`, async () => {
86 const client = makeClient(),
87 abort = new AbortController(),
88 rows = rowsFor(1)
89 Object.defineProperty(abort.signal, `throwIfAborted`, { value: undefined })
90 const pager = createCursorPager({
91 queryClient: client,
92 queryKey: [`compat`],
93 fetchPage: () => Promise.resolve({ rows, nextCursor: null }),
94 })
95 try {
96 expect(await pager.read({}, abort.signal)).toEqual(rows)
97 abort.abort()
98 await expect(pager.read({}, abort.signal)).rejects.toMatchObject({
99 name: `AbortError`,
100 })
101 } finally {
102 client.clear()
103 }
104 })
105​
106 it.each([`response`, `cache`] as const)(
107 `invalid continuation rejects without spinning from %s`,
108 async (origin) => {
109 const client = makeClient(),
110 key = [`invalid`]
111 const invalid = { rows: rowsFor(1), nextCursor: undefined }
112 const pager = createCursorPager({
113 queryClient: client,
114 queryKey: key,
115 fetchPage: () =>
116 Promise.resolve(
117 invalid as unknown as {
118 rows: Array<{ id: number }>
119 nextCursor: null
120 },
121 ),
122 })
123 if (origin === `cache`)
124 client.setQueryData(key, { pages: [invalid], pageParams: [undefined] })
125 // A semantic work budget turns a microtask loop into a finite RED witness.
126 let attempts = 0
127 if (origin === `cache`) {
128 const query = client
129 .getQueryCache()
130 .find({ queryKey: key, exact: true })!
131 const run = query.fetch.bind(query)
132 vi.spyOn(query, `fetch`).mockImplementation((...input) => {
133 if (++attempts > 3) throw new Error(`loop budget exceeded`)
134 return run(...input)
135 })
136 }
137 try {
138 await expect(pager.read({ limit: 10 })).rejects.toThrow(
139 `Invalid cursor page`,
140 )
141 expect(attempts).toBeLessThanOrEqual(1)
142 } finally {
143 vi.restoreAllMocks()
144 client.clear()
145 }
146 },
147 )
148​
149 it(`fresh reads do not hash unrelated cached queries`, async () => {
150 const client = makeClient()
151 let hashes = 0
152 client.setDefaultOptions({
153 queries: {
154 ...client.getDefaultOptions().queries,
155 queryKeyHashFn: (key) => {
156 hashes++
157 return hashKey(key)
158 },
159 },
160 })
161 for (let index = 0; index < 100; index++)
162 client.setQueryData([`unrelated`, index], index)
163 const pager = createCursorPager({
164 queryClient: client,
165 queryKey: [`work`],
166 fetchPage: () => Promise.resolve({ rows: rowsFor(1), nextCursor: null }),
167 })
168 try {
169 await pager.read({})
170 hashes = 0
171 await pager.read({ limit: 1 })
172 expect(hashes).toBeLessThan(10)
173 } finally {
174 client.clear()
175 }
176 })
177})