Skip to content
refs
History
135 lines · 6.7 KBRaw
1import { WorkflowEntrypoint, type WorkflowEvent, type WorkflowStep } from "cloudflare:workers";
2import type { Advance } from "../runs/run.ts";
3import type { RunState } from "../runs/states.ts";
4import type { CiEnv } from "./ci-env.ts";
5import { failedJob, type AgentProgress, type AgentStart, type JobResult, type JobSpec } from "./job-spec.ts";
6import { SLOTS } from "./job-slots.ts";
7import { approvalEvent, jobRunnerName } from "./run-id.ts";
8
9export interface RunParams {
10 readonly runId: string;
11}
12
13const MAX_WAVES = 200;
14const APPROVAL_TIMEOUT = "7 days";
15const STEP_MARGIN_MINUTES = 10;
16const SLOT_WAIT = "30 seconds";
17const AGENT_POLL_SECONDS = 15;
18const MAX_SLOT_WAITS = 240;
19
20const TERMINAL: readonly RunState[] = ["succeeded", "failed", "cancelled", "timed_out"];
21
22/**
23 * The durable driver of one run (D2). Each wave asks RunHub which jobs may start, runs them in parallel as steps, and
24 * records each result. When nothing may start, it waits for an approval event or ends. Step names are stable, so a
25 * replay after a restart reuses every finished step instead of running a job twice.
26 */
27export class RunPipeline extends WorkflowEntrypoint<CiEnv, RunParams> {
28 async run(event: Readonly<WorkflowEvent<RunParams>>, step: WorkflowStep): Promise<RunState> {
29 const { runId } = event.payload;
30 const hub = this.env.RUN_HUB.getByName(runId);
31 for (let wave = 0; wave < MAX_WAVES; wave++) {
32 const advance = await step.do(`advance ${wave}`, async (): Promise<Advance> => hub.advance());
33 if (advance.start.length) {
34 await Promise.all(advance.start.map(({ job, waitSeconds }) => this.#runJob(step, runId, job, waitSeconds)));
35 continue;
36 }
37 const state = await step.do(`state ${wave}`, async (): Promise<RunState> => hub.state());
38 if (TERMINAL.includes(state)) return state;
39 const [waiting] = await step.do(`waiting ${wave}`, async (): Promise<readonly string[]> => hub.awaitingApproval());
40 if (!waiting) return state;
41 try {
42 await step.waitForEvent(`approval ${waiting} ${wave}`, { type: approvalEvent(waiting), timeout: APPROVAL_TIMEOUT });
43 } catch {
44 await step.do(`approval expired ${wave}`, async () => {
45 await hub.cancel(`Nobody approved ${waiting} within ${APPROVAL_TIMEOUT}.`);
46 });
47 }
48 }
49 return step.do("give up", async (): Promise<RunState> => {
50 await hub.cancel(`The run stopped after ${MAX_WAVES} waves.`);
51 return hub.state();
52 });
53 }
54
55 /** Waits out the environment's timer, then for a free slot in refs, then runs the job and frees the slot. */
56 async #runJob(step: WorkflowStep, runId: string, job: string, waitSeconds: number): Promise<string> {
57 const hub = this.env.RUN_HUB.getByName(runId);
58 if (waitSeconds > 0) await step.sleep(`wait ${job}`, waitSeconds * 1000);
59 const spec = await step.do(`spec ${job}`, async (): Promise<JobSpec> => hub.spec(job));
60 if (spec.agent) return this.#runAgentJob(step, spec);
61 const slots = this.env.JOB_SLOTS.getByName(SLOTS);
62 const key = jobRunnerName(runId, job);
63 const leaseMs = (spec.timeoutMinutes + STEP_MARGIN_MINUTES) * 60_000;
64 for (let attempt = 0; ; attempt++) {
65 const slot = await step.do(`slot ${job} ${attempt}`, async (): Promise<"taken" | "full" | "gone"> => {
66 if (!(await hub.isQueued(job))) return "gone";
67 return (await slots.acquire(key, leaseMs)) ? "taken" : "full";
68 });
69 if (slot === "gone") return "cancelled";
70 if (slot === "taken") break;
71 if (attempt + 1 >= MAX_SLOT_WAITS) {
72 return step.do(`no slot ${job}`, async (): Promise<string> => {
73 await hub.record(job, failedJob("refs ran its limit of jobs for 2 hours, so this job never got a slot."));
74 return "failed";
75 });
76 }
77 await step.sleep(`slot wait ${job} ${attempt}`, SLOT_WAIT);
78 }
79 const outcome = await step.do(`job ${job}`, { retries: { limit: 0, delay: 0 }, timeout: `${spec.timeoutMinutes + STEP_MARGIN_MINUTES} minutes` }, async (): Promise<string> => {
80 let result: JobResult;
81 try {
82 result = await this.env.JOB_RUNNER.getByName(key).run(spec);
83 } catch (error) {
84 result = failedJob(`The job runner failed: ${error instanceof Error ? error.message : String(error)}`);
85 }
86 await hub.record(job, result);
87 return result.outcome;
88 });
89 await step.do(`release ${job}`, async () => slots.release(key));
90 return outcome;
91 }
92
93 /** Starts the hosted agent, then checks on its run until it ends or the job times out. An agent job needs no container slot. */
94 async #runAgentJob(step: WorkflowStep, spec: JobSpec): Promise<string> {
95 const hub = this.env.RUN_HUB.getByName(spec.runId);
96 const { job } = spec;
97 const start = await step.do(`agent ${job}`, async (): Promise<AgentStart | null> => {
98 if (!(await hub.started(job))) return null;
99 await hub.stepStarted(job, 0);
100 try {
101 return await this.startAgent(spec);
102 } catch (error) {
103 return { kind: "ended", result: failedJob(`The agent could not start: ${error instanceof Error ? error.message : String(error)}`) };
104 }
105 });
106 if (!start) return "cancelled";
107 if (start.kind === "ended") return this.#finishAgentJob(step, spec, start.result, start.result.reason ?? "");
108 const polls = Math.ceil((spec.timeoutMinutes * 60) / AGENT_POLL_SECONDS);
109 for (let poll = 0; poll < polls; poll++) {
110 await step.sleep(`agent wait ${job} ${poll}`, AGENT_POLL_SECONDS * 1000);
111 const progress = await step.do(`agent check ${job} ${poll}`, async (): Promise<AgentProgress> => this.agentProgress(start.session));
112 if (progress.done) return this.#finishAgentJob(step, spec, progress.result, progress.log);
113 }
114 return this.#finishAgentJob(step, spec, { outcome: "timed_out", exitCode: null, failedStep: 0, reason: `The agent did not answer within ${spec.timeoutMinutes} minutes.` }, "");
115 }
116
117 async #finishAgentJob(step: WorkflowStep, spec: JobSpec, result: JobResult, log: string): Promise<string> {
118 const hub = this.env.RUN_HUB.getByName(spec.runId);
119 return step.do(`agent end ${spec.job}`, async (): Promise<string> => {
120 if (log) await hub.append(spec.job, 0, `${log}\n`);
121 await hub.record(spec.job, result);
122 return result.outcome;
123 });
124 }
125
126 /** Starts a hosted agent for an agent job. The Worker that hosts the agents replaces this. */
127 protected async startAgent(_spec: JobSpec): Promise<AgentStart> {
128 return { kind: "ended", result: failedJob("This server does not run hosted agents.") };
129 }
130
131 /** Where a started agent job stands. The Worker that hosts the agents replaces this. */
132 protected async agentProgress(_session: string): Promise<AgentProgress> {
133 return { done: true, result: failedJob("This server does not run hosted agents."), log: "" };
134 }
135}