| 1 | import { Hono } from "hono"; |
| 2 | import type { AppVars } from "../auth/principal.js"; |
| 3 | import type { Env } from "../env.js"; |
| 4 | import { now } from "../lib/util.js"; |
| 5 | import { githubApp, webhookSigned } from "./github.js"; |
| 6 | import { runnerFor, type JobEvent, type QueuedJob } from "./service.js"; |
| 7 | |
| 8 | /** |
| 9 | * POST /-/github/webhook: the GitHub App's webhook (github-runners/github.ts). Off (404) until the app is |
| 10 | * configured; every delivery must carry GitHub's signature made with GITHUB_APP_WEBHOOK_SECRET. |
| 11 | * |
| 12 | * - workflow_job: a queued job whose runs-on asks for a Diffinery runner waits for one in the GitHubRunnersDO |
| 13 | * of the account its installation is linked to; in_progress and completed say which job a Diffinery |
| 14 | * runner took, and drop queued jobs that no longer need one. |
| 15 | * - installation and installation_target: an uninstalled app's link goes, a suspended one starts nothing, |
| 16 | * and a renamed GitHub account keeps its link under the new name. |
| 17 | */ |
| 18 | |
| 19 | /** Largest delivery read, in bytes: workflow_job deliveries are a few kilobytes, installation ones list repositories. */ |
| 20 | export const MAX_WEBHOOK_BODY = 5 << 20; |
| 21 | |
| 22 | export const githubWebhook = new Hono<{ Bindings: Env; Variables: AppVars }>(); |
| 23 | |
| 24 | interface WorkflowJobPayload { |
| 25 | action: string; |
| 26 | workflow_job: { id: number; run_id?: number; name?: string; workflow_name?: string | null; labels?: string[]; runner_name?: string | null; conclusion?: string | null; html_url?: string }; |
| 27 | repository: { full_name: string }; |
| 28 | installation?: { id: number }; |
| 29 | } |
| 30 | |
| 31 | interface InstallationPayload { |
| 32 | action: string; |
| 33 | installation: { id: number; account?: { login?: string } | null }; |
| 34 | } |
| 35 | |
| 36 | githubWebhook.post("/-/github/webhook", async (c) => { |
| 37 | const app = githubApp(c.env); |
| 38 | if (!app || !c.env.GITHUB_RUNNERS) return c.json({ message: "GitHub runners are off: this Diffinery has no GitHub App" }, 404); |
| 39 | if (Number(c.req.header("content-length") ?? 0) > MAX_WEBHOOK_BODY) return c.json({ message: "body too large" }, 413); |
| 40 | const body = await c.req.text(); |
| 41 | if (body.length > MAX_WEBHOOK_BODY) return c.json({ message: "body too large" }, 413); |
| 42 | if (!(await webhookSigned(app.webhookSecret, c.req.header("x-hub-signature-256"), body))) return c.json({ message: "missing or bad signature" }, 401); |
| 43 | let payload: unknown; |
| 44 | try { |
| 45 | payload = JSON.parse(body); |
| 46 | } catch { |
| 47 | return c.json({ message: "body must be JSON" }, 400); |
| 48 | } |
| 49 | const event = c.req.header("x-github-event") ?? ""; |
| 50 | const db = c.env.DB; |
| 51 | if (event === "ping") return c.json({ ok: true }); |
| 52 | |
| 53 | if (event === "installation" || event === "installation_target") { |
| 54 | const p = payload as InstallationPayload; |
| 55 | const id = p.installation?.id; |
| 56 | if (typeof id !== "number") return c.json({ message: "no installation" }, 400); |
| 57 | if (event === "installation" && p.action === "deleted") await db.prepare("DELETE FROM github_installations WHERE id = ?").bind(id).run(); |
| 58 | else if (event === "installation" && p.action === "suspend") await db.prepare("UPDATE github_installations SET suspended_at = ? WHERE id = ?").bind(now(), id).run(); |
| 59 | else if (event === "installation" && p.action === "unsuspend") await db.prepare("UPDATE github_installations SET suspended_at = NULL WHERE id = ?").bind(id).run(); |
| 60 | else if (event === "installation_target" && p.action === "renamed" && p.installation.account?.login) await db.prepare("UPDATE github_installations SET github_login = ? WHERE id = ?").bind(p.installation.account.login, id).run(); |
| 61 | return c.json({ ok: true }); |
| 62 | } |
| 63 | |
| 64 | if (event !== "workflow_job") return c.json({ ignored: `event ${event}` }); |
| 65 | const p = payload as WorkflowJobPayload; |
| 66 | const job = p.workflow_job; |
| 67 | const installationId = p.installation?.id; |
| 68 | if (!job || typeof job.id !== "number" || typeof installationId !== "number" || !p.repository?.full_name) return c.json({ message: "not a workflow_job delivery" }, 400); |
| 69 | const labels = (job.labels ?? []).filter((l): l is string => typeof l === "string").slice(0, 100); |
| 70 | const size = runnerFor(labels); |
| 71 | const ours = typeof job.runner_name === "string" && job.runner_name.startsWith("diffinery-"); |
| 72 | // Most jobs of an installed repository aren't for Diffinery: nothing to look up for those. |
| 73 | if (!size && !ours) return c.json({ ignored: "not for a Diffinery runner" }); |
| 74 | const link = await db.prepare("SELECT account_id FROM github_installations WHERE id = ?").bind(installationId).first<{ account_id: string }>(); |
| 75 | if (!link) return c.json({ ignored: "this installation isn't linked to a Diffinery account" }); |
| 76 | const stub = c.env.GITHUB_RUNNERS.get(c.env.GITHUB_RUNNERS.idFromName(link.account_id)); |
| 77 | |
| 78 | if (p.action === "queued" && size) { |
| 79 | const q: QueuedJob = { |
| 80 | installationId, |
| 81 | repo: p.repository.full_name, |
| 82 | githubJobId: job.id, |
| 83 | runId: typeof job.run_id === "number" ? job.run_id : null, |
| 84 | workflowName: job.workflow_name ?? null, |
| 85 | jobName: job.name ?? null, |
| 86 | htmlUrl: typeof job.html_url === "string" && job.html_url.startsWith(app.webUrl + "/") ? job.html_url : null, |
| 87 | labels, |
| 88 | }; |
| 89 | await stub.queued(link.account_id, q, size); |
| 90 | return c.json({ queued: true, size }); |
| 91 | } |
| 92 | if (p.action === "in_progress" || p.action === "completed") { |
| 93 | const ev: JobEvent = { installationId, githubJobId: job.id, action: p.action, runnerName: ours ? job.runner_name! : null, jobName: job.name ?? null, conclusion: job.conclusion ?? null }; |
| 94 | await stub.jobEvent(link.account_id, ev); |
| 95 | } |
| 96 | return c.json({ ok: true }); |
| 97 | }); |