358 lines · 16.1 KBRaw
| 1 | import { DurableObject } from "cloudflare:workers"; |
| 2 | import { JobGraph } from "../config/job-graph.ts"; |
| 3 | import { parsePipeline } from "../config/parse-pipeline.ts"; |
| 4 | import type { Pipeline } from "../config/pipeline.ts"; |
| 5 | import { LogMasker } from "../logs/log-masker.ts"; |
| 6 | import { gateEnvironment, type EnvironmentRules } from "../runs/environment-gate.ts"; |
| 7 | import { Run, type Advance, type JobRecord } from "../runs/run.ts"; |
| 8 | import type { JobState, RunState } from "../runs/states.ts"; |
| 9 | import type { TrustDecision } from "../runs/trust.ts"; |
| 10 | import { openJobSecrets, type OpenedSecrets } from "../secrets/job-secrets.ts"; |
| 11 | import type { CiEnv } from "./ci-env.ts"; |
| 12 | import type { JobResult, JobSpec } from "./job-spec.ts"; |
| 13 | |
| 14 | const TERMINAL_RUN: readonly RunState[] = ["succeeded", "failed", "cancelled", "timed_out"]; |
| 15 | |
| 16 | export interface RunMeta { |
| 17 | readonly runId: string; |
| 18 | readonly repoId: string; |
| 19 | readonly namespaceId: string; |
| 20 | /** The Artifacts repository name. */ |
| 21 | readonly repo: string; |
| 22 | readonly sha: string; |
| 23 | readonly ref: string; |
| 24 | /** The branch that environment rules check: the pushed branch or the pull request's head. Null for a tag. */ |
| 25 | readonly branch: string | null; |
| 26 | readonly pull: number | null; |
| 27 | readonly trigger: "push" | "pull_request" | "manual"; |
| 28 | readonly trust: TrustDecision; |
| 29 | /** The rules of each environment the pipeline names, as they were when the run started. */ |
| 30 | readonly environments: Readonly<Record<string, EnvironmentRules | null>>; |
| 31 | readonly createdAt: number; |
| 32 | } |
| 33 | |
| 34 | export interface JobView extends JobRecord { |
| 35 | readonly environment: string | null; |
| 36 | readonly image: string; |
| 37 | readonly steps: readonly string[]; |
| 38 | readonly exitCode: number | null; |
| 39 | readonly failedStep: number | null; |
| 40 | readonly startedAt: number | null; |
| 41 | readonly endedAt: number | null; |
| 42 | } |
| 43 | |
| 44 | export interface RunStatus { |
| 45 | readonly meta: RunMeta; |
| 46 | readonly state: RunState; |
| 47 | readonly jobs: readonly JobView[]; |
| 48 | } |
| 49 | |
| 50 | export type LogLine = { |
| 51 | readonly seq: number; |
| 52 | readonly job: string; |
| 53 | readonly step: number; |
| 54 | readonly at: number; |
| 55 | readonly text: string; |
| 56 | }; |
| 57 | |
| 58 | /** One step's output. Step 0 sets the job up: secrets and the checkout. Times are in milliseconds. */ |
| 59 | export interface StepLog { |
| 60 | readonly step: number; |
| 61 | readonly text: string; |
| 62 | readonly startedAt: number | null; |
| 63 | readonly endedAt: number | null; |
| 64 | } |
| 65 | |
| 66 | export class RunNotFound extends Error { |
| 67 | constructor() { |
| 68 | super("This run does not exist."); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | const REPLAYED_LINES = 2000; |
| 73 | |
| 74 | interface Loaded { |
| 75 | readonly meta: RunMeta; |
| 76 | readonly pipeline: Pipeline; |
| 77 | readonly run: Run; |
| 78 | } |
| 79 | |
| 80 | 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 }; |
| 81 | |
| 82 | /** |
| 83 | * One run's state and logs (D4). It is the only writer of both: the Workflow, the job runners and the backend all |
| 84 | * call it, and it saves after each change. It masks job output with the job's secrets before it stores or sends a line. |
| 85 | */ |
| 86 | export class RunHub extends DurableObject<CiEnv> { |
| 87 | #loaded: Loaded | null = null; |
| 88 | #mirroredRun: RunState | null = null; |
| 89 | readonly #mirroredJobs = new Map<string, string>(); |
| 90 | readonly #maskers = new Map<string, LogMasker>(); |
| 91 | readonly #watchers = new Set<WritableStreamDefaultWriter<Uint8Array>>(); |
| 92 | |
| 93 | constructor(ctx: DurableObjectState, env: CiEnv) { |
| 94 | super(ctx, env); |
| 95 | ctx.blockConcurrencyWhile(async () => { |
| 96 | ctx.storage.sql.exec(` |
| 97 | CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); |
| 98 | 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); |
| 99 | 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); |
| 100 | CREATE TABLE IF NOT EXISTS steps (job TEXT NOT NULL, step INTEGER NOT NULL, started_at INTEGER NOT NULL, PRIMARY KEY (job, step)); |
| 101 | `); |
| 102 | }); |
| 103 | } |
| 104 | |
| 105 | init(meta: RunMeta, config: string): "created" | "exists" { |
| 106 | if (this.#meta("meta")) return "exists"; |
| 107 | const pipeline = parseValid(config); |
| 108 | const sql = this.ctx.storage.sql; |
| 109 | sql.exec("INSERT INTO meta (key, value) VALUES ('meta', ?), ('config', ?)", JSON.stringify(meta), config); |
| 110 | for (const name of pipeline.jobs.keys()) sql.exec("INSERT INTO jobs (name, state) VALUES (?, 'pending')", name); |
| 111 | return "created"; |
| 112 | } |
| 113 | |
| 114 | /** |
| 115 | * Moves the run on, and returns the jobs to start: the ones it queued now, and queued jobs that a person approved. |
| 116 | * Only the Workflow calls it, and only when no job is in flight, so a queued job here has not started. |
| 117 | */ |
| 118 | advance(): Advance { |
| 119 | const { meta, pipeline, run } = this.#load(); |
| 120 | const advance = run.advance((job) => { |
| 121 | const environment = pipeline.jobs.get(job)?.environment; |
| 122 | return environment ? gateEnvironment(environment, meta.environments[environment] ?? null, { branch: meta.branch, trust: meta.trust.trust }) : null; |
| 123 | }); |
| 124 | this.#save(); |
| 125 | const approved = run.records().filter((job) => job.state === "queued" && !advance.start.some((entry) => entry.job === job.name)); |
| 126 | return { ...advance, start: [...advance.start, ...approved.map((job) => ({ job: job.name, waitSeconds: 0 }))] }; |
| 127 | } |
| 128 | |
| 129 | spec(job: string): JobSpec { |
| 130 | const { meta, pipeline } = this.#load(); |
| 131 | const definition = pipeline.jobs.get(job); |
| 132 | if (!definition) throw new Error(`No job named ${job}.`); |
| 133 | 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 }; |
| 134 | } |
| 135 | |
| 136 | /** Opens the secrets the job names and starts masking them in its output. Only the job's runner calls it. */ |
| 137 | async secrets(job: string): Promise<OpenedSecrets> { |
| 138 | const opened = await this.#openSecrets(job); |
| 139 | this.#maskers.set(job, new LogMasker(Object.values(opened.values))); |
| 140 | return opened; |
| 141 | } |
| 142 | |
| 143 | /** Marks the job running. Returns false when it ended before its container came up, such as after a cancel. */ |
| 144 | started(job: string): boolean { |
| 145 | const applied = this.#load().run.started(job) === "applied"; |
| 146 | if (applied) this.ctx.storage.sql.exec("UPDATE jobs SET started_at = ? WHERE name = ?", Date.now(), job); |
| 147 | this.#save(); |
| 148 | return applied; |
| 149 | } |
| 150 | |
| 151 | isQueued(job: string): boolean { |
| 152 | return this.#load().run.job(job).state === "queued"; |
| 153 | } |
| 154 | |
| 155 | record(job: string, result: JobResult): void { |
| 156 | const { run } = this.#load(); |
| 157 | this.#flushMasker(job); |
| 158 | const applied = result.outcome === "cancelled" ? run.finished(job, "failed", result.reason) : run.finished(job, result.outcome, result.reason); |
| 159 | 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); |
| 160 | this.#save(); |
| 161 | } |
| 162 | |
| 163 | decide(job: string, decision: "approved" | "rejected", by: { readonly id: string; readonly name: string }): void { |
| 164 | const { meta, run } = this.#load(); |
| 165 | if (decision === "approved") { |
| 166 | run.approve(job, by.name); |
| 167 | this.ctx.storage.sql.exec("INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)", `approved:${job}`, by.id); |
| 168 | } else run.reject(job, by.name); |
| 169 | this.#save(); |
| 170 | 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(); |
| 171 | this.ctx.waitUntil(audit.then(() => undefined, (error: unknown) => console.error(`ci_approvals write failed for ${meta.runId}`, error))); |
| 172 | } |
| 173 | |
| 174 | /** Cancels the run. Returns the jobs that have a container, so the caller can stop them. */ |
| 175 | cancel(reason: string): readonly string[] { |
| 176 | const live = this.#load().run.cancel(reason); |
| 177 | this.#save(); |
| 178 | return live; |
| 179 | } |
| 180 | |
| 181 | awaitingApproval(): readonly string[] { |
| 182 | return this.#load().run.records().filter((job) => job.state === "waiting_approval").map((job) => job.name); |
| 183 | } |
| 184 | |
| 185 | state(): RunState { |
| 186 | return this.#load().run.state; |
| 187 | } |
| 188 | |
| 189 | status(): RunStatus { |
| 190 | const { meta, pipeline, run } = this.#load(); |
| 191 | const rows = new Map(this.ctx.storage.sql.exec<JobRow>("SELECT * FROM jobs").toArray().map((row) => [row.name, row])); |
| 192 | const jobs = run.records().map((record) => { |
| 193 | const row = rows.get(record.name); |
| 194 | const definition = pipeline.jobs.get(record.name); |
| 195 | return { |
| 196 | ...record, |
| 197 | environment: definition?.environment ?? null, |
| 198 | image: definition?.image.name ?? "base", |
| 199 | steps: definition?.steps.map((step) => step.name) ?? [], |
| 200 | exitCode: row?.exit_code ?? null, |
| 201 | failedStep: row?.failed_step ?? null, |
| 202 | startedAt: row?.started_at ?? null, |
| 203 | endedAt: row?.ended_at ?? null, |
| 204 | }; |
| 205 | }); |
| 206 | return { meta, state: run.state, jobs }; |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Job runners send output in order, one batch at a time, so a masker rebuilt after an eviction sees no race. When the |
| 211 | * secrets cannot be opened again, the batch is refused and dropped rather than stored unmasked. |
| 212 | */ |
| 213 | async append(job: string, step: number, text: string): Promise<void> { |
| 214 | let masker = this.#maskers.get(job); |
| 215 | if (!masker) { |
| 216 | masker = new LogMasker(Object.values((await this.#openSecrets(job)).values)); |
| 217 | this.#maskers.set(job, masker); |
| 218 | } |
| 219 | this.#store(job, step, masker.push(text)); |
| 220 | } |
| 221 | |
| 222 | /** Records the time a step of a job starts, so a step that prints nothing still has a start and an end. */ |
| 223 | stepStarted(job: string, step: number): void { |
| 224 | const at = Date.now(); |
| 225 | this.ctx.storage.sql.exec("INSERT OR IGNORE INTO steps (job, step, started_at) VALUES (?, ?, ?)", job, step, at); |
| 226 | this.#broadcast(sse("step", { job, step, at })); |
| 227 | } |
| 228 | |
| 229 | /** |
| 230 | * The stored output of one job, split by step, and the sequence number of the last line in the whole run, so a |
| 231 | * reader of the event stream can skip what it has. A step ends when the next one starts, or when the job ends. |
| 232 | */ |
| 233 | logs(job: string): { readonly steps: readonly StepLog[]; readonly seq: number } { |
| 234 | const sql = this.ctx.storage.sql; |
| 235 | const steps = new Map<number, { step: number; text: string; startedAt: number | null; endedAt: number | null }>(); |
| 236 | const entry = (step: number) => steps.get(step) ?? steps.set(step, { step, text: "", startedAt: null, endedAt: null }).get(step)!; |
| 237 | 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; |
| 238 | let last = 0; |
| 239 | for (const row of sql.exec<{ step: number; text: string }>("SELECT step, text FROM logs WHERE job = ? ORDER BY seq", job)) { |
| 240 | last = row.step < 0 ? last : row.step; |
| 241 | entry(last).text += row.text; |
| 242 | } |
| 243 | const ordered = [...steps.values()].sort((a, b) => a.step - b.step); |
| 244 | const jobEnd = sql.exec<{ ended_at: number | null }>("SELECT ended_at FROM jobs WHERE name = ?", job).toArray()[0]?.ended_at ?? null; |
| 245 | ordered.forEach((step, index) => (step.endedAt = ordered[index + 1]?.startedAt ?? jobEnd)); |
| 246 | return { steps: ordered, seq: sql.exec<{ seq: number | null }>("SELECT max(seq) AS seq FROM logs").one().seq ?? 0 }; |
| 247 | } |
| 248 | |
| 249 | async fetch(request: Request): Promise<Response> { |
| 250 | if (new URL(request.url).pathname !== "/events") return new Response("Not found\n", { status: 404 }); |
| 251 | this.#load(); |
| 252 | const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>(); |
| 253 | const writer = writable.getWriter(); |
| 254 | const recent = this.ctx.storage.sql.exec<LogLine>("SELECT * FROM (SELECT * FROM logs ORDER BY seq DESC LIMIT ?) ORDER BY seq", REPLAYED_LINES).toArray(); |
| 255 | void writer.write(sse("status", this.status())); |
| 256 | for (const line of recent) void writer.write(sse("log", line)); |
| 257 | this.#watchers.add(writer); |
| 258 | writer.closed.catch(() => undefined).finally(() => this.#watchers.delete(writer)); |
| 259 | return new Response(readable, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } }); |
| 260 | } |
| 261 | |
| 262 | #openSecrets(job: string): Promise<OpenedSecrets> { |
| 263 | const { meta, pipeline } = this.#load(); |
| 264 | const definition = pipeline.jobs.get(job); |
| 265 | if (!definition) throw new Error(`No job named ${job}.`); |
| 266 | return openJobSecrets(this.env.DB, this.env.CI_SECRETS_KEY, { |
| 267 | repoId: meta.repoId, |
| 268 | namespaceId: meta.namespaceId, |
| 269 | environment: definition.environment, |
| 270 | access: meta.trust.secrets, |
| 271 | approved: this.#meta(`approved:${job}`) !== null, |
| 272 | names: definition.secrets, |
| 273 | }); |
| 274 | } |
| 275 | |
| 276 | #load(): Loaded { |
| 277 | if (this.#loaded) return this.#loaded; |
| 278 | const meta = this.#meta("meta"); |
| 279 | const config = this.#meta("config"); |
| 280 | if (!meta || !config) throw new RunNotFound(); |
| 281 | const pipeline = parseValid(config); |
| 282 | const checked = JobGraph.check(pipeline.jobs); |
| 283 | if ("problems" in checked) throw new Error("The stored pipeline has a job graph problem."); |
| 284 | const records = this.ctx.storage.sql.exec<JobRow>("SELECT name, state, reason FROM jobs").toArray(); |
| 285 | this.#loaded = { meta: JSON.parse(meta) as RunMeta, pipeline, run: new Run(checked.graph, records) }; |
| 286 | return this.#loaded; |
| 287 | } |
| 288 | |
| 289 | #meta(key: string): string | null { |
| 290 | return this.ctx.storage.sql.exec<{ value: string }>("SELECT value FROM meta WHERE key = ?", key).toArray()[0]?.value ?? null; |
| 291 | } |
| 292 | |
| 293 | #save(): void { |
| 294 | const { run } = this.#load(); |
| 295 | for (const job of run.records()) this.ctx.storage.sql.exec("UPDATE jobs SET state = ?, reason = ? WHERE name = ?", job.state, job.reason, job.name); |
| 296 | this.#broadcast(sse("status", this.status())); |
| 297 | this.#mirror(); |
| 298 | } |
| 299 | |
| 300 | /** 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. */ |
| 301 | #mirror(): void { |
| 302 | const { meta, run } = this.#load(); |
| 303 | const db = this.env.DB; |
| 304 | const statements: D1PreparedStatement[] = []; |
| 305 | const state = run.state; |
| 306 | const runChanged = state !== this.#mirroredRun; |
| 307 | 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)); |
| 308 | const changedJobs: string[] = []; |
| 309 | for (const row of this.ctx.storage.sql.exec<JobRow>("SELECT * FROM jobs").toArray()) { |
| 310 | const signature = JSON.stringify(row); |
| 311 | if (this.#mirroredJobs.get(row.name) === signature) continue; |
| 312 | changedJobs.push(row.name); |
| 313 | this.#mirroredJobs.set(row.name, signature); |
| 314 | 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)); |
| 315 | } |
| 316 | if (!statements.length) return; |
| 317 | this.#mirroredRun = state; |
| 318 | this.ctx.waitUntil( |
| 319 | db.batch(statements).then( |
| 320 | () => undefined, |
| 321 | (error: unknown) => { |
| 322 | if (runChanged) this.#mirroredRun = null; |
| 323 | for (const name of changedJobs) this.#mirroredJobs.delete(name); |
| 324 | console.error(`CI mirror failed for ${meta.runId}`, error); |
| 325 | }, |
| 326 | ), |
| 327 | ); |
| 328 | } |
| 329 | |
| 330 | #flushMasker(job: string): void { |
| 331 | const masker = this.#maskers.get(job); |
| 332 | if (!masker) return; |
| 333 | this.#maskers.delete(job); |
| 334 | const rest = masker.flush(); |
| 335 | if (rest) this.#store(job, -1, rest); |
| 336 | } |
| 337 | |
| 338 | #store(job: string, step: number, text: string): void { |
| 339 | if (!text) return; |
| 340 | const at = Date.now(); |
| 341 | 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; |
| 342 | this.#broadcast(sse("log", { seq, job, step, at, text } satisfies LogLine)); |
| 343 | } |
| 344 | |
| 345 | #broadcast(event: Uint8Array): void { |
| 346 | for (const writer of this.#watchers) writer.write(event).catch(() => this.#watchers.delete(writer)); |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | function parseValid(config: string): Pipeline { |
| 351 | const result = parsePipeline(config); |
| 352 | if (result.kind === "invalid") throw new Error(`The pipeline is invalid: ${result.problems.map((problem) => problem.message).join(" ")}`); |
| 353 | return result.pipeline; |
| 354 | } |
| 355 | |
| 356 | function sse(event: string, data: unknown): Uint8Array { |
| 357 | return new TextEncoder().encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`); |
| 358 | } |