diff --git a/.github/workflows/migration-check.yml b/.github/workflows/migration-check.yml new file mode 100644 index 00000000..9ec65eb7 --- /dev/null +++ b/.github/workflows/migration-check.yml @@ -0,0 +1,43 @@ +name: D1 migration check + +on: + pull_request: + types: [opened, synchronize, reopened, edited] + paths: + - "apps/dashboard/drizzle/**" + - "apps/dashboard/src/db/**" + - "apps/dashboard/drizzle.config.ts" + - "scripts/check-d1-migrations.mjs" + - ".github/workflows/migration-check.yml" + +concurrency: + group: migration-check-${{ github.event.pull_request.number }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + migrations: + name: D1 migrations + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 2 + + - uses: pnpm/action-setup@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: pnpm + + - name: Install dependencies + run: pnpm install --frozen-lockfile --filter @diffkit/dashboard + + - name: Check migrations + env: + PR_BODY: ${{ github.event.pull_request.body }} + run: node scripts/check-d1-migrations.mjs --base HEAD^1 diff --git a/.github/workflows/production-alerts.yml b/.github/workflows/production-alerts.yml new file mode 100644 index 00000000..365b98bf --- /dev/null +++ b/.github/workflows/production-alerts.yml @@ -0,0 +1,39 @@ +name: Production alerts + +on: + schedule: + - cron: "7,22,37,52 * * * *" + workflow_dispatch: + +concurrency: + group: production-alerts + cancel-in-progress: false + +permissions: + contents: read + issues: write + +jobs: + watchdog: + name: Alert watchdog + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + sparse-checkout: scripts/production-alerts.mjs + sparse-checkout-cone-mode: false + + - uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Evaluate alerts and reconcile issues + env: + HEALTH_URL: https://diff-kit.com/api/health + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + D1_DATABASE_ID: ${{ secrets.DASHBOARD_PROD_D1_DATABASE_ID }} + WORKER_NAME: ${{ secrets.DASHBOARD_PROD_WORKER_NAME }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: node scripts/production-alerts.mjs diff --git a/apps/dashboard/src/entry-worker.test.ts b/apps/dashboard/src/entry-worker.test.ts index 511e5d8b..e4d093b6 100644 --- a/apps/dashboard/src/entry-worker.test.ts +++ b/apps/dashboard/src/entry-worker.test.ts @@ -75,7 +75,7 @@ describe("entry worker scheduled", () => { await worker.scheduled( { scheduledTime: 1234 } as ScheduledController, - { DB: {} as D1Database }, + { DB: {} as D1Database, GITHUB_CACHE_KV: {} as KVNamespace }, context, ); diff --git a/apps/dashboard/src/entry-worker.ts b/apps/dashboard/src/entry-worker.ts index edc27c0c..c0891c4d 100644 --- a/apps/dashboard/src/entry-worker.ts +++ b/apps/dashboard/src/entry-worker.ts @@ -60,13 +60,22 @@ export default { async scheduled( controller: ScheduledController, - env: { DB: D1Database }, + env: { DB: D1Database; GITHUB_CACHE_KV: KVNamespace }, ctx: ExecutionContext, ): Promise { ctx.waitUntil( - import("#/lib/scheduled-maintenance.server") - .then(({ runScheduledMaintenance }) => - runScheduledMaintenance(env.DB, controller.scheduledTime), + Promise.all([ + import("#/lib/scheduled-maintenance.server"), + import("#/lib/health.server"), + ]) + .then( + async ([{ runScheduledMaintenance }, { recordMaintenanceRun }]) => { + const summary = await runScheduledMaintenance( + env.DB, + controller.scheduledTime, + ); + await recordMaintenanceRun(env.GITHUB_CACHE_KV, summary); + }, ) .catch((error: unknown) => { logRouteError("worker", "scheduled maintenance failed", error); diff --git a/apps/dashboard/src/lib/health.server.test.ts b/apps/dashboard/src/lib/health.server.test.ts new file mode 100644 index 00000000..8f3b58ce --- /dev/null +++ b/apps/dashboard/src/lib/health.server.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; +import { checkHealth, healthResponse } from "./health.server"; +import { createTestD1 } from "./testing/d1-sqlite"; + +describe("health check", () => { + it("answers 503 with the failing dependency's details while the rest stay ok", async () => { + const { db } = createTestD1(); + const kv = { + get: async () => { + throw new Error("KV GET failed: 503 Service Unavailable"); + }, + } as unknown as KVNamespace; + + const response = healthResponse(await checkHealth({ db, kv })); + + expect(response.status).toBe(503); + expect(await response.json()).toMatchObject({ + status: "degraded", + version: { status: "unknown" }, + checks: { + d1: { status: "ok" }, + kv: { + status: "failed", + error: "KV GET failed: 503 Service Unavailable", + }, + }, + maintenance: { status: "unreadable" }, + }); + }); +}); diff --git a/apps/dashboard/src/lib/health.server.ts b/apps/dashboard/src/lib/health.server.ts new file mode 100644 index 00000000..b3982d32 --- /dev/null +++ b/apps/dashboard/src/lib/health.server.ts @@ -0,0 +1,160 @@ +export type DependencyCheck> = + | ({ status: "ok"; latencyMs: number } & T) + | { status: "failed"; latencyMs: number; error: string }; + +export type MaintenanceRun = + | { + status: "recent" | "stale"; + lastRunAt: string; + ageSeconds: number; + result: MaintenanceResult; + } + | { status: "never_recorded" } + | { status: "unreadable" }; + +export type WorkerVersion = + | { status: "known"; id: string; tag: string; uploadedAt: string } + | { status: "unknown" }; + +export type HealthReport = { + status: "ok" | "degraded"; + checkedAt: string; + version: WorkerVersion; + checks: { + d1: DependencyCheck<{ sizeBytes?: number }>; + kv: DependencyCheck; + }; + maintenance: MaintenanceRun; +}; + +type MaintenanceResult = "ok" | "errors"; +type MaintenanceHeartbeat = { ranAt: number; result: MaintenanceResult }; + +const MAINTENANCE_HEARTBEAT_KEY = "health:maintenance-heartbeat"; +const MAINTENANCE_HEARTBEAT_TTL_SECONDS = 24 * 60 * 60; +/** Two missed 5-minute cron runs plus scheduling slack. */ +const MAINTENANCE_STALE_AFTER_MS = 12 * 60 * 1000; +const CHECK_TIMEOUT_MS = 5_000; + +export async function recordMaintenanceRun( + kv: KVNamespace, + summary: Record, + ranAt = Date.now(), +) { + const heartbeat: MaintenanceHeartbeat = { + ranAt, + result: + "sweepError" in summary || "healthError" in summary ? "errors" : "ok", + }; + try { + await kv.put(MAINTENANCE_HEARTBEAT_KEY, JSON.stringify(heartbeat), { + expirationTtl: MAINTENANCE_HEARTBEAT_TTL_SECONDS, + }); + } catch (error) { + console.warn("[health] maintenance heartbeat write failed", error); + } +} + +export async function checkHealth(deps: { + db: D1Database; + kv: KVNamespace; + versionMetadata?: WorkerVersionMetadata; + now?: number; +}): Promise { + const now = deps.now ?? Date.now(); + const [d1, kvRead] = await Promise.all([ + timedCheck(async () => { + const result = await deps.db.prepare("SELECT 1 AS ok").all(); + const sizeBytes = result.meta.size_after; + return typeof sizeBytes === "number" ? { sizeBytes } : {}; + }), + timedCheck(async () => ({ + heartbeat: await deps.kv.get( + MAINTENANCE_HEARTBEAT_KEY, + "json", + ), + })), + ]); + + const checks = { d1, kv: withoutValue(kvRead) }; + return { + status: overallStatus(checks), + checkedAt: new Date(now).toISOString(), + version: workerVersion(deps.versionMetadata), + checks, + maintenance: maintenanceRun(kvRead, now), + }; +} + +export function healthResponse(report: HealthReport) { + return Response.json(report, { + status: report.status === "ok" ? 200 : 503, + headers: { "Cache-Control": "no-store" }, + }); +} + +function overallStatus(checks: HealthReport["checks"]): HealthReport["status"] { + return Object.values(checks).every((check) => check.status === "ok") + ? "ok" + : "degraded"; +} + +function workerVersion( + metadata: WorkerVersionMetadata | undefined, +): WorkerVersion { + if (!metadata?.id) return { status: "unknown" }; + return { + status: "known", + id: metadata.id, + tag: metadata.tag, + uploadedAt: metadata.timestamp, + }; +} + +function maintenanceRun( + kvRead: DependencyCheck<{ heartbeat: MaintenanceHeartbeat | null }>, + now: number, +): MaintenanceRun { + if (kvRead.status === "failed") return { status: "unreadable" }; + if (!kvRead.heartbeat) return { status: "never_recorded" }; + const { ranAt, result } = kvRead.heartbeat; + const ageMs = Math.max(0, now - ranAt); + return { + status: ageMs > MAINTENANCE_STALE_AFTER_MS ? "stale" : "recent", + lastRunAt: new Date(ranAt).toISOString(), + ageSeconds: Math.round(ageMs / 1000), + result, + }; +} + +function withoutValue( + check: DependencyCheck<{ heartbeat: unknown }>, +): DependencyCheck { + if (check.status === "failed") return check; + return { status: "ok", latencyMs: check.latencyMs }; +} + +async function timedCheck( + probe: () => Promise, +): Promise> { + const startedAt = Date.now(); + let timer: ReturnType | undefined; + const timeout = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`timed out after ${CHECK_TIMEOUT_MS}ms`)), + CHECK_TIMEOUT_MS, + ); + }); + try { + const value = await Promise.race([probe(), timeout]); + return { status: "ok", latencyMs: Date.now() - startedAt, ...value }; + } catch (error) { + return { + status: "failed", + latencyMs: Date.now() - startedAt, + error: error instanceof Error ? error.message : String(error), + }; + } finally { + clearTimeout(timer); + } +} diff --git a/apps/dashboard/src/routeTree.gen.ts b/apps/dashboard/src/routeTree.gen.ts index 11f4cb8f..f529073f 100644 --- a/apps/dashboard/src/routeTree.gen.ts +++ b/apps/dashboard/src/routeTree.gen.ts @@ -16,6 +16,7 @@ import { Route as LoginRouteImport } from './routes/login' import { Route as ProtectedRouteImport } from './routes/_protected' import { Route as SplatRouteImport } from './routes/$' import { Route as ProtectedIndexRouteImport } from './routes/_protected/index' +import { Route as ApiHealthRouteImport } from './routes/api/health' import { Route as ApiChangesRouteImport } from './routes/api/changes' import { Route as ProtectedSettingsRouteImport } from './routes/_protected/settings' import { Route as ProtectedReviewsRouteImport } from './routes/_protected/reviews' @@ -88,6 +89,11 @@ const ProtectedIndexRoute = ProtectedIndexRouteImport.update({ path: '/', getParentRoute: () => ProtectedRoute, } as any) +const ApiHealthRoute = ApiHealthRouteImport.update({ + id: '/api/health', + path: '/api/health', + getParentRoute: () => rootRouteImport, +} as any) const ApiChangesRoute = ApiChangesRouteImport.update({ id: '/api/changes', path: '/api/changes', @@ -309,6 +315,7 @@ export interface FileRoutesByFullPath { '/reviews': typeof ProtectedReviewsRoute '/settings': typeof ProtectedSettingsRouteWithChildren '/api/changes': typeof ApiChangesRoute + '/api/health': typeof ApiHealthRoute '/settings/shortcuts': typeof ProtectedSettingsShortcutsRoute '/api/auth/$': typeof ApiAuthSplatRoute '/api/webhooks/github': typeof ApiWebhooksGithubRoute @@ -352,6 +359,7 @@ export interface FileRoutesByTo { '/repos': typeof ProtectedReposRoute '/reviews': typeof ProtectedReviewsRoute '/api/changes': typeof ApiChangesRoute + '/api/health': typeof ApiHealthRoute '/': typeof ProtectedIndexRoute '/settings/shortcuts': typeof ProtectedSettingsShortcutsRoute '/api/auth/$': typeof ApiAuthSplatRoute @@ -399,6 +407,7 @@ export interface FileRoutesById { '/_protected/reviews': typeof ProtectedReviewsRoute '/_protected/settings': typeof ProtectedSettingsRouteWithChildren '/api/changes': typeof ApiChangesRoute + '/api/health': typeof ApiHealthRoute '/_protected/': typeof ProtectedIndexRoute '/_protected/settings/shortcuts': typeof ProtectedSettingsShortcutsRoute '/api/auth/$': typeof ApiAuthSplatRoute @@ -447,6 +456,7 @@ export interface FileRouteTypes { | '/reviews' | '/settings' | '/api/changes' + | '/api/health' | '/settings/shortcuts' | '/api/auth/$' | '/api/webhooks/github' @@ -490,6 +500,7 @@ export interface FileRouteTypes { | '/repos' | '/reviews' | '/api/changes' + | '/api/health' | '/' | '/settings/shortcuts' | '/api/auth/$' @@ -536,6 +547,7 @@ export interface FileRouteTypes { | '/_protected/reviews' | '/_protected/settings' | '/api/changes' + | '/api/health' | '/_protected/' | '/_protected/settings/shortcuts' | '/api/auth/$' @@ -576,6 +588,7 @@ export interface RootRouteChildren { SetupRoute: typeof SetupRoute TermsRoute: typeof TermsRoute ApiChangesRoute: typeof ApiChangesRoute + ApiHealthRoute: typeof ApiHealthRoute ApiAuthSplatRoute: typeof ApiAuthSplatRoute ApiWebhooksGithubRoute: typeof ApiWebhooksGithubRoute ApiGithubAppAuthorizeRoute: typeof ApiGithubAppAuthorizeRoute @@ -633,6 +646,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ProtectedIndexRouteImport parentRoute: typeof ProtectedRoute } + '/api/health': { + id: '/api/health' + path: '/api/health' + fullPath: '/api/health' + preLoaderRoute: typeof ApiHealthRouteImport + parentRoute: typeof rootRouteImport + } '/api/changes': { id: '/api/changes' path: '/api/changes' @@ -991,6 +1011,7 @@ const rootRouteChildren: RootRouteChildren = { SetupRoute: SetupRoute, TermsRoute: TermsRoute, ApiChangesRoute: ApiChangesRoute, + ApiHealthRoute: ApiHealthRoute, ApiAuthSplatRoute: ApiAuthSplatRoute, ApiWebhooksGithubRoute: ApiWebhooksGithubRoute, ApiGithubAppAuthorizeRoute: ApiGithubAppAuthorizeRoute, diff --git a/apps/dashboard/src/routes/api/health.ts b/apps/dashboard/src/routes/api/health.ts new file mode 100644 index 00000000..a564f43a --- /dev/null +++ b/apps/dashboard/src/routes/api/health.ts @@ -0,0 +1,29 @@ +import { createFileRoute } from "@tanstack/react-router"; +import { PRIVATE_ROUTE_HEADERS } from "#/lib/seo"; + +/** + * GET /api/health: unauthenticated liveness for the deploy gate and uptime + * checks. 200 when D1 and KV answer, 503 with per-check details otherwise. + */ +export const Route = createFileRoute("/api/health")({ + headers: () => PRIVATE_ROUTE_HEADERS, + server: { + handlers: { + GET: async () => { + const [{ env }, health] = await Promise.all([ + import("cloudflare:workers"), + import("#/lib/health.server"), + ]); + const { CF_VERSION_METADATA } = env as Cloudflare.Env & { + CF_VERSION_METADATA?: WorkerVersionMetadata; + }; + const report = await health.checkHealth({ + db: env.DB, + kv: env.GITHUB_CACHE_KV, + versionMetadata: CF_VERSION_METADATA, + }); + return health.healthResponse(report); + }, + }, + }, +}); diff --git a/docs/data-fetching.md b/docs/data-fetching.md index 4b7d65c0..180d2495 100644 --- a/docs/data-fetching.md +++ b/docs/data-fetching.md @@ -244,14 +244,23 @@ Database size comes from D1's `meta.size_after`, the number `github_change` exceeds 50k rows (a stuck sweeper), it also logs `{"level":"warn","alert":"d1_size_warning" | "d1_change_table_growth", …}`. -To alert: - -1. In the Cloudflare dashboard, open the Worker → **Observability**, filter - on `alert = d1_size_warning OR alert = d1_change_table_growth`, and save - the query as an alert. Notify on any match in 15 minutes. -2. Or, with Logpush, push Workers trace events and alert on the same field. -3. Also add a **Notifications → D1** usage alert for the database as a second - signal that doesn't depend on the Worker running. +Alerts (what exists, and what is still manual): + +1. **GitHub issues from a watchdog.** `.github/workflows/production-alerts.yml` + runs every 15 minutes and opens one issue per firing check, labelled + `production-alert` and de-duplicated by title. It closes the issue when the + check recovers. Checks: `/api/health` failing, D1 above 8 GB (from the D1 + API, so it works when the Worker is down), the cron not completing a clean + run in 12 minutes (from `/api/health` → `maintenance`), and Worker error + rate above 5% over 15 minutes (Workers analytics). A check it cannot + evaluate opens a "(check unavailable)" issue rather than staying silent. +2. Cloudflare Notifications has no type for Worker error rate, cron failures or + D1 size, which is why (1) exists. Optionally, in the Cloudflare dashboard, + open the Worker → **Observability** → Issues and add an automation, which + groups uncaught exceptions and 5xx responses. + +Runbooks: [d1-full.md](runbooks/d1-full.md), +[deploy-rollback.md](runbooks/deploy-rollback.md). `sweep.complete: false` on consecutive runs means the backlog is outgrowing 10 × 20k rows per 5 minutes; raise `GITHUB_CHANGE_SWEEP_MAX_BATCHES`. diff --git a/docs/runbooks/d1-full.md b/docs/runbooks/d1-full.md new file mode 100644 index 00000000..faf1b229 --- /dev/null +++ b/docs/runbooks/d1-full.md @@ -0,0 +1,146 @@ +# Runbook: D1 database full or filling up + +Production D1 is `quickhub-db`, bound as `DB` in the `diffkit` Worker. +Cloudflare caps one D1 database at **10 GB**. On 2026-11-08 it hit the cap +after 11 weeks of unpruned cache tables, and nothing alerted (see +[platform-plan.md → Incidents](../platform-plan.md#incidents)). + +## Symptoms + +At the cap, **inserts fail and in-place updates keep working**. That pattern +is the tell: + +- New GitHub sign-ins fail: the OAuth callback cannot insert `verification`, + `account` or `session` rows. People who are already signed in stay signed in, + because session refreshes are updates. +- `POST /api/webhooks/github` returns 500. `wrangler tail` shows + `Failed query: insert into …`. +- Any code that awaits a D1 write on the request path turns the failure into a + page error (that is how #189 took the dashboard down). + +## Alerts that should have fired + +| Signal | Where | Fires at | +| --- | --- | --- | +| GitHub issue **"Production alert: D1 database above 8 GB"** | [`production-alerts.yml`](../../.github/workflows/production-alerts.yml), every 15 min, reads the D1 API (`file_size`), so it works even when the Worker is down | 8 GB | +| `{"alert":"d1_size_warning"}` log line | Worker cron (`scheduled-maintenance.server.ts`), every 5 min | 80% (8 GB) | +| `{"alert":"d1_change_table_growth"}` log line | same | `github_change` > 50k rows (sweeper stuck) | +| GitHub issue **"Production alert: scheduled maintenance cron is not running cleanly"** | watchdog, via `/api/health` → `maintenance` | no clean cron run in 12 min | + +Open alert issues: . + +## 1. Measure + +From `apps/dashboard`, logged in with `pnpm exec wrangler login`: + +```sh +pnpm exec wrangler d1 info quickhub-db # database_size, num_tables +curl -s https://diff-kit.com/api/health | jq .checks.d1 # sizeBytes as seen by the Worker + +# Row counts per table. List tables first, then count the suspects. +pnpm exec wrangler d1 execute quickhub-db --remote --command \ + "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name" +pnpm exec wrangler d1 execute quickhub-db --remote --command \ + "SELECT (SELECT COUNT(*) FROM github_change) AS github_change, + (SELECT COUNT(*) FROM session) AS session, + (SELECT COUNT(*) FROM verification) AS verification" +``` + +A `COUNT(*)` over tens of millions of rows is slow and counts toward D1's +per-query limits, so run counts one table at a time. + +Expected steady state: `github_change` stays in the low thousands (15-minute +retention). + +## 2. Stop the growth + +Find the writer before you delete anything, or the purge loses the race. + +- A table with no pruning: ship a fix that stops the writes or adds a TTL and + sweeper. Every store needs one (docs/data-fetching.md). +- `github_change` growing: the cron sweeper is not running or not keeping up. + Check the cron alert issue. In Workers → `diffkit` → Logs, search + `"task":"scheduled-maintenance"`. `sweep.complete: false` on consecutive runs + means the backlog is outgrowing 10 × 20k rows per 5 minutes: raise + `GITHUB_CHANGE_SWEEP_MAX_BATCHES` in `github-change.server.ts`. + +## 3. Purge a large table + +Delete in **20,000-row batches with a 4-second pause**. These are the numbers +that worked on 2026-11-08: + +- 50k-row batches tripped D1 error **7429** ("too many resources in a 10 + second window") and slowed live queries. +- 500k-row batches hit the per-query time limit. + +```sh +TABLE=github_webhook_event # the table to purge +WHERE="1 = 1" # or e.g. "received_at < 1790000000000" +BATCH=20000 + +while true; do + out=$(pnpm exec wrangler d1 execute quickhub-db --remote --json --command \ + "DELETE FROM $TABLE WHERE rowid IN (SELECT rowid FROM $TABLE WHERE $WHERE LIMIT $BATCH)" 2>&1) + if echo "$out" | grep -q 7429; then + echo "$(date -u +%T) 7429: backing off 30s"; sleep 30; continue + fi + changes=$(echo "$out" | jq -r '.[0].meta.changes' 2>/dev/null) + if [ -z "$changes" ] || [ "$changes" = "null" ]; then + echo "$out"; break # an error that is not 7429: stop and read it + fi + echo "$(date -u +%T) deleted $changes" + [ "$changes" -lt "$BATCH" ] && break + sleep 4 +done +``` + +On a 7429, back off and retry the same batch. If 7429s keep coming at 20k, +halve `BATCH`, because live traffic is using the headroom. Tens of millions of +rows take hours, so run the loop in `tmux` or `nohup`. + +Check progress with `wrangler d1 info quickhub-db`. The reported size goes down +as rows are deleted (on 2026-11-08: 10 GB → 8.34 GB → 7.99 GB during the +purge). + +### Dropping the table afterwards + +Drop a table only once it is empty, or nearly so. The drop is a migration, and +deploys apply migrations before shipping the Worker (5-minute timeout, +[deploy-rollback.md](./deploy-rollback.md#migration-timed-out)). Dropping a +multi-GB table in one statement blocks the deploy pipeline. A migration PR +with `DROP TABLE` needs a `migration-destructive: approved` line in its body to +pass the **D1 migrations** check. + +The incident's emergency fix (owner, 2026-11-08) was to drop +`github_response_cache` by hand, then recreate it empty so the deployed bundle +kept working. Only do this for a table that holds nothing you need. Recreate it +in the same session if the serving code still queries it. + +## 4. If data was lost or damaged: Time Travel + +D1 Time Travel restores the whole database to a minute in the last 30 days +(Workers Paid; 7 days on Free). A restore **discards every write after that +point**, including sign-ins and sessions, so it is a last resort, not a way to +free space. + +```sh +# A bookmark for a point in time (read-only) +pnpm exec wrangler d1 time-travel info quickhub-db --timestamp 2026-11-08T05:00:00Z + +# Each production deploy also prints one taken before migrations: see the +# deploy job summary, "D1 bookmark (pre-migration)". + +# Restore (destructive). Wrangler prints the bookmark of the state it +# replaced; save it, because restoring to it undoes the restore. +pnpm exec wrangler d1 time-travel restore quickhub-db --bookmark +``` + +After a restore, check that the serving Worker version expects the restored +schema (`wrangler d1 migrations list quickhub-db --remote`). If it doesn't, +roll the Worker back ([deploy-rollback.md](./deploy-rollback.md)). + +## 5. Afterwards + +- Close the alert issue, or let the watchdog close it within 15 minutes of the + size dropping below 8 GB. +- Add the cause to [platform-plan.md → Incidents](../platform-plan.md#incidents). diff --git a/docs/runbooks/deploy-rollback.md b/docs/runbooks/deploy-rollback.md new file mode 100644 index 00000000..c35ad846 --- /dev/null +++ b/docs/runbooks/deploy-rollback.md @@ -0,0 +1,118 @@ +# Runbook: production deploy and rollback + +Production is the `diffkit` Worker on , backed by the +`quickhub-db` D1 database. Every push to `main` that touches the dashboard runs +[`.github/workflows/dashboard-deploy-production.yml`](../../.github/workflows/dashboard-deploy-production.yml). +Deploys are serialized (`concurrency: dashboard-production`); a second merge +waits for the first deploy to finish. + +## What a deploy does + +The workflow builds the Worker, then runs +[`scripts/deploy-dashboard.mjs`](../../scripts/deploy-dashboard.mjs), which moves +through one phase at a time: + +| Phase | What happened | If the job stops here | +| --- | --- | --- | +| `bookmarked` | Read the serving version id (the rollback target) and a D1 Time Travel bookmark. | Nothing changed. Re-run the job. | +| `migrated` | Applied pending D1 migrations, with a 5-minute timeout. | Migrations may be applied, old code still serves. See "Migration timed out". | +| `deployed` | `wrangler deploy` uploaded the new version, tagged with the short commit SHA. | New code serves, not yet verified. | +| `verified` | Within 2 minutes, `/login` (redirects followed) answered 200 and `/api/health` answered 200 **reporting the new version id**. | Done. | +| `rolled_back` | The gate failed, and `wrangler rollback` restored the previous version. The job fails. | Previous code serves. Investigate before you merge a fix. | +| `rollback_failed` | The gate failed and the rollback failed too. The job fails with a 🚨 headline. | Production may be broken. Roll back by hand (below). | +| `failed after ` | A command threw. The phase it names is the last one that completed. | See that phase's row. | + +The job summary (Actions → the run → Summary) shows the phase, the commit, +the previous and new version ids, the D1 bookmark, and the health-gate result. +The bookmark is also printed in the log as +`D1 Time Travel bookmark before migrations: …`. + +## Rolling back by hand + +You need a Cloudflare login with Workers access (`pnpm exec wrangler login`). +Run these from `apps/dashboard`. + +```sh +# 1. What is serving now, and what came before it? +pnpm exec wrangler deployments status --name diffkit +pnpm exec wrangler deployments list --name diffkit # newest last; message = " " + +# 2. Roll back to a known-good version id +pnpm exec wrangler rollback --name diffkit --message "why" --yes + +# 3. Confirm +curl -s https://diff-kit.com/api/health | jq '{status, version, checks}' +curl -sL -o /dev/null -w '%{http_code}\n' https://diff-kit.com/login # expect 200 +``` + +`/api/health` reports `version.id`. It is the version id from step 1 only for +versions deployed with the `CF_VERSION_METADATA` binding, which the deploy +workflow adds. Older versions report `{"status":"unknown"}`. + +A rollback restores code, bindings and vars of that version. It does **not** +undo D1 migrations, KV or R2 data. Write migrations that the previous version +can run against: add columns and tables first, remove them in a later deploy. + +### Then stop the next deploy from re-shipping the bad commit + +A rollback lasts until the next push to `main`. Revert the bad PR +(`gh pr revert ` or a revert commit) before you merge anything else. + +## Deploying while D1 or KV is degraded + +The gate requires `/api/health` to return 200, and it returns 503 when D1 or KV +fails. If the fix you need to ship is for that outage, the gate will roll the fix +back. Run the workflow by hand with the gate off: + +```sh +gh workflow run dashboard-deploy-production.yml -R stylessh/diffkit -f health_gate=skip +``` + +The run ends in phase `unverified`. Check the site by hand afterwards. + +## Migration timed out + +The deploy fails with `D1 migrations timed out after 300s`. The Worker was not +deployed. The migration statement can still finish on D1's side after the +client gives up, so check what was applied: + +```sh +pnpm exec wrangler d1 migrations list quickhub-db --remote +``` + +- **Listed as applied** (not under "Migrations to be applied"): re-run the + deploy job. It skips the migration and deploys the code. +- **Still pending**: the statement is too slow for one request. Usually it is a + `DROP TABLE` or a table rewrite on a big table. Shrink the table first with + throttled deletes ([d1-full.md](./d1-full.md#purge-a-large-table)), then + re-run. + +PRs that add destructive migration statements (`DROP`, `ALTER … DROP COLUMN`, +`TRUNCATE`, or `DELETE` without `WHERE`) fail the **D1 migrations** check +unless the PR body has a line `migration-destructive: approved`. That check +also fails when a PR edits an already-applied migration (override: +`migration-edit: approved`), or when `src/db/schema.ts` and the migrations +disagree. + +## Restoring D1 to the pre-deploy bookmark + +Only do this when a migration damaged data. A restore rewinds **the whole +database**: every sign-in, session and change-feed row written after the +bookmark is lost. + +```sh +# The bookmark is in the deploy job summary +pnpm exec wrangler d1 time-travel restore quickhub-db --bookmark +``` + +Wrangler prints the bookmark of the state it replaced. Save it, because it lets +you undo the restore with the same command. Roll the Worker back to the +version that matches the restored schema first, so code and schema agree. + +To pick a point in time instead of a bookmark: + +```sh +pnpm exec wrangler d1 time-travel info quickhub-db --timestamp 2026-11-08T05:00:00Z +``` + +Time Travel keeps 30 days on the Workers Paid plan (7 days on Free). diff --git a/scripts/check-d1-migrations.mjs b/scripts/check-d1-migrations.mjs new file mode 100644 index 00000000..66340943 --- /dev/null +++ b/scripts/check-d1-migrations.mjs @@ -0,0 +1,312 @@ +import { spawnSync } from "node:child_process"; +import { + mkdtempSync, + readdirSync, + readFileSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { DatabaseSync } from "node:sqlite"; +import { parseArgs } from "node:util"; + +const REPO_ROOT = resolve(import.meta.dirname, ".."); +const DASHBOARD_DIR = join(REPO_ROOT, "apps/dashboard"); +const MIGRATIONS_DIR = join(DASHBOARD_DIR, "drizzle"); +const MIGRATIONS_PATH = "apps/dashboard/drizzle/"; + +const DESTRUCTIVE_MARKER = /migration-destructive:\s*approved/i; +const EDIT_MARKER = /migration-edit:\s*approved/i; + +const DESTRUCTIVE_PATTERNS = [ + { label: "DROP", pattern: /\bDROP\s+(TABLE|INDEX|VIEW|TRIGGER)\b/i }, + { label: "ALTER ... DROP COLUMN", pattern: /\bALTER\s+TABLE\b[^;]*\bDROP\s+COLUMN\b/i }, + { label: "ALTER ... RENAME", pattern: /\bALTER\s+TABLE\b[^;]*\bRENAME\b/i }, + { label: "TRUNCATE", pattern: /\bTRUNCATE\b/i }, + { label: "UPDATE without WHERE", pattern: /^\s*UPDATE\b(?![\s\S]*\bWHERE\b)/i }, + { label: "DELETE without WHERE", pattern: /\bDELETE\s+FROM\s+[`"\w.]+\s*(;|$)/i }, +]; + +// Tables still created by 0001–0004 but removed from the Drizzle schema in +// #193. They exist in production until the drop migration (#198) ships; the +// check reports when an entry here is no longer needed. +const KNOWN_LEGACY_TABLES = new Set([ + "github_response_cache", + "github_revalidation_signal", + "github_cache_namespace", + "github_webhook_event", +]); + +const OUTCOME_ICON = { pass: "✅", fail: "❌", skip: "⏭️" }; + +const PLATFORM_TABLE = /^(sqlite_|_cf_|d1_migrations$)/; + +const { values: options } = parseArgs({ options: { base: { type: "string" } } }); +const prBody = process.env.PR_BODY ?? ""; +const scratch = mkdtempSync(join(tmpdir(), "d1-migration-check-")); + +const applied = guarded("Apply to fresh local D1", checkMigrationsApplyToFreshD1); +const results = [ + guarded("Changed migrations", () => checkChangedMigrations(options.base)), + applied, + guarded("drizzle-kit check", checkDrizzleSnapshots), + applied.outcome === "pass" + ? guarded("Drizzle schema matches migrations", checkSchemaDrift) + : skip("Drizzle schema matches migrations", "migrations did not apply"), +]; + +writeSummary(results); +process.exit(results.some((result) => result.outcome === "fail") ? 1 : 0); + +function guarded(name, check) { + try { + return check(); + } catch (error) { + return fail(name, [error instanceof Error ? error.message : String(error)]); + } +} + +function run(command, args, cwd = DASHBOARD_DIR) { + const result = spawnSync(command, args, { cwd, encoding: "utf8" }); + return { + ok: result.status === 0, + output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim(), + }; +} + +function pass(name, details = []) { + return { name, outcome: "pass", details }; +} + +function fail(name, details) { + return { name, outcome: "fail", details }; +} + +function skip(name, reason) { + return { name, outcome: "skip", details: [`Skipped: ${reason}.`] }; +} + +function stripSqlComments(sql) { + return sql.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/--[^\n]*/g, " "); +} + +function changedMigrationFiles(base) { + const diff = run("git", ["diff", "--name-status", `${base}...HEAD`, "--", MIGRATIONS_PATH], REPO_ROOT); + if (!diff.ok) throw new Error(`git diff against ${base} failed:\n${diff.output}`); + return diff.output + .split("\n") + .filter(Boolean) + .map((line) => { + const [status, ...paths] = line.split("\t"); + return { status: status[0], path: paths.at(-1) }; + }) + .filter(({ path }) => path.endsWith(".sql")); +} + +function checkChangedMigrations(base) { + const name = "Changed migrations"; + if (!base) return pass(name, ["No --base given; scanning skipped."]); + + const changes = changedMigrationFiles(base); + if (changes.length === 0) return pass(name, ["No migration files changed."]); + + const edits = EDIT_MARKER.test(prBody) + ? [] + : changes + .filter(({ status }) => status !== "A") + .map( + ({ status, path }) => + `${path} (${status}): migrations already applied in production are never re-run. Add a new migration instead, or put \`migration-edit: approved\` in the PR body.`, + ); + + const destructive = changes + .filter(({ status }) => status !== "D") + .flatMap(({ path }) => destructiveStatements(path)); + const destructiveApproved = DESTRUCTIVE_MARKER.test(prBody); + const unapproved = destructiveApproved || destructive.length === 0 + ? [] + : [ + ...destructive, + "Destructive statements need `migration-destructive: approved` in the PR body. Large tables: purge in throttled batches first (docs/runbooks/d1-full.md).", + ]; + + const problems = [...edits, ...unapproved]; + if (problems.length > 0) return fail(name, problems); + return pass(name, [ + `${changes.length} file(s) changed.`, + ...(destructiveApproved ? destructive.map((line) => `approved: ${line}`) : []), + ]); +} + +function destructiveStatements(path) { + const sql = stripSqlComments(readFileSync(join(REPO_ROOT, path), "utf8")); + return sql.split(/;|--> statement-breakpoint/).flatMap((statement) => + DESTRUCTIVE_PATTERNS.filter(({ pattern }) => pattern.test(statement)).map( + ({ label }) => `${path}: ${label}: ${statement.trim().replace(/\s+/g, " ").slice(0, 120)}`, + ), + ); +} + +function checkMigrationsApplyToFreshD1() { + const name = "Apply to fresh local D1"; + const persistDir = join(scratch, "state"); + const configPath = join(scratch, "wrangler.json"); + writeFileSync( + configPath, + JSON.stringify({ + name: "migration-check", + compatibility_date: "2025-09-02", + d1_databases: [ + { + binding: "DB", + database_name: "migration-check", + database_id: "00000000-0000-0000-0000-000000000000", + migrations_dir: MIGRATIONS_DIR, + }, + ], + }), + ); + + const startedAt = Date.now(); + const applied = run("pnpm", [ + "exec", + "wrangler", + "d1", + "migrations", + "apply", + "DB", + "--local", + "-c", + configPath, + "--persist-to", + persistDir, + ]); + const seconds = ((Date.now() - startedAt) / 1000).toFixed(1); + if (!applied.ok) return fail(name, [`wrangler failed after ${seconds}s:`, applied.output]); + + const migrationCount = readdirSync(MIGRATIONS_DIR).filter((file) => file.endsWith(".sql")).length; + return pass(name, [`${migrationCount} migrations applied in ${seconds}s.`]); +} + +function checkDrizzleSnapshots() { + const name = "drizzle-kit check"; + const checked = run("pnpm", ["exec", "drizzle-kit", "check"]); + return checked.ok ? pass(name) : fail(name, [checked.output]); +} + +function findLocalD1File() { + const dir = join(scratch, "state", "v3", "d1", "miniflare-D1DatabaseObject"); + const file = readdirSync(dir).find((entry) => entry.endsWith(".sqlite")); + if (!file) throw new Error(`No local D1 database found in ${dir}`); + return join(dir, file); +} + +function generatedSchemaDatabase() { + const outDir = join(scratch, "generated"); + const generated = run("pnpm", [ + "exec", + "drizzle-kit", + "generate", + "--dialect", + "sqlite", + "--schema", + "./src/db/schema.ts", + "--out", + outDir, + "--name", + "schema", + ]); + if (!generated.ok) throw new Error(`drizzle-kit generate failed:\n${generated.output}`); + + const db = new DatabaseSync(":memory:"); + const sqlFile = readdirSync(outDir).find((file) => file.endsWith(".sql")); + for (const statement of readFileSync(join(outDir, sqlFile), "utf8").split("--> statement-breakpoint")) { + if (statement.trim()) db.exec(statement); + } + return db; +} + +// SQLite stores TRUE/FALSE defaults as 1/0; drizzle's boolean mode emits the keywords. +function normalizeDefault(value) { + const boolean = { true: "1", false: "0" }[String(value).toLowerCase()]; + return boolean ?? value; +} + +function describeSchema(db) { + const tables = db + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name") + .all() + .map(({ name }) => name) + .filter((name) => !PLATFORM_TABLE.test(name)); + + const describe = (table) => { + const quoted = `"${table.replaceAll('"', '""')}"`; + const columns = db + .prepare(`PRAGMA table_xinfo(${quoted})`) + .all() + .map((c) => `${c.name} ${String(c.type).toLowerCase()} notnull=${c.notnull} default=${normalizeDefault(c.dflt_value)} pk=${c.pk}`); + const indexes = db + .prepare(`PRAGMA index_list(${quoted})`) + .all() + .filter((index) => index.origin === "c") + .map((index) => { + const cols = db + .prepare(`PRAGMA index_xinfo("${index.name}")`) + .all() + .filter((c) => c.key === 1) + .map((c) => `${c.name ?? ""}${c.desc ? " desc" : ""}`) + .join(","); + return `index ${index.name} unique=${index.unique} partial=${index.partial} (${cols})`; + }); + const foreignKeys = db + .prepare(`PRAGMA foreign_key_list(${quoted})`) + .all() + .map((fk) => `fk ${fk.from} -> ${fk.table}.${fk.to} update=${fk.on_update} delete=${fk.on_delete}`); + return [...columns, ...indexes, ...foreignKeys].sort(); + }; + + return new Map(tables.map((table) => [table, describe(table)])); +} + +function checkSchemaDrift() { + const name = "Drizzle schema matches migrations"; + const fromSchema = describeSchema(generatedSchemaDatabase()); + const fromMigrations = describeSchema(new DatabaseSync(findLocalD1File(), { readOnly: true })); + + const drift = []; + const notes = []; + + for (const [table, definition] of fromMigrations) { + if (fromSchema.has(table)) continue; + if (KNOWN_LEGACY_TABLES.has(table)) notes.push(`legacy table \`${table}\` still created by migrations (dropped by #198).`); + else drift.push(`\`${table}\` exists after migrations but not in src/db/schema.ts.`); + } + for (const legacy of KNOWN_LEGACY_TABLES) { + if (!fromMigrations.has(legacy)) notes.push(`\`${legacy}\` is gone; remove it from KNOWN_LEGACY_TABLES.`); + } + for (const [table, expected] of fromSchema) { + const actual = fromMigrations.get(table); + if (!actual) { + drift.push(`\`${table}\` is in src/db/schema.ts but no migration creates it. Run \`pnpm exec drizzle-kit generate\` or add a migration.`); + continue; + } + const missing = expected.filter((line) => !actual.includes(line)); + const extra = actual.filter((line) => !expected.includes(line)); + for (const line of missing) drift.push(`\`${table}\`: schema has \`${line}\`, migrations do not.`); + for (const line of extra) drift.push(`\`${table}\`: migrations have \`${line}\`, schema does not.`); + } + + return drift.length > 0 ? fail(name, [...drift, ...notes]) : pass(name, notes); +} + +function writeSummary(checks) { + const lines = ["## D1 migration check", ""]; + for (const check of checks) { + lines.push(`### ${OUTCOME_ICON[check.outcome]} ${check.name}`); + for (const detail of check.details) lines.push(detail.includes("\n") ? `\n\`\`\`\n${detail}\n\`\`\`` : `- ${detail}`); + lines.push(""); + } + const text = lines.join("\n"); + console.log(text); + if (process.env.GITHUB_STEP_SUMMARY) writeFileSync(process.env.GITHUB_STEP_SUMMARY, `${text}\n`, { flag: "a" }); +} diff --git a/scripts/production-alerts.mjs b/scripts/production-alerts.mjs new file mode 100644 index 00000000..3f80188d --- /dev/null +++ b/scripts/production-alerts.mjs @@ -0,0 +1,309 @@ +import { writeFileSync } from "node:fs"; + +const env = requireEnv([ + "HEALTH_URL", + "CLOUDFLARE_API_TOKEN", + "CLOUDFLARE_ACCOUNT_ID", + "D1_DATABASE_ID", + "WORKER_NAME", + "GITHUB_TOKEN", + "GITHUB_REPOSITORY", +]); + +const ALERT_LABEL = "production-alert"; +const D1_SIZE_ALERT_BYTES = 8 * 1000 * 1000 * 1000; +const D1_LIMIT_BYTES = 10 * 1000 * 1000 * 1000; +const ERROR_RATE_WINDOW_MS = 15 * 60 * 1000; +// Workers analytics lag a few minutes behind; a window ending now undercounts. +const ERROR_RATE_LAG_MS = 5 * 60 * 1000; +const ERROR_RATE_MIN_REQUESTS = 50; +const ERROR_RATE_THRESHOLD = 0.05; +const HEALTH_ATTEMPTS = 3; +const HEALTH_RETRY_MS = 20_000; + +const runbook = (name) => + `https://github.com/${env.GITHUB_REPOSITORY}/blob/main/docs/runbooks/${name}`; + +const health = await fetchHealth(); +const evaluations = [ + evaluateWorkerHealth(health), + await guarded("Production alert: D1 database above 8 GB", evaluateD1Size), + evaluateMaintenance(health), + await guarded("Production alert: Worker error rate above 5%", evaluateErrorRate), +]; + +const actions = []; +for (const evaluation of evaluations) { + try { + actions.push(await reconcile(evaluation)); + } catch (error) { + actions.push(`reconcile failed: ${messageOf(error)}`); + } +} +writeSummary(evaluations, actions); +process.exit(actions.some((action) => action.startsWith("reconcile failed")) ? 1 : 0); + +function requireEnv(names) { + const missing = names.filter((name) => !process.env[name]); + if (missing.length > 0) { + console.error(`Missing environment: ${missing.join(", ")}`); + process.exit(1); + } + return Object.fromEntries(names.map((name) => [name, process.env[name]])); +} + +function messageOf(error) { + return error instanceof Error ? error.message : String(error); +} + +async function guarded(title, evaluate) { + try { + return await evaluate(title); + } catch (error) { + return unknown(title, messageOf(error)); + } +} + +function firing(title, body) { + return { state: "firing", title, body }; +} + +function clear(title, detail) { + return { state: "clear", title, detail }; +} + +function unknown(title, reason) { + return { state: "unknown", title, reason }; +} + +function formatGB(bytes) { + return `${(bytes / 1e9).toFixed(2)} GB`; +} + +async function fetchHealth() { + let last = { state: "unreachable", reason: "not attempted" }; + for (let attempt = 1; attempt <= HEALTH_ATTEMPTS; attempt += 1) { + if (attempt > 1) await new Promise((resolve) => setTimeout(resolve, HEALTH_RETRY_MS)); + try { + const response = await fetch(env.HEALTH_URL, { signal: AbortSignal.timeout(10_000) }); + const text = await response.text(); + const report = parseJson(text); + if (response.status === 200 && report?.status === "ok") return { state: "healthy", report }; + last = report + ? { state: "degraded", httpStatus: response.status, report } + : { state: "unreachable", reason: `HTTP ${response.status}, non-JSON body: ${text.slice(0, 200)}` }; + } catch (error) { + last = { state: "unreachable", reason: error instanceof Error ? error.message : String(error) }; + } + } + return last; +} + +function parseJson(text) { + try { + return JSON.parse(text); + } catch { + return null; + } +} + +function evaluateWorkerHealth(result) { + const title = "Production alert: /api/health is failing"; + if (result.state === "healthy") return clear(title, "200 ok"); + const evidence = + result.state === "degraded" + ? `HTTP ${result.httpStatus}:\n\n\`\`\`json\n${JSON.stringify(result.report, null, 2)}\n\`\`\`` + : `Unreachable: ${result.reason}`; + return firing( + title, + `\`GET ${env.HEALTH_URL}\` failed ${HEALTH_ATTEMPTS} times in a row.\n\n${evidence}\n\nRunbooks: [deploy rollback](${runbook("deploy-rollback.md")}), [D1 full](${runbook("d1-full.md")}).`, + ); +} + +async function evaluateD1Size(title) { + const response = await fetch( + `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/d1/database/${env.D1_DATABASE_ID}`, + { headers: { Authorization: `Bearer ${env.CLOUDFLARE_API_TOKEN}` }, signal: AbortSignal.timeout(15_000) }, + ); + const payload = parseJson(await response.text()); + const sizeBytes = payload?.result?.file_size; + if (!response.ok || typeof sizeBytes !== "number") { + return unknown(title, `D1 API answered HTTP ${response.status}: ${JSON.stringify(payload?.errors ?? payload)}`); + } + const share = `${formatGB(sizeBytes)} of ${formatGB(D1_LIMIT_BYTES)} (${((sizeBytes / D1_LIMIT_BYTES) * 100).toFixed(1)}%)`; + if (sizeBytes < D1_SIZE_ALERT_BYTES) return clear(title, share); + return firing( + title, + `D1 database \`${payload.result.name}\` is at **${share}**. At 10 GB inserts fail and sign-in breaks (2026-11-08 incident).\n\nFollow the [D1 full runbook](${runbook("d1-full.md")}).`, + ); +} + +function evaluateMaintenance(result) { + const title = "Production alert: scheduled maintenance cron is not running cleanly"; + if (result.state === "unreachable") return unknown(title, "/api/health unreachable"); + const maintenance = result.report.maintenance; + const explain = (meaning) => + firing( + title, + `The 5-minute cron (change-feed sweeper and D1 size check) ${meaning}\n\n\`\`\`json\n${JSON.stringify(maintenance, null, 2)}\n\`\`\`\n\nCheck the Worker's logs for \`"task":"scheduled-maintenance"\`. Without the sweeper \`github_change\` grows unbounded ([D1 full runbook](${runbook("d1-full.md")})).`, + ); + + switch (maintenance?.status) { + case "recent": + return maintenance.result === "ok" + ? clear(title, `last run ${maintenance.lastRunAt}`) + : explain("ran, but the sweep or the size check threw."); + case "stale": + return explain(`has not completed a run since ${maintenance.lastRunAt}.`); + case "never_recorded": + return explain("has not completed a run in the last 24 hours."); + case "unreadable": + return unknown(title, "/api/health could not read the heartbeat from KV"); + default: + return unknown(title, `/api/health returned no maintenance status: ${JSON.stringify(maintenance)}`); + } +} + +async function evaluateErrorRate(title) { + const end = Date.now() - ERROR_RATE_LAG_MS; + const start = end - ERROR_RATE_WINDOW_MS; + const query = `query ($account: String!, $script: String!, $start: Time!, $end: Time!) { + viewer { accounts(filter: { accountTag: $account }) { + workersInvocationsAdaptive(limit: 100, filter: { scriptName: $script, datetime_geq: $start, datetime_lt: $end }) { + sum { requests errors } + dimensions { httpResponseStatus } + } + } } + }`; + const response = await fetch("https://api.cloudflare.com/client/v4/graphql", { + method: "POST", + headers: { Authorization: `Bearer ${env.CLOUDFLARE_API_TOKEN}`, "Content-Type": "application/json" }, + body: JSON.stringify({ + query, + variables: { + account: env.CLOUDFLARE_ACCOUNT_ID, + script: env.WORKER_NAME, + start: new Date(start).toISOString(), + end: new Date(end).toISOString(), + }, + }), + signal: AbortSignal.timeout(15_000), + }); + const payload = parseJson(await response.text()); + const rows = payload?.data?.viewer?.accounts?.[0]?.workersInvocationsAdaptive; + if (!response.ok || payload?.errors?.length || !Array.isArray(rows)) { + const errors = JSON.stringify(payload?.errors ?? payload); + const permissionHint = /auth|permission|forbidden/i.test(errors) + ? " The CLOUDFLARE_API_TOKEN secret needs Account Analytics: Read." + : ""; + return unknown(title, `Workers analytics query failed (HTTP ${response.status}): ${errors}.${permissionHint}`); + } + const requests = rows.reduce((total, row) => total + row.sum.requests, 0); + // `sum.errors` only counts invocations that threw; the Worker catches + // errors and answers 500, so count 5xx responses as failures too. + const errors = rows.reduce( + (total, row) => total + (row.dimensions.httpResponseStatus >= 500 ? row.sum.requests : row.sum.errors), + 0, + ); + const rate = requests === 0 ? 0 : errors / requests; + const window = `${new Date(start).toISOString()} – ${new Date(end).toISOString()}`; + const detail = `${errors} failed (5xx or exception) / ${requests} requests (${(rate * 100).toFixed(2)}%) in ${window}`; + if (requests < ERROR_RATE_MIN_REQUESTS || rate < ERROR_RATE_THRESHOLD) return clear(title, detail); + return firing( + title, + `Worker \`${env.WORKER_NAME}\`: **${detail}**.\n\nIf this started with a deploy, follow the [deploy rollback runbook](${runbook("deploy-rollback.md")}). Otherwise check Workers → ${env.WORKER_NAME} → Observability for the failing route.`, + ); +} + +async function github(path, init = {}) { + const response = await fetch(`https://api.github.com/repos/${env.GITHUB_REPOSITORY}${path}`, { + ...init, + signal: AbortSignal.timeout(15_000), + headers: { + Authorization: `Bearer ${env.GITHUB_TOKEN}`, + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + ...(init.body ? { "Content-Type": "application/json" } : {}), + }, + }); + if (!response.ok && response.status !== 422) { + throw new Error(`GitHub ${init.method ?? "GET"} ${path}: ${response.status} ${await response.text()}`); + } + return response.status === 204 ? null : response.json(); +} + +let openAlertIssues; +async function openIssuesFor(check) { + openAlertIssues ??= (await github(`/issues?state=open&labels=${ALERT_LABEL}&per_page=100`)).filter( + (issue) => !issue.pull_request, + ); + const titles = Object.values(issueTitles(check)); + return openAlertIssues.filter((issue) => titles.includes(issue.title)); +} + +function issueTitles(check) { + return { firing: check.title, unknown: `${check.title} (check unavailable)` }; +} + +async function closeIssue(issue, comment) { + await github(`/issues/${issue.number}/comments`, { method: "POST", body: JSON.stringify({ body: comment }) }); + await github(`/issues/${issue.number}`, { + method: "PATCH", + body: JSON.stringify({ state: "closed", state_reason: "completed" }), + }); +} + +async function reconcile(evaluation) { + const runLink = `[the alert watchdog](${process.env.GITHUB_SERVER_URL}/${env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID})`; + const open = await openIssuesFor(evaluation); + const titles = issueTitles(evaluation); + const firingIssue = open.find((issue) => issue.title === titles.firing); + // A check that cannot be evaluated says nothing about recovery: keep a + // firing issue open instead of churning it into an "unavailable" one. + if (evaluation.state === "unknown" && firingIssue) return `open #${firingIssue.number} (check unavailable this run)`; + const wantedTitle = evaluation.state === "clear" ? null : titles[evaluation.state]; + + const outdated = open.filter((issue) => issue.title !== wantedTitle); + for (const issue of outdated) { + const comment = + evaluation.state === "clear" + ? `Recovered: ${evaluation.detail}. Closed by ${runLink}.` + : `Superseded: this check is now \`${evaluation.state}\`. Closed by ${runLink}.`; + await closeIssue(issue, comment); + } + const closed = outdated.map((issue) => `closed #${issue.number}`); + + if (!wantedTitle) return closed.join(", ") || "none"; + const current = open.find((issue) => issue.title === wantedTitle); + if (current) return [...closed, `open #${current.number}`].join(", "); + + const body = + evaluation.state === "firing" + ? evaluation.body + : `The alert watchdog cannot evaluate this check, so it is not protecting production:\n\n${evaluation.reason}`; + await github("/labels", { + method: "POST", + body: JSON.stringify({ name: ALERT_LABEL, color: "b60205", description: "Opened by .github/workflows/production-alerts.yml" }), + }); + const issue = await github("/issues", { + method: "POST", + body: JSON.stringify({ + title: wantedTitle, + labels: [ALERT_LABEL], + body: `${body}\n\n---\nOpened by ${runLink}, which runs every 15 minutes and closes this issue when the check recovers.`, + }), + }); + return [...closed, `opened #${issue.number}`].join(", "); +} + +function writeSummary(results, outcomes) { + const icon = { firing: "🔴", clear: "🟢", unknown: "⚪" }; + const lines = ["## Production alerts", "", "| Check | State | Detail | Issue |", "| --- | --- | --- | --- |"]; + results.forEach((result, index) => { + const detail = result.state === "clear" ? result.detail : result.state === "unknown" ? result.reason : "see issue"; + lines.push(`| ${result.title.replace("Production alert: ", "")} | ${icon[result.state]} ${result.state} | ${detail.replaceAll("|", "\\|").replaceAll("\n", " ")} | ${outcomes[index]} |`); + }); + const text = lines.join("\n"); + console.log(text); + if (process.env.GITHUB_STEP_SUMMARY) writeFileSync(process.env.GITHUB_STEP_SUMMARY, `${text}\n`, { flag: "a" }); +}