Open History to see the last commit
1import { QueryClient } from '@tanstack/query-core'
2import { BTreeIndex, createCollection } from '@tanstack/db'
3import { queryCollectionOptions } from '../src/index'
4import { evaluateReferenceExpression } from '../../db/tests/reference-expression'
5import { Func, PropRef, Value } from '../../db/src/query/ir'
6import type { LoadSubsetOptions } from '@tanstack/db'
7import type { BasicExpression } from '../../db/src/query/ir'
8
9export { QueryClient }
10
11export type ServerRow = { id: number; rank: number }
12type Field = keyof ServerRow
13
14function invalid(): never {
15 throw new Error(`Unsupported server pagination request`)
16}
17
18function record(value: unknown, keys: ReadonlyArray<string>) {
19 if (typeof value !== `object` || value === null || Array.isArray(value))
20 return invalid()
21 const copy: Record<string, unknown> = {}
22 for (const key of Reflect.ownKeys(value)) {
23 if (typeof key !== `string` || !keys.includes(key)) return invalid()
24 const descriptor = Object.getOwnPropertyDescriptor(value, key)!
25 if (!(`value` in descriptor)) return invalid()
26 copy[key] = descriptor.value
27 }
28 return copy
29}
30
31function list(value: unknown): Array<unknown> {
32 if (!Array.isArray(value)) return invalid()
33 if (Reflect.ownKeys(value).length !== value.length + 1) return invalid()
34 for (let index = 0; index < value.length; index++) {
35 const descriptor = Object.getOwnPropertyDescriptor(value, index)
36 if (!descriptor || !(`value` in descriptor)) return invalid()
37 }
38 return value
39}
40
41function numeric(value: unknown): value is number {
42 return typeof value === `number` && Number.isFinite(value)
43}
44
45// A finite non-null numeric grammar, not general SQL/string semantics.
46// Validate every branch before evaluation, including predicates over no rows.
47function expression(
48 input: unknown,
49 kind: `number` | `numbers` | `boolean`,
50): BasicExpression {
51 const node = record(input, [`type`, `path`, `value`, `name`, `args`])
52 if (node.type === `val`) {
53 record(input, [`type`, `value`])
54 if (kind === `numbers`) {
55 const values = list(node.value)
56 if (!values.every(numeric)) return invalid()
57 return new Value([...values])
58 }
59 if (
60 kind === `number` ? numeric(node.value) : typeof node.value === `boolean`
61 )
62 return new Value(node.value)
63 return invalid()
64 }
65 if (node.type === `ref` && kind === `number`) {
66 record(input, [`type`, `path`])
67 const path = list(node.path)
68 if (path.length !== 1 || (path[0] !== `id` && path[0] !== `rank`))
69 return invalid()
70 return new PropRef([path[0]])
71 }
72 if (node.type !== `func` || kind !== `boolean`) return invalid()
73 record(input, [`type`, `name`, `args`])
74 const args = list(node.args)
75 if (node.name === `and` || node.name === `or`) {
76 if (!args.length) return invalid()
77 return new Func(
78 node.name,
79 args.map((arg) => expression(arg, `boolean`)),
80 )
81 }
82 if (node.name === `not` && args.length === 1)
83 return new Func(`not`, [expression(args[0], `boolean`)])
84 if (
85 typeof node.name !== `string` ||
86 ![`eq`, `gt`, `gte`, `lt`, `lte`, `in`].includes(node.name) ||
87 args.length !== 2
88 )
89 return invalid()
90 return new Func(node.name, [
91 expression(args[0], `number`),
92 expression(args[1], node.name === `in` ? `numbers` : `number`),
93 ])
94}
95
96function freezeStatic<T>(value: T): T {
97 if (value !== null && typeof value === `object`) {
98 for (const child of Object.values(value)) freezeStatic(child)
99 Object.freeze(value)
100 }
101 return value
102}
103
104function captureSubset(
105 input: LoadSubsetOptions | undefined,
106 intendedOrder: ReadonlyArray<Field>,
107): LoadSubsetOptions | undefined {
108 if (input === undefined) return undefined
109 const raw = record(input, [
110 `where`,
111 `orderBy`,
112 `limit`,
113 `offset`,
114 `cursor`,
115 `signal`,
116 `subscription`,
117 ])
118 for (const value of [raw.limit, raw.offset]) {
119 if (
120 value !== undefined &&
121 (!numeric(value) || !Number.isInteger(value) || value < 0)
122 )
123 return invalid()
124 }
125 const where =
126 raw.where === undefined ? undefined : expression(raw.where, `boolean`)
127 const orderBy =
128 raw.orderBy === undefined
129 ? undefined
130 : list(raw.orderBy).map((value, index) => {
131 const clause = record(value, [`expression`, `compareOptions`])
132 const ref = expression(clause.expression, `number`)
133 if (ref.type !== `ref` || ref.path[0] !== intendedOrder[index])
134 return invalid()
135 const compare = record(clause.compareOptions, [
136 `direction`,
137 `nulls`,
138 `stringSort`,
139 `locale`,
140 `localeOptions`,
141 ])
142 if (
143 compare.direction !== `asc` ||
144 (compare.nulls !== `first` && compare.nulls !== `last`) ||
145 (compare.stringSort !== undefined &&
146 compare.stringSort !== `lexical` &&
147 compare.stringSort !== `locale`) ||
148 compare.locale !== undefined ||
149 compare.localeOptions !== undefined
150 )
151 return invalid()
152 // String collation payloads are outside this numeric fixture. Both null
153 // placements and default/lexical/locale modes are harmless for finite numbers.
154 return {
155 expression: ref,
156 compareOptions: { ...compare },
157 } as NonNullable<LoadSubsetOptions[`orderBy`]>[number]
158 })
159 if (orderBy?.length === 0) return invalid()
160 if ((raw.limit !== undefined || (raw.offset ?? 0) !== 0) && !orderBy?.length)
161 return invalid()
162 let cursor: LoadSubsetOptions[`cursor`]
163 if (raw.cursor !== undefined) {
164 const value = record(raw.cursor, [`whereFrom`, `whereCurrent`, `lastKey`])
165 if (value.lastKey !== undefined && !numeric(value.lastKey)) return invalid()
166 cursor = {
167 whereFrom: expression(value.whereFrom, `boolean`),
168 whereCurrent: expression(value.whereCurrent, `boolean`),
169 lastKey: value.lastKey,
170 }
171 }
172 const snapshot = freezeStatic({
173 where,
174 orderBy,
175 cursor,
176 limit: raw.limit as number | undefined,
177 offset: raw.offset as number | undefined,
178 })
179 // Detach/freeze static meaning only. Cancellation and subscription lifecycle
180 // stay live, and their identities must not be cloned or frozen.
181 return Object.freeze({
182 ...snapshot,
183 signal: input.signal,
184 subscription: input.subscription,
185 })
186}
187
188// An ordinary QueryObserver, not InfiniteQueryObserver. This fixture models
189// numeric rows supplied in the query's requested order; it is not a general sorter.
190// The endpoint either fulfills the request or returns one nonconforming cap.
191export function createServerPaginationFixture(
192 options: {
193 rows: Array<ServerRow>
194 autoIndex?: `off` | `eager`
195 cap?: number
196 serverPageSize?: number
197 } & (
198 | { syncMode: `on-demand`; order: ReadonlyArray<Field> }
199 | { syncMode: `eager`; order?: ReadonlyArray<Field> }
200 ),
201) {
202 const client = new QueryClient({
203 defaultOptions: { queries: { retry: false, staleTime: Infinity } },
204 })
205 const requests: Array<{
206 pageParam: unknown
207 subset: LoadSubsetOptions | undefined
208 signalAborted: boolean | undefined
209 subscriptionStatus: string | undefined
210 }> = []
211 const serverPages: Array<number> = []
212 const fetchRows = async (
213 input: LoadSubsetOptions | undefined,
214 pageParam?: unknown,
215 ): Promise<Array<ServerRow>> => {
216 const subset = captureSubset(input, options.order ?? [])
217 requests.push({
218 pageParam,
219 subset,
220 signalAborted: subset?.signal?.aborted,
221 subscriptionStatus: subset?.subscription?.status,
222 })
223 const start = subset?.offset ?? 0
224 const limit = options.cap ?? subset?.limit ?? options.rows.length
225 const matching = options.rows.filter((row) =>
226 subset?.where
227 ? evaluateReferenceExpression(subset.where, row) === true
228 : true,
229 )
230 if (options.serverPageSize !== undefined) {
231 const pageSize = options.serverPageSize
232 const firstPage = Math.floor(start / pageSize)
233 const prefixSkip = start % pageSize
234 const gathered: Array<ServerRow> = []
235 let page: number | undefined = firstPage
236 while (page !== undefined && gathered.length < prefixSkip + limit) {
237 serverPages.push(page)
238 // Server authority stays inside the adapter. Query DB receives only
239 // the completed row array, not this endpoint-specific continuation.
240 const response: {
241 rows: Array<ServerRow>
242 nextPage: number | undefined
243 } = await Promise.resolve({
244 rows: matching.slice(page * pageSize, (page + 1) * pageSize),
245 nextPage:
246 (page + 1) * pageSize < matching.length ? page + 1 : undefined,
247 })
248 gathered.push(...response.rows)
249 page = response.nextPage
250 }
251 return gathered.slice(prefixSkip, prefixSkip + limit)
252 }
253 return matching.slice(start, start + limit)
254 }
255 try {
256 const collection = createCollection(
257 queryCollectionOptions({
258 queryClient: client,
259 queryKey: [`server-pagination-probe`],
260 syncMode: options.syncMode,
261 autoIndex: options.autoIndex ?? `eager`,
262 defaultIndexType: BTreeIndex,
263 getKey: (row: ServerRow) => row.id,
264 queryFn: (context) =>
265 fetchRows(
266 context.meta?.loadSubsetOptions,
267 `pageParam` in context ? context.pageParam : undefined,
268 ),
269 }),
270 )
271 return { collection, requests, serverPages, client, fetchRows }
272 } catch (primaryError) {
273 try {
274 client.clear()
275 } catch (cleanupError) {
276 throw new AggregateError(
277 [primaryError, cleanupError],
278 `Server fixture construction and cleanup failed`,
279 { cause: primaryError },
280 )
281 }
282 throw primaryError
283 }
284}