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

One plugin host: an OS process (a JVM running Camel, say) the proxy starts
through a port and talks to in `PluginHosts.Frame`s on file
descriptors 3 and 4 (`:nouse_stdio`). This process is the only owner of
the port, and nothing the host does can reach further than it: a crash,
a hang or bytes that are not a frame end the OS process, never the BEAM.

## Lifecycle

The process is started through `/bin/sh -c 'exec …'` so its stdout and
stderr go to the log file (`:log_path`) while the OS pid stays the
host's. The Host sends `hello`; the host answers with its protocol
version and its catalogue of operations, and the Host is `:ready`.
An answer that does not come within `:boot_timeout_ms` counts as a
failed start.

A spec with `:variables` (an `{m, f, a}` answering `{:ok, values}` or
`{:error, reasons}`, `PluginHosts.variable_values/2`) is read before
every start, and the values go to the process in a `variables` frame
ahead of the hello, never in its environment or arguments: the
tenant variables the host's own routes read. A value that does not
resolve is logged and counts as a failed start, so the backoff below
tries again and defining the variable brings the host up. `status/1`
says what the values were as `:variables`, a fingerprint
(`fingerprint/1`), so the pool can tell a member that started with
older values (`PluginHosts.Refresher`).

While ready, the Host pings every `:ping_interval_ms`. A pong is answered
by the host's reader, so a host that misses one by `:ping_timeout_ms` is
stuck, and is killed. Whenever the process ends (it exited, it was
killed, it sent something that is not a frame), every call in flight
fails with `:host_down` and the process is started again after a
backoff that doubles from `:backoff_min_ms` to `:backoff_max_ms`. After
`:max_failures` failures in a row the Host is `:unavailable`: calls fail
at once, and it keeps retrying at the longest backoff. A host that has
been ready for `:stable_after_ms` has its failure count cleared.

If the BEAM itself dies, the pipes close and the host exits at end of
file on fd 3; that rule is the host's (see the Camel package's `plugin_host`).

## Calls

