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