Skip to content

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

feat(bindgen): added error for mixed sync exports and async imports (#15000)

Andrew Steurerec63b69f3da9
diff --git a/crates/component-macro/src/bindgen.rs b/crates/component-macro/src/bindgen.rs
index 2f997aebdd..5dcda38d78 100644
--- a/crates/component-macro/src/bindgen.rs
+++ b/crates/component-macro/src/bindgen.rs
@@ -10,7 +10,7 @@ use syn::{Token, braced, token};
use wasmtime_wit_bindgen::{
FunctionConfig, FunctionFilter, FunctionFlags, Opts, Ownership, TrappableError,
};
-use wit_parser::{PackageId, Resolve, WorldId};
+use wit_parser::{Function, IndexMap, PackageId, Resolve, WorldId, WorldItem, WorldKey};
pub struct Config {
opts: Opts,
@@ -30,6 +30,8 @@ pub fn expand(input: &mut Config) -> Result<TokenStream> {
return Ok(quote::quote!(#src));
}
+ check_for_sync_exports_and_async_imports(input)?;
+
// If a magical `WASMTIME_DEBUG_BINDGEN` environment variable is set then
// place a formatted version of the expanded code into a file. This file
// will then show up in rustc error messages for any codegen issues and can
@@ -74,6 +76,67 @@ pub fn expand(input: &mut Config) -> Result<TokenStream> {
Ok(contents)
}
+fn check_for_sync_exports_and_async_imports(input: &Config) -> Result<()> {
+ let world = &input.resolve.worlds[input.world];
+ let async_imports =
+ filter_function_names(&input.resolve, &world.imports, |f| f.kind.is_async());
+ let sync_exports =
+ filter_function_names(&input.resolve, &world.exports, |f| !f.kind.is_async());
+
+ if !sync_exports.is_empty() && !async_imports.is_empty() {
+ let format_list = |names: &[String]| {
+ names
+ .iter()
+ .map(|n| format!(" - {n}\n"))
+ .collect::<String>()
+ };
+
+ return Err(Error::new(
+ Span::call_site(),
+ format!(
+ "World `{world}` mixes synchronous exports with asynchronous imports, which is not allowed.\n\
+ \n\
+ synchronous exports:\n{sync_exports}\n\
+ asynchronous imports:\n{async_imports}\n\
+ help: This error will resolve if either all imports are non-async or all exports \
+ are async. For more details, see the async bindgen example:\n\
+ https://docs.wasmtime.dev/api/wasmtime/component/bindgen_examples/_7_async/index.html",
+ world = world.name,
+ sync_exports = format_list(&sync_exports),
+ async_imports = format_list(&async_imports),
+ ),
+ ));
+ }
+
+ Ok(())
+}
+
+/// Get a list of world and interface-level function names that match some predicate
+fn filter_function_names(
+ resolve: &Resolve,
+ items: &IndexMap<WorldKey, WorldItem>,
+ pred: impl Fn(&Function) -> bool,
+) -> Vec<String> {
+ let mut names = vec![];
+ for (key, item) in items {
+ match item {
+ WorldItem::Function(f) if pred(f) => names.push(f.name.clone()),
+ WorldItem::Interface { id, .. } => {
+ let iface = resolve.name_world_key(key);
+ names.extend(
+ resolve.interfaces[*id]
+ .functions
+ .values()
+ .filter(|f| pred(f))
+ .map(|f| format!("{iface}.{}", f.name)),
+ );
+ }
+ _ => {}
+ }
+ }
+ names
+}
+
impl Parse for Config {
fn parse(input: ParseStream<'_>) -> Result<Self> {
let call_site = Span::call_site();
diff --git a/crates/wasmtime/src/runtime/component/bindgen_examples/_7_async.rs b/crates/wasmtime/src/runtime/component/bindgen_examples/_7_async.rs
index 16b83995b1..bdec4a6fbf 100644
--- a/crates/wasmtime/src/runtime/component/bindgen_examples/_7_async.rs
+++ b/crates/wasmtime/src/runtime/component/bindgen_examples/_7_async.rs
@@ -1,40 +1,51 @@
bindgen!({
inline: r#"
- package example:imported-resources;
-
- interface logging {
- enum level {
- debug,
- info,
- warn,
- error,
- }
-
- resource logger {
- constructor(max-level: level);
-
- get-max-level: func() -> level;
- set-max-level: func(level: level);
-
- log: func(level: level, msg: string);
- }
- }
-
- world import-some-resources {
- import logging;
- }
- "#,
+package example:resource-async;
+
+interface logging {
+ enum level {
+ debug,
+ info,
+ warn,
+ error,
+ }
+
+ resource logger {
+ constructor(max-level: level);
+ get-max-level: func() -> level;
+ set-max-level: func(level: level);
+ /// May block if the host's log buffer is full (i.e. backpressure).
+ log: async func(level: level, msg: string);
+ }
+}
- // NEW: Make all imports/exports `async` by default, and additionally
- // interactions with `ResourceTable` can possibly trap so enable the ability
- // to return traps from generated functions with `trappable`.
- imports: { default: async | trappable },
- exports: { default: async },
+world app {
+ import logging;
+ /// Because `logging.logger.log` is async, `run` must also be async; otherwise,
+ /// a trap will occur at runtime if `run` calls `log` and it blocks.
+ export run: async func();
+}
+"#,
+
+ imports: {
+
+ // This is the notation that's used to flag individual methods:
+ //
+ // "example:resource-async/logging.[constructor]logger": trappable,
+ // "example:resource-async/logging.[method]logger.get-max-level": trappable,
+ // "example:resource-async/logging.[method]logger.set-max-level": trappable,
+ // "example:resource-async/logging.[method]logger.log": trappable,
+ //
+ // Note that if one resource method specifies a flag, the remaining resource methods
+ // are no longer covered by e.g. `default: trappable`, and must be flagged
+ // individually.
+ default: trappable,
+ },
with: {
- // Specify that our host resource is going to point to the `MyLogger`
+ // Specify that our host resource is going to point to the `MyLogger`
// which is defined just below this macro.
- "example:imported-resources/logging.logger": MyLogger,
+ "example:resource-async/logging.logger": MyLogger,
},
});
@@ -43,5 +54,5 @@ bindgen!({
/// In this case this is relatively simple but there's no restrictions on what
/// this type can hold other than that it must be `'static + Send`.
pub struct MyLogger {
- pub max_level: example::imported_resources::logging::Level,
+ pub max_level: example::resource_async::logging::Level,
}
diff --git a/crates/wasmtime/src/runtime/component/bindgen_examples/mod.rs b/crates/wasmtime/src/runtime/component/bindgen_examples/mod.rs
index 6bbba5b291..daccdb2f89 100644
--- a/crates/wasmtime/src/runtime/component/bindgen_examples/mod.rs
+++ b/crates/wasmtime/src/runtime/component/bindgen_examples/mod.rs
@@ -519,67 +519,119 @@ pub mod _6_exported_resources;
/// Notable differences from [`_4_imported_resources`] are:
/// * async functions are used
/// * enabled async in bindgen! macro
+/// * flags configured for individual resource functions
+/// * `*_async` entry points are required, such as `instantiate_async`,
+/// awaiting `call_*` functions, and [`ResourceAny::resource_drop_async`]
///
-/// See [wasi_async_example](https://github.com/bytecodealliance/wasmtime/blob/main/examples/wasip1-async/main.rs) for async function calls on a host.
+/// See [wasi_async_example](https://github.com/bytecodealliance/wasmtime/blob/main/examples/wasip2-async/main.rs) for async function calls on a host.
+///
+/// [`ResourceAny::resource_drop_async`]: crate::component::ResourceAny::resource_drop_async
///
/// ```rust
-/// use wasmtime::Result;
-/// use wasmtime::component::{bindgen, ResourceTable, Resource};
-/// use example::imported_resources::logging::{Level, Host, HostLogger};
+/// use wasmtime::{
+/// Config, Engine, Result, Store,
+/// component::{bindgen, Component, HasSelf, Linker, ResourceTable},
+/// };
///
#[doc = include_str!("./_7_async.rs")]
///
+/// use self::example::resource_async::logging::{self as bindings, Level};
+///
/// #[derive(Default)]
-/// struct MyState {
+/// struct State {
/// // Manages the mapping of `MyLogger` structures to `Resource<MyLogger>`.
/// table: ResourceTable,
/// }
///
-/// // There are no free-functions on `interface logging`, so this is an empty
-/// // impl.
-/// impl Host for MyState {}
-///
/// // This separate `HostLogger` trait serves to act as a namespace for just
/// // the `logger`-related resource methods.
-/// impl HostLogger for MyState {
-/// // A `constructor` in WIT maps to a `new` function in Rust.
-/// async fn new(&mut self, max_level: Level) -> Result<Resource<MyLogger>> {
-/// let id = self.table.push(MyLogger { max_level })?;
-/// Ok(id)
+/// impl bindings::HostLogger for State {
+/// fn drop(
+/// &mut self,
+/// rep: wasmtime::component::Resource<bindings::Logger>,
+/// ) -> wasmtime::Result<()> {
+/// self.table.delete(rep)?;
+/// // ... custom destruction logic here if necessary, otherwise
+/// // a `Drop for MyLogger` would also work.
+/// Ok(())
/// }
///
-/// async fn get_max_level(&mut self, logger: Resource<MyLogger>) -> Result<Level> {
-/// debug_assert!(!logger.owned());
-/// let logger = self.table.get(&logger)?;
+/// fn get_max_level(
+/// &mut self,
+/// self_: wasmtime::component::Resource<MyLogger>,
+/// ) -> wasmtime::Result<bindings::Level> {
+/// let logger = self.table.get(&self_)?;
/// Ok(logger.max_level)
/// }
///
-/// async fn set_max_level(&mut self, logger: Resource<MyLogger>, level: Level) -> Result<()> {
-/// debug_assert!(!logger.owned());
-/// let logger = self.table.get_mut(&logger)?;
-/// logger.max_level = level;
-/// Ok(())
+/// // A `constructor` in WIT maps to a `new` function in Rust.
+/// fn new(
+/// &mut self,
+/// max_level: bindings::Level,
+/// ) -> wasmtime::Result<wasmtime::component::Resource<bindings::Logger>> {
+/// let id = self.table.push(MyLogger { max_level })?;
+/// Ok(id)
/// }
///
-/// async fn log(&mut self, logger: Resource<MyLogger>, level: Level, msg: String) -> Result<()> {
-/// debug_assert!(!logger.owned());
-/// let logger = self.table.get_mut(&logger)?;
-/// if (level as u32) <= (logger.max_level as u32) {
-/// println!("{msg}");
-/// }
+/// fn set_max_level(
+/// &mut self,
+/// self_: wasmtime::component::Resource<MyLogger>,
+/// level: bindings::Level,
+/// ) -> wasmtime::Result<()> {
+/// let logger = self.table.get_mut(&self_)?;
+/// logger.max_level = level;
/// Ok(())
/// }
+/// }
///
-/// async fn drop(&mut self, logger: Resource<MyLogger>) -> Result<()> {
-/// debug_assert!(logger.owned());
-/// let _logger: MyLogger = self.table.delete(logger)?;
-/// // ... custom destruction logic here if necessary, otherwise
-/// // a `Drop for MyLogger` would also work.
-/// Ok(())
+/// impl<T> bindings::HostLoggerWithStore<T> for HasSelf<State> {
+/// async fn log(
+/// accessor: &wasmtime::component::Accessor<T, Self>,
+/// self_: wasmtime::component::Resource<MyLogger>,
+/// level: Level,
+/// msg: String,
+/// ) -> wasmtime::Result<()> {
+/// // Do something that blocks
+/// tokio::time::sleep(std::time::Duration::from_secs(5)).await;
+///
+/// accessor.with(|mut access| {
+/// let state = access.get();
+/// let logger = state.table.get(&self_)?;
+/// if (level as u32) <= (logger.max_level as u32) {
+/// println!("{msg}");
+/// }
+/// Ok(())
+/// })
/// }
/// }
///
-/// # fn main() {}
+/// // There are no free-functions on `interface logging`, so this is an empty
+/// // impl that satisfies the trait bounds required by the linker.
+/// impl bindings::Host for State {}
+///
+/// #[tokio::main]
+/// async fn main() -> Result<()> {
+/// # if true { return Ok(()) }
+/// let mut config = Config::new();
+/// config.wasm_component_model_async(true);
+///
+/// let engine = Engine::new(&config)?;
+/// let component = Component::from_file(&engine, "/path/to/component")?;
+/// let mut store = Store::new(&engine, State::default());
+///
+/// let mut linker = Linker::<State>::new(&engine);
+/// bindings::add_to_linker::<_, HasSelf<State>>(&mut linker, |state| state)?;
+///
+/// // If you try to use the `App::instantiate` method, you'll get a runtime error that
+/// // looks something like:
+/// // "Error: store configuration requires that `*_async` functions are used instead"
+/// let bindings = App::instantiate_async(&mut store, &component, &linker).await?;
+/// let bindings = crate::App::instantiate_async(&mut store, &component, &linker).await?;
+/// store
+/// .run_concurrent(async |accessor| bindings.call_run(&accessor).await)
+/// .await??;
+/// Ok(())
+/// }
/// ```
pub mod _7_async;
diff --git a/crates/wasmtime/src/runtime/component/mod.rs b/crates/wasmtime/src/runtime/component/mod.rs
index 3834eb057d..96cfbc1309 100644
--- a/crates/wasmtime/src/runtime/component/mod.rs
+++ b/crates/wasmtime/src/runtime/component/mod.rs
@@ -272,11 +272,28 @@ pub(crate) use self::store::ComponentStoreData;
/// // functionality per-function or by default for all imports. Note that
/// // exports are also supported via the `exports` key below.
/// //
-/// // Functions in this list are specified as their interface first then
-/// // the raw wasm name of the function. Interface versions can be
-/// // optionally omitted and prefixes are also supported to configure
-/// // entire interfaces at once for example. Only the first matching item
-/// // in this list is used to configure a function.
+/// // Each key names either one function or a group of functions:
+/// //
+/// // * `"my-func"` - a function imported directly by the world.
+/// // * `"wasi:io/poll.poll"` - the `poll` function in the `wasi:io/poll`
+/// // interface. A version is optional: `"wasi:io/[email protected]"`.
+/// // * `"wasi:io/poll"` - every function in the `wasi:io/poll` interface.
+/// // * `"wasi:io"` or `"wasi"` - every function in a package or namespace.
+/// //
+/// // Resource functions are named by their component-model name, written
+/// // after the interface:
+/// //
+/// // * `"my:local/api.[constructor]my-resource"`
+/// // * `"my:local/api.[method]my-resource.my-method"`
+/// // * `"my:local/api.[static]my-resource.my-static-func"`
+/// // * `"my:local/api.[drop]my-resource"`
+/// //
+/// // A resource name on its own (`"my:local/api.my-resource"`) isn't a valid
+/// // key. List each resource function by itself, or use the interface key
+/// // to cover all of them.
+/// //
+/// // When more than one key matches a function, the most specific one is
+/// // used and the rest are ignored for that function.
/// //
/// // Configuration for a function is a set of flags which can be added
/// // per-function. Each flag's meaning is documented below and the final
@@ -354,6 +371,18 @@ pub(crate) use self::store::ComponentStoreData;
/// // for example and instead return `Result<WitOk, RustErrorType>`.
/// "my:local/api.fallible": trappable,
///
+/// // Resource methods, constructors, and static functions are
+/// // configured with their `[method]`, `[constructor]`, `[drop]`, or `[static]`
+/// // name as described above.
+/// //
+/// // Note that if one resource method specifies a flag, the remaining resource methods
+/// // are no longer covered by e.g. `default: trappable`, and must be flagged
+/// // individually.
+/// "my:local/api.[method]my-resource.my-method": async | trappable,
+/// "my:local/api.[static]my-resource.my-static-func": trappable,
+/// "my:local/api.[constructor]my-resource": trappable,
+/// "my:local/api.[drop]my-resource": trappable,
+///
/// // The `exact` flag ensures that the filter, here "f", only matches
/// // functions exactly. For example "f" here would only refer to
/// // `import f: func()` in a world. Without this flag then "f"