name: Test chunk
on:
  workflow_call:
    inputs:
      serialize:
        required: false
        type: boolean
      cmd:
        required: true
        type: string
      chunk-no:
        required: true
        type: number
      wdir:
        required: true
        type: string
    outputs:
      wdir:
        description: "Cache key for the working directory after running tests"
        value: test-${{ inputs.cmd }}-${{ inputs.chunk-no }}-${{ github.run_id }}
    secrets:
      BROWSERSTACK_USER_NAME:
        description: "Browserstack user name"
      BROWSERSTACK_ACCESS_KEY:
        description: "Browserstack access key"

concurrency:
  # The following generates 'browserstack-<run_id>' when inputs.serialize is true, and a hopefully unique ID otherwise
  # Ideally we'd like to serialize browserstack access across all workflows, but github's max queue length is only 1
  # (cfr. https://github.com/orgs/community/discussions/12835)
  # so we add the run_id to serialize only within one push / pull request (which has the effect of queueing e2e and unit tests)
  group: ${{ inputs.serialize && 'browser' || github.run_id }}${{ inputs.serialize && 'stack' || inputs.cmd }}-${{ github.run_id }}
  cancel-in-progress: false

jobs:
  test:
    name: "Test chunk ${{ inputs.chunk-no }}"
    env:
      BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USER_NAME }}
      BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
      TEST_CHUNKS: 4
      TEST_CHUNK: ${{ inputs.chunk-no }}
    runs-on: ubuntu-latest
    steps:
      - name: Set up Node.js
        uses: actions/setup-node@v5
        with:
          node-version: '20'

      - name: Restore working directory
        id: restore-dir
        uses: actions/cache/restore@v4
        with:
          path: .
          key: ${{ inputs.wdir }}
          fail-on-cache-miss: true

      - name: Run tests
        uses: nick-fields/retry@v3
        with:
          timeout_minutes: 8
          max_attempts: 3
          command: ${{ inputs.cmd }}

      - name: Save working directory
        uses: actions/cache/save@v4
        with:
          path: .
          key: test-${{ inputs.cmd }}-${{ inputs.chunk-no }}-${{ github.run_id }}

      - name: Verify cache
        uses: actions/cache/restore@v4
        with:
          path: .
          key: test-${{ inputs.cmd }}-${{ inputs.chunk-no }}-${{ github.run_id }}
          lookup-only: true
          fail-on-cache-miss: true


