# `Alternera.PluginHosts.Pool`
[🔗](https://github.com/10e-ab/alternera-camel/blob/v0.9.0/alternera_plugin_hosts/lib/alternera/plugin_hosts/pool.ex#L1)

One plugin host served by several processes: `PluginHosts.Host` members,
each with its own OS process started from the same spec. Calls spread
over them, a crash takes down only the calls in flight on one member, and
`rolling_restart/2` replaces them one at a time while the others serve.

The pool is a supervisor of a `DynamicSupervisor`, which runs the
members, and a `Pool.Manager`, which decides how many run: `:min` at
boot, never more than `:max`, each in a slot (`Pool.Manager`), starts
one more when every ready member has `:grow_at` calls in flight, and
stops a member beyond `:min` that has been idle for `:idle_ms`. Should
the manager stop, the pool restarts everything (`:one_for_all`), since
only the manager knows the slots.

## Picking a member

A member is in the pool's registry (duplicate keys, `{:pool, name}`) only
while it is ready, and keeps its number of calls in flight in a
`:counters` array shared by the pool. `call/4` reads both, with no message
to any member: of two ready members picked at random it takes the one
with fewer calls in flight ("power of two choices"), which spreads load
nearly as well as asking every member and costs two counter reads.

## Failing over

A call that a member refused before sending it (`Host.not_sent?/1`:
starting, restarting, busy, unavailable, gone) goes to another ready
member, each member tried at most once, within the call's deadline. A
call that was sent and then lost (`:host_down`, `:timeout`) is never
repeated: its operation may have had effects. With no ready member the
call fails with `:no_ready_host`.

## Starting on demand

A call, a `checkout/2` or a `ready_member/2` that finds no ready member
at all waits for one within its deadline (`Pool.Manager.await_ready/2`),
which starts a member when none is running: so a pool of `min: 0` runs
nothing until it is called. It waits only while a member starts (or
drains for a restart, or is being retired idle) or none runs; members
all down between crashes or
`:unavailable` answer at once, so a host in an outage fails fast. The
wait ends at the deadline, or when every member has become
`:unavailable`; the call then fails with `:no_ready_host`, never sent. A
call whose ready members all refused it because they were stopping (a
member retired idle, or draining for a restart, between the caller's
lookup and its call) waits again, as if it had found none, at most twice
within its deadline; one whose members refused it for another reason
(busy, unavailable) fails at once.

## Definitions

A call with `:definition` (`PluginHosts.Definition`) names its hash. A
member that answers `unknown_definition` is sent the document
(`Host.define/3`) and called again, once, within the same deadline; a
document the member refuses is that refusal.

# `call`

```elixir
@spec call(term(), String.t(), term(), keyword()) :: {:ok, map()} | {:error, term()}
```

Calls `op` on a ready member of pool `name` (see `Host.call/4`; options
`:deadline_ms`, `:registry` and `:definition`, a `PluginHosts.Definition`
the operation is in). Returns what the member returned, or `{:error,
:no_ready_host}`. With no ready member it waits for one to start
(see "Starting on demand"), within the deadline.

# `catalogue`

The last catalogue a member of the pool had, or nil before any was
ready (`Pool.Manager.catalogue/1`): what the pool serves, without
starting a member.

# `certs`

```elixir
@spec certs(String.t(), keyword()) :: [binary()]
```

The certificates of host `name`'s ready TLS members, as DER.

# `checkin`

```elixir
@spec checkin(map()) :: :ok
```

Ends a call over HTTP that `checkout/2` began.

# `checkout`

```elixir
@spec checkout(term(), keyword()) :: {:ok, map()} | {:error, :no_ready_host}
```

A ready member of pool `name` that serves calls over HTTP, picked as
`call/4` picks one and counting the caller's call until `checkin/1`:
`{:ok, %{pid, ref, port, protocols, token, cert, left_ms}}` (`left_ms`
what is left of the deadline after any wait), or `{:error,
:no_ready_host}` (no ready member has an HTTP endpoint). A member that
stopped being ready since its registration is passed over. With no
ready member it waits for one to start (see "Starting on demand").
Options: `:registry`, `:deadline_ms` (how long it may wait, default
5000).

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `listening?`

```elixir
@spec listening?(term(), :inet.port_number(), keyword()) :: boolean()
```

Whether a ready member of pool `name` listens on `port` over HTTP.
Option: `:registry`.

# `members`

The running members' pids, by slot.

# `ready_member`

```elixir
@spec ready_member(term(), keyword()) ::
  {:ok, pid(), pos_integer()} | {:error, :not_ready | :host_unavailable}
```

A ready member of pool `name`, picked as `call/4` picks one, waiting for
one to start when none is ready (see "Starting on demand"), and what is
left of the deadline: `{:ok, pid, left_ms}`, or `{:error, :not_ready}`
(none in time, or the deadline spent) or `{:error, :host_unavailable}`
(none could start). Options: `:registry`, `:deadline_ms` (default 5000).

# `reload`

```elixir
@spec reload(Supervisor.supervisor()) :: {:ok, [map()]} | {:error, term()}
```

Has every member read its operations again in place (`Host.reload/1`),
one at a time: `{:ok, catalogue}`, the last member's, or the first
member's error, the members after it left as they were. With none
running it starts none, and answers the last catalogue (`catalogue/1`;
`[]` before any member was ready): the next member reads the files as
it starts.

# `rolling_restart`

Restarts the members one at a time, each drained first, waiting for each
to be ready again (with a new OS process) before the next. The others
serve meanwhile. A member that is not ready (starting, waiting to
start again, draining) is passed over: its next process starts anew. A lone member would leave none to serve, so when `max`
allows the pool first starts one more (`Pool.Manager.add/1`), waits for
it to be ready, and stops it (`Host.retire/1`) once the restart is done.
Option: `:timeout_ms` per member (default 120000).

# `start_link`

Starts a pool. Options: `:name` (the pool's name: the key calls use, any
term), `:label` (what logs and member names call it, default `:name`
when that is a string, else its `inspect`),
`:min` (members started at boot, default 1; 0 starts none) and `:max`
(most members, default 4; an `ArgumentError` unless `0 <= min <= max`
and `max >= 1`), `:spec` (`t:Host.spec/0`; each member's log file gets its
slot, `host.log` → `host-1.log`), `:registry` (a registry
with duplicate keys, default `Alternera.PluginHosts.PoolRegistry`), `:supervisor_name`,
`:scope` (the `:pg` scope the manager announces the host and its
outages in and each ready member joins, `PluginHosts.Cluster`; none by
default), `:idle_ms` (how long a member beyond `:min` may go without a
call before it is stopped, default 600000), `:grow_at` (the calls in
flight on every ready member at which one more starts, default 8) and
the `Host` tunables, passed to every member.

# `status`

Every running member's `Host.status/1`, by slot; none for a pool that runs none.

# `summary`

The pool as a whole: `%{running, min, max, idle_ms, grow_at, waiting,
catalogue, members}` (`Pool.Manager.summary/1`), each
member its `Host.status/1` with its `slot` and `idle_ms`, the time since
its last call started or ended.

# `take_waited_us`

```elixir
@spec take_waited_us() :: non_neg_integer()
```

The microseconds this process spent waiting for a pool's member to be
ready since the last take, 0 when it did not wait, and starts again. A
step reads it to leave the wait out of the time the host worked
(`PluginHosts.Step`): waiting for a member to start is no work of the
host's.

---

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