Skip to content

Commit 6707995

Browse files
committed
fix(web): fail renders on late default serializer errors
1 parent ab29345 commit 6707995

6 files changed

Lines changed: 234 additions & 13 deletions
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+
Fail `renderToStream` when an asynchronous value cannot be serialized after its key was handed to the default serializer. The render tears down without calling `onCompleteAll`; a piped response ends with the HTML already sent. Synchronous serialization failures and custom serializers keep their existing behavior.

‎packages/web/src/server.ts‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2344,22 +2344,37 @@ export function renderToStream(code, options = {}) {
23442344
let stableOrder = false;
23452345
let parkedWrites = null;
23462346
const byKey = (a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
2347+
// A failure reported after write returns leaves a pending client key, so
2348+
// fail the render once the other writes settle (#4647). Keep synchronous
2349+
// failures completing as before (#4227). A buffered stream can emit its
2350+
// initial chunk and fail inside write; detecting that case would require
2351+
// publication information from the serializer.
2352+
let writing = 0;
2353+
let stranded = false;
2354+
const handOver = (id, value) => {
2355+
writing++;
2356+
try {
2357+
serializer.write(id, value);
2358+
} finally {
2359+
writing--;
2360+
}
2361+
};
23472362
const write = (id, value) => {
23482363
if (stableOrder && !dead) (parkedWrites ||= []).push([id, value]);
2349-
else serializer.write(id, value);
2364+
else handOver(id, value);
23502365
};
23512366
const flushParkedWrites = () => {
23522367
if (!parkedWrites) return;
23532368
const writes = parkedWrites.sort(byKey);
23542369
parkedWrites = null;
2355-
for (let i = 0; i < writes.length; i++) serializer.write(writes[i][0], writes[i][1]);
2370+
for (let i = 0; i < writes.length; i++) handOver(writes[i][0], writes[i][1]);
23562371
};
23572372
const flushStubBatch = () => {
23582373
if (!stubBatch) return;
23592374
const entries = [...stubBatch];
23602375
stubBatch = null;
23612376
if (stableOrder) entries.sort(byKey);
2362-
for (let i = 0; i < entries.length; i++) serializer.write(entries[i][0], entries[i][1]);
2377+
for (let i = 0; i < entries.length; i++) handOver(entries[i][0], entries[i][1]);
23632378
};
23642379
let headerEmitted = false;
23652380
const pushTask = task => {
@@ -2385,6 +2400,9 @@ export function renderToStream(code, options = {}) {
23852400
// wind-down, so seroval still reaches here; do nothing (#3569).
23862401
if (dead) return;
23872402
writeTasks();
2403+
// A key the client waits on forever: what settled went out above, and
2404+
// the render fails as a rejection there would, already reported.
2405+
if (stranded) return abandon();
23882406
// Every blocker has settled by definition here (the render is complete),
23892407
// so doShell's growth gate has nothing to wait for: align its baseline
23902408
// rather than let a stale flush-loop snapshot hold a finished shell.
@@ -2529,7 +2547,10 @@ export function renderToStream(code, options = {}) {
25292547
// throws from its promise callback and never reaches `onDone` — the
25302548
// render would stay pending. Heard as `handling: "serialize"` by the
25312549
// render's hook, else the ambient one, else `console.error`.
2532-
onError: err => reportFailure(err, "serialize")
2550+
onError: err => {
2551+
reportFailure(err, "serialize");
2552+
if (!writing && !options.serializer) stranded = true;
2553+
}
25332554
});
25342555
let rootAssetsSerialized = false;
25352556
const serializeRootAssets = () => {

‎packages/web/test/server/async-memo-element-4242.spec.tsx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -250,11 +250,12 @@ describe("ASYNC_MEMO_ELEMENT — the finding and what the detection refuses", ()
250250
}
251251
// A class instance is never inspected: whether it crosses is the
252252
// serializer's (and its plugins') call, as before — seroval has no
253-
// encoding for this one and says so itself.
253+
// encoding for this one and says so itself, and the key it leaves
254+
// pending on the client fails the render (#4647).
254255
const instance = await land(() => tick().then(() => new Point("<b>")), {
255256
show: v => `landed:${typeof v}`
256257
});
257-
expect(instance.html).toContain("landed:object");
258+
expect(instance.html).toBe("");
258259
expect(instance.errors.map(e => String(e))).toEqual([
259260
expect.stringContaining("cannot be parsed/serialized")
260261
]);

‎packages/web/test/server/stream-ambient-error-hook-4193.spec.tsx‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,12 +64,16 @@ function page(value: unknown, extra?: () => void) {
6464
describe("renderToStream: a value the serializer cannot handle (#4193)", () => {
6565
test("reaches the ambient hook as render/serialize and the render settles", async () => {
6666
configureServerErrors({ onError: ambient });
67+
const ran: string[] = [];
6768
let completed = false;
6869
let result: { state: string; html: string } | undefined;
6970
const escaped = await watchEscapes(async () => {
7071
result = await settle(
7172
renderToStream(
72-
page(() => "fn"),
73+
page(
74+
() => "fn",
75+
() => onCleanup(() => ran.push("cleanup"))
76+
),
7377
{
7478
onCompleteAll() {
7579
completed = true;
@@ -80,7 +84,11 @@ describe("renderToStream: a value the serializer cannot handle (#4193)", () => {
8084
});
8185
expect(escaped).toEqual([]);
8286
expect(result!.state).toBe("settled");
83-
expect(completed).toBe(true);
87+
// Its key went out pending and nothing settles it: the render fails
88+
// rather than report the document complete (#4647).
89+
expect(result!.html).toBe("");
90+
expect(completed).toBe(false);
91+
expect(ran).toEqual(["cleanup"]);
8492
expect(kinds()).toEqual(["render/serialize"]);
8593
});
8694

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
*
4+
* solidjs/solid#4647: a serialized async value whose answer the serializer
5+
* cannot handle. The key already went out to the client as a pending
6+
* promise and nothing will ever settle it; the hook heard
7+
* `render/serialize`, yet the render completed and `onCompleteAll` reported
8+
* the document whole. A rejected value in the same spot fails the render;
9+
* so does this one. A value that fails as it is handed over never reaches
10+
* the client and still completes (#4227).
11+
*/
12+
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
13+
import { renderToStream, type ServerErrorContext } from "@solidjs/web";
14+
import { createMemo, Loading, onCleanup } from "solid-js";
15+
import { settle, watchEscapes } from "./stream-settle-harness.js";
16+
17+
class Unserializable {}
18+
19+
let heard: string[];
20+
let ran: string[];
21+
const onError = (_: unknown, context: ServerErrorContext) =>
22+
void heard.push(`${context.kind}/${context.handling}`);
23+
24+
beforeEach(() => {
25+
heard = [];
26+
ran = [];
27+
});
28+
afterEach(() => {
29+
vi.restoreAllMocks();
30+
});
31+
32+
function App() {
33+
onCleanup(() => ran.push("cleanup"));
34+
const value = createMemo(() => Promise.resolve(new Unserializable()));
35+
return <main>{String(value() instanceof Unserializable)}</main>;
36+
}
37+
38+
/** A page whose boundary value settles once `gate` opens. */
39+
function late(gate: Promise<void>) {
40+
return () => {
41+
onCleanup(() => ran.push("cleanup"));
42+
const value = createMemo(() => gate.then(() => new Unserializable()));
43+
return (
44+
<main>
45+
<Loading fallback="pending">
46+
<p>{String(value() instanceof Unserializable)}</p>
47+
</Loading>
48+
</main>
49+
);
50+
};
51+
}
52+
53+
describe("renderToStream: an async value that fails to serialize (#4647)", () => {
54+
test("the awaited render fails like a rejection: no HTML, no onCompleteAll", async () => {
55+
let completed = false;
56+
let result: { state: string; html: string } | undefined;
57+
const escaped = await watchEscapes(async () => {
58+
result = await settle(
59+
renderToStream(App, {
60+
onError,
61+
onCompleteAll() {
62+
completed = true;
63+
}
64+
})
65+
);
66+
});
67+
expect(escaped).toEqual([]);
68+
expect(result!.state).toBe("settled");
69+
expect(result!.html).toBe("");
70+
expect(completed).toBe(false);
71+
expect(heard).toEqual(["render/serialize"]);
72+
expect(ran).toEqual(["cleanup"]);
73+
});
74+
75+
test("after the shell, the piped stream ends without onCompleteAll", async () => {
76+
let release!: () => void;
77+
const gate = new Promise<void>(r => (release = r));
78+
let completed = false;
79+
let result: { state: string; html: string } | undefined;
80+
const escaped = await watchEscapes(async () => {
81+
result = await settle(
82+
new Promise<string>(resolve => {
83+
const chunks: string[] = [];
84+
renderToStream(late(gate), {
85+
onError,
86+
onCompleteAll() {
87+
completed = true;
88+
}
89+
}).pipe({
90+
write(chunk: string) {
91+
chunks.push(String(chunk));
92+
release();
93+
},
94+
end() {
95+
resolve(chunks.join(""));
96+
}
97+
});
98+
})
99+
);
100+
});
101+
expect(escaped).toEqual([]);
102+
expect(result!.state).toBe("settled");
103+
expect(result!.html).toContain("pending");
104+
expect(completed).toBe(false);
105+
expect(heard).toEqual(["render/serialize"]);
106+
expect(ran).toEqual(["cleanup"]);
107+
});
108+
109+
test("a custom serializer's late failure is its own to settle: the render completes", async () => {
110+
// Reports every promise's answer as a failure, then settles the write.
111+
const serializer = ({ onError, onDone }: { onError(e: unknown): void; onDone(): void }) => {
112+
let pending = 0;
113+
let flushed = false;
114+
let finished = false;
115+
const settleWrite = () => {
116+
if (!flushed || pending || finished) return;
117+
finished = true;
118+
onDone();
119+
};
120+
return {
121+
write(_: string, value: any) {
122+
if (!value || typeof value.then !== "function") return;
123+
pending++;
124+
value.then(
125+
() => {
126+
onError(new Error("late"));
127+
pending--;
128+
settleWrite();
129+
},
130+
() => {
131+
pending--;
132+
settleWrite();
133+
}
134+
);
135+
},
136+
flush() {
137+
flushed = true;
138+
settleWrite();
139+
}
140+
};
141+
};
142+
let completed = false;
143+
let result: { state: string; html: string } | undefined;
144+
const escaped = await watchEscapes(async () => {
145+
result = await settle(
146+
renderToStream(App, {
147+
onError,
148+
serializer,
149+
onCompleteAll() {
150+
completed = true;
151+
}
152+
} as any)
153+
);
154+
});
155+
expect(escaped).toEqual([]);
156+
expect(result!.state).toBe("settled");
157+
expect(result!.html).toContain("<main");
158+
expect(completed).toBe(true);
159+
expect(heard).toEqual(["render/serialize"]);
160+
expect(ran).toEqual(["cleanup"]);
161+
});
162+
163+
test("without a hook anywhere the failure reaches console.error once", async () => {
164+
const logged: unknown[][] = [];
165+
vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => {
166+
logged.push(args);
167+
});
168+
let result: { state: string; html: string } | undefined;
169+
const escaped = await watchEscapes(async () => {
170+
result = await settle(renderToStream(App));
171+
});
172+
expect(escaped).toEqual([]);
173+
expect(result!.state).toBe("settled");
174+
expect(result!.html).toBe("");
175+
expect(logged.length).toBe(1);
176+
});
177+
});

‎packages/web/test/server/stream-batch-serialize-failure-4242.spec.tsx‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
* that fails to serialize ends the whole write it belongs to, so one async
77
* value seroval cannot handle left every other value in its batch pending on
88
* the client, Loading boundaries' `_fr` completion flags included, and the
9-
* page never finished hydrating. A failed value fails only its own key.
9+
* page never finished hydrating. Writes remain isolated, but an async
10+
* serialization failure fails the render rather than reporting it complete
11+
* with a stranded key (#4647).
1012
*/
1113
import vm from "node:vm";
1214
import { describe, expect, test } from "vitest";
@@ -107,12 +109,19 @@ describe("renderToStream: a value that fails to serialize in the pre-shell batch
107109
]);
108110
});
109111

110-
test("a boundary rejecting with a value seroval cannot handle: its siblings still complete", async () => {
111-
const { r } = await render(() => [
112+
test("a boundary rejecting with a value seroval cannot handle: the render fails before the shell", async () => {
113+
const { html, r, heard } = await render(() => [
112114
slot(() => Promise.reject(Object.assign(new Error("boom"), { retry: () => 1 })), "bad"),
113115
slot(async () => "fine", "fine")
114116
]);
115-
expect(Object.keys(r).filter(k => k.endsWith("_fr"))).toEqual(["0_fr", "1_fr"]);
116-
expect(await outcome(r["1_fr"])).toEqual({ fulfilled: true });
117+
// The rejection never reaches the client, so `0_fr` would stay pending
118+
// there forever: the render fails instead (#4647), and nothing of the
119+
// document ships beside the key that cannot settle.
120+
expect(heard.map(e => String(e))).toEqual([
121+
expect.stringContaining("cannot be parsed/serialized"),
122+
"Error: boom"
123+
]);
124+
expect(html).toBe("");
125+
expect(Object.keys(r)).toEqual([]);
117126
});
118127
});

0 commit comments

Comments
 (0)