wasm_component (wasm v0.16.0)

View Source

Decode and run a WebAssembly component: the Component Model's entry point. docs/components.md is the guide; this is the reference.

A component binary shares the core preamble magic but a different version/layer (00 61 73 6d 0d 00 01 00, layer 1) where a core module is layer 0 (... 01 00 00 00). decode/1 walks the top-level sections, extracts the embedded core modules (section id 1) and the exported names (section id 11). instantiate/1 loads and instantiates that core module through the existing runtime, providing the resource intrinsics its imports declare; call/4 lowers Erlang terms into the guest, calls the export, lifts the result and runs the post-return.

Resources. A component that exports a resource imports the resource built-ins [resource-new]/[resource-rep]/[resource-drop] from its own canon, and the host provides them: they are the instance's handle table (wasm_resources). A handle is a small index the table mints, not the guest's representation. call/4 checks and translates handles by the export's real signature, read from the component's type space: an own result passes to the host, a borrow argument is lent and the guest gets the representation, an own argument passes back to the guest. drop_resource/3 checks a host-held handle and runs the guest destructor with its representation.

A component whose entry core imports only WASI (every program we build) stays on this single-core path. When the entry core imports from another core, wasm_component_link reads the core-instance graph and wires those imports from the other cores' exports; instantiate/3 keeps every built core in cores so destroy/1 frees them all.

A component with no top-level core, such as one wac composed from nested components, is instantiated component by component and its exports dispatched to the one that provides each. call_async/4 drives an async func export through wasm_async.

ToUse
decode a binarydecode/1
decode and check once, for many instantiationsprepare/1, and source/1 for the bytes it was made from
keep the core modules loaded while instances come and gohold/1
instantiate, with host imports and optionsinstantiate/1, instantiate/2, instantiate/3
list the exportsexports/1
describe every export and import with its types, without running itdescribe/1
read the custom sections, such as producerscustom_sections/1
call an export, sync or asynccall/4, call_async/4, call_async/5
check arguments against a signature, as a call does firstcheck/2
return when an async export resolves, and run what it leftstart_async/4, start_async/5, pump/2
drop a resource the host holdsdrop_resource/3
free the instancedestroy/1, destroy/2
capture an initialised instance, and start a new one from itsnapshot/2, restore/3
keep an image alive past the process that captured itacquire/1, release/1
write a host importimport_fun/2
keep host-side state behind a handlehost_new/2, host_get/1, host_update/2, host_drop/1
a host entry an image can keep, because it says where it came fromhost_new/3
the live host handles, for tests and teardown checkshost_live/0

The wiring of several cores is wasm_component_link; lifting and lowering values is wasm_canon; the handle tables are wasm_resources.

Where things are

The banners divide the file in this order.

bannerwhat is there
%%% holding coreshold/1
%%% decodedecode/1: the section walk, the core modules and the export names
%%% prepareprepare/1, source/1, and derive/3, what instantiation reads from the bytes alone
%%% describedescribe/1, and composed_exports/1 for a composed component; custom_sections/1
%%% instantiateinstantiate/3; instantiate_valid/4 picks the single-core path or link_in/3, which hands linked cores to wasm_component_link
%%% compositiona component with no top-level core: instantiate_composed/3 folds compose_step/2 over its graph
%%% bridges between componentsone nested component calling another, sync (bridge/3) or async (bridge_async/3), and how a handle crosses (to_provider/3, from_provider/4)
%%% drops and the entry coredrop_fun/1, which reads resource_closer and resource_predrop; start/6, which builds the single core
%%% snapshotssnapshot/2, acquire/1, release/1, restore/3
%%% destroy and callsdestroy/1, destroy/2, exports/1, call/4, check/2
%%% host boundarychecking and translating handles on a call: handle_sig/4, lower_handles/3, lift_handles/3, with_loans/2
%%% async callscall_async/5, start_async/5, pump/2, and the callback loop, drive/5
%%% host imports and dropsimport_fun/2, drop_resource/3
%%% import resolutionresolve_imports/3, and host_key/1, which strips an interface version
%%% resource tablethe resource built-ins a single core imports, bound to wasm_resources by resource_imports/2
%%% host resource tablehost_new/2, host_new/3, host_get/1, host_update/2, host_drop/1, host_live/0
%%% helpersrun_post_return/3

