Skip to content
refs
History
88 lines · 5.0 KBRaw
1import { now } from "./auth.ts";
2import { captureWorkEvent } from "./analytics.ts";
3import { recordEvent, repoStream } from "./events.ts";
4import { parseGitRoute, proxyGit, readReceiveCommands, rejectPush, scopeFor, type RefUpdate } from "./git.ts";
5import { admitAgentPush } from "./decisions.ts";
6import type { Actor } from "./contract/actor.ts";
7import { resolveActor } from "./identity.ts";
8import { oauth } from "./oauth.ts";
9import { ok } from "./outcomes.ts";
10import { heldBranch, Policy } from "./policy.ts";
11import { findRepoRecord, namespacePolicy, repoFacts } from "./repos.ts";
12import { pusher, type PushMessage } from "./pushes.ts";
13import { claimableBranch, refProblem } from "@refs/protocol";
14
15export async function serveGit(env: Env, ctx: ExecutionContext, request: Request): Promise<Response | null> {
16 const route = parseGitRoute(request.method, new URL(request.url));
17 if (!route) return null;
18
19 const unauthorized = () => new Response("Authentication required\n", { status: 401, headers: { "www-authenticate": 'Basic realm="refs"' } });
20 const { actor, badCredentials } = await resolveActor(env.DB, ctx, request, oauth(env));
21 if (badCredentials) return unauthorized();
22
23 const record = await findRepoRecord(env.DB, route.repo);
24 const policy = record ? await namespacePolicy(env.DB, new Policy(actor, null), record.namespace_id) : new Policy(actor, null);
25 const facts = record ? repoFacts(record) : null;
26 const allowed = facts !== null && policy.canSeeRepo(facts) && (scopeFor(route.service) === "read" || policy.canWriteRepo(facts));
27 if (!allowed) return policy.signedIn ? new Response("Repository not found\n", { status: 404 }) : unauthorized();
28
29 if (route.suffix !== "/git-receive-pack" || !request.body) return proxyGit(request, env.ARTIFACTS, record!.artifacts_name, route);
30
31 const [forwarded, inspected] = request.body.tee();
32 const commands = readReceiveCommands(inspected);
33
34 if (actor.kind === "agent") {
35 const received = await commands;
36 const branch = heldBranch(actor.grant);
37 const claim = branch === null ? claimableBranch(received.updates, record!.default_branch) : null;
38 const reasons = new Map<string, string>();
39 for (const update of received.updates) {
40 const reason = claim ? null : refProblem(branch, update);
41 if (reason) reasons.set(update.ref, reason);
42 }
43 if (reasons.size) {
44 ctx.waitUntil(forwarded.cancel());
45 return rejectPush(received, reasons);
46 }
47 const admitted = await admitAgentPush(env, record!, received, forwarded);
48 if (admitted.landed && claim) await claimBranch(env.DB, actor, record!.id, claim);
49 if (admitted.landed) {
50 ctx.waitUntil(queuePush(env, record!.id, actor, received.updates));
51 captureWorkEvent(env, ctx, actor, { name: "agent.push_accepted", repoId: record!.id, namespaceId: record!.namespace_id, branch: claim ?? branch });
52 }
53 return admitted.response;
54 }
55
56 const response = await proxyGit(new Request(request, { body: forwarded }), env.ARTIFACTS, record!.artifacts_name, route);
57 if (response.ok) {
58 ctx.waitUntil(
59 commands.then(async ({ updates }) => {
60 const corrected = await agentBranch(env.DB, record!.id, updates);
61 if (corrected) captureWorkEvent(env, ctx, actor, { name: "work.corrected", repoId: record!.id, namespaceId: record!.namespace_id, ...corrected });
62 return queuePush(env, record!.id, actor, updates);
63 }),
64 );
65 }
66 return response;
67}
68
69/** The agent work a person's push changed: an existing branch a live agent session works on. */
70async function agentBranch(db: D1Database, repoId: string, updates: readonly RefUpdate[]): Promise<{ branch: string } | null> {
71 const branches = updates.flatMap((update) => (update.from !== null && update.to !== null && update.ref.startsWith("refs/heads/") ? [update.ref.slice("refs/heads/".length)] : []));
72 if (!branches.length) return null;
73 const branch = await db
74 .prepare("SELECT branch FROM agent_sessions WHERE repo_id = ? AND ended_at IS NULL AND branch IN (SELECT value FROM json_each(?)) LIMIT 1")
75 .bind(repoId, JSON.stringify(branches))
76 .first<string>("branch");
77 return branch === null ? null : { branch };
78}
79
80/** Makes the branch an agent just created by pushing it the session's branch, unless the session claimed another one meanwhile. */
81async function claimBranch(db: D1Database, actor: Extract<Actor, { kind: "agent" }>, repoId: string, branch: string): Promise<void> {
82 const { meta } = await db.prepare("UPDATE agent_sessions SET branch = ? WHERE id = ? AND branch IS NULL AND ended_at IS NULL").bind(branch, actor.sessionId).run();
83 if (meta.changes) await recordEvent(db, actor, repoStream(repoId), "session.tasked", { session: actor.sessionId, branch }, now()).run();
84}
85
86async function queuePush(env: Env, repoId: string, actor: Actor, updates: RefUpdate[]): Promise<void> {
87 if (updates.length) await env.PUSHES.send({ repoId, actor: pusher(actor), updates, at: now() } satisfies PushMessage).catch((error) => console.error(`push not queued for repo ${repoId}`, error));
88}