name: Profile with Samply
on:
  push:
    branches: [ main ]
  workflow_dispatch:
jobs:
  profile:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@nightly
        with:
          components: llvm-tools-preview

      - uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}

      - name: Install samply
        uses: taiki-e/cache-cargo-install-action@v2
        with:
          tool: samply

      - name: Configure kernel for profiling
        run: echo '1' | sudo tee /proc/sys/kernel/perf_event_paranoid

      - name: Create test volumes
        run: |
          for i in {0..4}; do
          mkdir -p ./target/volume/test$i
          done

      - name: Set environment variables
        run: |
          echo "RUSTFS_VOLUMES=./target/volume/test{0...4}" >> $GITHUB_ENV
          echo "RUST_LOG=rustfs=info,ecstore=info,s3s=info,iam=info,rustfs-obs=info" >> $GITHUB_ENV

      - name: Download static files
        run: |
          curl -L "https://dl.rustfs.com/artifacts/console/rustfs-console-latest.zip" -o tempfile.zip && unzip -o tempfile.zip -d ./rustfs/static && rm tempfile.zip

      - name: Build with profiling
        run: |
          RUSTFLAGS="-C force-frame-pointers=yes" cargo +nightly build --profile profiling -p rustfs --bins

      - name: Run samply with timeout
        id: samply_record
        run: |
          timeout 120s samply record --output samply.json ./target/profiling/rustfs ${RUSTFS_VOLUMES}
          if [ -f "samply.json" ]; then
            echo "profile_generated=true" >> $GITHUB_OUTPUT
          else
            echo "profile_generated=false" >> $GITHUB_OUTPUT
            echo "::error::Failed to generate profile data"
          fi

      - name: Upload profile data
        if: steps.samply_record.outputs.profile_generated == 'true'
        uses: actions/upload-artifact@v4
        with:
          name: samply-profile-${{ github.run_number }}
          path: samply.json
          retention-days: 7