import { DurableObject } from "cloudflare:workers"; import type { CiEnv } from "./ci-env.ts"; import { failedJob, type JobResult, type JobSpec } from "./job-spec.ts"; import { LogBatcher } from "./log-batcher.ts"; const WORKDIR = "/work"; const READY_ATTEMPTS = 120; const READY_WAIT_MS = 500; const TOKEN_TTL_SECONDS = 900; const CHECKOUT_STEP = 0; const PATH = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; const CHECKOUT = `set -eu mkdir -p ${WORKDIR} && cd ${WORKDIR} git init -q auth="Authorization: Bearer $REFS_CLONE_TOKEN" if ! git -c http.extraHeader="$auth" fetch -q --depth 1 "$REFS_REMOTE" "$REFS_SHA" 2>/dev/null; then git -c http.extraHeader="$auth" fetch -q --depth 50 "$REFS_REMOTE" "$REFS_REF" fi git checkout -q "$REFS_SHA" echo "Checked out $REFS_REF at $(git rev-parse --short HEAD)" `; type Stop = "cancelled" | "timed_out" | null; /** * Runs one job in its own container (D3): start the image, clone the commit with a read-only token that lives only * for the checkout, run each step with bash, stream output to RunHub, and always destroy the container at the end. */ export class JobRunner extends DurableObject { #stop: Stop = null; async run(spec: JobSpec): Promise { const container = this.ctx.container; if (!container) return failedJob("The job runner has no container binding."); const image = container.images[spec.image]; if (!image) return failedJob(`The ${spec.image} image is not deployed yet.`); const hub = this.env.RUN_HUB.getByName(spec.runId); const log = new LogBatcher((step, text) => hub.append(spec.job, step, text)); this.#stop = null; const deadline = setTimeout(() => this.#halt("timed_out"), spec.timeoutMinutes * 60_000); try { if (container.running) await container.destroy(); const env = jobEnv(spec); container.start({ image, enableInternet: true, instance: spec.size, env }); await waitUntilReady(container); if (!(await hub.started(spec.job))) return { outcome: "cancelled", exitCode: null, failedStep: null, reason: "The run was cancelled." }; await hub.stepStarted(spec.job, CHECKOUT_STEP); const secrets = await hub.secrets(spec.job); for (const note of secrets.notes) log.write(CHECKOUT_STEP, `${note}\n`); const checkout = await this.#checkout(container, spec, env, log); if (checkout !== 0) return this.#result(checkout, CHECKOUT_STEP, "The checkout failed."); const stepEnv = { ...secrets.values, ...env }; for (const [index, step] of spec.steps.entries()) { const number = index + 1; await hub.stepStarted(spec.job, number); const code = await this.#exec(container, ["bash", "-eo", "pipefail", "-c", step.run], stepEnv, number, log); if (code !== 0) return this.#result(code, number, `Step ${number} (${step.name}) exited with ${code}.`); } return { outcome: "succeeded", exitCode: 0, failedStep: null, reason: null }; } catch (error) { return this.#result(null, null, `The container stopped: ${error instanceof Error ? error.message : String(error)}`); } finally { clearTimeout(deadline); await log.flush(); if (container.running) await container.destroy().catch(() => undefined); } } async cancel(): Promise { this.#halt("cancelled"); } #halt(stop: Exclude): void { this.#stop ??= stop; const container = this.ctx.container; if (container?.running) void container.destroy().catch(() => undefined); } #result(exitCode: number | null, failedStep: number | null, reason: string): JobResult { if (this.#stop === "cancelled") return { outcome: "cancelled", exitCode: null, failedStep: null, reason: "The run was cancelled." }; if (this.#stop === "timed_out") return { outcome: "timed_out", exitCode, failedStep, reason: "The job ran longer than its timeout." }; return { outcome: "failed", exitCode, failedStep, reason }; } async #checkout(container: Container, spec: JobSpec, env: Record, log: LogBatcher): Promise { using repo = await this.env.ARTIFACTS.get(spec.repo); const [info, token] = await Promise.all([repo.info(), repo.createToken("read", TOKEN_TTL_SECONDS)]); try { return await this.#exec(container, ["bash", "-c", CHECKOUT], { ...env, REFS_REMOTE: info.remote, REFS_CLONE_TOKEN: token.plaintext }, CHECKOUT_STEP, log); } finally { await repo.revokeToken(token.id).catch(() => false); } } async #exec(container: Container, command: string[], env: Record, step: number, log: LogBatcher): Promise { const process = await container.exec(command, { cwd: step === CHECKOUT_STEP ? "/" : WORKDIR, env, stderr: "combined" }); const pump = (async () => { if (!process.stdout) return; const decoder = new TextDecoder(); for await (const chunk of process.stdout) log.write(step, decoder.decode(chunk, { stream: true })); const rest = decoder.decode(); if (rest) log.write(step, rest); })(); const [code] = await Promise.all([process.exitCode, pump]); return code; } } /** exec() does not inherit the env given to start(), so every command gets the whole env. */ function jobEnv(spec: JobSpec): Record { 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 }; } async function waitUntilReady(container: Container): Promise { for (let attempt = 0; attempt < READY_ATTEMPTS; attempt++) { try { const probe = await container.exec(["true"]); if ((await probe.exitCode) === 0) return; } catch { await new Promise((resolve) => setTimeout(resolve, READY_WAIT_MS)); } } throw new Error("The container did not become ready in 60 seconds."); }