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