feat: streaming rendering with suspense (#59)

This commit introduces support for streaming server side rendering using
<Suspense>.
This commit is contained in:
Luca Casonato
2021-09-26 01:21:02 +02:00
committed by GitHub
parent 75afa6daca
commit 7cf4ca07ed
11 changed files with 256 additions and 48 deletions
+6 -20
View File
@@ -1,32 +1,18 @@
// This module adds twind support.
import {
getStyleTagProperties,
virtualSheet,
} from "https://esm.sh/twind/sheets";
import { h, setup } from "../deps.ts";
import { virtualSheet } from "https://esm.sh/twind/sheets";
import { setup } from "../deps.ts";
import { RenderContext, RenderFn } from "../server_deps.ts";
const sheet = virtualSheet();
const initial = sheet.reset();
sheet.reset();
setup({ sheet });
export function render(ctx: RenderContext, render: RenderFn) {
const snapshot = ctx.state.get("twindSnapshot") as unknown[] | null;
sheet.reset(snapshot || initial);
sheet.reset(snapshot || undefined);
render();
const newSnapshot = sheet.reset(initial);
ctx.styles.splice(0, ctx.styles.length, ...sheet.target);
const newSnapshot = sheet.reset();
ctx.state.set("twindSnapshot", newSnapshot);
}
export function postRender(ctx: RenderContext) {
const snapshot = ctx.state.get("twindSnapshot") as unknown[] | null;
if (snapshot !== null) {
sheet.reset(snapshot);
const { id, textContent } = getStyleTagProperties(sheet);
ctx.head.push(
h("style", { id, dangerouslySetInnerHTML: { __html: textContent } }),
);
}
sheet.reset(initial);
}
+28
View File
@@ -0,0 +1,28 @@
/** @jsx h */
import { h, Suspense, tw, useData } from "../deps.ts";
export default function SuspensePage() {
return (
<Suspense
fallback={(
<p class={tw`text-red-500 hover:text-purple-500`}>
Loading...
</p>
)}
>
<SuspendedComponent />
</Suspense>
);
}
export function SuspendedComponent() {
const data = useData("Loaded", delayer);
return <p class={tw`text-blue-500 hover:text-green-500`}>{data}!</p>;
}
// A function that returns a promise that resolves after a delay with the given
// value.
function delayer(key: string) {
return new Promise((resolve) => setTimeout(() => resolve(key), 2000));
}
+10 -8
View File
@@ -2,19 +2,21 @@
// This file SHOULD be checked into source version control.
// To update this file, run `fresh routes`.
import * as $0 from "./pages/api/joke.ts";
import * as $0 from "./pages/index.tsx";
import * as $1 from "./pages/_render.ts";
import * as $2 from "./pages/x/[module].tsx";
import * as $3 from "./pages/[name].tsx";
import * as $4 from "./pages/index.tsx";
import * as $2 from "./pages/suspense.tsx";
import * as $3 from "./pages/api/joke.ts";
import * as $4 from "./pages/[name].tsx";
import * as $5 from "./pages/x/[module].tsx";
const routes = {
pages: {
"./pages/api/joke.ts": $0,
"./pages/index.tsx": $0,
"./pages/_render.ts": $1,
"./pages/x/[module].tsx": $2,
"./pages/[name].tsx": $3,
"./pages/index.tsx": $4,
"./pages/suspense.tsx": $2,
"./pages/api/joke.ts": $3,
"./pages/[name].tsx": $4,
"./pages/x/[module].tsx": $5,
},
baseUrl: import.meta.url,
};
+2 -2
View File
@@ -5,7 +5,7 @@ lint:
deno lint
test:
deno test --no-check -A
deno test -A
watch_example:
deno run -A --unstable --watch example/main.ts
deno run -A --unstable --watch --no-check example/main.ts
+1
View File
@@ -1,4 +1,5 @@
export * from "./src/runtime/deps.ts";
export * from "./src/runtime/types.ts";
export * from "./src/runtime/suspense.ts";
export * from "./src/runtime/utils.ts";
export * from "./src/runtime/hooks.ts";
+33
View File
@@ -0,0 +1,33 @@
import {
ComponentChild,
ComponentChildren,
createContext,
Fragment,
h,
useContext,
} from "./deps.ts";
import { IS_BROWSER } from "./utils.ts";
export const SUSPENSE_CONTEXT = createContext<ComponentChildren[]>([]);
export interface SuspenseProps {
fallback: ComponentChild;
children: ComponentChildren;
}
export function Suspense(props: SuspenseProps) {
if (IS_BROWSER) {
throw new Error(`'<Suspense>' is not supported on the client yet.`);
}
const suspenseData = useContext(SUSPENSE_CONTEXT);
const id = suspenseData.push(props.children);
return h(
Fragment,
null,
h("template", { id: `S:${id}` }),
props.fallback,
h("template", { id: `E:${id}` }),
);
}
+34
View File
@@ -0,0 +1,34 @@
(() => {
/** Replace a suspense component with it's final variant. */
window.$SR = (id) => {
const targetStart = document.getElementById("S:" + id);
const targetEnd = document.getElementById("E:" + id);
const replacement = document.getElementById("R:" + id);
replacement.parentNode.removeChild(replacement);
while (targetStart.nextSibling !== targetEnd) {
targetStart.parentNode.removeChild(targetStart.nextSibling);
}
while (replacement.firstChild) {
targetStart.parentNode.insertBefore(replacement.firstChild, targetEnd);
}
targetStart.parentNode.removeChild(targetStart);
targetEnd.parentNode.removeChild(targetEnd);
};
/** @type {HTMLStyleElement} */
const sheetElement = document.getElementById("__FRSH_STYLE");
const rules = sheetElement.childNodes[0].textContent.split(`\n`);
sheetElement.removeChild(sheetElement.firstChild);
for (const rule of rules) {
sheetElement.append(document.createTextNode(rule));
}
/** Insert new style rules. */
window.$ST = (inserts) => {
for (const [rule, index] of inserts) {
sheetElement.insertBefore(
document.createTextNode(rule),
sheetElement.childNodes[index],
);
}
};
})();
+11 -3
View File
@@ -144,11 +144,12 @@ export class ServerContext {
params: Record<string, string | string[]>,
) => {
if (page.component === undefined) return undefined;
// deno-lint-ignore require-await
const render = async () => {
const preloads = page.runtimeJS
? this.#bundler.getPreloads(bundlePath).map(bundleAssetUrl)
: [];
const body = await internalRender({
const body = internalRender({
page,
imports,
preloads,
@@ -156,7 +157,15 @@ export class ServerContext {
url: new URL(req.url),
params,
});
return new Response(body, {
const bodyStream = new ReadableStream<Uint8Array>({
async start(controller) {
for await (const chunk of body) {
controller.enqueue(new TextEncoder().encode(chunk));
}
controller.close();
},
});
return new Response(bodyStream, {
status: 200,
headers: {
"content-type": "text/html; charset=utf-8",
@@ -243,7 +252,6 @@ const DEFAULT_RENDERER: Renderer = {
render(_ctx, render) {
render();
},
postRender(_ctx) {},
};
/**
+125 -13
View File
@@ -1,10 +1,11 @@
/** @jsx h */
import { renderToString } from "./deps.ts";
import { ComponentChild, h } from "../runtime/deps.ts";
import { ComponentChild, ComponentChildren, h } from "../runtime/deps.ts";
import { DATA_CONTEXT } from "../runtime/hooks.ts";
import { Page, Renderer } from "./types.ts";
import { PageProps } from "../runtime/types.ts";
import { SUSPENSE_CONTEXT } from "../runtime/suspense.ts";
export interface RenderOptions {
page: Page;
@@ -20,7 +21,7 @@ export type RenderFn = () => void;
export class RenderContext {
#id: string;
#state: Map<string, unknown> = new Map();
#head: ComponentChild[] = [];
#styles: string[] = [];
#url: URL;
#route: string;
#lang = "en";
@@ -46,10 +47,13 @@ export class RenderContext {
}
/**
* Items to add to the <head> for this render.
* All of the CSS style rules that should be inlined into the document.
* Adding to this list across multiple renders is supported (even across
* suspense!). The CSS rules will always be inserted on the client in the
* order specified here.
*/
get head(): ComponentChild[] {
return this.#head;
get styles(): string[] {
return this.#styles;
}
/** The URL of the page being rendered. */
@@ -74,20 +78,49 @@ export class RenderContext {
const MAX_SUSPENSE_DEPTH = 10;
export async function render(opts: RenderOptions): Promise<string> {
/**
* This function renders out a page. Rendering is asynchronous, and streaming.
* Rendering happens in multiple steps, because of the need to handle suspense.
*
* 1. The page's vnode tree is constructed.
* 2. The page's vnode tree is passed to the renderer.
* - If the rendering throws a promise, the promise is awaited before
* continuing. This allows the renderer to handle async hooks.
* - Once the rendering throws no more promises, the initial render is
* complete and a body string is returned.
* - During rendering, every time a `<Suspense>` is rendered, it, and it's
* attached children are recorded for later rendering.
* 3. Once the inital render is complete, the body string is fitted into the
* HTML wrapper template.
* 4. The full inital render in the template is yielded to be sent to the
* client.
* 5. Now the suspended vnodes are rendered. These are individually rendered
* like described in step 2 above. Once each node is done rendering, it
* wrapped in some boilderplate HTML, and suffixed with some JS, and then
* sent to the client. On the client the HTML will be slotted into the DOM
* at the location of the original `<Suspense>` node.
*/
export async function* render(opts: RenderOptions): AsyncIterable<string> {
const props = { params: opts.params, url: opts.url, route: opts.page.route };
const dataCache = new Map();
const suspenseQueue: ComponentChildren[] = [];
const vnode = h(DATA_CONTEXT.Provider, {
value: dataCache,
children: h(opts.page.component!, props),
children: h(SUSPENSE_CONTEXT.Provider, {
value: suspenseQueue,
children: h(opts.page.component!, props),
}),
});
const ctx = new RenderContext(crypto.randomUUID(), opts.url, opts.page.route);
let suspended = 0;
const renderWithRenderer = (): string | Promise<string> => {
// Clear the suspense queue
suspenseQueue.splice(0, suspenseQueue.length);
if (++suspended > MAX_SUSPENSE_DEPTH) {
throw new Error(
`Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`,
@@ -122,8 +155,6 @@ export async function render(opts: RenderOptions): Promise<string> {
const bodyHtml = await renderWithRenderer();
opts.renderer.postRender(ctx, bodyHtml);
let templateProps: {
props: PageProps;
data?: [string, unknown][];
@@ -142,18 +173,96 @@ export async function render(opts: RenderOptions): Promise<string> {
bodyHtml,
imports: opts.imports,
preloads: opts.preloads,
head: ctx.head,
styles: ctx.styles,
props: templateProps,
lang: ctx.lang,
});
return html;
let clientStyles = [...ctx.styles];
yield html;
if (suspenseQueue.length > 0) {
// minified client-side JS
yield `<script>(()=>{window.$SR=(e=>{const t=document.getElementById("S:"+e),o=document.getElementById("E:"+e),d=document.getElementById("R:"+e);for(d.parentNode.removeChild(d);t.nextSibling!==o;)t.parentNode.removeChild(t.nextSibling);for(;d.firstChild;)t.parentNode.insertBefore(d.firstChild,o);t.parentNode.removeChild(t),o.parentNode.removeChild(o)});const e=document.getElementById("__FRSH_STYLE"),t=e.childNodes[0].textContent.split("\n");e.removeChild(e.firstChild);for(const o of t)e.append(document.createTextNode(o));window.$ST=(t=>{for(const[o,d]of t)e.insertBefore(document.createTextNode(o),e.childNodes[d])})})();</script>`
.replaceAll("\n", "\\n");
}
// TODO(lucacasonato): parallelize this
for (const [id, children] of suspenseQueue.entries()) {
const fragment = await suspenseRender(opts.renderer, ctx, id + 1, children);
const cssInserts: [string, number][] = [];
for (const [i, style] of ctx.styles.entries()) {
if (!clientStyles.includes(style)) {
cssInserts.push([style, i]);
}
}
clientStyles = [...ctx.styles];
if (cssInserts.length > 0) {
yield `<script>$ST(${JSON.stringify(cssInserts)});</script>`;
}
yield fragment;
}
}
export async function suspenseRender(
renderer: Renderer,
ctx: RenderContext,
id: number,
children: ComponentChildren,
): Promise<string> {
const dataCache = new Map();
const vnode = h(DATA_CONTEXT.Provider, {
value: dataCache,
children,
});
let suspended = 0;
const renderWithRenderer = (): string | Promise<string> => {
if (++suspended > MAX_SUSPENSE_DEPTH) {
throw new Error(
`Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`,
);
}
let body: string | null = null;
let promise: Promise<unknown> | null = null;
function render() {
try {
body = renderToString(vnode);
} catch (e) {
if (e && e.then) {
promise = e;
return;
}
throw e;
}
}
renderer.render(ctx, render);
if (body !== null) {
return body;
} else if (promise !== null) {
return (promise as Promise<unknown>).then(renderWithRenderer);
} else {
throw new Error("`render` function not called by renderer.");
}
};
const html = await renderWithRenderer();
return `<div hidden id="R:${id}">${html}</div><script>$SR(${id})</script>`;
}
export interface TemplateOptions {
bodyHtml: string;
imports: string[];
head: ComponentChild[];
styles: string[];
preloads: string[];
props: unknown;
lang: string;
@@ -165,7 +274,10 @@ export function template(opts: TemplateOptions): string {
<head>
{opts.preloads.map((src) => <link rel="modulepreload" href={src} />)}
{opts.imports.map((src) => <script src={src} type="module"></script>)}
{opts.head}
<style
id="__FRSH_STYLE"
dangerouslySetInnerHTML={{ __html: opts.styles.join("\n") }}
/>
</head>
<body>
<div dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} id="__FRSH" />
-2
View File
@@ -34,10 +34,8 @@ export interface Page {
export interface RendererModule {
render(ctx: RenderContext, render: RenderFn): void;
postRender(ctx: RenderContext, bodyHtml: string): void;
}
export interface Renderer {
render(ctx: RenderContext, render: RenderFn): void;
postRender(ctx: RenderContext, bodyHtml: string): void;
}
+6
View File
@@ -1 +1,7 @@
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />
/// <reference lib="deno.unstable" />
export * from "../../runtime.ts";