A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Effectively replace AccessorTask with AsyncFnOnce in Accessor::spawn functions (#14376)
SilverMira37ebb15b9729
diff --git a/crates/misc/component-async-tests/tests/scenario/round_trip.rs b/crates/misc/component-async-tests/tests/scenario/round_trip.rsindex f602cdfdb8..d6975a7c0b 100644--- a/crates/misc/component-async-tests/tests/scenario/round_trip.rs+++ b/crates/misc/component-async-tests/tests/scenario/round_trip.rs@@ -8,9 +8,7 @@ use futures::{};use std::sync::Arc;use std::sync::atomic::{AtomicU32, Ordering::Relaxed};-use wasmtime::component::{- Accessor, AccessorTask, HasData, HasSelf, Instance, Linker, ResourceTable, Val,-};+use wasmtime::component::{Accessor, HasData, Instance, Linker, ResourceTable, Val};use wasmtime::{Engine, Result, Store, format_err};use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};@@ -397,51 +395,37 @@ pub async fn test_round_trip(if call_style == 1 || !cfg!(miri) {// And again using `Instance::spawn`:- struct Task {- instance: Instance,- inputs_and_outputs: Vec<(String, String)>,- tx: oneshot::Sender<()>,- }-- impl AccessorTask<Ctx, HasSelf<Ctx>> for Task {- async fn run(self, accessor: &Accessor<Ctx>) -> Result<()> {- let round_trip = accessor.with(|mut store| {- component_async_tests::round_trip::bindings::RoundTrip::new(- &mut store,- &self.instance,- )- })?;-- let mut futures = FuturesUnordered::new();- for (input, output) in &self.inputs_and_outputs {- let output = output.clone();- futures.push(- round_trip- .local_local_baz()- .call_foo(accessor, input.clone())- .map(move |v| v.map(move |v| (v, output)))- .boxed(),- );- }-- while let Some((actual, expected)) = futures.try_next().await? {- assert_eq!(expected, actual);- }-- _ = self.tx.send(());+ let (tx, rx) = oneshot::channel();+ let inputs_and_outputs = inputs_and_outputs+ .iter()+ .map(|(a, b)| (String::from(*a), String::from(*b)))+ .collect::<Vec<_>>();+ store.spawn(async move |accessor| {+ let round_trip = accessor.with(|mut store| {+ component_async_tests::round_trip::bindings::RoundTrip::new(+ &mut store, &instance,+ )+ })?;++ let mut futures = FuturesUnordered::new();+ for (input, output) in &inputs_and_outputs {+ let output = output.clone();+ futures.push(+ round_trip+ .local_local_baz()+ .call_foo(accessor, input.clone())+ .map(move |v| v.map(move |v| (v, output)))+ .boxed(),+ );+ }- Ok(())+ while let Some((actual, expected)) = futures.try_next().await? {+ assert_eq!(expected, actual);}- }- let (tx, rx) = oneshot::channel();- store.spawn(Task {- instance,- inputs_and_outputs: inputs_and_outputs- .iter()- .map(|(a, b)| (String::from(*a), String::from(*b)))- .collect::<Vec<_>>(),- tx,+ _ = tx.send(());++ Ok(())})?;store.run_concurrent(async |_| rx.await).await??;diff --git a/crates/wasi-tls/src/p3/host.rs b/crates/wasi-tls/src/p3/host.rsindex 66c084f415..3ca7092d92 100644--- a/crates/wasi-tls/src/p3/host.rs+++ b/crates/wasi-tls/src/p3/host.rs@@ -7,9 +7,7 @@ use std::pin::Pin;use std::task::{Context, Poll};use tokio::{io::AsyncWriteExt as _, sync::oneshot};use wasmtime::StoreContextMut;-use wasmtime::component::{- Access, Accessor, AccessorTask, FutureProducer, FutureReader, HasData, Resource, StreamReader,-};+use wasmtime::component::{Access, Accessor, FutureProducer, FutureReader, Resource, StreamReader};/// Host-side state stored for `wasi:tls/client` `connector` resources.pub struct Connector {@@ -90,7 +88,7 @@ impl<T> bindings::tls::client::HostConnectorWithStore<T> for WasiTls {)?;let ciphertext = AsyncReadProducer::new(ciphertext_reader, ciphertext_result_tx);- store.spawn(FnTask(async move || {+ store.spawn(async move |_| {let cleartext_result = match cleartext_result_rx.await? {Ok(mut inner) => inner.shutdown().await, // Drive the close_notify sequenceErr(e) => Err(e),@@ -101,7 +99,7 @@ impl<T> bindings::tls::client::HostConnectorWithStore<T> for WasiTls {.map_err(|e| Error::from(e));_ = send_result_tx.send(combined_result);Ok(())- }))?;+ })?;let result = ResultProducer::new(getter, send_result_rx);Ok((@@ -152,7 +150,7 @@ impl<T> bindings::tls::client::HostConnectorWithStore<T> for WasiTls {)?;let cleartext = AsyncReadProducer::new(connection, cleartext_result_tx);- store.spawn(FnTask(async move || {+ store.spawn(async move |_| {let ciphertext_result = match ciphertext_result_rx.await? {// Let the TLS implementation know the transport is closed.// Most likely, `shutdown` will be entirely synchronous and@@ -167,7 +165,7 @@ impl<T> bindings::tls::client::HostConnectorWithStore<T> for WasiTls {.map_err(|e| Error::from(e));_ = recv_result_tx.send(combined_result);Ok(())- }))?;+ })?;let result = ResultProducer::new(getter, recv_result_rx);Ok((@@ -224,21 +222,6 @@ impl<T> bindings::tls::client::HostConnectorWithStore<T> for WasiTls {}}-pub(crate) struct FnTask<Fn>(pub(crate) Fn);-impl<Fn, Fut, T, D> AccessorTask<T, D> for FnTask<Fn>-where- Fn: FnOnce() -> Fut + Send + 'static,- Fut: Future<Output = wasmtime::Result<()>> + Send + 'static,- D: HasData + ?Sized,-{- fn run(- self,- _accessor: &wasmtime::component::Accessor<T, D>,- ) -> impl Future<Output = wasmtime::Result<()>> + Send {- self.0()- }-}-pub(crate) struct ResultProducer<D> {result: oneshot::Receiver<Result<(), Error>>,getter: for<'a> fn(&'a mut D) -> WasiTlsCtxView<'a>,diff --git a/crates/wasmtime/src/runtime/component/concurrent.rs b/crates/wasmtime/src/runtime/component/concurrent.rsindex ea5851f970..db337adf06 100644--- a/crates/wasmtime/src/runtime/component/concurrent.rs+++ b/crates/wasmtime/src/runtime/component/concurrent.rs@@ -241,7 +241,7 @@ where/// Spawn a background task.////// See [`Accessor::spawn`] for details.- pub fn spawn(&mut self, task: impl AccessorTask<T, D>) -> Result<JoinHandle>+ pub fn spawn(&mut self, task: impl for<'fut> AccessorTask<'fut, T, D>) -> Result<JoinHandle>whereT: 'static,{@@ -517,7 +517,7 @@ where/// Panics if called within a closure provided to the [`Accessor::with`]/// function. This can only be called outside an active invocation of/// [`Accessor::with`].- pub fn spawn(&self, task: impl AccessorTask<T, D>) -> Result<JoinHandle>+ pub fn spawn(&self, task: impl for<'fut> AccessorTask<'fut, T, D>) -> Result<JoinHandle>whereT: 'static,{@@ -614,23 +614,47 @@ where}}-/// Represents a task which may be provided to `Accessor::spawn`,-/// `Accessor::forward`, or `StorecContextMut::spawn`.-// TODO: Replace this with `core::ops::AsyncFnOnce` when that becomes a viable-// option.+/// Represents an async closure which may be provided to `Accessor::spawn`,+/// `Accessor::forward`, or `StoreContextMut::spawn`.+// TODO: Replace this with `core::ops::AsyncFnOnce` when we are able to put `Send`+// bound on the unnamed `Future` directly.//// As of this writing, it's not possible to specify e.g. `Send` and `Sync`// bounds on the `Future` type returned by an `AsyncFnOnce`. Also, using `F:// Future<Output = Result<()>> + Send + Sync, FN: FnOnce(&Accessor<T>) -> F +-// Send + Sync + 'static` fails with a type mismatch error when we try to pass-// it an async closure (e.g. `async move |_| { ... }`). So this seems to be the-// best we can do for the time being.-pub trait AccessorTask<T, D = HasSelf<T>>: Send + 'static+// Send + Sync + 'static` fails with a type mismatch error as we cannot describe+// that `F` should have `&Accessor<T>`'s unnamed lifetime+//+// Instead, this trait is used as a workaround for this limitation, the bound on `Self`+// implementing `AsyncFnOnce()` is required for Rust to automatically infer that an async+// closure is to be provided wherever we are accepting `impl for<'fut> AccessorTask<'fut, T, D>`+// as argument. Otherwise, users will have to fully qualify the closure types before it+// is accepted as a valid value. This also means that it is not intended for a user+// to manually implement this trait for any arbitrary type, since they would first+// have to implement `AsyncFnOnce`, which is unstable.+//+// The blanket implementation for this trait will ensure that `Self` is an async closure+// that returns a `Future` that is `Send`, and lives as long as `&Accessor<T, D>`+pub trait AccessorTask<'fut, T, D = HasSelf<T>>:+ AsyncFnOnce(&Accessor<T, D>) -> Result<()> + Send + 'staticwhereD: HasData + ?Sized,{/// Run the task.- fn run(self, accessor: &Accessor<T, D>) -> impl Future<Output = Result<()>> + Send;+ fn run(self, accessor: &'fut Accessor<T, D>) -> impl Future<Output = Result<()>> + Send + 'fut;+}++impl<'fut, F, Fut, T, D> AccessorTask<'fut, T, D> for F+where+ T: 'static,+ F: AsyncFnOnce(&Accessor<T, D>) -> Result<()>,+ F: FnOnce(&'fut Accessor<T, D>) -> Fut + Send + 'static,+ Fut: Future<Output = Result<()>> + Send + 'fut,+ D: HasData,+{+ fn run(self, accessor: &'fut Accessor<T, D>) -> impl Future<Output = Result<()>> + Send + 'fut {+ (self)(accessor)+ }}/// Represents parameter and result metadata for the caller side of a@@ -1027,7 +1051,10 @@ impl<T> Store<T> {}/// Convenience wrapper for [`StoreContextMut::spawn`].- pub fn spawn(&mut self, task: impl AccessorTask<T, HasSelf<T>>) -> Result<JoinHandle>+ pub fn spawn(+ &mut self,+ task: impl for<'fut> AccessorTask<'fut, T, HasSelf<T>>,+ ) -> Result<JoinHandle>whereT: 'static,{@@ -1092,7 +1119,7 @@ impl<T> StoreContextMut<'_, T> {/// for this instance is run.////// The returned [`JoinHandle`] may be used to cancel the task.- pub fn spawn(mut self, task: impl AccessorTask<T>) -> Result<JoinHandle>+ pub fn spawn(mut self, task: impl for<'fut> AccessorTask<'fut, T>) -> Result<JoinHandle>whereT: 'static,{@@ -1105,7 +1132,7 @@ impl<T> StoreContextMut<'_, T> {fn spawn_with_accessor<D>(self,accessor: Accessor<T, D>,- task: impl AccessorTask<T, D>,+ task: impl for<'fut> AccessorTask<'fut, T, D>,) -> Result<JoinHandle>whereT: 'static,