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