Open History to see the last commit
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 { declareOracle } from '../../db/tests/oracle-declaration'
34import { mockSyncCollectionOptions } from '../../db/tests/utils'
35import { useLiveQuery } from '../src/useLiveQuery'
36
37type Row = { id: string; value: number }
38type Snapshot = Array<[string, number]>
39
40const histories: ReadonlyArray<{
41 name: string
42 initial: Array<Row>
43 change: { type: `insert` | `update` | `delete`; value: Row }
44}> = [
45 {
46 name: `insert`,
47 initial: [
48 { id: `1`, value: 1 },
49 { id: `2`, value: 2 },
50 ],
51 change: { type: `insert`, value: { id: `3`, value: 3 } },
52 },
53 {
54 name: `update`,
55 initial: [
56 { id: `1`, value: 1 },
57 { id: `2`, value: 2 },
58 ],
59 change: { type: `update`, value: { id: `1`, value: 4 } },
60 },
61 {
62 name: `delete`,
63 initial: [
64 { id: `1`, value: 1 },
65 { id: `2`, value: 2 },
66 { id: `3`, value: 3 },
67 ],
68 change: { type: `delete`, value: { id: `2`, value: 2 } },
69 },
70]
71
72const cases = histories.flatMap((history) =>
73 ([`collection`, `query`] as const).map((input) => ({ ...history, input })),
74)
75
76function snapshot(rows: Iterable<Row>): Snapshot {
77 return [...rows].map(({ id, value }) => [id, value])
78}
79
80/**
81 * The refinement check at the synchronous watcher cut: every public value the
82 * watcher saw is the preceding or the final snapshot, the source already held
83 * the final rows at each callback, the watcher fired once, and the final
84 * public result equals the final snapshot.
85 */
86function expectCoherentPublication(
87 expected: { before: Snapshot; after: Snapshot },
88 observed: ReadonlyArray<{ publicData: Snapshot; sourceAtCallback: Snapshot }>,
89 finalData: Snapshot,
90): void {
91 for (const { publicData, sourceAtCallback } of observed) {
92 expect(sourceAtCallback).toEqual(expected.after)
93 expect([expected.before, expected.after]).toContainEqual(publicData)
94 }
95 expect(observed).toHaveLength(1)
96 expect(finalData).toEqual(expected.after)
97 expect(observed.at(-1)?.publicData).toEqual(expected.after)
98}
99
100it.each(cases)(
101 `publishes one coherent Vue data snapshot for a source $name through $input`,
102 async ({ name, initial, change, input }) => {
103 const source = createCollection(
104 mockSyncCollectionOptions<Row>({
105 id: `vue-publication-${name}-${input}`,
106 getKey: (row) => row.id,
107 initialData: initial,
108 }),
109 )
110 const scope = effectScope()
111 const expectedBefore = snapshot(initial)
112 let resultCollection: { value: unknown } | undefined
113 let primaryFailure: unknown
114 try {
115 const result = scope.run(() =>
116 input === `collection`
117 ? useLiveQuery(source)
118 : useLiveQuery((q) =>
119 q.from({ items: source }).select(({ items }) => ({
120 id: items.id,
121 value: items.value,
122 })),
123 ),
124 )!
125 resultCollection = result.collection
126 await vi.waitFor(() =>
127 expect(snapshot(result.data.value)).toEqual(expectedBefore),
128 )
129
130 const observed: Array<{
131 publicData: Snapshot
132 sourceAtCallback: Snapshot
133 }> = []
134 scope.run(() =>
135 watch(
136 () => snapshot(result.data.value),
137 (publicData) => {
138 observed.push({
139 publicData,
140 sourceAtCallback: snapshot(source.values()),
141 })
142 },
143 { flush: `sync` },
144 ),
145 )
146
147 source.utils.begin()
148 source.utils.write(change)
149 source.utils.commit()
150
151 const expectedAfter = snapshot(source.values())
152 expect(expectedAfter).not.toEqual(expectedBefore)
153 expectCoherentPublication(
154 { before: expectedBefore, after: expectedAfter },
155 observed,
156 snapshot(result.data.value),
157 )
158 } catch (error) {
159 primaryFailure = error
160 }
161 const cleanupErrors: Array<unknown> = []
162 let liveQueryCollection: typeof source | null = null
163 if (resultCollection) {
164 try {
165 liveQueryCollection = resultCollection.value as typeof source | null
166 } catch (error) {
167 cleanupErrors.push(error)
168 }
169 }
170 try {
171 scope.stop()
172 } catch (error) {
173 cleanupErrors.push(error)
174 }
175 if (liveQueryCollection && liveQueryCollection !== source) {
176 try {
177 await liveQueryCollection.cleanup()
178 } catch (error) {
179 cleanupErrors.push(error)
180 }
181 }
182 try {
183 await source.cleanup()
184 } catch (error) {
185 cleanupErrors.push(error)
186 }
187 if (cleanupErrors.length > 0) {
188 throw new AggregateError(
189 primaryFailure === undefined
190 ? cleanupErrors
191 : [primaryFailure, ...cleanupErrors],
192 `Vue publication oracle cleanup failed`,
193 { cause: primaryFailure },
194 )
195 }
196 if (primaryFailure !== undefined) throw primaryFailure
197 },
198)
199
200declareOracle({ check: [expectCoherentPublication] })