# `Alternera.PluginWasmFramework.Runtime.Port.Pool`
[🔗](https://github.com/10e-ab/alternera-wasm/blob/v0.9.1/alternera_plugin_wasm_framework/lib/alternera/plugin_wasm_framework/runtime/port/pool.ex#L1)

The node's `alternera_wasm_host serve` processes for `Runtime.Port`,
each an Erlang port running one call at a time.

## Checkout and checkin

`checkout/2` answers a free process within the caller's deadline and
makes the caller its port's owner (`Port.connect/2`): the caller then
reads and writes the port itself, so a call costs one pipe round trip
and no relay through this server. `checkin/1` hands the port back. A
caller that waits past its deadline withdraws; a port granted as it gave
up is checked straight back in. The port is linked to its owner, so an
owner killed in mid-call (a step's task the runner stopped) closes the
port, the OS process reads end of file and exits, and the pool starts
another.

A parked guest, one waiting on a `pipeline.call`, keeps its process:
`port_max` therefore bounds how many language steps are in flight on
the node, parked ones included, not only how many run. A nested call
made while its caller's holder is parked in a host call runs on that
holder's port (`held_port/0`), so one request holds one process
whatever its depth.

## Lending

The table holds a row per holder and port, `{{pid, port}, depth,
state}`: `depth` counts the calls stacked in the OS process (the
holder's own is 1, each borrow one more), `state` is `:busy` while the
call at that depth drives the port and `:lendable` while it is parked in
a host call (`lend/3`). `held_port/0` takes a lendable port by moving
its row one depth deeper and `:busy` in one ETS operation, so two
borrowers never share it, and a call up the chain whose guest is
running is never lent one: it checks out a process of its own. A
borrower's end (`give_back/3`) moves the row back a depth, and a driver
leaving its host call takes it back (`reclaim/4`) only at its own
depth: the host runs the calls as a stack, so a driver waits while a
borrower deeper still has the port, parked or not (an Async step's task
that outlives the host call that started it), until its deadline. A
holder's rows go with its port, so a holder killed mid-call leaves none.

## Size and lifecycle

The pool starts `port_min` processes when warmed (`warm/0`, by the
application when `Runtime.Port` is the runtime), grows on demand to
`port_max`, and closes idle processes past `port_min` after
`port_idle_ms`. A process is replaced after `port_max_calls` calls, and
when idle with more than `port_max_rss_mib` resident, so a slow leak in
the host or the engine cannot build up. A process that exits is
replaced. Starts that fail back off, doubling from 100 ms to 30 s;
after five in a row the runtime is unavailable, every waiting call and
every new one fails at once with the reason, and the pool keeps trying
one start at each backoff, warmed or not, until one succeeds. A
starter that crashes counts as a failed start.

Each process says hello (the protocol version must be
`Protocol.version/0`) and loads the shipped modules (`preload/1`) before
it serves.

The application env keys, with their defaults: `port_min` (the slot
limit, `Slots.limit/0`), `port_max` (four times `port_min`),
`port_idle_ms` (60,000), `port_max_calls` (100,000), `port_max_rss_mib`
(512).

## Telemetry

  * `[:alternera, :wasm_port, :pool]` every 10 s: `ports`,
    `busy`, `idle`, `waiting`, `rss_bytes` (the processes' resident
    memory together);
  * `[:alternera, :wasm_port, :start]`: `duration_ms` of a
    process's start, hello and preloads;
  * `[:alternera, :wasm_port, :exit]`: a process that exited
    unasked, with `reason` in the metadata.

# `lease`

```elixir
@type lease() :: %{port: port(), os_pid: pos_integer(), pool: pid()}
```

A checked-out process: its port and OS pid.

# `checkin`

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

Hands a checked-out process back.

# `checkout`

```elixir
@spec checkout(integer()) :: {:ok, lease()} | :busy | {:error, String.t()}
```

A process for the calling process, which becomes its port's owner,
waiting until `deadline` (monotonic ms). `:busy` when none came in time;
`{:error, reason}` when the runtime is unavailable.

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `drain`

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

Closes every process (a test's clean slate); the pool stays up.

# `give_back`

```elixir
@spec give_back(pid(), port(), pos_integer()) :: :ok
```

Ends a borrow at `depth`: the port goes back to the driver below it,
still parked in its host call, so lendable again.

# `held_port`

```elixir
@spec held_port() :: {:ok, pid(), port(), pos_integer()} | :none
```

A port to borrow for a nested call: that of the nearest holder up this
process's chain of callers (itself, then `$callers`) whose driver is
parked in a host call, taken (`:busy`, one depth deeper) so no other
caller borrows it meanwhile. Answers the holder, the port and the
borrow's depth; end it with `give_back/3`. `:none` when no holder up the
chain is parked, or when a borrow would stack more calls in its process
than the host holds instances for (`Binary.instances/0`; sibling Async
tasks, each parked in a host call, stack one deeper each): the call
checks out a process of its own.

# `hold`

```elixir
@spec hold(port()) :: :ok
```

Notes that the calling process holds `port` for a call, driving it.

# `lend`

```elixir
@spec lend(pid(), port(), pos_integer()) :: :ok
```

Says that the driver at `depth` of `holder`'s port is parked in a host
call: a call up the chain may borrow the port for the next depth.

# `preload`

```elixir
@spec preload(struct()) :: :ok
```

Says that `module` (`Runtime.Port`) is a shipped language's: every
process loads it as it starts and keeps it; one already running loads
it on its first call that needs it.

# `preloaded?`

```elixir
@spec preloaded?(binary()) :: boolean()
```

Whether `raw_digest` is a preloaded module's (a call loads it pinned).

# `probe`

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

Starts one host process in a process of its own, checks its hello (the
binary is there, runs, and speaks this node's protocol) and closes it:
`:ok`, or why not, in words that name the path. `Runtime.resolve/0`
asks before it chooses the port runtime, so a binary of an older
protocol is not found out only by every step failing.

# `reclaim`

```elixir
@spec reclaim(pid(), port(), pos_integer(), integer()) :: :ok | :closed | :timeout
```

Takes `holder`'s port back for the driver at `depth` leaving its host
call, waiting while a borrower deeper still has it, until `deadline`
(monotonic ms). Only that depth matches, so a borrower parked in a host
call of its own is never taken from. `:closed` when the port went
meanwhile, `:timeout` when a borrower kept it past the deadline.

# `stats`

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

The pool's counts, for a test or a look.

# `unhold`

```elixir
@spec unhold(port()) :: :ok
```

Notes that the calling process no longer holds `port`.

# `warm`

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

Starts `port_min` processes and keeps that many from now on.

---

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