mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
## Problem Since #54339, the docs alert in `docs-master-alert.yml` names only the workflow, the run type, and the run link. That stopped it from blaming whoever merged last, but nothing says which change broke things. A failure needs to trace back to the commit that introduced it, for push, scheduled, and manual runs alike. Nobody needs to be pinged. ## Solution Each docs workflow that runs on `master` keeps a list of open failures. The alert posts to Slack only when a failure is added or fixed. Each new failure names the commit that introduced it, or lists the possible commits as unconfirmed. It never names the latest commit by default. - **What counts as a failure.** - Accessibility scan: a page and axe rule pair, from a new Playwright reporter (`e2e/docs/utils/a11y-failures-reporter.ts`). A guide that returns a status of 400 or higher fails as `<page>: http-<status>`. - Production smoke tests: one Vitest test, keyed as `<file> › <test>`, from Vitest's JSON reporter. A run where no test passed and some timed out counts as one failure, `every test timed out`. - Every other workflow: a failed job or step, from the Actions API. - Both test workflows upload their results as a `docs-failures-<attempt>` artifact for the alert to read, so a re-run never picks up an earlier attempt's results. - A Vitest file that fails to load, such as an import error, counts as one failure for that file, and its tests keep their earlier results. - **Which commit.** - Accessibility scan: the commits deployed to production since the last run, narrowed to the ones that touched the failing page's MDX file or a partial it includes. - Smoke tests: the deployed commits, not narrowed further. - Push runs: the run's own commit, plus the commits of every earlier run since the baseline whose alert didn't run, such as one that was cancelled or dropped. A run among them that passed still counts, since it may have skipped the failing step. - Other scheduled or manual runs: the commits since the last run without that failure. - One commit left is named. Several, or none on the failing page, are listed as unconfirmed. - **Deployed commits.** One GraphQL query reads the `Vercel – docs` status on recent `master` commits. A commit counts as deployed once its build finished before the run ended, so the range includes a commit that deploys partway through a scan. Builds Vercel skipped as not affected count too, because they leave the docs unchanged. The `Production – docs` GitHub deployments stopped updating, so they can't be used. No new secrets. - **Flaky results.** A page or smoke test that times out keeps its earlier result, so it doesn't count as a new failure or a fix. The same goes for a page whose scan is missing, empty, or skipped, for a skipped smoke test, and for a job or step that neither passed nor failed, such as one skipped after a failed step, cancelled, or with no conclusion. A job that timed out counts as failed. A step keeps its result when its whole job was skipped or failed without listing its steps, or when a passing run's condition skipped it. A guide that returns an error status keeps its earlier axe failures until a scan runs, and a new status replaces the earlier one. A step skipped in one run and then under a skipped job in the next keeps the baseline from the run that last ran it. When one of these later fails, its range starts at the last run that actually checked it. If no run has checked it since tracking started, the alert names no commit. - **Saving the list.** The list is saved as a run artifact for each workflow, kept for 90 days. The next alert downloads it. A failure that's still open keeps the commit from when it first failed. The alert only accepts a saved list from a `master` run in this repo, and ignores one without the expected shape and version. - **Pure logic and orchestration.** `e2e/docs/utils/open-failures.ts` holds the logic and the Slack message, with unit tests. `e2e/docs/scripts/docs-alert.ts` handles the API calls and posting. `pageSourceFiles` in `resolve-docs-scope.ts` lists a guide's MDX file and every partial it includes. `failure-sequences.test.ts` runs every sequence of four runs, for a job's steps, a smoke test file's tests, and a guide's status and scan, plus sequences that start with no saved list. It checks the open list and each new failure's baseline against a model of what each run observed. The axe rules and result checks the reporter needs moved to `utils/axe-rules.ts`, so the unit tests still run before CI installs packages. ### Behavior changes to review 1. **The alert also runs on passing runs.** It needs them to clear fixed failures, and it posts only when the list changes. A workflow that keeps failing no longer posts on every run. 2. **Smoke tests aren't narrowed to a page.** They test API routes, not guides, so the alert lists every deployed commit since the last passing run. 3. **First run.** With no saved list, the alert compares against the previous run if that run passed. The jobs and steps that run skipped count as never checked. Otherwise, current failures show as "already failing when tracking started", with no commit. 4. **Fewer workflows trigger the alert.** Docs Navigation Checks, Docs removed anchors, and Docs Tests run only on `pull_request`, so they never matched `branches: [master]`. They're removed from the trigger list. 5. **Runs from forks are ignored.** The `branches: [master]` filter also matches a fork branch named `master`, and the alert now reads artifacts from the run that triggered it. For the same reason, a saved list that a fork or another branch uploaded is never used. 6. **Missing results.** If the scan or smoke tests have no readable results, the list stays as it was. A scan whose spec fails to load and a smoke run with no test files count as no results too. When the run failed, the alert posts a plain "failed before it reported any results" message. ## Limitations - With no saved list, the scan and smoke tests count everything the previous passing run skipped as checked, because the alert doesn't read that run's results. - Failures are matched by name, so a renamed job, step, or test, or a moved smoke test file, looks like one fixed failure and one new failure. - An incoming webhook can't edit an earlier message, so each change to the list is a new post. - The compare API returns at most 250 commits per page, oldest first. A longer range fetches its last two pages, so the alert lists the newest commits and the full count. - GitHub keeps only one pending run per concurrency group. If three runs of the same workflow finish at once, the middle alert is dropped, and the next one covers its commits. ## Review instructions 1. Run `pnpm -C e2e/docs test` and confirm all 55 tests pass. 2. Run the scan with the new reporter on a real guide and one that doesn't exist: ```bash cd e2e/docs && CI=1 DOCS_A11Y_FAILURES_FILE=/tmp/a11y.json PLAYWRIGHT_BASE_URL=https://supabase.com \ DOCS_E2E_PAGE_PATHS=/docs/guides/resources,/docs/guides/not-a-real-guide pnpm exec playwright test --grep @a11y cat /tmp/a11y.json ``` Expect one failure, `/docs/guides/not-a-real-guide: http-404`, with that guide also listed as unchecked, so its axe rules keep their earlier results. 3. Dry-run the alert against a real smoke test run, with a fake failure. `DRY_RUN` prints the Slack payload instead of posting it: ```bash mkdir -p /tmp/alert/results gh api repos/supabase/supabase/actions/runs/46574787371 \ | jq '{workflow_run: (. + {conclusion: "failure", path: ".github/workflows/docs-a11y-scan.yml", name: "Docs Accessibility Scan"})}' > /tmp/alert/event.json echo '{"failures":[{"key":"/docs/guides/database/custom-postgres-config: heading-order","page":"/docs/guides/database/custom-postgres-config"}],"unchecked":[]}' > /tmp/alert/results/a11y-failures.json GITHUB_TOKEN=$(gh auth token) GITHUB_REPOSITORY=supabase/supabase DRY_RUN=1 \ GITHUB_EVENT_PATH=/tmp/alert/event.json STATE_OUT=/tmp/alert/state.json RESULTS_DIR=/tmp/alert/results \ node e2e/docs/scripts/docs-alert.ts ``` Expect the failure to be `introduced by 450939c`, the only deployed commit in that range that touched the page. 4. Run step 3 again with `STATE_IN=/tmp/alert/state.json` and no other change. Expect no output, because the list didn't change. Verified locally: - Unit tests, typecheck, oxfmt, and actionlint on the changed workflows. The unit tests also pass in a copy of the repo with no installed packages, as CI runs them. - Mutation probes on the rules for unchecked pages, the push range, the unchecked baseline, Vitest files that fail to load, the saved-list check, deploy narrowing, skipped steps, smoke runs where every test timed out, the compare total, guides that return an error status, a guide whose error status changes, steps under a skipped job, and step baselines across skipped jobs. The sequence test alone catches all 14 unchecked-state bugs found in review when each is put back. - The reporter against production, including a guide that returns 404. - Dry runs against real runs: both workflows that test production, a failed push run, and a failed scheduled run. These covered a step whose range starts at the last run that ran it, a compare range of 400 commits, a new failure, a second failure added while the first stayed open, an unchanged list, every failure fixed, a crash before results, missing results, an older run, a saved list in the wrong shape, a passing run whose condition skipped a step with a saved failure, a push range that spans three pages of runs, and a first run with no saved list after a run that skipped a step. - The saved-list filter on real artifact data. Not run live: - The push and scheduled paths for the other workflows, because none had a recent failed run to test against. - The alert workflow itself. A `workflow_run` workflow only runs from `master`, so the first real alert comes after merge. Resolves [DOCS-1831](https://linear.app/supabase/issue/DOCS-1831/trace-docs-workflow-failures-to-the-commits-that-introduced-them) ## Checklist - [x] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
442 lines
14 KiB
JavaScript
442 lines
14 KiB
JavaScript
#!/usr/bin/env node
|
||
// Keeps the open-failures list for a docs workflow run on master and posts to Slack when it
|
||
// changes. Run by .github/workflows/docs-master-alert.yml.
|
||
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
||
import { dirname, join } from 'node:path'
|
||
import { fileURLToPath } from 'node:url'
|
||
|
||
import {
|
||
attribute,
|
||
baselineFor,
|
||
compareFailures,
|
||
deployedCommitsBetween,
|
||
failuresFromJobs,
|
||
failuresFromVitest,
|
||
formatAlert,
|
||
formatCrashAlert,
|
||
nextLastChecked,
|
||
parseFailureState,
|
||
parseRunFailures,
|
||
pushCandidates,
|
||
stateFromPassingRun,
|
||
titleOf,
|
||
type ActionsJob,
|
||
type ActionsRun,
|
||
type Attribution,
|
||
type Commit,
|
||
type Failure,
|
||
type FailureState,
|
||
type HistoryCommit,
|
||
type OpenFailure,
|
||
type RunFailures,
|
||
type RunRef,
|
||
} from '../utils/open-failures.ts'
|
||
import { pageSourceFiles } from '../utils/resolve-docs-scope.ts'
|
||
|
||
const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '../../..')
|
||
|
||
// Workflows that test production and upload their results as the `docs-failures-<attempt>`
|
||
// artifact (see the upload steps in docs-a11y-scan.yml and docs-tests-smoke.yml)
|
||
const RESULTS_WORKFLOWS: Record<
|
||
string,
|
||
{ file: string; narrowToPage: boolean; parse: (report: unknown) => RunFailures | null }
|
||
> = {
|
||
'.github/workflows/docs-a11y-scan.yml': {
|
||
file: 'a11y-failures.json',
|
||
narrowToPage: true,
|
||
parse: parseRunFailures,
|
||
},
|
||
'.github/workflows/docs-tests-smoke.yml': {
|
||
file: 'smoke-results.json',
|
||
narrowToPage: false,
|
||
parse: failuresFromVitest,
|
||
},
|
||
}
|
||
|
||
const VERCEL_STATUS_CONTEXT = 'Vercel – docs'
|
||
const HISTORY_PADDING_MS = 3 * 24 * 60 * 60 * 1000
|
||
const NEVER_CHECKED: Attribution = {
|
||
kind: 'none',
|
||
reason: 'no earlier run checked this since tracking started',
|
||
}
|
||
|
||
type WorkflowRun = ActionsRun & {
|
||
id: number
|
||
run_attempt: number
|
||
name: string
|
||
path: string
|
||
event: string
|
||
run_started_at: string
|
||
updated_at: string
|
||
html_url: string
|
||
workflow_id: number
|
||
}
|
||
|
||
const env = (name: string, fallback?: string): string => {
|
||
const value = process.env[name] ?? fallback
|
||
if (value === undefined) throw new Error(`${name} is not set.`)
|
||
return value
|
||
}
|
||
|
||
const repo = env('GITHUB_REPOSITORY')
|
||
const token = env('GITHUB_TOKEN')
|
||
const apiUrl = env('GITHUB_API_URL', 'https://api.github.com')
|
||
const repoUrl = `${env('GITHUB_SERVER_URL', 'https://github.com')}/${repo}`
|
||
|
||
// Response shapes follow GitHub's documented REST and GraphQL schemas
|
||
async function github<T>(path: string, init?: RequestInit): Promise<T> {
|
||
const response = await fetch(`${apiUrl}${path}`, {
|
||
...init,
|
||
headers: {
|
||
Accept: 'application/vnd.github+json',
|
||
Authorization: `Bearer ${token}`,
|
||
'X-GitHub-Api-Version': '2022-11-28',
|
||
...init?.headers,
|
||
},
|
||
})
|
||
if (!response.ok) {
|
||
throw new Error(`GitHub API ${path} returned ${response.status}: ${await response.text()}`)
|
||
}
|
||
return (await response.json()) as T
|
||
}
|
||
|
||
function readJson(path: string | undefined): unknown {
|
||
if (!path || !existsSync(path)) return null
|
||
try {
|
||
return JSON.parse(readFileSync(path, 'utf8'))
|
||
} catch {
|
||
return null
|
||
}
|
||
}
|
||
|
||
function toRunRef(run: WorkflowRun): RunRef {
|
||
return {
|
||
id: run.id,
|
||
attempt: run.run_attempt,
|
||
runNumber: run.run_number,
|
||
headSha: run.head_sha,
|
||
startedAt: run.run_started_at,
|
||
}
|
||
}
|
||
|
||
function runLabel(event: string): string {
|
||
if (event === 'push') return 'push to master'
|
||
if (event === 'schedule') return 'scheduled run'
|
||
if (event === 'workflow_dispatch') return 'manual run'
|
||
return `${event} run`
|
||
}
|
||
|
||
async function jobFailures(run: WorkflowRun): Promise<RunFailures> {
|
||
const { jobs } = await github<{ jobs: ActionsJob[] }>(
|
||
`/repos/${repo}/actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100`
|
||
)
|
||
return failuresFromJobs(jobs)
|
||
}
|
||
|
||
// null when the run's results are missing or unreadable, so this run can't change the list
|
||
async function currentFailures(run: WorkflowRun, resultsDir: string): Promise<RunFailures | null> {
|
||
const results = RESULTS_WORKFLOWS[run.path]
|
||
if (results) return results.parse(readJson(join(resultsDir, results.file)))
|
||
|
||
// Read jobs on a passing run too, so a step its condition skipped keeps its earlier result
|
||
const fromJobs = await jobFailures(run)
|
||
if (run.conclusion === 'success' || fromJobs.failures.length > 0) return fromJobs
|
||
return { failures: [{ key: 'run' }], unchecked: fromJobs.unchecked }
|
||
}
|
||
|
||
// With no saved list, a previous run that passed still says nothing was open
|
||
async function baselineFromApi(run: WorkflowRun): Promise<FailureState | null> {
|
||
const { workflow_runs: runs } = await github<{ workflow_runs: WorkflowRun[] }>(
|
||
`/repos/${repo}/actions/workflows/${run.workflow_id}/runs?branch=master&status=completed&per_page=20`
|
||
)
|
||
const previous = runs.find(
|
||
(candidate) =>
|
||
candidate.event !== 'pull_request' &&
|
||
candidate.run_number < run.run_number &&
|
||
(candidate.conclusion === 'success' || candidate.conclusion === 'failure')
|
||
)
|
||
if (previous?.conclusion !== 'success') return null
|
||
// A results workflow's earlier artifact isn't read here, so its skipped pages count as checked
|
||
const skipped = RESULTS_WORKFLOWS[run.path] ? [] : (await jobFailures(previous)).unchecked
|
||
return stateFromPassingRun(toRunRef(previous), skipped)
|
||
}
|
||
|
||
async function deployHistory(since: string): Promise<HistoryCommit[]> {
|
||
const [owner, name] = repo.split('/')
|
||
const query = `query($owner: String!, $name: String!, $since: GitTimestamp!, $cursor: String) {
|
||
repository(owner: $owner, name: $name) {
|
||
ref(qualifiedName: "refs/heads/master") {
|
||
target {
|
||
... on Commit {
|
||
history(first: 100, since: $since, after: $cursor) {
|
||
pageInfo { hasNextPage endCursor }
|
||
nodes {
|
||
oid
|
||
messageHeadline
|
||
status { context(name: "${VERCEL_STATUS_CONTEXT}") { state description createdAt } }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}`
|
||
|
||
type Page = {
|
||
data: {
|
||
repository: {
|
||
ref: {
|
||
target: {
|
||
history: {
|
||
pageInfo: { hasNextPage: boolean; endCursor: string }
|
||
nodes: {
|
||
oid: string
|
||
messageHeadline: string
|
||
status: { context: HistoryCommit['status'] } | null
|
||
}[]
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
const commits: HistoryCommit[] = []
|
||
let cursor: string | null = null
|
||
for (let page = 0; page < 5; page++) {
|
||
const result: Page = await github<Page>('/graphql', {
|
||
method: 'POST',
|
||
body: JSON.stringify({ query, variables: { owner, name, since, cursor } }),
|
||
})
|
||
const history = result.data.repository.ref.target.history
|
||
for (const node of history.nodes) {
|
||
commits.push({
|
||
sha: node.oid,
|
||
title: node.messageHeadline,
|
||
status: node.status?.context ?? null,
|
||
})
|
||
}
|
||
if (!history.pageInfo.hasNextPage) break
|
||
cursor = history.pageInfo.endCursor
|
||
}
|
||
return commits
|
||
}
|
||
|
||
async function pushRange(run: WorkflowRun, baseline: RunRef): Promise<Commit[]> {
|
||
const runs: WorkflowRun[] = []
|
||
for (let page = 1; ; page++) {
|
||
const { workflow_runs: batch } = await github<{ workflow_runs: WorkflowRun[] }>(
|
||
`/repos/${repo}/actions/workflows/${run.workflow_id}/runs?branch=master&event=push&created=>=${baseline.startedAt.slice(0, 10)}&per_page=100&page=${page}`
|
||
)
|
||
runs.push(...batch)
|
||
// Runs come newest first, so stop once a page reaches back to the baseline
|
||
if (batch.length < 100 || batch.some((item) => item.run_number <= baseline.runNumber)) break
|
||
}
|
||
return pushCandidates(runs, baseline.runNumber, run)
|
||
}
|
||
|
||
type CommitRange = { commits: Commit[]; total: number }
|
||
|
||
type Comparison = {
|
||
total_commits: number
|
||
commits: { sha: string; commit: { message: string } }[]
|
||
}
|
||
|
||
// The compare API lists the oldest commits first and returns at most 250, so a longer range
|
||
// fetches its last two pages of 100 to list the newest commits
|
||
async function compareRange(base: string, head: string): Promise<CommitRange> {
|
||
if (base === head) return { commits: [], total: 0 }
|
||
const path = `/repos/${repo}/compare/${base}...${head}`
|
||
const first = await github<Comparison>(`${path}?per_page=250`)
|
||
let commits = first.commits
|
||
if (first.total_commits > commits.length) {
|
||
const lastPage = Math.ceil(first.total_commits / 100)
|
||
const pages = await Promise.all(
|
||
[lastPage - 1, lastPage].map((page) =>
|
||
github<Comparison>(`${path}?per_page=100&page=${page}`)
|
||
)
|
||
)
|
||
commits = pages.flatMap((page) => page.commits)
|
||
}
|
||
return {
|
||
commits: commits.map((commit) => ({
|
||
sha: commit.sha,
|
||
title: titleOf(commit.commit.message),
|
||
})),
|
||
total: first.total_commits,
|
||
}
|
||
}
|
||
|
||
async function attributeNew(
|
||
run: WorkflowRun,
|
||
state: FailureState,
|
||
added: Failure[]
|
||
): Promise<Map<string, Attribution>> {
|
||
const attributions = new Map<string, Attribution>()
|
||
const results = RESULTS_WORKFLOWS[run.path]
|
||
|
||
if (!results) {
|
||
const ranges = new Map<number, CommitRange>()
|
||
for (const failure of added) {
|
||
const baseline = baselineFor(failure, state)
|
||
if (baseline === null) {
|
||
attributions.set(failure.key, NEVER_CHECKED)
|
||
continue
|
||
}
|
||
let range = ranges.get(baseline.id)
|
||
if (!range) {
|
||
if (run.event === 'push') {
|
||
const commits = await pushRange(run, baseline)
|
||
range = { commits, total: commits.length }
|
||
} else {
|
||
range = await compareRange(baseline.headSha, run.head_sha)
|
||
}
|
||
ranges.set(baseline.id, range)
|
||
}
|
||
attributions.set(failure.key, attribute(range.commits, null, range.total))
|
||
}
|
||
return attributions
|
||
}
|
||
|
||
const baselines = added.map((failure) => baselineFor(failure, state))
|
||
const known = baselines.filter((baseline) => baseline !== null)
|
||
if (known.length === 0) {
|
||
for (const failure of added) attributions.set(failure.key, NEVER_CHECKED)
|
||
return attributions
|
||
}
|
||
const earliest = Math.min(...known.map((baseline) => Date.parse(baseline.startedAt)))
|
||
const since = new Date(earliest - HISTORY_PADDING_MS).toISOString()
|
||
const history = await deployHistory(since)
|
||
|
||
const touchedByFile = new Map<string, Set<string>>()
|
||
const commitsTouching = async (file: string): Promise<Set<string>> => {
|
||
const cached = touchedByFile.get(file)
|
||
if (cached) return cached
|
||
const commits = await github<{ sha: string }[]>(
|
||
`/repos/${repo}/commits?sha=${run.head_sha}&path=${encodeURIComponent(file)}&since=${since}&per_page=100`
|
||
)
|
||
const shas = new Set(commits.map((commit) => commit.sha))
|
||
touchedByFile.set(file, shas)
|
||
return shas
|
||
}
|
||
|
||
for (const [index, failure] of added.entries()) {
|
||
const baseline = baselines[index]
|
||
if (baseline === null) {
|
||
attributions.set(failure.key, NEVER_CHECKED)
|
||
continue
|
||
}
|
||
// The run's end, since a commit that deploys mid-scan reaches the pages scanned after it
|
||
const range = deployedCommitsBetween(history, baseline.startedAt, run.updated_at)
|
||
if (range === null) {
|
||
attributions.set(failure.key, {
|
||
kind: 'none',
|
||
reason: `couldn't tell which commit production was running`,
|
||
})
|
||
continue
|
||
}
|
||
if (!results.narrowToPage || !failure.page || range.length === 0) {
|
||
attributions.set(failure.key, attribute(range, null))
|
||
continue
|
||
}
|
||
const touched = new Set<string>()
|
||
for (const file of await pageSourceFiles(REPO_ROOT, failure.page)) {
|
||
for (const sha of await commitsTouching(file)) touched.add(sha)
|
||
}
|
||
const matching = range.filter((commit) => touched.has(commit.sha))
|
||
attributions.set(failure.key, attribute(range, matching))
|
||
}
|
||
return attributions
|
||
}
|
||
|
||
async function postToSlack(payload: unknown): Promise<void> {
|
||
if (process.env.DRY_RUN) {
|
||
console.log(JSON.stringify(payload, null, 2))
|
||
return
|
||
}
|
||
const response = await fetch(env('SLACK_WEBHOOK_URL'), {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(payload),
|
||
})
|
||
if (!response.ok) throw new Error(`Slack returned ${response.status}: ${await response.text()}`)
|
||
}
|
||
|
||
function isOlderRun(run: WorkflowRun, lastRun: RunRef): boolean {
|
||
if (run.run_number !== lastRun.runNumber) return run.run_number < lastRun.runNumber
|
||
return run.run_attempt < lastRun.attempt
|
||
}
|
||
|
||
async function main(): Promise<void> {
|
||
const event = readJson(env('GITHUB_EVENT_PATH')) as { workflow_run?: WorkflowRun } | null
|
||
const run = event?.workflow_run
|
||
if (!run) throw new Error('No workflow_run in the event payload.')
|
||
if (run.conclusion !== 'success' && run.conclusion !== 'failure') return
|
||
|
||
const stateOut = env('STATE_OUT')
|
||
const saved = parseFailureState(readJson(process.env.STATE_IN))
|
||
const keepSaved = () => {
|
||
if (saved) writeFileSync(stateOut, JSON.stringify(saved, null, 2))
|
||
}
|
||
if (saved && isOlderRun(run, saved.lastRun)) return keepSaved()
|
||
|
||
const context = {
|
||
workflowName: run.name,
|
||
runUrl: run.html_url,
|
||
runLabel: runLabel(run.event),
|
||
repoUrl,
|
||
}
|
||
|
||
const current = await currentFailures(run, env('RESULTS_DIR'))
|
||
if (current === null) {
|
||
keepSaved()
|
||
if (run.conclusion === 'failure') await postToSlack(formatCrashAlert(context))
|
||
return
|
||
}
|
||
|
||
const baseline = saved ?? (await baselineFromApi(run))
|
||
const { added, stillOpen, fixed } = compareFailures(baseline?.open ?? [], current)
|
||
|
||
let attributions = new Map<string, Attribution>()
|
||
if (baseline && added.length > 0) {
|
||
try {
|
||
attributions = await attributeNew(run, baseline, added)
|
||
} catch (error) {
|
||
console.error(error instanceof Error ? error.message : error)
|
||
for (const failure of added) {
|
||
attributions.set(failure.key, { kind: 'none', reason: `couldn't read the commit history` })
|
||
}
|
||
}
|
||
}
|
||
|
||
const open: OpenFailure[] = [
|
||
...stillOpen,
|
||
...added.map((failure) => ({
|
||
...failure,
|
||
firstSeen: run.run_started_at,
|
||
attribution: attributions.get(failure.key) ?? { kind: 'preexisting' as const },
|
||
})),
|
||
]
|
||
|
||
const state: FailureState = {
|
||
version: 1,
|
||
lastRun: toRunRef(run),
|
||
open,
|
||
lastChecked: nextLastChecked(
|
||
baseline?.lastChecked ?? {},
|
||
current.unchecked,
|
||
baseline?.lastRun ?? null
|
||
),
|
||
}
|
||
writeFileSync(stateOut, JSON.stringify(state, null, 2))
|
||
|
||
if (added.length === 0 && fixed.length === 0) return
|
||
const addedKeys = new Set(added.map((failure) => failure.key))
|
||
await postToSlack(formatAlert(context, open, addedKeys, fixed))
|
||
}
|
||
|
||
main().catch((error) => {
|
||
console.error(error instanceof Error ? error.message : error)
|
||
process.exit(1)
|
||
})
|