feat(harness): sealed WASI shims replace wasmtime-wasi; wasmtime async off
33d04b803551d1fde44d50dfbdadbe281633fcae
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: d045dc2acbbc
There are many coding harnesses - but this one is fast
33d04b803551d1fde44d50dfbdadbe281633fcae
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+968 / −253 text lines
+9 / −225 text lines
[[package]]name = "cap-primitives"version = "4.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"dependencies = [ "ambient-authority", "fs-set-times", "io-extras", "io-lifetimes 3.0.1", "ipnet", "maybe-owned", "rustix", "rustix-linux-procfs", "windows-sys 0.61.2", "winx",][[package]]name = "io-extras"version = "0.19.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"dependencies = [ "io-lifetimes 3.0.1", "windows-sys 0.60.2",][[package]]name = "io-lifetimes"version = "2.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"[[package]]name = "io-lifetimes"version = "3.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96" "wasmtime-wasi", "tracing-attributes",[[package]]name = "wasmtime-wasi"version = "49.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ce11727cb331abeaace3681a4b072e4fe04818d7b99786d183b318671f9e4e0e"dependencies = [ "async-trait", "bitflags", "bytes", "cap-primitives", "futures", "rand", "rustix", "rustix-linux-procfs", "thiserror 2.0.21", "tokio", "tracing", "url", "wasmtime", "wasmtime-wasi-io", "windows-sys 0.61.2", "winx",][[package]]name = "wasmtime-wasi-io"version = "49.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "35f5ed8d710d8daf71cb4742c6b90c1fd121acb62b6848556eb4e0661cbd28bd"dependencies = [ "async-trait", "bytes", "futures", "tracing", "wasmtime",] "windows-targets 0.52.6",][[package]]name = "windows-sys"version = "0.59.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"dependencies = [ "windows-targets 0.52.6",][[package]]name = "windows-sys"version = "0.60.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"dependencies = [ "windows-targets 0.53.5", "windows-targets", "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", "windows_i686_gnullvm 0.52.6", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6",][[package]]name = "windows-targets"version = "0.53.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"dependencies = [ "windows-link", "windows_aarch64_gnullvm 0.53.1", "windows_aarch64_msvc 0.53.1", "windows_i686_gnu 0.53.1", "windows_i686_gnullvm 0.53.1", "windows_i686_msvc 0.53.1", "windows_x86_64_gnu 0.53.1", "windows_x86_64_gnullvm 0.53.1", "windows_x86_64_msvc 0.53.1",+0 / −3 text lines
+1 / −2 text lines
+0 / −1 text lines
+36 / −22 text lines
use wasmtime::{Config, Engine, Store, component::ResourceTable}; path: "../wit", inline: " package smith:host; world plugin-host { include smith:plugin/plugin-world@0.1.0; import wasi:io/error@0.2.12; import wasi:io/poll@0.2.12; import wasi:io/streams@0.2.12; import wasi:clocks/monotonic-clock@0.2.12; import wasi:cli/environment@0.2.12; import wasi:cli/exit@0.2.12; import wasi:cli/stdin@0.2.12; import wasi:cli/stdout@0.2.12; import wasi:cli/stderr@0.2.12; import wasi:cli/terminal-stdin@0.2.12; import wasi:cli/terminal-stdout@0.2.12; import wasi:cli/terminal-stderr@0.2.12; } ", imports: { "wasi:cli/exit.exit": trappable, "wasi:cli/exit.exit-with-code": trappable, }, monotonic_now: 0, wasmtime_wasi::p2::add_to_linker_sync::<PluginHostState>(&mut linker) .map_err(|e| plugin_fault(format!("wasi linking failed: {e}")))?; PluginWorld::add_to_linker::<PluginHostState, PluginHasSelf>(&mut linker, |state| state) PluginHost::add_to_linker::<PluginHostState, PluginHasSelf>(&mut linker, |state| state)new file mode 100644+313 / −0 text lines
//! Sealed WASI: Smith's own synchronous implementations of the WASI imports//! that guest std runtimes pull in (`SMH-SPEC-WASM0001`, no ambient WASI).//!//! Sealed by default: empty environment and arguments, empty stdin, stdout//! and stderr writes discarded, no terminals, `exit` traps, the monotonic//! clock reads a host-injected value, and every pollable is ready.//!//! No host state backs a stream or pollable, so resources are bare handles//! with no table entry; dropping one is a no-op.use super::PluginHostState;use super::bindings::wasi::cli::{ environment, exit, stderr, stdin, stdout, terminal_input, terminal_output, terminal_stderr, terminal_stdin, terminal_stdout,};use super::bindings::wasi::clocks::monotonic_clock;use super::bindings::wasi::io::error::{self, Error};use super::bindings::wasi::io::poll::{self, Pollable};use super::bindings::wasi::io::streams::{self, InputStream, OutputStream, StreamError};use wasmtime::component::Resource;/// The only handle value ever minted; no handle carries host state.const SEALED: u32 = 0;/// Bytes a sealed output stream accepts per write; writes are discarded.const WRITE_BUDGET: u64 = 4096;fn sealed<T: 'static>() -> Resource<T> { Resource::new_own(SEALED)}impl poll::HostPollable for PluginHostState { fn ready(&mut self, _pollable: Resource<Pollable>) -> bool { true } fn block(&mut self, _pollable: Resource<Pollable>) {} fn drop(&mut self, _pollable: Resource<Pollable>) -> wasmtime::Result<()> { Ok(()) }}impl poll::Host for PluginHostState { fn poll(&mut self, pollables: Vec<Resource<Pollable>>) -> Vec<u32> { (0..u32::try_from(pollables.len()).unwrap_or(u32::MAX)).collect() }}impl error::HostError for PluginHostState { fn to_debug_string(&mut self, _error: Resource<Error>) -> String { String::new() } fn drop(&mut self, _error: Resource<Error>) -> wasmtime::Result<()> { Ok(()) }}impl error::Host for PluginHostState {}impl streams::HostInputStream for PluginHostState { fn read(&mut self, _stream: Resource<InputStream>, _len: u64) -> Result<Vec<u8>, StreamError> { Err(StreamError::Closed) } fn blocking_read( &mut self, _stream: Resource<InputStream>, _len: u64, ) -> Result<Vec<u8>, StreamError> { Err(StreamError::Closed) } fn skip(&mut self, _stream: Resource<InputStream>, _len: u64) -> Result<u64, StreamError> { Err(StreamError::Closed) } fn blocking_skip( &mut self, _stream: Resource<InputStream>, _len: u64, ) -> Result<u64, StreamError> { Err(StreamError::Closed) } fn subscribe(&mut self, _stream: Resource<InputStream>) -> Resource<Pollable> { sealed() } fn drop(&mut self, _stream: Resource<InputStream>) -> wasmtime::Result<()> { Ok(()) }}impl streams::HostOutputStream for PluginHostState { fn check_write(&mut self, _stream: Resource<OutputStream>) -> Result<u64, StreamError> { Ok(WRITE_BUDGET) } fn write( &mut self, _stream: Resource<OutputStream>, _contents: Vec<u8>, ) -> Result<(), StreamError> { Ok(()) } fn blocking_write_and_flush( &mut self, _stream: Resource<OutputStream>, _contents: Vec<u8>, ) -> Result<(), StreamError> { Ok(()) } fn flush(&mut self, _stream: Resource<OutputStream>) -> Result<(), StreamError> { Ok(()) } fn blocking_flush(&mut self, _stream: Resource<OutputStream>) -> Result<(), StreamError> { Ok(()) } fn subscribe(&mut self, _stream: Resource<OutputStream>) -> Resource<Pollable> { sealed() } fn write_zeroes( &mut self, _stream: Resource<OutputStream>, _len: u64, ) -> Result<(), StreamError> { Ok(()) } fn blocking_write_zeroes_and_flush( &mut self, _stream: Resource<OutputStream>, _len: u64, ) -> Result<(), StreamError> { Ok(()) } fn splice( &mut self, _stream: Resource<OutputStream>, _source: Resource<InputStream>, _len: u64, ) -> Result<u64, StreamError> { Err(StreamError::Closed) } fn blocking_splice( &mut self, _stream: Resource<OutputStream>, _source: Resource<InputStream>, _len: u64, ) -> Result<u64, StreamError> { Err(StreamError::Closed) } fn drop(&mut self, _stream: Resource<OutputStream>) -> wasmtime::Result<()> { Ok(()) }}impl streams::Host for PluginHostState {}impl monotonic_clock::Host for PluginHostState { fn now(&mut self) -> monotonic_clock::Instant { self.monotonic_now } fn resolution(&mut self) -> monotonic_clock::Duration { 1 } fn subscribe_instant(&mut self, _when: monotonic_clock::Instant) -> Resource<Pollable> { sealed() } fn subscribe_duration(&mut self, _when: monotonic_clock::Duration) -> Resource<Pollable> { sealed() }}impl environment::Host for PluginHostState { fn get_environment(&mut self) -> Vec<(String, String)> { Vec::new() } fn get_arguments(&mut self) -> Vec<String> { Vec::new() } fn initial_cwd(&mut self) -> Option<String> { None }}impl exit::Host for PluginHostState { fn exit(&mut self, status: Result<(), ()>) -> wasmtime::Result<()> { Err(wasmtime::format_err!("guest exited: {status:?}")) } fn exit_with_code(&mut self, status_code: u8) -> wasmtime::Result<()> { Err(wasmtime::format_err!( "guest exited with code {status_code}" )) }}impl stdin::Host for PluginHostState { fn get_stdin(&mut self) -> Resource<InputStream> { sealed() }}impl stdout::Host for PluginHostState { fn get_stdout(&mut self) -> Resource<OutputStream> { sealed() }}impl stderr::Host for PluginHostState { fn get_stderr(&mut self) -> Resource<OutputStream> { sealed() }}impl terminal_input::HostTerminalInput for PluginHostState { fn drop(&mut self, _terminal: Resource<terminal_input::TerminalInput>) -> wasmtime::Result<()> { Ok(()) }}impl terminal_input::Host for PluginHostState {}impl terminal_output::HostTerminalOutput for PluginHostState { fn drop( &mut self, _terminal: Resource<terminal_output::TerminalOutput>, ) -> wasmtime::Result<()> { Ok(()) }}impl terminal_output::Host for PluginHostState {}impl terminal_stdin::Host for PluginHostState { fn get_terminal_stdin(&mut self) -> Option<Resource<terminal_input::TerminalInput>> { None }}impl terminal_stdout::Host for PluginHostState { fn get_terminal_stdout(&mut self) -> Option<Resource<terminal_output::TerminalOutput>> { None }}impl terminal_stderr::Host for PluginHostState { fn get_terminal_stderr(&mut self) -> Option<Resource<terminal_output::TerminalOutput>> { None }}#[cfg(test)]mod tests { use super::*; use crate::wasm::PluginCeilings; use poll::Host as _; use streams::{HostInputStream as _, HostOutputStream as _}; fn state() -> PluginHostState { PluginHostState { monotonic_now: 42, ceilings: PluginCeilings::default(), } } #[test] fn poll_reports_every_pollable_ready() { let mut host = state(); assert_eq!(host.poll(vec![sealed(), sealed(), sealed()]), [0, 1, 2]); assert!(host.poll(Vec::new()).is_empty()); } #[test] fn stdin_is_closed_and_stdout_discards() { let mut host = state(); assert!(matches!(host.read(sealed(), 16), Err(StreamError::Closed))); assert_eq!(host.check_write(sealed()).unwrap(), WRITE_BUDGET); assert!(host.write(sealed(), b"dropped".to_vec()).is_ok()); } #[test] fn clock_is_host_injected_and_exit_traps() { let mut host = state(); assert_eq!(monotonic_clock::Host::now(&mut host), 42); assert!(exit::Host::exit(&mut host, Ok(())).is_err()); assert!(exit::Host::exit_with_code(&mut host, 0).is_err()); } #[test] fn environment_is_empty() { let mut host = state(); assert!(environment::Host::get_environment(&mut host).is_empty()); assert!(environment::Host::get_arguments(&mut host).is_empty()); assert!(environment::Host::initial_cwd(&mut host).is_none()); }}new file mode 100644+144 / −0 text lines
// Copied from wasmtime-wasi 49.0.1 `src/p2/wit/deps/cli.wit`// (Apache-2.0 WITH LLVM-exception).// Modified: the `imports` and `command` worlds are removed; they pull in// filesystem, sockets, and random, which Smith never grants ambiently.// Interfaces are unchanged.package wasi:cli@0.2.12;@since(version = 0.2.0)interface environment { /// Get the POSIX-style environment variables. /// /// Each environment variable is provided as a pair of string variable names /// and string value. /// /// Morally, these are a value import, but until value imports are available /// in the component model, this import function should return the same /// values each time it is called. @since(version = 0.2.0) get-environment: func() -> list<tuple<string, string>>; /// Get the POSIX-style arguments to the program. @since(version = 0.2.0) get-arguments: func() -> list<string>; /// Return a path that programs should use as their initial current working /// directory, interpreting `.` as shorthand for this. @since(version = 0.2.0) initial-cwd: func() -> option<string>;}@since(version = 0.2.0)interface exit { /// Exit the current instance and any linked instances. @since(version = 0.2.0) exit: func(status: result); /// Exit the current instance and any linked instances, reporting the /// specified status code to the host. /// /// The meaning of the code depends on the context, with 0 usually meaning /// "success", and other values indicating various types of failure. /// /// This function does not return; the effect is analogous to a trap, but /// without the connotation that something bad has happened. @since(version = 0.2.12) exit-with-code: func(status-code: u8);}@since(version = 0.2.0)interface run { /// Run the program. @since(version = 0.2.0) run: func() -> result;}@since(version = 0.2.0)interface stdin { @since(version = 0.2.0) use wasi:io/streams@0.2.12.{input-stream}; @since(version = 0.2.0) get-stdin: func() -> input-stream;}@since(version = 0.2.0)interface stdout { @since(version = 0.2.0) use wasi:io/streams@0.2.12.{output-stream}; @since(version = 0.2.0) get-stdout: func() -> output-stream;}@since(version = 0.2.0)interface stderr { @since(version = 0.2.0) use wasi:io/streams@0.2.12.{output-stream}; @since(version = 0.2.0) get-stderr: func() -> output-stream;}/// Terminal input.////// In the future, this may include functions for disabling echoing,/// disabling input buffering so that keyboard events are sent through/// immediately, querying supported features, and so on.@since(version = 0.2.0)interface terminal-input { /// The input side of a terminal. @since(version = 0.2.0) resource terminal-input;}/// Terminal output.////// In the future, this may include functions for querying the terminal/// size, being notified of terminal size changes, querying supported/// features, and so on.@since(version = 0.2.0)interface terminal-output { /// The output side of a terminal. @since(version = 0.2.0) resource terminal-output;}/// An interface providing an optional `terminal-input` for stdin as a/// link-time authority.@since(version = 0.2.0)interface terminal-stdin { @since(version = 0.2.0) use terminal-input.{terminal-input}; /// If stdin is connected to a terminal, return a `terminal-input` handle /// allowing further interaction with it. @since(version = 0.2.0) get-terminal-stdin: func() -> option<terminal-input>;}/// An interface providing an optional `terminal-output` for stdout as a/// link-time authority.@since(version = 0.2.0)interface terminal-stdout { @since(version = 0.2.0) use terminal-output.{terminal-output}; /// If stdout is connected to a terminal, return a `terminal-output` handle /// allowing further interaction with it. @since(version = 0.2.0) get-terminal-stdout: func() -> option<terminal-output>;}/// An interface providing an optional `terminal-output` for stderr as a/// link-time authority.@since(version = 0.2.0)interface terminal-stderr { @since(version = 0.2.0) use terminal-output.{terminal-output}; /// If stderr is connected to a terminal, return a `terminal-output` handle /// allowing further interaction with it. @since(version = 0.2.0) get-terminal-stderr: func() -> option<terminal-output>;}new file mode 100644+164 / −0 text lines
// Copied verbatim from wasmtime-wasi 49.0.1 `src/p2/wit/deps/clocks.wit`// (Apache-2.0 WITH LLVM-exception).package wasi:clocks@0.2.12;/// WASI Monotonic Clock is a clock API intended to let users measure elapsed/// time.////// It is intended to be portable at least between Unix-family platforms and/// Windows.////// A monotonic clock is a clock which has an unspecified initial value, and/// successive reads of the clock will produce non-decreasing values.@since(version = 0.2.0)interface monotonic-clock { @since(version = 0.2.0) use wasi:io/poll@0.2.12.{pollable}; /// An instant in time, in nanoseconds. An instant is relative to an /// unspecified initial value, and can only be compared to instances from /// the same monotonic-clock. @since(version = 0.2.0) type instant = u64; /// A duration of time, in nanoseconds. @since(version = 0.2.0) type duration = u64; /// Read the current value of the clock. /// /// The clock is monotonic, therefore calling this function repeatedly will /// produce a sequence of non-decreasing values. /// /// For completeness, this function traps if it's not possible to represent /// the value of the clock in an `instant`. Consequently, implementations /// should ensure that the starting time is low enough to avoid the /// possibility of overflow in practice. @since(version = 0.2.0) now: func() -> instant; /// Query the resolution of the clock. Returns the duration of time /// corresponding to a clock tick. @since(version = 0.2.0) resolution: func() -> duration; /// Create a `pollable` which will resolve once the specified instant /// has occurred. @since(version = 0.2.0) subscribe-instant: func(when: instant) -> pollable; /// Create a `pollable` that will resolve after the specified duration has /// elapsed from the time this function is invoked. @since(version = 0.2.0) subscribe-duration: func(when: duration) -> pollable;}/// WASI Wall Clock is a clock API intended to let users query the current/// time. The name "wall" makes an analogy to a "clock on the wall", which/// is not necessarily monotonic as it may be reset.////// It is intended to be portable at least between Unix-family platforms and/// Windows.////// A wall clock is a clock which measures the date and time according to/// some external reference.////// External references may be reset, so this clock is not necessarily/// monotonic, making it unsuitable for measuring elapsed time.////// It is intended for reporting the current date and time for humans.@since(version = 0.2.0)interface wall-clock { /// A time and date in seconds plus nanoseconds. @since(version = 0.2.0) record datetime { seconds: u64, nanoseconds: u32, } /// Read the current value of the clock. /// /// This clock is not monotonic, therefore calling this function repeatedly /// will not necessarily produce a sequence of non-decreasing values. /// /// The returned timestamps represent the number of seconds since /// 1970-01-01T00:00:00Z, also known as [POSIX's Seconds Since the Epoch], /// also known as [Unix Time]. /// /// The nanoseconds field of the output is always less than 1000000000. /// /// [POSIX's Seconds Since the Epoch]: https://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xbd_chap04.html#tag_21_04_16 /// [Unix Time]: https://en.wikipedia.org/wiki/Unix_time @since(version = 0.2.0) now: func() -> datetime; /// Query the resolution of the clock. /// /// The nanoseconds field of the output is always less than 1000000000. @since(version = 0.2.0) resolution: func() -> datetime;}@unstable(feature = clocks-timezone)interface timezone { @unstable(feature = clocks-timezone) use wall-clock.{datetime}; /// Information useful for displaying the timezone of a specific `datetime`. /// /// This information may vary within a single `timezone` to reflect daylight /// saving time adjustments. @unstable(feature = clocks-timezone) record timezone-display { /// The number of seconds difference between UTC time and the local /// time of the timezone. /// /// The returned value will always be less than 86400 which is the /// number of seconds in a day (24*60*60). /// /// In implementations that do not expose an actual time zone, this /// should return 0. utc-offset: s32, /// The abbreviated name of the timezone to display to a user. The name /// `UTC` indicates Coordinated Universal Time. Otherwise, this should /// reference local standards for the name of the time zone. /// /// In implementations that do not expose an actual time zone, this /// should be the string `UTC`. /// /// In time zones that do not have an applicable name, a formatted /// representation of the UTC offset may be returned, such as `-04:00`. name: string, /// Whether daylight saving time is active. /// /// In implementations that do not expose an actual time zone, this /// should return false. in-daylight-saving-time: bool, } /// Return information needed to display the given `datetime`. This includes /// the UTC offset, the time zone name, and a flag indicating whether /// daylight saving time is active. /// /// If the timezone cannot be determined for the given `datetime`, return a /// `timezone-display` for `UTC` with a `utc-offset` of 0 and no daylight /// saving time. @unstable(feature = clocks-timezone) display: func(when: datetime) -> timezone-display; /// The same as `display`, but only return the UTC offset. @unstable(feature = clocks-timezone) utc-offset: func(when: datetime) -> s32;}@since(version = 0.2.0)world imports { @since(version = 0.2.0) import wasi:io/poll@0.2.12; @since(version = 0.2.0) import monotonic-clock; @since(version = 0.2.0) import wall-clock; @unstable(feature = clocks-timezone) import timezone;}new file mode 100644+301 / −0 text lines
// Copied verbatim from wasmtime-wasi 49.0.1 `src/p2/wit/deps/io.wit`// (Apache-2.0 WITH LLVM-exception).package wasi:io@0.2.12;@since(version = 0.2.0)interface error { /// A resource which represents some error information. /// /// The only method provided by this resource is `to-debug-string`, /// which provides some human-readable information about the error. /// /// In the `wasi:io` package, this resource is returned through the /// `wasi:io/streams.stream-error` type. /// /// To provide more specific error information, other interfaces may /// offer functions to "downcast" this error into more specific types. For example, /// errors returned from streams derived from filesystem types can be described using /// the filesystem's own error-code type. This is done using the function /// `wasi:filesystem/types.filesystem-error-code`, which takes a `borrow<error>` /// parameter and returns an `option<wasi:filesystem/types.error-code>`. /// /// The set of functions which can "downcast" an `error` into a more /// concrete type is open. @since(version = 0.2.0) resource error { /// Returns a string that is suitable to assist humans in debugging /// this error. /// /// WARNING: The returned string should not be consumed mechanically! /// It may change across platforms, hosts, or other implementation /// details. Parsing this string is a major platform-compatibility /// hazard. @since(version = 0.2.0) to-debug-string: func() -> string; }}/// A poll API intended to let users wait for I/O events on multiple handles/// at once.@since(version = 0.2.0)interface poll { /// `pollable` represents a single I/O event which may be ready, or not. @since(version = 0.2.0) resource pollable { /// Return the readiness of a pollable. This function never blocks. /// /// Returns `true` when the pollable is ready, and `false` otherwise. @since(version = 0.2.0) ready: func() -> bool; /// `block` returns immediately if the pollable is ready, and otherwise /// blocks until ready. /// /// This function is equivalent to calling `poll.poll` on a list /// containing only this pollable. @since(version = 0.2.0) block: func(); } /// Poll for completion on a set of pollables. /// /// This function takes a list of pollables, which identify I/O sources of /// interest, and waits until one or more of the events is ready for I/O. /// /// The result `list<u32>` contains one or more indices of handles in the /// argument list that is ready for I/O. /// /// This function traps if either: /// - the list is empty, or: /// - the list contains more elements than can be indexed with a `u32` value. /// /// A timeout can be implemented by adding a pollable from the /// wasi-clocks API to the list. /// /// This function does not return a `result`; polling in itself does not /// do any I/O so it doesn't fail. If any of the I/O sources identified by /// the pollables has an error, it is indicated by marking the source as /// being ready for I/O. @since(version = 0.2.0) poll: func(in: list<borrow<pollable>>) -> list<u32>;}/// WASI I/O is an I/O abstraction API which is currently focused on providing/// stream types.////// In the future, the component model is expected to add built-in stream types;/// when it does, they are expected to subsume this API.@since(version = 0.2.0)interface streams { @since(version = 0.2.0) use error.{error}; @since(version = 0.2.0) use poll.{pollable}; /// An error for input-stream and output-stream operations. @since(version = 0.2.0) variant stream-error { /// The last operation (a write or flush) failed before completion. /// /// More information is available in the `error` payload. /// /// After this, the stream will be closed. All future operations return /// `stream-error::closed`. last-operation-failed(error), /// The stream is closed: no more input will be accepted by the /// stream. A closed output-stream will return this error on all /// future operations. closed, } /// An input bytestream. /// /// `input-stream`s are *non-blocking* to the extent practical on underlying /// platforms. I/O operations always return promptly; if fewer bytes are /// promptly available than requested, they return the number of bytes promptly /// available, which could even be zero. To wait for data to be available, /// use the `subscribe` function to obtain a `pollable` which can be polled /// for using `wasi:io/poll`. @since(version = 0.2.0) resource input-stream { /// Perform a non-blocking read from the stream. /// /// When the source of a `read` is binary data, the bytes from the source /// are returned verbatim. When the source of a `read` is known to the /// implementation to be text, bytes containing the UTF-8 encoding of the /// text are returned. /// /// This function returns a list of bytes containing the read data, /// when successful. The returned list will contain up to `len` bytes; /// it may return fewer than requested, but not more. The list is /// empty when no bytes are available for reading at this time. The /// pollable given by `subscribe` will be ready when more bytes are /// available. /// /// This function fails with a `stream-error` when the operation /// encounters an error, giving `last-operation-failed`, or when the /// stream is closed, giving `closed`. /// /// When the caller gives a `len` of 0, it represents a request to /// read 0 bytes. If the stream is still open, this call should /// succeed and return an empty list, or otherwise fail with `closed`. /// /// The `len` parameter is a `u64`, which could represent a list of u8 which /// is not possible to allocate in wasm32, or not desirable to allocate as /// as a return value by the callee. The callee may return a list of bytes /// less than `len` in size while more bytes are available for reading. @since(version = 0.2.0) read: func(len: u64) -> result<list<u8>, stream-error>; /// Read bytes from a stream, after blocking until at least one byte can /// be read. Except for blocking, behavior is identical to `read`. @since(version = 0.2.0) blocking-read: func(len: u64) -> result<list<u8>, stream-error>; /// Skip bytes from a stream. Returns number of bytes skipped. /// /// Behaves identical to `read`, except instead of returning a list /// of bytes, returns the number of bytes consumed from the stream. @since(version = 0.2.0) skip: func(len: u64) -> result<u64, stream-error>; /// Skip bytes from a stream, after blocking until at least one byte /// can be skipped. Except for blocking behavior, identical to `skip`. @since(version = 0.2.0) blocking-skip: func(len: u64) -> result<u64, stream-error>; /// Create a `pollable` which will resolve once either the specified stream /// has bytes available to read or the other end of the stream has been /// closed. /// The created `pollable` is a child resource of the `input-stream`. /// Implementations may trap if the `input-stream` is dropped before /// all derived `pollable`s created with this function are dropped. @since(version = 0.2.0) subscribe: func() -> pollable; } /// An output bytestream. /// /// `output-stream`s are *non-blocking* to the extent practical on /// underlying platforms. Except where specified otherwise, I/O operations also /// always return promptly, after the number of bytes that can be written /// promptly, which could even be zero. To wait for the stream to be ready to /// accept data, the `subscribe` function to obtain a `pollable` which can be /// polled for using `wasi:io/poll`. /// /// Dropping an `output-stream` while there's still an active write in /// progress may result in the data being lost. Before dropping the stream, /// be sure to fully flush your writes. @since(version = 0.2.0) resource output-stream { /// Check readiness for writing. This function never blocks. /// /// Returns the number of bytes permitted for the next call to `write`, /// or an error. Calling `write` with more bytes than this function has /// permitted will trap. /// /// When this function returns 0 bytes, the `subscribe` pollable will /// become ready when this function will report at least 1 byte, or an /// error. @since(version = 0.2.0) check-write: func() -> result<u64, stream-error>; /// Perform a write. This function never blocks. /// /// When the destination of a `write` is binary data, the bytes from /// `contents` are written verbatim. When the destination of a `write` is /// known to the implementation to be text, the bytes of `contents` are /// transcoded from UTF-8 into the encoding of the destination and then /// written. /// /// Precondition: check-write gave permit of Ok(n) and contents has a /// length of less than or equal to n. Otherwise, this function will trap. /// /// returns Err(closed) without writing if the stream has closed since /// the last call to check-write provided a permit. @since(version = 0.2.0) write: func(contents: list<u8>) -> result<_, stream-error>; /// Perform a write of up to 4096 bytes, and then flush the stream. Block /// until all of these operations are complete, or an error occurs. /// /// Returns success when all of the contents written are successfully /// flushed to output. If an error occurs at any point before all /// contents are successfully flushed, that error is returned as soon as /// possible. If writing and flushing the complete contents causes the /// stream to become closed, this call should return success, and /// subsequent calls to check-write or other interfaces should return /// stream-error::closed. @since(version = 0.2.0) blocking-write-and-flush: func(contents: list<u8>) -> result<_, stream-error>; /// Request to flush buffered output. This function never blocks. /// /// This tells the output-stream that the caller intends any buffered /// output to be flushed. the output which is expected to be flushed /// is all that has been passed to `write` prior to this call. /// /// Upon calling this function, the `output-stream` will not accept any /// writes (`check-write` will return `ok(0)`) until the flush has /// completed. The `subscribe` pollable will become ready when the /// flush has completed and the stream can accept more writes. @since(version = 0.2.0) flush: func() -> result<_, stream-error>; /// Request to flush buffered output, and block until flush completes /// and stream is ready for writing again. @since(version = 0.2.0) blocking-flush: func() -> result<_, stream-error>; /// Create a `pollable` which will resolve once the output-stream /// is ready for more writing, or an error has occurred. When this /// pollable is ready, `check-write` will return `ok(n)` with n>0, or an /// error. /// /// If the stream is closed, this pollable is always ready immediately. /// /// The created `pollable` is a child resource of the `output-stream`. /// Implementations may trap if the `output-stream` is dropped before /// all derived `pollable`s created with this function are dropped. @since(version = 0.2.0) subscribe: func() -> pollable; /// Write zeroes to a stream. /// /// This should be used precisely like `write` with the exact same /// preconditions (must use check-write first), but instead of /// passing a list of bytes, you simply pass the number of zero-bytes /// that should be written. @since(version = 0.2.0) write-zeroes: func(len: u64) -> result<_, stream-error>; /// Perform a write of up to 4096 zeroes, and then flush the stream. /// Block until all of these operations are complete, or an error /// occurs. /// /// Functionality is equivelant to `blocking-write-and-flush` with /// contents given as a list of len containing only zeroes. @since(version = 0.2.0) blocking-write-zeroes-and-flush: func(len: u64) -> result<_, stream-error>; /// Read from one stream and write to another. /// /// The behavior of splice is equivalent to: /// 1. calling `check-write` on the `output-stream` /// 2. calling `read` on the `input-stream` with the smaller of the /// `check-write` permitted length and the `len` provided to `splice` /// 3. calling `write` on the `output-stream` with that read data. /// /// Any error reported by the call to `check-write`, `read`, or /// `write` ends the splice and reports that error. /// /// This function returns the number of bytes transferred; it may be less /// than `len`. @since(version = 0.2.0) splice: func(src: borrow<input-stream>, len: u64) -> result<u64, stream-error>; /// Read from one stream and write to another, with blocking. /// /// This is similar to `splice`, except that it blocks until the /// `output-stream` is ready for writing, and the `input-stream` /// is ready for reading, before performing the `splice`. @since(version = 0.2.0) blocking-splice: func(src: borrow<input-stream>, len: u64) -> result<u64, stream-error>; }}@since(version = 0.2.0)world imports { @since(version = 0.2.0) import error; @since(version = 0.2.0) import poll; @since(version = 0.2.0) import streams;}