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

QueryClientProvider.tsx

271 lines11.3 KB

1import { createContext, isHydratable, onCleanup, useContext } from 'solid-js'
2import { REVALIDATE_HEADER, getHydrationWriter } from '@solidjs/web'
3import { hydrate } from '@tanstack/query-core'
4import { subscribeFlightData } from '@solidjs/web/server-functions'
5import type { DehydratedState, Query } from '@tanstack/query-core'
6import type { QueryClient } from './QueryClient'
7import type { JSX } from '@solidjs/web'
8​
9const isServer = typeof window === 'undefined'
10​
11/**
12 * Namespace prefix for cache entries in Solid's hydration registry β€” the
13 * registry is shared with positional node ids and other libraries'
14 * content-addressed keys (Solid Router uses its own cache keys), so query
15 * hashes get their own prefix.
16 */
17export const HYDRATION_KEY_PREFIX = 'sq:'
18​
19/**
20 * The query cache's single-flight source id. Mutation responses can fold
21 * fresh data for multiple caches at once (Solid's multi-source
22 * single-flight protocol); this is the slice the query cache claims β€” the
23 * provider subscribes its consumer under it, and server collectors
24 * register under it to produce the data:
25 *
26 * ```ts
27 * import { registerFlightDataSource } from '@solidjs/web/server-functions/server'
28 * import { FLIGHT_DATA_SOURCE, dehydrate } from '@tanstack/solid-query'
29 *
30 * registerFlightDataSource(FLIGHT_DATA_SOURCE, async (event, outcome) => {
31 * // rebuild the data for outcome.targetUrl into a QueryClient, then
32 * return dehydrate(queryClient)
33 * })
34 * ```
35 *
36 * The slice's payload is a `DehydratedState`; the provider consumes it
37 * with `hydrate()`, so every mounted query on those keys updates before
38 * the mutation's promise resolves β€” no follow-up refetches.
39 *
40 * A mutation can additionally declare its invalidation SCOPE with
41 * `X-Revalidate` keys (the `revalidate` option of Solid's `reload`/
42 * `redirect`/`respond` response helpers). The payload covers the slice of
43 * that scope the server could recompute; whatever a declared key matches
44 * beyond it is swept client-side (see the consumer below). The transport
45 * delivers a response carrying keys to the consumer whether or not the
46 * collector contributed a slice β€” with no slice, the whole scope is swept.
47 */
48export const FLIGHT_DATA_SOURCE = 'sq'
49​
50/**
51 * The reserved `X-Revalidate` key meaning every entry: `revalidate: '*'`
52 * on Solid's response helpers. Named so a host that keys its cache
53 * differently still reads the same spelling as "all".
54 */
55const REVALIDATE_ALL = '*'
56​
57/**
58 * The client half of key-scoped invalidation. A mutation declares its
59 * invalidation scope with `X-Revalidate` keys; the flight payload covers
60 * the part of that scope the server's collector recomputed (typically the
61 * target page's loader graph). Whatever a declared key matches BEYOND the
62 * payload β€” parameterized instances only this client holds, queries no
63 * loader owns β€” is invalidated here: active queries refetch in the
64 * background, inactive ones are marked stale for their next mount. This
65 * mirrors how Solid Router consumes the same header for its own cache.
66 *
67 * A key matches by queryKey prefix β€” `revalidate: 'users'` sweeps every
68 * query whose key begins with `'users'`. Payload-covered hashes are exempt:
69 * they hydrated with fresh data a moment ago, and refetching them would
70 * spend the round trip single flight just saved. The payload is absent
71 * when the server folded no slice for this cache (no collector registered,
72 * a redirect leaving the app) β€” then nothing is covered and the declared
73 * scope is swept in full.
74 *
75 * The header's three states are three scopes. Absent: the mutation
76 * declared nothing, and this cache is left as it is β€” the route data the
77 * router reloads is its own business, and a response helper without
78 * `revalidate` is a host-default that Solid Router reads as "everything"
79 * but the query cache does not presume. Empty (`revalidate: []`): nothing,
80 * explicitly. The reserved key `*` (`revalidate: '*'`): every query in the
81 * cache, minus what the payload covered β€” the way to say "all" to any
82 * host, rather than relying on one host's default.
83 * @param client - The `QueryClient` whose queries are invalidated.
84 * @param payload - The dehydrated slice the response carried for this cache, if any.
85 * @param response - The mutation response, read for its `X-Revalidate` header.
86 */
87function sweepRevalidatedQueries(
88 client: QueryClient,
89 payload: DehydratedState | undefined,
90 response: Response,
91): void {
92 const declared = response.headers.get(REVALIDATE_HEADER)
93 if (declared === null) return
94 const covered = new Set(
95 payload?.queries.map((query) => query.queryHash) ?? [],
96 )
97 const uncovered = (query: Query) => !covered.has(query.queryHash)
98 const keys = declared.split(',')
99 // Background refetch failures surface through the queries' own error
100 // states; an unhandled rejection here would fail the mutation instead.
101 if (keys.includes(REVALIDATE_ALL)) {
102 client.invalidateQueries({ predicate: uncovered }).catch(() => undefined)
103 return
104 }
105 for (const key of keys) {
106 // An empty key is the empty declaration's spelling, not a prefix that
107 // happens to match everything.
108 if (!key) continue
109 client
110 .invalidateQueries({ queryKey: [key], predicate: uncovered })
111 .catch(() => undefined)
112 }
114​
115export const QueryClientContext = createContext<(() => QueryClient) | null>(
116 null,
118​
119/**
120 * The `useQueryClient` primitive returns the current `QueryClient` instance.
121 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
122 * be used.
123 * @returns The current `QueryClient` instance.
124 * @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the
125 * component tree.
126 */
127export const useQueryClient = (queryClient?: QueryClient) => {
128 if (queryClient) {
129 return queryClient
130 }
131 const client = useContext(QueryClientContext)
132​
133 if (!client) {
134 throw new Error('No QueryClient set, use QueryClientProvider to set one')
135 }
136​
137 return client()
139​
140/**
141 * The props accepted by `QueryClientProvider`.
142 */
143export type QueryClientProviderProps = {
144 /**
145 * **Required**
146 *
147 * The `QueryClient` instance to provide.
148 */
149 client: QueryClient
150 /**
151 * The components that get access to the provided `QueryClient`.
152 */
153 children?: JSX.Element
155​
156/**
157 * Server side of hydration: serialize every query the request touches into
158 * Solid's hydration registry, content-addressed by query hash (the Solid
159 * Router `query()` pattern). Serialization happens at fetch-DISPATCH time β€”
160 * synchronously, while the request's serialization context is live β€” by
161 * handing seroval the fetch promise; it streams the `{ data, t }` payload
162 * whenever the fetch settles. Settled entries (initialData, setQueryData,
163 * loader prefetches that already landed) serialize their value directly.
164 *
165 * Content addressing is what makes this cover MORE than rendered
166 * components: a query prefetched in a loader and never read by any
167 * component still transfers, and any client hook (hydrating or mounted
168 * long after) finds it by hash. One entry per hash regardless of how many
169 * hooks read it; the payload object is the same reference the data nodes
170 * serialize, so seroval's cross-reference dedupe emits it once.
171 * @param client - The request's `QueryClient`.
172 */
173function serializeCacheOnServer(client: QueryClient): void {
174 const writer = getHydrationWriter()
175 if (!writer || !writer.async || !isHydratable()) return
176​
177 const cache = client.getQueryCache()
178 // The standard dehydrate filter gates the wire here too, so apps keep
179 // sensitive or oversized queries out of the HTML with the same option
180 // they'd pass any other transport.
181 const shouldDehydrateQuery =
182 client.getDefaultOptions().dehydrate?.shouldDehydrateQuery
183 const seen = new Set<string>()
184 const serializeQuery = (query: Query<any, any, any, any>) => {
185 if (seen.has(query.queryHash)) return
186 // Consulted per cache event until it passes, so a filter that rejects
187 // pending queries (e.g. the core default) still admits the settled
188 // value if it lands while the request's serialization context is live.
189 if (shouldDehydrateQuery && !shouldDehydrateQuery(query)) return
190 const state = query.state
191 if (state.status === 'success') {
192 seen.add(query.queryHash)
193 writer.write(HYDRATION_KEY_PREFIX + query.queryHash, {
194 data: state.data,
195 t: state.dataUpdatedAt,
196 })
197 } else if (state.fetchStatus !== 'idle') {
198 // Serialize the PROMISE now, while the context is live β€” the settle
199 // event fires from IO, where no request context exists anymore.
200 const promise = query.promise as Promise<unknown> | undefined
201 if (!promise) return
202 seen.add(query.queryHash)
203 writer.write(
204 HYDRATION_KEY_PREFIX + query.queryHash,
205 promise.then(() => ({
206 data: query.state.data,
207 t: query.state.dataUpdatedAt,
208 })),
209 )
210 }
211 }
212​
213 for (const query of cache.getAll()) serializeQuery(query)
214 onCleanup(cache.subscribe((event) => serializeQuery(event.query)))
216​
217/**
218 * Provides the QueryClient and manages its mount lifecycle. On the server
219 * it also registers the cache serializer above; on the client, hooks prime
220 * the cache from their hash-keyed registry entries themselves (see
221 * `useBaseQuery`) and the provider subscribes the cache's single-flight
222 * consumer: mutation responses carrying a `FLIGHT_DATA_SOURCE` slice (a
223 * `DehydratedState` produced by a server collector registered under the
224 * same id) hydrate this client before the mutation's promise resolves.
225 * Subscribing is inert when no server collector exists β€” the server just
226 * folds nothing β€” so it is unconditional. One consumer per source: with
227 * nested providers, the innermost mounted one owns the slice.
228 * @param props - The `client` to provide, and the `children` that get access to it.
229 * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`.
230 */
231export const QueryClientProvider = (
232 props: QueryClientProviderProps,
233): JSX.Element => {
234 props.client.mount()
235 onCleanup(() => props.client.unmount())
236 if (isServer) {
237 serializeCacheOnServer(props.client)
238 // Render disposal ends the request: abort what's still in flight and
239 // drop the cache so user-configured finite gcTime timers can't pin
240 // the per-request client (and whatever its queries closed over) until
241 // they fire. Serialized promises are already in seroval's hands, so
242 // clearing here can't affect the streamed payload.
243 onCleanup(() => {
244 props.client.cancelQueries().catch(() => undefined)
245 props.client.clear()
246 })
247 } else {
248 // Client-only: the server's consumer registry is module state shared
249 // across requests β€” registering there would leak between them.
250 onCleanup(
251 subscribeFlightData<DehydratedState>(
252 FLIGHT_DATA_SOURCE,
253 (data, context) => {
254 // `data` is undefined for a response that carried metadata but
255 // no slice for this cache.
256 if (data) hydrate(props.client, data)
257 // Fresh data first, then the declared-scope sweep: stale marks
258 // land synchronously, refetches run in the background β€” the
259 // mutation's promise never waits on them.
260 sweepRevalidatedQueries(props.client, data, context.response)
261 },
262 ),
263 )
264 }
265​
266 return (
267 <QueryClientContext value={() => props.client}>
268 {props.children}
269 </QueryClientContext>
270 )