A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
cm-async: Start to fill out `{Future,Stream}Any` (#12142)
Alex Crichtonf586be111d38
diff --git a/crates/misc/component-async-tests/tests/scenario/transmit.rs b/crates/misc/component-async-tests/tests/scenario/transmit.rsindex f4f5b109b2..16c6fb0a9f 100644--- a/crates/misc/component-async-tests/tests/scenario/transmit.rs+++ b/crates/misc/component-async-tests/tests/scenario/transmit.rs@@ -552,6 +552,7 @@ pub trait TransmitTest {) -> impl Future<Output = Result<Self::Result>> + Send + 'a;fn into_params(+ store: impl AsContextMut<Data = Ctx>,control: StreamReader<Control>,caller_stream: StreamReader<String>,caller_future1: FutureReader<String>,@@ -603,6 +604,7 @@ impl TransmitTest for StaticTransmitTest {}fn into_params(+ _store: impl AsContextMut<Data = Ctx>,control: StreamReader<Control>,caller_stream: StreamReader<String>,caller_future1: FutureReader<String>,@@ -663,21 +665,31 @@ impl TransmitTest for DynamicTransmitTest {}fn into_params(+ mut store: impl AsContextMut<Data = Ctx>,control: StreamReader<Control>,caller_stream: StreamReader<String>,caller_future1: FutureReader<String>,caller_future2: FutureReader<String>,) -> Self::Params {vec![- control.into_val(),- caller_stream.into_val(),- caller_future1.into_val(),- caller_future2.into_val(),+ control.try_into_stream_any(&mut store).unwrap().into(),+ caller_stream+ .try_into_stream_any(&mut store)+ .unwrap()+ .into(),+ caller_future1+ .try_into_future_any(&mut store)+ .unwrap()+ .into(),+ caller_future2+ .try_into_future_any(&mut store)+ .unwrap()+ .into(),]}fn from_result(- mut store: impl AsContextMut<Data = Ctx>,+ _store: impl AsContextMut<Data = Ctx>,result: Self::Result,) -> Result<(StreamReader<String>,@@ -687,9 +699,19 @@ impl TransmitTest for DynamicTransmitTest {let Val::Tuple(fields) = result else {unreachable!()};- let stream = StreamReader::from_val(store.as_context_mut(), &fields[0])?;- let future1 = FutureReader::from_val(store.as_context_mut(), &fields[1])?;- let future2 = FutureReader::from_val(store.as_context_mut(), &fields[2])?;+ let mut fields = fields.into_iter();+ let Val::Stream(stream) = fields.next().unwrap() else {+ unreachable!()+ };+ let Val::Future(future1) = fields.next().unwrap() else {+ unreachable!()+ };+ let Val::Future(future2) = fields.next().unwrap() else {+ unreachable!()+ };+ let stream = StreamReader::try_from_stream_any(stream).unwrap();+ let future1 = FutureReader::try_from_future_any(future1).unwrap();+ let future2 = FutureReader::try_from_future_any(future2).unwrap();Ok((stream, future1, future2))}}@@ -770,19 +792,20 @@ async fn test_transmit_with<Test: TransmitTest + 'static>(component: &str) -> Re.boxed(),);- futures.push(- Test::call(- accessor,- &test,- Test::into_params(- control_rx,- caller_stream_rx,- caller_future1_rx,- caller_future2_rx,- ),+ let params = accessor.with(|s| {+ Test::into_params(+ s,+ control_rx,+ caller_stream_rx,+ caller_future1_rx,+ caller_future2_rx,)- .map(|v| v.map(Event::Result))- .boxed(),+ });++ futures.push(+ Test::call(accessor, &test, params)+ .map(|v| v.map(Event::Result))+ .boxed(),);while let Some(event) = futures.try_next().await? {diff --git a/crates/wasmtime/src/runtime/component/concurrent.rs b/crates/wasmtime/src/runtime/component/concurrent.rsindex b028e12b41..dc0fe129a8 100644--- a/crates/wasmtime/src/runtime/component/concurrent.rs+++ b/crates/wasmtime/src/runtime/component/concurrent.rs@@ -90,17 +90,17 @@ use wasmtime_environ::component::{};pub use abort::JoinHandle;+pub use future_stream_any::{FutureAny, StreamAny};pub use futures_and_streams::{Destination, DirectDestination, DirectSource, ErrorContext, FutureConsumer, FutureProducer,FutureReader, GuardedFutureReader, GuardedStreamReader, ReadBuffer, Source, StreamConsumer,StreamProducer, StreamReader, StreamResult, VecBuffer, WriteBuffer,};-pub(crate) use futures_and_streams::{- ResourcePair, lower_error_context_to_index, lower_future_to_index, lower_stream_to_index,-};+pub(crate) use futures_and_streams::{ResourcePair, lower_error_context_to_index};mod abort;mod error_contexts;+mod future_stream_any;mod futures_and_streams;pub(crate) mod table;pub(crate) mod tls;diff --git a/crates/wasmtime/src/runtime/component/concurrent/future_stream_any.rs b/crates/wasmtime/src/runtime/component/concurrent/future_stream_any.rsnew file mode 100644index 0000000000..f29193bbe8--- /dev/null+++ b/crates/wasmtime/src/runtime/component/concurrent/future_stream_any.rs@@ -0,0 +1,453 @@+//! Implementation of [`FutureAny`] and [`StreamAny`].++use crate::AsContextMut;+use crate::component::concurrent::futures_and_streams::{self, TransmitOrigin};+use crate::component::concurrent::{TableId, TransmitHandle};+use crate::component::func::{LiftContext, LowerContext, bad_type_info, desc};+use crate::component::matching::InstanceType;+use crate::component::types::{self, FutureType, StreamType};+use crate::component::{+ ComponentInstanceId, ComponentType, FutureReader, Lift, Lower, StreamReader,+};+use crate::store::StoreOpaque;+use anyhow::{Context, Result, bail};+use std::any::TypeId;+use std::mem::MaybeUninit;+use wasmtime_environ::component::{+ CanonicalAbiInfo, InterfaceType, TypeFutureTableIndex, TypeStreamTableIndex,+};++/// Represents a type-erased component model `future`.+///+/// This type is similar to [`ResourceAny`](crate::component::ResourceAny)+/// where it's a static guarantee that it represents a component model+/// `future`, but it does not contain any information about the underlying type+/// that is associated with this future. This is intended to be used in+/// "dynamically typed" situations where embedders may not know ahead of time+/// the type of a `future` being used by component that is loaded.+///+/// # Closing futures+///+/// A [`FutureAny`] represents a resource that is owned by a [`Store`]. Proper+/// disposal of a future requires invoking the [`FutureAny::close`] method to+/// ensure that this handle does not leak. If [`FutureAny::close`] is not+/// called then memory will not be leaked once the owning [`Store`] is dropped,+/// but the resource handle will be leaked until the [`Store`] is dropped.+///+/// [`Store`]: crate::Store+#[derive(Debug, Clone, PartialEq)]+pub struct FutureAny {+ id: TableId<TransmitHandle>,+ ty: PayloadType<FutureType>,+}++impl FutureAny {+ fn lower_to_index<T>(&self, cx: &mut LowerContext<'_, T>, ty: InterfaceType) -> Result<u32> {+ // Note that unlike `FutureReader<T>` we need to perform an extra+ // typecheck to ensure that the dynamic type of this future matches+ // what the guest we're lowering into expects. This couldn't happen+ // before this point (see the `ComponentType::typecheck` implementation+ // for this type), so do it now.+ let future_ty = match ty {+ InterfaceType::Future(payload) => payload,+ _ => bad_type_info(),+ };+ let payload = cx.types[cx.types[future_ty].ty].payload.as_ref();+ self.ty.typecheck_guest(+ &cx.instance_type(),+ payload,+ FutureType::equivalent_payload_guest,+ )?;++ // Like `FutureReader<T>`, however, lowering "just" gets a u32.+ futures_and_streams::lower_future_to_index(self.id, cx, ty)+ }++ /// Attempts to convert this [`FutureAny`] to a [`FutureReader<T>`]+ /// with a statically known type.+ ///+ /// # Errors+ ///+ /// This function will return an error if `T` does not match the type of+ /// value on this future.+ pub fn try_into_future_reader<T>(self) -> Result<FutureReader<T>>+ where+ T: ComponentType + 'static,+ {+ self.ty+ .typecheck_host::<T>(FutureType::equivalent_payload_host::<T>)?;+ Ok(FutureReader::new_(self.id))+ }++ /// Attempts to convert `reader` to a [`FutureAny`], erasing its statically+ /// known type.+ ///+ /// # Errors+ ///+ /// This function will return an error if `reader` does not belong to+ /// `store`.+ pub fn try_from_future_reader<T>(+ mut store: impl AsContextMut,+ reader: FutureReader<T>,+ ) -> Result<Self>+ where+ T: ComponentType + 'static,+ {+ let store = store.as_context_mut();+ let ty = match store.0.transmit_origin(reader.id())? {+ TransmitOrigin::Host => PayloadType::new_host::<T>(),+ TransmitOrigin::GuestFuture(id, ty) => PayloadType::new_guest_future(store.0, id, ty),+ TransmitOrigin::GuestStream(..) => bail!("not a future"),+ };+ Ok(FutureAny {+ id: reader.id(),+ ty,+ })+ }++ fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {+ let id = futures_and_streams::lift_index_to_future(cx, ty, index)?;+ let InterfaceType::Future(ty) = ty else {+ unreachable!()+ };+ let ty = cx.types[ty].ty;+ Ok(FutureAny {+ id,+ // Note that this future might actually be a host-originating+ // future which means that this ascription of "the type is the+ // guest" may be slightly in accurate. The guest, however, has the+ // most accurate view of what type this future has so that should+ // be reasonable to ascribe as the type here regardless.+ ty: PayloadType::Guest(FutureType::from(ty, &cx.instance_type())),+ })+ }++ /// Close this `FutureAny`.+ ///+ /// This will close this future and cause any write that happens later to+ /// returned `DROPPED`.+ ///+ /// # Panics+ ///+ /// Panics if the `store` does not own this future. Usage of this future+ /// after calling `close` will also cause a panic.+ pub fn close(&mut self, mut store: impl AsContextMut) {+ futures_and_streams::future_close(store.as_context_mut().0, &mut self.id)+ }+}++unsafe impl ComponentType for FutureAny {+ const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;++ type Lower = <u32 as ComponentType>::Lower;++ fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {+ match ty {+ InterfaceType::Future(_) => Ok(()),+ other => bail!("expected `future`, found `{}`", desc(other)),+ }+ }+}++unsafe impl Lower for FutureAny {+ fn linear_lower_to_flat<T>(+ &self,+ cx: &mut LowerContext<'_, T>,+ ty: InterfaceType,+ dst: &mut MaybeUninit<Self::Lower>,+ ) -> Result<()> {+ self.lower_to_index(cx, ty)?+ .linear_lower_to_flat(cx, InterfaceType::U32, dst)+ }++ fn linear_lower_to_memory<T>(+ &self,+ cx: &mut LowerContext<'_, T>,+ ty: InterfaceType,+ offset: usize,+ ) -> Result<()> {+ self.lower_to_index(cx, ty)?+ .linear_lower_to_memory(cx, InterfaceType::U32, offset)+ }+}++unsafe impl Lift for FutureAny {+ fn linear_lift_from_flat(+ cx: &mut LiftContext<'_>,+ ty: InterfaceType,+ src: &Self::Lower,+ ) -> Result<Self> {+ let index = u32::linear_lift_from_flat(cx, InterfaceType::U32, src)?;+ Self::lift_from_index(cx, ty, index)+ }++ fn linear_lift_from_memory(+ cx: &mut LiftContext<'_>,+ ty: InterfaceType,+ bytes: &[u8],+ ) -> Result<Self> {+ let index = u32::linear_lift_from_memory(cx, InterfaceType::U32, bytes)?;+ Self::lift_from_index(cx, ty, index)+ }+}++/// Represents a type-erased component model `stream`.+///+/// This type is similar to [`ResourceAny`](crate::component::ResourceAny)+/// where it's a static guarantee that it represents a component model+/// `stream`, but it does not contain any information about the underlying type+/// that is associated with this stream. This is intended to be used in+/// "dynamically typed" situations where embedders may not know ahead of time+/// the type of a `stream` being used by component that is loaded.+///+/// # Closing streams+///+/// A [`StreamAny`] represents a resource that is owned by a [`Store`]. Proper+/// disposal of a stream requires invoking the [`StreamAny::close`] method to+/// ensure that this handle does not leak. If [`StreamAny::close`] is not+/// called then memory will not be leaked once the owning [`Store`] is dropped,+/// but the resource handle will be leaked until the [`Store`] is dropped.+///+/// [`Store`]: crate::Store+#[derive(Debug, Clone, PartialEq)]+pub struct StreamAny {+ id: TableId<TransmitHandle>,+ ty: PayloadType<StreamType>,+}++impl StreamAny {+ fn lower_to_index<T>(&self, cx: &mut LowerContext<'_, T>, ty: InterfaceType) -> Result<u32> {+ // See comments in `FutureAny::lower_to_index` for why this is+ // different from `StreamReader`'s implementation.+ let stream_ty = match ty {+ InterfaceType::Stream(payload) => payload,+ _ => bad_type_info(),+ };+ let payload = cx.types[cx.types[stream_ty].ty].payload.as_ref();+ self.ty.typecheck_guest(+ &cx.instance_type(),+ payload,+ StreamType::equivalent_payload_guest,+ )?;+ futures_and_streams::lower_stream_to_index(self.id, cx, ty)+ }++ /// Attempts to convert this [`StreamAny`] to a [`StreamReader<T>`]+ /// with a statically known type.+ ///+ /// # Errors+ ///+ /// This function will return an error if `T` does not match the type of+ /// value on this stream.+ pub fn try_into_stream_reader<T>(self) -> Result<StreamReader<T>>+ where+ T: ComponentType + 'static,+ {+ self.ty+ .typecheck_host::<T>(StreamType::equivalent_payload_host::<T>)?;+ Ok(StreamReader::new_(self.id))+ }++ /// Attempts to convert `reader` to a [`StreamAny`], erasing its statically+ /// known type.+ ///+ /// # Errors+ ///+ /// This function will return an error if `reader` does not belong to+ /// `store`.+ pub fn try_from_stream_reader<T>(+ mut store: impl AsContextMut,+ reader: StreamReader<T>,+ ) -> Result<Self>+ where+ T: ComponentType + 'static,+ {+ let store = store.as_context_mut();+ let ty = match store.0.transmit_origin(reader.id())? {+ TransmitOrigin::Host => PayloadType::new_host::<T>(),+ TransmitOrigin::GuestStream(id, ty) => PayloadType::new_guest_stream(store.0, id, ty),+ TransmitOrigin::GuestFuture(..) => bail!("not a stream"),+ };+ Ok(StreamAny {+ id: reader.id(),+ ty,+ })+ }++ fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {+ let id = futures_and_streams::lift_index_to_stream(cx, ty, index)?;+ let InterfaceType::Stream(ty) = ty else {+ unreachable!()+ };+ let ty = cx.types[ty].ty;+ Ok(StreamAny {+ id,+ // Note that this stream might actually be a host-originating, but+ // see the documentation in `FutureAny::lift_from_index` for why+ // this should be ok.+ ty: PayloadType::Guest(StreamType::from(ty, &cx.instance_type())),+ })+ }++ /// Close this `StreamAny`.+ ///+ /// This will close this stream and cause any write that happens later to+ /// returned `DROPPED`.+ ///+ /// # Panics+ ///+ /// Panics if the `store` does not own this stream. Usage of this stream+ /// after calling `close` will also cause a panic.+ pub fn close(&mut self, mut store: impl AsContextMut) {+ futures_and_streams::future_close(store.as_context_mut().0, &mut self.id)+ }+}++unsafe impl ComponentType for StreamAny {+ const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;++ type Lower = <u32 as ComponentType>::Lower;++ fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {+ match ty {+ InterfaceType::Stream(_) => Ok(()),+ other => bail!("expected `stream`, found `{}`", desc(other)),+ }+ }+}++unsafe impl Lower for StreamAny {+ fn linear_lower_to_flat<T>(+ &self,+ cx: &mut LowerContext<'_, T>,+ ty: InterfaceType,+ dst: &mut MaybeUninit<Self::Lower>,+ ) -> Result<()> {+ self.lower_to_index(cx, ty)?+ .linear_lower_to_flat(cx, InterfaceType::U32, dst)+ }++ fn linear_lower_to_memory<T>(+ &self,+ cx: &mut LowerContext<'_, T>,+ ty: InterfaceType,+ offset: usize,+ ) -> Result<()> {+ self.lower_to_index(cx, ty)?+ .linear_lower_to_memory(cx, InterfaceType::U32, offset)+ }+}++unsafe impl Lift for StreamAny {+ fn linear_lift_from_flat(+ cx: &mut LiftContext<'_>,+ ty: InterfaceType,+ src: &Self::Lower,+ ) -> Result<Self> {+ let index = u32::linear_lift_from_flat(cx, InterfaceType::U32, src)?;+ Self::lift_from_index(cx, ty, index)+ }++ fn linear_lift_from_memory(+ cx: &mut LiftContext<'_>,+ ty: InterfaceType,+ bytes: &[u8],+ ) -> Result<Self> {+ let index = u32::linear_lift_from_memory(cx, InterfaceType::U32, bytes)?;+ Self::lift_from_index(cx, ty, index)+ }+}++#[derive(Debug, Clone)]+enum PayloadType<T> {+ Guest(T),+ Host {+ id: TypeId,+ typecheck: fn(Option<&InterfaceType>, &InstanceType<'_>) -> Result<()>,+ },+}++impl<T: PartialEq> PartialEq for PayloadType<T> {+ fn eq(&self, other: &Self) -> bool {+ match (self, other) {+ (PayloadType::Guest(a), PayloadType::Guest(b)) => a == b,+ (PayloadType::Guest(_), _) => false,+ (PayloadType::Host { id: a_id, .. }, PayloadType::Host { id: b_id, .. }) => {+ a_id == b_id+ }+ (PayloadType::Host { .. }, _) => false,+ }+ }+}++impl PayloadType<FutureType> {+ fn new_guest_future(+ store: &StoreOpaque,+ id: ComponentInstanceId,+ ty: TypeFutureTableIndex,+ ) -> Self {+ let types = InstanceType::new(&store.component_instance(id));+ let ty = types.types[ty].ty;+ PayloadType::Guest(FutureType::from(ty, &types))+ }+}++impl PayloadType<StreamType> {+ fn new_guest_stream(+ store: &StoreOpaque,+ id: ComponentInstanceId,+ ty: TypeStreamTableIndex,+ ) -> Self {+ let types = InstanceType::new(&store.component_instance(id));+ let ty = types.types[ty].ty;+ PayloadType::Guest(StreamType::from(ty, &types))+ }+}++impl<T> PayloadType<T> {+ fn new_host<P>() -> Self+ where+ P: ComponentType + 'static,+ {+ PayloadType::Host {+ typecheck: types::typecheck_payload::<P>,+ id: TypeId::of::<P>(),+ }+ }++ fn typecheck_guest(+ &self,+ types: &InstanceType<'_>,+ payload: Option<&InterfaceType>,+ equivalent: fn(&T, &InstanceType<'_>, Option<&InterfaceType>) -> bool,+ ) -> Result<()> {+ match self {+ Self::Guest(ty) => {+ if equivalent(ty, types, payload) {+ Ok(())+ } else {+ bail!("future payload types differ")+ }+ }+ Self::Host { typecheck, .. } => {+ typecheck(payload, types).context("future payload types differ")+ }+ }+ }++ fn typecheck_host<P>(&self, equivalent: fn(&T) -> Result<()>) -> Result<()>+ where+ P: ComponentType + 'static,+ {+ match self {+ Self::Guest(ty) => equivalent(ty),+ Self::Host { id, .. } => {+ if *id == TypeId::of::<P>() {+ Ok(())+ } else {+ bail!("future payload types differ")+ }+ }+ }+ }+}diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rsindex ca0af10cd1..42290a8d2e 100644--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs@@ -3,8 +3,12 @@ use super::{Event, GlobalErrorContextRefCount, Waitable, WaitableCommon};use crate::component::concurrent::{ConcurrentState, WorkItem, tls};use crate::component::func::{self, LiftContext, LowerContext};use crate::component::matching::InstanceType;-use crate::component::values::{ErrorContextAny, FutureAny, StreamAny};-use crate::component::{AsAccessor, Instance, Lift, Lower, Val, WasmList};+use crate::component::types;+use crate::component::values::ErrorContextAny;+use crate::component::{+ AsAccessor, ComponentInstanceId, ComponentType, FutureAny, Instance, Lift, Lower, StreamAny,+ Val, WasmList,+};use crate::store::{StoreOpaque, StoreToken};use crate::vm::component::{ComponentInstance, HandleTable, TransmitLocalState};use crate::vm::{AlwaysMut, VMStore};@@ -1136,13 +1140,17 @@ impl<T> FutureReader<T> {)}- fn new_(id: TableId<TransmitHandle>) -> Self {+ pub(super) fn new_(id: TableId<TransmitHandle>) -> Self {Self {id,_phantom: PhantomData,}}+ pub(super) fn id(&self) -> TableId<TransmitHandle> {+ self.id+ }+/// Set the consumer that accepts the result of this future.pub fn pipe<S: AsContextMut>(self,@@ -1194,51 +1202,18 @@ impl<T> FutureReader<T> {.set_consumer(self.id, TransmitKind::Future, Consumer(consumer));}- /// Convert this `FutureReader` into a [`Val`].- // See TODO comment for `FutureAny`; this is prone to handle leakage.- pub fn into_val(self) -> Val {- Val::Future(FutureAny(self.id.rep()))- }-- /// Attempt to convert the specified [`Val`] to a `FutureReader`.- pub fn from_val(mut store: impl AsContextMut<Data: Send>, value: &Val) -> Result<Self> {- let Val::Future(FutureAny(rep)) = value else {- bail!("expected `future`; got `{}`", value.desc());- };- let store = store.as_context_mut();- let id = TableId::<TransmitHandle>::new(*rep);- store.0.concurrent_state_mut().get_mut(id)?; // Just make sure it's present- Ok(Self::new_(id))- }-/// Transfer ownership of the read end of a future from a guest to the host.fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {- match ty {- InterfaceType::Future(src) => {- let handle_table = cx- .instance_mut()- .table_for_transmit(TransmitIndex::Future(src));- let (rep, is_done) = handle_table.future_remove_readable(src, index)?;- if is_done {- bail!("cannot lift future after being notified that the writable end dropped");- }- let id = TableId::<TransmitHandle>::new(rep);- let concurrent_state = cx.concurrent_state_mut();- let future = concurrent_state.get_mut(id)?;- future.common.handle = None;- let state = future.state;-- if concurrent_state.get_mut(state)?.done {- bail!("cannot lift future after previous read succeeded");- }-- Ok(Self::new_(id))- }- _ => func::bad_type_info(),- }+ let id = lift_index_to_future(cx, ty, index)?;+ Ok(Self::new_(id))}- /// Close this `FutureReader`, writing the default value.+ /// Close this `FutureReader`.+ ///+ /// This will close this half of the future which will signal to a pending+ /// write, if any, that the reader side is dropped. If the writer half has+ /// not yet written a value then when it attempts to write a value it will+ /// see that this end is closed.////// # Panics///@@ -1246,13 +1221,7 @@ impl<T> FutureReader<T> {/// this future. Usage of this future after calling `close` will also cause/// a panic.pub fn close(&mut self, mut store: impl AsContextMut) {- // `self` should never be used again, but leave an invalid handle there just in case.- let id = mem::replace(&mut self.id, TableId::new(u32::MAX));- store- .as_context_mut()- .0- .host_drop_reader(id, TransmitKind::Future)- .unwrap();+ future_close(store.as_context_mut().0, &mut self.id)}/// Convenience method around [`Self::close`].@@ -1271,6 +1240,32 @@ impl<T> FutureReader<T> {{GuardedFutureReader::new(accessor, self)}++ /// Attempts to convert this [`FutureReader<T>`] to a [`FutureAny`].+ ///+ /// # Errors+ ///+ /// This function will return an error if `self` does not belong to+ /// `store`.+ pub fn try_into_future_any(self, store: impl AsContextMut) -> Result<FutureAny>+ where+ T: ComponentType + 'static,+ {+ FutureAny::try_from_future_reader(store, self)+ }++ /// Attempts to convert a [`FutureAny`] into a [`FutureReader<T>`].+ ///+ /// # Errors+ ///+ /// This function will fail if `T` doesn't match the type of the value that+ /// `future` is sending.+ pub fn try_from_future_any(future: FutureAny) -> Result<Self>+ where+ T: ComponentType + 'static,+ {+ future.try_into_future_reader()+ }}impl<T> fmt::Debug for FutureReader<T> {@@ -1281,16 +1276,51 @@ impl<T> fmt::Debug for FutureReader<T> {}}+pub(super) fn future_close(store: &mut StoreOpaque, id: &mut TableId<TransmitHandle>) {+ let id = mem::replace(id, TableId::new(u32::MAX));+ store.host_drop_reader(id, TransmitKind::Future).unwrap();+}+/// Transfer ownership of the read end of a future from the host to a guest.-pub(crate) fn lower_future_to_index<U>(- rep: u32,+pub(super) fn lift_index_to_future(+ cx: &mut LiftContext<'_>,+ ty: InterfaceType,+ index: u32,+) -> Result<TableId<TransmitHandle>> {+ match ty {+ InterfaceType::Future(src) => {+ let handle_table = cx+ .instance_mut()+ .table_for_transmit(TransmitIndex::Future(src));+ let (rep, is_done) = handle_table.future_remove_readable(src, index)?;+ if is_done {+ bail!("cannot lift future after being notified that the writable end dropped");+ }+ let id = TableId::<TransmitHandle>::new(rep);+ let concurrent_state = cx.concurrent_state_mut();+ let future = concurrent_state.get_mut(id)?;+ future.common.handle = None;+ let state = future.state;++ if concurrent_state.get_mut(state)?.done {+ bail!("cannot lift future after previous read succeeded");+ }++ Ok(id)+ }+ _ => func::bad_type_info(),+ }+}++/// Transfer ownership of the read end of a future from the host to a guest.+pub(super) fn lower_future_to_index<U>(+ id: TableId<TransmitHandle>,cx: &mut LowerContext<'_, U>,ty: InterfaceType,) -> Result<u32> {match ty {InterfaceType::Future(dst) => {let concurrent_state = cx.store.0.concurrent_state_mut();- let id = TableId::<TransmitHandle>::new(rep);let state = concurrent_state.get_mut(id)?.state;let rep = concurrent_state.get_mut(state)?.read_handle.rep();@@ -1309,32 +1339,31 @@ pub(crate) fn lower_future_to_index<U>(// SAFETY: This relies on the `ComponentType` implementation for `u32` being// safe and correct since we lift and lower future handles as `u32`s.-unsafe impl<T: Send + Sync> func::ComponentType for FutureReader<T> {+unsafe impl<T: ComponentType> ComponentType for FutureReader<T> {const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;type Lower = <u32 as func::ComponentType>::Lower;- fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {+ fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {match ty {- InterfaceType::Future(_) => Ok(()),+ InterfaceType::Future(ty) => {+ let ty = types.types[*ty].ty;+ types::typecheck_payload::<T>(types.types[ty].payload.as_ref(), types)+ }other => bail!("expected `future`, found `{}`", func::desc(other)),}}}// SAFETY: See the comment on the `ComponentType` `impl` for this type.-unsafe impl<T: Send + Sync> func::Lower for FutureReader<T> {+unsafe impl<T: ComponentType> func::Lower for FutureReader<T> {fn linear_lower_to_flat<U>(&self,cx: &mut LowerContext<'_, U>,ty: InterfaceType,dst: &mut MaybeUninit<Self::Lower>,) -> Result<()> {- lower_future_to_index(self.id.rep(), cx, ty)?.linear_lower_to_flat(- cx,- InterfaceType::U32,- dst,- )+ lower_future_to_index(self.id, cx, ty)?.linear_lower_to_flat(cx, InterfaceType::U32, dst)}fn linear_lower_to_memory<U>(@@ -1343,7 +1372,7 @@ unsafe impl<T: Send + Sync> func::Lower for FutureReader<T> {ty: InterfaceType,offset: usize,) -> Result<()> {- lower_future_to_index(self.id.rep(), cx, ty)?.linear_lower_to_memory(+ lower_future_to_index(self.id, cx, ty)?.linear_lower_to_memory(cx,InterfaceType::U32,offset,@@ -1352,7 +1381,7 @@ unsafe impl<T: Send + Sync> func::Lower for FutureReader<T> {}// SAFETY: See the comment on the `ComponentType` `impl` for this type.-unsafe impl<T: Send + Sync> func::Lift for FutureReader<T> {+unsafe impl<T: ComponentType> func::Lift for FutureReader<T> {fn linear_lift_from_flat(cx: &mut LiftContext<'_>,ty: InterfaceType,@@ -1454,13 +1483,17 @@ impl<T> StreamReader<T> {)}- fn new_(id: TableId<TransmitHandle>) -> Self {+ pub(super) fn new_(id: TableId<TransmitHandle>) -> Self {Self {id,_phantom: PhantomData,}}+ pub(super) fn id(&self) -> TableId<TransmitHandle> {+ self.id+ }+/// Attempt to consume this object by converting it into the specified type.////// This can be useful for "short-circuiting" host-to-host streams,@@ -1507,57 +1540,23 @@ impl<T> StreamReader<T> {.set_consumer(self.id, TransmitKind::Stream, consumer);}- /// Convert this `StreamReader` into a [`Val`].- // See TODO comment for `StreamAny`; this is prone to handle leakage.- pub fn into_val(self) -> Val {- Val::Stream(StreamAny(self.id.rep()))- }-- /// Attempt to convert the specified [`Val`] to a `StreamReader`.- pub fn from_val(mut store: impl AsContextMut<Data: Send>, value: &Val) -> Result<Self> {- let Val::Stream(StreamAny(rep)) = value else {- bail!("expected `stream`; got `{}`", value.desc());- };- let store = store.as_context_mut();- let id = TableId::<TransmitHandle>::new(*rep);- store.0.concurrent_state_mut().get_mut(id)?; // Just make sure it's present- Ok(Self::new_(id))- }-/// Transfer ownership of the read end of a stream from a guest to the host.fn lift_from_index(cx: &mut LiftContext<'_>, ty: InterfaceType, index: u32) -> Result<Self> {- match ty {- InterfaceType::Stream(src) => {- let handle_table = cx- .instance_mut()- .table_for_transmit(TransmitIndex::Stream(src));- let (rep, is_done) = handle_table.stream_remove_readable(src, index)?;- if is_done {- bail!("cannot lift stream after being notified that the writable end dropped");- }- let id = TableId::<TransmitHandle>::new(rep);- cx.concurrent_state_mut().get_mut(id)?.common.handle = None;- Ok(Self::new_(id))- }- _ => func::bad_type_info(),- }+ let id = lift_index_to_stream(cx, ty, index)?;+ Ok(Self::new_(id))}- /// Close this `StreamReader`, writing the default value.+ /// Close this `StreamReader`.+ ///+ /// This will signal that this portion of the stream is closed causing all+ /// future writes to return immediately with "DROPPED".////// # Panics///- /// Panics if the store that the [`Accessor`] is derived from does not own- /// this future. Usage of this future after calling `close` will also cause- /// a panic.+ /// Panics if the `store` does not own this future. Usage of this future+ /// after calling `close` will also cause a panic.pub fn close(&mut self, mut store: impl AsContextMut) {- // `self` should never be used again, but leave an invalid handle there just in case.- let id = mem::replace(&mut self.id, TableId::new(u32::MAX));- store- .as_context_mut()- .0- .host_drop_reader(id, TransmitKind::Stream)- .unwrap()+ stream_close(store.as_context_mut().0, &mut self.id);}/// Convenience method around [`Self::close`].@@ -1576,6 +1575,32 @@ impl<T> StreamReader<T> {{GuardedStreamReader::new(accessor, self)}++ /// Attempts to convert this [`StreamReader<T>`] to a [`StreamAny`].+ ///+ /// # Errors+ ///+ /// This function will return an error if `self` does not belong to+ /// `store`.+ pub fn try_into_stream_any(self, store: impl AsContextMut) -> Result<StreamAny>+ where+ T: ComponentType + 'static,+ {+ StreamAny::try_from_stream_reader(store, self)+ }++ /// Attempts to convert a [`StreamAny`] into a [`StreamReader<T>`].+ ///+ /// # Errors+ ///+ /// This function will fail if `T` doesn't match the type of the value that+ /// `stream` is sending.+ pub fn try_from_stream_any(stream: StreamAny) -> Result<Self>+ where+ T: ComponentType + 'static,+ {+ stream.try_into_stream_reader()+ }}impl<T> fmt::Debug for StreamReader<T> {@@ -1586,16 +1611,43 @@ impl<T> fmt::Debug for StreamReader<T> {}}+pub(super) fn stream_close(store: &mut StoreOpaque, id: &mut TableId<TransmitHandle>) {+ let id = mem::replace(id, TableId::new(u32::MAX));+ store.host_drop_reader(id, TransmitKind::Stream).unwrap();+}++/// Transfer ownership of the read end of a stream from a guest to the host.+pub(super) fn lift_index_to_stream(+ cx: &mut LiftContext<'_>,+ ty: InterfaceType,+ index: u32,+) -> Result<TableId<TransmitHandle>> {+ match ty {+ InterfaceType::Stream(src) => {+ let handle_table = cx+ .instance_mut()+ .table_for_transmit(TransmitIndex::Stream(src));+ let (rep, is_done) = handle_table.stream_remove_readable(src, index)?;+ if is_done {+ bail!("cannot lift stream after being notified that the writable end dropped");+ }+ let id = TableId::<TransmitHandle>::new(rep);+ cx.concurrent_state_mut().get_mut(id)?.common.handle = None;+ Ok(id)+ }+ _ => func::bad_type_info(),+ }+}+/// Transfer ownership of the read end of a stream from the host to a guest.-pub(crate) fn lower_stream_to_index<U>(- rep: u32,+pub(super) fn lower_stream_to_index<U>(+ id: TableId<TransmitHandle>,cx: &mut LowerContext<'_, U>,ty: InterfaceType,) -> Result<u32> {match ty {InterfaceType::Stream(dst) => {let concurrent_state = cx.store.0.concurrent_state_mut();- let id = TableId::<TransmitHandle>::new(rep);let state = concurrent_state.get_mut(id)?.state;let rep = concurrent_state.get_mut(state)?.read_handle.rep();@@ -1614,32 +1666,31 @@ pub(crate) fn lower_stream_to_index<U>(// SAFETY: This relies on the `ComponentType` implementation for `u32` being// safe and correct since we lift and lower stream handles as `u32`s.-unsafe impl<T: Send + Sync> func::ComponentType for StreamReader<T> {+unsafe impl<T: ComponentType> ComponentType for StreamReader<T> {const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;type Lower = <u32 as func::ComponentType>::Lower;- fn typecheck(ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {+ fn typecheck(ty: &InterfaceType, types: &InstanceType<'_>) -> Result<()> {match ty {- InterfaceType::Stream(_) => Ok(()),+ InterfaceType::Stream(ty) => {+ let ty = types.types[*ty].ty;+ types::typecheck_payload::<T>(types.types[ty].payload.as_ref(), types)+ }other => bail!("expected `stream`, found `{}`", func::desc(other)),}}}// SAFETY: See the comment on the `ComponentType` `impl` for this type.-unsafe impl<T: Send + Sync> func::Lower for StreamReader<T> {+unsafe impl<T: ComponentType> func::Lower for StreamReader<T> {fn linear_lower_to_flat<U>(&self,cx: &mut LowerContext<'_, U>,ty: InterfaceType,dst: &mut MaybeUninit<Self::Lower>,) -> Result<()> {- lower_stream_to_index(self.id.rep(), cx, ty)?.linear_lower_to_flat(- cx,- InterfaceType::U32,- dst,- )+ lower_stream_to_index(self.id, cx, ty)?.linear_lower_to_flat(cx, InterfaceType::U32, dst)}fn linear_lower_to_memory<U>(@@ -1648,7 +1699,7 @@ unsafe impl<T: Send + Sync> func::Lower for StreamReader<T> {ty: InterfaceType,offset: usize,) -> Result<()> {- lower_stream_to_index(self.id.rep(), cx, ty)?.linear_lower_to_memory(+ lower_stream_to_index(self.id, cx, ty)?.linear_lower_to_memory(cx,InterfaceType::U32,offset,@@ -1657,7 +1708,7 @@ unsafe impl<T: Send + Sync> func::Lower for StreamReader<T> {}// SAFETY: See the comment on the `ComponentType` `impl` for this type.-unsafe impl<T: Send + Sync> func::Lift for StreamReader<T> {+unsafe impl<T: ComponentType> func::Lift for StreamReader<T> {fn linear_lift_from_flat(cx: &mut LiftContext<'_>,ty: InterfaceType,@@ -1883,16 +1934,27 @@ struct TransmitState {read: ReadState,/// Whether futher values may be transmitted via this stream or future.done: bool,+ /// The original creator of this stream, used for type-checking with+ /// `{Future,Stream}Any`.+ pub(super) origin: TransmitOrigin,}-impl Default for TransmitState {- fn default() -> Self {+#[derive(Copy, Clone)]+pub(super) enum TransmitOrigin {+ Host,+ GuestFuture(ComponentInstanceId, TypeFutureTableIndex),+ GuestStream(ComponentInstanceId, TypeStreamTableIndex),+}++impl TransmitState {+ fn new(origin: TransmitOrigin) -> Self {Self {write_handle: TableId::new(u32::MAX),read_handle: TableId::new(u32::MAX),read: ReadState::Open,write: WriteState::Open,done: false,+ origin,}}}@@ -1903,6 +1965,15 @@ impl TableDebug for TransmitState {}}+impl TransmitOrigin {+ fn guest(id: ComponentInstanceId, index: TransmitIndex) -> Self {+ match index {+ TransmitIndex::Future(ty) => TransmitOrigin::GuestFuture(id, ty),+ TransmitIndex::Stream(ty) => TransmitOrigin::GuestStream(id, ty),+ }+ }+}+type PollStream = Box<dyn Fn() -> Pin<Box<dyn Future<Output = Result<StreamResult>> + Send + 'static>> + Send + Sync,>;@@ -2265,6 +2336,15 @@ impl StoreOpaque {}Ok(())}++ pub(super) fn transmit_origin(+ &mut self,+ id: TableId<TransmitHandle>,+ ) -> Result<TransmitOrigin> {+ let state = self.concurrent_state_mut();+ let state_id = state.get_mut(id)?.state;+ Ok(state.get_mut(state_id)?.origin)+ }}impl<T> StoreContextMut<'_, T> {@@ -2278,7 +2358,7 @@ impl<T> StoreContextMut<'_, T> {{let token = StoreToken::new(self.as_context_mut());let state = self.0.concurrent_state_mut();- let (_, read) = state.new_transmit().unwrap();+ let (_, read) = state.new_transmit(TransmitOrigin::Host).unwrap();let producer = Arc::new(Mutex::new(Some((Box::pin(producer), P::Buffer::default()))));let id = state.get_mut(read).unwrap().state;let mut dropped = false;@@ -3996,7 +4076,9 @@ impl Instance {/// write ends to the (sub-)component instance to which the specified/// `TransmitIndex` belongs.fn guest_new(self, store: &mut StoreOpaque, ty: TransmitIndex) -> Result<ResourcePair> {- let (write, read) = store.concurrent_state_mut().new_transmit()?;+ let (write, read) = store+ .concurrent_state_mut()+ .new_transmit(TransmitOrigin::guest(self.id().instance(), ty))?;let table = self.id().get_mut(store).table_for_transmit(ty);let (read_handle, write_handle) = match ty {@@ -4320,8 +4402,11 @@ impl ConcurrentState {/// Allocate a new future or stream, including the `TransmitState` and the/// `TransmitHandle`s corresponding to the read and write ends.- fn new_transmit(&mut self) -> Result<(TableId<TransmitHandle>, TableId<TransmitHandle>)> {- let state_id = self.push(TransmitState::default())?;+ fn new_transmit(+ &mut self,+ origin: TransmitOrigin,+ ) -> Result<(TableId<TransmitHandle>, TableId<TransmitHandle>)> {+ let state_id = self.push(TransmitState::new(origin))?;let write = self.push(TransmitHandle::new(state_id))?;let read = self.push(TransmitHandle::new(state_id))?;diff --git a/crates/wasmtime/src/runtime/component/concurrent_disabled.rs b/crates/wasmtime/src/runtime/component/concurrent_disabled.rsindex 12d1445ade..a99a73b5db 100644--- a/crates/wasmtime/src/runtime/component/concurrent_disabled.rs+++ b/crates/wasmtime/src/runtime/component/concurrent_disabled.rs@@ -1,13 +1,14 @@-use crate::component::Val;-use crate::component::func::{ComponentType, LiftContext, LowerContext};+use crate::component::func::{LiftContext, LowerContext};+use crate::component::matching::InstanceType;+use crate::component::{ComponentType, Lift, Lower, Val};use crate::runtime::vm::VMStore;-use anyhow::{Result, anyhow};+use anyhow::{Result, anyhow, bail};use core::convert::Infallible;use core::future::Future;-use core::marker::PhantomData;+use core::mem::MaybeUninit;use core::pin::pin;use core::task::{Context, Poll, Waker};-use wasmtime_environ::component::{InterfaceType, RuntimeComponentInstanceIndex};+use wasmtime_environ::component::{CanonicalAbiInfo, InterfaceType, RuntimeComponentInstanceIndex};#[derive(Default)]pub struct ConcurrentState;@@ -36,22 +37,6 @@ pub(crate) fn poll_and_block<R: Send + Sync + 'static>(}}-pub(crate) fn lower_future_to_index<U>(- _rep: u32,- _cx: &mut LowerContext<'_, U>,- _ty: InterfaceType,-) -> Result<u32> {- should_have_failed_validation("use of `future`")-}--pub(crate) fn lower_stream_to_index<U>(- _rep: u32,- _cx: &mut LowerContext<'_, U>,- _ty: InterfaceType,-) -> Result<u32> {- should_have_failed_validation("use of `stream`")-}-pub(crate) fn lower_error_context_to_index<U>(_rep: u32,_cx: &mut LowerContext<'_, U>,@@ -84,56 +69,102 @@ impl ErrorContext {}}-pub struct StreamReader<P> {- uninhabited: Infallible,- _phantom: PhantomData<P>,-}+#[derive(PartialEq, Clone, Debug)]+pub struct FutureAny(Infallible);-impl<P> StreamReader<P> {- pub(crate) fn into_val(self) -> Val {- match self.uninhabited {}+unsafe impl ComponentType for FutureAny {+ type Lower = <u32 as ComponentType>::Lower;+ const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;++ fn typecheck(_ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {+ bail!("support for component-model-async disabled at compile time")}+}- pub(crate) fn linear_lift_from_flat(+unsafe impl Lift for FutureAny {+ fn linear_lift_from_flat(_cx: &mut LiftContext<'_>,_ty: InterfaceType,- _src: &<u32 as ComponentType>::Lower,+ _src: &Self::Lower,) -> Result<Self> {- should_have_failed_validation("use of `stream`")+ bail!("support for component-model-async disabled at compile time")}- pub(crate) fn linear_lift_from_memory(+ fn linear_lift_from_memory(_cx: &mut LiftContext<'_>,_ty: InterfaceType,_bytes: &[u8],) -> Result<Self> {- should_have_failed_validation("use of `stream`")+ bail!("support for component-model-async disabled at compile time")}}-pub struct FutureReader<P> {- uninhabited: Infallible,- _phantom: PhantomData<P>,+unsafe impl Lower for FutureAny {+ fn linear_lower_to_flat<T>(+ &self,+ _cx: &mut LowerContext<'_, T>,+ _ty: InterfaceType,+ _dst: &mut MaybeUninit<Self::Lower>,+ ) -> Result<()> {+ match self.0 {}+ }++ fn linear_lower_to_memory<T>(+ &self,+ _cx: &mut LowerContext<'_, T>,+ _ty: InterfaceType,+ _offset: usize,+ ) -> Result<()> {+ match self.0 {}+ }}-impl<P> FutureReader<P> {- pub(crate) fn into_val(self) -> Val {- match self.uninhabited {}+#[derive(PartialEq, Clone, Debug)]+pub struct StreamAny(Infallible);++unsafe impl ComponentType for StreamAny {+ type Lower = <u32 as ComponentType>::Lower;+ const ABI: CanonicalAbiInfo = CanonicalAbiInfo::SCALAR4;++ fn typecheck(_ty: &InterfaceType, _types: &InstanceType<'_>) -> Result<()> {+ bail!("support for component-model-async disabled at compile time")}+}- pub(crate) fn linear_lift_from_flat(+unsafe impl Lift for StreamAny {+ fn linear_lift_from_flat(_cx: &mut LiftContext<'_>,_ty: InterfaceType,- _src: &<u32 as ComponentType>::Lower,+ _src: &Self::Lower,) -> Result<Self> {- should_have_failed_validation("use of `future`")+ bail!("support for component-model-async disabled at compile time")}- pub(crate) fn linear_lift_from_memory(+ fn linear_lift_from_memory(_cx: &mut LiftContext<'_>,_ty: InterfaceType,_bytes: &[u8],) -> Result<Self> {- should_have_failed_validation("use of `future`")+ bail!("support for component-model-async disabled at compile time")+ }+}++unsafe impl Lower for StreamAny {+ fn linear_lower_to_flat<T>(+ &self,+ _cx: &mut LowerContext<'_, T>,+ _ty: InterfaceType,+ _dst: &mut MaybeUninit<Self::Lower>,+ ) -> Result<()> {+ match self.0 {}+ }++ fn linear_lower_to_memory<T>(+ &self,+ _cx: &mut LowerContext<'_, T>,+ _ty: InterfaceType,+ _offset: usize,+ ) -> Result<()> {+ match self.0 {}}}diff --git a/crates/wasmtime/src/runtime/component/mod.rs b/crates/wasmtime/src/runtime/component/mod.rsindex 2d28f9596b..43fb2c7ea6 100644--- a/crates/wasmtime/src/runtime/component/mod.rs+++ b/crates/wasmtime/src/runtime/component/mod.rs@@ -120,8 +120,8 @@ pub use self::component::{Component, ComponentExportIndex};#[cfg(feature = "component-model-async")]pub use self::concurrent::{Access, Accessor, AccessorTask, AsAccessor, Destination, DirectDestination, DirectSource,- ErrorContext, FutureConsumer, FutureProducer, FutureReader, GuardedFutureReader,- GuardedStreamReader, JoinHandle, ReadBuffer, Source, StreamConsumer, StreamProducer,+ ErrorContext, FutureAny, FutureConsumer, FutureProducer, FutureReader, GuardedFutureReader,+ GuardedStreamReader, JoinHandle, ReadBuffer, Source, StreamAny, StreamConsumer, StreamProducer,StreamReader, StreamResult, VMComponentAsyncStore, VecBuffer, WriteBuffer,};#[cfg(feature = "component-model-async")]diff --git a/crates/wasmtime/src/runtime/component/types.rs b/crates/wasmtime/src/runtime/component/types.rsindex e1badf710a..54434005a2 100644--- a/crates/wasmtime/src/runtime/component/types.rs+++ b/crates/wasmtime/src/runtime/component/types.rs@@ -1,5 +1,7 @@//! This module defines the `Type` type, representing the dynamic form of a component interface type.+#[cfg(feature = "component-model-async")]+use crate::component::ComponentType;use crate::component::matching::InstanceType;use crate::{Engine, ExternType, FuncType};use alloc::sync::Arc;@@ -529,6 +531,26 @@ impl PartialEq for Flags {impl Eq for Flags {}+#[cfg(feature = "component-model-async")]+pub(crate) fn typecheck_payload<T>(+ payload: Option<&InterfaceType>,+ types: &InstanceType<'_>,+) -> anyhow::Result<()>+where+ T: ComponentType,+{+ match payload {+ Some(a) => T::typecheck(a, types),+ None => {+ if T::IS_RUST_UNIT_TYPE {+ Ok(())+ } else {+ anyhow::bail!("future payload types differ")+ }+ }+ }+}+/// An `future` interface type#[derive(Clone, Debug)]pub struct FutureType(Handle<TypeFutureIndex>);@@ -545,6 +567,37 @@ impl FutureType {&self.0.instance(),))}++ #[cfg(feature = "component-model-async")]+ pub(crate) fn equivalent_payload_guest(+ &self,+ ty: &InstanceType<'_>,+ payload: Option<&InterfaceType>,+ ) -> bool {+ let my_payload = self.0.types[self.0.index].payload.as_ref();+ match (my_payload, payload) {+ (Some(a), Some(b)) => TypeChecker {+ a_types: &self.0.types,+ a_resource: &self.0.resources,+ b_types: ty.types,+ b_resource: ty.resources,+ }+ .interface_types_equal(*a, *b),+ (None, None) => true,+ (Some(_), None) | (None, Some(_)) => false,+ }+ }++ #[cfg(feature = "component-model-async")]+ pub(crate) fn equivalent_payload_host<T>(&self) -> anyhow::Result<()>+ where+ T: ComponentType,+ {+ typecheck_payload::<T>(+ self.0.types[self.0.index].payload.as_ref(),+ &self.0.instance(),+ )+ }}impl PartialEq for FutureType {@@ -571,6 +624,37 @@ impl StreamType {&self.0.instance(),))}++ #[cfg(feature = "component-model-async")]+ pub(crate) fn equivalent_payload_guest(+ &self,+ ty: &InstanceType<'_>,+ payload: Option<&InterfaceType>,+ ) -> bool {+ let my_payload = self.0.types[self.0.index].payload.as_ref();+ match (my_payload, payload) {+ (Some(a), Some(b)) => TypeChecker {+ a_types: &self.0.types,+ a_resource: &self.0.resources,+ b_types: ty.types,+ b_resource: ty.resources,+ }+ .interface_types_equal(*a, *b),+ (None, None) => true,+ (Some(_), None) | (None, Some(_)) => false,+ }+ }++ #[cfg(feature = "component-model-async")]+ pub(crate) fn equivalent_payload_host<T>(&self) -> anyhow::Result<()>+ where+ T: ComponentType,+ {+ typecheck_payload::<T>(+ self.0.types[self.0.index].payload.as_ref(),+ &self.0.instance(),+ )+ }}impl PartialEq for StreamType {diff --git a/crates/wasmtime/src/runtime/component/values.rs b/crates/wasmtime/src/runtime/component/values.rsindex eb2bcb69e5..0215ea504e 100644--- a/crates/wasmtime/src/runtime/component/values.rs+++ b/crates/wasmtime/src/runtime/component/values.rs@@ -1,6 +1,6 @@use crate::ValRaw;use crate::component::ResourceAny;-use crate::component::concurrent::{self, ErrorContext, FutureReader, StreamReader};+use crate::component::concurrent::{self, ErrorContext, FutureAny, StreamAny};use crate::component::func::{Lift, LiftContext, Lower, LowerContext, desc};use crate::prelude::*;use core::mem::MaybeUninit;@@ -207,10 +207,10 @@ impl Val {Val::Flags(flags)}InterfaceType::Future(_) => {- FutureReader::<()>::linear_lift_from_flat(cx, ty, next(src))?.into_val()+ Val::Future(FutureAny::linear_lift_from_flat(cx, ty, next(src))?)}InterfaceType::Stream(_) => {- StreamReader::<()>::linear_lift_from_flat(cx, ty, next(src))?.into_val()+ Val::Stream(StreamAny::linear_lift_from_flat(cx, ty, next(src))?)}InterfaceType::ErrorContext(_) => {ErrorContext::linear_lift_from_flat(cx, ty, next(src))?.into_val()@@ -336,12 +336,8 @@ impl Val {}Val::Flags(flags)}- InterfaceType::Future(_) => {- FutureReader::<()>::linear_lift_from_memory(cx, ty, bytes)?.into_val()- }- InterfaceType::Stream(_) => {- StreamReader::<()>::linear_lift_from_memory(cx, ty, bytes)?.into_val()- }+ InterfaceType::Future(_) => FutureAny::linear_lift_from_memory(cx, ty, bytes)?.into(),+ InterfaceType::Stream(_) => StreamAny::linear_lift_from_memory(cx, ty, bytes)?.into(),InterfaceType::ErrorContext(_) => {ErrorContext::linear_lift_from_memory(cx, ty, bytes)?.into_val()}@@ -479,20 +475,12 @@ impl Val {Ok(())}(InterfaceType::Flags(_), _) => unexpected(ty, self),- (InterfaceType::Future(_), Val::Future(FutureAny(rep))) => {- concurrent::lower_future_to_index(*rep, cx, ty)?.linear_lower_to_flat(- cx,- InterfaceType::U32,- next_mut(dst),- )+ (InterfaceType::Future(_), Val::Future(f)) => {+ f.linear_lower_to_flat(cx, ty, next_mut(dst))}(InterfaceType::Future(_), _) => unexpected(ty, self),- (InterfaceType::Stream(_), Val::Stream(StreamAny(rep))) => {- concurrent::lower_stream_to_index(*rep, cx, ty)?.linear_lower_to_flat(- cx,- InterfaceType::U32,- next_mut(dst),- )+ (InterfaceType::Stream(_), Val::Stream(s)) => {+ s.linear_lower_to_flat(cx, ty, next_mut(dst))}(InterfaceType::Stream(_), _) => unexpected(ty, self),(InterfaceType::ErrorContext(_), Val::ErrorContext(ErrorContextAny(rep))) => {@@ -644,21 +632,9 @@ impl Val {Ok(())}(InterfaceType::Flags(_), _) => unexpected(ty, self),- (InterfaceType::Future(_), Val::Future(FutureAny(rep))) => {- concurrent::lower_future_to_index::<T>(*rep, cx, ty)?.linear_lower_to_memory(- cx,- InterfaceType::U32,- offset,- )- }+ (InterfaceType::Future(_), Val::Future(f)) => f.linear_lower_to_memory(cx, ty, offset),(InterfaceType::Future(_), _) => unexpected(ty, self),- (InterfaceType::Stream(_), Val::Stream(StreamAny(rep))) => {- concurrent::lower_stream_to_index::<T>(*rep, cx, ty)?.linear_lower_to_memory(- cx,- InterfaceType::U32,- offset,- )- }+ (InterfaceType::Stream(_), Val::Stream(s)) => s.linear_lower_to_memory(cx, ty, offset),(InterfaceType::Stream(_), _) => unexpected(ty, self),(InterfaceType::ErrorContext(_), Val::ErrorContext(ErrorContextAny(rep))) => {concurrent::lower_error_context_to_index(*rep, cx, ty)?.linear_lower_to_memory(@@ -1111,30 +1087,6 @@ fn unexpected<T>(ty: InterfaceType, val: &Val) -> Result<T> {)}-/// Represents a component model `future`.-///-/// Note that this type is not usable at this time as its implementation has not-/// been filled out. There are no operations on this and there's additionally no-/// ability to "drop" or deallocate this index. This means that from the-/// perspective of wasm it'll appear that this handle has "leaked" without ever-/// being dropped or read from.-//-// FIXME(#11161) this needs to be filled out implementation-wise-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct FutureAny(pub(crate) u32);--/// Represents a component model `stream`.-///-/// Note that this type is not usable at this time as its implementation has not-/// been filled out. There are no operations on this and there's additionally no-/// ability to "drop" or deallocate this index. This means that from the-/// perspective of wasm it'll appear that this handle has "leaked" without ever-/// being dropped or read from.-//-// FIXME(#11161) this needs to be filled out implementation-wise-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct StreamAny(pub(crate) u32);-/// Represents a component model `error-context`.////// Note that this type is not usable at this time as its implementation has not@@ -1144,3 +1096,87 @@ pub struct StreamAny(pub(crate) u32);// FIXME(#11161) this needs to be filled out implementation-wise#[derive(Debug, Clone, PartialEq, Eq)]pub struct ErrorContextAny(pub(crate) u32);++impl From<bool> for Val {+ fn from(b: bool) -> Self {+ Val::Bool(b)+ }+}++impl From<u8> for Val {+ fn from(u: u8) -> Self {+ Val::U8(u)+ }+}++impl From<i8> for Val {+ fn from(i: i8) -> Self {+ Val::S8(i)+ }+}++impl From<u16> for Val {+ fn from(u: u16) -> Self {+ Val::U16(u)+ }+}++impl From<i16> for Val {+ fn from(i: i16) -> Self {+ Val::S16(i)+ }+}++impl From<u32> for Val {+ fn from(u: u32) -> Self {+ Val::U32(u)+ }+}++impl From<i32> for Val {+ fn from(i: i32) -> Self {+ Val::S32(i)+ }+}++impl From<u64> for Val {+ fn from(u: u64) -> Self {+ Val::U64(u)+ }+}++impl From<i64> for Val {+ fn from(i: i64) -> Self {+ Val::S64(i)+ }+}++impl From<char> for Val {+ fn from(i: char) -> Self {+ Val::Char(i)+ }+}++impl From<String> for Val {+ fn from(i: String) -> Self {+ Val::String(i)+ }+}++impl From<ResourceAny> for Val {+ fn from(i: ResourceAny) -> Self {+ Val::Resource(i)+ }+}++impl From<FutureAny> for Val {+ fn from(i: FutureAny) -> Self {+ Val::Future(i)+ }+}++impl From<StreamAny> for Val {+ fn from(i: StreamAny) -> Self {+ Val::Stream(i)+ }+}diff --git a/tests/all/component_model.rs b/tests/all/component_model.rsindex 3bc1891df8..87d85aaf01 100644--- a/tests/all/component_model.rs+++ b/tests/all/component_model.rs@@ -7,6 +7,7 @@ use wasmtime_test_util::component::{TypedFuncExt, async_engine, engine};mod aot;mod r#async;+mod async_dynamic;mod bindgen;mod call_hook;mod dynamic;diff --git a/tests/all/component_model/async_dynamic.rs b/tests/all/component_model/async_dynamic.rsnew file mode 100644index 0000000000..34713255d1--- /dev/null+++ b/tests/all/component_model/async_dynamic.rs@@ -0,0 +1,184 @@+use wasmtime::component::{Component, FutureAny, FutureReader, Linker, StreamAny, StreamReader};+use wasmtime::{Config, Engine, Result, Store};++#[test]+fn simple_type_conversions() {+ let engine = Engine::default();+ let mut store = Store::new(&engine, ());++ let f = FutureReader::new(&mut store, async { anyhow::Ok(10_u32) });+ let f = f.try_into_future_any(&mut store).unwrap();+ assert!(f.clone().try_into_future_reader::<()>().is_err());+ assert!(f.clone().try_into_future_reader::<u64>().is_err());+ let f = f.try_into_future_reader::<u32>().unwrap();+ f.try_into_future_any(&mut store).unwrap().close(&mut store);++ let s = StreamReader::new(&mut store, vec![10_u32]);+ let s = s.try_into_stream_any(&mut store).unwrap();+ assert!(s.clone().try_into_stream_reader::<()>().is_err());+ assert!(s.clone().try_into_stream_reader::<u64>().is_err());+ let s = s.try_into_stream_reader::<u32>().unwrap();+ s.try_into_stream_any(&mut store).unwrap().close(&mut store);+}++#[test]+#[cfg_attr(miri, ignore)]+fn simple_type_assertions() -> Result<()> {+ let mut config = Config::new();+ config.wasm_component_model_async(true);+ let engine = Engine::new(&config)?;+ let mut store = Store::new(&engine, ());++ let component = Component::new(+ &engine,+ r#"+ (component+ (type $f (future u32))+ (type $s (stream u32))+ (core func $mk-f (canon future.new $f))+ (core func $mk-s (canon stream.new $s))++ (core module $m+ (import "" "mk-f" (func $mk-f (result i64)))+ (import "" "mk-s" (func $mk-s (result i64)))++ (func (export "x") (param i32) (result i32) local.get 0)++ (func (export "mk-f") (result i32)+ (i32.wrap_i64 (call $mk-f)))+ (func (export "mk-s") (result i32)+ (i32.wrap_i64 (call $mk-s)))+ )+ (core instance $i (instantiate $m+ (with "" (instance+ (export "mk-f" (func $mk-f))+ (export "mk-s" (func $mk-s))+ ))+ ))+ (func (export "f") (param "f" $f) (result $f)+ (canon lift (core func $i "x")))+ (func (export "s") (param "s" $s) (result $s)+ (canon lift (core func $i "x")))+ (func (export "mk-f") (result $f)+ (canon lift (core func $i "mk-f")))+ (func (export "mk-s") (result $s)+ (canon lift (core func $i "mk-s")))+ )+ "#,+ )?;++ let instance = Linker::new(&engine).instantiate(&mut store, &component)?;++ let f_t_t =+ instance.get_typed_func::<(FutureReader<u32>,), (FutureReader<u32>,)>(&mut store, "f")?;+ let f_t_a = instance.get_typed_func::<(FutureReader<u32>,), (FutureAny,)>(&mut store, "f")?;+ let f_a_t = instance.get_typed_func::<(FutureAny,), (FutureReader<u32>,)>(&mut store, "f")?;+ let f_a_a = instance.get_typed_func::<(FutureAny,), (FutureAny,)>(&mut store, "f")?;++ let s_t_t =+ instance.get_typed_func::<(StreamReader<u32>,), (StreamReader<u32>,)>(&mut store, "s")?;+ let s_t_a = instance.get_typed_func::<(StreamReader<u32>,), (StreamAny,)>(&mut store, "s")?;+ let s_a_t = instance.get_typed_func::<(StreamAny,), (StreamReader<u32>,)>(&mut store, "s")?;+ let s_a_a = instance.get_typed_func::<(StreamAny,), (StreamAny,)>(&mut store, "s")?;++ let mk_f_t = instance.get_typed_func::<(), (FutureReader<u32>,)>(&mut store, "mk-f")?;+ let mk_f_a = instance.get_typed_func::<(), (FutureAny,)>(&mut store, "mk-f")?;+ let mk_s_t = instance.get_typed_func::<(), (StreamReader<u32>,)>(&mut store, "mk-s")?;+ let mk_s_a = instance.get_typed_func::<(), (StreamAny,)>(&mut store, "mk-s")?;++ assert!(instance.get_typed_func::<(), ()>(&mut store, "f").is_err());+ assert!(+ instance+ .get_typed_func::<(u32,), (FutureReader<u32>,)>(&mut store, "f")+ .is_err()+ );+ assert!(+ instance+ .get_typed_func::<(FutureReader<u32>,), (u32,)>(&mut store, "f")+ .is_err()+ );+ assert!(+ instance+ .get_typed_func::<(FutureReader<()>,), (FutureReader<u32>,)>(&mut store, "f")+ .is_err()+ );+ assert!(+ instance+ .get_typed_func::<(FutureReader<u64>,), (FutureReader<u32>,)>(&mut store, "f")+ .is_err()+ );++ assert!(instance.get_typed_func::<(), ()>(&mut store, "s").is_err());+ assert!(+ instance+ .get_typed_func::<(u32,), (StreamReader<u32>,)>(&mut store, "s")+ .is_err()+ );+ assert!(+ instance+ .get_typed_func::<(StreamReader<u32>,), (u32,)>(&mut store, "s")+ .is_err()+ );+ assert!(+ instance+ .get_typed_func::<(StreamReader<()>,), (StreamReader<u32>,)>(&mut store, "s")+ .is_err()+ );+ assert!(+ instance+ .get_typed_func::<(StreamReader<u64>,), (StreamReader<u32>,)>(&mut store, "s")+ .is_err()+ );++ let roundtrip = |store: &mut Store<()>, f: FutureReader<u32>| -> Result<()> {+ let (f,) = f_t_t.call(&mut *store, (f,))?;+ f_t_t.post_return(&mut *store)?;+ let (f,) = f_t_a.call(&mut *store, (f,))?;+ f_t_a.post_return(&mut *store)?;+ let (f,) = f_a_a.call(&mut *store, (f,))?;+ f_a_a.post_return(&mut *store)?;+ let (mut f,) = f_a_t.call(&mut *store, (f,))?;+ f_a_t.post_return(&mut *store)?;+ f.close(&mut *store);+ Ok(())+ };++ let f = FutureReader::new(&mut store, async { anyhow::Ok(10_u32) });+ roundtrip(&mut store, f)?;++ let (f,) = mk_f_t.call(&mut store, ())?;+ mk_f_t.post_return(&mut store)?;+ roundtrip(&mut store, f)?;++ let (f,) = mk_f_a.call(&mut store, ())?;+ mk_f_a.post_return(&mut store)?;+ let f = f.try_into_future_reader::<u32>()?;+ roundtrip(&mut store, f)?;++ let roundtrip = |store: &mut Store<()>, s: StreamReader<u32>| -> Result<()> {+ let (s,) = s_t_t.call(&mut *store, (s,))?;+ s_t_t.post_return(&mut *store)?;+ let (s,) = s_t_a.call(&mut *store, (s,))?;+ s_t_a.post_return(&mut *store)?;+ let (s,) = s_a_a.call(&mut *store, (s,))?;+ s_a_a.post_return(&mut *store)?;+ let (mut s,) = s_a_t.call(&mut *store, (s,))?;+ s_a_t.post_return(&mut *store)?;+ s.close(&mut *store);+ Ok(())+ };++ let s = StreamReader::new(&mut store, vec![10_u32]);+ roundtrip(&mut store, s)?;++ let (s,) = mk_s_t.call(&mut store, ())?;+ mk_s_t.post_return(&mut store)?;+ roundtrip(&mut store, s)?;++ let (s,) = mk_s_a.call(&mut store, ())?;+ mk_s_a.post_return(&mut store)?;+ let s = s.try_into_stream_reader::<u32>()?;+ roundtrip(&mut store, s)?;++ Ok(())+}