name: chaos / metrics daily

# M5 of chaos engineering: 每日拉 epsilon access.jsonl 聚合 p50/p95/p99
# + error rate，输出 shields.io 徽章 JSON。
# 设计见 brain/issues/006-performance-monitoring.md

on:
  schedule:
    - cron: "0 6 * * *"   # UTC 06:00（= 北京 14:00）
  workflow_dispatch:

jobs:
  aggregate:
    name: 拉 access.jsonl + 聚合 + commit 徽章到 metrics-data 分支
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4

      - uses: webfactory/ssh-agent@v0.9.0
        with:
          ssh-private-key: ${{ secrets.EPSILON_SSH_KEY }}

      - name: known_hosts
        run: |
          mkdir -p ~/.ssh
          ssh-keyscan ${{ secrets.EPSILON_HOST }} >> ~/.ssh/known_hosts

      - name: 拉 epsilon access.jsonl
        run: |
          mkdir -p /tmp/metrics-in
          # epsilon 上 access.jsonl 由 xiangqin user 写，root 能读
          scp root@${{ secrets.EPSILON_HOST }}:/opt/xiangqin/logs/access.jsonl /tmp/metrics-in/ 2>/dev/null \
            || echo "access.jsonl 不存在（epsilon 可能刚部署还没流量）"
          ls -la /tmp/metrics-in/ 2>&1 || true

      - name: 跑 aggregate
        run: |
          python3 scripts/aggregate_metrics.py \
            /tmp/metrics-in/access.jsonl \
            /tmp/metrics-out

          echo "=== output ==="
          ls -la /tmp/metrics-out/
          cat /tmp/metrics-out/latest.json

      - name: force-push 徽章 JSON 到 metrics-data 分支（孤儿）
        run: |
          set -euo pipefail
          # 用孤儿分支存徽章 JSON，不污染 main 历史
          cd /tmp/metrics-out
          git init -q
          git config user.email "chaos@acong.tech"
          git config user.name "chaos-metrics"
          git checkout -q -b metrics-data
          git add .
          git commit -q -m "metrics update $(date -u +%Y-%m-%dT%H:%M:%SZ)"
          git push -q --force "https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git" metrics-data
          echo "✓ pushed to branch metrics-data"

      - name: summary
        if: always()
        run: |
          cat <<EOF >> "$GITHUB_STEP_SUMMARY"
          ### Metrics daily aggregate

          过去 24h epsilon 请求的 p50/p95/p99 + error_rate，
          输出到 \`metrics-data\` 分支，shields.io 通过 raw
          GitHub URL 读取渲染徽章。

          \`\`\`
          $(cat /tmp/metrics-out/latest.json 2>/dev/null || echo "(no data)")
          \`\`\`
          EOF
