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