import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers"; import type { Advance } from "../runs/run.ts"; import type { RunState } from "../runs/states.ts"; import type { CiEnv } from "./ci-env.ts"; import { failedJob, type AgentProgress, type AgentStart, type JobResult, type JobSpec } from "./job-spec.ts"; import { SLOTS } from "./job-slots.ts"; import { approvalEvent, jobRunnerName } from "./run-id.ts"; export interface RunParams { readonly runId: string; } const MAX_WAVES = 200; const APPROVAL_TIMEOUT = "7 days"; const STEP_MARGIN_MINUTES = 10; const SLOT_WAIT = "30 seconds"; const AGENT_POLL_SECONDS = 15; const MAX_SLOT_WAITS = 240; const TERMINAL: readonly RunState[] = ["succeeded", "failed", "cancelled", "timed_out"]; /** * The durable driver of one run (D2). Each wave asks RunHub which jobs may start, runs them in parallel as steps, and * records each result. When nothing may start, it waits for an approval event or ends. Step names are stable, so a * replay after a restart reuses every finished step instead of running a job twice. */ export class RunPipeline extends WorkflowEntrypoint { async run(event: Readonly>, step: WorkflowStep): Promise { const { runId } = event.payload; const hub = this.env.RUN_HUB.getByName(runId); for (let wave = 0; wave < MAX_WAVES; wave++) { const advance = await step.do(`advance ${wave}`, async (): Promise => hub.advance()); if (advance.start.length) { await Promise.all(advance.start.map(({ job, waitSeconds }) => this.#runJob(step, runId, job, waitSeconds))); continue; } const state = await step.do(`state ${wave}`, async (): Promise => hub.state()); if (TERMINAL.includes(state)) return state; const [waiting] = await step.do(`waiting ${wave}`, async (): Promise => hub.awaitingApproval()); if (!waiting) return state; try { await step.waitForEvent(`approval ${waiting} ${wave}`, { type: approvalEvent(waiting), timeout: APPROVAL_TIMEOUT }); } catch { await step.do(`approval expired ${wave}`, async () => { await hub.cancel(`Nobody approved ${waiting} within ${APPROVAL_TIMEOUT}.`); }); } } return step.do("give up", async (): Promise => { await hub.cancel(`The run stopped after ${MAX_WAVES} waves.`); return hub.state(); }); } /** Waits out the environment's timer, then for a free slot in refs, then runs the job and frees the slot. */ async #runJob(step: WorkflowStep, runId: string, job: string, waitSeconds: number): Promise { const hub = this.env.RUN_HUB.getByName(runId); if (waitSeconds > 0) await step.sleep(`wait ${job}`, waitSeconds * 1000); const spec = await step.do(`spec ${job}`, async (): Promise => hub.spec(job)); if (spec.agent) return this.#runAgentJob(step, spec); const slots = this.env.JOB_SLOTS.getByName(SLOTS); const key = jobRunnerName(runId, job); const leaseMs = (spec.timeoutMinutes + STEP_MARGIN_MINUTES) * 60_000; for (let attempt = 0; ; attempt++) { const slot = await step.do(`slot ${job} ${attempt}`, async (): Promise<"taken" | "full" | "gone"> => { if (!(await hub.isQueued(job))) return "gone"; return (await slots.acquire(key, leaseMs)) ? "taken" : "full"; }); if (slot === "gone") return "cancelled"; if (slot === "taken") break; if (attempt + 1 >= MAX_SLOT_WAITS) { return step.do(`no slot ${job}`, async (): Promise => { await hub.record(job, failedJob("refs ran its limit of jobs for 2 hours, so this job never got a slot.")); return "failed"; }); } await step.sleep(`slot wait ${job} ${attempt}`, SLOT_WAIT); } const outcome = await step.do(`job ${job}`, { retries: { limit: 0, delay: 0 }, timeout: `${spec.timeoutMinutes + STEP_MARGIN_MINUTES} minutes` }, async (): Promise => { let result: JobResult; try { result = await this.env.JOB_RUNNER.getByName(key).run(spec); } catch (error) { result = failedJob(`The job runner failed: ${error instanceof Error ? error.message : String(error)}`); } await hub.record(job, result); return result.outcome; }); await step.do(`release ${job}`, async () => slots.release(key)); return outcome; } /** Starts the hosted agent, then checks on its run until it ends or the job times out. An agent job needs no container slot. */ async #runAgentJob(step: WorkflowStep, spec: JobSpec): Promise { const hub = this.env.RUN_HUB.getByName(spec.runId); const { job } = spec; const start = await step.do(`agent ${job}`, async (): Promise => { if (!(await hub.started(job))) return null; await hub.stepStarted(job, 0); try { return await this.startAgent(spec); } catch (error) { return { kind: "ended", result: failedJob(`The agent could not start: ${error instanceof Error ? error.message : String(error)}`) }; } }); if (!start) return "cancelled"; if (start.kind === "ended") return this.#finishAgentJob(step, spec, start.result, start.result.reason ?? ""); const polls = Math.ceil((spec.timeoutMinutes * 60) / AGENT_POLL_SECONDS); for (let poll = 0; poll < polls; poll++) { await step.sleep(`agent wait ${job} ${poll}`, AGENT_POLL_SECONDS * 1000); const progress = await step.do(`agent check ${job} ${poll}`, async (): Promise => this.agentProgress(start.session)); if (progress.done) return this.#finishAgentJob(step, spec, progress.result, progress.log); } return this.#finishAgentJob(step, spec, { outcome: "timed_out", exitCode: null, failedStep: 0, reason: `The agent did not answer within ${spec.timeoutMinutes} minutes.` }, ""); } async #finishAgentJob(step: WorkflowStep, spec: JobSpec, result: JobResult, log: string): Promise { const hub = this.env.RUN_HUB.getByName(spec.runId); return step.do(`agent end ${spec.job}`, async (): Promise => { if (log) await hub.append(spec.job, 0, `${log}\n`); await hub.record(spec.job, result); return result.outcome; }); } /** Starts a hosted agent for an agent job. The Worker that hosts the agents replaces this. */ protected async startAgent(_spec: JobSpec): Promise { return { kind: "ended", result: failedJob("This server does not run hosted agents.") }; } /** Where a started agent job stands. The Worker that hosts the agents replaces this. */ protected async agentProgress(_session: string): Promise { return { done: true, result: failedJob("This server does not run hosted agents."), log: "" }; } }