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

infinite-query-render-cuts.test.tsx

322 lines10.1 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 )
173 useLayoutEffect(() => {
174 commits.push({
175 minimum,
176 status: result.status,
177 ranks: result.data.map((row) => row.rank),
178 })
179 })
180 if (suspend) throw gate
181 return null
182 }
183​
184 const view = render(
185 <Suspense fallback={null}>
186 <Query minimum={0} />
187 </Suspense>,
188 )
189 cleanups.push(() => view.unmount())
190 await act(async () => {
191 await vi.advanceTimersByTimeAsync(0)
192 })
193​
194 suspend = true
195 await act(async () => {
196 view.rerender(
197 <Suspense fallback={null}>
198 <Query minimum={5} />
199 </Suspense>,
200 )
201 await vi.advanceTimersByTimeAsync(0)
202 })
203 await act(async () => {
204 await vi.advanceTimersByTimeAsync(200)
205 })
206​
207 suspend = false
208 await act(async () => {
209 release()
210 await vi.advanceTimersByTimeAsync(0)
211 })
212​
213 expect(commits.find((commit) => commit.minimum === 5)).toEqual({
214 minimum: 5,
215 status: `ready`,
216 ranks: [10, 9, 8],
217 })
218 })
219})
220​
221describe(`collections kept from an abandoned render`, () => {
222 // An eager source that writes `current` as a snapshot each time its sync
223 // run starts, so a reload serves new rows from the same source object.
224 function makeRestartableSource(initial: Array<Row>) {
225 let current = initial
226 const source = createCollection<Row>({
227 id: `infinite-render-cuts-restartable-${nextSequence()}`,
228 getKey: (row) => row.id,
229 autoIndex: `eager`,
230 defaultIndexType: BTreeIndex,
231 startSync: true,
232 sync: {
233 sync: ({ begin, write, commit, markReady }) => {
234 // The run's rows are the full state: its snapshot replaces the
235 // rows a reload keeps.
236 begin({ snapshot: true })
237 for (const row of current) write({ type: `insert`, value: row })
238 commit()
239 markReady()
240 },
241 },
242 })
243 cleanups.push(() => source.cleanup())
244 return {
245 source,
246 // A reload starts a new sync run under mounted queries; its snapshot
247 // replaces the rows.
248 restartWith: async (next: Array<Row>) => {
249 current = next
250 await source.reload()
251 },
252 }
253 }
254 const byId = (ids: Array<number>): Array<Row> =>
255 ids.map((id) => ({ id: String(id), label: `row-${id}`, rank: id }))
256​
257 it.each([`live`, `infinite`] as const)(
258 `shows the restarted source's rows when an abandoned render's query is selected again (%s)`,
259 async (hook) => {
260 // Model: after the restart the source holds ids 4-8, so the query for
261 // ranks above 2, ascending, shows ids 4 and 5 on its first page.
262 const { source, restartWith } = makeRestartableSource(
263 byId([1, 2, 3, 4, 5]),
264 )
265 const never = new Promise<void>(() => {})
266 const commits: Array<{
267 minimum: number
268 status: string
269 ids: Array<string>
270 }> = []
271 function Query({
272 minimum,
273 suspend,
274 }: {
275 minimum: number
276 suspend: boolean
277 }): ReactNode {
278 const query = (q: any) =>
279 q
280 .from({ items: source })
281 .where(({ items }: any) => gt(items.rank, minimum))
282 .orderBy(({ items }: any) => items.rank, `asc`)
283 const result: any =
284 hook === `live`
285 ? useLiveQuery((q: any) => query(q).limit(PAGE_SIZE + 1))
286 : useLiveInfiniteQuery(query, { pageSize: PAGE_SIZE })
287 useLayoutEffect(() => {
288 commits.push({
289 minimum,
290 status: result.status,
291 ids: result.data.slice(0, PAGE_SIZE).map((row: Row) => row.id),
292 })
293 })
294 if (suspend) throw never
295 return null
296 }
297 const tree = (minimum: number, suspend: boolean) => (
298 <Suspense fallback={null}>
299 <Query minimum={minimum} suspend={suspend} />
300 </Suspense>
301 )
302 const view = render(tree(0, false))
303 cleanups.push(() => view.unmount())
304 await act(async () => {})
305 // Render B and abandon it, then commit A again.
306 act(() => view.rerender(tree(2, true)))
307 act(() => view.rerender(tree(0, false)))
308 await act(async () => restartWith(byId([4, 5, 6, 7, 8])))
309 commits.length = 0
310 act(() => view.rerender(tree(2, false)))
311 await act(async () => {
312 await new Promise((resolve) => setTimeout(resolve, 0))
313 })
314​
315 expect(commits.filter((commit) => commit.minimum === 2).at(-1)).toEqual({
316 minimum: 2,
317 status: `ready`,
318 ids: [`4`, `5`],
319 })
320 },
321 )
322})