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

bound-schema-options-oracle.test.tsx

262 lines9.6 KB

1/**
2 * React's two config hooks receive the shared mutation-schema binding law.
3 * Native act establishes committed hook data; the common driver also captures
4 * the Collection immediately when update returns. Schema source passthrough,
5 * retained mutations and identity replacement use the same independent model.
6 * Controlled Collections supply no provider, SSR, or concurrent-render claim.
7 */
8import { act, renderHook } from '@testing-library/react'
9import { afterAll, expect, test } from 'vitest'
10import { useLiveQuery } from '../src/useLiveQuery'
11import { useLiveSuspenseQuery } from '../src/useLiveSuspenseQuery'
12import { declareOracle } from '../../db/tests/oracle-declaration'
13import { createOracleReach } from '../../db/tests/oracle-reach'
14import {
15 boundSchemaHistories,
16 boundSchemaModes,
17 boundSchemaReachStates,
18 checkBoundSchemaMutation,
19 checkBoundSchemaRows,
20 checkBoundSchemaValues,
21 modelBoundSchemaBinding,
22 modelBoundSchemaLabel,
23 modelBoundSchemaMutation,
24 modelBoundSchemaRows,
25} from '../../db/tests/live-query-bound-options-oracle'
26import { runBoundSchemaHistory } from '../../db/tests/live-query-bound-options-support'
27import type { ExtractContext } from '@tanstack/db'
28import type { BoundSchemaNativeHost } from '../../db/tests/live-query-bound-options-support'
29import type { BoundSchemaObservation } from '../../db/tests/live-query-bound-options-oracle'
30​
31for (const hook of [`live`, `suspense`] as const) {
32 const reach = createOracleReach(
33 `React ${hook} schema binding`,
34 boundSchemaReachStates,
35 )
36 let ran = false
37 afterAll(() => {
38 if (!ran) return
39 reach.assertReached()
40 if (process.env.TANSTACK_DB_ORACLE_STATISTICS === `1`)
41 console.info(
42 `React ${hook} schema binding reach`,
43 Object.fromEntries(reach.counts()),
44 )
45 })
46 test.each(boundSchemaHistories)(
47 `React ${hook} binds mutation schemas %j`,
48 async (history) => {
49 ran = true
50 const host: BoundSchemaNativeHost = {
51 mount: (input) => {
52 type QueryContext = ExtractContext<
53 ReturnType<ReturnType<typeof input>[`query`]>
54 >
55 const mounted = renderHook(
56 (props: { revision: number; proposed: boolean }) =>
57 hook === `live`
58 ? useLiveQuery<QueryContext>(input(props))
59 : useLiveSuspenseQuery<QueryContext>(input(props)),
60 { initialProps: { revision: 0, proposed: false } },
61 )
62 return {
63 current: () => mounted.result.current,
64 rerender: mounted.rerender,
65 flush: async (action) => {
66 await act(() => {
67 action?.()
68 })
69 },
70 unmount: mounted.unmount,
71 }
72 },
73 }
74 await runBoundSchemaHistory(history, host, reach)
75 },
76 )
78​
79// These controls send deliberately wrong public observations to the same
80// judgment used by every native receiver. An earlier wrong immediate result
81// cannot be hidden by correct later host data. Unordered rows may be reordered,
82// but occurrences, ordinary fields, keys and handler payloads remain exact.
83function observationFromModel(
84 expected: ReturnType<typeof modelBoundSchemaMutation>,
85): BoundSchemaObservation {
86 const rows = () =>
87 expected.rows.map(({ key, value }) => ({ key, value: { ...value } }))
88 return {
89 immediate: rows(),
90 collection: rows(),
91 state: rows(),
92 data: expected.rows.map(({ value }) => ({ ...value })),
93 mutations: expected.mutations.map((mutation) => ({
94 ...mutation,
95 original: { ...mutation.original },
96 modified: { ...mutation.modified },
97 changes: { ...mutation.changes },
98 })),
99 }
101test.each(boundSchemaHistories)(
102 `schema judgment rejects wrong binding and mutation observations %j`,
103 (history) => {
104 const base = [
105 { id: `one`, label: ` untouched first `, rank: 1 },
106 { id: `peer`, label: ` untouched peer `, rank: 2 },
107 ]
108 for (const phase of [`initial`, `retained`, `rebound`] as const) {
109 const expected = modelBoundSchemaMutation(history, phase, base)
110 const binding = modelBoundSchemaBinding(history, phase)
111 const faults: Array<{
112 label: string
113 observation: BoundSchemaObservation
114 }> = []
115 for (const schema of boundSchemaModes) {
116 if (schema === binding.schema) continue
117 const wrong = modelBoundSchemaMutation(
118 { ...history, firstSchema: schema, nextSchema: schema },
119 phase,
120 base,
121 )
122 faults.push({
123 label: `wrong schema ${schema}`,
124 observation: observationFromModel(wrong),
125 })
126 }
127 const immediate = observationFromModel(expected)
128 immediate.immediate = immediate.immediate.map((row, index) =>
129 index === 0
130 ? { ...row, value: { ...row.value, label: `wrong immediate` } }
131 : row,
132 )
133 faults.push({
134 label: `earlier mismatch with correct later state`,
135 observation: immediate,
136 })
137 for (const field of [`immediate`, `collection`, `state`] as const) {
138 const undefinedField = observationFromModel(expected)
139 undefinedField[field] = undefinedField[field].map((row) => ({
140 ...row,
141 value: { ...row.value, unexpected: undefined },
142 }))
143 faults.push({
144 label: `extra undefined field in ${field}`,
145 observation: undefinedField,
146 })
147 }
148 const undefinedData = observationFromModel(expected)
149 undefinedData.data = undefinedData.data.map((row) => ({
150 ...row,
151 unexpected: undefined,
152 }))
153 faults.push({
154 label: `extra undefined field in host data`,
155 observation: undefinedData,
156 })
157 const undefinedMutation = observationFromModel(expected)
158 undefinedMutation.mutations = undefinedMutation.mutations.map(
159 (mutation) => ({
160 ...mutation,
161 changes: { ...mutation.changes, unexpected: undefined },
162 }),
163 )
164 faults.push({
165 label: `extra undefined field in handler`,
166 observation: undefinedMutation,
167 })
168 const collection = observationFromModel(expected)
169 collection.collection = collection.collection.slice(0, 1)
170 faults.push({ label: `missing Collection peer`, observation: collection })
171 const state = observationFromModel(expected)
172 state.state = [...state.state, state.state[1]!]
173 faults.push({ label: `duplicate state row`, observation: state })
174 const data = observationFromModel(expected)
175 data.data = data.data.map((row, index) =>
176 index === 1 ? { ...row, extra: `unexpected` } : row,
177 )
178 faults.push({ label: `extra host data field`, observation: data })
179 const key = observationFromModel(expected)
180 key.state = key.state.map((row) => ({
181 ...row,
182 key: `wrong-${String(row.key)}`,
183 }))
184 faults.push({ label: `wrong public keys`, observation: key })
185 const missing = observationFromModel(expected)
186 missing.mutations = []
187 faults.push({ label: `missing handler mutation`, observation: missing })
188 const duplicate = observationFromModel(expected)
189 duplicate.mutations = [...duplicate.mutations, duplicate.mutations[0]!]
190 faults.push({
191 label: `duplicate handler mutation`,
192 observation: duplicate,
193 })
194 const original = observationFromModel(expected)
195 original.mutations = original.mutations.map((mutation) => ({
196 ...mutation,
197 original: { ...mutation.original, label: mutation.modified.label },
198 }))
199 faults.push({
200 label: `original replaced with modified`,
201 observation: original,
202 })
203 if (binding.schema !== `absent`) {
204 const raw = observationFromModel(expected)
205 const label = modelBoundSchemaLabel(`absent`, history.input)
206 raw.mutations = raw.mutations.map((mutation) => ({
207 ...mutation,
208 modified: { ...mutation.modified, label },
209 changes: { ...mutation.changes, label },
210 }))
211 faults.push({
212 label: `raw handler payload with transformed public rows`,
213 observation: raw,
214 })
215 }
216 for (const fault of faults)
217 expect(
218 () =>
219 checkBoundSchemaMutation(fault.observation, expected, fault.label),
220 fault.label,
221 ).toThrow(fault.label)
222 const reordered = observationFromModel(expected)
223 for (const field of [`immediate`, `collection`, `state`] as const)
224 reordered[field] = [...reordered[field]].reverse()
225 reordered.data = [...reordered.data].reverse()
226 checkBoundSchemaMutation(reordered, expected, `allowed unordered rows`)
227​
228 const source = modelBoundSchemaRows(base, binding.key)
229 const transformed = source.map((row) => ({
230 ...row,
231 value: {
232 ...row.value,
233 label: modelBoundSchemaLabel(`trim`, history.input),
234 },
235 }))
236 expect(() =>
237 checkBoundSchemaRows(transformed, source, `sync rows stay raw`),
238 ).toThrow(`sync rows stay raw`)
239 expect(() =>
240 checkBoundSchemaValues(
241 transformed.map(({ value }) => value),
242 source.map(({ value }) => value),
243 `sync host data stays raw`,
244 ),
245 ).toThrow(`sync host data stays raw`)
246 checkBoundSchemaRows([...source].reverse(), source, `raw unordered rows`)
247 checkBoundSchemaValues(
248 source.map(({ value }) => value).reverse(),
249 source.map(({ value }) => value),
250 `raw unordered host data`,
251 )
252 }
253 },
255declareOracle({
256 grammar: [boundSchemaHistories],
257 check: [
258 checkBoundSchemaMutation,
259 checkBoundSchemaRows,
260 checkBoundSchemaValues,
261 ],
262})