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

useLiveQuery-publication-oracle.test.ts

179 lines5.8 KB

1/**
2 * Vue public-result publication law.
3 *
4 * Contract: One applied source change must not expose a torn `data` snapshot
5 * to a synchronous Vue watcher. The source Collection has published a coherent
6 * snapshot by the time its change reaches this hook. This adapter must expose
7 * either the preceding result or that new result, never a transient clear.
8 * For these one-message transactions, it must notify the watcher once with
9 * the final result.
10 * Authority: `packages/db/tests/conformance/contract.ts` defines `data` as
11 * the rows exposed by the live-query Collection. The project glossary defines
12 * publication as coherent visibility. This oracle checks that binding at
13 * Vue's synchronous watcher cut.
14 *
15 * Model: For these identity queries, copy source rows into a plain array after
16 * each sync transaction. The model uses no Vue refs or hook array mechanics.
17 *
18 * History grammar: start with two or three distinct rows; mount a supplied
19 * Collection or an identity live query; then perform one insert, update, or
20 * nonterminal delete. The empty final result, multiple source changes in one
21 * transaction, and query recompilation are not covered.
22 *
23 * Driver and checkpoint: use the real Vue hook with a source Collection, then
24 * apply one sync transaction. A `flush: 'sync'` Vue watcher records every
25 * public `data` value during that transaction, before a Vue scheduler tick.
26 * The refinement check rejects every value other than the old or final rows
27 * and requires the final rows to appear. A clear-then-publish adapter would
28 * expose `[]` between two nonempty results and fail at the watcher checkpoint.
29 */
30import { createCollection } from '@tanstack/db'
31import { effectScope, watch } from 'vue'
32import { expect, it, vi } from 'vitest'
33import { mockSyncCollectionOptions } from '../../db/tests/utils'
34import { useLiveQuery } from '../src/useLiveQuery'
35​
36type Row = { id: string; value: number }
37type Snapshot = Array<[string, number]>
38​
39const histories: ReadonlyArray<{
40 name: string
41 initial: Array<Row>
42 change: { type: `insert` | `update` | `delete`; value: Row }
43}> = [
44 {
45 name: `insert`,
46 initial: [
47 { id: `1`, value: 1 },
48 { id: `2`, value: 2 },
49 ],
50 change: { type: `insert`, value: { id: `3`, value: 3 } },
51 },
52 {
53 name: `update`,
54 initial: [
55 { id: `1`, value: 1 },
56 { id: `2`, value: 2 },
57 ],
58 change: { type: `update`, value: { id: `1`, value: 4 } },
59 },
60 {
61 name: `delete`,
62 initial: [
63 { id: `1`, value: 1 },
64 { id: `2`, value: 2 },
65 { id: `3`, value: 3 },
66 ],
67 change: { type: `delete`, value: { id: `2`, value: 2 } },
68 },
70​
71const cases = histories.flatMap((history) =>
72 ([`collection`, `query`] as const).map((input) => ({ ...history, input })),
74​
75function snapshot(rows: Iterable<Row>): Snapshot {
76 return [...rows].map(({ id, value }) => [id, value])
78​
79it.each(cases)(
80 `publishes one coherent Vue data snapshot for a source $name through $input`,
81 async ({ name, initial, change, input }) => {
82 const source = createCollection(
83 mockSyncCollectionOptions<Row>({
84 id: `vue-publication-${name}-${input}`,
85 getKey: (row) => row.id,
86 initialData: initial,
87 }),
88 )
89 const scope = effectScope()
90 const expectedBefore = snapshot(initial)
91 let resultCollection: { value: unknown } | undefined
92 let primaryFailure: unknown
93 try {
94 const result = scope.run(() =>
95 input === `collection`
96 ? useLiveQuery(source)
97 : useLiveQuery((q) =>
98 q.from({ items: source }).select(({ items }) => ({
99 id: items.id,
100 value: items.value,
101 })),
102 ),
103 )!
104 resultCollection = result.collection
105 await vi.waitFor(() =>
106 expect(snapshot(result.data.value)).toEqual(expectedBefore),
107 )
108​
109 const observed: Array<{
110 publicData: Snapshot
111 sourceAtCallback: Snapshot
112 }> = []
113 scope.run(() =>
114 watch(
115 () => snapshot(result.data.value),
116 (publicData) => {
117 observed.push({
118 publicData,
119 sourceAtCallback: snapshot(source.values()),
120 })
121 },
122 { flush: `sync` },
123 ),
124 )
125​
126 source.utils.begin()
127 source.utils.write(change)
128 source.utils.commit()
129​
130 const expectedAfter = snapshot(source.values())
131 expect(expectedAfter).not.toEqual(expectedBefore)
132 for (const { publicData, sourceAtCallback } of observed) {
133 expect(sourceAtCallback).toEqual(expectedAfter)
134 expect([expectedBefore, expectedAfter]).toContainEqual(publicData)
135 }
136 expect(observed).toHaveLength(1)
137 expect(snapshot(result.data.value)).toEqual(expectedAfter)
138 expect(observed.at(-1)?.publicData).toEqual(expectedAfter)
139 } catch (error) {
140 primaryFailure = error
141 }
142 const cleanupErrors: Array<unknown> = []
143 let liveQueryCollection: typeof source | null = null
144 if (resultCollection) {
145 try {
146 liveQueryCollection = resultCollection.value as typeof source | null
147 } catch (error) {
148 cleanupErrors.push(error)
149 }
150 }
151 try {
152 scope.stop()
153 } catch (error) {
154 cleanupErrors.push(error)
155 }
156 if (liveQueryCollection && liveQueryCollection !== source) {
157 try {
158 await liveQueryCollection.cleanup()
159 } catch (error) {
160 cleanupErrors.push(error)
161 }
162 }
163 try {
164 await source.cleanup()
165 } catch (error) {
166 cleanupErrors.push(error)
167 }
168 if (cleanupErrors.length > 0) {
169 throw new AggregateError(
170 primaryFailure === undefined
171 ? cleanupErrors
172 : [primaryFailure, ...cleanupErrors],
173 `Vue publication oracle cleanup failed`,
174 { cause: primaryFailure },
175 )
176 }
177 if (primaryFailure !== undefined) throw primaryFailure
178 },