Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: simplify ssr flight stream #458

Merged
merged 3 commits into from
Jun 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/react-server/src/entry/browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
} from "../lib/client/router";
import { $__global } from "../lib/global";
import type { CallServerCallback } from "../lib/types";
import { readStreamScript } from "../utils/stream-script";
import { getFlightStreamBrowser } from "../utils/stream-script";

const debug = createDebug("react-server:browser");

Expand Down Expand Up @@ -67,7 +67,7 @@ export async function start() {
// TODO: needs to await for hydration formState. does it affect startup perf?
const initialLayout =
await ReactClient.createFromReadableStream<ServerRouterData>(
readStreamScript<string>().pipeThrough(new TextEncoderStream()),
getFlightStreamBrowser(),
{ callServer },
);
const initialLayoutPromise = Promise.resolve(initialLayout);
Expand Down
13 changes: 2 additions & 11 deletions packages/react-server/src/entry/server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,9 @@ import {
import { $__global } from "../lib/global";
import { ENTRY_REACT_SERVER_WRAPPER, invalidateModule } from "../plugin/utils";
import { escpaeScriptString } from "../utils/escape";
import { jsonStringifyTransform } from "../utils/stream";
import {
createBufferedTransformStream,
injectStreamScript,
injectFlightStream,
} from "../utils/stream-script";
import type { ReactServerHandlerStreamResult } from "./react-server";

Expand Down Expand Up @@ -181,8 +180,6 @@ export async function renderHtml(
// render empty as error fallback and
// let browser render full CSR instead of hydration
// which will replay client error boudnary from RSC error
// TODO: proper two-pass SSR with error route tracking?
// TODO: meta tag system
const errorRoot = (
<html data-no-hydrate>
<head>
Expand All @@ -204,13 +201,7 @@ export async function renderHtml(
.pipeThrough(new TextDecoderStream())
.pipeThrough(createBufferedTransformStream())
.pipeThrough(injectToHead(head))
.pipeThrough(
injectStreamScript(
stream2
.pipeThrough(new TextDecoderStream())
.pipeThrough(jsonStringifyTransform()),
),
)
.pipeThrough(injectFlightStream(stream2))
.pipeThrough(new TextEncoderStream());

return new Response(htmlStream, {
Expand Down
85 changes: 36 additions & 49 deletions packages/react-server/src/utils/stream-script.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,66 +4,53 @@
// https://github.com/vercel/next.js/blob/1c5aa7fa09cc5503c621c534fc40065cbd2aefcb/packages/next/src/client/app-index.tsx#L110-L113
// https://github.com/devongovett/rsc-html-stream/

export function injectStreamScript(stream: ReadableStream<string>) {
const search = "</body>";
const INIT_SCRIPT = `
self.__flightStream = new ReadableStream({
start(controller) {
self.__f_push = (c) => controller.enqueue(c);
self.__f_close = () => controller.close();
}
}).pipeThrough(new TextEncoderStream());
`;

export function injectFlightStream(stream: ReadableStream<Uint8Array>) {
return new TransformStream<string, string>({
async transform(chunk, controller) {
if (!chunk.includes(search)) {
if (chunk.includes("</head>")) {
chunk = chunk.replace(
"</head>",
() => `<script>${INIT_SCRIPT}</script></head>`,
);
}
if (chunk.includes("</body>")) {
const i = chunk.indexOf("</body>");
controller.enqueue(chunk.slice(0, i));
await stream.pipeThrough(new TextDecoderStream()).pipeTo(
new WritableStream({
write(chunk) {
controller.enqueue(
`<script>__f_push(${JSON.stringify(chunk)})</script>`,
);
},
close() {
controller.enqueue(`<script>__f_close()</script>`);
},
}),
);
controller.enqueue(chunk.slice(i));
} else {
controller.enqueue(chunk);
return;
}

const [pre, post] = chunk.split(search);
controller.enqueue(pre);

// TODO: handle cancel?
await stream.pipeTo(
new WritableStream({
start() {
controller.enqueue(`<script>self.__stream_chunks||=[]</script>`);
},
write(chunk) {
// assume chunk is already encoded as javascript code e.g. by
// stream.pipeThrough(jsonStringifyTransform())
controller.enqueue(
`<script>__stream_chunks.push(${chunk})</script>`,
);
},
}),
);

controller.enqueue(search + post);
},
});
}

export function readStreamScript<T>() {
return new ReadableStream<T>({
start(controller) {
const chunks: T[] = ((globalThis as any).__stream_chunks ||= []);

for (const chunk of chunks) {
controller.enqueue(chunk);
}

chunks.push = function (chunk) {
controller.enqueue(chunk);
return 0;
};

if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => {
controller.close();
});
} else {
controller.close();
}
},
});
export function getFlightStreamBrowser(): ReadableStream<Uint8Array> {
return (self as any).__flightStream;
}

// it seems buffering is necessary to ensure tag marker (e.g. `</body>`) is not split into multiple chunks.
// Without this, above `injectStreamScript` breaks when receiving two chunks for "...<" and "/body>...".
// Without this, above `injectFlightStream` breaks when receiving two chunks separately for "...<" and "/body>...".
// see https://github.com/hi-ogawa/vite-plugins/pull/457
export function createBufferedTransformStream() {
let timeout: ReturnType<typeof setTimeout> | undefined;
Expand Down
11 changes: 0 additions & 11 deletions packages/react-server/src/utils/stream.ts

This file was deleted.