192 lines · 6.6 KB
import { env } from "cloudflare:workers";
import { first } from "../db";
import { repoDb, stmt } from "../scoped-db";
import { registerLocators, type LocatorKind } from "../scoped-db/locators";
import { scopedId } from "../scoped-db/ids";
import { rememberScope, runDb } from "./scope";
import type { CompiledJob, CompileInput } from "./compile";
import type { Trigger } from "./triggers";
import type { RepoRow } from "~/lib/types";

export async function allocateRunNumber(repoId: string): Promise<number> {
  const row = await first<{ run_number: number }>(
    "UPDATE repos SET next_run_number = next_run_number + 1 WHERE id = ? RETURNING next_run_number - 1 AS run_number",
    repoId,
  );
  if (!row) throw new Error("Repository disappeared while scheduling workflows");
  return row.run_number;
}

export type RunInsert = {
  repo: RepoRow;
  trigger: Trigger;
  path: string;
  workflowName: string;
  runId: string;
  runNumber: number;
  jobs: CompiledJob[];
  error: string | null;
  approvalRequired: boolean;
  source: string | null;
  context: CompileInput | null;
  rerunOf: string | null;
};

/** Returns the generated job ids keyed by job key. */
export async function insertRun(input: RunInsert): Promise<Map<string, string>> {
  const now = Date.now();
  const { repo, trigger } = input;
  const statements = [
    stmt(