Skip to content

Commit 350ba40

Browse files
committed
fix(web): route renderToStream serializer and cleanup errors to the ambient hook (#4193)
renderToStream only gave the serializer an error callback when the render had a local onError, so a late value seroval could not serialize threw from its promise callback (an unhandled rejection) and never reached onDone: the render stayed pending forever. The stream's serializer is now always wired and reports through the render's hook, else the ambient one, else console.error, as render/serialize. The normal-completion dispose called the owner's dispose unguarded, so a throwing onCleanup escaped as an unhandled rejection. The containment that abandon() had (#4029) now lives in the dispose itself, so every ending reports it as render/failed. The repeated report + console.error fallback is one local helper. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015hPxMkC3jg3Uivh65gvaf2
1 parent 6cca8b5 commit 350ba40

3 files changed

Lines changed: 268 additions & 28 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
`renderToStream` now reports two failures through the server error hook even when the render has no `onError` of its own (#4193). A value the serializer cannot handle reaches the render's hook, else the one set with `configureServerErrors`, as `{ kind: "render", handling: "serialize" }`, and the render settles. Before, it was an unhandled rejection and the render stayed pending forever. With no hook anywhere, the failure goes to `console.error`. An `onCleanup` that throws when the render is disposed after a normal completion is now contained as `abandon()` already did (#4029): it is reported as `{ kind: "render", handling: "failed" }` instead of escaping as an unhandled rejection.

‎packages/web/src/server.ts‎

Lines changed: 26 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2031,6 +2031,13 @@ export function renderToStream(code, options = {}) {
20312031
// The server error hook's ledger scope (`reportServerError`): the request
20322032
// this render serves, else the render itself — never the process.
20332033
const errorScope = requestEvent || {};
2034+
// The render's one report for a failure nothing is on the stack to catch:
2035+
// through its hook, else the ambient one, else `console.error` — never
2036+
// silent.
2037+
const reportFailure = (err, handling) => {
2038+
reportServerError(err, { kind: "render", handling }, null, options.onError, errorScope);
2039+
if (!options.onError && ambientServerErrorHook() === undefined) console.error(err);
2040+
};
20342041
let dispose;
20352042
let dead = false;
20362043
// The render's `"render"` record (`timeDocument`, once the context is up):
@@ -2128,27 +2135,11 @@ export function renderToStream(code, options = {}) {
21282135
const sink = writable;
21292136
buffer = { write() {} };
21302137
writable = { end() {} };
2131-
// Contained (#4029): an `onCleanup` that throws here must not escape the
2132-
// teardown. On the `signal` path this runs inside an `abort` listener,
2133-
// where a throw becomes an uncaught exception that takes the process down;
2134-
// on the `failRender` path it would cut the wind-down short. It is the
2135-
// render's failure, so it goes to the hook as one (`handling: "failed"`),
2136-
// and with no hook anywhere it is never silent.
2138+
// The dispose contains a throwing `onCleanup` itself (#4029, #4193).
21372139
if (dispose) {
21382140
const d = dispose;
21392141
dispose = () => {};
2140-
try {
2141-
d();
2142-
} catch (err) {
2143-
reportServerError(
2144-
err,
2145-
{ kind: "render", handling: "failed" },
2146-
null,
2147-
options.onError,
2148-
errorScope
2149-
);
2150-
if (!options.onError && ambientServerErrorHook() === undefined) console.error(err);
2151-
}
2142+
d();
21522143
}
21532144
// Close the serializer AFTER `dead` is set: seroval's `close()` runs
21542145
// each pending write's cleanup — a serialized async iterator gets its
@@ -2207,14 +2198,7 @@ export function renderToStream(code, options = {}) {
22072198
// boundary that already reported this error with its location leaves
22082199
// this a no-op (once per error). With no hook anywhere the failure is
22092200
// never silent.
2210-
reportServerError(
2211-
err,
2212-
{ kind: "render", handling: "failed" },
2213-
null,
2214-
options.onError,
2215-
errorScope
2216-
);
2217-
if (!options.onError && ambientServerErrorHook() === undefined) console.error(err);
2201+
reportFailure(err, "failed");
22182202
abandon();
22192203
};
22202204
// The same containment reached from the renderer's OWN retry passes (root
@@ -2511,7 +2495,12 @@ export function renderToStream(code, options = {}) {
25112495
plugins: options.plugins,
25122496
onData: payload => sink.data(payload),
25132497
onDone,
2514-
onError: serializerErrorHook(options.onError)
2498+
// Always wired (#4193), unlike `renderToString`'s: a stream has no caller
2499+
// to throw a late value's failure to, and without an `onError` seroval
2500+
// throws from its promise callback and never reaches `onDone` — the
2501+
// render would stay pending. Heard as `handling: "serialize"` by the
2502+
// render's hook, else the ambient one, else `console.error`.
2503+
onError: err => reportFailure(err, "serialize")
25152504
});
25162505
let rootAssetsSerialized = false;
25172506
const serializeRootAssets = () => {
@@ -3127,7 +3116,16 @@ export function renderToStream(code, options = {}) {
31273116
context.trace = undefined;
31283117
if (onAbort) signal.removeEventListener("abort", onAbort);
31293118
if (endEdges) endEdges();
3130-
d();
3119+
// Contained (#4029, #4193): an `onCleanup` that throws must not
3120+
// escape the teardown — inside the `signal`'s `abort` listener it is
3121+
// an uncaught exception, on the completion paths an unhandled
3122+
// rejection, and on `failRender`'s it cuts the wind-down short. It
3123+
// is the render's failure (`handling: "failed"`).
3124+
try {
3125+
d();
3126+
} catch (err) {
3127+
reportFailure(err, "failed");
3128+
}
31313129
};
31323130
rootOwner = claimRenderRoot(context);
31333131
if (requestEvent) claimEventRender(requestEvent, context);
Lines changed: 237 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,237 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
*
4+
* solidjs/solid#4193 — two `renderToStream` failures bypassed the ambient
5+
* server error hook (`configureServerErrors`) when the render had no
6+
* `onError` of its own, and escaped as unhandled rejections:
7+
*
8+
* - a value the serializer cannot handle, settling after the shell: the
9+
* serializer was only given an error callback when the render had a local
10+
* `onError`, so seroval threw from its promise callback, never reached its
11+
* `onDone`, and the render stayed pending forever;
12+
* - an `onCleanup` that throws in the final dispose after a normal
13+
* completion: only `abandon()` contained a throwing dispose (#4029).
14+
*
15+
* Not pinned here: whether the cleanups registered before a throwing one
16+
* still run. The owner teardown stops at a throw on the server as it does on
17+
* the client (`disposeOwner` / `runDisposal`); that is owner semantics, not
18+
* this containment.
19+
*/
20+
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
21+
import {
22+
Loading,
23+
configureServerErrors,
24+
renderToStream,
25+
type ServerErrorContext
26+
} from "@solidjs/web";
27+
import { createMemo, onCleanup } from "solid-js";
28+
29+
const delay = (ms: number) => new Promise(r => setTimeout(r, ms));
30+
31+
/** Own the process's uncaught channels so an escape fails THIS test. */
32+
async function watchEscapes(run: () => Promise<void>) {
33+
const events = ["uncaughtException", "unhandledRejection"] as const;
34+
const previous = events.map(e => process.listeners(e));
35+
events.forEach(e => process.removeAllListeners(e));
36+
const escaped: unknown[] = [];
37+
const capture = (reason: unknown) => escaped.push(reason);
38+
events.forEach(e => process.on(e, capture));
39+
try {
40+
await run();
41+
for (let turn = 0; turn < 4; turn++) await delay(20);
42+
return escaped;
43+
} finally {
44+
events.forEach((e, i) => {
45+
process.off(e, capture);
46+
for (const listener of previous[i]) process.on(e, listener as any);
47+
});
48+
}
49+
}
50+
51+
/** Resolves "settled" with the HTML, or "pending" if the render never ends. */
52+
function settle(p: PromiseLike<string>) {
53+
return Promise.race([
54+
Promise.resolve(p).then(html => ({ state: "settled", html })),
55+
delay(500).then(() => ({ state: "pending", html: "" }))
56+
]);
57+
}
58+
59+
function pipeSettle(code: () => any, options: Parameters<typeof renderToStream>[1] = {}) {
60+
return settle(
61+
new Promise<string>(resolve => {
62+
const chunks: string[] = [];
63+
renderToStream(code, options).pipe({
64+
write(chunk: string) {
65+
chunks.push(String(chunk));
66+
},
67+
end() {
68+
resolve(chunks.join(""));
69+
}
70+
});
71+
})
72+
);
73+
}
74+
75+
type Heard = { error: unknown; context: ServerErrorContext };
76+
let heard: Heard[];
77+
let logged: unknown[][];
78+
const ambient = (error: unknown, context: ServerErrorContext) => {
79+
heard.push({ error, context });
80+
};
81+
const kinds = () => heard.map(h => `${h.context.kind}/${h.context.handling}`);
82+
83+
beforeEach(() => {
84+
heard = [];
85+
logged = [];
86+
vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => {
87+
logged.push(args);
88+
});
89+
});
90+
afterEach(() => {
91+
configureServerErrors({ onError: undefined });
92+
vi.restoreAllMocks();
93+
});
94+
95+
/** A page whose async value settles after the shell to `value`. */
96+
function page(value: unknown, extra?: () => void) {
97+
return () => {
98+
extra && extra();
99+
const data = createMemo(() => Promise.resolve(value));
100+
return (
101+
<main>
102+
<Loading fallback="pending">
103+
<p>{String(data())}</p>
104+
</Loading>
105+
</main>
106+
);
107+
};
108+
}
109+
110+
describe("renderToStream: a value the serializer cannot handle (#4193)", () => {
111+
test("reaches the ambient hook as render/serialize and the render settles", async () => {
112+
configureServerErrors({ onError: ambient });
113+
let completed = false;
114+
let result: { state: string; html: string } | undefined;
115+
const escaped = await watchEscapes(async () => {
116+
result = await settle(
117+
renderToStream(
118+
page(() => "fn"),
119+
{
120+
onCompleteAll() {
121+
completed = true;
122+
}
123+
}
124+
)
125+
);
126+
});
127+
expect(escaped).toEqual([]);
128+
expect(result!.state).toBe("settled");
129+
expect(completed).toBe(true);
130+
expect(kinds()).toEqual(["render/serialize"]);
131+
});
132+
133+
test("the piped render settles too", async () => {
134+
configureServerErrors({ onError: ambient });
135+
let result: { state: string; html: string } | undefined;
136+
const escaped = await watchEscapes(async () => {
137+
result = await pipeSettle(page(() => "fn"));
138+
});
139+
expect(escaped).toEqual([]);
140+
expect(result!.state).toBe("settled");
141+
expect(kinds()).toEqual(["render/serialize"]);
142+
});
143+
144+
test("the render's own onError still wins over the ambient hook", async () => {
145+
configureServerErrors({ onError: ambient });
146+
const local: Heard[] = [];
147+
let result: { state: string; html: string } | undefined;
148+
const escaped = await watchEscapes(async () => {
149+
result = await settle(
150+
renderToStream(
151+
page(() => "fn"),
152+
{ onError: (error, context) => void local.push({ error, context }) }
153+
)
154+
);
155+
});
156+
expect(escaped).toEqual([]);
157+
expect(result!.state).toBe("settled");
158+
expect(heard).toEqual([]);
159+
expect(local.map(h => h.context.handling)).toEqual(["serialize"]);
160+
});
161+
162+
test("without a hook anywhere the render settles and the failure reaches console.error", async () => {
163+
let result: { state: string; html: string } | undefined;
164+
const escaped = await watchEscapes(async () => {
165+
result = await settle(renderToStream(page(() => "fn")));
166+
});
167+
expect(escaped).toEqual([]);
168+
expect(result!.state).toBe("settled");
169+
expect(logged.length).toBe(1);
170+
});
171+
});
172+
173+
describe("renderToStream: an onCleanup that throws in the final dispose (#4193)", () => {
174+
const cleanupBoom = (ran: string[]) => () => {
175+
onCleanup(() => ran.push("first"));
176+
onCleanup(() => {
177+
throw new Error("cleanup threw");
178+
});
179+
};
180+
181+
test("reaches the ambient hook as render/failed when awaited", async () => {
182+
configureServerErrors({ onError: ambient });
183+
const ran: string[] = [];
184+
let completed = false;
185+
let result: { state: string; html: string } | undefined;
186+
const escaped = await watchEscapes(async () => {
187+
result = await settle(
188+
renderToStream(page("resolved", cleanupBoom(ran)), {
189+
onCompleteAll() {
190+
completed = true;
191+
}
192+
})
193+
);
194+
});
195+
expect(escaped).toEqual([]);
196+
expect(result!.state).toBe("settled");
197+
expect(result!.html).toContain("resolved");
198+
expect(completed).toBe(true);
199+
expect(kinds()).toEqual(["render/failed"]);
200+
expect((heard[0].error as Error).message).toBe("cleanup threw");
201+
});
202+
203+
test("reaches the ambient hook as render/failed when piped", async () => {
204+
configureServerErrors({ onError: ambient });
205+
const ran: string[] = [];
206+
let result: { state: string; html: string } | undefined;
207+
const escaped = await watchEscapes(async () => {
208+
result = await pipeSettle(page("resolved", cleanupBoom(ran)));
209+
});
210+
expect(escaped).toEqual([]);
211+
expect(result!.state).toBe("settled");
212+
expect(kinds()).toEqual(["render/failed"]);
213+
});
214+
215+
test("the render's own onError hears it ahead of the ambient hook", async () => {
216+
configureServerErrors({ onError: ambient });
217+
const local: Heard[] = [];
218+
const escaped = await watchEscapes(async () => {
219+
await settle(
220+
renderToStream(page("resolved", cleanupBoom([])), {
221+
onError: (error, context) => void local.push({ error, context })
222+
})
223+
);
224+
});
225+
expect(escaped).toEqual([]);
226+
expect(heard).toEqual([]);
227+
expect(local.map(h => `${h.context.kind}/${h.context.handling}`)).toEqual(["render/failed"]);
228+
});
229+
230+
test("without a hook anywhere it reaches console.error", async () => {
231+
const escaped = await watchEscapes(async () => {
232+
await settle(renderToStream(page("resolved", cleanupBoom([]))));
233+
});
234+
expect(escaped).toEqual([]);
235+
expect(logged.some(args => (args[0] as Error)?.message === "cleanup threw")).toBe(true);
236+
});
237+
});

0 commit comments

Comments
 (0)