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

OG cards as PNG: the SVG card rasterized once per input hash and stored under FORGE_APP_DATA #1756

Closed opened this
Closed without merging

scout/forge:scout/568-og-cards-as-png-the-svg-card-rasterized → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +498 −3
README.md +22 −2
@@ -19,8 +19,8 @@ git underneath is one click away — the switch in the top bar, or `?mode=dev` o
1919 any URL — and it is the rest of this page.
2020
2121 Git hosting, code browsing, and a JSON API in one fast Bun process, with
22 **zero runtime dependencies** — the `package.json` dependency list is empty and
23 stays that way. The one exception is dev-only: `@anthropic-ai/sandbox-runtime`
22 **one runtime dependency** (`@resvg/resvg-wasm`, for PNG link-preview cards; see
23 "Link-preview cards"). Dev-only: `@anthropic-ai/sandbox-runtime`
2424 (a devDependency, with its own few transitive packages) lets
2525 `test/crew-sandbox-real.test.ts` run a shell under the very sandbox Claude Code
2626 builds from the crew's settings; it never ships and the app never imports it. Everything worth having is written here: the Result type, the
@@ -564,6 +564,26 @@ thoughts are web-only there; `POST /api/v1/thoughts` is the other way in.
564564 social cards. They show only what an anonymous reader can open; anything
565565 private, sealed or unknown is the same 404.
566566
567 Link previews on X, Slack and iMessage need PNG, so each card also answers at
568 the same path ending `.png` (`/og/repo/owner~name.png`, …), rasterized from the
569 SVG. A PNG is drawn once per sha256 of the card's inputs and stored in
570 `FORGE_APP_DATA/og-cache/`; the cache holds at most **500** files, the least
571 recently used going first (the newest 32 also stay in memory). Measured here:
572 first render in a process 150 ms (wasm load included), a later cold render
573 about 45 ms, a warm one under 1 ms; `test/og-png.test.ts` holds the 300 ms and
574 5 ms limits. If the rasterizer fails the route answers 503 and logs it; nothing
575 else is affected.
576
577 **Dependency, `@resvg/resvg-wasm`** (the only runtime one): a rasterizer is
578 needed and none is built in to Bun; a native binding would need a build per
579 platform, while this is one wasm file that runs anywhere Bun does. It is 2.4 MB
580 on disk (loaded once, lazily, on the first PNG), has no dependencies of its
581 own, and is MPL-2.0. Fonts are vendored in `src/web/og/fonts/` (DejaVu Sans,
582 Sans Bold and Sans Mono, 1.8 MB, free licence in `LICENSE` beside them) and
583 are the only fonts the rasterizer is given, so a PNG's text never depends on
584 the host; DejaVu is wider than the SVG's system stack, which the card's
585 width estimate already assumes.
586
567587 ## Develop
568588
569589 ```sh
bun.lock +5
@@ -4,6 +4,9 @@
44 "workspaces": {
55 "": {
66 "name": "forge",
7 "dependencies": {
8 "@resvg/resvg-wasm": "^2.6.2",
9 },
710 "devDependencies": {
811 "@anthropic-ai/sandbox-runtime": "^0.0.79",
912 "@types/bun": "^1.2.0",
@@ -16,6 +19,8 @@
1619
1720 "@pondwader/socks5-server": ["@pondwader/[email protected]", "", {}, "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg=="],
1821
22 "@resvg/resvg-wasm": ["@resvg/[email protected]", "", {}, "sha512-FqALmHI8D4o6lk/LRWDnhw95z5eO+eAa6ORjVg09YRR7BkcM6oPHU9uyC0gtQG5vpFLvgpeU4+zEAz2H8APHNw=="],
23
1924 "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
2025
2126 "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-Vu4a5UFA9rIIFJ7rB/Vaafh9lrCQszopTCx6KjFboXTGQbPNasehVR5TEiithSDGyd1DEiUByggTZsg8jukeIg=="],
package.json +3
@@ -15,5 +15,8 @@
1515 "@anthropic-ai/sandbox-runtime": "^0.0.79",
1616 "@types/bun": "^1.2.0",
1717 "typescript": "^5.9.0"
18 },
19 "dependencies": {
20 "@resvg/resvg-wasm": "^2.6.2"
1821 }
1922 }
scripts/gate.ts +1
@@ -52,6 +52,7 @@ export const GATE: readonly string[] = [
5252 "test/claim-link.test.ts",
5353 "test/og-card.test.ts",
5454 "test/og-route.test.ts",
55 "test/og-png.test.ts",
5556 "test/health.test.ts",
5657 "test/client-address.test.ts",
5758 "test/client-list.test.ts",
src/http/server.ts +6 −1
@@ -254,7 +254,7 @@ import {
254254 runsList,
255255 } from "../web/pages/runs.ts";
256256 import { lookImage } from "../web/pages/looks.ts";
257 import { ogCard } from "../web/pages/og.ts";
257 import { ogCard, ogPng } from "../web/pages/og.ts";
258258 import { bigRedirect, boardPage } from "../web/pages/board.ts";
259259 import { returnsPage } from "../web/pages/returns.ts";
260260 import {
@@ -1033,10 +1033,15 @@ export function buildRouter(): Router<Handler> {
10331033 router.add("POST", "/:owner/:name/runs/:id/steer", runSteer);
10341034 // The public social cards: a repo as owner~name, an app as its slug.
10351035 router.add("GET", "/og/repo/:ref.svg", ogCard("repo"));
1036 router.add("GET", "/og/repo/:ref.png", ogPng("repo"));
10361037 router.add("GET", "/og/app/:ref.svg", ogCard("app"));
1038 router.add("GET", "/og/app/:ref.png", ogPng("app"));
10371039 router.add("GET", "/og/issue/:ref.svg", ogCard("issue"));
1040 router.add("GET", "/og/issue/:ref.png", ogPng("issue"));
10381041 router.add("GET", "/og/pull/:ref.svg", ogCard("pull"));
1042 router.add("GET", "/og/pull/:ref.png", ogPng("pull"));
10391043 router.add("GET", "/og/run/:ref.svg", ogCard("run"));
1044 router.add("GET", "/og/run/:ref.png", ogPng("run"));
10401045 // The pictures of an environment, read like the repository.
10411046 router.add("GET", "/:owner/:name/looks/:env/:commit/:kind.png", lookImage);
10421047
src/web/og/fonts/DejaVuSans-Bold.ttf added
Binary file not shown.
src/web/og/fonts/DejaVuSans.ttf added
Binary file not shown.
src/web/og/fonts/DejaVuSansMono.ttf added
Binary file not shown.
src/web/og/fonts/LICENSE added +187
@@ -0,0 +1,187 @@
1 Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
2 Glyphs imported from Arev fonts are (c) Tavmjong Bah (see below)
3
4
5 Bitstream Vera Fonts Copyright
6 ------------------------------
7
8 Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is
9 a trademark of Bitstream, Inc.
10
11 Permission is hereby granted, free of charge, to any person obtaining a copy
12 of the fonts accompanying this license ("Fonts") and associated
13 documentation files (the "Font Software"), to reproduce and distribute the
14 Font Software, including without limitation the rights to use, copy, merge,
15 publish, distribute, and/or sell copies of the Font Software, and to permit
16 persons to whom the Font Software is furnished to do so, subject to the
17 following conditions:
18
19 The above copyright and trademark notices and this permission notice shall
20 be included in all copies of one or more of the Font Software typefaces.
21
22 The Font Software may be modified, altered, or added to, and in particular
23 the designs of glyphs or characters in the Fonts may be modified and
24 additional glyphs or characters may be added to the Fonts, only if the fonts
25 are renamed to names not containing either the words "Bitstream" or the word
26 "Vera".
27
28 This License becomes null and void to the extent applicable to Fonts or Font
29 Software that has been modified and is distributed under the "Bitstream
30 Vera" names.
31
32 The Font Software may be sold as part of a larger software package but no
33 copy of one or more of the Font Software typefaces may be sold by itself.
34
35 THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
36 OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
37 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
38 TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
39 FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING
40 ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
41 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
42 THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE
43 FONT SOFTWARE.
44
45 Except as contained in this notice, the names of Gnome, the Gnome
46 Foundation, and Bitstream Inc., shall not be used in advertising or
47 otherwise to promote the sale, use or other dealings in this Font Software
48 without prior written authorization from the Gnome Foundation or Bitstream
49 Inc., respectively. For further information, contact: fonts at gnome dot
50 org.
51
52 Arev Fonts Copyright
53 ------------------------------
54
55 Copyright (c) 2006 by Tavmjong Bah. All Rights Reserved.
56
57 Permission is hereby granted, free of charge, to any person obtaining
58 a copy of the fonts accompanying this license ("Fonts") and
59 associated documentation files (the "Font Software"), to reproduce
60 and distribute the modifications to the Bitstream Vera Font Software,
61 including without limitation the rights to use, copy, merge, publish,
62 distribute, and/or sell copies of the Font Software, and to permit
63 persons to whom the Font Software is furnished to do so, subject to
64 the following conditions:
65
66 The above copyright and trademark notices and this permission notice
67 shall be included in all copies of one or more of the Font Software
68 typefaces.
69
70 The Font Software may be modified, altered, or added to, and in
71 particular the designs of glyphs or characters in the Fonts may be
72 modified and additional glyphs or characters may be added to the
73 Fonts, only if the fonts are renamed to names not containing either
74 the words "Tavmjong Bah" or the word "Arev".
75
76 This License becomes null and void to the extent applicable to Fonts
77 or Font Software that has been modified and is distributed under the
78 "Tavmjong Bah Arev" names.
79
80 The Font Software may be sold as part of a larger software package but
81 no copy of one or more of the Font Software typefaces may be sold by
82 itself.
83
84 THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
85 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
86 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
87 OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL
88 TAVMJONG BAH BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
89 INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
90 DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
91 FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
92 OTHER DEALINGS IN THE FONT SOFTWARE.
93
94 Except as contained in this notice, the name of Tavmjong Bah shall not
95 be used in advertising or otherwise to promote the sale, use or other
96 dealings in this Font Software without prior written authorization
97 from Tavmjong Bah. For further information, contact: tavmjong @ free
98 . fr.
99
100 TeX Gyre DJV Math
101 -----------------
102 Fonts are (c) Bitstream (see below). DejaVu changes are in public domain.
103
104 Math extensions done by B. Jackowski, P. Strzelczyk and P. Pianowski
105 (on behalf of TeX users groups) are in public domain.
106
107 Letters imported from Euler Fraktur from AMSfonts are (c) American
108 Mathematical Society (see below).
109 Bitstream Vera Fonts Copyright
110 Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera
111 is a trademark of Bitstream, Inc.
112
113 Permission is hereby granted, free of charge, to any person obtaining a copy
114 of the fonts accompanying this license (“Fonts”) and associated
115 documentation
116 files (the “Font Software”), to reproduce and distribute the Font Software,
117 including without limitation the rights to use, copy, merge, publish,
118 distribute,
119 and/or sell copies of the Font Software, and to permit persons to whom
120 the Font Software is furnished to do so, subject to the following
121 conditions:
122
123 The above copyright and trademark notices and this permission notice
124 shall be
125 included in all copies of one or more of the Font Software typefaces.
126
127 The Font Software may be modified, altered, or added to, and in particular
128 the designs of glyphs or characters in the Fonts may be modified and
129 additional
130 glyphs or characters may be added to the Fonts, only if the fonts are
131 renamed
132 to names not containing either the words “Bitstream” or the word “Vera”.
133
134 This License becomes null and void to the extent applicable to Fonts or
135 Font Software
136 that has been modified and is distributed under the “Bitstream Vera”
137 names.
138
139 The Font Software may be sold as part of a larger software package but
140 no copy
141 of one or more of the Font Software typefaces may be sold by itself.
142
143 THE FONT SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
144 OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY,
145 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT,
146 TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME
147 FOUNDATION
148 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL,
149 SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN
150 ACTION
151 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR
152 INABILITY TO USE
153 THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
154 Except as contained in this notice, the names of GNOME, the GNOME
155 Foundation,
156 and Bitstream Inc., shall not be used in advertising or otherwise to promote
157 the sale, use or other dealings in this Font Software without prior written
158 authorization from the GNOME Foundation or Bitstream Inc., respectively.
159 For further information, contact: fonts at gnome dot org.
160
161 AMSFonts (v. 2.2) copyright
162
163 The PostScript Type 1 implementation of the AMSFonts produced by and
164 previously distributed by Blue Sky Research and Y&Y, Inc. are now freely
165 available for general use. This has been accomplished through the
166 cooperation
167 of a consortium of scientific publishers with Blue Sky Research and Y&Y.
168 Members of this consortium include:
169
170 Elsevier Science IBM Corporation Society for Industrial and Applied
171 Mathematics (SIAM) Springer-Verlag American Mathematical Society (AMS)
172
173 In order to assure the authenticity of these fonts, copyright will be
174 held by
175 the American Mathematical Society. This is not meant to restrict in any way
176 the legitimate use of the fonts, such as (but not limited to) electronic
177 distribution of documents containing these fonts, inclusion of these fonts
178 into other public domain or commercial font collections or computer
179 applications, use of the outline data to create derivative fonts and/or
180 faces, etc. However, the AMS does require that the AMS copyright notice be
181 removed from any derivative versions of the fonts which have been altered in
182 any way. In addition, to ensure the fidelity of TeX documents using Computer
183 Modern fonts, Professor Donald Knuth, creator of the Computer Modern faces,
184 has requested that any alterations which yield different font metrics be
185 given a different name.
186
187 $Id$
src/web/og/raster.ts added +136
@@ -0,0 +1,136 @@
1 /**
2 * The social card as PNG — the SVG card rasterized with resvg (WebAssembly),
3 * stored on disk under `<data>/og-cache/` and keyed by the sha256 of the
4 * card's inputs, so a card is drawn once and then read back. The cache keeps
5 * at most CACHE_CAP files; a hit refreshes a file's mtime and the oldest
6 * mtimes go first (LRU).
7 *
8 * Fonts are vendored in ./fonts (DejaVu Sans, Bold, Sans Mono; free licence)
9 * and are the only fonts the rasterizer sees, so the text never depends on
10 * the host. Any failure here is thrown to the caller, which answers 503.
11 */
12
13 import { createHash } from "node:crypto";
14 import { mkdirSync, readdirSync, renameSync, statSync, unlinkSync, utimesSync } from "node:fs";
15 import { join } from "node:path";
16 import { fileURLToPath } from "node:url";
17 import { initWasm, Resvg } from "@resvg/resvg-wasm";
18 import { CARD_WIDTH, renderCard, type CardInput } from "./card.ts";
19
20 /** Most PNGs kept on disk (~40 KB each: about 20 MB at the cap). */
21 export const CACHE_CAP = 500;
22 /** Bump when the fonts or the rasterizer settings change: old files go stale. */
23 const RENDER_VERSION = "1";
24
25 const FONT_FILES = ["DejaVuSans.ttf", "DejaVuSans-Bold.ttf", "DejaVuSansMono.ttf"];
26
27 let ready: Promise<Uint8Array[]> | undefined;
28
29 /** Load the wasm and the fonts once; a failed load is retried next time. */
30 function load(): Promise<Uint8Array[]> {
31 ready ??= (async () => {
32 const wasm = fileURLToPath(import.meta.resolve("@resvg/resvg-wasm/index_bg.wasm"));
33 await initWasm(Bun.file(wasm).arrayBuffer());
34 return Promise.all(
35 FONT_FILES.map(async (f) =>
36 new Uint8Array(await Bun.file(new URL(`./fonts/${f}`, import.meta.url)).arrayBuffer()),
37 ),
38 );
39 })();
40 ready.catch(() => {
41 ready = undefined;
42 });
43 return ready;
44 }
45
46 /** Rasterize an SVG string to PNG bytes at the card's own width. */
47 export async function rasterize(svg: string): Promise<Uint8Array> {
48 const fontBuffers = await load();
49 const resvg = new Resvg(svg, {
50 fitTo: { mode: "width", value: CARD_WIDTH },
51 font: {
52 fontBuffers,
53 loadSystemFonts: false,
54 defaultFontFamily: "DejaVu Sans",
55 sansSerifFamily: "DejaVu Sans",
56 monospaceFamily: "DejaVu Sans Mono",
57 },
58 });
59 try {
60 const image = resvg.render();
61 try {
62 return image.asPng();
63 } finally {
64 image.free();
65 }
66 } finally {
67 resvg.free();
68 }
69 }
70
71 /** The cache key: sha256 of the inputs (and of how they are drawn). */
72 export function pngKey(input: CardInput): string {
73 return createHash("sha256")
74 .update(`${RENDER_VERSION}\n${JSON.stringify(input)}`)
75 .digest("hex");
76 }
77
78 function evict(dir: string, cap: number): void {
79 const files = readdirSync(dir)
80 .filter((f) => f.endsWith(".png"))
81 .map((f) => ({ f, t: statSync(join(dir, f)).mtimeMs }));
82 if (files.length <= cap) return;
83 files.sort((a, b) => a.t - b.t);
84 for (const { f } of files.slice(0, files.length - cap)) unlinkSync(join(dir, f));
85 }
86
87 /** The newest PNGs also stay in memory (Map order = recency), keyed by path. */
88 const HOT_CAP = 32;
89 const hot = new Map<string, Uint8Array>();
90
91 function remember(path: string, png: Uint8Array): void {
92 hot.delete(path);
93 hot.set(path, png);
94 if (hot.size > HOT_CAP) hot.delete(hot.keys().next().value as string);
95 }
96
97 function touch(path: string): void {
98 const now = new Date();
99 try {
100 utimesSync(path, now, now);
101 } catch {}
102 }
103
104 /** The card's PNG: from memory or disk when drawn before, else drawn, stored, returned. */
105 export async function cardPng(
106 dataDir: string,
107 input: CardInput,
108 cap = CACHE_CAP,
109 ): Promise<{ key: string; png: Uint8Array }> {
110 const key = pngKey(input);
111 const dir = join(dataDir, "og-cache");
112 const path = join(dir, `${key}.png`);
113 const kept = hot.get(path);
114 if (kept) {
115 remember(path, kept);
116 touch(path);
117 return { key, png: kept };
118 }
119 const hit = Bun.file(path);
120 if (await hit.exists()) {
121 const png = new Uint8Array(await hit.arrayBuffer());
122 remember(path, png);
123 touch(path);
124 return { key, png };
125 }
126 const png = await rasterize(renderCard(input));
127 mkdirSync(dir, { recursive: true });
128 const tmp = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
129 await Bun.write(tmp, png);
130 renameSync(tmp, path);
131 remember(path, png);
132 try {
133 evict(dir, cap);
134 } catch {}
135 return { key, png };
136 }
src/web/pages/og.ts +27
@@ -27,6 +27,7 @@ import { isSafeName } from "../../git/guard.ts";
2727 import type { Ctx } from "../../http/context.ts";
2828 import { notFound } from "../../http/respond.ts";
2929 import { renderCard, type CardInput } from "../og/card.ts";
30 import { cardPng } from "../og/raster.ts";
3031
3132 /** What an anonymous reader may see of a repository, or nothing. */
3233 function publicRepo(ctx: Ctx, repo: Repo | undefined): Repo | undefined {
@@ -125,3 +126,29 @@ export function ogCard(kind: OgKind) {
125126 return new Response(renderCard(input), { headers });
126127 };
127128 }
129
130 /** The same card as PNG, rasterized once per input hash; a failure is a 503. */
131 export function ogPng(kind: OgKind) {
132 return async (ctx: Ctx): Promise<Response> => {
133 const input = resolve(ctx, kind, ctx.params.ref ?? "");
134 if (!input) return notFound();
135 try {
136 const { key, png } = await cardPng(ctx.app.config.dataDir, input);
137 const etag = `"${key}"`;
138 const headers = {
139 etag,
140 "cache-control": "public, max-age=300",
141 "content-type": "image/png",
142 };
143 if (ctx.request.headers.get("if-none-match") === etag)
144 return new Response(null, { status: 304, headers });
145 return new Response(png, { headers });
146 } catch (error) {
147 ctx.app.log.warn("og png failed", { kind, error: String(error) });
148 return new Response("card unavailable\n", {
149 status: 503,
150 headers: { "content-type": "text/plain; charset=utf-8", "retry-after": "30" },
151 });
152 }
153 };
154 }
test/og-png.test.ts added +111
@@ -0,0 +1,111 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp as createForge, type App } from "../src/app.ts";
6 import { createRepo } from "../src/actions/repos.ts";
7 import { createUser } from "../src/core/users.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9 import { cardPng, pngKey, rasterize } from "../src/web/og/raster.ts";
10 import { renderCard } from "../src/web/og/card.ts";
11
12 const MAGIC = [0x89, 0x50, 0x4e, 0x47];
13 const card = (title: string) => ({ kind: "repo" as const, title, lines: ["a line"], stat: "1 issues" });
14
15 describe("og png", () => {
16 let dir: string;
17 beforeAll(async () => {
18 dir = await mkdtemp(join(tmpdir(), "forge-ogpng-"));
19 });
20 afterAll(() => rm(dir, { recursive: true, force: true }));
21
22 test("rasterizes the SVG card to a 1200-wide PNG", async () => {
23 const png = await rasterize(renderCard(card("alice/shown")));
24 expect([...png.slice(0, 4)]).toEqual(MAGIC);
25 expect(new DataView(png.buffer, png.byteOffset).getUint32(16)).toBe(1200);
26 });
27
28 test("cold under 300 ms, warm under 5 ms, same bytes, one file per key", async () => {
29 await cardPng(dir, card("warmup")); // wasm + fonts load once per process
30 const input = card("alice/timed");
31 let t = performance.now();
32 const cold = await cardPng(dir, input);
33 const coldMs = performance.now() - t;
34 t = performance.now();
35 const warm = await cardPng(dir, input);
36 const warmMs = performance.now() - t;
37 expect(coldMs).toBeLessThan(300);
38 expect(warmMs).toBeLessThan(5);
39 expect(warm.png).toEqual(cold.png);
40 expect(warm.key).toBe(pngKey(input));
41 expect(await readdir(join(dir, "og-cache"))).toContain(`${cold.key}.png`);
42 expect(pngKey(card("other"))).not.toBe(cold.key);
43 });
44
45 test("LRU cap: the least recently used file goes first", async () => {
46 const d = await mkdtemp(join(tmpdir(), "forge-ogpng-lru-"));
47 try {
48 const a = await cardPng(d, card("a"), 2);
49 await Bun.sleep(20);
50 const b = await cardPng(d, card("b"), 2);
51 await Bun.sleep(20);
52 await cardPng(d, card("a"), 2); // touch a: b is now the oldest
53 await Bun.sleep(20);
54 const c = await cardPng(d, card("c"), 2);
55 const left = (await readdir(join(d, "og-cache"))).sort();
56 expect(left).toEqual([`${a.key}.png`, `${c.key}.png`].sort());
57 expect(left).not.toContain(`${b.key}.png`);
58 } finally {
59 await rm(d, { recursive: true, force: true });
60 }
61 });
62
63 describe("route", () => {
64 let app: App;
65 let servers: Servers;
66 let data: string;
67 beforeAll(async () => {
68 data = await mkdtemp(join(tmpdir(), "forge-ogpng-app-"));
69 app = createForge({ dataDir: data, port: 0 });
70 servers = await serve(app);
71 const u = await createUser(app.db, {
72 trusted: true,
73 username: "alice",
74 email: "[email protected]",
75 password: "alice-passphrase",
76 adminIfFirst: true,
77 });
78 if (!u.ok) throw new Error(u.error);
79 const made = await createRepo(app, u.value, { name: "shown", visibility: "public" });
80 if (!made.ok) throw new Error(String(made.error));
81 await createRepo(app, u.value, { name: "hidden", visibility: "private" });
82 await createRepo(app, u.value, { name: "fresh", visibility: "public" });
83 });
84 afterAll(async () => {
85 await servers.stop?.();
86 await rm(data, { recursive: true, force: true });
87 });
88
89 test("serves PNG with an ETag, 304s, and 404s what the SVG 404s", async () => {
90 const res = await fetch(`${servers.url}/og/repo/alice~shown.png`);
91 expect(res.status).toBe(200);
92 expect(res.headers.get("content-type")).toBe("image/png");
93 expect([...new Uint8Array(await res.arrayBuffer()).slice(0, 4)]).toEqual(MAGIC);
94 const etag = res.headers.get("etag")!;
95 const again = await fetch(`${servers.url}/og/repo/alice~shown.png`, {
96 headers: { "if-none-match": etag },
97 });
98 expect(again.status).toBe(304);
99 expect((await fetch(`${servers.url}/og/repo/alice~hidden.png`)).status).toBe(404);
100 });
101
102 test("a rasterizer failure is a 503, and the server keeps answering", async () => {
103 // A file where the cache directory should be makes every store fail.
104 await rm(join(data, "og-cache"), { recursive: true, force: true });
105 await writeFile(join(data, "og-cache"), "not a directory");
106 const res = await fetch(`${servers.url}/og/repo/alice~fresh.png`);
107 expect(res.status).toBe(503);
108 expect((await fetch(`${servers.url}/`)).status).toBeLessThan(500);
109 });
110 });
111 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs