prerender.ts
This file
Path
apps/web/src/features/code/prerender.ts
271 lines · 8.4 KiB · TypeScript
Last changed by
Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
History of this fileTake it
Merge perf/ssr-highlight into mainoscabrielbefore adoption5881ff2
lines 1–271why, one step back1/**2 * Which code the server sends highlighted, and where its drawing waits3 * between the page's loader and its render.4 *5 * The server highlights a fixed set of languages (`SERVER_LANGUAGES`, the6 * grammars the Worker bundles) and only within its own limit, far below7 * the browser's: a page highlights at most `SERVER_LINES` lines of text8 * (a diff counts both sides, as Pierre highlights both whole files), and9 * no line longer than the drawing's own line limit, so a minified file is10 * never tokenized on the server. Anything else is sent as plain text, as11 * before, and the browser highlights it.12 *13 * Both sides decide alike from the page's own data, so the browser knows14 * which code arrived highlighted without being told.15 *16 * The drawing is made once per (blob, path) or (both blobs, path), so it17 * is kept here, keyed by those ids, which never change what they name: the18 * loader starts it and waits for it, and the render reads it at once. A19 * few are kept, within a byte budget, so a file read again is not drawn20 * again. Nothing here runs in the browser but the decision.21 */22import { getFiletypeFromFileName } from "@pierre/diffs";23import type { ChangedFile } from "@repo/protocol/domain/code";24import { Effect, Option } from "effect";2526import { drawnFiles } from "./diff-model.ts";27import type { DrawnFile } from "./diff-model.ts";28import { diffsOptions } from "./pierre.ts";2930/** The languages the Worker bundles a grammar for, by the names Pierre gives a file's type. */31export const SERVER_LANGUAGES = [32 "css",33 "html",34 "javascript",35 "json",36 "jsx",37 "markdown",38 "toml",39 "tsx",40 "typescript",41 "yaml",42 "yml",43 "zsh",44] as const;4546export type ServerLanguage = (typeof SERVER_LANGUAGES)[number];4748/**49 * The most lines the server highlights for one page. Measured in the dev50 * world's workerd (ADR 0027), warm: 2,400 lines of TypeScript took about51 * 315 ms, 600 about 85 ms and 400 about 57 ms, so a page spends at most52 * some 60 ms highlighting, and a longer file is sent plain.53 */54export const SERVER_LINES = 400;5556/** The most files of a diff the server highlights: those a reader sees first. */57export const SERVER_FILES = 8;5859const isServerLanguage = (name: string): name is ServerLanguage =>60 SERVER_LANGUAGES.some((language) => language === name);6162/** The language the server highlights `path` in, if it highlights it at all. */63export const serverLanguageOf = (64 path: string65): Option.Option<ServerLanguage> => {66 const name = getFiletypeFromFileName(path);6768 return isServerLanguage(name) ? Option.some(name) : Option.none();69};7071/** `text`'s lines, or none when one is longer than the drawing tokenizes. */72const linesWithin = (text: string): Option.Option<number> => {73 const lines = text.split("\n");7475 return lines.every(76 (line) => line.length <= diffsOptions.tokenizeMaxLineLength77 )78 ? Option.some(lines.length)79 : Option.none();80};8182/** Whether the server sends this file highlighted. */83export const prerendersFile = (file: {84 readonly path: string;85 readonly text: string;86}) =>87 Option.isSome(serverLanguageOf(file.path)) &&88 file.text.length <= diffsOptions.tokenizeMaxLength &&89 Option.exists(linesWithin(file.text), (lines) => lines <= SERVER_LINES);9091/** A diff's lines on both sides, or none when a side has a line too long. */92const diffLines = (drawn: DrawnFile): Option.Option<number> => {93 const sides = [drawn.file.oldText, drawn.file.newText].flatMap((text) =>94 text === undefined ? [] : [linesWithin(text)]95 );9697 return Option.all(sides).pipe(98 Option.map((counts) => counts.reduce((sum, count) => sum + count, 0))99 );100};101102/**103 * The paths of a diff the server sends highlighted, unified: among the104 * first `SERVER_FILES` files that start open and have lines, those in a105 * server language, within `SERVER_LINES` together.106 */107export const prerenderedPaths = (108 drawn: readonly DrawnFile[]109): ReadonlySet<string> => {110 const paths = new Set<string>();111 let spent = 0;112113 const open = drawn114 .filter((file) => !file.folded && Option.isSome(file.diff))115 .slice(0, SERVER_FILES);116117 for (const file of open) {118 const lines = diffLines(file);119120 if (121 Option.isSome(serverLanguageOf(file.file.path)) &&122 Option.isSome(lines) &&123 spent + lines.value <= SERVER_LINES124 ) {125 spent += lines.value;126 paths.add(file.file.path);127 }128 }129130 return paths;131};132133/** A drawing as React's `use` reads it: settled ones say so, so a render never waits on them. */134type Drawing = Promise<string | undefined> & {135 status?: "fulfilled";136 value?: string | undefined;137};138139/** How many drawings are kept, and how many characters of HTML at most. */140const KEPT = { count: 24, size: 8_000_000 } as const;141142/** The drawings made, the oldest first; each id names what it draws for good. */143const kept = new Map<string, { readonly drawing: Drawing; size: number }>();144145const sizeOf = () =>146 [...kept.values()].reduce((sum, entry) => sum + entry.size, 0);147148/** Drops the oldest drawings past the count or the size. */149const trim = () => {150 for (const id of kept.keys()) {151 if (kept.size <= KEPT.count && sizeOf() <= KEPT.size) {152 return;153 }154155 kept.delete(id);156 }157};158159/** The drawing `id` names: the one kept, or one `make` starts now. */160const keptDrawing = <E>(161 id: string,162 make: Effect.Effect<string | undefined, E>163): Drawing => {164 const known = kept.get(id);165166 if (known !== undefined) {167 kept.delete(id);168 kept.set(id, known);169170 return known.drawing;171 }172173 // A drawing that fails is none: the page sends the plain text instead.174 const drawing: Drawing = Effect.runPromise(175 make.pipe(Effect.orElseSucceed((): string | undefined => undefined))176 );177178 const entry = { drawing, size: 0 };179180 kept.set(id, entry);181 // Settled, it says so (`use` then reads it without waiting) and counts182 // its size. Subscribed first, so whoever awaits it next finds it marked.183 Effect.runFork(184 Effect.promise(() => drawing).pipe(185 Effect.andThen((html) =>186 Effect.sync(() => {187 drawing.status = "fulfilled";188 drawing.value = html;189 entry.size = html?.length ?? 0;190 trim();191 })192 )193 )194 );195 trim();196197 return drawing;198};199200/**201 * The server's drawing module, on its first use. The browser's build has202 * none (`import.meta.env.SSR` is false there, so the import is dead code),203 * and draws nothing here.204 */205const server = () =>206 import.meta.env.SSR207 ? Effect.tryPromise(() => import("./prerender-server.ts"))208 : Effect.die("Only the server draws code ahead");209210/** The id a file's drawing is kept by: its blob and its path (which names its language). */211export const fileDrawingId = (file: {212 readonly path: string;213 readonly sha: string;214}) => `file:${file.sha}:${file.path}`;215216/** The id a diff's drawing is kept by: both its blobs and its path. */217export const diffDrawingId = (drawn: DrawnFile) =>218 `${drawn.file.before ?? "none"}:${drawn.file.after ?? "none"}:${drawn.file.path}`;219220/** A file highlighted by the server, as the HTML of its shadow root; none if it could not be. */221export const fileDrawing = (file: {222 readonly path: string;223 readonly sha: string;224 readonly text: string;225}) =>226 keptDrawing(227 fileDrawingId(file),228 server().pipe(Effect.andThen(({ prerenderFile }) => prerenderFile(file)))229 );230231/** A diff's file highlighted by the server, unified, as the HTML of its shadow root. */232export const diffDrawing = (drawn: DrawnFile) =>233 keptDrawing(234 diffDrawingId(drawn),235 server().pipe(Effect.andThen(({ prerenderDiff }) => prerenderDiff(drawn)))236 );237238/**239 * A page's file highlighted ahead of its render, which then finds it240 * drawn and waits for nothing; nothing to do for a file sent plain.241 */242export const drawFileAhead = ({243 path,244 sha,245 text,246}: {247 readonly path: string;248 readonly sha: string;249 readonly text?: string | undefined;250}) =>251 Effect.runPromise(252 text === undefined || !prerendersFile({ path, text })253 ? Effect.void254 : Effect.promise(() => fileDrawing({ path, sha, text })).pipe(255 Effect.asVoid256 )257 );258259/** A diff's first files highlighted ahead of its render, as `drawFileAhead`. */260export const drawDiffAhead = (files: readonly ChangedFile[]) => {261 const drawn = drawnFiles(files);262 const paths = prerenderedPaths(drawn);263264 return Effect.runPromise(265 Effect.forEach(266 drawn.filter((file) => paths.has(file.file.path)),267 (file) => Effect.promise(() => diffDrawing(file)),268 { concurrency: "unbounded", discard: true }269 )270 );271};