如何在 CI 中基于“main”分支构建耗时基线,当 PR 分支超出 10% 即失败?请给出 GitHub Actions 表达式。

解读

  1. 场景定位
    国内一线/二线前端团队普遍把“构建耗时”写进 PR 门禁,防止新依赖、误配插件或冗余资源把流水线拖垮。Parcel 虽然零配置,但项目一旦引入 SASS、WASM、Workbox 后,构建时长仍可能翻倍,因此必须在 CI 侧做“可量化的性能卡口”。
  2. 基线来源
    基线只能取自“main”分支最近一次成功的构建,而不是本地开发机;否则不同 runner 规格(GitHub Hosted 2-core vs 自建 16-core)会让数据失真。
  3. 判定规则
    超出 10% 即失败,意味着“PR 耗时 > 基线 × 1.1”时退出码非 0;同时要给产品经理留一个“强制合并”按钮,因此要把结论写到 PR comment 而不是直接 block merge(国内习惯用 comment + status check 组合)。
  4. 数据持久化
    GitHub Actions 的跨 workflow 共享缓存只有 cache 和 artifact 两种可靠方式。构建耗时是“单值+时间戳”,用 artifact 存 JSON 最轻量,也避免 cache 被 LRU 清掉。
  5. 并发安全
    main 分支的 push 事件可能并发,上传 artifact 时必须带 run-id 或 commit-sha 作为命名空间,防止竞态覆盖。

知识点

  • GitHub Actions 表达式语法:${{ }} 内可使用运算符 +、*、>,以及内置函数 contains、startsWith 等。
  • artifact 上传/下载:actions/upload-artifact@v4 和 actions/download-artifact@v4(v4 开始支持跨 workflow)。
  • 数值比较:shell 里用 bc 或 awk,bash 不支持浮点,> 只能比较整数;因此把毫秒放大成整数再比。
  • 状态回写:gh api repos/{owner}/{repo}/statuses/${{ github.event.pull_request.head.sha }} -f state=failure
  • 评论写入:gh pr comment ${{ github.event.number }} --body "构建耗时 18.3 s,超出基线 10%(16.2 s)"

答案

以下给出可直接落地的 workflow 片段,全部用 GitHub Actions 表达式与官方 action 完成,不依赖第三方市场 action,符合国内私有仓库可移植要求。

name: Parcel Build Perf Gate

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

env:
  ART_NAME: parcel-baseline

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      # 统一 Node 版本,保证耗时可比
      - uses: actions/setup-node@v4
        with: { node-version: 18, cache: 'npm' }

      - name: Install & Build
        run: |
          npm ci
          # 把耗时精确到毫秒,写入文件
          start=$(date +%s%3N)
          npx parcel build src/index.html --no-source-maps --no-cache
          end=$(date +%s%3N)
          echo $((end-start)) > build-time.txt
          cat build-time.txt

      # --------- main 分支:上传新基线 ---------
      - name: Upload baseline artifact
        if: github.ref == 'refs/heads/main'
        uses: actions/upload-artifact@v4
        with:
          name: ${{ env.ART_NAME }}
          path: build-time.txt
          retention-days: 30

      # --------- PR 分支:下载基线并比较 ---------
      - name: Download baseline
        if: github.event_name == 'pull_request'
        uses: actions/download-artifact@v4
        continue-on-error: true
        with:
          name: ${{ env.ART_NAME }}
          path: baseline/

      - name: Performance gate
        if: github.event_name == 'pull_request'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          # 如果基线不存在,跳过门禁(首次提交场景)
          if [ ! -f baseline/build-time.txt ]; then
            echo "No baseline found, skip gate."
            exit 0
          fi
          baseline=$(cat baseline/build-time.txt)
          current=$(cat build-time.txt)
          # 放大 100 倍转整数,避免 bash 浮点问题
          threshold=$(( baseline * 110 ))
          actual=$(( current * 100 ))
          echo "baseline=${baseline}ms, current=${current}ms, threshold=${threshold}, actual=${actual}"
          if [ "$actual" -gt "$threshold" ]; then
            percent=$(awk "BEGIN{printf \"%.1f\", ($current-$baseline)/$baseline*100}")
            gh pr comment ${{ github.event.number }} --body \
              "🚫 构建性能门禁未通过:PR 耗时 **${current}ms**,基线 **${baseline}ms**,超出 **${percent}%**(>10%)。"
            # 写状态检查,让分支保护规则生效
            gh api repos/${{ github.repository }}/statuses/${{ github.event.pull_request.head.sha }} \
              -f state=failure \
              -f context="Parcel Build Perf Gate" \
              -f description "Build time exceeded baseline by >10%"
            exit 1
          else
            gh api repos/${{ github.repository }}/statuses/${{ github.event.pull_request.head.sha }} \
              -f state=success \
              -f context="Parcel Build Perf Gate" \
              -f description "Build time within 10% of baseline"
          fi

关键表达式/变量

  • ${{ github.ref == 'refs/heads/main' }} 用于区分基线采集与 PR 检查。
  • ${{ github.event.pull_request.head.sha }} 是 PR 最新 commit,status 必须打在它上面才能触发分支保护。
  • 数值比较在 bash 完成,避免 GitHub 表达式不支持浮点。

拓展思考

  1. 基线老化问题
    国内项目迭代快,基线 30 天不变会失真。可在 artifact 里再存一个时间戳,当下载到的基线早于 7 天,自动以当前 PR 的 90% 作为“临时基线”,并评论提醒负责人 review。
  2. 多目标输出
    Parcel 同时打出 web 与 electron 两份 bundle 时,需分别统计耗时并做加权;否则 electron 主进程 bundle 很小,会掩盖 web bundle 的劣化。
  3. 缓存污染
    若 CI 启用了 parcel-cache 或 GitHub cache,PR 分支可能命中 main 的缓存,导致耗时“虚低”。解决办法是在性能门禁 job 里加 PARCEL_WORKERS=0 与 --no-cache,强制冷编译,保证数据可比。
  4. 统计可视化
    把每次 main 的耗时再推到 Prometheus + Grafana,就能在自建监控大屏里看到“构建性能趋势”,方便架构组做专项优化。
  5. 渐进式阈值
    对老项目第一次接入,可直接用 20% 阈值,运行两周后取 95 分位值作为正式基线,避免初期频繁失败打击业务方积极性。