pr_01m47d15m3e54sn21z27rpy5n9/services/og/src/index.ts

121 lines4,771 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Social cards for every page: og.g1t.sh1/**
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=
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 by their full address; the site adds `v`, which changes
11 * when what a card shows does, so an edited title gets a new card.
12 */
13import { type ServiceBinding, identityClient, projectsClient, reposClient, workClient } from "@g1t/contracts";
14import type { Font } from "satori/standalone";
15import resvgWasm from "@resvg/resvg-wasm/index_bg.wasm";
16import yogaWasm from "satori/yoga.wasm";
17
18import inter400 from "./fonts/inter-400.ttf";
19import inter500 from "./fonts/inter-500.ttf";
20import inter600 from "./fonts/inter-600.ttf";
21import inter700 from "./fonts/inter-700.ttf";
22import mono400 from "./fonts/jetbrains-mono-400.ttf";
23import mono500 from "./fonts/jetbrains-mono-500.ttf";
24import { cardPng } from "./render.ts";
25import { cacheKey } from "./cache.ts";
26import { BRAND, type Card, docsCard, resolve } from "./resolve.ts";
27
28interface Env {
29 IDENTITY: ServiceBinding;
30 REPOS: ServiceBinding;
31 WORK: ServiceBinding;
32 PROJECTS: ServiceBinding;
33}
34
35const FONTS: Font[] = [
36 { name: "Inter", data: inter400, weight: 400, style: "normal" },
37 { name: "Inter", data: inter500, weight: 500, style: "normal" },
38 { name: "Inter", data: inter600, weight: 600, style: "normal" },
39 { name: "Inter", data: inter700, weight: 700, style: "normal" },
40 { name: "JetBrains Mono", data: mono400, weight: 400, style: "normal" },
41 { name: "JetBrains Mono", data: mono500, weight: 500, style: "normal" },
42];
43
44const ASSETS = { yoga: yogaWasm, resvg: resvgWasm, fonts: FONTS };
45
46/** Kept an hour by browsers and a day at the edge. */
47const CACHE_CONTROL = "public, max-age=3600, s-maxage=86400";
48/** When a service could not be reached: soon tried again. */
49const BRIEF_CACHE_CONTROL = "public, max-age=60";
50
51/** The static card, for when rendering itself fails. */
52const FALLBACK = "https://g1t.sh/brand/g1t-og.png";
53
54export default {
55 async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
56 const url = new URL(request.url);
57 if (request.method !== "GET" && request.method !== "HEAD") {
58 return new Response("Method not allowed", { status: 405, headers: { allow: "GET, HEAD" } });
59 }
60 if (url.pathname === "/health") return new Response("ok");
61 if (url.pathname !== "/" && url.pathname !== "/image" && url.pathname !== "/docs") {
62 return new Response("Not found", { status: 404 });
63 }
64
65 const key = cacheKey(url);
66 const cache = (caches as unknown as { default: Cache }).default;
67 const hit = await cache.match(key);
68 if (hit) return hit;
69
70 const card = await cardFor(url, env);
71 const failed = card.kind === "brand" && card.failed === true;
72 // Every page without a card of its own shares the one brand card, so
73 // made-up paths cannot make the service draw it again and again.
74 const brandKey = cacheKey(new URL("/", url));
75 if (card.kind === "brand" && key !== brandKey) {
76 const brand = await cache.match(brandKey);
77 if (brand) return withCacheControl(brand, failed);
78 }
79
80 let png: Uint8Array;
81 try {
82 png = await cardPng(card, ASSETS);
83 } catch (error) {
84 console.error("og: rendering failed", url.pathname, error);
85 return Response.redirect(FALLBACK, 302);
86 }
87 const response = new Response(png, {
88 headers: {
89 "content-type": "image/png",
90 "cache-control": CACHE_CONTROL,
91 "access-control-allow-origin": "*",
92 "x-content-type-options": "nosniff",
93 },
94 });
95 if (card.kind === "brand") {
96 ctx.waitUntil(cache.put(brandKey, response.clone()));
97 } else {
98 ctx.waitUntil(cache.put(key, response.clone()));
99 }
100 return withCacheControl(response, failed);
101 },
102} satisfies ExportedHandler<Env>;
103
104/** A card shown because a service failed is kept only briefly, by anyone. */
105function withCacheControl(response: Response, failed: boolean): Response {
106 if (!failed) return response;
107 const brief = new Response(response.body, response);
108 brief.headers.set("cache-control", BRIEF_CACHE_CONTROL);
109 return brief;
110}
111
112async function cardFor(url: URL, env: Env): Promise<Card> {
113 if (url.pathname === "/docs") return docsCard(url.searchParams);
114 if (url.pathname === "/") return BRAND;
115 return resolve(url.searchParams.get("path") ?? "/", {
116 identity: identityClient(env.IDENTITY),
117 repos: reposClient(env.REPOS),
118 work: workClient(env.WORK),
119 projects: projectsClient(env.PROJECTS),
120 });
121}