import { first, run } from "../db";
import { loadPull } from "../pulls";
import type { RepoRow } from "~/lib/types";
import type { WorkflowRunRow } from "../ci/jobs";
import { notifyQuietly } from "./deliver";
import { repoWatchers } from "./recipients";
const FAILED = new Set(["failure", "timed_out", "startup_failure"]);
/**
* Failure notices go to the actor, the PR author for PR runs and (by the "ci_watching" pref) watchers;
* a success right after a failure on the same workflow and ref sends a "fixed" notice to the same people.
*/
export async function notifyRunCompleted(repo: RepoRow, runRow: WorkflowRunRow, conclusion: string): Promise<void> {
const previous = await first<{ conclusion: string }>(
"SELECT conclusion FROM ci_notify_state WHERE repo_id = ? AND workflow_path = ? AND ref = ?",
repo.id,
runRow.workflow_path,
runRow.ref,
);
await run(
`INSERT INTO ci_notify_state (repo_id, workflow_path, ref, conclusion, updated_at) VALUES (?, ?, ?, ?, ?)
ON CONFLICT (repo_id, workflow_path, ref) DO UPDATE SET conclusion = excluded.conclusion, updated_at = excluded.updated_at`,
repo.id,
runRow.workflow_path,
runRow.ref,
conclusion,
Date.now(),
);
const failed = FAILED.has(conclusion);
const fixed = conclusion === "success" && previous !== null && FAILED.has(previous.conclusion);
if (!failed && !fixed) return;
const pull = runRow.pr_number ? await loadPull(repo.id, runRow.pr_number) : null;
const branch = runRow.ref.replace(/^refs\/(heads|tags)\//, "");
const where = pull ? `#${pull.number}` : branch;
const title = failed
? `${runRow.workflow_name} failed on ${where} in ${repo.owner_name}/${repo.name}`
: `${runRow.workflow_name} fixed on ${where} in ${repo.owner_name}/${repo.name}`;
const details = [