Skip to content

Commit 8506dbf

Browse files
ryansolidclaude
andauthored
fix(web): a deferStream rejection goes out as a rejection (#4747) (#4750)
renderToStream's serialize wrote a deferStream source's rejection reason as the key's value. The client adopted the Error as the memo's value, so after reset() the content rendered the Error and the memo never ran. The reason now goes out as a rejected promise, the way a streamed source's does, and a reason the serializer cannot encode takes the streamed path's replacement. Claude-Session: https://claude.ai/code/session_0117BoWNSSgtemsSYsaX2hXE Co-authored-by: Claude <[email protected]>
1 parent da402ca commit 8506dbf

8 files changed

Lines changed: 215 additions & 17 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+
fix(web): a `deferStream` source that rejects on the server hydrates as a rejection, so `reset()` refetches it on the client (#4747)

‎packages/web/src/server.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2387,7 +2387,6 @@ export function renderToStream(code, options = {}) {
23872387
// The reason each serialized promise rejected with, by key: what a write
23882388
// of that key fails on when seroval cannot encode it.
23892389
const rejected = new Map();
2390-
const REJECTION = 2;
23912390
const plainMessage = (id, value) =>
23922391
value != null && typeof value.message === "string"
23932392
? value.message
@@ -2420,8 +2419,7 @@ export function renderToStream(code, options = {}) {
24202419
}
24212420
unclaimed.add(reason);
24222421
};
2423-
// `error`: true for an `<Errored>` record, REJECTION for the reason a
2424-
// deferStream source rejected with.
2422+
// `error`: true for an `<Errored>` record.
24252423
const handOver = (id, value, error) => {
24262424
if (!error || options.serializer) return serializer.write(id, value);
24272425
let plain = value !== null && typeof value === "object" && plainRecords.get(value);
@@ -2437,7 +2435,6 @@ export function renderToStream(code, options = {}) {
24372435
plain = plainFor(id, value);
24382436
}
24392437
serializer.write(id, plain);
2440-
if (error === REJECTION) claimLater(value);
24412438
};
24422439
const write = (id, value, error) => {
24432440
if (stableOrder && !dead) (parkedWrites ||= []).push([id, value, error]);
@@ -3064,7 +3061,17 @@ export function renderToStream(code, options = {}) {
30643061
if (p && typeof p === "object" && typeof p.then === "function") {
30653062
if (!firstFlushed && deferStream) {
30663063
blockingPromises.add(p);
3067-
p.then(d => write(id, d)).catch(e => write(id, e, REJECTION));
3064+
// A rejection goes out as one (#4747): a rejected promise the
3065+
// client reads off its mark and rethrows, as it does a streamed
3066+
// source's, never the reason as the source's value. Its reason
3067+
// fails to encode, if it does, as a streamed rejection's does
3068+
// (`rejected`, the serializer's `onError`).
3069+
p.then(d => write(id, d)).catch(e => {
3070+
rejected.set(id, e);
3071+
const r = Promise.reject(e);
3072+
r.catch(() => {});
3073+
write(id, r);
3074+
});
30683075
return;
30693076
}
30703077
// Every pending promise handed to seroval joins the abandonment
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"shell": "<main _hk=1><p _hk=30 class=\"fb\">x</p></main><script>(self.$R=self.$R||{})[\"\"]=[];_$HY.r[\"0\"]=$R[0]=($R[1]=($R[2]=() => {\n\tconst resolver = {\n\t\tp: 0,\n\t\ts: 0,\n\t\tf: 0\n\t};\n\tresolver.p = new Promise((resolve, reject) => {\n\t\tresolver.s = resolve;\n\t\tresolver.f = reject;\n\t});\n\treturn resolver;\n})()).p;($R[4]=(resolver, data) => {\n\tresolver.f(data);\n\tresolver.p.s = 2;\n\tresolver.p.v = data;\n})($R[1],$R[3]=Object.assign(new Error(\"x\"),{code:42}));_$HY.r[\"2\"]=$R[3];</script>",
3+
"chunks": []
4+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"shell": "<main _hk=1><p _hk=30 class=\"fb\">x</p></main><script>(self.$R=self.$R||{})[\"\"]=[];_$HY.r[\"0\"]=$R[0]=($R[1]=($R[2]=() => {\n\tconst resolver = {\n\t\tp: 0,\n\t\ts: 0,\n\t\tf: 0\n\t};\n\tresolver.p = new Promise((resolve, reject) => {\n\t\tresolver.s = resolve;\n\t\tresolver.f = reject;\n\t});\n\treturn resolver;\n})()).p;($R[4]=(resolver, data) => {\n\tresolver.f(data);\n\tresolver.p.s = 2;\n\tresolver.p.v = data;\n})($R[1],$R[3]=Object.assign(new Error(\"x\"),{code:42}));_$HY.r[\"2\"]=$R[3];</script>",
3+
"chunks": []
4+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
*
4+
* Fixtures for #4747: a memo that rejects on the server inside an
5+
* `<Errored>`, read with and without `deferStream`. Rendered by
6+
* test/server/errored-deferstream-rejection-4747.gen.spec.tsx, replayed by
7+
* test/hydration/errored-deferstream-rejection-4747.spec.tsx. The same
8+
* components run on both sides: `env.client` picks what `ask` answers.
9+
*/
10+
import { createMemo } from "solid-js";
11+
import { Errored } from "@solidjs/web";
12+
13+
export const env: {
14+
client: boolean;
15+
runs: number;
16+
RealPromise: PromiseConstructor;
17+
reset?: () => void;
18+
} = { client: false, runs: 0, RealPromise: Promise };
19+
20+
// Server: a rejection; client: a value. The hydration dry run computes under
21+
// a mock Promise: count real asks only.
22+
function ask(): Promise<string> {
23+
if (!env.client) return Promise.reject(Object.assign(new Error("x"), { code: 42 }));
24+
if (Promise === env.RealPromise) env.runs++;
25+
return Promise.resolve("client value");
26+
}
27+
28+
function App(props: { deferStream: boolean }) {
29+
const item = createMemo(() => ask(), { deferStream: props.deferStream });
30+
return (
31+
<main>
32+
<Errored
33+
fallback={(e: () => any, reset: () => void) => {
34+
env.reset = reset;
35+
return <p class="fb">{e().message}</p>;
36+
}}
37+
>
38+
<p class="content">{String(item())}</p>
39+
</Errored>
40+
</main>
41+
);
42+
}
43+
44+
export const AppStreamed = () => <App deferStream={false} />;
45+
export const AppDeferred = () => <App deferStream={true} />;
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
* @vitest-environment jsdom
4+
*
5+
* #4747: a source that rejected on the server inside an `<Errored>` hydrates
6+
* as a rejection whether or not it was `deferStream`. The boundary keeps the
7+
* server's fallback without a fetch, and `reset()` reruns the source as a
8+
* client fetch (#4273). Before the fix, a `deferStream` rejection went out as
9+
* a value: after `reset()` the content rendered the `Error` and the memo never
10+
* ran on the client.
11+
*
12+
* Replays the streamed output test/server/errored-deferstream-rejection-4747.gen.spec.tsx
13+
* records from the same components (test/harness/errored-deferstream-rejection-4747.tsx).
14+
*/
15+
import { readFileSync } from "node:fs";
16+
import { dirname, resolve } from "node:path";
17+
import { fileURLToPath } from "node:url";
18+
import { afterEach, beforeEach, expect, test } from "vitest";
19+
import { enableHydration, flush } from "solid-js";
20+
import { hydrate } from "@solidjs/web";
21+
import { AppDeferred, AppStreamed, env } from "../harness/errored-deferstream-rejection-4747.jsx";
22+
23+
enableHydration();
24+
env.client = true;
25+
const RealPromise = Promise;
26+
env.RealPromise = RealPromise;
27+
28+
const load = (name: string) => {
29+
const { shell, chunks } = JSON.parse(
30+
readFileSync(
31+
resolve(
32+
dirname(fileURLToPath(import.meta.url)),
33+
`../harness/__artifacts__/errored-deferstream-rejection-4747-${name}.json`
34+
),
35+
"utf-8"
36+
)
37+
) as { shell: string; chunks: string[] };
38+
return shell + chunks.join("");
39+
};
40+
41+
async function drain(n = 3) {
42+
for (let i = 0; i < n; i++) {
43+
await new RealPromise(r => setTimeout(r, 5));
44+
flush();
45+
}
46+
}
47+
48+
const uncaught: string[] = [];
49+
const onRejection = (e: any) => void uncaught.push("unhandledRejection:" + (e?.message || e));
50+
const onException = (e: any) => void uncaught.push("uncaughtException:" + (e?.message || e));
51+
52+
function mount(container: HTMLElement, html: string) {
53+
delete (globalThis as any).$R;
54+
(globalThis as any)._$HY = { events: [], completed: new WeakSet(), r: {}, fe() {} };
55+
const scriptRe = /<script(?:[^>]*)>([\s\S]*?)<\/script>/g;
56+
const scripts = [...html.matchAll(scriptRe)].map(m => m[1]);
57+
container.innerHTML = html.replace(scriptRe, "");
58+
for (const s of scripts) (0, eval)(s);
59+
}
60+
61+
let container: HTMLDivElement;
62+
let dispose: (() => void) | undefined;
63+
beforeEach(() => {
64+
container = document.createElement("div");
65+
document.body.appendChild(container);
66+
env.runs = 0;
67+
env.reset = undefined;
68+
uncaught.length = 0;
69+
process.on("unhandledRejection", onRejection);
70+
process.on("uncaughtException", onException);
71+
});
72+
afterEach(() => {
73+
dispose?.();
74+
dispose = undefined;
75+
container.remove();
76+
process.off("unhandledRejection", onRejection);
77+
process.off("uncaughtException", onException);
78+
});
79+
80+
test.each([
81+
["streamed", AppStreamed],
82+
["deferred", AppDeferred]
83+
] as const)(
84+
"%s: the server's fallback is kept without a fetch, and reset() recovers by one client run",
85+
async (name, App) => {
86+
mount(container, load(name));
87+
const fb = container.querySelector(".fb");
88+
expect(fb?.textContent).toBe("x");
89+
dispose = hydrate(() => <App />, container);
90+
await drain();
91+
expect(container.querySelector(".fb")).toBe(fb);
92+
expect(env.runs).toBe(0);
93+
94+
env.reset!();
95+
await drain(8);
96+
expect(env.runs).toBe(1);
97+
expect(container.querySelector(".content")?.textContent).toBe("client value");
98+
expect(container.querySelector(".fb")).toBeNull();
99+
expect(uncaught).toEqual([]);
100+
}
101+
);
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @jsxImportSource @solidjs/web
3+
*
4+
* Server half of test/hydration/errored-deferstream-rejection-4747.spec.tsx:
5+
* renders each fixture and writes its shell plus each later chunk.
6+
*/
7+
import { expect, test } from "vitest";
8+
import { AppDeferred, AppStreamed } from "../harness/errored-deferstream-rejection-4747.jsx";
9+
import { recordStream, writeArtifact } from "./artifact-recorder.js";
10+
11+
for (const [name, App] of [
12+
["streamed", AppStreamed],
13+
["deferred", AppDeferred]
14+
] as const) {
15+
test(`render errored-deferstream-rejection-4747-${name} chunks`, async () => {
16+
let completed = false;
17+
const { shell, chunks } = await recordStream(() => <App />, {
18+
onError: () => {},
19+
onCompleteAll: () => void (completed = true)
20+
});
21+
expect(completed).toBe(true);
22+
expect(shell + chunks.join("")).toContain('class="fb"');
23+
writeArtifact(`errored-deferstream-rejection-4747-${name}`, { shell, chunks });
24+
});
25+
}

‎packages/web/test/server/stream-contained-error-serialize-4709.spec.tsx‎

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,10 @@ const contained: [string, Contained][] = [
158158
);
159159
},
160160
main: "<main><p>fallback</p></main>",
161-
// The source's key and the boundary's record carry the one replacement.
162-
records: [plain("x"), plain("x")],
161+
// The boundary's record; the source's promise rejects with the same
162+
// replacement, as a streamed source's does (#4747).
163+
records: [plain("x")],
164+
rejected: [plain("x")],
163165
heard: ["render/fallback", "render/serialize"]
164166
}
165167
],
@@ -213,7 +215,8 @@ const contained: [string, Contained][] = [
213215
);
214216
},
215217
main: "<main><p>fallback</p></main>",
216-
records: [plain("x"), plain("x")],
218+
records: [plain("x")],
219+
rejected: [plain("x")],
217220
heard: ["render/fallback", "render/serialize"]
218221
}
219222
],
@@ -265,8 +268,9 @@ const contained: [string, Contained][] = [
265268
},
266269
map: mapFallback,
267270
main: /^<main><p>(<!--\$-->)?mapped(<!--\/-->)?<\/p><\/main>$/,
268-
// The source's key carries what its channel rejected with; the record is the mapping.
269-
records: [plain("x"), plain("mapped")],
271+
// The source's promise rejects with what its channel rejected with; the record is the mapping.
272+
records: [plain("mapped")],
273+
rejected: [plain("x")],
270274
heard: ["render/fallback", "render/serialize"]
271275
}
272276
],
@@ -302,7 +306,8 @@ const contained: [string, Contained][] = [
302306
);
303307
},
304308
main: "<main><p>inner</p></main>",
305-
records: [plain("x"), plain("x")],
309+
records: [plain("x")],
310+
rejected: [plain("x")],
306311
heard: ["render/fallback", "render/serialize"]
307312
}
308313
],
@@ -328,7 +333,8 @@ const contained: [string, Contained][] = [
328333
);
329334
},
330335
main: /^<main><p>(<!--\$-->)?outer(<!--\/-->)?<\/p><\/main>$/,
331-
records: [plain("inner"), plain("outer"), plain("inner")],
336+
records: [plain("outer"), plain("inner")],
337+
rejected: [plain("inner")],
332338
heard: ["render/fallback", "render/fallback", "render/serialize", "render/serialize"]
333339
}
334340
]
@@ -436,10 +442,9 @@ describe("unchanged", () => {
436442
expect(main(html)).toBe("<main><p>fallback</p></main>");
437443
expect(completed).toBe(true);
438444
expect(heard).toEqual(["render/fallback"]);
439-
expect(errorRecords(html)).toEqual([
440-
{ message: "x", keys: ["code"] },
441-
{ message: "x", keys: ["code"] }
442-
]);
445+
// The boundary's record, and the source's rejection (#4747).
446+
expect(errorRecords(html)).toEqual([{ message: "x", keys: ["code"] }]);
447+
expect(rejections(html)).toEqual([{ message: "x", keys: ["code"] }]);
443448
});
444449

445450
test("a value that fails to serialize fails the render inside a boundary too (#4709)", async () => {
@@ -594,7 +599,9 @@ describe.each([
594599
const records = [...errorRecords(results[key].html), ...rejections(results[key].html)];
595600
expect(records.map(r => r.message)).toContain(wire);
596601
expect(records.every(r => r.keys.length === 0)).toBe(true);
597-
expect(rejections(results[key].html)).toEqual(key === "streamed" ? [plain(wire)] : []);
602+
// Every source rejects as a rejection (#4747), with what its channel
603+
// rejected with: a hook's mapping is the boundary's record only.
604+
expect(rejections(results[key].html)).toEqual([plain(key === "mapped" ? plainWire : wire)]);
598605
expect(results[key].heard).toEqual([
599606
"render/fallback",
600607
...Array(failures).fill("render/serialize")

0 commit comments

Comments
 (0)