wasi_preview2 (wasm v0.16.0)

View Source

The WASI Preview 2 host: the wasi:* interfaces a component imports, each supplied as a host function keyed by {Interface, Field} for wasm_component:instantiate/2.

Preview 2 is the component-model side of WASI. A guest imports a world such as wasi:random/random and the host provides every function in it. The functions map onto the same hardened internals as Preview 1: paths go through wasi_fs, address decisions through wasi_net, randomness through crypto:strong_rand_bytes/1.

Keys are the bare interface ids (wasi:random/random). A component imports versioned ids (wasi:io/streams@0.2.0), and wasm_component strips the version when it resolves them, so one host serves every 0.2.x.

InterfaceBuilt by
wasi:randomrandom/0
wasi:clocksclocks/0
wasi:cli/environmentenvironment/0
wasi:io streams and pollio/0, poll/1
wasi:filesystem, read-only or writable per mountwasi_p2_filesystem:filesystem/1
wasi:sockets: TCP, UDP, name lookupwasi_p2_sockets:sockets/1, over wasi_sock2
wasi:httpwasi_http:http/1
wasi:nn, with the nn optionwasi_nn:imports/1
a whole wasi:cli/command worldcommand/1, run by run_command/2
one wasi:http/incoming-handler requestrun_serve/3

imports/0 is the merged map of the stateless interfaces. command/1 is the one to hand a command component: it merges everything above under the grants in its options. docs/components.md shows both from the caller's side.

Summary

Functions

wasi:cli/exit: exit and exit-with-code, which record the code and trap.

wasi:clocks: monotonic-clock (now, resolution in nanoseconds) and wall-clock (now, resolution as a datetime record of seconds and nanoseconds). The subscribe-* functions return a pollable and wait for wasi:io. Monotonic now counts from the node's first reading, so it is non-negative and non-decreasing; wall now is the system clock.

Every import a wasi:cli/command component needs, merged into one map: io (with stdin as the input source and stdout/stderr as sinks), clocks, random, the environment, exit, and the terminal interfaces (which report no tty). Hand it to a command component and call its wasi:cli/run.run export.

The mounts the preopen, writable and preopens options describe.

wasi:cli/environment: get-environment, get-arguments, initial-cwd. The default exposes nothing, the sandboxed posture: an empty environment, no arguments, no working directory. It never reads the node's real environment.

wasi:cli/environment with a given argv, environment and initial working directory. get-arguments returns Args verbatim (the caller includes argv[0]; nothing is prepended), get-environment returns Env as name/value pairs, and initial-cwd returns Cwd (none or {some, Path}).

For wasm_component:restore/3's host_remake: a fun that makes again, from Opts (what command/1 takes for this instance), each host entry an image kept. Stdout and stderr write to this instance's sinks, stdin reads this instance's input, and a preopen opens this instance's directory of the same guest name; a name it does not mount fails the restore with preopen_missing.

Every implemented wasi:* interface, merged into one imports map.

The stream side of wasi:io with default endpoints: get-stdout over a sink that discards, get-stdin over an empty source.

The stream side of wasi:io. wasi:cli/stdout.get-stdout mints a host-owned output-stream whose blocking-write-and-flush writes to sink, and wasi:cli/stdin.get-stdin mints an input-stream that hands out source through read/blocking-read until it is drained, then closed. The [resource-drop] intrinsics free the host handle.

wasi:random/random: get-random-u64 and get-random-bytes, backed by the system CSPRNG. The returned byte length is the guest's request, bounded by the guest's own linear-memory limit when the result is lowered.

Run a wasi:cli/command component with Stdin on its standard input and return what it wrote to standard output. Instantiates with command/1, calls the wasi:cli/run.run export, and collects the output stream. This is the byte-in/byte-out entry: a real component reads stdin and writes stdout.

As run_command/2 with extra command/1 options, such as preopen => Dir to give the command a directory to read (a mount), or network => Grant to grant the wasi:sockets slice (opt-in; without it a command imports no sockets).

As run_command/3, with the imports built by Host(Opts) instead of command/1: wasi_preview3:run_command/3 passes the 0.2 and 0.3 host together.

Serve one request to a wasi:http/incoming-handler reactor component. Request is #{method, path, scheme, authority, headers, body}; the host synthesizes the incoming-request, calls the guest's handle, and returns the response the guest set on the outparam as {ok, Status, Headers, Body}. Extra is the command/1 options (a network grant lets the reactor make its own outbound requests).

As run_serve/3, with the imports built by Host(Opts), or given as a map built once beforehand, and the request served by Serve(Instance, Request): wasi_preview3:run_serve/3,4 serve a 0.3 handler this way.

Serve Request through the 0.2 incoming-handler export of Instance.

