diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index deb0328f796e..74fd1d6e13b0 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -961,10 +961,10 @@ jobs: autoRetestRequestForCP: name: File retest request for cherry-picked deploy-blocker fixes runs-on: blacksmith-2vcpu-ubuntu-2404 - # androidSubmit/iosSubmit always skip on staging (they're prod-only), so the implicit - # success() check would skip this job too unless we override it with always(). - if: ${{ always() && github.repository == 'Expensify/App' && needs.prep.outputs.DEPLOY_ENV == 'staging' && fromJSON(needs.prep.outputs.IS_CHERRY_PICK) && fromJSON(needs.checkDeploymentSuccess.outputs.IS_ALL_PLATFORMS_DEPLOYED) }} - needs: [prep, checkDeploymentSuccess] + # A later staging deploy can supersede a cherry-pick, even if it was not itself a cherry-pick. + # always() lets this run when production-only submit jobs are skipped on staging. + if: ${{ always() && !cancelled() && github.repository == 'Expensify/App' && needs.prep.outputs.DEPLOY_ENV == 'staging' && needs.deployChecklist.result == 'success' && fromJSON(needs.checkDeploymentSuccess.outputs.IS_ALL_PLATFORMS_DEPLOYED) }} + needs: [prep, deployChecklist, checkDeploymentSuccess] steps: - name: Checkout uses: useblacksmith/checkout@0647fdbab2614a5eb86d2971070e325060d91056 # v1.7.0 diff --git a/scripts/createRetestRequestForCP.ts b/scripts/createRetestRequestForCP.ts index 4af79bab1de0..dff1df86e18b 100644 --- a/scripts/createRetestRequestForCP.ts +++ b/scripts/createRetestRequestForCP.ts @@ -1,6 +1,6 @@ #!/usr/bin/env bun import CONST from '@github/libs/CONST'; -import {getDeployChecklist, NoOpenDeployChecklistError} from '@github/libs/DeployChecklistUtils'; +import {getDeployChecklist, getDeployChecklistData, NoOpenDeployChecklistError} from '@github/libs/DeployChecklistUtils'; import GithubUtils from '@github/libs/GithubUtils'; import CLI from 'expensify-common/CLI'; @@ -8,15 +8,15 @@ import CLI from 'expensify-common/CLI'; // GitHub REST API request fields are snake_case (per_page, commit_sha, pull_number), which this rule would otherwise flag. /* eslint-disable @typescript-eslint/naming-convention */ -// Tags come back paginated; the request size and the "last page" check must stay in sync. -const TAGS_PER_PAGE = 100; +// GitHub limits issue and pull request commit lists to 100 entries per page. +const GITHUB_PAGE_SIZE = 100; /** * When a deploy-blocker fix is cherry-picked to staging, QA needs to retest the blocker. * The deployer used to file that retest request in Slack by hand. This script does it for them. * * It fires only when all three are true: - * 1. The deploy was triggered by a cherry-pick to staging. + * 1. The cherry-pick is included in a staging deploy on all platforms. * 2. The cherry-picked PR is on the current StagingDeployCash checklist. * 3. An issue linked in that PR's body is listed as a deploy blocker on that same checklist. */ @@ -31,21 +31,38 @@ const WHITELIST_PATH = 'www/files/www-whitelist.php'; // Each whitelist entry lists 'github' a few lines above 'slack', so keep the match bounded to one entry. const WHITELIST_ENTRY_REGEX = /'github'\s*=>\s*'([^']+)'[\s\S]{0,400}?'slack'\s*=>\s*'([^']+)'/g; +const RETEST_MARKER_PREFIX = ''; +const RETEST_MARKER_REGEX = new RegExp(`${RETEST_MARKER_PREFIX}([^\\s]+)${RETEST_MARKER_SUFFIX}`); + // Marker left on a PR after we file its retest request, so a re-run of the deploy doesn't file a duplicate. -const getRetestMarker = (tag: string) => ``; +const getRetestMarker = (tag: string) => `${RETEST_MARKER_PREFIX}${tag}${RETEST_MARKER_SUFFIX}`; + +// A later deploy can include the same cherry-pick, so its commit needs a marker independent of the deploy tag. +const getCherryPickRetestMarker = (sha: string) => `${CHERRY_PICK_RETEST_MARKER_PREFIX}${sha}${RETEST_MARKER_SUFFIX}`; +const getPendingRetestMarker = (sha: string) => `${PENDING_RETEST_MARKER_PREFIX}${sha}${RETEST_MARKER_SUFFIX}`; const DEPLOYER_CHANNEL_ID = 'C07J32337'; const RETESTS_CHANNEL_ID = 'C09V78U42D8'; const SLACK_HISTORY_PAGE_SIZE = 100; const CHERRY_PICK_REQUEST_HISTORY_MAX_PAGES = 20; const RETEST_MESSAGE_HISTORY_MAX_PAGES = 1; +const RETEST_RECOVERY_HISTORY_MAX_PAGES = 20; const RETEST_MESSAGE_LOOKUP_ATTEMPTS = 6; const RETEST_MESSAGE_LOOKUP_DELAY_MS = 5000; +const HTTP_CLIENT_ERROR_MIN = 400; +const HTTP_SERVER_ERROR_MIN = 500; +const HTTP_REQUEST_TIMEOUT = 408; +const HTTP_CLIENT_CLOSED_REQUEST = 499; +const RETEST_WEBHOOK_ERROR_NAME = 'RetestWebhookError'; type RetestHit = { prNumber: number; prURL: string; prAuthor: string; + cherryPickSHA: string; // A single PR can fix more than one deploy blocker, so all of them go in one retest request. blockerIssueURLs: string[]; prTitle: string; @@ -55,9 +72,32 @@ type RetestHit = { type CherryPick = { sourceSHA: string; + cherryPickSHA: string; actor: string; }; +type DeployedCommit = { + sha: string; + message: string; +}; + +type RevertTargets = { + commitSHAs: string[]; + pullNumbers: number[]; +}; + +type RetestWebhookError = Error & {status: number}; + +class PendingRetestRequestError extends Error { + readonly deployTag: string; + + constructor(prNumber: number, deployTag: string) { + super(`Retest for PR #${prNumber} on ${deployTag} is pending; check Slack before retrying.`); + this.name = 'PendingRetestRequestError'; + this.deployTag = deployTag; + } +} + type SlackMessage = { text?: string; ts: string; @@ -84,6 +124,10 @@ function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null; } +function isRetestWebhookError(error: unknown): error is RetestWebhookError { + return error instanceof Error && error.name === RETEST_WEBHOOK_ERROR_NAME && 'status' in error && typeof error.status === 'number'; +} + function isSlackResponse(value: unknown): value is SlackResponse { return isRecord(value) && typeof value.ok === 'boolean' && (value.error === undefined || typeof value.error === 'string'); } @@ -113,45 +157,49 @@ function isSlackPermalinkResponse(value: unknown): value is SlackPermalinkRespon return isRecord(value) && (value.permalink === undefined || typeof value.permalink === 'string'); } -/** - * List the commit messages deployed since the previous staging release. - * We look at the whole range, not just HEAD, because a cherry-pick pushes several commits - * (version bumps plus the actual picked commit) and the picked commit isn't always HEAD. - */ -async function getDeployedCommitMessages(deploySHA: string, deployTag: string): Promise { - let previousStagingTag: string | null = null; - for (let page = 1; !previousStagingTag; page++) { - const {data: tags} = await GithubUtils.octokit.repos.listTags({ +/** Use the same release boundary as the checklist so canceled deploys cannot hide earlier cherry-picks. */ +async function getPreviousChecklistTag(checklistNumber: number): Promise { + let foundCurrentChecklist = false; + for (let page = 1; ; page++) { + const {data: checklists} = await GithubUtils.octokit.issues.listForRepo({ owner: CONST.GITHUB_OWNER, repo: CONST.APP_REPO, - per_page: TAGS_PER_PAGE, + labels: CONST.LABELS.STAGING_DEPLOY, + state: 'all', + sort: 'created', + direction: 'desc', + per_page: GITHUB_PAGE_SIZE, page, }); - if (tags.length === 0) { - break; + for (const checklist of checklists) { + if (foundCurrentChecklist) { + const previousChecklist = getDeployChecklistData(checklist); + if (!previousChecklist.version) { + throw new Error(`Previous deploy checklist #${checklist.number} has no release version.`); + } + return previousChecklist.tag; + } + foundCurrentChecklist = checklist.number === checklistNumber; } - previousStagingTag = tags.find((tag) => tag.name !== deployTag && tag.name.endsWith('-staging'))?.name ?? null; - if (tags.length < TAGS_PER_PAGE) { + if (checklists.length < GITHUB_PAGE_SIZE) { break; } } + throw new Error(`Could not find the deploy checklist before #${checklistNumber}.`); +} - if (!previousStagingTag) { - const {data: headCommit} = await GithubUtils.octokit.git.getCommit({ - owner: CONST.GITHUB_OWNER, - repo: CONST.APP_REPO, - commit_sha: deploySHA, - }); - return [headCommit.message]; - } +/** Fetch every commit in the release; GitHub truncates unpaginated comparisons at 250 commits. */ +async function getDeployedCommits(previousTag: string, deploySHA: string): Promise { + const commits = await GithubUtils.getCommitHistoryBetweenTags(previousTag, deploySHA, CONST.APP_REPO); + return commits.map((commit) => ({sha: commit.commit, message: commit.subject})); +} - const {data: comparison} = await GithubUtils.octokit.repos.compareCommits({ - owner: CONST.GITHUB_OWNER, - repo: CONST.APP_REPO, - base: previousStagingTag, - head: deploySHA, - }); - return comparison.commits.map((commit) => commit.commit.message); +const CHERRY_PICK_SOURCE_REGEX = /cherry picked from commit ([0-9a-f]{7,40})/g; +const REVERTED_COMMIT_REGEX = /\bthis reverts commit ([0-9a-f]{7,40})\b/gi; +const APP_PULL_REFERENCE = `(?:${CONST.APP_REPO_URL.replaceAll('.', '\\.')}/pull/|${CONST.GITHUB_OWNER}/${CONST.APP_REPO}#|(? match[1]); } /** @@ -160,37 +208,192 @@ async function getDeployedCommitMessages(deploySHA: string, deployTag: string): * 2. `(cherry-picked to by )` amended by the cherry-pick workflow, which names who asked for it. * They live in the same message, so each cherry-pick keeps its own requester. */ -function getCherryPicks(commitMessages: string[]): CherryPick[] { - const actorBySHA = new Map(); - for (const message of commitMessages) { +function getCherryPicks(commits: DeployedCommit[]): CherryPick[] { + const cherryPicksBySourceSHA = new Map(); + for (const {sha, message} of commits) { const actor = message.match(/\(cherry-picked to .* by (.+?)\)/)?.[1] ?? ''; - for (const match of message.matchAll(/cherry picked from commit ([0-9a-f]{7,40})/g)) { - if (actorBySHA.has(match[1])) { - continue; - } - actorBySHA.set(match[1], actor); + for (const sourceSHA of getCherryPickSourceSHAs(message)) { + // Reinsert repeated sources so PRs associated with multiple commits use the latest pick and requester. + cherryPicksBySourceSHA.delete(sourceSHA); + cherryPicksBySourceSHA.set(sourceSHA, {sourceSHA, cherryPickSHA: sha, actor}); } } - return [...actorBySHA].map(([sourceSHA, actor]) => ({sourceSHA, actor})); + return [...cherryPicksBySourceSHA.values()]; } /** Resolve the original App PRs that produced the cherry-picked commits, keeping who requested each one. */ -async function getCherryPickActorByPullRequest(cherryPicks: CherryPick[]): Promise> { - const actorByPR = new Map(); - for (const {sourceSHA, actor} of cherryPicks) { +async function getCherryPicksByPullRequest(cherryPicks: CherryPick[]): Promise> { + const cherryPickByPR = new Map(); + for (const cherryPick of cherryPicks) { const {data: pulls} = await GithubUtils.octokit.repos.listPullRequestsAssociatedWithCommit({ owner: CONST.GITHUB_OWNER, repo: CONST.APP_REPO, - commit_sha: sourceSHA, + commit_sha: cherryPick.sourceSHA, }); for (const pull of pulls) { - if (actorByPR.has(pull.number)) { + cherryPickByPR.set(pull.number, cherryPick); + } + } + return cherryPickByPR; +} + +function getRevertedCommitSHAs(text: string): string[] { + return [...text.matchAll(REVERTED_COMMIT_REGEX)].map((match) => match[1].toLowerCase()); +} + +function getRevertedPullNumbers(text: string): number[] { + const pullNumbers = new Set(); + // Revert descriptions can mention unrelated PRs, so only explicit targets and revert lists count. + const directReference = new RegExp(`\\brevert(?:s|ed|ing)?\\b\\s+(?:(?:of|the|a|PR|pull request)\\s+)*(?:\\[[^\\]\\n]+\\]\\()?${APP_PULL_REFERENCE}`, 'gi'); + const pullReference = new RegExp(APP_PULL_REFERENCE, 'gi'); + for (const match of text.matchAll(directReference)) { + pullNumbers.add(Number.parseInt(match[1], 10)); + } + + const lines = text.split(/\r?\n/); + for (let index = 0; index < lines.length; index++) { + if (!/\brevert(?:s|ed|ing)?\b[^\r\n]*:\s*$/i.test(lines[index])) { + continue; + } + let listStarted = false; + for (const line of lines.slice(index + 1)) { + if (!line.trim() && !listStarted) { continue; } - actorByPR.set(pull.number, actor); + if (!/^\s*[-*]\s+/.test(line)) { + break; + } + listStarted = true; + for (const match of line.matchAll(pullReference)) { + pullNumbers.add(Number.parseInt(match[1], 10)); + } + } + } + return [...pullNumbers]; +} + +function getDeployedPullNumber(message: string): number | undefined { + const subject = message.split('\n')[0] ?? ''; + const match = subject.match(/^Merge pull request #(\d+)\b/) ?? subject.match(/\(#(\d+)\)\s*$/); + return match ? Number.parseInt(match[1], 10) : undefined; +} + +function isRevertCommit(message: string): boolean { + const lines = message.split('\n'); + const subject = lines[0] ?? ''; + const title = subject.startsWith('Merge pull request #') ? (lines.slice(1).find((line) => line.trim()) ?? '') : subject; + return /^(?:\[[^\]]+\]\s*)*(?:revert(?:s|ed)?|rollback|roll back)\b/i.test(title.trim()); +} + +/** Cherry-picking a revert PR's merge commit can omit the revert trailers from its individual commits. */ +async function getRevertTargetsForPullRequest(pullNumber: number): Promise { + const {data: pull} = await GithubUtils.octokit.pulls.get({ + owner: CONST.GITHUB_OWNER, + repo: CONST.APP_REPO, + pull_number: pullNumber, + }); + const texts = [pull.title, pull.body ?? '']; + for (let page = 1; ; page++) { + const {data: commits} = await GithubUtils.octokit.pulls.listCommits({ + owner: CONST.GITHUB_OWNER, + repo: CONST.APP_REPO, + pull_number: pullNumber, + per_page: GITHUB_PAGE_SIZE, + page, + }); + texts.push(...commits.map((commit) => commit.commit.message)); + if (commits.length < GITHUB_PAGE_SIZE) { + break; + } + } + return { + commitSHAs: [...new Set(texts.flatMap(getRevertedCommitSHAs))], + pullNumbers: [...new Set(texts.flatMap(getRevertedPullNumbers))], + }; +} + +function hasRevertedSHA(sha: string, revertedSHAs: Set): boolean { + for (const revertedSHA of revertedSHAs) { + // Either trailer can use Git's abbreviated SHA, so compare both prefixes. + if (sha.startsWith(revertedSHA) || revertedSHA.startsWith(sha)) { + return true; + } + } + return false; +} + +/** Ignore picks that were undone before this deploy, while keeping re-picks and reverted reverts. */ +async function filterRevertedCherryPicks(commits: DeployedCommit[], cherryPickByPR: Map): Promise> { + const pickSHAs = new Set([...cherryPickByPR.values()].map((pick) => pick.cherryPickSHA)); + const firstPickIndex = commits.findIndex((commit) => pickSHAs.has(commit.sha)); + if (firstPickIndex < 0) { + throw new Error('Could not find the cherry-picked commits in the deployment history.'); + } + // Reverts before every candidate cannot undo those picks and do not need GitHub lookups. + const relevantCommits = commits.slice(firstPickIndex); + const revertTargetsByCommit = new Map(); + const revertTargetsByPR = new Map(); + for (const commit of relevantCommits) { + const commitSHAs = getRevertedCommitSHAs(commit.message); + const pullNumbers: number[] = []; + const pullNumber = getDeployedPullNumber(commit.message); + if (pullNumber && isRevertCommit(commit.message)) { + let targets = revertTargetsByPR.get(pullNumber); + if (!targets) { + targets = await getRevertTargetsForPullRequest(pullNumber); + revertTargetsByPR.set(pullNumber, targets); + } + commitSHAs.push(...targets.commitSHAs); + pullNumbers.push(...targets.pullNumbers); + if (commitSHAs.length === 0 && pullNumbers.length === 0) { + throw new Error(`Could not identify the target of revert PR #${pullNumber}.`); + } + } + if (commitSHAs.length > 0 || pullNumbers.length > 0) { + revertTargetsByCommit.set(commit.sha, {commitSHAs, pullNumbers}); + } + } + if (revertTargetsByCommit.size === 0) { + return cherryPickByPR; + } + + const activePicks = new Map(cherryPickByPR); + const pullNumbersByCommit = new Map(); + for (const [pullNumber, cherryPick] of cherryPickByPR) { + const pullNumbers = pullNumbersByCommit.get(cherryPick.cherryPickSHA) ?? []; + pullNumbers.push(pullNumber); + pullNumbersByCommit.set(cherryPick.cherryPickSHA, pullNumbers); + } + const revertedSHAs = new Set(); + const revertedPullNumbers = new Set(); + // Newer reverts have to be applied first so an undone revert cannot cancel its targets. + for (const commit of relevantCommits.toReversed()) { + const pullNumber = getDeployedPullNumber(commit.message); + const pickedPRs = pullNumbersByCommit.get(commit.sha) ?? []; + const isReverted = + hasRevertedSHA(commit.sha, revertedSHAs) || + getCherryPickSourceSHAs(commit.message).some((sha) => hasRevertedSHA(sha, revertedSHAs)) || + (pullNumber !== undefined && revertedPullNumbers.has(pullNumber)) || + pickedPRs.some((number) => revertedPullNumbers.has(number)); + // A reverted revert no longer cancels its own targets. + if (isReverted) { + for (const number of pickedPRs) { + activePicks.delete(number); + } + continue; + } + const targets = revertTargetsByCommit.get(commit.sha); + if (!targets) { + continue; + } + for (const sha of targets.commitSHAs) { + revertedSHAs.add(sha); + } + for (const number of targets.pullNumbers) { + revertedPullNumbers.add(number); } } - return actorByPR; + return activePicks; } /** Map every GitHub login in the employee whitelist to its Slack member ID. */ @@ -246,11 +449,62 @@ function getLinkedIssueNumbers(prBody: string | null): number[] { return [...issueNumbers]; } -/** Has a retest request for this staging deploy already been filed on this PR? */ -async function isRetestAlreadyRequested(prNumber: number, deployTag: string): Promise { +/** Find the original tag so reruns can avoid duplicate requests and locate the existing Slack message. */ +async function getRequestedRetestTag(prNumber: number, cherryPickSHA: string, deployTag: string): Promise { const comments = await GithubUtils.getAllComments(prNumber); - const marker = getRetestMarker(deployTag); - return comments.some((comment) => comment?.includes(marker)); + const legacyTags: string[] = []; + let pendingTag: string | undefined; + for (const comment of comments) { + const tag = comment?.match(RETEST_MARKER_REGEX)?.[1]; + if (!comment || !tag) { + continue; + } + if (comment.includes(getCherryPickRetestMarker(cherryPickSHA))) { + return tag; + } + if (comment.includes(getPendingRetestMarker(cherryPickSHA))) { + pendingTag = tag; + continue; + } + if (comment.includes(CHERRY_PICK_RETEST_MARKER_PREFIX) || comment.includes(PENDING_RETEST_MARKER_PREFIX)) { + continue; + } + if (tag === deployTag) { + return tag; + } + + legacyTags.push(tag); + } + + let firstError: unknown; + let didFail = false; + for (const tag of legacyTags) { + try { + // Older comments only record the tag; check that the tagged deploy contained this exact pick. + const {data: comparison} = await GithubUtils.octokit.repos.compareCommits({ + owner: CONST.GITHUB_OWNER, + repo: CONST.APP_REPO, + base: cherryPickSHA, + head: tag, + per_page: 1, + }); + if (comparison.status === 'ahead' || comparison.status === 'identical') { + return tag; + } + } catch (error) { + if (!didFail) { + firstError = error; + didFail = true; + } + } + } + if (pendingTag) { + throw new PendingRetestRequestError(prNumber, pendingTag); + } + if (didFail) { + throw firstError; + } + return undefined; } /** Map a hit to the flat string payload the Slack workflow webhook expects. */ @@ -268,6 +522,10 @@ function buildRetestPayload(hit: RetestHit, deployTag: string): Record { const payload = buildRetestPayload(hit, deployTag); @@ -278,7 +536,10 @@ async function fireRetestRequest(hit: RetestHit, deployTag: string, webhookURL: body: JSON.stringify(payload), }); if (!response.ok) { - throw new Error(`Slack webhook returned ${response.status} ${response.statusText}: ${await response.text()}`); + throw Object.assign(new Error(`Slack webhook returned ${response.status} ${response.statusText}: ${await response.text()}`), { + name: RETEST_WEBHOOK_ERROR_NAME, + status: response.status, + }); } } @@ -348,15 +609,30 @@ async function findSlackMessage( return undefined; } +function hasRetestRequestReference(message: SlackMessage, reference: string): boolean { + const text = message.text ?? ''; + let index = text.indexOf(reference); + while (index >= 0) { + const nextCharacter = text[index + reference.length]; + // A shorter PR number must not match the prefix of a longer one. + if (nextCharacter === undefined || !/\d/.test(nextCharacter)) { + return true; + } + index = text.indexOf(reference, index + reference.length); + } + return false; +} + /** Slack Workflow Builder posts asynchronously, so wait briefly for the retest request to appear. */ -async function findRetestRequestMessage(hit: RetestHit, deployTag: string, token: string): Promise { +async function findRetestRequestMessage(hit: RetestHit, deployTag: string, token: string, maxPages = RETEST_MESSAGE_HISTORY_MAX_PAGES): Promise { const reference = getRetestRequestReference(hit, deployTag); for (let attempt = 1; attempt <= RETEST_MESSAGE_LOOKUP_ATTEMPTS; attempt++) { const message = await findSlackMessage( RETESTS_CHANNEL_ID, token, - (candidate) => isTopLevelSlackMessage(candidate) && candidate.text?.includes(reference) === true, - RETEST_MESSAGE_HISTORY_MAX_PAGES, + (candidate) => isTopLevelSlackMessage(candidate) && hasRetestRequestReference(candidate, reference), + // A newly posted request appears on the newest page; only the first lookup needs older pages. + attempt === 1 ? maxPages : RETEST_MESSAGE_HISTORY_MAX_PAGES, ); if (message) { return message; @@ -402,8 +678,8 @@ function buildRetestLinkReply(threadTS: string, retestPermalink: string): Record } /** Add the retest request link to the Cherry Pick Request that triggered the deploy. */ -async function postRetestRequestLink(hit: RetestHit, deployTag: string, token: string, deployerWebhookURL: string): Promise { - const retestRequest = await findRetestRequestMessage(hit, deployTag, token); +async function postRetestRequestLink(hit: RetestHit, deployTag: string, token: string, deployerWebhookURL: string, existingRequest?: SlackMessage): Promise { + const retestRequest = existingRequest ?? (await findRetestRequestMessage(hit, deployTag, token)); if (!retestRequest) { console.warn(`Could not find the retest request for PR #${hit.prNumber} on ${deployTag}.`); return; @@ -437,8 +713,96 @@ async function postRetestRequestLink(hit: RetestHit, deployTag: string, token: s console.log(`Added the retest request link to the Cherry Pick Request thread for PR #${hit.prNumber}.`); } +/** Keep an unavailable legacy tag or a failed request from blocking the other fixes in this deploy. */ +async function fileRetestRequests(hits: RetestHit[], deployTag: string, webhookURL: string, slackToken?: string, deployerWebhookURL?: string): Promise { + const failedPRs: number[] = []; + for (const hit of hits) { + try { + let requestedTag: string | undefined; + let recoveredRequest: SlackMessage | undefined; + try { + requestedTag = await getRequestedRetestTag(hit.prNumber, hit.cherryPickSHA, deployTag); + } catch (error) { + if (!(error instanceof PendingRetestRequestError) || !slackToken) { + throw error; + } + // A webhook can succeed even if its confirmation comment fails. Never post again until Slack confirms the outcome. + recoveredRequest = await findRetestRequestMessage(hit, error.deployTag, slackToken, RETEST_RECOVERY_HISTORY_MAX_PAGES); + if (!recoveredRequest) { + throw error; + } + await GithubUtils.createComment(CONST.APP_REPO, hit.prNumber, buildRetestComment(hit, error.deployTag)); + requestedTag = error.deployTag; + } + if (!requestedTag) { + // Save the pending state before the webhook so a failed confirmation cannot cause a duplicate. + const pendingComment = await GithubUtils.createComment( + CONST.APP_REPO, + hit.prNumber, + `${getRetestMarker(deployTag)}\n${getPendingRetestMarker(hit.cherryPickSHA)}\n⏳ Staging retest request is being filed. If it stays pending, check #retests before retrying.`, + ); + try { + await fireRetestRequest(hit, deployTag, webhookURL); + } catch (error) { + // Timeouts and client disconnects can be ambiguous even when returned as 4xx responses. + if ( + isRetestWebhookError(error) && + error.status >= HTTP_CLIENT_ERROR_MIN && + error.status < HTTP_SERVER_ERROR_MIN && + error.status !== HTTP_REQUEST_TIMEOUT && + error.status !== HTTP_CLIENT_CLOSED_REQUEST + ) { + try { + // A client error confirms Slack rejected the request, so a later deploy may retry it. + await GithubUtils.octokit.issues.updateComment({ + owner: CONST.GITHUB_OWNER, + repo: CONST.APP_REPO, + comment_id: pendingComment.data.id, + body: `⚠️ Slack rejected the Staging retest request (HTTP ${error.status}). A later deploy can retry it.`, + }); + } catch (updateError) { + console.error(`Could not record the rejected retest request for PR #${hit.prNumber}.`, updateError); + } + } + throw error; + } + await GithubUtils.octokit.issues.updateComment({ + owner: CONST.GITHUB_OWNER, + repo: CONST.APP_REPO, + comment_id: pendingComment.data.id, + body: buildRetestComment(hit, deployTag), + }); + console.log(`Filed retest request for PR #${hit.prNumber} (blockers ${hit.blockerIssueURLs.join(', ')}).`); + } else { + console.log(`Retest for PR #${hit.prNumber} was already filed on ${requestedTag}.`); + // Searching old Slack history on every deploy can delay new requests; the original deploy can retry its link. + if (requestedTag !== deployTag && !recoveredRequest) { + continue; + } + } + + if (!slackToken || !deployerWebhookURL) { + console.warn(`Cannot add the retest request link for PR #${hit.prNumber}: ${!slackToken ? 'SLACK_RETEST_USER_TOKEN' : 'SLACK_WEBHOOK'} is not configured.`); + continue; + } + try { + await postRetestRequestLink(hit, requestedTag ?? deployTag, slackToken, deployerWebhookURL, recoveredRequest); + } catch (error) { + // The retest has already been filed. Keep a Slack lookup or reply failure from marking the deploy unsuccessful. + console.warn(`Could not add the retest request link to the Cherry Pick Request thread for PR #${hit.prNumber}.`, error); + } + } catch (error) { + failedPRs.push(hit.prNumber); + console.error(`Could not process the retest request for PR #${hit.prNumber}.`, error); + } + } + if (failedPRs.length > 0) { + throw new Error(`Could not process retest requests for PRs ${failedPRs.map((number) => `#${number}`).join(', ')}.`); + } +} + async function run(): Promise { - // Gate 1 (this deploy is a cherry-pick to staging, on all platforms) is enforced by the job's `if:` in deploy.yml. + // Gate 1 (staging deployed on all platforms) is enforced by the job's `if:` in deploy.yml. const cli = new CLI({ namedArgs: { 'deploy-sha': {description: 'The deploy commit SHA on the staging branch', required: true}, @@ -456,20 +820,6 @@ async function run(): Promise { const slackToken = process.env.SLACK_RETEST_USER_TOKEN; const deployerWebhookURL = process.env.SLACK_WEBHOOK; - const commitMessages = await getDeployedCommitMessages(deploySHA, deployTag); - const cherryPicks = getCherryPicks(commitMessages); - if (cherryPicks.length === 0) { - console.log('No cherry-pick source commits found in this deploy, nothing to do.'); - return; - } - - const cherryPickActorByPR = await getCherryPickActorByPullRequest(cherryPicks); - const candidatePRNumbers = [...cherryPickActorByPR.keys()]; - if (candidatePRNumbers.length === 0) { - console.log('No original PRs resolved from cherry-pick source commits, nothing to do.'); - return; - } - let checklist; try { checklist = await getDeployChecklist(); @@ -481,17 +831,32 @@ async function run(): Promise { throw error; } - const slackIDsByGithubLogin = await getSlackIDsByGithubLogin(); const checklistPRNumbers = new Set(checklist.PRList.map((item) => item.number)); const blockerIssueByNumber = new Map(checklist.deployBlockers.map((item) => [item.number, item.url])); + if (checklistPRNumbers.size === 0 || blockerIssueByNumber.size === 0) { + console.log('No checklist pull requests or deploy blockers, nothing to file.'); + return; + } - const hits: RetestHit[] = []; - for (const prNumber of candidatePRNumbers) { - // Gate 2: the cherry-picked PR must be on the current checklist. - if (!checklistPRNumbers.has(prNumber)) { - continue; - } + const previousTag = await getPreviousChecklistTag(checklist.number); + const commits = await getDeployedCommits(previousTag, deploySHA); + const cherryPicks = getCherryPicks(commits); + if (cherryPicks.length === 0) { + console.log('No cherry-pick source commits found in this deploy, nothing to do.'); + return; + } + + const cherryPickByPR = await getCherryPicksByPullRequest(cherryPicks); + const checklistCherryPicks = new Map([...cherryPickByPR].filter(([prNumber]) => checklistPRNumbers.has(prNumber))); + if (checklistCherryPicks.size === 0) { + console.log('No cherry-picked PRs found on the deploy checklist, nothing to do.'); + return; + } + const activeCherryPickByPR = await filterRevertedCherryPicks(commits, checklistCherryPicks); + let slackIDsByGithubLogin: Map | undefined; + const hits: RetestHit[] = []; + for (const [prNumber, cherryPick] of activeCherryPickByPR) { const {data: pull} = await GithubUtils.octokit.pulls.get({ owner: CONST.GITHUB_OWNER, repo: CONST.APP_REPO, @@ -507,13 +872,15 @@ async function run(): Promise { continue; } + slackIDsByGithubLogin ??= await getSlackIDsByGithubLogin(); hits.push({ prNumber, prURL: pull.html_url, prAuthor: pull.user?.login ?? '', + cherryPickSHA: cherryPick.cherryPickSHA, blockerIssueURLs, prTitle: pull.title, - author: getSlackAuthor(cherryPickActorByPR.get(prNumber) ?? '', slackIDsByGithubLogin), + author: getSlackAuthor(cherryPick.actor, slackIDsByGithubLogin), }); } @@ -522,31 +889,7 @@ async function run(): Promise { return; } - for (const hit of hits) { - if (!(await isRetestAlreadyRequested(hit.prNumber, deployTag))) { - await fireRetestRequest(hit, deployTag, webhookURL); - const blockerList = hit.blockerIssueURLs.join(', '); - await GithubUtils.createComment( - CONST.APP_REPO, - hit.prNumber, - `${getRetestMarker(deployTag)}\n🔁 Filed a Staging retest request for deploy blockers ${blockerList} after this PR was cherry-picked to staging.`, - ); - console.log(`Filed retest request for PR #${hit.prNumber} (blockers ${blockerList}).`); - } else { - console.log(`Retest for PR #${hit.prNumber} on ${deployTag} was already filed, checking its Cherry Pick Request thread.`); - } - - if (!slackToken || !deployerWebhookURL) { - console.warn(`Cannot add the retest request link for PR #${hit.prNumber}: ${!slackToken ? 'SLACK_RETEST_USER_TOKEN' : 'SLACK_WEBHOOK'} is not configured.`); - continue; - } - try { - await postRetestRequestLink(hit, deployTag, slackToken, deployerWebhookURL); - } catch (error) { - // The retest has already been filed. Keep a Slack lookup or reply failure from marking the deploy unsuccessful. - console.warn(`Could not add the retest request link to the Cherry Pick Request thread for PR #${hit.prNumber}.`, error); - } - } + await fileRetestRequests(hits, deployTag, webhookURL, slackToken, deployerWebhookURL); } if (require.main === module) { @@ -557,5 +900,22 @@ if (require.main === module) { } export default run; -export {getCherryPicks, getLinkedIssueNumbers, buildRetestPayload, buildRetestLinkReply, getRetestMarker, getRetestRequestReference, getSlackAuthor, isCherryPickRequest}; +export { + getCherryPicks, + filterRevertedCherryPicks, + getRevertedPullNumbers, + getDeployedCommits, + getPreviousChecklistTag, + getRequestedRetestTag, + fileRetestRequests, + getLinkedIssueNumbers, + buildRetestPayload, + buildRetestLinkReply, + getRetestMarker, + getCherryPickRetestMarker, + getPendingRetestMarker, + getRetestRequestReference, + getSlackAuthor, + isCherryPickRequest, +}; export type {RetestHit, SlackMessage}; diff --git a/tests/tooling/createRetestRequestForCP.test.ts b/tests/tooling/createRetestRequestForCP.test.ts index e0152ca30943..bca3a76f25ee 100644 --- a/tests/tooling/createRetestRequestForCP.test.ts +++ b/tests/tooling/createRetestRequestForCP.test.ts @@ -1,47 +1,1004 @@ // cspell:ignore Julesssss jasperhuangg GYJH // Slack API fields use snake case. /* eslint-disable @typescript-eslint/naming-convention */ -import {describe, expect, it} from 'bun:test'; +import type {Mock} from 'bun:test'; +import {afterAll, afterEach, beforeAll, describe, expect, it, jest} from 'bun:test'; import CONST from '@github/libs/CONST'; +import GithubUtils from '@github/libs/GithubUtils'; +import type {InternalOctokit} from '@github/libs/GithubUtils'; -import { +import run, { buildRetestLinkReply, buildRetestPayload, + fileRetestRequests, + filterRevertedCherryPicks, + getCherryPickRetestMarker, getCherryPicks, + getDeployedCommits, getLinkedIssueNumbers, + getPreviousChecklistTag, + getPendingRetestMarker, + getRevertedPullNumbers, getRetestMarker, getRetestRequestReference, + getRequestedRetestTag, getSlackAuthor, isCherryPickRequest, } from '@scripts/createRetestRequestForCP'; import type {RetestHit, SlackMessage} from '@scripts/createRetestRequestForCP'; +import fs from 'fs'; + +import createMock from '../utils/createMock'; +import materializeOctokitNamespace from '../utils/materializeOctokitNamespace'; + +type CompareCommits = InternalOctokit['rest']['repos']['compareCommits']; +type CompareResponse = Awaited>; +type ListForRepo = InternalOctokit['rest']['issues']['listForRepo']; +type ListForRepoResponse = Awaited>; +type ListPulls = InternalOctokit['rest']['repos']['listPullRequestsAssociatedWithCommit']; +type GetPull = InternalOctokit['rest']['pulls']['get']; +type UpdateComment = InternalOctokit['rest']['issues']['updateComment']; + +let compareCommits: Mock; +let listForRepo: Mock; +let getAllComments: Mock; +let octokit: InternalOctokit; +let compareStatics: Pick; +let listStatics: Pick; + +beforeAll(() => { + GithubUtils.initOctokitWithToken('fake_token'); + if (!GithubUtils.internalOctokit) { + throw new Error('Expected GithubUtils to initialize an Octokit client.'); + } + octokit = GithubUtils.internalOctokit; + octokit.rest.issues = materializeOctokitNamespace(octokit.rest.issues); + octokit.rest.repos = materializeOctokitNamespace(octokit.rest.repos); + octokit.rest.pulls = materializeOctokitNamespace(octokit.rest.pulls); + compareStatics = {endpoint: octokit.rest.repos.compareCommits.endpoint, defaults: octokit.rest.repos.compareCommits.defaults}; + listStatics = {endpoint: octokit.rest.issues.listForRepo.endpoint, defaults: octokit.rest.issues.listForRepo.defaults}; + compareCommits = jest.spyOn(octokit.rest.repos, 'compareCommits'); + listForRepo = jest.spyOn(octokit.rest.issues, 'listForRepo'); + getAllComments = jest.spyOn(GithubUtils, 'getAllComments'); +}); + +afterEach(() => { + compareCommits.mockReset(); + listForRepo.mockReset(); + getAllComments.mockReset(); +}); + +afterAll(() => { + jest.restoreAllMocks(); +}); + describe('createRetestRequestForCP', () => { describe('getCherryPicks', () => { it('pulls the source SHA and the requester out of the trailers', () => { + // Given a deployed cherry-pick with both Git trailers const message = 'Fix the thing\n\n(cherry picked from commit 1234567890abcdef1234567890abcdef12345678)\n\n(cherry-picked to staging by Julesssss)'; - expect(getCherryPicks([message])).toEqual([{sourceSHA: '1234567890abcdef1234567890abcdef12345678', actor: 'Julesssss'}]); + + // When the deploy is inspected + const result = getCherryPicks([{sha: 'picked-sha', message}]); + + // Then the request keeps the original PR, the exact pick, and its requester + expect(result).toEqual([{sourceSHA: '1234567890abcdef1234567890abcdef12345678', cherryPickSHA: 'picked-sha', actor: 'Julesssss'}]); }); - it('keeps each cherry-pick with its own requester and dedupes repeats', () => { - const messages = [ - '(cherry picked from commit aaaaaaa)\n\n(cherry-picked to staging by mountiny)', - '(cherry picked from commit bbbbbbb)\n\n(cherry-picked to staging by Julesssss)', - '(cherry picked from commit aaaaaaa)\n\n(cherry-picked to staging by someoneElse)', + it('uses the latest pick and requester if a PR is picked again after a revert', () => { + // Given two PRs and a second pick of the first PR + const commits = [ + {sha: 'first-pick', message: '(cherry picked from commit aaaaaaa)\n\n(cherry-picked to staging by mountiny)'}, + {sha: 'second-pick', message: '(cherry picked from commit bbbbbbb)\n\n(cherry-picked to staging by Julesssss)'}, + {sha: 're-pick', message: '(cherry picked from commit aaaaaaa)\n\n(cherry-picked to staging by someoneElse)'}, ]; - expect(getCherryPicks(messages)).toEqual([ - {sourceSHA: 'aaaaaaa', actor: 'mountiny'}, - {sourceSHA: 'bbbbbbb', actor: 'Julesssss'}, + + // When the release is scanned for cherry-picks + const result = getCherryPicks(commits); + + // Then the re-applied fix can receive a new retest with the correct requester + expect(result).toEqual([ + {sourceSHA: 'bbbbbbb', cherryPickSHA: 'second-pick', actor: 'Julesssss'}, + {sourceSHA: 'aaaaaaa', cherryPickSHA: 're-pick', actor: 'someoneElse'}, ]); }); it('still returns the SHA when the requester trailer is missing', () => { - expect(getCherryPicks(['(cherry picked from commit aaaaaaa)'])).toEqual([{sourceSHA: 'aaaaaaa', actor: ''}]); + // Given a manually resolved pick without a requester trailer + const commits = [{sha: 'picked-sha', message: '(cherry picked from commit aaaaaaa)'}]; + + // When the release is scanned + const result = getCherryPicks(commits); + + // Then the fix remains eligible for a retest + expect(result).toEqual([{sourceSHA: 'aaaaaaa', cherryPickSHA: 'picked-sha', actor: ''}]); }); it('returns nothing when no commit was cherry-picked', () => { - expect(getCherryPicks(['Merge pull request #1 from foo/bar', 'Update version to 1.2.3-4'])).toEqual([]); + // Given a staging deploy with only ordinary commits + const commits = [ + {sha: 'merge', message: 'Merge pull request #1 from foo/bar'}, + {sha: 'version', message: 'Update version to 1.2.3-4'}, + ]; + + // When the release is scanned + const result = getCherryPicks(commits); + + // Then no retest is requested + expect(result).toEqual([]); + }); + }); + + describe('release commit range', () => { + it('finds the preceding checklist even when it is on the next page', async () => { + // Given the current checklist is the last entry on a GitHub page + const checklists = Array.from({length: 100}, (_, index) => ({number: 1000 - index})); + listForRepo.mockResolvedValueOnce(createMock({data: checklists})); + listForRepo.mockResolvedValueOnce( + createMock({ + data: [{number: 900, url: 'https://api.github.com/repos/Expensify/App/issues/900', body: '**Release Version:** `9.5.23-3`'}], + }), + ); + + // When the scan finds the start of the current release + const tag = await getPreviousChecklistTag(901); + + // Then it uses the preceding checklist instead of a tag from a canceled deploy + expect(tag).toBe('9.5.23-3-staging'); + expect(listForRepo).toHaveBeenCalledTimes(2); + }); + + it('fails rather than silently missing picks if the previous checklist is unavailable', async () => { + // Given GitHub cannot find a previous checklist + listForRepo.mockResolvedValueOnce(createMock({data: [{number: 901}]})); + + // When the release boundary is requested + const result = getPreviousChecklistTag(901); + + // Then the failure is surfaced instead of hiding picks from canceled deploys + await expect(result).rejects.toThrow('Could not find the deploy checklist before #901.'); + }); + + it('fetches picks beyond GitHub’s unpaginated comparison limit', async () => { + // Given a large release where three consecutive picks appear after the first 300 commits + const ordinaryCommits = Array.from({length: 300}, (_, index) => ({sha: `commit-${index}`, commit: {message: 'A normal commit'}})); + compareCommits.mockResolvedValueOnce(createMock({data: {commits: ordinaryCommits.slice(0, 250)}})); + compareCommits.mockResolvedValueOnce( + createMock({ + data: { + commits: [ + ...ordinaryCommits.slice(250), + {sha: 'pick-a', commit: {message: '(cherry picked from commit aaaaaaa)\n\n(cherry-picked to staging by first)'}}, + {sha: 'pick-b', commit: {message: '(cherry picked from commit bbbbbbb)\n\n(cherry-picked to staging by second)'}}, + {sha: 'pick-c', commit: {message: '(cherry picked from commit ccccccc)\n\n(cherry-picked to staging by third)'}}, + ], + }, + }), + ); + + // When the successful deploy scans the entire release + const commits = await getDeployedCommits('9.5.23-3-staging', 'deployed-sha'); + + // Then picks from both canceled deploys and the last deploy are found with their own requesters + expect(getCherryPicks(commits)).toEqual([ + {sourceSHA: 'aaaaaaa', cherryPickSHA: 'pick-a', actor: 'first'}, + {sourceSHA: 'bbbbbbb', cherryPickSHA: 'pick-b', actor: 'second'}, + {sourceSHA: 'ccccccc', cherryPickSHA: 'pick-c', actor: 'third'}, + ]); + expect(compareCommits).toHaveBeenCalledTimes(2); + expect(compareCommits).toHaveBeenLastCalledWith(expect.objectContaining({base: '9.5.23-3-staging', head: 'deployed-sha', per_page: 250, page: 2})); + }); + }); + + describe('reverted cherry-picks', () => { + const sourceSHA = 'a'.repeat(40); + const pickSHA = 'b'.repeat(40); + const revertSHA = 'c'.repeat(40); + const pick = {sourceSHA, cherryPickSHA: pickSHA, actor: 'first'}; + const pickedCommit = {sha: pickSHA, message: `Merge pull request #101 from example/fix\n\nFix\n\n(cherry picked from commit ${sourceSHA})`}; + + it('drops a pick reverted by its staged commit SHA or original merge SHA', async () => { + // Given the fix was picked and then reverted before the successful deploy + const candidates = new Map([[101, pick]]); + + // When Git's revert trailer names either form of the commit + const byPick = await filterRevertedCherryPicks([pickedCommit, {sha: revertSHA, message: `Revert "Fix"\n\nThis reverts commit ${pickSHA}.`}], candidates); + const bySource = await filterRevertedCherryPicks([pickedCommit, {sha: revertSHA, message: `Revert "Fix"\n\nThis reverts commit ${sourceSHA}.`}], candidates); + const byShortSHA = await filterRevertedCherryPicks([pickedCommit, {sha: revertSHA, message: `Revert "Fix"\n\nThis reverts commit ${pickSHA.slice(0, 7)}.`}], candidates); + + // Then QA is not asked to test a fix missing from the deployed tree + expect([...byPick]).toEqual([]); + expect([...bySource]).toEqual([]); + expect([...byShortSHA]).toEqual([]); + }); + + it('ignores unrelated revert PRs from before the first candidate pick', async () => { + // Given an older revert has no bearing on a later cherry-pick + const earlierRevert = {sha: revertSHA, message: 'Merge pull request #102 from example/revert\n\nRevert an older change'}; + const getPull = jest.spyOn(octokit.rest.pulls, 'get'); + + try { + // When the release history is scanned + const active = await filterRevertedCherryPicks([earlierRevert, pickedCommit], new Map([[101, pick]])); + + // Then the fix remains eligible without looking up the unrelated revert + expect([...active]).toEqual([[101, pick]]); + expect(getPull).not.toHaveBeenCalled(); + } finally { + getPull.mockRestore(); + } + }); + + it('keeps a later re-pick of a reverted fix', async () => { + // Given the original pick was reverted and then picked again + const newPickSHA = 'd'.repeat(40); + const commits = [ + pickedCommit, + {sha: revertSHA, message: `Revert "Fix"\n\nThis reverts commit ${pickSHA}.`}, + {sha: newPickSHA, message: `Merge pull request #101 from example/fix\n\nFix\n\n(cherry picked from commit ${sourceSHA})`}, + ]; + const candidates = new Map([[101, {...pick, cherryPickSHA: newPickSHA, actor: 'second'}]]); + + // When the deployed history is inspected + const active = await filterRevertedCherryPicks(commits, candidates); + + // Then the re-applied fix remains eligible for a retest + expect([...active]).toEqual([[101, {...pick, cherryPickSHA: newPickSHA, actor: 'second'}]]); + }); + + it('keeps a pick when its revert was itself reverted', async () => { + // Given a revert was undone before the successful deployment + const commits = [ + pickedCommit, + {sha: revertSHA, message: `Revert "Fix"\n\nThis reverts commit ${pickSHA}.`}, + {sha: 'd'.repeat(40), message: `Revert "Revert Fix"\n\nThis reverts commit ${revertSHA}.`}, + ]; + + // When the history is inspected from the deployed commit backwards + const active = await filterRevertedCherryPicks(commits, new Map([[101, pick]])); + + // Then the restored fix is still retested + expect([...active]).toEqual([[101, pick]]); + }); + + it('recognizes a cherry-picked revert PR even when its commit has no revert trailer', async () => { + // Given the revert PR describes its target, as GitHub-generated App revert PRs do + const revertSource = 'd'.repeat(40); + const revertPick = {sourceSHA: revertSource, cherryPickSHA: revertSHA, actor: 'second'}; + const commits = [ + pickedCommit, + {sha: revertSHA, message: `Merge pull request #102 from example/revert\n\n[CP Staging] Revert "Fix"\n\n(cherry picked from commit ${revertSource})`}, + ]; + const getPull = jest + .spyOn(octokit.rest.pulls, 'get') + .mockResolvedValueOnce(createMock>>({data: {title: '[CP Staging] Revert "Fix"', body: 'Reverts Expensify/App#101.'}})); + const listCommits = jest + .spyOn(octokit.rest.pulls, 'listCommits') + .mockResolvedValueOnce(createMock>>({data: [{commit: {message: 'Revert "Fix"'}}]})); + + try { + // When the deploy includes both the fix and its revert + const active = await filterRevertedCherryPicks( + commits, + new Map([ + [101, pick], + [102, revertPick], + ]), + ); + + // Then only the revert PR remains eligible, since it may itself fix a blocker + expect([...active]).toEqual([[102, revertPick]]); + expect(getPull).toHaveBeenCalledWith(expect.objectContaining({pull_number: 102})); + } finally { + getPull.mockRestore(); + listCommits.mockRestore(); + } + }); + + it('reads a revert PR’s individual commits when its merge message lost the trailers', async () => { + // Given a revert PR has no explicit PR link but its original commit names the reverted merge + const revert = {sha: revertSHA, message: 'Merge pull request #102 from example/revert\n\nRevert "Fix"'}; + const getPull = jest.spyOn(octokit.rest.pulls, 'get').mockResolvedValueOnce(createMock>>({data: {title: 'Revert "Fix"', body: ''}})); + const listCommits = jest + .spyOn(octokit.rest.pulls, 'listCommits') + .mockResolvedValueOnce( + createMock>>({data: [{commit: {message: `Revert "Fix"\n\nThis reverts commit ${sourceSHA}.`}}]}), + ); + + try { + // When the successful deploy contains the cherry-picked revert + const active = await filterRevertedCherryPicks([pickedCommit, revert], new Map([[101, pick]])); + + // Then the original fix is excluded even though the deployed merge has no trailer + expect([...active]).toEqual([]); + expect(listCommits).toHaveBeenCalledWith(expect.objectContaining({pull_number: 102})); + } finally { + getPull.mockRestore(); + listCommits.mockRestore(); + } + }); + + it('handles a revert PR that undoes several merged fixes', async () => { + // Given one revert PR contains separate Git reverts for two cherry-picked fixes + const otherSource = 'd'.repeat(40); + const otherPick = {sourceSHA: otherSource, cherryPickSHA: 'e'.repeat(40), actor: 'second'}; + const commits = [ + pickedCommit, + {sha: otherPick.cherryPickSHA, message: `Merge pull request #103 from example/other\n\nOther fix\n\n(cherry picked from commit ${otherSource})`}, + {sha: revertSHA, message: 'Merge pull request #102 from example/revert\n\nRevert both fixes'}, + ]; + const getPull = jest.spyOn(octokit.rest.pulls, 'get').mockResolvedValueOnce(createMock>>({data: {title: 'Revert both fixes', body: ''}})); + const listCommits = jest.spyOn(octokit.rest.pulls, 'listCommits').mockResolvedValueOnce( + createMock>>({ + data: [{commit: {message: `This reverts commit ${sourceSHA}.`}}, {commit: {message: `This reverts commit ${otherSource}.`}}], + }), + ); + + try { + // When the deployed revert is inspected + const active = await filterRevertedCherryPicks( + commits, + new Map([ + [101, pick], + [103, otherPick], + ]), + ); + + // Then neither missing fix is sent to QA + expect([...active]).toEqual([]); + } finally { + getPull.mockRestore(); + listCommits.mockRestore(); + } + }); + + it('keeps the original pick when a revert PR is reverted by another PR', async () => { + // Given the fix was reverted in one PR and that revert was itself reverted in another + const revertSource = 'd'.repeat(40); + const restoreSHA = 'e'.repeat(40); + const restoreSource = 'f'.repeat(40); + const revertPick = {sourceSHA: revertSource, cherryPickSHA: revertSHA, actor: 'second'}; + const restorePick = {sourceSHA: restoreSource, cherryPickSHA: restoreSHA, actor: 'third'}; + const commits = [ + pickedCommit, + {sha: revertSHA, message: `Merge pull request #102 from example/revert\n\nRevert "Fix"\n\n(cherry picked from commit ${revertSource})`}, + {sha: restoreSHA, message: `Merge pull request #103 from example/restore\n\nRevert "Revert Fix"\n\n(cherry picked from commit ${restoreSource})`}, + ]; + const getPull = jest + .spyOn(octokit.rest.pulls, 'get') + .mockResolvedValueOnce(createMock>>({data: {title: 'Revert "Fix"', body: 'Reverts Expensify/App#101.'}})) + .mockResolvedValueOnce(createMock>>({data: {title: 'Revert "Revert Fix"', body: 'Reverts Expensify/App#102.'}})); + const listCommits = jest.spyOn(octokit.rest.pulls, 'listCommits').mockResolvedValue(createMock>>({data: []})); + + try { + // When the final staging deploy is examined + const active = await filterRevertedCherryPicks( + commits, + new Map([ + [101, pick], + [102, revertPick], + [103, restorePick], + ]), + ); + + // Then the restored fix and the second revert remain, but the first revert is excluded + expect([...active]).toEqual([ + [101, pick], + [103, restorePick], + ]); + } finally { + getPull.mockRestore(); + listCommits.mockRestore(); + } + }); + + it('finds explicit revert links without treating other context as reverted PRs', () => { + // Given a revert lists its target and mentions other PRs for context + const text = `Reverts Expensify/App#101. Its base, Expensify/App#102, was reverted first in Expensify/App#103.\n\nDirectly reverts the follow-ups:\n\n- ${CONST.APP_REPO_URL}/pull/104\n- ${CONST.APP_REPO_URL}/pull/105\n\nMore context: ${CONST.APP_REPO_URL}/pull/106`; + + // When the revert references are parsed + const numbers = getRevertedPullNumbers(text); + + // Then only the explicitly reverted PRs are excluded + expect(numbers).toEqual([101, 104, 105]); + expect(getRevertedPullNumbers(`Reverts [the original fix](${CONST.APP_REPO_URL}/pull/107).`)).toEqual([107]); + expect(getRevertedPullNumbers('Reverts OtherOrg/OtherRepo#108.')).toEqual([]); + }); + + it('fails safely when a revert PR does not identify what it undoes', async () => { + // Given the revert has neither a PR reference nor a Git revert trailer + const revert = {sha: revertSHA, message: 'Merge pull request #102 from example/revert\n\nRevert "Fix"'}; + const getPull = jest.spyOn(octokit.rest.pulls, 'get').mockResolvedValueOnce(createMock>>({data: {title: 'Revert "Fix"', body: ''}})); + const listCommits = jest + .spyOn(octokit.rest.pulls, 'listCommits') + .mockResolvedValueOnce(createMock>>({data: [{commit: {message: 'Revert "Fix"'}}]})); + + try { + // When the deploy is inspected + const result = filterRevertedCherryPicks([pickedCommit, revert], new Map([[101, pick]])); + + // Then the job reports the ambiguity rather than requesting an invalid retest + await expect(result).rejects.toThrow('Could not identify the target of revert PR #102.'); + } finally { + getPull.mockRestore(); + listCommits.mockRestore(); + } + }); + }); + + describe('existing retest requests', () => { + it('recognizes the same pick across different deploy tags', async () => { + // Given a previous deploy already requested the retest before it was superseded + getAllComments.mockResolvedValueOnce([`${getRetestMarker('9.5.24-3-staging')}\n${getCherryPickRetestMarker('pick-a')}`]); + + // When the next deploy includes the same cherry-pick + const tag = await getRequestedRetestTag(123, 'pick-a', '9.5.24-5-staging'); + + // Then it keeps the old request instead of filing another one + expect(tag).toBe('9.5.24-3-staging'); + expect(compareCommits).not.toHaveBeenCalled(); + }); + + it('allows a new retest when the same PR is cherry-picked again', async () => { + // Given a request for an earlier pick of this PR + getAllComments.mockResolvedValueOnce([`${getRetestMarker('9.5.24-3-staging')}\n${getCherryPickRetestMarker('old-pick')}`]); + + // When the PR is re-applied after a revert + const tag = await getRequestedRetestTag(123, 'new-pick', '9.5.24-5-staging'); + + // Then the old request does not suppress the new retest + expect(tag).toBeUndefined(); + expect(compareCommits).not.toHaveBeenCalled(); + }); + + it('recognizes a tag-only marker when that deployment contained the pick', async () => { + // Given a request created before commit-specific markers were introduced + getAllComments.mockResolvedValueOnce([getRetestMarker('9.5.24-3-staging')]); + compareCommits.mockResolvedValueOnce(createMock({data: {status: 'ahead'}})); + + // When a later deploy includes that same pick + const tag = await getRequestedRetestTag(123, 'pick-a', '9.5.24-5-staging'); + + // Then the earlier tag is reused to avoid a duplicate + expect(tag).toBe('9.5.24-3-staging'); + expect(compareCommits).toHaveBeenCalledWith(expect.objectContaining({base: 'pick-a', head: '9.5.24-3-staging', per_page: 1})); + }); + + it('does not match a tag-only marker from before a new pick', async () => { + // Given an old request whose deployment did not contain the new pick + getAllComments.mockResolvedValueOnce([getRetestMarker('9.5.24-3-staging')]); + compareCommits.mockResolvedValueOnce(createMock({data: {status: 'behind'}})); + + // When a new cherry-pick of the PR is deployed + const tag = await getRequestedRetestTag(123, 'new-pick', '9.5.24-5-staging'); + + // Then it remains eligible for another retest + expect(tag).toBeUndefined(); + }); + + it('recognizes a tag-only marker on a rerun of the same deploy', async () => { + // Given a legacy request on the deployment being rerun + getAllComments.mockResolvedValueOnce([getRetestMarker('9.5.24-5-staging')]); + + // When the same deploy is processed again + const tag = await getRequestedRetestTag(123, 'pick-a', '9.5.24-5-staging'); + + // Then the request is reused without another GitHub comparison + expect(tag).toBe('9.5.24-5-staging'); + expect(compareCommits).not.toHaveBeenCalled(); + }); + + it('does not risk a duplicate if a legacy tag cannot be checked', async () => { + // Given an earlier tag-only marker and a GitHub API error + getAllComments.mockResolvedValueOnce([getRetestMarker('9.5.24-3-staging')]); + compareCommits.mockRejectedValueOnce(new Error('GitHub unavailable')); + + // When the earlier request is checked + const result = getRequestedRetestTag(123, 'pick-a', '9.5.24-5-staging'); + + // Then the scan fails instead of filing an unverified duplicate + await expect(result).rejects.toThrow('GitHub unavailable'); + }); + + it('checks exact markers before comparing an older missing tag', async () => { + // Given a deleted legacy tag appears before a completed marker for this exact pick + getAllComments.mockResolvedValueOnce([getRetestMarker('deleted-staging'), `${getRetestMarker('9.5.24-5-staging')}\n${getCherryPickRetestMarker('pick-a')}`]); + + // When the existing request is located + const tag = await getRequestedRetestTag(123, 'pick-a', '9.5.24-6-staging'); + + // Then the exact marker prevents a needless lookup of the deleted tag + expect(tag).toBe('9.5.24-5-staging'); + expect(compareCommits).not.toHaveBeenCalled(); + }); + + it('checks later legacy markers when an earlier tag is missing', async () => { + // Given one legacy tag was deleted but a later tagged deploy contains the pick + getAllComments.mockResolvedValueOnce([getRetestMarker('deleted-staging'), getRetestMarker('9.5.24-5-staging')]); + compareCommits.mockRejectedValueOnce(Object.assign(new Error('Tag not found'), {status: 404})); + compareCommits.mockResolvedValueOnce(createMock({data: {status: 'ahead'}})); + + // When the old requests are compared to the pick + const tag = await getRequestedRetestTag(123, 'pick-a', '9.5.24-6-staging'); + + // Then the valid marker is reused rather than failing or filing a duplicate + expect(tag).toBe('9.5.24-5-staging'); + expect(compareCommits).toHaveBeenCalledTimes(2); + }); + + it('prefers a completed marker to an older pending marker for the same pick', async () => { + // Given a pending request was later confirmed in a separate comment + getAllComments.mockResolvedValueOnce([ + `${getRetestMarker('9.5.24-3-staging')}\n${getPendingRetestMarker('pick-a')}`, + `${getRetestMarker('9.5.24-3-staging')}\n${getCherryPickRetestMarker('pick-a')}`, + ]); + + // When the next deploy checks for an existing request + const tag = await getRequestedRetestTag(123, 'pick-a', '9.5.24-5-staging'); + + // Then the completed marker wins and no duplicate is posted + expect(tag).toBe('9.5.24-3-staging'); + }); + + it('continues the batch when a legacy tag is missing without duplicating that request', async () => { + // Given one PR has an unresolvable old marker and another needs a retest + const hit: RetestHit = { + prNumber: 101, + prURL: `${CONST.APP_REPO_URL}/pull/101`, + prAuthor: 'author', + cherryPickSHA: 'pick-a', + blockerIssueURLs: [`${CONST.APP_REPO_URL}/issues/201`], + prTitle: 'First fix', + author: 'first', + }; + getAllComments.mockImplementation(async (number) => (number === 101 ? [getRetestMarker('deleted-staging')] : [])); + compareCommits.mockRejectedValueOnce(Object.assign(new Error('Tag not found'), {status: 404})); + const createComment = jest.spyOn(GithubUtils, 'createComment').mockResolvedValue(createMock>>({data: {id: 1}})); + const updateComment = jest.spyOn(octokit.rest.issues, 'updateComment').mockResolvedValue(createMock>>({})); + const mockFetch = Object.assign(async () => new Response('', {status: 200}), {preconnect: globalThis.fetch.preconnect}); + const postWebhook = jest.spyOn(globalThis, 'fetch').mockImplementation(mockFetch); + + try { + // When the batch processes both PRs + const result = fileRetestRequests( + [hit, {...hit, prNumber: 102, prURL: `${CONST.APP_REPO_URL}/pull/102`, cherryPickSHA: 'pick-b'}], + 'current-staging', + 'https://example.com/retest', + ); + + // Then the other request is filed and the uncertain PR is reported for manual attention + await expect(result).rejects.toThrow('Could not process retest requests for PRs #101.'); + expect(postWebhook).toHaveBeenCalledTimes(1); + expect(createComment).toHaveBeenCalledTimes(1); + expect(createComment.mock.calls[0]?.[1]).toBe(102); + expect(updateComment).toHaveBeenCalledTimes(1); + } finally { + createComment.mockRestore(); + updateComment.mockRestore(); + postWebhook.mockRestore(); + } + }); + + it('does not post again when Slack accepted a request but the confirmation update failed', async () => { + // Given Slack accepts a request after its pending marker was saved, but GitHub cannot confirm it + const hit: RetestHit = { + prNumber: 101, + prURL: `${CONST.APP_REPO_URL}/pull/101`, + prAuthor: 'author', + cherryPickSHA: 'pick-a', + blockerIssueURLs: [`${CONST.APP_REPO_URL}/issues/201`], + prTitle: 'First fix', + author: 'first', + }; + const comments: string[] = []; + getAllComments.mockImplementation(async () => comments); + const createComment = jest.spyOn(GithubUtils, 'createComment').mockImplementation(async (_repo, _number, body) => { + comments.push(body); + return createMock>>({data: {id: 1}}); + }); + const updateComment = jest.spyOn(octokit.rest.issues, 'updateComment').mockRejectedValueOnce(new Error('GitHub unavailable')); + const mockFetch = Object.assign( + async () => { + expect(comments[0]).toContain(getPendingRetestMarker('pick-a')); + return new Response('', {status: 200}); + }, + {preconnect: globalThis.fetch.preconnect}, + ); + const postWebhook = jest.spyOn(globalThis, 'fetch').mockImplementation(mockFetch); + + try { + // When the failed deployment is followed by a different staging deploy without Slack lookup credentials + await expect(fileRetestRequests([hit], 'first-staging', 'https://example.com/retest')).rejects.toThrow('Could not process retest requests for PRs #101.'); + await expect(fileRetestRequests([hit], 'second-staging', 'https://example.com/retest')).rejects.toThrow('Could not process retest requests for PRs #101.'); + + // Then the pending marker prevents a second webhook and leaves the uncertain request for follow-up + expect(postWebhook).toHaveBeenCalledTimes(1); + expect(comments[0]).toContain(getPendingRetestMarker('pick-a')); + } finally { + createComment.mockRestore(); + updateComment.mockRestore(); + postWebhook.mockRestore(); + } + }); + + it('retries a request after Slack confirms it was rejected', async () => { + // Given Slack rejects the first webhook with a client error + const hit: RetestHit = { + prNumber: 101, + prURL: `${CONST.APP_REPO_URL}/pull/101`, + prAuthor: 'author', + cherryPickSHA: 'pick-a', + blockerIssueURLs: [`${CONST.APP_REPO_URL}/issues/201`], + prTitle: 'First fix', + author: 'first', + }; + const comments: string[] = []; + getAllComments.mockImplementation(async () => comments); + const createComment = jest.spyOn(GithubUtils, 'createComment').mockImplementation(async (_repo, _number, body) => { + comments.push(body); + return createMock>>({data: {id: comments.length}}); + }); + const updateCommentStatics = {endpoint: octokit.rest.issues.updateComment.endpoint, defaults: octokit.rest.issues.updateComment.defaults}; + const updateCommentBody = async (parameters?: Parameters[0]): Promise>> => { + if (!parameters || !('comment_id' in parameters) || !('body' in parameters) || typeof parameters.body !== 'string') { + throw new Error('Expected a comment update.'); + } + comments[parameters.comment_id - 1] = parameters.body; + return createMock>>({data: {id: parameters.comment_id}}); + }; + const updateComment = jest.spyOn(octokit.rest.issues, 'updateComment').mockImplementation(Object.assign(updateCommentBody, updateCommentStatics)); + const fetchSpy = jest + .spyOn(globalThis, 'fetch') + .mockResolvedValueOnce(new Response('Rejected', {status: 400})) + .mockResolvedValueOnce(new Response('', {status: 200})); + + try { + // When the failed request is followed by another staging deploy + await expect(fileRetestRequests([hit], 'first-staging', 'https://example.com/retest')).rejects.toThrow('Could not process retest requests for PRs #101.'); + expect(comments[0]).not.toContain(getPendingRetestMarker('pick-a')); + await fileRetestRequests([hit], 'second-staging', 'https://example.com/retest'); + + // Then the confirmed rejection can be retried and the new request is recorded + expect(fetchSpy).toHaveBeenCalledTimes(2); + expect(comments[1]).toContain(getCherryPickRetestMarker('pick-a')); + } finally { + createComment.mockRestore(); + updateComment.mockRestore(); + fetchSpy.mockRestore(); + } + }); + + it.each([408, 499, 503])('keeps a pending marker when webhook status %i is ambiguous', async (status) => { + // Given the webhook result does not prove whether Slack accepted the request + const hit: RetestHit = { + prNumber: 101, + prURL: `${CONST.APP_REPO_URL}/pull/101`, + prAuthor: 'author', + cherryPickSHA: 'pick-a', + blockerIssueURLs: [`${CONST.APP_REPO_URL}/issues/201`], + prTitle: 'First fix', + author: 'first', + }; + const comments: string[] = []; + getAllComments.mockImplementation(async () => comments); + const createComment = jest.spyOn(GithubUtils, 'createComment').mockImplementation(async (_repo, _number, body) => { + comments.push(body); + return createMock>>({data: {id: 1}}); + }); + const updateComment = jest.spyOn(octokit.rest.issues, 'updateComment').mockResolvedValue(createMock>>({})); + const fetchSpy = jest.spyOn(globalThis, 'fetch').mockResolvedValueOnce(new Response('Uncertain', {status})); + + try { + // When a later deploy tries again without Slack lookup credentials + await expect(fileRetestRequests([hit], 'first-staging', 'https://example.com/retest')).rejects.toThrow('Could not process retest requests for PRs #101.'); + await expect(fileRetestRequests([hit], 'second-staging', 'https://example.com/retest')).rejects.toThrow('Could not process retest requests for PRs #101.'); + + // Then the pending marker prevents another webhook until the outcome is checked + expect(fetchSpy).toHaveBeenCalledTimes(1); + expect(updateComment).not.toHaveBeenCalled(); + expect(comments[0]).toContain(getPendingRetestMarker('pick-a')); + } finally { + createComment.mockRestore(); + updateComment.mockRestore(); + fetchSpy.mockRestore(); + } + }); + + it('recovers an exact pending request from an older Slack history page and reuses it for the link', async () => { + // Given the newest history page has a different PR with the same number prefix + const hit: RetestHit = { + prNumber: 101, + prURL: `${CONST.APP_REPO_URL}/pull/101`, + prAuthor: 'author', + cherryPickSHA: 'pick-a', + blockerIssueURLs: [`${CONST.APP_REPO_URL}/issues/201`], + prTitle: 'First fix', + author: 'first', + }; + getAllComments.mockResolvedValueOnce([`${getRetestMarker('first-staging')}\n${getPendingRetestMarker('pick-a')}`]); + const createComment = jest.spyOn(GithubUtils, 'createComment').mockResolvedValue(createMock>>({data: {id: 1}})); + const retestPermalink = 'https://example.com/retest-message'; + const fetchSpy = jest + .spyOn(globalThis, 'fetch') + .mockResolvedValueOnce( + new Response(JSON.stringify({ok: true, messages: [{ts: '111.111', text: 'Retest ID: first-staging / App PR #1010'}], response_metadata: {next_cursor: 'next-page'}}), { + status: 200, + }), + ) + .mockResolvedValueOnce(new Response(JSON.stringify({ok: true, messages: [{ts: '123.456', text: 'Retest ID: first-staging / App PR #101\n'}]}), {status: 200})) + .mockResolvedValueOnce(new Response(JSON.stringify({ok: true, permalink: retestPermalink}), {status: 200})) + .mockResolvedValueOnce( + new Response(JSON.stringify({ok: true, messages: [{ts: '789.000', text: `*Cherry Pick Request* Link to PR: <${hit.prURL}> *Where:* staging`}]}), {status: 200}), + ) + .mockResolvedValueOnce(new Response(JSON.stringify({ok: true, messages: [{ts: '789.000', text: 'Parent request'}]}), {status: 200})) + .mockResolvedValueOnce(new Response('', {status: 200})); + + try { + // When the later deploy recovers and links the pending request + await fileRetestRequests([hit], 'second-staging', 'https://example.com/retest', 'slack-token', 'https://example.com/deployer'); + + // Then it finds PR 101 on the second page, reuses that message, and never fires the retest webhook + expect(fetchSpy.mock.calls.map((call) => call[0])).toEqual([ + 'https://slack.com/api/conversations.history', + 'https://slack.com/api/conversations.history', + 'https://slack.com/api/chat.getPermalink', + 'https://slack.com/api/conversations.history', + 'https://slack.com/api/conversations.replies', + 'https://example.com/deployer', + ]); + const secondPageBody = fetchSpy.mock.calls[1]?.[1]?.body; + if (typeof secondPageBody !== 'string') { + throw new Error('Expected the Slack history request.'); + } + const secondPage: unknown = JSON.parse(secondPageBody); + expect(secondPage).toEqual(expect.objectContaining({cursor: 'next-page'})); + expect(createComment.mock.calls[0]?.[2]).toContain(getCherryPickRetestMarker('pick-a')); + } finally { + createComment.mockRestore(); + fetchSpy.mockRestore(); + } + }); + }); + + describe('staging deploy', () => { + it('does not scan release history when there are no checklist blockers', async () => { + // Given the checklist contains a PR but no deploy blockers + const checklist = { + number: 901, + url: 'https://api.github.com/repos/Expensify/App/issues/901', + title: 'Current checklist', + labels: [], + body: [ + '**Release Version:** `9.5.24-5`', + '', + '**This release contains changes from the following pull requests:**', + `- [ ] ${CONST.APP_REPO_URL}/pull/101`, + '', + '', + '**Deploy Blockers:**', + '', + ].join('\n'), + }; + listForRepo.mockResolvedValueOnce(createMock({data: [checklist]})); + const originalArgv = process.argv; + const originalWebhook = process.env.SLACK_RETEST_WEBHOOK; + + try { + process.argv = ['bun', 'script', '--deploy-sha=deployed-sha', '--deploy-tag=9.5.24-5-staging']; + process.env.SLACK_RETEST_WEBHOOK = 'https://example.com/retest'; + + // When a fully deployed staging build looks for retests + await run(); + + // Then it avoids reading the release history or filing another request + expect(listForRepo).toHaveBeenCalledTimes(1); + expect(compareCommits).not.toHaveBeenCalled(); + } finally { + process.argv = originalArgv; + if (originalWebhook === undefined) { + delete process.env.SLACK_RETEST_WEBHOOK; + } else { + process.env.SLACK_RETEST_WEBHOOK = originalWebhook; + } + } + }); + + it('requests every outstanding pick once, including picks from canceled deploys', async () => { + // Given several blocker fixes were picked before a successful deploy, including a checked blocker and a subsequently reverted fix + const previousChecklist = { + number: 900, + url: 'https://api.github.com/repos/Expensify/App/issues/900', + title: 'Previous checklist', + body: '**Release Version:** `9.5.23-3`', + labels: [], + }; + const checklist = { + number: 901, + url: 'https://api.github.com/repos/Expensify/App/issues/901', + title: 'Current checklist', + labels: [], + body: [ + '**Release Version:** `9.5.24-5`', + '', + '**This release contains changes from the following pull requests:**', + ...[101, 102, 103, 104, 106].map((number) => `- [ ] ${CONST.APP_REPO_URL}/pull/${number}`), + '', + '', + '**Deploy Blockers:**', + ...[201, 202, 203].map((number) => `- [ ] ${CONST.APP_REPO_URL}/issues/${number}`), + `- [x] ${CONST.APP_REPO_URL}/issues/204`, + `- [ ] ${CONST.APP_REPO_URL}/issues/206`, + '', + ].join('\n'), + }; + const listIssues = async (parameters?: Parameters[0]): Promise => + createMock({data: parameters && 'state' in parameters && parameters.state === 'all' ? [checklist, previousChecklist] : [checklist]}); + listForRepo.mockImplementation(Object.assign(listIssues, listStatics)); + + const picks = [ + {source: 'aaaaaaa', sha: 'pick-a', pr: 101, actor: 'first'}, + {source: 'bbbbbbb', sha: 'pick-b', pr: 102, actor: 'second'}, + {source: 'ccccccc', sha: 'pick-c', pr: 103, actor: 'third'}, + {source: 'ddddddd', sha: 'pick-d', pr: 104, actor: 'fourth'}, + {source: 'eeeeeee', sha: 'pick-e', pr: 105, actor: 'fifth'}, + {source: 'fffffff', sha: 'f'.repeat(40), pr: 106, actor: 'sixth'}, + ]; + const compare = async (): Promise => + createMock({ + data: { + commits: [ + ...picks.map((pick) => ({sha: pick.sha, commit: {message: `(cherry picked from commit ${pick.source})\n\n(cherry-picked to staging by ${pick.actor})`}})), + {sha: 'd'.repeat(40), commit: {message: `Revert "Sixth fix"\n\nThis reverts commit ${'f'.repeat(40)}.`}}, + ], + }, + }); + compareCommits.mockImplementation(Object.assign(compare, compareStatics)); + let includeChecklistPRs = false; + const listPullsStatics = {endpoint: octokit.rest.repos.listPullRequestsAssociatedWithCommit.endpoint, defaults: octokit.rest.repos.listPullRequestsAssociatedWithCommit.defaults}; + const listPullsForCommit = async (parameters?: Parameters[0]): Promise>> => { + const pick = picks.find((item) => item.source === (parameters && 'commit_sha' in parameters ? parameters.commit_sha : undefined)); + return createMock>>({data: pick && (includeChecklistPRs || pick.pr === 105) ? [{number: pick.pr}] : []}); + }; + const listPulls = jest.spyOn(octokit.rest.repos, 'listPullRequestsAssociatedWithCommit').mockImplementation(Object.assign(listPullsForCommit, listPullsStatics)); + const getPullStatics = {endpoint: octokit.rest.pulls.get.endpoint, defaults: octokit.rest.pulls.get.defaults}; + const getPullForNumber = async (parameters?: Parameters[0]): Promise>> => { + const number = parameters && 'pull_number' in parameters ? parameters.pull_number : 0; + return createMock>>({ + data: {html_url: `${CONST.APP_REPO_URL}/pull/${number}`, body: `${CONST.APP_REPO_URL}/issues/${number + 100}`, title: `Fix ${number}`, user: {login: 'author'}}, + }); + }; + const getPull = jest.spyOn(octokit.rest.pulls, 'get').mockImplementation(Object.assign(getPullForNumber, getPullStatics)); + const getContent = jest + .spyOn(octokit.rest.repos, 'getContent') + .mockResolvedValue(createMock>>({data: {content: ''}})); + const comments = new Map(); + const commentLocations = new Map(); + let nextCommentID = 1; + getAllComments.mockImplementation(async (number) => comments.get(number) ?? []); + const createComment = jest.spyOn(GithubUtils, 'createComment').mockImplementation(async (_repo, number, body) => { + const entries = [...(comments.get(number) ?? []), body]; + comments.set(number, entries); + const id = nextCommentID++; + commentLocations.set(id, {prNumber: number, index: entries.length - 1}); + return createMock>>({data: {id}}); + }); + const updateCommentStatics = {endpoint: octokit.rest.issues.updateComment.endpoint, defaults: octokit.rest.issues.updateComment.defaults}; + const updateCommentBody = async (parameters?: Parameters[0]): Promise>> => { + if (!parameters || !('comment_id' in parameters) || !('body' in parameters) || typeof parameters.body !== 'string') { + throw new Error('Expected a comment update.'); + } + const location = commentLocations.get(parameters.comment_id); + const entries = location ? comments.get(location.prNumber) : undefined; + if (!location || !entries) { + throw new Error('Expected the pending comment.'); + } + entries[location.index] = parameters.body; + return createMock>>({data: {id: parameters.comment_id}}); + }; + const updateComment = jest.spyOn(octokit.rest.issues, 'updateComment').mockImplementation(Object.assign(updateCommentBody, updateCommentStatics)); + const mockFetch = Object.assign(async () => new Response('', {status: 200}), {preconnect: globalThis.fetch.preconnect}); + const postWebhook = jest.spyOn(globalThis, 'fetch').mockImplementation(mockFetch); + const originalArgv = process.argv; + const originalWebhook = process.env.SLACK_RETEST_WEBHOOK; + const originalToken = process.env.SLACK_RETEST_USER_TOKEN; + const originalDeployerWebhook = process.env.SLACK_WEBHOOK; + + try { + process.env.SLACK_RETEST_WEBHOOK = 'https://example.com/retest'; + delete process.env.SLACK_RETEST_USER_TOKEN; + delete process.env.SLACK_WEBHOOK; + process.argv = ['bun', 'script', '--deploy-sha=deployed-sha', '--deploy-tag=9.5.24-5-staging']; + + // When no deployed pick belongs to the checklist + await run(); + + // Then the deploy does not read the employee whitelist or notify QA + expect(getContent).not.toHaveBeenCalled(); + expect(postWebhook).not.toHaveBeenCalled(); + includeChecklistPRs = true; + + // When the last deploy processes the whole release and a later deploy repeats the scan + await run(); + process.argv = ['bun', 'script', '--deploy-sha=next-sha', '--deploy-tag=9.5.24-6-staging']; + await run(); + + // Then every deployed fix gets one request, including checked blockers, while reverted and unrelated PRs get none + expect(postWebhook).toHaveBeenCalledTimes(4); + expect(createComment).toHaveBeenCalledTimes(4); + expect(updateComment).toHaveBeenCalledTimes(4); + const payloads = postWebhook.mock.calls.map((call) => { + const body = call[1]?.body; + if (typeof body !== 'string') { + throw new Error('Expected a JSON webhook body.'); + } + const payload: unknown = JSON.parse(body); + if ( + typeof payload !== 'object' || + !payload || + !('cpLink' in payload) || + typeof payload.cpLink !== 'string' || + !('author' in payload) || + typeof payload.author !== 'string' + ) { + throw new Error('Expected the retest webhook payload.'); + } + return {cpLink: payload.cpLink, author: payload.author}; + }); + expect(payloads.map((payload) => payload.cpLink)).toEqual([101, 102, 103, 104].map((number) => `${CONST.APP_REPO_URL}/pull/${number}`)); + expect(payloads.map((payload) => payload.author)).toEqual(['first', 'second', 'third', 'fourth']); + expect(comments.get(101)?.[0]).toContain(getCherryPickRetestMarker('pick-a')); + + // When the first PR is picked again after a revert + picks.push({source: 'aaaaaaa', sha: 'new-pick-a', pr: 101, actor: 'new-requester'}); + process.argv = ['bun', 'script', '--deploy-sha=third-sha', '--deploy-tag=9.5.24-7-staging']; + await run(); + + // Then only the new pick gets another retest request + expect(postWebhook).toHaveBeenCalledTimes(5); + expect(comments.get(101)?.[1]).toContain(getCherryPickRetestMarker('new-pick-a')); + } finally { + process.argv = originalArgv; + if (originalWebhook === undefined) { + delete process.env.SLACK_RETEST_WEBHOOK; + } else { + process.env.SLACK_RETEST_WEBHOOK = originalWebhook; + } + if (originalToken === undefined) { + delete process.env.SLACK_RETEST_USER_TOKEN; + } else { + process.env.SLACK_RETEST_USER_TOKEN = originalToken; + } + if (originalDeployerWebhook === undefined) { + delete process.env.SLACK_WEBHOOK; + } else { + process.env.SLACK_WEBHOOK = originalDeployerWebhook; + } + listPulls.mockRestore(); + getPull.mockRestore(); + getContent.mockRestore(); + createComment.mockRestore(); + updateComment.mockRestore(); + postWebhook.mockRestore(); + } + }); + + it('runs after any successful staging deployment and its checklist update', () => { + // Given a regular staging deploy can supersede a canceled cherry-pick deploy + const workflow = fs.readFileSync('.github/workflows/deploy.yml', 'utf8'); + const retestJob = workflow.split(' autoRetestRequestForCP:')[1]?.split('\n createRelease:')[0] ?? ''; + + // When the retest job conditions are checked + const conditions = retestJob.split('\n').find((line) => line.trimStart().startsWith('if:')) ?? ''; + + // Then it waits for all platforms and the checklist without requiring the latest push to be a cherry-pick + expect(conditions).toContain("needs.prep.outputs.DEPLOY_ENV == 'staging'"); + expect(conditions).toContain("needs.deployChecklist.result == 'success'"); + expect(conditions).toContain('needs.checkDeploymentSuccess.outputs.IS_ALL_PLATFORMS_DEPLOYED'); + expect(conditions).toContain('!cancelled()'); + expect(conditions).not.toContain('IS_CHERRY_PICK'); + expect(retestJob).toContain('needs: [prep, deployChecklist, checkDeploymentSuccess]'); }); }); @@ -84,6 +1041,7 @@ describe('createRetestRequestForCP', () => { prNumber: 123, prURL: `${CONST.APP_REPO_URL}/pull/123`, prAuthor: 'octocat', + cherryPickSHA: 'pick-a', blockerIssueURLs: [`${CONST.APP_REPO_URL}/issues/42`], prTitle: 'Fix crash on staging', author: 'U01N2A6GYJH', @@ -118,6 +1076,7 @@ describe('createRetestRequestForCP', () => { prNumber: 123, prURL: `${CONST.APP_REPO_URL}/pull/123`, prAuthor: 'octocat', + cherryPickSHA: 'pick-a', blockerIssueURLs: [`${CONST.APP_REPO_URL}/issues/42`], prTitle: 'Fix crash on staging', author: 'U01N2A6GYJH',