Summary

Functions

Keep a component image alive past the process that captured it, as wasm:acquire/1 does for a core image.

Call a lifted export, lowering Args and lifting the result by Sig.

Call an async-lifted export, lowering Args and lifting the result by Sig.

Check Args against the parameters of Sig as call/4 checks them before it lowers anything: ok, or the error call/4 would answer, with class invalid and kind bad_argument. No component is needed, so you can check a request before you spawn or queue the call that will make it.

The component's top-level custom sections, in the order of the binary, as {Name, Payload}, with each payload as the bytes hold it. Nothing is instantiated and no section is interpreted.

Decode a component binary into its embedded core module and export names.

What a component exports and imports, with the type of every function, read from the binary without instantiating it and without running guest code.

Destroy a component instance, freeing every core it built and sweeping the host resource tables. A resource may own an OS handle (a file descriptor, a socket) that GC does not reclaim, so destroy/2 takes a closer the host layer supplies to close each one; destroy/1 closes nothing, for pure components with no OS state.

As destroy/1, closing each live host resource with Closer first.

Drop a resource handle the host holds, running the resource's destructor.

The export names a decoded component instance offers.

Keep a component's core modules loaded while the calling process lives.

Drop a host handle. A miss (double drop, unknown handle) is a no-op.

The tag and state behind a host handle, or error if it is not live.

The live host handles in this process, for tests and teardown checks.

Mint a fresh host-owned resource handle carrying State, tagged Tag.

As host_new/2, saying where the entry came from: an origin the host can make the entry again from, for another instance, as a restore does. WASI's stdio streams and preopened directories have one; nothing else does.

Replace the state behind a live host handle, keeping its tag.

Wrap a typed host function as an import, handling the Canonical ABI both ways.

Decode and instantiate a component, wiring any resource intrinsics.

Instantiate a component, providing host functions for the interfaces it imports.

As instantiate/2, passing Limits (memory and fuel bounds) to the inner core instance, so a component honours the same limits a core module does. This is what the worker uses per request.

Decode, check and parse component Bin once, for many instantiations.

Run the tasks still pending in the instance (from start_async/5) until all have finished, none can progress, or Timeout milliseconds pass: {finished, 0}, {idle, Pending} (each waits for the host, such as for it to read a stream), {timeout, Pending}, or {error, Reason} when a task traps.

Stop holding a component image.

A component instance at the point an image was captured: the same link, replayed over Imports given for this instance, each core laid from its part of the image instead of instantiated, so no start function runs and nothing is initialised again. A composition is replayed the same way, each nested component restored in its place and its bridges built again.

Capture a component instance made with snapshotable => true, after it is initialised, so that each later instance can start from that point with restore/3 instead of being instantiated and initialised again.

The bytes a component was prepared from, or the bytes themselves.

Call an async-lifted export and return as soon as it resolves.

Types

component()

-opaque component()

description()

-type description() :: #{exports := [export_desc()], imports := [import_desc()]}.

export_desc()

-type export_desc() ::
          #{name := binary(),
            interface := binary() | none,
            func := binary(),
            kind := func | constructor | method | static,
            resource => binary(),
            params := [{binary(), wasm_canon:desc()}],
            result := wasm_canon:desc() | none | {named, [{binary(), wasm_canon:desc()}]},
            async := boolean()}.

image()

-type image() :: #{component_image := wasm_component, owner := pid(), atom() => term()}.

import_desc()

