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