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

conformance.test.ts

333 lines9.0 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 gt,
20 sum,
21} from '@tanstack/db'
22import { effectScope, nextTick, onScopeDispose, ref } from 'vue'
23import {
24 mockSyncCollectionOptions,
25 mockSyncCollectionOptionsNoInitialState,
26} from '../../db/tests/utils'
27import { useLiveQuery } from '../src/useLiveQuery'
28import { runSuite } from '../../db/tests/conformance/suite'
29import { makeLaggingSource } from '../../db/tests/conformance/lagging-source'
30import { expectResultSurface } from '../../db/tests/conformance/result-laws'
31import { withScopeSetup } from '../../db/tests/conformance/scope-setup'
32import type {
33 ConformanceResult,
34 ControllableHandle,
35 DeferredSourceHandle,
36 LiveQueryDriver,
37 LiveQueryHandle,
38 QueryBuild,
39 SourceHandle,
40} from '../../db/tests/conformance/contract'
41​
42let sourceSeq = 0
43​
44function writer<T extends { id: string }>(collection: any) {
45 return (type: `insert` | `update` | `delete`, value: T) => {
46 collection.utils.begin()
47 collection.utils.write({ type, value })
48 collection.utils.commit()
49 }
51​
52function makeSource<T extends { id: string }>(
53 initialData: ReadonlyArray<T>,
54): SourceHandle<T> {
55 const collection = createCollection(
56 mockSyncCollectionOptions<T>({
57 id: `conformance-vue-${sourceSeq++}`,
58 getKey: (r) => r.id,
59 initialData: [...initialData],
60 }),
61 )
62 const write = writer<T>(collection)
63 return {
64 collection,
65 insert: (row) => write(`insert`, row),
66 update: (row) => write(`update`, row),
67 remove: (row) => write(`delete`, row),
68 }
70​
71function makeDeferredSource<
72 T extends { id: string },
73>(): DeferredSourceHandle<T> {
74 const collection = createCollection(
75 mockSyncCollectionOptionsNoInitialState<T>({
76 id: `conformance-vue-${sourceSeq++}`,
77 getKey: (r) => r.id,
78 }),
79 )
80 collection.startSyncImmediate()
81 const write = writer<T>(collection)
82 return {
83 collection,
84 insert: (row) => write(`insert`, row),
85 update: (row) => write(`update`, row),
86 remove: (row) => write(`delete`, row),
87 emit: (rows) => {
88 collection.utils.begin()
89 rows.forEach((value) => collection.utils.write({ type: `insert`, value }))
90 collection.utils.commit()
91 },
92 markReady: () => collection.utils.markReady(),
93 }
95​
96function makePrecreated(
97 build: QueryBuild,
98 opts?: { startSync?: boolean; gcTime?: number },
99) {
100 const collection = createLiveQueryCollection({
101 query: build as any,
102 startSync: opts?.startSync ?? true,
103 gcTime: opts?.gcTime,
104 })
105 return { collection }
107​
108function makeErrorSource() {
109 const expectedError = new Error(`conformance: sync failure`)
110 let startup: { returned: true } | { returned: false; error: unknown } = {
111 returned: true,
112 }
113 const collection = createCollection<{ id: string }>({
114 id: `conformance-vue-err-${sourceSeq++}`,
115 getKey: (r) => r.id,
116 startSync: false,
117 sync: {
118 sync: () => {
119 throw expectedError
120 },
121 },
122 })
123 try {
124 collection.startSyncImmediate()
125 } catch (error) {
126 startup = { returned: false, error }
127 }
128 return { collection, expectedError, startup }
130​
131async function settle() {
132 await nextTick()
133 await new Promise((resolve) => setTimeout(resolve, 10))
135​
136function makeHandle(result: any, scope: ReturnType<typeof effectScope>) {
137 const handle: LiveQueryHandle = {
138 collection: () => result.collection?.value ?? null,
139 current(): ConformanceResult {
140 return expectResultSurface({
141 data: result.data?.value,
142 state: result.state?.value,
143 status: result.status?.value,
144 isReady: result.isReady?.value,
145 persistedStatus: result.persistedStatus?.value,
146 isPersistedReady: result.isPersistedReady?.value,
147 persistedError: result.persistedError?.value,
148 isError: result.isError?.value,
149 // vue-db exposes no `isEnabled`; derive it from status (status-derived).
150 isEnabled: result.status?.value !== `disabled`,
151 })
152 },
153 flush: settle,
154 async apply(fn: () => void) {
155 fn()
156 await settle()
157 },
158 unmount() {
159 scope.stop()
160 },
161 }
162 return handle
164​
165function runInScope<R>(fn: () => R): {
166 result: R
167 scope: ReturnType<typeof effectScope>
168} {
169 const scope = effectScope()
170 let result!: R
171 withScopeSetup(
172 () =>
173 scope.run(() => {
174 result = fn()
175 }),
176 () => scope.stop(),
177 )
178 return { result, scope }
180​
181function mount(build: QueryBuild) {
182 const { result, scope } = runInScope(() => useLiveQuery(build as any))
183 return makeHandle(result, scope)
185​
186function mountCollection(collection: any) {
187 const { result, scope } = runInScope(() => useLiveQuery(collection))
188 return makeHandle(result, scope)
190​
191function mountConfig(build: QueryBuild, opts?: { gcTime?: number }) {
192 const { result, scope } = runInScope(() =>
193 useLiveQuery({ query: build, ...opts } as any),
194 )
195 return makeHandle(result, scope)
197​
198function mountDisabled() {
199 // Vue's disabled convention: the query callback returns undefined.
200 const { result, scope } = runInScope(() =>
201 useLiveQuery(() => undefined as any),
202 )
203 return makeHandle(result, scope)
205​
206function mountControllable<P>(
207 build: (q: any, param: P) => any,
208 initial: P,
209): ControllableHandle<P> {
210 const param = ref(initial) as { value: P }
211 const { result, scope } = runInScope(() =>
212 useLiveQuery((q: any) => build(q, param.value), [() => param.value]),
213 )
214 const handle = makeHandle(result, scope)
215 return {
216 ...handle,
217 async setParam(next: P) {
218 param.value = next
219 await settle()
220 },
221 }
223​
224const vueDriver: LiveQueryDriver = {
225 name: `vue`,
226 disabledRepresentation: `empty-reactive`,
227 ops: { eq, gt, count, sum, coalesce, createOptimisticAction },
228 makeSource,
229 makeDeferredSource,
230 makeLaggingSource: <T extends { id: string }>() =>
231 makeLaggingSource<T>(
232 createCollection,
233 `conformance-vue-lagging-${sourceSeq++}`,
234 ),
235 makePrecreated,
236 makeErrorSource,
237 mount,
238 mountControllable,
239 mountCollection,
240 mountConfig,
241 mountDisabled,
242 knownGaps: [],
243 features: { serverSnapshot: false, suspense: false, pooledEqFilters: true },
245​
246describe(`owned native scope setup`, () => {
247 it(`keeps a successful scope alive until explicit disposal`, () => {
248 let calls = 0
249 const handle = runInScope(() => {
250 onScopeDispose(() => {
251 calls++
252 })
253 return 7
254 })
255 expect(calls).toBe(0)
256 handle.scope.stop()
257 expect(calls).toBe(1)
258 })
259​
260 it.each([false, true])(
261 `disposes failed setup and retains errors, cleanupFails=%s`,
262 (cleanupFails) => {
263 const primary = new Error(`scope setup failure`)
264 const secondary = new Error(`scope cleanup failure`)
265 let calls = 0
266 let caught: unknown
267 try {
268 runInScope(() => {
269 onScopeDispose(() => {
270 calls++
271 if (cleanupFails) throw secondary
272 })
273 throw primary
274 })
275 } catch (error) {
276 caught = error
277 }
278 expect(calls).toBe(1)
279 if (cleanupFails) {
280 expect(caught).toBeInstanceOf(AggregateError)
281 expect((caught as AggregateError).errors).toEqual([primary, secondary])
282 expect((caught as AggregateError).cause).toBe(primary)
283 } else expect(caught).toBe(primary)
284 },
285 )
286})
287​
288runSuite(vueDriver)
289it(`preserves raw result types through the actual driver reader`, () => {
290 const raw: Record<string, unknown> = {
291 data: [{ id: `a`, value: undefined }],
292 state: new Map(),
293 status: `disabled`,
294 isReady: false,
295 isError: false,
296 isEnabled: false,
297 }
298 const scope = effectScope()
299 const result = Object.fromEntries(
300 Object.keys(raw).map((key) => [
301 key,
302 {
303 get value() {
304 return raw[key]
305 },
306 },
307 ]),
308 )
309 const handle = makeHandle(result, scope)
310 try {
311 const healthy = handle.current()
312 expect(healthy.data).toBe(raw.data)
313 expect(healthy.state).toBe(raw.state)
314 expect(healthy.isReady).toBe(false)
315 expect(healthy.isError).toBe(false)
316 expect(healthy.isEnabled).toBe(false)
317 for (const key of [`status`, `isReady`, `isError`]) {
318 const original = raw[key]
319 delete raw[key]
320 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
321 for (const invalid of key === `status`
322 ? [undefined, 0]
323 : [undefined, 0, ``]) {
324 raw[key] = invalid
325 expect(() => handle.current()).toThrowError(new RegExp(`raw ${key}`))
326 }
327 raw[key] = original
328 expect(handle.current()[key as keyof ConformanceResult]).toBe(original)
329 }
330 } finally {
331 handle.unmount()
332 }
333})