Skip to content

Commit f41c6a4

Browse files
ryansolidClaude via Cursor
andauthored
fix(ssr): contain post-render and bare-child async rejections in renderToString/renderToStream (#3570, #3569) (#3594)
* fix(solid): observe the server async deferred so a post-render rejection cannot exit the process (#3570) Every server async flight (memo, store, projection, async generator) settles an internal deferred from `createDeferredPromise`, and `settleServerAsync` settles it unconditionally so a serialized flight lands whatever the node's lifetime. Under `renderToString` there is no serialization channel (`ctx.async` is unset) and the sync `<Loading>` path never awaits the NotReadyError's source; a `<NoHydration>` zone or an unread source has no consumer either. A rejection landing after the HTML was returned therefore rejected a promise with zero subscribers — an `unhandledRejection` that took Node down with exit code 1, and no `<Errored>` could see it because the render was over. Observe the deferred at creation. Real subscribers still see the rejection exactly as before (a no-op rejection arm is a separate derived promise). The other internal promises on the path (`subscribePendingRetry`, the user promise's `.then(v, e)`, the abandoned duplicate flight, the iterator close) were already observed. Co-authored-by: Claude via Cursor <[email protected]> * fix(ssr): a rejecting direct child of <Loading> no longer hangs or crashes renderToStream (#3569) Two independent layers, each verified on its own. Routing (solid-js, `ssrLoadingBoundary.runDiscovery`): a template hole that throws is routed through `ssrHandleError` to the boundary's own ErrorContext handler, which — once the fragment is registered — owns the error: `<key>_fr` rejects and the client re-renders the subtree (`handling: "client"`, the #2997 verdict). A bare child (`<Loading>{data()}</Loading>`, or a component whose return IS the read) threw straight out of `fn()` and bypassed that handler, so `finalizeError` saw an uncontained error and, pre-flush, failed the whole request. Bare child ≡ template hole now; an error a hole already routed (`handledRenderError === err`) propagates as before so an enclosing Errored renders its fallback once. Containment (@solidjs/web, `renderToStream`): `failRender → abandon()` disposed the render (clearing `context.trace`) but completed nothing, and seroval's `onDone` then ran `doShell()` on the disposed render — `traceMetaMarkup(undefined)` threw the 'emit' TypeError inside a flush microtask, `onCompleteAll` was never reached, and the awaited promise (and a pre-flush `.pipe()`) hung forever. `abandon` now completes the consumer on a render failure (the awaited promise resolves with the HTML produced so far — the thenable's documented never-rejects contract — `pipe()` ends its sink, `pipeTo()`/`readable` close the writable) while a client disconnect still leaves the sink untouched (`disconnected`), and `onDone` returns on a dead render. Co-authored-by: Claude via Cursor <[email protected]> --------- Co-authored-by: Claude via Cursor <[email protected]>
1 parent c74365d commit f41c6a4

7 files changed

Lines changed: 713 additions & 20 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"solid-js": patch
3+
---
4+
5+
Fix `renderToString` exiting the process on a late async rejection (#3570). Every server async flight settles an internal deferred; under `renderToString` (no serialization channel, the sync `<Loading>` path never awaits the pending source), in a `<NoHydration>` zone, or for an unread source, nothing observed it, so an async memo/store/projection that rejected after the HTML was returned became an `unhandledRejection`. The deferred is now observed at creation; consumers see exactly what they saw before.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
"solid-js": patch
3+
"@solidjs/web": patch
4+
---
5+
6+
Fix `renderToStream` hanging or throwing `TypeError: Cannot read properties of undefined (reading 'emit')` when an async read that rejects is the direct child of `<Loading>` (#3569).
7+
8+
- `solid-js`: a bare child's throw (`<Loading>{data()}</Loading>`, or a component whose return is the read) now routes through the boundary's error handler exactly like a template hole's does — the fragment rejects and the client re-renders the subtree (`handling: "client"`), instead of escalating to a request failure pre-flush.
9+
- `@solidjs/web`: a render failure (`failRender`) now completes the consumer — the awaited promise resolves with the HTML produced so far, `pipe()` ends its sink, `pipeTo()`/`readable` close the writable — and the serializer's completion no longer assembles a shell on the disposed render.

‎packages/solid/src/server/hydration.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,24 @@ function ssrLoadingBoundary(
402402
retryPromise = (err as any).source as Promise<any>;
403403
return undefined;
404404
}
405-
throw err;
405+
// Already routed: a template hole ran `ssrHandleError` on its way
406+
// here (the handler rethrows after routing) — propagate as before,
407+
// or the enclosing Errored would render its fallback twice.
408+
if (handledRenderError === err) throw err;
409+
// A bare child — `<Loading>{data()}</Loading>`, or a component whose
410+
// return IS the read — throws straight out of `fn()`: no template
411+
// hole sits between it and this boundary, so nothing ran
412+
// `ssrHandleError` for it the way `ssr()` does for a hole. Route it
413+
// the same way: the ErrorContext handler installed by
414+
// `runLoadingPhase` owns it once the fragment is registered (`_fr`
415+
// rejects, the client re-renders the subtree — `handling: "client"`,
416+
// the verdict #2997 pins for a hole in the same position); on the
417+
// synchronous first pass it defers to the enclosing Errored's
418+
// handler, or rethrows when there is none. Rethrown raw instead, a
419+
// rejection here reached `finalizeError` as an uncontained error and
420+
// failed the whole request pre-flush (#3569).
421+
ssrHandleError(err);
422+
return undefined;
406423
}
407424
}) as any;
408425
}