The options of run_serve/3's Extra that shape its imports, not its instance.

The WASI interfaces this host serves, declared for wasm_component:snapshot/2's snapshot_hooks. Their functions keep nothing between calls but the host entries the capture checks itself: a stdio stream or a preopened directory is kept and made again by host_remake/1; any other entry refuses the capture.

wasi:sockets, built by wasi_p2_sockets:sockets/1.

Functions

blocking_read_stream(Handle, Len)

check_write(Handle)

cli_exit()

-spec cli_exit() -> #{{binary(), binary()} => fun()}.

wasi:cli/exit: exit and exit-with-code, which record the code and trap.

clocks()

-spec clocks() -> #{{binary(), binary()} => fun()}.

wasi:clocks: monotonic-clock (now, resolution in nanoseconds) and wall-clock (now, resolution as a datetime record of seconds and nanoseconds). The subscribe-* functions return a pollable and wait for wasi:io. Monotonic now counts from the node's first reading, so it is non-negative and non-decreasing; wall now is the system clock.

close_resource/1

-spec close_resource({atom(), term()}) -> ok.

command(Opts)

-spec command(#{stdin => binary(),
                stdout => fun((binary()) -> ok),
                stderr => fun((binary()) -> ok),
                args => [binary()],
                env => [{binary(), binary()}],
                preopen => file:filename_all(),
                writable => boolean(),
                preopens => [{binary(), file:filename_all(), boolean()}],
                initial_cwd => binary(),
                network => term(),
                http => term(),
                http_authorize => fun((map()) -> allow | deny),
                http_transport => module(),
                http_tls => [ssl:tls_client_option()],
                http_max_body_bytes => pos_integer(),
                nn => wasi_nn:grant()}) ->
                 #{{binary(), binary()} => fun()}.

Every import a wasi:cli/command component needs, merged into one map: io (with stdin as the input source and stdout/stderr as sinks), clocks, random, the environment, exit, and the terminal interfaces (which report no tty). Hand it to a command component and call its wasi:cli/run.run export.

Options: stdin (a binary, default empty), stdout and stderr (fun((binary()) -> ok) sinks, default discard). nn is a wasi_nn:grant() and adds wasi:nn; without it a component that imports wasi:nn is refused.

network is a wasi_net grant for wasi:sockets and, unless http is given, for wasi:http. http is a grant for wasi:http alone, #{connect => Rules}: the host resolves the host names a guest's requests name, and the guest gets no socket and no name lookup from it. http_authorize is a fun(Request) -> allow | deny that sees each request by host name before any lookup, and by address once the grant admitted one; wasi_http:policy/1 says what it is called with.

command_mounts(Opts)

-spec command_mounts(map()) -> [{binary(), file:filename_all(), boolean()}].

The mounts the preopen, writable and preopens options describe.

datagram_allowed(Datagram, Peer, Grant)

environment()

-spec environment() -> #{{binary(), binary()} => fun()}.

wasi:cli/environment: get-environment, get-arguments, initial-cwd. The default exposes nothing, the sandboxed posture: an empty environment, no arguments, no working directory. It never reads the node's real environment.

environment(Args, Env, Cwd)

-spec environment([binary()], [{binary(), binary()}], none | {some, binary()}) ->
                     #{{binary(), binary()} => fun()}.

wasi:cli/environment with a given argv, environment and initial working directory. get-arguments returns Args verbatim (the caller includes argv[0]; nothing is prepended), get-environment returns Env as name/value pairs, and initial-cwd returns Cwd (none or {some, Path}).

filesystem(Opts)

-spec filesystem(#{preopen => file:filename_all(),
                   name => binary(),
                   writable => boolean(),
                   mounts => [{binary(), file:filename_all(), boolean()}]}) ->
                    #{{binary(), binary()} => fun()}.

wasi:filesystem, built by wasi_p2_filesystem:filesystem/1.

host_remake(Opts)

-spec host_remake(map()) -> fun((term()) -> {ok, atom(), term()} | {error, atom()}).

For wasm_component:restore/3's host_remake: a fun that makes again, from Opts (what command/1 takes for this instance), each host entry an image kept. Stdout and stderr write to this instance's sinks, stdin reads this instance's input, and a preopen opens this instance's directory of the same guest name; a name it does not mount fails the restore with preopen_missing.

imports()

-spec imports() -> #{{binary(), binary()} => fun()}.

Every implemented wasi:* interface, merged into one imports map.

io()

-spec io() -> #{{binary(), binary()} => fun()}.

The stream side of wasi:io with default endpoints: get-stdout over a sink that discards, get-stdin over an empty source.

io(Opts)