`call/4` encodes in the caller's process, and the caller decodes the
reply: this process only writes frames and routes replies by id, so it
does no per-call work that grows with the payload. Calls run
concurrently up to `:max_in_flight`; past it a call fails with
`:host_busy` at once. Each call has a deadline: when it passes, the
caller gets `:timeout` and the host a `cancel`. A caller that dies
(a step's task killed at its time left) is noticed by a monitor and its
call is cancelled.

The errors say whether the call reached the host. `:host_starting`,
`:host_restarting`, `:host_unavailable`, `:host_busy` and `:host_gone`
mean it was never sent (`not_sent?/1`), so trying another host is safe.
`:host_down` and `:timeout` mean it was sent and its outcome is unknown:
a call with effects may have had them.

## Definitions

`define/3` sends a written document (`PluginHosts.Definition`) in a
`define` frame, on the frame channel whatever the call protocol; the host
answers with a `reply` of the same id, as for a call, so a define has the
call's deadline, limits and errors. A call that names a definition this
member does not hold fails `{:op_failed, "unknown_definition", …}`, and
`PluginHosts.Pool` and `PluginHosts.HttpCall` define it and call again.

## Reload

`reload/2` asks the host to read its operations again in place (a Camel
host its route files) with a `reload` frame; the host answers with a
`catalogue` frame of the same id, the operations it now serves or why it
kept the old ones, and the Host keeps the new catalogue. A host may also
send a `catalogue` of id 0 on its own (a Camel host watching its route
files), which the Host takes the same way. A host that does not answer a
reload within `:reload_timeout_ms` fails it with `:timeout`, and is left
running: a host that does not know the frame ignores it.

## Message sources

`source/3` sends a call to one of the host's message sources (a `source`
frame, answered as a call is). A source that pushes sends its messages
in `messages` frames of id 0 naming a sink; `subscribe/3` names the
process that gets them, as `{:plugin_host_messages, sink, payload}` (the
frame's JSON, decoded), monitored and dropped when it ends. A frame for a
sink nobody holds is dropped: the host takes its messages back when their
hold lapses. When the host's process ends, every sink gets `%{"closed" =>
"host_down"}` and is dropped, since what it was sent went back with the
process.

## Restart and pools

`restart/1` drains: the Host takes no new calls (`:host_restarting`),
waits for the calls in flight up to `:drain_timeout_ms`, closes the
channel and starts a new process. A planned restart is not a failure.

A Host in an `PluginHosts.Pool` gets `:pool`, `%{registry, key,
index, counters, last_use, manager, grow_at}`: while ready it is registered under `key` in the
pool's registry, and it keeps its number of calls in flight in
`counters` at `index`, so the pool picks a member with two ETS and
counter reads and no message to any Host. With `last_use` (an
`:atomics`) it also writes the time of its last activity, a call
starting or ending, and the moment it became ready, at `index`: the
pool stops a member idle too long. With `manager` (a pid) it sends it
`{:member, index, self(), event}` when it becomes ready (`{:ready,
catalogue}`), when it becomes `:unavailable` and when a reload changes
its catalogue (`{:catalogue, ops}`): the pool answers callers waiting
for a member to start (`Pool.Manager.await_ready/2`). With `grow_at`
too it sends `:busy` when its calls in flight reach `grow_at`, then not
again until they have dropped to half of it: the pool may start one more
member.

## The HTTP call channel

A host whose `protocol` is HTTP or HTTPS (`PluginHosts`, the value in
`ALTERNERA_HOST_PROTOCOL`) serves calls on a loopback port of its own.
Every start hands the process a new random token in
`ALTERNERA_HOST_TOKEN`, which the host requires on every request, and,
over HTTPS, a new certificate for its name with the key
(`ALTERNERA_HOST_CERT`, `ALTERNERA_HOST_KEY`); its hello then carries
`"http": {"port", "protocols"}`. While ready, the Host registers that
endpoint with the token and the certificate beside its
counters (`{index, counters, endpoint}`), and `PluginHosts.Endpoint`
answers the dial of a call addressed to it. Calls over HTTP do not pass
through this process: the frame channel stays the lifecycle (hello,
ping, drain, end of file on fd 3). A caller reports each one
(`begin_http/1`, `end_http/2`) and is monitored for as long, so a call
over HTTP counts as in flight like a framed one, a drain waits for it, and
a caller killed mid-call does not stay counted.

# `error`

```elixir
@type error() ::
  :host_starting
  | :host_restarting
  | :host_down
  | :host_gone
  | :host_unavailable
  | :host_busy
  | :timeout
  | :too_large
  | :invalid_input
  | :invalid_reply
  | {:op_failed, String.t(), String.t(), map()}
  | {:reload_failed, String.t()}
```

# `spec`

```elixir
@type spec() :: %{
  :executable =&gt; String.t(),
  :args =&gt; [String.t()],
  :log_path =&gt; String.t(),
  optional(:cd) =&gt; String.t(),
  optional(:env) =&gt; [{String.t(), String.t()}],
  optional(:variables) =&gt; {module(), atom(), [term()]}
}
```

How to start the host: the executable and its arguments, the working
directory, extra environment and the file its stdout and stderr go to.

# `begin_http`

```elixir
@spec begin_http(GenServer.server()) :: {:ok, reference()} | {:error, error()}
```

Counts a call over HTTP as in flight on this member until `end_http/2`
or the caller's death. `{:ok, ref}`, or `{:error, t:error/0}` for a
member that is not ready (so it may be draining) or is gone.

# `call`

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

Calls operation `op` with `input` (JSON-ready). Returns `{:ok, values}`,
the reply's `values` map, or `{:error, t:error/0}`; an error the
operation answered is `{:op_failed, type, message, details}`, `details`
the rest of the reply's error object (a Camel host's `status`,
`on_purpose`, `exception`, `at` and `trace`). Options:
`:deadline_ms` (default 5000) and `:extras`, more keys of the call frame
beside `input` (a Camel step's `"headers"` and `"properties"`), none by
default.

# `check`

```elixir
@spec check(GenServer.server(), map(), keyword()) :: {:ok, map()} | {:error, error()}
```

Has the host check a written document without defining it (a `check`
frame, `%{"tenant", "text", "values", "entry"}`): `{:ok, %{"routes",
"inputs", "diagnostics"}}`, each diagnostic `%{"severity", "message"}`
with `"line"` and `"column"` when known, or `{:error, t:error/0}`.
Options as `define/3`.

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `define`

```elixir
@spec define(GenServer.server(), map(), keyword()) :: {:ok, map()} | {:error, error()}
```

Sends a written document to the host (`PluginHosts.Definition.frame/1`):
`{:ok, %{"routes" => names, "inputs" => …}}`, or `{:error, t:error/0}`, a
refusal as `{:op_failed, "invalid_definition", message, details}` (with
`"line"` and `"column"` when the host knows where). Options:
`:deadline_ms` (default 5000) and `:codec`.

# `describe`

```elixir
@spec describe(GenServer.server(), map(), keyword()) ::
  {:ok, map()} | {:error, error()}
