Unverified Commit a584bb87 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

[ci]: add workflow to bump canary after backport (#92801)

This adds an automated path to keep canary semver-ahead after a
successful stable backport publish.

Today, a backport release can produce a stable version that is newer
than the current canary version, which creates confusing version
ordering for tooling. This change adds a follow-up workflow that
evaluates completed backport publishes and, when appropriate, triggers a
canary preminor release on canary.

The `Sync Canary After Backport Release` workflow evaluates whether a
completed `build-and-deploy` run should trigger a canary sync.

The evaluation only triggers when:
- the upstream `Potentially publish release` job succeeded
- the head commit is a stable release commit
- the published stable version is a backport relative to next@latest
- the current canary version is not already semver-ahead
- there is not already a queued or in-progress Trigger Release run on
canary

When all checks pass, the workflow dispatches trigger_release.yml on
canary with:
- releaseType=canary
- semverType=minor
- force=true

(This is currently gated behind an env flag so we can dry-run it)
parent f381e3e5
name: Sync Canary After Backport Release
on:
workflow_run:
workflows:
- build-and-deploy
types:
- completed
workflow_dispatch:
inputs:
workflowRunId:
description: Completed build-and-deploy workflow run ID to evaluate
required: true
type: string
headSha:
description: Release commit SHA from that workflow run
required: true
type: string
dispatch:
description: Dispatch trigger_release after evaluation
default: false
required: false
type: boolean
concurrency:
group: sync-backport-canary-release
cancel-in-progress: true
jobs:
evaluate:
if: ${{ github.repository_owner == 'vercel' && (github.event_name == 'workflow_dispatch' || (github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_branch != 'canary')) }}
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
should_dispatch: ${{ steps.evaluate.outputs.should_dispatch }}
reason: ${{ steps.evaluate.outputs.reason }}
current_canary_version: ${{ steps.evaluate.outputs.current_canary_version }}
released_version: ${{ steps.evaluate.outputs.released_version }}
latest_version: ${{ steps.evaluate.outputs.latest_version }}
steps:
- name: Check whether head commit is a stable release
id: precheck
uses: actions/github-script@v7
with:
script: |
if (context.eventName === 'workflow_dispatch') {
core.setOutput('should_evaluate', 'true')
return
}
const headCommitMessage =
context.payload.workflow_run.head_commit?.message?.trim() || ''
const stableReleaseCommitRegex = /^v\d+\.\d+\.\d+$/
if (stableReleaseCommitRegex.test(headCommitMessage)) {
core.setOutput('should_evaluate', 'true')
return
}
core.setOutput('should_evaluate', 'false')
core.setOutput('should_dispatch', 'false')
core.setOutput('reason', 'Head commit is not a stable release commit')
- uses: actions/checkout@v6
if: steps.precheck.outputs.should_evaluate == 'true'
with:
ref: canary
fetch-depth: 1
- name: Evaluate backport release
id: evaluate
if: steps.precheck.outputs.should_evaluate == 'true'
env:
RELEASE_BOT_GITHUB_TOKEN: ${{ secrets.RELEASE_BOT_GITHUB_TOKEN }}
WORKFLOW_RUN_ID: ${{ github.event_name == 'workflow_dispatch' && inputs.workflowRunId || github.event.workflow_run.id }}
HEAD_SHA: ${{ github.event_name == 'workflow_dispatch' && inputs.headSha || github.event.workflow_run.head_sha }}
HEAD_COMMIT_MESSAGE: ${{ github.event_name == 'workflow_dispatch' && '' || github.event.workflow_run.head_commit.message }}
run: node ./scripts/check-backport-canary-release.js --workflow-run-id "$WORKFLOW_RUN_ID" --head-sha "$HEAD_SHA"
- name: Print evaluation
run: |
echo "should_dispatch=${{ steps.evaluate.outputs.should_dispatch || steps.precheck.outputs.should_dispatch }}"
echo "reason=${{ steps.evaluate.outputs.reason || steps.precheck.outputs.reason }}"
echo "released_version=${{ steps.evaluate.outputs.released_version }}"
echo "latest_version=${{ steps.evaluate.outputs.latest_version }}"
echo "current_canary_version=${{ steps.evaluate.outputs.current_canary_version }}"
echo "dispatch_input=${{ github.event_name == 'workflow_dispatch' && inputs.dispatch || false }}"
echo "auto_dispatch_enabled=${{ vars.ENABLE_BACKPORT_CANARY_SYNC || 'false' }}"
dispatch:
needs: evaluate
if: ${{ needs.evaluate.outputs.should_dispatch == 'true' && ((github.event_name == 'workflow_dispatch' && inputs.dispatch) || (github.event_name == 'workflow_run' && vars.ENABLE_BACKPORT_CANARY_SYNC == 'true')) }}
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@v7
with:
github-token: ${{ secrets.RELEASE_BOT_GITHUB_TOKEN }}
script: |
await github.request(
"POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches",
{
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: "trigger_release.yml",
ref: "canary",
inputs: {
releaseType: "canary",
semverType: "minor",
force: "true",
},
}
)
console.info(
`Triggered canary release after backport ${process.env.RELEASED_VERSION}; current canary was ${process.env.CURRENT_CANARY_VERSION}`
)
env:
RELEASED_VERSION: ${{ needs.evaluate.outputs.released_version }}
CURRENT_CANARY_VERSION: ${{ needs.evaluate.outputs.current_canary_version }}
#!/usr/bin/env node
// @ts-check
const fs = require('fs/promises')
const path = require('path')
const semver = require('semver')
const PUBLISH_RELEASE_JOB_NAME = 'Potentially publish release'
const TRIGGER_RELEASE_WORKFLOW = 'trigger_release.yml'
const RELEASE_COMMIT_REGEX = /^v\d+\.\d+\.\d+(-\w+\.\d+)?$/
// This helper is used by a workflow_run listener on build-and-deploy.
// It decides whether a successful stable backport publish should trigger
// a canary preminor release so canary stays semver-ahead of the backport.
function getArgValue(flag) {
const index = process.argv.indexOf(flag)
return index === -1 ? undefined : process.argv[index + 1]
}
function parseReleaseVersion(commitMessage) {
const versionString = commitMessage.split(' ').pop()?.trim()
return versionString && RELEASE_COMMIT_REGEX.test(versionString)
? versionString.slice(1)
: null
}
function compareSemver(left, right) {
const result = semver.compare(left, right)
if (Number.isNaN(result)) {
throw new Error(`Invalid semver comparison "${left}" vs "${right}"`)
}
return result
}
async function fetchJson(url, token) {
const headers = {
Accept: 'application/vnd.github+json',
}
if (token) {
headers.Authorization = `Bearer ${token}`
headers['X-GitHub-Api-Version'] = '2022-11-28'
}
const response = await fetch(url, { headers })
if (!response.ok) {
throw new Error(
`Request failed (${response.status}) for ${url}: ${await response.text()}`
)
}
return response.json()
}
async function appendOutputs(outputs) {
if (!process.env.GITHUB_OUTPUT) {
return
}
let output = ''
for (const [key, value] of Object.entries(outputs)) {
output += `${key}=${String(value ?? '').replace(/\n/g, ' ')}\n`
}
await fs.appendFile(process.env.GITHUB_OUTPUT, output)
}
async function getWorkflowRunJobs(owner, repo, workflowRunId, token) {
const jobs = []
for (let page = 1; ; page++) {
const params = new URLSearchParams({
per_page: '100',
page: String(page),
})
const data = await fetchJson(
`https://api.github.com/repos/${owner}/${repo}/actions/runs/${workflowRunId}/jobs?${params}`,
token
)
jobs.push(...data.jobs)
if (jobs.length >= data.total_count || data.jobs.length === 0) {
return jobs
}
}
}
async function getActiveTriggerReleaseRun(owner, repo, token) {
for (const status of ['queued', 'in_progress']) {
const params = new URLSearchParams({
branch: 'canary',
status,
per_page: '100',
})
const data = await fetchJson(
`https://api.github.com/repos/${owner}/${repo}/actions/workflows/${TRIGGER_RELEASE_WORKFLOW}/runs?${params}`,
token
)
if (data.total_count > 0) {
return data.workflow_runs[0]
}
}
return null
}
async function getCommitMessage(owner, repo, sha, token) {
const data = await fetchJson(
`https://api.github.com/repos/${owner}/${repo}/commits/${sha}`,
token
)
return data.commit.message.trim()
}
async function finish(outputs) {
await appendOutputs(outputs)
if (outputs.should_dispatch === 'true') {
console.log(outputs.reason)
} else {
console.log(`Skipping canary sync: ${outputs.reason}`)
}
}
async function main() {
const workflowRunId = getArgValue('--workflow-run-id')
const headSha = getArgValue('--head-sha')
const headCommitMessage = process.env.HEAD_COMMIT_MESSAGE?.trim()
if (!workflowRunId) {
throw new Error('Missing --workflow-run-id')
}
if (!headSha) {
throw new Error('Missing --head-sha')
}
const token = process.env.RELEASE_BOT_GITHUB_TOKEN || process.env.GITHUB_TOKEN
const repoFullName = process.env.GITHUB_REPOSITORY
if (!token) {
throw new Error('Missing RELEASE_BOT_GITHUB_TOKEN or GITHUB_TOKEN')
}
if (!repoFullName) {
throw new Error('Missing GITHUB_REPOSITORY')
}
const [owner, repo] = repoFullName.split('/')
const currentCanaryVersion = JSON.parse(
await fs.readFile(path.join(process.cwd(), 'lerna.json'), 'utf8')
).version
const releaseCommitMessage =
headCommitMessage || (await getCommitMessage(owner, repo, headSha, token))
const releasedVersion = parseReleaseVersion(releaseCommitMessage)
if (!releasedVersion) {
await finish({
should_dispatch: 'false',
reason: 'Head commit is not a release commit',
current_canary_version: currentCanaryVersion,
})
return
}
const jobs = await getWorkflowRunJobs(owner, repo, workflowRunId, token)
const publishJob = jobs.find((job) => job.name === PUBLISH_RELEASE_JOB_NAME)
// Only continue if the upstream workflow really reached the publish step.
// A successful build-and-deploy run can still skip publishing entirely.
if (publishJob?.conclusion !== 'success') {
await finish({
should_dispatch: 'false',
reason: `${PUBLISH_RELEASE_JOB_NAME} did not complete successfully`,
current_canary_version: currentCanaryVersion,
publish_job_conclusion: publishJob?.conclusion ?? 'missing',
released_version: releasedVersion,
})
return
}
if (releasedVersion.includes('-')) {
await finish({
should_dispatch: 'false',
reason: `Released version ${releasedVersion} is not a stable release`,
current_canary_version: currentCanaryVersion,
released_version: releasedVersion,
})
return
}
const distTags = await fetchJson(
'https://registry.npmjs.org/-/package/next/dist-tags'
)
const latestStableVersion = distTags.latest
// Backports publish a stable version lower than npm's current latest.
// If the released version is not lower than latest, this was not a backport.
if (compareSemver(releasedVersion, latestStableVersion) >= 0) {
await finish({
should_dispatch: 'false',
reason: `Released version ${releasedVersion} is not a backport`,
current_canary_version: currentCanaryVersion,
released_version: releasedVersion,
latest_version: latestStableVersion,
})
return
}
if (compareSemver(currentCanaryVersion, releasedVersion) > 0) {
await finish({
should_dispatch: 'false',
reason: `Current canary version ${currentCanaryVersion} is already ahead of ${releasedVersion}`,
current_canary_version: currentCanaryVersion,
released_version: releasedVersion,
latest_version: latestStableVersion,
})
return
}
const activeTriggerReleaseRun = await getActiveTriggerReleaseRun(
owner,
repo,
token
)
// Avoid stacking multiple canary bumps if several workflow_run events land
// while a previous Trigger Release dispatch is still being processed.
if (activeTriggerReleaseRun) {
await finish({
should_dispatch: 'false',
reason: `Trigger Release is already ${activeTriggerReleaseRun.status} on canary`,
active_trigger_release_url: activeTriggerReleaseRun.html_url,
current_canary_version: currentCanaryVersion,
released_version: releasedVersion,
latest_version: latestStableVersion,
})
return
}
await finish({
should_dispatch: 'true',
reason: `Dispatching canary preminor release because backport ${releasedVersion} is ahead of ${currentCanaryVersion}`,
current_canary_version: currentCanaryVersion,
released_version: releasedVersion,
latest_version: latestStableVersion,
})
}
if (require.main === module) {
main().catch((error) => {
console.error(error)
process.exit(1)
})
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment