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

infinite-query-render-cuts-oracle.test.tsx

260 lines9.2 KB

1/**
2 * React's pre-commit cut for `useLiveInfiniteQuery`.
3 *
4 * React can render a component without committing it: a Suspense render that
5 * throws, a StrictMode double render, or a retry after an earlier attempt was
6 * discarded. The shared infinite-query suite cannot express that cut, because
7 * Vue's setup is its commit. These laws belong to the React driver:
8 *
9 * - A live-query Collection starts no provider work before it has a
10 * subscriber or a preload. A render that never commits therefore starts no
11 * acquisition attempt on an on-demand source, whether a query callback or a
12 * supplied collection reads it, directly or through a live-query Collection.
13 * A StrictMode double render requests the first window once, after commit,
14 * and its first commit is a loading, unpublished window. The hook matches
15 * useLiveQuery under the same history in every case.
16 * - When GC has reclaimed an abandoned render's collection, the retry's first
17 * commit is the ready first page, after a fresh mount and after a mounted
18 * component's suspended update.
19 * - The hook agrees with `useLiveQuery`: for the same synchronous source, both
20 * commit the same ready rows first.
21 * - A collection kept from an abandoned render is reused only while it can
22 * still serve the query. When its source restarts after cleanup, that
23 * collection is in terminal error, so selecting its query again shows the
24 * restarted source's rows, ready, as useLiveQuery does.
25 * - A mounted replacement whose synchronous startup throws delivers that error
26 * to the error boundary, as useLiveQuery does. React retries the render; a
27 * retry that reused the failed render's collection would commit
28 * `status: error` instead.
29 *
30 * Expectations come from the source rows, page size, request counts, and
31 * useLiveQuery under the same history, never from the hook's controller state.
32 */
33import { StrictMode, Suspense, useLayoutEffect } from 'react'
34import { act, render, renderHook, waitFor } from '@testing-library/react'
35import { afterEach, describe, expect, it } from 'vitest'
36import {
37 BTreeIndex,
38 createCollection,
39 createLiveQueryCollection,
40} from '@tanstack/db'
41import { makeInfiniteOnDemandSource } from '../../db/tests/conformance/infinite-on-demand'
42import { declareOracle } from '../../db/tests/oracle-declaration'
43import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
44import { useLiveQuery } from '../src/useLiveQuery'
45import {
46 PAGE_SIZE,
47 cleanups,
48 makeSyncSource,
49 nextSequence,
50 rows,
51} from './infinite-query-render-cuts-support'
52import type { Row } from './infinite-query-render-cuts-support'
53import type { ReactNode } from 'react'
54​
55afterEach(async () => {
56 // Unmount hooks before cleaning up the sources they read.
57 for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
58})
59​
60type HookName = `live` | `infinite`
61type InputForm = `query` | `supplied`
62​
63// Counts source acquisitions. The load never settles, so only the request
64// itself is observed. A wrapped source sits behind a live-query Collection,
65// which does not copy its source's sync mode.
66function makeCountingOnDemandSource(wrapped: boolean) {
67 let loads = 0
68 const source = createCollection<Row>({
69 id: `infinite-render-cuts-remote-${nextSequence()}`,
70 getKey: (row) => row.id,
71 syncMode: `on-demand`,
72 autoIndex: `eager`,
73 defaultIndexType: BTreeIndex,
74 sync: {
75 sync: ({ markReady }) => {
76 markReady()
77 return {
78 loadSubset: () => {
79 loads++
80 return new Promise<void>(() => {})
81 },
82 }
83 },
84 },
85 })
86 cleanups.push(() => source.cleanup())
87 if (!wrapped) return { target: source as any, loads: () => loads }
88 const intermediate = createLiveQueryCollection({
89 query: (q) =>
90 q.from({ row: source }).orderBy(({ row }) => row.rank, `desc`),
91 startSync: false,
92 gcTime: 1,
93 })
94 cleanups.push(() => intermediate.cleanup())
95 return { target: intermediate as any, loads: () => loads }
97​
98// The same read through either hook. A query callback asks useLiveQuery for
99// the infinite hook's first window, so both build the same physical query.
100function useHookUnderTest(hook: HookName, form: InputForm, target: any) {
101 if (form === `supplied`) {
102 return hook === `live`
103 ? useLiveQuery(target)
104 : useLiveInfiniteQuery(target, { pageSize: PAGE_SIZE })
105 }
106 return hook === `live`
107 ? useLiveQuery((q: any) =>
108 q
109 .from({ items: target })
110 .orderBy(({ items }: any) => items.rank, `desc`)
111 .limit(PAGE_SIZE + 1),
112 )
113 : useLiveInfiniteQuery(
114 (q: any) =>
115 q
116 .from({ items: target })
117 .orderBy(({ items }: any) => items.rank, `desc`),
118 { pageSize: PAGE_SIZE },
119 )
121​
122async function acquisitionsForAbandonedRender(
123 hook: HookName,
124 form: InputForm,
125 wrapped: boolean,
126): Promise<number> {
127 const { target, loads } = makeCountingOnDemandSource(wrapped)
128 const never = new Promise<void>(() => {})
129 function Abandoned(): ReactNode {
130 useHookUnderTest(hook, form, target)
131 throw never
132 }
133 const view = render(
134 <Suspense fallback={null}>
135 <Abandoned />
136 </Suspense>,
137 )
138 cleanups.push(() => view.unmount())
139 await act(async () => {
140 await new Promise((resolve) => setTimeout(resolve, 0))
141 })
142 return loads()
144​
145async function firstWindowLoadsForStrictMount(hook: HookName) {
146 const source = makeInfiniteOnDemandSource(
147 { createCollection, BTreeIndex },
148 rows(8),
149 )
150 cleanups.push(() => source.collection.cleanup())
151 const commits: Array<{ status: string; ids: Array<string> }> = []
152 const hook_ = renderHook(
153 () => {
154 const result: any = useHookUnderTest(hook, `query`, source.collection)
155 useLayoutEffect(() => {
156 commits.push({
157 status: result.status,
158 ids: result.data.slice(0, PAGE_SIZE).map((row: Row) => row.id),
159 })
160 })
161 return result
162 },
163 { wrapper: StrictMode },
164 )
165 cleanups.push(() => hook_.unmount())
166 await waitFor(() => expect(commits.length).toBeGreaterThan(0))
167 return {
168 loads: source.calls.filter((call) => call.limit === PAGE_SIZE + 1).length,
169 firstCommit: commits[0],
170 }
172​
173// The law: a render that never commits starts no acquisition, and the infinite
174// hook starts the same acquisitions as useLiveQuery under the same history.
175async function checkAbandonedRenderAcquisitions(
176 form: InputForm,
177 wrapped: boolean,
178): Promise<void> {
179 const reference = await acquisitionsForAbandonedRender(`live`, form, wrapped)
180 expect(reference).toBe(0)
181 expect(await acquisitionsForAbandonedRender(`infinite`, form, wrapped)).toBe(
182 reference,
183 )
185​
186declareOracle({ check: [checkAbandonedRenderAcquisitions] })
187​
188describe(`on-demand sources match useLiveQuery`, () => {
189 it.each([
190 { form: `query` as const, wrapped: false },
191 { form: `query` as const, wrapped: true },
192 { form: `supplied` as const, wrapped: true },
193 ])(
194 `starts no acquisition attempt for a render that never commits, as useLiveQuery does (%o)`,
195 async ({ form, wrapped }) => {
196 await checkAbandonedRenderAcquisitions(form, wrapped)
197 },
198 )
199​
200 it(`requests the first window and commits the first value as useLiveQuery does across a StrictMode double render`, async () => {
201 const reference = await firstWindowLoadsForStrictMount(`live`)
202 // No provider work before commit: the on-demand window is unpublished.
203 expect(reference.firstCommit).toEqual({ status: `loading`, ids: [] })
204 // React 19 keeps refs across the double render, so both hooks request the
205 // first window once, after commit. React 18 does not; see the coverage map.
206 expect(reference.loads).toBe(1)
207 expect(await firstWindowLoadsForStrictMount(`infinite`)).toEqual(reference)
208 })
209})
210​
211// The law: with a synchronous source, the first commit is ready and shows every
212// row in source order. This model gives that commit for `count` rows.
213function expectedReadyFirstCommit(count: number): {
214 status: string
215 ids: Array<string>
216} {
217 return { status: `ready`, ids: rows(count).map((row) => row.id) }
219​
220declareOracle({ model: [expectedReadyFirstCommit] })
221​
222describe(`agreement with useLiveQuery`, () => {
223 it(`commits the same ready rows first as useLiveQuery for a synchronous source`, async () => {
224 const source = makeSyncSource(10)
225 const firstCommit = (
226 useResult: () => { status: string; data: Array<Row> },
227 ) => {
228 const commits: Array<{ status: string; ids: Array<string> }> = []
229 const hook = renderHook(() => {
230 const result = useResult()
231 useLayoutEffect(() => {
232 commits.push({
233 status: result.status,
234 ids: result.data.map((row) => row.id),
235 })
236 })
237 return result
238 })
239 cleanups.push(() => hook.unmount())
240 return commits
241 }
242​
243 const live = firstCommit(() =>
244 useLiveQuery((q) =>
245 q.from({ row: source }).orderBy(({ row }) => row.rank, `desc`),
246 ),
247 )
248 const infinite = firstCommit(() =>
249 useLiveInfiniteQuery(
250 (q) => q.from({ row: source }).orderBy(({ row }) => row.rank, `desc`),
251 { pageSize: 20 },
252 ),
253 )
254 await waitFor(() => expect(infinite.length).toBeGreaterThan(0))
255​
256 const expected = expectedReadyFirstCommit(10)
257 expect(live[0]).toEqual(expected)
258 expect(infinite[0]).toEqual(expected)
259 })
260})