-spec io(#{sink => fun((binary()) -> ok), source => binary()}) -> #{{binary(), binary()} => fun()}.

The stream side of wasi:io. wasi:cli/stdout.get-stdout mints a host-owned output-stream whose blocking-write-and-flush writes to sink, and wasi:cli/stdin.get-stdin mints an input-stream that hands out source through read/blocking-read until it is drained, then closed. The [resource-drop] intrinsics free the host handle.

sink defaults to discarding (so a guest never writes to the node's own stdout); source defaults to empty.

monotonic_now()

new_output_stream(Backing)

-spec new_output_stream(term()) -> pos_integer().

next_sleep_ms(Deadline)

peer_matches(Peer, Addr, Port)

permit_write(Handle, Bytes)

poll(Handles)

-spec poll([non_neg_integer()]) -> [non_neg_integer()].

random()

-spec random() -> #{{binary(), binary()} => fun()}.

wasi:random/random: get-random-u64 and get-random-bytes, backed by the system CSPRNG. The returned byte length is the guest's request, bounded by the guest's own linear-memory limit when the result is lowered.

random_bytes/1

run_command(Bin, Stdin)

-spec run_command(wasi_preview3:component(), binary()) -> {ok, binary()} | {error, term()}.

Run a wasi:cli/command component with Stdin on its standard input and return what it wrote to standard output. Instantiates with command/1, calls the wasi:cli/run.run export, and collects the output stream. This is the byte-in/byte-out entry: a real component reads stdin and writes stdout.

run_command(Bin, Stdin, Extra)

-spec run_command(wasi_preview3:component(),
                  binary(),
                  #{args => [binary()],
                    env => [{binary(), binary()}],
                    preopen => file:filename_all(),
                    writable => boolean(),
                    preopens => [{binary(), file:filename_all(), boolean()}],
                    initial_cwd => binary(),
                    network => term(),
                    compile => boolean()}) ->
                     {ok, #{stdout := binary(), stderr := binary(), exit_code := integer()}} |
                     {error, term()}.

As run_command/2 with extra command/1 options, such as preopen => Dir to give the command a directory to read (a mount), or network => Grant to grant the wasi:sockets slice (opt-in; without it a command imports no sockets).

run_command_with(Bin, Stdin, Extra, Host)

-spec run_command_with(wasi_preview3:component(), binary(), map(), fun((map()) -> map())) ->
                          {ok, #{stdout := binary(), stderr := binary(), exit_code := integer()}} |
                          {error, term()}.

As run_command/3, with the imports built by Host(Opts) instead of command/1: wasi_preview3:run_command/3 passes the 0.2 and 0.3 host together.

run_serve(Bin, Request, Extra)

-spec run_serve(wasi_preview3:component(),
                map(),
                #{network => term(),
                  compile => boolean(),
                  resource_limit => non_neg_integer() | infinity,
                  fuel => non_neg_integer() | infinity,
                  max_depth => pos_integer(),
                  max_memory_pages => non_neg_integer(),
                  max_heap_words => pos_integer(),
                  max_host_calls => non_neg_integer() | infinity}) ->
                   {ok, 0..65535, [{binary(), binary()}], binary()} | {error, term()}.

Serve one request to a wasi:http/incoming-handler reactor component. Request is #{method, path, scheme, authority, headers, body}; the host synthesizes the incoming-request, calls the guest's handle, and returns the response the guest set on the outparam as {ok, Status, Headers, Body}. Extra is the command/1 options (a network grant lets the reactor make its own outbound requests).

run_serve_with(Bin, Request, Extra, Host, Serve)

-spec run_serve_with(wasi_preview3:component(),
                     map(),
                     map(),
                     fun((map()) -> map()) | map(),
                     fun((wasm_component:instance(), map()) -> term())) ->
                        term().

As run_serve/3, with the imports built by Host(Opts), or given as a map built once beforehand, and the request served by Serve(Instance, Request): wasi_preview3:run_serve/3,4 serve a 0.3 handler this way.

serve(Instance, Request)

-spec serve(wasm_component:instance(), map()) -> term().

Serve Request through the 0.2 incoming-handler export of Instance.

serve_options(Extra)

-spec serve_options(map()) -> map().

The options of run_serve/3's Extra that shape its imports, not its instance.

snapshot_hooks()

-spec snapshot_hooks() -> #{binary() => stateless}.

The WASI interfaces this host serves, declared for wasm_component:snapshot/2's snapshot_hooks. Their functions keep nothing between calls but the host entries the capture checks itself: a stdio stream or a preopened directory is kept and made again by host_remake/1; any other entry refuses the capture.

sockets(Opts)

-spec sockets(#{grant => term()}) -> #{{binary(), binary()} => fun()}.

wasi:sockets, built by wasi_p2_sockets:sockets/1.

write_stream(Handle, Bytes)