Skip to content
refs
History
125 lines · 5.7 KBRaw
1import { DurableObject } from "cloudflare:workers";
2import type { CiEnv } from "./ci-env.ts";
3import { failedJob, type JobResult, type JobSpec } from "./job-spec.ts";
4import { LogBatcher } from "./log-batcher.ts";
5
6const WORKDIR = "/work";
7const READY_ATTEMPTS = 120;
8const READY_WAIT_MS = 500;
9const TOKEN_TTL_SECONDS = 900;
10const CHECKOUT_STEP = 0;
11const PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
12
13const CHECKOUT = `set -eu
14mkdir -p ${WORKDIR} && cd ${WORKDIR}
15git init -q
16auth="Authorization: Bearer $REFS_CLONE_TOKEN"
17if ! git -c http.extraHeader="$auth" fetch -q --depth 1 "$REFS_REMOTE" "$REFS_SHA" 2>/dev/null; then
18 git -c http.extraHeader="$auth" fetch -q --depth 50 "$REFS_REMOTE" "$REFS_REF"
19fi
20git checkout -q "$REFS_SHA"
21echo "Checked out $REFS_REF at $(git rev-parse --short HEAD)"
22`;
23
24type Stop = "cancelled" | "timed_out" | null;
25
26/**
27 * Runs one job in its own container (D3): start the image, clone the commit with a read-only token that lives only
28 * for the checkout, run each step with bash, stream output to RunHub, and always destroy the container at the end.
29 */
30export class JobRunner extends DurableObject<CiEnv> {
31 #stop: Stop = null;
32
33 async run(spec: JobSpec): Promise<JobResult> {
34 const container = this.ctx.container;
35 if (!container) return failedJob("The job runner has no container binding.");
36 const image = container.images[spec.image];
37 if (!image) return failedJob(`The ${spec.image} image is not deployed yet.`);
38 const hub = this.env.RUN_HUB.getByName(spec.runId);
39 const log = new LogBatcher((step, text) => hub.append(spec.job, step, text));
40 this.#stop = null;
41 const deadline = setTimeout(() => this.#halt("timed_out"), spec.timeoutMinutes * 60_000);
42 try {
43 if (container.running) await container.destroy();
44 const env = jobEnv(spec);
45 container.start({ image, enableInternet: true, instance: spec.size, env });
46 await waitUntilReady(container);
47 if (!(await hub.started(spec.job))) return { outcome: "cancelled", exitCode: null, failedStep: null, reason: "The run was cancelled." };
48 await hub.stepStarted(spec.job, CHECKOUT_STEP);
49 const secrets = await hub.secrets(spec.job);
50 for (const note of secrets.notes) log.write(CHECKOUT_STEP, `${note}\n`);
51 const checkout = await this.#checkout(container, spec, env, log);
52 if (checkout !== 0) return this.#result(checkout, CHECKOUT_STEP, "The checkout failed.");
53 const stepEnv = { ...secrets.values, ...env };
54 for (const [index, step] of spec.steps.entries()) {
55 const number = index + 1;
56 await hub.stepStarted(spec.job, number);
57 const code = await this.#exec(container, ["bash", "-eo", "pipefail", "-c", step.run], stepEnv, number, log);
58 if (code !== 0) return this.#result(code, number, `Step ${number} (${step.name}) exited with ${code}.`);
59 }
60 return { outcome: "succeeded", exitCode: 0, failedStep: null, reason: null };
61 } catch (error) {
62 return this.#result(null, null, `The container stopped: ${error instanceof Error ? error.message : String(error)}`);
63 } finally {
64 clearTimeout(deadline);
65 await log.flush();
66 if (container.running) await container.destroy().catch(() => undefined);
67 }
68 }
69
70 async cancel(): Promise<void> {
71 this.#halt("cancelled");
72 }
73
74 #halt(stop: Exclude<Stop, null>): void {
75 this.#stop ??= stop;
76 const container = this.ctx.container;
77 if (container?.running) void container.destroy().catch(() => undefined);
78 }
79
80 #result(exitCode: number | null, failedStep: number | null, reason: string): JobResult {
81 if (this.#stop === "cancelled") return { outcome: "cancelled", exitCode: null, failedStep: null, reason: "The run was cancelled." };
82 if (this.#stop === "timed_out") return { outcome: "timed_out", exitCode, failedStep, reason: "The job ran longer than its timeout." };
83 return { outcome: "failed", exitCode, failedStep, reason };
84 }
85
86 async #checkout(container: Container, spec: JobSpec, env: Record<string, string>, log: LogBatcher): Promise<number> {
87 using repo = await this.env.ARTIFACTS.get(spec.repo);
88 const [info, token] = await Promise.all([repo.info(), repo.createToken("read", TOKEN_TTL_SECONDS)]);
89 try {
90 return await this.#exec(container, ["bash", "-c", CHECKOUT], { ...env, REFS_REMOTE: info.remote, REFS_CLONE_TOKEN: token.plaintext }, CHECKOUT_STEP, log);
91 } finally {
92 await repo.revokeToken(token.id).catch(() => false);
93 }
94 }
95
96 async #exec(container: Container, command: string[], env: Record<string, string>, step: number, log: LogBatcher): Promise<number> {
97 const process = await container.exec(command, { cwd: step === CHECKOUT_STEP ? "/" : WORKDIR, env, stderr: "combined" });
98 const pump = (async () => {
99 if (!process.stdout) return;
100 const decoder = new TextDecoder();
101 for await (const chunk of process.stdout) log.write(step, decoder.decode(chunk, { stream: true }));
102 const rest = decoder.decode();
103 if (rest) log.write(step, rest);
104 })();
105 const [code] = await Promise.all([process.exitCode, pump]);
106 return code;
107 }
108}
109
110/** exec() does not inherit the env given to start(), so every command gets the whole env. */
111function jobEnv(spec: JobSpec): Record<string, string> {
112 return { PATH, HOME: "/root", LANG: "C.UTF-8", CI: "true", REFS_SHA: spec.sha, REFS_REF: spec.ref, REFS_JOB: spec.job, REFS_RUN_ID: spec.runId };
113}
114
115async function waitUntilReady(container: Container): Promise<void> {
116 for (let attempt = 0; attempt < READY_ATTEMPTS; attempt++) {
117 try {
118 const probe = await container.exec(["true"]);
119 if ((await probe.exitCode) === 0) return;
120 } catch {
121 await new Promise((resolve) => setTimeout(resolve, READY_WAIT_MS));
122 }
123 }
124 throw new Error("The container did not become ready in 60 seconds.");
125}