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

The WebAssembly runtime a language step runs its module on, as a
behaviour, so the binding underneath can be replaced without touching
anything above it. Nothing outside an implementation names the binding,
its engine, epochs or fuel: callers speak in `t:limits/0` and
`t:host/0`.

`prepare/1` compiles a module once (`PluginWasmFramework.Modules` keeps
the result per node). `call/5` runs one export of it in a **fresh store
and instance**, never reused, with the call's limits; the instance is
gone when it returns. The implementation is configured under `:runtime`:

    config :alternera_plugin_wasm_framework, runtime: :port   # or :wasmex

`Runtime.Port`, guests in OS processes of the package's own host
program, is the default; `Runtime.Wasmex` (wasmex, a NIF in the node)
is the other. Both answer the same results for the same module and
input. The package's application settles which one when it starts
(`resolve/0`).

## A call

`input` is written into the guest through its `alternera_alloc` export
and the export is called with its pointer and length; the export answers
`(ptr << 32) | len` of its reply, which is read back. Host calls the
guest makes on the way (`alternera.host_call`, `alternera.body_read`;
`c_src/alternera_guest.h`) are served by `host` **in the process that
called `call/5`**, so a host function may use what lives there (a
`pipeline.call` runs the pipeline in the request's process).

The result is one of:

  * `{:ok, reply}`: the export's reply bytes;
  * `{:error, {:trap, message}}`: the guest trapped (a fault, an
    unreachable, a host call that failed at the runtime's level);
  * `:timeout`: the call ran past `timeout_ms` and was interrupted;
  * `:memory_limit`: the guest could not even start or take its input
    within `memory_bytes`;
  * `{:error, {:claim_refused, kind, message}}`: the call asked to have
    its guest's growth claimed (`claim: true` in its limits) and the
    application's held-bytes budget refused a claim
    (`Plugin.Host.claim_held_bytes/2`; `kind` is `:busy` or `:size`).
    Only a runtime that sees the guest grow claims (`Runtime.Port`).

A refusal inside the call (the guest's allocator got no memory) is not
a runtime result: the guest reports it in its reply frame
(`PluginWasmFramework.Frame`). A guest whose language aborts on a
refused allocation (Rust's does) traps instead; when it exports
`alternera_allocation_refused` and that answers 1 after the trap, the
result is `:memory_limit`. Beside the result comes what the call
used (`t:stats/0`): the guest's memory at the end of the call, which is
its peak, since WebAssembly memory only grows.

# `host`

```elixir
@type host() :: %{
  state: term(),
  call: (String.t(), binary(), term() -&gt;
           {{:ok, iodata()} | {:error, String.t(), String.t()}, term()}),
  body: (:request | :response, non_neg_integer(), non_neg_integer(), term() -&gt;
           {binary() | :none, term()})
}
```

What serves the guest's host calls, in the calling process, threading
`state` from one host call to the next:

  * `call`: `(op, arg, state) -> {{:ok, answer} | {:error, type,
    message}, state}`, for `alternera.host_call`; `answer` is the
    operation's JSON text;
  * `body`: `(which, offset, len, state) -> {binary | :none, state}`, for
    `alternera.body_read`; `which` is `:request` or `:response`, and
    `:none` says the step holds no such body.

`call/5` answers the last state beside its result.

# `limits`

```elixir
@type limits() :: %{
  :timeout_ms =&gt; pos_integer(),
  :memory_bytes =&gt; pos_integer(),
  optional(:tenant) =&gt; term(),
  optional(:claim) =&gt; boolean()
}
```

What one call may use: wall-clock milliseconds and bytes of guest
memory, optionally the `tenant` the call runs for, which the node's
limit on guests running at once shares its slots between
(`PluginWasmFramework.Slots`; a call with none counts under `nil`), and
`claim`: whether the guest's memory past a free floor is claimed against
the application's held-bytes budget as it grows (default false).

# `result`

```elixir
@type result() ::
  {:ok, binary()}
  | {:error, {:trap, String.t()}}
  | {:error, {:claim_refused, :busy | :size, String.t()}}
  | :timeout
  | :memory_limit
```

# `stats`

```elixir
@type stats() :: %{
  :memory_bytes =&gt; non_neg_integer(),
  optional(:guest_us) =&gt; non_neg_integer()
}
```

What a call used: `memory_bytes`, the guest's memory at its end (its
peak), and optionally `guest_us`, the wall-clock microseconds the guest
itself ran, outside the BEAM's schedulers: not waiting for a slot, nor
while the calling process served one of its host calls. A runtime that
does not say is taken to have run the guest for the whole call less its
host calls (`PluginWasmFramework.Language`).

# `call`

```elixir
@callback call(
  prepared :: term(),
  export :: String.t(),
  input :: iodata(),
  limits(),
  host()
) ::
  {result(), stats(), host_state :: term()}
```

Runs `export` of a prepared module on `input` in a fresh instance.

# `discard`
*optional* 

```elixir
@callback discard(prepared :: term()) :: :ok
```

Says that `prepared` will not be called again, so what it holds can go.

# `max_running`

```elixir
@callback max_running() :: pos_integer()
```

How many guests may run at once on this node (`Slots`).

# `preload`
*optional* 

```elixir
@callback preload(prepared :: term()) :: :ok
```

Says that `prepared` is a shipped language's module, wanted by every
call of its plugin: a runtime may keep it ready (`Runtime.Port` loads it
into each of its processes as they start).

# `prepare`

```elixir
@callback prepare(wasm :: binary()) :: {:ok, term()} | {:error, String.t()}
```

Compiles `wasm` once, for any number of calls.

# `impl`

```elixir
@spec impl() :: module()
```

The configured implementation: the application env's `:runtime`, a
module or one of its short names, `:port` (the default) or `:wasmex`,
which the proxy's configuration and the load harness use, so they name
no module of this package. Read on every call: a change takes effect at
the next call, each runtime keeping its own compiled modules. The
package's application sets it when it starts (`resolve/0`), so the
default here is only what a caller sees before that.

# `no_host`

```elixir
@spec no_host() :: host()
```

A host that serves nothing: every host call fails and no body is held.

# `resolve`

```elixir
@spec resolve() :: module()
```

Settles the runtime once, as the package's application starts, before
anything sizes itself by it (`Slots`, the port pool), and puts it in
the application env's `:runtime`:

  1. the `:runtime` the application env already names, the
     configuration's choice;
  2. else the `ALTERNERA_WASM_RUNTIME` environment variable, `port` or
     `wasmex`;
  3. else the port runtime when its host program starts and speaks this
     node's protocol (`Runtime.Port.Pool.probe/0`), and wasmex when it
     does not, with a warning that says why and where the program was
     looked for.

A runtime that was asked for, by the env or the variable, is never
swapped: the port runtime asked for without a host program that serves
raises, and so does a `:runtime` that names neither short name nor a
module implementing this behaviour, and the node does not start,
rather than failing every step. The choice is logged once.

What it chose by default (3) is remembered as such (`:resolved_runtime`),
so a later call, as the application starts again in the same VM, settles
afresh rather than taking its own earlier choice for the configuration's.

---

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