export type JobState = "pending" | "waiting_image" | "waiting_approval" | "queued" | "running" | "succeeded" | "failed" | "skipped" | "cancelled" | "timed_out"; export type RunState = "queued" | "waiting_image" | "running" | "waiting_approval" | "succeeded" | "failed" | "cancelled" | "timed_out"; const MOVES: Readonly> = { pending: ["waiting_image", "waiting_approval", "queued", "skipped", "failed", "cancelled"], waiting_image: ["pending", "failed", "cancelled"], waiting_approval: ["queued", "cancelled"], queued: ["running", "failed", "cancelled"], running: ["succeeded", "failed", "cancelled", "timed_out"], succeeded: [], failed: [], skipped: [], cancelled: [], timed_out: [], }; export class InvalidJobTransition extends Error { readonly job: string; readonly from: JobState; readonly to: JobState; constructor(job: string, from: JobState, to: JobState) { super(`Job "${job}" cannot move from ${from} to ${to}.`); this.job = job; this.from = from; this.to = to; } } export function isTerminal(state: JobState): boolean { return MOVES[state].length === 0; } /** A finished job that makes the jobs which need it skip. */ export function blocksDependents(state: JobState): boolean { return state === "failed" || state === "skipped" || state === "cancelled" || state === "timed_out"; } export function assertMove(job: string, from: JobState, to: JobState): void { if (!MOVES[from].includes(to)) throw new InvalidJobTransition(job, from, to); } /** The run's state follows from its jobs. Nothing stores it apart from them, so the two cannot disagree. */ export function runStateOf(states: readonly JobState[]): RunState { if (states.every(isTerminal)) { if (states.includes("failed")) return "failed"; if (states.includes("timed_out")) return "timed_out"; if (states.includes("cancelled")) return "cancelled"; return "succeeded"; } if (states.some((state) => state === "running" || state === "queued")) return "running"; if (states.includes("waiting_approval")) return "waiting_approval"; if (states.includes("waiting_image")) return "waiting_image"; return states.every((state) => state === "pending") ? "queued" : "running"; }