name: CodSpeed Benchmarks

on:
  push:
    branches:
      - "main"
  pull_request:
  workflow_dispatch:

jobs:
  benchmarks:
    name: Run benchmarks
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        group:
          - receiver
          - processor
          - exporter
          - pkg
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
      - run: ./.github/workflows/scripts/free-disk-space.sh
      - name: Setup Go
        uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0
        with:
          go-version: stable
          cache: true
          
      - name: Calculate Modules
        id: calc
        run: |
          if [ "${{ matrix.group }}" == "root" ]; then
            echo "TARGET_MODULES=$(pwd)" >> $GITHUB_ENV
          else
            MODULES=$(find ./${{ matrix.group }} -mindepth 1 -maxdepth 2 -type f -name "go.mod" -exec dirname {} \; 2>/dev/null | sort | xargs echo -n || true)
            if [ -z "$MODULES" ]; then
              echo "SKIP_BENCH=true" >> $GITHUB_ENV
              echo "No Go modules found in ${{ matrix.group }}, skipping this job."
            else
              echo "TARGET_MODULES=$MODULES" >> $GITHUB_ENV
            fi
          fi

      - name: Run the benchmarks
        if: env.SKIP_BENCH != 'true'
        uses: CodSpeedHQ/action@658a901452bb54c799643e060733b7afe9121b8d # v4.14.0
        with:
          mode: walltime
          run: make for-all-target TARGET="timebenchmark" GOMODULES="${{ env.TARGET_MODULES }}"
          cache-instruments: true
