pr_01m47d24b0e6n91zwymwxg0vpx/services/og/src/screenshot.ts
| 1 | /** |
| 2 | * Screenshots of a project's production: one per deploy, kept in R2 under |
| 3 | * the app's g1t.page hostname, with the commit it shows. Only apps on |
| 4 | * g1t.page are ever visited, and only by hostname: a custom domain serves |
| 5 | * the same app. |
| 6 | */ |
| 7 | |
| 8 | export const DEPLOYMENTS_DOMAIN = "g1t.page"; |
| 9 | /** The page is drawn at this size; the overview shows it scaled down. */ |
| 10 | export const VIEWPORT = { width: 1280, height: 800 }; |
| 11 | /** How long a page has to settle before it is taken anyway. */ |
| 12 | export const SETTLE_MS = 12_000; |
| 13 | /** A screenshot that could not be taken is tried again after this long. */ |
| 14 | export const RETRY_AFTER_MS = 5 * 60 * 1000; |
| 15 | |
| 16 | export type ShotRequest = { host: string; commit: string }; |
| 17 | |
| 18 | /** Hostnames on g1t.page that are not apps. */ |
| 19 | const RESERVED = new Set(["domains", "www"]); |
| 20 | |
| 21 | /** The request, if it names an app on g1t.page and a commit. */ |
| 22 | export function parseShot(input: unknown): ShotRequest | null { |
| 23 | if (!input || typeof input !== "object") return null; |
| 24 | const { host, commit } = input as Record<string, unknown>; |
| 25 | if (typeof host !== "string" || typeof commit !== "string") return null; |
| 26 | const name = host.toLowerCase(); |
| 27 | const suffix = `.${DEPLOYMENTS_DOMAIN}`; |
| 28 | if (!name.endsWith(suffix)) return null; |
| 29 | const label = name.slice(0, -suffix.length); |
| 30 | if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label) || RESERVED.has(label)) return null; |
| 31 | if (!/^[0-9a-f]{7,64}$/i.test(commit)) return null; |
| 32 | return { host: name, commit: commit.toLowerCase() }; |
| 33 | } |
| 34 | |
| 35 | /** Where an app's screenshot is kept. */ |
| 36 | export function shotKey(host: string): string { |
| 37 | return `production/${host}.jpg`; |
| 38 | } |
| 39 | |
| 40 | /** Where the last attempt at an app's screenshot is noted. */ |
| 41 | export function attemptKey(host: string): string { |
| 42 | return `attempts/${host}`; |
| 43 | } |
| 44 | |
| 45 | /** Whether to try again: not for the same commit within `RETRY_AFTER_MS`. */ |
| 46 | export function shouldAttempt(last: { commit?: string; at?: string } | null | undefined, commit: string, now: number): boolean { |
| 47 | if (!last?.at || last.commit !== commit) return true; |
| 48 | const at = Date.parse(last.at); |
| 49 | return !Number.isFinite(at) || now - at >= RETRY_AFTER_MS; |
| 50 | } |