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

QueryClientProvider.tsx

246 lines10.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 */
84function sweepRevalidatedQueries(
85 client: QueryClient,
86 payload: DehydratedState | undefined,
87 response: Response,
88): void {
89 const declared = response.headers.get(REVALIDATE_HEADER)
90 if (declared === null) return
91 const covered = new Set(
92 payload?.queries.map((query) => query.queryHash) ?? [],
93 )
94 const uncovered = (query: Query) => !covered.has(query.queryHash)
95 const keys = declared.split(',')
96 // Background refetch failures surface through the queries' own error
97 // states; an unhandled rejection here would fail the mutation instead.
98 if (keys.includes(REVALIDATE_ALL)) {
99 client.invalidateQueries({ predicate: uncovered }).catch(() => undefined)
100 return
101 }
102 for (const key of keys) {
103 // An empty key is the empty declaration's spelling, not a prefix that
104 // happens to match everything.
105 if (!key) continue
106 client
107 .invalidateQueries({ queryKey: [key], predicate: uncovered })
108 .catch(() => undefined)
109 }
111​
112export const QueryClientContext = createContext<(() => QueryClient) | null>(
113 null,
115​
116export const useQueryClient = (queryClient?: QueryClient) => {
117 if (queryClient) {
118 return queryClient
119 }
120 const client = useContext(QueryClientContext)
121​
122 if (!client) {
123 throw new Error('No QueryClient set, use QueryClientProvider to set one')
124 }
125​
126 return client()
128​
129export type QueryClientProviderProps = {
130 client: QueryClient
131 children?: JSX.Element
133​
134/**
135 * Server side of hydration: serialize every query the request touches into
136 * Solid's hydration registry, content-addressed by query hash (the Solid
137 * Router `query()` pattern). Serialization happens at fetch-DISPATCH time β€”
138 * synchronously, while the request's serialization context is live β€” by
139 * handing seroval the fetch promise; it streams the `{ data, t }` payload
140 * whenever the fetch settles. Settled entries (initialData, setQueryData,
141 * loader prefetches that already landed) serialize their value directly.
142 *
143 * Content addressing is what makes this cover MORE than rendered
144 * components: a query prefetched in a loader and never read by any
145 * component still transfers, and any client hook (hydrating or mounted
146 * long after) finds it by hash. One entry per hash regardless of how many
147 * hooks read it; the payload object is the same reference the data nodes
148 * serialize, so seroval's cross-reference dedupe emits it once.
149 */
150function serializeCacheOnServer(client: QueryClient): void {
151 const writer = getHydrationWriter()
152 if (!writer || !writer.async || !isHydratable()) return
153​
154 const cache = client.getQueryCache()
155 // The standard dehydrate filter gates the wire here too, so apps keep
156 // sensitive or oversized queries out of the HTML with the same option
157 // they'd pass any other transport.
158 const shouldDehydrateQuery =
159 client.getDefaultOptions().dehydrate?.shouldDehydrateQuery
160 const seen = new Set<string>()
161 const serializeQuery = (query: Query<any, any, any, any>) => {
162 if (seen.has(query.queryHash)) return
163 // Consulted per cache event until it passes, so a filter that rejects
164 // pending queries (e.g. the core default) still admits the settled
165 // value if it lands while the request's serialization context is live.
166 if (shouldDehydrateQuery && !shouldDehydrateQuery(query)) return
167 const state = query.state
168 if (state.status === 'success') {
169 seen.add(query.queryHash)
170 writer.write(HYDRATION_KEY_PREFIX + query.queryHash, {
171 data: state.data,
172 t: state.dataUpdatedAt,
173 })
174 } else if (state.fetchStatus !== 'idle') {
175 // Serialize the PROMISE now, while the context is live β€” the settle
176 // event fires from IO, where no request context exists anymore.
177 const promise = query.promise as Promise<unknown> | undefined
178 if (!promise) return
179 seen.add(query.queryHash)
180 writer.write(
181 HYDRATION_KEY_PREFIX + query.queryHash,
182 promise.then(() => ({
183 data: query.state.data,
184 t: query.state.dataUpdatedAt,
185 })),
186 )
187 }
188 }
189​
190 for (const query of cache.getAll()) serializeQuery(query)
191 onCleanup(cache.subscribe((event) => serializeQuery(event.query)))
193​
194/**
195 * Provides the QueryClient and manages its mount lifecycle. On the server
196 * it also registers the cache serializer above; on the client, hooks prime
197 * the cache from their hash-keyed registry entries themselves (see
198 * `useBaseQuery`) and the provider subscribes the cache's single-flight
199 * consumer: mutation responses carrying a `FLIGHT_DATA_SOURCE` slice (a
200 * `DehydratedState` produced by a server collector registered under the
201 * same id) hydrate this client before the mutation's promise resolves.
202 * Subscribing is inert when no server collector exists β€” the server just
203 * folds nothing β€” so it is unconditional. One consumer per source: with
204 * nested providers, the innermost mounted one owns the slice.
205 */
206export const QueryClientProvider = (
207 props: QueryClientProviderProps,
208): JSX.Element => {
209 props.client.mount()
210 onCleanup(() => props.client.unmount())
211 if (isServer) {
212 serializeCacheOnServer(props.client)
213 // Render disposal ends the request: abort what's still in flight and
214 // drop the cache so user-configured finite gcTime timers can't pin
215 // the per-request client (and whatever its queries closed over) until
216 // they fire. Serialized promises are already in seroval's hands, so
217 // clearing here can't affect the streamed payload.
218 onCleanup(() => {
219 props.client.cancelQueries().catch(() => undefined)
220 props.client.clear()
221 })
222 } else {
223 // Client-only: the server's consumer registry is module state shared
224 // across requests β€” registering there would leak between them.
225 onCleanup(
226 subscribeFlightData<DehydratedState>(
227 FLIGHT_DATA_SOURCE,
228 (data, context) => {
229 // `data` is undefined for a response that carried metadata but
230 // no slice for this cache; `hydrate` ignores a non-object.
231 hydrate(props.client, data)
232 // Fresh data first, then the declared-scope sweep: stale marks
233 // land synchronously, refetches run in the background β€” the
234 // mutation's promise never waits on them.
235 sweepRevalidatedQueries(props.client, data, context.response)
236 },
237 ),
238 )
239 }
240​
241 return (
242 <QueryClientContext value={() => props.client}>
243 {props.children}
244 </QueryClientContext>
245 )