```

Asks the host about a database a written route may use (a `describe`
frame: `%{"bean"}`, with `"table"` or `"procedure"` as `%{"schema",
"name"}`): `{:ok, %{"body" => answer}}` (the Camel host's
`WrittenDatabases`), or `{:error, t:error/0}`. The host keeps its
answers for a while; this keeps none. Options as `define/3`.

# `end_http`

```elixir
@spec end_http(GenServer.server(), reference()) :: :ok
```

Ends a call `begin_http/1` counted.

# `fingerprint`

```elixir
@spec fingerprint(map() | nil) :: binary() | nil
```

A fingerprint of a member's variable values (`status/1`'s `:variables`),
to compare with what they read now; nil for none. Salted per node, so
it says nothing of the values anywhere else.

# `not_sent?`

```elixir
@spec not_sent?(term()) :: boolean()
```

Whether `reason` says the call never reached the host, so another may take it.

# `reload`

```elixir
@spec reload(GenServer.server()) :: {:ok, [map()]} | {:error, error()}
```

Has the host read its operations again in place (see the moduledoc):
`{:ok, catalogue}`, or `{:error, reason}`, `{:reload_failed, message}`
when the host kept its old operations, `:timeout`, or the error of a
Host that is not ready.

# `restart`

Drains the host and starts a new process (see the moduledoc). Returns at
once; `status/1` shows `:draining`, then `:starting`, then `:ready`.

# `retire`

```elixir
@spec retire(GenServer.server()) :: :ok
```

Drains the host as `restart/1` does, then stops the Host, `:normal`,
its OS process with it. Returns at once. A Host that is not ready has
nothing to drain and stops now.

# `retry_now`

```elixir
@spec retry_now(GenServer.server()) :: :ok
```

Starts the process now if it is waiting to start again after a failure
(`:down`, `:unavailable`) rather than at the end of its backoff: what a
start failed on (a tenant variable) may be fixed. Ignored in any other
state.

# `source`

```elixir
@spec source(GenServer.server(), map(), keyword()) :: {:ok, map()} | {:error, error()}
```

A call to one of the host's message sources (a `source` frame:
`%{"source", "verb", …}`): `{:ok, values}` or `{:error, t:error/0}`, a
refusal as `{:op_failed, type, message, details}`. Options as `define/3`.

# `start_link`

Starts a Host. Options: `:name` (the host's name, for logs and the
registry), `:spec` (`t:spec/0`), `:server` (a GenServer name) and the
tunables listed in the moduledoc.

# `status`

The Host's state for status pages and tests.

# `subscribe`

```elixir
@spec subscribe(GenServer.server(), String.t(), pid()) :: :ok | {:error, :host_gone}
```

Sends the `messages` frames that name `sink` to `pid` (see "Message
sources"), until `unsubscribe/2`, `pid`'s end or the host process's end.
`{:error, :host_gone}` when the Host is not there.

# `unsubscribe`

```elixir
@spec unsubscribe(GenServer.server(), String.t()) :: :ok
```

Stops sending `sink`'s messages.

# `vocabulary`

```elixir
@spec vocabulary(GenServer.server(), keyword()) :: {:ok, map()} | {:error, error()}
```

Asks the host what the editor completes in a written document (a
`vocabulary` frame, an empty object): `{:ok, map}` (the Camel host's
`WrittenVocabulary`), or `{:error, t:error/0}`. Options as `define/3`.

The host's rules and components do not change while its process runs,
so the first answer with a body is kept for the process's generation
and given again without a frame; a new process asks anew.

---

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