# `Juggernaut.Peer.Boot`
[🔗](https://github.com/holsee/juggernaut/blob/v0.4.0/lib/juggernaut/peer/boot.ex#L1)

Boots a worker: run once inside a fresh `:peer`, before any job (design notes §10.5).

`boot/1` goes through these stages, timing each:

  1. `:project` - cd into the sandbox, start Mix in `:test`, load the sandbox's
     `mix.exs` with type inference off (as the sandbox compile does, so Mix sees the
     same options and does not recompile), and run `app.config --no-compile
     --no-deps-check` (load paths, the project's config). The compile phase has built the
     sandbox and its dependencies before any worker boots, so the check it skips would
     find nothing to do; it was most of a boot (2 s of a 4.4 s boot on a small fixture),
     paid again by every recycle and boot-lane job. The worker's environment
     (`MIX_TEST_PARTITION`) was set by `:peer` before this, so the config sees it;
  2. `:setup` - the `worker_setup` tasks (by default the steps of the project's `test`
     alias other than `test`, such as `ecto.create` and `ecto.migrate`), each retried
     `retries` times, `backoff_ms` apart and doubling, before the boot fails;
  3. `:start` - on a boot-lane worker, mark the `progress` file (`mark_switched/1`)
     and set its switch; on any other, start recording
     the boot set (`Juggernaut.Peer.Recorder.arm_boot/0`, the switch in probe mode);
     then `app.start`;
  4. `:tests` - `ExUnit.start(autorun: false)`, each test path's `test_helper.exs`, and
     the test files (Mix's `test_load_filters`, default `*_test.exs`) required once, and the
     `ExUnit.after_suite/1` callbacks they registered dropped (`drop_after_suite/0`).
     With `test_files`, only those are required, and the others wait for a job that
     asks for them (`load_pending/0`);
     then the boot set is taken and the switch set back to 0 (not on a boot-lane
     worker, whose mutant stays on);
  5. `:ready` - one run with no test selected, which empties ExUnit's module queue (test
     modules register themselves when they load); the test inventory; the partition
     facts; the state snapshot (`Juggernaut.Peer.Snapshot`) and the health fingerprint
     (`Juggernaut.Peer.Health`) that every job is compared against.

A boot can stop after the first stage: `park/1` runs `:project` only and leaves the peer
parked (a fresh VM with the project loaded, no database touched, the app not started,
no test file loaded), and `resume/1` runs the other four later, with options merged
over the parked ones (a boot-lane job's switch and progress file). A parked peer is a
worker's spare (`Juggernaut.Pool.Worker`): nothing it has done depends on the switch or
on the database, so a recycle or a boot-lane job that takes it skips the VM start and
the project load and loses nothing. `boot/1` is `park/1` then `resume/1`.

The stages run in a keeper process that lives as long as the worker (`kept/1`), so what
the test helpers own outlives the boot, as under `mix test`. It returns `{:ok, info}` or
`{:error, %{stage: stage, message: message}}`; nothing it does raises past it. The info carries the inventory (each test's file, line and
whether the project's tag filters exclude it), the databases of the project's Ecto
repos (the partition check), the boot set (`boot_sites`: the sites hit from app start to
the test files loaded), the stage clocks in milliseconds, and memory.

This module runs inside workers and is never mutated.

# `info`

```elixir
@type info() :: %{
  tests: %{required({module(), atom()}) =&gt; test_info()},
  databases: [String.t()],
  boot_sites: [pos_integer()],
  env: %{required(String.t()) =&gt; String.t() | nil},
  clocks: %{required(atom()) =&gt; non_neg_integer()},
  memory: non_neg_integer(),
  schedulers: pos_integer()
}
```

# `opts`

```elixir
@type opts() :: %{
  :sandbox =&gt; Path.t(),
  optional(:setup) =&gt; :test_alias | [String.t()],
  optional(:lasting) =&gt; [atom()],
  optional(:lasting_servers) =&gt; [module()],
  optional(:retries) =&gt; non_neg_integer(),
  optional(:backoff_ms) =&gt; non_neg_integer(),
  optional(:switch) =&gt; integer(),
  optional(:progress) =&gt; Path.t(),
  optional(:env_names) =&gt; [String.t()],
  optional(:test_files) =&gt; [Path.t()] | nil
}
```

# `test_info`

```elixir
@type test_info() :: %{
  file: String.t(),
  line: pos_integer(),
  excluded?: boolean(),
  tags: [atom()]
}
```

# `boot`

```elixir
@spec boot(opts()) :: {:ok, info()} | {:error, %{stage: atom(), message: String.t()}}
```

Boots the worker (see the module doc): `park/1`, then `resume/1` with no overrides.

# `drop_after_suite`

```elixir
@spec drop_after_suite() :: :ok
```

Removes the `ExUnit.after_suite/1` callbacks the test helpers and test files
registered. A worker calls `ExUnit.run/1` once per job, and each call would run them,
though no job is the end of the suite. A callback written for the end of a whole run,
such as one reading a table its helper's process owned, can fail in a job and fail
it; and its report would come once per job. Returns `:ok`.

# `inventory`

```elixir
@spec inventory([module()], Path.t()) :: %{
  required({module(), atom()}) =&gt; test_info()
}
```

Each test of `modules` by id: its file (relative to `root`), line, exclusion, and the
tags it has set (to anything but `false` or `nil`) besides those ExUnit sets on every
test, sorted: what the test lanes are told by (`Juggernaut.TestLanes`).

# `kept`

```elixir
@spec kept((-&gt; result)) :: result | {:error, %{stage: :boot, message: String.t()}}
when result: term()
```

Runs `fun` in a process that outlives the call (the keeper) and returns its result.
`:peer.call/4` runs `boot/1` in a process that exits once it returns, and under `mix
test` the test helper runs in the process that lives for the whole run: what a helper
owns (a named ETS table, a process linked to it) must outlive the boot, or the first
job finds it gone. A keeper that exits before answering is an error of the `:boot`
stage.

# `load_pending`

```elixir
@spec load_pending() :: :ok | {:error, String.t()}
```

Loads the test files the boot left for later (its `test_files` option), in the calling
process, as the `tests` and `ready` stages would have: required at once, their
`after_suite` callbacks dropped, their modules taken from ExUnit's queue, their tests
added to the inventory, and the snapshot and health fingerprint taken again, so the
next job is compared against the worker as it now is. `:ok` (also when nothing was
left), or `{:error, message}` when a file fails to load.

A boot-lane job loads only its first run's test files at boot and the others before
its next run (`Juggernaut.Runner.BootLane`), so a mutant its first tests kill never
waits for the whole suite to compile.

# `mark_switched`

```elixir
@spec mark_switched(Path.t() | nil) :: :ok
```

Marks, in the file `progress` (when given), that the boot-lane switch is about to go
on, so that the controller can tell a peer lost from then on (dead or hung) from one
lost before. A file that cannot be written is left unmarked: the loss then counts as
an infrastructure error, the conservative answer.

# `park`

```elixir
@spec park(opts()) ::
  {:ok, %{clocks: map()}} | {:error, %{stage: atom(), message: String.t()}}
```

Runs the `:project` stage in a new keeper (`kept/1`) and parks the peer there:
`{:ok, %{clocks: clocks}}`, or the stage's error. Nothing in it reads the switch or
touches the database, so the peer can wait beside a worker whose peer uses the same
partition. `resume/1` boots it the rest of the way.

# `peer_modules`

```elixir
@spec peer_modules() :: [module()]
```

The worker's own modules, loaded before Mix prunes the code paths (`boot/1`).

# `repo_databases`

```elixir
@spec repo_databases([module()]) :: [String.t()]
```

The `:database` each of `repos` is configured with (from the repo's `config/0`, as Ecto
repos have); a module that is not a repo, or a repo with no database, gives none.

# `resume`

```elixir
@spec resume(map()) :: {:ok, info()} | {:error, %{stage: atom(), message: String.t()}}
```

Boots a parked peer the rest of the way (`:setup`, `:start`, `:tests`, `:ready`) in its
keeper, with `overrides` merged over the options `park/1` was given (a boot-lane job's
`switch` and `progress`). The info's clocks hold every stage's, `:project` included.
A peer that was never parked, or a keeper that is gone, is an error of the `:boot`
stage.

# `retried`

```elixir
@spec retried(String.t(), non_neg_integer(), non_neg_integer(), (String.t(),
                                                           [String.t()] -&gt;
                                                             term())) ::
  :ok | {:error, String.t()}
```

Runs the Mix task `step` (`"name arg..."`) until it succeeds, at most `retries + 1`
times, waiting `backoff_ms` before the first retry and twice as long before each next.
The error names the number of attempts made and the last attempt's message.

# `setup_steps`

```elixir
@spec setup_steps(:test_alias | [String.t()], keyword()) :: [String.t()]
```

The setup steps: the given list, or for `:test_alias` the string steps of the
project's `test` alias that do not run `test` itself.

# `split_files`

```elixir
@spec split_files([Path.t()], [Path.t()] | nil) :: {[Path.t()], [Path.t()]}
```

The test files `all` split into those to load at boot and those left for later
(`load_pending/0`): all of them at boot when `only` is `nil`, else those of `all` that
are in `only` at boot and the others later.

# `stage_names`

```elixir
@spec stage_names() :: [atom()]
```

The names of the boot stages, in order, as a boot's clocks are keyed.

# `stages`

```elixir
@spec stages([{atom(), (map() -&gt; {:ok, map()} | {:error, String.t()})}], map()) ::
  {:ok, info()} | {:error, %{stage: atom(), message: String.t()}}
```

Runs `stages` in order over `acc`, each a function returning `{:ok, acc}` or
`{:error, message}`, recording each stage's clock in `acc.clocks`. The first error
stops the boot; a stage that raises, throws or exits is an error of that stage.

# `state`

```elixir
@spec state() :: map()
```

The state recorded at boot: the inventory, the snapshot and the fingerprint.

# `test_files`

```elixir
@spec test_files([Path.t()], [Regex.t() | (String.t() -&gt; boolean())] | nil) :: [
  Path.t()
]
```

The test files under `paths`: `.exs` files kept by `filters` (Mix's
`test_load_filters`: regexes or one-argument functions; default: ending in
`_test.exs`), sorted.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
