wasm_tools_host behaviour (wasm_tools v0.1.0)

View Source

Host interfaces: the functions your application gives a component.

A component may import an interface of its own, such as example:app/kv, and expect the application to implement it. You give one handler per interface when you load the component:

{ok, App} = wasm_tools:load({file, "app.wasm"},
                            #{host => #{<<"example:app/kv">> => my_kv_host}}).

A handler is a module with this behaviour, or a fun of the same arity:

-module(my_kv_host).
-behaviour(wasm_tools_host).
-export([handle/3]).

handle(<<"get">>, [Key], #{context := #{tenant := T}}) -> my_store:get(T, Key);
handle(<<"put">>, [Key, Value], #{context := #{tenant := T}}) -> my_store:put(T, Key, Value).
  • Func is the function's WIT name, a binary; nothing a guest names becomes an atom. Args are native values, in parameter order, and the return value is the native value of the function's result (erlang_wasm checks it, and a value that does not fit its type traps the call).
  • The types come from the component's own import declaration: you write no descriptor.
  • Ctx holds context, the context option of the call, tool, the tool called, interface, and deadline, the call's deadline in erlang:monotonic_time(millisecond), or infinity.
  • A handler runs in the call's runner process, so it stops with the call. Work it hands to other processes is its own to stop.
  • An exception in a handler traps the call (#{class := trap, kind := host_error}).
  • An interface is named as the component imports it, with or without its version. Only the interfaces you name are given; a component that imports another one does not load.

Summary

Types

handler()

-type handler() :: module() | fun((binary(), [term()], map()) -> term()).

host()

-type host() :: #{binary() => handler()}.

Callbacks

handle(Func, Args, Ctx)

-callback handle(Func :: binary(), Args :: [term()], Ctx :: map()) -> term().