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

conformance.test.ts

361 lines10.1 KB

1/**
2 * Vue driver for the shared live-query conformance suite.
3 *
4 * Realm-sensitive pieces (collection factories, query operators) are imported
5 * from Vue's `@tanstack/db` and handed to the shared scenarios. Vue composables
6 * run inside an `effectScope` so `unmount` can dispose them via `scope.stop()`,
7 * which triggers the `watchEffect` `onInvalidate` cleanup.
8 *
9 * All registered laws must pass; the driver has no whole-test waivers.
10 */
11import { describe, expect, it } from 'vitest'
12import {
13 coalesce,
14 count,
15 createCollection,
16 createLiveQueryCollection,
17 createOptimisticAction,
18 eq,
19 groupKeys,
20 gt,
21 sum,
22} from '@tanstack/db'
23import { effectScope, nextTick, onScopeDispose, ref, watch } from 'vue'
24import {
25 mockSyncCollectionOptions,
26 mockSyncCollectionOptionsNoInitialState,
27} from '../../db/tests/utils'
28import { useLiveQuery } from '../src/useLiveQuery'
29import { runSuite } from '../../db/tests/conformance/suite'
30import { createPublicationLog } from '../../db/tests/conformance/publication-log'
31import { makeLaggingSource } from '../../db/tests/conformance/lagging-source'
32import { makeSyncSource } from '../../db/tests/conformance/sync-source'
33import { makeErrorSource as makeSharedErrorSource } from '../../db/tests/conformance/error-source'
34import { expectResultSurface } from '../../db/tests/conformance/result-laws'
35import { withScopeSetup } from '../../db/tests/conformance/scope-setup'
36import type { PooledLiveQueries } from '@tanstack/db'
37import type {
38 ConformanceResult,
39 ControllableHandle,
40 DeferredSourceHandle,
41 LiveQueryDriver,
42 LiveQueryHandle,
43 QueryBuild,
44 SourceHandle,
45} from '../../db/tests/conformance/contract'
46​
47let sourceSeq = 0
48​
49function writer<T extends { id: string }>(collection: any) {
50 return (type: `insert` | `update` | `delete`, value: T) => {
51 collection.utils.begin()
52 collection.utils.write({ type, value })
53 collection.utils.commit()
54 }
56​
57function makeSource<T extends { id: string }>(
58 initialData: ReadonlyArray<T>,
59 collectionId?: string,
60): SourceHandle<T> {
61 const collection = createCollection(
62 mockSyncCollectionOptions<T>({
63 id: collectionId ?? `conformance-vue-${sourceSeq++}`,
64 getKey: (r) => r.id,
65 initialData: [...initialData],
66 }),
67 )
68 const write = writer<T>(collection)
69 return {
70 collection,
71 insert: (row) => write(`insert`, row),
72 update: (row) => write(`update`, row),
73 remove: (row) => write(`delete`, row),
74 }
76​
77function makeDeferredSource<
78 T extends { id: string },
79>(): DeferredSourceHandle<T> {
80 const collection = createCollection(
81 mockSyncCollectionOptionsNoInitialState<T>({
82 id: `conformance-vue-${sourceSeq++}`,
83 getKey: (r) => r.id,
84 }),
85 )
86 collection.startSyncImmediate()
87 const write = writer<T>(collection)
88 return {
89 collection,
90 insert: (row) => write(`insert`, row),
91 update: (row) => write(`update`, row),
92 remove: (row) => write(`delete`, row),
93 emit: (rows) => {
94 collection.utils.begin()
95 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
96 collection.utils.commit()
97 },
98 markReady: () => collection.utils.markReady(),
99 }
101​
102function makePrecreated(
103 build: QueryBuild,
104 opts?: { startSync?: boolean; gcTime?: number },
105) {
106 const collection = createLiveQueryCollection({
107 query: build as any,
108 startSync: opts?.startSync ?? true,
109 gcTime: opts?.gcTime,
110 })
111 return { collection }
113​
114function makeErrorSource(kind: `fail` | `crash`) {
115 return makeSharedErrorSource(
116 createCollection,
117 `conformance-vue-err-${sourceSeq++}`,
118 kind,
119 )
121​
122async function settle() {
123 await nextTick()
124 await new Promise((resolve) => setTimeout(resolve, 10))
126​
127function makeHandle(result: any, scope: ReturnType<typeof effectScope>) {
128 const handle: LiveQueryHandle = {
129 collection: () => result.collection?.value ?? null,
130 current(): ConformanceResult {
131 return expectResultSurface({
132 data: result.data?.value,
133 state: result.state?.value,
134 status: result.status?.value,
135 isReady: result.isReady?.value,
136 isLoadingError: result.isLoadingError?.value,
137 isCrashed: result.isCrashed?.value,
138 isSyncError: result.isSyncError?.value,
139 // vue-db exposes no `isEnabled`; derive it from status (status-derived).
140 isEnabled: result.status?.value !== `disabled`,
141 health: result.health?.value,
142 })
143 },
144 flush: settle,
145 async apply(fn: () => void) {
146 fn()
147 await settle()
148 },
149 unmount() {
150 scope.stop()
151 },
152 }
153 return handle
155​
156function runInScope<R>(fn: () => R): {
157 result: R
158 scope: ReturnType<typeof effectScope>
159} {
160 const scope = effectScope()
161 let result!: R
162 withScopeSetup(
163 () =>
164 scope.run(() => {
165 result = fn()
166 }),
167 () => scope.stop(),
168 )
169 return { result, scope }
171​
172function mount(build: QueryBuild) {
173 const { result, scope } = runInScope(() => useLiveQuery(build as any))
174 return makeHandle(result, scope)
176​
177function mountCollection(collection: any) {
178 const { result, scope } = runInScope(() => useLiveQuery(collection))
179 return makeHandle(result, scope)
181​
182function mountConfig(
183 build: QueryBuild,
184 opts?: { gcTime?: number; pool?: PooledLiveQueries },
185) {
186 const { result, scope } = runInScope(() =>
187 useLiveQuery({ query: build, ...opts } as any),
188 )
189 return makeHandle(result, scope)
191​
192function mountDisabled() {
193 // Vue's disabled convention: the query callback returns undefined.
194 const { result, scope } = runInScope(() =>
195 useLiveQuery(() => undefined as any),
196 )
197 return makeHandle(result, scope)
199​
200function mountControllable<P>(
201 build: (q: any, param: P) => any,
202 initial: P,
203 opts?: { pool?: PooledLiveQueries },
204): ControllableHandle<P> {
205 const param = ref(initial) as { value: P }
206 const published = createPublicationLog()
207 const { result, scope } = runInScope(() => {
208 const query =
209 opts?.pool !== undefined
210 ? useLiveQuery(
211 {
212 query: (q: any) => build(q, param.value),
213 pool: opts.pool,
214 } as any,
215 [() => param.value],
216 )
217 : useLiveQuery((q: any) => build(q, param.value), [() => param.value])
218 // Vue renders the value present at each pre-flush.
219 watch(
220 () => [query.data.value, [...query.state.value.values()]],
221 ([data]) => published.record(data, query.state.value),
222 { flush: `pre`, immediate: true },
223 )
224 return query
225 })
226 const handle = makeHandle(result, scope)
227 return {
228 ...handle,
229 publications: published.values,
230 statePublications: published.stateValues,
231 async setParam(next: P) {
232 param.value = next
233 // The first paint after the change: the framework has flushed its
234 // reactive work, but no later task has run.
235 await nextTick()
236 published.record(result.data.value, result.state.value)
237 await settle()
238 },
239 }
241​
242const vueDriver: LiveQueryDriver = {
243 name: `vue`,
244 // Reactive reads decide when the query compiles again.
245 comparesQueryIdentity: false,
246 disabledRepresentation: `empty-reactive`,
247 ops: { eq, gt, count, sum, coalesce, groupKeys, createOptimisticAction },
248 makeSource,
249 makeDeferredSource,
250 makeLaggingSource: <T extends { id: string }>() =>
251 makeLaggingSource<T>(
252 createCollection,
253 `conformance-vue-lagging-${sourceSeq++}`,
254 ),
255 makeSyncSource: <T extends { id: string }>(data: ReadonlyArray<T>) =>
256 makeSyncSource<T>(
257 createCollection,
258 `conformance-vue-health-${sourceSeq++}`,
259 data,
260 ),
261 makePrecreated,
262 makeErrorSource,
263 mount,
264 mountControllable,
265 mountCollection,
266 mountConfig,
267 mountDisabled,
268 knownGaps: [],
269 features: { serverSnapshot: false, suspense: false, pooledEqFilters: true },
271​
272describe(`owned native scope setup`, () => {
273 it(`keeps a successful scope alive until explicit disposal`, () => {
274 let calls = 0
275 const handle = runInScope(() => {
276 onScopeDispose(() => {
277 calls++
278 })
279 return 7
280 })
281 expect(calls).toBe(0)
282 handle.scope.stop()
283 expect(calls).toBe(1)
284 })
285​
286 it.each([false, true])(
287 `disposes failed setup and retains errors, cleanupFails=%s`,
288 (cleanupFails) => {
289 const primary = new Error(`scope setup failure`)
290 const secondary = new Error(`scope cleanup failure`)
291 let calls = 0
292 let caught: unknown
293 try {
294 runInScope(() => {
295 onScopeDispose(() => {
296 calls++
297 if (cleanupFails) throw secondary
298 })
299 throw primary
300 })
301 } catch (error) {
302 caught = error
303 }
304 expect(calls).toBe(1)
305 if (cleanupFails) {
306 expect(caught).toBeInstanceOf(AggregateError)
307 expect((caught as AggregateError).errors).toEqual([primary, secondary])
308 expect((caught as AggregateError).cause).toBe(primary)
309 } else expect(caught).toBe(primary)
310 },
311 )
312})
313​
314runSuite(vueDriver)
315it(`preserves raw result types through the actual driver reader`, () => {
316 const raw: Record<string, unknown> = {
317 data: [{ id: `a`, value: undefined }],
318 state: new Map(),
319 status: `disabled`,
320 isReady: false,
321 isLoadingError: false,
322 isCrashed: false,
323 isSyncError: false,
324 isEnabled: false,
325 }
326 const scope = effectScope()
327 const result = Object.fromEntries(
328 Object.keys(raw).map((key) => [
329 key,
330 {
331 get value() {
332 return raw[key]
333 },
334 },
335 ]),
336 )
337 const handle = makeHandle(result, scope)
338 try {
339 const healthy = handle.current()
340 expect(healthy.data).toBe(raw.data)
341 expect(healthy.state).toBe(raw.state)
342 expect(healthy.isReady).toBe(false)
343 expect(healthy.isLoadingError).toBe(false)
344 expect(healthy.isEnabled).toBe(false)
345 for (const key of [`status`, `isReady`, `isLoadingError`]) {
346 const original = raw[key]
347 delete raw[key]
348 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
349 for (const invalid of key === `status`
350 ? [undefined, 0]
351 : [undefined, 0, ``]) {
352 raw[key] = invalid
353 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
354 }
355 raw[key] = original
356 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
357 }
358 } finally {
359 handle.unmount()
360 }
361})