Skip to content

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

support continuing host-to-host streams after store is dropped (#11763)

Joel Diceda6336188582
diff --git a/Cargo.lock b/Cargo.lock
index 5bb64582df..2d8cc60612 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4989,6 +4989,7 @@ dependencies = [
"async-trait",
"base64",
"bytes",
+ "env_logger 0.11.5",
"flate2",
"futures",
"http",
diff --git a/crates/test-programs/src/bin/p3_http_echo.rs b/crates/test-programs/src/bin/p3_http_echo.rs
index a502d546fe..a1ac89529d 100644
--- a/crates/test-programs/src/bin/p3_http_echo.rs
+++ b/crates/test-programs/src/bin/p3_http_echo.rs
@@ -18,7 +18,11 @@ impl Handler for Component {
let (_, result_rx) = wit_future::new(|| Ok(()));
let (body, trailers) = Request::consume_body(request, result_rx);
- let (response, _result) = if false {
+ let (response, _result) = if headers
+ .get("x-host-to-host")
+ .into_iter()
+ .any(|v| v == b"true")
+ {
// This is the easy and efficient way to do it...
Response::new(headers, Some(body), trailers)
} else {
diff --git a/crates/test-programs/src/bin/p3_http_middleware.rs b/crates/test-programs/src/bin/p3_http_middleware.rs
index 566b8bc4ba..30f733bec1 100644
--- a/crates/test-programs/src/bin/p3_http_middleware.rs
+++ b/crates/test-programs/src/bin/p3_http_middleware.rs
@@ -60,15 +60,16 @@ impl Handler for Component {
wit_bindgen::spawn(async move {
{
let mut decoder = DeflateDecoder::new(Vec::new());
+ let mut status = StreamResult::Complete(0);
+ let mut chunk = Vec::with_capacity(64 * 1024);
- let (mut status, mut chunk) = body.read(Vec::with_capacity(64 * 1024)).await;
while let StreamResult::Complete(_) = status {
+ (status, chunk) = body.read(chunk).await;
decoder.write_all(&chunk).unwrap();
let remaining = pipe_tx.write_all(mem::take(decoder.get_mut())).await;
assert!(remaining.is_empty());
*decoder.get_mut() = remaining;
chunk.clear();
- (status, chunk) = body.read(chunk).await;
}
let remaining = pipe_tx.write_all(decoder.finish().unwrap()).await;
@@ -123,15 +124,16 @@ impl Handler for Component {
wit_bindgen::spawn(async move {
{
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::fast());
- let (mut status, mut chunk) = body.read(Vec::with_capacity(64 * 1024)).await;
+ let mut status = StreamResult::Complete(0);
+ let mut chunk = Vec::with_capacity(64 * 1024);
while let StreamResult::Complete(_) = status {
+ (status, chunk) = body.read(chunk).await;
encoder.write_all(&chunk).unwrap();
let remaining = pipe_tx.write_all(mem::take(encoder.get_mut())).await;
assert!(remaining.is_empty());
*encoder.get_mut() = remaining;
chunk.clear();
- (status, chunk) = body.read(chunk).await;
}
let remaining = pipe_tx.write_all(encoder.finish().unwrap()).await;
diff --git a/crates/wasi-http/Cargo.toml b/crates/wasi-http/Cargo.toml
index ae03c814fa..0b360ac16c 100644
--- a/crates/wasi-http/Cargo.toml
+++ b/crates/wasi-http/Cargo.toml
@@ -54,3 +54,4 @@ base64 = { workspace = true }
flate2 = { workspace = true }
wasm-compose = { workspace = true }
tempfile = { workspace = true }
+env_logger = { workspace = true }
diff --git a/crates/wasi-http/src/p3/body.rs b/crates/wasi-http/src/p3/body.rs
index a63c86ba09..0779f4c7db 100644
--- a/crates/wasi-http/src/p3/body.rs
+++ b/crates/wasi-http/src/p3/body.rs
@@ -9,6 +9,7 @@ use core::task::{Context, Poll, ready};
use http::HeaderMap;
use http_body::Body as _;
use http_body_util::combinators::BoxBody;
+use std::any::{Any, TypeId};
use std::io::Cursor;
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot};
@@ -445,8 +446,8 @@ where
}
/// [StreamProducer] implementation for bodies originating in the host.
-struct HostBodyStreamProducer<T> {
- body: BoxBody<Bytes, ErrorCode>,
+pub(crate) struct HostBodyStreamProducer<T> {
+ pub(crate) body: BoxBody<Bytes, ErrorCode>,
trailers: Option<oneshot::Sender<Result<Option<Resource<Trailers>>, ErrorCode>>>,
getter: fn(&mut T) -> WasiHttpCtxView<'_>,
}
@@ -536,4 +537,13 @@ where
self.close(res);
Poll::Ready(Ok(StreamResult::Dropped))
}
+
+ fn try_into(me: Pin<Box<Self>>, ty: TypeId) -> Result<Box<dyn Any>, Pin<Box<Self>>> {
+ if ty == TypeId::of::<Self>() {
+ let me = Pin::into_inner(me);
+ Ok(me)
+ } else {
+ Err(me)
+ }
+ }
}
diff --git a/crates/wasi-http/src/p3/host/handler.rs b/crates/wasi-http/src/p3/host/handler.rs
index 4f3da56deb..f3706b4713 100644
--- a/crates/wasi-http/src/p3/host/handler.rs
+++ b/crates/wasi-http/src/p3/host/handler.rs
@@ -12,12 +12,13 @@ use http::{HeaderValue, Uri};
use http_body_util::BodyExt as _;
use std::sync::Arc;
use tokio::sync::oneshot;
+use tokio::task::{self, JoinHandle};
use tracing::debug;
-use wasmtime::component::{Accessor, AccessorTask, JoinHandle, Resource};
+use wasmtime::component::{Accessor, Resource};
/// A wrapper around [`JoinHandle`], which will [`JoinHandle::abort`] the task
/// when dropped
-struct AbortOnDropJoinHandle(JoinHandle);
+struct AbortOnDropJoinHandle(JoinHandle<()>);
impl Drop for AbortOnDropJoinHandle {
fn drop(&mut self) {
@@ -171,20 +172,6 @@ trait BodyExt {
impl<T> BodyExt for T {}
-struct SendRequestTask {
- io: Pin<Box<dyn Future<Output = Result<(), ErrorCode>> + Send>>,
- result_tx: oneshot::Sender<Result<(), ErrorCode>>,
-}
-
-impl<T> AccessorTask<T, WasiHttp, wasmtime::Result<()>> for SendRequestTask {
- async fn run(self, _: &Accessor<T, WasiHttp>) -> wasmtime::Result<()> {
- let res = self.io.await;
- debug!(?res, "`send_request` I/O future finished");
- _ = self.result_tx.send(res);
- Ok(())
- }
-}
-
async fn io_task_result(
rx: oneshot::Receiver<(
Arc<AbortOnDropJoinHandle>,
@@ -336,7 +323,11 @@ impl HostWithStore for WasiHttp {
Poll::Pending => {
// I/O driver still needs to be polled, spawn a task and send handles to it
let (tx, rx) = oneshot::channel();
- let io = store.spawn(SendRequestTask { io, result_tx: tx });
+ let io = task::spawn(async move {
+ let res = io.await;
+ debug!(?res, "`send_request` I/O future finished");
+ _ = tx.send(res);
+ });
let io = Arc::new(AbortOnDropJoinHandle(io));
_ = io_result_tx.send((Arc::clone(&io), rx));
_ = io_task_tx.send(Arc::clone(&io));
diff --git a/crates/wasi-http/src/p3/host/types.rs b/crates/wasi-http/src/p3/host/types.rs
index 8f78117dcb..4747a57bcc 100644
--- a/crates/wasi-http/src/p3/host/types.rs
+++ b/crates/wasi-http/src/p3/host/types.rs
@@ -4,18 +4,19 @@ use crate::p3::bindings::http::types::{
HostRequestOptions, HostRequestWithStore, HostResponse, HostResponseWithStore, Method, Request,
RequestOptions, RequestOptionsError, Response, Scheme, StatusCode, Trailers,
};
-use crate::p3::body::Body;
+use crate::p3::body::{Body, HostBodyStreamProducer};
use crate::p3::{HeaderResult, HttpError, RequestOptionsResult, WasiHttp, WasiHttpCtxView};
use anyhow::Context as _;
+use core::mem;
use core::pin::Pin;
use core::task::{Context, Poll, ready};
use http::header::CONTENT_LENGTH;
use std::sync::Arc;
use tokio::sync::oneshot;
-use wasmtime::StoreContextMut;
use wasmtime::component::{
Access, Accessor, FutureProducer, FutureReader, Resource, ResourceTable, StreamReader,
};
+use wasmtime::{AsContextMut, StoreContextMut};
fn get_fields<'a>(
table: &'a ResourceTable,
@@ -602,13 +603,26 @@ impl HostResponseWithStore for WasiHttp {
let instance = store.instance();
store.with(|mut store| {
let (result_tx, result_rx) = oneshot::channel();
+ let body = match contents
+ .map(|rx| rx.try_into::<HostBodyStreamProducer<T>>(store.as_context_mut()))
+ {
+ Some(Ok(mut producer)) => Body::Host {
+ body: mem::take(&mut producer.body),
+ result_tx,
+ },
+ Some(Err(rx)) => Body::Guest {
+ contents_rx: Some(rx),
+ trailers_rx: trailers,
+ result_tx,
+ },
+ None => Body::Guest {
+ contents_rx: None,
+ trailers_rx: trailers,
+ result_tx,
+ },
+ };
let WasiHttpCtxView { table, .. } = store.get();
let headers = delete_fields(table, headers)?;
- let body = Body::Guest {
- contents_rx: contents,
- trailers_rx: trailers,
- result_tx,
- };
let res = Response {
status: http::StatusCode::OK,
headers: headers.into(),
diff --git a/crates/wasi-http/tests/all/p3/mod.rs b/crates/wasi-http/tests/all/p3/mod.rs
index 8701cb3f6a..cfa1d8c25d 100644
--- a/crates/wasi-http/tests/all/p3/mod.rs
+++ b/crates/wasi-http/tests/all/p3/mod.rs
@@ -123,25 +123,36 @@ async fn run_http<E: Into<ErrorCode> + 'static>(
let instance = linker.instantiate_async(&mut store, &component).await?;
let proxy = Proxy::new(&mut store, &instance)?;
let (req, io) = Request::from_http(req);
- let (res, ()) = instance
- .run_concurrent(&mut store, async |store| {
- try_join!(
- async {
- let (res, task) = match proxy.handle(store, req).await? {
- Ok(pair) => pair,
- Err(err) => return Ok(Err(Some(err))),
- };
- let res = store.with(|store| res.into_http(store, async { Ok(()) }))?;
- let (parts, body) = res.into_parts();
- let body = body.collect().await.context("failed to collect body")?;
- task.block(store).await;
- Ok(Ok(http::Response::from_parts(parts, body)))
- },
- async { io.await.context("failed to consume request body") }
- )
- })
- .await??;
- Ok(res)
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ let ((handle_result, ()), res) = try_join!(
+ async move {
+ instance
+ .run_concurrent(&mut store, async |store| {
+ try_join!(
+ async {
+ let (res, task) = match proxy.handle(store, req).await? {
+ Ok(pair) => pair,
+ Err(err) => return Ok(Err(Some(err))),
+ };
+ _ = tx
+ .send(store.with(|store| res.into_http(store, async { Ok(()) }))?);
+ task.block(store).await;
+ Ok(Ok(()))
+ },
+ async { io.await.context("failed to consume request body") }
+ )
+ })
+ .await?
+ },
+ async move {
+ let res = rx.await?;
+ let (parts, body) = res.into_parts();
+ let body = body.collect().await.context("failed to collect body")?;
+ anyhow::Ok(http::Response::from_parts(parts, body))
+ }
+ )?;
+
+ Ok(handle_result.map(|()| res))
}
#[test_log::test(tokio::test(flavor = "multi_thread"))]
@@ -254,18 +265,32 @@ async fn wasi_http_proxy_tests() -> anyhow::Result<()> {
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_echo() -> Result<()> {
- test_http_echo(P3_HTTP_ECHO_COMPONENT, false).await
+ test_http_echo(P3_HTTP_ECHO_COMPONENT, false, false).await
+}
+
+#[test_log::test(tokio::test(flavor = "multi_thread"))]
+async fn p3_http_echo_host_to_host() -> Result<()> {
+ test_http_echo(P3_HTTP_ECHO_COMPONENT, false, true).await
}
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_middleware() -> Result<()> {
+ test_http_middleware(false).await
+}
+
+#[test_log::test(tokio::test(flavor = "multi_thread"))]
+async fn p3_http_middleware_host_to_host() -> Result<()> {
+ test_http_middleware(true).await
+}
+
+async fn test_http_middleware(host_to_host: bool) -> Result<()> {
let tempdir = tempfile::tempdir()?;
let echo = &fs::read(P3_HTTP_ECHO_COMPONENT).await?;
let middleware = &fs::read(P3_HTTP_MIDDLEWARE_COMPONENT).await?;
let path = tempdir.path().join("temp.wasm");
fs::write(&path, compose(middleware, echo).await?).await?;
- test_http_echo(&path.to_str().unwrap(), true).await
+ test_http_echo(&path.to_str().unwrap(), true, host_to_host).await
}
async fn compose(a: &[u8], b: &[u8]) -> Result<Vec<u8>> {
@@ -290,6 +315,15 @@ async fn compose(a: &[u8], b: &[u8]) -> Result<Vec<u8>> {
#[test_log::test(tokio::test(flavor = "multi_thread"))]
async fn p3_http_middleware_with_chain() -> Result<()> {
+ test_http_middleware_with_chain(false).await
+}
+
+#[test_log::test(tokio::test(flavor = "multi_thread"))]
+async fn p3_http_middleware_with_chain_host_to_host() -> Result<()> {
+ test_http_middleware_with_chain(true).await
+}
+
+async fn test_http_middleware_with_chain(host_to_host: bool) -> Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("temp.wasm");
@@ -334,10 +368,12 @@ async fn p3_http_middleware_with_chain() -> Result<()> {
.compose()?;
fs::write(&path, &bytes).await?;
- test_http_echo(&path.to_str().unwrap(), true).await
+ test_http_echo(&path.to_str().unwrap(), true, host_to_host).await
}
-async fn test_http_echo(component: &str, use_compression: bool) -> Result<()> {
+async fn test_http_echo(component: &str, use_compression: bool, host_to_host: bool) -> Result<()> {
+ _ = env_logger::try_init();
+
let body = b"And the mome raths outgrabe";
// Prepare the raw body, optionally compressed if that's what we're
@@ -353,23 +389,7 @@ async fn test_http_echo(component: &str, use_compression: bool) -> Result<()> {
// Prepare the http_body body, modeled here as a channel with the body
// chunk above buffered up followed by some trailers. Note that trailers
// are always here to test that code paths throughout the components.
- let (mut body_tx, body_rx) = futures::channel::mpsc::channel::<Result<_, ErrorCode>>(2);
- body_tx
- .send(Ok(http_body::Frame::data(raw_body)))
- .await
- .unwrap();
- body_tx
- .send(Ok(http_body::Frame::trailers({
- let mut trailers = http::HeaderMap::new();
- assert!(
- trailers
- .insert("fizz", http::HeaderValue::from_static("buzz"))
- .is_none()
- );
- trailers
- })))
- .await
- .unwrap();
+ let (mut body_tx, body_rx) = futures::channel::mpsc::channel::<Result<_, ErrorCode>>(1);
// Build the `http::Request`, optionally specifying compression-related
// headers.
@@ -382,16 +402,40 @@ async fn test_http_echo(component: &str, use_compression: bool) -> Result<()> {
.header("content-encoding", "deflate")
.header("accept-encoding", "nonexistent-encoding, deflate");
}
+ if host_to_host {
+ request = request.header("x-host-to-host", "true");
+ }
// Send this request to wasm and assert that success comes back.
//
// Note that this will read the entire body internally and wait for
// everything to get collected before proceeding to below.
- let response = run_http(
- component,
- request.body(http_body_util::StreamBody::new(body_rx))?,
+ let response = futures::join!(
+ run_http(
+ component,
+ request.body(http_body_util::StreamBody::new(body_rx))?,
+ ),
+ async {
+ body_tx
+ .send(Ok(http_body::Frame::data(raw_body)))
+ .await
+ .unwrap();
+ body_tx
+ .send(Ok(http_body::Frame::trailers({
+ let mut trailers = http::HeaderMap::new();
+ assert!(
+ trailers
+ .insert("fizz", http::HeaderValue::from_static("buzz"))
+ .is_none()
+ );
+ trailers
+ })))
+ .await
+ .unwrap();
+ drop(body_tx);
+ }
)
- .await?
+ .0?
.unwrap();
assert!(response.status().as_u16() == 200);
diff --git a/crates/wasmtime/src/runtime/component/concurrent.rs b/crates/wasmtime/src/runtime/component/concurrent.rs
index c42989e1bd..9c6d52b684 100644
--- a/crates/wasmtime/src/runtime/component/concurrent.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent.rs
@@ -3779,6 +3779,12 @@ impl GuestTask {
}
}
+ for subtask in self.subtasks {
+ if state.get_mut(subtask)?.exited {
+ Waitable::Guest(subtask).delete_from(state)?;
+ }
+ }
+
Ok(())
}
diff --git a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
index a693d59fea..6f90d4f790 100644
--- a/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
+++ b/crates/wasmtime/src/runtime/component/concurrent/futures_and_streams.rs
@@ -20,6 +20,7 @@ use core::pin::Pin;
use core::task::{Context, Poll, Waker, ready};
use futures::channel::oneshot;
use futures::{FutureExt as _, stream};
+use std::any::{Any, TypeId};
use std::boxed::Box;
use std::io::Cursor;
use std::string::{String, ToString};
@@ -507,6 +508,15 @@ pub trait StreamProducer<D>: Send + 'static {
destination: Destination<'a, Self::Item, Self::Buffer>,
finish: bool,
) -> Poll<Result<StreamResult>>;
+
+ /// Attempt to convert the specified object into a `Box<dyn Any>` which may
+ /// be downcast to the specified type.
+ ///
+ /// The implementation must ensure that, if it returns `Ok(_)`, a downcast
+ /// to the specified type is guaranteed to succeed.
+ fn try_into(me: Pin<Box<Self>>, _ty: TypeId) -> Result<Box<dyn Any>, Pin<Box<Self>>> {
+ Err(me)
+ }
}
impl<T, D> StreamProducer<D> for iter::Empty<T>
@@ -1398,6 +1408,39 @@ impl<T> StreamReader<T> {
}
}
+ /// Attempt to consume this object by converting it into the specified type.
+ ///
+ /// This can be useful for "short-circuiting" host-to-host streams,
+ /// bypassing the guest entirely. For example, if a guest task returns a
+ /// host-created stream and then exits, this function may be used to
+ /// retrieve the write end, after which the guest instance and store may be
+ /// disposed of if no longer needed.
+ ///
+ /// This will return `Ok(_)` if and only if the following conditions are
+ /// met:
+ ///
+ /// - The stream was created by the host (i.e. not by the guest).
+ ///
+ /// - The `StreamProducer::try_into` function returns `Ok(_)` when given the
+ /// producer provided to `StreamReader::new` when the stream was created,
+ /// along with `TypeId::of::<V>()`.
+ pub fn try_into<V: 'static>(mut self, mut store: impl AsContextMut) -> Result<V, Self> {
+ let store = store.as_context_mut();
+ let state = self.instance.concurrent_state_mut(store.0);
+ let id = state.get_mut(self.id).unwrap().state;
+ if let WriteState::HostReady { try_into, .. } = &state.get_mut(id).unwrap().write {
+ match try_into(TypeId::of::<V>()) {
+ Some(result) => {
+ self.close(store);
+ Ok(*result.downcast::<V>().unwrap())
+ }
+ None => Err(self),
+ }
+ } else {
+ Err(self)
+ }
+ }
+
/// Set the consumer that accepts the items delivered to this stream.
pub fn pipe<S: AsContextMut>(self, store: S, consumer: impl StreamConsumer<S::Data, Item = T>)
where
@@ -1818,6 +1861,8 @@ type PollStream = Box<
dyn Fn() -> Pin<Box<dyn Future<Output = Result<StreamResult>> + Send + 'static>> + Send + Sync,
>;
+type TryInto = Box<dyn Fn(TypeId) -> Option<Box<dyn Any>> + Send + Sync>;
+
/// Represents the state of the write end of a stream or future.
enum WriteState {
/// The write end is open, but no write is pending.
@@ -1834,6 +1879,7 @@ enum WriteState {
/// The write end is owned by the host, which is ready to produce items.
HostReady {
produce: PollStream,
+ try_into: TryInto,
guest_offset: usize,
cancel: bool,
cancel_waker: Option<Waker>,
@@ -1927,13 +1973,15 @@ impl Instance {
let (_, read) = state.new_transmit().unwrap();
let producer = Arc::new(Mutex::new(Some((Box::pin(producer), P::Buffer::default()))));
let id = state.get_mut(read).unwrap().state;
- let produce = Box::new(move || {
+ let produce = Box::new({
let producer = producer.clone();
- async move {
- let (mut mine, mut buffer) = producer.lock().unwrap().take().unwrap();
+ move || {
+ let producer = producer.clone();
+ async move {
+ let (mut mine, mut buffer) = producer.lock().unwrap().take().unwrap();
- let (result, cancelled) = if buffer.remaining().is_empty() {
- future::poll_fn(|cx| {
+ let (result, cancelled) = if buffer.remaining().is_empty() {
+ future::poll_fn(|cx| {
tls::get(|store| {
let transmit = self.concurrent_state_mut(store).get_mut(id).unwrap();
@@ -2007,62 +2055,74 @@ impl Instance {
})
})
.await?
- } else {
- (StreamResult::Completed, false)
- };
-
- let (guest_offset, host_offset, count) = tls::get(|store| {
- let transmit = self.concurrent_state_mut(store).get_mut(id).unwrap();
- let (count, host_offset) = match &transmit.read {
- &ReadState::GuestReady { count, .. } => (count, 0),
- &ReadState::HostToHost { limit, .. } => (1, limit),
- _ => unreachable!(),
- };
- let guest_offset = match &transmit.write {
- &WriteState::HostReady { guest_offset, .. } => guest_offset,
- _ => unreachable!(),
+ } else {
+ (StreamResult::Completed, false)
};
- (guest_offset, host_offset, count)
- });
- match result {
- StreamResult::Completed => {
- if count > 1
- && buffer.remaining().is_empty()
- && guest_offset == 0
- && host_offset == 0
- {
- bail!(
- "StreamProducer::poll_produce returned StreamResult::Completed \
- without producing any items"
- );
+ let (guest_offset, host_offset, count) = tls::get(|store| {
+ let transmit = self.concurrent_state_mut(store).get_mut(id).unwrap();
+ let (count, host_offset) = match &transmit.read {
+ &ReadState::GuestReady { count, .. } => (count, 0),
+ &ReadState::HostToHost { limit, .. } => (1, limit),
+ _ => unreachable!(),
+ };
+ let guest_offset = match &transmit.write {
+ &WriteState::HostReady { guest_offset, .. } => guest_offset,
+ _ => unreachable!(),
+ };
+ (guest_offset, host_offset, count)
+ });
+
+ match result {
+ StreamResult::Completed => {
+ if count > 1
+ && buffer.remaining().is_empty()
+ && guest_offset == 0
+ && host_offset == 0
+ {
+ bail!(
+ "StreamProducer::poll_produce returned StreamResult::Completed \
+ without producing any items"
+ );
+ }
}
- }
- StreamResult::Cancelled => {
- if !cancelled {
- bail!(
- "StreamProducer::poll_produce returned StreamResult::Cancelled \
- without being given a `finish` parameter value of true"
- );
+ StreamResult::Cancelled => {
+ if !cancelled {
+ bail!(
+ "StreamProducer::poll_produce returned StreamResult::Cancelled \
+ without being given a `finish` parameter value of true"
+ );
+ }
}
+ StreamResult::Dropped => {}
}
- StreamResult::Dropped => {}
- }
- let write_buffer = !buffer.remaining().is_empty() || host_offset > 0;
+ let write_buffer = !buffer.remaining().is_empty() || host_offset > 0;
- *producer.lock().unwrap() = Some((mine, buffer));
+ *producer.lock().unwrap() = Some((mine, buffer));
- if write_buffer {
- self.write(token, id, producer, kind).await?;
- }
+ if write_buffer {
+ self.write(token, id, producer, kind).await?;
+ }
- Ok(result)
+ Ok(result)
+ }
+ .boxed()
+ }
+ });
+ let try_into = Box::new(move |ty| {
+ let (mine, buffer) = producer.lock().unwrap().take().unwrap();
+ match P::try_into(mine, ty) {
+ Ok(value) => Some(value),
+ Err(mine) => {
+ *producer.lock().unwrap() = Some((mine, buffer));
+ None
+ }
}
- .boxed()
});
state.get_mut(id).unwrap().write = WriteState::HostReady {
produce,
+ try_into,
guest_offset: 0,
cancel: false,
cancel_waker: None,
@@ -2215,6 +2275,7 @@ impl Instance {
&mut transmit.write,
WriteState::HostReady {
produce: Box::new(|| unreachable!()),
+ try_into: Box::new(|_| unreachable!()),
guest_offset: 0,
cancel: false,
cancel_waker: None,
@@ -2482,6 +2543,7 @@ impl Instance {
let transmit = state.get_mut(id)?;
let WriteState::HostReady {
produce,
+ try_into,
guest_offset,
..
} = mem::replace(&mut transmit.write, WriteState::Open)
@@ -2493,6 +2555,7 @@ impl Instance {
StreamResult::Dropped => WriteState::Dropped,
StreamResult::Completed | StreamResult::Cancelled => WriteState::HostReady {
produce,
+ try_into,
guest_offset: 0,
cancel: false,
cancel_waker: None,
@@ -3298,6 +3361,7 @@ impl Instance {
WriteState::HostReady {
produce,
+ try_into,
guest_offset,
cancel,
cancel_waker,
@@ -3312,7 +3376,7 @@ impl Instance {
set_guest_ready(concurrent_state)?;
- self.produce(store.0, ty.kind(), transmit_id, produce, 0, false)?
+ self.produce(store.0, ty.kind(), transmit_id, produce, try_into, 0, false)?
}
WriteState::Open => {
@@ -3352,12 +3416,14 @@ impl Instance {
kind: TransmitKind,
transmit_id: TableId<TransmitState>,
produce: PollStream,
+ try_into: TryInto,
guest_offset: usize,
cancel: bool,
) -> Result<ReturnCode> {
let mut future = produce();
self.concurrent_state_mut(store).get_mut(transmit_id)?.write = WriteState::HostReady {
produce,
+ try_into,
guest_offset,
cancel,
cancel_waker: None,