Skip to content
267 linesCodeBlameRaw
1/**
2 * Social cards: the PNG a link to g1t shows in a chat, a post or a search
3 * result, at `https://og.g1t.sh`.
4 *
5 * GET /image?path=/<any page of g1t.sh>[&v=<version>]
6 * GET /docs?title=&section=&description=[&v=<version>]
7 *
8 * A page's card is looked up as an anonymous visitor would see the page,
9 * so nothing private ever reaches one (see `resolve.ts`). Cards are kept in
10 * the edge cache under the render version and the parameters that change
11 * them (see `cache.ts`). The site and the docs add `v`, which changes when
12 * the design does (`OG_RENDER_VERSION` in packages/contracts) or when what
13 * a card shows does, so a new logo or an edited title gets a new address.
14 *
15 * Also the `Screenshots` entrypoint, reached only through service
16 * bindings: a screenshot of each project's production, per deploy (see
17 * `capture.ts`).
18 */
19import { WorkerEntrypoint } from "cloudflare:workers";
20import { type ServiceBinding, identityClient, platformPaused, projectsClient, reposClient, workClient } from "@g1t/contracts";
21import { type RateLimitBinding, clientAddress, isLimited } from "@g1t/contracts/rate-limits";
22import type { Font } from "satori/standalone";
23import resvgWasm from "@resvg/resvg-wasm/index_bg.wasm";
24import yogaWasm from "satori/yoga.wasm";
25
26import display500 from "./fonts/bricolage-grotesque-500.ttf";
27import display600 from "./fonts/bricolage-grotesque-600.ttf";
28import sans400 from "./fonts/hanken-grotesk-400.ttf";
29import sans500 from "./fonts/hanken-grotesk-500.ttf";
30import sans600 from "./fonts/hanken-grotesk-600.ttf";
31import sans700 from "./fonts/hanken-grotesk-700.ttf";
32import mono400 from "./fonts/ibm-plex-mono-400.ttf";
33import mono500 from "./fonts/ibm-plex-mono-500.ttf";
34import { cardPng } from "./render.ts";
35import { cacheKey, drawnKey } from "./cache.ts";
36import { type Shot, screenshotOf, sweep, take } from "./capture.ts";
37import { pausedCard } from "./paused.ts";
38import { parseShot } from "./screenshot.ts";
39import { BRAND, type Card, cardPath, docsCard, resolve } from "./resolve.ts";
40
41interface Env {
42 /** Uploaded avatars by hash, with `{ contentType }`; written by identity. */
43 AVATARS: KVNamespace;
44 IDENTITY: ServiceBinding;
45 REPOS: ServiceBinding;
46 WORK: ServiceBinding;
47 PROJECTS: ServiceBinding;
48 /** Whether rendering is paused across g1t (billing's `platform_pause`). */
49 BILLING?: ServiceBinding;
50 /** Browser Rendering, for production screenshots. */
51 BROWSER: Fetcher;
52 /** Production screenshots, by app hostname. */
53 SCREENSHOTS: R2Bucket;
54 /** Cards drawn per address (RATE_LIMITS in packages/contracts). Absent: no limit. */
55 OG_RENDER_LIMIT?: RateLimitBinding;
56}
57
58/**
59 * Production screenshots. `capture` is called by deployments when
60 * production goes live; `image` by the site, for a project's overview, which
61 * decides who may see it.
62 */
63export class Screenshots extends WorkerEntrypoint<Env> {
64 /** Takes the screenshot of `{ host, commit }` in the background. */
65 async capture(input: unknown): Promise<boolean> {
66 const request = parseShot(input);
67 if (!request) return false;
68 this.ctx.waitUntil(take(this.env, request));
69 return true;
70 }
71
72 /**
73 * The screenshot of `{ host, commit }`, taken now if it has not been, or
74 * the last one kept for that app. Its `commit` says which it is.
75 */
76 async image(input: unknown): Promise<Shot | null> {
77 const request = parseShot(input);
78 if (!request) return null;
79 return screenshotOf(this.env, request);
80 }
81}
82
83/*
84 * g1t's typefaces, as on the site (packages/theme), but static: the
85 * renderer takes no variable fonts. Bricolage is cut at the optical size
86 * of the headlines it sets on a card.
87 */
88const FONTS: Font[] = [
89 { name: "Hanken Grotesk", data: sans400, weight: 400, style: "normal" },
90 { name: "Hanken Grotesk", data: sans500, weight: 500, style: "normal" },
91 { name: "Hanken Grotesk", data: sans600, weight: 600, style: "normal" },
92 { name: "Hanken Grotesk", data: sans700, weight: 700, style: "normal" },
93 { name: "Bricolage Grotesque", data: display500, weight: 500, style: "normal" },
94 { name: "Bricolage Grotesque", data: display600, weight: 600, style: "normal" },
95 { name: "IBM Plex Mono", data: mono400, weight: 400, style: "normal" },
96 { name: "IBM Plex Mono", data: mono500, weight: 500, style: "normal" },
97];
98
99const ASSETS = { yoga: yogaWasm, resvg: resvgWasm, fonts: FONTS };
100
101/** Kept an hour by browsers and a day at the edge. */
102const CACHE_CONTROL = "public, max-age=3600, s-maxage=86400";
103/** When a service could not be reached: soon tried again. */
104const BRIEF_CACHE_CONTROL = "public, max-age=60";
105
106/** When even the brand card cannot be drawn: never kept, so the next request tries again. */
107const NO_STORE = "no-store";
108
109export default {
110 /** Once a day: old screenshots out (capture.ts `sweep`). */
111 async scheduled(_event: ScheduledController, env: Env): Promise<void> {
112 const removed = await sweep(env).catch((error) => (console.error("og: sweep failed", error), 0));
113 if (removed) console.log(`og: removed ${removed} old screenshots`);
114 },
115
116 async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
117 const url = new URL(request.url);
118 if (request.method !== "GET" && request.method !== "HEAD") {
119 return new Response("Method not allowed", { status: 405, headers: { allow: "GET, HEAD" } });
120 }
121 if (url.pathname === "/health") return new Response("ok");
122 if (url.pathname !== "/" && url.pathname !== "/image" && url.pathname !== "/docs") {
123 return new Response("Not found", { status: 404 });
124 }
125
126 const key = cacheKey(url);
127 const cache = (caches as unknown as { default: Cache }).default;
128 const hit = await cache.match(key);
129 if (hit) return hit;
130 // Rendering paused across g1t: no card is drawn (paused.ts).
131 if (await platformPaused(env.BILLING, "renders")) return pausedCard(await cache.match(cacheKey(new URL("/", url))));
132
133 // Every page without a card of its own shares the one brand card, so
134 // made-up paths cannot make the service draw it again and again.
135 const brandKey = cacheKey(new URL("/", url));
136 // A miss looks the page up and draws its card: limited per address.
137 // Past the limit, the brand card, kept only briefly so the page's own
138 // card is asked for again later.
139 if (key !== brandKey && (await isLimited(env.OG_RENDER_LIMIT, `ip:${clientAddress(request)}`))) {
140 const brand = await cache.match(brandKey);
141 if (brand) return withCacheControl(brand, true);
142 const drawn = await brandCard(ctx, cache, brandKey);
143 return drawn.ok ? withCacheControl(drawn, true) : drawn;
144 }
145
146 const found = await lookUpCard(url, env);
147 const failed = found.kind === "brand" && found.failed === true;
148 if (found.kind === "brand" && key !== brandKey) {
149 const brand = await cache.match(brandKey);
150 if (brand) return withCacheControl(brand, failed);
151 }
152 // The same card under another address (another `v`): drawn once.
153 const drawn = found.kind === "brand" ? null : await drawnKey(url.origin, found);
154 const same = drawn ? await cache.match(drawn) : undefined;
155 if (same) {
156 ctx.waitUntil(cache.put(key, same.clone()));
157 return same;
158 }
159 const card = await withIcon(found, env);
160
161 let png: Uint8Array;
162 let fellBack = false;
163 try {
164 png = await cardPng(card, ASSETS);
165 } catch (error) {
166 console.error("og: rendering failed", url.pathname, error);
167 try {
168 // An icon it could not draw is left out rather than losing the card;
169 // anything else gets the brand card, kept only briefly.
170 if ((card.kind === "workspace" || card.kind === "person") && card.icon) {
171 png = await cardPng({ ...card, icon: undefined }, ASSETS);
172 } else if (card.kind !== "brand") {
173 png = await cardPng(BRAND, ASSETS);
174 fellBack = true;
175 } else {
176 throw error;
177 }
178 } catch (again) {
179 console.error("og: the brand card could not be drawn either", again);
180 return new Response("The card could not be drawn", { status: 503, headers: { "cache-control": NO_STORE } });
181 }
182 }
183 const response = new Response(png, {
184 headers: {
185 "content-type": "image/png",
186 "cache-control": CACHE_CONTROL,
187 "access-control-allow-origin": "*",
188 "x-content-type-options": "nosniff",
189 },
190 });
191 if (fellBack) return withCacheControl(response, true);
192 if (card.kind === "brand") {
193 ctx.waitUntil(cache.put(brandKey, response.clone()));
194 } else {
195 ctx.waitUntil(cache.put(key, response.clone()));
196 if (drawn) ctx.waitUntil(cache.put(drawn, response.clone()));
197 }
198 return withCacheControl(response, failed);
199 },
200} satisfies ExportedHandler<Env>;
201
202/** A card shown because a service failed is kept only briefly, by anyone. */
203function withCacheControl(response: Response, failed: boolean): Response {
204 if (!failed) return response;
205 const brief = new Response(response.body, response);
206 brief.headers.set("cache-control", BRIEF_CACHE_CONTROL);
207 return brief;
208}
209
210/** The brand card when the cache has lost it: drawn once and kept again. */
211async function brandCard(ctx: ExecutionContext, cache: Cache, brandKey: string): Promise<Response> {
212 try {
213 const response = new Response(await cardPng(BRAND, ASSETS), {
214 headers: {
215 "content-type": "image/png",
216 "cache-control": CACHE_CONTROL,
217 "access-control-allow-origin": "*",
218 "x-content-type-options": "nosniff",
219 },
220 });
221 ctx.waitUntil(cache.put(brandKey, response.clone()));
222 return response;
223 } catch (error) {
224 console.error("og: the brand card could not be drawn", error);
225 return new Response("The card could not be drawn", { status: 503, headers: { "cache-control": NO_STORE } });
226 }
227}
228
229/** What satori can draw: PNG and JPEG. A WebP or GIF icon is left off the card. */
230const DRAWABLE = new Set(["image/png", "image/jpeg"]);
231
232/** A workspace's or person's uploaded icon as a data URI, if it has one satori can draw. */
233async function iconFor(env: Env, avatar: string | null | undefined): Promise<string | undefined> {
234 if (!avatar || !/^[0-9a-f]{64}$/.test(avatar)) return undefined;
235 try {
236 // An avatar's key is its hash: what is under it never changes.
237 const { value, metadata } = await env.AVATARS.getWithMetadata<{ contentType?: string }>(avatar, {
238 type: "arrayBuffer",
239 cacheTtl: 86_400,
240 });
241 const type = metadata?.contentType;
242 if (!value || !type || !DRAWABLE.has(type)) return undefined;
243 const bytes = new Uint8Array(value);
244 let binary = "";
245 for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
246 return `data:${type};base64,${btoa(binary)}`;
247 } catch {
248 return undefined;
249 }
250}
251
252async function withIcon(card: Card, env: Env): Promise<Card> {
253 if (card.kind === "workspace" || card.kind === "person") return { ...card, icon: await iconFor(env, card.avatar) };
254 return card;
255}
256
257async function lookUpCard(url: URL, env: Env): Promise<Card> {
258 if (url.pathname === "/docs") return docsCard(url.searchParams);
259 if (url.pathname === "/") return BRAND;
260 // The page whose card it is, as the cache key has it (cache.ts).
261 return resolve(cardPath(url.searchParams.get("path") ?? "/"), {
262 identity: identityClient(env.IDENTITY),
263 repos: reposClient(env.REPOS),
264 work: workClient(env.WORK),
265 projects: projectsClient(env.PROJECTS),
266 });
267}