import { DurableObject } from "cloudflare:workers"; import { JobGraph } from "../config/job-graph.ts"; import { parsePipeline } from "../config/parse-pipeline.ts"; import type { Pipeline } from "../config/pipeline.ts"; import { LogMasker } from "../logs/log-masker.ts"; import { gateEnvironment, type EnvironmentRules } from "../runs/environment-gate.ts"; import { Run, type Advance, type JobRecord } from "../runs/run.ts"; import type { JobState, RunState } from "../runs/states.ts"; import type { TrustDecision } from "../runs/trust.ts"; import { openJobSecrets, type OpenedSecrets } from "../secrets/job-secrets.ts"; import type { CiEnv } from "./ci-env.ts"; import type { JobResult, JobSpec } from "./job-spec.ts"; const TERMINAL_RUN: readonly RunState[] = ["succeeded", "failed", "cancelled", "timed_out"]; export interface RunMeta { readonly runId: string; readonly repoId: string; readonly namespaceId: string; /** The Artifacts repository name. */ readonly repo: string; readonly sha: string; readonly ref: string; /** The branch that environment rules check: the pushed branch or the pull request's head. Null for a tag. */ readonly branch: string | null; readonly pull: number | null; readonly trigger: "push" | "pull_request" | "manual"; readonly trust: TrustDecision; /** The rules of each environment the pipeline names, as they were when the run started. */ readonly environments: Readonly>; readonly createdAt: number; } export interface JobView extends JobRecord { readonly environment: string | null; readonly image: string; readonly steps: readonly string[]; readonly exitCode: number | null; readonly failedStep: number | null; readonly startedAt: number | null; readonly endedAt: number | null; } export interface RunStatus { readonly meta: RunMeta; readonly state: RunState; readonly jobs: readonly JobView[]; } export type LogLine = { readonly seq: number; readonly job: string; readonly step: number; readonly at: number; readonly text: string; }; /** One step's output. Step 0 sets the job up: secrets and the checkout. Times are in milliseconds. */ export interface StepLog { readonly step: number; readonly text: string; readonly startedAt: number | null; readonly endedAt: number | null; } export class RunNotFound extends Error { constructor() { super("This run does not exist."); } } const REPLAYED_LINES = 2000; interface Loaded { readonly meta: RunMeta; readonly pipeline: Pipeline; readonly run: Run; } type JobRow = { name: string; state: JobState; reason: string | null; exit_code: number | null; failed_step: number | null; started_at: number | null; ended_at: number | null }; /** * One run's state and logs (D4). It is the only writer of both: the Workflow, the job runners and the backend all * call it, and it saves after each change. It masks job output with the job's secrets before it stores or sends a line. */ export class RunHub extends DurableObject { #loaded: Loaded | null = null; #mirroredRun: RunState | null = null; readonly #mirroredJobs = new Map(); readonly #maskers = new Map(); readonly #watchers = new Set>(); constructor(ctx: DurableObjectState, env: CiEnv) { super(ctx, env); ctx.blockConcurrencyWhile(async () => { ctx.storage.sql.exec(` CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE IF NOT EXISTS jobs (name TEXT PRIMARY KEY, state TEXT NOT NULL, reason TEXT, exit_code INTEGER, failed_step INTEGER, started_at INTEGER, ended_at INTEGER); CREATE TABLE IF NOT EXISTS logs (seq INTEGER PRIMARY KEY AUTOINCREMENT, job TEXT NOT NULL, step INTEGER NOT NULL, at INTEGER NOT NULL, text TEXT NOT NULL); CREATE TABLE IF NOT EXISTS steps (job TEXT NOT NULL, step INTEGER NOT NULL, started_at INTEGER NOT NULL, PRIMARY KEY (job, step)); `); }); } init(meta: RunMeta, config: string): "created" | "exists" { if (this.#meta("meta")) return "exists"; const pipeline = parseValid(config); const sql = this.ctx.storage.sql; sql.exec("INSERT INTO meta (key, value) VALUES ('meta', ?), ('config', ?)", JSON.stringify(meta), config); for (const name of pipeline.jobs.keys()) sql.exec("INSERT INTO jobs (name, state) VALUES (?, 'pending')", name); return "created"; } /** * Moves the run on, and returns the jobs to start: the ones it queued now, and queued jobs that a person approved. * Only the Workflow calls it, and only when no job is in flight, so a queued job here has not started. */ advance(): Advance { const { meta, pipeline, run } = this.#load(); const advance = run.advance((job) => { const environment = pipeline.jobs.get(job)?.environment; return environment ? gateEnvironment(environment, meta.environments[environment] ?? null, { branch: meta.branch, trust: meta.trust.trust }) : null; }); this.#save(); const approved = run.records().filter((job) => job.state === "queued" && !advance.start.some((entry) => entry.job === job.name)); return { ...advance, start: [...advance.start, ...approved.map((job) => ({ job: job.name, waitSeconds: 0 }))] }; } spec(job: string): JobSpec { const { meta, pipeline } = this.#load(); const definition = pipeline.jobs.get(job); if (!definition) throw new Error(`No job named ${job}.`); return { runId: meta.runId, job, repo: meta.repo, sha: meta.sha, ref: meta.ref, image: definition.image.name, size: definition.size, steps: definition.steps, timeoutMinutes: definition.timeoutMinutes, agent: definition.agent }; } /** Opens the secrets the job names and starts masking them in its output. Only the job's runner calls it. */ async secrets(job: string): Promise { const opened = await this.#openSecrets(job); this.#maskers.set(job, new LogMasker(Object.values(opened.values))); return opened; } /** Marks the job running. Returns false when it ended before its container came up, such as after a cancel. */ started(job: string): boolean { const applied = this.#load().run.started(job) === "applied"; if (applied) this.ctx.storage.sql.exec("UPDATE jobs SET started_at = ? WHERE name = ?", Date.now(), job); this.#save(); return applied; } isQueued(job: string): boolean { return this.#load().run.job(job).state === "queued"; } record(job: string, result: JobResult): void { const { run } = this.#load(); this.#flushMasker(job); const applied = result.outcome === "cancelled" ? run.finished(job, "failed", result.reason) : run.finished(job, result.outcome, result.reason); if (applied === "applied") this.ctx.storage.sql.exec("UPDATE jobs SET exit_code = ?, failed_step = ?, ended_at = ? WHERE name = ?", result.exitCode, result.failedStep, Date.now(), job); this.#save(); } decide(job: string, decision: "approved" | "rejected", by: { readonly id: string; readonly name: string }): void { const { meta, run } = this.#load(); if (decision === "approved") { run.approve(job, by.name); this.ctx.storage.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", `approved:${job}`, by.id); } else run.reject(job, by.name); this.#save(); const audit = this.env.DB.prepare("INSERT OR REPLACE INTO ci_approvals (run_id, job, decided_by, decision, at) VALUES (?, ?, ?, ?, ?)").bind(meta.runId, job, by.id, decision, Date.now()).run(); this.ctx.waitUntil(audit.then(() => undefined, (error: unknown) => console.error(`ci_approvals write failed for ${meta.runId}`, error))); } /** Cancels the run. Returns the jobs that have a container, so the caller can stop them. */ cancel(reason: string): readonly string[] { const live = this.#load().run.cancel(reason); this.#save(); return live; } awaitingApproval(): readonly string[] { return this.#load().run.records().filter((job) => job.state === "waiting_approval").map((job) => job.name); } state(): RunState { return this.#load().run.state; } status(): RunStatus { const { meta, pipeline, run } = this.#load(); const rows = new Map(this.ctx.storage.sql.exec("SELECT * FROM jobs").toArray().map((row) => [row.name, row])); const jobs = run.records().map((record) => { const row = rows.get(record.name); const definition = pipeline.jobs.get(record.name); return { ...record, environment: definition?.environment ?? null, image: definition?.image.name ?? "base", steps: definition?.steps.map((step) => step.name) ?? [], exitCode: row?.exit_code ?? null, failedStep: row?.failed_step ?? null, startedAt: row?.started_at ?? null, endedAt: row?.ended_at ?? null, }; }); return { meta, state: run.state, jobs }; } /** * Job runners send output in order, one batch at a time, so a masker rebuilt after an eviction sees no race. When the * secrets cannot be opened again, the batch is refused and dropped rather than stored unmasked. */ async append(job: string, step: number, text: string): Promise { let masker = this.#maskers.get(job); if (!masker) { masker = new LogMasker(Object.values((await this.#openSecrets(job)).values)); this.#maskers.set(job, masker); } this.#store(job, step, masker.push(text)); } /** Records the time a step of a job starts, so a step that prints nothing still has a start and an end. */ stepStarted(job: string, step: number): void { const at = Date.now(); this.ctx.storage.sql.exec("INSERT OR IGNORE INTO steps (job, step, started_at) VALUES (?, ?, ?)", job, step, at); this.#broadcast(sse("step", { job, step, at })); } /** * The stored output of one job, split by step, and the sequence number of the last line in the whole run, so a * reader of the event stream can skip what it has. A step ends when the next one starts, or when the job ends. */ logs(job: string): { readonly steps: readonly StepLog[]; readonly seq: number } { const sql = this.ctx.storage.sql; const steps = new Map(); const entry = (step: number) => steps.get(step) ?? steps.set(step, { step, text: "", startedAt: null, endedAt: null }).get(step)!; for (const row of sql.exec<{ step: number; started_at: number }>("SELECT step, started_at FROM steps WHERE job = ? ORDER BY step", job)) entry(row.step).startedAt = row.started_at; let last = 0; for (const row of sql.exec<{ step: number; text: string }>("SELECT step, text FROM logs WHERE job = ? ORDER BY seq", job)) { last = row.step < 0 ? last : row.step; entry(last).text += row.text; } const ordered = [...steps.values()].sort((a, b) => a.step - b.step); const jobEnd = sql.exec<{ ended_at: number | null }>("SELECT ended_at FROM jobs WHERE name = ?", job).toArray()[0]?.ended_at ?? null; ordered.forEach((step, index) => (step.endedAt = ordered[index + 1]?.startedAt ?? jobEnd)); return { steps: ordered, seq: sql.exec<{ seq: number | null }>("SELECT max(seq) AS seq FROM logs").one().seq ?? 0 }; } async fetch(request: Request): Promise { if (new URL(request.url).pathname !== "/events") return new Response("Not found\n", { status: 404 }); this.#load(); const { readable, writable } = new TransformStream(); const writer = writable.getWriter(); const recent = this.ctx.storage.sql.exec("SELECT * FROM (SELECT * FROM logs ORDER BY seq DESC LIMIT ?) ORDER BY seq", REPLAYED_LINES).toArray(); void writer.write(sse("status", this.status())); for (const line of recent) void writer.write(sse("log", line)); this.#watchers.add(writer); writer.closed.catch(() => undefined).finally(() => this.#watchers.delete(writer)); return new Response(readable, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } }); } #openSecrets(job: string): Promise { const { meta, pipeline } = this.#load(); const definition = pipeline.jobs.get(job); if (!definition) throw new Error(`No job named ${job}.`); return openJobSecrets(this.env.DB, this.env.CI_SECRETS_KEY, { repoId: meta.repoId, namespaceId: meta.namespaceId, environment: definition.environment, access: meta.trust.secrets, approved: this.#meta(`approved:${job}`) !== null, names: definition.secrets, }); } #load(): Loaded { if (this.#loaded) return this.#loaded; const meta = this.#meta("meta"); const config = this.#meta("config"); if (!meta || !config) throw new RunNotFound(); const pipeline = parseValid(config); const checked = JobGraph.check(pipeline.jobs); if ("problems" in checked) throw new Error("The stored pipeline has a job graph problem."); const records = this.ctx.storage.sql.exec("SELECT name, state, reason FROM jobs").toArray(); this.#loaded = { meta: JSON.parse(meta) as RunMeta, pipeline, run: new Run(checked.graph, records) }; return this.#loaded; } #meta(key: string): string | null { return this.ctx.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", key).toArray()[0]?.value ?? null; } #save(): void { const { run } = this.#load(); for (const job of run.records()) this.ctx.storage.sql.exec("UPDATE jobs SET state = ?, reason = ? WHERE name = ?", job.state, job.reason, job.name); this.#broadcast(sse("status", this.status())); this.#mirror(); } /** Copies the run and job states to D1's ci_runs and ci_jobs, where lists read them. A failed copy is retried at the next save. */ #mirror(): void { const { meta, run } = this.#load(); const db = this.env.DB; const statements: D1PreparedStatement[] = []; const state = run.state; const runChanged = state !== this.#mirroredRun; if (runChanged) statements.push(db.prepare("UPDATE ci_runs SET state = ?, ended_at = COALESCE(ended_at, ?) WHERE id = ?").bind(state, TERMINAL_RUN.includes(state) ? Date.now() : null, meta.runId)); const changedJobs: string[] = []; for (const row of this.ctx.storage.sql.exec("SELECT * FROM jobs").toArray()) { const signature = JSON.stringify(row); if (this.#mirroredJobs.get(row.name) === signature) continue; changedJobs.push(row.name); this.#mirroredJobs.set(row.name, signature); statements.push(db.prepare("UPDATE ci_jobs SET state = ?, reason = ?, exit_code = ?, failed_step = ?, started_at = ?, ended_at = ? WHERE run_id = ? AND name = ?").bind(row.state, row.reason, row.exit_code, row.failed_step, row.started_at, row.ended_at, meta.runId, row.name)); } if (!statements.length) return; this.#mirroredRun = state; this.ctx.waitUntil( db.batch(statements).then( () => undefined, (error: unknown) => { if (runChanged) this.#mirroredRun = null; for (const name of changedJobs) this.#mirroredJobs.delete(name); console.error(`CI mirror failed for ${meta.runId}`, error); }, ), ); } #flushMasker(job: string): void { const masker = this.#maskers.get(job); if (!masker) return; this.#maskers.delete(job); const rest = masker.flush(); if (rest) this.#store(job, -1, rest); } #store(job: string, step: number, text: string): void { if (!text) return; const at = Date.now(); const seq = this.ctx.storage.sql.exec<{ seq: number }>("INSERT INTO logs (job, step, at, text) VALUES (?, ?, ?, ?) RETURNING seq", job, step, at, text).one().seq; this.#broadcast(sse("log", { seq, job, step, at, text } satisfies LogLine)); } #broadcast(event: Uint8Array): void { for (const writer of this.#watchers) writer.write(event).catch(() => this.#watchers.delete(writer)); } } function parseValid(config: string): Pipeline { const result = parsePipeline(config); if (result.kind === "invalid") throw new Error(`The pipeline is invalid: ${result.problems.map((problem) => problem.message).join(" ")}`); return result.pipeline; } function sse(event: string, data: unknown): Uint8Array { return new TextEncoder().encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); }