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 #461

Closed opened this in answer to
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +1138 −4
CLAUDE.md +5 −1
@@ -137,7 +137,11 @@ src/
137137 surface, one module per concept: words (the vocabulary every
138138 page says it in), asks, previews, shelf (an app as one
139139 row, for any page that lists apps), home, app, change, tell,
140 run, lists, actions, style (the page sheet, assembled)
140 run, lists, actions, style (the page sheet, assembled),
141 and og/ — link previews: metrics (the fonts' advances),
142 card (the SVG, from plain data), kinds (what each preview
143 says, read as nobody), raster (resvg, spawned), cache
144 (sha256 of the input), route (`/og/:kind/*path`)
141145 feed/ a viewer's feed (docs/FEED.md): items (candidates read through
142146 the access every page uses), affinity (decayed counts), rank,
143147 feed (filter, page, cursor)
Dockerfile +15 −2
@@ -3,14 +3,27 @@
33 # npm), and chromium for the look — a picture of every green preview
44 # (docs/APPS.md). Chromium and a font to draw with add about 450 MB to the
55 # image; it is the largest thing here by far, and the only way to see a page
6 # as a browser does. package.json's dependency list is empty, so there is
7 # nothing to install.
6 # as a browser does. A fourth, resvg, draws the link previews (src/web/og):
7 # one static 5 MB binary, pinned to a release and its sha256, and the
8 # Liberation fonts it draws them in are the ones chromium already uses.
9 # package.json's dependency list is empty, so there is nothing to install.
810 FROM oven/bun:1.3-debian
11 ARG TARGETARCH
12 ARG RESVG_VERSION=0.48.1
13 ARG RESVG_SHA256_AMD64=fa8c26495a187e592c501db15bf9e8a9fdc051d4b2b336b39703d5b59f912b9d
914 RUN apt-get update \
1015 && apt-get install -y --no-install-recommends git ca-certificates curl bubblewrap socat nodejs npm tini chromium fonts-liberation \
1116 && rm -rf /var/lib/apt/lists/* \
1217 && npm install -g @anthropic-ai/claude-code \
1318 && npm cache clean --force
19 # resvg publishes a Linux binary for x86_64 only; elsewhere the previews
20 # answer 503 until one is installed and named by FORGE_RESVG.
21 RUN if [ "${TARGETARCH:-amd64}" = "amd64" ]; then \
22 curl -fsSL -o /tmp/resvg.tgz "https://github.com/linebender/resvg/releases/download/v${RESVG_VERSION}/resvg-linux-x86_64.tar.gz" \
23 && echo "${RESVG_SHA256_AMD64} /tmp/resvg.tgz" | sha256sum -c - \
24 && tar -xzf /tmp/resvg.tgz -C /usr/local/bin resvg \
25 && rm /tmp/resvg.tgz; \
26 fi
1427 WORKDIR /app
1528 COPY package.json tsconfig.json ./
1629 COPY src ./src
README.md +23
@@ -365,6 +365,29 @@ not as a crew run; AWS audits look at us-east-1 only; over-provisioned
365365 droplets and forgotten DNS records need metrics or resolution and are not
366366 attempted; Backblaze audits find nothing yet. No dependency was added.
367367
368 ## Link previews
369
370 A link to the forge unfurls as a 1200 × 630 picture drawn from the page's
371 data — the card a chat app shows before anyone clicks:
372
373 ```
374 /og/site/home.png the forge: what it holds in the open
375 /og/repo/<owner>/<name>.png a repository: its description, what is open
376 /og/<kind>/<path>.svg the same card, before it is rasterized
377 ```
378
379 Every preview reads as an anonymous viewer, whoever asks — unfurlers are
380 anonymous, and a picture is cached and shared — so a private repository and
381 a missing one draw the same card: the name in the URL, and "private". The
382 card is SVG composed from plain data in the studio's palette and rasterized
383 by [resvg](https://github.com/linebender/resvg), a static binary the image
384 pins (`FORGE_RESVG` names another); it is spawned like git, so there is
385 still no runtime dependency. PNGs are kept in memory under the sha256 of
386 their input, which is also the ETag: unchanged data is a 304, changed data
387 is a new picture, and nothing is ever invalidated. A cold render is about
388 60–130 ms. Without resvg the PNG answers 503 and says why; the SVG still
389 works.
390
368391 ## Develop
369392
370393 ```sh
docs/APPS.md +2
@@ -906,6 +906,8 @@ one line and a link to the asks screen is posted there (`src/crew/notify.ts`).
906906 | `FORGE_CLAUDE` | `claude` on `PATH` | the Claude Code binary |
907907 | `FORGE_CLAUDE_CONFIG_DIR` | Claude Code's own | a `CLAUDE_CONFIG_DIR` for runs, when wanted |
908908 | `FORGE_CHROMIUM` | `chromium` on `PATH` | the browser the look is taken with |
909 | `FORGE_RESVG` | `resvg` on `PATH` | what draws the link previews (`/og/…png`) |
910 | `FORGE_OG_FONTS` | where `fonts-liberation` lives | a directory holding the three Liberation faces |
909911 | `ANTHROPIC_API_KEY` | — | handed to agent runs when set |
910912 | `CLAUDE_CODE_OAUTH_TOKEN` | — | handed to agent runs when set |
911913 | `TYPESAFE_API_KEY` | — | TypeSafe's Jev answers fixed-choice decisions |
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 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/web-apps.test.ts test/fleet-ops.test.ts",
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/web-apps.test.ts test/fleet-ops.test.ts test/og.test.ts",
1010 "timeout": 1800
1111 }
1212 }
src/http/server.ts +3
@@ -298,6 +298,7 @@ import {
298298 type StoredResponse,
299299 } from "../core/idempotency.ts";
300300 import { sseStream, viewerStream } from "./sse.ts";
301 import { ogImage } from "../web/og/route.ts";
301302 import { Router } from "./router.ts";
302303 import { getUserById } from "../core/users.ts";
303304 import { appsRuntime } from "../apps/runtime.ts";
@@ -412,6 +413,8 @@ 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 // Link previews: a picture of a page, drawn from its data as nobody sees it.
417 router.add("GET", "/og/:kind/*path", ogImage);
415418 // The highlighter bundle, content-addressed. A stale hash is a 404 rather
416419 // than a redirect: the page that asked for it names the hash it was built
417420 // with, so a miss means an old tab, and an old tab should reload.
src/web/og/cache.ts added +99
@@ -0,0 +1,99 @@
1 /**
2 * Rendered previews, kept by what they were rendered from. The key is the
3 * sha256 of the card's input in canonical JSON (keys sorted) plus the
4 * renderer's version: the same data always maps to the same PNG, changed
5 * data is a different key, and nothing has to be invalidated — a stale
6 * entry simply stops being asked for and falls off the end of the LRU.
7 *
8 * The same key is the response's ETag, so an unfurler or a browser that
9 * already holds the picture is answered 304 without a render.
10 *
11 * In memory, bounded by bytes: a card is ~20–40 KB, so the default 32 MB
12 * holds about a thousand. After a restart the first request for each pays
13 * one cold render (≤ 300 ms is the bar; resvg does it in under 100).
14 * Concurrent requests for one key share one render.
15 */
16
17 import { sha256 } from "../../kernel/hash.ts";
18 import { ok, type Result } from "../../kernel/result.ts";
19
20 /** Bumped when the drawing changes, so an old picture is never served for new code. */
21 export const RENDER_VERSION = "og-1";
22
23 /** JSON with object keys sorted at every depth: equal data, equal text. */
24 export function canonical(value: unknown): string {
25 if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
26 if (value !== null && typeof value === "object") {
27 const entries = Object.entries(value as Record<string, unknown>)
28 .filter(([, v]) => v !== undefined)
29 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
30 return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
31 }
32 return JSON.stringify(value) ?? "null";
33 }
34
35 /** The cache key of one preview's input. */
36 export function inputHash(kind: string, input: unknown): string {
37 return sha256(`${RENDER_VERSION}\n${kind}\n${canonical(input)}`);
38 }
39
40 export class PngCache {
41 private readonly entries = new Map<string, Uint8Array>();
42 private readonly pending = new Map<
43 string,
44 Promise<Result<Uint8Array, string>>
45 >();
46 private bytes = 0;
47
48 constructor(readonly maxBytes = 32 * 1024 * 1024) {}
49
50 get size(): number {
51 return this.entries.size;
52 }
53
54 get(key: string): Uint8Array | undefined {
55 const hit = this.entries.get(key);
56 if (hit === undefined) return undefined;
57 // Re-insert: a Map iterates in insertion order, so the oldest is first.
58 this.entries.delete(key);
59 this.entries.set(key, hit);
60 return hit;
61 }
62
63 set(key: string, png: Uint8Array): void {
64 if (png.length > this.maxBytes) return;
65 const old = this.entries.get(key);
66 if (old !== undefined) {
67 this.bytes -= old.length;
68 this.entries.delete(key);
69 }
70 this.entries.set(key, png);
71 this.bytes += png.length;
72 for (const [k, v] of this.entries) {
73 if (this.bytes <= this.maxBytes) break;
74 this.entries.delete(k);
75 this.bytes -= v.length;
76 }
77 }
78
79 /** The PNG for `key`: from memory, from a render already running, or from `render`. */
80 async through(
81 key: string,
82 render: () => Promise<Result<Uint8Array, string>>,
83 ): Promise<Result<Uint8Array, string>> {
84 const hit = this.get(key);
85 if (hit !== undefined) return ok(hit);
86 const running = this.pending.get(key);
87 if (running !== undefined) return running;
88 const started = render().then((result) => {
89 if (result.ok) this.set(key, result.value);
90 return result;
91 });
92 this.pending.set(key, started);
93 try {
94 return await started;
95 } finally {
96 this.pending.delete(key);
97 }
98 }
99 }
src/web/og/card.ts added +220
@@ -0,0 +1,220 @@
1 /**
2 * The preview card: one 1200 × 630 SVG composed from plain data, in the
3 * studio's own palette (Porcelain, `design/themes.ts`) and its mark. Every
4 * kind of preview is a `Card` — a kind decides what to say, this file
5 * decides how it looks — so every link the forge unfurls is one visual
6 * system.
7 *
8 * ┌──────────────────────────────────────────────┐
9 * │ ■ eyebrow ( state ) │ y 72
10 * │ Title, bold, up to two lines │ y 196
11 * │ Description, up to three lines │
12 * │ │
13 * │ 12 3 $41 │ y 508
14 * │ open waiting today │
15 * │ host │ y 590
16 * └▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀┘
17 *
18 * 1200 × 630 is the size every unfurler (iMessage, Slack, X, Discord)
19 * crops least; text is placed by arithmetic (`metrics.ts`) because SVG
20 * does not wrap. Nothing here reads a database: a card is a pure function
21 * of its input, which is what lets the cache key be a hash of that input.
22 */
23
24 import { THEMES } from "../../design/themes.ts";
25 import { clip, measure, wrap } from "./metrics.ts";
26
27 export const WIDTH = 1200;
28 export const HEIGHT = 630;
29
30 /** The palette roles a card may colour a state or a number with. */
31 export type Tone = "accent" | "success" | "attn" | "danger" | "merged" | "muted";
32
33 export interface Stat {
34 readonly value: string;
35 readonly label: string;
36 readonly tone?: Tone;
37 }
38
39 /** Everything a preview says. Plain data: what is hashed is what is drawn. */
40 export interface Card {
41 /** Where this is, small, above the title — `owner/name`, `forge`. */
42 readonly eyebrow: string;
43 readonly title: string;
44 readonly description?: string;
45 /** One word for the state of the thing, in a pill at the top right. */
46 readonly state?: { readonly label: string; readonly tone: Tone };
47 /** Up to four numbers along the bottom. */
48 readonly stats?: readonly Stat[];
49 /** The forge's host, bottom left: whose link this is. */
50 readonly host: string;
51 }
52
53 /** The families resvg is handed (`raster.ts`), with a fallback for any other. */
54 export const SANS = "'Liberation Sans', Arial, Helvetica, sans-serif";
55 export const MONO = "'Liberation Mono', 'Courier New', monospace";
56
57 const P = THEMES.light.tokens;
58
59 const PAD = 72;
60 const INNER = WIDTH - PAD * 2;
61 const MAX_TEXT = 400;
62 const MAX_STATS = 4;
63
64 function tone(t: Tone | undefined): string {
65 switch (t) {
66 case "accent":
67 return P.accent;
68 case "success":
69 return P.success;
70 case "attn":
71 return P.attn;
72 case "danger":
73 return P.danger;
74 case "merged":
75 return P.merged;
76 case "muted":
77 return P["muted-fg"];
78 default:
79 return P.fg;
80 }
81 }
82
83 /**
84 * Text as it may appear in XML: escaped, and with the C0 controls (and
85 * U+FFFE/FFFF) XML 1.0 forbids removed — one stray byte from an issue
86 * title would otherwise make the whole document unparseable.
87 */
88 export function xmlText(s: string): string {
89 return s
90 .slice(0, MAX_TEXT)
91 .toWellFormed()
92 .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/g, "")
93 .replace(/[\t\n\r]/g, " ")
94 .replace(
95 /[<>&'"]/g,
96 (c) =>
97 ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", "'": "&apos;", '"': "&quot;" })[c]!,
98 );
99 }
100
101 function text(
102 x: number,
103 y: number,
104 body: string,
105 attrs: string,
106 anchor: "start" | "end" = "start",
107 ): string {
108 const a = anchor === "end" ? ` text-anchor="end"` : "";
109 return `<text x="${x}" y="${y}"${a} ${attrs}>${xmlText(body)}</text>`;
110 }
111
112 /** The mark, as the favicon draws it, at `size` px with its top-left at x, y. */
113 function mark(x: number, y: number, size: number): string {
114 const r = (size * 8) / 26;
115 return `<rect x="${x}" y="${y}" width="${size}" height="${size}" rx="${r}" fill="url(#mark)"/>`;
116 }
117
118 function pill(label: string, t: Tone): string {
119 const size = 24;
120 const shown = clip(label, size, "bold", 360);
121 // 22 px to the dot, 14 more to the text, 24 after it.
122 const w = Math.ceil(measure(shown, size, "bold")) + 60;
123 const h = 48;
124 const x = WIDTH - PAD - w;
125 const y = PAD - 32;
126 const c = tone(t);
127 return [
128 `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${h / 2}" fill="${c}" fill-opacity="0.12"/>`,
129 `<circle cx="${x + 22}" cy="${y + h / 2}" r="6" fill="${c}"/>`,
130 text(
131 x + 36,
132 y + 32,
133 shown,
134 `font-family="${SANS}" font-weight="700" font-size="${size}" fill="${c}"`,
135 ),
136 ].join("");
137 }
138
139 function stats(list: readonly Stat[]): string {
140 const shown = list.slice(0, MAX_STATS);
141 if (shown.length === 0) return "";
142 const cell = INNER / Math.max(3, shown.length);
143 return shown
144 .map((s, i) => {
145 const x = PAD + i * cell;
146 return [
147 text(
148 x,
149 510,
150 clip(s.value, 52, "bold", cell - 24),
151 `font-family="${SANS}" font-weight="700" font-size="52" fill="${tone(s.tone)}"`,
152 ),
153 text(
154 x,
155 546,
156 clip(s.label, 24, "sans", cell - 24),
157 `font-family="${SANS}" font-size="24" fill="${P["muted-fg"]}"`,
158 ),
159 ].join("");
160 })
161 .join("");
162 }
163
164 /** The card as an SVG document. */
165 export function cardSvg(card: Card): string {
166 const pillRoom = card.state === undefined ? 0 : 420;
167 const eyebrow = clip(card.eyebrow, 28, "mono", INNER - 64 - pillRoom);
168 const hasStats = (card.stats ?? []).length > 0;
169 // Up to two lines of title at 68 px; the description takes the lines
170 // left above the numbers (44 px apart, last baseline ≤ 420) or, with no
171 // numbers, above the host — four at most.
172 const title = wrap(card.title, 68, "bold", INNER, 2);
173 const descTop = 196 + (title.length - 1) * 80 + 72;
174 const descLines = Math.max(
175 0,
176 Math.floor(((hasStats ? 420 : 560) - descTop) / 44) + 1,
177 );
178 const desc =
179 card.description === undefined
180 ? []
181 : wrap(card.description, 32, "sans", INNER, Math.min(4, descLines));
182 return [
183 `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}">`,
184 `<defs><linearGradient id="mark" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${P.accent}"/><stop offset="1" stop-color="${P.merged}"/></linearGradient></defs>`,
185 `<rect width="${WIDTH}" height="${HEIGHT}" fill="${P.bg}"/>`,
186 `<rect y="${HEIGHT - 12}" width="${WIDTH}" height="12" fill="url(#mark)"/>`,
187 mark(PAD, PAD - 32, 44),
188 text(
189 PAD + 64,
190 PAD + 2,
191 eyebrow,
192 `font-family="${MONO}" font-size="28" fill="${P["muted-fg"]}"`,
193 ),
194 card.state === undefined ? "" : pill(card.state.label, card.state.tone),
195 ...title.map((line, i) =>
196 text(
197 PAD,
198 196 + i * 80,
199 line,
200 `font-family="${SANS}" font-weight="700" font-size="68" fill="${P.fg}"`,
201 ),
202 ),
203 ...desc.map((line, i) =>
204 text(
205 PAD,
206 descTop + i * 44,
207 line,
208 `font-family="${SANS}" font-size="32" fill="${P["muted-fg"]}"`,
209 ),
210 ),
211 stats(card.stats ?? []),
212 text(
213 PAD,
214 596,
215 clip(card.host, 22, "mono", INNER),
216 `font-family="${MONO}" font-size="22" fill="${P.faint}"`,
217 ),
218 `</svg>`,
219 ].join("");
220 }
src/web/og/kinds.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * What each kind of preview says: `/og/<kind>/<path>.png` names a kind and
3 * the thing it is a picture of, and the kind reads that thing's data and
4 * answers a `Card`. A new design (the map, the audit, an app, a change —
5 * #454, #455) is a new entry in `KINDS`, or a richer card from an old one.
6 *
7 * A preview is fetched by unfurlers — iMessage, Slack, X, Discord — and
8 * they are anonymous, so every kind reads as nobody. That is mechanical,
9 * not a convention: a loader is handed `OgSource`, which carries the
10 * database and the forge's host and no viewer at all, so a signed-in
11 * person's access can never end up drawn into a cached, shareable PNG.
12 *
13 * A thing nobody may see and a thing that does not exist draw the same
14 * card — its name, as the URL already spelled it, and "private" — the
15 * picture-shaped twin of `not_found`'s deliberate ambiguity.
16 */
17
18 import type { Database } from "bun:sqlite";
19 import { canRead, countsForRepos, getRepo } from "../../core/repos.ts";
20 import type { Card } from "./card.ts";
21
22 /** All a loader may read: no request, no session, no viewer. */
23 export interface OgSource {
24 readonly db: Database;
25 /** The forge's public host, e.g. `forge.example.com`. */
26 readonly host: string;
27 }
28
29 /** A kind reads its data; `undefined` means the path is not one of its shape. */
30 export type Kind = (source: OgSource, path: readonly string[]) => Card | undefined;
31
32 /** A user, org or repository name, as the forge allows them. */
33 const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
34
35 function plural(n: number, one: string, many = `${one}s`): string {
36 return n === 1 ? one : many;
37 }
38
39 /** The card for something an anonymous viewer may not see — or that is not there. */
40 export function privateCard(source: OgSource, name: string): Card {
41 return {
42 eyebrow: name,
43 title: name.split("/").at(-1) ?? name,
44 description: "Private. Sign in on this forge to see it.",
45 state: { label: "private", tone: "muted" },
46 host: source.host,
47 };
48 }
49
50 /** `/og/site/home.png` — the forge itself: what it holds in the open. */
51 const site: Kind = (source, path) => {
52 if (path.length !== 1 || path[0] !== "home") return undefined;
53 const row = source.db
54 .query<{ repos: number; issues: number; pulls: number }, []>(
55 `SELECT
56 (SELECT COUNT(*) FROM repo WHERE visibility = 'public') AS repos,
57 (SELECT COUNT(*) FROM issue JOIN repo ON repo.id = issue.repo_id
58 WHERE repo.visibility = 'public' AND issue.state = 'open' AND issue.kind = 'issue') AS issues,
59 (SELECT COUNT(*) FROM issue JOIN repo ON repo.id = issue.repo_id
60 WHERE repo.visibility = 'public' AND issue.state = 'open' AND issue.kind = 'pull') AS pulls`,
61 )
62 .get() ?? { repos: 0, issues: 0, pulls: 0 };
63 return {
64 eyebrow: "forge",
65 // The host's first label names the forge; the whole host is the footer.
66 title: source.host.split(".")[0] || source.host,
67 description: "Your code, your machine: repositories, apps and the crew that builds them.",
68 stats: [
69 { value: String(row.repos), label: plural(row.repos, "public repository", "public repositories") },
70 { value: String(row.issues), label: `open ${plural(row.issues, "issue")}` },
71 { value: String(row.pulls), label: `open ${plural(row.pulls, "change")}`, tone: row.pulls > 0 ? "accent" : "muted" },
72 ],
73 host: source.host,
74 };
75 };
76
77 /** `/og/repo/<owner>/<name>.png` — a repository: what it is, and what is open. */
78 const repo: Kind = (source, path) => {
79 const [owner, name] = path;
80 if (path.length !== 2 || owner === undefined || name === undefined) return undefined;
81 if (!NAME.test(owner) || !NAME.test(name)) return undefined;
82 const found = getRepo(source.db, owner, name);
83 if (found === undefined || !canRead(source.db, found, undefined))
84 return privateCard(source, `${owner}/${name}`);
85 const counts = countsForRepos(source.db, [found.id]).get(found.id);
86 const issues = counts?.openIssues ?? 0;
87 const pulls = counts?.openPulls ?? 0;
88 return {
89 eyebrow: `${found.ownerName}/${found.name}`,
90 title: found.name,
91 ...(found.description.trim() === "" ? {} : { description: found.description.trim() }),
92 state: { label: "public", tone: "success" },
93 stats: [
94 { value: String(issues), label: `open ${plural(issues, "issue")}` },
95 { value: String(pulls), label: `open ${plural(pulls, "change")}`, tone: pulls > 0 ? "accent" : "muted" },
96 { value: found.defaultBranch, label: "default branch", tone: "muted" },
97 ],
98 host: source.host,
99 };
100 };
101
102 export const KINDS: Readonly<Record<string, Kind>> = { site, repo };
103
104 export function kindNamed(name: string): Kind | undefined {
105 return Object.hasOwn(KINDS, name) ? KINDS[name] : undefined;
106 }
src/web/og/metrics.ts added +132
@@ -0,0 +1,132 @@
1 /**
2 * How wide a line of text is, before anything draws it. SVG has no line
3 * wrapping, so a title that would run off a 1200 px card has to be broken
4 * and clipped here, by arithmetic, before the rasterizer ever sees it.
5 *
6 * The widths are the fonts' own: the horizontal advances (`hmtx`, indexed
7 * through `cmap` format 4) of Liberation Sans Regular and Bold for U+0020…
8 * U+007E, in font units of a 2048-unit em, read out of the TTFs the image
9 * ships (`fonts-liberation`). Liberation Sans is metric-compatible with
10 * Arial by design, so the same table is exact for either. Liberation Mono
11 * is 1229/2048 em for every glyph.
12 *
13 * width(px) = Σ advance(ch) × size(px) / 2048
14 *
15 * Anything outside ASCII is counted at a digit's width (1139/2048 — also
16 * the advance of `é`), and a wide (CJK) character at a full em: an
17 * estimate that errs wide, so a line is clipped early rather than late.
18 */
19
20 export type Face = "sans" | "bold" | "mono";
21
22 const EM = 2048;
23
24 // prettier-ignore
25 const SANS = [
26 569,569,727,1139,1139,1821,1366,391,682,682,797,1196,569,682,569,569,
27 1139,1139,1139,1139,1139,1139,1139,1139,1139,1139,569,569,1196,1196,1196,1139,
28 2079,1366,1366,1479,1479,1366,1251,1593,1479,569,1024,1366,1139,1706,1479,1593,
29 1366,1593,1479,1366,1251,1479,1366,1933,1366,1366,1251,569,569,569,961,1139,
30 682,1139,1139,1024,1139,1139,569,1139,1139,455,455,1024,455,1706,1139,1139,
31 1139,1139,682,1024,569,1139,1024,1479,1024,1024,1024,684,532,684,1196,
32 ];
33
34 // prettier-ignore
35 const BOLD = [
36 569,682,971,1139,1139,1821,1479,487,682,682,797,1196,569,682,569,569,
37 1139,1139,1139,1139,1139,1139,1139,1139,1139,1139,682,682,1196,1196,1196,1251,
38 1997,1479,1479,1479,1479,1366,1251,1593,1479,569,1139,1479,1251,1706,1479,1593,
39 1366,1593,1479,1366,1251,1479,1366,1933,1366,1366,1251,682,569,682,1196,1139,
40 682,1139,1251,1139,1251,1139,682,1251,1251,569,569,1139,569,1821,1251,1251,
41 1251,1251,797,1139,682,1251,1139,1593,1139,1139,1024,797,573,797,1196,
42 ];
43
44 const MONO = 1229;
45 const OTHER = 1139;
46 /** `…` U+2026 in both sans faces; one mono cell in mono. */
47 const ELLIPSIS = "…";
48
49 function isWide(code: number): boolean {
50 return (
51 (code >= 0x1100 && code <= 0x115f) ||
52 (code >= 0x2e80 && code <= 0xa4cf) ||
53 (code >= 0xac00 && code <= 0xd7a3) ||
54 (code >= 0xf900 && code <= 0xfaff) ||
55 (code >= 0xff00 && code <= 0xff60) ||
56 code >= 0x1f300
57 );
58 }
59
60 function advance(ch: string, face: Face): number {
61 const code = ch.codePointAt(0) ?? 0;
62 if (face === "mono") return isWide(code) ? EM : MONO;
63 if (code === 0x2026) return EM;
64 if (code >= 0x20 && code <= 0x7e) {
65 const table = face === "bold" ? BOLD : SANS;
66 return table[code - 0x20] ?? OTHER;
67 }
68 return isWide(code) ? EM : OTHER;
69 }
70
71 /** The width in pixels of `text` set in `face` at `size` px. */
72 export function measure(text: string, size: number, face: Face): number {
73 let units = 0;
74 for (const ch of text) units += advance(ch, face);
75 return (units * size) / EM;
76 }
77
78 /** `text` cut to fit `max` px, ending in `…` when anything was cut. */
79 export function clip(
80 text: string,
81 size: number,
82 face: Face,
83 max: number,
84 ): string {
85 if (measure(text, size, face) <= max) return text;
86 const room = max - measure(ELLIPSIS, size, face);
87 let used = 0;
88 let out = "";
89 for (const ch of text) {
90 const w = (advance(ch, face) * size) / EM;
91 if (used + w > room) break;
92 used += w;
93 out += ch;
94 }
95 return `${out.trimEnd()}${ELLIPSIS}`;
96 }
97
98 /**
99 * `text` broken at spaces into at most `lines` lines of at most `max` px;
100 * the last line is clipped with `…` when the text does not fit. A word
101 * longer than a whole line is clipped where it stands.
102 */
103 export function wrap(
104 text: string,
105 size: number,
106 face: Face,
107 max: number,
108 lines: number,
109 ): string[] {
110 const words = text.split(/\s+/).filter((w) => w !== "");
111 const out: string[] = [];
112 let i = 0;
113 while (i < words.length && out.length < lines) {
114 // The last line allowed takes everything left, clipped.
115 if (out.length === lines - 1) {
116 out.push(clip(words.slice(i).join(" "), size, face, max));
117 break;
118 }
119 let line = words[i++]!;
120 if (measure(line, size, face) > max) {
121 out.push(clip(line, size, face, max));
122 continue;
123 }
124 while (
125 i < words.length &&
126 measure(`${line} ${words[i]}`, size, face) <= max
127 )
128 line = `${line} ${words[i++]}`;
129 out.push(line);
130 }
131 return out;
132 }
src/web/og/raster.ts added +141
@@ -0,0 +1,141 @@
1 /**
2 * SVG → PNG, by resvg (https://github.com/linebender/resvg): a static
3 * binary, spawned the way git and chromium are — the forge's dependency
4 * list stays empty, and the host provides the tool (the Dockerfile pins a
5 * release and its sha256). A cold render of a card is one spawn and about
6 * 60–90 ms; the cache in front of it (`cache.ts`) makes the second one free.
7 *
8 * The fonts are handed over by file, with system fonts skipped, when the
9 * three faces the card is measured against are on the machine
10 * (`metrics.ts` holds their advances): what was measured is what is drawn,
11 * and the render does not depend on whatever else fontconfig would find.
12 * Without them resvg falls back to the system's fonts, and the text still
13 * draws, a few pixels off the arithmetic.
14 *
15 * Nothing in the SVG can reach outside it: the card emits no `href`, and
16 * `--resources-dir` points at a directory that does not exist.
17 */
18
19 import { existsSync } from "node:fs";
20 import { join } from "node:path";
21 import { childEnv } from "../../apps/process.ts";
22 import { Gate } from "../../git/env.ts";
23 import { isPng } from "../../design/image/png.ts";
24 import { err, ok, type Result } from "../../kernel/result.ts";
25
26 /** The resvg binary: `FORGE_RESVG`, else `resvg` on `PATH`. */
27 export function findResvg(): string | undefined {
28 const named = (process.env["FORGE_RESVG"] ?? "").trim();
29 if (named !== "") return existsSync(named) ? named : undefined;
30 return Bun.which("resvg") ?? undefined;
31 }
32
33 const FACES = [
34 "LiberationSans-Regular.ttf",
35 "LiberationSans-Bold.ttf",
36 "LiberationMono-Regular.ttf",
37 ] as const;
38
39 const FONT_DIRS = [
40 "/usr/share/fonts/truetype/liberation",
41 "/usr/share/fonts/truetype/liberation2",
42 "/usr/share/fonts/liberation-sans",
43 "/usr/share/fonts/liberation",
44 "/opt/homebrew/share/fonts",
45 "/usr/local/share/fonts",
46 ];
47
48 /**
49 * The three font files, from `FORGE_OG_FONTS` (a directory) or the places
50 * distributions put `fonts-liberation` — or undefined when any is missing.
51 */
52 export function findFonts(): readonly string[] | undefined {
53 const named = (process.env["FORGE_OG_FONTS"] ?? "").trim();
54 for (const dir of named !== "" ? [named] : FONT_DIRS) {
55 const files = FACES.map((f) => join(dir, f));
56 if (files.every((f) => existsSync(f))) return files;
57 }
58 return undefined;
59 }
60
61 /** The argv after the binary: fonts, families, then stdin → stdout. */
62 export function resvgArgs(fonts: readonly string[] | undefined): string[] {
63 const args: string[] = [];
64 if (fonts !== undefined) {
65 args.push("--skip-system-fonts");
66 for (const f of fonts) args.push("--use-font-file", f);
67 }
68 args.push(
69 "--sans-serif-family",
70 "Liberation Sans",
71 "--monospace-family",
72 "Liberation Mono",
73 "--resources-dir",
74 "/nonexistent/forge-og",
75 "-",
76 "-c",
77 );
78 return args;
79 }
80
81 /**
82 * Two renders at once, forge-wide, and at most `MAX_WAITING` in line: an
83 * unfurler storm queues, and a flood of made-up URLs (each one a distinct
84 * card, so each one a cold render) is refused rather than piled up.
85 */
86 const gate = new Gate(2);
87 export const MAX_WAITING = 16;
88 /** Renders running plus renders waiting for a permit. */
89 let inFlight = 0;
90
91 const TIMEOUT_MS = 5_000;
92 const MAX_SVG = 256 * 1024;
93
94 /** Rasterize `svg` to PNG bytes. */
95 export async function rasterize(
96 svg: string,
97 ): Promise<Result<Uint8Array, string>> {
98 const binary = findResvg();
99 if (binary === undefined)
100 return err("no resvg on this forge: install one, or set FORGE_RESVG");
101 if (svg.length > MAX_SVG) return err("the SVG is larger than a card can be");
102 if (inFlight >= gate.limit + MAX_WAITING)
103 return err("busy: too many previews rendering");
104 inFlight++;
105 const release = await gate.acquire();
106 try {
107 const proc = Bun.spawn([binary, ...resvgArgs(findFonts())], {
108 env: childEnv({}),
109 stdin: new TextEncoder().encode(svg),
110 stdout: "pipe",
111 stderr: "pipe",
112 });
113 const timer = setTimeout(() => proc.kill("SIGKILL"), TIMEOUT_MS);
114 try {
115 // `arrayBuffer()`, not `bytes()`: Bun 1.3's `bytes()` on a spawned
116 // pipe sometimes resolves to a bare ArrayBuffer.
117 const [out, said, code] = await Promise.all([
118 new Response(proc.stdout).arrayBuffer(),
119 new Response(proc.stderr).text(),
120 proc.exited,
121 ]);
122 const png = new Uint8Array(out);
123 if (code !== 0 || !isPng(png)) {
124 const last = said
125 .split("\n")
126 .map((l) => l.trim())
127 .filter((l) => l !== "" && !l.startsWith("Warning"))
128 .at(-1);
129 return err(
130 `resvg exited ${code}${last === undefined ? "" : `: ${last.slice(0, 300)}`}`,
131 );
132 }
133 return ok(png);
134 } finally {
135 clearTimeout(timer);
136 }
137 } finally {
138 release();
139 inFlight--;
140 }
141 }
src/web/og/route.ts added +77
@@ -0,0 +1,77 @@
1 /**
2 * GET /og/:kind/*path — a link preview, 1200 × 630.
3 *
4 * /og/site/home.png the forge
5 * /og/repo/<owner>/<name>.png a repository
6 * …/<thing>.svg the same card before rasterizing, for
7 * looking at and for tests
8 *
9 * The kind reads its data as nobody (`kinds.ts`), the card is drawn from
10 * that data (`card.ts`), and the PNG is kept under the sha256 of the data
11 * (`cache.ts`), which is also its ETag. `cache-control` is short: the data
12 * is live, and a preview that is five minutes stale is still the story.
13 */
14
15 import type { Ctx } from "../../http/context.ts";
16 import { notFound } from "../../http/respond.ts";
17 import { PngCache, inputHash } from "./cache.ts";
18 import { cardSvg } from "./card.ts";
19 import { kindNamed } from "./kinds.ts";
20 import { rasterize } from "./raster.ts";
21
22 const cache = new PngCache();
23
24 const MAX_AGE = 300;
25
26 function etagMatches(ctx: Ctx, etag: string): boolean {
27 const asked = ctx.request.headers.get("if-none-match");
28 if (asked === null) return false;
29 return asked.split(",").some((t) => t.trim().replace(/^W\//, "") === etag);
30 }
31
32 export async function ogImage(ctx: Ctx): Promise<Response> {
33 const kindName = ctx.params["kind"] ?? "";
34 const rest = ctx.params["path"] ?? "";
35 const m = /^(.+)\.(png|svg)$/.exec(rest);
36 const kind = kindName === "" ? undefined : kindNamed(kindName);
37 if (m === null || kind === undefined) return notFound();
38 const format = m[2] as "png" | "svg";
39 const card = kind(
40 { db: ctx.app.db, host: ctx.url.host },
41 m[1]!.split("/"),
42 );
43 if (card === undefined) return notFound();
44
45 const hash = inputHash(kindName, card);
46 const etag = `"${hash}"`;
47 const headers = {
48 etag,
49 "cache-control": `public, max-age=${MAX_AGE}`,
50 };
51 if (etagMatches(ctx, etag)) return new Response(null, { status: 304, headers });
52
53 if (format === "svg")
54 return new Response(cardSvg(card), {
55 headers: { ...headers, "content-type": "image/svg+xml; charset=utf-8" },
56 });
57
58 const png = await cache.through(hash, () => rasterize(cardSvg(card)));
59 if (!png.ok) {
60 ctx.app.log.warn("og: render failed", { kind: kindName, error: png.error });
61 return new Response(`preview unavailable: ${png.error}\n`, {
62 status: 503,
63 headers: {
64 "content-type": "text/plain; charset=utf-8",
65 "cache-control": "no-store",
66 "retry-after": "60",
67 },
68 });
69 }
70 return new Response(png.value, {
71 headers: {
72 ...headers,
73 "content-type": "image/png",
74 "content-length": String(png.value.length),
75 },
76 });
77 }
test/og.test.ts added +314
@@ -0,0 +1,314 @@
1 /**
2 * The link-preview renderer (src/web/og): text arithmetic that matches a
3 * hand calculation, a card that escapes whatever it is given, a cache keyed
4 * by the input's hash, kinds that read as nobody — proven over HTTP with a
5 * signed-in owner — and, where resvg is installed, every kind rendered to a
6 * 1200 × 630 PNG inside the time budget.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { createRepo } from "../src/actions/repos.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { pngHeader } from "../src/design/image/png.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { canonical, inputHash, PngCache } from "../src/web/og/cache.ts";
19 import { cardSvg, HEIGHT, WIDTH, xmlText, type Card } from "../src/web/og/card.ts";
20 import { KINDS, kindNamed, privateCard, type OgSource } from "../src/web/og/kinds.ts";
21 import { clip, measure, wrap } from "../src/web/og/metrics.ts";
22 import { findResvg, MAX_WAITING, rasterize, resvgArgs } from "../src/web/og/raster.ts";
23 import { err, ok } from "../src/kernel/result.ts";
24
25 describe("metrics", () => {
26 test("a width is the sum of the font's advances, scaled from a 2048-unit em", () => {
27 // Liberation Sans: H 1479, e 1139, l 455, l 455, o 1139 = 4667 units.
28 expect(measure("Hello", 2048, "sans")).toBe(4667);
29 expect(measure("Hello", 100, "sans")).toBeCloseTo((4667 * 100) / 2048, 9);
30 // Bold: H 1479, i 569 = 2048 units — exactly one em.
31 expect(measure("Hi", 68, "bold")).toBe(68);
32 // Mono is 1229 units a glyph, whatever the glyph.
33 expect(measure("abc", 28, "mono")).toBeCloseTo((3 * 1229 * 28) / 2048, 9);
34 expect(measure("", 40, "sans")).toBe(0);
35 });
36
37 test("clip leaves what fits, and cuts what does not to fit with an ellipsis", () => {
38 expect(clip("short", 32, "sans", 1000)).toBe("short");
39 const cut = clip("a title much too long for the room it is given", 32, "sans", 200);
40 expect(cut.endsWith("…")).toBe(true);
41 expect(measure(cut, 32, "sans")).toBeLessThanOrEqual(200);
42 // Only just over: still cut, never drawn past the edge.
43 const word = "WWWWWWWWWW";
44 const max = measure(word, 20, "bold") - 1;
45 expect(measure(clip(word, 20, "bold", max), 20, "bold")).toBeLessThanOrEqual(max);
46 });
47
48 test("wrap breaks at spaces, keeps every line inside the width, and folds the rest into the last", () => {
49 const text = "one two three four five six seven eight nine ten eleven twelve";
50 const lines = wrap(text, 32, "sans", 300, 2);
51 expect(lines.length).toBe(2);
52 for (const l of lines) expect(measure(l, 32, "sans")).toBeLessThanOrEqual(300);
53 // "one two three four" is 16508 units = 257.9 px at 32 px; " five"
54 // (569 + 3187 units) would take it to 316.6 px, past 300.
55 expect(measure("one two three four", 2048, "sans")).toBe(16508);
56 expect(lines[0]).toBe("one two three four");
57 expect(lines[1]!.endsWith("…")).toBe(true);
58 // Room enough: every word, no ellipsis.
59 expect(wrap("a b c", 32, "sans", 1000, 3)).toEqual(["a b c"]);
60 // A word wider than a line is clipped where it stands.
61 const long = wrap(`${"x".repeat(200)} tail`, 32, "sans", 300, 3);
62 expect(long[0]!.endsWith("…")).toBe(true);
63 expect(long[1]).toBe("tail");
64 expect(wrap(" ", 32, "sans", 300, 2)).toEqual([]);
65 });
66 });
67
68 const sample: Card = {
69 eyebrow: "acme/engine",
70 title: "engine",
71 description: "A tick-accurate match engine.",
72 state: { label: "working", tone: "attn" },
73 stats: [
74 { value: "3", label: "changes waiting", tone: "accent" },
75 { value: "2", label: "crew working" },
76 { value: "$41", label: "today" },
77 ],
78 host: "forge.example.com",
79 };
80
81 describe("card", () => {
82 test("is a 1200 × 630 SVG that says what it was given", () => {
83 const svg = cardSvg(sample);
84 expect(svg).toStartWith(`<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}"`);
85 expect([WIDTH, HEIGHT]).toEqual([1200, 630]);
86 for (const s of ["acme/engine", "engine", "A tick-accurate match engine.", "working", "changes waiting", "$41", "forge.example.com"])
87 expect(svg).toContain(`>${s}<`);
88 });
89
90 test("escapes markup and drops the bytes XML forbids, so no input can change the document", () => {
91 expect(xmlText(`</text><image href="x"/>&`)).toBe("&lt;/text&gt;&lt;image href=&quot;x&quot;/&gt;&amp;");
92 expect(xmlText("a\u0000b\u001bc￾\nd")).toBe("abc d");
93 expect(xmlText("lone \ud800 surrogate")).toBe("lone � surrogate");
94 const svg = cardSvg({ ...sample, title: `<script>alert(1)</script>`, eyebrow: `x" onload="y` });
95 expect(svg).not.toContain("<script");
96 expect(svg).not.toContain(`x" onload`);
97 // The only elements are the ones the card draws: nothing that loads.
98 expect(svg).not.toMatch(/<(image|script|foreignObject|use)\b|href=/);
99 });
100
101 test("never draws more than four numbers", () => {
102 const stats = Array.from({ length: 6 }, (_, i) => ({ value: `${i}${i}${i}`, label: `n${i}` }));
103 const svg = cardSvg({ ...sample, stats });
104 expect(svg).toContain(">333<");
105 expect(svg).not.toContain(">444<");
106 });
107 });
108
109 describe("cache", () => {
110 test("the key is the input's hash: key order does not matter, any change does", () => {
111 expect(canonical({ b: 1, a: [{ d: 2, c: 3 }], u: undefined })).toBe(`{"a":[{"c":3,"d":2}],"b":1}`);
112 const reordered = Object.fromEntries(Object.entries(sample).reverse()) as unknown as Card;
113 expect(Object.keys(reordered)[0]).toBe("host");
114 expect(inputHash("repo", reordered)).toBe(inputHash("repo", sample));
115 expect(inputHash("repo", { ...sample, title: "engine2" })).not.toBe(inputHash("repo", sample));
116 expect(inputHash("site", sample)).not.toBe(inputHash("repo", sample));
117 expect(inputHash("repo", sample)).toMatch(/^[0-9a-f]{64}$/);
118 });
119
120 test("evicts the least recently used by bytes", () => {
121 const cache = new PngCache(10);
122 cache.set("a", new Uint8Array(4));
123 cache.set("b", new Uint8Array(4));
124 expect(cache.get("a")).toBeDefined(); // a is now the most recent
125 cache.set("c", new Uint8Array(4));
126 expect(cache.get("b")).toBeUndefined();
127 expect(cache.get("a")).toBeDefined();
128 expect(cache.get("c")).toBeDefined();
129 cache.set("huge", new Uint8Array(11));
130 expect(cache.get("huge")).toBeUndefined();
131 });
132
133 test("one render for concurrent asks; a failure is not kept", async () => {
134 const cache = new PngCache();
135 let renders = 0;
136 const render = async () => {
137 renders++;
138 await Bun.sleep(5);
139 return ok(new Uint8Array([1, 2, 3]));
140 };
141 const [x, y] = await Promise.all([cache.through("k", render), cache.through("k", render)]);
142 expect(x.ok && y.ok).toBe(true);
143 expect(renders).toBe(1);
144 await cache.through("k", render);
145 expect(renders).toBe(1);
146 let failures = 0;
147 const failing = async () => (failures++, err("no"));
148 expect((await cache.through("f", failing)).ok).toBe(false);
149 expect((await cache.through("f", failing)).ok).toBe(false);
150 expect(failures).toBe(2);
151 });
152 });
153
154 describe("raster arguments", () => {
155 test("with the measured fonts, only they are used; without, the system's", () => {
156 const fonts = ["/f/LiberationSans-Regular.ttf", "/f/LiberationSans-Bold.ttf", "/f/LiberationMono-Regular.ttf"];
157 const args = resvgArgs(fonts);
158 expect(args).toContain("--skip-system-fonts");
159 expect(args.filter((a) => a === "--use-font-file").length).toBe(3);
160 expect(args.slice(-2)).toEqual(["-", "-c"]);
161 expect(resvgArgs(undefined)).not.toContain("--skip-system-fonts");
162 });
163 });
164
165 describe("kinds and the route", () => {
166 let dataDir: string;
167 let app: App;
168 let servers: Servers;
169 let alice: User;
170 let cookie: string;
171 let source: OgSource;
172
173 beforeAll(async () => {
174 dataDir = await mkdtemp(join(tmpdir(), "forge-og-"));
175 app = createApp({ dataDir, port: 0 });
176 servers = await serve(app);
177 const made = await createUser(app.db, {
178 username: "alice",
179 email: "[email protected]",
180 password: "a-good-passphrase",
181 adminIfFirst: true,
182 });
183 if (!made.ok) throw new Error(made.error);
184 alice = made.value;
185 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
186 const open = await createRepo(app, alice, { name: "engine", visibility: "public", description: "A match engine." });
187 const secret = await createRepo(app, alice, { name: "secret", visibility: "private", description: "the launch plan" });
188 if (!open.ok || !secret.ok) throw new Error("repos");
189 source = { db: app.db, host: "forge.example.com" };
190 });
191
192 afterAll(async () => {
193 servers.stop();
194 app.close();
195 await rm(dataDir, { recursive: true, force: true });
196 });
197
198 test("a public repository says what it is and what is open", () => {
199 const card = kindNamed("repo")!(source, ["alice", "engine"])!;
200 expect(card.eyebrow).toBe("alice/engine");
201 expect(card.description).toBe("A match engine.");
202 expect(card.state).toEqual({ label: "public", tone: "success" });
203 expect(card.stats?.map((s) => s.value)).toEqual(["0", "0", "main"]);
204 });
205
206 test("a private repository and a missing one draw the same card, and neither says more than its name", () => {
207 const repo = kindNamed("repo")!;
208 const hidden = repo(source, ["alice", "secret"]);
209 const missing = repo(source, ["alice", "nothing"]);
210 expect(hidden).toEqual(privateCard(source, "alice/secret"));
211 expect(missing).toEqual(privateCard(source, "alice/nothing"));
212 expect(JSON.stringify(hidden)).not.toContain("launch plan");
213 });
214
215 test("the forge's own card counts only what is public", () => {
216 const card = KINDS["site"]!(source, ["home"])!;
217 expect(card.title).toBe("forge");
218 expect(card.host).toBe("forge.example.com");
219 expect(card.stats?.[0]).toEqual({ value: "1", label: "public repository" });
220 });
221
222 test("a path that is not a kind's shape is no card", () => {
223 expect(kindNamed("repo")!(source, ["alice"])).toBeUndefined();
224 expect(kindNamed("repo")!(source, ["alice", "../etc"])).toBeUndefined();
225 expect(KINDS["site"]!(source, ["elsewhere"])).toBeUndefined();
226 expect(kindNamed("constructor")).toBeUndefined();
227 expect(kindNamed("toString")).toBeUndefined();
228 });
229
230 test("over HTTP: the SVG, its ETag, a 304 for the same data, a 404 for no such kind", async () => {
231 const url = `${servers.url}/og/repo/alice/engine.svg`;
232 const res = await fetch(url);
233 expect(res.status).toBe(200);
234 expect(res.headers.get("content-type")).toStartWith("image/svg+xml");
235 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
236 expect(res.headers.get("content-security-policy")).not.toBeNull();
237 const etag = res.headers.get("etag")!;
238 expect(etag).toMatch(/^"[0-9a-f]{64}"$/);
239 expect(await res.text()).toContain(">A match engine.<");
240 const again = await fetch(url, { headers: { "if-none-match": etag } });
241 expect(again.status).toBe(304);
242 for (const path of ["/og/nope/x.png", "/og/repo/alice/engine.gif", "/og/repo/alice.png", "/og/site/home"])
243 expect((await fetch(`${servers.url}${path}`)).status).toBe(404);
244 });
245
246 test("over HTTP, a signed-in owner is still served what nobody sees", async () => {
247 const anonymous = await fetch(`${servers.url}/og/repo/alice/secret.svg`);
248 const owner = await fetch(`${servers.url}/og/repo/alice/secret.svg`, { headers: { cookie } });
249 const body = await owner.text();
250 expect(body).toBe(await anonymous.text());
251 expect(body).toContain(">private<");
252 expect(body).not.toContain("launch plan");
253 expect(owner.headers.get("etag")).toBe(anonymous.headers.get("etag"));
254 });
255
256 // Conditional on the tool, and loud about it (test/helpers/tools.ts):
257 // a machine without resvg skips these, and says so.
258 const noResvg = findResvg() === undefined;
259 if (noResvg)
260 console.log("SKIPPING: resvg is not installed here (nor FORGE_RESVG set), so the tests that rasterize cannot run on this machine");
261 describe.skipIf(noResvg)("rendered by resvg", () => {
262 const cards: Record<string, () => Card> = {
263 site: () => KINDS["site"]!(source, ["home"])!,
264 repo: () => KINDS["repo"]!(source, ["alice", "engine"])!,
265 private: () => KINDS["repo"]!(source, ["alice", "secret"])!,
266 full: () => ({ ...sample, title: "a title long enough to need ".repeat(5) }),
267 };
268
269 test("every kind is a 1200 × 630 PNG, cold inside the 300 ms budget", async () => {
270 const times: number[] = [];
271 for (const [name, card] of Object.entries(cards)) {
272 const started = performance.now();
273 const png = await rasterize(cardSvg(card()));
274 times.push(performance.now() - started);
275 if (!png.ok) throw new Error(`${name}: ${png.error}`);
276 const head = pngHeader(png.value);
277 expect(head.ok && [head.value.width, head.value.height]).toEqual([1200, 630]);
278 expect(png.value.length).toBeLessThan(200 * 1024);
279 }
280 // The median, so one scheduler hiccup on a busy machine is not a red gate.
281 times.sort((a, b) => a - b);
282 expect(times[Math.floor(times.length / 2)]!).toBeLessThan(300);
283 });
284
285 test("over HTTP: a PNG, and the second ask is served from the cache", async () => {
286 const url = `${servers.url}/og/site/home.png`;
287 const first = await fetch(url);
288 expect(first.status).toBe(200);
289 expect(first.headers.get("content-type")).toBe("image/png");
290 const bytes = new Uint8Array(await first.arrayBuffer());
291 expect(Number(first.headers.get("content-length"))).toBe(bytes.length);
292 const started = performance.now();
293 const second = await fetch(url);
294 const warm = performance.now() - started;
295 expect(new Uint8Array(await second.arrayBuffer())).toEqual(bytes);
296 expect(second.headers.get("etag")).toBe(first.headers.get("etag"));
297 expect(warm).toBeLessThan(50);
298 });
299 });
300 });
301
302 describe.skipIf(findResvg() === undefined)("the render queue", () => {
303 test("is bounded: past the line, a render is refused, not queued", async () => {
304 const svg = cardSvg(sample);
305 const all = await Promise.all(
306 Array.from({ length: 2 + MAX_WAITING + 4 }, () => rasterize(svg)),
307 );
308 const refused = all.filter((r) => !r.ok);
309 expect(refused.length).toBe(4);
310 for (const r of refused) expect(!r.ok && r.error).toStartWith("busy");
311 // And the line drains: the next one renders.
312 expect((await rasterize(svg)).ok).toBe(true);
313 }, 30_000);
314 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs