Skip to content

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

Support resources for implements (#13666)

Bailey Hayes944abfe157c1
diff --git a/crates/component-macro/tests/codegen.rs b/crates/component-macro/tests/codegen.rs
index 4b2eed85ab..bcb0e15829 100644
--- a/crates/component-macro/tests/codegen.rs
+++ b/crates/component-macro/tests/codegen.rs
@@ -884,4 +884,123 @@ mod named_imports {
imports: { default: async | store },
});
}
+
+ // An interface that defines a resource (with a constructor, a method, and
+ // a static function) reached through a named import. The named-imports
+ // resource trait threads the embedder-chosen id through every method,
+ // including the destructor.
+ mod resources_sync {
+ use wasmtime::component::Resource;
+
+ wasmtime::component::bindgen!({
+ inline: "
+ package foo:foo;
+
+ interface store {
+ resource cache {
+ constructor(label: u32);
+ get: func(key: u32) -> u32;
+ set: func(key: u32, value: u32);
+ merge: static func(a: u32, b: u32) -> u32;
+ }
+ touch: func();
+ }
+
+ world the-world {
+ import store;
+ }
+ ",
+ named_imports: {
+ "foo:foo/store": String,
+ },
+ });
+
+ struct MyHost;
+
+ // The normal resource trait is generated as usual, with no id...
+ impl foo::foo::store::HostCache for MyHost {
+ fn new(&mut self, label: u32) -> Resource<foo::foo::store::Cache> {
+ Resource::new_own(label)
+ }
+ fn get(&mut self, _self_: Resource<foo::foo::store::Cache>, key: u32) -> u32 {
+ key
+ }
+ fn set(&mut self, _self_: Resource<foo::foo::store::Cache>, _key: u32, _value: u32) {}
+ fn merge(&mut self, a: u32, b: u32) -> u32 {
+ a + b
+ }
+ fn drop(&mut self, _rep: Resource<foo::foo::store::Cache>) -> wasmtime::Result<()> {
+ Ok(())
+ }
+ }
+ impl foo::foo::store::Host for MyHost {
+ fn touch(&mut self) {}
+ }
+
+ // ...and the named-imports resource trait has the extra id parameter on
+ // the constructor, methods, the static function, and the destructor.
+ impl named_imports::foo::foo::store::HostCache for MyHost {
+ fn new(&mut self, _id: String, label: u32) -> Resource<foo::foo::store::Cache> {
+ Resource::new_own(label)
+ }
+ fn get(
+ &mut self,
+ _id: String,
+ _self_: Resource<foo::foo::store::Cache>,
+ key: u32,
+ ) -> u32 {
+ key
+ }
+ fn set(
+ &mut self,
+ _id: String,
+ _self_: Resource<foo::foo::store::Cache>,
+ _key: u32,
+ _value: u32,
+ ) {
+ }
+ fn merge(&mut self, _id: String, a: u32, b: u32) -> u32 {
+ a + b
+ }
+ 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 touch(&mut self, _id: String) {}
+ }
+ }
+
+ // Compile-only coverage that resources also generate correctly through the
+ // async/concurrent (store) path of named imports, which uses the
+ // `*WithStore` resource trait variants and the concurrent destructor.
+ mod resources_async_store {
+ #[derive(Clone)]
+ pub struct MyId(u32);
+
+ wasmtime::component::bindgen!({
+ inline: "
+ package foo:foo;
+
+ interface store {
+ resource cache {
+ constructor(label: u32);
+ get: func(key: u32) -> u32;
+ }
+ }
+
+ world the-world {
+ import store;
+ }
+ ",
+ named_imports: {
+ "foo:foo/store": MyId,
+ },
+ imports: { default: async | store },
+ });
+ }
}
diff --git a/crates/wit-bindgen/src/lib.rs b/crates/wit-bindgen/src/lib.rs
index f5eda5df32..6ca77d39d4 100644
--- a/crates/wit-bindgen/src/lib.rs
+++ b/crates/wit-bindgen/src/lib.rs
@@ -463,7 +463,7 @@ impl Wasmtime {
) {
assert!(projection.is_empty());
if key == interface_name {
- self.generate_named_import(resolve, id, &interface_name, &id_type)?;
+ self.generate_named_import(resolve, id, &id_type)?;
continue 'outer;
}
}
@@ -479,19 +479,8 @@ impl Wasmtime {
&mut self,
resolve: &Resolve,
id: InterfaceId,
- named_import_key: &str,
id_type: &str,
) -> anyhow::Result<()> {
- // Resources are not supported for named imports just yet, it's a bit
- // weird with the resource traits.
- if get_resources(resolve, id).next().is_some() {
- bail!(
- "the interface {named_import_key:?} was specified in \
- `named_imports` but defines a resource, which is not \
- supported"
- );
- }
-
let key = WorldKey::Interface(id);
let mut generator = InterfaceGenerator::new(self, resolve);
generator.current_interface = Some((id, &key, InterfaceKind::Named));
@@ -1568,7 +1557,7 @@ impl Wasmtime {
);
let gate = FeatureGate::open(&mut self.src, &resolve.worlds[world].stability);
for (ty, _name) in get_world_resources(resolve, world) {
- self.generate_add_resource_to_linker(None, None, "linker", resolve, ty);
+ self.generate_add_resource_to_linker(None, None, "linker", resolve, ty, false);
}
for f in self.world_import_functions.clone() {
let mut generator = InterfaceGenerator::new(self, resolve);
@@ -1665,6 +1654,7 @@ impl Wasmtime {
inst: &str,
resolve: &Resolve,
ty: TypeId,
+ named: bool,
) {
let ty = &resolve.types[ty];
let name = ty.name.as_ref().unwrap();
@@ -1674,6 +1664,22 @@ impl Wasmtime {
let gate = FeatureGate::open(src, stability);
let camel = name.to_upper_camel_case();
+ // For named imports the destructor closure additionally closes over
+ // the embedder-chosen `id` and threads it into `drop`. This mirrors
+ // the per-function closures generated by `generate_add_function_to_linker`:
+ // `id_outer` clones the id once for the `move` closure, `id_inner`
+ // re-clones it on each invocation, and `id_arg` forwards it to `drop`.
+ let (id_outer, id_close, id_inner, id_arg) = if named {
+ (
+ "{ let id = id.clone(); ",
+ " }",
+ "let id = id.clone();",
+ "id, ",
+ )
+ } else {
+ ("", "", "", "")
+ };
+
let flags = self.opts.imports.resource_drop_flags(resolve, key, name);
if flags.contains(FunctionFlags::ASYNC) {
if flags.contains(FunctionFlags::STORE) {
@@ -1682,14 +1688,15 @@ impl Wasmtime {
"{inst}.resource_concurrent(
\"{name}\",
{wt}::component::ResourceType::host::<{camel}>(),
- move |caller: &{wt}::component::Accessor::<T>, rep| {{
+ {id_outer}move |caller: &{wt}::component::Accessor::<T>, rep| {{
+ {id_inner}
{wt}::component::__internal::Box::pin(async move {{
let accessor = &caller.with_getter(host_getter);
{wt}::ToWasmtimeResult::to_wasmtime_result(
- Host{camel}WithStore::<T>::drop(accessor, {wt}::component::Resource::new_own(rep)).await
+ Host{camel}WithStore::<T>::drop(accessor, {id_arg}{wt}::component::Resource::new_own(rep)).await
)
}})
- }},
+ }}{id_close},
)?;"
)
} else {
@@ -1698,13 +1705,14 @@ impl Wasmtime {
"{inst}.resource_async(
\"{name}\",
{wt}::component::ResourceType::host::<{camel}>(),
- move |mut store, rep| {{
+ {id_outer}move |mut store, rep| {{
+ {id_inner}
{wt}::component::__internal::Box::new(async move {{
{wt}::ToWasmtimeResult::to_wasmtime_result(
- Host{camel}::drop(&mut host_getter(store.data_mut()), {wt}::component::Resource::new_own(rep)).await
+ Host{camel}::drop(&mut host_getter(store.data_mut()), {id_arg}{wt}::component::Resource::new_own(rep)).await
)
}})
- }},
+ }}{id_close},
)?;"
)
}
@@ -1722,13 +1730,13 @@ impl Wasmtime {
"{inst}.resource(
\"{name}\",
{wt}::component::ResourceType::host::<{camel}>(),
- move |mut store, rep| -> {wt}::Result<()> {{
-
+ {id_outer}move |mut store, rep| -> {wt}::Result<()> {{
+ {id_inner}
let resource = {wt}::component::Resource::new_own(rep);
{wt}::ToWasmtimeResult::to_wasmtime_result(
- Host{camel}{trait_suffix}::drop({first_arg}, resource)
+ Host{camel}{trait_suffix}::drop({first_arg}, {id_arg}resource)
)
- }},
+ }}{id_close},
)?;",
)
}
@@ -2477,6 +2485,33 @@ impl<'a> InterfaceGenerator<'a> {
functions
};
+ // For named imports the resource traits are not generated by the
+ // normal `type_resource` path (those bindings live in the sibling
+ // interface-import module). Generate them here within this module
+ // instead: the opaque marker type is reused from that sibling module
+ // via a `pub use` while the `Host{Resource}` traits are regenerated
+ // with the embedder-chosen `id` threaded through every method,
+ // including the destructor.
+ if self.named_import_id.is_some() {
+ for (ty, resource_name) in get_resources(self.resolve, id).collect::<Vec<_>>() {
+ let camel = resource_name.to_upper_camel_case();
+ let path = self
+ .path_to_interface(id)
+ .expect("named import always has a sibling interface-import module");
+ uwriteln!(self.src, "pub use {path}::{camel};");
+ let functions = get_resource_functions(self.resolve, ty);
+ let trait_ = self.generate_trait(
+ &format!("Host{camel}"),
+ &functions,
+ &[ExtraTraitMethod::ResourceDrop {
+ name: resource_name,
+ }],
+ &[],
+ );
+ self.all_func_flags |= trait_.all_func_flags;
+ }
+ }
+
// Generate the `pub trait` which represents the host functionality for
// this import which additionally inherits from all resource traits
// for this interface defined by `type_resource`.
@@ -2555,6 +2590,7 @@ impl<'a> InterfaceGenerator<'a> {
"inst",
self.resolve,
ty,
+ self.named_import_id.is_some(),
);
}
@@ -3187,6 +3223,20 @@ pub fn add_to_linker<T, D>(
let wt = self.generator.wasmtime_path();
let partition = self.partition_concurrent_funcs(functions.iter().copied());
+ // For named imports every trait method (including the resource
+ // destructor) additionally takes the embedder-chosen `id`. This
+ // mirrors `generate_function_trait_sig`, which threads the same
+ // parameter through the non-destructor methods.
+ let id_param = match &self.named_import_id {
+ Some(id) => format!("id: {id}, "),
+ None => String::new(),
+ };
+ let id_arg = if self.named_import_id.is_some() {
+ "id, "
+ } else {
+ ""
+ };
+
for (_, flags) in partition.with_store.iter().chain(&partition.without_store) {
ret.all_func_flags |= *flags;
}
@@ -3229,7 +3279,7 @@ pub fn add_to_linker<T, D>(
uwrite!(
self.src,
"
-fn drop(accessor: &{wt}::component::Accessor<T, Self>, rep: {wt}::component::Resource<{camel}>)
+fn drop(accessor: &{wt}::component::Accessor<T, Self>, {id_param}rep: {wt}::component::Resource<{camel}>)
-> impl ::core::future::Future<Output =
"
);
@@ -3239,7 +3289,7 @@ fn drop(accessor: &{wt}::component::Accessor<T, Self>, rep: {wt}::component::Res
uwrite!(
self.src,
"
-fn drop(accessor: {wt}::component::Access<T, Self>, rep: {wt}::component::Resource<{camel}>)
+fn drop(accessor: {wt}::component::Access<T, Self>, {id_param}rep: {wt}::component::Resource<{camel}>)
->
"
);
@@ -3293,7 +3343,7 @@ fn drop(accessor: {wt}::component::Access<T, Self>, rep: {wt}::component::Resour
let camel = name.to_upper_camel_case();
uwrite!(
self.src,
- "fn drop(&mut self, rep: {wt}::component::Resource<{camel}>) -> "
+ "fn drop(&mut self, {id_param}rep: {wt}::component::Resource<{camel}>) -> "
);
if flags.contains(FunctionFlags::ASYNC) {
uwrite!(self.src, "impl ::core::future::Future<Output =");
@@ -3376,13 +3426,13 @@ fn convert_{snake}(&mut self, err: {root}{custom_name}) ->
}
uwrite!(
self.src,
- "fn drop(&mut self, rep: {wt}::component::Resource<{camel}>) -> ",
+ "fn drop(&mut self, {id_param}rep: {wt}::component::Resource<{camel}>) -> ",
);
self.push_wasmtime_or_anyhow_result();
uwriteln!(
self.src,
"<()> {{
- {trait_name}::drop(*self, rep){await_}
+ {trait_name}::drop(*self, {id_arg}rep){await_}
}}
",
);
diff --git a/tests/all/component_model/bindgen.rs b/tests/all/component_model/bindgen.rs
index d25de28f36..cc3bae74ee 100644
--- a/tests/all/component_model/bindgen.rs
+++ b/tests/all/component_model/bindgen.rs
@@ -1291,3 +1291,394 @@ mod named_imports {
Ok(())
}
}
+
+/// A component shared by the sync and async resource named-import tests below.
+///
+/// It imports `demo:pkg/store` (which defines a `counter` resource plus a free
+/// `label` function) twice, under arbitrary names `a` and `b`, each annotated
+/// as implementing that interface. The exported `run` exercises, through *both*
+/// imports: the constructor, an instance method (`value`/`bump`), a static
+/// method (`combine`), the free function (`label`), and the destructor.
+const RESOURCE_COMPONENT: &str = r#"
+ (component
+ (import "a" (implements "demo:pkg/store") (instance $a
+ (export "counter" (type $counter_a (sub resource)))
+ (export "[constructor]counter" (func (param "init" u32) (result (own $counter_a))))
+ (export "[method]counter.value" (func (param "self" (borrow $counter_a)) (result u32)))
+ (export "[method]counter.bump" (func (param "self" (borrow $counter_a)) (param "by" u32)))
+ (export "[static]counter.combine" (func (param "a" u32) (param "b" u32) (result u32)))
+ (export "label" (func (result u32)))
+ ))
+ (import "b" (implements "demo:pkg/store") (instance $b
+ (export "counter" (type $counter_b (sub resource)))
+ (export "[constructor]counter" (func (param "init" u32) (result (own $counter_b))))
+ (export "[method]counter.value" (func (param "self" (borrow $counter_b)) (result u32)))
+ (export "[method]counter.bump" (func (param "self" (borrow $counter_b)) (param "by" u32)))
+ (export "[static]counter.combine" (func (param "a" u32) (param "b" u32) (result u32)))
+ (export "label" (func (result u32)))
+ ))
+
+ (alias export $a "counter" (type $ca))
+ (alias export $b "counter" (type $cb))
+
+ (core func $a-ctor (canon lower (func $a "[constructor]counter")))
+ (core func $a-value (canon lower (func $a "[method]counter.value")))
+ (core func $a-bump (canon lower (func $a "[method]counter.bump")))
+ (core func $a-combine (canon lower (func $a "[static]counter.combine")))
+ (core func $a-label (canon lower (func $a "label")))
+ (core func $a-drop (canon resource.drop $ca))
+ (core func $b-ctor (canon lower (func $b "[constructor]counter")))
+ (core func $b-value (canon lower (func $b "[method]counter.value")))
+ (core func $b-bump (canon lower (func $b "[method]counter.bump")))
+ (core func $b-combine (canon lower (func $b "[static]counter.combine")))
+ (core func $b-label (canon lower (func $b "label")))
+ (core func $b-drop (canon resource.drop $cb))
+
+ (core module $m
+ (import "" "a-ctor" (func $a-ctor (param i32) (result i32)))
+ (import "" "a-value" (func $a-value (param i32) (result i32)))
+ (import "" "a-bump" (func $a-bump (param i32 i32)))
+ (import "" "a-combine" (func $a-combine (param i32 i32) (result i32)))
+ (import "" "a-label" (func $a-label (result i32)))
+ (import "" "a-drop" (func $a-drop (param i32)))
+ (import "" "b-ctor" (func $b-ctor (param i32) (result i32)))
+ (import "" "b-value" (func $b-value (param i32) (result i32)))
+ (import "" "b-bump" (func $b-bump (param i32 i32)))
+ (import "" "b-combine" (func $b-combine (param i32 i32) (result i32)))
+ (import "" "b-label" (func $b-label (result i32)))
+ (import "" "b-drop" (func $b-drop (param i32)))
+
+ (func (export "run")
+ (local $ha i32)
+ (local $hb i32)
+
+ (local.set $ha (call $a-ctor (i32.const 10)))
+ (call $a-bump (local.get $ha) (i32.const 5))
+ (if (i32.ne (call $a-value (local.get $ha)) (i32.const 15))
+ (then unreachable))
+
+ (local.set $hb (call $b-ctor (i32.const 100)))
+ (if (i32.ne (call $b-value (local.get $hb)) (i32.const 100))
+ (then unreachable))
+
+ ;; static method through each import
+ (if (i32.ne (call $a-combine (i32.const 3) (i32.const 4)) (i32.const 7))
+ (then unreachable))
+ (if (i32.ne (call $b-combine (i32.const 5) (i32.const 6)) (i32.const 11))
+ (then unreachable))
+
+ ;; free function in the same interface, id-dependent result
+ (if (i32.ne (call $a-label) (i32.const 1000))
+ (then unreachable))
+ (if (i32.ne (call $b-label) (i32.const 2000))
+ (then unreachable))
+
+ (call $a-drop (local.get $ha))
+ (call $b-drop (local.get $hb))
+ )
+ )
+ (core instance $i (instantiate $m
+ (with "" (instance
+ (export "a-ctor" (func $a-ctor))
+ (export "a-value" (func $a-value))
+ (export "a-bump" (func $a-bump))
+ (export "a-combine" (func $a-combine))
+ (export "a-label" (func $a-label))
+ (export "a-drop" (func $a-drop))
+ (export "b-ctor" (func $b-ctor))
+ (export "b-value" (func $b-value))
+ (export "b-bump" (func $b-bump))
+ (export "b-combine" (func $b-combine))
+ (export "b-label" (func $b-label))
+ (export "b-drop" (func $b-drop))
+ ))
+ ))
+
+ (func (export "run") (canon lift (core func $i "run")))
+ )
+"#;
+
+mod named_imports_resources {
+ use super::*;
+ use std::collections::HashMap;
+ use wasmtime::component::{HasSelf, Resource};
+
+ /// Host-chosen id threaded into every resource method.
+ #[derive(Clone)]
+ pub struct MyId(u32);
+
+ wasmtime::component::bindgen!({
+ inline: "
+ package demo:pkg;
+
+ interface store {
+ resource counter {
+ constructor(init: u32);
+ value: func() -> u32;
+ bump: func(by: u32);
+ combine: static func(a: u32, b: u32) -> u32;
+ }
+
+ label: func() -> u32;
+ }
+
+ world runner {
+ import store;
+
+ export run: func();
+ }
+ ",
+ named_imports: {
+ "demo:pkg/store": MyId,
+ },
+ });
+
+ use demo::pkg::store::Counter;
+
+ fn implements_engine() -> Engine {
+ let mut config = Config::new();
+ config.wasm_component_model(true);
+ config.wasm_component_model_implements(true);
+ Engine::new(&config).unwrap()
+ }
+
+ #[derive(Default)]
+ struct MyHost {
+ /// Resource state keyed by `(id, rep)`.
+ counters: HashMap<(u32, u32), u32>,
+ /// Global rep allocator producing distinct reps across imports.
+ next_rep: u32,
+ /// Records `(id, op)` of every static/free-function call.
+ calls: Vec<(u32, &'static str)>,
+ /// Records `(id, rep)` of every destructor call.
+ drops: Vec<(u32, u32)>,
+ }
+
+ impl named_imports::demo::pkg::store::HostCounter for MyHost {
+ fn new(&mut self, id: MyId, init: u32) -> Resource<Counter> {
+ self.next_rep += 1;
+ let rep = self.next_rep;
+ self.counters.insert((id.0, rep), init);
+ Resource::new_own(rep)
+ }
+
+ fn value(&mut self, id: MyId, self_: Resource<Counter>) -> u32 {
+ self.counters[&(id.0, self_.rep())]
+ }
+
+ fn bump(&mut self, id: MyId, self_: Resource<Counter>, by: u32) {
+ *self.counters.get_mut(&(id.0, self_.rep())).unwrap() += by;
+ }
+
+ fn combine(&mut self, id: MyId, a: u32, b: u32) -> u32 {
+ self.calls.push((id.0, "combine"));
+ a + b
+ }
+
+ fn drop(&mut self, id: MyId, rep: Resource<Counter>) -> Result<()> {
+ self.drops.push((id.0, rep.rep()));
+ self.counters.remove(&(id.0, rep.rep()));
+ Ok(())
+ }
+ }
+
+ impl named_imports::demo::pkg::store::Host for MyHost {
+ fn label(&mut self, id: MyId) -> u32 {
+ self.calls.push((id.0, "label"));
+ id.0 * 1000
+ }
+ }
+
+ #[test]
+ fn resource_ids_are_threaded_through() -> Result<()> {
+ let engine = implements_engine();
+ let component = Component::new(&engine, super::RESOURCE_COMPONENT)?;
+ let mut linker = Linker::new(&engine);
+ named_imports::demo::pkg::store::add_to_linker::<_, HasSelf<MyHost>>(
+ &mut linker,
+ &component,
+ |name| match name {
+ "a" => Ok(MyId(1)),
+ "b" => Ok(MyId(2)),
+ other => wasmtime::bail!("unexpected import: {other}"),
+ },
+ |s| s,
+ )?;
+ let mut store = Store::new(&engine, MyHost::default());
+ let runner = Runner::instantiate(&mut store, &component, &linker)?;
+
+ runner.call_run(&mut store)?;
+
+ let data = store.data();
+ // Destructors ran with the right id and distinct reps (a -> 1, b -> 2),
+ // so a swapped drop id would fail these assertions.
+ assert!(data.drops.contains(&(1, 1)), "drops: {:?}", data.drops);
+ assert!(data.drops.contains(&(2, 2)), "drops: {:?}", data.drops);
+ // The static method and the free function were each routed to the right
+ // id through both imports.
+ assert!(
+ data.calls.contains(&(1, "combine")),
+ "calls: {:?}",
+ data.calls
+ );
+ assert!(
+ data.calls.contains(&(2, "combine")),
+ "calls: {:?}",
+ data.calls
+ );
+ assert!(
+ data.calls.contains(&(1, "label")),
+ "calls: {:?}",
+ data.calls
+ );
+ assert!(
+ data.calls.contains(&(2, "label")),
+ "calls: {:?}",
+ data.calls
+ );
+ // Every counter was removed on drop.
+ assert!(data.counters.is_empty(), "counters: {:?}", data.counters);
+ Ok(())
+ }
+}
+
+// The same resource exercise as above, but with the host bindings generated in
+// async mode (`imports`/`exports` async). This drives the `resource_async`
+// destructor closure and the async resource methods through the runtime, where
+// `call_async` runs each host future. The WIT functions remain synchronous, so
+// the component itself (`super::RESOURCE_COMPONENT`) is unchanged.
+mod named_imports_resources_async {
+ use super::*;
+ use std::collections::HashMap;
+ use wasmtime::component::{HasSelf, Resource};
+
+ #[derive(Clone)]
+ pub struct MyId(u32);
+
+ wasmtime::component::bindgen!({
+ inline: "
+ package demo:pkg;
+
+ interface store {
+ resource counter {
+ constructor(init: u32);
+ value: func() -> u32;
+ bump: func(by: u32);
+ combine: static func(a: u32, b: u32) -> u32;
+ }
+
+ label: func() -> u32;
+ }
+
+ world runner {
+ import store;
+
+ export run: func();
+ }
+ ",
+ named_imports: {
+ "demo:pkg/store": MyId,
+ },
+ imports: { default: async },
+ exports: { default: async },
+ });
+
+ use demo::pkg::store::Counter;
+
+ fn implements_async_engine() -> Engine {
+ let mut config = Config::new();
+ config.wasm_component_model(true);
+ config.wasm_component_model_implements(true);
+ Engine::new(&config).unwrap()
+ }
+
+ #[derive(Default)]
+ struct MyHost {
+ counters: HashMap<(u32, u32), u32>,
+ next_rep: u32,
+ calls: Vec<(u32, &'static str)>,
+ drops: Vec<(u32, u32)>,
+ }
+
+ impl named_imports::demo::pkg::store::HostCounter for MyHost {
+ async fn new(&mut self, id: MyId, init: u32) -> Resource<Counter> {
+ self.next_rep += 1;
+ let rep = self.next_rep;
+ self.counters.insert((id.0, rep), init);
+ Resource::new_own(rep)
+ }
+
+ async fn value(&mut self, id: MyId, self_: Resource<Counter>) -> u32 {
+ self.counters[&(id.0, self_.rep())]
+ }
+
+ async fn bump(&mut self, id: MyId, self_: Resource<Counter>, by: u32) {
+ *self.counters.get_mut(&(id.0, self_.rep())).unwrap() += by;
+ }
+
+ async fn combine(&mut self, id: MyId, a: u32, b: u32) -> u32 {
+ self.calls.push((id.0, "combine"));
+ a + b
+ }
+
+ async fn drop(&mut self, id: MyId, rep: Resource<Counter>) -> Result<()> {
+ self.drops.push((id.0, rep.rep()));
+ self.counters.remove(&(id.0, rep.rep()));
+ Ok(())
+ }
+ }
+
+ impl named_imports::demo::pkg::store::Host for MyHost {
+ async fn label(&mut self, id: MyId) -> u32 {
+ self.calls.push((id.0, "label"));
+ id.0 * 1000
+ }
+ }
+
+ #[tokio::test]
+ async fn resource_ids_are_threaded_through_async() -> Result<()> {
+ let engine = implements_async_engine();
+ let component = Component::new(&engine, super::RESOURCE_COMPONENT)?;
+ let mut linker = Linker::new(&engine);
+ named_imports::demo::pkg::store::add_to_linker::<_, HasSelf<MyHost>>(
+ &mut linker,
+ &component,
+ |name| match name {
+ "a" => Ok(MyId(1)),
+ "b" => Ok(MyId(2)),
+ other => wasmtime::bail!("unexpected import: {other}"),
+ },
+ |s| s,
+ )?;
+ let mut store = Store::new(&engine, MyHost::default());
+ let runner = Runner::instantiate_async(&mut store, &component, &linker).await?;
+
+ runner.call_run(&mut store).await?;
+
+ let data = store.data();
+ assert!(data.drops.contains(&(1, 1)), "drops: {:?}", data.drops);
+ assert!(data.drops.contains(&(2, 2)), "drops: {:?}", data.drops);
+ assert!(
+ data.calls.contains(&(1, "combine")),
+ "calls: {:?}",
+ data.calls
+ );
+ assert!(
+ data.calls.contains(&(2, "combine")),
+ "calls: {:?}",
+ data.calls
+ );
+ assert!(
+ data.calls.contains(&(1, "label")),
+ "calls: {:?}",
+ data.calls
+ );
+ assert!(
+ data.calls.contains(&(2, "label")),
+ "calls: {:?}",
+ data.calls
+ );
+ assert!(data.counters.is_empty(), "counters: {:?}", data.counters);
+ Ok(())
+ }
+}