Open History to see the last commit
1/**
2 * End-to-end SSR β hydration tests for solid-query.
3 *
4 * The fixture app in `fixtures/hydration/` is built with vite (server,
5 * streaming-server, and hydratable client bundles). SSR runs in a node
6 * subprocess so `solid-js` resolves to its server build; the resulting HTML
7 * (including Solid's serialized hydration payload) is then hydrated in this
8 * jsdom process with the real `hydrate()` from `@solidjs/web`.
9 */
10import { hydrate as hydrateQueryClient } from '@tanstack/query-core'
11import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
12import {
13 applyChunks,
14 bootstrapHydrationGlobals,
15 buildFixture,
16 cleanupFixture,
17 microtasks,
18 tick,
19} from './hydration-utils'
20import type { ClientBundle, Harness } from './hydration-utils'
21β
22let harness: Harness
23let bundle: ClientBundle
24β
25beforeAll(async () => {
26 harness = buildFixture()
27 bundle = (await import(
28 /* @vite-ignore */ harness.clientBundleUrl
29 )) as ClientBundle
30}, 180_000)
31β
32afterAll(() => {
33 cleanupFixture(harness)
34})
35β
36describe('SSR hydration', () => {
37 it('server render produces data and content-addressed cache payloads', () => {
38 const { string } = harness.report
39 // The placeholder query must NOT fetch during SSR: the data compute
40 // serves the placeholder before the fetch-pull branch, so the
41 // placeholder itself is the render output.
42 expect(string.counts).toEqual({
43 fresh: 1,
44 stale: 1,
45 placeholder: 0,
46 prefetched: 1,
47 })
48 expect(string.html).toContain('fresh-server')
49 expect(string.html).toContain('stale-server')
50 // Cache entries ride Solid's hydration registry content-addressed by
51 // query hash (`sq:<hash>` β { data, t }) β `t` (dataUpdatedAt) lets
52 // the hydrating client reconstruct the entry with staleness intact,
53 // and hash addressing means coverage is the cache's, not the rendered
54 // tree's. There is no separate dehydration channel...
55 expect(string.html).toMatch(
56 /sq:\[\\"fresh\\"\]"\]=[^<]*data:"fresh-server"/,
57 )
58 expect(string.html).toMatch(
59 /sq:\[\\"stale\\"\]"\]=[^<]*data:"stale-server"/,
60 )
61 expect(string.html).toMatch(/\{data:"fresh-server",t:\d+\}/)
62 // Content addressing covers the whole cache: this query was prefetched
63 // during SSR and never rendered by any component, yet it transfers.
64 // (It serializes at fetch-dispatch time as a promise ref β the key
65 // registers up front and the payload streams in a later fulfillment
66 // script, so the two are asserted separately.)
67 expect(string.html).toMatch(/sq:\[\\"prefetched\\"\]/)
68 expect(string.html).toMatch(/\{data:"prefetched-server",t:\d+\}/)
69 expect(string.html).not.toContain('dehydratedAt')
70 // ...and the per-observer-result hydrationData copy is gone.
71 expect(string.html).not.toContain('hydrationData')
72β
73 // Meta guards serialize SETTLED state only (status|isFetching|isSuccess|
74 // isFetchedAfterMount from the fixture's #meta span). Boundaries hold
75 // until async settles; meta must honor the same contract β a transient
76 // 'pending'/'fetching'/isFetchedAfterMount-true here would contradict
77 // what the hydrating client computes from the primed cache.
78 const meta = /<span id="meta"[^>]*>(.*?)<\/span>/.exec(string.html)![1]!
79 expect(meta.replace(/<!--[^>]*-->/g, '')).toBe('success|false|true|false')
80β
81 // Cross-cache aggregates (useIsFetching) serialize the hydration-time
82 // truth: the hydrating client's own fetches are held inside the window
83 // and primed entries land settled, so it can only ever compute 0 at
84 // claim time β any other serialized value is a structural mismatch in
85 // waiting (a server-side in-flight count does not transfer).
86 const global = /<span id="global"[^>]*>(.*?)<\/span>/.exec(string.html)![1]!
87 expect(global.replace(/<!--[^>]*-->/g, '')).toBe('0')
88β
89 // Placeholder serializes AS the placeholder (data|isPlaceholderData|
90 // status): no boundary hold, the status face masks to 'success' on
91 // both sides, and the hydrating client computes the identical
92 // placeholder from its unprimed cache β no mismatch, no undermining
93 // of the streamed payload (a placeholder derive settles synchronously,
94 // so its node serializes nothing and the client fetches after its
95 // window closes).
96 const ph = /<span id="ph"[^>]*>(.*?)<\/span>/.exec(string.html)![1]!
97 expect(ph.replace(/<!--[^>]*-->/g, '')).toBe(
98 'placeholder-value|true|success',
99 )
100 })
101β
102 it('finishes a render that reads a disabled query', () => {
103 // A disabled query has nothing in flight, nothing cached, and nothing
104 // that can enable it or write the cache before the render finishes, so
105 // a server read of it has nothing to wait on. Its idle state is the
106 // settled SSR truth: the render must complete and serialize that,
107 // rather than park the reader the way the client does (where a later
108 // enable, refetch or cache write revives the compute). Rendered
109 // without a boundary, so parking cannot hide as a fallback.
110 const { disabled } = harness.report
111 expect(disabled.finished).toBe(true)
112 expect(disabled.fetches).toBe(0)
113 const out = /<div [^>]*id="out"[^>]*>(.*?)<\/div>/.exec(disabled.html)![1]!
114 expect(out.replace(/<!--[^>]*-->/g, '')).toBe('undefined|pending|false')
115 })
116β
117 it('clears the per-request cache when the render disposes', () => {
118 // The provider's dispose-time teardown (cancel + clear) must leave
119 // nothing behind: user-configured finite gcTime schedules timers on
120 // fetched queries, and without the clear those timers pin the
121 // per-request client (and everything its queries closed over) alive
122 // until they fire.
123 expect(harness.report.string.cacheEmptyAfterDispose).toBe(true)
124 expect(harness.report.stream.cacheEmptyAfterDispose).toBe(true)
125 })
126β
127 it('keeps filtered queries out of the payload via shouldDehydrateQuery', () => {
128 const { filteredHtml } = harness.report.string
129 // The filtered client renders the data into the HTML as usual...
130 expect(filteredHtml).toContain('stale-server')
131 // ...but the standard dehydrate filter gates the registry, so the
132 // stale query's cache entry never ships,
133 expect(filteredHtml).not.toMatch(/sq:\[\\"stale\\"\]/)
134 // while unfiltered queries transfer exactly as before β including the
135 // never-rendered prefetch.
136 expect(filteredHtml).toMatch(
137 /sq:\[\\"fresh\\"\]"\]=[^<]*data:"fresh-server"/,
138 )
139 expect(filteredHtml).toMatch(/sq:\[\\"prefetched\\"\]/)
140 })
141β
142 it('hydration primes the query cache and refetches only per staleness rules', async () => {
143 const { string } = harness.report
144 const app = bundle.createApp()
145 const container = document.createElement('div')
146 document.body.appendChild(container)
147 bootstrapHydrationGlobals()
148 container.innerHTML = string.html
149β
150 // jsdom does not execute scripts inserted via innerHTML; replay them in
151 // document order the way a browser would.
152 for (const script of Array.from(container.querySelectorAll('script'))) {
153 if (script.textContent) {
154 window.eval(script.textContent)
155 }
156 script.remove()
157 }
158β
159 const dispose = app.mount(container)
160β
161 try {
162 // Cache must be warm within microtasks of hydration (each hook
163 // primes from its own node entry at setup, before a browser would
164 // paint): same data and the server's dataUpdatedAt β `t` rides the
165 // serialized root, and priming goes through hydrate() newer-wins
166 // semantics.
167 await microtasks()
168 const serverFresh = string.queries.find(
169 (q) => q.queryHash === '["fresh"]',
170 )!
171 const freshState = app.queryClient.getQueryState(['fresh'])
172 expect(freshState?.data).toBe('fresh-server')
173 expect(freshState?.dataUpdatedAt).toBe(serverFresh.state.dataUpdatedAt)
174β
175 const staleState = app.queryClient.getQueryState(['stale'])
176 expect(staleState?.data).toBe('stale-server')
177β
178 // The DOM keeps showing the server-rendered fresh data.
179 expect(container.querySelector('#fresh')?.textContent).toBe(
180 'fresh-server',
181 )
182β
183 // The immediately-stale query refetches on mount (normal staleness
184 // rules) and updates the DOM with client data.
185 await vi.waitFor(() => {
186 expect(app.counts.stale).toBe(1)
187 expect(container.querySelector('#stale')?.textContent).toBe(
188 'stale-client',
189 )
190 })
191β
192 // ...while the fresh query was never fetched again.
193 expect(app.counts.fresh).toBe(0)
194 expect(container.querySelector('#fresh')?.textContent).toBe(
195 'fresh-server',
196 )
197β
198 // The placeholder query hydrated showing its placeholder (identical
199 // to the server HTML), then fetched for real once its window closed
200 // (its node had no serialized entry) and swapped in data.
201 await vi.waitFor(() => {
202 expect(app.counts.placeholder).toBe(1)
203 expect(container.querySelector('#ph')?.textContent).toContain(
204 'placeholder-resolved-client',
205 )
206 })
207β
208 // The serialized observer results no longer carry a hydrationData
209 // copy at all β the node payload is the only transport.
210 const registry = (globalThis as any)._$HY.r as Record<string, any>
211 const lingering = Object.values(registry).filter((entry) => {
212 const value = entry != null && entry.s === 1 ? entry.v : entry
213 return (
214 value != null && typeof value === 'object' && 'hydrationData' in value
215 )
216 })
217 expect(lingering).toEqual([])
218 } finally {
219 dispose()
220 container.remove()
221 }
222 })
223β
224 it('a component mounted after hydration adopts a prefetched-never-rendered payload', async () => {
225 // The server prefetched ['prefetched'] in a loader-style call and no
226 // component rendered it. Content-addressed registry entries outlive
227 // the hydration window (the Solid Router pattern), so a subtree
228 // mounted later β lazy route, user interaction β adopts the server's
229 // payload instead of refetching.
230 const { string } = harness.report
231 const app = bundle.createApp()
232 const container = document.createElement('div')
233 document.body.appendChild(container)
234 bootstrapHydrationGlobals()
235 container.innerHTML = string.html
236 for (const script of Array.from(container.querySelectorAll('script'))) {
237 if (script.textContent) window.eval(script.textContent)
238 script.remove()
239 }
240β
241 const dispose = app.mount(container)
242 try {
243 // Nothing consumed the prefetched entry during hydration: the cache
244 // has no such query and the registry still holds the payload.
245 await tick(30)
246 expect(app.queryClient.getQueryState(['prefetched'])).toBeUndefined()
247β
248 // Mount the consumer long after hydration completed.
249 app.showLate()
250 await vi.waitFor(() => {
251 expect(container.querySelector('#late')?.textContent).toBe(
252 'prefetched-server',
253 )
254 })
255 // Adopted with zero client fetches β and staleness metadata came
256 // across with it.
257 expect(app.counts.prefetched).toBe(0)
258 const serverPrefetched = string.queries.find(
259 (q) => q.queryHash === '["prefetched"]',
260 )!
261 expect(app.queryClient.getQueryState(['prefetched'])?.dataUpdatedAt).toBe(
262 serverPrefetched.state.dataUpdatedAt,
263 )
264 } finally {
265 dispose()
266 container.remove()
267 }
268 })
269β
270 it('applies cache writes that land between priming and subscriber attach', async () => {
271 const { string } = harness.report
272 const app = bundle.createApp()
273 const container = document.createElement('div')
274 document.body.appendChild(container)
275 bootstrapHydrationGlobals()
276 container.innerHTML = string.html
277 for (const script of Array.from(container.querySelectorAll('script'))) {
278 if (script.textContent) window.eval(script.textContent)
279 script.remove()
280 }
281β
282 const dispose = app.mount(container)
283 try {
284 // Synchronously after hydrate() returns β before the subscriber attach
285 // microtask has run β write newer data into the cache, the way an
286 // already-live component (or a settling mutation) would.
287 app.queryClient.setQueryData(['fresh'], 'updated-client')
288β
289 // The hydrated component must pick the write up when its subscriber
290 // attaches, without any refetch.
291 await vi.waitFor(() => {
292 expect(container.querySelector('#fresh')?.textContent).toBe(
293 'updated-client',
294 )
295 })
296 expect(app.counts.fresh).toBe(0)
297 } finally {
298 dispose()
299 container.remove()
300 }
301 })
302β
303 it('coexists with a host that primes the cache through its own hydrate() channel', async () => {
304 // TanStack Start-style hosts apply a dehydrated QueryClient via
305 // query-core hydrate() before Solid's DOM hydrate() runs. The hooks'
306 // own node priming then re-applies the same entries; pin that the
307 // second application is silent (hydrate() only writes strictly-newer
308 // data, so equal dataUpdatedAt is a no-op with no observer
309 // notification) and that attach coordination still resolves.
310 const { string } = harness.report
311 const app = bundle.createApp()
312 const container = document.createElement('div')
313 document.body.appendChild(container)
314 bootstrapHydrationGlobals()
315 container.innerHTML = string.html
316 for (const script of Array.from(container.querySelectorAll('script'))) {
317 if (script.textContent) window.eval(script.textContent)
318 script.remove()
319 }
320β
321 // The host's channel primes first, with the exact server states.
322 hydrateQueryClient(app.queryClient, {
323 queries: string.queries.map((q) => ({
324 queryKey: q.queryKey,
325 queryHash: q.queryHash,
326 state: q.state,
327 dehydratedAt: q.state.dataUpdatedAt,
328 })),
329 mutations: [],
330 })
331β
332 // Record every cache update from here on: the provider channel's
333 // re-priming must not produce any for the already-primed fresh query.
334 const updatedHashes: Array<string> = []
335 const unsubscribe = app.queryClient.getQueryCache().subscribe((event) => {
336 if (event.type === 'updated') updatedHashes.push(event.query.queryHash)
337 })
338β
339 const dispose = app.mount(container)
340 try {
341 // Attach coordination is not deadlocked by the pre-primed cache: the
342 // channel still yields, waiters resolve, the observer subscribes.
343 await vi.waitFor(() => {
344 expect(
345 app.queryClient
346 .getQueryCache()
347 .find({ queryKey: ['fresh'] })
348 ?.getObserversCount(),
349 ).toBe(1)
350 })
351β
352 // Double-priming was silent: no state write, no observer churn, no
353 // refetch of the fresh query. (The stale query's mount refetch per
354 // normal staleness rules is the only update source.)
355 expect(updatedHashes.filter((hash) => hash === '["fresh"]')).toEqual([])
356 expect(app.counts.fresh).toBe(0)
357 expect(container.querySelector('#fresh')?.textContent).toBe(
358 'fresh-server',
359 )
360 await vi.waitFor(() => {
361 expect(app.counts.stale).toBe(1)
362 })
363β
364 // And the component is live afterwards.
365 app.queryClient.setQueryData(['fresh'], 'updated-client')
366 await vi.waitFor(() => {
367 expect(container.querySelector('#fresh')?.textContent).toBe(
368 'updated-client',
369 )
370 })
371 } finally {
372 unsubscribe()
373 dispose()
374 container.remove()
375 }
376 })
377})
378β
379describe('streaming SSR hydration', () => {
380 function splitStream() {
381 const { chunks } = harness.report.stream
382 const idx = chunks.findIndex((c) => c.payload.includes('feed-server'))
383 expect(idx).toBeGreaterThan(0)
384 return {
385 phase1: chunks.slice(0, idx).map((c) => c.payload),
386 phase2: chunks.slice(idx).map((c) => c.payload),
387 }
388 }
389β
390 it('primes shell-flush entries at shell hydration, not at stream end', async () => {
391 const { phase1, phase2 } = splitStream()
392 const app = bundle.createStreamApp()
393 const container = document.createElement('div')
394 document.body.appendChild(container)
395 bootstrapHydrationGlobals()
396β
397 // Deliver only the first flush; the stream stays open (phase2 is never
398 // applied until later), so anything observable now provably did not
399 // wait for stream end.
400 applyChunks(container, phase1)
401 const dispose = app.mount(container)
402β
403 try {
404 // The header query settled before the first flush, so its node
405 // entry rides the same chunks β the hook primes from it within
406 // microtasks of shell hydration, with the server's dataUpdatedAt
407 // intact (`t` on the serialized root).
408 await microtasks()
409 const serverHeader = harness.report.stream.queries.find(
410 (q) => q.queryHash === '["header"]',
411 )!
412 const headerState = app.queryClient.getQueryState(['header'])
413 expect(headerState?.data).toBe('header-server')
414 expect(headerState?.dataUpdatedAt).toBe(serverHeader.state.dataUpdatedAt)
415 // Fresh (staleTime 60s) hydrated data β no mount refetch.
416 expect(app.counts.header).toBe(0)
417 // The observer attached (per-query, not at hydration end): the query
418 // is active while the stream is still open.
419 expect(
420 app.queryClient
421 .getQueryCache()
422 .find({ queryKey: ['header'] })
423 ?.getObserversCount(),
424 ).toBe(1)
425β
426 // The feed entry rides the second flush; it must not be primed early.
427 expect(app.queryClient.getQueryState(['feed'])).toBeUndefined()
428β
429 // When the boundary's flush arrives, its entry arrives with it.
430 applyChunks(container, phase2)
431 await vi.waitFor(() => {
432 expect(app.queryClient.getQueryState(['feed'])?.data).toBe(
433 'feed-server',
434 )
435 expect(container.querySelector('#feed')?.textContent).toBe(
436 'feed-server',
437 )
438 })
439 expect(app.counts.feed).toBe(0)
440 await tick(30)
441 } finally {
442 dispose()
443 container.remove()
444 }
445 })
446β
447 it('primes everything when hydration starts after the whole stream arrived (buffered replay)', async () => {
448 // Hydration long after the stream completed (slow client / late
449 // script): every node entry is already settled in the registry when
450 // the components mount, so each hook primes synchronously at setup
451 // from its own entry. All entries primed, all observers attached, no
452 // refetches β and the takeover recompute at hydration end must not
453 // race ahead of a not-yet-primed hook (the `primed` gate).
454 const { chunks } = harness.report.stream
455 const app = bundle.createStreamApp()
456 const container = document.createElement('div')
457 document.body.appendChild(container)
458 bootstrapHydrationGlobals()
459β
460 // Deliver the ENTIRE stream before mounting.
461 applyChunks(
462 container,
463 chunks.map((c) => c.payload),
464 )
465 const dispose = app.mount(container)
466β
467 try {
468 await microtasks()
469 // Both queries primed with the server's exact states, from the single
470 // conflated snapshot.
471 for (const key of ['header', 'feed'] as const) {
472 const server = harness.report.stream.queries.find(
473 (q) => q.queryHash === `["${key}"]`,
474 )!
475 const state = app.queryClient.getQueryState([key])
476 expect(state?.data).toBe(`${key}-server`)
477 expect(state?.dataUpdatedAt).toBe(server.state.dataUpdatedAt)
478 }
479 // Both observers attach (the done snapshot was not dropped, waiters
480 // resolved) and neither fresh query refetches.
481 await vi.waitFor(() => {
482 expect(
483 app.queryClient
484 .getQueryCache()
485 .find({ queryKey: ['header'] })
486 ?.getObserversCount(),
487 ).toBe(1)
488 expect(
489 app.queryClient
490 .getQueryCache()
491 .find({ queryKey: ['feed'] })
492 ?.getObserversCount(),
493 ).toBe(1)
494 })
495 expect(app.counts).toEqual({ header: 0, feed: 0 })
496β
497 // And the late-hydrated components are live.
498 app.queryClient.setQueryData(['feed'], 'updated-client')
499 await vi.waitFor(() => {
500 expect(container.querySelector('#feed')?.textContent).toBe(
501 'updated-client',
502 )
503 })
504 } finally {
505 dispose()
506 container.remove()
507 }
508 })
509β
510 // Hydration does not wait for the page: once the root pass is over, a
511 // node outside every still-pending streamed boundary answers client
512 // writes. The header's boundary has resumed, so a cache write while the
513 // feed keeps the stream open reaches its DOM immediately, and so does a
514 // mid-stream refetch (observers attach per-query as the channel primes).
515 // The pending feed boundary is untouched and hydrates from the server
516 // payload when its chunk lands.
517 it('cache writes during the open stream commit immediately outside pending boundaries', async () => {
518 const { phase1, phase2 } = splitStream()
519 const app = bundle.createStreamApp()
520 const container = document.createElement('div')
521 document.body.appendChild(container)
522 bootstrapHydrationGlobals()
523β
524 // Deliver the shell and the fast boundary only; the slow boundary keeps
525 // the page in "hydration in progress" state.
526 applyChunks(container, phase1)
527 const dispose = app.mount(container)
528β
529 try {
530 expect(container.querySelector('#header')?.textContent).toBe(
531 'header-server',
532 )
533 // The slow section still shows its fallback.
534 expect(container.querySelector('#feed')).toBeNull()
535β
536 // A write while the stream is open reaches the cache and the
537 // resumed header's DOM at once.
538 app.queryClient.setQueryData(['header'], 'updated-client')
539 await vi.waitFor(() => {
540 expect(container.querySelector('#header')?.textContent).toBe(
541 'updated-client',
542 )
543 })
544 expect(app.queryClient.getQueryData(['header'])).toBe('updated-client')
545 expect(container.querySelector('#feed')).toBeNull()
546β
547 // An invalidation while the stream is open refetches immediately
548 // (the observer is subscribed) and its result commits as it lands.
549 void app.queryClient.invalidateQueries({ queryKey: ['header'] })
550 await vi.waitFor(() => {
551 expect(container.querySelector('#header')?.textContent).toBe(
552 'header-client',
553 )
554 })
555 expect(app.counts.header).toBe(1)
556 expect(container.querySelector('#feed')).toBeNull()
557β
558 // The late boundary hydrates from the server payload, closing the
559 // stream; the header keeps its client state.
560 applyChunks(container, phase2)
561 await vi.waitFor(() => {
562 expect(container.querySelector('#feed')?.textContent).toBe(
563 'feed-server',
564 )
565 })
566 expect(container.querySelector('#header')?.textContent).toBe(
567 'header-client',
568 )
569 expect(app.counts.feed).toBe(0)
570β
571 // And fully live from then on.
572 app.queryClient.setQueryData(['header'], 'updated-live')
573 await vi.waitFor(() => {
574 expect(container.querySelector('#header')?.textContent).toBe(
575 'updated-live',
576 )
577 })
578 } finally {
579 dispose()
580 container.remove()
581 }
582 })
583})