diff --git a/.github/actions/check-maintenance/action.yml b/.github/actions/check-maintenance/action.yml index e2cfd9cc8a..688dec1ad5 100644 --- a/.github/actions/check-maintenance/action.yml +++ b/.github/actions/check-maintenance/action.yml @@ -10,159 +10,138 @@ inputs: runs: using: composite steps: + # Runs on the Node runtime bundled with the Actions runner; do not depend on + # tools from the runner image (jq, gh), which self-hosted images may lack. - name: Check maintenance mode - shell: bash + uses: actions/github-script@v8 env: - GH_TOKEN: ${{ inputs.github-token }} - run: | - MAINTENANCE_ISSUE=21065 - REPO="${{ github.repository }}" - PR_NUMBER="${{ github.event.pull_request.number }}" - PR_HEAD_SHA="${{ github.event.pull_request.head.sha }}" + PR_TEST_BYPASS_MAINTENANCE_ON_MAIN: ${{ env.PR_TEST_BYPASS_MAINTENANCE_ON_MAIN }} + with: + github-token: ${{ inputs.github-token }} + # Retries 5xx and dropped connections so a blip does not fail the gate open; + # 4xx (e.g. 404 for an unknown MIN_BASE_SHA) is exempt by default. + retries: 2 + script: | + const MAINTENANCE_ISSUE = 21065; + const { owner, repo } = context.repo; + const issueUrl = `https://github.com/${owner}/${repo}/issues/${MAINTENANCE_ISSUE}`; - # PR Test workflow only: scheduled runs and runs on main (dispatch / workflow_call) set this env - if [[ "${PR_TEST_BYPASS_MAINTENANCE_ON_MAIN:-}" == "true" ]]; then - echo "✅ PR Test on main branch; bypassing maintenance gate." - exit 0 - fi + async function block(lines) { + const msg = lines.join('\n'); + await core.summary.addRaw(msg + '\n').write(); + core.setFailed(msg); + } - # Use curl + jq instead of `gh` because self-hosted GPU runners - # don't have the gh CLI installed. Without this, the action - # silently fell through to "Proceeding with CI" on every GPU - # job — the rebase gate only fired on ubuntu-latest jobs that - # had gh pre-installed. curl+jq are reliably available on every - # Linux runner. - gh_api() { - local path="$1" - local err_file="$2" - curl --silent --show-error --fail \ - --max-time 30 \ - -H "Authorization: Bearer $GH_TOKEN" \ - -H "Accept: application/vnd.github+json" \ - -H "X-GitHub-Api-Version: 2022-11-28" \ - "https://api.github.com/$path" 2>"$err_file" - } + // PR Test workflow only: scheduled runs and runs on main (dispatch / workflow_call) set this env + if (process.env.PR_TEST_BYPASS_MAINTENANCE_ON_MAIN === 'true') { + core.info('✅ PR Test on main branch; bypassing maintenance gate.'); + return; + } - # Fetch issue state and body. Fail-open: if we can't read the issue - # (network blip, missing token scope), CI proceeds. - ERR_FILE=$(mktemp) - ISSUE_JSON=$(gh_api "repos/$REPO/issues/$MAINTENANCE_ISSUE" "$ERR_FILE" || true) - if [[ -z "$ISSUE_JSON" ]]; then - echo "⚠️ Issue fetch returned empty. curl stderr was:" - cat "$ERR_FILE" || true - fi - rm -f "$ERR_FILE" - ISSUE_STATE=$(printf '%s' "$ISSUE_JSON" | jq -r '.state // "UNKNOWN"' 2>/dev/null || echo "UNKNOWN") - # Issues API returns state in lowercase ("open"/"closed"); normalize - # to uppercase so existing comparisons against "OPEN" still work. - ISSUE_STATE=$(printf '%s' "$ISSUE_STATE" | tr '[:lower:]' '[:upper:]') - ISSUE_BODY=$(printf '%s' "$ISSUE_JSON" | jq -r '.body // ""' 2>/dev/null || echo "") - echo "DEBUG: ISSUE_STATE=$ISSUE_STATE body_length=${#ISSUE_BODY}" + // Fail-open only when the API call itself fails after retries; + // CI proceeds with a warning (outage, missing token scope). + let issue; + try { + ({ data: issue } = await github.rest.issues.get({ owner, repo, issue_number: MAINTENANCE_ISSUE })); + } catch (e) { + core.warning(`Could not fetch issue #${MAINTENANCE_ISSUE} (${e.status ?? e.message}); fail-open, proceeding with CI.`); + return; + } + const issueOpen = issue.state === 'open'; + const body = (issue.body || '').replace(/\r/g, ''); + core.info(`DEBUG: ISSUE_STATE=${issue.state} body_length=${body.length}`); - # Parse optional `MIN_BASE_SHA: ` directive from the issue body - # (first occurrence wins). Whenever this directive is present, the - # rebase check is enforced regardless of whether the issue is open - # or closed — so maintainers can require all PRs to rebase past a - # specific commit without having to open the maintenance issue. - # `grep` exits 1 on no-match, which under `set -eo pipefail` (the - # default for `shell: bash` composite steps) would abort the whole - # script — silently failing every PR whose issue body has no - # MIN_BASE_SHA line. Wrap grep in a brace group with `|| true` so - # an empty match falls through cleanly to "no directive set". - MIN_BASE_SHA=$( - { printf '%s' "$ISSUE_BODY" | tr -d '\r' | grep -iE '^[[:space:]]*`?MIN_BASE_SHA`?[[:space:]]*[:=]' || true; } \ - | head -n1 | sed -E 's/.*[:=][[:space:]]*//; s/`//g' | awk '{print $1}' - ) - if [[ -n "$MIN_BASE_SHA" ]] && ! [[ "$MIN_BASE_SHA" =~ ^[a-fA-F0-9]{7,40}$ ]]; then - WARN="⚠️ Ignoring malformed MIN_BASE_SHA directive in issue #$MAINTENANCE_ISSUE: '$MIN_BASE_SHA' (must be 7-40 hex chars)" - echo "$WARN" - echo "$WARN" >> "$GITHUB_STEP_SUMMARY" - MIN_BASE_SHA="" - fi + // First matching `MIN_BASE_SHA: ` line wins; it is enforced + // whether the issue is open or closed. + let minBaseSha = ''; + const directive = body.split('\n') + .map(line => line.match(/^\s*`?MIN_BASE_SHA`?\s*[:=]\s*(.*)$/i)) + .find(Boolean); + if (directive) { + const value = directive[1].replace(/`/g, '').trim().split(/\s+/)[0] || ''; + if (/^[0-9a-f]{7,40}$/i.test(value)) { + minBaseSha = value; + } else { + const warn = `⚠️ Ignoring malformed MIN_BASE_SHA directive in issue #${MAINTENANCE_ISSUE}: '${value}' (must be 7-40 hex chars)`; + core.warning(warn); + await core.summary.addRaw(warn + '\n').write(); + } + } + core.info(`DEBUG: MIN_BASE_SHA=${minBaseSha || '(none)'}`); - # If neither gate is active (no MIN_BASE_SHA, issue not open), nothing to do. - if [[ -z "$MIN_BASE_SHA" && "$ISSUE_STATE" != "OPEN" ]]; then - echo "✅ Maintenance mode is OFF and no MIN_BASE_SHA directive. Proceeding with CI." - exit 0 - fi + // If neither gate is active (no MIN_BASE_SHA, issue not open), nothing to do. + if (!minBaseSha && !issueOpen) { + core.info('✅ Maintenance mode is OFF and no MIN_BASE_SHA directive. Proceeding with CI.'); + return; + } - # bypass-maintenance label bypasses both gates. PR labels live on - # the issue resource (PRs are issues with extra metadata in the - # GH API), so we hit the same /issues/{n} endpoint. - if [[ -n "$PR_NUMBER" ]]; then - ERR_FILE=$(mktemp) - PR_JSON=$(gh_api "repos/$REPO/issues/$PR_NUMBER" "$ERR_FILE" || true) - rm -f "$ERR_FILE" - HAS_BYPASS=$(printf '%s' "$PR_JSON" | jq -r '[.labels[]?.name] | map(select(. == "bypass-maintenance")) | length' 2>/dev/null || echo "0") - if [[ "${HAS_BYPASS:-0}" -gt 0 ]]; then - echo "✅ PR #$PR_NUMBER has 'bypass-maintenance' label. Bypassing maintenance + rebase checks." - exit 0 - fi - fi + const pr = context.payload.pull_request; - # Rebase-required gate (independent of issue open/closed state). - if [[ -n "$MIN_BASE_SHA" ]]; then - if [[ -z "$PR_NUMBER" || -z "$PR_HEAD_SHA" ]]; then - echo "✅ Not a PR context; skipping rebase check." - else - # Use GitHub compare API: status is "ahead"/"identical" when MIN_BASE_SHA is reachable from PR head. - ERR_FILE=$(mktemp) - COMPARE_JSON=$(gh_api "repos/$REPO/compare/$MIN_BASE_SHA...$PR_HEAD_SHA" "$ERR_FILE" || true) - if [[ -z "$COMPARE_JSON" ]]; then - echo "⚠️ Compare API failed. curl stderr was:" - cat "$ERR_FILE" || true - fi - rm -f "$ERR_FILE" - COMPARE_STATUS=$(printf '%s' "$COMPARE_JSON" | jq -r '.status // "UNKNOWN"' 2>/dev/null || echo "UNKNOWN") - COMPARE_STATUS="${COMPARE_STATUS:-UNKNOWN}" + // Read labels live; the event payload is frozen at the first attempt, + // so a rerun would miss a bypass-maintenance label added since. + if (pr) { + let labels = []; + try { + labels = await github.paginate(github.rest.issues.listLabelsOnIssue, + { owner, repo, issue_number: pr.number, per_page: 100 }); + } catch (e) { + core.warning(`Could not read labels of PR #${pr.number} (${e.status ?? e.message}); assuming no bypass label.`); + } + if (labels.some(l => l.name === 'bypass-maintenance')) { + core.info(`✅ PR #${pr.number} has 'bypass-maintenance' label. Bypassing maintenance + rebase checks.`); + return; + } + } - case "$COMPARE_STATUS" in - ahead|identical) - echo "✅ PR #$PR_NUMBER contains required base ${MIN_BASE_SHA:0:12} ($COMPARE_STATUS)." - ;; - UNKNOWN) - echo "⚠️ Could not determine rebase status via GitHub API; fail-open, allowing rebase check to pass." - ;; - *) - MSG=$(printf "%s\n" \ - "## ⚠️ Rebase Required Before CI Can Run" \ - "A major update has landed on \`main\`. All PRs must rebase onto the latest \`main\` before CI will run." \ - "Required base commit: \`${MIN_BASE_SHA:0:12}\` (your PR is \`$COMPARE_STATUS\` relative to this commit)." \ - "" \ - "What should you do?" \ - "- Rebase your branch onto the latest \`main\` and push again" \ - "- Follow CI Maintenance Mode issue: https://github.com/$REPO/issues/$MAINTENANCE_ISSUE for context" \ - "- CI-fix PRs may request the \`bypass-maintenance\` label to skip this check") - echo "$MSG" >> "$GITHUB_STEP_SUMMARY" - while IFS= read -r line; do - echo "::error::$line" - done <<< "$MSG" - exit 1 - ;; - esac - fi - fi + // Rebase-required gate (independent of issue open/closed state). + if (minBaseSha) { + if (!pr?.number || !pr?.head?.sha) { + core.info('✅ Not a PR context; skipping rebase check.'); + } else { + // Compare status is "ahead"/"identical" when MIN_BASE_SHA is reachable from PR head. + let status = 'UNKNOWN'; + try { + ({ data: { status } } = await github.rest.repos.compareCommitsWithBasehead( + { owner, repo, basehead: `${minBaseSha}...${pr.head.sha}`, per_page: 1 })); + } catch (e) { + core.warning(`Compare API failed (${e.status ?? e.message}).`); + } + if (status === 'ahead' || status === 'identical') { + core.info(`✅ PR #${pr.number} contains required base ${minBaseSha.slice(0, 12)} (${status}).`); + } else if (status === 'UNKNOWN') { + core.warning('Could not determine rebase status via GitHub API; fail-open, allowing rebase check to pass.'); + } else { + await block([ + '## ⚠️ Rebase Required Before CI Can Run', + 'A major update has landed on `main`. All PRs must rebase onto the latest `main` before CI will run.', + `Required base commit: \`${minBaseSha.slice(0, 12)}\` (your PR is \`${status}\` relative to this commit).`, + '', + 'What should you do?', + '- Rebase your branch onto the latest `main` and push again', + `- Follow CI Maintenance Mode issue: ${issueUrl} for context`, + '- CI-fix PRs may request the `bypass-maintenance` label to skip this check', + ]); + return; + } + } + } - # Full-pause maintenance gate (only when issue is open). - if [[ "$ISSUE_STATE" == "OPEN" ]]; then - MSG=$(printf "%s\n" \ - "## ⚠️ CI Maintenance Mode is Active" \ - "The CI infrastructure is currently under maintenance." \ - "All PR CI runs are paused until maintenance is complete." \ - "**Merging non-CI-fix PRs is prohibited during maintenance mode.** In severe cases, merge permissions may be revoked." \ - "You might also experience unexpected failures during this period." \ - "The team is working on the issue and will update the status as soon as possible." \ - "" \ - "What should you do?" \ - "- **Do NOT merge non-CI-fix PRs** until maintenance mode is lifted" \ - "- Check back later (~12 hours)" \ - "- Follow CI Maintenance Mode issue: https://github.com/$REPO/issues/$MAINTENANCE_ISSUE for status updates") + // Full-pause maintenance gate (only when issue is open). + if (issueOpen) { + await block([ + '## ⚠️ CI Maintenance Mode is Active', + 'The CI infrastructure is currently under maintenance.', + 'All PR CI runs are paused until maintenance is complete.', + '**Merging non-CI-fix PRs is prohibited during maintenance mode.** In severe cases, merge permissions may be revoked.', + 'You might also experience unexpected failures during this period.', + 'The team is working on the issue and will update the status as soon as possible.', + '', + 'What should you do?', + '- **Do NOT merge non-CI-fix PRs** until maintenance mode is lifted', + '- Check back later (~12 hours)', + `- Follow CI Maintenance Mode issue: ${issueUrl} for status updates`, + ]); + return; + } - echo "$MSG" >> "$GITHUB_STEP_SUMMARY" - while IFS= read -r line; do - echo "::error::$line" - done <<< "$MSG" - exit 1 - fi - - echo "✅ Rebase check passed; full-pause not active. Proceeding with CI." + core.info('✅ Rebase check passed; full-pause not active. Proceeding with CI.');