A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
component: add `ResourceAny::resource_drop_concurrent` (#14362)
B. Naut7c55e310786c
diff --git a/crates/wasmtime/src/runtime/component/concurrent.rs b/crates/wasmtime/src/runtime/component/concurrent.rsindex 0df6cead55..66fe1be36d 100644--- a/crates/wasmtime/src/runtime/component/concurrent.rs+++ b/crates/wasmtime/src/runtime/component/concurrent.rs@@ -2489,7 +2489,7 @@ impl StoreOpaque {})}- fn queue_task(+ pub(crate) fn queue_task(&mut self,task: impl FnOnce(&mut dyn VMStore) -> Result<()> + Send + 'static,) -> Result<()> {diff --git a/crates/wasmtime/src/runtime/component/resources/any.rs b/crates/wasmtime/src/runtime/component/resources/any.rsindex 8dda3dc2d4..3497b76984 100644--- a/crates/wasmtime/src/runtime/component/resources/any.rs+++ b/crates/wasmtime/src/runtime/component/resources/any.rs@@ -151,11 +151,20 @@ impl ResourceAny {/// Destroy this resource and release any state associated with it.///- /// This is required to be called (or the async version) for all instances- /// of [`ResourceAny`] to ensure that state associated with this resource is- /// properly cleaned up. For owned resources this may execute the- /// guest-defined destructor if applicable (or the host-defined destructor- /// if one was specified).+ /// This is required to be called for all instances of [`ResourceAny`] to+ /// ensure that state associated with this resource is properly cleaned up.+ /// For owned resources this may execute the guest-defined destructor if+ /// applicable (or the host-defined destructor if one was specified).+ ///+ /// Exactly one of the following must be called for each [`ResourceAny`],+ /// depending on how the store is being driven:+ ///+ /// * [`ResourceAny::resource_drop`] for synchronous stores.+ /// * `ResourceAny::resource_drop_async` for [async](crate#async) stores+ /// when a `StoreContextMut` is available.+ /// * `ResourceAny::resource_drop_concurrent` when only an `Accessor` is+ /// available, such as inside `Store::run_concurrent` or an+ /// `AccessorTask`.////// # Errors///@@ -184,6 +193,42 @@ impl ResourceAny {.await?}+ /// Same as [`ResourceAny::resource_drop`] except for use with an+ /// [`Accessor`](crate::component::Accessor) while a store is executing+ /// [`Store::run_concurrent`](crate::Store::run_concurrent).+ ///+ /// The resource drop is queued for execution on the store's worker fiber.+ /// This method must be awaited while the store's concurrent event loop is+ /// running so the queued drop can make progress.+ ///+ /// Once this future has been polled and the drop has been queued, dropping+ /// the future does not cancel the resource drop.+ ///+ /// # Errors+ ///+ /// This function will return an [`OutOfMemory`][crate::OutOfMemory] error when+ /// memory allocation fails. See the `OutOfMemory` type's documentation for+ /// details on Wasmtime's out-of-memory handling.+ #[cfg(feature = "component-model-async")]+ pub async fn resource_drop_concurrent(+ self,+ accessor: impl crate::component::AsAccessor,+ ) -> Result<()> {+ let receiver = accessor.as_accessor().with(|mut store| -> Result<_> {+ let mut store = store.as_context_mut();+ let (sender, receiver) = futures::channel::oneshot::channel();+ let token = crate::store::StoreToken::new(store.as_context_mut());+ store.0.queue_task(move |store| {+ _ = sender.send(self.resource_drop_impl(&mut token.as_context_mut(store)));+ Ok(())+ })?;+ Ok(receiver)+ })?;+ receiver+ .await+ .map_err(|_| format_err!("resource drop task canceled"))?+ }+fn resource_drop_impl<T: 'static>(self, store: &mut StoreContextMut<'_, T>) -> Result<()> {// Attempt to remove `self.idx` from the host table in `store`.//diff --git a/tests/all/component_model.rs b/tests/all/component_model.rsindex 43b6a9b194..ac394a2b76 100644--- a/tests/all/component_model.rs+++ b/tests/all/component_model.rs@@ -91,9 +91,17 @@ impl ApiStyle {) -> Result<()> {match self {ApiStyle::Sync => resource.resource_drop(store),- ApiStyle::Async | ApiStyle::AsyncNotConcurrent | ApiStyle::Concurrent => {+ ApiStyle::Async | ApiStyle::AsyncNotConcurrent => {resource.resource_drop_async(store).await}+ ApiStyle::Concurrent => {+ store+ .run_concurrent(async |accessor| {+ resource.resource_drop_concurrent(accessor).await+ })+ .await??;+ Ok(())+ }}}}diff --git a/tests/all/component_model/func.rs b/tests/all/component_model/func.rsindex 16bde83b10..3d86d4ef1f 100644--- a/tests/all/component_model/func.rs+++ b/tests/all/component_model/func.rs@@ -3209,8 +3209,9 @@ async fn thread_index_via_resource_drop_concurrent() -> Result<()> {thread_index_via_resource_drop(ApiStyle::Concurrent).await}-async fn thread_index_via_resource_drop(style: ApiStyle) -> Result<()> {- let component = r#"+/// A component exporting a resource whose destructor traps unless it runs on a+/// non-zero `thread.index`, i.e. within a guest thread context.+const THREAD_INDEX_VIA_RESOURCE_DROP_COMPONENT: &str = r#"(component(core module $m(import "" "thread.index" (func $thread-index (result i32)))@@ -3247,8 +3248,10 @@ async fn thread_index_via_resource_drop(style: ApiStyle) -> Result<()> {(export "i" (instance $c)))"#;++async fn thread_index_via_resource_drop(style: ApiStyle) -> Result<()> {let engine = Engine::new(&style.config())?;- let component = Component::new(&engine, component)?;+ let component = Component::new(&engine, THREAD_INDEX_VIA_RESOURCE_DROP_COMPONENT)?;let mut store = Store::new(&engine, ());let linker = Linker::new(&engine);let instance = style.instantiate(&mut store, &linker, &component).await?;@@ -3262,6 +3265,33 @@ async fn thread_index_via_resource_drop(style: ApiStyle) -> Result<()> {Ok(())}+/// Test that a guest-exported `ResourceAny` can be dropped with+/// `resource_drop_concurrent` inside the same `Store::run_concurrent` call+/// that produced it, i.e. while the store's event loop is already running.+/// This is the scenario from issue #14291.+#[tokio::test]+async fn resource_drop_concurrent_in_run_concurrent() -> Result<()> {+ let style = ApiStyle::Concurrent;+ let engine = Engine::new(&style.config())?;+ let component = Component::new(&engine, THREAD_INDEX_VIA_RESOURCE_DROP_COMPONENT)?;+ let mut store = Store::new(&engine, ());+ let linker = Linker::new(&engine);+ let instance = style.instantiate(&mut store, &linker, &component).await?;+ let instance_index = instance.get_export_index(&mut store, None, "i").unwrap();+ let func_index = instance+ .get_export_index(&mut store, Some(&instance_index), "new")+ .unwrap();+ let run = instance.get_typed_func::<(), (ResourceAny,)>(&mut store, &func_index)?;+ store+ .run_concurrent(async |accessor| {+ let (resource,) = run.call_concurrent(accessor, ()).await?;+ resource.resource_drop_concurrent(accessor).await+ })+ .await??;+ store.assert_concurrent_state_empty();+ Ok(())+}+#[tokio::test]async fn thread_index_via_guest_call_sync() -> Result<()> {thread_index_via_guest_call(ApiStyle::Sync).await