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