用 Sentry 的真实用户数据给 CI/CD 装一个自动性能告警——超过阈值直接 block 部署

Sentry 装了一大堆,上线之后还是被用户告状说页面卡了——这种事儿估计每个前端团队都经历过。问题出在哪?CI/CD 跑了一晚上,绿灯全亮,测的是测试环境,上线之后才是真实用户在用。

Sentry 本身就是在前线看你的应用,但它和数据门禁之间隔了一层。我今天把这个接上,40 行代码,给 CI/CD 装一个用真实用户数据做判断的自动拦截。

场景:上线前你只知道「能跑」,不知道「跑得怎么样」

传统 CI/CD 质量门禁是这样的:Lint 通过 → 单元测试通过 → E2E 测试通过 → 合并。Sentry 那边呢?错误日志一点点积累,等某个用户甩截图到群里你才知道出问题了。

这两条线从来没接上。Sentry 有 API,有 release 数据,有每小时的错误数统计——但没有人把它拿进 CI 里当 gate 用。我来把它接上。

方案:用 Sentry API 在 CI 里拿真实错误数,超过阈值就 block 部署

思路很直接:每次 deploy 到 staging 之后,CI 跑一个脚本,去 Sentry 拿这个 release 在接下来 10 分钟内的错误数。如果超过了设定的阈值,pipeline 失败,阻止后续的 production 部署。核心就是这个脚本,拿 Node.js 写,依赖只有 axios:

// scripts/sentry-release-gate.js
import axios from 'axios';

const {
  SENTRY_AUTH_TOKEN,
  SENTRY_ORG,
  SENTRY_PROJECT,
  SENTRY_VERSION,
  THRESHOLD_MINUTES = 10,
  ERROR_THRESHOLD = 5,
} = process.env;

async function getReleaseErrorCount() {
  const now = Math.floor(Date.now() / 1000);
  const start = now - THRESHOLD_MINUTES * 60;

  const response = await axios.get(
    `https://sentry.io/api/0/projects/${SENTRY_ORG}/${SENTRY_PROJECT}/events/`,
    {
      headers: { Authorization: `Bearer ${SENTRY_AUTH_TOKEN}` },
      params: {
        query: `release:${SENTRY_VERSION}`,
        statsFor: '1h',
        start: new Date(start * 1000).toISOString(),
        end: new Date(now * 1000).toISOString(),
      },
    }
  );
  return response.data.length;
}

async function main() {
  console.log(`[Sentry Gate] 检查 release ${SENTRY_VERSION},窗口 ${THRESHOLD_MINUTES} 分钟...`);
  const errorCount = await getReleaseErrorCount();
  console.log(`[Sentry Gate] 错误数:${errorCount},阈值:${ERROR_THRESHOLD}`);

  if (errorCount > ERROR_THRESHOLD) {
    console.error(`[Sentry Gate] 错误数 ${errorCount} 超过阈值 ${ERROR_THRESHOLD},block 本次部署`);
    process.exit(1);
  } else {
    console.log(`[Sentry Gate] 通过,错误数在容忍范围内`);
  }
}

main().catch((err) => {
  console.error('[Sentry Gate] 检查失败:', err.message);
  process.exit(1);
});

GitHub Actions 里的完整 pipeline

# .github/workflows/deploy.yml
name: Deploy & Sentry Gate

on:
  push:
    branches: [main]

jobs:
  deploy-staging:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Deploy to Staging
        run: ./deploy.sh staging
      - name: Create Sentry Release
        run: |
          npx sentry-cli releases new "$GITHUB_SHA"
          npx sentry-cli releases set-commits --commit "my-repo@$GITHUB_SHA"
          npx sentry-cli releases finalize "$GITHUB_SHA"
      - name: Persist release version
        run: echo "$GITHUB_SHA" > /tmp/release_version
      - uses: actions/upload-artifact@v4
        with:
          name: release-version
          path: /tmp/release_version

  sentry-gate:
    runs-on: ubuntu-latest
    needs: deploy-staging
    steps:
      - uses: actions/download-artifact@v4
        with:
          name: release-version
          path: .
      - name: Run Sentry Release Gate
        run: node scripts/sentry-release-gate.js
        env:
          SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
          SENTRY_ORG: my-org
          SENTRY_PROJECT: my-frontend-app
          SENTRY_VERSION: ${{ github.sha }}
          THRESHOLD_MINUTES: 10
          ERROR_THRESHOLD: 5

  deploy-production:
    runs-on: ubuntu-latest
    needs: [deploy-staging, sentry-gate]
    if: always() && needs.deploy-staging.result == 'success' && needs.sentry-gate.result == 'success'
    steps:
      - name: Deploy to Production
        run: ./deploy.sh production

关键点是这里用了 always() && needs.sentry-gate.result == 'success' 来保证 gate 失败时 production deploy 不会跑。

阈值怎么定

  • 小型应用(DAU < 1 万):THRESHOLD_MINUTES=10,ERROR_THRESHOLD=3
  • 中型应用(1 万 ~ 50 万):THRESHOLD_MINUTES=10,ERROR_THRESHOLD=10
  • 大型应用(50 万+):THRESHOLD_MINUTES=30,ERROR_THRESHOLD=20

数字不是死的,跑一个月之后调到你们自己的基线。Sentry 本身就有 release 的 crash free session 统计,那个数字比拍脑袋定阈值靠谱得多。

进阶:这个 gate 本身也可以是 Sentry Alert

上面这套是 CI 主动去拉数据。更稳健的做法是反过来:用 Sentry Alert 触发 workflow dispatch——当某个 release 的错误数触发 Sentry 的 alert rule 时,自动创建一个 GitHub Issue 并把负责这个 commit 的人 assign 进去。

// 接到 alert 之后自动在 GitHub 开 issue 并 assign 相关工程师
app.post('/webhook/sentry', async (req, res) => {
  const { release, error_count, assigned_team } = req.body;
  await github.rest.issues.create({
    owner: 'my-org',
    repo: 'my-frontend-app',
    title: `Sentry Alert: release ${release} 错误数超标 (${error_count})`,
    labels: ['sentry-alert', 'performance'],
    assignees: assigned_team,
  });
  res.status(200).send('OK');
});

这样 Sentry Alert 本身就是第一道防线,CI Gate 是第二道,一道报警、一道拦截,配合着来。

这个方案的核心价值

不是「Sentry 接入 CI」这件事本身有多难,而是把质量门禁从「我知道上线后可能会出问题」变成「我有一个自动化的机制在上线前告诉我不能上线」。以前质量门禁的逻辑是:代码通过了测试 = 代码没问题。现在的逻辑是:代码通过了测试 + Sentry 在真实流量下没有异常 = 代码暂时没问题。第二条判断以前是缺失的,现在把它补上了。

评论区

0 条评论

登录后可评论。

阿监·前端工程化 2708 阅读