A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Add support for named imports to WASI implementations (#14275)
Alex Crichton1c5e7c854fcf
diff --git a/crates/component-macro/tests/codegen.rs b/crates/component-macro/tests/codegen.rsindex dd237ba79b..7cdd400bfc 100644--- a/crates/component-macro/tests/codegen.rs+++ b/crates/component-macro/tests/codegen.rs@@ -197,6 +197,37 @@ mod trappable_errors {});type MyX = u32;++ mod trappable2 {+ wasmtime::component::bindgen!({+ inline: r#"+ package test:pkg;++ interface types {+ variant error {+ test,+ }+ }++ interface test {+ use types.{error};++ test: func() -> result<_, error>;+ }++ world repro {+ import test;+ }+ "#,+ world: "repro",+ trappable_error_type: {+ "test:pkg/test.error" => String,+ },+ imports: {+ default: trappable,+ }+ });+ }}mod interface_name_with_rust_keyword {@@ -1028,6 +1059,89 @@ mod named_imports {imports: { default: async | store },});}++ mod trappable_errors {+ use wasmtime::component::Resource;++ wasmtime::component::bindgen!({+ inline: "+ package foo:foo;++ interface store {+ variant error {+ not-found,+ }++ resource cache {+ get: func(key: u32) -> result<u32, error>;+ }+ }++ world the-world {+ import store;+ }+ ",+ imports: { default: trappable },+ named_imports: {+ "foo:foo/store": String,+ },+ trappable_error_type: {+ "foo:foo/store.error" => MyError,+ },+ });++ pub struct MyError;++ struct MyHost;++ impl named_imports::foo::foo::store::HostCache for MyHost {+ fn get(+ &mut self,+ _id: String,+ _self_: Resource<foo::foo::store::Cache>,+ key: u32,+ ) -> Result<u32, MyError> {+ Ok(key)+ }+ fn drop(+ &mut self,+ _id: String,+ _rep: Resource<foo::foo::store::Cache>,+ ) -> wasmtime::Result<()> {+ Ok(())+ }+ }+ impl named_imports::foo::foo::store::Host for MyHost {+ fn convert_error(&mut self, _err: MyError) -> wasmtime::Result<foo::foo::store::Error> {+ Ok(foo::foo::store::Error::NotFound)+ }+ }+ }++ mod trappable2 {+ pub struct ErrorA;+ pub struct ErrorB;+ wasmtime::component::bindgen!({+ inline: "+ package test:collision;+ interface a { enum error { failed } }+ interface b { enum error { failed } }+ interface combined {+ use a.{error as error-a};+ use b.{error as error-b};+ first: func() -> result<_, error-a>;+ second: func() -> result<_, error-b>;+ }+ world test { import combined; }+ ",+ imports: { default: trappable },+ named_imports: { "test:collision/combined": usize },+ trappable_error_type: {+ "test:collision/a.error" => ErrorA,+ "test:collision/b.error" => ErrorB,+ },+ });+ }}mod include_component_type {diff --git a/crates/component-macro/tests/expanded/unstable-features.rs b/crates/component-macro/tests/expanded/unstable-features.rsindex ce5cd369b2..a7567d2810 100644--- a/crates/component-macro/tests/expanded/unstable-features.rs+++ b/crates/component-macro/tests/expanded/unstable-features.rs@@ -1,15 +1,15 @@/// Link-time configurations.#[derive(Clone, Debug, Default)]pub struct LinkOptions {- experimental_interface: bool,- experimental_interface_function: bool,- experimental_interface_resource: bool,- experimental_interface_resource_method: bool,- experimental_world: bool,- experimental_world_function_import: bool,- experimental_world_interface_import: bool,- experimental_world_resource: bool,- experimental_world_resource_method: bool,+ pub(crate) experimental_interface: bool,+ pub(crate) experimental_interface_function: bool,+ pub(crate) experimental_interface_resource: bool,+ pub(crate) experimental_interface_resource_method: bool,+ pub(crate) experimental_world: bool,+ pub(crate) experimental_world_function_import: bool,+ pub(crate) experimental_world_interface_import: bool,+ pub(crate) experimental_world_resource: bool,+ pub(crate) experimental_world_resource_method: bool,}impl LinkOptions {/// Enable members marked as `@unstable(feature = experimental-interface)`@@ -358,10 +358,10 @@ pub mod foo {/// Link-time configurations.#[derive(Clone, Debug, Default)]pub struct LinkOptions {- experimental_interface: bool,- experimental_interface_function: bool,- experimental_interface_resource: bool,- experimental_interface_resource_method: bool,+ pub(crate) experimental_interface: bool,+ pub(crate) experimental_interface_function: bool,+ pub(crate) experimental_interface_resource: bool,+ pub(crate) experimental_interface_resource_method: bool,}impl LinkOptions {/// Enable members marked as `@unstable(feature = experimental-interface)`diff --git a/crates/component-macro/tests/expanded/unstable-features_async.rs b/crates/component-macro/tests/expanded/unstable-features_async.rsindex 282a7fd56e..4b36db8956 100644--- a/crates/component-macro/tests/expanded/unstable-features_async.rs+++ b/crates/component-macro/tests/expanded/unstable-features_async.rs@@ -1,15 +1,15 @@/// Link-time configurations.#[derive(Clone, Debug, Default)]pub struct LinkOptions {- experimental_interface: bool,- experimental_interface_function: bool,- experimental_interface_resource: bool,- experimental_interface_resource_method: bool,- experimental_world: bool,- experimental_world_function_import: bool,- experimental_world_interface_import: bool,- experimental_world_resource: bool,- experimental_world_resource_method: bool,+ pub(crate) experimental_interface: bool,+ pub(crate) experimental_interface_function: bool,+ pub(crate) experimental_interface_resource: bool,+ pub(crate) experimental_interface_resource_method: bool,+ pub(crate) experimental_world: bool,+ pub(crate) experimental_world_function_import: bool,+ pub(crate) experimental_world_interface_import: bool,+ pub(crate) experimental_world_resource: bool,+ pub(crate) experimental_world_resource_method: bool,}impl LinkOptions {/// Enable members marked as `@unstable(feature = experimental-interface)`@@ -380,10 +380,10 @@ pub mod foo {/// Link-time configurations.#[derive(Clone, Debug, Default)]pub struct LinkOptions {- experimental_interface: bool,- experimental_interface_function: bool,- experimental_interface_resource: bool,- experimental_interface_resource_method: bool,+ pub(crate) experimental_interface: bool,+ pub(crate) experimental_interface_function: bool,+ pub(crate) experimental_interface_resource: bool,+ pub(crate) experimental_interface_resource_method: bool,}impl LinkOptions {/// Enable members marked as `@unstable(feature = experimental-interface)`diff --git a/crates/component-macro/tests/expanded/unstable-features_concurrent.rs b/crates/component-macro/tests/expanded/unstable-features_concurrent.rsindex 494e82ba28..c0f6d32e22 100644--- a/crates/component-macro/tests/expanded/unstable-features_concurrent.rs+++ b/crates/component-macro/tests/expanded/unstable-features_concurrent.rs@@ -1,15 +1,15 @@/// Link-time configurations.#[derive(Clone, Debug, Default)]pub struct LinkOptions {- experimental_interface: bool,- experimental_interface_function: bool,- experimental_interface_resource: bool,- experimental_interface_resource_method: bool,- experimental_world: bool,- experimental_world_function_import: bool,- experimental_world_interface_import: bool,- experimental_world_resource: bool,- experimental_world_resource_method: bool,+ pub(crate) experimental_interface: bool,+ pub(crate) experimental_interface_function: bool,+ pub(crate) experimental_interface_resource: bool,+ pub(crate) experimental_interface_resource_method: bool,+ pub(crate) experimental_world: bool,+ pub(crate) experimental_world_function_import: bool,+ pub(crate) experimental_world_interface_import: bool,+ pub(crate) experimental_world_resource: bool,+ pub(crate) experimental_world_resource_method: bool,}impl LinkOptions {/// Enable members marked as `@unstable(feature = experimental-interface)`@@ -374,10 +374,10 @@ pub mod foo {/// Link-time configurations.#[derive(Clone, Debug, Default)]pub struct LinkOptions {- experimental_interface: bool,- experimental_interface_function: bool,- experimental_interface_resource: bool,- experimental_interface_resource_method: bool,+ pub(crate) experimental_interface: bool,+ pub(crate) experimental_interface_function: bool,+ pub(crate) experimental_interface_resource: bool,+ pub(crate) experimental_interface_resource_method: bool,}impl LinkOptions {/// Enable members marked as `@unstable(feature = experimental-interface)`diff --git a/crates/component-macro/tests/expanded/unstable-features_tracing_async.rs b/crates/component-macro/tests/expanded/unstable-features_tracing_async.rsindex 558bb09c27..95675ade6c 100644--- a/crates/component-macro/tests/expanded/unstable-features_tracing_async.rs+++ b/crates/component-macro/tests/expanded/unstable-features_tracing_async.rs@@ -1,15 +1,15 @@/// Link-time configurations.#[derive(Clone, Debug, Default)]pub struct LinkOptions {- experimental_interface: bool,- experimental_interface_function: bool,- experimental_interface_resource: bool,- experimental_interface_resource_method: bool,- experimental_world: bool,- experimental_world_function_import: bool,- experimental_world_interface_import: bool,- experimental_world_resource: bool,- experimental_world_resource_method: bool,+ pub(crate) experimental_interface: bool,+ pub(crate) experimental_interface_function: bool,+ pub(crate) experimental_interface_resource: bool,+ pub(crate) experimental_interface_resource_method: bool,+ pub(crate) experimental_world: bool,+ pub(crate) experimental_world_function_import: bool,+ pub(crate) experimental_world_interface_import: bool,+ pub(crate) experimental_world_resource: bool,+ pub(crate) experimental_world_resource_method: bool,}impl LinkOptions {/// Enable members marked as `@unstable(feature = experimental-interface)`@@ -409,10 +409,10 @@ pub mod foo {/// Link-time configurations.#[derive(Clone, Debug, Default)]pub struct LinkOptions {- experimental_interface: bool,- experimental_interface_function: bool,- experimental_interface_resource: bool,- experimental_interface_resource_method: bool,+ pub(crate) experimental_interface: bool,+ pub(crate) experimental_interface_function: bool,+ pub(crate) experimental_interface_resource: bool,+ pub(crate) experimental_interface_resource_method: bool,}impl LinkOptions {/// Enable members marked as `@unstable(feature = experimental-interface)`diff --git a/crates/test-programs/src/bin/p2_environment_named_imports.rs b/crates/test-programs/src/bin/p2_environment_named_imports.rsnew file mode 100644index 0000000000..d88651f6da--- /dev/null+++ b/crates/test-programs/src/bin/p2_environment_named_imports.rs@@ -0,0 +1,36 @@+mod a {+ wit_bindgen::generate!({+ inline: r#"+ package a:b;++ world foo {+ import a: wasi:cli/[email protected];+ }+ "#,+ path: "../wasi/src/p2/wit",+ generate_all,+ });+}++mod b {+ wit_bindgen::generate!({+ inline: r#"+ package a:b;++ world bar {+ import b: wasi:cli/[email protected];+ }+ "#,+ path: "../wasi/src/p2/wit",+ generate_all,+ });+}++fn main() {+ let a = a::a::get_environment();+ let b = b::b::get_environment();+ let c = wasip2::cli::environment::get_environment();+ assert_ne!(a, b);+ assert_ne!(a, c);+ assert_ne!(b, c);+}diff --git a/crates/test-programs/src/bin/p2_http_named_imports.rs b/crates/test-programs/src/bin/p2_http_named_imports.rsnew file mode 100644index 0000000000..0f10a20c0f--- /dev/null+++ b/crates/test-programs/src/bin/p2_http_named_imports.rs@@ -0,0 +1,41 @@+mod a {+ wit_bindgen::generate!({+ inline: r#"+ package a:b;++ world foo {+ import a: wasi:http/[email protected];+ }+ "#,+ path: "../wasi-http/wit",+ generate_all,+ });+}++mod b {+ wit_bindgen::generate!({+ inline: r#"+ package a:b;++ world bar {+ import b: wasi:http/[email protected];+ }+ "#,+ path: "../wasi-http/wit",+ generate_all,+ });+}++fn main() {+ let a = a::a::Fields::new();+ assert!(a.append("a", b"0").is_err());+ assert!(a.append("b", b"0").is_ok());++ let b = b::b::Fields::new();+ assert!(b.append("a", b"0").is_ok());+ assert!(b.append("b", b"0").is_err());++ let c = wasip2::http::types::Fields::new();+ assert!(c.append("a", b"0").is_ok());+ assert!(c.append("b", b"0").is_ok());+}diff --git a/crates/test-programs/src/bin/p3_environment_named_imports.rs b/crates/test-programs/src/bin/p3_environment_named_imports.rsnew file mode 100644index 0000000000..9f3e4fdaa8--- /dev/null+++ b/crates/test-programs/src/bin/p3_environment_named_imports.rs@@ -0,0 +1,45 @@+mod a {+ wit_bindgen::generate!({+ inline: r#"+ package a:b;++ world foo {+ import a: wasi:cli/[email protected];+ }+ "#,+ path: "../wasi/src/p3/wit",+ generate_all,+ });+}++mod b {+ wit_bindgen::generate!({+ inline: r#"+ package a:b;++ world bar {+ import b: wasi:cli/[email protected];+ }+ "#,+ path: "../wasi/src/p3/wit",+ generate_all,+ });+}++struct Component;++test_programs::p3::export!(Component);++impl test_programs::p3::exports::wasi::cli::run::Guest for Component {+ async fn run() -> Result<(), ()> {+ let a = a::a::get_environment();+ let b = b::b::get_environment();+ let c = test_programs::p3::wasi::cli::environment::get_environment();+ assert_ne!(a, b);+ assert_ne!(a, c);+ assert_ne!(b, c);+ Ok(())+ }+}++fn main() {}diff --git a/crates/test-programs/src/bin/p3_http_named_imports.rs b/crates/test-programs/src/bin/p3_http_named_imports.rsnew file mode 100644index 0000000000..9d78ec0126--- /dev/null+++ b/crates/test-programs/src/bin/p3_http_named_imports.rs@@ -0,0 +1,50 @@+mod a {+ wit_bindgen::generate!({+ inline: r#"+ package a:b;++ world foo {+ import a: wasi:http/[email protected];+ }+ "#,+ path: "../wasi-http/src/p3/wit",+ generate_all,+ });+}++mod b {+ wit_bindgen::generate!({+ inline: r#"+ package a:b;++ world bar {+ import b: wasi:http/[email protected];+ }+ "#,+ path: "../wasi-http/src/p3/wit",+ generate_all,+ });+}++struct Component;++test_programs::p3::export!(Component);++impl test_programs::p3::exports::wasi::cli::run::Guest for Component {+ async fn run() -> Result<(), ()> {+ let a = a::a::Fields::new();+ assert!(a.append("a", b"0").is_err());+ assert!(a.append("b", b"0").is_ok());++ let b = b::b::Fields::new();+ assert!(b.append("a", b"0").is_ok());+ assert!(b.append("b", b"0").is_err());++ let c = test_programs::p3::wasi::http::types::Fields::new();+ assert!(c.append("a", b"0").is_ok());+ assert!(c.append("b", b"0").is_ok());+ Ok(())+ }+}++fn main() {}diff --git a/crates/wasi-http/src/ctx.rs b/crates/wasi-http/src/ctx.rsindex 2d58c1e771..704e4564ed 100644--- a/crates/wasi-http/src/ctx.rs+++ b/crates/wasi-http/src/ctx.rs@@ -6,7 +6,9 @@ use crate::{DEFAULT_FORBIDDEN_HEADERS, Error, RequestOptions, Result};use bytes::Bytes;use http::{HeaderName, uri::Scheme};use http_body_util::combinators::UnsyncBoxBody;+use std::marker;use wasmtime::component::{HasData, ResourceTable};+use wasmtime_wasi::{NamedId, WasiCtxNamedView};/// A helper struct which implements [`HasData`] for the `wasi:http` APIs.///@@ -404,3 +406,158 @@ impl<'a> Default for &'a mut dyn WasiHttpHooks {#[doc(hidden)]#[cfg(feature = "default-send-request")]impl WasiHttpHooks for [(); 0] {}++/// A helper struct which implements [`HasData`] for the `wasi:http` APIs when+/// used in combination with named imports.+///+/// This structure is similar in purpose to [`WasiHttp`] and is used+/// when using the [`named_imports`] module for `wasi:http`. This structure+/// serves as the `D` type parameter for `add_to_linker` functions.+///+/// [`named_imports`]: crate::p3::bindings::named_imports::wasi::http+///+/// # Meaning of the `T` parameter+///+/// Here the `T` must be something that implements [`WasiHttpNamedView`]. The+/// corresponding `Data` for this type is [`WasiCtxNamedView`] which internally+/// will contain `&mut T`.+///+/// Effectively you're going to implement [`WasiHttpNamedView`] for something in+/// your embedding, and that's the `T` you'll fill in here.+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component, ResourceTable};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};+/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpCtxView, WasiHttpNamed, WasiHttpNamedView};+/// use wasmtime_wasi_http::p2::bindings::named_imports;+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// table: ResourceTable,+/// states: HashMap<NamedId, WasiHttpCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// named_imports::wasi::http::outgoing_handler::add_to_linker::<MyStoreState, WasiHttpNamed<MyStoreState>>(+/// &mut linker,+/// &component,+/// |name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// |state| WasiCtxNamedView(state),+/// )?;+/// Ok(())+/// }+///+/// impl WasiHttpNamedView for MyStoreState {+/// fn http(&mut self, id: NamedId) -> WasiHttpCtxView<'_> {+/// let ctx = self.states.get_mut(&id).expect("state for id");+/// WasiHttpCtxView {+/// ctx,+/// table: &mut self.table,+/// hooks: Default::default(),+/// }+/// }+/// }+/// ```+pub struct WasiHttpNamed<T>(marker::PhantomData<fn() -> T>);++impl<T> HasData for WasiHttpNamed<T>+where+ T: WasiHttpNamedView,+{+ type Data<'a> = WasiCtxNamedView<'a, T>;+}++/// A trait used to look up a specific `wasi:http` context for a named import.+///+/// This trait is used in conjunction with the [`named_imports`] bindings+/// generated for all `wasi:http` interfaces. The purpose of this trait is for+/// embedders to define how a [`NamedId`] maps to a particular `wasi:http`+/// context, here returned as [`WasiHttpCtxView`]. Embedders are responsible+/// for assigning meaning to [`NamedId`] values themselves. These IDs are+/// assigned when [`add_named_to_linker`] is called, for example, as the+/// `lookup` argument to that function.+///+/// When using [`add_named_to_linker`] it's sufficient to implement this trait+/// for the `T` in `Store<T>`.+///+/// When using `add_to_linker` in the generated `bindings::named_imports`+/// module then values implementing this live within the `T` of `Store<T>`, and+/// be temporarily referenced in [`WasiCtxNamedView`] where internally that'll+/// hold `WasiCtxNamedView(&mut your_type)`.+///+/// [`named_imports`]: crate::p3::bindings::named_imports+/// [`add_named_to_linker`]: crate::p3::add_named_to_linker+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component, ResourceTable};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::NamedId;+/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpCtxView, WasiHttpNamedView};+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// table: ResourceTable,+/// states: HashMap<NamedId, WasiHttpCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// wasmtime_wasi_http::p3::add_named_to_linker::<MyStoreState>(+/// &mut linker,+/// &component,+/// |_, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// )?;+/// Ok(())+/// }+///+/// impl WasiHttpNamedView for MyStoreState {+/// fn http(&mut self, id: NamedId) -> WasiHttpCtxView<'_> {+/// let ctx = self.states.get_mut(&id).expect("state for id");+/// WasiHttpCtxView {+/// ctx,+/// table: &mut self.table,+/// hooks: Default::default(),+/// }+/// }+/// }+/// ```+pub trait WasiHttpNamedView: Send + 'static {+ /// Looks up the [`WasiHttpCtxView`] for the given [`NamedId`].+ ///+ /// This method will resolve the `id` specified to a specific HTTP context+ /// that is available to be used. Note that this method is specifically+ /// infallible meaning that an HTTP context must be returned and this cannot+ /// generate a trap or panic or similar.+ ///+ /// Embedders are responsible for allocating [`NamedId`] and assigning+ /// meaning to ids. When a `Linker` is populated embedders will have the+ /// ability to generate a `NamedId` for all imports found, and then that+ /// embedder-allocated id is then passed back here when the corresponding+ /// imported function is invoked.+ ///+ /// Note that the [`ResourceTable`] referenced in the returned+ /// [`WasiHttpCtxView`] need not be unique. It's ok to use the same+ /// [`ResourceTable`] for all imports. This is not a guest-visible+ /// abstraction and just helps the host allocate and manage state.+ fn http(&mut self, id: NamedId) -> WasiHttpCtxView<'_>;+}diff --git a/crates/wasi-http/src/p2/bindings.rs b/crates/wasi-http/src/p2/bindings.rsindex afd4b77ff0..447cbc8621 100644--- a/crates/wasi-http/src/p2/bindings.rs+++ b/crates/wasi-http/src/p2/bindings.rs@@ -33,6 +33,10 @@ mod generated {"wasi:http/types.error-code" => crate::p2::HttpError,"wasi:http/types.header-error" => crate::p2::HeaderError,},+ named_imports: {+ "wasi:http/outgoing-handler": wasmtime_wasi::NamedId,+ "wasi:http/types": wasmtime_wasi::NamedId,+ },});}@@ -41,6 +45,9 @@ pub use self::generated::wasi::*;/// Raw bindings to the `wasi:http/proxy` exports.pub use self::generated::exports;+/// Raw bindings to `wasi:http` interfaces when used as named imports.+pub use self::generated::named_imports;+/// Bindings to the `wasi:http/proxy` world.pub use self::generated::{LinkOptions, Proxy, ProxyIndices, ProxyPre};diff --git a/crates/wasi-http/src/p2/http_impl.rs b/crates/wasi-http/src/p2/http_impl.rsindex d0d1ccedbd..d9b52124a9 100644--- a/crates/wasi-http/src/p2/http_impl.rs+++ b/crates/wasi-http/src/p2/http_impl.rs@@ -118,3 +118,31 @@ impl outgoing_handler::Host for WasiHttpCtxView<'_> {.push(HostFutureIncomingResponse::Pending(future))?)}}++mod named {+ use crate::WasiHttpNamedView;+ use crate::p2::bindings::http::types;+ use crate::p2::bindings::named_imports::wasi::http::outgoing_handler;+ use crate::p2::types::{HostFutureIncomingResponse, HostOutgoingRequest};+ use crate::p2::{HttpError, HttpResult};+ use wasmtime::component::Resource;+ use wasmtime_wasi::{NamedId, WasiCtxNamedView};++ impl<T> outgoing_handler::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn handle(+ &mut self,+ id: NamedId,+ request_id: Resource<HostOutgoingRequest>,+ options: Option<Resource<types::RequestOptions>>,+ ) -> HttpResult<Resource<HostFutureIncomingResponse>> {+ super::outgoing_handler::Host::handle(&mut self.0.http(id), request_id, options)+ }++ fn convert_error_code(&mut self, err: HttpError) -> wasmtime::Result<types::ErrorCode> {+ err.downcast()+ }+ }+}diff --git a/crates/wasi-http/src/p2/mod.rs b/crates/wasi-http/src/p2/mod.rsindex 587be8d1d8..274a42f326 100644--- a/crates/wasi-http/src/p2/mod.rs+++ b/crates/wasi-http/src/p2/mod.rs@@ -226,8 +226,9 @@//! [`ResourceTable`]: wasmtime::component::ResourceTable//! [`default_hooks`]: crate::default_hooks-use crate::{WasiHttp, WasiHttpView};-use wasmtime::component::Linker;+use crate::{WasiHttp, WasiHttpNamed, WasiHttpNamedView, WasiHttpView};+use wasmtime::component::{Component, Linker};+use wasmtime_wasi::{NamedId, WasiCtxNamedView};mod error;mod http_impl;@@ -320,6 +321,140 @@ whereOk(())}+/// Interfaces that are added via [`add_named_to_linker_async`].+#[derive(Copy, Clone, PartialEq, Eq, Debug)]+pub enum Interface {+ /// `wasi:http/outgoing-handler`+ HttpOutgoingHandler,+ /// `wasi:http/types`+ HttpTypes,+}++/// Add all `wasi:http` interfaces from this crate into the `linker` provided+/// for any named imports that a component has.+///+/// This function is similar to [`add_only_http_to_linker_async`] except that+/// it's specifically designed to work with named imports of `wasi:http`+/// interfaces that components may have. This requires a [`Component`] parameter+/// to be passed in when populating the [`Linker`] provided to see what the+/// [`Component`] actually imports.+///+/// Like [`add_only_http_to_linker_async`] this only adds `wasi:http`+/// interfaces, so [`wasmtime_wasi::p2::add_named_to_linker_async`] should+/// additionally be used to bind named imports of the rest of WASI. If this+/// isn't low level enough you can invoke the bindgen-generated `add_to_linker`+/// functions within the [`named_imports`] module directly instead.+///+/// [`wasmtime_wasi::p2::add_named_to_linker_async`]: wasmtime_wasi::p2::add_named_to_linker_async+/// [`named_imports`]: crate::p2::bindings::named_imports+///+/// The `lookup` function provided here is invoked for every named import found+/// for a particular interface. The [`Interface`] given is what's being bound,+/// and the `&str` argument is the name that the component imports it as. The+/// embedder can then decide how it would like to allocate a [`NamedId`] for+/// this import. If `Ok` is returned then the linker is populated with this+/// name, and imported functions will pass the [`NamedId`] later to the+/// implementation of [`WasiHttpNamedView`] on `T` when invoked. If `Err` is+/// returned then the error will cause this entire function to fail and this+/// function call will return the same error.+///+/// # Example+///+/// ```+/// use std::collections::HashMap;+/// use wasmtime::component::{Component, Linker, ResourceTable};+/// use wasmtime::{Engine, Result, Store};+/// use wasmtime_wasi::NamedId;+/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpCtxView, WasiHttpNamedView};+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let component = Component::new(&engine, "(component)")?;+///+/// let mut linker = Linker::<MyState>::new(&engine);+///+/// // ... add default functionality to `linker` as needed ...+///+/// // and then additionally fill in any specific named imports `component`+/// // might have for `wasi:http` interfaces.+/// let mut name_map = HashMap::new();+/// wasmtime_wasi_http::p2::add_named_to_linker_async(&mut linker, &component, |_i, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// })?;+///+/// // Here a `WasiHttpCtx` is allocated per-named-import and will then be+/// // referred to internally by the [`NamedId`] allocated above. You could+/// // also use `name_map` to configure each context differently.+/// let mut my_state = MyState::default();+/// for _ in 0..name_map.len() {+/// my_state.contexts.push(WasiHttpCtx::default());+/// }+/// let mut store = Store::new(&engine, my_state);+///+/// // ... use `linker` to instantiate within `store` ...+///+/// Ok(())+/// }+///+/// #[derive(Default)]+/// struct MyState {+/// table: ResourceTable,+/// contexts: Vec<WasiHttpCtx>,+/// }+///+/// impl WasiHttpNamedView for MyState {+/// fn http(&mut self, id: NamedId) -> WasiHttpCtxView<'_> {+/// WasiHttpCtxView {+/// ctx: &mut self.contexts[id.0],+/// table: &mut self.table,+/// hooks: Default::default(),+/// }+/// }+/// }+/// ```+pub fn add_named_to_linker_async<T>(+ linker: &mut Linker<T>,+ component: &Component,+ lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiHttpNamedView,+{+ let options = bindings::LinkOptions::default(); // FIXME: Thread through to the CLI options.+ add_named_to_linker_with_options_async(linker, &options, component, lookup)+}++/// Same as [`add_named_to_linker_async`] except [`bindings::LinkOptions`] can+/// be specified to configure interfaces that are added.+pub fn add_named_to_linker_with_options_async<T>(+ linker: &mut Linker<T>,+ options: &bindings::LinkOptions,+ component: &Component,+ mut lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiHttpNamedView,+{+ use crate::p2::bindings::named_imports::wasi::http::{outgoing_handler, types};++ let l = linker;+ outgoing_handler::add_to_linker::<_, WasiHttpNamed<T>>(+ l,+ component,+ |name| lookup(Interface::HttpOutgoingHandler, name),+ |x| WasiCtxNamedView(x),+ )?;+ types::add_to_linker::<_, WasiHttpNamed<T>>(+ l,+ component,+ |name| lookup(Interface::HttpTypes, name),+ &options.into(),+ |x| WasiCtxNamedView(x),+ )?;+ Ok(())+}+/// Add all of the `wasi:http/proxy` world's interfaces to a [`wasmtime::component::Linker`].////// This function will add the `sync` variant of all interfaces into thediff --git a/crates/wasi-http/src/p2/types_impl.rs b/crates/wasi-http/src/p2/types_impl.rsindex 4703948bc6..fa00f557ff 100644--- a/crates/wasi-http/src/p2/types_impl.rs+++ b/crates/wasi-http/src/p2/types_impl.rs@@ -771,3 +771,621 @@ impl types::HostRequestOptions for WasiHttpCtxView<'_> {Ok(())}}++mod named {+ use crate::p2::bindings::http::types::{self, Method, Scheme, StatusCode, Trailers};+ use crate::p2::bindings::named_imports::wasi::http::types as named_types;+ use crate::p2::body::{HostFutureTrailers, HostIncomingBody, HostOutgoingBody};+ use crate::p2::types::{+ HostFutureIncomingResponse, HostIncomingRequest, HostIncomingResponse, HostOutgoingRequest,+ HostOutgoingResponse, HostResponseOutparam,+ };+ use crate::p2::{HeaderError, HeaderResult, HttpError, HttpResult};+ use crate::{FieldMap, WasiHttpNamedView};+ use wasmtime::component::Resource;+ use wasmtime_wasi::p2::{DynInputStream, DynOutputStream, DynPollable};+ use wasmtime_wasi::{NamedId, WasiCtxNamedView};++ impl<T> named_types::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn convert_error_code(&mut self, err: HttpError) -> wasmtime::Result<types::ErrorCode> {+ err.downcast()+ }++ fn convert_header_error(+ &mut self,+ err: HeaderError,+ ) -> wasmtime::Result<types::HeaderError> {+ err.downcast()+ }++ fn http_error_code(+ &mut self,+ id: NamedId,+ err: wasmtime::component::Resource<types::IoError>,+ ) -> wasmtime::Result<Option<types::ErrorCode>> {+ super::types::Host::http_error_code(&mut self.0.http(id), err)+ }+ }++ impl<T> named_types::HostFields for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn new(&mut self, id: NamedId) -> wasmtime::Result<Resource<FieldMap>> {+ super::types::HostFields::new(&mut self.0.http(id))+ }++ fn from_list(+ &mut self,+ id: NamedId,+ entries: Vec<(String, Vec<u8>)>,+ ) -> HeaderResult<Resource<FieldMap>> {+ super::types::HostFields::from_list(&mut self.0.http(id), entries)+ }++ fn drop(&mut self, id: NamedId, fields: Resource<FieldMap>) -> wasmtime::Result<()> {+ super::types::HostFields::drop(&mut self.0.http(id), fields)+ }++ fn get(+ &mut self,+ id: NamedId,+ fields: Resource<FieldMap>,+ name: String,+ ) -> wasmtime::Result<Vec<Vec<u8>>> {+ super::types::HostFields::get(&mut self.0.http(id), fields, name)+ }++ fn has(+ &mut self,+ id: NamedId,+ fields: Resource<FieldMap>,+ name: String,+ ) -> wasmtime::Result<bool> {+ super::types::HostFields::has(&mut self.0.http(id), fields, name)+ }++ fn set(+ &mut self,+ id: NamedId,+ fields: Resource<FieldMap>,+ name: String,+ values: Vec<Vec<u8>>,+ ) -> HeaderResult<()> {+ super::types::HostFields::set(&mut self.0.http(id), fields, name, values)+ }++ fn delete(+ &mut self,+ id: NamedId,+ fields: Resource<FieldMap>,+ name: String,+ ) -> HeaderResult<()> {+ super::types::HostFields::delete(&mut self.0.http(id), fields, name)+ }++ fn append(+ &mut self,+ id: NamedId,+ fields: Resource<FieldMap>,+ name: String,+ value: Vec<u8>,+ ) -> HeaderResult<()> {+ super::types::HostFields::append(&mut self.0.http(id), fields, name, value)+ }++ fn entries(+ &mut self,+ id: NamedId,+ fields: Resource<FieldMap>,+ ) -> wasmtime::Result<Vec<(String, Vec<u8>)>> {+ super::types::HostFields::entries(&mut self.0.http(id), fields)+ }++ fn clone(+ &mut self,+ id: NamedId,+ fields: Resource<FieldMap>,+ ) -> wasmtime::Result<Resource<FieldMap>> {+ super::types::HostFields::clone(&mut self.0.http(id), fields)+ }+ }++ impl<T> named_types::HostIncomingRequest for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn method(+ &mut self,+ id: NamedId,+ this: Resource<HostIncomingRequest>,+ ) -> wasmtime::Result<Method> {+ super::types::HostIncomingRequest::method(&mut self.0.http(id), this)+ }++ fn path_with_query(+ &mut self,+ id: NamedId,+ this: Resource<HostIncomingRequest>,+ ) -> wasmtime::Result<Option<String>> {+ super::types::HostIncomingRequest::path_with_query(&mut self.0.http(id), this)+ }++ fn scheme(+ &mut self,+ id: NamedId,+ this: Resource<HostIncomingRequest>,+ ) -> wasmtime::Result<Option<Scheme>> {+ super::types::HostIncomingRequest::scheme(&mut self.0.http(id), this)+ }++ fn authority(+ &mut self,+ id: NamedId,+ this: Resource<HostIncomingRequest>,+ ) -> wasmtime::Result<Option<String>> {+ super::types::HostIncomingRequest::authority(&mut self.0.http(id), this)+ }++ fn headers(+ &mut self,+ id: NamedId,+ this: Resource<HostIncomingRequest>,+ ) -> wasmtime::Result<Resource<FieldMap>> {+ super::types::HostIncomingRequest::headers(&mut self.0.http(id), this)+ }++ fn consume(+ &mut self,+ id: NamedId,+ this: Resource<HostIncomingRequest>,+ ) -> wasmtime::Result<Result<Resource<HostIncomingBody>, ()>> {+ super::types::HostIncomingRequest::consume(&mut self.0.http(id), this)+ }++ fn drop(+ &mut self,+ id: NamedId,+ this: Resource<HostIncomingRequest>,+ ) -> wasmtime::Result<()> {+ super::types::HostIncomingRequest::drop(&mut self.0.http(id), this)+ }+ }++ impl<T> named_types::HostOutgoingRequest for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn new(+ &mut self,+ id: NamedId,+ headers: Resource<FieldMap>,+ ) -> wasmtime::Result<Resource<HostOutgoingRequest>> {+ super::types::HostOutgoingRequest::new(&mut self.0.http(id), headers)+ }++ fn body(+ &mut self,+ id: NamedId,+ request: Resource<HostOutgoingRequest>,+ ) -> wasmtime::Result<Result<Resource<HostOutgoingBody>, ()>> {+ super::types::HostOutgoingRequest::body(&mut self.0.http(id), request)+ }++ fn drop(+ &mut self,+ id: NamedId,+ request: Resource<HostOutgoingRequest>,+ ) -> wasmtime::Result<()> {+ super::types::HostOutgoingRequest::drop(&mut self.0.http(id), request)+ }++ fn method(+ &mut self,+ id: NamedId,+ request: wasmtime::component::Resource<types::OutgoingRequest>,+ ) -> wasmtime::Result<Method> {+ super::types::HostOutgoingRequest::method(&mut self.0.http(id), request)+ }++ fn set_method(+ &mut self,+ id: NamedId,+ request: wasmtime::component::Resource<types::OutgoingRequest>,+ method: Method,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::types::HostOutgoingRequest::set_method(&mut self.0.http(id), request, method)+ }++ fn path_with_query(+ &mut self,+ id: NamedId,+ request: wasmtime::component::Resource<types::OutgoingRequest>,+ ) -> wasmtime::Result<Option<String>> {+ super::types::HostOutgoingRequest::path_with_query(&mut self.0.http(id), request)+ }++ fn set_path_with_query(+ &mut self,+ id: NamedId,+ request: wasmtime::component::Resource<types::OutgoingRequest>,+ path_with_query: Option<String>,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::types::HostOutgoingRequest::set_path_with_query(+ &mut self.0.http(id),+ request,+ path_with_query,+ )+ }++ fn scheme(+ &mut self,+ id: NamedId,+ request: wasmtime::component::Resource<types::OutgoingRequest>,+ ) -> wasmtime::Result<Option<Scheme>> {+ super::types::HostOutgoingRequest::scheme(&mut self.0.http(id), request)+ }++ fn set_scheme(+ &mut self,+ id: NamedId,+ request: wasmtime::component::Resource<types::OutgoingRequest>,+ scheme: Option<Scheme>,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::types::HostOutgoingRequest::set_scheme(&mut self.0.http(id), request, scheme)+ }++ fn authority(+ &mut self,+ id: NamedId,+ request: wasmtime::component::Resource<types::OutgoingRequest>,+ ) -> wasmtime::Result<Option<String>> {+ super::types::HostOutgoingRequest::authority(&mut self.0.http(id), request)+ }++ fn set_authority(+ &mut self,+ id: NamedId,+ request: wasmtime::component::Resource<types::OutgoingRequest>,+ authority: Option<String>,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::types::HostOutgoingRequest::set_authority(+ &mut self.0.http(id),+ request,+ authority,+ )+ }++ fn headers(+ &mut self,+ id: NamedId,+ request: wasmtime::component::Resource<types::OutgoingRequest>,+ ) -> wasmtime::Result<wasmtime::component::Resource<FieldMap>> {+ super::types::HostOutgoingRequest::headers(&mut self.0.http(id), request)+ }+ }++ impl<T> named_types::HostResponseOutparam for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn drop(+ &mut self,+ id: NamedId,+ this: Resource<HostResponseOutparam>,+ ) -> wasmtime::Result<()> {+ super::types::HostResponseOutparam::drop(&mut self.0.http(id), this)+ }++ fn set(+ &mut self,+ id: NamedId,+ this: Resource<HostResponseOutparam>,+ resp: Result<Resource<HostOutgoingResponse>, types::ErrorCode>,+ ) -> wasmtime::Result<()> {+ super::types::HostResponseOutparam::set(&mut self.0.http(id), this, resp)+ }++ fn send_informational(+ &mut self,+ id: NamedId,+ _id: Resource<HostResponseOutparam>,+ _status: u16,+ _headers: Resource<FieldMap>,+ ) -> HttpResult<()> {+ super::types::HostResponseOutparam::send_informational(+ &mut self.0.http(id),+ _id,+ _status,+ _headers,+ )+ }+ }++ impl<T> named_types::HostIncomingResponse for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn drop(+ &mut self,+ id: NamedId,+ response: Resource<HostIncomingResponse>,+ ) -> wasmtime::Result<()> {+ super::types::HostIncomingResponse::drop(&mut self.0.http(id), response)+ }++ fn status(+ &mut self,+ id: NamedId,+ response: Resource<HostIncomingResponse>,+ ) -> wasmtime::Result<StatusCode> {+ super::types::HostIncomingResponse::status(&mut self.0.http(id), response)+ }++ fn headers(+ &mut self,+ id: NamedId,+ response: Resource<HostIncomingResponse>,+ ) -> wasmtime::Result<Resource<FieldMap>> {+ super::types::HostIncomingResponse::headers(&mut self.0.http(id), response)+ }++ fn consume(+ &mut self,+ id: NamedId,+ response: Resource<HostIncomingResponse>,+ ) -> wasmtime::Result<Result<Resource<HostIncomingBody>, ()>> {+ super::types::HostIncomingResponse::consume(&mut self.0.http(id), response)+ }+ }++ impl<T> named_types::HostFutureTrailers for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn drop(+ &mut self,+ id: NamedId,+ this: Resource<HostFutureTrailers>,+ ) -> wasmtime::Result<()> {+ super::types::HostFutureTrailers::drop(&mut self.0.http(id), this)+ }++ fn subscribe(+ &mut self,+ id: NamedId,+ index: Resource<HostFutureTrailers>,+ ) -> wasmtime::Result<Resource<DynPollable>> {+ super::types::HostFutureTrailers::subscribe(&mut self.0.http(id), index)+ }++ fn get(+ &mut self,+ id: NamedId,+ this: Resource<HostFutureTrailers>,+ ) -> wasmtime::Result<+ Option<Result<Result<Option<Resource<Trailers>>, types::ErrorCode>, ()>>,+ > {+ super::types::HostFutureTrailers::get(&mut self.0.http(id), this)+ }+ }++ impl<T> named_types::HostIncomingBody for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn stream(+ &mut self,+ id: NamedId,+ this: Resource<HostIncomingBody>,+ ) -> wasmtime::Result<Result<Resource<DynInputStream>, ()>> {+ super::types::HostIncomingBody::stream(&mut self.0.http(id), this)+ }++ fn finish(+ &mut self,+ id: NamedId,+ this: Resource<HostIncomingBody>,+ ) -> wasmtime::Result<Resource<HostFutureTrailers>> {+ super::types::HostIncomingBody::finish(&mut self.0.http(id), this)+ }++ fn drop(&mut self, id: NamedId, this: Resource<HostIncomingBody>) -> wasmtime::Result<()> {+ super::types::HostIncomingBody::drop(&mut self.0.http(id), this)+ }+ }++ impl<T> named_types::HostOutgoingResponse for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn new(+ &mut self,+ id: NamedId,+ headers: Resource<FieldMap>,+ ) -> wasmtime::Result<Resource<HostOutgoingResponse>> {+ super::types::HostOutgoingResponse::new(&mut self.0.http(id), headers)+ }++ fn body(+ &mut self,+ id: NamedId,+ this: Resource<HostOutgoingResponse>,+ ) -> wasmtime::Result<Result<Resource<HostOutgoingBody>, ()>> {+ super::types::HostOutgoingResponse::body(&mut self.0.http(id), this)+ }++ fn status_code(+ &mut self,+ id: NamedId,+ this: Resource<HostOutgoingResponse>,+ ) -> wasmtime::Result<types::StatusCode> {+ super::types::HostOutgoingResponse::status_code(&mut self.0.http(id), this)+ }++ fn set_status_code(+ &mut self,+ id: NamedId,+ this: Resource<HostOutgoingResponse>,+ status: types::StatusCode,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::types::HostOutgoingResponse::set_status_code(&mut self.0.http(id), this, status)+ }++ fn headers(+ &mut self,+ id: NamedId,+ this: Resource<HostOutgoingResponse>,+ ) -> wasmtime::Result<Resource<FieldMap>> {+ super::types::HostOutgoingResponse::headers(&mut self.0.http(id), this)+ }++ fn drop(+ &mut self,+ id: NamedId,+ this: Resource<HostOutgoingResponse>,+ ) -> wasmtime::Result<()> {+ super::types::HostOutgoingResponse::drop(&mut self.0.http(id), this)+ }+ }++ impl<T> named_types::HostFutureIncomingResponse for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn drop(+ &mut self,+ id: NamedId,+ this: Resource<HostFutureIncomingResponse>,+ ) -> wasmtime::Result<()> {+ super::types::HostFutureIncomingResponse::drop(&mut self.0.http(id), this)+ }++ fn get(+ &mut self,+ id: NamedId,+ this: Resource<HostFutureIncomingResponse>,+ ) -> wasmtime::Result<+ Option<Result<Result<Resource<HostIncomingResponse>, types::ErrorCode>, ()>>,+ > {+ super::types::HostFutureIncomingResponse::get(&mut self.0.http(id), this)+ }++ fn subscribe(+ &mut self,+ id: NamedId,+ this: Resource<HostFutureIncomingResponse>,+ ) -> wasmtime::Result<Resource<DynPollable>> {+ super::types::HostFutureIncomingResponse::subscribe(&mut self.0.http(id), this)+ }+ }++ impl<T> named_types::HostOutgoingBody for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn write(+ &mut self,+ id: NamedId,+ this: Resource<HostOutgoingBody>,+ ) -> wasmtime::Result<Result<Resource<DynOutputStream>, ()>> {+ super::types::HostOutgoingBody::write(&mut self.0.http(id), this)+ }++ fn finish(+ &mut self,+ id: NamedId,+ this: Resource<HostOutgoingBody>,+ ts: Option<Resource<Trailers>>,+ ) -> HttpResult<()> {+ super::types::HostOutgoingBody::finish(&mut self.0.http(id), this, ts)+ }++ fn drop(&mut self, id: NamedId, this: Resource<HostOutgoingBody>) -> wasmtime::Result<()> {+ super::types::HostOutgoingBody::drop(&mut self.0.http(id), this)+ }+ }++ impl<T> named_types::HostRequestOptions for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn new(&mut self, id: NamedId) -> wasmtime::Result<Resource<types::RequestOptions>> {+ super::types::HostRequestOptions::new(&mut self.0.http(id))+ }++ fn connect_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<types::RequestOptions>,+ ) -> wasmtime::Result<Option<types::Duration>> {+ super::types::HostRequestOptions::connect_timeout(&mut self.0.http(id), opts)+ }++ fn set_connect_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<types::RequestOptions>,+ duration: Option<types::Duration>,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::types::HostRequestOptions::set_connect_timeout(+ &mut self.0.http(id),+ opts,+ duration,+ )+ }++ fn first_byte_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<types::RequestOptions>,+ ) -> wasmtime::Result<Option<types::Duration>> {+ super::types::HostRequestOptions::first_byte_timeout(&mut self.0.http(id), opts)+ }++ fn set_first_byte_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<types::RequestOptions>,+ duration: Option<types::Duration>,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::types::HostRequestOptions::set_first_byte_timeout(+ &mut self.0.http(id),+ opts,+ duration,+ )+ }++ fn between_bytes_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<types::RequestOptions>,+ ) -> wasmtime::Result<Option<types::Duration>> {+ super::types::HostRequestOptions::between_bytes_timeout(&mut self.0.http(id), opts)+ }++ fn set_between_bytes_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<types::RequestOptions>,+ duration: Option<types::Duration>,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::types::HostRequestOptions::set_between_bytes_timeout(+ &mut self.0.http(id),+ opts,+ duration,+ )+ }++ fn drop(+ &mut self,+ id: NamedId,+ rep: Resource<types::RequestOptions>,+ ) -> wasmtime::Result<()> {+ super::types::HostRequestOptions::drop(&mut self.0.http(id), rep)+ }+ }+}diff --git a/crates/wasi-http/src/p3/bindings.rs b/crates/wasi-http/src/p3/bindings.rsindex 340b2cb7f8..b82c53b621 100644--- a/crates/wasi-http/src/p3/bindings.rs+++ b/crates/wasi-http/src/p3/bindings.rs@@ -27,6 +27,10 @@ mod generated {"wasi:http/types.header-error" => crate::p3::HeaderError,"wasi:http/types.request-options-error" => crate::p3::RequestOptionsError,},+ named_imports: {+ "wasi:http/client": wasmtime_wasi::NamedId,+ "wasi:http/types": wasmtime_wasi::NamedId,+ },});mod with {@@ -40,5 +44,8 @@ pub use self::generated::wasi::*;/// Raw bindings to the `wasi:http/service` exports.pub use self::generated::exports;+/// Raw bindings to `wasi:http` interfaces when used as named imports.+pub use self::generated::named_imports;+/// Bindings to the `wasi:http/service` world.pub use self::generated::{Service, ServiceIndices, ServicePre};diff --git a/crates/wasi-http/src/p3/body.rs b/crates/wasi-http/src/p3/body.rsindex 4712aa9905..1279212a3f 100644--- a/crates/wasi-http/src/p3/body.rs+++ b/crates/wasi-http/src/p3/body.rs@@ -1,11 +1,12 @@use crate::p3::bindings::http::types::{ErrorCode, Trailers};use crate::p3::helpers::FutureReaderExt;-use crate::{Error, FieldMap, WasiHttp, WasiHttpCtxView};+use crate::{Error, FieldMap, WasiHttpCtxView};use bytes::Bytes;use core::iter;use core::num::NonZeroUsize;use core::pin::Pin;use core::task::{Context, Poll, ready};+use http::HeaderMap;use http_body::Body as _;use http_body_util::combinators::UnsyncBoxBody;use std::any::{Any, TypeId};@@ -14,8 +15,8 @@ use std::sync::Arc;use tokio::sync::{mpsc, oneshot};use tokio_util::sync::PollSender;use wasmtime::component::{- Access, Destination, FutureReader, Resource, Source, StreamConsumer, StreamProducer,- StreamReader, StreamResult,+ Destination, FutureReader, Resource, Source, StreamConsumer, StreamProducer, StreamReader,+ StreamResult,};use wasmtime::error::Context as _;use wasmtime::{AsContextMut, StoreContextMut};@@ -51,19 +52,22 @@ async fn guest_body_result<E>(}impl Body {- pub(crate) fn new_guest<T>(- store: &mut Access<'_, T, WasiHttp>,+ pub(crate) fn new_guest<S>(+ mut store: S,+ mut getter: impl FnMut(&mut S::Data) -> WasiHttpCtxView<'_> + Send + 'static,contents: Option<StreamReader<u8>>,mut trailers: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,- ) -> wasmtime::Result<(Self, FutureReader<Result<(), ErrorCode>>)> {- let getter = store.getter();+ ) -> wasmtime::Result<(Self, FutureReader<Result<(), ErrorCode>>)>+ where+ S: AsContextMut,+ {// Attempt to unwrap this guest-specified body stream as a host-owned// stream. That helps bypass a layer of indirection where possible.let contents = match contents- .map(|rx| rx.try_into::<HostBodyStreamProducer<T>>(&mut *store))+ .map(|rx| rx.try_into::<HostBodyStreamProducer>(store.as_context_mut())){Some(Ok(mut producer)) => {- trailers.close(&mut *store)?;+ trailers.close(store.as_context_mut())?;let (result_tx, result_rx) = oneshot::channel();let body = Body::Host {body: mem::take(&mut producer.body),@@ -72,9 +76,11 @@ impl Body {return Ok((body,FutureReader::new_cb(- &mut *store,+ store.as_context_mut(),guest_body_result(result_rx),- move |d, res: Result<_, Error>| res.map_err(|e| getter(d).error_to_p3(&e)),+ move |d, res: Result<_, Error>| {+ Ok(res.map_err(|e| getter(d).error_to_p3(&e)))+ },)?,));}@@ -90,23 +96,26 @@ impl Body {Ok((body,FutureReader::new_cb(- &mut *store,+ store.as_context_mut(),guest_body_result(result_rx),- move |d, res: Result<_, Error>| res.map_err(|e| getter(d).error_to_p3(&e)),+ move |d, res: Result<_, Error>| Ok(res.map_err(|e| getter(d).error_to_p3(&e))),)?,))}/// Implementation of `consume-body` shared between requests and responses- pub(crate) fn consume<T>(+ pub(crate) fn consume<S>(self,- mut store: Access<'_, T, WasiHttp>,+ mut store: S,fut: FutureReader<Result<(), ErrorCode>>,- getter: fn(&mut T) -> WasiHttpCtxView<'_>,+ mut getter: impl FnMut(&mut S::Data) -> WasiHttpCtxView<'_> + Send + 'static,) -> wasmtime::Result<(StreamReader<u8>,FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,- )> {+ )>+ where+ S: AsContextMut,+ {let (contents_rx, trailers_rx) = match self {Body::Guest {contents_rx,@@ -115,34 +124,42 @@ impl Body {} => {let body = match contents_rx {Some(stream) => stream,- None => StreamReader::new(&mut store, iter::empty())?,+ None => StreamReader::new(store.as_context_mut(), iter::empty())?,};- fut.pipe_cb(&mut store, |_, res| {+ fut.pipe_cb(store.as_context_mut(), |_, res| {_ = result_tx.send(Box::new(async { res.map_err(|e| e.into()) }));Ok(())})?;(body, trailers_rx)}Body::Host { body, result_tx } => {- fut.pipe_cb(&mut store, |_, res| {+ fut.pipe_cb(store.as_context_mut(), |_, res| {_ = result_tx.send(Box::new(async { res.map_err(|e| e.into()) }));Ok(())})?;let (trailers_tx, trailers_rx) = oneshot::channel();(StreamReader::new(- &mut store,+ store.as_context_mut(),HostBodyStreamProducer {body,trailers: Some(trailers_tx),- getter,},)?,- FutureReader::new_cb(- &mut store,- trailers_rx,- move |d, res: Result<_, Error>| res.map_err(|e| getter(d).error_to_p3(&e)),- )?,+ FutureReader::new_cb(store.as_context_mut(), trailers_rx, move |d, res| {+ let mut view = getter(d);+ let trailers = match res {+ Ok(Some(trailers)) => trailers,+ Ok(None) => return Ok(Ok(None)),+ Err(e) => return Ok(Err(view.error_to_p3(&e))),+ };+ let trailers = FieldMap::new_immutable(view.hooks, trailers);+ let trailers = view+ .table+ .push(trailers)+ .context("failed to push trailers to table")?;+ Ok(Ok(Some(trailers)))+ })?,)}};@@ -315,8 +332,13 @@ impl GuestBody {result_fut: impl Future<Output = Result<(), Error>> + Send + 'static,content_length: Option<u64>,make_error: fn(Option<u64>) -> ErrorCode,- getter: fn(&mut T) -> WasiHttpCtxView<'_>,+ mut getter: impl FnMut(&mut T) -> WasiHttpCtxView<'_> + Unpin + Send + 'static,) -> wasmtime::Result<Self> {+ let max_chunk_size = getter(store.as_context_mut().data_mut())+ .hooks+ .p3_outgoing_body_chunk_size()+ .max(1);+let (trailers_http_tx, trailers_http_rx) = oneshot::channel();trailers_rx.pipe_cb(&mut store, move |data, res| {let res = match res {@@ -334,11 +356,6 @@ impl GuestBody {Ok(())})?;- let max_chunk_size = getter(store.as_context_mut().data_mut())- .hooks- .p3_outgoing_body_chunk_size()- .max(1);-let contents_rx = if let Some(rx) = contents_rx {let (http_tx, http_rx) = mpsc::channel(1);let contents_tx = PollSender::new(http_tx);@@ -465,27 +482,26 @@ impl http_body::Body for GuestBody {}/// [StreamProducer] implementation for bodies originating in the host.-pub(crate) struct HostBodyStreamProducer<T> {+pub(crate) struct HostBodyStreamProducer {pub(crate) body: UnsyncBoxBody<Bytes, Error>,- trailers: Option<oneshot::Sender<Result<Option<Resource<Trailers>>, Error>>>,- getter: fn(&mut T) -> WasiHttpCtxView<'_>,+ trailers: Option<oneshot::Sender<Result<Option<HeaderMap>, Error>>>,}-impl<T> Drop for HostBodyStreamProducer<T> {+impl Drop for HostBodyStreamProducer {fn drop(&mut self) {self.close(Ok(None))}}-impl<T> HostBodyStreamProducer<T> {- fn close(&mut self, res: Result<Option<Resource<Trailers>>, Error>) {+impl HostBodyStreamProducer {+ fn close(&mut self, res: Result<Option<HeaderMap>, Error>) {if let Some(tx) = self.trailers.take() {_ = tx.send(res);}}}-impl<D> StreamProducer<D> for HostBodyStreamProducer<D>+impl<D> StreamProducer<D> for HostBodyStreamProducerwhereD: 'static,{@@ -552,15 +568,7 @@ where}return Poll::Ready(Ok(StreamResult::Completed));}- Err(Ok(trailers)) => {- let view = (self.getter)(store.data_mut());- let trailers = FieldMap::new_immutable(view.hooks, trailers);- let trailers = view- .table- .push(trailers)- .context("failed to push trailers to table")?;- break 'result Ok(Some(trailers));- }+ Err(Ok(trailers)) => break 'result Ok(Some(trailers)),Err(Err(..)) => break 'result Err(Error::HttpProtocolError),}}diff --git a/crates/wasi-http/src/p3/helpers.rs b/crates/wasi-http/src/p3/helpers.rsindex 35e59ff574..66efb5b18a 100644--- a/crates/wasi-http/src/p3/helpers.rs+++ b/crates/wasi-http/src/p3/helpers.rs@@ -70,7 +70,7 @@ pub trait FutureReaderExt<T> {fn new_cb<U, S, E>(store: S,future: impl Future<Output = Result<U, E>> + Send + 'static,- cb: impl FnOnce(&mut S::Data, U) -> T + Send + 'static,+ cb: impl FnOnce(&mut S::Data, U) -> wasmtime::Result<T> + Send + 'static,) -> wasmtime::Result<FutureReader<T>>whereS: AsContextMut,@@ -89,7 +89,7 @@ pub trait FutureReaderExt<T> {impl<F, C, D, T, U, E> FutureProducer<D> for Producer<F, C, D, T>whereF: Future<Output = Result<U, E>> + Send + 'static,- C: FnOnce(&mut D, U) -> T + Send + 'static,+ C: FnOnce(&mut D, U) -> wasmtime::Result<T> + Send + 'static,D: 'static,T: 'static,E: Into<wasmtime::Error>,@@ -115,7 +115,7 @@ pub trait FutureReaderExt<T> {}};let cb = this.cb.take().context("polled after returning `Ready`")?;- let res = cb(store.data_mut(), res);+ let res = cb(store.data_mut(), res)?;Poll::Ready(Ok(Some(res)))}}diff --git a/crates/wasi-http/src/p3/host/handler.rs b/crates/wasi-http/src/p3/host/handler.rsindex 3b3fc42516..6a4633c836 100644--- a/crates/wasi-http/src/p3/host/handler.rs+++ b/crates/wasi-http/src/p3/host/handler.rs@@ -10,7 +10,8 @@ use std::sync::Arc;use tokio::sync::oneshot;use tokio::task::{self, JoinHandle};use tracing::debug;-use wasmtime::component::{Accessor, Resource};+use wasmtime::AsContextMut as _;+use wasmtime::component::{Accessor, HasData, Resource};use wasmtime::error::Context as _;/// A wrapper around [`JoinHandle`], which will [`JoinHandle::abort`] the task@@ -52,15 +53,20 @@ fn send_dummy_io(let _ = io_result_tx.send((None, rx));}-fn send_dummy_io_err<T>(- store: &Accessor<T, WasiHttp>,+fn send_dummy_io_err<T, D>(+ store: &Accessor<T, D>,+ mut getter: impl FnMut(&mut T) -> WasiHttpCtxView<'_>,e: Error,io_result_tx: oneshot::Sender<(Option<Arc<AbortOnDropJoinHandle>>,oneshot::Receiver<Result<(), Error>>,)>,-) -> HttpError {- let err_code = store.with(|mut store| store.get().error_to_p3(&e));+) -> HttpError+where+ D: HasData,+{+ let err_code =+ store.with(|mut store| getter(store.as_context_mut().data_mut()).error_to_p3(&e));send_dummy_io(Err(e), io_result_tx);err_code.into()}@@ -70,107 +76,151 @@ impl<T> HostWithStore<T> for WasiHttp {store: &Accessor<T, Self>,req: Resource<Request>,) -> HttpResult<Resource<Response>> {- // A handle to the I/O task, if spawned, will be sent on this channel- // and kept as part of request body state- let (io_task_tx, io_task_rx) = oneshot::channel();+ let getter = store.getter();+ send(store, getter, req).await+ }+}- // A handle to the I/O task, if spawned, will be sent on this channel- // along with the result receiver- let (io_result_tx, io_result_rx) = oneshot::channel();+async fn send<T, D>(+ store: &Accessor<T, D>,+ mut getter: impl FnMut(&mut T) -> WasiHttpCtxView<'_> + Copy + Unpin + Send + 'static,+ req: Resource<Request>,+) -> HttpResult<Resource<Response>>+where+ D: HasData,+ T: 'static,+{+ // A handle to the I/O task, if spawned, will be sent on this channel+ // and kept as part of request body state+ let (io_task_tx, io_task_rx) = oneshot::channel();- // Response processing result will be sent on this channel- let (res_result_tx, res_result_rx) = oneshot::channel();+ // A handle to the I/O task, if spawned, will be sent on this channel+ // along with the result receiver+ let (io_result_tx, io_result_rx) = oneshot::channel();- let getter = store.getter();- let fut = store.with(|mut store| {- let WasiHttpCtxView { table, .. } = store.get();- let req = table- .delete(req)- .context("failed to delete request from table")- .map_err(HttpError::trap)?;- let (req, options) =- req.into_http_with_getter(&mut store, io_task_result(io_result_rx), getter)?;- HttpResult::Ok(store.get().hooks.send_request(- // Attach a reference to the io task to the body so that it- // isn't cancelled if the body is dropped.- req.map(|body| body.with_state(io_task_rx).boxed_unsync()),- options.as_deref().copied(),- Box::new(async {- // Forward the response processing result to `WasiHttpCtx` implementation- let Ok(fut) = res_result_rx.await else {- return Ok(());- };- Box::into_pin(fut).await- }),- ))- });- let fut = match fut {- Ok(fut) => fut,- Err(e) => match e.downcast() {- Ok(err_code) => {- send_dummy_io(Err(err_code.clone().into()), io_result_tx);- return Err(err_code.into());- }- Err(e) => {- let e = Error::InternalError(Some(format!("{e}")));- return Err(send_dummy_io_err(store, e, io_result_tx));- }- },- };- let (res, io) = match Box::into_pin(fut).await {- Ok(r) => r,+ // Response processing result will be sent on this channel+ let (res_result_tx, res_result_rx) = oneshot::channel();++ let fut = store.with(|mut store| {+ let WasiHttpCtxView { table, .. } = getter(store.data_mut());+ let req = table+ .delete(req)+ .context("failed to delete request from table")+ .map_err(HttpError::trap)?;+ let (req, options) =+ req.into_http_with_getter(&mut store, io_task_result(io_result_rx), getter)?;+ HttpResult::Ok(getter(store.data_mut()).hooks.send_request(+ // Attach a reference to the io task to the body so that it+ // isn't cancelled if the body is dropped.+ req.map(|body| body.with_state(io_task_rx).boxed_unsync()),+ options.as_deref().copied(),+ Box::new(async {+ // Forward the response processing result to `WasiHttpCtx` implementation+ let Ok(fut) = res_result_rx.await else {+ return Ok(());+ };+ Box::into_pin(fut).await+ }),+ ))+ });+ let fut = match fut {+ Ok(fut) => fut,+ Err(e) => match e.downcast() {+ Ok(err_code) => {+ send_dummy_io(Err(err_code.clone().into()), io_result_tx);+ return Err(err_code.into());+ }Err(e) => {- return Err(send_dummy_io_err(store, e, io_result_tx));+ let e = Error::InternalError(Some(format!("{e}")));+ return Err(send_dummy_io_err(store, getter, e, io_result_tx));}- };- let (- http::response::Parts {- status, headers, ..+ },+ };+ let (res, io) = match Box::into_pin(fut).await {+ Ok(r) => r,+ Err(e) => {+ return Err(send_dummy_io_err(store, getter, e, io_result_tx));+ }+ };+ let (+ http::response::Parts {+ status, headers, ..+ },+ body,+ ) = res.into_parts();++ let mut io = Box::into_pin(io);+ let body = match io.as_mut().poll(&mut Context::from_waker(Waker::noop())) {+ Poll::Ready(Ok(())) => {+ send_dummy_io(Ok(()), io_result_tx);+ body+ }+ Poll::Ready(Err(e)) => {+ return Err(send_dummy_io_err(store, getter, e, io_result_tx));+ }+ Poll::Pending => {+ // I/O driver still needs to be polled, spawn a task and send handles to it+ let (tx, rx) = oneshot::channel();+ let io = Arc::new(AbortOnDropJoinHandle(task::spawn(async move {+ let res = io.await;+ debug!(?res, "`send_request` I/O future finished");+ _ = tx.send(res);+ })));+ _ = io_result_tx.send((Some(Arc::clone(&io)), rx));+ _ = io_task_tx.send(Arc::clone(&io));+ // Attach a reference to the io task to the body so that it+ // isn't cancelled if the body is dropped.+ body.with_state(io).boxed_unsync()+ }+ };+ store.with(|mut store| {+ let view = getter(store.data_mut());+ let res = Response {+ status,+ headers: FieldMap::new_immutable(view.hooks, headers),+ body: Body::Host {+ body,+ result_tx: res_result_tx,},- body,- ) = res.into_parts();-- let mut io = Box::into_pin(io);- let body = match io.as_mut().poll(&mut Context::from_waker(Waker::noop())) {- Poll::Ready(Ok(())) => {- send_dummy_io(Ok(()), io_result_tx);- body- }- Poll::Ready(Err(e)) => {- return Err(send_dummy_io_err(store, e, io_result_tx));- }- Poll::Pending => {- // I/O driver still needs to be polled, spawn a task and send handles to it- let (tx, rx) = oneshot::channel();- let io = Arc::new(AbortOnDropJoinHandle(task::spawn(async move {- let res = io.await;- debug!(?res, "`send_request` I/O future finished");- _ = tx.send(res);- })));- _ = io_result_tx.send((Some(Arc::clone(&io)), rx));- _ = io_task_tx.send(Arc::clone(&io));- // Attach a reference to the io task to the body so that it- // isn't cancelled if the body is dropped.- body.with_state(io).boxed_unsync()- }};- store.with(|mut store| {- let res = Response {- status,- headers: FieldMap::new_immutable(store.get().hooks, headers),- body: Body::Host {- body,- result_tx: res_result_tx,- },- };- store- .get()- .table- .push(res)- .context("failed to push response to table")- .map_err(HttpError::trap)- })- }+ view.table+ .push(res)+ .context("failed to push response to table")+ .map_err(HttpError::trap)+ })}impl Host for WasiHttpCtxView<'_> {}++mod named {+ use crate::p3::bindings::http::types::{ErrorCode, Request, Response};+ use crate::p3::bindings::named_imports::wasi::http::client::{Host, HostWithStore};+ use crate::p3::{HttpError, HttpResult};+ use crate::{WasiHttpNamed, WasiHttpNamedView};+ use wasmtime::component::{Accessor, Resource};+ use wasmtime_wasi::{NamedId, WasiCtxNamedView};++ impl<T, U> HostWithStore<U> for WasiHttpNamed<T>+ where+ T: WasiHttpNamedView,+ U: 'static,+ {+ async fn send(+ store: &Accessor<U, Self>,+ id: NamedId,+ req: Resource<Request>,+ ) -> HttpResult<Resource<Response>> {+ let getter = store.getter();+ super::send(store, move |data| getter(data).0.http(id), req).await+ }+ }++ impl<T> Host for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn convert_error_code(&mut self, error: HttpError) -> wasmtime::Result<ErrorCode> {+ error.downcast()+ }+ }+}diff --git a/crates/wasi-http/src/p3/host/types.rs b/crates/wasi-http/src/p3/host/types.rsindex 036c656c70..e8aeaa5349 100644--- a/crates/wasi-http/src/p3/host/types.rs+++ b/crates/wasi-http/src/p3/host/types.rs@@ -9,6 +9,7 @@ use crate::p3::body::Body;use crate::p3::{HeaderResult, HttpError, RequestOptionsResult};use crate::{WasiHttp, WasiHttpCtxView};use std::sync::Arc;+use wasmtime::AsContextMut;use wasmtime::component::{Access, FutureReader, Resource, ResourceTable, StreamReader};use wasmtime::error::Context as _;@@ -212,31 +213,50 @@ impl HostFields for WasiHttpCtxView<'_> {}}+fn new_request<S>(+ mut store: S,+ mut getter: impl FnMut(&mut S::Data) -> WasiHttpCtxView<'_> + Copy + Send + 'static,+ headers: Resource<Headers>,+ contents: Option<StreamReader<u8>>,+ trailers: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,+ options: Option<Resource<RequestOptions>>,+) -> wasmtime::Result<(Resource<Request>, FutureReader<Result<(), ErrorCode>>)>+where+ S: AsContextMut,+{+ let mut store = store.as_context_mut();+ let (body, body_result) = Body::new_guest(&mut store, getter, contents, trailers)?;+ let cx = getter(store.data_mut());+ let headers = delete_fields(cx.table, headers)?;+ let options = options+ .map(|options| delete_request_options(cx.table, options))+ .transpose()?;+ let req = Request {+ method: http::Method::GET,+ scheme: None,+ authority: None,+ path_with_query: None,+ headers,+ options: options.map(Into::into),+ body,+ };+ let req = cx+ .table+ .push(req)+ .context("failed to push request to table")?;+ Ok((req, body_result))+}+impl<T> HostRequestWithStore<T> for WasiHttp {fn new(- mut store: Access<T, Self>,+ store: Access<T, Self>,headers: Resource<Headers>,contents: Option<StreamReader<u8>>,trailers: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,options: Option<Resource<RequestOptions>>,) -> wasmtime::Result<(Resource<Request>, FutureReader<Result<(), ErrorCode>>)> {- let (body, body_result) = Body::new_guest(&mut store, contents, trailers)?;- let WasiHttpCtxView { table, .. } = store.get();- let headers = delete_fields(table, headers)?;- let options = options- .map(|options| delete_request_options(table, options))- .transpose()?;- let req = Request {- method: http::Method::GET,- scheme: None,- authority: None,- path_with_query: None,- headers,- options: options.map(Into::into),- body,- };- let req = table.push(req).context("failed to push request to table")?;- Ok((req, body_result))+ let getter = store.getter();+ new_request(store, getter, headers, contents, trailers, options)}fn consume_body(@@ -248,20 +268,12 @@ impl<T> HostRequestWithStore<T> for WasiHttp {FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,)> {let getter = store.getter();- let Request { body, .. } = store- .get()- .table- .delete(req)- .context("failed to delete request from table")?;+ let Request { body, .. } = store.get().table.delete(req)?;body.consume(store, fut, getter)}fn drop(mut store: Access<'_, T, Self>, req: Resource<Request>) -> wasmtime::Result<()> {- let Request { body, .. } = store- .get()- .table- .delete(req)- .context("failed to delete request from table")?;+ let Request { body, .. } = store.get().table.delete(req)?;body.drop(store)?;Ok(())}@@ -470,25 +482,38 @@ impl HostRequestOptions for WasiHttpCtxView<'_> {}}+fn new_response<S>(+ mut store: S,+ mut getter: impl FnMut(&mut S::Data) -> WasiHttpCtxView<'_> + Copy + Send + 'static,+ headers: Resource<Headers>,+ contents: Option<StreamReader<u8>>,+ trailers: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,+) -> wasmtime::Result<(Resource<Response>, FutureReader<Result<(), ErrorCode>>)>+where+ S: AsContextMut,+{+ let mut store = store.as_context_mut();+ let (body, body_result) = Body::new_guest(&mut store, getter, contents, trailers)?;+ let cx = getter(store.data_mut());+ let headers = delete_fields(cx.table, headers)?;+ let res = Response {+ status: http::StatusCode::OK,+ headers,+ body,+ };+ let res = cx.table.push(res)?;+ Ok((res, body_result))+}+impl<T> HostResponseWithStore<T> for WasiHttp {fn new(- mut store: Access<T, Self>,+ store: Access<T, Self>,headers: Resource<Headers>,contents: Option<StreamReader<u8>>,trailers: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,) -> wasmtime::Result<(Resource<Response>, FutureReader<Result<(), ErrorCode>>)> {- let (body, body_result) = Body::new_guest(&mut store, contents, trailers)?;- let WasiHttpCtxView { table, .. } = store.get();- let headers = delete_fields(table, headers)?;- let res = Response {- status: http::StatusCode::OK,- headers,- body,- };- let res = table- .push(res)- .context("failed to push response to table")?;- Ok((res, body_result))+ let getter = store.getter();+ new_response(store, getter, headers, contents, trailers)}fn consume_body(@@ -500,20 +525,12 @@ impl<T> HostResponseWithStore<T> for WasiHttp {FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,)> {let getter = store.getter();- let Response { body, .. } = store- .get()- .table- .delete(res)- .context("failed to delete response from table")?;+ let Response { body, .. } = store.get().table.delete(res)?;body.consume(store, fut, getter)}fn drop(mut store: Access<'_, T, Self>, res: Resource<Response>) -> wasmtime::Result<()> {- let Response { body, .. } = store- .get()- .table- .delete(res)- .context("failed to delete response from table")?;+ let Response { body, .. } = store.get().table.delete(res)?;body.drop(store)?;Ok(())}@@ -565,3 +582,419 @@ impl Host for WasiHttpCtxView<'_> {error.downcast()}}++mod named {+ use crate::p3::bindings::clocks::monotonic_clock::Duration;+ use crate::p3::bindings::http::types::{+ ErrorCode, FieldName, FieldValue, Fields, HeaderError, Headers, Method, Request,+ RequestOptions, RequestOptionsError, Response, Scheme, StatusCode, Trailers,+ };+ use crate::p3::bindings::named_imports::wasi::http::types;+ use crate::p3::{HeaderResult, HttpError, RequestOptionsResult};+ use crate::{WasiHttpNamed, WasiHttpNamedView};+ use wasmtime::component::{Access, FutureReader, Resource, StreamReader};+ use wasmtime_wasi::{NamedId, WasiCtxNamedView};++ impl<T> types::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn convert_error_code(&mut self, error: HttpError) -> wasmtime::Result<ErrorCode> {+ error.downcast()+ }++ fn convert_header_error(+ &mut self,+ error: crate::p3::HeaderError,+ ) -> wasmtime::Result<HeaderError> {+ error.downcast()+ }++ fn convert_request_options_error(+ &mut self,+ error: crate::p3::RequestOptionsError,+ ) -> wasmtime::Result<RequestOptionsError> {+ error.downcast()+ }+ }++ impl<T> types::HostFields for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn new(&mut self, id: NamedId) -> wasmtime::Result<Resource<Fields>> {+ super::HostFields::new(&mut self.0.http(id))+ }++ fn from_list(+ &mut self,+ id: NamedId,+ entries: Vec<(FieldName, FieldValue)>,+ ) -> HeaderResult<Resource<Fields>> {+ super::HostFields::from_list(&mut self.0.http(id), entries)+ }++ fn get(+ &mut self,+ id: NamedId,+ fields: Resource<Fields>,+ name: FieldName,+ ) -> wasmtime::Result<Vec<FieldValue>> {+ super::HostFields::get(&mut self.0.http(id), fields, name)+ }++ fn has(+ &mut self,+ id: NamedId,+ fields: Resource<Fields>,+ name: FieldName,+ ) -> wasmtime::Result<bool> {+ super::HostFields::has(&mut self.0.http(id), fields, name)+ }++ fn set(+ &mut self,+ id: NamedId,+ fields: Resource<Fields>,+ name: FieldName,+ values: Vec<FieldValue>,+ ) -> HeaderResult<()> {+ super::HostFields::set(&mut self.0.http(id), fields, name, values)+ }++ fn delete(+ &mut self,+ id: NamedId,+ fields: Resource<Fields>,+ name: FieldName,+ ) -> HeaderResult<()> {+ super::HostFields::delete(&mut self.0.http(id), fields, name)+ }++ fn get_and_delete(+ &mut self,+ id: NamedId,+ fields: Resource<Fields>,+ name: FieldName,+ ) -> HeaderResult<Vec<FieldValue>> {+ super::HostFields::get_and_delete(&mut self.0.http(id), fields, name)+ }++ fn append(+ &mut self,+ id: NamedId,+ fields: Resource<Fields>,+ name: FieldName,+ value: FieldValue,+ ) -> HeaderResult<()> {+ super::HostFields::append(&mut self.0.http(id), fields, name, value)+ }++ fn copy_all(+ &mut self,+ id: NamedId,+ fields: Resource<Fields>,+ ) -> wasmtime::Result<Vec<(FieldName, FieldValue)>> {+ super::HostFields::copy_all(&mut self.0.http(id), fields)+ }++ fn clone(+ &mut self,+ id: NamedId,+ fields: Resource<Fields>,+ ) -> wasmtime::Result<Resource<Fields>> {+ super::HostFields::clone(&mut self.0.http(id), fields)+ }++ fn drop(&mut self, id: NamedId, fields: Resource<Fields>) -> wasmtime::Result<()> {+ super::HostFields::drop(&mut self.0.http(id), fields)+ }+ }++ impl<T> types::HostRequest for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn get_method(&mut self, id: NamedId, req: Resource<Request>) -> wasmtime::Result<Method> {+ super::HostRequest::get_method(&mut self.0.http(id), req)+ }++ fn set_method(+ &mut self,+ id: NamedId,+ req: Resource<Request>,+ method: Method,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::HostRequest::set_method(&mut self.0.http(id), req, method)+ }++ fn get_path_with_query(+ &mut self,+ id: NamedId,+ req: Resource<Request>,+ ) -> wasmtime::Result<Option<String>> {+ super::HostRequest::get_path_with_query(&mut self.0.http(id), req)+ }++ fn set_path_with_query(+ &mut self,+ id: NamedId,+ req: Resource<Request>,+ path_with_query: Option<String>,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::HostRequest::set_path_with_query(&mut self.0.http(id), req, path_with_query)+ }++ fn get_scheme(+ &mut self,+ id: NamedId,+ req: Resource<Request>,+ ) -> wasmtime::Result<Option<Scheme>> {+ super::HostRequest::get_scheme(&mut self.0.http(id), req)+ }++ fn set_scheme(+ &mut self,+ id: NamedId,+ req: Resource<Request>,+ scheme: Option<Scheme>,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::HostRequest::set_scheme(&mut self.0.http(id), req, scheme)+ }++ fn get_authority(+ &mut self,+ id: NamedId,+ req: Resource<Request>,+ ) -> wasmtime::Result<Option<String>> {+ super::HostRequest::get_authority(&mut self.0.http(id), req)+ }++ fn set_authority(+ &mut self,+ id: NamedId,+ req: Resource<Request>,+ authority: Option<String>,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::HostRequest::set_authority(&mut self.0.http(id), req, authority)+ }++ fn get_options(+ &mut self,+ id: NamedId,+ req: Resource<Request>,+ ) -> wasmtime::Result<Option<Resource<RequestOptions>>> {+ super::HostRequest::get_options(&mut self.0.http(id), req)+ }++ fn get_headers(+ &mut self,+ id: NamedId,+ req: Resource<Request>,+ ) -> wasmtime::Result<Resource<Headers>> {+ super::HostRequest::get_headers(&mut self.0.http(id), req)+ }+ }++ impl<T> types::HostRequestOptions for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn new(&mut self, id: NamedId) -> wasmtime::Result<Resource<RequestOptions>> {+ super::HostRequestOptions::new(&mut self.0.http(id))+ }++ fn get_connect_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<RequestOptions>,+ ) -> wasmtime::Result<Option<Duration>> {+ super::HostRequestOptions::get_connect_timeout(&mut self.0.http(id), opts)+ }++ fn set_connect_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<RequestOptions>,+ duration: Option<Duration>,+ ) -> RequestOptionsResult<()> {+ super::HostRequestOptions::set_connect_timeout(&mut self.0.http(id), opts, duration)+ }++ fn get_first_byte_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<RequestOptions>,+ ) -> wasmtime::Result<Option<Duration>> {+ super::HostRequestOptions::get_first_byte_timeout(&mut self.0.http(id), opts)+ }++ fn set_first_byte_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<RequestOptions>,+ duration: Option<Duration>,+ ) -> RequestOptionsResult<()> {+ super::HostRequestOptions::set_first_byte_timeout(&mut self.0.http(id), opts, duration)+ }++ fn get_between_bytes_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<RequestOptions>,+ ) -> wasmtime::Result<Option<Duration>> {+ super::HostRequestOptions::get_between_bytes_timeout(&mut self.0.http(id), opts)+ }++ fn set_between_bytes_timeout(+ &mut self,+ id: NamedId,+ opts: Resource<RequestOptions>,+ duration: Option<Duration>,+ ) -> RequestOptionsResult<()> {+ super::HostRequestOptions::set_between_bytes_timeout(+ &mut self.0.http(id),+ opts,+ duration,+ )+ }++ fn clone(+ &mut self,+ id: NamedId,+ opts: Resource<RequestOptions>,+ ) -> wasmtime::Result<Resource<RequestOptions>> {+ super::HostRequestOptions::clone(&mut self.0.http(id), opts)+ }++ fn drop(&mut self, id: NamedId, opts: Resource<RequestOptions>) -> wasmtime::Result<()> {+ super::HostRequestOptions::drop(&mut self.0.http(id), opts)+ }+ }++ impl<T> types::HostResponse for WasiCtxNamedView<'_, T>+ where+ T: WasiHttpNamedView,+ {+ fn get_status_code(+ &mut self,+ id: NamedId,+ res: Resource<Response>,+ ) -> wasmtime::Result<StatusCode> {+ super::HostResponse::get_status_code(&mut self.0.http(id), res)+ }++ fn set_status_code(+ &mut self,+ id: NamedId,+ res: Resource<Response>,+ status_code: StatusCode,+ ) -> wasmtime::Result<Result<(), ()>> {+ super::HostResponse::set_status_code(&mut self.0.http(id), res, status_code)+ }++ fn get_headers(+ &mut self,+ id: NamedId,+ res: Resource<Response>,+ ) -> wasmtime::Result<Resource<Headers>> {+ super::HostResponse::get_headers(&mut self.0.http(id), res)+ }+ }++ impl<T, U> types::HostRequestWithStore<U> for WasiHttpNamed<T>+ where+ T: WasiHttpNamedView,+ U: 'static,+ {+ fn new(+ store: Access<U, Self>,+ id: NamedId,+ headers: Resource<Headers>,+ contents: Option<StreamReader<u8>>,+ trailers: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,+ options: Option<Resource<RequestOptions>>,+ ) -> wasmtime::Result<(Resource<Request>, FutureReader<Result<(), ErrorCode>>)> {+ let getter = store.getter();+ super::new_request(+ store,+ move |data| getter(data).0.http(id),+ headers,+ contents,+ trailers,+ options,+ )+ }++ fn consume_body(+ mut store: Access<U, Self>,+ id: NamedId,+ req: Resource<Request>,+ fut: FutureReader<Result<(), ErrorCode>>,+ ) -> wasmtime::Result<(+ StreamReader<u8>,+ FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,+ )> {+ let getter = store.getter();+ let Request { body, .. } = store.get().0.http(id).table.delete(req)?;+ body.consume(store, fut, move |data: &mut U| getter(data).0.http(id))+ }++ fn drop(+ mut store: Access<'_, U, Self>,+ id: NamedId,+ req: Resource<Request>,+ ) -> wasmtime::Result<()> {+ let Request { body, .. } = store.get().0.http(id).table.delete(req)?;+ body.drop(store)?;+ Ok(())+ }+ }++ impl<T, U> types::HostResponseWithStore<U> for WasiHttpNamed<T>+ where+ T: WasiHttpNamedView,+ U: 'static,+ {+ fn new(+ store: Access<U, Self>,+ id: NamedId,+ headers: Resource<Headers>,+ contents: Option<StreamReader<u8>>,+ trailers: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,+ ) -> wasmtime::Result<(Resource<Response>, FutureReader<Result<(), ErrorCode>>)> {+ let getter = store.getter();+ super::new_response(+ store,+ move |data| getter(data).0.http(id),+ headers,+ contents,+ trailers,+ )+ }++ fn consume_body(+ mut store: Access<U, Self>,+ id: NamedId,+ res: Resource<Response>,+ fut: FutureReader<Result<(), ErrorCode>>,+ ) -> wasmtime::Result<(+ StreamReader<u8>,+ FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,+ )> {+ let getter = store.getter();+ let Response { body, .. } = store.get().0.http(id).table.delete(res)?;+ body.consume(store, fut, move |data: &mut U| getter(data).0.http(id))+ }++ fn drop(+ mut store: Access<'_, U, Self>,+ id: NamedId,+ res: Resource<Response>,+ ) -> wasmtime::Result<()> {+ let Response { body, .. } = store.get().0.http(id).table.delete(res)?;+ body.drop(store)?;+ Ok(())+ }+ }+}diff --git a/crates/wasi-http/src/p3/mod.rs b/crates/wasi-http/src/p3/mod.rsindex 39c8b19727..a809794306 100644--- a/crates/wasi-http/src/p3/mod.rs+++ b/crates/wasi-http/src/p3/mod.rs@@ -25,12 +25,12 @@ pub use response::Response;/// [`WasiHttpHooks::p3_outgoing_body_chunk_size`]: crate::WasiHttpHooks::p3_outgoing_body_chunk_sizepub const DEFAULT_OUTGOING_BODY_CHUNK_SIZE: usize = 1024 * 1024;-use crate::{FieldMapError, WasiHttp, WasiHttpView};+use crate::{FieldMapError, WasiHttp, WasiHttpNamed, WasiHttpNamedView, WasiHttpView};use bindings::http::{client, types};use core::ops::Deref;use std::sync::Arc;-use wasmtime::component::Linker;-use wasmtime_wasi::TrappableError;+use wasmtime::component::{Component, Linker};+use wasmtime_wasi::{NamedId, TrappableError, WasiCtxNamedView};pub(crate) type HttpResult<T> = Result<T, HttpError>;pub(crate) type HttpError = TrappableError<types::ErrorCode>;@@ -113,6 +113,121 @@ whereOk(())}+/// Interfaces that are added via [`add_named_to_linker`].+#[derive(Copy, Clone, PartialEq, Eq, Debug)]+pub enum Interface {+ /// `wasi:http/client`+ HttpClient,+ /// `wasi:http/types`+ HttpTypes,+}++/// Add all interfaces from this module into the `linker` provided for any+/// named imports that a component has.+///+/// This function is similar to [`add_to_linker`] except that it's specifically+/// designed to work with named imports of `wasi:http` interfaces that+/// components may have. This requires a [`Component`] parameter to be passed in+/// when populating the [`Linker`] provided to see what the [`Component`]+/// actually imports.+///+/// If this isn't low level enough you can invoke the bindgen-generated+/// `add_to_linker` functions within the [`named_imports`] module directly+/// instead.+///+/// [`named_imports`]: crate::p3::bindings::named_imports+///+/// The `lookup` function provided here is invoked for every named import found+/// for a particular interface. The [`Interface`] given is what's being bound,+/// and the `&str` argument is the name that the component imports it as. The+/// embedder can then decide how it would like to allocate a [`NamedId`] for+/// this import. If `Ok` is returned then the linker is populated with this+/// name, and imported functions will pass the [`NamedId`] later to the+/// implementation of [`WasiHttpNamedView`] on `T` when invoked. If `Err` is+/// returned then the error will cause this entire function to fail and this+/// function call will return the same error.+///+/// # Example+///+/// ```+/// use std::collections::HashMap;+/// use wasmtime::component::{Component, Linker, ResourceTable};+/// use wasmtime::{Engine, Result, Store, Config};+/// use wasmtime_wasi::NamedId;+/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpCtxView, WasiHttpNamedView};+///+/// fn main() -> Result<()> {+/// let mut config = Config::new();+/// config.wasm_component_model_async(true);+/// let engine = Engine::new(&config)?;+/// let component = Component::new(&engine, "(component)")?;+///+/// let mut linker = Linker::<MyState>::new(&engine);+///+/// // ... add default functionality to `linker` as needed ...+///+/// // and then additionally fill in any specific named imports `component`+/// // might have for `wasi:http` interfaces.+/// let mut name_map = HashMap::new();+/// wasmtime_wasi_http::p3::add_named_to_linker(&mut linker, &component, |_i, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// })?;+///+/// // Here a `WasiHttpCtx` is allocated per-named-import and will then be+/// // referred to internally by the [`NamedId`] allocated above. You could+/// // also use `name_map` to configure each context differently.+/// let mut my_state = MyState::default();+/// for _ in 0..name_map.len() {+/// my_state.contexts.push(WasiHttpCtx::default());+/// }+/// let mut store = Store::new(&engine, my_state);+///+/// // ... use `linker` to instantiate within `store` ...+///+/// Ok(())+/// }+///+/// #[derive(Default)]+/// struct MyState {+/// table: ResourceTable,+/// contexts: Vec<WasiHttpCtx>,+/// }+///+/// impl WasiHttpNamedView for MyState {+/// fn http(&mut self, id: NamedId) -> WasiHttpCtxView<'_> {+/// WasiHttpCtxView {+/// ctx: &mut self.contexts[id.0],+/// table: &mut self.table,+/// hooks: Default::default(),+/// }+/// }+/// }+/// ```+pub fn add_named_to_linker<T>(+ linker: &mut Linker<T>,+ component: &Component,+ mut lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiHttpNamedView,+{+ use crate::p3::bindings::named_imports::wasi::http::{client, types};+ client::add_to_linker::<_, WasiHttpNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::HttpClient, name),+ |x| WasiCtxNamedView(x),+ )?;+ types::add_to_linker::<_, WasiHttpNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::HttpTypes, name),+ |x| WasiCtxNamedView(x),+ )?;+ Ok(())+}+/// An [Arc], which may be immutable.////// In `wasi:http` resources like `fields` or `request-options` may bediff --git a/crates/wasi-http/src/p3/request.rs b/crates/wasi-http/src/p3/request.rsindex 11b5dde76d..0fe9414fc1 100644--- a/crates/wasi-http/src/p3/request.rs+++ b/crates/wasi-http/src/p3/request.rs@@ -142,7 +142,7 @@ impl Request {self,mut store: impl AsContextMut<Data = T>,fut: impl Future<Output = Result<(), Error>> + Send + 'static,- getter: fn(&mut T) -> WasiHttpCtxView<'_>,+ mut getter: impl FnMut(&mut T) -> WasiHttpCtxView<'_> + Clone + Unpin + Send + 'static,) -> HttpResult<(http::Request<UnsyncBoxBody<Bytes, Error>>,Option<Arc<RequestOptions>>,@@ -182,7 +182,7 @@ impl Request {fut,content_length,ErrorCode::HttpRequestBodySize,- getter,+ getter.clone(),).map_err(HttpError::trap)?.boxed_unsync(),diff --git a/crates/wasi-http/src/p3/response.rs b/crates/wasi-http/src/p3/response.rsindex 7b41974f0c..5cd13174b2 100644--- a/crates/wasi-http/src/p3/response.rs+++ b/crates/wasi-http/src/p3/response.rs@@ -55,7 +55,7 @@ impl Response {self,store: impl AsContextMut<Data = T>,fut: impl Future<Output = Result<(), Error>> + Send + 'static,- getter: fn(&mut T) -> WasiHttpCtxView<'_>,+ getter: impl FnMut(&mut T) -> WasiHttpCtxView<'_> + Clone + Unpin + Send + 'static,) -> wasmtime::Result<http::Response<UnsyncBoxBody<Bytes, Error>>> {let res = http::Response::try_from(self)?;let (res, body) = res.into_parts();diff --git a/crates/wasi-http/tests/all/main.rs b/crates/wasi-http/tests/all/main.rsindex 6db5cd0742..08d13fae8f 100644--- a/crates/wasi-http/tests/all/main.rs+++ b/crates/wasi-http/tests/all/main.rs@@ -11,6 +11,7 @@ mod http_server;mod p2;#[cfg(feature = "p3")]mod p3;+mod shared;mod body {use http_body_util::{BodyExt, Empty, Full, combinators::BoxBody};diff --git a/crates/wasi-http/tests/all/p2/async_.rs b/crates/wasi-http/tests/all/p2/async_.rsindex 176a713cd6..05cbac3176 100644--- a/crates/wasi-http/tests/all/p2/async_.rs+++ b/crates/wasi-http/tests/all/p2/async_.rs@@ -109,3 +109,18 @@ async fn p2_http_outbound_request_missing_path_and_query() -> Result<()> {).await}++#[test_log::test(tokio::test(flavor = "multi_thread"))]+async fn p2_http_named_imports() -> Result<()> {+ crate::shared::run_named_imports_test(+ P2_HTTP_NAMED_IMPORTS_COMPONENT,+ wasmtime_wasi_http::p2::add_only_http_to_linker_async,+ wasmtime_wasi_http::p2::add_named_to_linker_async,+ async |store, component, linker| {+ let command = Command::instantiate_async(&mut *store, component, linker).await?;+ let result = command.wasi_cli_run().call_run(&mut *store).await?;+ result.map_err(|()| wasmtime::format_err!("run returned an error"))+ },+ )+ .await+}diff --git a/crates/wasi-http/tests/all/p2/sync.rs b/crates/wasi-http/tests/all/p2/sync.rsindex a715c4ba31..a234dbc7c2 100644--- a/crates/wasi-http/tests/all/p2/sync.rs+++ b/crates/wasi-http/tests/all/p2/sync.rs@@ -107,3 +107,8 @@ fn p2_http_outbound_request_missing_path_and_query() -> Result<()> {&server,)}++#[test_log::test]+fn p2_http_named_imports() {+ // named imports are intentionally not implemented for sync at this time+}diff --git a/crates/wasi-http/tests/all/p3/mod.rs b/crates/wasi-http/tests/all/p3/mod.rsindex 3b30567446..b24e31bc46 100644--- a/crates/wasi-http/tests/all/p3/mod.rs+++ b/crates/wasi-http/tests/all/p3/mod.rs@@ -952,3 +952,22 @@ async fn p3_http_drop_transmit() -> Result<()> {let server = Server::http1(1)?;run_cli(P3_HTTP_DROP_TRANSMIT_COMPONENT, &server).await}++#[test_log::test(tokio::test(flavor = "multi_thread"))]+async fn p3_http_named_imports() -> Result<()> {+ crate::shared::run_named_imports_test(+ P3_HTTP_NAMED_IMPORTS_COMPONENT,+ wasmtime_wasi_http::p3::add_to_linker,+ wasmtime_wasi_http::p3::add_named_to_linker,+ async |store, component, linker| {+ let command = Command::instantiate_async(&mut *store, component, linker).await?;+ store+ .run_concurrent(async |store| command.wasi_cli_run().call_run(store).await)+ .await+ .context("failed to call `wasi:cli/run#run`")?+ .context("guest trapped")?+ .map_err(|()| format_err!("`wasi:cli/run#run` failed"))+ },+ )+ .await+}diff --git a/crates/wasi-http/tests/all/shared.rs b/crates/wasi-http/tests/all/shared.rsnew file mode 100644index 0000000000..f64ae45a66--- /dev/null+++ b/crates/wasi-http/tests/all/shared.rs@@ -0,0 +1,96 @@+use wasmtime::component::{Component, Linker, ResourceTable};+use wasmtime::{Result, Store};+use wasmtime_wasi::{NamedId, WasiCtx, WasiCtxView, WasiView};+use wasmtime_wasi_http::{+ WasiHttpCtx, WasiHttpCtxView, WasiHttpHooks, WasiHttpNamedView, WasiHttpView,+};++pub struct NamedImportsData {+ wasi: WasiCtx,+ http: WasiHttpCtx,+ table: ResourceTable,+ a: NamedImportsHooks,+ b: NamedImportsHooks,+}++struct NamedImportsHooks(&'static str);++impl WasiView for NamedImportsData {+ fn ctx(&mut self) -> WasiCtxView<'_> {+ WasiCtxView {+ ctx: &mut self.wasi,+ table: &mut self.table,+ }+ }+}++impl WasiHttpView for NamedImportsData {+ fn http(&mut self) -> WasiHttpCtxView<'_> {+ WasiHttpCtxView {+ ctx: &mut self.http,+ table: &mut self.table,+ hooks: Default::default(),+ }+ }+}++impl WasiHttpNamedView for NamedImportsData {+ fn http(&mut self, id: NamedId) -> WasiHttpCtxView<'_> {+ WasiHttpCtxView {+ ctx: &mut self.http,+ table: &mut self.table,+ hooks: match id.0 {+ 0 => &mut self.a,+ 1 => &mut self.b,+ _ => panic!("unexpected id: {}", id.0),+ },+ }+ }+}++impl WasiHttpHooks for NamedImportsHooks {+ fn is_forbidden_header(&mut self, name: &http::HeaderName) -> bool {+ name == self.0+ }+}++pub async fn run_named_imports_test<T>(+ component: &str,+ add_only_http_to_linker: fn(&mut Linker<NamedImportsData>) -> Result<()>,+ add_named_to_linker: fn(+ &mut Linker<NamedImportsData>,+ &Component,+ fn(T, &str) -> Result<NamedId>,+ ) -> Result<()>,+ run: impl AsyncFnOnce(+ &mut Store<NamedImportsData>,+ &Component,+ &Linker<NamedImportsData>,+ ) -> Result<()>,+) -> Result<()> {+ let engine = test_programs_artifacts::engine(|config| {+ config.wasm_component_model_implements(true);+ });+ let component = Component::from_file(&engine, component)?;+ let mut store = Store::new(+ &engine,+ NamedImportsData {+ wasi: WasiCtx::builder().inherit_stdio().build(),+ table: ResourceTable::new(),+ http: Default::default(),+ a: NamedImportsHooks("a"),+ b: NamedImportsHooks("b"),+ },+ );+ let mut linker = Linker::new(&engine);+ wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;+ add_only_http_to_linker(&mut linker)?;+ add_named_to_linker(&mut linker, &component, |_, name| {+ Ok(match name {+ "a" => NamedId(0),+ "b" => NamedId(1),+ _ => panic!("unexpected name: {name}"),+ })+ })?;+ run(&mut store, &component, &linker).await+}diff --git a/crates/wasi/src/cli.rs b/crates/wasi/src/cli.rsindex eff5089d1c..879262706e 100644--- a/crates/wasi/src/cli.rs+++ b/crates/wasi/src/cli.rs@@ -1,4 +1,6 @@use crate::p2;+use crate::{NamedId, WasiCtxNamedView};+use std::marker;use std::pin::Pin;use std::sync::Arc;use tokio::io::{AsyncRead, AsyncWrite, empty};@@ -283,6 +285,163 @@ impl<T: ?Sized + StdoutStream + Sync> StdoutStream for Arc<T> {}}+/// A helper struct which implements [`HasData`] for the `wasi:cli` APIs when+/// used in combination with named imports.+///+/// This structure is similar in purpose to [`WasiCli`] and is used+/// when using the [`named_imports`] module for `wasi:cli`. This structure+/// serves as the `D` type parameter for `add_to_linker` functions.+///+/// [`named_imports`]: crate::p3::bindings::named_imports::wasi::cli+///+/// # Meaning of the `T` parameter+///+/// Here the `T` must be something that implements [`WasiCliNamedView`]. The+/// corresponding `Data` for this type is [`WasiCtxNamedView`] which internally+/// will contain `&mut T`.+///+/// Effectively you're going to implement [`WasiCliNamedView`] for something in+/// your embedding, and that's the `T` you'll fill in here.+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component, ResourceTable};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};+/// use wasmtime_wasi::cli::*;+/// use wasmtime_wasi::p2::bindings::named_imports;+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// table: ResourceTable,+/// states: HashMap<NamedId, WasiCliCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// named_imports::wasi::cli::environment::add_to_linker::<MyStoreState, WasiCliNamed<MyStoreState>>(+/// &mut linker,+/// &component,+/// |name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// |state| WasiCtxNamedView(state),+/// )?;+/// Ok(())+/// }+///+/// impl WasiCliNamedView for MyStoreState {+/// fn cli(&mut self, id: NamedId) -> WasiCliCtxView<'_> {+/// let ctx = self.states.get_mut(&id).expect("state for id");+/// WasiCliCtxView {+/// table: &mut self.table,+/// ctx,+/// }+/// }+/// }+/// ```+pub struct WasiCliNamed<T>(marker::PhantomData<fn() -> T>);++impl<T> HasData for WasiCliNamed<T>+where+ T: WasiCliNamedView,+{+ type Data<'a> = WasiCtxNamedView<'a, T>;+}++/// A trait used to look up a specific `wasi:cli` context for a named import.+///+/// This trait is used in conjunction with the [`named_imports`] bindings+/// generated for all WASI interfaces. The purpose of this trait is for+/// embedders to define how a [`NamedId`] maps to a particular `wasi:cli`+/// context, here returned as [`WasiCliCtxView`]. Embedders are responsible+/// for assigning meaning to [`NamedId`] values themselves. These IDs are+/// assigned when [`add_named_to_linker`] is called, for example, as the+/// `lookup` argument to that function.+///+/// When using [`add_named_to_linker`] it's sufficient to implement this trait+/// for the `T` in `Store<T>`. You can also instead implement the+/// [`WasiNamedView`] trait for `T` which implies an implementation of this+/// trait.+///+/// When using `add_to_linker` in the generated `bindings::named_imports`+/// module then values implementing this live within the `T` of `Store<T>`, and+/// be temporarily referenced in [`WasiCtxNamedView`] where internally that'll+/// hold `WasiCtxNamedView(&mut your_type)`.+///+/// [`named_imports`]: crate::p3::bindings::named_imports+/// [`add_named_to_linker`]: crate::p3::cli::add_named_to_linker+/// [`WasiNamedView`]: crate::WasiNamedView+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component, ResourceTable};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};+/// use wasmtime_wasi::cli::*;+/// use wasmtime_wasi::p2::bindings::named_imports;+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// table: ResourceTable,+/// states: HashMap<NamedId, WasiCliCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// wasmtime_wasi::p3::cli::add_named_to_linker::<MyStoreState>(+/// &mut linker,+/// &component,+/// |_, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// )?;+/// Ok(())+/// }+///+/// impl WasiCliNamedView for MyStoreState {+/// fn cli(&mut self, id: NamedId) -> WasiCliCtxView<'_> {+/// let ctx = self.states.get_mut(&id).expect("state for id");+/// WasiCliCtxView {+/// table: &mut self.table,+/// ctx,+/// }+/// }+/// }+/// ```+pub trait WasiCliNamedView: Send + 'static {+ /// Looks up the [`WasiCliCtxView`] for the given [`NamedId`].+ ///+ /// This method will resolve the `id` specified to a specific CLI context+ /// that is available to be used. Note that this method is specifically+ /// infallible meaning that a CLI context must be returned and this cannot+ /// generate a trap or panic or similar.+ ///+ /// Embedders are responsible for allocating [`NamedId`] and assigning+ /// meaning to ids. When a `Linker` is populated embedders will have the+ /// ability to generate a `NamedId` for all imports found, and then that+ /// embedder-allocated id is then passed back here when the corresponding+ /// imported function is invoked.+ ///+ /// Note that the [`ResourceTable`] referenced in the returned+ /// [`WasiCliCtxView`] need not be unique. It's ok to use the same+ /// [`ResourceTable`] for all imports. This is not a guest-visible+ /// abstraction and just helps the host allocate and manage state.+ fn cli(&mut self, id: NamedId) -> WasiCliCtxView<'_>;+}+#[cfg(test)]mod test {use crate::cli::{AsyncStdoutStream, StdinStream, StdoutStream};diff --git a/crates/wasi/src/clocks.rs b/crates/wasi/src/clocks.rsindex 4c213ae241..0cc22c697b 100644--- a/crates/wasi/src/clocks.rs+++ b/crates/wasi/src/clocks.rs@@ -1,5 +1,7 @@+use crate::{NamedId, WasiCtxNamedView};use std::error::Error;use std::fmt;+use std::marker;use std::time::{Duration, Instant, SystemTime};use wasmtime::component::{HasData, ResourceTable};@@ -229,3 +231,160 @@ impl From<std::num::TryFromIntError> for DatetimeError {DatetimeError}}++/// A helper struct which implements [`HasData`] for the `wasi:clocks` APIs+/// when used in combination with named imports.+///+/// This structure is similar in purpose to [`WasiClocks`] and is used+/// when using the [`named_imports`] module for `wasi:clocks`. This structure+/// serves as the `D` type parameter for `add_to_linker` functions.+///+/// [`named_imports`]: crate::p3::bindings::named_imports::wasi::clocks+///+/// # Meaning of the `T` parameter+///+/// Here the `T` must be something that implements [`WasiClocksNamedView`]. The+/// corresponding `Data` for this type is [`WasiCtxNamedView`] which internally+/// will contain `&mut T`.+///+/// Effectively you're going to implement [`WasiClocksNamedView`] for something in+/// your embedding, and that's the `T` you'll fill in here.+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component, ResourceTable};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};+/// use wasmtime_wasi::clocks::*;+/// use wasmtime_wasi::p2::bindings::named_imports;+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// table: ResourceTable,+/// states: HashMap<NamedId, WasiClocksCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// named_imports::wasi::clocks::wall_clock::add_to_linker::<MyStoreState, WasiClocksNamed<MyStoreState>>(+/// &mut linker,+/// &component,+/// |name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// |state| WasiCtxNamedView(state),+/// )?;+/// Ok(())+/// }+///+/// impl WasiClocksNamedView for MyStoreState {+/// fn clocks(&mut self, id: NamedId) -> WasiClocksCtxView<'_> {+/// let ctx = self.states.get_mut(&id).expect("state for id");+/// WasiClocksCtxView {+/// table: &mut self.table,+/// ctx,+/// }+/// }+/// }+/// ```+pub struct WasiClocksNamed<T>(marker::PhantomData<fn() -> T>);++impl<T> HasData for WasiClocksNamed<T>+where+ T: WasiClocksNamedView,+{+ type Data<'a> = WasiCtxNamedView<'a, T>;+}++/// A trait used to look up a specific `wasi:clocks` context for a named+/// import.+///+/// This trait is used in conjunction with the [`named_imports`] bindings+/// generated for all WASI interfaces. The purpose of this trait is for+/// embedders to define how a [`NamedId`] maps to a particular `wasi:clocks`+/// context, here returned as [`WasiClocksCtxView`]. Embedders are responsible+/// for assigning meaning to [`NamedId`] values themselves. These IDs are+/// assigned when [`add_named_to_linker`] is called, for example, as the+/// `lookup` argument to that function.+///+/// When using [`add_named_to_linker`] it's sufficient to implement this trait+/// for the `T` in `Store<T>`. You can also instead implement the+/// [`WasiNamedView`] trait for `T` which implies an implementation of this+/// trait.+///+/// When using `add_to_linker` in the generated `bindings::named_imports`+/// module then values implementing this live within the `T` of `Store<T>`, and+/// be temporarily referenced in [`WasiCtxNamedView`] where internally that'll+/// hold `WasiCtxNamedView(&mut your_type)`.+///+/// [`named_imports`]: crate::p3::bindings::named_imports+/// [`add_named_to_linker`]: crate::p3::clocks::add_named_to_linker+/// [`WasiNamedView`]: crate::WasiNamedView+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component, ResourceTable};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};+/// use wasmtime_wasi::clocks::*;+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// table: ResourceTable,+/// states: HashMap<NamedId, WasiClocksCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// wasmtime_wasi::p3::clocks::add_named_to_linker::<MyStoreState>(+/// &mut linker,+/// &component,+/// |_, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// )?;+/// Ok(())+/// }+///+/// impl WasiClocksNamedView for MyStoreState {+/// fn clocks(&mut self, id: NamedId) -> WasiClocksCtxView<'_> {+/// let ctx = self.states.get_mut(&id).expect("state for id");+/// WasiClocksCtxView {+/// table: &mut self.table,+/// ctx,+/// }+/// }+/// }+/// ```+pub trait WasiClocksNamedView: Send + 'static {+ /// Looks up the [`WasiClocksCtxView`] for the given [`NamedId`].+ ///+ /// This method will resolve the `id` specified to a specific clocks+ /// context that is available to be used. Note that this method is+ /// specifically infallible meaning that a clocks context must be returned+ /// and this cannot generate a trap or panic or similar.+ ///+ /// Embedders are responsible for allocating [`NamedId`] and assigning+ /// meaning to ids. When a `Linker` is populated embedders will have the+ /// ability to generate a `NamedId` for all imports found, and then that+ /// embedder-allocated id is then passed back here when the corresponding+ /// imported function is invoked.+ ///+ /// Note that the [`ResourceTable`] referenced in the returned+ /// [`WasiClocksCtxView`] need not be unique. It's ok to use the same+ /// [`ResourceTable`] for all imports. This is not a guest-visible+ /// abstraction and just helps the host allocate and manage state.+ fn clocks(&mut self, id: NamedId) -> WasiClocksCtxView<'_>;+}diff --git a/crates/wasi/src/filesystem.rs b/crates/wasi/src/filesystem.rsindex f74621ad03..e6f00ea704 100644--- a/crates/wasi/src/filesystem.rs+++ b/crates/wasi/src/filesystem.rs@@ -1,7 +1,9 @@use crate::clocks::Datetime;use crate::filesystem::primitives::{DirOptions, FollowSymlinks, Metadata, OpenOptions};use crate::runtime::{AbortOnDropJoinHandle, spawn_blocking};+use crate::{NamedId, WasiCtxNamedView};use std::collections::hash_map;+use std::marker;use std::sync::Arc;use std::time::SystemTime;use tracing::debug;@@ -1159,3 +1161,160 @@ impl WasiFilesystemCtxView<'_> {Ok(results)}}++/// A helper struct which implements [`HasData`] for the `wasi:filesystem` APIs+/// when used in combination with named imports.+///+/// This structure is similar in purpose to [`WasiFilesystem`] and is used+/// when using the [`named_imports`] module for `wasi:filesystem`. This structure+/// serves as the `D` type parameter for `add_to_linker` functions.+///+/// [`named_imports`]: crate::p3::bindings::named_imports::wasi::filesystem+///+/// # Meaning of the `T` parameter+///+/// Here the `T` must be something that implements [`WasiFilesystemNamedView`]. The+/// corresponding `Data` for this type is [`WasiCtxNamedView`] which internally+/// will contain `&mut T`.+///+/// Effectively you're going to implement [`WasiFilesystemNamedView`] for something in+/// your embedding, and that's the `T` you'll fill in here.+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component, ResourceTable};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};+/// use wasmtime_wasi::filesystem::*;+/// use wasmtime_wasi::p2::bindings::named_imports;+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// table: ResourceTable,+/// states: HashMap<NamedId, WasiFilesystemCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// named_imports::wasi::filesystem::preopens::add_to_linker::<MyStoreState, WasiFilesystemNamed<MyStoreState>>(+/// &mut linker,+/// &component,+/// |name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// |state| WasiCtxNamedView(state),+/// )?;+/// Ok(())+/// }+///+/// impl WasiFilesystemNamedView for MyStoreState {+/// fn filesystem(&mut self, id: NamedId) -> WasiFilesystemCtxView<'_> {+/// let ctx = self.states.get_mut(&id).expect("state for id");+/// WasiFilesystemCtxView {+/// table: &mut self.table,+/// ctx,+/// }+/// }+/// }+/// ```+pub struct WasiFilesystemNamed<T>(marker::PhantomData<fn() -> T>);++impl<T> HasData for WasiFilesystemNamed<T>+where+ T: WasiFilesystemNamedView,+{+ type Data<'a> = WasiCtxNamedView<'a, T>;+}++/// A trait used to look up a specific `wasi:filesystem` context for a named+/// import.+///+/// This trait is used in conjunction with the [`named_imports`] bindings+/// generated for all WASI interfaces. The purpose of this trait is for+/// embedders to define how a [`NamedId`] maps to a particular `wasi:filesystem`+/// context, here returned as [`WasiFilesystemCtxView`]. Embedders are responsible+/// for assigning meaning to [`NamedId`] values themselves. These IDs are+/// assigned when [`add_named_to_linker`] is called, for example, as the+/// `lookup` argument to that function.+///+/// When using [`add_named_to_linker`] it's sufficient to implement this trait+/// for the `T` in `Store<T>`. You can also instead implement the+/// [`WasiNamedView`] trait for `T` which implies an implementation of this+/// trait.+///+/// When using `add_to_linker` in the generated `bindings::named_imports`+/// module then values implementing this live within the `T` of `Store<T>`, and+/// be temporarily referenced in [`WasiCtxNamedView`] where internally that'll+/// hold `WasiCtxNamedView(&mut your_type)`.+///+/// [`named_imports`]: crate::p3::bindings::named_imports+/// [`add_named_to_linker`]: crate::p3::filesystem::add_named_to_linker+/// [`WasiNamedView`]: crate::WasiNamedView+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component, ResourceTable};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};+/// use wasmtime_wasi::filesystem::*;+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// table: ResourceTable,+/// states: HashMap<NamedId, WasiFilesystemCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// wasmtime_wasi::p3::filesystem::add_named_to_linker::<MyStoreState>(+/// &mut linker,+/// &component,+/// |_, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// )?;+/// Ok(())+/// }+///+/// impl WasiFilesystemNamedView for MyStoreState {+/// fn filesystem(&mut self, id: NamedId) -> WasiFilesystemCtxView<'_> {+/// let ctx = self.states.get_mut(&id).expect("state for id");+/// WasiFilesystemCtxView {+/// table: &mut self.table,+/// ctx,+/// }+/// }+/// }+/// ```+pub trait WasiFilesystemNamedView: Send + 'static {+ /// Looks up the [`WasiFilesystemCtxView`] for the given [`NamedId`].+ ///+ /// This method will resolve the `id` specified to a specific filesystem+ /// context that is available to be used. Note that this method is+ /// specifically infallible meaning that a filesystem context must be returned+ /// and this cannot generate a trap or panic or similar.+ ///+ /// Embedders are responsible for allocating [`NamedId`] and assigning+ /// meaning to ids. When a `Linker` is populated embedders will have the+ /// ability to generate a `NamedId` for all imports found, and then that+ /// embedder-allocated id is then passed back here when the corresponding+ /// imported function is invoked.+ ///+ /// Note that the [`ResourceTable`] referenced in the returned+ /// [`WasiFilesystemCtxView`] need not be unique. It's ok to use the same+ /// [`ResourceTable`] for all imports. This is not a guest-visible+ /// abstraction and just helps the host allocate and manage state.+ fn filesystem(&mut self, id: NamedId) -> WasiFilesystemCtxView<'_>;+}diff --git a/crates/wasi/src/lib.rs b/crates/wasi/src/lib.rsindex 005d8155d5..5c582225e8 100644--- a/crates/wasi/src/lib.rs+++ b/crates/wasi/src/lib.rs@@ -51,11 +51,11 @@ pub mod sockets;mod view;pub use self::clocks::{HostMonotonicClock, HostWallClock};-pub use self::ctx::{WasiCtx, WasiCtxBuilder};+pub use self::ctx::*;pub use self::error::{I32Exit, TrappableError};pub use self::filesystem::{FsPerms, OpenMode};pub use self::random::{Deterministic, thread_rng};-pub use self::view::{WasiCtxView, WasiView};+pub use self::view::*;#[doc(no_inline)]pub use async_trait::async_trait;#[doc(no_inline)]diff --git a/crates/wasi/src/p2/bindings.rs b/crates/wasi/src/p2/bindings.rsindex 0e35a4c021..f26afd8f1e 100644--- a/crates/wasi/src/p2/bindings.rs+++ b/crates/wasi/src/p2/bindings.rs@@ -403,11 +403,38 @@ mod async_io {"wasi:cli/terminal-input.terminal-input": crate::p2::stdio::TerminalInput,"wasi:cli/terminal-output.terminal-output": crate::p2::stdio::TerminalOutput,},+ named_imports: {+ "wasi:clocks/monotonic-clock": crate::NamedId,+ "wasi:clocks/wall-clock": crate::NamedId,+ "wasi:random/random": crate::NamedId,+ "wasi:random/insecure": crate::NamedId,+ "wasi:random/insecure-seed": crate::NamedId,+ "wasi:cli/exit": crate::NamedId,+ "wasi:cli/environment": crate::NamedId,+ "wasi:cli/stdin": crate::NamedId,+ "wasi:cli/stdout": crate::NamedId,+ "wasi:cli/stderr": crate::NamedId,+ "wasi:cli/terminal-input": crate::NamedId,+ "wasi:cli/terminal-output": crate::NamedId,+ "wasi:cli/terminal-stdin": crate::NamedId,+ "wasi:cli/terminal-stdout": crate::NamedId,+ "wasi:cli/terminal-stderr": crate::NamedId,+ "wasi:filesystem/types": crate::NamedId,+ "wasi:filesystem/preopens": crate::NamedId,+ "wasi:sockets/instance-network": crate::NamedId,+ "wasi:sockets/network": crate::NamedId,+ "wasi:sockets/ip-name-lookup": crate::NamedId,+ "wasi:sockets/tcp-create-socket": crate::NamedId,+ "wasi:sockets/tcp": crate::NamedId,+ "wasi:sockets/udp-create-socket": crate::NamedId,+ "wasi:sockets/udp": crate::NamedId,+ },});}pub use self::async_io::LinkOptions;pub use self::async_io::exports;+pub use self::async_io::named_imports;pub use self::async_io::wasi::*;/// Asynchronous bindings to execute and run a `wasi:cli/command`.diff --git a/crates/wasi/src/p2/host/clocks.rs b/crates/wasi/src/p2/host/clocks.rsindex e89be8ddff..91f1d7fc9a 100644--- a/crates/wasi/src/p2/host/clocks.rs+++ b/crates/wasi/src/p2/host/clocks.rs@@ -151,3 +151,55 @@ impl Pollable for Deadline {}}}++mod named {+ use crate::clocks::WasiClocksNamedView;+ use crate::p2::DynPollable;+ use crate::p2::bindings::clocks::monotonic_clock::{Duration as WasiDuration, Instant};+ use crate::p2::bindings::clocks::wall_clock::Datetime;+ use crate::p2::bindings::named_imports::wasi::clocks::{monotonic_clock, wall_clock};+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::Resource;++ impl<T> wall_clock::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiClocksNamedView,+ {+ fn now(&mut self, id: NamedId) -> wasmtime::Result<Datetime> {+ super::wall_clock::Host::now(&mut self.0.clocks(id))+ }++ fn resolution(&mut self, id: NamedId) -> wasmtime::Result<Datetime> {+ super::wall_clock::Host::resolution(&mut self.0.clocks(id))+ }+ }++ impl<T> monotonic_clock::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiClocksNamedView,+ {+ fn now(&mut self, id: NamedId) -> wasmtime::Result<Instant> {+ super::monotonic_clock::Host::now(&mut self.0.clocks(id))+ }++ fn resolution(&mut self, id: NamedId) -> wasmtime::Result<Instant> {+ super::monotonic_clock::Host::resolution(&mut self.0.clocks(id))+ }++ fn subscribe_instant(+ &mut self,+ id: NamedId,+ when: Instant,+ ) -> wasmtime::Result<Resource<DynPollable>> {+ super::monotonic_clock::Host::subscribe_instant(&mut self.0.clocks(id), when)+ }++ fn subscribe_duration(+ &mut self,+ id: NamedId,+ duration: WasiDuration,+ ) -> wasmtime::Result<Resource<DynPollable>> {+ super::monotonic_clock::Host::subscribe_duration(&mut self.0.clocks(id), duration)+ }+ }+}diff --git a/crates/wasi/src/p2/host/env.rs b/crates/wasi/src/p2/host/env.rsindex 550f9938ba..22e15e7088 100644--- a/crates/wasi/src/p2/host/env.rs+++ b/crates/wasi/src/p2/host/env.rs@@ -12,3 +12,26 @@ impl environment::Host for WasiCliCtxView<'_> {Ok(self.ctx.initial_cwd.clone())}}++mod named {+ use crate::cli::WasiCliNamedView;+ use crate::p2::bindings::named_imports::wasi::cli::environment;+ use crate::{NamedId, WasiCtxNamedView};++ impl<T> environment::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn get_environment(&mut self, id: NamedId) -> wasmtime::Result<Vec<(String, String)>> {+ super::environment::Host::get_environment(&mut self.0.cli(id))+ }++ fn get_arguments(&mut self, id: NamedId) -> wasmtime::Result<Vec<String>> {+ super::environment::Host::get_arguments(&mut self.0.cli(id))+ }++ fn initial_cwd(&mut self, id: NamedId) -> wasmtime::Result<Option<String>> {+ super::environment::Host::initial_cwd(&mut self.0.cli(id))+ }+ }+}diff --git a/crates/wasi/src/p2/host/exit.rs b/crates/wasi/src/p2/host/exit.rsindex 76cb8dcfe9..c631e9942e 100644--- a/crates/wasi/src/p2/host/exit.rs+++ b/crates/wasi/src/p2/host/exit.rs@@ -15,3 +15,22 @@ impl exit::Host for WasiCliCtxView<'_> {Err(wasmtime::format_err!(I32Exit(status_code.into())))}}++mod named {+ use crate::cli::WasiCliNamedView;+ use crate::p2::bindings::named_imports::wasi::cli::exit;+ use crate::{NamedId, WasiCtxNamedView};++ impl<T> exit::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn exit(&mut self, id: NamedId, status: Result<(), ()>) -> wasmtime::Result<()> {+ super::exit::Host::exit(&mut self.0.cli(id), status)+ }++ fn exit_with_code(&mut self, id: NamedId, status_code: u8) -> wasmtime::Result<()> {+ super::exit::Host::exit_with_code(&mut self.0.cli(id), status_code)+ }+ }+}diff --git a/crates/wasi/src/p2/host/filesystem.rs b/crates/wasi/src/p2/host/filesystem.rsindex 7f5ef8aec7..db42d4495c 100644--- a/crates/wasi/src/p2/host/filesystem.rs+++ b/crates/wasi/src/p2/host/filesystem.rs@@ -261,7 +261,6 @@ impl HostDescriptor for WasiFilesystemCtxView<'_> {async fn link_at(&mut self,fd: Resource<types::Descriptor>,- // TODO delete the path flags from this functionold_path_flags: types::PathFlags,old_path: String,new_descriptor: Resource<types::Descriptor>,@@ -755,3 +754,364 @@ mod test {table.delete(ix).unwrap();}}++mod named {+ use crate::filesystem::WasiFilesystemNamedView;+ use crate::p2::bindings::filesystem::types::{+ Advice, Descriptor, DescriptorFlags, DescriptorStat, DescriptorType, DirectoryEntry,+ DirectoryEntryStream, ErrorCode, Filesize, MetadataHashValue, NewTimestamp, OpenFlags,+ PathFlags,+ };+ use crate::p2::bindings::named_imports::wasi::filesystem::{preopens, types};+ use crate::p2::{FsError, FsResult};+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::Resource;+ use wasmtime_wasi_io::streams::{DynInputStream, DynOutputStream};++ impl<T> preopens::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiFilesystemNamedView,+ {+ fn get_directories(+ &mut self,+ id: NamedId,+ ) -> wasmtime::Result<Vec<(Resource<Descriptor>, String)>> {+ super::preopens::Host::get_directories(&mut self.0.filesystem(id))+ }+ }++ impl<T> types::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiFilesystemNamedView,+ {+ fn convert_error_code(&mut self, err: FsError) -> wasmtime::Result<ErrorCode> {+ err.downcast()+ }++ fn filesystem_error_code(+ &mut self,+ id: NamedId,+ err: Resource<wasmtime::Error>,+ ) -> wasmtime::Result<Option<ErrorCode>> {+ super::types::Host::filesystem_error_code(&mut self.0.filesystem(id), err)+ }+ }++ impl<T> types::HostDescriptor for WasiCtxNamedView<'_, T>+ where+ T: WasiFilesystemNamedView,+ {+ async fn advise(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ offset: Filesize,+ len: Filesize,+ advice: Advice,+ ) -> FsResult<()> {+ super::HostDescriptor::advise(&mut self.0.filesystem(id), fd, offset, len, advice).await+ }++ async fn sync_data(&mut self, id: NamedId, fd: Resource<Descriptor>) -> FsResult<()> {+ super::HostDescriptor::sync_data(&mut self.0.filesystem(id), fd).await+ }++ async fn get_flags(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FsResult<DescriptorFlags> {+ super::HostDescriptor::get_flags(&mut self.0.filesystem(id), fd).await+ }++ async fn get_type(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FsResult<DescriptorType> {+ super::HostDescriptor::get_type(&mut self.0.filesystem(id), fd).await+ }++ async fn set_size(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ size: Filesize,+ ) -> FsResult<()> {+ super::HostDescriptor::set_size(&mut self.0.filesystem(id), fd, size).await+ }++ async fn set_times(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ atim: NewTimestamp,+ mtim: NewTimestamp,+ ) -> FsResult<()> {+ super::HostDescriptor::set_times(&mut self.0.filesystem(id), fd, atim, mtim).await+ }++ async fn read(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ len: Filesize,+ offset: Filesize,+ ) -> FsResult<(Vec<u8>, bool)> {+ super::HostDescriptor::read(&mut self.0.filesystem(id), fd, len, offset).await+ }++ async fn write(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ buf: Vec<u8>,+ offset: Filesize,+ ) -> FsResult<Filesize> {+ super::HostDescriptor::write(&mut self.0.filesystem(id), fd, buf, offset).await+ }++ async fn read_directory(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FsResult<Resource<DirectoryEntryStream>> {+ super::HostDescriptor::read_directory(&mut self.0.filesystem(id), fd).await+ }++ async fn sync(&mut self, id: NamedId, fd: Resource<Descriptor>) -> FsResult<()> {+ super::HostDescriptor::sync(&mut self.0.filesystem(id), fd).await+ }++ async fn create_directory_at(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ path: String,+ ) -> FsResult<()> {+ super::HostDescriptor::create_directory_at(&mut self.0.filesystem(id), fd, path).await+ }++ async fn stat(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FsResult<DescriptorStat> {+ super::HostDescriptor::stat(&mut self.0.filesystem(id), fd).await+ }++ async fn stat_at(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ ) -> FsResult<DescriptorStat> {+ super::HostDescriptor::stat_at(&mut self.0.filesystem(id), fd, path_flags, path).await+ }++ async fn set_times_at(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ atim: NewTimestamp,+ mtim: NewTimestamp,+ ) -> FsResult<()> {+ super::HostDescriptor::set_times_at(+ &mut self.0.filesystem(id),+ fd,+ path_flags,+ path,+ atim,+ mtim,+ )+ .await+ }++ async fn link_at(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ old_path_flags: PathFlags,+ old_path: String,+ new_descriptor: Resource<Descriptor>,+ new_path: String,+ ) -> FsResult<()> {+ super::HostDescriptor::link_at(+ &mut self.0.filesystem(id),+ fd,+ old_path_flags,+ old_path,+ new_descriptor,+ new_path,+ )+ .await+ }++ async fn open_at(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ oflags: OpenFlags,+ flags: DescriptorFlags,+ ) -> FsResult<Resource<Descriptor>> {+ super::HostDescriptor::open_at(+ &mut self.0.filesystem(id),+ fd,+ path_flags,+ path,+ oflags,+ flags,+ )+ .await+ }++ fn drop(&mut self, id: NamedId, fd: Resource<Descriptor>) -> wasmtime::Result<()> {+ super::HostDescriptor::drop(&mut self.0.filesystem(id), fd)+ }++ async fn readlink_at(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ path: String,+ ) -> FsResult<String> {+ super::HostDescriptor::readlink_at(&mut self.0.filesystem(id), fd, path).await+ }++ async fn remove_directory_at(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ path: String,+ ) -> FsResult<()> {+ super::HostDescriptor::remove_directory_at(&mut self.0.filesystem(id), fd, path).await+ }++ async fn rename_at(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ old_path: String,+ new_fd: Resource<Descriptor>,+ new_path: String,+ ) -> FsResult<()> {+ super::HostDescriptor::rename_at(+ &mut self.0.filesystem(id),+ fd,+ old_path,+ new_fd,+ new_path,+ )+ .await+ }++ async fn symlink_at(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ src_path: String,+ dest_path: String,+ ) -> FsResult<()> {+ super::HostDescriptor::symlink_at(&mut self.0.filesystem(id), fd, src_path, dest_path)+ .await+ }++ async fn unlink_file_at(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ path: String,+ ) -> FsResult<()> {+ super::HostDescriptor::unlink_file_at(&mut self.0.filesystem(id), fd, path).await+ }++ fn read_via_stream(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ offset: Filesize,+ ) -> FsResult<Resource<DynInputStream>> {+ super::HostDescriptor::read_via_stream(&mut self.0.filesystem(id), fd, offset)+ }++ fn write_via_stream(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ offset: Filesize,+ ) -> FsResult<Resource<DynOutputStream>> {+ super::HostDescriptor::write_via_stream(&mut self.0.filesystem(id), fd, offset)+ }++ fn append_via_stream(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FsResult<Resource<DynOutputStream>> {+ super::HostDescriptor::append_via_stream(&mut self.0.filesystem(id), fd)+ }++ async fn is_same_object(+ &mut self,+ id: NamedId,+ a: Resource<Descriptor>,+ b: Resource<Descriptor>,+ ) -> wasmtime::Result<bool> {+ super::HostDescriptor::is_same_object(&mut self.0.filesystem(id), a, b).await+ }++ async fn metadata_hash(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FsResult<MetadataHashValue> {+ super::HostDescriptor::metadata_hash(&mut self.0.filesystem(id), fd).await+ }++ async fn metadata_hash_at(+ &mut self,+ id: NamedId,+ fd: Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ ) -> FsResult<MetadataHashValue> {+ super::HostDescriptor::metadata_hash_at(+ &mut self.0.filesystem(id),+ fd,+ path_flags,+ path,+ )+ .await+ }+ }++ impl<T> types::HostDirectoryEntryStream for WasiCtxNamedView<'_, T>+ where+ T: WasiFilesystemNamedView,+ {+ async fn read_directory_entry(+ &mut self,+ id: NamedId,+ stream: Resource<DirectoryEntryStream>,+ ) -> FsResult<Option<DirectoryEntry>> {+ super::HostDirectoryEntryStream::read_directory_entry(+ &mut self.0.filesystem(id),+ stream,+ )+ .await+ }++ fn drop(+ &mut self,+ id: NamedId,+ stream: Resource<DirectoryEntryStream>,+ ) -> wasmtime::Result<()> {+ super::HostDirectoryEntryStream::drop(&mut self.0.filesystem(id), stream)+ }+ }+}diff --git a/crates/wasi/src/p2/host/instance_network.rs b/crates/wasi/src/p2/host/instance_network.rsindex 23e7cd4da2..b1ad03620a 100644--- a/crates/wasi/src/p2/host/instance_network.rs+++ b/crates/wasi/src/p2/host/instance_network.rs@@ -10,3 +10,20 @@ impl instance_network::Host for WasiSocketsCtxView<'_> {Ok(network)}}++mod named {+ use crate::p2::bindings::named_imports::wasi::sockets::instance_network;+ use crate::p2::network::Network;+ use crate::sockets::WasiSocketsNamedView;+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::Resource;++ impl<T> instance_network::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn instance_network(&mut self, id: NamedId) -> Result<Resource<Network>, wasmtime::Error> {+ super::instance_network::Host::instance_network(&mut self.0.sockets(id))+ }+ }+}diff --git a/crates/wasi/src/p2/host/network.rs b/crates/wasi/src/p2/host/network.rsindex 501483a872..68d7d496c8 100644--- a/crates/wasi/src/p2/host/network.rs+++ b/crates/wasi/src/p2/host/network.rs@@ -217,3 +217,39 @@ impl std::net::ToSocketAddrs for Ipv6SocketAddress {std::net::SocketAddrV6::from(*self).to_socket_addrs()}}++mod named {+ use crate::p2::SocketError;+ use crate::p2::bindings::named_imports::wasi::sockets::network;+ use crate::p2::bindings::sockets::network::{ErrorCode, Network};+ use crate::sockets::WasiSocketsNamedView;+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::Error;+ use wasmtime::component::Resource;++ impl<T> network::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn convert_error_code(&mut self, error: SocketError) -> wasmtime::Result<ErrorCode> {+ error.downcast()+ }++ fn network_error_code(+ &mut self,+ id: NamedId,+ err: Resource<Error>,+ ) -> wasmtime::Result<Option<ErrorCode>> {+ super::network::Host::network_error_code(&mut self.0.sockets(id), err)+ }+ }++ impl<T> network::HostNetwork for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn drop(&mut self, id: NamedId, this: Resource<Network>) -> Result<(), wasmtime::Error> {+ super::network::HostNetwork::drop(&mut self.0.sockets(id), this)+ }+ }+}diff --git a/crates/wasi/src/p2/host/random.rs b/crates/wasi/src/p2/host/random.rsindex 889ab12a91..8061010988 100644--- a/crates/wasi/src/p2/host/random.rs+++ b/crates/wasi/src/p2/host/random.rs@@ -41,3 +41,48 @@ impl insecure_seed::Host for WasiRandomCtx {Ok((seed as u64, (seed >> 64) as u64))}}++mod named {+ use crate::p2::bindings::named_imports::wasi::random::{insecure, insecure_seed, random};+ use crate::random::WasiRandomNamedView;+ use crate::{NamedId, WasiCtxNamedView};++ impl<T> random::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiRandomNamedView,+ {+ fn get_random_bytes(&mut self, id: NamedId, len: u64) -> wasmtime::Result<Vec<u8>> {+ super::random::Host::get_random_bytes(self.0.random(id), len)+ }++ fn get_random_u64(&mut self, id: NamedId) -> wasmtime::Result<u64> {+ super::random::Host::get_random_u64(self.0.random(id))+ }+ }++ impl<T> insecure::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiRandomNamedView,+ {+ fn get_insecure_random_bytes(+ &mut self,+ id: NamedId,+ len: u64,+ ) -> wasmtime::Result<Vec<u8>> {+ super::insecure::Host::get_insecure_random_bytes(self.0.random(id), len)+ }++ fn get_insecure_random_u64(&mut self, id: NamedId) -> wasmtime::Result<u64> {+ super::insecure::Host::get_insecure_random_u64(self.0.random(id))+ }+ }++ impl<T> insecure_seed::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiRandomNamedView,+ {+ fn insecure_seed(&mut self, id: NamedId) -> wasmtime::Result<(u64, u64)> {+ super::insecure_seed::Host::insecure_seed(self.0.random(id))+ }+ }+}diff --git a/crates/wasi/src/p2/host/tcp.rs b/crates/wasi/src/p2/host/tcp.rsindex 27707fabbc..e73bdd5994 100644--- a/crates/wasi/src/p2/host/tcp.rs+++ b/crates/wasi/src/p2/host/tcp.rs@@ -540,3 +540,280 @@ pub mod sync {}}}++mod named {+ use crate::p2::SocketError;+ use crate::p2::SocketResult;+ use crate::p2::bindings::named_imports::wasi::sockets::tcp;+ use crate::p2::bindings::sockets::network::ErrorCode;+ use crate::p2::bindings::sockets::network::{IpAddressFamily, IpSocketAddress, Network};+ use crate::p2::bindings::sockets::tcp::ShutdownType;+ use crate::p2::tcp::TcpSocket;+ use crate::sockets::WasiSocketsNamedView;+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::Resource;+ use wasmtime_wasi_io::poll::DynPollable;+ use wasmtime_wasi_io::streams::{DynInputStream, DynOutputStream};++ impl<T> tcp::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn convert_error_code(&mut self, err: SocketError) -> wasmtime::Result<ErrorCode> {+ err.downcast()+ }+ }++ impl<T> tcp::HostTcpSocket for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ async fn start_bind(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ network: Resource<Network>,+ local_address: IpSocketAddress,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::start_bind(+ &mut self.0.sockets(id),+ this,+ network,+ local_address,+ )+ .await+ }++ fn finish_bind(&mut self, id: NamedId, this: Resource<TcpSocket>) -> SocketResult<()> {+ super::tcp::HostTcpSocket::finish_bind(&mut self.0.sockets(id), this)+ }++ fn start_connect(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ network: Resource<Network>,+ remote_address: IpSocketAddress,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::start_connect(+ &mut self.0.sockets(id),+ this,+ network,+ remote_address,+ )+ }++ fn finish_connect(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> SocketResult<(Resource<DynInputStream>, Resource<DynOutputStream>)> {+ super::tcp::HostTcpSocket::finish_connect(&mut self.0.sockets(id), this)+ }++ async fn start_listen(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::start_listen(&mut self.0.sockets(id), this).await+ }++ fn finish_listen(&mut self, id: NamedId, this: Resource<TcpSocket>) -> SocketResult<()> {+ super::tcp::HostTcpSocket::finish_listen(&mut self.0.sockets(id), this)+ }++ fn accept(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> SocketResult<(+ Resource<TcpSocket>,+ Resource<DynInputStream>,+ Resource<DynOutputStream>,+ )> {+ super::tcp::HostTcpSocket::accept(&mut self.0.sockets(id), this)+ }++ fn local_address(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> SocketResult<IpSocketAddress> {+ super::tcp::HostTcpSocket::local_address(&mut self.0.sockets(id), this)+ }++ fn remote_address(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> SocketResult<IpSocketAddress> {+ super::tcp::HostTcpSocket::remote_address(&mut self.0.sockets(id), this)+ }++ fn is_listening(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> Result<bool, wasmtime::Error> {+ super::tcp::HostTcpSocket::is_listening(&mut self.0.sockets(id), this)+ }++ fn address_family(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> Result<IpAddressFamily, wasmtime::Error> {+ super::tcp::HostTcpSocket::address_family(&mut self.0.sockets(id), this)+ }++ fn set_listen_backlog_size(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::set_listen_backlog_size(&mut self.0.sockets(id), this, value)+ }++ fn keep_alive_enabled(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> SocketResult<bool> {+ super::tcp::HostTcpSocket::keep_alive_enabled(&mut self.0.sockets(id), this)+ }++ fn set_keep_alive_enabled(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ value: bool,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::set_keep_alive_enabled(&mut self.0.sockets(id), this, value)+ }++ fn keep_alive_idle_time(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> SocketResult<u64> {+ super::tcp::HostTcpSocket::keep_alive_idle_time(&mut self.0.sockets(id), this)+ }++ fn set_keep_alive_idle_time(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::set_keep_alive_idle_time(+ &mut self.0.sockets(id),+ this,+ value,+ )+ }++ fn keep_alive_interval(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> SocketResult<u64> {+ super::tcp::HostTcpSocket::keep_alive_interval(&mut self.0.sockets(id), this)+ }++ fn set_keep_alive_interval(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::set_keep_alive_interval(&mut self.0.sockets(id), this, value)+ }++ fn keep_alive_count(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> SocketResult<u32> {+ super::tcp::HostTcpSocket::keep_alive_count(&mut self.0.sockets(id), this)+ }++ fn set_keep_alive_count(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ value: u32,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::set_keep_alive_count(&mut self.0.sockets(id), this, value)+ }++ fn hop_limit(&mut self, id: NamedId, this: Resource<TcpSocket>) -> SocketResult<u8> {+ super::tcp::HostTcpSocket::hop_limit(&mut self.0.sockets(id), this)+ }++ fn set_hop_limit(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ value: u8,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::set_hop_limit(&mut self.0.sockets(id), this, value)+ }++ fn receive_buffer_size(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> SocketResult<u64> {+ super::tcp::HostTcpSocket::receive_buffer_size(&mut self.0.sockets(id), this)+ }++ fn set_receive_buffer_size(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::set_receive_buffer_size(&mut self.0.sockets(id), this, value)+ }++ fn send_buffer_size(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> SocketResult<u64> {+ super::tcp::HostTcpSocket::send_buffer_size(&mut self.0.sockets(id), this)+ }++ fn set_send_buffer_size(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::set_send_buffer_size(&mut self.0.sockets(id), this, value)+ }++ fn subscribe(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ ) -> wasmtime::Result<Resource<DynPollable>> {+ super::tcp::HostTcpSocket::subscribe(&mut self.0.sockets(id), this)+ }++ fn shutdown(+ &mut self,+ id: NamedId,+ this: Resource<TcpSocket>,+ shutdown_type: ShutdownType,+ ) -> SocketResult<()> {+ super::tcp::HostTcpSocket::shutdown(&mut self.0.sockets(id), this, shutdown_type)+ }++ fn drop(&mut self, id: NamedId, this: Resource<TcpSocket>) -> Result<(), wasmtime::Error> {+ super::tcp::HostTcpSocket::drop(&mut self.0.sockets(id), this)+ }+ }+}diff --git a/crates/wasi/src/p2/host/tcp_create_socket.rs b/crates/wasi/src/p2/host/tcp_create_socket.rsindex e2c07db356..895a7f29a8 100644--- a/crates/wasi/src/p2/host/tcp_create_socket.rs+++ b/crates/wasi/src/p2/host/tcp_create_socket.rs@@ -22,3 +22,34 @@ impl From<IpAddressFamily> for SocketAddressFamily {}}}++mod named {+ use crate::p2::SocketError;+ use crate::p2::bindings::named_imports::wasi::sockets::tcp_create_socket;+ use crate::p2::bindings::sockets::network::ErrorCode;+ use crate::p2::bindings::sockets::network::IpAddressFamily;+ use crate::p2::{SocketResult, TcpSocket};+ use crate::sockets::WasiSocketsNamedView;+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::Resource;++ impl<T> tcp_create_socket::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn convert_error_code(&mut self, err: SocketError) -> wasmtime::Result<ErrorCode> {+ err.downcast()+ }++ fn create_tcp_socket(+ &mut self,+ id: NamedId,+ address_family: IpAddressFamily,+ ) -> SocketResult<Resource<TcpSocket>> {+ super::tcp_create_socket::Host::create_tcp_socket(+ &mut self.0.sockets(id),+ address_family,+ )+ }+ }+}diff --git a/crates/wasi/src/p2/host/udp.rs b/crates/wasi/src/p2/host/udp.rsindex 8aa15b38e1..029d97e568 100644--- a/crates/wasi/src/p2/host/udp.rs+++ b/crates/wasi/src/p2/host/udp.rs@@ -538,3 +538,223 @@ pub mod sync {}}}++mod named {+ use crate::p2::SocketError;+ use crate::p2::bindings::named_imports::wasi::sockets::udp;+ use crate::p2::bindings::sockets::network::ErrorCode;+ use crate::p2::bindings::sockets::network::{IpAddressFamily, IpSocketAddress, Network};+ use crate::p2::bindings::sockets::udp::{+ IncomingDatagram, IncomingDatagramStream, OutgoingDatagram, OutgoingDatagramStream,+ };+ use crate::p2::{SocketResult, UdpSocket};+ use crate::sockets::WasiSocketsNamedView;+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::Resource;+ use wasmtime_wasi_io::poll::DynPollable;++ impl<T> udp::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn convert_error_code(&mut self, err: SocketError) -> wasmtime::Result<ErrorCode> {+ err.downcast()+ }+ }++ impl<T> udp::HostUdpSocket for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ async fn start_bind(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ network: Resource<Network>,+ local_address: IpSocketAddress,+ ) -> SocketResult<()> {+ super::udp::HostUdpSocket::start_bind(+ &mut self.0.sockets(id),+ this,+ network,+ local_address,+ )+ .await+ }++ fn finish_bind(&mut self, id: NamedId, this: Resource<UdpSocket>) -> SocketResult<()> {+ super::udp::HostUdpSocket::finish_bind(&mut self.0.sockets(id), this)+ }++ async fn stream(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ remote_address: Option<IpSocketAddress>,+ ) -> SocketResult<(+ Resource<IncomingDatagramStream>,+ Resource<OutgoingDatagramStream>,+ )> {+ super::udp::HostUdpSocket::stream(&mut self.0.sockets(id), this, remote_address).await+ }++ fn local_address(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ ) -> SocketResult<IpSocketAddress> {+ super::udp::HostUdpSocket::local_address(&mut self.0.sockets(id), this)+ }++ fn remote_address(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ ) -> SocketResult<IpSocketAddress> {+ super::udp::HostUdpSocket::remote_address(&mut self.0.sockets(id), this)+ }++ fn address_family(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ ) -> Result<IpAddressFamily, wasmtime::Error> {+ super::udp::HostUdpSocket::address_family(&mut self.0.sockets(id), this)+ }++ fn unicast_hop_limit(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ ) -> SocketResult<u8> {+ super::udp::HostUdpSocket::unicast_hop_limit(&mut self.0.sockets(id), this)+ }++ fn set_unicast_hop_limit(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ value: u8,+ ) -> SocketResult<()> {+ super::udp::HostUdpSocket::set_unicast_hop_limit(&mut self.0.sockets(id), this, value)+ }++ fn receive_buffer_size(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ ) -> SocketResult<u64> {+ super::udp::HostUdpSocket::receive_buffer_size(&mut self.0.sockets(id), this)+ }++ fn set_receive_buffer_size(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::udp::HostUdpSocket::set_receive_buffer_size(&mut self.0.sockets(id), this, value)+ }++ fn send_buffer_size(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ ) -> SocketResult<u64> {+ super::udp::HostUdpSocket::send_buffer_size(&mut self.0.sockets(id), this)+ }++ fn set_send_buffer_size(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::udp::HostUdpSocket::set_send_buffer_size(&mut self.0.sockets(id), this, value)+ }++ fn subscribe(+ &mut self,+ id: NamedId,+ this: Resource<UdpSocket>,+ ) -> wasmtime::Result<Resource<DynPollable>> {+ super::udp::HostUdpSocket::subscribe(&mut self.0.sockets(id), this)+ }++ fn drop(&mut self, id: NamedId, this: Resource<UdpSocket>) -> Result<(), wasmtime::Error> {+ super::udp::HostUdpSocket::drop(&mut self.0.sockets(id), this)+ }+ }++ impl<T> udp::HostIncomingDatagramStream for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn receive(+ &mut self,+ id: NamedId,+ this: Resource<IncomingDatagramStream>,+ max_results: u64,+ ) -> SocketResult<Vec<IncomingDatagram>> {+ super::udp::HostIncomingDatagramStream::receive(+ &mut self.0.sockets(id),+ this,+ max_results,+ )+ }++ fn subscribe(+ &mut self,+ id: NamedId,+ this: Resource<IncomingDatagramStream>,+ ) -> wasmtime::Result<Resource<DynPollable>> {+ super::udp::HostIncomingDatagramStream::subscribe(&mut self.0.sockets(id), this)+ }++ async fn drop(+ &mut self,+ id: NamedId,+ this: Resource<IncomingDatagramStream>,+ ) -> Result<(), wasmtime::Error> {+ super::udp::HostIncomingDatagramStream::drop(&mut self.0.sockets(id), this).await+ }+ }++ impl<T> udp::HostOutgoingDatagramStream for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn check_send(+ &mut self,+ id: NamedId,+ this: Resource<OutgoingDatagramStream>,+ ) -> SocketResult<u64> {+ super::udp::HostOutgoingDatagramStream::check_send(&mut self.0.sockets(id), this)+ }++ fn send(+ &mut self,+ id: NamedId,+ this: Resource<OutgoingDatagramStream>,+ datagrams: Vec<OutgoingDatagram>,+ ) -> SocketResult<u64> {+ super::udp::HostOutgoingDatagramStream::send(&mut self.0.sockets(id), this, datagrams)+ }++ fn subscribe(+ &mut self,+ id: NamedId,+ this: Resource<OutgoingDatagramStream>,+ ) -> wasmtime::Result<Resource<DynPollable>> {+ super::udp::HostOutgoingDatagramStream::subscribe(&mut self.0.sockets(id), this)+ }++ async fn drop(+ &mut self,+ id: NamedId,+ this: Resource<OutgoingDatagramStream>,+ ) -> Result<(), wasmtime::Error> {+ super::udp::HostOutgoingDatagramStream::drop(&mut self.0.sockets(id), this).await+ }+ }+}diff --git a/crates/wasi/src/p2/host/udp_create_socket.rs b/crates/wasi/src/p2/host/udp_create_socket.rsindex a24115f440..5c6fa7cf05 100644--- a/crates/wasi/src/p2/host/udp_create_socket.rs+++ b/crates/wasi/src/p2/host/udp_create_socket.rs@@ -35,3 +35,35 @@ pub mod sync {}}}++mod named {+ use crate::p2::SocketError;+ use crate::p2::bindings::named_imports::wasi::sockets::udp_create_socket;+ use crate::p2::bindings::sockets::network::ErrorCode;+ use crate::p2::bindings::sockets::network::IpAddressFamily;+ use crate::p2::{SocketResult, UdpSocket};+ use crate::sockets::WasiSocketsNamedView;+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::Resource;++ impl<T> udp_create_socket::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn convert_error_code(&mut self, err: SocketError) -> wasmtime::Result<ErrorCode> {+ err.downcast()+ }++ async fn create_udp_socket(+ &mut self,+ id: NamedId,+ address_family: IpAddressFamily,+ ) -> SocketResult<Resource<UdpSocket>> {+ super::udp_create_socket::Host::create_udp_socket(+ &mut self.0.sockets(id),+ address_family,+ )+ .await+ }+ }+}diff --git a/crates/wasi/src/p2/ip_name_lookup.rs b/crates/wasi/src/p2/ip_name_lookup.rsindex 3867c31d7f..28c0806339 100644--- a/crates/wasi/src/p2/ip_name_lookup.rs+++ b/crates/wasi/src/p2/ip_name_lookup.rs@@ -118,3 +118,63 @@ mod sync {}}}++mod named {+ use crate::p2::SocketError;+ use crate::p2::bindings::named_imports::wasi::sockets::ip_name_lookup;+ use crate::p2::bindings::sockets::network::ErrorCode;+ use crate::p2::bindings::sockets::network::{IpAddress, Network};+ use crate::p2::ip_name_lookup::ResolveAddressStream;+ use crate::sockets::WasiSocketsNamedView;+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::Result;+ use wasmtime::component::Resource;+ use wasmtime_wasi_io::poll::DynPollable;++ impl<T> ip_name_lookup::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn convert_error_code(&mut self, err: SocketError) -> wasmtime::Result<ErrorCode> {+ err.downcast()+ }++ fn resolve_addresses(+ &mut self,+ id: NamedId,+ network: Resource<Network>,+ name: String,+ ) -> Result<Resource<ResolveAddressStream>, SocketError> {+ super::Host::resolve_addresses(&mut self.0.sockets(id), network, name)+ }+ }++ impl<T> ip_name_lookup::HostResolveAddressStream for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn resolve_next_address(+ &mut self,+ id: NamedId,+ resource: Resource<ResolveAddressStream>,+ ) -> Result<Option<IpAddress>, SocketError> {+ super::HostResolveAddressStream::resolve_next_address(&mut self.0.sockets(id), resource)+ }++ fn subscribe(+ &mut self,+ id: NamedId,+ resource: Resource<ResolveAddressStream>,+ ) -> Result<Resource<DynPollable>> {+ super::HostResolveAddressStream::subscribe(&mut self.0.sockets(id), resource)+ }++ async fn drop(+ &mut self,+ id: NamedId,+ resource: Resource<ResolveAddressStream>,+ ) -> Result<()> {+ super::HostResolveAddressStream::drop(&mut self.0.sockets(id), resource).await+ }+ }+}diff --git a/crates/wasi/src/p2/mod.rs b/crates/wasi/src/p2/mod.rsindex 7f66b79ed1..b76e2dd3f1 100644--- a/crates/wasi/src/p2/mod.rs+++ b/crates/wasi/src/p2/mod.rs@@ -225,13 +225,13 @@//! [`StdinStream`]: crate::cli::StdinStream//! [`StdoutStream`]: crate::cli::StdoutStream-use crate::WasiView;-use crate::cli::{WasiCli, WasiCliView as _};-use crate::clocks::{WasiClocks, WasiClocksView as _};-use crate::filesystem::{WasiFilesystem, WasiFilesystemView as _};-use crate::random::WasiRandom;-use crate::sockets::{WasiSockets, WasiSocketsView as _};-use wasmtime::component::{HasData, Linker, ResourceTable};+use crate::cli::{WasiCli, WasiCliNamed, WasiCliView as _};+use crate::clocks::{WasiClocks, WasiClocksNamed, WasiClocksView as _};+use crate::filesystem::{WasiFilesystem, WasiFilesystemNamed, WasiFilesystemView as _};+use crate::random::{WasiRandom, WasiRandomNamed};+use crate::sockets::{WasiSockets, WasiSocketsNamed, WasiSocketsView as _};+use crate::{NamedId, WasiCtxNamedView, WasiNamedView, WasiView};+use wasmtime::component::{Component, HasData, Linker, ResourceTable};pub mod bindings;pub(crate) mod filesystem;@@ -503,3 +503,309 @@ fn add_async_io_to_linker<T: WasiView>(l: &mut Linker<T>) -> wasmtime::Result<()wasmtime_wasi_io::bindings::wasi::io::streams::add_to_linker::<T, HasIo>(l, |t| t.ctx().table)?;Ok(())}++/// Interfaces that are added via [`add_named_to_linker_async`].+#[derive(Copy, Clone, PartialEq, Eq, Debug)]+pub enum Interface {+ /// `wasi:clocks/monotonic-clock`+ ClocksMonotonicClock,+ /// `wasi:clocks/wall-clock`+ ClocksWallClock,+ /// `wasi:random/random`+ RandomRandom,+ /// `wasi:random/insecure`+ RandomInsecure,+ /// `wasi:random/insecure-seed`+ RandomInsecureSeed,+ /// `wasi:cli/exit`+ CliExit,+ /// `wasi:cli/environment`+ CliEnvironment,+ /// `wasi:cli/stdin`+ CliStdin,+ /// `wasi:cli/stdout`+ CliStdout,+ /// `wasi:cli/stderr`+ CliStderr,+ /// `wasi:cli/terminal-input`+ CliTerminalInput,+ /// `wasi:cli/terminal-output`+ CliTerminalOutput,+ /// `wasi:cli/terminal-stdin`+ CliTerminalStdin,+ /// `wasi:cli/terminal-stdout`+ CliTerminalStdout,+ /// `wasi:cli/terminal-stderr`+ CliTerminalStderr,+ /// `wasi:filesystem/types`+ FilesystemTypes,+ /// `wasi:filesystem/preopens`+ FilesystemPreopens,+ /// `wasi:sockets/instance-network`+ SocketsInstanceNetwork,+ /// `wasi:sockets/network`+ SocketsNetwork,+ /// `wasi:sockets/ip-name-lookup`+ SocketsIpNameLookup,+ /// `wasi:sockets/tcp-create-socket`+ SocketsTcpCreateSocket,+ /// `wasi:sockets/tcp`+ SocketsTcp,+ /// `wasi:sockets/udp-create-socket`+ SocketsUdpCreateSocket,+ /// `wasi:sockets/udp`+ SocketsUdp,+}++/// Add all WASI interfaces from this crate into the `linker` provided for any+/// named imports that a component has.+///+/// This function is similar to [`add_to_linker_async`] except that it's specifically+/// designed to work with named imports of WASI interfaces that components may+/// have. This requires a [`Component`] parameter to be passed in when+/// populating the [`Linker`] provided to see what the [`Component`] actually+/// imports.+///+/// Like [`add_to_linker_async`] this adds the `async` variant of all+/// interfaces. If this isn't low level enough you can invoke the+/// bindgen-generated `add_to_linker` functions within the [`named_imports`]+/// module directly instead.+///+/// [`named_imports`]: crate::p2::bindings::named_imports+///+/// The `lookup` function provided here is invoked for every named import found+/// for a particular interface. The [`Interface`] given is what's being bound,+/// and the `&str` argument is the name that the component imports it as. The+/// embedder can then decide how it would like to allocate a [`NamedId`] for+/// this import. If `Ok` is returned then the linker is populated with this+/// name, and imported functions will pass the [`NamedId`] later to the+/// implementation of [`WasiNamedView`] on `T` when invoked. If `Err` is+/// returned then the error will cause this entire function to fail and this+/// function call will return the same error.+///+/// # Example+///+/// ```+/// use std::collections::HashMap;+/// use wasmtime::component::{Component, Linker, ResourceTable};+/// use wasmtime::{Engine, Result, Store, Config};+/// use wasmtime_wasi::{NamedId, WasiCtx, WasiCtxView, WasiNamedView};+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let component = Component::new(&engine, "(component)")?;+///+/// let mut linker = Linker::<MyState>::new(&engine);+///+/// // ... add default functionality to `linker` as needed ...+///+/// // and then additionally fill in any specific named imports `component`+/// // might have for WASI interfaces.+/// let mut name_map = HashMap::new();+/// wasmtime_wasi::p2::add_named_to_linker_async(&mut linker, &component, |_i, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// })?;+///+/// // Here a `WasiCtx` is allocated per-named-import and will then be+/// // referred to internally by the [`NamedId`] allocated above. You could+/// // also use `name_map` to configure each context differently.+/// let mut my_state = MyState::default();+/// for _ in 0..name_map.len() {+/// my_state.contexts.push(WasiCtx::default());+/// }+/// let mut store = Store::new(&engine, my_state);+///+/// // ... use `linker` to instantiate within `store` ...+///+/// Ok(())+/// }+///+/// #[derive(Default)]+/// struct MyState {+/// table: ResourceTable,+/// contexts: Vec<WasiCtx>,+/// }+///+/// impl WasiNamedView for MyState {+/// fn ctx(&mut self, id: NamedId) -> WasiCtxView<'_> {+/// WasiCtxView {+/// ctx: &mut self.contexts[id.0],+/// table: &mut self.table,+/// }+/// }+/// }+/// ```+pub fn add_named_to_linker_async<T>(+ linker: &mut Linker<T>,+ component: &Component,+ lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiNamedView,+{+ let options = bindings::LinkOptions::default();+ add_named_to_linker_with_options_async(linker, &options, component, lookup)+}++/// Same as [`add_named_to_linker_async`] except [`bindings::LinkOptions`]+/// can be specified to configure interfaces that are added.+pub fn add_named_to_linker_with_options_async<T>(+ linker: &mut Linker<T>,+ options: &bindings::LinkOptions,+ component: &Component,+ mut lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiNamedView,+{+ use crate::p2::bindings::named_imports::wasi::{cli, clocks, filesystem, random, sockets};++ let l = linker;+ clocks::wall_clock::add_to_linker::<T, WasiClocksNamed<T>>(+ l,+ component,+ |name| lookup(Interface::ClocksWallClock, name),+ |x| WasiCtxNamedView(x),+ )?;+ clocks::monotonic_clock::add_to_linker::<T, WasiClocksNamed<T>>(+ l,+ component,+ |name| lookup(Interface::ClocksMonotonicClock, name),+ |x| WasiCtxNamedView(x),+ )?;+ filesystem::types::add_to_linker::<T, WasiFilesystemNamed<T>>(+ l,+ component,+ |name| lookup(Interface::FilesystemTypes, name),+ |x| WasiCtxNamedView(x),+ )?;+ filesystem::preopens::add_to_linker::<T, WasiFilesystemNamed<T>>(+ l,+ component,+ |name| lookup(Interface::FilesystemPreopens, name),+ |x| WasiCtxNamedView(x),+ )?;+ random::random::add_to_linker::<T, WasiRandomNamed<T>>(+ l,+ component,+ |name| lookup(Interface::RandomRandom, name),+ |x| WasiCtxNamedView(x),+ )?;+ random::insecure::add_to_linker::<T, WasiRandomNamed<T>>(+ l,+ component,+ |name| lookup(Interface::RandomInsecure, name),+ |x| WasiCtxNamedView(x),+ )?;+ random::insecure_seed::add_to_linker::<T, WasiRandomNamed<T>>(+ l,+ component,+ |name| lookup(Interface::RandomInsecureSeed, name),+ |x| WasiCtxNamedView(x),+ )?;+ cli::exit::add_to_linker::<T, WasiCliNamed<T>>(+ l,+ component,+ |name| lookup(Interface::CliExit, name),+ |x| WasiCtxNamedView(x),+ )?;+ cli::environment::add_to_linker::<T, WasiCliNamed<T>>(+ l,+ component,+ |name| lookup(Interface::CliEnvironment, name),+ |x| WasiCtxNamedView(x),+ )?;+ cli::stdin::add_to_linker::<T, WasiCliNamed<T>>(+ l,+ component,+ |name| lookup(Interface::CliStdin, name),+ |x| WasiCtxNamedView(x),+ )?;+ cli::stdout::add_to_linker::<T, WasiCliNamed<T>>(+ l,+ component,+ |name| lookup(Interface::CliStdout, name),+ |x| WasiCtxNamedView(x),+ )?;+ cli::stderr::add_to_linker::<T, WasiCliNamed<T>>(+ l,+ component,+ |name| lookup(Interface::CliStderr, name),+ |x| WasiCtxNamedView(x),+ )?;+ cli::terminal_input::add_to_linker::<T, WasiCliNamed<T>>(+ l,+ component,+ |name| lookup(Interface::CliTerminalInput, name),+ |x| WasiCtxNamedView(x),+ )?;+ cli::terminal_output::add_to_linker::<T, WasiCliNamed<T>>(+ l,+ component,+ |name| lookup(Interface::CliTerminalOutput, name),+ |x| WasiCtxNamedView(x),+ )?;+ cli::terminal_stdin::add_to_linker::<T, WasiCliNamed<T>>(+ l,+ component,+ |name| lookup(Interface::CliTerminalStdin, name),+ |x| WasiCtxNamedView(x),+ )?;+ cli::terminal_stdout::add_to_linker::<T, WasiCliNamed<T>>(+ l,+ component,+ |name| lookup(Interface::CliTerminalStdout, name),+ |x| WasiCtxNamedView(x),+ )?;+ cli::terminal_stderr::add_to_linker::<T, WasiCliNamed<T>>(+ l,+ component,+ |name| lookup(Interface::CliTerminalStderr, name),+ |x| WasiCtxNamedView(x),+ )?;+ sockets::instance_network::add_to_linker::<T, WasiSocketsNamed<T>>(+ l,+ component,+ |name| lookup(Interface::SocketsInstanceNetwork, name),+ |x| WasiCtxNamedView(x),+ )?;+ sockets::network::add_to_linker::<T, WasiSocketsNamed<T>>(+ l,+ component,+ |name| lookup(Interface::SocketsNetwork, name),+ &options.into(),+ |x| WasiCtxNamedView(x),+ )?;+ sockets::ip_name_lookup::add_to_linker::<T, WasiSocketsNamed<T>>(+ l,+ component,+ |name| lookup(Interface::SocketsIpNameLookup, name),+ |x| WasiCtxNamedView(x),+ )?;+ sockets::tcp_create_socket::add_to_linker::<T, WasiSocketsNamed<T>>(+ l,+ component,+ |name| lookup(Interface::SocketsTcpCreateSocket, name),+ |x| WasiCtxNamedView(x),+ )?;+ sockets::tcp::add_to_linker::<T, WasiSocketsNamed<T>>(+ l,+ component,+ |name| lookup(Interface::SocketsTcp, name),+ |x| WasiCtxNamedView(x),+ )?;+ sockets::udp_create_socket::add_to_linker::<T, WasiSocketsNamed<T>>(+ l,+ component,+ |name| lookup(Interface::SocketsUdpCreateSocket, name),+ |x| WasiCtxNamedView(x),+ )?;+ sockets::udp::add_to_linker::<T, WasiSocketsNamed<T>>(+ l,+ component,+ |name| lookup(Interface::SocketsUdp, name),+ |x| WasiCtxNamedView(x),+ )?;+ Ok(())+}diff --git a/crates/wasi/src/p2/stdio.rs b/crates/wasi/src/p2/stdio.rsindex ffad53f7dd..a5906c642f 100644--- a/crates/wasi/src/p2/stdio.rs+++ b/crates/wasi/src/p2/stdio.rs@@ -80,3 +80,107 @@ impl terminal_stderr::Host for WasiCliCtxView<'_> {}}}++mod named {+ use crate::cli::WasiCliNamedView;+ use crate::p2::bindings::named_imports::wasi::cli::{+ stderr, stdin, stdout, terminal_input, terminal_output, terminal_stderr, terminal_stdin,+ terminal_stdout,+ };+ use crate::p2::stdio::{TerminalInput, TerminalOutput};+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::Resource;+ use wasmtime_wasi_io::streams;++ impl<T> stdin::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn get_stdin(+ &mut self,+ id: NamedId,+ ) -> Result<Resource<streams::DynInputStream>, wasmtime::Error> {+ super::stdin::Host::get_stdin(&mut self.0.cli(id))+ }+ }++ impl<T> stdout::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn get_stdout(+ &mut self,+ id: NamedId,+ ) -> Result<Resource<streams::DynOutputStream>, wasmtime::Error> {+ super::stdout::Host::get_stdout(&mut self.0.cli(id))+ }+ }++ impl<T> stderr::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn get_stderr(+ &mut self,+ id: NamedId,+ ) -> Result<Resource<streams::DynOutputStream>, wasmtime::Error> {+ super::stderr::Host::get_stderr(&mut self.0.cli(id))+ }+ }++ impl<T> terminal_input::Host for WasiCtxNamedView<'_, T> where T: WasiCliNamedView {}+ impl<T> terminal_input::HostTerminalInput for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn drop(&mut self, id: NamedId, r: Resource<TerminalInput>) -> wasmtime::Result<()> {+ super::terminal_input::HostTerminalInput::drop(&mut self.0.cli(id), r)+ }+ }++ impl<T> terminal_output::Host for WasiCtxNamedView<'_, T> where T: WasiCliNamedView {}+ impl<T> terminal_output::HostTerminalOutput for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn drop(&mut self, id: NamedId, r: Resource<TerminalOutput>) -> wasmtime::Result<()> {+ super::terminal_output::HostTerminalOutput::drop(&mut self.0.cli(id), r)+ }+ }++ impl<T> terminal_stdin::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn get_terminal_stdin(+ &mut self,+ id: NamedId,+ ) -> wasmtime::Result<Option<Resource<TerminalInput>>> {+ super::terminal_stdin::Host::get_terminal_stdin(&mut self.0.cli(id))+ }+ }++ impl<T> terminal_stdout::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn get_terminal_stdout(+ &mut self,+ id: NamedId,+ ) -> wasmtime::Result<Option<Resource<TerminalOutput>>> {+ super::terminal_stdout::Host::get_terminal_stdout(&mut self.0.cli(id))+ }+ }++ impl<T> terminal_stderr::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn get_terminal_stderr(+ &mut self,+ id: NamedId,+ ) -> wasmtime::Result<Option<Resource<TerminalOutput>>> {+ super::terminal_stderr::Host::get_terminal_stderr(&mut self.0.cli(id))+ }+ }+}diff --git a/crates/wasi/src/p3/bindings.rs b/crates/wasi/src/p3/bindings.rsindex 8951b28fbf..11be5fa17d 100644--- a/crates/wasi/src/p3/bindings.rs+++ b/crates/wasi/src/p3/bindings.rs@@ -106,10 +106,32 @@ mod generated {"wasi:filesystem/types.error-code" => crate::p3::filesystem::FilesystemError,"wasi:sockets/types.error-code" => crate::p3::sockets::SocketError,},+ named_imports: {+ "wasi:clocks/monotonic-clock": crate::NamedId,+ "wasi:clocks/system-clock": crate::NamedId,+ "wasi:random/random": crate::NamedId,+ "wasi:random/insecure": crate::NamedId,+ "wasi:random/insecure-seed": crate::NamedId,+ "wasi:cli/exit": crate::NamedId,+ "wasi:cli/environment": crate::NamedId,+ "wasi:cli/stdin": crate::NamedId,+ "wasi:cli/stdout": crate::NamedId,+ "wasi:cli/stderr": crate::NamedId,+ "wasi:cli/terminal-input": crate::NamedId,+ "wasi:cli/terminal-output": crate::NamedId,+ "wasi:cli/terminal-stdin": crate::NamedId,+ "wasi:cli/terminal-stdout": crate::NamedId,+ "wasi:cli/terminal-stderr": crate::NamedId,+ "wasi:filesystem/types": crate::NamedId,+ "wasi:filesystem/preopens": crate::NamedId,+ "wasi:sockets/types": crate::NamedId,+ "wasi:sockets/ip-name-lookup": crate::NamedId,+ },});}pub use self::generated::LinkOptions;pub use self::generated::exports;+pub use self::generated::named_imports;pub use self::generated::wasi::*;/// Bindings to execute and run a `wasi:cli/command`.diff --git a/crates/wasi/src/p3/cli/host.rs b/crates/wasi/src/p3/cli/host.rsindex cce2faa3b4..47f3f81ba4 100644--- a/crates/wasi/src/p3/cli/host.rs+++ b/crates/wasi/src/p3/cli/host.rs@@ -13,11 +13,12 @@ use core::task::{Context, Poll};use std::io;use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};use tokio::sync::oneshot;+use wasmtime::AsContextMut;use wasmtime::component::{Access, Destination, FutureReader, Resource, Source, StreamConsumer, StreamProducer,StreamReader, StreamResult,};-use wasmtime::{AsContextMut as _, StoreContextMut, error::Context as _, format_err};+use wasmtime::{StoreContextMut, error::Context as _, format_err};struct InputStreamProducer {rx: Pin<Box<dyn AsyncRead + Send + Sync>>,@@ -222,52 +223,68 @@ impl terminal_stderr::Host for WasiCliCtxView<'_> {}}+fn read_stdin(+ mut store: impl AsContextMut,+ stdin: Box<dyn AsyncRead + Send + Sync>,+) -> wasmtime::Result<(StreamReader<u8>, FutureReader<Result<(), ErrorCode>>)> {+ let mut store = store.as_context_mut();+ let (result_tx, result_rx) = oneshot::channel();+ let stream = StreamReader::new(+ &mut store,+ InputStreamProducer {+ rx: Box::into_pin(stdin),+ result_tx: Some(result_tx),+ },+ )?;+ let future = FutureReader::new(&mut store, async {+ wasmtime::error::Ok(match result_rx.await {+ Ok(err) => Err(err),+ Err(_) => Ok(()),+ })+ })?;+ Ok((stream, future))+}+impl<U> stdin::HostWithStore<U> for WasiCli {fn read_via_stream(mut store: Access<U, Self>,) -> wasmtime::Result<(StreamReader<u8>, FutureReader<Result<(), ErrorCode>>)> {let rx = store.get().ctx.stdin.async_stream();- let (result_tx, result_rx) = oneshot::channel();- let stream = StreamReader::new(- &mut store,- InputStreamProducer {- rx: Box::into_pin(rx),- result_tx: Some(result_tx),- },- )?;- let future = FutureReader::new(&mut store, async {- wasmtime::error::Ok(match result_rx.await {- Ok(err) => Err(err),- Err(_) => Ok(()),- })- })?;- Ok((stream, future))+ read_stdin(&mut store, rx)}}impl stdin::Host for WasiCliCtxView<'_> {}+fn write_output(+ mut store: impl AsContextMut,+ data: StreamReader<u8>,+ writer: Box<dyn AsyncWrite + Send + Sync>,+) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {+ let (result_tx, result_rx) = oneshot::channel();+ data.pipe(+ &mut store,+ OutputStreamConsumer {+ tx: Box::into_pin(writer),+ result_tx: Some(result_tx),+ flush_pending: false,+ },+ )?;+ FutureReader::new(&mut store, async {+ wasmtime::error::Ok(match result_rx.await {+ Ok(err) => Err(err),+ Err(_) => Ok(()),+ })+ })+}+impl<U> stdout::HostWithStore<U> for WasiCli {fn write_via_stream(mut store: Access<'_, U, Self>,data: StreamReader<u8>,) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {- let (result_tx, result_rx) = oneshot::channel();let tx = store.get().ctx.stdout.async_stream();- data.pipe(- &mut store,- OutputStreamConsumer {- tx: Box::into_pin(tx),- result_tx: Some(result_tx),- flush_pending: false,- },- )?;- FutureReader::new(&mut store, async {- wasmtime::error::Ok(match result_rx.await {- Ok(err) => Err(err),- Err(_) => Ok(()),- })- })+ write_output(store, data, tx)}}@@ -278,22 +295,8 @@ impl<U> stderr::HostWithStore<U> for WasiCli {mut store: Access<'_, U, Self>,data: StreamReader<u8>,) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {- let (result_tx, result_rx) = oneshot::channel();let tx = store.get().ctx.stderr.async_stream();- data.pipe(- &mut store,- OutputStreamConsumer {- tx: Box::into_pin(tx),- result_tx: Some(result_tx),- flush_pending: false,- },- )?;- FutureReader::new(&mut store, async {- wasmtime::error::Ok(match result_rx.await {- Ok(err) => Err(err),- Err(_) => Ok(()),- })- })+ write_output(store, data, tx)}}@@ -326,3 +329,149 @@ impl exit::Host for WasiCliCtxView<'_> {Err(format_err!(I32Exit(status_code.into())))}}++mod named {+ use crate::cli::{WasiCliNamed, WasiCliNamedView};+ use crate::p3::bindings::cli::types::ErrorCode;+ use crate::p3::bindings::named_imports::wasi::cli::{+ environment, exit, stderr, stdin, stdout, terminal_input, terminal_output, terminal_stderr,+ terminal_stdin, terminal_stdout,+ };+ use crate::p3::cli::{TerminalInput, TerminalOutput};+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::{Access, FutureReader, Resource, StreamReader};++ impl<T> exit::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn exit(&mut self, id: NamedId, status: Result<(), ()>) -> wasmtime::Result<()> {+ super::exit::Host::exit(&mut self.0.cli(id), status)+ }++ fn exit_with_code(&mut self, id: NamedId, status_code: u8) -> wasmtime::Result<()> {+ super::exit::Host::exit_with_code(&mut self.0.cli(id), status_code)+ }+ }++ impl<T> terminal_input::Host for WasiCtxNamedView<'_, T> where T: WasiCliNamedView {}+ impl<T> terminal_output::Host for WasiCtxNamedView<'_, T> where T: WasiCliNamedView {}++ impl<T> terminal_input::HostTerminalInput for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn drop(&mut self, id: NamedId, rep: Resource<TerminalInput>) -> wasmtime::Result<()> {+ super::terminal_input::HostTerminalInput::drop(&mut self.0.cli(id), rep)+ }+ }++ impl<T> terminal_output::HostTerminalOutput for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn drop(&mut self, id: NamedId, rep: Resource<TerminalOutput>) -> wasmtime::Result<()> {+ super::terminal_output::HostTerminalOutput::drop(&mut self.0.cli(id), rep)+ }+ }++ impl<T> terminal_stdin::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn get_terminal_stdin(+ &mut self,+ id: NamedId,+ ) -> wasmtime::Result<Option<Resource<TerminalInput>>> {+ super::terminal_stdin::Host::get_terminal_stdin(&mut self.0.cli(id))+ }+ }++ impl<T> terminal_stdout::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn get_terminal_stdout(+ &mut self,+ id: NamedId,+ ) -> wasmtime::Result<Option<Resource<TerminalOutput>>> {+ super::terminal_stdout::Host::get_terminal_stdout(&mut self.0.cli(id))+ }+ }++ impl<T> terminal_stderr::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn get_terminal_stderr(+ &mut self,+ id: NamedId,+ ) -> wasmtime::Result<Option<Resource<TerminalOutput>>> {+ super::terminal_stderr::Host::get_terminal_stderr(&mut self.0.cli(id))+ }+ }++ impl<T, U> stdin::HostWithStore<U> for WasiCliNamed<T>+ where+ T: WasiCliNamedView,+ {+ fn read_via_stream(+ mut store: Access<U, Self>,+ id: NamedId,+ ) -> wasmtime::Result<(StreamReader<u8>, FutureReader<Result<(), ErrorCode>>)> {+ let rx = store.get().0.cli(id).ctx.stdin.async_stream();+ super::read_stdin(&mut store, rx)+ }+ }++ impl<T> stdin::Host for WasiCtxNamedView<'_, T> where T: WasiCliNamedView {}++ impl<T, U> stdout::HostWithStore<U> for WasiCliNamed<T>+ where+ T: WasiCliNamedView,+ {+ fn write_via_stream(+ mut store: Access<'_, U, Self>,+ id: NamedId,+ data: StreamReader<u8>,+ ) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {+ let tx = store.get().0.cli(id).ctx.stdout.async_stream();+ super::write_output(store, data, tx)+ }+ }++ impl<T> stdout::Host for WasiCtxNamedView<'_, T> where T: WasiCliNamedView {}++ impl<T, U> stderr::HostWithStore<U> for WasiCliNamed<T>+ where+ T: WasiCliNamedView,+ {+ fn write_via_stream(+ mut store: Access<'_, U, Self>,+ id: NamedId,+ data: StreamReader<u8>,+ ) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {+ let tx = store.get().0.cli(id).ctx.stderr.async_stream();+ super::write_output(store, data, tx)+ }+ }++ impl<T> stderr::Host for WasiCtxNamedView<'_, T> where T: WasiCliNamedView {}++ impl<T> environment::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiCliNamedView,+ {+ fn get_environment(&mut self, id: NamedId) -> wasmtime::Result<Vec<(String, String)>> {+ super::environment::Host::get_environment(&mut self.0.cli(id))+ }++ fn get_arguments(&mut self, id: NamedId) -> wasmtime::Result<Vec<String>> {+ super::environment::Host::get_arguments(&mut self.0.cli(id))+ }++ fn get_initial_cwd(&mut self, id: NamedId) -> wasmtime::Result<Option<String>> {+ super::environment::Host::get_initial_cwd(&mut self.0.cli(id))+ }+ }+}diff --git a/crates/wasi/src/p3/cli/mod.rs b/crates/wasi/src/p3/cli/mod.rsindex 630bc748ea..6fc441c411 100644--- a/crates/wasi/src/p3/cli/mod.rs+++ b/crates/wasi/src/p3/cli/mod.rs@@ -1,11 +1,13 @@mod host;-use crate::cli::{WasiCli, WasiCliView};+use crate::cli::{WasiCli, WasiCliNamed, WasiCliNamedView, WasiCliView};+use crate::p3::Interface;use crate::p3::bindings::cli::{environment, exit, stderr, stdin, stdout, terminal_input, terminal_output, terminal_stderr,terminal_stdin, terminal_stdout,};-use wasmtime::component::Linker;+use crate::{NamedId, WasiCtxNamedView};+use wasmtime::component::{Component, Linker};/// Add all WASI interfaces from this module into the `linker` provided.///@@ -75,5 +77,163 @@ whereOk(())}+/// Convenience function to add `wasi:cli` interfaces into `linker` for any+/// named imports of `wasi:cli` interfaces.+///+/// This function is similar to [`add_to_linker`] except that it's specifically+/// designed to work with named imports of `wasi:cli` interfaces that components+/// may have. This requires a [`Component`] parameter to be passed in when+/// populating the [`Linker`] provided to see what the [`Component`] actually+/// imports.+///+/// Like [`add_to_linker`] this is a bit low level and you may want to possibly+/// invoke [`wasmtime_wasi::p3::add_named_to_linker`] instead. Alternatively if+/// this isn't low level enough you can additionally invoke bindgen-generated+/// `add_to_linker` functions directly from within the+/// [`named_imports::wasi::cli`] module.+///+/// [`wasmtime_wasi::p3::add_named_to_linker`]: crate::p3::add_named_to_linker+/// [`named_imports::wasi::cli`]: crate::p3::bindings::named_imports::wasi::cli+///+/// The `lookup` function provided here is invoked for every named import found+/// for a particular interface. The [`Interface`] given is what's being bound,+/// and the `&str` argument is the name that the component imports it as. The+/// embedder can then decide how it would like to allocate a [`NamedId`] for+/// this import. If `Ok` is returned then the linker is populated with this+/// name, and imported functions will pass the [`NamedId`] later to the+/// implementation of [`WasiCliNamedView`] on `T` when invoked. If `Err` is+/// returned then the error will cause this entire function to fail and this+/// function call will return the same error.+///+/// # Example+///+/// ```+/// use std::collections::HashMap;+/// use wasmtime::component::{Component, Linker, ResourceTable};+/// use wasmtime::{Engine, Result, Store, Config};+/// use wasmtime_wasi::NamedId;+/// use wasmtime_wasi::cli::{WasiCliCtx, WasiCliNamedView, WasiCliCtxView};+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let component = Component::new(&engine, "(component)")?;+///+/// let mut linker = Linker::<MyState>::new(&engine);+///+/// // ... add default functionality to `linker` as needed ...+///+/// // and then additionally fill in any specific named imports `component`+/// // might have for `wasi:cli` interfaces.+/// let mut name_map = HashMap::new();+/// wasmtime_wasi::p3::cli::add_named_to_linker(&mut linker, &component, |_i, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// })?;+///+/// // Here a `WasiCliCtx` is allocated per-named-import and will then be+/// // referred to internally by the [`NamedId`] allocated above. You could+/// // also use `name_map` to configure each context differently.+/// let mut my_state = MyState::default();+/// for _ in 0..name_map.len() {+/// my_state.contexts.push(WasiCliCtx::default());+/// }+/// let mut store = Store::new(&engine, my_state);+/// let instance = linker.instantiate(&mut store, &component)?;+///+/// // ... work with `instance` ...+///+/// Ok(())+/// }+///+/// #[derive(Default)]+/// struct MyState {+/// table: ResourceTable,+/// contexts: Vec<WasiCliCtx>,+/// }+///+/// impl WasiCliNamedView for MyState {+/// fn cli(&mut self, id: NamedId) -> WasiCliCtxView<'_> {+/// WasiCliCtxView {+/// ctx: &mut self.contexts[id.0],+/// table: &mut self.table,+/// }+/// }+/// }+/// ```+pub fn add_named_to_linker<T>(+ linker: &mut Linker<T>,+ component: &Component,+ mut lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiCliNamedView + 'static,+{+ use crate::p3::bindings::named_imports::wasi::cli::{+ environment, exit, stderr, stdin, stdout, terminal_input, terminal_output, terminal_stderr,+ terminal_stdin, terminal_stdout,+ };+ exit::add_to_linker::<_, WasiCliNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::CliExit, name),+ |x| WasiCtxNamedView(x),+ )?;+ environment::add_to_linker::<_, WasiCliNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::CliEnvironment, name),+ |x| WasiCtxNamedView(x),+ )?;+ stdin::add_to_linker::<_, WasiCliNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::CliStdin, name),+ |x| WasiCtxNamedView(x),+ )?;+ stdout::add_to_linker::<_, WasiCliNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::CliStdout, name),+ |x| WasiCtxNamedView(x),+ )?;+ stderr::add_to_linker::<_, WasiCliNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::CliStderr, name),+ |x| WasiCtxNamedView(x),+ )?;+ terminal_input::add_to_linker::<_, WasiCliNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::CliTerminalInput, name),+ |x| WasiCtxNamedView(x),+ )?;+ terminal_output::add_to_linker::<_, WasiCliNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::CliTerminalOutput, name),+ |x| WasiCtxNamedView(x),+ )?;+ terminal_stdin::add_to_linker::<_, WasiCliNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::CliTerminalStdin, name),+ |x| WasiCtxNamedView(x),+ )?;+ terminal_stdout::add_to_linker::<_, WasiCliNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::CliTerminalStdout, name),+ |x| WasiCtxNamedView(x),+ )?;+ terminal_stderr::add_to_linker::<_, WasiCliNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::CliTerminalStderr, name),+ |x| WasiCtxNamedView(x),+ )?;+ Ok(())+}+pub struct TerminalInput;pub struct TerminalOutput;diff --git a/crates/wasi/src/p3/clocks/host.rs b/crates/wasi/src/p3/clocks/host.rsindex a93438e587..55f08ad29d 100644--- a/crates/wasi/src/p3/clocks/host.rs+++ b/crates/wasi/src/p3/clocks/host.rs@@ -5,6 +5,17 @@ use core::time::Duration;use tokio::time::sleep;use wasmtime::component::Accessor;+impl WasiClocksCtxView<'_> {+ fn monotonic_wait_until_duration(&mut self, when: monotonic_clock::Mark) -> Option<Duration> {+ let clock_now = self.ctx.monotonic_clock.now();+ if when > clock_now {+ Some(Duration::from_nanos(when - clock_now))+ } else {+ None+ }+ }+}+impl types::Host for WasiClocksCtxView<'_> {}impl system_clock::Host for WasiClocksCtxView<'_> {@@ -27,10 +38,9 @@ impl<U> monotonic_clock::HostWithStore<U> for WasiClocks {store: &Accessor<U, Self>,when: monotonic_clock::Mark,) -> wasmtime::Result<()> {- let clock_now = store.with(|mut view| view.get().ctx.monotonic_clock.now());- if when > clock_now {- sleep(Duration::from_nanos(when - clock_now)).await;- };+ if let Some(dur) = store.with(|mut view| view.get().monotonic_wait_until_duration(when)) {+ sleep(dur).await;+ }Ok(())}@@ -54,3 +64,70 @@ impl monotonic_clock::Host for WasiClocksCtxView<'_> {Ok(self.ctx.monotonic_clock.resolution())}}++mod named {+ use crate::clocks::{WasiClocksNamed, WasiClocksNamedView};+ use crate::p3::bindings::clocks::monotonic_clock::Mark;+ use crate::p3::bindings::clocks::system_clock::Instant;+ use crate::p3::bindings::clocks::types;+ use crate::p3::bindings::named_imports::wasi::clocks::{monotonic_clock, system_clock};+ use crate::{NamedId, WasiCtxNamedView};+ use core::time::Duration;+ use tokio::time::sleep;+ use wasmtime::component::Accessor;++ impl<T> system_clock::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiClocksNamedView,+ {+ fn now(&mut self, id: NamedId) -> wasmtime::Result<Instant> {+ super::system_clock::Host::now(&mut self.0.clocks(id))+ }++ fn get_resolution(&mut self, id: NamedId) -> wasmtime::Result<types::Duration> {+ super::system_clock::Host::get_resolution(&mut self.0.clocks(id))+ }+ }++ impl<T, U> monotonic_clock::HostWithStore<U> for WasiClocksNamed<T>+ where+ T: WasiClocksNamedView,+ {+ async fn wait_until(+ store: &Accessor<U, Self>,+ id: NamedId,+ when: Mark,+ ) -> wasmtime::Result<()> {+ if let Some(dur) =+ store.with(|mut view| view.get().0.clocks(id).monotonic_wait_until_duration(when))+ {+ sleep(dur).await;+ }+ Ok(())+ }++ async fn wait_for(+ _store: &Accessor<U, Self>,+ _id: NamedId,+ duration: types::Duration,+ ) -> wasmtime::Result<()> {+ if duration > 0 {+ sleep(Duration::from_nanos(duration)).await;+ }+ Ok(())+ }+ }++ impl<T> monotonic_clock::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiClocksNamedView,+ {+ fn now(&mut self, id: NamedId) -> wasmtime::Result<Mark> {+ super::monotonic_clock::Host::now(&mut self.0.clocks(id))+ }++ fn get_resolution(&mut self, id: NamedId) -> wasmtime::Result<types::Duration> {+ super::monotonic_clock::Host::get_resolution(&mut self.0.clocks(id))+ }+ }+}diff --git a/crates/wasi/src/p3/clocks/mod.rs b/crates/wasi/src/p3/clocks/mod.rsindex 5a0298fd78..870af3778f 100644--- a/crates/wasi/src/p3/clocks/mod.rs+++ b/crates/wasi/src/p3/clocks/mod.rs@@ -1,8 +1,10 @@mod host;-use crate::clocks::{WasiClocks, WasiClocksView};+use crate::clocks::{WasiClocks, WasiClocksNamed, WasiClocksNamedView, WasiClocksView};+use crate::p3::Interface;use crate::p3::bindings::clocks::{monotonic_clock, system_clock, types};-use wasmtime::component::Linker;+use crate::{NamedId, WasiCtxNamedView};+use wasmtime::component::{Component, Linker};/// Add all WASI interfaces from this module into the `linker` provided.///@@ -62,6 +64,113 @@ whereOk(())}+/// Convenience function to add `wasi:clocks` interfaces into `linker` for any+/// named imports of `wasi:clocks` interfaces.+///+/// This function is similar to [`add_to_linker`] except that it's specifically+/// designed to work with named imports of `wasi:clocks` interfaces that+/// components may have. This requires a [`Component`] parameter to be passed in+/// when populating the [`Linker`] provided to see what the [`Component`]+/// actually imports.+///+/// Like [`add_to_linker`] this is a bit low level and you may want to possibly+/// invoke [`wasmtime_wasi::p3::add_named_to_linker`] instead. Alternatively if+/// this isn't low level enough you can additionally invoke bindgen-generated+/// `add_to_linker` functions directly from within the+/// [`named_imports::wasi::clocks`] module.+///+/// [`wasmtime_wasi::p3::add_named_to_linker`]: crate::p3::add_named_to_linker+/// [`named_imports::wasi::clocks`]: crate::p3::bindings::named_imports::wasi::clocks+///+/// The `lookup` function provided here is invoked for every named import found+/// for a particular interface. The [`Interface`] given is what's being bound,+/// and the `&str` argument is the name that the component imports it as. The+/// embedder can then decide how it would like to allocate a [`NamedId`] for+/// this import. If `Ok` is returned then the linker is populated with this+/// name, and imported functions will pass the [`NamedId`] later to the+/// implementation of [`WasiClocksNamedView`] on `T` when invoked. If `Err` is+/// returned then the error will cause this entire function to fail and this+/// function call will return the same error.+///+/// # Example+///+/// ```+/// use std::collections::HashMap;+/// use wasmtime::component::{Component, Linker, ResourceTable};+/// use wasmtime::{Engine, Result, Store, Config};+/// use wasmtime_wasi::NamedId;+/// use wasmtime_wasi::clocks::{WasiClocksCtx, WasiClocksCtxView, WasiClocksNamedView};+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let component = Component::new(&engine, "(component)")?;+///+/// let mut linker = Linker::<MyState>::new(&engine);+///+/// // ... add default functionality to `linker` as needed ...+///+/// // and then additionally fill in any specific named imports `component`+/// // might have for `wasi:clocks` interfaces.+/// let mut name_map = HashMap::new();+/// wasmtime_wasi::p3::clocks::add_named_to_linker(&mut linker, &component, |_i, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// })?;+///+/// // Here a `WasiClocksCtx` is allocated per-named-import and will then be+/// // referred to internally by the [`NamedId`] allocated above. You could+/// // also use `name_map` to configure each context differently.+/// let mut my_state = MyState::default();+/// for _ in 0..name_map.len() {+/// my_state.contexts.push(WasiClocksCtx::default());+/// }+/// let mut store = Store::new(&engine, my_state);+/// let instance = linker.instantiate(&mut store, &component)?;+///+/// // ... work with `instance` ...+///+/// Ok(())+/// }+///+/// #[derive(Default)]+/// struct MyState {+/// table: ResourceTable,+/// contexts: Vec<WasiClocksCtx>,+/// }+///+/// impl WasiClocksNamedView for MyState {+/// fn clocks(&mut self, id: NamedId) -> WasiClocksCtxView<'_> {+/// WasiClocksCtxView {+/// ctx: &mut self.contexts[id.0],+/// table: &mut self.table,+/// }+/// }+/// }+/// ```+pub fn add_named_to_linker<T>(+ linker: &mut Linker<T>,+ component: &Component,+ mut lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiClocksNamedView + 'static,+{+ use crate::p3::bindings::named_imports::wasi::clocks::{monotonic_clock, system_clock};+ monotonic_clock::add_to_linker::<_, WasiClocksNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::ClocksMonotonicClock, name),+ |x| WasiCtxNamedView(x),+ )?;+ system_clock::add_to_linker::<_, WasiClocksNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::ClocksSystemClock, name),+ |x| WasiCtxNamedView(x),+ )?;+ Ok(())+}+impl From<crate::clocks::Datetime> for system_clock::Instant {fn from(crate::clocks::Datetime {diff --git a/crates/wasi/src/p3/filesystem/host.rs b/crates/wasi/src/p3/filesystem/host.rsindex 6ea173bbe4..fbbceef740 100644--- a/crates/wasi/src/p3/filesystem/host.rs+++ b/crates/wasi/src/p3/filesystem/host.rs@@ -16,12 +16,12 @@ use std::sync::Arc;use std::time::SystemTime;use tokio::sync::{mpsc, oneshot};use tokio::task::{JoinHandle, spawn_blocking};-use wasmtime::StoreContextMut;use wasmtime::component::{Access, Accessor, Destination, FutureReader, Resource, ResourceTable, Source, StreamConsumer,StreamProducer, StreamReader, StreamResult,};use wasmtime::error::Context as _;+use wasmtime::{AsContextMut, StoreContextMut};fn get_descriptor<'a>(table: &'a ResourceTable,@@ -49,51 +49,12 @@ fn get_dir<'a>(Ok(dir)}-trait AccessorExt {- fn get_descriptor(&self, fd: &Resource<Descriptor>) -> FilesystemResult<Descriptor>;- fn get_file(&self, fd: &Resource<Descriptor>) -> FilesystemResult<File>;- fn get_dir(&self, fd: &Resource<Descriptor>) -> FilesystemResult<Dir>;- fn get_dir_pair(- &self,- a: &Resource<Descriptor>,- b: &Resource<Descriptor>,- ) -> FilesystemResult<(Dir, Dir)>;-}--impl<T> AccessorExt for Accessor<T, WasiFilesystem> {- fn get_descriptor(&self, fd: &Resource<Descriptor>) -> FilesystemResult<Descriptor> {- self.with(|mut store| {- let fd = get_descriptor(store.get().table, fd)?;- Ok(fd.clone())- })- }-- fn get_file(&self, fd: &Resource<Descriptor>) -> FilesystemResult<File> {- self.with(|mut store| {- let file = get_file(store.get().table, fd)?;- Ok(file.clone())- })- }-- fn get_dir(&self, fd: &Resource<Descriptor>) -> FilesystemResult<Dir> {- self.with(|mut store| {- let dir = get_dir(store.get().table, fd)?;- Ok(dir.clone())- })- }-- fn get_dir_pair(- &self,- a: &Resource<Descriptor>,- b: &Resource<Descriptor>,- ) -> FilesystemResult<(Dir, Dir)> {- self.with(|mut store| {- let table = store.get().table;- let a = get_dir(table, a)?;- let b = get_dir(table, b)?;- Ok((a.clone(), b.clone()))- })+fn get_writable_file(table: &ResourceTable, fd: &Resource<Descriptor>) -> FilesystemResult<File> {+ let file = get_file(table, fd)?;+ if file.perms.write_not_permitted() {+ return Err(ErrorCode::NotPermitted.into());}+ Ok(file.clone())}fn systemtime_from(t: system_clock::Instant) -> Result<std::time::SystemTime, ErrorCode> {@@ -382,20 +343,14 @@ enum WriteLocation {}impl WriteStreamConsumer {- fn new_at(file: File, offset: u64, result: oneshot::Sender<Result<(), ErrorCode>>) -> Self {- Self {- file,- location: WriteLocation::Offset(offset),- result: Some(result),- buffer: BytesMut::default(),- task: None,- }- }-- fn new_append(file: File, result: oneshot::Sender<Result<(), ErrorCode>>) -> Self {+ fn new(+ file: File,+ location: WriteLocation,+ result: oneshot::Sender<Result<(), ErrorCode>>,+ ) -> Self {Self {file,- location: WriteLocation::End,+ location,result: Some(result),buffer: BytesMut::default(),task: None,@@ -517,88 +472,406 @@ impl types::Host for WasiFilesystemCtxView<'_> {}}+fn read_via_stream(+ mut store: impl AsContextMut,+ fd: Descriptor,+ offset: Filesize,+) -> wasmtime::Result<(StreamReader<u8>, FutureReader<Result<(), ErrorCode>>)> {+ let mut store = store.as_context_mut();+ let file = match fd {+ Descriptor::File(file) => file,+ Descriptor::Dir(_) => {+ return Ok((+ StreamReader::new(&mut store, iter::empty())?,+ FutureReader::new(&mut store, async move {+ wasmtime::error::Ok(Err(ErrorCode::IsDirectory))+ })?,+ ));+ }+ };+ let (result_tx, result_rx) = oneshot::channel();+ Ok((+ StreamReader::new(+ &mut store,+ ReadStreamProducer {+ file,+ offset,+ result: Some(result_tx),+ task: None,+ },+ )?,+ FutureReader::new(&mut store, result_rx)?,+ ))+}++fn write_via_stream(+ mut store: impl AsContextMut,+ file: FilesystemResult<File>,+ mut data: StreamReader<u8>,+ location: WriteLocation,+) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {+ let mut store = store.as_context_mut();+ let (result_tx, result_rx) = oneshot::channel();+ match file {+ Ok(file) => {+ data.pipe(+ &mut store,+ WriteStreamConsumer::new(file, location, result_tx),+ )?;+ }+ Err(err) => {+ data.close(&mut store)?;+ let _ = result_tx.send(Err(err.downcast().unwrap_or(ErrorCode::Io)));+ }+ }+ FutureReader::new(&mut store, result_rx)+}++fn read_directory(+ mut store: impl AsContextMut,+ dir: FilesystemResult<Dir>,+) -> wasmtime::Result<(+ StreamReader<DirectoryEntry>,+ FutureReader<Result<(), ErrorCode>>,+)> {+ let mut store = store.as_context_mut();+ let (result_tx, result_rx) = oneshot::channel();+ let stream = match dir {+ Ok(dir) => {+ let allow_blocking_current_thread = dir.allow_blocking_current_thread;+ let dir = Arc::clone(dir.as_dir());+ if allow_blocking_current_thread {+ match crate::filesystem::primitives::read_base_dir(&dir) {+ Ok(readdir) => StreamReader::new(+ &mut store,+ FallibleIteratorProducer::new(+ readdir.filter_map(|e| map_dir_entry(e).transpose()),+ result_tx,+ ),+ )?,+ Err(e) => {+ let _ = result_tx.send(Err(e.into()));+ StreamReader::new(&mut store, iter::empty())?+ }+ }+ } else {+ StreamReader::new(&mut store, ReadDirStream::new(dir, result_tx))?+ }+ }+ Err(err) => {+ let _ = result_tx.send(Err(err.downcast().unwrap_or(ErrorCode::Io)));+ StreamReader::new(&mut store, iter::empty())?+ }+ };+ Ok((stream, FutureReader::new(&mut store, result_rx)?))+}++impl WasiFilesystemCtxView<'_> {+ fn advise(+ &self,+ fd: &Resource<Descriptor>,+ offset: Filesize,+ length: Filesize,+ advice: Advice,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let file = get_file(self.table, fd).cloned();+ async move {+ file?.advise(offset, length, advice.into()).await?;+ Ok(())+ }+ }++ fn get_flags(+ &self,+ fd: &Resource<Descriptor>,+ ) -> impl Future<Output = FilesystemResult<DescriptorFlags>> + use<> {+ let fd = get_descriptor(self.table, fd).cloned();+ async move {+ let flags = fd?.get_flags().await?;+ Ok(flags.into())+ }+ }++ fn get_type(+ &self,+ fd: &Resource<Descriptor>,+ ) -> impl Future<Output = FilesystemResult<DescriptorType>> + use<> {+ let fd = get_descriptor(self.table, fd).cloned();+ async move {+ let ty = fd?.get_type().await?;+ Ok(ty.into())+ }+ }++ fn set_size(+ &self,+ fd: &Resource<Descriptor>,+ size: Filesize,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let file = get_file(self.table, fd).cloned();+ async move {+ file?.set_size(size).await?;+ Ok(())+ }+ }++ fn set_times(+ &self,+ fd: &Resource<Descriptor>,+ data_access_timestamp: NewTimestamp,+ data_modification_timestamp: NewTimestamp,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let fd = get_descriptor(self.table, &fd).cloned();+ async move {+ let atim = systemtimespec_from(data_access_timestamp)?;+ let mtim = systemtimespec_from(data_modification_timestamp)?;+ fd?.set_times(atim, mtim).await?;+ Ok(())+ }+ }++ fn sync(+ &self,+ fd: &Resource<Descriptor>,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let fd = get_descriptor(self.table, &fd).cloned();+ async move {+ fd?.sync().await?;+ Ok(())+ }+ }++ fn sync_data(+ &self,+ fd: &Resource<Descriptor>,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let fd = get_descriptor(self.table, &fd).cloned();+ async move {+ fd?.sync_data().await?;+ Ok(())+ }+ }++ fn create_directory_at(+ &self,+ fd: &Resource<Descriptor>,+ path: String,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let dir = get_dir(self.table, &fd).cloned();+ async move {+ dir?.create_directory_at(path).await?;+ Ok(())+ }+ }++ fn stat(+ &self,+ fd: &Resource<Descriptor>,+ ) -> impl Future<Output = FilesystemResult<DescriptorStat>> + use<> {+ let fd = get_descriptor(self.table, &fd).cloned();+ async move {+ let stat = fd?.stat().await?;+ Ok(stat.into())+ }+ }++ fn stat_at(+ &self,+ fd: &Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ ) -> impl Future<Output = FilesystemResult<DescriptorStat>> + use<> {+ let dir = get_dir(self.table, &fd).cloned();+ async move {+ let stat = dir?.stat_at(path_flags.into(), path).await?;+ Ok(stat.into())+ }+ }++ fn set_times_at(+ &self,+ fd: &Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ data_access_timestamp: NewTimestamp,+ data_modification_timestamp: NewTimestamp,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let dir = get_dir(self.table, &fd).cloned();+ async move {+ let atim = systemtimespec_from(data_access_timestamp)?;+ let mtim = systemtimespec_from(data_modification_timestamp)?;+ dir?.set_times_at(path_flags.into(), path, atim, mtim)+ .await?;+ Ok(())+ }+ }++ fn link_at(+ &self,+ old_fd: &Resource<Descriptor>,+ old_path_flags: PathFlags,+ old_path: String,+ new_fd: &Resource<Descriptor>,+ new_path: String,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let old_dir = get_dir(self.table, old_fd).cloned();+ let new_dir = get_dir(self.table, new_fd).cloned();++ async move {+ old_dir?+ .link_at(old_path_flags.into(), old_path, &new_dir?, new_path)+ .await?;+ Ok(())+ }+ }++ fn open_at(+ &self,+ fd: &Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ open_flags: OpenFlags,+ flags: DescriptorFlags,+ ) -> impl Future<Output = FilesystemResult<Descriptor>> + use<> {+ let dir = get_dir(self.table, fd).cloned();+ let allow_blocking_current_thread = self.ctx.allow_blocking_current_thread;+ async move {+ let fd = dir?+ .open_at(+ path_flags.into(),+ path,+ open_flags.into(),+ flags.into(),+ allow_blocking_current_thread,+ )+ .await?;+ Ok(fd)+ }+ }++ fn readlink_at(+ &self,+ fd: &Resource<Descriptor>,+ path: String,+ ) -> impl Future<Output = FilesystemResult<String>> + use<> {+ let dir = get_dir(self.table, fd).cloned();+ async move { Ok(dir?.readlink_at(path).await?) }+ }++ fn remove_directory_at(+ &self,+ fd: &Resource<Descriptor>,+ path: String,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let dir = get_dir(self.table, fd).cloned();+ async move {+ dir?.remove_directory_at(path).await?;+ Ok(())+ }+ }++ fn rename_at(+ &self,+ fd: &Resource<Descriptor>,+ old_path: String,+ new_fd: &Resource<Descriptor>,+ new_path: String,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let old_dir = get_dir(self.table, fd).cloned();+ let new_dir = get_dir(self.table, new_fd).cloned();+ async move {+ old_dir?.rename_at(old_path, &new_dir?, new_path).await?;+ Ok(())+ }+ }++ fn symlink_at(+ &self,+ fd: &Resource<Descriptor>,+ old_path: String,+ new_path: String,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let dir = get_dir(self.table, fd).cloned();+ async move {+ dir?.symlink_at(old_path, new_path).await?;+ Ok(())+ }+ }++ fn unlink_file_at(+ &self,+ fd: &Resource<Descriptor>,+ path: String,+ ) -> impl Future<Output = FilesystemResult<()>> + use<> {+ let dir = get_dir(self.table, fd).cloned();+ async move {+ dir?.unlink_file_at(path).await?;+ Ok(())+ }+ }++ fn is_same_object(+ &self,+ fd: &Resource<Descriptor>,+ other: &Resource<Descriptor>,+ ) -> impl Future<Output = wasmtime::Result<bool>> + use<> {+ let fd = get_descriptor(self.table, fd).cloned();+ let other = get_descriptor(self.table, other).cloned();+ async move { fd?.is_same_object(&other?).await }+ }++ fn metadata_hash(+ &self,+ fd: &Resource<Descriptor>,+ ) -> impl Future<Output = FilesystemResult<MetadataHashValue>> + use<> {+ let fd = get_descriptor(self.table, fd).cloned();+ async move {+ let meta = fd?.metadata_hash().await?;+ Ok(meta.into())+ }+ }++ fn metadata_hash_at(+ &self,+ fd: &Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ ) -> impl Future<Output = FilesystemResult<MetadataHashValue>> + use<> {+ let dir = get_dir(self.table, fd).cloned();+ async move {+ let meta = dir?.metadata_hash_at(path_flags.into(), path).await?;+ Ok(meta.into())+ }+ }+}+impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {fn read_via_stream(mut store: Access<U, Self>,fd: Resource<Descriptor>,offset: Filesize,) -> wasmtime::Result<(StreamReader<u8>, FutureReader<Result<(), ErrorCode>>)> {- let file = match get_descriptor(store.get().table, &fd)? {- Descriptor::File(file) => file.clone(),- Descriptor::Dir(_) => {- return Ok((- StreamReader::new(&mut store, iter::empty())?,- FutureReader::new(&mut store, async move {- wasmtime::error::Ok(Err(ErrorCode::IsDirectory))- })?,- ));- }- };- let (result_tx, result_rx) = oneshot::channel();- Ok((- StreamReader::new(- &mut store,- ReadStreamProducer {- file,- offset,- result: Some(result_tx),- task: None,- },- )?,- FutureReader::new(&mut store, result_rx)?,- ))+ let fd = get_descriptor(store.get().table, &fd)?.clone();+ read_via_stream(&mut store, fd, offset)}fn write_via_stream(mut store: Access<'_, U, Self>,fd: Resource<Descriptor>,- mut data: StreamReader<u8>,+ data: StreamReader<u8>,offset: Filesize,) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {- let (result_tx, result_rx) = oneshot::channel();- match get_file(store.get().table, &fd).and_then(|file| {- if file.perms.write_not_permitted() {- Err(ErrorCode::NotPermitted.into())- } else {- Ok(file.clone())- }- }) {- Ok(file) => {- data.pipe(- &mut store,- WriteStreamConsumer::new_at(file, offset, result_tx),- )?;- }- Err(err) => {- data.close(&mut store)?;- let _ = result_tx.send(Err(err.downcast().unwrap_or(ErrorCode::Io)));- }- }- FutureReader::new(&mut store, result_rx)+ let file = get_writable_file(store.get().table, &fd);+ write_via_stream(&mut store, file, data, WriteLocation::Offset(offset))}fn append_via_stream(mut store: Access<'_, U, Self>,fd: Resource<Descriptor>,- mut data: StreamReader<u8>,+ data: StreamReader<u8>,) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {- let (result_tx, result_rx) = oneshot::channel();- match get_file(store.get().table, &fd).and_then(|file| {- if file.perms.write_not_permitted() {- Err(ErrorCode::NotPermitted.into())- } else {- Ok(file.clone())- }- }) {- Ok(file) => {- data.pipe(&mut store, WriteStreamConsumer::new_append(file, result_tx))?;- }- Err(err) => {- data.close(&mut store)?;- let _ = result_tx.send(Err(err.downcast().unwrap_or(ErrorCode::Io)));- }- }- FutureReader::new(&mut store, result_rx)+ let file = get_writable_file(store.get().table, &fd);+ write_via_stream(&mut store, file, data, WriteLocation::End)}async fn advise(@@ -608,36 +881,30 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {length: Filesize,advice: Advice,) -> FilesystemResult<()> {- let file = store.get_file(&fd)?;- file.advise(offset, length, advice.into()).await?;- Ok(())+ store+ .with(|mut s| s.get().advise(&fd, offset, length, advice))+ .await}async fn sync_data(store: &Accessor<U, Self>,fd: Resource<Descriptor>,) -> FilesystemResult<()> {- let fd = store.get_descriptor(&fd)?;- fd.sync_data().await?;- Ok(())+ store.with(|mut s| s.get().sync_data(&fd)).await}async fn get_flags(store: &Accessor<U, Self>,fd: Resource<Descriptor>,) -> FilesystemResult<DescriptorFlags> {- let fd = store.get_descriptor(&fd)?;- let flags = fd.get_flags().await?;- Ok(flags.into())+ store.with(|mut s| s.get().get_flags(&fd)).await}async fn get_type(store: &Accessor<U, Self>,fd: Resource<Descriptor>,) -> FilesystemResult<DescriptorType> {- let fd = store.get_descriptor(&fd)?;- let ty = fd.get_type().await?;- Ok(ty.into())+ store.with(|mut s| s.get().get_type(&fd)).await}async fn set_size(@@ -645,9 +912,7 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {fd: Resource<Descriptor>,size: Filesize,) -> FilesystemResult<()> {- let file = store.get_file(&fd)?;- file.set_size(size).await?;- Ok(())+ store.with(|mut s| s.get().set_size(&fd, size)).await}async fn set_times(@@ -656,11 +921,12 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {data_access_timestamp: NewTimestamp,data_modification_timestamp: NewTimestamp,) -> FilesystemResult<()> {- let fd = store.get_descriptor(&fd)?;- let atim = systemtimespec_from(data_access_timestamp)?;- let mtim = systemtimespec_from(data_modification_timestamp)?;- fd.set_times(atim, mtim).await?;- Ok(())+ store+ .with(|mut s| {+ s.get()+ .set_times(&fd, data_access_timestamp, data_modification_timestamp)+ })+ .await}fn read_directory(@@ -670,41 +936,12 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {StreamReader<DirectoryEntry>,FutureReader<Result<(), ErrorCode>>,)> {- let (result_tx, result_rx) = oneshot::channel();- let stream = match get_dir(store.get().table, &fd) {- Ok(dir) => {- let allow_blocking_current_thread = dir.allow_blocking_current_thread;- let dir = Arc::clone(dir.as_dir());- if allow_blocking_current_thread {- match crate::filesystem::primitives::read_base_dir(&dir) {- Ok(readdir) => StreamReader::new(- &mut store,- FallibleIteratorProducer::new(- readdir.filter_map(|e| map_dir_entry(e).transpose()),- result_tx,- ),- )?,- Err(e) => {- let _ = result_tx.send(Err(e.into()));- StreamReader::new(&mut store, iter::empty())?- }- }- } else {- StreamReader::new(&mut store, ReadDirStream::new(dir, result_tx))?- }- }- Err(err) => {- let _ = result_tx.send(Err(err.downcast().unwrap_or(ErrorCode::Io)));- StreamReader::new(&mut store, iter::empty())?- }- };- Ok((stream, FutureReader::new(&mut store, result_rx)?))+ let dir = get_dir(store.get().table, &fd).cloned();+ read_directory(&mut store, dir)}async fn sync(store: &Accessor<U, Self>, fd: Resource<Descriptor>) -> FilesystemResult<()> {- let fd = store.get_descriptor(&fd)?;- fd.sync().await?;- Ok(())+ store.with(|mut s| s.get().sync(&fd)).await}async fn create_directory_at(@@ -712,18 +949,16 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {fd: Resource<Descriptor>,path: String,) -> FilesystemResult<()> {- let dir = store.get_dir(&fd)?;- dir.create_directory_at(path).await?;- Ok(())+ store+ .with(|mut s| s.get().create_directory_at(&fd, path))+ .await}async fn stat(store: &Accessor<U, Self>,fd: Resource<Descriptor>,) -> FilesystemResult<DescriptorStat> {- let fd = store.get_descriptor(&fd)?;- let stat = fd.stat().await?;- Ok(stat.into())+ store.with(|mut s| s.get().stat(&fd)).await}async fn stat_at(@@ -732,9 +967,9 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {path_flags: PathFlags,path: String,) -> FilesystemResult<DescriptorStat> {- let dir = store.get_dir(&fd)?;- let stat = dir.stat_at(path_flags.into(), path).await?;- Ok(stat.into())+ store+ .with(|mut s| s.get().stat_at(&fd, path_flags, path))+ .await}async fn set_times_at(@@ -745,12 +980,17 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {data_access_timestamp: NewTimestamp,data_modification_timestamp: NewTimestamp,) -> FilesystemResult<()> {- let dir = store.get_dir(&fd)?;- let atim = systemtimespec_from(data_access_timestamp)?;- let mtim = systemtimespec_from(data_modification_timestamp)?;- dir.set_times_at(path_flags.into(), path, atim, mtim)- .await?;- Ok(())+ store+ .with(|mut s| {+ s.get().set_times_at(+ &fd,+ path_flags,+ path,+ data_access_timestamp,+ data_modification_timestamp,+ )+ })+ .await}async fn link_at(@@ -761,11 +1001,12 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {new_fd: Resource<Descriptor>,new_path: String,) -> FilesystemResult<()> {- let (old_dir, new_dir) = store.get_dir_pair(&fd, &new_fd)?;- old_dir- .link_at(old_path_flags.into(), old_path, &new_dir, new_path)- .await?;- Ok(())+ store+ .with(|mut s| {+ s.get()+ .link_at(&fd, old_path_flags, old_path, &new_fd, new_path)+ })+ .await}async fn open_at(@@ -776,19 +1017,8 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {open_flags: OpenFlags,flags: DescriptorFlags,) -> FilesystemResult<Resource<Descriptor>> {- let (allow_blocking_current_thread, dir) = store.with(|mut store| {- let store = store.get();- let dir = get_dir(&store.table, &fd)?;- FilesystemResult::Ok((store.ctx.allow_blocking_current_thread, dir.clone()))- })?;- let fd = dir- .open_at(- path_flags.into(),- path,- open_flags.into(),- flags.into(),- allow_blocking_current_thread,- )+ let fd = store+ .with(|mut s| s.get().open_at(&fd, path_flags, path, open_flags, flags)).await?;let fd = store.with(|mut store| store.get().table.push(fd))?;Ok(fd)@@ -799,9 +1029,7 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {fd: Resource<Descriptor>,path: String,) -> FilesystemResult<String> {- let dir = store.get_dir(&fd)?;- let path = dir.readlink_at(path).await?;- Ok(path)+ store.with(|mut s| s.get().readlink_at(&fd, path)).await}async fn remove_directory_at(@@ -809,9 +1037,9 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {fd: Resource<Descriptor>,path: String,) -> FilesystemResult<()> {- let dir = store.get_dir(&fd)?;- dir.remove_directory_at(path).await?;- Ok(())+ store+ .with(|mut s| s.get().remove_directory_at(&fd, path))+ .await}async fn rename_at(@@ -821,9 +1049,9 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {new_fd: Resource<Descriptor>,new_path: String,) -> FilesystemResult<()> {- let (old_dir, new_dir) = store.get_dir_pair(&fd, &new_fd)?;- old_dir.rename_at(old_path, &new_dir, new_path).await?;- Ok(())+ store+ .with(|mut s| s.get().rename_at(&fd, old_path, &new_fd, new_path))+ .await}async fn symlink_at(@@ -832,9 +1060,9 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {old_path: String,new_path: String,) -> FilesystemResult<()> {- let dir = store.get_dir(&fd)?;- dir.symlink_at(old_path, new_path).await?;- Ok(())+ store+ .with(|mut s| s.get().symlink_at(&fd, old_path, new_path))+ .await}async fn unlink_file_at(@@ -842,9 +1070,7 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {fd: Resource<Descriptor>,path: String,) -> FilesystemResult<()> {- let dir = store.get_dir(&fd)?;- dir.unlink_file_at(path).await?;- Ok(())+ store.with(|mut s| s.get().unlink_file_at(&fd, path)).await}async fn is_same_object(@@ -852,22 +1078,16 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {fd: Resource<Descriptor>,other: Resource<Descriptor>,) -> wasmtime::Result<bool> {- let (fd, other) = store.with(|mut store| {- let table = store.get().table;- let fd = get_descriptor(table, &fd)?.clone();- let other = get_descriptor(table, &other)?.clone();- wasmtime::error::Ok((fd, other))- })?;- fd.is_same_object(&other).await+ store+ .with(|mut s| s.get().is_same_object(&fd, &other))+ .await}async fn metadata_hash(store: &Accessor<U, Self>,fd: Resource<Descriptor>,) -> FilesystemResult<MetadataHashValue> {- let fd = store.get_descriptor(&fd)?;- let meta = fd.metadata_hash().await?;- Ok(meta.into())+ store.with(|mut s| s.get().metadata_hash(&fd)).await}async fn metadata_hash_at(@@ -876,9 +1096,9 @@ impl<U> types::HostDescriptorWithStore<U> for WasiFilesystem {path_flags: PathFlags,path: String,) -> FilesystemResult<MetadataHashValue> {- let dir = store.get_dir(&fd)?;- let meta = dir.metadata_hash_at(path_flags.into(), path).await?;- Ok(meta.into())+ store+ .with(|mut s| s.get().metadata_hash_at(&fd, path_flags, path))+ .await}}@@ -896,3 +1116,385 @@ impl preopens::Host for WasiFilesystemCtxView<'_> {self.get_directories()}}++mod named {+ use crate::filesystem::{Descriptor, WasiFilesystemNamed, WasiFilesystemNamedView};+ use crate::p3::bindings::filesystem::types::{+ Advice, DescriptorFlags, DescriptorStat, DescriptorType, DirectoryEntry, ErrorCode,+ Filesize, MetadataHashValue, NewTimestamp, OpenFlags, PathFlags,+ };+ use crate::p3::bindings::named_imports::wasi::filesystem::{preopens, types};+ use crate::p3::filesystem::{FilesystemError, FilesystemResult};+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::{Access, Accessor, FutureReader, Resource, StreamReader};++ impl<T> types::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiFilesystemNamedView,+ {+ fn convert_error_code(&mut self, error: FilesystemError) -> wasmtime::Result<ErrorCode> {+ error.downcast()+ }+ }++ impl<T, U> types::HostDescriptorWithStore<U> for WasiFilesystemNamed<T>+ where+ T: WasiFilesystemNamedView,+ {+ fn read_via_stream(+ mut store: Access<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ offset: Filesize,+ ) -> wasmtime::Result<(StreamReader<u8>, FutureReader<Result<(), ErrorCode>>)> {+ let fd = super::get_descriptor(store.get().0.filesystem(id).table, &fd)?.clone();+ super::read_via_stream(&mut store, fd, offset)+ }++ fn write_via_stream(+ mut store: Access<'_, U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ data: StreamReader<u8>,+ offset: Filesize,+ ) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {+ let file = super::get_writable_file(store.get().0.filesystem(id).table, &fd);+ super::write_via_stream(&mut store, file, data, super::WriteLocation::Offset(offset))+ }++ fn append_via_stream(+ mut store: Access<'_, U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ data: StreamReader<u8>,+ ) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {+ let file = super::get_writable_file(store.get().0.filesystem(id).table, &fd);+ super::write_via_stream(&mut store, file, data, super::WriteLocation::End)+ }++ async fn advise(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ offset: Filesize,+ length: Filesize,+ advice: Advice,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.advise(&fd, offset, length, advice)+ });+ result.await+ }++ async fn sync_data(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.sync_data(&fd)+ });+ result.await+ }++ async fn get_flags(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FilesystemResult<DescriptorFlags> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.get_flags(&fd)+ });+ result.await+ }++ async fn get_type(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FilesystemResult<DescriptorType> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.get_type(&fd)+ });+ result.await+ }++ async fn set_size(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ size: Filesize,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.set_size(&fd, size)+ });+ result.await+ }++ async fn set_times(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ data_access_timestamp: NewTimestamp,+ data_modification_timestamp: NewTimestamp,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.set_times(&fd, data_access_timestamp, data_modification_timestamp)+ });+ result.await+ }++ fn read_directory(+ mut store: Access<'_, U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> wasmtime::Result<(+ StreamReader<DirectoryEntry>,+ FutureReader<Result<(), ErrorCode>>,+ )> {+ let dir = super::get_dir(store.get().0.filesystem(id).table, &fd).cloned();+ super::read_directory(&mut store, dir)+ }++ async fn sync(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.sync(&fd)+ });+ result.await+ }++ async fn create_directory_at(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ path: String,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.create_directory_at(&fd, path)+ });+ result.await+ }++ async fn stat(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FilesystemResult<DescriptorStat> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.stat(&fd)+ });+ result.await+ }++ async fn stat_at(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ ) -> FilesystemResult<DescriptorStat> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.stat_at(&fd, path_flags, path)+ });+ result.await+ }++ async fn set_times_at(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ data_access_timestamp: NewTimestamp,+ data_modification_timestamp: NewTimestamp,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.set_times_at(+ &fd,+ path_flags,+ path,+ data_access_timestamp,+ data_modification_timestamp,+ )+ });+ result.await+ }++ async fn link_at(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ old_path_flags: PathFlags,+ old_path: String,+ new_fd: Resource<Descriptor>,+ new_path: String,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.link_at(&fd, old_path_flags, old_path, &new_fd, new_path)+ });+ result.await+ }++ async fn open_at(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ open_flags: OpenFlags,+ flags: DescriptorFlags,+ ) -> FilesystemResult<Resource<Descriptor>> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.open_at(&fd, path_flags, path, open_flags, flags)+ });+ let fd = result.await?;+ let fd = store.with(|mut store| store.get().0.filesystem(id).table.push(fd))?;+ Ok(fd)+ }++ async fn readlink_at(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ path: String,+ ) -> FilesystemResult<String> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.readlink_at(&fd, path)+ });+ result.await+ }++ async fn remove_directory_at(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ path: String,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.remove_directory_at(&fd, path)+ });+ result.await+ }++ async fn rename_at(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ old_path: String,+ new_fd: Resource<Descriptor>,+ new_path: String,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.rename_at(&fd, old_path, &new_fd, new_path)+ });+ result.await+ }++ async fn symlink_at(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ old_path: String,+ new_path: String,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.symlink_at(&fd, old_path, new_path)+ });+ result.await+ }++ async fn unlink_file_at(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ path: String,+ ) -> FilesystemResult<()> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.unlink_file_at(&fd, path)+ });+ result.await+ }++ async fn is_same_object(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ other: Resource<Descriptor>,+ ) -> wasmtime::Result<bool> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.is_same_object(&fd, &other)+ });+ result.await+ }++ async fn metadata_hash(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ ) -> FilesystemResult<MetadataHashValue> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.metadata_hash(&fd)+ });+ result.await+ }++ async fn metadata_hash_at(+ store: &Accessor<U, Self>,+ id: NamedId,+ fd: Resource<Descriptor>,+ path_flags: PathFlags,+ path: String,+ ) -> FilesystemResult<MetadataHashValue> {+ let result = store.with(|mut s| {+ let ctx = s.get().0.filesystem(id);+ ctx.metadata_hash_at(&fd, path_flags, path)+ });+ result.await+ }+ }++ impl<T> types::HostDescriptor for WasiCtxNamedView<'_, T>+ where+ T: WasiFilesystemNamedView,+ {+ fn drop(&mut self, id: NamedId, fd: Resource<Descriptor>) -> wasmtime::Result<()> {+ super::types::HostDescriptor::drop(&mut self.0.filesystem(id), fd)+ }+ }++ impl<T> preopens::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiFilesystemNamedView,+ {+ fn get_directories(+ &mut self,+ id: NamedId,+ ) -> wasmtime::Result<Vec<(Resource<Descriptor>, String)>> {+ super::preopens::Host::get_directories(&mut self.0.filesystem(id))+ }+ }+}diff --git a/crates/wasi/src/p3/filesystem/mod.rs b/crates/wasi/src/p3/filesystem/mod.rsindex 31ccb52ed6..fab4c4009a 100644--- a/crates/wasi/src/p3/filesystem/mod.rs+++ b/crates/wasi/src/p3/filesystem/mod.rs@@ -1,9 +1,13 @@mod host;use crate::TrappableError;-use crate::filesystem::{WasiFilesystem, WasiFilesystemView};+use crate::filesystem::{+ WasiFilesystem, WasiFilesystemNamed, WasiFilesystemNamedView, WasiFilesystemView,+};+use crate::p3::Interface;use crate::p3::bindings::filesystem::{preopens, types};-use wasmtime::component::Linker;+use crate::{NamedId, WasiCtxNamedView};+use wasmtime::component::{Component, Linker};pub type FilesystemResult<T> = Result<T, FilesystemError>;pub type FilesystemError = TrappableError<types::ErrorCode>;@@ -68,6 +72,113 @@ whereOk(())}+/// Convenience function to add `wasi:filesystem` interfaces into `linker` for any+/// named imports of `wasi:filesystem` interfaces.+///+/// This function is similar to [`add_to_linker`] except that it's specifically+/// designed to work with named imports of `wasi:filesystem` interfaces that+/// components may have. This requires a [`Component`] parameter to be passed in+/// when populating the [`Linker`] provided to see what the [`Component`]+/// actually imports.+///+/// Like [`add_to_linker`] this is a bit low level and you may want to possibly+/// invoke [`wasmtime_wasi::p3::add_named_to_linker`] instead. Alternatively if+/// this isn't low level enough you can additionally invoke bindgen-generated+/// `add_to_linker` functions directly from within the+/// [`named_imports::wasi::filesystem`] module.+///+/// [`wasmtime_wasi::p3::add_named_to_linker`]: crate::p3::add_named_to_linker+/// [`named_imports::wasi::filesystem`]: crate::p3::bindings::named_imports::wasi::filesystem+///+/// The `lookup` function provided here is invoked for every named import found+/// for a particular interface. The [`Interface`] given is what's being bound,+/// and the `&str` argument is the name that the component imports it as. The+/// embedder can then decide how it would like to allocate a [`NamedId`] for+/// this import. If `Ok` is returned then the linker is populated with this+/// name, and imported functions will pass the [`NamedId`] later to the+/// implementation of [`WasiFilesystemNamedView`] on `T` when invoked. If `Err` is+/// returned then the error will cause this entire function to fail and this+/// function call will return the same error.+///+/// # Example+///+/// ```+/// use std::collections::HashMap;+/// use wasmtime::component::{Component, Linker, ResourceTable};+/// use wasmtime::{Engine, Result, Store, Config};+/// use wasmtime_wasi::NamedId;+/// use wasmtime_wasi::filesystem::{WasiFilesystemCtx, WasiFilesystemCtxView, WasiFilesystemNamedView};+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let component = Component::new(&engine, "(component)")?;+///+/// let mut linker = Linker::<MyState>::new(&engine);+///+/// // ... add default functionality to `linker` as needed ...+///+/// // and then additionally fill in any specific named imports `component`+/// // might have for `wasi:filesystem` interfaces.+/// let mut name_map = HashMap::new();+/// wasmtime_wasi::p3::filesystem::add_named_to_linker(&mut linker, &component, |_i, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// })?;+///+/// // Here a `WasiFilesystemCtx` is allocated per-named-import and will then be+/// // referred to internally by the [`NamedId`] allocated above. You could+/// // also use `name_map` to configure each context differently.+/// let mut my_state = MyState::default();+/// for _ in 0..name_map.len() {+/// my_state.contexts.push(WasiFilesystemCtx::default());+/// }+/// let mut store = Store::new(&engine, my_state);+/// let instance = linker.instantiate(&mut store, &component)?;+///+/// // ... work with `instance` ...+///+/// Ok(())+/// }+///+/// #[derive(Default)]+/// struct MyState {+/// table: ResourceTable,+/// contexts: Vec<WasiFilesystemCtx>,+/// }+///+/// impl WasiFilesystemNamedView for MyState {+/// fn filesystem(&mut self, id: NamedId) -> WasiFilesystemCtxView<'_> {+/// WasiFilesystemCtxView {+/// ctx: &mut self.contexts[id.0],+/// table: &mut self.table,+/// }+/// }+/// }+/// ```+pub fn add_named_to_linker<T>(+ linker: &mut Linker<T>,+ component: &Component,+ mut lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiFilesystemNamedView + 'static,+{+ use crate::p3::bindings::named_imports::wasi::filesystem::{preopens, types};+ types::add_to_linker::<_, WasiFilesystemNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::FilesystemTypes, name),+ |x| WasiCtxNamedView(x),+ )?;+ preopens::add_to_linker::<_, WasiFilesystemNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::FilesystemPreopens, name),+ |x| WasiCtxNamedView(x),+ )?;+ Ok(())+}+impl<'a> From<&'a std::io::Error> for types::ErrorCode {fn from(err: &'a std::io::Error) -> Self {crate::filesystem::ErrorCode::from(err).into()diff --git a/crates/wasi/src/p3/mod.rs b/crates/wasi/src/p3/mod.rsindex 96df64a067..303bbd9f35 100644--- a/crates/wasi/src/p3/mod.rs+++ b/crates/wasi/src/p3/mod.rs@@ -15,13 +15,15 @@ pub mod filesystem;pub mod random;pub mod sockets;-use crate::WasiView;use crate::p3::bindings::LinkOptions;+use crate::{NamedId, WasiNamedView, WasiView};use core::pin::Pin;use core::task::{Context, Poll};use tokio::sync::oneshot;use wasmtime::StoreContextMut;-use wasmtime::component::{Destination, Linker, StreamProducer, StreamResult, VecBuffer};+use wasmtime::component::{+ Component, Destination, Linker, StreamProducer, StreamResult, VecBuffer,+};// Default buffer capacity to use for reads of byte-sized values.const DEFAULT_BUFFER_CAPACITY: usize = 8192;@@ -190,3 +192,159 @@ wheresockets::add_to_linker(linker)?;Ok(())}++/// Interfaces that are added via [`add_named_to_linker`].+#[derive(Copy, Clone, PartialEq, Eq, Debug)]+pub enum Interface {+ /// `wasi:clocks/monotonic-clock`+ ClocksMonotonicClock,+ /// `wasi:clocks/system-clock`+ ClocksSystemClock,+ /// `wasi:random/random`+ RandomRandom,+ /// `wasi:random/insecure`+ RandomInsecure,+ /// `wasi:random/insecure-seed`+ RandomInsecureSeed,+ /// `wasi:cli/exit`+ CliExit,+ /// `wasi:cli/environment`+ CliEnvironment,+ /// `wasi:cli/stdin`+ CliStdin,+ /// `wasi:cli/stdout`+ CliStdout,+ /// `wasi:cli/stderr`+ CliStderr,+ /// `wasi:cli/terminal-input`+ CliTerminalInput,+ /// `wasi:cli/terminal-output`+ CliTerminalOutput,+ /// `wasi:cli/terminal-stdin`+ CliTerminalStdin,+ /// `wasi:cli/terminal-stdout`+ CliTerminalStdout,+ /// `wasi:cli/terminal-stderr`+ CliTerminalStderr,+ /// `wasi:filesystem/types`+ FilesystemTypes,+ /// `wasi:filesystem/preopens`+ FilesystemPreopens,+ /// `wasi:sockets/types`+ SocketsTypes,+ /// `wasi:sockets/ip-name-lookup`+ SocketsIpNameLookup,+}++/// Add all WASI interfaces from this module into the `linker` provided for any+/// named imports that a component has.+///+/// This function is similar to [`add_to_linker`] except that it's specifically+/// designed to work with named imports of WASI interfaces that components may+/// have. This requires a [`Component`] parameter to be passed in when+/// populating the [`Linker`] provided to see what the [`Component`] actually+/// imports.+///+/// All interfaces implemented by this module are added here, so the+/// per-package functions such as [`cli::add_named_to_linker`] do not+/// additionally need to be invoked. If this isn't low level enough you can+/// invoke those functions, or the bindgen-generated `add_to_linker` functions+/// within the [`named_imports`] module, directly instead.+///+/// [`named_imports`]: crate::p3::bindings::named_imports+///+/// The `lookup` function provided here is invoked for every named import found+/// for a particular interface. The [`Interface`] given is what's being bound,+/// and the `&str` argument is the name that the component imports it as. The+/// embedder can then decide how it would like to allocate a [`NamedId`] for+/// this import. If `Ok` is returned then the linker is populated with this+/// name, and imported functions will pass the [`NamedId`] later to the+/// implementation of [`WasiNamedView`] on `T` when invoked. If `Err` is+/// returned then the error will cause this entire function to fail and this+/// function call will return the same error.+///+/// # Example+///+/// ```+/// use std::collections::HashMap;+/// use wasmtime::component::{Component, Linker, ResourceTable};+/// use wasmtime::{Engine, Result, Store, Config};+/// use wasmtime_wasi::{NamedId, WasiCtx, WasiCtxView, WasiNamedView};+///+/// fn main() -> Result<()> {+/// let mut config = Config::new();+/// config.wasm_component_model_async(true);+/// let engine = Engine::new(&config)?;+/// let component = Component::new(&engine, "(component)")?;+///+/// let mut linker = Linker::<MyState>::new(&engine);+///+/// // ... add default functionality to `linker` as needed ...+///+/// // and then additionally fill in any specific named imports `component`+/// // might have for WASI interfaces.+/// let mut name_map = HashMap::new();+/// wasmtime_wasi::p3::add_named_to_linker(&mut linker, &component, |_i, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// })?;+///+/// // Here a `WasiCtx` is allocated per-named-import and will then be+/// // referred to internally by the [`NamedId`] allocated above. You could+/// // also use `name_map` to configure each context differently.+/// let mut my_state = MyState::default();+/// for _ in 0..name_map.len() {+/// my_state.contexts.push(WasiCtx::default());+/// }+/// let mut store = Store::new(&engine, my_state);+///+/// // ... use `linker` to instantiate within `store` ...+///+/// Ok(())+/// }+///+/// #[derive(Default)]+/// struct MyState {+/// table: ResourceTable,+/// contexts: Vec<WasiCtx>,+/// }+///+/// impl WasiNamedView for MyState {+/// fn ctx(&mut self, id: NamedId) -> WasiCtxView<'_> {+/// WasiCtxView {+/// ctx: &mut self.contexts[id.0],+/// table: &mut self.table,+/// }+/// }+/// }+/// ```+pub fn add_named_to_linker<T>(+ linker: &mut Linker<T>,+ component: &Component,+ lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiNamedView + 'static,+{+ let options = LinkOptions::default();+ add_named_to_linker_with_options(linker, &options, component, lookup)+}++/// Same as [`add_named_to_linker`] except [`LinkOptions`] can be specified to+/// configure interfaces that are added.+pub fn add_named_to_linker_with_options<T>(+ linker: &mut Linker<T>,+ _options: &LinkOptions,+ component: &Component,+ mut lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiNamedView + 'static,+{+ cli::add_named_to_linker(linker, component, &mut lookup)?;+ clocks::add_named_to_linker(linker, component, &mut lookup)?;+ filesystem::add_named_to_linker(linker, component, &mut lookup)?;+ random::add_named_to_linker(linker, component, &mut lookup)?;+ sockets::add_named_to_linker(linker, component, &mut lookup)?;+ Ok(())+}diff --git a/crates/wasi/src/p3/random/host.rs b/crates/wasi/src/p3/random/host.rsindex 540afe126c..fa5f3328cf 100644--- a/crates/wasi/src/p3/random/host.rs+++ b/crates/wasi/src/p3/random/host.rs@@ -34,3 +34,48 @@ impl insecure_seed::Host for WasiRandomCtx {Ok((seed as u64, (seed >> 64) as u64))}}++mod named {+ use crate::p3::bindings::named_imports::wasi::random::{insecure, insecure_seed, random};+ use crate::random::WasiRandomNamedView;+ use crate::{NamedId, WasiCtxNamedView};++ impl<T> random::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiRandomNamedView,+ {+ fn get_random_bytes(&mut self, id: NamedId, len: u64) -> wasmtime::Result<Vec<u8>> {+ super::random::Host::get_random_bytes(&mut self.0.random(id), len)+ }++ fn get_random_u64(&mut self, id: NamedId) -> wasmtime::Result<u64> {+ super::random::Host::get_random_u64(&mut self.0.random(id))+ }+ }++ impl<T> insecure::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiRandomNamedView,+ {+ fn get_insecure_random_bytes(+ &mut self,+ id: NamedId,+ len: u64,+ ) -> wasmtime::Result<Vec<u8>> {+ super::insecure::Host::get_insecure_random_bytes(&mut self.0.random(id), len)+ }++ fn get_insecure_random_u64(&mut self, id: NamedId) -> wasmtime::Result<u64> {+ super::insecure::Host::get_insecure_random_u64(&mut self.0.random(id))+ }+ }++ impl<T> insecure_seed::Host for WasiCtxNamedView<'_, T>+ where+ T: WasiRandomNamedView,+ {+ fn get_insecure_seed(&mut self, id: NamedId) -> wasmtime::Result<(u64, u64)> {+ super::insecure_seed::Host::get_insecure_seed(&mut self.0.random(id))+ }+ }+}diff --git a/crates/wasi/src/p3/random/mod.rs b/crates/wasi/src/p3/random/mod.rsindex 2ac7338422..0cfbd73428 100644--- a/crates/wasi/src/p3/random/mod.rs+++ b/crates/wasi/src/p3/random/mod.rs@@ -1,8 +1,10 @@mod host;+use crate::p3::Interface;use crate::p3::bindings::random::{insecure, insecure_seed, random};-use crate::random::{WasiRandom, WasiRandomView};-use wasmtime::component::Linker;+use crate::random::{WasiRandom, WasiRandomNamed, WasiRandomNamedView, WasiRandomView};+use crate::{NamedId, WasiCtxNamedView};+use wasmtime::component::{Component, Linker};/// Add all WASI interfaces from this module into the `linker` provided.///@@ -58,3 +60,112 @@ whereinsecure_seed::add_to_linker::<_, WasiRandom>(linker, T::random)?;Ok(())}++/// Convenience function to add `wasi:random` interfaces into `linker` for any+/// named imports of `wasi:random` interfaces.+///+/// This function is similar to [`add_to_linker`] except that it's specifically+/// designed to work with named imports of `wasi:random` interfaces that+/// components may have. This requires a [`Component`] parameter to be passed in+/// when populating the [`Linker`] provided to see what the [`Component`]+/// actually imports.+///+/// Like [`add_to_linker`] this is a bit low level and you may want to possibly+/// invoke [`wasmtime_wasi::p3::add_named_to_linker`] instead. Alternatively if+/// this isn't low level enough you can additionally invoke bindgen-generated+/// `add_to_linker` functions directly from within the+/// [`named_imports::wasi::random`] module.+///+/// [`wasmtime_wasi::p3::add_named_to_linker`]: crate::p3::add_named_to_linker+/// [`named_imports::wasi::random`]: crate::p3::bindings::named_imports::wasi::random+///+/// The `lookup` function provided here is invoked for every named import found+/// for a particular interface. The [`Interface`] given is what's being bound,+/// and the `&str` argument is the name that the component imports it as. The+/// embedder can then decide how it would like to allocate a [`NamedId`] for+/// this import. If `Ok` is returned then the linker is populated with this+/// name, and imported functions will pass the [`NamedId`] later to the+/// implementation of [`WasiRandomNamedView`] on `T` when invoked. If `Err` is+/// returned then the error will cause this entire function to fail and this+/// function call will return the same error.+///+/// # Example+///+/// ```+/// use std::collections::HashMap;+/// use wasmtime::component::{Component, Linker};+/// use wasmtime::{Engine, Result, Store, Config};+/// use wasmtime_wasi::NamedId;+/// use wasmtime_wasi::random::{WasiRandomCtx, WasiRandomNamedView};+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let component = Component::new(&engine, "(component)")?;+///+/// let mut linker = Linker::<MyState>::new(&engine);+///+/// // ... add default functionality to `linker` as needed ...+///+/// // and then additionally fill in any specific named imports `component`+/// // might have for `wasi:random` interfaces.+/// let mut name_map = HashMap::new();+/// wasmtime_wasi::p3::random::add_named_to_linker(&mut linker, &component, |_i, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// })?;+///+/// // Here a `WasiRandomCtx` is allocated per-named-import and will then be+/// // referred to internally by the [`NamedId`] allocated above. You could+/// // also use `name_map` to configure each context differently.+/// let mut my_state = MyState::default();+/// for _ in 0..name_map.len() {+/// my_state.contexts.push(WasiRandomCtx::default());+/// }+/// let mut store = Store::new(&engine, my_state);+/// let instance = linker.instantiate(&mut store, &component)?;+///+/// // ... work with `instance` ...+///+/// Ok(())+/// }+///+/// #[derive(Default)]+/// struct MyState {+/// contexts: Vec<WasiRandomCtx>,+/// }+///+/// impl WasiRandomNamedView for MyState {+/// fn random(&mut self, id: NamedId) -> &mut WasiRandomCtx {+/// &mut self.contexts[id.0]+/// }+/// }+/// ```+pub fn add_named_to_linker<T>(+ linker: &mut Linker<T>,+ component: &Component,+ mut lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiRandomNamedView + 'static,+{+ use crate::p3::bindings::named_imports::wasi::random::{insecure, insecure_seed, random};+ random::add_to_linker::<_, WasiRandomNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::RandomRandom, name),+ |x| WasiCtxNamedView(x),+ )?;+ insecure::add_to_linker::<_, WasiRandomNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::RandomInsecure, name),+ |x| WasiCtxNamedView(x),+ )?;+ insecure_seed::add_to_linker::<_, WasiRandomNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::RandomInsecureSeed, name),+ |x| WasiCtxNamedView(x),+ )?;+ Ok(())+}diff --git a/crates/wasi/src/p3/sockets/host/ip_name_lookup.rs b/crates/wasi/src/p3/sockets/host/ip_name_lookup.rsindex 084e9af317..d4bab90ceb 100644--- a/crates/wasi/src/p3/sockets/host/ip_name_lookup.rs+++ b/crates/wasi/src/p3/sockets/host/ip_name_lookup.rs@@ -10,12 +10,52 @@ impl<U> HostWithStore<U> for WasiSockets {store: &Accessor<U, Self>,name: String,) -> wasmtime::Result<Result<Vec<types::IpAddress>, ErrorCode>> {- let fut = store.with(|mut view| resolve_addresses(&view.get().ctx, name));- Ok(match fut.await {- Ok(addrs) => Ok(addrs.into_iter().map(|addr| addr.into()).collect()),- Err(err) => Err(err.into()),- })+ store+ .with(|mut view| view.get().resolve_addresses(name))+ .await}}impl Host for WasiSocketsCtxView<'_> {}++impl WasiSocketsCtxView<'_> {+ fn resolve_addresses(+ &self,+ name: String,+ ) -> impl Future<Output = wasmtime::Result<Result<Vec<types::IpAddress>, ErrorCode>>> + use<>+ {+ let fut = resolve_addresses(self.ctx, name);+ async move {+ Ok(match fut.await {+ Ok(addrs) => Ok(addrs.into_iter().map(|addr| addr.into()).collect()),+ Err(err) => Err(err.into()),+ })+ }+ }+}++mod named {+ use crate::p3::bindings::named_imports::wasi::sockets::ip_name_lookup::{Host, HostWithStore};+ use crate::p3::bindings::sockets::ip_name_lookup::ErrorCode;+ use crate::p3::bindings::sockets::types;+ use crate::sockets::{WasiSocketsNamed, WasiSocketsNamedView};+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::Accessor;++ impl<T, U> HostWithStore<U> for WasiSocketsNamed<T>+ where+ T: WasiSocketsNamedView,+ {+ async fn resolve_addresses(+ store: &Accessor<U, Self>,+ id: NamedId,+ name: String,+ ) -> wasmtime::Result<Result<Vec<types::IpAddress>, ErrorCode>> {+ store+ .with(|mut view| view.get().0.sockets(id).resolve_addresses(name))+ .await+ }+ }++ impl<T> Host for WasiCtxNamedView<'_, T> where T: WasiSocketsNamedView {}+}diff --git a/crates/wasi/src/p3/sockets/host/types/mod.rs b/crates/wasi/src/p3/sockets/host/types/mod.rsindex 56deba72f8..f0a0613433 100644--- a/crates/wasi/src/p3/sockets/host/types/mod.rs+++ b/crates/wasi/src/p3/sockets/host/types/mod.rs@@ -10,3 +10,20 @@ impl Host for WasiSocketsCtxView<'_> {error.downcast()}}++mod named {+ use crate::WasiCtxNamedView;+ use crate::p3::bindings::named_imports::wasi::sockets::types::Host;+ use crate::p3::bindings::sockets::types::ErrorCode;+ use crate::p3::sockets::SocketError;+ use crate::sockets::WasiSocketsNamedView;++ impl<T> Host for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ fn convert_error_code(&mut self, error: SocketError) -> wasmtime::Result<ErrorCode> {+ error.downcast()+ }+ }+}diff --git a/crates/wasi/src/p3/sockets/host/types/tcp.rs b/crates/wasi/src/p3/sockets/host/types/tcp.rsindex 02e3051173..9cb165c6fa 100644--- a/crates/wasi/src/p3/sockets/host/types/tcp.rs+++ b/crates/wasi/src/p3/sockets/host/types/tcp.rs@@ -6,17 +6,18 @@ use crate::p3::bindings::sockets::types::{use crate::p3::sockets::{SocketError, SocketResult, WasiSockets};use crate::sockets::{TcpListenStream, TcpReceiveStream, TcpSendStream, WasiSocketsCtxView};use bytes::BytesMut;-use core::iter;-use core::pin::Pin;-use core::task::{Context, Poll};+use std::iter;+use std::marker::Unpin;use std::net::SocketAddr;+use std::pin::Pin;+use std::task::{Context, Poll};use tokio::sync::oneshot;use wasmtime::component::{Access, Accessor, Destination, FutureReader, Resource, ResourceTable, Source, StreamConsumer,StreamProducer, StreamReader, StreamResult,};use wasmtime::error::Context as _;-use wasmtime::{AsContextMut as _, StoreContextMut};+use wasmtime::{AsContextMut, StoreContextMut};fn get_socket<'a>(table: &'a ResourceTable,@@ -38,14 +39,15 @@ fn get_socket_mut<'a>(.map_err(SocketError::trap)}-struct ListenStreamProducer<T> {+struct ListenStreamProducer<F> {listener: TcpListenStream,- getter: for<'a> fn(&'a mut T) -> WasiSocketsCtxView<'a>,+ getter: F,}-impl<D> StreamProducer<D> for ListenStreamProducer<D>+impl<D, F> StreamProducer<D> for ListenStreamProducer<F>whereD: 'static,+ F: FnMut(&mut D) -> WasiSocketsCtxView<'_> + Send + Unpin + 'static,{type Item = Resource<TcpSocket>;type Buffer = Option<Self::Item>;@@ -199,63 +201,117 @@ impl<D> StreamConsumer<D> for SendStreamConsumer {}}+fn send(+ mut store: impl AsContextMut,+ stream: Result<TcpSendStream, crate::sockets::ErrorCode>,+ mut data: StreamReader<u8>,+) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {+ let mut store = store.as_context_mut();+ match stream {+ Ok(stream) => {+ let (result_tx, result_rx) = oneshot::channel();+ data.pipe(&mut store, SendStreamConsumer(Some((stream, result_tx))))?;+ FutureReader::new(&mut store, result_rx)+ }+ Err(err) => {+ data.close(&mut store)?;+ FutureReader::new(+ &mut store,+ async move { wasmtime::error::Ok(Err(err.into())) },+ )+ }+ }+}++fn receive(+ mut store: impl AsContextMut,+ stream: Result<TcpReceiveStream, crate::sockets::ErrorCode>,+) -> wasmtime::Result<(StreamReader<u8>, FutureReader<Result<(), ErrorCode>>)> {+ let mut store = store.as_context_mut();+ match stream {+ Ok(stream) => {+ let (result_tx, result_rx) = oneshot::channel();+ Ok((+ StreamReader::new(&mut store, ReceiveStreamProducer(Some((stream, result_tx))))?,+ FutureReader::new(&mut store, result_rx)?,+ ))+ }+ Err(err) => Ok((+ StreamReader::new(&mut store, iter::empty())?,+ FutureReader::new(+ &mut store,+ async move { wasmtime::error::Ok(Err(err.into())) },+ )?,+ )),+ }+}++async fn listen<S>(+ mut store: S,+ socket: &Resource<TcpSocket>,+ mut getter: impl FnMut(&mut S::Data) -> WasiSocketsCtxView<'_> + Send + Unpin + 'static,+) -> SocketResult<StreamReader<Resource<TcpSocket>>>+where+ S: AsContextMut,+{+ let mut store = store.as_context_mut();+ let socket = get_socket_mut(getter(store.data_mut()).table, socket)?;+ let listener = socket.listen().await?;+ let ret = StreamReader::new(&mut store, ListenStreamProducer { listener, getter })+ .map_err(SocketError::trap)?;+ Ok(ret)+}++impl WasiSocketsCtxView<'_> {+ fn start_connect(+ &mut self,+ socket: &Resource<TcpSocket>,+ remote_address: IpSocketAddress,+ ) -> SocketResult<()> {+ let remote_address = SocketAddr::from(remote_address);+ let socket = get_socket_mut(self.table, &socket)?;+ let socket = socket.start_connect(remote_address)?;+ Ok(socket)+ }++ fn poll_finish_connect(+ &mut self,+ cx: &mut Context<'_>,+ socket: &Resource<TcpSocket>,+ ) -> Poll<SocketResult<()>> {+ get_socket_mut(self.table, &socket)?+ .poll_finish_connect(cx)+ .map_err(SocketError::from)+ }+}+impl<T: Send> HostTcpSocketWithStore<T> for WasiSockets {async fn connect(store: &Accessor<T, Self>,socket: Resource<TcpSocket>,remote_address: IpSocketAddress,) -> SocketResult<()> {- let remote_address = SocketAddr::from(remote_address);-- store.with(|mut store| {- let socket = get_socket_mut(store.get().table, &socket)?;- let socket = socket.start_connect(remote_address)?;- SocketResult::Ok(socket)- })?;-- std::future::poll_fn(|cx| {- store.with(|mut store| -> Poll<SocketResult<()>> {- let socket = get_socket_mut(store.get().table, &socket)?;- socket.poll_finish_connect(cx).map_err(SocketError::from)- })- })- .await+ store.with(|mut s| s.get().start_connect(&socket, remote_address))?;+ std::future::poll_fn(|cx| store.with(|mut s| s.get().poll_finish_connect(cx, &socket)))+ .await}async fn listen(- mut store: Access<'_, T, Self>,+ store: Access<'_, T, Self>,socket_resource: Resource<TcpSocket>,) -> SocketResult<StreamReader<Resource<TcpSocket>>> {let getter = store.getter();- let socket = get_socket_mut(store.get().table, &socket_resource)?;-- let listener = socket.listen().await?;-- let ret = StreamReader::new(&mut store, ListenStreamProducer { listener, getter })- .map_err(SocketError::trap)?;- Ok(ret)+ listen(store, &socket_resource, getter).await}fn send(mut store: Access<'_, T, Self>,socket: Resource<TcpSocket>,- mut data: StreamReader<u8>,+ data: StreamReader<u8>,) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {let socket = get_socket_mut(store.get().table, &socket)?;- match socket.take_send_stream() {- Ok(stream) => {- let (result_tx, result_rx) = oneshot::channel();- data.pipe(&mut store, SendStreamConsumer(Some((stream, result_tx))))?;- FutureReader::new(&mut store, result_rx)- }- Err(err) => {- data.close(&mut store)?;- FutureReader::new(- &mut store,- async move { wasmtime::error::Ok(Err(err.into())) },- )- }- }+ let stream = socket.take_send_stream();+ send(&mut store, stream, data)}fn receive(@@ -263,25 +319,8 @@ impl<T: Send> HostTcpSocketWithStore<T> for WasiSockets {socket: Resource<TcpSocket>,) -> wasmtime::Result<(StreamReader<u8>, FutureReader<Result<(), ErrorCode>>)> {let socket = get_socket_mut(store.get().table, &socket)?;- match socket.take_receive_stream() {- Ok(stream) => {- let (result_tx, result_rx) = oneshot::channel();- Ok((- StreamReader::new(- &mut store,- ReceiveStreamProducer(Some((stream, result_tx))),- )?,- FutureReader::new(&mut store, result_rx)?,- ))- }- Err(err) => Ok((- StreamReader::new(&mut store, iter::empty())?,- FutureReader::new(- &mut store,- async move { wasmtime::error::Ok(Err(err.into())) },- )?,- )),- }+ let stream = socket.take_receive_stream();+ receive(&mut store, stream)}}@@ -449,3 +488,250 @@ impl HostTcpSocket for WasiSocketsCtxView<'_> {Ok(())}}++mod named {+ use crate::p3::bindings::named_imports::wasi::sockets::types::{+ HostTcpSocket, HostTcpSocketWithStore,+ };+ use crate::p3::bindings::sockets::types::{+ Duration, ErrorCode, IpAddressFamily, IpSocketAddress, TcpSocket,+ };+ use crate::p3::sockets::SocketResult;+ use crate::sockets::{WasiSocketsNamed, WasiSocketsNamedView};+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::{Access, Accessor, FutureReader, Resource, StreamReader};++ impl<T, U> HostTcpSocketWithStore<U> for WasiSocketsNamed<T>+ where+ T: WasiSocketsNamedView,+ U: Send,+ {+ async fn connect(+ store: &Accessor<U, Self>,+ id: NamedId,+ socket: Resource<TcpSocket>,+ remote_address: IpSocketAddress,+ ) -> SocketResult<()> {+ store.with(|mut s| s.get().0.sockets(id).start_connect(&socket, remote_address))?;+ std::future::poll_fn(|cx| {+ store.with(|mut s| s.get().0.sockets(id).poll_finish_connect(cx, &socket))+ })+ .await+ }++ async fn listen(+ store: Access<'_, U, Self>,+ id: NamedId,+ socket_resource: Resource<TcpSocket>,+ ) -> SocketResult<StreamReader<Resource<TcpSocket>>> {+ let getter = store.getter();+ super::listen(store, &socket_resource, move |data| {+ getter(data).0.sockets(id)+ })+ .await+ }++ fn send(+ mut store: Access<'_, U, Self>,+ id: NamedId,+ socket: Resource<TcpSocket>,+ data: StreamReader<u8>,+ ) -> wasmtime::Result<FutureReader<Result<(), ErrorCode>>> {+ let socket = super::get_socket_mut(store.get().0.sockets(id).table, &socket)?;+ let stream = socket.take_send_stream();+ super::send(&mut store, stream, data)+ }++ fn receive(+ mut store: Access<U, Self>,+ id: NamedId,+ socket: Resource<TcpSocket>,+ ) -> wasmtime::Result<(StreamReader<u8>, FutureReader<Result<(), ErrorCode>>)> {+ let socket = super::get_socket_mut(store.get().0.sockets(id).table, &socket)?;+ let stream = socket.take_receive_stream();+ super::receive(&mut store, stream)+ }+ }++ impl<T> HostTcpSocket for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ async fn bind(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ local_address: IpSocketAddress,+ ) -> SocketResult<()> {+ super::HostTcpSocket::bind(&mut self.0.sockets(id), socket, local_address).await+ }++ fn create(+ &mut self,+ id: NamedId,+ address_family: IpAddressFamily,+ ) -> SocketResult<Resource<TcpSocket>> {+ super::HostTcpSocket::create(&mut self.0.sockets(id), address_family)+ }++ fn get_local_address(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ ) -> SocketResult<IpSocketAddress> {+ super::HostTcpSocket::get_local_address(&mut self.0.sockets(id), socket)+ }++ fn get_remote_address(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ ) -> SocketResult<IpSocketAddress> {+ super::HostTcpSocket::get_remote_address(&mut self.0.sockets(id), socket)+ }++ fn get_is_listening(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ ) -> wasmtime::Result<bool> {+ super::HostTcpSocket::get_is_listening(&mut self.0.sockets(id), socket)+ }++ fn get_address_family(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ ) -> wasmtime::Result<IpAddressFamily> {+ super::HostTcpSocket::get_address_family(&mut self.0.sockets(id), socket)+ }++ fn set_listen_backlog_size(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::HostTcpSocket::set_listen_backlog_size(&mut self.0.sockets(id), socket, value)+ }++ fn get_keep_alive_enabled(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ ) -> SocketResult<bool> {+ super::HostTcpSocket::get_keep_alive_enabled(&mut self.0.sockets(id), socket)+ }++ fn set_keep_alive_enabled(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ value: bool,+ ) -> SocketResult<()> {+ super::HostTcpSocket::set_keep_alive_enabled(&mut self.0.sockets(id), socket, value)+ }++ fn get_keep_alive_idle_time(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ ) -> SocketResult<Duration> {+ super::HostTcpSocket::get_keep_alive_idle_time(&mut self.0.sockets(id), socket)+ }++ fn set_keep_alive_idle_time(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ value: Duration,+ ) -> SocketResult<()> {+ super::HostTcpSocket::set_keep_alive_idle_time(&mut self.0.sockets(id), socket, value)+ }++ fn get_keep_alive_interval(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ ) -> SocketResult<Duration> {+ super::HostTcpSocket::get_keep_alive_interval(&mut self.0.sockets(id), socket)+ }++ fn set_keep_alive_interval(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ value: Duration,+ ) -> SocketResult<()> {+ super::HostTcpSocket::set_keep_alive_interval(&mut self.0.sockets(id), socket, value)+ }++ fn get_keep_alive_count(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ ) -> SocketResult<u32> {+ super::HostTcpSocket::get_keep_alive_count(&mut self.0.sockets(id), socket)+ }++ fn set_keep_alive_count(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ value: u32,+ ) -> SocketResult<()> {+ super::HostTcpSocket::set_keep_alive_count(&mut self.0.sockets(id), socket, value)+ }++ fn get_hop_limit(&mut self, id: NamedId, socket: Resource<TcpSocket>) -> SocketResult<u8> {+ super::HostTcpSocket::get_hop_limit(&mut self.0.sockets(id), socket)+ }++ fn set_hop_limit(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ value: u8,+ ) -> SocketResult<()> {+ super::HostTcpSocket::set_hop_limit(&mut self.0.sockets(id), socket, value)+ }++ fn get_receive_buffer_size(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ ) -> SocketResult<u64> {+ super::HostTcpSocket::get_receive_buffer_size(&mut self.0.sockets(id), socket)+ }++ fn set_receive_buffer_size(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::HostTcpSocket::set_receive_buffer_size(&mut self.0.sockets(id), socket, value)+ }++ fn get_send_buffer_size(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ ) -> SocketResult<u64> {+ super::HostTcpSocket::get_send_buffer_size(&mut self.0.sockets(id), socket)+ }++ fn set_send_buffer_size(+ &mut self,+ id: NamedId,+ socket: Resource<TcpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::HostTcpSocket::set_send_buffer_size(&mut self.0.sockets(id), socket, value)+ }++ fn drop(&mut self, id: NamedId, sock: Resource<TcpSocket>) -> wasmtime::Result<()> {+ super::HostTcpSocket::drop(&mut self.0.sockets(id), sock)+ }+ }+}diff --git a/crates/wasi/src/p3/sockets/host/types/udp.rs b/crates/wasi/src/p3/sockets/host/types/udp.rsindex 2a69817855..79c90f1459 100644--- a/crates/wasi/src/p3/sockets/host/types/udp.rs+++ b/crates/wasi/src/p3/sockets/host/types/udp.rs@@ -36,25 +36,42 @@ impl<T> HostUdpSocketWithStore<T> for WasiSockets {remote_address: Option<IpSocketAddress>,) -> SocketResult<()> {store- .with(|mut view| -> SocketResult<_> {- let socket = get_socket_mut(view.get().table, &socket)?;- Ok(socket.send(data, remote_address.map(SocketAddr::from)))- })?- .await?;- Ok(())+ .with(|mut view| view.get().send(&socket, data, remote_address))+ .await}async fn receive(store: &Accessor<T, Self>,socket: Resource<UdpSocket>,) -> SocketResult<(Vec<u8>, IpSocketAddress)> {- let (data, addr) = store- .with(|mut view| -> SocketResult<_> {- let socket = get_socket_mut(view.get().table, &socket)?;- Ok(socket.recv())- })?- .await?;- Ok((data, addr.into()))+ store.with(|mut view| view.get().receive(&socket)).await+ }+}++impl WasiSocketsCtxView<'_> {+ fn send(+ &mut self,+ socket: &Resource<UdpSocket>,+ data: Vec<u8>,+ remote_address: Option<IpSocketAddress>,+ ) -> impl Future<Output = SocketResult<()>> + use<> {+ let socket = get_socket_mut(self.table, socket);+ let fut = socket.map(|s| s.send(data, remote_address.map(SocketAddr::from)));+ async move {+ fut?.await?;+ Ok(())+ }+ }++ fn receive(+ &mut self,+ socket: &Resource<UdpSocket>,+ ) -> impl Future<Output = SocketResult<(Vec<u8>, IpSocketAddress)>> + use<> {+ let fut = get_socket_mut(self.table, socket).map(|s| s.recv());+ async move {+ let (data, addr) = fut?.await?;+ Ok((data, addr.into()))+ }}}@@ -168,3 +185,155 @@ impl HostUdpSocket for WasiSocketsCtxView<'_> {Ok(())}}++mod named {+ use crate::p3::bindings::named_imports::wasi::sockets::types::{+ HostUdpSocket, HostUdpSocketWithStore,+ };+ use crate::p3::bindings::sockets::types::{IpAddressFamily, IpSocketAddress};+ use crate::p3::sockets::SocketResult;+ use crate::sockets::{UdpSocket, WasiSocketsNamed, WasiSocketsNamedView};+ use crate::{NamedId, WasiCtxNamedView};+ use wasmtime::component::{Accessor, Resource};++ impl<T, U> HostUdpSocketWithStore<U> for WasiSocketsNamed<T>+ where+ T: WasiSocketsNamedView,+ {+ async fn send(+ store: &Accessor<U, Self>,+ id: NamedId,+ socket: Resource<UdpSocket>,+ data: Vec<u8>,+ remote_address: Option<IpSocketAddress>,+ ) -> SocketResult<()> {+ store+ .with(|mut view| view.get().0.sockets(id).send(&socket, data, remote_address))+ .await+ }++ async fn receive(+ store: &Accessor<U, Self>,+ id: NamedId,+ socket: Resource<UdpSocket>,+ ) -> SocketResult<(Vec<u8>, IpSocketAddress)> {+ store+ .with(|mut view| view.get().0.sockets(id).receive(&socket))+ .await+ }+ }++ impl<T> HostUdpSocket for WasiCtxNamedView<'_, T>+ where+ T: WasiSocketsNamedView,+ {+ async fn bind(+ &mut self,+ id: NamedId,+ socket: Resource<UdpSocket>,+ local_address: IpSocketAddress,+ ) -> SocketResult<()> {+ super::HostUdpSocket::bind(&mut self.0.sockets(id), socket, local_address).await+ }++ async fn connect(+ &mut self,+ id: NamedId,+ socket: Resource<UdpSocket>,+ remote_address: IpSocketAddress,+ ) -> SocketResult<()> {+ super::HostUdpSocket::connect(&mut self.0.sockets(id), socket, remote_address).await+ }++ async fn create(+ &mut self,+ id: NamedId,+ address_family: IpAddressFamily,+ ) -> SocketResult<Resource<UdpSocket>> {+ super::HostUdpSocket::create(&mut self.0.sockets(id), address_family).await+ }++ fn disconnect(&mut self, id: NamedId, socket: Resource<UdpSocket>) -> SocketResult<()> {+ super::HostUdpSocket::disconnect(&mut self.0.sockets(id), socket)+ }++ fn get_local_address(+ &mut self,+ id: NamedId,+ socket: Resource<UdpSocket>,+ ) -> SocketResult<IpSocketAddress> {+ super::HostUdpSocket::get_local_address(&mut self.0.sockets(id), socket)+ }++ fn get_remote_address(+ &mut self,+ id: NamedId,+ socket: Resource<UdpSocket>,+ ) -> SocketResult<IpSocketAddress> {+ super::HostUdpSocket::get_remote_address(&mut self.0.sockets(id), socket)+ }++ fn get_address_family(+ &mut self,+ id: NamedId,+ socket: Resource<UdpSocket>,+ ) -> wasmtime::Result<IpAddressFamily> {+ super::HostUdpSocket::get_address_family(&mut self.0.sockets(id), socket)+ }++ fn get_unicast_hop_limit(+ &mut self,+ id: NamedId,+ socket: Resource<UdpSocket>,+ ) -> SocketResult<u8> {+ super::HostUdpSocket::get_unicast_hop_limit(&mut self.0.sockets(id), socket)+ }++ fn set_unicast_hop_limit(+ &mut self,+ id: NamedId,+ socket: Resource<UdpSocket>,+ value: u8,+ ) -> SocketResult<()> {+ super::HostUdpSocket::set_unicast_hop_limit(&mut self.0.sockets(id), socket, value)+ }++ fn get_receive_buffer_size(+ &mut self,+ id: NamedId,+ socket: Resource<UdpSocket>,+ ) -> SocketResult<u64> {+ super::HostUdpSocket::get_receive_buffer_size(&mut self.0.sockets(id), socket)+ }++ fn set_receive_buffer_size(+ &mut self,+ id: NamedId,+ socket: Resource<UdpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::HostUdpSocket::set_receive_buffer_size(&mut self.0.sockets(id), socket, value)+ }++ fn get_send_buffer_size(+ &mut self,+ id: NamedId,+ socket: Resource<UdpSocket>,+ ) -> SocketResult<u64> {+ super::HostUdpSocket::get_send_buffer_size(&mut self.0.sockets(id), socket)+ }++ fn set_send_buffer_size(+ &mut self,+ id: NamedId,+ socket: Resource<UdpSocket>,+ value: u64,+ ) -> SocketResult<()> {+ super::HostUdpSocket::set_send_buffer_size(&mut self.0.sockets(id), socket, value)+ }++ fn drop(&mut self, id: NamedId, sock: Resource<UdpSocket>) -> wasmtime::Result<()> {+ super::HostUdpSocket::drop(&mut self.0.sockets(id), sock)+ }+ }+}diff --git a/crates/wasi/src/p3/sockets/mod.rs b/crates/wasi/src/p3/sockets/mod.rsindex d490ec2dec..0cac1c8553 100644--- a/crates/wasi/src/p3/sockets/mod.rs+++ b/crates/wasi/src/p3/sockets/mod.rs@@ -1,7 +1,9 @@use crate::TrappableError;+use crate::p3::Interface;use crate::p3::bindings::sockets::{ip_name_lookup, types};-use crate::sockets::{WasiSockets, WasiSocketsView};-use wasmtime::component::Linker;+use crate::sockets::{WasiSockets, WasiSocketsNamed, WasiSocketsNamedView, WasiSocketsView};+use crate::{NamedId, WasiCtxNamedView};+use wasmtime::component::{Component, Linker};mod conv;mod host;@@ -68,3 +70,110 @@ wheretypes::add_to_linker::<_, WasiSockets>(linker, T::sockets)?;Ok(())}++/// Convenience function to add `wasi:sockets` interfaces into `linker` for any+/// named imports of `wasi:sockets` interfaces.+///+/// This function is similar to [`add_to_linker`] except that it's specifically+/// designed to work with named imports of `wasi:sockets` interfaces that+/// components may have. This requires a [`Component`] parameter to be passed in+/// when populating the [`Linker`] provided to see what the [`Component`]+/// actually imports.+///+/// Like [`add_to_linker`] this is a bit low level and you may want to possibly+/// invoke [`wasmtime_wasi::p3::add_named_to_linker`] instead. Alternatively if+/// this isn't low level enough you can additionally invoke bindgen-generated+/// `add_to_linker` functions directly from within the+/// [`named_imports::wasi::sockets`] module.+///+/// [`wasmtime_wasi::p3::add_named_to_linker`]: crate::p3::add_named_to_linker+/// [`named_imports::wasi::sockets`]: crate::p3::bindings::named_imports::wasi::sockets+///+/// The `lookup` function provided here is invoked for every named import found+/// for a particular interface. The [`Interface`] given is what's being bound,+/// and the `&str` argument is the name that the component imports it as. The+/// embedder can then decide how it would like to allocate a [`NamedId`] for+/// this import. If `Ok` is returned then the linker is populated with this+/// name, and imported functions will pass the [`NamedId`] later to the+/// implementation of [`WasiSocketsNamedView`] on `T` when invoked. If `Err` is+/// returned then the error will cause this entire function to fail and this+/// function call will return the same error.+///+/// # Example+///+/// ```+/// use std::collections::HashMap;+/// use wasmtime::component::{Component, Linker, ResourceTable};+/// use wasmtime::{Engine, Result, Store, Config};+/// use wasmtime_wasi::NamedId;+/// use wasmtime_wasi::sockets::{WasiSocketsCtx, WasiSocketsCtxView, WasiSocketsNamedView};+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let component = Component::new(&engine, "(component)")?;+///+/// let mut linker = Linker::<MyState>::new(&engine);+///+/// // ... add default functionality to `linker` as needed ...+///+/// // and then additionally fill in any specific named imports `component`+/// // might have for `wasi:sockets` interfaces.+/// let mut name_map = HashMap::new();+/// wasmtime_wasi::p3::sockets::add_named_to_linker(&mut linker, &component, |_i, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// })?;+///+/// // Here a `WasiSocketsCtx` is allocated per-named-import and will then be+/// // referred to internally by the [`NamedId`] allocated above. You could+/// // also use `name_map` to configure each context differently.+/// let mut my_state = MyState::default();+/// for _ in 0..name_map.len() {+/// my_state.contexts.push(WasiSocketsCtx::default());+/// }+/// let mut store = Store::new(&engine, my_state);+/// let instance = linker.instantiate(&mut store, &component)?;+///+/// // ... work with `instance` ...+///+/// Ok(())+/// }+///+/// #[derive(Default)]+/// struct MyState {+/// table: ResourceTable,+/// contexts: Vec<WasiSocketsCtx>,+/// }+///+/// impl WasiSocketsNamedView for MyState {+/// fn sockets(&mut self, id: NamedId) -> WasiSocketsCtxView<'_> {+/// WasiSocketsCtxView {+/// ctx: &mut self.contexts[id.0],+/// table: &mut self.table,+/// }+/// }+/// }+/// ```+pub fn add_named_to_linker<T>(+ linker: &mut Linker<T>,+ component: &Component,+ mut lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,+) -> wasmtime::Result<()>+where+ T: WasiSocketsNamedView + 'static,+{+ use crate::p3::bindings::named_imports::wasi::sockets::{ip_name_lookup, types};+ ip_name_lookup::add_to_linker::<_, WasiSocketsNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::SocketsIpNameLookup, name),+ |x| WasiCtxNamedView(x),+ )?;+ types::add_to_linker::<_, WasiSocketsNamed<T>>(+ linker,+ component,+ |name| lookup(Interface::SocketsTypes, name),+ |x| WasiCtxNamedView(x),+ )?;+ Ok(())+}diff --git a/crates/wasi/src/random.rs b/crates/wasi/src/random.rsindex 03719b2d5f..313bc3bfa2 100644--- a/crates/wasi/src/random.rs+++ b/crates/wasi/src/random.rs@@ -1,5 +1,7 @@+use crate::{NamedId, WasiCtxNamedView};use rand::{Rng, SeedableRng as _, TryRng};use std::convert::Infallible;+use std::marker;use wasmtime::component::HasData;/// A helper struct which implements [`HasData`] for the `wasi:random` APIs.@@ -136,3 +138,145 @@ pub fn thread_rng() -> Box<dyn Rng + Send> {let mut rng = rand::rng();Box::new(rand::rngs::StdRng::from_rng(&mut rng))}++/// A helper struct which implements [`HasData`] for the `wasi:random` APIs+/// when used in combination with named imports.+///+/// This structure is similar in purpose to [`WasiRandom`] and is used+/// when using the [`named_imports`] module for `wasi:random`. This structure+/// serves as the `D` type parameter for `add_to_linker` functions.+///+/// [`named_imports`]: crate::p3::bindings::named_imports::wasi::random+///+/// # Meaning of the `T` parameter+///+/// Here the `T` must be something that implements [`WasiRandomNamedView`]. The+/// corresponding `Data` for this type is [`WasiCtxNamedView`] which internally+/// will contain `&mut T`.+///+/// Effectively you're going to implement [`WasiRandomNamedView`] for something in+/// your embedding, and that's the `T` you'll fill in here.+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};+/// use wasmtime_wasi::random::*;+/// use wasmtime_wasi::p2::bindings::named_imports;+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// states: HashMap<NamedId, WasiRandomCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// named_imports::wasi::random::random::add_to_linker::<MyStoreState, WasiRandomNamed<MyStoreState>>(+/// &mut linker,+/// &component,+/// |name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// |state| WasiCtxNamedView(state),+/// )?;+/// Ok(())+/// }+///+/// impl WasiRandomNamedView for MyStoreState {+/// fn random(&mut self, id: NamedId) -> &mut WasiRandomCtx {+/// self.states.get_mut(&id).expect("state for id")+/// }+/// }+/// ```+pub struct WasiRandomNamed<T>(marker::PhantomData<fn() -> T>);++impl<T> HasData for WasiRandomNamed<T>+where+ T: WasiRandomNamedView,+{+ type Data<'a> = WasiCtxNamedView<'a, T>;+}++/// A trait used to look up a specific `wasi:random` context for a named+/// import.+///+/// This trait is used in conjunction with the [`named_imports`] bindings+/// generated for all WASI interfaces. The purpose of this trait is for+/// embedders to define how a [`NamedId`] maps to a particular `wasi:random`+/// context, here returned as [`WasiRandomCtx`]. Embedders are responsible+/// for assigning meaning to [`NamedId`] values themselves. These IDs are+/// assigned when [`add_named_to_linker`] is called, for example, as the+/// `lookup` argument to that function.+///+/// When using [`add_named_to_linker`] it's sufficient to implement this trait+/// for the `T` in `Store<T>`. You can also instead implement the+/// [`WasiNamedView`] trait for `T` which implies an implementation of this+/// trait.+///+/// When using `add_to_linker` in the generated `bindings::named_imports`+/// module then values implementing this live within the `T` of `Store<T>`, and+/// be temporarily referenced in [`WasiCtxNamedView`] where internally that'll+/// hold `WasiCtxNamedView(&mut your_type)`.+///+/// [`named_imports`]: crate::p3::bindings::named_imports+/// [`add_named_to_linker`]: crate::p3::random::add_named_to_linker+/// [`WasiNamedView`]: crate::WasiNamedView+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};+/// use wasmtime_wasi::random::*;+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// states: HashMap<NamedId, WasiRandomCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// wasmtime_wasi::p3::random::add_named_to_linker::<MyStoreState>(+/// &mut linker,+/// &component,+/// |_, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// )?;+/// Ok(())+/// }+///+/// impl WasiRandomNamedView for MyStoreState {+/// fn random(&mut self, id: NamedId) -> &mut WasiRandomCtx {+/// self.states.get_mut(&id).expect("state for id")+/// }+/// }+/// ```+pub trait WasiRandomNamedView: Send + 'static {+ /// Looks up the [`WasiRandomCtx`] for the given [`NamedId`].+ ///+ /// This method will resolve the `id` specified to a specific random+ /// context that is available to be used. Note that this method is+ /// specifically infallible meaning that a random context must be returned+ /// and this cannot generate a trap or panic or similar.+ ///+ /// Embedders are responsible for allocating [`NamedId`] and assigning+ /// meaning to ids. When a `Linker` is populated embedders will have the+ /// ability to generate a `NamedId` for all imports found, and then that+ /// embedder-allocated id is then passed back here when the corresponding+ /// imported function is invoked.+ fn random(&mut self, id: NamedId) -> &mut WasiRandomCtx;+}diff --git a/crates/wasi/src/sockets/mod.rs b/crates/wasi/src/sockets/mod.rsindex 745b7ee072..98e562e362 100644--- a/crates/wasi/src/sockets/mod.rs+++ b/crates/wasi/src/sockets/mod.rs@@ -1,4 +1,5 @@use crate::runtime::{AbortOnDropJoinHandle, poll_noop};+use crate::{NamedId, WasiCtxNamedView};use core::fmt;use core::future::Future;use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};@@ -6,6 +7,7 @@ use core::ops::Deref;use rustix::fd::AsFd;use rustix::io::Errno;use rustix::net::sockopt;+use std::marker;use std::pin::Pin;use std::sync::Arc;use std::task::Poll;@@ -583,3 +585,160 @@ pub(crate) fn unspecified_addr(family: SocketAddressFamily) -> SocketAddr {};SocketAddr::new(ip, 0)}++/// A helper struct which implements [`HasData`] for the `wasi:sockets` APIs+/// when used in combination with named imports.+///+/// This structure is similar in purpose to [`WasiSockets`] and is used+/// when using the [`named_imports`] module for `wasi:sockets`. This structure+/// serves as the `D` type parameter for `add_to_linker` functions.+///+/// [`named_imports`]: crate::p3::bindings::named_imports::wasi::sockets+///+/// # Meaning of the `T` parameter+///+/// Here the `T` must be something that implements [`WasiSocketsNamedView`]. The+/// corresponding `Data` for this type is [`WasiCtxNamedView`] which internally+/// will contain `&mut T`.+///+/// Effectively you're going to implement [`WasiSocketsNamedView`] for something in+/// your embedding, and that's the `T` you'll fill in here.+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component, ResourceTable};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};+/// use wasmtime_wasi::sockets::*;+/// use wasmtime_wasi::p2::bindings::named_imports;+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// table: ResourceTable,+/// states: HashMap<NamedId, WasiSocketsCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// named_imports::wasi::sockets::instance_network::add_to_linker::<MyStoreState, WasiSocketsNamed<MyStoreState>>(+/// &mut linker,+/// &component,+/// |name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// |state| WasiCtxNamedView(state),+/// )?;+/// Ok(())+/// }+///+/// impl WasiSocketsNamedView for MyStoreState {+/// fn sockets(&mut self, id: NamedId) -> WasiSocketsCtxView<'_> {+/// let ctx = self.states.get_mut(&id).expect("state for id");+/// WasiSocketsCtxView {+/// table: &mut self.table,+/// ctx,+/// }+/// }+/// }+/// ```+pub struct WasiSocketsNamed<T>(marker::PhantomData<fn() -> T>);++impl<T> HasData for WasiSocketsNamed<T>+where+ T: WasiSocketsNamedView,+{+ type Data<'a> = WasiCtxNamedView<'a, T>;+}++/// A trait used to look up a specific `wasi:sockets` context for a named+/// import.+///+/// This trait is used in conjunction with the [`named_imports`] bindings+/// generated for all WASI interfaces. The purpose of this trait is for+/// embedders to define how a [`NamedId`] maps to a particular `wasi:sockets`+/// context, here returned as [`WasiSocketsCtxView`]. Embedders are responsible+/// for assigning meaning to [`NamedId`] values themselves. These IDs are+/// assigned when [`add_named_to_linker`] is called, for example, as the+/// `lookup` argument to that function.+///+/// When using [`add_named_to_linker`] it's sufficient to implement this trait+/// for the `T` in `Store<T>`. You can also instead implement the+/// [`WasiNamedView`] trait for `T` which implies an implementation of this+/// trait.+///+/// When using `add_to_linker` in the generated `bindings::named_imports`+/// module then values implementing this live within the `T` of `Store<T>`, and+/// be temporarily referenced in [`WasiCtxNamedView`] where internally that'll+/// hold `WasiCtxNamedView(&mut your_type)`.+///+/// [`named_imports`]: crate::p3::bindings::named_imports+/// [`add_named_to_linker`]: crate::p3::sockets::add_named_to_linker+/// [`WasiNamedView`]: crate::WasiNamedView+///+/// # Examples+///+/// ```+/// use wasmtime::component::{Linker, Component, ResourceTable};+/// use wasmtime::{Engine, Result};+/// use wasmtime_wasi::{NamedId, WasiCtxNamedView};+/// use wasmtime_wasi::sockets::*;+/// use std::collections::HashMap;+///+/// struct MyStoreState {+/// table: ResourceTable,+/// states: HashMap<NamedId, WasiSocketsCtx>,+/// }+///+/// fn main() -> Result<()> {+/// let engine = Engine::default();+/// let mut linker = Linker::new(&engine);+/// let component = Component::new(&engine, "(component)")?;+/// let mut name_map = HashMap::new();+///+/// wasmtime_wasi::p3::sockets::add_named_to_linker::<MyStoreState>(+/// &mut linker,+/// &component,+/// |_, name| {+/// let len = name_map.len();+/// Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))+/// },+/// )?;+/// Ok(())+/// }+///+/// impl WasiSocketsNamedView for MyStoreState {+/// fn sockets(&mut self, id: NamedId) -> WasiSocketsCtxView<'_> {+/// let ctx = self.states.get_mut(&id).expect("state for id");+/// WasiSocketsCtxView {+/// table: &mut self.table,+/// ctx,+/// }+/// }+/// }+/// ```+pub trait WasiSocketsNamedView: Send + 'static {+ /// Looks up the [`WasiSocketsCtxView`] for the given [`NamedId`].+ ///+ /// This method will resolve the `id` specified to a specific sockets+ /// context that is available to be used. Note that this method is+ /// specifically infallible meaning that a sockets context must be returned+ /// and this cannot generate a trap or panic or similar.+ ///+ /// Embedders are responsible for allocating [`NamedId`] and assigning+ /// meaning to ids. When a `Linker` is populated embedders will have the+ /// ability to generate a `NamedId` for all imports found, and then that+ /// embedder-allocated id is then passed back here when the corresponding+ /// imported function is invoked.+ ///+ /// Note that the [`ResourceTable`] referenced in the returned+ /// [`WasiSocketsCtxView`] need not be unique. It's ok to use the same+ /// [`ResourceTable`] for all imports. This is not a guest-visible+ /// abstraction and just helps the host allocate and manage state.+ fn sockets(&mut self, id: NamedId) -> WasiSocketsCtxView<'_>;+}diff --git a/crates/wasi/src/view.rs b/crates/wasi/src/view.rsindex effdec9f62..6f95c911c4 100644--- a/crates/wasi/src/view.rs+++ b/crates/wasi/src/view.rs@@ -93,3 +93,91 @@ impl<T: WasiView> crate::sockets::WasiSocketsView for T {}}}++/// Identifier used to correlate a named import to a host-defined value.+///+/// This type is a small newtype wrapper around a `usize`, its only field which+/// is also public. Embeders define the meaning of this value and are in control+/// of both creating this an interpreting it. Creation of [`NamedId`] happens in+/// functions like [`wasmtime_wasi::p3::add_named_to_linker`] where embedders+/// will allocate a [`NamedId`] for all recognized named imports. Interpreting+/// a [`NamedId`] happens later in traits such as [`WasiNamedView`] where the id+/// is passed back to the embedder and a corresponding context must be returned.+///+/// Internally the `wasmtime-wasi` crate does not inspect the internal field+/// here nor ever create one. Embedders are solely responsible for managing this+/// id and its conetnts.+///+/// [`wasmtime_wasi::p3::add_named_to_linker`]: crate::p3::add_named_to_linker+#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Debug)]+pub struct NamedId(pub usize);++/// A helper structure by which to implement generated-`Host` traits for+/// bindings corresponding to named imports.+///+/// This is an implementation detail of how named imports are organized.+/// Embedders invoking generated `add_to_linker` functions directly will be+/// required to create this structure directly. Otherwise you probably won't+/// need to interact with this.+pub struct WasiCtxNamedView<'a, T>(pub &'a mut T);++/// A trait which provides access to a specific [`WasiCtx`] as scoped by a+/// [`NamedId`] parameter.+///+/// This trait is used as part of convenience+/// [`wasmtime_wasi::p3::add_named_to_linker`] functions for example. This is+/// used to scope access of a WASI context within a specific `id` or named+/// import.+///+/// [`wasmtime_wasi::p3::add_named_to_linker`]: crate::p3::add_named_to_linker+pub trait WasiNamedView: Send + 'static {+ /// Yields mutable access to the [`WasiCtx`] configuration used for this+ /// context.+ fn ctx(&mut self, id: NamedId) -> WasiCtxView<'_>;+}++impl<T: WasiNamedView> crate::cli::WasiCliNamedView for T {+ fn cli(&mut self, id: NamedId) -> crate::cli::WasiCliCtxView<'_> {+ let WasiCtxView { ctx, table } = self.ctx(id);+ crate::cli::WasiCliCtxView {+ ctx: &mut ctx.cli,+ table,+ }+ }+}++impl<T: WasiNamedView> crate::clocks::WasiClocksNamedView for T {+ fn clocks(&mut self, id: NamedId) -> crate::clocks::WasiClocksCtxView<'_> {+ let WasiCtxView { ctx, table } = self.ctx(id);+ crate::clocks::WasiClocksCtxView {+ ctx: &mut ctx.clocks,+ table,+ }+ }+}++impl<T: WasiNamedView> crate::filesystem::WasiFilesystemNamedView for T {+ fn filesystem(&mut self, id: NamedId) -> crate::filesystem::WasiFilesystemCtxView<'_> {+ let WasiCtxView { ctx, table } = self.ctx(id);+ crate::filesystem::WasiFilesystemCtxView {+ ctx: &mut ctx.filesystem,+ table,+ }+ }+}++impl<T: WasiNamedView> crate::random::WasiRandomNamedView for T {+ fn random(&mut self, id: NamedId) -> &mut crate::random::WasiRandomCtx {+ self.ctx(id).ctx.random()+ }+}++impl<T: WasiNamedView> crate::sockets::WasiSocketsNamedView for T {+ fn sockets(&mut self, id: NamedId) -> crate::sockets::WasiSocketsCtxView<'_> {+ let WasiCtxView { ctx, table } = self.ctx(id);+ crate::sockets::WasiSocketsCtxView {+ ctx: &mut ctx.sockets,+ table,+ }+ }+}diff --git a/crates/wasi/tests/all/p2/async_.rs b/crates/wasi/tests/all/p2/async_.rsindex 2783097168..b026abc825 100644--- a/crates/wasi/tests/all/p2/async_.rs+++ b/crates/wasi/tests/all/p2/async_.rs@@ -2,10 +2,10 @@ use crate::store::{Ctx, MyWasiCtx};use std::path::Path;use test_programs_artifacts::*;use wasmtime::Result;-use wasmtime::component::{Component, Linker};-use wasmtime_wasi::WasiCtxBuilder;+use wasmtime::component::{Component, Linker, ResourceTable};use wasmtime_wasi::p2::add_to_linker_async;use wasmtime_wasi::p2::bindings::Command;+use wasmtime_wasi::{NamedId, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiNamedView, WasiView};async fn run(path: &str, with_builder: impl FnOnce(&mut WasiCtxBuilder)) -> Result<()> {run_with_workspace_setup(path, |_| Ok(()), with_builder).await@@ -508,3 +508,70 @@ async fn file_stream_not_permitted(component_path: &str) {async fn p2_clocks_zero_wait() {run(P2_CLOCKS_ZERO_WAIT_COMPONENT, |_| {}).await.unwrap()}++#[test_log::test(tokio::test(flavor = "multi_thread"))]+async fn p2_environment_named_imports() -> Result<()> {+ struct StoreData {+ default: WasiCtx,+ a: WasiCtx,+ b: WasiCtx,+ table: ResourceTable,+ }++ impl WasiView for Ctx<StoreData> {+ fn ctx(&mut self) -> WasiCtxView<'_> {+ WasiCtxView {+ ctx: &mut self.wasi.default,+ table: &mut self.wasi.table,+ }+ }+ }++ impl WasiNamedView for Ctx<StoreData> {+ fn ctx(&mut self, id: NamedId) -> WasiCtxView<'_> {+ WasiCtxView {+ ctx: match id.0 {+ 0 => &mut self.wasi.a,+ 1 => &mut self.wasi.b,+ _ => panic!("unexpected id: {}", id.0),+ },+ table: &mut self.wasi.table,+ }+ }+ }++ let path = Path::new(P2_ENVIRONMENT_NAMED_IMPORTS_COMPONENT);+ let name = path.file_stem().unwrap().to_str().unwrap();+ let engine = test_programs_artifacts::engine(|config| {+ config.wasm_component_model_implements(true);+ });+ let component = Component::from_file(&engine, path)?;+ let mut linker = Linker::new(&engine);+ add_to_linker_async(&mut linker)?;+ wasmtime_wasi::p2::add_named_to_linker_async(&mut linker, &component, |i, name| {+ assert_eq!(i, wasmtime_wasi::p2::Interface::CliEnvironment);+ Ok(match name {+ "a" => NamedId(0),+ "b" => NamedId(1),+ _ => panic!("unexpected name: {name}"),+ })+ })?;++ let (mut store, _td) = Ctx::new_with_workspace_setup(+ &engine,+ name,+ |_| Ok(()),+ |builder| StoreData {+ default: builder.env("DEFAULT", "0").build(),+ a: WasiCtx::builder().env("A", "0").build(),+ b: WasiCtx::builder().env("B", "0").build(),+ table: ResourceTable::default(),+ },+ )?;+ let command = Command::instantiate_async(&mut store, &component, &linker).await?;+ command+ .wasi_cli_run()+ .call_run(&mut store)+ .await?+ .map_err(|()| wasmtime::format_err!("run returned a failure"))+}diff --git a/crates/wasi/tests/all/p2/sync.rs b/crates/wasi/tests/all/p2/sync.rsindex 610488eac8..4b4ab8d594 100644--- a/crates/wasi/tests/all/p2/sync.rs+++ b/crates/wasi/tests/all/p2/sync.rs@@ -478,3 +478,9 @@ fn file_stream_not_permitted(component_path: &str) {fn p2_clocks_zero_wait() {run(P2_CLOCKS_ZERO_WAIT_COMPONENT, |_| {}).unwrap()}++#[test]+fn p2_environment_named_imports() {+ // intentionally omitted as named imports are just for async bindings right+ // now.+}diff --git a/crates/wasi/tests/all/p3/mod.rs b/crates/wasi/tests/all/p3/mod.rsindex 4cf3115883..801bb5db84 100644--- a/crates/wasi/tests/all/p3/mod.rs+++ b/crates/wasi/tests/all/p3/mod.rs@@ -1,10 +1,12 @@use crate::store::{Ctx, MyWasiCtx};use std::path::{Path, PathBuf};use test_programs_artifacts::*;-use wasmtime::component::{Component, Linker};+use wasmtime::component::{Component, Linker, ResourceTable};use wasmtime::{Result, error::Context as _, format_err};use wasmtime_wasi::p3::bindings::Command;-use wasmtime_wasi::{FsPerms, WasiCtxBuilder};+use wasmtime_wasi::{+ FsPerms, NamedId, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiNamedView, WasiView,+};async fn run(path: &str) -> Result<()> {run_allow_blocking_current_thread(path, false).await@@ -226,3 +228,75 @@ async fn p3_file_hardlink_across_perms() -> wasmtime::Result<()> {async fn p3_file_rename_across_perms() -> wasmtime::Result<()> {run_with_readonly_testfile(P3_FILE_RENAME_ACROSS_PERMS_COMPONENT).await}++#[test_log::test(tokio::test(flavor = "multi_thread"))]+async fn p3_environment_named_imports() -> Result<()> {+ struct StoreData {+ default: WasiCtx,+ a: WasiCtx,+ b: WasiCtx,+ table: ResourceTable,+ }++ impl WasiView for Ctx<StoreData> {+ fn ctx(&mut self) -> WasiCtxView<'_> {+ WasiCtxView {+ ctx: &mut self.wasi.default,+ table: &mut self.wasi.table,+ }+ }+ }++ impl WasiNamedView for Ctx<StoreData> {+ fn ctx(&mut self, id: NamedId) -> WasiCtxView<'_> {+ WasiCtxView {+ ctx: match id.0 {+ 0 => &mut self.wasi.a,+ 1 => &mut self.wasi.b,+ _ => panic!("unexpected id: {}", id.0),+ },+ table: &mut self.wasi.table,+ }+ }+ }++ let path = Path::new(P3_ENVIRONMENT_NAMED_IMPORTS_COMPONENT);+ let name = path.file_stem().unwrap().to_str().unwrap();+ let engine = test_programs_artifacts::engine(|config| {+ config.wasm_component_model_implements(true);+ });+ let component = Component::from_file(&engine, path)?;+ let mut linker = Linker::new(&engine);+ wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;+ wasmtime_wasi::p3::add_to_linker(&mut linker)?;+ wasmtime_wasi::p3::add_named_to_linker(&mut linker, &component, |i, name| {+ assert_eq!(i, wasmtime_wasi::p3::Interface::CliEnvironment);+ Ok(match name {+ "a" => NamedId(0),+ "b" => NamedId(1),+ _ => panic!("unexpected name: {name}"),+ })+ })?;++ let (mut store, _td) = Ctx::new_with_workspace_setup(+ &engine,+ name,+ |_| Ok(()),+ |builder| StoreData {+ default: builder.env("DEFAULT", "0").build(),+ a: WasiCtx::builder().env("A", "0").build(),+ b: WasiCtx::builder().env("B", "0").build(),+ table: ResourceTable::default(),+ },+ )?;+ let command = Command::instantiate_async(&mut store, &component, &linker).await?;+ store+ .run_concurrent(async |store| {+ command+ .wasi_cli_run()+ .call_run(store)+ .await?+ .map_err(|()| wasmtime::format_err!("run returned a failure"))+ })+ .await?+}diff --git a/crates/wit-bindgen/src/lib.rs b/crates/wit-bindgen/src/lib.rsindex 31fab6ea90..fc3ed1b164 100644--- a/crates/wit-bindgen/src/lib.rs+++ b/crates/wit-bindgen/src/lib.rs@@ -2482,17 +2482,60 @@ impl<'a> InterfaceGenerator<'a> {_ => return None,};let error_typeid = match result.err? {- Type::Id(id) => resolve_type_definition_id(&self.resolve, id),+ Type::Id(id) => id,_ => return None,};- let name = self.generator.trappable_errors.get(&error_typeid)?;+ let trappable_error_id = resolve_type_definition_id(self.resolve, error_typeid);+ let name = self.generator.trappable_errors.get(&trappable_error_id)?;let mut path = self.path_to_root();uwrite!(path, "{name}");Some((result, error_typeid, path))}+ /// Determines the path to the `Host` trait and type name/identifier to use+ /// when using `id` as an error type.+ ///+ /// The `id` provided is the `E` in `result<T, E>`, and its root definition+ /// must be in `self.generator.trappable_errors`. This function will return+ /// the path to the `Host` trait, or `None` if it's in the trait in this+ /// module being generated. Additionally a new `TypeId` is returned which is+ /// either `id` or the root definition of `id` if it's a `use` alias for+ /// example.+ ///+ /// The returned `id` should be used for naming purposes for the error+ /// conversion.+ fn error_convert_path_to_host_and_id(&self, id: TypeId) -> (Option<String>, TypeId) {+ let trappable_error_id = resolve_type_definition_id(self.resolve, id);++ // If we're generating a trait for a named import then don't use the+ // `Host` trait for non-named imports since that's likely got other+ // methods we're not interested in. By returning `None` here it means+ // that named import traits will have their own conversions for errors.+ //+ // Note that this is a bit unfortunate where it means that every+ // interface referring to an error will have a conversion method instead+ // of just one conversion method on the original definition. The only+ // way I can think of to solve that would be to have a new trait+ // generated like `HostErrorConvert` but that's a bit heavyweight of a+ // change for now. In the meantime we'll just live with some duplicated+ // error conversions in `wasmtime-wasi` hopefully...+ if self.named_import_id.is_some() {+ return (None, id);+ }++ // Otherwise though if we're not generating anything for a named import+ // then we're specifically interested in the root definition of the `id`+ // error type, so look it up all based on its resolved version (aka+ // `trappable_error_id` here).+ let owner = match self.resolve.types[trappable_error_id].owner {+ TypeOwner::Interface(i) => i,+ _ => unimplemented!(),+ };+ (self.path_to_interface(owner), trappable_error_id)+ }+fn generate_add_to_linker(&mut self, id: InterfaceId, name: &str) {let iface = &self.resolve.interfaces[id];let owner = TypeOwner::Interface(id);@@ -2501,7 +2544,7 @@ impl<'a> InterfaceGenerator<'a> {let mut required_conversion_traits = IndexSet::new();let extra_functions = {let mut functions = Vec::new();- let mut errors_converted = IndexMap::new();+ let mut errors_converted = IndexSet::new();let mut my_error_types = iface.types.iter()@@ -2516,23 +2559,31 @@ impl<'a> InterfaceGenerator<'a> {.map(|(_, id, _)| id),);for err_id in my_error_types {- let err = &self.resolve.types[resolve_type_definition_id(self.resolve, err_id)];- let err_name = err.name.as_ref().unwrap();- let owner = match err.owner {- TypeOwner::Interface(i) => i,- _ => unimplemented!(),- };- match self.path_to_interface(owner) {+ let (convert_path, err_id) = self.error_convert_path_to_host_and_id(err_id);+ let trappable_error_id = resolve_type_definition_id(self.resolve, err_id);+ match convert_path {Some(path) => {required_conversion_traits.insert(format!("{path}::Host"));}None => {- if errors_converted.insert(err_name, err_id).is_none() {- functions.push(ExtraTraitMethod::ErrorConvert {- name: err_name,- id: err_id,- })+ if !errors_converted.insert(err_id) {+ continue;}+ let err = &self.resolve.types[err_id];+ let err_name = err.name.as_ref().unwrap();+ let owner = match err.owner {+ TypeOwner::Interface(i) => i,+ _ => unimplemented!(),+ };+ let ty_path_prefix = match self.path_to_interface(owner) {+ Some(path) => format!("{path}::"),+ None => String::new(),+ };+ functions.push(ExtraTraitMethod::ErrorConvert {+ name: err_name,+ trappable_error_id,+ ty_path_prefix,+ });}}}@@ -2602,9 +2653,18 @@ impl<'a> InterfaceGenerator<'a> {}let options_param = if self.generator.interface_link_options[&id].has_any() {- "options: &LinkOptions,"+ let path = match self.named_import_id {+ Some(_) => {+ let path = self+ .path_to_interface(id)+ .expect("named import always has a sibling interface-import module");+ format!("{path}::")+ }+ None => String::new(),+ };+ format!("options: &{path}LinkOptions,")} else {- ""+ String::new()};let options_param_forward = if self.generator.interface_link_options[&id].has_any() {"options,"@@ -2930,13 +2990,10 @@ pub fn add_to_linker<T, D>(uwrite!(self.src, "Ok(r)\n");}} else if let Some((_, err, _)) = self.special_case_trappable_error(func) {- let err = &self.resolve.types[resolve_type_definition_id(self.resolve, err)];+ let (convert_path, err) = self.error_convert_path_to_host_and_id(err);+ let err = &self.resolve.types[err];let err_name = err.name.as_ref().unwrap();- let owner = match err.owner {- TypeOwner::Interface(i) => i,- _ => unimplemented!(),- };- let convert_trait = match self.path_to_interface(owner) {+ let convert_trait = match convert_path {Some(path) => format!("{path}::Host"),None => format!("Host"),};@@ -3404,9 +3461,13 @@ fn drop(accessor: {wt}::component::Access<T, Self>, {id_param}rep: {wt}::compone}uwrite!(self.src, ";");}- ExtraTraitMethod::ErrorConvert { name, id } => {+ ExtraTraitMethod::ErrorConvert {+ name,+ trappable_error_id,+ ty_path_prefix,+ } => {let root = self.path_to_root();- let custom_name = &self.generator.trappable_errors[id];+ let custom_name = &self.generator.trappable_errors[trappable_error_id];let snake = name.to_snake_case();let camel = name.to_upper_camel_case();uwrite!(@@ -3416,7 +3477,7 @@ fn convert_{snake}(&mut self, err: {root}{custom_name}) ->");self.push_wasmtime_or_anyhow_result();- uwrite!(self.src, "<{camel}>;");+ uwrite!(self.src, "<{ty_path_prefix}{camel}>;");}}}@@ -3486,9 +3547,13 @@ fn convert_{snake}(&mut self, err: {root}{custom_name}) ->",);}- ExtraTraitMethod::ErrorConvert { name, id } => {+ ExtraTraitMethod::ErrorConvert {+ name,+ trappable_error_id,+ ty_path_prefix,+ } => {let root = self.path_to_root();- let custom_name = &self.generator.trappable_errors[id];+ let custom_name = &self.generator.trappable_errors[trappable_error_id];let snake = name.to_snake_case();let camel = name.to_upper_camel_case();uwrite!(@@ -3498,7 +3563,7 @@ fn convert_{snake}(&mut self, err: {root}{custom_name}) ->self.push_wasmtime_or_anyhow_result();uwriteln!(self.src,- "<{camel}> {{+ "<{ty_path_prefix}{camel}> {{{trait_name}::convert_{snake}(*self, err)}}",@@ -3513,8 +3578,21 @@ fn convert_{snake}(&mut self, err: {root}{custom_name}) ->}enum ExtraTraitMethod<'a> {- ResourceDrop { name: &'a str },- ErrorConvert { name: &'a str, id: TypeId },+ ResourceDrop {+ name: &'a str,+ },+ ErrorConvert {+ name: &'a str,+ /// This is the `TypeId` that's a member of the `trappable_errors` set+ /// within the generator.+ ///+ /// Note that this is distinct from the `E` in `result<T, E>` where `E`+ /// might actually be a `use` or a rename of some other type. Here the+ /// `trappable_error_id` is the "root" type or the type definition+ /// itself.+ trappable_error_id: TypeId,+ ty_path_prefix: String,+ },}struct FunctionPartitioning<'a> {@@ -3656,7 +3734,7 @@ impl LinkOptionsBuilder {for feature in unstable_features.iter() {let feature_rust_name = feature.to_snake_case();- uwriteln!(src, "{feature_rust_name}: bool,");+ uwriteln!(src, "pub(crate) {feature_rust_name}: bool,");}uwriteln!(src, "}}");