g1t/services/og/src/index.ts

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