120 lines · 7.5 KBRaw
| 1 | import { matchesAny } from "../config/branch-pattern.ts"; |
| 2 | import { CONFIG_PATH, parsePipeline } from "../config/parse-pipeline.ts"; |
| 3 | import type { ConfigProblem, Pipeline } from "../config/pipeline.ts"; |
| 4 | import type { EnvironmentRules } from "../runs/environment-gate.ts"; |
| 5 | import { decideTrust, type RunSource } from "../runs/trust.ts"; |
| 6 | import type { CiEnv } from "./ci-env.ts"; |
| 7 | import type { RunMeta } from "./run-hub.ts"; |
| 8 | import { configHash, jobRunnerName, runIdFor } from "./run-id.ts"; |
| 9 | |
| 10 | export interface RunRequest { |
| 11 | readonly repoId: string; |
| 12 | readonly namespaceId: string; |
| 13 | /** The Artifacts repository name. */ |
| 14 | readonly repo: string; |
| 15 | readonly sha: string; |
| 16 | readonly ref: string; |
| 17 | readonly source: RunSource; |
| 18 | readonly actorId: string | null; |
| 19 | } |
| 20 | |
| 21 | export type StartResult = |
| 22 | | { readonly kind: "started" | "exists"; readonly runId: string } |
| 23 | | { readonly kind: "no_config" } |
| 24 | | { readonly kind: "invalid"; readonly problems: readonly ConfigProblem[] } |
| 25 | | { readonly kind: "not_triggered"; readonly reason: string }; |
| 26 | |
| 27 | /** |
| 28 | * Starts one run for one commit (D2): read the pipeline at that commit, check that the source triggers it, decide |
| 29 | * trust, create the RunHub and the Workflow instance. Starting the same commit, config and source again starts nothing. |
| 30 | */ |
| 31 | export async function startRun(env: CiEnv, request: RunRequest): Promise<StartResult> { |
| 32 | using handle = await env.ARTIFACTS.get(request.repo); |
| 33 | const file = await handle.readFile({ ref: request.sha, path: CONFIG_PATH }); |
| 34 | if (!file) return { kind: "no_config" }; |
| 35 | const config = await file.text(); |
| 36 | const parsed = parsePipeline(config); |
| 37 | if (parsed.kind === "invalid") return { kind: "invalid", problems: parsed.problems }; |
| 38 | const { source } = request; |
| 39 | const refused = notTriggered(parsed.pipeline, source); |
| 40 | if (refused) return { kind: "not_triggered", reason: refused }; |
| 41 | |
| 42 | const [protectedBranches, environments] = await Promise.all([protectedBranchesOf(env.DB, request.repoId), environmentsOf(env.DB, request.repoId, parsed.pipeline)]); |
| 43 | const trust = decideTrust(source, protectedBranches); |
| 44 | const variant = source.kind === "pull_request" ? `pr${source.number}` : source.kind === "manual" ? `m${Date.now().toString(36)}` : ""; |
| 45 | const runId = await runIdFor(request.repo, request.sha, config, variant); |
| 46 | 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; |
| 47 | const pull = source.kind === "pull_request" ? source.number : null; |
| 48 | 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() }; |
| 49 | const hub = env.RUN_HUB.getByName(runId); |
| 50 | if ((await hub.init(meta, config)) === "exists") return { kind: "exists", runId }; |
| 51 | const actorKind = source.kind === "push" ? source.pusher : source.kind === "pull_request" ? source.author : "human"; |
| 52 | await env.DB.batch([ |
| 53 | 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") |
| 54 | .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), |
| 55 | ...[...parsed.pipeline.jobs.values()].map((job) => |
| 56 | 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), |
| 57 | ), |
| 58 | ]); |
| 59 | await env.RUNS.create({ id: runId, params: { runId } }); |
| 60 | if (source.kind !== "manual") await supersede(env, request.repoId, request.ref, source.kind, pull, runId, meta.createdAt); |
| 61 | return { kind: "started", runId }; |
| 62 | } |
| 63 | |
| 64 | function notTriggered(pipeline: Pipeline, source: RunSource): string | null { |
| 65 | const { triggers } = pipeline; |
| 66 | switch (source.kind) { |
| 67 | case "manual": |
| 68 | return triggers.manual ? null : `The pipeline does not allow manual runs. Add manual under on in ${CONFIG_PATH}.`; |
| 69 | case "push": |
| 70 | return triggers.push && matchesAny(triggers.push.branches, source.branch) ? null : `The pipeline does not run on pushes to ${source.branch}.`; |
| 71 | case "pull_request": |
| 72 | return triggers.pullRequest && matchesAny(triggers.pullRequest.branches, source.base) ? null : `The pipeline does not run on pull requests into ${source.base}.`; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /** A newer run of the same branch push, or of the same pull request, cancels the older ones that have not ended. */ |
| 77 | async function supersede(env: CiEnv, repoId: string, ref: string, trigger: "push" | "pull_request", pull: number | null, newer: string, createdAt: number): Promise<void> { |
| 78 | 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") |
| 79 | .bind(repoId, ref, trigger, pull ?? 0, newer, createdAt) |
| 80 | .all<{ id: string }>(); |
| 81 | for (const { id } of results) { |
| 82 | try { |
| 83 | await cancelRun(env, id, `A newer push to ${ref} replaced this run.`); |
| 84 | await env.DB.prepare("UPDATE ci_runs SET superseded_by = ? WHERE id = ?").bind(newer, id).run(); |
| 85 | } catch (error) { |
| 86 | console.error(`could not supersede run ${id}`, error); |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | async function protectedBranchesOf(db: D1Database, repoId: string): Promise<string[]> { |
| 92 | const { results } = await db.prepare("SELECT pattern FROM ci_protected_branches WHERE repo_id = ?").bind(repoId).all<{ pattern: string }>(); |
| 93 | return results.map((row) => row.pattern); |
| 94 | } |
| 95 | |
| 96 | /** The rules of each environment the pipeline names, as they are when the run starts. A missing environment is null. */ |
| 97 | async function environmentsOf(db: D1Database, repoId: string, pipeline: Pipeline): Promise<Record<string, EnvironmentRules | null>> { |
| 98 | const names = [...new Set([...pipeline.jobs.values()].flatMap((job) => (job.environment ? [job.environment] : [])))]; |
| 99 | if (!names.length) return {}; |
| 100 | const { results } = await db |
| 101 | .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(?))") |
| 102 | .bind(repoId, JSON.stringify(names)) |
| 103 | .all<{ name: string; requires_approval: number; wait_seconds: number; branches: string }>(); |
| 104 | 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[] }])); |
| 105 | return Object.fromEntries(names.map((name) => [name, found.get(name) ?? null])); |
| 106 | } |
| 107 | |
| 108 | /** |
| 109 | * Cancels a run and stops what still runs. With jobs live, the runners stop their containers and the Workflow ends on |
| 110 | * its own. With none, the Workflow may wait for an approval that will not come, so it is ended. |
| 111 | */ |
| 112 | export async function cancelRun(env: CiEnv, runId: string, reason: string): Promise<void> { |
| 113 | const live = await env.RUN_HUB.getByName(runId).cancel(reason); |
| 114 | if (live.length) { |
| 115 | await Promise.all(live.map((job) => env.JOB_RUNNER.getByName(jobRunnerName(runId, job)).cancel())); |
| 116 | return; |
| 117 | } |
| 118 | const instance = await env.RUNS.get(runId).catch(() => null); |
| 119 | await instance?.terminate().catch(() => undefined); |
| 120 | } |