The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Better error handling and messaging for missing release artifacts (#84199)
Ryan Laurie83f788556e75
diff --git a/.github/actions/fetch-artifact/action.yml b/.github/actions/fetch-artifact/action.ymlindex bcc1a59a0b9..1a301db7461 100644--- a/.github/actions/fetch-artifact/action.yml+++ b/.github/actions/fetch-artifact/action.yml@@ -41,7 +41,6 @@ runs:const fs = require('fs');const isRelease = "${{ inputs.release }}" === "true";- const failOnMiss = "${{ inputs.fail-on-fetch-miss }}" !== "false";const shouldDownload = "${{ inputs.download }}" !== "false";const prefix = isRelease ? "metabase-release" : "metabase";const artifactName = `${prefix}-${{ inputs.edition }}-${{ inputs.commit }}-uberjar`;@@ -54,19 +53,28 @@ runs:per_page: 1,});- const artifact_id = artifacts.data?.artifacts?.[0]?.id;+ const artifact = artifacts.data?.artifacts?.[0];+ const artifact_id = artifact && !artifact.expired ? artifact.id : undefined;- if (!artifact_id) {- core.setOutput('fetch-hit', 'false');- } else {- core.setOutput('fetch-hit', 'true');- }+ core.setOutput('fetch-hit', artifact_id ? 'true' : 'false');if (!shouldDownload) {console.log(`skipping download (download: false)`);return;}+ // Nothing to download, so fail now rather than retrying a request for no artifact.+ if (!artifact_id) {+ const reason = artifact+ ? `it expired on ${artifact.expires_at}`+ : `no workflow uploaded it for commit ${{ inputs.commit }}`;+ const hint = isRelease+ ? ' Release artifacts come from "Release 1 - Tag Release Artifact"; check it ran for this exact commit.'+ : '';+ core.setFailed(`Artifact ${artifactName} not found: ${reason}.${hint}`);+ return;+ }+let download;const maxAttempts = 3;for (let attempt = 1; attempt <= maxAttempts; attempt++) {diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex e485c6d1e9e..ef869e27f11 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -87,6 +87,54 @@ jobs:});return versions+ # Everything after this job fetches the uberjars Release 1 built for this commit, so check they+ # exist before any of it starts, and say which commit Release 1 built if they don't.+ - name: Check the release uberjars exist for this commit+ uses: actions/github-script@v9+ env:+ VERSION: ${{ inputs.version }}+ COMMIT: ${{ inputs.commit }}+ SLACK_RELEASE_CHANNEL: ${{ vars.SLACK_RELEASE_CHANNEL }}+ SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}+ with:+ script: | # js+ const {+ checkReleaseArtifacts,+ buildReleaseArtifactMismatchMessage,+ sendPublishFailureMessage,+ slackLink,+ } = require('${{ github.workspace }}/release/dist/index.cjs');++ const { VERSION: version, COMMIT: commit } = process.env;+ const { owner, repo } = context.repo;++ let error;+ let slackError;+ try {+ const result = await checkReleaseArtifacts({ github, owner, repo, version, commit });++ if (result.ok) {+ console.log(`Found the release uberjars for ${version} at ${commit}`);+ return;+ }++ error = buildReleaseArtifactMismatchMessage(result);+ slackError = buildReleaseArtifactMismatchMessage(result, slackLink);+ } catch (err) {+ // e.g. a short SHA: still worth telling the release thread+ error = slackError = err.message;+ }++ await sendPublishFailureMessage({+ owner,+ repo,+ version,+ runId: context.runId,+ channelName: process.env.SLACK_RELEASE_CHANNEL,+ details: slackError,+ }).catch(console.error);++ core.setFailed(error);publish-start-message:runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}diff --git a/release/src/index.ts b/release/src/index.tsindex 016350f2fa4..4d9b8328546 100644--- a/release/src/index.ts+++ b/release/src/index.ts@@ -3,6 +3,7 @@ export * from "./backports";export * from "./github";export * from "./linked-issues";export * from "./milestones";+export * from "./release-artifacts";export * from "./release-notes";export * from "./slack";export * from "./version-helpers";diff --git a/release/src/release-artifacts.ts b/release/src/release-artifacts.tsnew file mode 100644index 00000000000..b13b5a0e820--- /dev/null+++ b/release/src/release-artifacts.ts@@ -0,0 +1,182 @@+import type { GithubProps } from "./types";+import {+ getOSSVersion,+ isValidCommitHash,+ isValidVersionString,+} from "./version-helpers";++// Release 1 builds these; Release 2 and Release 3 fetch them by name.+const TAG_WORKFLOW = "tag-for-release.yml";+const TAG_WORKFLOW_NAME = "Release 1 - Tag Release Artifact";++const EDITIONS = ["oss", "ee"] as const;+type Edition = (typeof EDITIONS)[number];++const RELEASE_ARTIFACT_NAME =+ /^metabase-release-(?:oss|ee)-([0-9a-f]{40})-uberjar$/;++export const getReleaseArtifactName = (edition: Edition, commit: string) =>+ `metabase-release-${edition}-${commit}-uberjar`;++const shortSha = (commit: string) => commit.slice(0, 7);++type TagRun = {+ id: number;+ url: string;+ title: string;+ // null when the run's release artifacts have expired+ commit: string | null;+};++export type ReleaseArtifactCheck =+ | { ok: true }+ | {+ ok: false;+ version: string;+ commit: string;+ missing: string[];+ tagRun: TagRun | null;+ };++async function hasLiveArtifact({+ github,+ owner,+ repo,+ name,+}: GithubProps & { name: string }) {+ const { data } = await github.rest.actions.listArtifactsForRepo({+ owner,+ repo,+ name,+ per_page: 100,+ });++ return data.artifacts.some(+ (artifact) => artifact.name === name && !artifact.expired,+ );+}++const isSameVersion = (a: string, b: string) =>+ isValidVersionString(a) &&+ isValidVersionString(b) &&+ getOSSVersion(a) === getOSSVersion(b);++// The latest successful Release 1 run for this version, and the commit it built.+export async function findTagRun({+ github,+ owner,+ repo,+ version,+}: GithubProps & { version: string }): Promise<TagRun | null> {+ const { data } = await github.rest.actions.listWorkflowRuns({+ owner,+ repo,+ workflow_id: TAG_WORKFLOW,+ status: "success",+ per_page: 100,+ });++ // Release 1's run-name is "Tag <version>", and it accepts either the v0 or v1 form.+ const run = data.workflow_runs.find((run) =>+ isSameVersion(run.display_title.replace(/^Tag /, ""), version),+ );++ if (!run) {+ return null;+ }++ const { data: artifacts } =+ await github.rest.actions.listWorkflowRunArtifacts({+ owner,+ repo,+ run_id: run.id,+ per_page: 100,+ });++ const commit =+ artifacts.artifacts+ .filter((artifact) => !artifact.expired)+ .map((artifact) => RELEASE_ARTIFACT_NAME.exec(artifact.name)?.[1])+ .find(Boolean) ?? null;++ return { id: run.id, url: run.html_url, title: run.display_title, commit };+}++export async function checkReleaseArtifacts({+ github,+ owner,+ repo,+ version,+ commit,+}: GithubProps & {+ version: string;+ commit: string;+}): Promise<ReleaseArtifactCheck> {+ if (!isValidCommitHash(commit)) {+ throw new Error(+ `"${commit}" is not a full-length commit SHA. Pass the 40-character SHA Release 1 built.`,+ );+ }++ const names = EDITIONS.map((edition) =>+ getReleaseArtifactName(edition, commit),+ );+ const found = await Promise.all(+ names.map((name) => hasLiveArtifact({ github, owner, repo, name })),+ );+ const missing = names.filter((_name, index) => !found[index]);++ if (missing.length === 0) {+ return { ok: true };+ }++ const tagRun = await findTagRun({ github, owner, repo, version });++ return { ok: false, version, commit, missing, tagRun };+}++type Link = (text: string, url: string) => string;++const plainLink: Link = (text, url) => `${text} (${url})`;++export function buildReleaseArtifactMismatchMessage(+ check: Extract<ReleaseArtifactCheck, { ok: false }>,+ link: Link = plainLink,+) {+ const { version, commit, missing, tagRun } = check;++ const problem = `No release uberjars for ${version} at commit ${shortSha(commit)}: ${missing.join(", ")} not found or expired.`;++ if (!tagRun) {+ return [+ problem,+ `No successful "${TAG_WORKFLOW_NAME}" run found for ${version}.`,+ `Run Release 1 for ${version} with commit ${commit} first, then re-run this workflow.`,+ ].join("\n");+ }++ const tagRunLink = link(tagRun.title, tagRun.url);++ if (!tagRun.commit) {+ return [+ problem,+ `${tagRunLink} has no release uberjars left; they may have expired.`,+ `Re-run Release 1 for ${version} with commit ${commit}, then re-run this workflow.`,+ ].join("\n");+ }++ if (tagRun.commit === commit) {+ return [+ problem,+ `${tagRunLink} built this commit, but its release uberjars could not be found.`,+ `Re-run Release 1 for ${version} with commit ${commit}, then re-run this workflow.`,+ ].join("\n");+ }++ return [+ problem,+ `${tagRunLink} built commit ${shortSha(tagRun.commit)}, not ${shortSha(commit)}.`,+ `To ship what Release 1 built, re-run this workflow with commit ${tagRun.commit}.`,+ `To ship ${shortSha(commit)}, re-run Release 1 for ${version} with commit ${commit} first.`,+ ].join("\n");+}diff --git a/release/src/release-artifacts.unit.spec.ts b/release/src/release-artifacts.unit.spec.tsnew file mode 100644index 00000000000..3331414bcf3--- /dev/null+++ b/release/src/release-artifacts.unit.spec.ts@@ -0,0 +1,236 @@+import {+ buildReleaseArtifactMismatchMessage,+ checkReleaseArtifacts,+ getReleaseArtifactName,+} from "./release-artifacts";++const TAGGED = "2540625628432c7165de87307c993ad88f6ba716";+const DISPATCHED = "1bfedb8761c2f66c01da1f8d12818be4d9caa8f3";+const TAG_RUN_URL =+ "https://github.com/metabase/metabase/actions/runs/38220812337";++type Artifact = { name: string; expired?: boolean };++const releaseArtifacts = (commit: string, expired = false): Artifact[] => [+ { name: getReleaseArtifactName("oss", commit), expired },+ { name: getReleaseArtifactName("ee", commit), expired },+ { name: "metabase-test-ee-uberjar", expired },+];++const build = ({+ repoArtifacts = [],+ tagRuns = [{ id: 38220812337, display_title: "Tag v0.65.0-beta" }],+ tagRunArtifacts = releaseArtifacts(TAGGED),+}: {+ repoArtifacts?: Artifact[];+ tagRuns?: Array<{ id: number; display_title: string }>;+ tagRunArtifacts?: Artifact[];+} = {}) => ({+ rest: {+ actions: {+ listArtifactsForRepo: jest.fn(({ name }: { name: string }) =>+ Promise.resolve({+ data: {+ artifacts: repoArtifacts+ .filter((artifact) => artifact.name === name)+ .map((artifact) => ({ expired: false, ...artifact })),+ },+ }),+ ),+ listWorkflowRuns: jest.fn().mockResolvedValue({+ data: {+ workflow_runs: tagRuns.map((run) => ({+ ...run,+ html_url: `https://github.com/metabase/metabase/actions/runs/${run.id}`,+ })),+ },+ }),+ listWorkflowRunArtifacts: jest.fn().mockResolvedValue({+ data: {+ artifacts: tagRunArtifacts.map((artifact) => ({+ expired: false,+ ...artifact,+ })),+ },+ }),+ },+ },+});++const check = (+ github: ReturnType<typeof build>,+ { version = "v0.65.0-beta", commit = DISPATCHED } = {},+) =>+ checkReleaseArtifacts({+ github: github as any,+ owner: "metabase",+ repo: "metabase",+ version,+ commit,+ });++const failedCheck = async (...args: Parameters<typeof check>) => {+ const result = await check(...args);+ if (result.ok) {+ throw new Error("expected the check to fail");+ }+ return result;+};++describe("checkReleaseArtifacts", () => {+ it("passes when both release uberjars exist for the commit", async () => {+ const github = build({ repoArtifacts: releaseArtifacts(DISPATCHED) });++ expect(await check(github)).toEqual({ ok: true });+ expect(github.rest.actions.listWorkflowRuns).not.toHaveBeenCalled();+ });++ it("rejects a SHA that is not full length before looking anything up", async () => {+ const github = build();++ await expect(check(github, { commit: "1bfedb8" })).rejects.toThrow(+ /not a full-length commit SHA/,+ );+ expect(github.rest.actions.listArtifactsForRepo).not.toHaveBeenCalled();+ });++ it("reports the commit Release 1 built when it differs from the input", async () => {+ const result = await failedCheck(build());++ expect(result.missing).toEqual([+ getReleaseArtifactName("oss", DISPATCHED),+ getReleaseArtifactName("ee", DISPATCHED),+ ]);+ expect(result.tagRun).toEqual({+ id: 38220812337,+ url: TAG_RUN_URL,+ title: "Tag v0.65.0-beta",+ commit: TAGGED,+ });+ });++ it("only reports the edition that is missing", async () => {+ const result = await failedCheck(+ build({+ repoArtifacts: [{ name: getReleaseArtifactName("oss", DISPATCHED) }],+ }),+ );++ expect(result.missing).toEqual([getReleaseArtifactName("ee", DISPATCHED)]);+ });++ it("treats expired artifacts as missing", async () => {+ const result = await failedCheck(+ build({ repoArtifacts: releaseArtifacts(DISPATCHED, true) }),+ );++ expect(result.missing).toHaveLength(2);+ });++ it("matches a Release 1 run started with the enterprise form of the version", async () => {+ const result = await failedCheck(+ build({ tagRuns: [{ id: 1, display_title: "Tag v1.65.0-beta" }] }),+ );++ expect(result.tagRun?.commit).toBe(TAGGED);+ });++ it("ignores Release 1 runs for other versions", async () => {+ const result = await failedCheck(+ build({+ tagRuns: [+ { id: 1, display_title: "Tag v0.64.1" },+ { id: 2, display_title: "Tag v0.65.0" },+ ],+ }),+ );++ expect(result.tagRun).toBeNull();+ });++ it("reports a Release 1 run whose release uberjars have expired", async () => {+ const result = await failedCheck(+ build({ tagRunArtifacts: releaseArtifacts(TAGGED, true) }),+ );++ expect(result.tagRun?.commit).toBeNull();+ });+});++describe("buildReleaseArtifactMismatchMessage", () => {+ const base = {+ ok: false as const,+ version: "v0.65.0-beta",+ commit: DISPATCHED,+ missing: [+ getReleaseArtifactName("oss", DISPATCHED),+ getReleaseArtifactName("ee", DISPATCHED),+ ],+ };+ const tagRun = { id: 1, url: TAG_RUN_URL, title: "Tag v0.65.0-beta" };++ it("names both commits and both ways out of a mismatch", () => {+ const message = buildReleaseArtifactMismatchMessage({+ ...base,+ tagRun: { ...tagRun, commit: TAGGED },+ });++ expect(message).toContain(+ "No release uberjars for v0.65.0-beta at commit 1bfedb8",+ );+ expect(message).toContain(+ `Tag v0.65.0-beta (${TAG_RUN_URL}) built commit 2540625, not 1bfedb8.`,+ );+ expect(message).toContain(`re-run this workflow with commit ${TAGGED}`);+ expect(message).toContain(+ `re-run Release 1 for v0.65.0-beta with commit ${DISPATCHED} first`,+ );+ });++ it("formats links with the link function it is given", () => {+ const message = buildReleaseArtifactMismatchMessage(+ { ...base, tagRun: { ...tagRun, commit: TAGGED } },+ (text, url) => `<${url}|${text}>`,+ );++ expect(message).toContain(+ `<${TAG_RUN_URL}|Tag v0.65.0-beta> built commit 2540625`,+ );+ });++ it("asks for Release 1 when there is no run for the version", () => {+ const message = buildReleaseArtifactMismatchMessage({+ ...base,+ tagRun: null,+ });++ expect(message).toContain(+ 'No successful "Release 1 - Tag Release Artifact" run found for v0.65.0-beta.',+ );+ expect(message).toContain(+ `Run Release 1 for v0.65.0-beta with commit ${DISPATCHED} first`,+ );+ });++ it("explains a Release 1 run with nothing left to fetch", () => {+ const message = buildReleaseArtifactMismatchMessage({+ ...base,+ tagRun: { ...tagRun, commit: null },+ });++ expect(message).toContain(+ "has no release uberjars left; they may have expired.",+ );+ });++ it("explains a run that built this commit but whose uberjars are gone", () => {+ const message = buildReleaseArtifactMismatchMessage({+ ...base,+ tagRun: { ...tagRun, commit: DISPATCHED },+ });++ expect(message).toContain(+ "built this commit, but its release uberjars could not be found.",+ );+ });+});diff --git a/release/src/slack.ts b/release/src/slack.tsindex a443a534040..26b9ed81d53 100644--- a/release/src/slack.ts+++ b/release/src/slack.ts@@ -439,6 +439,35 @@ export async function sendPublishStartMessage({await sendSlackReply({ channelName, message, messageId: buildThread?.id });}+export async function sendPublishFailureMessage({+ channelName,+ version,+ runId,+ owner,+ repo,+ details,+}: {+ channelName: string,+ version: string,+ runId: number,+ owner: string,+ repo: string,+ details: string,+}) {+ const message = `:x: ${githubRunLink(`Publishing ${getGenericVersion(version)} failed`, runId.toString(), owner, repo)}\n${details}`;++ const buildThread = await getExistingSlackMessage(version, channelName);++ if (!buildThread?.id) {+ // Without the release thread, say it in the channel rather than not at all.+ await sendSlackMessage({ channelName, message });+ return;+ }++ await sendSlackReply({ channelName, message, messageId: buildThread.id });+ await addSlackReaction({ channelName, messageId: buildThread.id, emoji: 'warning' });+}+export async function sendPublishCompleteMessage({channelName,version,