Public: anyone can read this; the crew can change it.

OG renderer: SVG composed from data, rasterized to PNG with resvg, cached by input hash #536

Closed opened this in answer to
Closed without merging

scout/forge:scout/452-og-renderer-svg-composed-from-data-raste → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +374 −1
forge.json +1 −1
@@ -6,7 +6,7 @@
66 "ready": 90
77 },
88 "check": {
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 -- crew crew-wrapup crew-limits crew-sandbox steer landing decide ledger checks dependencies autonomy studio studio-words forks fork-flow cross-repo-pull pulls apps apps-adversarial apps-busy apps-token web git-trust helpers shards migrate vitals asks feed feed-page offline share cloud run-secrets forge-cloudflare usage standing board-windows spawn-plan spawn web-apps fleet-ops meter",
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 -- crew crew-wrapup crew-limits crew-sandbox steer landing decide ledger checks dependencies autonomy studio studio-words forks fork-flow cross-repo-pull pulls apps apps-adversarial apps-busy apps-token web git-trust helpers shards migrate vitals asks feed feed-page offline share cloud run-secrets forge-cloudflare usage standing board-windows spawn-plan spawn web-apps fleet-ops meter og",
1010 "timeout": 1800
1111 }
1212 }
src/http/server.ts +2
@@ -68,6 +68,7 @@ import {
6868 subscriptionHeadroom,
6969 subscriptionWake,
7070 } from "../web/pages/subscriptions.ts";
71 import { ogPng } from "../web/og/route.ts";
7172 import {
7273 changePassword,
7374 iconPng,
@@ -412,6 +413,7 @@ export function buildRouter(): Router<Handler> {
412413 router.add("GET", "/sitemap.xml", sitemapXml);
413414 router.add("GET", "/manifest.webmanifest", webManifest);
414415 router.add("GET", "/icons/:spec.png", iconPng);
416 router.add("GET", "/og/:kind/:slug.png", (ctx) => ogPng(ctx));
415417 // The highlighter bundle, content-addressed. A stale hash is a 404 rather
416418 // than a redirect: the page that asked for it names the hash it was built
417419 // with, so a miss means an old tab, and an old tab should reload.
src/web/og/compose.ts added +97
@@ -0,0 +1,97 @@
1 /**
2 * The picture, as SVG: typed inputs in, one string out. No I/O, no clock, so
3 * the same inputs are always the same bytes and the cache can key on them.
4 *
5 * Colors come from the studio's own palette (`design/themes.ts`). Fonts do
6 * not travel with the SVG: the rasterizer draws with whatever the host has,
7 * so the stack names the faces the forge's image ships (Liberation) after the
8 * ones the stylesheet prefers, and ends in a generic family.
9 */
10
11 import { THEMES } from "../../design/themes.ts";
12
13 export const OG_KINDS = ["page", "repo", "pull", "app"] as const;
14 export type OgKind = (typeof OG_KINDS)[number];
15
16 export const OG_WIDTH = 1200;
17 export const OG_HEIGHT = 630;
18
19 export interface OgInput {
20 readonly kind: OgKind;
21 readonly title: string;
22 readonly sub: string;
23 }
24
25 const LABELS: Record<OgKind, string> = {
26 page: "forge",
27 repo: "Repository",
28 pull: "Pull request",
29 app: "App",
30 };
31
32 const FONT = "Inter, 'Liberation Sans', 'Helvetica Neue', Arial, sans-serif";
33
34 export const isOgKind = (v: string): v is OgKind =>
35 (OG_KINDS as readonly string[]).includes(v);
36
37 export function escapeXml(text: string): string {
38 return text.replace(
39 /[&<>"']/g,
40 (c) =>
41 ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
42 c
43 ]!,
44 );
45 }
46
47 /** Greedy wrap by character count, at most `lines` lines, ending in an ellipsis if cut. */
48 export function wrap(text: string, width: number, lines: number): string[] {
49 const out: string[] = [];
50 let line = "";
51 const words = text.split(/\s+/).filter((w) => w !== "");
52 let i = 0;
53 for (; i < words.length && out.length < lines; i++) {
54 let word = words[i]!;
55 if (word.length > width) word = `${word.slice(0, width - 1)}…`;
56 if (line === "") line = word;
57 else if (line.length + 1 + word.length <= width) line += ` ${word}`;
58 else {
59 out.push(line);
60 line = word;
61 }
62 }
63 if (out.length < lines && line !== "") {
64 out.push(line);
65 line = "";
66 }
67 if ((line !== "" || i < words.length) && out.length > 0) {
68 const last = out[out.length - 1]!;
69 out[out.length - 1] = `${last.slice(0, Math.max(0, width - 1)).trimEnd()}…`;
70 }
71 return out;
72 }
73
74 export function composeSvg(input: OgInput): string {
75 const t = THEMES.dark.tokens;
76 const title = wrap(input.title, 30, 3);
77 const sub = wrap(input.sub, 60, 2);
78 const text = (lines: string[], y: number, size: number, step: number, fill: string, weight: number) =>
79 lines
80 .map(
81 (l, n) =>
82 `<text x="80" y="${y + n * step}" font-family="${FONT}" font-size="${size}" font-weight="${weight}" fill="${fill}">${escapeXml(l)}</text>`,
83 )
84 .join("");
85 const subY = 230 + title.length * 84 + 20;
86 return (
87 `<svg xmlns="http://www.w3.org/2000/svg" width="${OG_WIDTH}" height="${OG_HEIGHT}" viewBox="0 0 ${OG_WIDTH} ${OG_HEIGHT}">` +
88 `<rect width="${OG_WIDTH}" height="${OG_HEIGHT}" fill="${t.bg}"/>` +
89 `<rect x="0" y="0" width="12" height="${OG_HEIGHT}" fill="${t.accent}"/>` +
90 `<rect x="40" y="40" width="${OG_WIDTH - 80}" height="${OG_HEIGHT - 80}" rx="20" fill="none" stroke="${t.border}" stroke-width="2"/>` +
91 `<text x="80" y="124" font-family="${FONT}" font-size="30" font-weight="600" fill="${t.accent}">${escapeXml(LABELS[input.kind].toUpperCase())}</text>` +
92 text(title, 230, 72, 84, t.fg, 700) +
93 text(sub, subY, 34, 48, t["muted-fg"], 400) +
94 `<text x="80" y="570" font-family="${FONT}" font-size="26" fill="${t.faint}">forge</text>` +
95 `</svg>`
96 );
97 }
src/web/og/raster.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * SVG → PNG by the `resvg` binary the host already has (`FORGE_RESVG` or
3 * PATH). It is not a package, so the forge's dependency list stays empty.
4 * Chromium was tried as a fallback and takes ~14 s a picture, which no
5 * request can wait for. Without resvg the answer is an error, never a
6 * made-up picture.
7 */
8
9 import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { childEnv } from "../../apps/process.ts";
13 import { err, ok, type Result } from "../../kernel/result.ts";
14
15 export type Rasterize = (svg: string) => Promise<Result<Uint8Array, string>>;
16
17 export function findResvg(): string | undefined {
18 const named = (process.env["FORGE_RESVG"] ?? "").trim();
19 return named !== "" ? named : (Bun.which("resvg") ?? undefined);
20 }
21
22 export const rasterize: Rasterize = async (svg) => {
23 const resvg = findResvg();
24 if (resvg === undefined) return err("no resvg on this forge: install it or set FORGE_RESVG");
25 const dir = await mkdtemp(join(tmpdir(), "forge-og-"));
26 try {
27 const from = join(dir, "og.svg");
28 const to = join(dir, "og.png");
29 await writeFile(from, svg);
30 const proc = Bun.spawn([resvg, from, to], {
31 env: childEnv({}),
32 stdin: "ignore",
33 stdout: "ignore",
34 stderr: "pipe",
35 timeout: 10_000,
36 });
37 const code = await proc.exited;
38 if (code !== 0)
39 return err(`resvg exited ${code}: ${(await new Response(proc.stderr).text()).slice(0, 200)}`);
40 return ok(new Uint8Array(await readFile(to)));
41 } catch (error) {
42 return err(String(error));
43 } finally {
44 await rm(dir, { recursive: true, force: true });
45 }
46 };
src/web/og/render.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * Inputs → PNG, remembered. The key is the sha256 of the inputs, so equal
3 * inputs share one picture and a changed title is a new one. The cache is
4 * in memory and bounded: a restart re-renders, which is what a cache is.
5 * Identical requests in flight share one render.
6 */
7
8 import { sha256 } from "../../kernel/hash.ts";
9 import { err, type Result } from "../../kernel/result.ts";
10 import { composeSvg, type OgInput } from "./compose.ts";
11 import { rasterize, type Rasterize } from "./raster.ts";
12
13 const MAX_ENTRIES = 256;
14
15 export interface OgRenderer {
16 render(input: OgInput): Promise<Result<{ key: string; png: Uint8Array }, string>>;
17 }
18
19 export const ogKey = (input: OgInput): string =>
20 sha256(JSON.stringify([input.kind, input.title, input.sub]));
21
22 export function createOgRenderer(raster: Rasterize = rasterize): OgRenderer {
23 const done = new Map<string, Uint8Array>();
24 const flying = new Map<string, Promise<Result<Uint8Array, string>>>();
25 return {
26 async render(input) {
27 const key = ogKey(input);
28 const hit = done.get(key);
29 if (hit !== undefined) {
30 done.delete(key);
31 done.set(key, hit); // most recent last
32 return { ok: true, value: { key, png: hit } };
33 }
34 let job = flying.get(key);
35 if (job === undefined) {
36 job = raster(composeSvg(input)).finally(() => flying.delete(key));
37 flying.set(key, job);
38 }
39 const result = await job;
40 if (!result.ok) return err(result.error);
41 done.set(key, result.value);
42 if (done.size > MAX_ENTRIES) done.delete(done.keys().next().value!);
43 return { ok: true, value: { key, png: result.value } };
44 },
45 };
46 }
src/web/og/route.ts added +48
@@ -0,0 +1,48 @@
1 /** GET /og/:kind/:slug.png?t=title&s=sub — the share picture, from query inputs. */
2
3 import { notFound } from "../../http/respond.ts";
4 import type { Ctx } from "../../http/context.ts";
5 import { isOgKind } from "./compose.ts";
6 import { createOgRenderer, type OgRenderer } from "./render.ts";
7
8 const TITLE_MAX = 120;
9 const SUB_MAX = 240;
10
11 /** One line of printable text, bounded; control bytes and runs of space go. */
12 const clean = (v: string | null, max: number): string =>
13 (v ?? "")
14 .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ")
15 .replace(/\s+/g, " ")
16 .trim()
17 .slice(0, max);
18
19 let shared: OgRenderer | undefined;
20
21 export async function ogPng(ctx: Ctx, renderer?: OgRenderer): Promise<Response> {
22 const kind = ctx.params["kind"] ?? "";
23 if (!isOgKind(kind)) return notFound();
24 const query = ctx.url.searchParams;
25 const title = clean(query.get("t"), TITLE_MAX);
26 if (title === "") return notFound();
27 const sub = clean(query.get("s"), SUB_MAX);
28 const made = await (renderer ?? (shared ??= createOgRenderer())).render({ kind, title, sub });
29 if (!made.ok)
30 return new Response("the picture is not available", {
31 status: 503,
32 headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
33 });
34 const etag = `"${made.value.key}"`;
35 const headers = {
36 etag,
37 "cache-control": "public, max-age=86400, immutable",
38 };
39 if (ctx.request.headers.get("if-none-match") === etag)
40 return new Response(null, { status: 304, headers });
41 return new Response(made.value.png, {
42 headers: {
43 ...headers,
44 "content-type": "image/png",
45 "content-length": String(made.value.png.length),
46 },
47 });
48 }
test/og.test.ts added +134
@@ -0,0 +1,134 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { decodePng, pngHeader } from "../src/design/image/png.ts";
7 import { serve, type Servers } from "../src/http/server.ts";
8 import { err, ok } from "../src/kernel/result.ts";
9 import { OG_HEIGHT, OG_KINDS, OG_WIDTH, composeSvg, wrap } from "../src/web/og/compose.ts";
10 import { findResvg } from "../src/web/og/raster.ts";
11 import { ogPng } from "../src/web/og/route.ts";
12 import { createOgRenderer } from "../src/web/og/render.ts";
13
14 describe("compose", () => {
15 test("escapes every input", () => {
16 const svg = composeSvg({ kind: "repo", title: `<script>"x"&'`, sub: "</text><g/>" });
17 expect(svg).not.toContain("<script>");
18 expect(svg).not.toContain("</text><g/>");
19 expect(svg).toContain("&lt;script&gt;&quot;x&quot;&amp;&#39;");
20 });
21 test("is deterministic and differs per kind", () => {
22 const a = composeSvg({ kind: "page", title: "T", sub: "" });
23 expect(composeSvg({ kind: "page", title: "T", sub: "" })).toBe(a);
24 expect(composeSvg({ kind: "pull", title: "T", sub: "" })).not.toBe(a);
25 });
26 test("wrap bounds lines and marks the cut", () => {
27 const lines = wrap("one two three four five six seven", 9, 2);
28 expect(lines.length).toBe(2);
29 expect(lines[1]!.endsWith("…")).toBe(true);
30 expect(wrap("x".repeat(100), 10, 1)[0]!.length).toBeLessThanOrEqual(10);
31 });
32 });
33
34 describe("renderer cache", () => {
35 test("equal inputs rasterize once; changed inputs again; failures are not cached", async () => {
36 let calls = 0;
37 let fail = true;
38 const r = createOgRenderer(async () => {
39 calls++;
40 return fail ? err("down") : ok(new Uint8Array([1, 2, 3]));
41 });
42 const input = { kind: "page", title: "A", sub: "" } as const;
43 expect((await r.render(input)).ok).toBe(false);
44 fail = false;
45 const first = await r.render(input);
46 const again = await r.render(input);
47 expect(first.ok && again.ok && first.value.key === again.value.key).toBe(true);
48 expect(calls).toBe(2);
49 await r.render({ ...input, title: "B" });
50 expect(calls).toBe(3);
51 });
52 test("concurrent identical requests share one render", async () => {
53 let calls = 0;
54 const r = createOgRenderer(async () => {
55 calls++;
56 await Bun.sleep(20);
57 return ok(new Uint8Array([9]));
58 });
59 const input = { kind: "app", title: "A", sub: "" } as const;
60 await Promise.all([r.render(input), r.render(input), r.render(input)]);
61 expect(calls).toBe(1);
62 });
63 });
64
65 describe("GET /og/:kind/:slug.png", () => {
66 let app: App;
67 let servers: Servers;
68 let dir: string;
69 const canRaster = findResvg() !== undefined;
70 beforeAll(async () => {
71 dir = await mkdtemp(join(tmpdir(), "forge-og-test-"));
72 app = createApp({ dataDir: dir, port: 0 });
73 servers = await serve(app);
74 });
75 afterAll(async () => {
76 servers.stop();
77 await rm(dir, { recursive: true, force: true });
78 });
79 const get = (path: string, init?: RequestInit) => fetch(`${servers.url}${path}`, init);
80
81 test("unknown kind and missing title are 404", async () => {
82 expect((await get("/og/nope/x.png?t=hi")).status).toBe(404);
83 expect((await get("/og/repo/x.png")).status).toBe(404);
84 expect((await get("/og/repo/x.png?t=%00%01")).status).toBe(404);
85 });
86
87 test.skipIf(!canRaster)(
88 "renders every kind at 1200x630, then answers from cache",
89 async () => {
90 for (const kind of OG_KINDS) {
91 const path = `/og/${kind}/x.png?t=${encodeURIComponent(`A <${kind}> title`)}&s=${encodeURIComponent("with a subtitle")}`;
92 const res = await get(path);
93 expect(res.status).toBe(200);
94 expect(res.headers.get("content-type")).toBe("image/png");
95 expect(res.headers.get("cache-control")).toContain("immutable");
96 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
97 const bytes = new Uint8Array(await res.arrayBuffer());
98 const head = pngHeader(bytes);
99 expect(head.ok && head.value.width).toBe(OG_WIDTH);
100 expect(head.ok && head.value.height).toBe(OG_HEIGHT);
101 expect(decodePng(bytes).ok).toBe(true);
102 const t0 = performance.now();
103 const warm = await get(path);
104 await warm.arrayBuffer();
105 expect(performance.now() - t0).toBeLessThan(50);
106 const etag = res.headers.get("etag")!;
107 expect((await get(path, { headers: { "if-none-match": etag } })).status).toBe(304);
108 }
109 },
110 60_000,
111 );
112 });
113
114 describe("ogPng with a stand-in renderer", () => {
115 const ctxFor = (path: string, kind: string, headers: Record<string, string> = {}) =>
116 ({
117 params: { kind, slug: "x" },
118 url: new URL(`http://x${path}`),
119 request: new Request(`http://x${path}`, { headers }),
120 }) as unknown as Parameters<typeof ogPng>[0];
121 const fake = { render: async () => ({ ok: true as const, value: { key: "k1", png: new Uint8Array([1, 2]) } }) };
122 test("serves immutable png with an etag, 304 on match, 503 on failure", async () => {
123 const res = await ogPng(ctxFor("/og/repo/x.png?t=Hi", "repo"), fake);
124 expect(res.status).toBe(200);
125 expect(res.headers.get("content-type")).toBe("image/png");
126 expect(res.headers.get("etag")).toBe('"k1"');
127 const same = await ogPng(ctxFor("/og/repo/x.png?t=Hi", "repo", { "if-none-match": '"k1"' }), fake);
128 expect(same.status).toBe(304);
129 const down = await ogPng(ctxFor("/og/repo/x.png?t=Hi", "repo"), {
130 render: async () => err("no resvg"),
131 });
132 expect(down.status).toBe(503);
133 });
134 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs