name: Address Sanitizer

env:
  DEBUG: 'napi:*'

on:
  push:
    branches:
      - main
  pull_request:

jobs:
  build_and_test:
    name: nightly - ubuntu - node@16
    runs-on: ubuntu-20.04

    steps:
      - uses: actions/checkout@v3

      - name: Setup node
        uses: actions/setup-node@v3
        with:
          node-version: 16
          check-latest: true
          cache: 'yarn'

      - name: Install
        uses: actions-rs/toolchain@v1
        with:
          toolchain: nightly
          profile: minimal
          components: rust-src
          override: true

      - name: Cache cargo
        uses: actions/cache@v3
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
          key: nightly-ubuntu-node@16-cargo-cache

      - name: Cache NPM dependencies
        uses: actions/cache@v3
        with:
          path: .yarn/cache
          key: npm-cache-ubuntu-node@16

      - name: 'Install dependencies'
        run: yarn install --immutable --mode=skip-build

      - name: 'Build TypeScript'
        run: yarn build

      - name: Unit tests with address sanitizer
        run: |
          yarn build:test:asan
          LD_PRELOAD=/usr/lib/gcc/x86_64-linux-gnu/9/libasan.so yarn test
        env:
          RUST_TARGET: x86_64-unknown-linux-gnu
          RUST_BACKTRACE: 1
          RUSTFLAGS: -Z sanitizer=address
          ASAN_OPTIONS: detect_leaks=0

      - name: Clear the cargo caches
        run: |
          cargo install cargo-cache --no-default-features --features ci-autoclean
          cargo-cache