Repository navigation
feat(hydrate): cache platform closure and add opt-in window reuse - #6794
Armand-Lluka wants to merge 2 commits into
Conversation
872bc7a to
3a28bcb
Compare
There was a problem hiding this comment.
Pull request overview
This PR optimizes hydrate SSR performance by avoiding repeated evaluation of the hydrate platform closure and (optionally) reusing a process-global mock window for string-based renders.
Changes:
- Cache the evaluated
hydrateAppClosure()result on the provided window and reuse it when the same window is used again. - Add
HydrateDocumentOptions.reuseWindowto reuse a per-processMockWindow(keyed byserializeShadowRoot) for string-inputhydrateDocument()/renderToString(), serializing renders through a promise queue. - Update public type declarations/documentation to describe the new
reuseWindowoption.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| src/hydrate/runner/render.ts | Adds reusable MockWindow caching and a serialized render queue behind reuseWindow. |
| src/declarations/stencil-public-compiler.ts | Documents/exposes the new reuseWindow?: boolean public option. |
| src/compiler/output-targets/dist-hydrate-script/hydrate-factory-closure.ts | Changes generated hydrate factory to cache the evaluated hydrate closure on window. |
Comments suppressed due to low confidence (1)
src/hydrate/runner/render.ts:135
runRenderonly catches synchronous errors. Ifrender(reusedWin, ...)ever rejects, the cached window won't be evicted/closed and the rejection will propagate to callers (unlike other error paths which return aHydrateResults). It would be safer to attach a.catch()to perform the same cleanup +renderCatchErrorand always resolveresults.
reusedWin = getReusableWindow(doc, opts);
return render(reusedWin, opts, results).then(() => results);
} catch (e) {
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
3a28bcb to
f150d12
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.
Suppressed comments (1)
src/hydrate/runner/render.ts:140
- The reusable window cache key is recomputed in the catch block using the (potentially mutated)
opts.serializeShadowRoot, which can cause the wrong entry to be deleted ifserializeShadowRootchanges duringrender()(or if its object key order differs). Compute the key once per render attempt and reuse it for both lookup and cleanup.
} catch (e) {
if (reusedWin) {
reusableWindows.delete(JSON.stringify(opts.serializeShadowRoot ?? null));
if (reusedWin.close) {
reusedWin.close();
05a0488 to
3fb4315
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.
Suppressed comments (2)
src/compiler/output-targets/dist-hydrate-script/hydrate-factory-closure.ts:157
- The cache guard uses a truthiness check for
__stencilHydrateApp, but the code later assumes it is callable. If something (or a previous run) sets this property to a non-function truthy value, hydration will throw when invoked. Consider guarding by function type and defining the property as non-enumerable to reduce accidental collisions.
if (!$stencilWindow.__stencilHydrateApp) {
$stencilWindow.__stencilHydrateApp = hydrateAppClosure($stencilWindow);
}
$stencilWindow.__stencilHydrateApp($stencilWindow, $stencilHydrateOpts, $stencilHydrateResults, $stencilAfterHydrate, $stencilHydrateResolve);
src/hydrate/runner/reusable-window.ts:25
- When reusing a MockWindow, this reset currently leaves MockWindow timers/event listeners and constrainTimeouts-related internal flags intact. That means a prior render can leak pending timeouts/intervals and window/document listeners into the next render, and
constrainTimeoutscan remain enabled/disabled across calls unexpectedly.
const defaults = new MockWindow(false);
resetObject(win.location, defaults.location);
resetObject(win.navigator, defaults.navigator);
win.localStorage.clear();
win.sessionStorage.clear();
3fb4315 to
3c5d23e
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.
Suppressed comments (3)
src/compiler/output-targets/dist-hydrate-script/hydrate-factory-closure.ts:157
__stencilHydrateAppis only checked for truthiness before invoking. If a consumer-provided window already has a truthy non-function value at__stencilHydrateApp, this will throw at runtime when called. Guarding withtypeof === 'function'makes the caching logic robust to collisions.
if (!$stencilWindow.__stencilHydrateApp) {
$stencilWindow.__stencilHydrateApp = hydrateAppClosure($stencilWindow);
}
$stencilWindow.__stencilHydrateApp($stencilWindow, $stencilHydrateOpts, $stencilHydrateResults, $stencilAfterHydrate, $stencilHydrateResolve);
src/hydrate/runner/reusable-window.ts:21
getReusableWindow()creates a newMockWindow(false)on every reused render just to obtain defaultlocation/navigatorobjects. Even withhtml === false,MockWindowstill constructsperformance,customElements,console, and runsresetWindowDefaults/resetWindowDimensions(seesrc/mock-doc/window.ts:85-96), which can materially reduce the benefit ofreuseWindow.
const defaults = new MockWindow(false);
resetObject(win.location, defaults.location);
resetObject(win.navigator, defaults.navigator);
src/hydrate/runner/reusable-window.ts:23
- When
reuseWindowis enabled,destroyWindowis set tofalse, soMockWindow.close()is never called. That means any timers scheduled during a render remain inwin.__timeoutsand can fire during a later queued render, breaking the “serialized renders” concurrency guarantee and leaking work across renders (timeouts are only cleared inMockWindow.close()viaresetWindow(); seesrc/mock-doc/window.ts:850-858).
const document = win.document;
const defaults = new MockWindow(false);
resetObject(win.location, defaults.location);
resetObject(win.navigator, defaults.navigator);
win.localStorage.clear();
|
hey @Armand-Lluka - thanks for raising - I think the concept is a good one. |
a816432 to
c63b1e2
Compare
c63b1e2 to
35be571
Compare
7f43a8c to
06fb39a
Compare
457aea5 to
837a8f9
Compare
|
Let me know if anything here needs adjusting 🙂 @johnjenkins |
|
Hi @johnjenkins, just following up on this one 🙂 Since your review on:
If the PR has grown past what you'd like to review in one pass, happy to split it into smaller pieces or walk through it async, whatever's easiest. Otherwise, is it ready for a re-review? |
b9ac6ab to
e928aef
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved critical and moderate findings affect mode registration, browser-global freshness, and fetch abort handling.
Get a fresh assessment by requesting another Copilot review.
Review details
Suppressed comments (3)
src/compiler/output-targets/dist-hydrate-script/hydrate-factory-closure.ts:199
- This passes the same closure-scoped
$stencilAbortControllerto every render using the cached app.hydratedError()aborts that controller on a timeout or component failure, and anAbortControllercannot be reset, so every later queued render immediately observes an aborted signal and its wrappedfetch()calls are aborted as well. Allocate a fresh controller (and corresponding fetch signal wrapper) for each invocation of the cached app.
return hydrateApp($stencilWindow, $stencilHydrateOpts, $stencilHydrateResults, $stencilAfterHydrate, $stencilHydrateResolve, $stencilAbortController);
src/compiler/output-targets/dist-hydrate-script/hydrate-factory-closure.ts:219
- Caching this returned closure also caches the primitive globals captured when it was first evaluated (
origin,innerWidth,devicePixelRatio, etc.). The reuse path resets/applies the current window before this call, so a later render with a differenturlor window values can expose stale values to component code that reads those browser globals. Refresh these bindings from the current window for each invocation, or avoid caching bindings that cannot be reset in place.
$stencilHydrateApp = $stencilWindowApps.get($stencilShadowMode);
if (!$stencilHydrateApp) {
$stencilHydrateApp = hydrateAppClosure($stencilWindow);
$stencilWindowApps.set($stencilShadowMode, $stencilHydrateApp);
}
}
$stencilHydrateApp($stencilWindow, $stencilHydrateOpts, $stencilHydrateResults, $stencilAfterHydrate, $stencilHydrateResolve);
src/mock-doc/window.ts:876
- The first hydrate closure installs an own
win.fetchwrapper so requests receive the render's abort signal, but this reset deletes that property. Because the cached closure is not re-evaluated, later reused renders leavewindow.fetchas the raw prototype method and calls throughwindow.fetch(...)bypass the timeout/error abort wiring. Preserve or reinstall the wrapper for each render (in addition to using a per-render controller).
for (const key of Reflect.ownKeys(win)) {
delete (win as any)[key];
}
- Files reviewed: 11/11 changed files
- Comments generated: 1
- Review effort level: Lite
| return function($stencilWindow, $stencilHydrateOpts, $stencilHydrateResults, $stencilAfterHydrate, $stencilHydrateResolve) { | ||
| modeResolutionChain.length = 0; | ||
| if (Array.isArray($stencilHydrateOpts.modes)) { | ||
| $stencilHydrateOpts.modes.forEach((mode) => modeResolutionChain.push(mode)); | ||
| } |
|
hey @Armand-Lluka - sorry, I'm really just trying to get v5 over the line; minimise context switching and not really considering v4 features / feature releases now. I'll be sure to look at this as soon as v5 drops |
|
hey @Armand-Lluka - thanks so much again for looking at this. |
|
Glad to hear @johnjenkins, we'll for sure plan in some testing for v5 and give feedback if we discover anything 🫡 |
The hydrate factory wraps the entire platform (runtime, vdom and every component class) in hydrateAppClosure() so it lexically captures the per-call window, and re-executes that closure on EVERY renderToString call. For component libraries this is the dominant fixed cost per render (framework output targets call renderToString once per component instance).
Two changes:
The factory now caches the evaluated closure on the window object and reuses it whenever the same window is passed again. Transparent for fresh-window renders.
New opt-in HydrateDocumentOptions.reuseWindow: the string-input path of hydrateDocument()/renderToString() reuses a process-global MockWindow, one per serializeShadowRoot mode (scoped serialization permanently ORs shadowNeedsScopedCss into component metadata inside the cached closure). Fresh head/body ELEMENTS are swapped in per render (never innerHTML='') because rootAppliedStyles is keyed on the head node. Renders are serialized through an internal promise queue since the shared window is not concurrency-safe.
Measured 2.2x per-render speedup on a 2-component test app; scales with component count (~4.3x on a 475-component library).
What is the current behavior?
GitHub Issue Number: N/A
What is the new behavior?
Closes #6794
Documentation
Does this introduce a breaking change?
Testing
Other information