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

conformance.test.tsx

371 lines10.9 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 sum,
23} from '@tanstack/db'
24import {
25 createRenderEffect,
26 createRoot,
27 createSignal,
28 onCleanup,
29} from 'solid-js'
30import {
31 mockSyncCollectionOptions,
32 mockSyncCollectionOptionsNoInitialState,
33} from '../../db/tests/utils'
34import { useLiveQuery } from '../src/useLiveQuery'
35import { runSuite } from '../../db/tests/conformance/suite'
36import { createPublicationLog } from '../../db/tests/conformance/publication-log'
37import { makeLaggingSource } from '../../db/tests/conformance/lagging-source'
38import { makeSyncSource } from '../../db/tests/conformance/sync-source'
39import { makeErrorSource as makeSharedErrorSource } from '../../db/tests/conformance/error-source'
40import { expectResultSurface } from '../../db/tests/conformance/result-laws'
41import { withScopeSetup } from '../../db/tests/conformance/scope-setup'
42import type { PooledLiveQueries } from '@tanstack/db'
43import type {
44 ConformanceResult,
45 ControllableHandle,
46 DeferredSourceHandle,
47 LiveQueryDriver,
48 LiveQueryHandle,
49 QueryBuild,
50 SourceHandle,
51} from '../../db/tests/conformance/contract'
52​
53let sourceSeq = 0
54​
55function writer<T extends { id: string }>(collection: any) {
56 return (type: `insert` | `update` | `delete`, value: T) => {
57 collection.utils.begin()
58 collection.utils.write({ type, value })
59 collection.utils.commit()
60 }
62​
63function makeSource<T extends { id: string }>(
64 initialData: ReadonlyArray<T>,
65 collectionId?: string,
66): SourceHandle<T> {
67 const collection = createCollection(
68 mockSyncCollectionOptions<T>({
69 id: collectionId ?? `conformance-solid-${sourceSeq++}`,
70 getKey: (r) => r.id,
71 initialData: [...initialData],
72 }),
73 )
74 const write = writer<T>(collection)
75 return {
76 collection,
77 insert: (row) => write(`insert`, row),
78 update: (row) => write(`update`, row),
79 remove: (row) => write(`delete`, row),
80 }
82​
83function makeDeferredSource<
84 T extends { id: string },
85>(): DeferredSourceHandle<T> {
86 const collection = createCollection(
87 mockSyncCollectionOptionsNoInitialState<T>({
88 id: `conformance-solid-${sourceSeq++}`,
89 getKey: (r) => r.id,
90 }),
91 )
92 collection.startSyncImmediate()
93 const write = writer<T>(collection)
94 return {
95 collection,
96 insert: (row) => write(`insert`, row),
97 update: (row) => write(`update`, row),
98 remove: (row) => write(`delete`, row),
99 emit: (rows) => {
100 collection.utils.begin()
101 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
102 collection.utils.commit()
103 },
104 markReady: () => collection.utils.markReady(),
105 }
107​
108function makePrecreated(
109 build: QueryBuild,
110 opts?: { startSync?: boolean; gcTime?: number },
111) {
112 const collection = createLiveQueryCollection({
113 query: build as any,
114 startSync: opts?.startSync ?? true,
115 gcTime: opts?.gcTime,
116 })
117 return { collection }
119​
120function makeErrorSource(kind: `fail` | `crash`) {
121 return makeSharedErrorSource(
122 createCollection,
123 `conformance-solid-err-${sourceSeq++}`,
124 kind,
125 )
127​
128async function settle() {
129 await new Promise((resolve) => setTimeout(resolve, 10))
131​
132function makeHandle(
133 getResult: () => any,
134 dispose: () => void,
135): LiveQueryHandle {
136 return {
137 collection: () => getResult()?.collection ?? null,
138 current(): ConformanceResult {
139 const result = getResult()
140 return expectResultSurface({
141 data: result?.data,
142 state: result?.state,
143 status: result?.status,
144 isReady: result?.isReady,
145 isLoadingError: result?.isLoadingError,
146 isCrashed: result?.isCrashed,
147 isSyncError: result?.isSyncError,
148 // solid-db exposes no `isEnabled`; derive it from status (status-derived).
149 isEnabled: result?.status !== `disabled`,
150 health: result?.health,
151 })
152 },
153 // The hook's flags are getters that do not read the resource, so they
154 // stay readable when reading `data` throws for an <ErrorBoundary>.
155 statusSurface() {
156 const result = getResult()
157 return {
158 status: result?.status,
159 isReady: result?.isReady,
160 isLoadingError: result?.isLoadingError,
161 isCrashed: result?.isCrashed,
162 isSyncError: result?.isSyncError,
163 health: result?.health,
164 }
165 },
166 flush: settle,
167 async apply(fn: () => void) {
168 fn()
169 await settle()
170 },
171 unmount() {
172 dispose()
173 },
174 }
176​
177function inRoot(fn: () => any): { getResult: () => any; dispose: () => void } {
178 let result: any
179 let dispose!: () => void
180 withScopeSetup(
181 () =>
182 createRoot((d) => {
183 dispose = d
184 result = fn()
185 }),
186 () => dispose(),
187 )
188 return { getResult: () => result, dispose }
190​
191function mount(build: QueryBuild) {
192 const { getResult, dispose } = inRoot(() => useLiveQuery(build as any))
193 return makeHandle(getResult, dispose)
195​
196function mountCollection(collection: any) {
197 // Solid accepts a pre-created collection via an accessor.
198 const { getResult, dispose } = inRoot(() => useLiveQuery(() => collection))
199 return makeHandle(getResult, dispose)
201​
202function mountConfig(
203 build: QueryBuild,
204 opts?: { gcTime?: number; pool?: PooledLiveQueries },
205) {
206 // Solid accepts the config-object form via an accessor.
207 const { getResult, dispose } = inRoot(() =>
208 useLiveQuery(() => ({ query: build, ...opts })),
209 )
210 return makeHandle(getResult, dispose)
212​
213function mountDisabled() {
214 // Disabled: an accessor returning null.
215 const { getResult, dispose } = inRoot(() => useLiveQuery(() => null))
216 return makeHandle(getResult, dispose)
218​
219function mountControllable<P>(
220 build: (q: any, param: P) => any,
221 initial: P,
222 opts?: { pool?: PooledLiveQueries },
223): ControllableHandle<P> {
224 const [param, setParam] = createSignal<P>(initial)
225 const published = createPublicationLog()
226 const { getResult, dispose } = inRoot(() => {
227 const query =
228 opts?.pool !== undefined
229 ? // Reading param() in the config accessor makes Solid recompute on change.
230 useLiveQuery(() => {
231 const value = param()
232 return { query: (q: any) => build(q, value), pool: opts.pool }
233 })
234 : // Reading param() inside the query fn makes Solid recompute on change.
235 useLiveQuery((q: any) => build(q, param()))
236 // Solid renders the value each render effect reads.
237 createRenderEffect(() => published.record(query.data, query.state))
238 return query
239 })
240 const handle = makeHandle(getResult, dispose)
241 return {
242 ...handle,
243 publications: published.values,
244 statePublications: published.stateValues,
245 async setParam(next: P) {
246 setParam(() => next)
247 // The first paint after the change: the framework ran its reactive
248 // work synchronously, but no later task has run.
249 published.record(getResult().data, getResult().state)
250 await settle()
251 },
252 }
254​
255const solidDriver: LiveQueryDriver = {
256 name: `solid`,
257 // Reactive reads decide when the query compiles again.
258 comparesQueryIdentity: false,
259 disabledRepresentation: `empty-reactive`,
260 ops: { eq, gt, count, sum, coalesce, groupKeys, createOptimisticAction },
261 makeSource,
262 makeDeferredSource,
263 makeLaggingSource: <T extends { id: string }>() =>
264 makeLaggingSource<T>(
265 createCollection,
266 `conformance-solid-lagging-${sourceSeq++}`,
267 ),
268 makeSyncSource: <T extends { id: string }>(data: ReadonlyArray<T>) =>
269 makeSyncSource<T>(
270 createCollection,
271 `conformance-solid-health-${sourceSeq++}`,
272 data,
273 ),
274 makePrecreated,
275 makeErrorSource,
276 mount,
277 mountControllable,
278 mountCollection,
279 mountConfig,
280 mountDisabled,
281 // solid-db routes errors through its createResource/Suspense path: reading an
282 // errored query throws (CollectionStateError) for an <ErrorBoundary> to catch,
283 // rather than exposing a readable isLoadingError flag. That's a framework idiom, not a
284 // gap — the error-status scenario is parametrized to assert it via the boundary.
285 errorSurface: `throw`,
286 knownGaps: [],
287 features: { serverSnapshot: false, suspense: true, pooledEqFilters: true },
289​
290describe(`owned native scope setup`, () => {
291 it(`keeps a successful scope alive until explicit disposal`, () => {
292 let calls = 0
293 const handle = inRoot(() => {
294 onCleanup(() => {
295 calls++
296 })
297 return 7
298 })
299 expect(calls).toBe(0)
300 handle.dispose()
301 expect(calls).toBe(1)
302 })
303​
304 it.each([false, true])(
305 `disposes failed setup and retains errors, cleanupFails=%s`,
306 (cleanupFails) => {
307 const primary = new Error(`scope setup failure`)
308 const secondary = new Error(`scope cleanup failure`)
309 let calls = 0
310 let caught: unknown
311 try {
312 inRoot(() => {
313 onCleanup(() => {
314 calls++
315 if (cleanupFails) throw secondary
316 })
317 throw primary
318 })
319 } catch (error) {
320 caught = error
321 }
322 expect(calls).toBe(1)
323 if (cleanupFails) {
324 expect(caught).toBeInstanceOf(AggregateError)
325 expect((caught as AggregateError).errors).toEqual([primary, secondary])
326 expect((caught as AggregateError).cause).toBe(primary)
327 } else expect(caught).toBe(primary)
328 },
329 )
330})
331​
332runSuite(solidDriver)
333it(`preserves raw result types through the actual driver reader`, () => {
334 const raw: Record<string, unknown> = {
335 data: [{ id: `a`, value: undefined }],
336 state: new Map(),
337 status: `disabled`,
338 isReady: false,
339 isLoadingError: false,
340 isCrashed: false,
341 isSyncError: false,
342 isEnabled: false,
343 }
344 const handle = makeHandle(
345 () => raw,
346 () => {},
347 )
348 try {
349 const healthy = handle.current()
350 expect(healthy.data).toBe(raw.data)
351 expect(healthy.state).toBe(raw.state)
352 expect(healthy.isReady).toBe(false)
353 expect(healthy.isLoadingError).toBe(false)
354 expect(healthy.isEnabled).toBe(false)
355 for (const key of [`status`, `isReady`, `isLoadingError`]) {
356 const original = raw[key]
357 delete raw[key]
358 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
359 for (const invalid of key === `status`
360 ? [undefined, 0]
361 : [undefined, 0, ``]) {
362 raw[key] = invalid
363 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
364 }
365 raw[key] = original
366 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
367 }
368 } finally {
369 handle.unmount()
370 }
371})