name: benchmarks

on:
  schedule:
    - cron:  '0 3 * * *'
  workflow_dispatch:

env:
  GOPROXY: https://proxy.golang.org/

jobs:
  benchmarks:
    runs-on: ubuntu-latest
    timeout-minutes: 90
    steps:
      -
        name: Checkout
        uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # https://github.com/actions/checkout/releases/tag/v4.1.1
      -
        name: Unshallow
        run: git fetch --prune --unshallow
      -
        name: Set up Go
        uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # https://github.com/actions/setup-go/releases/tag/v4.1.0
        with:
          go-version-file: ".go-version"
      -
        name: Go mod download
        run: go mod download -x
      -
        name: Run benchmarks
        id: bench
        run: |
          go test ./internal/langserver/handlers \
            -bench=InitializeFolder_basic \
            -run=^# \
            -benchtime=60s \
            -timeout=60m | tee ${{ runner.temp }}/benchmarks.txt
      -
        name: Evaluate benchmarks
        id: bench-eval
        run: |
          BENCHDATA="go run go.bobheadxi.dev/gobenchdata"

          BENCH_PATH="${{ runner.temp }}/benchmarks.txt"
          DATA_PATH="${{ runner.temp }}/benchdata.json"
          RESULTS_PATH="${{ runner.temp }}/benchdata-results.json"
          CHECKS_CONFIG_PATH="${{ github.workspace }}/.github/gobenchdata-checks.yml"

          cat $BENCH_PATH | $BENCHDATA --json ${DATA_PATH} -v "${GITHUB_SHA}" -t "ref=${GITHUB_REF}"

          $BENCHDATA checks eval \
            ${DATA_PATH} \
            ${DATA_PATH} \
            --checks.config ${CHECKS_CONFIG_PATH} \
            --json ${RESULTS_PATH}

          cat $RESULTS_PATH | jq -e '.Status == "pass"'
      -
        name: Report failures
        id: report
        if: ${{ failure() && !cancelled() }}
        run: |
          BENCHDATA="go run go.bobheadxi.dev/gobenchdata"
          RESULTS_PATH="${{ runner.temp }}/benchdata-results.json"
          $BENCHDATA checks report $RESULTS_PATH
      -
        name: Upload benchmark data as artifact
        if: ${{ always() && !cancelled() }}
        uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # https://github.com/actions/upload-artifact/releases/tag/v3.1.3
        with:
          name: benchdata-${{ github.ref_name }}-${{ github.sha }}-${{ github.run_id }}.json
          path: "${{ runner.temp }}/benchdata.json"
      -
        name: Send failures to Slack
        if: ${{ failure() && !cancelled() }}
        uses: slackapi/slack-github-action@e28cf165c92ffef168d23c5c9000cffc8a25e117 # https://github.com/slackapi/slack-github-action/releases/tag/v1.24.0
        with:
          payload: |
            {
              "results_url": "https://github.com/hashicorp/terraform-ls/actions/runs/${{ github.run_id }}"
            }
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.BENCHMARKS_SLACK_WEBHOOK_URL }}
