Skip to content
refs
History
56 lines · 2.2 KBRaw
1export type JobState = "pending" | "waiting_image" | "waiting_approval" | "queued" | "running" | "succeeded" | "failed" | "skipped" | "cancelled" | "timed_out";
2
3export type RunState = "queued" | "waiting_image" | "running" | "waiting_approval" | "succeeded" | "failed" | "cancelled" | "timed_out";
4
5const MOVES: Readonly<Record<JobState, readonly JobState[]>> = {
6 pending: ["waiting_image", "waiting_approval", "queued", "skipped", "failed", "cancelled"],
7 waiting_image: ["pending", "failed", "cancelled"],
8 waiting_approval: ["queued", "cancelled"],
9 queued: ["running", "failed", "cancelled"],
10 running: ["succeeded", "failed", "cancelled", "timed_out"],
11 succeeded: [],
12 failed: [],
13 skipped: [],
14 cancelled: [],
15 timed_out: [],
16};
17
18export class InvalidJobTransition extends Error {
19 readonly job: string;
20 readonly from: JobState;
21 readonly to: JobState;
22
23 constructor(job: string, from: JobState, to: JobState) {
24 super(`Job "${job}" cannot move from ${from} to ${to}.`);
25 this.job = job;
26 this.from = from;
27 this.to = to;
28 }
29}
30
31export function isTerminal(state: JobState): boolean {
32 return MOVES[state].length === 0;
33}
34
35/** A finished job that makes the jobs which need it skip. */
36export function blocksDependents(state: JobState): boolean {
37 return state === "failed" || state === "skipped" || state === "cancelled" || state === "timed_out";
38}
39
40export function assertMove(job: string, from: JobState, to: JobState): void {
41 if (!MOVES[from].includes(to)) throw new InvalidJobTransition(job, from, to);
42}
43
44/** The run's state follows from its jobs. Nothing stores it apart from them, so the two cannot disagree. */
45export function runStateOf(states: readonly JobState[]): RunState {
46 if (states.every(isTerminal)) {
47 if (states.includes("failed")) return "failed";
48 if (states.includes("timed_out")) return "timed_out";
49 if (states.includes("cancelled")) return "cancelled";
50 return "succeeded";
51 }
52 if (states.some((state) => state === "running" || state === "queued")) return "running";
53 if (states.includes("waiting_approval")) return "waiting_approval";
54 if (states.includes("waiting_image")) return "waiting_image";
55 return states.every((state) => state === "pending") ? "queued" : "running";
56}