‎packages/solid/src/server/signals.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -662,6 +662,20 @@ function createDeferredPromise<T>(): DeferredPromise<T> {
662662
resolvePromise = resolve;
663663
rejectPromise = reject;
664664
}) as DeferredPromise<T>["promise"];
665+
// Observed at birth. This deferred is an internal channel: its outcome is
666+
// always mirrored where it matters (`comp.error`, the slot record, the
667+
// guarded serialized promise), and `settleServerAsync` settles it
668+
// unconditionally — a serialized flight must land whatever the node's
669+
// lifetime. But not every flight has a consumer: under renderToString
670+
// there is no serialization channel (`ctx.async` unset) and the sync
671+
// `<Loading>` path never awaits the NotReadyError's source; a
672+
// NoHydration zone or `serialize: false` opts out of the stream; an
673+
// unread source has no reader at all. There, a terminal rejection landed
674+
// on a promise with zero subscribers — an unhandledRejection that took
675+
// the process down after the HTML had already been returned (#3570).
676+
// A no-op rejection arm is a separate derived promise: real subscribers
677+
// still see the rejection exactly as before.
678+
promise.then(undefined, () => {});
665679

666680
return {
667681
promise,

‎packages/web/src/server.ts‎

Lines changed: 85 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1865,6 +1865,31 @@ export function renderToStream(code, options = {}) {
18651865
// still in flight. A render failure winds down through here too
18661866
// (`failRender`), silently: that one is already the render error's
18671867
// finding.
1868+
//
1869+
// The two differ in what is left alive. After a disconnect nobody is
1870+
// listening: the sink is never touched again (`disconnected`). After a
1871+
// render FAILURE the consumer is still waiting — the awaited promise, a
1872+
// `pipe` sink, a `pipeTo` writable — and must be completed by the
1873+
// wind-down itself, because nothing downstream will: seroval's `onDone`
1874+
// (the normal road to `onCompleteAll`/`writable.end()`) has nothing to
1875+
// assemble on a disposed render and returns early. Left incomplete, an
1876+
// awaited `renderToStream` hung the request forever (#3569). Each
1877+
// consumer registers its completion through `onFailure` (they chain —
1878+
// `then` may be called more than once, and beside a pipe); a failure that
1879+
// lands before the consumer claims the render runs it at registration.
1880+
let disconnected = false;
1881+
let failed = false;
1882+
let onFailed;
1883+
const onFailure = complete => {
1884+
if (failed) return complete(undefined);
1885+
const prev = onFailed;
1886+
onFailed = prev
1887+
? sink => {
1888+
prev(sink);
1889+
complete(sink);
1890+
}
1891+
: complete;
1892+
};
18681893
const abandon = disconnect => {
18691894
if (dead) return;
18701895
if ("_SOLID_OBSERVE_" && disconnect)
@@ -1882,13 +1907,21 @@ export function renderToStream(code, options = {}) {
18821907
);
18831908
dead = true;
18841909
completed = true;
1910+
if (disconnect) disconnected = true;
1911+
// The live sink wrapper (post-shell) is handed to the failure
1912+
// completion below; pre-shell there is none yet.
1913+
const sink = writable;
18851914
buffer = { write() {} };
18861915
writable = { end() {} };
18871916
if (dispose) {
18881917
const d = dispose;
18891918
dispose = () => {};
18901919
d();
18911920
}
1921+
if (!disconnect) {
1922+
failed = true;
1923+
onFailed && onFailed(sink);
1924+
}
18921925
};
18931926
// A retry pass that throws a REAL error (not NotReady) can have nothing on
18941927
// the stack to catch it: the initial render pass throws synchronously out
@@ -1964,18 +1997,20 @@ export function renderToStream(code, options = {}) {
19641997
};
19651998
};
19661999
// Wrap an integrator-supplied `pipe` sink: contain sync throws from
1967-
// `write`/`end` and treat them as disconnection.
2000+
// `write`/`end` and treat them as disconnection. Guarded on the CLIENT
2001+
// being gone, not on the render being dead: a failed render still ends
2002+
// the (alive) sink through this wrapper.
19682003
const guardSink = w => ({
19692004
write(payload) {
1970-
if (dead) return;
2005+
if (disconnected) return;
19712006
try {
19722007
w.write(payload);
19732008
} catch (_) {
19742009
abandon("sink");
19752010
}
19762011
},
19772012
end() {
1978-
if (dead) return;
2013+
if (disconnected) return;
19792014
try {
19802015
w.end();
19812016
} catch (_) {
@@ -2033,6 +2068,12 @@ export function renderToStream(code, options = {}) {
20332068
}
20342069
};
20352070
const onDone = () => {
2071+
// An abandoned render has no shell to assemble: `dispose` cleared the
2072+
// trace `doShell` reads (`traceMetaMarkup(context.trace)`), and the
2073+
// consumer was completed by the wind-down (`abandon`) — a disconnect has
2074+
// nobody to complete. Serialized promises still settle after the
2075+
// wind-down, so seroval still reaches here; do nothing (#3569).
2076+
if (dead) return;
20362077
writeTasks();
20372078
// Every blocker has settled by definition here (the render is complete),
20382079
// so doShell's growth gate has nothing to wait for: align its baseline
@@ -2821,18 +2862,31 @@ export function renderToStream(code, options = {}) {
28212862
const pipeToImpl = w => {
28222863
let resolve;
28232864
const p = new Promise(r => (resolve = r));
2865+
// A render failure (see `abandon`) completes this consumer: the promise
2866+
// settles and the writable — alive; the RENDER died — is closed so a
2867+
// `Response` built on `readable` completes instead of hanging. Post-
2868+
// shell the live wrapper ends (flushing what it coalesced, then the
2869+
// writer's own close path); pre-shell nothing was written yet.
2870+
onFailure(sink => {
2871+
try {
2872+
if (sink) sink.end();
2873+
else w.close().catch(() => {});
2874+
} catch (_) {}
2875+
resolve();
2876+
});
28242877
function flush() {
28252878
allSettled(blockingPromises).then(awaited => {
28262879
scheduleFlush(() => {
28272880
if (dead) return resolve();
28282881
// Root-hole retries and shell assembly run inside this microtask —
28292882
// a real error here (see failRender) must fail the request, not
2830-
// reject an unhandled promise.
2883+
// reject an unhandled promise. The failure completion above closes
2884+
// the writable and settles the promise.
28312885
try {
28322886
doShell();
28332887
} catch (err) {
28342888
failRootRender(err);
2835-
return resolve();
2889+
return;
28362890
}
28372891
if (!shellCompleted) return flush();
28382892
const encoder = new TextEncoder();
@@ -2928,9 +2982,21 @@ export function renderToStream(code, options = {}) {
29282982
complete();
29292983
};
29302984
} else onCompleteAll = complete;
2985+
// A render failure (see `abandon`) — the renderer's own retry pass
2986+
// below, or a boundary's resume loop through `failRender` — resolves
2987+
// with whatever HTML the render produced (nothing, pre-shell): the
2988+
// thenable never rejects, `onError` already heard the failure. The
2989+
// head is deliberately NOT frozen: the render died, its teardown
2990+
// retracts the declarations as it always did, and the consumer
2991+
// keeps a writable head for whatever error response it builds
2992+
// around the partial HTML.
2993+
onFailure(() => resolve(tmp));
29312994
function flush() {
29322995
allSettled(blockingPromises).then(awaited => {
29332996
scheduleFlush(() => {
2997+
// The wind-down already completed this consumer; a re-pull on
2998+
// the disposed render would only find another failure.
2999+
if (dead) return;
29343000
// Same gates as doShell: pending root head props are shell
29353001
// blockers, so flushEnd must not run ahead of them (their
29363002
// source may not be serialized, so the serializer alone
@@ -2946,15 +3012,10 @@ export function renderToStream(code, options = {}) {
29463012
)
29473013
return flush();
29483014
} catch (err) {
2949-
// Contain retry-pass errors (see failRender); the thenable
2950-
// contract already routes render errors through onError and
2951-
// resolves with whatever HTML the render produced. The head
2952-
// is deliberately NOT frozen on this path: the render died,
2953-
// its teardown retracts the declarations as it always did,
2954-
// and the consumer keeps a writable head for whatever error
2955-
// response it builds around the partial HTML.
3015+
// Contain retry-pass errors (see failRender): the failure
3016+
// completion above resolves the thenable.
29563017
failRootRender(err);
2957-
return resolve(tmp);
3018+
return;
29583019
}
29593020
queue(flushEnd);
29603021
}, awaited);
@@ -2966,20 +3027,25 @@ export function renderToStream(code, options = {}) {
29663027
},
29673028
pipe(w) {
29683029
claimConsumer("pipe");
3030+
// A render failure (see `abandon`) ends the sink: it is still alive —
3031+
// the RENDER died — and leaving it open would hang the response. Post-
3032+
// shell through the live wrapper (coalesced bytes flush first); pre-
3033+
// shell nothing was written, end the raw sink.
3034+
onFailure(sink => {
3035+
try {
3036+
sink ? sink.end() : w.end();
3037+
} catch (_) {}
3038+
});
29693039
function flush() {
29703040
allSettled(blockingPromises).then(awaited => {
29713041
scheduleFlush(() => {
29723042
if (dead) return;
29733043
try {
29743044
doShell();
29753045
} catch (err) {
2976-
// Contain retry-pass errors (see failRender) and end the sink:
2977-
// it is still alive — the RENDER died — and leaving it open
2978-
// would hang the response.
3046+
// Contain retry-pass errors (see failRender): the failure
3047+
// completion above ends the sink.
29793048
failRootRender(err);
2980-
try {
2981-
w.end();
2982-
} catch (_) {}
29833049
return;
29843050
}
29853051
if (!shellCompleted) return flush();

0 commit comments

Comments
 (0)