import { onPush } from "@refs/ci/control"; import { agentSessionById, now, type User } from "./auth.ts"; import type { Actor } from "./contract/actor.ts"; import { indexPushedTips } from "./code-maps.ts"; import { indexPush } from "./decisions.ts"; import { MAX_ANCESTORS, ancestors } from "./diff.ts"; import { recordEvent, repoStream, type Recorder } from "./events.ts"; import { readRefs, type RefUpdate } from "./git.ts"; import { agentActor, toPerson } from "./identity.ts"; import * as pulls from "./pulls.ts"; import { raise } from "./outcomes.ts"; import { findRepoRecordById, type RepoRecord } from "./repos.ts"; export type Pusher = { readonly kind: "human"; readonly person: string; readonly via: "session" | "token" | "cli" } | { readonly kind: "agent"; readonly person: string; readonly session: string } | { readonly kind: "system" }; /** One accepted push, queued so that what it means (its event, the pull requests it merges, its decision records) happens even if the request's isolate goes away. */ export interface PushMessage { readonly repoId: string; readonly actor: Pusher; readonly updates: readonly RefUpdate[]; readonly at: number; } export function pusher(actor: Actor): Pusher { if (actor.kind === "human") return { kind: "human", person: actor.person.id, via: actor.via }; if (actor.kind === "agent") return { kind: "agent", person: actor.onBehalfOf.id, session: actor.sessionId }; return raise("sign_in_required", "Only signed-in actors can push."); } async function resolvePusher(db: D1Database, by: Pusher): Promise { if (by.kind === "system") return by; if (by.kind === "agent") { const session = await agentSessionById(db, by.session); return session && agentActor(session); } const user = await db.prepare("SELECT id, email, name FROM users WHERE id = ?").bind(by.person).first(); return user && { kind: "human", person: toPerson(user), via: by.via }; } function pushedKey(updates: readonly RefUpdate[]): string { return updates.map((update) => `${update.ref}:${update.from ?? ""}:${update.to ?? ""}`).join(" "); } /** * Records a push and carries out what it means. Every step is safe to repeat, so a message delivered twice, or retried * after failing halfway, ends in the same state as one delivered once. Returns false when the push can never be processed. */ export async function processPush(env: Env, ctx: Pick, message: PushMessage): Promise { const [record, actor] = await Promise.all([findRepoRecordById(env.DB, message.repoId), resolvePusher(env.DB, message.actor)]); if (!record || !actor) return false; await recordEvent(env.DB, actor, repoStream(record.id), "repo.pushed", { updates: message.updates }, message.at, null, pushedKey(message.updates)).run(); await detectMerges(env, ctx, actor, record, message.updates); const indexed = await indexPush(env, actor, record, message.updates); await env.DB.batch(recordTips(env.DB, record.id, message.updates, message.at)); await indexPushedTips(env, record, message.updates).catch((error: unknown) => console.error(`code map indexing failed for ${describe(message)}`, error)); await startCi(env, record, message).catch((error: unknown) => console.error(`CI start failed for ${describe(message)}`, error)); return true; } /** * Starts the CI runs the pushed branch tips ask for. A run ID is fixed by repo, commit, config and source, so a push * processed twice starts each run once. */ async function startCi(env: Env, record: RepoRecord, message: PushMessage): Promise { const actorId = message.actor.kind === "system" ? null : message.actor.person; const outcomes = await onPush(env, { repoId: record.id, namespaceId: record.namespace_id, repo: record.artifacts_name, pusher: message.actor.kind, actorId, updates: message.updates.map(({ ref, to }) => ({ ref, to })) }); for (const outcome of outcomes) if (outcome.kind === "started" || outcome.kind === "invalid") console.log(`CI ${outcome.kind} for ${outcome.ref}${outcome.pull ? ` (pull ${outcome.pull})` : ""} in repo ${record.id}`); } /** Marks each ref as processed through its new tip, unless a push accepted later already moved the mark. */ function recordTips(db: D1Database, repoId: string, updates: readonly RefUpdate[], at: number): D1PreparedStatement[] { return updates.map((update) => update.to === null ? db.prepare("DELETE FROM ref_tips WHERE repo_id = ? AND ref = ? AND seen_at <= ?").bind(repoId, update.ref, at) : db.prepare("INSERT INTO ref_tips (repo_id, ref, sha, seen_at) VALUES (?, ?, ?, ?) ON CONFLICT (repo_id, ref) DO UPDATE SET sha = excluded.sha, seen_at = excluded.seen_at WHERE excluded.seen_at >= ref_tips.seen_at").bind(repoId, update.ref, update.to, at), ); } const SWEEP_REPOS = 50; const SWEEP_REFS = 100; const SWEEP_DELAY_SECONDS = 60; /** * The cron sweep: git is authoritative, so any ref whose live tip differs from the tip its last processed push left in * `ref_tips` is enqueued as a push found by refs. Checks the repositories checked longest ago, a bounded number per run. */ export async function reconcilePushes(env: Env): Promise { const { results } = await env.DB.prepare("SELECT id, artifacts_name, tips_checked_at FROM repos ORDER BY tips_checked_at LIMIT ?").bind(SWEEP_REPOS).all(); let seeded = 0; let enqueued = 0; for (const repo of results) { try { const found = await reconcileRepo(env, repo); if (found === null) seeded++; else enqueued += found; } catch (error) { console.error(`ref sweep failed for repo ${repo.id}`, error); } } console.log(`ref sweep: ${results.length} repos checked, ${seeded} seeded, ${enqueued} mismatched refs enqueued`); } type SweptRepo = { id: string; artifacts_name: string; tips_checked_at: number | null }; async function reconcileRepo(env: Env, repo: SweptRepo): Promise { using handle = await env.ARTIFACTS.get(repo.artifacts_name); const refs = await readRefs(handle); const live = new Map([...[...refs.branches].map(([name, sha]) => [`refs/heads/${name}`, sha] as const), ...[...refs.tags].map(([name, sha]) => [`refs/tags/${name}`, sha] as const)]); const at = now(); const checked = env.DB.prepare("UPDATE repos SET tips_checked_at = ? WHERE id = ?").bind(at, repo.id); if (repo.tips_checked_at === null) { await env.DB.batch([...recordTips(env.DB, repo.id, [...live].map(([ref, to]) => ({ ref, from: null, to })), at), checked]); console.log(`ref sweep seeded ${live.size} refs of repo ${repo.id} without replaying them`); return null; } const { results } = await env.DB.prepare("SELECT ref, sha FROM ref_tips WHERE repo_id = ?").bind(repo.id).all<{ ref: string; sha: string }>(); const recorded = new Map(results.map((row) => [row.ref, row.sha])); const updates = [...new Set([...live.keys(), ...recorded.keys()])] .filter((ref) => live.get(ref) !== recorded.get(ref)) .slice(0, SWEEP_REFS) .map((ref) => ({ ref, from: recorded.get(ref) ?? null, to: live.get(ref) ?? null })); if (updates.length) await env.PUSHES.sendBatch(updates.map((update) => ({ body: { repoId: repo.id, actor: { kind: "system" }, updates: [update], at } satisfies PushMessage, delaySeconds: SWEEP_DELAY_SECONDS }))); await checked.run(); return updates.length; } function describe(message: PushMessage): string { return `repo ${message.repoId} ${message.updates.map((update) => `${update.ref} ${update.to ?? "deleted"}`).join(", ")}`; } /** The queue consumer: retries a failed push with backoff until the queue dead-letters it, and logs every push that lands in the dead-letter queue. */ export async function consumePushes(batch: MessageBatch, env: Env, ctx: Pick): Promise { for (const msg of batch.messages) { if (batch.queue.endsWith("-dlq")) { console.error(`push dead-lettered after ${msg.attempts} attempts: ${describe(msg.body)}`, JSON.stringify(msg.body)); msg.ack(); continue; } try { if (!(await processPush(env, ctx, msg.body))) console.error(`push dropped, its repository or pusher no longer exists: ${describe(msg.body)}`); msg.ack(); } catch (error) { console.error(`push failed on attempt ${msg.attempts}, retrying: ${describe(msg.body)}`, error); msg.retry({ delaySeconds: Math.min(5 * 2 ** msg.attempts, 600) }); } } } /** A push that brings an open pull request's head into its base merges it, however the merge was made. */ async function detectMerges(env: Env, ctx: Pick, actor: Recorder, record: RepoRecord, updates: readonly RefUpdate[]): Promise { const moved = new Map(updates.flatMap((update) => (update.to && update.ref.startsWith("refs/heads/") ? [[update.ref.slice("refs/heads/".length), { from: update.from, to: update.to }] as const] : []))); if (!moved.size) return; const candidates = (await pulls.openPulls(env.DB, record.id)).filter((pull) => moved.has(pull.base_ref)); if (!candidates.length) return; const handle = await env.ARTIFACTS.get(record.artifacts_name); const tips = (await readRefs(handle)).branches; const reachable = new Map>>(); const at = now(); const merged: { pull: pulls.PullRecord; tips: { base: string; head: string } }[] = []; for (const pull of candidates) { const head = tips.get(pull.head_ref); const base = moved.get(pull.base_ref)!; if (!head) continue; if (!reachable.has(base.to)) reachable.set(base.to, ancestors(handle, base.to)); const reached = await reachable.get(base.to)!; if (reached.has(head)) merged.push({ pull, tips: { base: base.from ?? base.to, head } }); else if (reached.size >= MAX_ANCESTORS) console.warn(`merge check for pull ${pull.number} in repo ${record.id} gave up after ${MAX_ANCESTORS} commits of ${pull.base_ref} at ${base.to} without reaching ${head}`); } if (!merged.length) return; await env.DB.batch(merged.flatMap(({ pull, tips }) => pulls.markMerged(env.DB, actor, pull, tips, at))); }