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

cache-options-oracle.test.tsx

179 lines6.1 KB

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