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

source-id-reuse.test.tsx

385 lines12.6 KB

1// Ordinary React tests for source ID reuse: a rejected render releases the sync
2// deferral it acquired, so a later reader can start a shared Collection. The reuse
3// law is owned by source-id-reuse-oracle.test.tsx.
4import { act, render, renderHook, waitFor } from '@testing-library/react'
5import {
6 DbClient,
7 SourceCollectionIdReuseError,
8 collectionOptions,
9 createCollection,
10 eq,
11} from '@tanstack/db'
12import { describe, expect, it, vi } from 'vitest'
13import { Suspense } from 'react'
14import { DbProvider } from '../src/DbProvider'
15import { useLiveQuery } from '../src/useLiveQuery'
16import { useLiveSuspenseQuery } from '../src/useLiveSuspenseQuery'
17import { TestErrorBoundary, source } from './source-id-reuse-support'
18import type { Context, QueryBuilder } from '@tanstack/db'
19​
20import type { Row } from './source-id-reuse-support'
21​
22describe(`React source ID reuse`, () => {
23 it(`releases a later shared source when earlier deferred sync starts fail`, async () => {
24 const client = new DbClient()
25 const first = source(`settings`, `first`)
26 const replacement = source(`settings`, `replacement`)
27 const failedStarts: [number, number] = [0, 0]
28 const failing = ([0, 1] as const).map((index) =>
29 collectionOptions(`failing-${index}`, () => ({
30 id: `failing-${index}`,
31 getKey: (row: Row) => row.id,
32 startSync: true,
33 sync: {
34 sync: () => {
35 failedStarts[index]++
36 throw new Error(`sync ${index} failed`)
37 },
38 },
39 })),
40 )
41 let healthyStarts = 0
42 const healthy = collectionOptions(`healthy-after-failures`, () => ({
43 id: `healthy-after-failures`,
44 getKey: (row: Row) => row.id,
45 startSync: true,
46 sync: {
47 sync: ({ begin, write, commit, markReady }) => {
48 healthyStarts++
49 begin()
50 write({
51 type: `insert`,
52 value: { id: `one`, value: `healthy`, rank: 1 },
53 })
54 commit()
55 markReady()
56 },
57 },
58 }))
59 const consoleError = vi.spyOn(console, `error`).mockImplementation(() => {})
60​
61 function View({
62 current,
63 include,
64 }: {
65 current: typeof first
66 include: boolean
67 }) {
68 useLiveQuery({
69 client,
70 query: (q): QueryBuilder<Context> =>
71 include
72 ? q
73 .from({ failingA: failing[0]! })
74 .join({ failingB: failing[1]! }, ({ failingA, failingB }) =>
75 eq(failingA.id, failingB.id),
76 )
77 .join({ healthy }, ({ failingA, healthy: row }) =>
78 eq(failingA.id, row.id),
79 )
80 .join({ settings: current }, ({ failingA, settings }) =>
81 eq(failingA.id, settings.id),
82 )
83 : q.from({ settings: current }),
84 })
85 return <div>Query</div>
86 }
87​
88 try {
89 const root = render(
90 <TestErrorBoundary>
91 <View current={first} include={false} />
92 </TestErrorBoundary>,
93 )
94 await act(async () => {})
95 root.rerender(
96 <TestErrorBoundary>
97 <View current={replacement} include={true} />
98 </TestErrorBoundary>,
99 )
100 expect(root.getByText(`Rejected`)).toBeDefined()
101 expect(failedStarts).toEqual([1, 1])
102​
103 const shared = client.collection(healthy)
104 const reader = renderHook(() => useLiveQuery(shared))
105 await act(async () => {})
106 expect(reader.result.current.status).toBe(`ready`)
107 expect(reader.result.current.data[0]?.value).toBe(`healthy`)
108 expect(healthyStarts).toBe(1)
109 } finally {
110 consoleError.mockRestore()
111 }
112 })
113​
114 it(`rejects two distinct source objects with one ID in a single query`, () => {
115 const leftSource = source(`settings`, `first`)
116 const rightSource = source(`settings`, `second`)
117 expect(() =>
118 renderHook(() =>
119 useLiveQuery({
120 query: (q) =>
121 q
122 .from({ first: leftSource })
123 .join({ second: rightSource }, ({ first, second }) =>
124 eq(first.id, second.id),
125 ),
126 }),
127 ),
128 ).toThrow(SourceCollectionIdReuseError)
129 })
130​
131 it(`permits the same ID in a new hook after unmount and cleanup`, async () => {
132 const first = source(`settings`, `first`)
133 const oldHook = renderHook(() =>
134 useLiveQuery({ query: (q) => q.from({ settings: first }) }),
135 )
136 await waitFor(() =>
137 expect(oldHook.result.current.data[0]?.value).toBe(`first`),
138 )
139 const oldQuery = oldHook.result.current.collection
140 oldHook.unmount()
141 await waitFor(() => expect(oldQuery.status).toBe(`cleaned-up`))
142 await first.cleanup()
143​
144 const second = source(`settings`, `second`)
145 const newHook = renderHook(() =>
146 useLiveQuery({ query: (q) => q.from({ settings: second }) }),
147 )
148 await waitFor(() =>
149 expect(newHook.result.current.data[0]?.value).toBe(`second`),
150 )
151 })
152​
153 it(`lets a keyed query swap a source under its ID when the key changes`, async () => {
154 const first = source(`settings`, `first`)
155 const replacement = source(`settings`, `replacement`)
156 const hook = renderHook(
157 ({ current }: { current: typeof first }) =>
158 useLiveQuery({
159 queryKey: [`settings`, current === first ? 1 : 2],
160 query: (q) => q.from({ settings: current }),
161 }),
162 { initialProps: { current: first } },
163 )
164 await waitFor(() =>
165 expect(hook.result.current.data[0]?.value).toBe(`first`),
166 )
167 hook.rerender({ current: replacement })
168 await waitFor(() =>
169 expect(hook.result.current.data[0]?.value).toBe(`replacement`),
170 )
171 })
172​
173 // A Suspense mount suspends before it commits, so its retry render may
174 // reuse the cached Suspense collection instead of compiling again. With a
175 // dependency list, that retry must still claim the source's ID.
176 it(`claims a Suspense query's source when a dependency-list retry reuses its cached collection`, async () => {
177 let markFirstReady!: () => void
178 const first = createCollection<Row>({
179 id: `suspense-settings`,
180 getKey: (row) => row.id,
181 startSync: true,
182 sync: {
183 sync: ({ begin, write, commit, markReady }) => {
184 begin()
185 write({
186 type: `insert`,
187 value: { id: `one`, value: `first`, rank: 1 },
188 })
189 commit()
190 markFirstReady = markReady
191 },
192 },
193 })
194 const replacement = source(`suspense-settings`, `replacement`)
195 const labels = new Map<object, string>([
196 [first, `first`],
197 [replacement, `replacement`],
198 ])
199 const View = ({ current }: { current: typeof first }) => {
200 // A hashable dependency keys the Suspense cache; a Collection cannot.
201 const { data } = useLiveSuspenseQuery(
202 (q) => q.from({ settings: current }),
203 [labels.get(current)],
204 )
205 return <div>{data[0]?.value}</div>
206 }
207 const consoleError = vi.spyOn(console, `error`).mockImplementation(() => {})
208 try {
209 const root = render(
210 <TestErrorBoundary>
211 <Suspense fallback={<div>Loading</div>}>
212 <View current={first} />
213 </Suspense>
214 </TestErrorBoundary>,
215 )
216 expect(root.getByText(`Loading`)).toBeDefined()
217 await act(async () => markFirstReady())
218 await waitFor(() => expect(root.getByText(`first`)).toBeDefined())
219​
220 root.rerender(
221 <TestErrorBoundary>
222 <Suspense fallback={<div>Loading</div>}>
223 <View current={replacement} />
224 </Suspense>
225 </TestErrorBoundary>,
226 )
227 expect(root.getByText(`Rejected`)).toBeDefined()
228 } finally {
229 consoleError.mockRestore()
230 }
231 })
232​
233 it(`claims a Suspense query's source when a dependency-list hook mounts from a sibling's cached collection`, async () => {
234 const first = source(`sibling-suspense`, `first`)
235 const replacement = source(`sibling-suspense`, `replacement`)
236 const labels = new Map<object, string>([
237 [first, `first`],
238 [replacement, `replacement`],
239 ])
240 const View = ({ current }: { current: typeof first }) => {
241 // A hashable dependency keys the Suspense cache; a Collection cannot.
242 const { data } = useLiveSuspenseQuery(
243 (q) => q.from({ settings: current }),
244 [labels.get(current)],
245 )
246 return <div>{data[0]?.value}</div>
247 }
248 const tree = (second: typeof first) => (
249 <>
250 <Suspense fallback={<div>Loading</div>}>
251 <View current={first} />
252 </Suspense>
253 <TestErrorBoundary>
254 <Suspense fallback={<div>Loading</div>}>
255 <View current={second} />
256 </Suspense>
257 </TestErrorBoundary>
258 </>
259 )
260 const consoleError = vi.spyOn(console, `error`).mockImplementation(() => {})
261 try {
262 const root = render(tree(first))
263 await waitFor(() => expect(root.getAllByText(`first`)).toHaveLength(2))
264 root.rerender(tree(replacement))
265 expect(root.getByText(`Rejected`)).toBeDefined()
266 } finally {
267 consoleError.mockRestore()
268 }
269 })
270​
271 it(`permits independent client scopes to use the same ID`, async () => {
272 const firstClient = new DbClient()
273 const secondClient = new DbClient()
274 const first = source(`settings`, `first`)
275 const second = source(`settings`, `second`)
276 const firstHook = renderHook(() =>
277 useLiveQuery({
278 client: firstClient,
279 query: (q) => q.from({ settings: first }),
280 }),
281 )
282 const secondHook = renderHook(() =>
283 useLiveQuery({
284 client: secondClient,
285 query: (q) => q.from({ settings: second }),
286 }),
287 )
288​
289 await waitFor(() => {
290 expect(firstHook.result.current.data[0]?.value).toBe(`first`)
291 expect(secondHook.result.current.data[0]?.value).toBe(`second`)
292 })
293 })
294​
295 it(`keeps separate client-scoped Suspense hooks bound to their own sources`, async () => {
296 const client = new DbClient()
297 const first = source(`settings`, `first`)
298 const second = source(`settings`, `second`)
299 const View = ({ current }: { current: typeof first }) => {
300 const { data } = useLiveSuspenseQuery({
301 client,
302 query: (q) => q.from({ settings: current }),
303 })
304 return <div>{data[0]?.value}</div>
305 }
306 const firstView = render(
307 <Suspense fallback={<div>First loading</div>}>
308 <View current={first} />
309 </Suspense>,
310 )
311 await waitFor(() => expect(firstView.getByText(`first`)).toBeDefined())
312 const secondView = render(
313 <Suspense fallback={<div>Second loading</div>}>
314 <View current={second} />
315 </Suspense>,
316 )
317 await waitFor(() => expect(secondView.getByText(`second`)).toBeDefined())
318 })
319​
320 it(`keeps a client-scoped Suspense retry bound to its new source`, async () => {
321 const client = new DbClient()
322 const first = source(`settings`, `first`)
323 const second = source(`settings`, `second`)
324 const never = new Promise<void>(() => {})
325 const View = ({
326 current,
327 suspend,
328 }: {
329 current: typeof first
330 suspend: boolean
331 }) => {
332 const { data } = useLiveSuspenseQuery({
333 client,
334 query: (q) => q.from({ settings: current }),
335 })
336 if (suspend) throw never
337 return <div>{data[0]?.value}</div>
338 }
339 const root = render(
340 <Suspense fallback={<div>Loading</div>}>
341 <View current={first} suspend={true} />
342 </Suspense>,
343 )
344 expect(root.getByText(`Loading`)).toBeDefined()
345 root.rerender(
346 <Suspense fallback={<div>Loading</div>}>
347 <View current={second} suspend={false} />
348 </Suspense>,
349 )
350 await waitFor(() => expect(root.getByText(`second`)).toBeDefined())
351 })
352​
353 it(`remembers IDs across DbProvider client switches`, async () => {
354 const firstClient = new DbClient()
355 const secondClient = new DbClient()
356 const first = source(`settings`, `first`)
357 const otherScope = source(`settings`, `other`)
358 const replacement = source(`settings`, `replacement`)
359 const View = ({ current }: { current: typeof first }) => {
360 const { data } = useLiveQuery({
361 query: (q) => q.from({ settings: current }),
362 })
363 return <div>{data[0]?.value}</div>
364 }
365 const root = render(
366 <DbProvider client={firstClient}>
367 <View current={first} />
368 </DbProvider>,
369 )
370 await waitFor(() => expect(root.getByText(`first`)).toBeDefined())
371 root.rerender(
372 <DbProvider client={secondClient}>
373 <View current={otherScope} />
374 </DbProvider>,
375 )
376 await waitFor(() => expect(root.getByText(`other`)).toBeDefined())
377 expect(() =>
378 root.rerender(
379 <DbProvider client={firstClient}>
380 <View current={replacement} />
381 </DbProvider>,
382 ),
383 ).toThrow(SourceCollectionIdReuseError)
384 })
385})