Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .github/workflows/migration-check.yml
Original file line number Diff line number Diff line change
@@ -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
39 changes: 39 additions & 0 deletions .github/workflows/production-alerts.yml
Original file line number Diff line number Diff line change
@@ -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
2 changes: 1 addition & 1 deletion apps/dashboard/src/entry-worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);

Expand Down
17 changes: 13 additions & 4 deletions apps/dashboard/src/entry-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,22 @@ export default {

async scheduled(
controller: ScheduledController,
env: { DB: D1Database },
env: { DB: D1Database; GITHUB_CACHE_KV: KVNamespace },
ctx: ExecutionContext,
): Promise<void> {
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);
Expand Down
30 changes: 30 additions & 0 deletions apps/dashboard/src/lib/health.server.test.ts
Original file line number Diff line number Diff line change
@@ -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" },
});
});
});
160 changes: 160 additions & 0 deletions apps/dashboard/src/lib/health.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
export type DependencyCheck<T = Record<never, never>> =
| ({ 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<string, unknown>,
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<HealthReport> {
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<MaintenanceHeartbeat>(
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<T extends object>(
probe: () => Promise<T>,
): Promise<DependencyCheck<T>> {
const startedAt = Date.now();
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, 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);
}
}
Loading
Loading