Open History to see the last commit
1/**
2 * The shared local-declaration model receives both mounted browser hooks and
3 * real React server rendering. Server rendering never subscribes, so a passing
4 * mounted admission check cannot stand in for its cached-snapshot read.
5 *
6 * Each independent option/presence history preloads one real source and query,
7 * attempts the second config twice, then reads again with the original config.
8 * Admission and exact original keys/ordinary row values are the comparison cuts.
9 * The source-ID owner separately checks mounted inline retention. These drivers
10 * do not claim hydrateRoot scheduling or reactive-framework option semantics.
11 */
12import { act, cleanup, renderHook } from '@testing-library/react'
13import { renderToString } from 'react-dom/server'
14import { Suspense } from 'react'
15import { DbClient, Query, collectionOptions } from '@tanstack/db'
16import { afterAll, expect, test, vi } from 'vitest'
17import { DbProvider } from '../src/DbProvider'
18import { useLiveQuery } from '../src/useLiveQuery'
19import { useLiveSuspenseQuery } from '../src/useLiveSuspenseQuery'
20import {
21 cacheOptionDeclarations,
22 cacheOptionHistories,
23 cacheOptionReach,
24 cacheOptionReachStates,
25 checkCacheOptionAdmission,
26 checkCacheOptionRows,
27 conflictingCacheOptions,
28} from '../../db/tests/live-query-cache-options-oracle'
29import { declareOracle } from '../../db/tests/oracle-declaration'
30import { createOracleReach } from '../../db/tests/oracle-reach'
31import { withOracleCleanup } from '../../db/tests/utils'
32import type { CacheRow } from '../../db/tests/live-query-cache-options-oracle'
33
34declareOracle({
35 check: [checkCacheOptionAdmission, checkCacheOptionRows],
36 model: [conflictingCacheOptions],
37 grammar: [cacheOptionHistories],
38})
39const paths = [`client-render`, `suspense-render`, `server-render`] as const
40const reaches = Object.fromEntries(
41 paths.map((path) => [
42 path,
43 createOracleReach(`React cache options ${path}`, [
44 `admission`,
45 `retry`,
46 `original-reuse`,
47 ...(path !== `server-render` ? [`settled-client-rows`] : []),
48 ...cacheOptionReachStates,
49 ]),
50 ]),
51)
52afterAll(() => {
53 for (const reach of Object.values(reaches)) reach.assertReached()
54 if (process.env.TANSTACK_DB_ORACLE_STATISTICS === `1`)
55 console.info(
56 `React cache option reach`,
57 Object.fromEntries(
58 Object.entries(reaches).map(([path, reach]) => [
59 path,
60 Object.fromEntries(reach.counts()),
61 ]),
62 ),
63 )
64})
65
66test.each(
67 cacheOptionHistories.flatMap((history) =>
68 paths.map((path) => ({ history, path })),
69 ),
70)(`React cache admission %j`, async ({ history, path }) => {
71 const reach = reaches[path]!
72 reach.beginHistory()
73 const client = new DbClient()
74 const rows: Array<CacheRow> = [
75 { id: `one`, label: `first` },
76 { id: `two`, label: `peer` },
77 ]
78 const source = client.collection(
79 collectionOptions(`react-cache-options`, () => ({
80 getKey: (row: CacheRow) => row.id,
81 sync: {
82 sync: ({ begin, write, commit, markReady }) => {
83 begin()
84 for (const value of rows)
85 write({ type: `insert`, value: { ...value } })
86 commit()
87 markReady()
88 },
89 },
90 })),
91 )
92 const query = new Query().from({ row: source })
93 const [firstOptions, secondOptions] = cacheOptionDeclarations(history)
94 // Runtime schema declaration identity is intentional here; this driver makes
95 // no claim about public hook schema typing or schema transformation.
96 const first = {
97 query,
98 getKey: firstOptions!.getKey,
99 queryKey: firstOptions!.queryKey,
100 }
101 const second = {
102 query,
103 getKey: secondOptions!.getKey,
104 queryKey: secondOptions!.queryKey,
105 }
106 Object.assign(first, { schema: firstOptions!.schema })
107 Object.assign(second, { schema: secondOptions!.schema })
108
109 const unmounts: Array<() => void> = []
110 const settledReads: Array<() => void> = []
111 const render = (options: typeof first, declaration: 0 | 1) => {
112 if (path === `server-render`) {
113 vi.stubGlobal(`window`, undefined)
114 function Consumer() {
115 const result = useLiveQuery(options)
116 if (declaration === 0 || !conflictingCacheOptions(history))
117 checkCacheOptionRows(
118 Array.from(result.state, ([key, value]) => ({ key, value })),
119 rows,
120 history.getKey[declaration],
121 )
122 return <span>{result.data.map((row) => row.label).join(`,`)}</span>
123 }
124 const html = renderToString(
125 <DbProvider client={client}>
126 <Consumer />
127 </DbProvider>,
128 )
129 expect(html).toContain(`first,peer`)
130 } else {
131 const useQuery = path.startsWith(`suspense`)
132 ? useLiveSuspenseQuery
133 : useLiveQuery
134 const result = renderHook(() => useQuery(options), {
135 wrapper: ({ children }) => (
136 <DbProvider client={client}>
137 <Suspense fallback={null}>{children}</Suspense>
138 </DbProvider>
139 ),
140 })
141 unmounts.push(result.unmount)
142 if (declaration === 0 || !conflictingCacheOptions(history)) {
143 const checkRows = () =>
144 checkCacheOptionRows(
145 Array.from(result.result.current.state, ([key, value]) => ({
146 key,
147 value,
148 })),
149 rows,
150 history.getKey[declaration],
151 )
152 checkRows()
153 settledReads.push(checkRows)
154 }
155 }
156 }
157 await withOracleCleanup(async () => {
158 await client.preloadLiveQuery(first)
159 for (let attempt = 0; attempt < 2; attempt++) {
160 for (const state of cacheOptionReach(history)) reach.reach(state)
161 checkCacheOptionAdmission(() => render(second, 1), history)
162 reach.reach(attempt === 0 ? `admission` : `retry`)
163 }
164 render(first, 0)
165 reach.reach(`original-reuse`)
166 if (path !== `server-render`) {
167 // Admission stays synchronous. The receiving row law also applies after
168 // React commits the cached seed-to-live handoff in its native scheduler.
169 await act(async () => {})
170 for (const checkRows of settledReads) checkRows()
171 reach.reach(`settled-client-rows`)
172 }
173 }, [
174 () => vi.unstubAllGlobals(),
175 () =>
176 act(async () => {
177 await withOracleCleanup(() => {}, [
178 ...unmounts.map((unmount) => () => unmount()),
179 // Testing Library also owns roots whose initial render threw before
180 // renderHook could return an unmount handle.
181 () => cleanup(),
182 () => client.cleanup(),
183 ])
184 }),
185 ])
186})