Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Improve docs and tests for implements (#14868)

Randolf J.ba74a9face6d
diff --git a/crates/cli-flags/src/lib.rs b/crates/cli-flags/src/lib.rs
index 4369644af8..f19fd3aed9 100644
--- a/crates/cli-flags/src/lib.rs
+++ b/crates/cli-flags/src/lib.rs
@@ -529,8 +529,9 @@ wasmtime_option_group! {
/// Component model support for fixed-length lists: this corresponds
/// to the 🔧 emoji in the component model specification
pub component_model_fixed_length_lists: Option<bool>,
- /// Component model support for `(implements ...)`, corresponds to the
- /// 🏷️ emoji in the upstream spec.
+ /// Component model support for `(implements ...)` and
+ /// `(external-id ...)`, corresponds to the 🏷️ emoji in the upstream
+ /// spec.
pub component_model_implements: Option<bool>,
/// Component model support for canonical names, corresponds to the
/// 🔗 emoji in the upstream spec.
diff --git a/crates/environ/src/component/types.rs b/crates/environ/src/component/types.rs
index 18d37a4296..18d108092b 100644
--- a/crates/environ/src/component/types.rs
+++ b/crates/environ/src/component/types.rs
@@ -466,8 +466,11 @@ pub struct ComponentExtern {
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ComponentExternData {
/// The `(implements "...")` annotation, if present: the name of the
- /// interface that this item implements, used when matching this item
- /// against imports by interface name rather than by import name.
+ /// interface that this item implements.
+ ///
+ /// This is metadata only: imports are resolved by their own name (e.g.
+ /// `my-label`), not by this interface name. Embedders can use it to find
+ /// out which interface a labelled item implements.
pub implements: Option<String>,
/// The `(external-id "...")` annotation, if present: a free-form
/// host-defined identifier which is ignored by type checking.
diff --git a/crates/wasi-http/src/ctx.rs b/crates/wasi-http/src/ctx.rs
index 642c5d2194..a9d50c743c 100644
--- a/crates/wasi-http/src/ctx.rs
+++ b/crates/wasi-http/src/ctx.rs
@@ -670,9 +670,11 @@ pub trait WasiHttpNamedView: Send + 'static {
/// 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.
+ /// It's strongly recommended, though not always required, that the
+ /// [`ResourceTable`] in the returned [`WasiHttpCtxView`] is the same table
+ /// that the default context, [`WasiHttpView::http`], uses. Resources
+ /// created through a named import can be used through interfaces bound to
+ /// the default context (and vice versa), and with separate tables those
+ /// lookups fail or find another context's resources.
fn http(&mut self, id: NamedId) -> WasiHttpCtxView<'_>;
}
diff --git a/crates/wasi/src/cli.rs b/crates/wasi/src/cli.rs
index 879262706e..75a991e18f 100644
--- a/crates/wasi/src/cli.rs
+++ b/crates/wasi/src/cli.rs
@@ -435,10 +435,12 @@ pub trait WasiCliNamedView: Send + 'static {
/// 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.
+ /// It's strongly recommended, though not always required, that the
+ /// [`ResourceTable`] in the returned [`WasiCliCtxView`] is the same table
+ /// that the default context, [`WasiCliView::cli`], uses. Resources created
+ /// through a named import can be used through interfaces bound to the
+ /// default context (and vice versa), and with separate tables those lookups
+ /// fail or find another context's resources.
fn cli(&mut self, id: NamedId) -> WasiCliCtxView<'_>;
}
diff --git a/crates/wasi/src/clocks.rs b/crates/wasi/src/clocks.rs
index faf03a718f..a5bf9abecd 100644
--- a/crates/wasi/src/clocks.rs
+++ b/crates/wasi/src/clocks.rs
@@ -401,9 +401,11 @@ pub trait WasiClocksNamedView: Send + 'static {
/// 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.
+ /// It's strongly recommended, though not always required, that the
+ /// [`ResourceTable`] in the returned [`WasiClocksCtxView`] is the same
+ /// table that the default context, [`WasiClocksView::clocks`], uses.
+ /// Resources created through a named import can be used through interfaces
+ /// bound to the default context (and vice versa), and with separate tables
+ /// those lookups fail or find another context's resources.
fn clocks(&mut self, id: NamedId) -> WasiClocksCtxView<'_>;
}
diff --git a/crates/wasi/src/filesystem.rs b/crates/wasi/src/filesystem.rs
index eb7027c76f..7b8052a9a3 100644
--- a/crates/wasi/src/filesystem.rs
+++ b/crates/wasi/src/filesystem.rs
@@ -1309,9 +1309,11 @@ pub trait WasiFilesystemNamedView: Send + 'static {
/// 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.
+ /// It's strongly recommended, though not always required, that the
+ /// [`ResourceTable`] in the returned [`WasiFilesystemCtxView`] is the same
+ /// table that the default context, [`WasiFilesystemView::filesystem`],
+ /// uses. Resources created through a named import can be used through
+ /// interfaces bound to the default context (and vice versa), and with
+ /// separate tables those lookups fail or find another context's resources.
fn filesystem(&mut self, id: NamedId) -> WasiFilesystemCtxView<'_>;
}
diff --git a/crates/wasi/src/sockets/mod.rs b/crates/wasi/src/sockets/mod.rs
index 98e562e362..39f8689491 100644
--- a/crates/wasi/src/sockets/mod.rs
+++ b/crates/wasi/src/sockets/mod.rs
@@ -736,9 +736,11 @@ pub trait WasiSocketsNamedView: Send + 'static {
/// 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.
+ /// It's strongly recommended, though not always required, that the
+ /// [`ResourceTable`] in the returned [`WasiSocketsCtxView`] is the same
+ /// table that the default context, [`WasiSocketsView::sockets`], uses.
+ /// Resources created through a named import can be used through interfaces
+ /// bound to the default context (and vice versa), and with separate tables
+ /// those lookups fail or find another context's resources.
fn sockets(&mut self, id: NamedId) -> WasiSocketsCtxView<'_>;
}
diff --git a/crates/wasi/src/view.rs b/crates/wasi/src/view.rs
index 6f95c911c4..9b6c83e2aa 100644
--- a/crates/wasi/src/view.rs
+++ b/crates/wasi/src/view.rs
@@ -97,8 +97,8 @@ 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
+/// is also public. Embedders define the meaning of this value and are in control
+/// of both creating this and 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
@@ -106,7 +106,7 @@ impl<T: WasiView> crate::sockets::WasiSocketsView for T {
///
/// 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.
+/// id and its contents.
///
/// [`wasmtime_wasi::p3::add_named_to_linker`]: crate::p3::add_named_to_linker
#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Debug)]
@@ -133,6 +133,14 @@ pub struct WasiCtxNamedView<'a, T>(pub &'a mut T);
pub trait WasiNamedView: Send + 'static {
/// Yields mutable access to the [`WasiCtx`] configuration used for this
/// context.
+ ///
+ /// It's strongly recommended, though not always required, that the
+ /// [`ResourceTable`] in the returned [`WasiCtxView`] is the same table that
+ /// [`WasiView::ctx`] returns. Resources created through a named import can
+ /// be used through interfaces bound to the default context (and vice
+ /// versa), for example streams returned by a named `wasi:cli/stdout` are
+ /// used through `wasi:io/streams`, and with separate tables those lookups
+ /// fail or find another context's resources.
fn ctx(&mut self, id: NamedId) -> WasiCtxView<'_>;
}
diff --git a/crates/wasmtime/src/config.rs b/crates/wasmtime/src/config.rs
index bab1c970d8..c4f7bcddb7 100644
--- a/crates/wasmtime/src/config.rs
+++ b/crates/wasmtime/src/config.rs
@@ -1415,6 +1415,9 @@ impl Config {
self
}
+ /// Configures whether the component model `(implements "...")` and
+ /// `(external-id "...")` name annotations are enabled.
+ ///
/// This corresponds to the 🏷️ emoji in the component model specification.
///
/// Please note that Wasmtime's support for this feature is a work in
diff --git a/crates/wasmtime/src/runtime/component/mod.rs b/crates/wasmtime/src/runtime/component/mod.rs
index 2467367f8c..b1fef26809 100644
--- a/crates/wasmtime/src/runtime/component/mod.rs
+++ b/crates/wasmtime/src/runtime/component/mod.rs
@@ -451,11 +451,12 @@ pub(crate) use self::store::ComponentStoreData;
/// // interfaces, used together with the component model's
/// // `(implements "...")` annotation.
/// //
-/// // For each interface listed here an extra `Host` trait is generated
-/// // under a top-level `named_imports` module (mirroring the interface's
-/// // normal module path) whose methods each take an additional first
-/// // argument: a reference to the host-chosen "id" type given as the value
-/// // (here `MyHandlerId`). Alongside the trait a reflection-based
+/// // Each key must name an interface that the world imports. For each
+/// // one an extra `Host` trait is generated under a top-level
+/// // `named_imports` module (mirroring the interface's normal module
+/// // path) whose methods each take an additional first argument: the
+/// // host-chosen "id" type given as the value (here `MyHandlerId`),
+/// // passed by value. Alongside the trait a reflection-based
/// // `add_to_linker` is generated:
/// //
/// // ```ignore
@@ -467,15 +468,23 @@ pub(crate) use self::store::ComponentStoreData;
/// // ) -> Result<()>;
/// // ```
/// //
-/// // This inspects `component`'s imports, and for each one annotated with
-/// // `(implements "wasi:http/handler")` calls `lookup` with the import's
-/// // name to obtain an id. That id is then cloned into each linker closure
-/// // and passed as the first argument to every method call, letting a
-/// // single `Host` implementation distinguish between multiple imports
-/// // of the same interface.
+/// // This inspects `component`'s imports, and for each one whose
+/// // `(implements "...")` annotation matches `wasi:http/handler` calls
+/// // `lookup` with the import's name to obtain an id. Matching uses
+/// // `ComponentExtern::is_implements`, so semver-compatible versions also
+/// // match. The id is then cloned for each call and passed as the first
+/// // argument to every method, letting a single `Host` implementation
+/// // distinguish between multiple imports of the same interface. To bind a
+/// // single import instead, the generated `add_to_linker_instance` takes a
+/// // `LinkerInstance`, such as `linker.instance("my-handler")?`, and the
+/// // id to use for it.
/// //
-/// // The id type must be `Clone + Send + Sync + 'static`. Interfaces that
-/// // define a resource are not supported here and cause a compile error.
+/// // The id type must be `Clone + Send + Sync + 'static`.
+/// //
+/// // Without this option the host can only load components whose
+/// // imports match the shape of the world given to `bindgen!`. With it,
+/// // the host can also load components which import the listed
+/// // interfaces under any names of their choosing.
/// named_imports: {
/// "wasi:http/handler": MyHandlerId,
/// },
diff --git a/crates/wit-bindgen/src/lib.rs b/crates/wit-bindgen/src/lib.rs
index 584b0c8856..d14792cd79 100644
--- a/crates/wit-bindgen/src/lib.rs
+++ b/crates/wit-bindgen/src/lib.rs
@@ -457,7 +457,8 @@ impl Wasmtime {
///
/// For each configured interface this generates, into a body stored in
/// `named_import_modules`, a `Host`/`HostWithStore` trait whose methods take
- /// an extra `&Id` parameter alongside a reflection-based `add_to_linker`.
+ /// an extra `Id` parameter (by value, cloned for each call) alongside a
+ /// reflection-based `add_to_linker`.
/// These are emitted underneath a top-level `named_imports` module by
/// `finish`.
fn generate_named_imports(&mut self, resolve: &Resolve) -> anyhow::Result<()> {
diff --git a/tests/all/component_model/bindgen.rs b/tests/all/component_model/bindgen.rs
index 95bf96dcec..81cad90e9e 100644
--- a/tests/all/component_model/bindgen.rs
+++ b/tests/all/component_model/bindgen.rs
@@ -1027,11 +1027,11 @@ mod implements {
const DUMMY: &str = r#"
(component
- (import "hot-cache" (instance $hot
+ (import "hot-cache" (implements "demo:pkg/store") (instance $hot
(export "get" (func (param "key" u32) (result u32)))
(export "set" (func (param "key" u32) (param "value" u32)))
))
- (import "durable" (instance $dur
+ (import "durable" (implements "demo:pkg/store") (instance $dur
(export "get" (func (param "key" u32) (result u32)))
(export "set" (func (param "key" u32) (param "value" u32)))
))
@@ -1071,6 +1071,13 @@ mod implements {
)
"#;
+ fn implements_engine() -> Engine {
+ let mut config = Config::new();
+ config.wasm_component_model(true);
+ config.wasm_component_model_implements(true);
+ Engine::new(&config).unwrap()
+ }
+
#[test]
fn add_to_linker_can_instantiate() -> Result<()> {
#[derive(Default)]
@@ -1088,7 +1095,7 @@ mod implements {
}
}
- let engine = engine();
+ let engine = implements_engine();
let mut linker = Linker::new(&engine);
Cache::add_to_linker::<_, HasSelf<MyHost>>(&mut linker, |s| s)?;
let component = Component::new(&engine, DUMMY)?;
@@ -1119,7 +1126,7 @@ mod implements {
durable: HashMap<u32, u32>,
}
- let engine = engine();
+ let engine = implements_engine();
let mut linker = Linker::new(&engine);
demo::pkg::store::add_to_linker_instance::<MyHost, HasSelf<HashMap<u32, u32>>>(
&mut linker.instance("hot-cache")?,
@@ -1136,7 +1143,6 @@ mod implements {
Ok(())
}
}
-
mod named_imports {
use super::*;
use std::collections::HashMap;
diff --git a/tests/misc_testsuite/component-model/implements-disabled.wast b/tests/misc_testsuite/component-model/implements-disabled.wast
index e4db929d96..1f42f40a6a 100644
--- a/tests/misc_testsuite/component-model/implements-disabled.wast
+++ b/tests/misc_testsuite/component-model/implements-disabled.wast
@@ -3,3 +3,13 @@
(assert_invalid
(component (import "a" (implements "a:b/c") (instance)))
"the `cm-implements` feature is not active")
+
+(assert_invalid
+ (component (import "a" (external-id "x") (instance)))
+ "the `cm-implements` feature is not active")
+
+(assert_invalid
+ (component
+ (import "a" (instance $a))
+ (export "b" (external-id "x") (instance $a)))
+ "the `cm-implements` feature is not active")