A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
component: improve async-mismatch diagnostics and stub async imports (#13821)
Malformed C7e8021c8330a
diff --git a/crates/wasmtime/src/runtime/component/func/host.rs b/crates/wasmtime/src/runtime/component/func/host.rsindex 199ad5938d..b1d8a931f8 100644--- a/crates/wasmtime/src/runtime/component/func/host.rs+++ b/crates/wasmtime/src/runtime/component/func/host.rs@@ -596,6 +596,40 @@ where}}+/// Checks that a host function's `ASYNC`-ness (as encoded by which of+/// `func_new`/`func_new_async`/`func_new_concurrent` — or their `_wrap`+/// counterparts — constructed it) matches whether the component's WIT type+/// for this import is declared `async func`.+///+/// This isn't a case of one or the other being "correct": `func_new_async`/+/// `func_wrap_async` intentionally implement a *sync*-WIT-typed function via+/// blocking/async host code (see their docs), so they can never satisfy an+/// `async func` import — only `func_new_concurrent`/`func_wrap_concurrent`+/// can. The error message names which specific mismatch occurred and points+/// at the API that would work, since "type mismatch with async" alone gives+/// no indication of *why* or what to use instead.+fn typecheck_async(host_async: bool, wit_async: bool) -> Result<()> {+ if host_async == wit_async {+ return Ok(());+ }+ if wit_async {+ bail!(+ "type mismatch with async: this import is declared `async func` in WIT, but was \+ satisfied with a sync-style host function (`func_new`/`func_wrap`, or \+ `func_new_async`/`func_wrap_async` — despite the name, these implement a \+ *sync*-WIT-typed function via blocking host code, not an `async func` import); \+ use `func_new_concurrent`/`func_wrap_concurrent` instead"+ );+ } else {+ bail!(+ "type mismatch with async: this import's WIT type is a plain (non-`async`) \+ function, but was satisfied with `func_new_concurrent`/`func_wrap_concurrent`, \+ which is only for `async func`-typed imports; use `func_new`/`func_wrap` (or \+ `func_new_async`/`func_wrap_async` for blocking host code) instead"+ );+ }+}+/// Implementation of a "static" host function where the parameters and results/// of a function are known at compile time.#[repr(transparent)]@@ -624,9 +658,7 @@ wherefn typecheck(ty: TypeFuncIndex, types: &InstanceType<'_>) -> Result<()> {let ty = &types.types[ty];- if ASYNC != ty.async_ {- bail!("type mismatch with async");- }+ typecheck_async(ASYNC, ty.async_)?;P::typecheck(&InterfaceType::Tuple(ty.params), types).context("type mismatch with parameters")?;R::typecheck(&InterfaceType::Tuple(ty.results), types)@@ -707,11 +739,7 @@ where/// checks. However, we _do_ verify async-ness here.fn typecheck(ty: TypeFuncIndex, types: &InstanceType<'_>) -> Result<()> {let ty = &types.types[ty];- if ASYNC != ty.async_ {- bail!("type mismatch with async");- }-- Ok(())+ typecheck_async(ASYNC, ty.async_)}fn run(diff --git a/crates/wasmtime/src/runtime/component/linker.rs b/crates/wasmtime/src/runtime/component/linker.rsindex 23050b21a7..b468321b29 100644--- a/crates/wasmtime/src/runtime/component/linker.rs+++ b/crates/wasmtime/src/runtime/component/linker.rs@@ -365,7 +365,7 @@ impl<T: 'static> Linker<T> {}match item_def {- TypeDef::ComponentFunc(_) => {+ TypeDef::ComponentFunc(_func_idx) => {let fully_qualified_name = match parent_instance {Some(parent) => {let mut s = TryString::new();@@ -380,6 +380,30 @@ impl<T: 'static> Linker<T> {s}};++ // An `async func`-typed import can never be satisfied by+ // `func_new` (only a sync-typed import can) — see+ // `typecheck_async`'s doc comment. Stub it with+ // `func_new_concurrent` instead so unsatisfied async+ // imports can be stubbed-as-traps too, not just sync+ // ones; if concurrency support isn't enabled there's no+ // way to stub it here, so fall through to `func_new` and+ // let instantiation fail with that same explanatory+ // error.+ #[cfg(feature = "component-model-async")]+ if types[*_func_idx].async_ && linker.engine.tunables().concurrency_support {+ linker.func_new_concurrent(&item_name, move |_, _, _, _| {+ let fully_qualified_name = fully_qualified_name.try_clone();+ Box::pin(async move {+ let fully_qualified_name = fully_qualified_name?;+ bail!(+ "unknown import: `{fully_qualified_name}` has not been defined"+ )+ })+ })?;+ return Ok(());+ }+linker.func_new(&item_name, move |_, _, _, _| {bail!("unknown import: `{fully_qualified_name}` has not been defined")})?;diff --git a/tests/all/component_model/linker.rs b/tests/all/component_model/linker.rsindex 6c770c369a..42e8c7b44e 100644--- a/tests/all/component_model/linker.rs+++ b/tests/all/component_model/linker.rs@@ -1,7 +1,7 @@use wasmtime::Result;use wasmtime::component::types::ComponentItem;use wasmtime::component::{Component, Linker, ResourceType};-use wasmtime::{Engine, Store};+use wasmtime::{Config, Engine, Store};#[test]fn old_import_importing_new_item() -> Result<()> {@@ -167,6 +167,35 @@ fn linker_defines_unknown_imports_as_traps() -> Result<()> {Ok(())}+#[tokio::test]+async fn linker_defines_unknown_async_imports_as_traps() -> Result<()> {+ // `define_unknown_imports_as_traps` used to always stub with `func_new`,+ // which can never satisfy an `async func`-typed import - so a component+ // with an unsatisfied async import couldn't be stubbed (and thus+ // couldn't be instantiated) at all, even though nothing in the component+ // ever calls it. With concurrency support enabled, it should now stub+ // async imports with `func_new_concurrent` instead.+ let mut config = Config::new();+ config.wasm_component_model_async(true);+ let engine = Engine::new(&config)?;+ let mut linker = Linker::<()>::new(&engine);++ let component = Component::new(+ &engine,+ r#"(component+ (import "foo" (func async))+ (import "bar" (instance (export "baz" (func async))))+ (import "qux" (type (sub resource)))+ )"#,+ )?;+ linker.define_unknown_imports_as_traps(&component)?;++ let mut store = Store::new(&engine, ());+ let _ = linker.instantiate_async(&mut store, &component).await?;++ Ok(())+}+#[test]fn linker_fails_to_define_unknown_core_module_imports_as_traps() -> Result<()> {let engine = Engine::default();diff --git a/tests/all/component_model/missing_async.rs b/tests/all/component_model/missing_async.rsindex ec4fdc935a..b237e3756f 100644--- a/tests/all/component_model/missing_async.rs+++ b/tests/all/component_model/missing_async.rs@@ -156,6 +156,71 @@ async fn require_async_after_linker_with_func_new_concurrent() -> Result<()> {Ok(())}+#[tokio::test]+async fn func_new_async_cannot_satisfy_async_import() -> Result<()> {+ // `func_new_async` (like `func_wrap_async`) intentionally implements a+ // *sync*-WIT-typed function via blocking host code - it can never+ // satisfy an `async func` import, only `func_new_concurrent` can. The+ // error message should say so specifically, not just "type mismatch+ // with async" with no indication of what to do about it.+ let mut config = Config::new();+ config.wasm_component_model_async(true);+ let engine = Engine::new(&config)?;+ let mut store = Store::new(&engine, ());+ let mut linker = Linker::new(store.engine());+ linker+ .root()+ .func_new_async("hi", |_, _, _, _| Box::new(async { Ok(()) }))?;+ let component = Component::new(+ store.engine(),+ r#"+ (component+ (import "hi" (func async))+ (core func (canon lower (func 0) async))+ )+ "#,+ )?;+ let err = linker+ .instantiate_async(&mut store, &component)+ .await+ .unwrap_err();+ let msg = format!("{err:#}");+ assert!(msg.contains("declared `async func` in WIT"), "{msg}");+ assert!(msg.contains("func_new_concurrent"), "{msg}");+ Ok(())+}++#[tokio::test]+async fn func_new_concurrent_cannot_satisfy_sync_import() -> Result<()> {+ // The reverse mismatch: `func_new_concurrent` is only for `async+ // func`-typed imports, and shouldn't silently satisfy a plain one either.+ let mut config = Config::new();+ config.wasm_component_model_async(true);+ let engine = Engine::new(&config)?;+ let mut store = Store::new(&engine, ());+ let mut linker = Linker::new(store.engine());+ linker+ .root()+ .func_new_concurrent("hi", |_, _, _, _| Box::pin(async { Ok(()) }))?;+ let component = Component::new(+ store.engine(),+ r#"+ (component+ (import "hi" (func))+ (core func (canon lower (func 0)))+ )+ "#,+ )?;+ let err = linker+ .instantiate_async(&mut store, &component)+ .await+ .unwrap_err();+ let msg = format!("{err:#}");+ assert!(msg.contains("plain (non-`async`) function"), "{msg}");+ assert!(msg.contains("func_new"), "{msg}");+ Ok(())+}+#[tokio::test]async fn async_disallows_resource_any_drop() -> Result<()> {let mut store = async_store();