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
54 changes: 54 additions & 0 deletions pkgs/github-ci/worker/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# github-ci Worker

The GitHub webhook receiver (developing-today/code#5693), re-homed
off the Supabase Edge Function of the same name — the last Edge
Function on muse-dev2. Ported behavior-for-behavior from the Edge
Function (ACTIVE v8) so the two receivers can run side by side
during the dual-run diff period.

## Shape

- `src/index.ts` — HMAC-SHA256 gate (Web Crypto, same semantics as
the Edge Function), routing, workflow_run ingest.
- `src/policy.ts` — the v4 ingest policy as pure functions:
completed runs only, conclusion != skipped, raw payload kept
only for failures, dedupe_key `github:<repo>:<run>:<attempt>:<action>`.
- `src/turso.ts` — minimal libSQL `/v2/pipeline` client with typed
args (no string interpolation).
- `src/sink.ts` — the #5690 agent-events sink (POST the queue
broker's `/events-append` when `EVENTS_BROKER_URL` is set; until
a public broker route exists — the broker is tailnet-only — the
Worker performs the sink's own INSERT into fleet-queue `events`),
plus the fleet-queue stores that replace PG `agent.repo_snapshots`
(`agent_repo_snapshots`) and `agent.watermarks` (`agent_watermarks`,
`dirty:<repo>` keys).

## Writes (Turso only — no Postgres anywhere)

- `workflow_run` → `ci_events` in **fleet-platform**,
`INSERT OR IGNORE` on `dedupe_key`, `id` unset (dedupe_key is
the identity; readers use `received_at`).
- Fleet-repo `push` → head_sha advance in `agent_repo_snapshots`
(fleet-queue) + a `push` sink event.
- Fleet-repo `pull_request` / `issues` → sink event +
`dirty:<repo>` watermark in `agent_watermarks` (fleet-queue).

## Secrets (names only; set with `wrangler secret put`)

`GITHUB_WEBHOOK_SECRET` (new value minted for this Worker, vaulted
in BWS as `cloudflare.github-ci-webhook-secret`; the org/App flip
rotates it again per #5693), `TURSO_PLATFORM_TOKEN`
(`turso.fleet-platform-rw-token`), `TURSO_QUEUE_TOKEN`
(`turso.fleet-queue-rw-token`).

## Run

```sh
npm install
npm test # vitest + @cloudflare/vitest-pool-workers
npm run deploy # wrangler deploy (fleet Cloudflare account)
```

Cutover state lives on #5693: deploy dark → replay smoke → one
repo-level dual-run webhook → (later, separately) org/App flip.
The Edge Function stays deployed as rollback until then.
20 changes: 20 additions & 0 deletions pkgs/github-ci/worker/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "github-ci-worker",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "GitHub webhook receiver (#5693): workflow_run -> Turso ci_events only; fleet push/PR/issues -> agent events sink + fleet-queue snapshots/watermarks.",
"scripts": {
"deploy": "wrangler deploy",
"dev": "wrangler dev",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@cloudflare/vitest-pool-workers": "0.9.14",
"@cloudflare/workers-types": "^4.20251011.0",
"typescript": "^5.6.0",
"vitest": "^3.2.0",
"wrangler": "4.44.0"
}
}
173 changes: 173 additions & 0 deletions pkgs/github-ci/worker/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
/**
* github-ci Worker (#5693) — the GitHub webhook receiver, re-homed
* off the Supabase Edge Function of the same name (ACTIVE v8).
*
* Gate: HMAC-SHA256 over the raw body, X-Hub-Signature-256 header,
* verified with Web Crypto against GITHUB_WEBHOOK_SECRET — the same
* semantics as the Edge Function (which ran verify_jwt=false; the
* HMAC is the gate).
*
* Behavior (parity with the Edge Function, minus Postgres):
* - workflow_run (any repo): INSERT OR IGNORE into Turso
* fleet-platform ci_events ONLY, id unset (dedupe_key is the
* identity), v4 ingest policy: completed runs only, conclusion
* != skipped, raw payload kept only for failures. Fatal on
* failure (500 -> GitHub retries), as the EF's PG insert was.
* - Fleet repos only:
* - push: advance agent_repo_snapshots.head_sha in fleet-queue
* (default-branch pushes only), stamp fetch_source='webhook',
* append a 'push' agent event via the #5690 sink.
* - pull_request / issues: append an agent event via the sink
* and set the agent_watermarks key 'dirty:<repo>' in
* fleet-queue.
* - ping: pong. Everything else: 202 ignored.
*/
import { Turso, iArg, tArg } from "./turso";
import { FLEET_REPOS, buildRunRow, skipReason } from "./policy";
import {
advanceSnapshot,
appendAgentEvent,
queueNow,
stampDirtyWatermark,
type SinkEnv,
} from "./sink";

export interface Env extends SinkEnv {
GITHUB_WEBHOOK_SECRET: string;
TURSO_PLATFORM_URL: string;
TURSO_PLATFORM_TOKEN: string;
}

async function hmacHex(secret: string, body: string): Promise<string> {
const key = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(secret),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"],
);
const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body));
return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
}

function timingSafeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let out = 0;
for (let i = 0; i < a.length; i++) out |= a.charCodeAt(i) ^ b.charCodeAt(i);
return out === 0;
}

function json(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "content-type": "application/json" },
});
}

export default {
async fetch(req: Request, env: Env): Promise<Response> {
if (req.method === "GET") return new Response("github-ci worker ok", { status: 200 });
if (req.method !== "POST") return new Response("method not allowed", { status: 405 });

const raw = await req.text();
const secret = env.GITHUB_WEBHOOK_SECRET ?? "";
if (secret) {
const given = (req.headers.get("x-hub-signature-256") ?? "").replace("sha256=", "");
const expected = await hmacHex(secret, raw);
if (!timingSafeEqual(given, expected)) {
return new Response("bad signature", { status: 401 });
}
}

let payload: Record<string, unknown>;
try {
payload = JSON.parse(raw);
} catch {
return new Response("bad json", { status: 400 });
}

const eventType = req.headers.get("x-github-event") ?? "workflow_run";
if (eventType === "ping") return new Response("pong", { status: 200 });

const repo = (payload.repository ?? {}) as Record<string, unknown>;
const repoName = String(repo.full_name ?? "unknown");
const isFleet = FLEET_REPOS.has(repoName);
const nowIso = new Date().toISOString();

try {
// ---------------------------------------------------------- push ---
if (eventType === "push" && isFleet) {
const after = String(payload.after ?? "");
const ref = String(payload.ref ?? "");
await advanceSnapshot(env, repoName, after, ref, nowIso);
await appendAgentEvent(env, "push", { repo: repoName, after, ref });
return json({ ok: true, repo: repoName, after });
}

// ---------------------------------------- pull_request / issues ---
if ((eventType === "pull_request" || eventType === "issues") && isFleet) {
const obj = (payload.pull_request ?? payload.issue ?? {}) as Record<string, unknown>;
const action = String(payload.action ?? "");
const detail = {
repo: repoName,
action,
number: Number(obj.number ?? 0) || null,
title: (obj.title as string) ?? null,
};
await appendAgentEvent(env, eventType, detail);
await stampDirtyWatermark(env, repoName, eventType, nowIso);
return json({ ok: true, repo: repoName, event: eventType });
}

if (eventType !== "workflow_run") {
return new Response(`ignored event ${eventType}`, { status: 202 });
}

// -------------------------------------------------- workflow_run ---
const { row, runId, action, conclusion } = buildRunRow(
payload,
repoName,
eventType,
queueNow(),
);
const skipped = skipReason(action, conclusion);
if (skipped) {
return json({ ok: true, skipped, repo: repoName, run_id: runId });
}
const platform = new Turso(env.TURSO_PLATFORM_URL, env.TURSO_PLATFORM_TOKEN);
await platform.execute(
`INSERT OR IGNORE INTO ci_events (received_at, source, event_type,
action, repo, workflow_name, workflow_id, run_id, run_attempt,
branch, sha, status, conclusion, actor, html_url, ci_started_at,
ci_updated_at, payload, dedupe_key)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
tArg(row.received_at),
tArg(row.source),
tArg(row.event_type),
tArg(row.action),
tArg(row.repo),
tArg(row.workflow_name),
iArg(row.workflow_id),
iArg(row.run_id),
iArg(row.run_attempt),
tArg(row.branch),
tArg(row.sha),
tArg(row.status),
tArg(row.conclusion),
tArg(row.actor),
tArg(row.html_url),
tArg(row.ci_started_at),
tArg(row.ci_updated_at),
tArg(row.payload),
tArg(row.dedupe_key),
],
);
return json({ ok: true, repo: repoName, run_id: runId, conclusion: row.conclusion });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.error(`github-ci worker failed (${eventType} ${repoName}): ${msg}`);
return new Response(`receiver failed: ${msg}`, { status: 500 });
}
},
};
81 changes: 81 additions & 0 deletions pkgs/github-ci/worker/src/policy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/**
* Pure ingest policy, ported 1:1 from the github-ci Edge Function
* (ACTIVE v8) so the two receivers are interchangeable during the
* #5693 dual-run diff period.
*/
export const FLEET_REPOS = new Set([
"developing-today/code",
"developing-today/opencode",
"developing-today/openchamber",
"dezren39/nix",
]);

export interface RunRow {
received_at: string;
source: string;
event_type: string;
action: string;
repo: string;
workflow_name: string | null;
workflow_id: number | null;
run_id: number | null;
run_attempt: number;
branch: string | null;
sha: string | null;
status: string | null;
conclusion: string | null;
actor: string | null;
html_url: string | null;
ci_started_at: string | null;
ci_updated_at: string | null;
payload: string;
dedupe_key: string;
}

/** v4 ingest policy: store only completed runs, never skipped. */
export function skipReason(action: string, conclusion: string | null): string | null {
if (action !== "completed") return "not_completed";
if (conclusion === "skipped") return "skipped_conclusion";
return null;
}

export function dedupeKey(repo: string, runId: number | null, attempt: number, action: string): string {
return `github:${repo}:${runId}:${attempt}:${action}`;
}

export function buildRunRow(
payload: Record<string, unknown>,
repoName: string,
eventType: string,
receivedAt: string,
): { row: RunRow; runId: number | null; action: string; conclusion: string | null } {
const run = (payload.workflow_run ?? {}) as Record<string, unknown>;
const runId = Number(run.id ?? 0) || null;
const attempt = Number(run.run_attempt ?? 1) || 1;
const action = String(payload.action ?? "");
const conclusion = (run.conclusion as string | null) ?? null;
const row: RunRow = {
received_at: receivedAt,
source: "github",
event_type: eventType,
action,
repo: repoName,
workflow_name: (run.name as string) ?? null,
workflow_id: Number(run.workflow_id ?? 0) || null,
run_id: runId,
run_attempt: attempt,
branch: (run.head_branch as string) ?? null,
sha: (run.head_sha as string) ?? null,
status: (run.status as string) ?? null,
conclusion,
actor: ((run.actor as Record<string, unknown> | undefined)?.login as string) ?? null,
html_url: (run.html_url as string) ?? null,
ci_started_at: (run.run_started_at as string) ?? (run.created_at as string) ?? null,
ci_updated_at: (run.updated_at as string) ?? null,
// v4 policy: raw payload kept only for failures (forensics);
// every other stored row carries an empty object.
payload: conclusion === "failure" ? JSON.stringify(payload) : "{}",
dedupe_key: dedupeKey(repoName, runId, attempt, action),
};
return { row, runId, action, conclusion };
}
Loading
Loading