import { buffered, isObject, string, upstream, upstreamError, XrpcError } from "./xrpc"; export interface Commit { message: string; author?: { name: string; email: string }; } interface BuildInput extends Partial { commit: string; branch: string; repo: string; pipeline: string; workflow: string; cleanCheckout: boolean | undefined; baseBranch: string | undefined; inputs?: { key: string; value: string }[]; } interface Build { id?: string; number?: number; web_url?: string; } function build(body: unknown): Build { if (!isObject(body)) { return {}; } const { id, number, web_url: webUrl } = body; return { ...(typeof id === "string" ? { id } : {}), ...(typeof number === "number" ? { number } : {}), ...(typeof webUrl === "string" ? { web_url: webUrl } : {}), }; } export type RunStatus = | "started" | "running" | "blocked" | "success" | "failed" | "timeout" | "cancelled"; export function isTerminal(status: string): boolean { return ["success", "failed", "timeout", "cancelled"].includes(status); } export interface BuildState { id: string; number: number | undefined; url: string | undefined; status: RunStatus; startedAt: string | undefined; finishedAt: string | undefined; } const statuses = new Map([ ["scheduled", "started"], ["running", "running"], ["failing", "running"], ["blocked", "blocked"], ["passed", "success"], ["failed", "failed"], ["canceling", "cancelled"], ["canceled", "cancelled"], ["skipped", "cancelled"], ["not_run", "cancelled"], ]); export function time(value: unknown): string | undefined { const ms = typeof value === "string" ? Date.parse(value) : Number.NaN; return Number.isNaN(ms) ? undefined : new Date(ms).toISOString(); } // Reads a REST or webhook build object, or returns undefined for a state that treadle ignores. export function buildState(fields: Record): BuildState | undefined { const state = statuses.get(String(fields["state"])); // A build that waits at a block step keeps the state of its last step. const status = fields["blocked"] === true && (state === "running" || state === "success") ? "blocked" : state; const id = string(fields["id"]); if (status === undefined || id === undefined) { return undefined; } return { id, number: typeof fields["number"] === "number" ? fields["number"] : undefined, url: string(fields["web_url"]), status, startedAt: time(fields["started_at"]), finishedAt: isTerminal(status) ? time(fields["finished_at"]) : undefined, }; } const missingToken = "BUILDKITE_TOKEN is not set"; export function authorization(token: string | undefined): string { if (token === undefined || token === "") { throw new XrpcError(500, "InternalError", missingToken); } return `Bearer ${token}`; } export function pipelineUrl(org: string, pipeline: string): string { return `https://api.buildkite.com/v2/organizations/${encodeURIComponent(org)}/pipelines/${encodeURIComponent(pipeline)}`; } // A build with hundreds of jobs can exceed the default limit. export async function readBuild(response: Response): Promise { return await buffered(response, 16 * 1024 * 1024); } // Returns false when Buildkite refuses, because the build has finished or waits at a block step. export async function cancelBuild( token: string | undefined, org: string, pipeline: string, number: number, ): Promise { const url = `${pipelineUrl(org, pipeline)}/builds/${number}/cancel`; const response = await upstream( url, 503, { method: "PUT", headers: { Authorization: authorization(token) } }, { read: readBuild }, ); if (response.status === 422) { return false; } if (!response.ok) { throw upstreamError(url, 503, `HTTP ${response.status}`); } return true; } export async function getBuild( token: string | undefined, org: string, pipeline: string, number: number, ): Promise { const url = `${pipelineUrl(org, pipeline)}/builds/${number}`; const response = await upstream( url, 503, { headers: { Authorization: authorization(token) } }, { read: readBuild }, ); if (!response.ok) { throw new Error(`${url}: HTTP ${response.status}`); } const body: unknown = await response.json(); return isObject(body) ? buildState(body) : undefined; } export function branchFromRef(ref: string): string { return ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref; } export function createBuildBody(input: BuildInput): object { return { commit: input.commit, branch: input.branch, message: input.message ?? `tangled: ${input.workflow}`, ...(input.author === undefined ? {} : { author: input.author }), env: { TREADLE_REPO: input.repo, TREADLE_PIPELINE: input.pipeline, TREADLE_WORKFLOW: input.workflow, ...Object.fromEntries( (input.inputs ?? []).map(({ key, value }) => [ `TANGLED_INPUT_${key.toUpperCase()}`, value, ]), ), }, meta_data: { "treadle:repo": input.repo, "treadle:pipeline": input.pipeline, "treadle:workflow": input.workflow, }, ...(input.cleanCheckout === undefined ? {} : { clean_checkout: input.cleanCheckout }), ...(input.baseBranch === undefined ? {} : { pull_request_base_branch: input.baseBranch }), ignore_pipeline_branch_filters: true, }; } // Returns Buildkite's reason when it refuses the build for good, and throws when a retry may help. export async function createBuild( token: string | undefined, org: string, pipeline: string, body: object, ): Promise { if (token === undefined || token === "") { return missingToken; } const url = `${pipelineUrl(org, pipeline)}/builds`; const response = await upstream( url, 503, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, body: JSON.stringify(body), }, { // A slow answer may still create the build, and a retry would then duplicate it. timeoutMs: 60_000, // The build exists even when its details are unreadable, so a retry would duplicate it. read: async (answer) => answer.status === 201 ? new Response(await answer.arrayBuffer().catch(() => null), answer) : await buffered(answer), }, ); if (response.status === 201) { return build(await response.json().catch(() => null)); } const { status } = response; if (status >= 400 && status < 500 && ![401, 403, 408, 429].includes(status)) { return `HTTP ${status}: ${(await response.text()).slice(0, 1000)}`; } throw new Error(`${url}: HTTP ${status}`); }