import { matchesAny } from "../config/branch-pattern.ts"; import { CONFIG_PATH, parsePipeline } from "../config/parse-pipeline.ts"; import type { ConfigProblem, Pipeline } from "../config/pipeline.ts"; import type { EnvironmentRules } from "../runs/environment-gate.ts"; import { decideTrust, type RunSource } from "../runs/trust.ts"; import type { CiEnv } from "./ci-env.ts"; import type { RunMeta } from "./run-hub.ts"; import { configHash, jobRunnerName, runIdFor } from "./run-id.ts"; export interface RunRequest { readonly repoId: string; readonly namespaceId: string; /** The Artifacts repository name. */ readonly repo: string; readonly sha: string; readonly ref: string; readonly source: RunSource; readonly actorId: string | null; } export type StartResult = | { readonly kind: "started" | "exists"; readonly runId: string } | { readonly kind: "no_config" } | { readonly kind: "invalid"; readonly problems: readonly ConfigProblem[] } | { readonly kind: "not_triggered"; readonly reason: string }; /** * Starts one run for one commit (D2): read the pipeline at that commit, check that the source triggers it, decide * trust, create the RunHub and the Workflow instance. Starting the same commit, config and source again starts nothing. */ export async function startRun(env: CiEnv, request: RunRequest): Promise { using handle = await env.ARTIFACTS.get(request.repo); const file = await handle.readFile({ ref: request.sha, path: CONFIG_PATH }); if (!file) return { kind: "no_config" }; const config = await file.text(); const parsed = parsePipeline(config); if (parsed.kind === "invalid") return { kind: "invalid", problems: parsed.problems }; const { source } = request; const refused = notTriggered(parsed.pipeline, source); if (refused) return { kind: "not_triggered", reason: refused }; const [protectedBranches, environments] = await Promise.all([protectedBranchesOf(env.DB, request.repoId), environmentsOf(env.DB, request.repoId, parsed.pipeline)]); const trust = decideTrust(source, protectedBranches); const variant = source.kind === "pull_request" ? `pr${source.number}` : source.kind === "manual" ? `m${Date.now().toString(36)}` : ""; const runId = await runIdFor(request.repo, request.sha, config, variant); const branch = source.kind === "push" ? source.branch : source.kind === "pull_request" ? source.head : request.ref.startsWith("refs/heads/") ? request.ref.slice("refs/heads/".length) : null; const pull = source.kind === "pull_request" ? source.number : null; const meta: RunMeta = { runId, repoId: request.repoId, namespaceId: request.namespaceId, repo: request.repo, sha: request.sha, ref: request.ref, branch, pull, trigger: source.kind, trust, environments, createdAt: Date.now() }; const hub = env.RUN_HUB.getByName(runId); if ((await hub.init(meta, config)) === "exists") return { kind: "exists", runId }; const actorKind = source.kind === "push" ? source.pusher : source.kind === "pull_request" ? source.author : "human"; await env.DB.batch([ env.DB.prepare("INSERT INTO ci_runs (id, repo_id, sha, ref, trigger, actor_kind, actor_id, trust, secrets, trust_reason, state, config_hash, pull_number, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?) ON CONFLICT (id) DO NOTHING") .bind(runId, request.repoId, request.sha, request.ref, source.kind, actorKind, request.actorId, trust.trust, trust.secrets, trust.reason, await configHash(config), pull, meta.createdAt), ...[...parsed.pipeline.jobs.values()].map((job) => env.DB.prepare("INSERT INTO ci_jobs (run_id, name, image, size, environment, state) VALUES (?, ?, ?, ?, ?, 'pending') ON CONFLICT DO NOTHING").bind(runId, job.name, job.image.version ? `${job.image.name}@${job.image.version}` : job.image.name, job.size, job.environment), ), ]); await env.RUNS.create({ id: runId, params: { runId } }); if (source.kind !== "manual") await supersede(env, request.repoId, request.ref, source.kind, pull, runId, meta.createdAt); return { kind: "started", runId }; } function notTriggered(pipeline: Pipeline, source: RunSource): string | null { const { triggers } = pipeline; switch (source.kind) { case "manual": return triggers.manual ? null : `The pipeline does not allow manual runs. Add manual under on in ${CONFIG_PATH}.`; case "push": return triggers.push && matchesAny(triggers.push.branches, source.branch) ? null : `The pipeline does not run on pushes to ${source.branch}.`; case "pull_request": return triggers.pullRequest && matchesAny(triggers.pullRequest.branches, source.base) ? null : `The pipeline does not run on pull requests into ${source.base}.`; } } /** A newer run of the same branch push, or of the same pull request, cancels the older ones that have not ended. */ async function supersede(env: CiEnv, repoId: string, ref: string, trigger: "push" | "pull_request", pull: number | null, newer: string, createdAt: number): Promise { const { results } = await env.DB.prepare("SELECT id FROM ci_runs WHERE repo_id = ? AND ref = ? AND trigger = ? AND coalesce(pull_number, 0) = ? AND id != ? AND created_at < ? AND ended_at IS NULL") .bind(repoId, ref, trigger, pull ?? 0, newer, createdAt) .all<{ id: string }>(); for (const { id } of results) { try { await cancelRun(env, id, `A newer push to ${ref} replaced this run.`); await env.DB.prepare("UPDATE ci_runs SET superseded_by = ? WHERE id = ?").bind(newer, id).run(); } catch (error) { console.error(`could not supersede run ${id}`, error); } } } async function protectedBranchesOf(db: D1Database, repoId: string): Promise { const { results } = await db.prepare("SELECT pattern FROM ci_protected_branches WHERE repo_id = ?").bind(repoId).all<{ pattern: string }>(); return results.map((row) => row.pattern); } /** The rules of each environment the pipeline names, as they are when the run starts. A missing environment is null. */ async function environmentsOf(db: D1Database, repoId: string, pipeline: Pipeline): Promise> { const names = [...new Set([...pipeline.jobs.values()].flatMap((job) => (job.environment ? [job.environment] : [])))]; if (!names.length) return {}; const { results } = await db .prepare("SELECT e.name, e.requires_approval, e.wait_seconds, (SELECT json_group_array(pattern) FROM ci_environment_branches b WHERE b.repo_id = e.repo_id AND b.environment = e.name) AS branches FROM ci_environments e WHERE e.repo_id = ? AND e.name IN (SELECT value FROM json_each(?))") .bind(repoId, JSON.stringify(names)) .all<{ name: string; requires_approval: number; wait_seconds: number; branches: string }>(); const found = new Map(results.map((row) => [row.name, { name: row.name, requiresApproval: row.requires_approval === 1, waitSeconds: row.wait_seconds, allowedBranches: JSON.parse(row.branches) as string[] }])); return Object.fromEntries(names.map((name) => [name, found.get(name) ?? null])); } /** * Cancels a run and stops what still runs. With jobs live, the runners stop their containers and the Workflow ends on * its own. With none, the Workflow may wait for an approval that will not come, so it is ended. */ export async function cancelRun(env: CiEnv, runId: string, reason: string): Promise { const live = await env.RUN_HUB.getByName(runId).cancel(reason); if (live.length) { await Promise.all(live.map((job) => env.JOB_RUNNER.getByName(jobRunnerName(runId, job)).cancel())); return; } const instance = await env.RUNS.get(runId).catch(() => null); await instance?.terminate().catch(() => undefined); }