171 lines · 9.9 KBRaw
| 1 | import { onPush } from "@refs/ci/control"; |
| 2 | import { agentSessionById, now, type User } from "./auth.ts"; |
| 3 | import type { Actor } from "./contract/actor.ts"; |
| 4 | import { indexPushedTips } from "./code-maps.ts"; |
| 5 | import { indexPush } from "./decisions.ts"; |
| 6 | import { MAX_ANCESTORS, ancestors } from "./diff.ts"; |
| 7 | import { recordEvent, repoStream, type Recorder } from "./events.ts"; |
| 8 | import { readRefs, type RefUpdate } from "./git.ts"; |
| 9 | import { agentActor, toPerson } from "./identity.ts"; |
| 10 | import * as pulls from "./pulls.ts"; |
| 11 | import { raise } from "./outcomes.ts"; |
| 12 | import { findRepoRecordById, type RepoRecord } from "./repos.ts"; |
| 13 | |
| 14 | 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" }; |
| 15 | |
| 16 | /** 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. */ |
| 17 | export interface PushMessage { |
| 18 | readonly repoId: string; |
| 19 | readonly actor: Pusher; |
| 20 | readonly updates: readonly RefUpdate[]; |
| 21 | readonly at: number; |
| 22 | } |
| 23 | |
| 24 | export function pusher(actor: Actor): Pusher { |
| 25 | if (actor.kind === "human") return { kind: "human", person: actor.person.id, via: actor.via }; |
| 26 | if (actor.kind === "agent") return { kind: "agent", person: actor.onBehalfOf.id, session: actor.sessionId }; |
| 27 | return raise("sign_in_required", "Only signed-in actors can push."); |
| 28 | } |
| 29 | |
| 30 | async function resolvePusher(db: D1Database, by: Pusher): Promise<Recorder | null> { |
| 31 | if (by.kind === "system") return by; |
| 32 | if (by.kind === "agent") { |
| 33 | const session = await agentSessionById(db, by.session); |
| 34 | return session && agentActor(session); |
| 35 | } |
| 36 | const user = await db.prepare("SELECT id, email, name FROM users WHERE id = ?").bind(by.person).first<User>(); |
| 37 | return user && { kind: "human", person: toPerson(user), via: by.via }; |
| 38 | } |
| 39 | |
| 40 | function pushedKey(updates: readonly RefUpdate[]): string { |
| 41 | return updates.map((update) => `${update.ref}:${update.from ?? ""}:${update.to ?? ""}`).join(" "); |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * Records a push and carries out what it means. Every step is safe to repeat, so a message delivered twice, or retried |
| 46 | * after failing halfway, ends in the same state as one delivered once. Returns false when the push can never be processed. |
| 47 | */ |
| 48 | export async function processPush(env: Env, ctx: Pick<ExecutionContext, "waitUntil">, message: PushMessage): Promise<boolean> { |
| 49 | const [record, actor] = await Promise.all([findRepoRecordById(env.DB, message.repoId), resolvePusher(env.DB, message.actor)]); |
| 50 | if (!record || !actor) return false; |
| 51 | await recordEvent(env.DB, actor, repoStream(record.id), "repo.pushed", { updates: message.updates }, message.at, null, pushedKey(message.updates)).run(); |
| 52 | await detectMerges(env, ctx, actor, record, message.updates); |
| 53 | const indexed = await indexPush(env, actor, record, message.updates); |
| 54 | await env.DB.batch(recordTips(env.DB, record.id, message.updates, message.at)); |
| 55 | await indexPushedTips(env, record, message.updates).catch((error: unknown) => console.error(`code map indexing failed for ${describe(message)}`, error)); |
| 56 | await startCi(env, record, message).catch((error: unknown) => console.error(`CI start failed for ${describe(message)}`, error)); |
| 57 | return true; |
| 58 | } |
| 59 | |
| 60 | /** |
| 61 | * Starts the CI runs the pushed branch tips ask for. A run ID is fixed by repo, commit, config and source, so a push |
| 62 | * processed twice starts each run once. |
| 63 | */ |
| 64 | async function startCi(env: Env, record: RepoRecord, message: PushMessage): Promise<void> { |
| 65 | const actorId = message.actor.kind === "system" ? null : message.actor.person; |
| 66 | 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 })) }); |
| 67 | 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}`); |
| 68 | } |
| 69 | |
| 70 | /** Marks each ref as processed through its new tip, unless a push accepted later already moved the mark. */ |
| 71 | function recordTips(db: D1Database, repoId: string, updates: readonly RefUpdate[], at: number): D1PreparedStatement[] { |
| 72 | return updates.map((update) => |
| 73 | update.to === null |
| 74 | ? db.prepare("DELETE FROM ref_tips WHERE repo_id = ? AND ref = ? AND seen_at <= ?").bind(repoId, update.ref, at) |
| 75 | : 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), |
| 76 | ); |
| 77 | } |
| 78 | |
| 79 | const SWEEP_REPOS = 50; |
| 80 | const SWEEP_REFS = 100; |
| 81 | const SWEEP_DELAY_SECONDS = 60; |
| 82 | |
| 83 | /** |
| 84 | * The cron sweep: git is authoritative, so any ref whose live tip differs from the tip its last processed push left in |
| 85 | * `ref_tips` is enqueued as a push found by refs. Checks the repositories checked longest ago, a bounded number per run. |
| 86 | */ |
| 87 | export async function reconcilePushes(env: Env): Promise<void> { |
| 88 | 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<SweptRepo>(); |
| 89 | let seeded = 0; |
| 90 | let enqueued = 0; |
| 91 | for (const repo of results) { |
| 92 | try { |
| 93 | const found = await reconcileRepo(env, repo); |
| 94 | if (found === null) seeded++; |
| 95 | else enqueued += found; |
| 96 | } catch (error) { |
| 97 | console.error(`ref sweep failed for repo ${repo.id}`, error); |
| 98 | } |
| 99 | } |
| 100 | console.log(`ref sweep: ${results.length} repos checked, ${seeded} seeded, ${enqueued} mismatched refs enqueued`); |
| 101 | } |
| 102 | |
| 103 | type SweptRepo = { id: string; artifacts_name: string; tips_checked_at: number | null }; |
| 104 | |
| 105 | async function reconcileRepo(env: Env, repo: SweptRepo): Promise<number | null> { |
| 106 | using handle = await env.ARTIFACTS.get(repo.artifacts_name); |
| 107 | const refs = await readRefs(handle); |
| 108 | const live = new Map<string, string>([...[...refs.branches].map(([name, sha]) => [`refs/heads/${name}`, sha] as const), ...[...refs.tags].map(([name, sha]) => [`refs/tags/${name}`, sha] as const)]); |
| 109 | const at = now(); |
| 110 | const checked = env.DB.prepare("UPDATE repos SET tips_checked_at = ? WHERE id = ?").bind(at, repo.id); |
| 111 | if (repo.tips_checked_at === null) { |
| 112 | await env.DB.batch([...recordTips(env.DB, repo.id, [...live].map(([ref, to]) => ({ ref, from: null, to })), at), checked]); |
| 113 | console.log(`ref sweep seeded ${live.size} refs of repo ${repo.id} without replaying them`); |
| 114 | return null; |
| 115 | } |
| 116 | const { results } = await env.DB.prepare("SELECT ref, sha FROM ref_tips WHERE repo_id = ?").bind(repo.id).all<{ ref: string; sha: string }>(); |
| 117 | const recorded = new Map(results.map((row) => [row.ref, row.sha])); |
| 118 | const updates = [...new Set([...live.keys(), ...recorded.keys()])] |
| 119 | .filter((ref) => live.get(ref) !== recorded.get(ref)) |
| 120 | .slice(0, SWEEP_REFS) |
| 121 | .map((ref) => ({ ref, from: recorded.get(ref) ?? null, to: live.get(ref) ?? null })); |
| 122 | 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 }))); |
| 123 | await checked.run(); |
| 124 | return updates.length; |
| 125 | } |
| 126 | |
| 127 | function describe(message: PushMessage): string { |
| 128 | return `repo ${message.repoId} ${message.updates.map((update) => `${update.ref} ${update.to ?? "deleted"}`).join(", ")}`; |
| 129 | } |
| 130 | |
| 131 | /** 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. */ |
| 132 | export async function consumePushes(batch: MessageBatch<PushMessage>, env: Env, ctx: Pick<ExecutionContext, "waitUntil">): Promise<void> { |
| 133 | for (const msg of batch.messages) { |
| 134 | if (batch.queue.endsWith("-dlq")) { |
| 135 | console.error(`push dead-lettered after ${msg.attempts} attempts: ${describe(msg.body)}`, JSON.stringify(msg.body)); |
| 136 | msg.ack(); |
| 137 | continue; |
| 138 | } |
| 139 | try { |
| 140 | if (!(await processPush(env, ctx, msg.body))) console.error(`push dropped, its repository or pusher no longer exists: ${describe(msg.body)}`); |
| 141 | msg.ack(); |
| 142 | } catch (error) { |
| 143 | console.error(`push failed on attempt ${msg.attempts}, retrying: ${describe(msg.body)}`, error); |
| 144 | msg.retry({ delaySeconds: Math.min(5 * 2 ** msg.attempts, 600) }); |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | /** A push that brings an open pull request's head into its base merges it, however the merge was made. */ |
| 150 | async function detectMerges(env: Env, ctx: Pick<ExecutionContext, "waitUntil">, actor: Recorder, record: RepoRecord, updates: readonly RefUpdate[]): Promise<void> { |
| 151 | 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] : []))); |
| 152 | if (!moved.size) return; |
| 153 | const candidates = (await pulls.openPulls(env.DB, record.id)).filter((pull) => moved.has(pull.base_ref)); |
| 154 | if (!candidates.length) return; |
| 155 | const handle = await env.ARTIFACTS.get(record.artifacts_name); |
| 156 | const tips = (await readRefs(handle)).branches; |
| 157 | const reachable = new Map<string, Promise<Map<string, number>>>(); |
| 158 | const at = now(); |
| 159 | const merged: { pull: pulls.PullRecord; tips: { base: string; head: string } }[] = []; |
| 160 | for (const pull of candidates) { |
| 161 | const head = tips.get(pull.head_ref); |
| 162 | const base = moved.get(pull.base_ref)!; |
| 163 | if (!head) continue; |
| 164 | if (!reachable.has(base.to)) reachable.set(base.to, ancestors(handle, base.to)); |
| 165 | const reached = await reachable.get(base.to)!; |
| 166 | if (reached.has(head)) merged.push({ pull, tips: { base: base.from ?? base.to, head } }); |
| 167 | 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}`); |
| 168 | } |
| 169 | if (!merged.length) return; |
| 170 | await env.DB.batch(merged.flatMap(({ pull, tips }) => pulls.markMerged(env.DB, actor, pull, tips, at))); |
| 171 | } |