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

infinite-query-render-cuts.test.tsx

323 lines10.2 KB

1// Ordinary React tests for render cuts: a mounted replacement's startup error and
2// a collection reclaimed by GC before a Suspense retry, and a kept collection whose
3// source restarted. The render-cut laws are owned
4// by infinite-query-render-cuts-oracle.test.tsx.
5import { Suspense, useLayoutEffect } from 'react'
6import { act, render, waitFor } from '@testing-library/react'
7import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
8import { BTreeIndex, createCollection, gt } from '@tanstack/db'
9import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
10import { useLiveQuery } from '../src/useLiveQuery'
11import {
12 ErrorBoundary,
13 PAGE_SIZE,
14 cleanups,
15 makeSyncSource,
16 nextSequence,
17} from './infinite-query-render-cuts-support'
18import type { Row } from './infinite-query-render-cuts-support'
19import type { ReactNode } from 'react'
20​
21afterEach(async () => {
22 // Unmount hooks before cleaning up the sources they read.
23 for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
24})
25​
26describe(`on-demand sources match useLiveQuery`, () => {
27 it.each([`live`, `infinite`] as const)(
28 `delivers a mounted replacement's startup error to the error boundary (%s)`,
29 async (hook) => {
30 const source = makeSyncSource(4)
31 const failure = new Error(`replacement failed to start`)
32 const commits: Array<{ fail: boolean; status: string }> = []
33 const consoleError = vi
34 .spyOn(console, `error`)
35 .mockImplementation(() => {})
36 function View({ fail }: { fail: boolean }): ReactNode {
37 const query = (q: any) =>
38 q
39 .from({ items: source })
40 .fn.where(() => {
41 if (fail) throw failure
42 return true
43 })
44 .orderBy(({ items }: any) => items.rank, `desc`)
45 const result: any =
46 hook === `live`
47 ? useLiveQuery({
48 queryKey: [`startup-error`, fail],
49 query: (q: any) => query(q).limit(PAGE_SIZE + 1),
50 })
51 : useLiveInfiniteQuery(query, {
52 pageSize: PAGE_SIZE,
53 queryKey: [`startup-error`, fail],
54 })
55 useLayoutEffect(() => {
56 commits.push({ fail, status: result.status })
57 })
58 return null
59 }
60 try {
61 const view = render(
62 <ErrorBoundary>
63 <View fail={false} />
64 </ErrorBoundary>,
65 )
66 cleanups.push(() => view.unmount())
67 await waitFor(() =>
68 expect(commits.at(-1)).toEqual({ fail: false, status: `ready` }),
69 )
70 await act(async () => {
71 view.rerender(
72 <ErrorBoundary>
73 <View fail={true} />
74 </ErrorBoundary>,
75 )
76 })
77 // The error reaches the boundary; the replacement never commits.
78 expect(
79 view.getByText(`Rejected: replacement failed to start`),
80 ).toBeDefined()
81 expect(commits.filter((commit) => commit.fail)).toEqual([])
82 } finally {
83 consoleError.mockRestore()
84 }
85 },
86 )
87})
88​
89describe(`retries after GC`, () => {
90 beforeEach(() => vi.useFakeTimers())
91 afterEach(() => vi.useRealTimers())
92​
93 it(`shows the ready first page when a Suspense retry follows a GC-collected abandoned render`, async () => {
94 const source = makeSyncSource(10)
95 let suspend = true
96 let release!: () => void
97 const gate = new Promise<void>((resolve) => {
98 release = resolve
99 })
100 const commits: Array<{ status: string; ids: Array<string> }> = []
101 let abandonedCollection: { status: string } | undefined
102 let retryCollection: { status: string } | undefined
103​
104 function Query(): ReactNode {
105 const result = useLiveInfiniteQuery(
106 (q) =>
107 q.from({ items: source }).orderBy(({ items }) => items.rank, `desc`),
108 { pageSize: 3 },
109 )
110 if (suspend) {
111 abandonedCollection = result.collection as unknown as {
112 status: string
113 }
114 throw gate
115 }
116 retryCollection = result.collection as unknown as { status: string }
117 useLayoutEffect(() => {
118 commits.push({
119 status: result.status,
120 ids: result.data.map((row) => row.id),
121 })
122 })
123 return null
124 }
125​
126 const view = render(
127 <Suspense fallback={null}>
128 <Query />
129 </Suspense>,
130 )
131 cleanups.push(() => view.unmount())
132 // Let the 50 ms unsubscribed GC floor reclaim the abandoned collection.
133 await act(async () => {
134 await vi.advanceTimersByTimeAsync(100)
135 })
136​
137 suspend = false
138 await act(async () => {
139 release()
140 await vi.advanceTimersByTimeAsync(0)
141 })
142​
143 expect(abandonedCollection?.status).toBe(`cleaned-up`)
144 expect(retryCollection).not.toBe(abandonedCollection)
145 expect(commits[0]).toEqual({ status: `ready`, ids: [`1`, `2`, `3`] })
146 })
147​
148 it(`shows the ready first page when a mounted query's suspended update retries after GC`, async () => {
149 // A committed component keeps its hook refs across a suspended update. A
150 // retry that bound the update's collection after GC cleaned it up would
151 // commit an empty cleaned-up page before recovering.
152 const source = makeSyncSource(10)
153 let suspend = false
154 let release!: () => void
155 const gate = new Promise<void>((resolve) => {
156 release = resolve
157 })
158 const commits: Array<{
159 minimum: number
160 status: string
161 ranks: Array<number>
162 }> = []
163​
164 function Query({ minimum }: { minimum: number }): ReactNode {
165 const result = useLiveInfiniteQuery(
166 (q) =>
167 q
168 .from({ items: source })
169 .where(({ items }) => gt(items.rank, minimum))
170 .orderBy(({ items }) => items.rank, `desc`),
171 { pageSize: 3 },
172 [minimum],
173 )
174 useLayoutEffect(() => {
175 commits.push({
176 minimum,
177 status: result.status,
178 ranks: result.data.map((row) => row.rank),
179 })
180 })
181 if (suspend) throw gate
182 return null
183 }
184​
185 const view = render(
186 <Suspense fallback={null}>
187 <Query minimum={0} />
188 </Suspense>,
189 )
190 cleanups.push(() => view.unmount())
191 await act(async () => {
192 await vi.advanceTimersByTimeAsync(0)
193 })
194​
195 suspend = true
196 await act(async () => {
197 view.rerender(
198 <Suspense fallback={null}>
199 <Query minimum={5} />
200 </Suspense>,
201 )
202 await vi.advanceTimersByTimeAsync(0)
203 })
204 await act(async () => {
205 await vi.advanceTimersByTimeAsync(200)
206 })
207​
208 suspend = false
209 await act(async () => {
210 release()
211 await vi.advanceTimersByTimeAsync(0)
212 })
213​
214 expect(commits.find((commit) => commit.minimum === 5)).toEqual({
215 minimum: 5,
216 status: `ready`,
217 ranks: [10, 9, 8],
218 })
219 })
220})
221​
222describe(`collections kept from an abandoned render`, () => {
223 // An eager source that writes `current` as a snapshot each time its sync
224 // run starts, so a reload serves new rows from the same source object.
225 function makeRestartableSource(initial: Array<Row>) {
226 let current = initial
227 const source = createCollection<Row>({
228 id: `infinite-render-cuts-restartable-${nextSequence()}`,
229 getKey: (row) => row.id,
230 autoIndex: `eager`,
231 defaultIndexType: BTreeIndex,
232 startSync: true,
233 sync: {
234 sync: ({ begin, write, commit, markReady }) => {
235 // The run's rows are the full state: its snapshot replaces the
236 // rows a reload keeps.
237 begin({ snapshot: true })
238 for (const row of current) write({ type: `insert`, value: row })
239 commit()
240 markReady()
241 },
242 },
243 })
244 cleanups.push(() => source.cleanup())
245 return {
246 source,
247 // A reload starts a new sync run under mounted queries; its snapshot
248 // replaces the rows.
249 restartWith: async (next: Array<Row>) => {
250 current = next
251 await source.reload()
252 },
253 }
254 }
255 const byId = (ids: Array<number>): Array<Row> =>
256 ids.map((id) => ({ id: String(id), label: `row-${id}`, rank: id }))
257​
258 it.each([`live`, `infinite`] as const)(
259 `shows the restarted source's rows when an abandoned render's query is selected again (%s)`,
260 async (hook) => {
261 // Model: after the restart the source holds ids 4-8, so the query for
262 // ranks above 2, ascending, shows ids 4 and 5 on its first page.
263 const { source, restartWith } = makeRestartableSource(
264 byId([1, 2, 3, 4, 5]),
265 )
266 const never = new Promise<void>(() => {})
267 const commits: Array<{
268 minimum: number
269 status: string
270 ids: Array<string>
271 }> = []
272 function Query({
273 minimum,
274 suspend,
275 }: {
276 minimum: number
277 suspend: boolean
278 }): ReactNode {
279 const query = (q: any) =>
280 q
281 .from({ items: source })
282 .where(({ items }: any) => gt(items.rank, minimum))
283 .orderBy(({ items }: any) => items.rank, `asc`)
284 const result: any =
285 hook === `live`
286 ? useLiveQuery((q: any) => query(q).limit(PAGE_SIZE + 1))
287 : useLiveInfiniteQuery(query, { pageSize: PAGE_SIZE })
288 useLayoutEffect(() => {
289 commits.push({
290 minimum,
291 status: result.status,
292 ids: result.data.slice(0, PAGE_SIZE).map((row: Row) => row.id),
293 })
294 })
295 if (suspend) throw never
296 return null
297 }
298 const tree = (minimum: number, suspend: boolean) => (
299 <Suspense fallback={null}>
300 <Query minimum={minimum} suspend={suspend} />
301 </Suspense>
302 )
303 const view = render(tree(0, false))
304 cleanups.push(() => view.unmount())
305 await act(async () => {})
306 // Render B and abandon it, then commit A again.
307 act(() => view.rerender(tree(2, true)))
308 act(() => view.rerender(tree(0, false)))
309 await act(async () => restartWith(byId([4, 5, 6, 7, 8])))
310 commits.length = 0
311 act(() => view.rerender(tree(2, false)))
312 await act(async () => {
313 await new Promise((resolve) => setTimeout(resolve, 0))
314 })
315​
316 expect(commits.filter((commit) => commit.minimum === 2).at(-1)).toEqual({
317 minimum: 2,
318 status: `ready`,
319 ids: [`4`, `5`],
320 })
321 },
322 )
323})