Components

View Source

The WebAssembly Component Model lets you run a .wasm file that has typed interfaces. A core module only has functions over numbers. A component describes its imports and exports with strings, lists, records, variants and results. The runtime converts these values between Erlang and the guest for you, using the Canonical ABI. Read this page when your toolchain produces a component (cargo-component, wit-bindgen, componentize-py, jco, or a bundle built with wac), or when you want to connect several components.

Do you need this? Yes, if wasm-tools print your.wasm starts with (component ...), or your build targets wasm32-wasip2. No, for a core module ((module ...)) of functions over the memory you give it: use Hold modules and instances instead.

You use two modules: wasm_component to decode, instantiate and call, and wasi_preview2 for the WASI 0.2 host that a component imports. Components work whether the wasm application is started or not. When it is started, each core module goes through its module cache, so the same bytes are compiled once per node. When it is not started, each core module is compiled in the calling process, as wasm:compile/1 does. The async Canonical ABI (async func, stream<T>, future<T>) is supported: call an async export with wasm_component:call_async/4. A component built for WASI 0.3, whose interfaces use it, runs through wasi_preview3; see WASI 0.3.

The words on this page

wordwhat it means here
componenta Component Model binary: core modules plus typed interfaces. wasm-tools print shows (component ...).
core modulea plain WebAssembly module, (module ...), whose functions take and return numbers.
WITthe language that describes a component's interfaces and types.
Canonical ABIthe rules that copy a typed value (a string, a record, a handle) into a core module's memory and back.
signaturethe types of a function's parameters and result. You pass it to call/4.
descriptoran Erlang term that names one value type in a signature, such as u32 or {list, u8}.
resourcean object that a component owns, which you reach through a handle.
handlea small integer that names one resource in one instance.
own, borrowown gives the resource to the receiver; borrow lends it for one call only.
composecombine several components into one, so the imports of one are the exports of another.

More terms are in the glossary.

Run a component

Instantiate the bytes, and call an export by name with its signature. When you are done, destroy the instance to free its resources:

{ok, Bin} = file:read_file("echo.component.wasm"),
{ok, Inst} = wasm_component:instantiate(Bin),
{ok, Upper} = wasm_component:call(Inst, ~"run", {[{list, u8}], {list, u8}}, [~"hello"]),
ok = wasm_component:destroy(Inst).

The third argument is the export's signature as {Params, Result}: Params is a list of one descriptor per parameter, and Result is one descriptor or none. The signature is the WIT function type, written with the descriptors below. You can write it by hand, or read it from the binary with describe/1, as the next section shows; call/4 lowers and lifts by the signature you pass.

Describe a component

describe/1 lists every export and import of a component, with the type of each function, read from the bytes. It does not instantiate the component and runs no guest code, so you can call it on a component before you decide what to grant it. Use it to list what a component offers, or to build the signature you pass to call/4:

{ok, DBytes} = file:read_file("test/fixtures/component/vectors.component.wasm"),
{ok, #{exports := DExports}} = wasm_component:describe(DBytes),
[EchoPoint] = [E || #{name := ~"echo-point"} = E <- DExports],
maps:get(params, EchoPoint).
%% => [{~"v", {record, [{~"x", s32}, {~"y", s32}]}}]

echo-point takes one parameter, v, a point record, and returns a point, as its WIT says in From WIT to a call.

Take the descriptors out of params and call:

#{params := DParams, result := DResult} = EchoPoint,
{ok, DInst} = wasm_component:instantiate(DBytes),
DAnswer = wasm_component:call(DInst, ~"echo-point",
                              {[D || {_Name, D} <- DParams], DResult},
                              [#{~"x" => 3, ~"y" => -4}]),
ok = wasm_component:destroy(DInst),
DAnswer.
%% => {ok, #{~"x" := 3, ~"y" := -4}}

Each export is a map:

keywhat it holds
namethe name call/4 and call_async/4 take, such as ~"example:counter/counters#[method]counter.increment"
interfacethe exported interface, with its version, or none for a function of the world
functhe function's WIT name: ~"increment" for that method, and the resource's name for a constructor
kindfunc, constructor, method or static
resourcethe resource's name, for a constructor, a method or a static function only
params[{Name, Descriptor}], one per parameter, with its WIT name
resultthe result's descriptor, or none
asynctrue when the export is lifted async: call it 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}, where func is the name your imports map keys the function by, such as ~"[method]descriptor.read". Build a host function from it with import_fun/2.

Notes:

  • Every descriptor is one call/4 takes. A record, variant, enum or flags type that the world names is written out in full wherever a function uses it.
  • A resource handle is {own, T} or {borrow, T}, with T the resource type's index in the component, as in Resources.
  • Both lists keep the order of the binary.
  • A composed component (see Compose components) describes the exports of the nested components it re-exports, under the names you call them by.
  • A function with several named results has result => {named, [{Name, Descriptor}]}. Only an older encoding of the Component Model can declare one, and no descriptor stands for it, so call/4 cannot call it.
  • Bytes that are not a component, or a type the runtime cannot read, give {error, #{class := malformed}}.
  • describe/1 takes the bytes or a component from prepare/1.

Read the custom sections

A component can carry data no instantiation reads: who built it, the names of its items, the doc comments of its WIT. They are custom sections. custom_sections/1 lists the ones at the top of the component, in order, each as {Name, Payload} with the payload as the bytes hold it:

{ok, CSections} = wasm_component:custom_sections(DBytes),
[Name || {Name, _Payload} <- CSections].
%% => [~"component-name", ~"producers"]
  • producers names the tools that built the component, and component-name the names of its items. wasm-tools component new writes both.
  • package-docs holds the WIT doc comments. Checked with wasm-tools 1.256.0, wasm-tools component new does not write it into a component; an encoded WIT package (wasm-tools component wit wit/ --wasm) has it. The runtime does not read it: its format is wit-component's.
  • A doc comment is the guest author's text. Show it to a person or a language model as text you do not trust.

Name an export

The second argument of call/4 is the export's name. exports/1 lists the names at the top of a component: its own functions, and the interfaces it exports:

{ok, CounterBytes} = file:read_file("test/fixtures/component/counter.component.wasm"),
{ok, C} = wasm_component:instantiate(CounterBytes),
wasm_component:exports(C).
%% => [~"example:counter/counters"]

A function inside an exported interface is named by the interface, then #, then the function. A resource's functions carry a prefix in brackets:

in the WITthe name you pass
export run: func(), a function of the world~"run"
make-counter, in the exported interface example:counter/counters~"example:counter/counters#make-counter"
the constructor of resource counter~"example:counter/counters#[constructor]counter"
the method increment of counter~"example:counter/counters#[method]counter.increment"
a static function from-list of resource fields~"Interface#[static]fields.from-list"
the destructor of counter, for drop_resource/3~"example:counter/counters#[dtor]counter"

Write the interface name exactly as exports/1 lists it, with its version when it has one, such as wasi:cli/run@0.2.0#run.

Describe the signature

A descriptor names one Component Model value type. Use these in the parameter list and in the result of call/4:

descriptorWIT typeErlang value
u8 u16 u32 u64 s8 s16 s32 s64the fixed-width integersan integer
f32 f64float32 float64a float
boolbooltrue / false
charchara code point integer
stringstringa binary (UTF-8)
{list, D}list<D>a list of D values (a binary for {list, u8})
{record, [{Name, D}]}recorda map #{Name => value}
{tuple, [D]}tuple<...>a tuple
{variant, [{Name, D | none}]}variant{Name, Payload}; {Name, undefined} for a case with no payload
{enum, [Name]}enuma Name binary
{option, D}option<D>{some, V} or none
{result, OkD | none, ErrD | none}result<Ok, Err>{ok, V} / {error, E}
{flags, [Name]}flagsa list of the set Names

When an argument does not fit

call/4 checks every argument against its descriptor before it writes anything into the guest's memory. An argument that does not fit is an error, and the guest does not run. It checks:

  • an integer's range for its width: 0 to 255 for a u8, -128 to 127 for an s8, and so on;
  • a char: a Unicode scalar value, so no surrogate (16#D800 to 16#DFFF) and nothing above 16#10FFFF;
  • a string: a binary of valid UTF-8;
  • every aggregate's shape: a record map with exactly its fields, a tuple of its size, a case name the type declares, none or {some, V}, {ok, V} or {error, E}, flags the type declares, and a handle as an integer.

The values the table above shows are the ones that fit, and they are the values call/4 gives back when it lifts a result. A case or a result arm with no type takes undefined, or none. A float is an Erlang float, or infinity, neg_infinity or {nan, Sign, Payload}.

check/2 runs the same check alone, with no component, so you can refuse a request before you start a call:

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

The error's ctx says what did not fit:

keywhat it holds
pathwhere the value is: the parameter's position (from 0), then a record field's name, a list or tuple index (from 0), {'case', Name} for a variant's payload, some, ok or error
expectedthe descriptor the value should fit
gotthe value when it is an integer, a float or an atom, else its type (binary, list, map, tuple), so a large argument is never copied into the error; missing for a record field that is not there
name, fielda case, enum or flag name the type does not declare, or a record field it does not declare

A list of arguments of the wrong length gives path => [], with the two lengths in expected and got. A value that a host function returns to the guest is checked the same way: one that does not fit traps the call with kind host_error, and the same path, expected and got.

From WIT to a call

Take one function from its WIT to a call. The vectors component in test/fixtures/component/ declares, in its wit/vectors.wit:

record point { x: s32, y: s32 }
export echo-point: func(v: point) -> point;
  1. Write each type as a descriptor. point is a record of two s32 fields: {record, [{~"x", s32}, {~"y", s32}]}.
  2. Write the signature: one parameter of type point, and a result of type point, so {[Point], Point}.
  3. Pass the record as a map with the field names as binaries, and call:
{ok, VBytes} = file:read_file("test/fixtures/component/vectors.component.wasm"),
{ok, V} = wasm_component:instantiate(VBytes),
Point = {record, [{~"x", s32}, {~"y", s32}]},
R = wasm_component:call(V, ~"echo-point", {[Point], Point}, [#{~"x" => 3, ~"y" => -4}]),
ok = wasm_component:destroy(V),
R.
%% => {ok, #{~"x" := 3, ~"y" := -4}}

echo-point is a function of the world, not of an interface, so its name has no #. wasm_component_vectors_SUITE makes the same call, and one for every other descriptor in the table.

A guest exporting run: func(input: list<u8>) -> result<list<u8>, string> is called the same way:

Sig = {[{list, u8}], {result, {list, u8}, string}},
{ok, {ok, Output}} = wasm_component:call(Inst, ~"run", Sig, [~"data"]).

A result comes back as {ok, V} when the guest returns ok, and as {error, E} when it returns an error. So when a guest rejects its input, you get a value, not a trap:

{ok, {error, Reason}} = wasm_component:call(Inst, ~"run", Sig, [~""]).

Supply the imports it needs

A component may import interfaces. Anything built for wasm32-wasip2 imports WASI. You instantiate such a component with a map of host functions, with keys of the form {InterfaceName, FieldName}. The WASI 0.2 host builds that map for you:

{ok, Inst} = wasm_component:instantiate(Bin, wasi_preview2:imports()),
{ok, _} = wasm_component:call(Inst, ~"run", {[], u32}, []).

If you leave a capability out of the host options, the guest cannot reach it, as in Preview 1. To run a command component (one with a main) with a directory, stdin and arguments, see WASI 0.2 and the example Run a WASI 0.2 component.

Compose components

wac plug and wasm-tools compose build one component from several others. You run it like any other component. The runtime instantiates the inner components and connects their imports and exports inside the one instance. When one inner component calls another, the values are copied. Each side keeps its own memory.

{ok, Bin} = file:read_file("composed.component.wasm"),
{ok, Inst} = wasm_component:instantiate(Bin),
{ok, Greeting} = wasm_component:call(Inst, ~"run", {[], string}, []),
ok = wasm_component:destroy(Inst).

An inner component can call another's async func export, such as a wasi:http middleware that imports wasi:http/handler and forwards each request to the handler composed with it. The two pass streams and futures to each other: the ends are shared, not copied, so what one writes the other reads. Call the composed component's async exports with call_async/4 or start_async/4, as for any component.

Notes:

  • The called component runs until it returns its result or waits. If it returns, the call completes at once. If it waits first, the call is a subtask: the caller goes on, and the subtask reports that it has returned once the called component returns. What the called component does after it returns, such as writing a response body, runs with the caller's other tasks.
  • A called component lifted without a callback (a stackful lift) runs its whole call on one stack. Called from another component, it gets a process of its own for that call, so it can wait for what its caller does next. A call into it while it waits starts once it returns.
  • A component may not read and write the same stream or future when its elements are not numbers, as the specification requires for now. Doing so traps with intra_component_copy. A middleware that hands its own future back to itself through the handler it calls does this.

Resources

A component may give you a resource: a handle to state that the component owns. You cannot see inside it. You get it as an own<T> (you hold it) or as a borrow<T> (lent for one call). You create one, pass the handle back to call its methods, and drop it when you are done.

The handle is a small integer. It is an index into the instance's handle table, not an address inside the guest. In a signature, a resource type is {own, TypeIndex} or {borrow, TypeIndex}. TypeIndex is the resource type's position in the component's type list (the numbered types the binary declares). The runtime checks each handle against the type the component itself declares for that export, not against the number you write. So 0 works for any resource, and so does a plain u32.

With the counter component from Name an export, create a counter and add 1 to it. A method takes the handle as its first parameter:

Q = fun(Name) -> <<"example:counter/counters#", Name/binary>> end,
{ok, Handle} = wasm_component:call(C, Q(~"[constructor]counter"), {[u32], {own, 0}}, [41]),
wasm_component:call(C, Q(~"[method]counter.increment"), {[{borrow, 0}, u32], u32}, [Handle, 1]).
%% => {ok, 42}

Drop a handle with drop_resource/3, naming the resource's destructor export. It runs the destructor once and returns ok:

wasm_component:drop_resource(C, Q(~"[dtor]counter"), Handle).
%% => ok

Every handle is checked before the guest runs. If a check fails, the call returns {error, #{class := trap, kind := Kind, ctx := Ctx}}, and the guest is not called:

What you passedkindctx
a handle already dropped, dropped twice, or never handed outresource_not_livehandle, operation
a handle of one resource type where another is expectedresource_wrong_typehandle, expected, actual
{error, #{class := trap, kind := resource_not_live}} =
    wasm_component:drop_resource(C, Q(~"[dtor]counter"), Handle),
wasm_component:destroy(C).
%% => ok
  • Each instance has its own table. A handle from one instance means nothing in another.
  • destroy/1 discards every handle the instance still holds. No destructor runs, because the guest's memory goes with the instance.
  • When a resource passes between composed components, the component that receives an own gets its own new handle. It can use the resource while it holds the handle, and dropping it runs the destructor in the component that defined the resource.

For a runnable version, see Use a component resource.

Async exports

An async func export is called with call_async/4. It runs the task to its end and returns the result:

{ok, Sum} = wasm_component:call_async(I, ~"sum-stream",
                                      {[{stream, u8}], u32}, [<<1, 2, 3>>]).

Some tasks hand back their result and keep running. A wasi:http handler returns its response, then writes the body. Use start_async/4 for these. It returns as soon as the task has a result, and the task keeps running in the instance. A stream or future in the result is your end of it: read it, and the task runs while you wait.

{ok, Body} = wasm_component:start_async(I, ~"body", {[], {stream, u8}}, []),
{ok, Chunk} = wasm_async:host_read(Body, 65536, 5000).
  • wasm_async:host_read/3 answers {ok, Bytes}, then eof once the guest has finished writing.
  • wasm_async:host_sink/2 takes every write as it happens instead, for a destination such as stdout.
  • wasm_component:pump(Inst, Timeout) runs pending tasks without reading. It answers {finished, 0}, {idle, N} when the N tasks left wait for you, {timeout, N}, or {error, Reason} when a task traps.
  • destroy/1 stops tasks still running.

A host import can give the guest a stream or a future of its own: wasm_async:host_stream/1 and host_future/1 return the guest's end and yours.

Instantiate one component many times

Each instantiation from bytes decodes the component, checks it and parses its sections again. When you instantiate the same component many times, as a server does per request, prepare it once and pass the result instead of the bytes:

{ok, Bin} = file:read_file("echo.component.wasm"),
{ok, Prepared} = wasm_component:prepare(Bin),
{ok, Inst} = wasm_component:instantiate(Prepared),
ok = wasm_component:destroy(Inst).

prepare/1 checks the component before you instantiate it and can report unsupported_canon_builtin at that point. Instantiation still resolves host imports and can report further errors. hold/1 and the WASI runners take a prepared component too, and the HTTP listener prepares its component when it starts.

A component that should keep its state between messages, under a supervisor, is an actor: prepare it once and every restart instantiates the prepared component.

Notes

  • The process that instantiated a component instance owns it. Call it from that process, and call destroy/1 there.
  • Malformed input is a value, never a crash: a truncated or ill-typed component returns {error, _} from instantiate, and a bad argument or guest trap returns {error, _} from call/4. A bad argument is bad_argument, see When an argument does not fit.
  • Strings are passed as UTF-8 by default. They are passed as UTF-16 or as Latin-1+UTF-16 when the component declares that encoding. You do not choose it.
  • instantiate/3 takes loader => compile to build the core modules in the calling process, or loader => load for the module cache. Leave it out and it picks the cache while the wasm application runs. The WASI runners spell the same choice compile => true, and do not pick by themselves; see Options from preview 1.

Read this next

Use a component resource, then Security. To run a component as a process that handles typed messages, read Actors. To change the Component Model code itself, read Component internals.