Lifecycle

View Source

This page says who owns a component, a registry and a call, and what stops when something goes away. Read it when you embed wasm_tools in an application that loads, replaces or exposes components while it runs.

A component belongs to the process that loaded it

load/2 returns a value you can pass to any process. Its compiled code is kept by a small holder process, which belongs to the process that loaded it, as an ETS table does:

  • unload/1 stops the holder;
  • the loading process exiting stops it too;
  • owner => Pid at load gives it to another process.

After that, a call answers #{class := link, kind := unloaded}. Calls already running finish: each has its own instance.

{ok, _} = application:ensure_all_started(wasm_tools),
{ok, Calc} = wasm_tools:load({file, "test/fixtures/component/calculator.component.wasm"}),
ok = wasm_tools:unload(Calc),
wasm_tools:call(Calc, <<"add">>, #{<<"a">> => 1, <<"b">> => 2}).
%% => {error, #{class := link, kind := unloaded}}

Load components when your application starts and keep them: erlang_wasm loads at most 50 modules a second on a node, and a load past that answers #{class := overloaded, kind := load_rate_exceeded}.

A registry keeps its own copy

wasm_tools:add/3 gives the registry a holder of its own, owned by the registry process. The process that loaded the component can unload it; the registry's tools keep working until they are removed or the registry stops.

A call runs in two processes of its own

caller ──> watchdog ──> runner
  • The runner makes a fresh instance, calls the function, destroys the instance and answers the caller.
  • The watchdog starts the runner and is the only process that kills it: at the deadline, on cancel/1, when the caller exits, or when the registry stops. It tells the caller why.
  • The caller is never linked to either: a runner that dies is an error value, never an exit signal for the caller.
  • The runner traps exits, so a process linked to it (an HTTP connection the server closed, say) cannot end the call.
whenthe call
it returnsanswers {ok, Value} or {error, Error}
its deadline passesis killed; {error, #{class := timeout}}
cancel/1is killed; cancel/1 returns once it is gone
its caller exitsis killed
its heap passes max_heap_wordsis killed; {error, #{class := exhaustion, kind := heap_limit}}
its registry stopsis killed; {error, #{class := cancelled, kind := registry_down}}
its tool is removedfinishes, unless removed with kill => true

Replacing a component

To move a registry to a new version of a component, add the new one under new names (or another namespace), switch your callers, then remove the old names. Calls running on the old version finish on it.

Shutdown

Put registries in your supervision tree (wasm_tools:child_spec/1). When your application stops, each registry stops its calls, releases its components, and barrel_mcp drops the MCP tools the registry owned.