-type import_desc() ::
          #{name := binary(),
            kind := interface | func,
            funcs :=
                [#{func := binary(),
                   params := [{binary(), wasm_canon:desc()}],
                   result := wasm_canon:desc() | none | {named, [{binary(), wasm_canon:desc()}]},
                   async := boolean()}]}.

instance()

-opaque instance()

prepared()

-opaque prepared()

Functions

acquire/1

-spec acquire(image()) -> ok | {error, term()}.

Keep a component image alive past the process that captured it, as wasm:acquire/1 does for a core image.

call/4

-spec call(instance(), binary(), {[wasm_canon:desc()], wasm_canon:desc() | none}, [term()]) ->
              {ok, term()} | {error, term()}.

Call a lifted export, lowering Args and lifting the result by Sig.

Sig is {Params, Result} of Canonical ABI value descriptors (see wasm_canon). The post-return function the export's lift declares runs after the result is lifted.

Each argument is checked against its descriptor first, as check/2 does. One that does not fit, an integer out of its range for instance, is {error, #{class := invalid, kind := bad_argument}}, and the guest does not run. A value a host function returns to the guest is checked the same way, and one that does not fit traps the call with kind host_error.

call_async(I, Export, Sig, Args)

-spec call_async(instance(), binary(), {[wasm_canon:desc()], wasm_canon:desc() | none}, [term()]) ->
                    {ok, term()} | {error, term()}.

Call an async-lifted export, lowering Args and lifting the result by Sig.

The async counterpart of call/4, for an export lifted with the async Canonical ABI (async func). It calls the [async-lift]<export> core function and then drives the Component Model callback loop: on EXIT it lifts the value the guest handed back through task.return; on WAIT it waits on the named waitable-set (wasm_async:wait_on_set/1) for a completion from a producer and re-enters the guest through its callback with the (event, waitable, code) triple; on YIELD it re-enters with a NONE event. It loops until EXIT (or an execution budget is exhausted).

A future<T>/stream<T> parameter's argument selects how the readable end is fed: a bare value/binary is EAGER (read completes at once); {ready_before, V} queues the completion before the guest runs (found at WAIT without blocking); {producer, PFun} spawns a monitored producer that supplies the value/bytes later. Opts may carry wait_hook => Pid, notified each time the task blocks in wait_on_set (for tests to release a producer only after the owner is provably waiting).

call_async/5

-spec call_async(instance(), binary(), {[wasm_canon:desc()], wasm_canon:desc() | none}, [term()], map()) ->
                    {ok, term()} | {error, term()}.

check(Sig, Args)

-spec check({[wasm_canon:desc()], wasm_canon:desc() | none}, [term()]) ->
               ok | {error, wasm_error:error()}.

Check Args against the parameters of Sig as call/4 checks them before it lowers anything: ok, or the error call/4 would answer, with class invalid and kind bad_argument. No component is needed, so you can check a request before you spawn or queue the call that will make it.

ok = wasm_component:check({[u8, string], none}, [255, ~"ok"]),
{error, #{kind := bad_argument, ctx := #{path := [0], got := 256}}} =
    wasm_component:check({[u8, string], none}, [256, ~"ok"]).

ctx says where the value is and what was expected; "When an argument does not fit" in docs/components.md has the keys and what each holds. A Sig that is not {Params, Result} is an error too.

custom_sections(Comp)

-spec custom_sections(binary() | prepared()) ->
                         {ok, [{binary(), binary()}]} | {error, wasm_error:error()}.

The component's top-level custom sections, in the order of the binary, as {Name, Payload}, with each payload as the bytes hold it. Nothing is instantiated and no section is interpreted.

{ok, Sections} = wasm_component:custom_sections(Bin),
Producers = proplists:get_value(~"producers", Sections).

Which sections a component has depends on its toolchain. Checked with wasm-tools 1.256.0: wasm-tools component new writes producers (the tools that built it) and component-name (the names of its items), and no package-docs. package-docs, the WIT doc comments, is written into an encoded WIT package (wasm-tools component wit wit/ --wasm); its format is wit-component's, so read it with that. Only the top level is listed: a custom section of a nested component or of a core module is part of that component's or module's bytes.

Bytes that are not a component, a truncated section, or a section name that is not valid UTF-8 give {error, #{class := malformed}}.

decode/1

-spec decode(binary()) -> {ok, component()} | {error, term()}.

Decode a component binary into its embedded core module and export names.

{error, not_a_component} if the bytes are a core module or not wasm at all.

describe(Comp)

-spec describe(binary() | prepared()) -> {ok, description()} | {error, wasm_error:error()}.

What a component exports and imports, with the type of every function, read from the binary without instantiating it and without running guest code.

{ok, #{exports := Exports, imports := Imports}} = wasm_component:describe(Bin).

Each export is a map:

  • name: what call/4 and call_async/4 take, such as example:calc/ops@1.0.0#add or example:counter/counters#[method]counter.increment;
  • interface: the exported interface, with its version, or none for a function of the world;
  • func: the function's WIT name: add, increment, and for a constructor the resource's name;
  • kind: func, constructor, method or static, and resource, the resource's name, for the last three;
  • params: [{Name, Desc}], each parameter's WIT name and descriptor;
  • result: the descriptor of the result, or none;
  • async: true when the export is lifted async, and called with call_async/4.

Each import is #{name, kind, funcs}: name is the interface or function as the component imports it, with its version; kind is interface or func; funcs lists #{func, params, result, async}, with func the name your imports map keys the function by. For an import, async says the type is async.

Every descriptor is one call/4 takes, with every type reference resolved: a record, variant, enum or flags type the world names is written out. A resource is {own, T} or {borrow, T}, T its index in the component's type space. Both lists keep the order of the binary. A composed component describes the exports of the nested components it re-exports.

A function with several named results, which only an older encoding of the Component Model can declare, has result => {named, [{Name, Desc}]}. No descriptor stands for it, so call/4 cannot call such a function.

A binary that is not a component, or holds a type this runtime cannot read, is {error, Error} with class malformed.

destroy(Inst)

-spec destroy(instance()) -> ok.

Destroy a component instance, freeing every core it built and sweeping the host resource tables. A resource may own an OS handle (a file descriptor, a socket) that GC does not reclaim, so destroy/2 takes a closer the host layer supplies to close each one; destroy/1 closes nothing, for pure components with no OS state.

The instance's resource handle table goes with it: every handle still live is discarded and no guest destructor runs, since the guest memory the representations point into is freed with the instance. A handle used afterwards answers what the destroyed instance answers.

The host resource tables are per-process, not per-instance, so destroy sweeps every live host resource in the calling process. The contract is therefore one live instance per process, destroyed from that same process: the worker runs one instance per request and destroys it in its runner, and the inline API instantiates and destroys in order in one process. Running two instances concurrently in one process and destroying one would free the other's handles; do not.

destroy(Inst, Closer)

-spec destroy(instance(), fun(({atom(), term()}) -> ok)) -> ok.

As destroy/1, closing each live host resource with Closer first.

drop_resource/3

-spec drop_resource(instance(), binary(), non_neg_integer()) -> ok | {error, term()}.

Drop a resource handle the host holds, running the resource's destructor.

DtorExport is the destructor's export, the resource's interface-qualified prefix followed by [dtor]<res>, e.g. example:counter/counters#[dtor]counter. The handle must be live, held by the host, and of the type that destructor destroys; otherwise the answer is a resource_not_live or resource_wrong_type trap and the destructor is not called. On success the handle is removed from the instance's table, the destructor runs with the guest's representation, and its result is answered: ok, or the trap it raised.

exports/1

-spec exports(instance()) -> [binary()].

The export names a decoded component instance offers.

hold/1

-spec hold(binary() | prepared()) -> ok | {error, term()}.

Keep a component's core modules loaded while the calling process lives.

Instantiating loads each core module through the module cache, and a module nobody holds is evicted when its last instance's process exits. A server that instantiates per request, each in its own process, so loads every core again on every request, and every one of those loads counts against max_module_loads_per_second. Call hold/1 from a process that lives as long as the server: each instantiation then finds the modules already loaded.

ok once every core module is loaded, or the first error. Does nothing when the wasm application is not started, since instantiation then compiles in the caller and never uses the cache.

host_drop(Handle)

-spec host_drop(pos_integer()) -> ok.

Drop a host handle. A miss (double drop, unknown handle) is a no-op.

host_get(Handle)

-spec host_get(pos_integer()) -> {ok, {atom(), term()}} | error.

The tag and state behind a host handle, or error if it is not live.

host_live()

-spec host_live() -> [pos_integer()].

The live host handles in this process, for tests and teardown checks.

host_new(Tag, State)

-spec host_new(atom(), term()) -> pos_integer().

Mint a fresh host-owned resource handle carrying State, tagged Tag.

The table is per-process, shared by every instance in the process; destroy sweeps all of it, so the contract is one live instance per process (see destroy/2).

host_new(Tag, State, Origin)

-spec host_new(atom(), term(), term()) -> pos_integer().

As host_new/2, saying where the entry came from: an origin the host can make the entry again from, for another instance, as a restore does. WASI's stdio streams and preopened directories have one; nothing else does.

host_update(Handle, State)

-spec host_update(pos_integer(), term()) -> ok.

Replace the state behind a live host handle, keeping its tag.

import_fun/2

-spec import_fun({[wasm_canon:desc()], wasm_canon:desc() | none}, fun(([term()]) -> term())) ->
                    function().

Wrap a typed host function as an import, handling the Canonical ABI both ways.

Sig is {Params, Result} of value descriptors. The returned raw import lifts the guest's flat arguments to Erlang terms, calls Fun(Terms), and lowers the result -- into the guest's return area for a by-memory result (a string, a list, a record), or flat for a small one. Result may be none for a function that returns nothing.

instantiate(Bin)

-spec instantiate(binary()) -> {ok, instance()} | {error, term()}.

Decode and instantiate a component, wiring any resource intrinsics.

instantiate(Bin, Imports)

-spec instantiate(binary() | prepared(), #{{binary(), binary()} => function()}) ->
                     {ok, instance()} | {error, term()}.

Instantiate a component, providing host functions for the interfaces it imports.

Imports is a map keyed {InterfaceName, FieldName} (e.g. {~"example:host/clock", ~"now"}) to a fun(Ctx, Args) host function, the way the host supplies a WASI 0.2 world. It is merged over the resource intrinsics the component needs, so a component that both imports an interface and exports a resource gets both.

You do not need the wasm application started. When it runs, each core module is loaded through its module cache, so the same bytes compile once per node and are shared; when it does not, they are compiled inline, as wasm:compile/1 does.

instantiate(Bin, Imports, Opts0)

-spec instantiate(binary() | prepared(), #{{binary(), binary()} => function()}, map()) ->
                     {ok, instance()} | {error, term()}.

As instantiate/2, passing Limits (memory and fuel bounds) to the inner core instance, so a component honours the same limits a core module does. This is what the worker uses per request.

loader picks how core modules are built: load through the module cache (rate-limited, and it needs the wasm application), or compile inline. Left out, it is load while the cache runs and compile when it does not.

Three more keys are read here and not passed to the cores:

  • resource_limit: how many host resource handles may be live at once in the calling process, and how many subtasks an async task of this instance may have waiting. Past it, host_new/2 traps with resource_limit_reached. infinity when left out; each instantiation sets it again for the whole process.
  • resource_closer: a fun(Resource) that closes the host resource behind a handle the guest drops, at the drop rather than at destroy/2.
  • resource_predrop: a fun(Handle) called before that drop; answering {trap, Reason} refuses it.

resource_closer and resource_predrop are used when the cores are wired by wasm_component_link: a guest's canon resource.drop of a resource type the component does not define calls them. On the single-core path that drop is the host import of the same name. Everything else in the map goes to each core as its options, flat, as wasm:instantiate/3 takes them.

prepare/1

-spec prepare(binary() | prepared()) -> {ok, prepared()} | {error, term()}.

Decode, check and parse component Bin once, for many instantiations.

Every instantiation from bytes decodes the component, checks its lifts and parses its sections again. A server that instantiates per request prepares the component once and passes what prepare/1 returns wherever it would pass the bytes: instantiate/2,3, hold/1, and the WASI runners.

{ok, Prepared} = wasm_component:prepare(Bin),
{ok, I} = wasm_component:instantiate(Prepared, #{}).

pump/2

-spec pump(instance(), timeout()) -> {finished | idle | timeout, non_neg_integer()} | {error, term()}.

Run the tasks still pending in the instance (from start_async/5) until all have finished, none can progress, or Timeout milliseconds pass: {finished, 0}, {idle, Pending} (each waits for the host, such as for it to read a stream), {timeout, Pending}, or {error, Reason} when a task traps.

release/1

-spec release(image()) -> ok.

Stop holding a component image.

restore/3

-spec restore(image(), #{{binary(), binary()} => term()}, map()) -> {ok, instance()} | {error, term()}.

A component instance at the point an image was captured: the same link, replayed over Imports given for this instance, each core laid from its part of the image instead of instantiated, so no start function runs and nothing is initialised again. A composition is replayed the same way, each nested component restored in its place and its bridges built again.

Opts as instantiate/3, plus:

  • compatibility_key: must match the image's.
  • host_remake: the fun that makes again, from its origin, each host entry the image kept, such as wasi_preview2:host_remake/1 gives. Needed only when the image keeps any.

snapshot/2

-spec snapshot(instance(), map()) -> {ok, image()} | {error, term()}.

Capture a component instance made with snapshotable => true, after it is initialised, so that each later instance can start from that point with restore/3 instead of being instantiated and initialised again.

Every core is captured, together and under their leases: what each defines, not what it imports from a sibling, which the link wires again at restore. The image keeps what the component was built from, so a restore replays the same link.

Opts:

  • snapshot_hooks: #{Interface => stateless}, one entry for each interface the component imports from outside itself. Silence means no, as for a core snapshot: an import nobody declared refuses the capture, because only its author knows whether it keeps state of its own.
  • version, compatibility_key: as wasm:snapshot/2.

Refused when the instance holds what an image cannot: a task frame with work in it, a thread, a host resource, a resource of its own.

source/1

-spec source(binary() | prepared()) -> binary().

The bytes a component was prepared from, or the bytes themselves.

start_async(I, Export, Sig, Args)

-spec start_async(instance(), binary(), {[wasm_canon:desc()], wasm_canon:desc() | none}, [term()]) ->
                     {ok, term()} | {error, term()}.

Call an async-lifted export and return as soon as it resolves.

call_async/5 runs the task until it finishes. A task can hand back its result (task.return) and keep running: a wasi:http handler returns its response, then writes the body. start_async/5 returns {ok, Result} at that point and leaves the task running in the instance. Run it with pump/2, or with the wasm_async host-end calls, which run it until they can answer.

A stream<T> or future<T> result is the host's end of it: read it with wasm_async:host_read/3 or wasm_async:host_future_await/2 while the task writes. Arguments and Opts are as for call_async/5.

start_async/5

-spec start_async(instance(),
                  binary(),
                  {[wasm_canon:desc()], wasm_canon:desc() | none},
                  [term()],
                  map()) ->
                     {ok, term()} | {error, term()}.