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

conformance.test.tsx

464 lines14.1 KB

1/**
2 * Solid driver for the shared live-query conformance suite.
3 *
4 * Each mount runs inside a `createRoot` so `unmount` disposes via the captured
5 * dispose fn; the root stays alive between mount and reads so Solid's reactive
6 * getters stay current. Solid auto-tracks signals, so controllable inputs use a
7 * signal read inside the query fn (no deps array). Collection/config inputs are
8 * passed as accessors, per Solid's arity-based input detection.
9 *
10 * All registered laws must pass; the driver has no whole-test waivers.
11 */
12import { describe, expect, it } from 'vitest'
13import {
14 coalesce,
15 count,
16 createCollection,
17 createLiveQueryCollection,
18 createOptimisticAction,
19 eq,
20 groupKeys,
21 gt,
22 localOnlyCollectionOptions,
23 sum,
24} from '@tanstack/db'
25import {
26 createRenderEffect,
27 createRoot,
28 createSignal,
29 onCleanup,
30} from 'solid-js'
31import { createStore } from 'solid-js/store'
32import {
33 mockSyncCollectionOptions,
34 mockSyncCollectionOptionsNoInitialState,
35} from '../../db/tests/utils'
36import { useLiveQuery } from '../src/useLiveQuery'
37import { runSuite } from '../../db/tests/conformance/suite'
38import { runRowSnapshotHistories } from '../../db/tests/conformance/row-snapshot-oracle'
39import { createPublicationLog } from '../../db/tests/conformance/publication-log'
40import { expectPublishedRows } from '../../db/tests/conformance/publication-laws-oracle'
41import { makeLaggingSource } from '../../db/tests/conformance/lagging-source'
42import { makeSyncSource } from '../../db/tests/conformance/sync-source'
43import { makeErrorSource as makeSharedErrorSource } from '../../db/tests/conformance/error-source'
44import {
45 expectResultSurface,
46 selectedRowKeys,
47} from '../../db/tests/conformance/result-laws'
48import { withScopeSetup } from '../../db/tests/conformance/scope-setup'
49import type { PooledLiveQueries } from '@tanstack/db'
50import type {
51 ConformanceResult,
52 ControllableHandle,
53 DeferredSourceHandle,
54 LiveQueryDriver,
55 LiveQueryHandle,
56 QueryBuild,
57 SourceHandle,
58} from '../../db/tests/conformance/contract'
59​
60let sourceSeq = 0
61​
62function writer<T extends { id: string }>(collection: any) {
63 return (type: `insert` | `update` | `delete`, value: T) => {
64 collection.utils.begin()
65 collection.utils.write({ type, value })
66 collection.utils.commit()
67 }
69​
70function makeSource<T extends { id: string }>(
71 initialData: ReadonlyArray<T>,
72 collectionId?: string,
73 options?: { rowUpdateMode?: `full` },
74): SourceHandle<T> {
75 const collection = createCollection(
76 mockSyncCollectionOptions<T>({
77 id: collectionId ?? `conformance-solid-${sourceSeq++}`,
78 getKey: (r) => r.id,
79 initialData: [...initialData],
80 rowUpdateMode: options?.rowUpdateMode,
81 }),
82 )
83 const write = writer<T>(collection)
84 return {
85 collection,
86 insert: (row) => write(`insert`, row),
87 update: (row) => write(`update`, row),
88 remove: (row) => write(`delete`, row),
89 }
91​
92function makeDeferredSource<
93 T extends { id: string },
94>(): DeferredSourceHandle<T> {
95 const collection = createCollection(
96 mockSyncCollectionOptionsNoInitialState<T>({
97 id: `conformance-solid-${sourceSeq++}`,
98 getKey: (r) => r.id,
99 }),
100 )
101 collection.startSyncImmediate()
102 const write = writer<T>(collection)
103 return {
104 collection,
105 insert: (row) => write(`insert`, row),
106 update: (row) => write(`update`, row),
107 remove: (row) => write(`delete`, row),
108 emit: (rows) => {
109 collection.utils.begin()
110 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
111 collection.utils.commit()
112 },
113 markReady: () => collection.utils.markReady(),
114 }
116​
117function makePrecreated(
118 build: QueryBuild,
119 opts?: { startSync?: boolean; gcTime?: number },
120) {
121 const collection = createLiveQueryCollection({
122 query: build as any,
123 startSync: opts?.startSync ?? true,
124 gcTime: opts?.gcTime,
125 })
126 return { collection }
128​
129function makeErrorSource(kind: `fail` | `crash`) {
130 return makeSharedErrorSource(
131 createCollection,
132 `conformance-solid-err-${sourceSeq++}`,
133 kind,
134 )
136​
137async function settle() {
138 await new Promise((resolve) => setTimeout(resolve, 10))
140​
141function makeHandle(
142 getResult: () => any,
143 dispose: () => void,
144): LiveQueryHandle {
145 return {
146 collection: () => getResult()?.collection ?? null,
147 current(): ConformanceResult {
148 const result = getResult()
149 return expectResultSurface({
150 data: result?.(),
151 state: result?.state,
152 status: result?.status,
153 isReady: result?.isReady,
154 isLoadingError: result?.isLoadingError,
155 isCrashed: result?.isCrashed,
156 isSyncError: result?.isSyncError,
157 // solid-db exposes no `isEnabled`; derive it from status (status-derived).
158 isEnabled: result?.status !== `disabled`,
159 health: result?.health,
160 })
161 },
162 // The hook's flags are getters that do not read the resource, so they
163 // stay readable when reading `data` throws for an <ErrorBoundary>.
164 statusSurface() {
165 const result = getResult()
166 return {
167 status: result?.status,
168 isReady: result?.isReady,
169 isLoadingError: result?.isLoadingError,
170 isCrashed: result?.isCrashed,
171 isSyncError: result?.isSyncError,
172 health: result?.health,
173 }
174 },
175 flush: settle,
176 async apply(fn: () => void) {
177 fn()
178 await settle()
179 },
180 unmount() {
181 dispose()
182 },
183 }
185​
186function inRoot(fn: () => any): { getResult: () => any; dispose: () => void } {
187 let result: any
188 let dispose!: () => void
189 withScopeSetup(
190 () =>
191 createRoot((d) => {
192 dispose = d
193 result = fn()
194 }),
195 () => dispose(),
196 )
197 return { getResult: () => result, dispose }
199​
200function mount(build: QueryBuild) {
201 const { getResult, dispose } = inRoot(() => useLiveQuery(build as any))
202 return makeHandle(getResult, dispose)
204​
205function mountCollection(collection: any) {
206 // Solid accepts a pre-created collection via an accessor.
207 const { getResult, dispose } = inRoot(() => useLiveQuery(() => collection))
208 return makeHandle(getResult, dispose)
210​
211function mountConfig(
212 build: QueryBuild,
213 opts?: { gcTime?: number; pool?: PooledLiveQueries },
214) {
215 // Solid accepts the config-object form via an accessor.
216 const { getResult, dispose } = inRoot(() =>
217 useLiveQuery(() => ({ query: build, ...opts })),
218 )
219 return makeHandle(getResult, dispose)
221​
222function mountDisabled() {
223 // Disabled: an accessor returning null.
224 const { getResult, dispose } = inRoot(() => useLiveQuery(() => null))
225 return makeHandle(getResult, dispose)
227​
228function mountControllable<P>(
229 build: (q: any, param: P) => any,
230 initial: P,
231 opts?: { pool?: PooledLiveQueries },
232): ControllableHandle<P> {
233 const [param, setParam] = createSignal<P>(initial)
234 const published = createPublicationLog()
235 const { getResult, dispose } = inRoot(() => {
236 const query =
237 opts?.pool !== undefined
238 ? // Reading param() in the config accessor makes Solid recompute on change.
239 useLiveQuery(() => {
240 const value = param()
241 return { query: (q: any) => build(q, value), pool: opts.pool }
242 })
243 : // Reading param() inside the query fn makes Solid recompute on change.
244 useLiveQuery((q: any) => build(q, param()))
245 // Solid renders the value each render effect reads.
246 createRenderEffect(() => published.record(query(), query.state))
247 return query
248 })
249 const handle = makeHandle(getResult, dispose)
250 return {
251 ...handle,
252 publications: published.values,
253 statePublications: published.stateValues,
254 async setParam(next: P) {
255 setParam(() => next)
256 // The first paint after the change: the framework ran its reactive
257 // work synchronously, but no later task has run.
258 published.record(getResult()(), getResult().state)
259 await settle()
260 },
261 }
263​
264const solidDriver: LiveQueryDriver = {
265 name: `solid`,
266 // Reactive reads decide when the query compiles again.
267 comparesQueryIdentity: false,
268 disabledRepresentation: `empty-reactive`,
269 ops: { eq, gt, count, sum, coalesce, groupKeys, createOptimisticAction },
270 makeSource,
271 wrapSnapshotValue: <T extends object>(value: T) => createStore(value)[0],
272 makeDeferredSource,
273 makeLaggingSource: <T extends { id: string }>() =>
274 makeLaggingSource<T>(
275 createCollection,
276 `conformance-solid-lagging-${sourceSeq++}`,
277 ),
278 makeSyncSource: <T extends { id: string }>(data: ReadonlyArray<T>) =>
279 makeSyncSource<T>(
280 createCollection,
281 `conformance-solid-health-${sourceSeq++}`,
282 data,
283 ),
284 makePrecreated,
285 makeErrorSource,
286 mount,
287 mountControllable,
288 mountCollection,
289 mountConfig,
290 mountDisabled,
291 // solid-db routes errors through its createResource/Suspense path: reading an
292 // errored query throws (CollectionStateError) for an <ErrorBoundary> to catch,
293 // rather than exposing a readable isLoadingError flag. That's a framework idiom, not a
294 // gap — the error-status scenario is parametrized to assert it via the boundary.
295 errorSurface: `throw`,
296 knownGaps: [],
297 features: { serverSnapshot: false, suspense: true, pooledEqFilters: true },
299​
300describe(`owned native scope setup`, () => {
301 it(`keeps a successful scope alive until explicit disposal`, () => {
302 let calls = 0
303 const handle = inRoot(() => {
304 onCleanup(() => {
305 calls++
306 })
307 return 7
308 })
309 expect(calls).toBe(0)
310 handle.dispose()
311 expect(calls).toBe(1)
312 })
313​
314 it.each([false, true])(
315 `disposes failed setup and retains errors, cleanupFails=%s`,
316 (cleanupFails) => {
317 const primary = new Error(`scope setup failure`)
318 const secondary = new Error(`scope cleanup failure`)
319 let calls = 0
320 let caught: unknown
321 try {
322 inRoot(() => {
323 onCleanup(() => {
324 calls++
325 if (cleanupFails) throw secondary
326 })
327 throw primary
328 })
329 } catch (error) {
330 caught = error
331 }
332 expect(calls).toBe(1)
333 if (cleanupFails) {
334 expect(caught).toBeInstanceOf(AggregateError)
335 expect((caught as AggregateError).errors).toEqual([primary, secondary])
336 expect((caught as AggregateError).cause).toBe(primary)
337 } else expect(caught).toBe(primary)
338 },
339 )
340})
341​
342runSuite(solidDriver)
343​
344// The reported source is local-only. Keep that receiving path on the same
345// snapshot law and histories as the adapter suite's controlled sync source.
346it.each([`callback`, `config`, `collection`] as const)(
347 `preserves local-only row snapshots through the %s input`,
348 async (input) => {
349 await runRowSnapshotHistories(
350 {
351 ...solidDriver,
352 name: `solid-local-only`,
353 snapshotSourceUsesDraft: true,
354 makeSource<T extends { id: string }>(
355 initialData: ReadonlyArray<T>,
356 collectionId?: string,
357 options?: { rowUpdateMode?: `full` },
358 ) {
359 const collection = createCollection(
360 localOnlyCollectionOptions<T>({
361 id: collectionId,
362 getKey: (row) => row.id,
363 initialData: [...initialData],
364 }),
365 )
366 return {
367 collection,
368 insert: (row: T) => {
369 collection.insert(row)
370 },
371 update: (row: T) => {
372 return collection.update(row.id, (draft) => {
373 // Local-only sync already replaces full rows. Remove omitted
374 // keys from the draft when the shared history requests it.
375 if (options?.rowUpdateMode === `full`)
376 for (const key of selectedRowKeys(draft))
377 if (!Object.hasOwn(row, key))
378 Reflect.deleteProperty(draft, key)
379 Object.assign(draft, row)
380 })
381 },
382 remove: (row: T) => {
383 collection.delete(row.id)
384 },
385 }
386 },
387 },
388 input,
389 `sync`,
390 )
391 },
393​
394it(`preserves raw result types through the actual driver reader`, () => {
395 const rawData = [{ id: `a`, value: undefined }]
396 const raw = Object.assign(() => rawData, {
397 state: new Map(),
398 status: `disabled`,
399 isReady: false,
400 isLoadingError: false,
401 isCrashed: false,
402 isSyncError: false,
403 isEnabled: false,
404 })
405 const handle = makeHandle(
406 () => raw,
407 () => {},
408 )
409 try {
410 const healthy = handle.current()
411 expect(healthy.data).toBe(rawData)
412 expect(healthy.state).toBe(raw.state)
413 expect(healthy.isReady).toBe(false)
414 expect(healthy.isLoadingError).toBe(false)
415 expect(healthy.isEnabled).toBe(false)
416 for (const key of [`status`, `isReady`, `isLoadingError`] as const) {
417 const original = raw[key]
418 Reflect.deleteProperty(raw, key)
419 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
420 for (const invalid of key === `status`
421 ? [undefined, 0]
422 : [undefined, 0, ``]) {
423 Reflect.set(raw, key, invalid)
424 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
425 }
426 Reflect.set(raw, key, original)
427 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
428 }
429 } finally {
430 handle.unmount()
431 }
432})
433​
434// These controls supply wrong traces to the same comparison used by the
435// shared source-ID and pooled scenarios. They add no production histories.
436describe(`settled publication comparison`, () => {
437 const rows = [{ id: `current` }]
438 const stale = [{ id: `previous` }]
439 it.each([
440 { name: `settled rows`, values: [rows], expected: rows },
441 {
442 name: `empty loading turns before settled rows`,
443 values: [undefined, [], rows],
444 expected: rows,
445 },
446 {
447 name: `a model whose settled result is empty`,
448 values: [undefined, []],
449 expected: [],
450 },
451 ])(`accepts $name`, ({ values, expected }) => {
452 expectPublishedRows(values, expected)
453 })
454​
455 it.each([
456 { name: `an omitted log`, values: [] },
457 { name: `a dropped accessor value`, values: [undefined] },
458 { name: `a dropped settled publication`, values: [undefined, []] },
459 { name: `stale rows before the settled value`, values: [stale, rows] },
460 { name: `stale rows as the settled value`, values: [rows, stale] },
461 ])(`rejects $name`, ({ values }) => {
462 expect(() => expectPublishedRows(values, rows)).toThrow()
463 })
464})