Skip to content

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

Refactor wasip2 http host trait to look like wasip3 (#13810)

Alex Crichtone7fa0097f924
diff --git a/crates/wasi-http/src/lib.rs b/crates/wasi-http/src/lib.rs
index 874ccbe5c3..04f12bc285 100644
--- a/crates/wasi-http/src/lib.rs
+++ b/crates/wasi-http/src/lib.rs
@@ -20,9 +20,11 @@ pub mod io;
pub mod p2;
#[cfg(feature = "p3")]
pub mod p3;
+mod request_options;
pub use ctx::*;
pub use field_map::*;
+pub use request_options::*;
/// Extract the `Content-Length` header value from a [`http::HeaderMap`], returning `None` if it's not
/// present. This function will return `Err` if it's not possible to parse the `Content-Length`
diff --git a/crates/wasi-http/src/p2/bindings.rs b/crates/wasi-http/src/p2/bindings.rs
index f3e8b35035..afd4b77ff0 100644
--- a/crates/wasi-http/src/p2/bindings.rs
+++ b/crates/wasi-http/src/p2/bindings.rs
@@ -27,7 +27,7 @@ mod generated {
"wasi:http/types.outgoing-request": types::HostOutgoingRequest,
"wasi:http/types.incoming-request": types::HostIncomingRequest,
"wasi:http/types.fields": crate::FieldMap,
- "wasi:http/types.request-options": types::HostRequestOptions,
+ "wasi:http/types.request-options": crate::RequestOptions,
},
trappable_error_type: {
"wasi:http/types.error-code" => crate::p2::HttpError,
diff --git a/crates/wasi-http/src/p2/body.rs b/crates/wasi-http/src/p2/body.rs
index 99dbb949e8..5b1b543694 100644
--- a/crates/wasi-http/src/p2/body.rs
+++ b/crates/wasi-http/src/p2/body.rs
@@ -9,7 +9,9 @@ use http_body_util::combinators::UnsyncBoxBody;
use std::future::Future;
use std::mem;
use std::task::{Context, Poll};
-use std::{pin::Pin, sync::Arc, time::Duration};
+#[cfg(feature = "default-send-request")]
+use std::time::Duration;
+use std::{pin::Pin, sync::Arc};
use tokio::sync::{mpsc, oneshot};
use wasmtime::format_err;
use wasmtime_wasi::p2::{InputStream, OutputStream, Pollable, StreamError};
@@ -33,8 +35,7 @@ pub struct HostIncomingBody {
impl HostIncomingBody {
/// Create a new `HostIncomingBody` with the given `body` and a per-frame timeout
- pub fn new(body: HyperIncomingBody, between_bytes_timeout: Duration) -> HostIncomingBody {
- let body = BodyWithTimeout::new(body, between_bytes_timeout);
+ pub fn new(body: HyperIncomingBody) -> HostIncomingBody {
HostIncomingBody {
body: IncomingBodyState::Start(body),
worker: None,
@@ -76,7 +77,7 @@ impl HostIncomingBody {
enum IncomingBodyState {
/// The body is stored here meaning that within `HostIncomingBody` the
/// `take_stream` method can be called for example.
- Start(BodyWithTimeout),
+ Start(HyperIncomingBody),
/// The body is within a `HostIncomingBodyStream` meaning that it's not
/// currently owned here. The body will be sent back over this channel when
@@ -86,9 +87,10 @@ enum IncomingBodyState {
/// Small wrapper around [`HyperIncomingBody`] which adds a timeout to every frame.
#[derive(Debug)]
-struct BodyWithTimeout {
+#[cfg(feature = "default-send-request")]
+pub(crate) struct BodyWithTimeout<B> {
/// Underlying stream that frames are coming from.
- inner: HyperIncomingBody,
+ inner: B,
/// Currently active timeout that's reset between frames.
timeout: Pin<Box<tokio::time::Sleep>>,
/// Whether or not `timeout` needs to be reset on the next call to
@@ -99,8 +101,9 @@ struct BodyWithTimeout {
between_bytes_timeout: Duration,
}
-impl BodyWithTimeout {
- fn new(inner: HyperIncomingBody, between_bytes_timeout: Duration) -> BodyWithTimeout {
+#[cfg(feature = "default-send-request")]
+impl<B> BodyWithTimeout<B> {
+ pub(crate) fn new(inner: B, between_bytes_timeout: Duration) -> BodyWithTimeout<B> {
BodyWithTimeout {
inner,
between_bytes_timeout,
@@ -112,14 +115,18 @@ impl BodyWithTimeout {
}
}
-impl Body for BodyWithTimeout {
- type Data = Bytes;
+#[cfg(feature = "default-send-request")]
+impl<B> Body for BodyWithTimeout<B>
+where
+ B: Body<Error = types::ErrorCode> + Unpin,
+{
+ type Data = B::Data;
type Error = types::ErrorCode;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
- ) -> Poll<Option<Result<Frame<Bytes>, types::ErrorCode>>> {
+ ) -> Poll<Option<Result<Frame<B::Data>, types::ErrorCode>>> {
let me = Pin::into_inner(self);
// If the timeout timer needs to be reset, do that now relative to the
@@ -152,7 +159,7 @@ impl Body for BodyWithTimeout {
enum StreamEnd {
/// The body wasn't completely read and was dropped early. May still have
/// trailers, but requires reading more frames.
- Remaining(BodyWithTimeout),
+ Remaining(HyperIncomingBody),
/// Body was completely read and trailers were read. Here are the trailers.
/// Note that `None` means that the body finished without trailers.
@@ -223,7 +230,7 @@ enum IncomingBodyStreamState {
/// This state is transitioned to `Closed` when an error happens, EOF
/// happens, or when trailers are read.
Open {
- body: BodyWithTimeout,
+ body: HyperIncomingBody,
tx: oneshot::Sender<StreamEnd>,
},
diff --git a/crates/wasi-http/src/p2/http_impl.rs b/crates/wasi-http/src/p2/http_impl.rs
index ae73ef8a20..cdf83d63ea 100644
--- a/crates/wasi-http/src/p2/http_impl.rs
+++ b/crates/wasi-http/src/p2/http_impl.rs
@@ -8,11 +8,12 @@ use crate::p2::{
},
error::internal_error,
http_request_error,
- types::{HostFutureIncomingResponse, HostOutgoingRequest, OutgoingRequestConfig},
+ types::{HostFutureIncomingResponse, HostOutgoingRequest},
};
use bytes::Bytes;
use http_body_util::{BodyExt, Empty};
use hyper::Method;
+use std::pin::Pin;
use wasmtime::component::Resource;
impl outgoing_handler::Host for WasiHttpCtxView<'_> {
@@ -21,19 +22,7 @@ impl outgoing_handler::Host for WasiHttpCtxView<'_> {
request_id: Resource<HostOutgoingRequest>,
options: Option<Resource<types::RequestOptions>>,
) -> HttpResult<Resource<HostFutureIncomingResponse>> {
- let opts = options.and_then(|opts| self.table.get(&opts).ok());
-
- let connect_timeout = opts
- .and_then(|opts| opts.connect_timeout)
- .unwrap_or(std::time::Duration::from_secs(600));
-
- let first_byte_timeout = opts
- .and_then(|opts| opts.first_byte_timeout)
- .unwrap_or(std::time::Duration::from_secs(600));
-
- let between_bytes_timeout = opts
- .and_then(|opts| opts.between_bytes_timeout)
- .unwrap_or(std::time::Duration::from_secs(600));
+ let opts = options.and_then(|opts| self.table.get(&opts).ok()).cloned();
let req = self.table.delete(request_id)?;
let mut builder = hyper::Request::builder();
@@ -54,9 +43,9 @@ impl outgoing_handler::Host for WasiHttpCtxView<'_> {
},
});
- let (use_tls, scheme) = match req.scheme.unwrap_or(Scheme::Https) {
- Scheme::Http => (false, http::uri::Scheme::HTTP),
- Scheme::Https => (true, http::uri::Scheme::HTTPS),
+ let scheme = match req.scheme.unwrap_or(Scheme::Https) {
+ Scheme::Http => http::uri::Scheme::HTTP,
+ Scheme::Https => http::uri::Scheme::HTTPS,
// We can only support http/https
Scheme::Other(_) => return Err(types::ErrorCode::HttpProtocolError.into()),
@@ -88,16 +77,22 @@ impl outgoing_handler::Host for WasiHttpCtxView<'_> {
.body(body)
.map_err(|err| internal_error(err.to_string()))?;
- let future = self.hooks.send_request(
- request,
- OutgoingRequestConfig {
- use_tls,
- connect_timeout,
- first_byte_timeout,
- between_bytes_timeout,
- },
- )?;
+ let future = self.hooks.send_request(request, opts);
+ let future = wasmtime_wasi::runtime::spawn(async move {
+ let (res, io) = Pin::from(future).await?;
+ let io = wasmtime_wasi::runtime::spawn(async move {
+ match Pin::from(io).await {
+ Ok(()) => {}
+ // TODO: shouldn't throw away this error and ideally should
+ // surface somewhere.
+ Err(e) => tracing::warn!("dropping error {e}"),
+ }
+ });
+ Ok((res, io))
+ });
- Ok(self.table.push(future)?)
+ Ok(self
+ .table
+ .push(HostFutureIncomingResponse::Pending(future))?)
}
}
diff --git a/crates/wasi-http/src/p2/mod.rs b/crates/wasi-http/src/p2/mod.rs
index 962c372911..ba8661d2fe 100644
--- a/crates/wasi-http/src/p2/mod.rs
+++ b/crates/wasi-http/src/p2/mod.rs
@@ -219,8 +219,8 @@
//! }
//! ```
-#[cfg(feature = "default-send-request")]
use self::bindings::http::types::ErrorCode;
+use crate::RequestOptions;
use crate::{DEFAULT_FORBIDDEN_HEADERS, WasiHttpCtx};
use http::HeaderName;
use wasmtime::component::{HasData, Linker, ResourceTable};
@@ -287,19 +287,41 @@ pub trait WasiHttpHooks: Send {
#[cfg(feature = "default-send-request")]
fn send_request(
&mut self,
- request: hyper::Request<body::HyperOutgoingBody>,
- config: types::OutgoingRequestConfig,
- ) -> HttpResult<types::HostFutureIncomingResponse> {
- Ok(default_send_request(request, config))
+ request: http::Request<body::HyperOutgoingBody>,
+ options: Option<RequestOptions>,
+ ) -> Box<
+ dyn Future<
+ Output = HttpResult<(
+ http::Response<body::HyperIncomingBody>,
+ Box<dyn Future<Output = Result<(), ErrorCode>> + Send>,
+ )>,
+ > + Send,
+ > {
+ Box::new(async move {
+ use http_body_util::BodyExt;
+
+ let (res, io) = default_send_request(request, options).await?;
+ Ok((
+ res.map(BodyExt::boxed_unsync),
+ Box::new(io) as Box<dyn Future<Output = _> + Send>,
+ ))
+ })
}
/// Send an outgoing request.
#[cfg(not(feature = "default-send-request"))]
fn send_request(
&mut self,
- request: hyper::Request<body::HyperOutgoingBody>,
- config: types::OutgoingRequestConfig,
- ) -> HttpResult<types::HostFutureIncomingResponse>;
+ request: http::Request<body::HyperOutgoingBody>,
+ options: Option<RequestOptions>,
+ ) -> Box<
+ dyn Future<
+ Output = HttpResult<(
+ http::Response<body::HyperIncomingBody>,
+ Box<dyn Future<Output = Result<(), ErrorCode>> + Send>,
+ )>,
+ > + Send,
+ >;
/// Whether a given header should be considered forbidden and not allowed.
fn is_forbidden_header(&mut self, name: &HeaderName) -> bool {
@@ -552,36 +574,48 @@ where
/// This implementation is used by the `wasi:http/outgoing-handler` interface
/// default implementation.
#[cfg(feature = "default-send-request")]
-pub fn default_send_request(
- request: hyper::Request<body::HyperOutgoingBody>,
- config: types::OutgoingRequestConfig,
-) -> types::HostFutureIncomingResponse {
- let handle = wasmtime_wasi::runtime::spawn(async move {
- Ok(default_send_request_handler(request, config).await)
- });
- types::HostFutureIncomingResponse::pending(handle)
-}
-
-/// The underlying implementation of how an outgoing request is sent. This should likely be spawned
-/// in a task.
-///
-/// This is called from [default_send_request] to actually send the request.
-#[cfg(feature = "default-send-request")]
-pub async fn default_send_request_handler(
- mut request: hyper::Request<body::HyperOutgoingBody>,
- types::OutgoingRequestConfig {
- use_tls,
- connect_timeout,
- first_byte_timeout,
- between_bytes_timeout,
- }: types::OutgoingRequestConfig,
-) -> Result<types::IncomingResponse, ErrorCode> {
+pub async fn default_send_request(
+ mut request: http::Request<body::HyperOutgoingBody>,
+ options: Option<RequestOptions>,
+) -> Result<
+ (
+ http::Response<impl http_body::Body<Data = bytes::Bytes, Error = ErrorCode>>,
+ impl Future<Output = Result<(), ErrorCode>> + Send,
+ ),
+ ErrorCode,
+> {
use crate::io::TokioIo;
use crate::p2::{error::dns_error, hyper_request_error};
use http_body_util::BodyExt;
+ use std::future::poll_fn;
+ use std::pin::{Pin, pin};
+ use std::task::{Poll, ready};
+ use std::time::Duration;
+ use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpStream;
use tokio::time::timeout;
+ trait TokioStream: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static {
+ fn boxed(self) -> Box<dyn TokioStream>
+ where
+ Self: Sized,
+ {
+ Box::new(self)
+ }
+ }
+ impl<T> TokioStream for T where T: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static {}
+
+ let connect_timeout = options
+ .and_then(|o| o.connect_timeout)
+ .unwrap_or(Duration::from_secs(600));
+ let first_byte_timeout = options
+ .and_then(|o| o.first_byte_timeout)
+ .unwrap_or(Duration::from_secs(600));
+ let between_bytes_timeout = options
+ .and_then(|o| o.between_bytes_timeout)
+ .unwrap_or(Duration::from_secs(600));
+
+ let use_tls = request.uri().scheme() == Some(&http::uri::Scheme::HTTPS);
if !request.headers().contains_key(hyper::header::HOST) {
if let Some(authority) = request.uri().authority() {
if let Ok(value) = hyper::header::HeaderValue::from_str(authority.as_str()) {
@@ -619,7 +653,7 @@ pub async fn default_send_request_handler(
}
})?;
- let (mut sender, worker) = if use_tls {
+ let stream = if use_tls {
// derived from https://github.com/rustls/rustls/blob/main/examples/src/bin/simpleclient.rs
let root_cert_store = rustls::RootCertStore {
roots: webpki_roots::TLS_SERVER_ROOTS.into(),
@@ -636,48 +670,19 @@ pub async fn default_send_request_handler(
tracing::warn!("tls protocol error: {e:?}");
ErrorCode::TlsProtocolError
})?;
- let stream = TokioIo::new(stream);
-
- let (sender, conn) = timeout(
- connect_timeout,
- hyper::client::conn::http1::handshake(stream),
- )
- .await
- .map_err(|_| ErrorCode::ConnectionTimeout)?
- .map_err(hyper_request_error)?;
-
- let worker = wasmtime_wasi::runtime::spawn(async move {
- match conn.await {
- Ok(()) => {}
- // TODO: shouldn't throw away this error and ideally should
- // surface somewhere.
- Err(e) => tracing::warn!("dropping error {e}"),
- }
- });
-
- (sender, worker)
+ TokioIo::new(stream.boxed())
} else {
- let tcp_stream = TokioIo::new(tcp_stream);
- let (sender, conn) = timeout(
- connect_timeout,
- // TODO: we should plumb the builder through the http context, and use it here
- hyper::client::conn::http1::handshake(tcp_stream),
- )
- .await
- .map_err(|_| ErrorCode::ConnectionTimeout)?
- .map_err(hyper_request_error)?;
-
- let worker = wasmtime_wasi::runtime::spawn(async move {
- match conn.await {
- Ok(()) => {}
- // TODO: same as above, shouldn't throw this error away.
- Err(e) => tracing::warn!("dropping error {e}"),
- }
- });
-
- (sender, worker)
+ TokioIo::new(tcp_stream.boxed())
};
+ let (mut sender, conn) = timeout(
+ connect_timeout,
+ hyper::client::conn::http1::handshake(stream),
+ )
+ .await
+ .map_err(|_| ErrorCode::ConnectionTimeout)?
+ .map_err(hyper_request_error)?;
+
// at this point, the request contains the scheme and the authority, but
// the http packet should only include those if addressing a proxy, so
// remove them here, since SendRequest::send_request does not do it for us
@@ -692,15 +697,43 @@ pub async fn default_send_request_handler(
.build()
.expect("comes from valid request");
- let resp = timeout(first_byte_timeout, sender.send_request(request))
- .await
- .map_err(|_| ErrorCode::ConnectionReadTimeout)?
- .map_err(hyper_request_error)?
- .map(|body| body.map_err(hyper_request_error).boxed_unsync());
-
- Ok(types::IncomingResponse {
- resp,
- worker: Some(worker),
- between_bytes_timeout,
+ let resp = async move {
+ Ok(timeout(first_byte_timeout, sender.send_request(request))
+ .await
+ .map_err(|_| ErrorCode::ConnectionReadTimeout)?
+ .map_err(hyper_request_error)?
+ .map(|body| {
+ let body = body.map_err(hyper_request_error);
+ body::BodyWithTimeout::new(body, between_bytes_timeout)
+ }))
+ };
+ let mut resp = pin!(resp);
+ let mut conn = Some(conn);
+ // Wait for response while driving connection I/O
+ let resp = poll_fn(|cx| match resp.as_mut().poll(cx) {
+ Poll::Ready(r) => Poll::Ready(r),
+ // Response is not ready, poll `hyper` connection to drive I/O if it
+ // has not completed yet.
+ Poll::Pending => {
+ let res = match conn.as_mut() {
+ Some(conn) => ready!(Pin::new(conn).poll(cx)),
+ None => return Poll::Pending,
+ };
+ conn = None;
+ match res {
+ // `hyper` connection has successfully completed, optimistically poll for response
+ Ok(()) => resp.as_mut().poll(cx),
+ // `hyper` connection has failed, return the error
+ Err(err) => Poll::Ready(Err(hyper_request_error(err))),
+ }
+ }
})
+ .await?;
+
+ Ok((resp, async move {
+ if let Some(conn) = conn {
+ conn.await.map_err(hyper_request_error)?;
+ }
+ Ok(())
+ }))
}
diff --git a/crates/wasi-http/src/p2/types.rs b/crates/wasi-http/src/p2/types.rs
index 7018b392d8..4dda336cbd 100644
--- a/crates/wasi-http/src/p2/types.rs
+++ b/crates/wasi-http/src/p2/types.rs
@@ -3,14 +3,13 @@
use crate::FieldMap;
use crate::p2::{
- WasiHttpCtxView, WasiHttpHooks,
+ HttpResult, WasiHttpCtxView, WasiHttpHooks,
bindings::http::types::{self, ErrorCode, Method, Scheme},
body::{HostIncomingBody, HyperIncomingBody, HyperOutgoingBody},
};
use bytes::Bytes;
use http_body_util::BodyExt;
use hyper::body::Body;
-use std::time::Duration;
use wasmtime::component::Resource;
use wasmtime::{Result, bail};
use wasmtime_wasi::p2::Pollable;
@@ -34,18 +33,6 @@ pub(crate) fn remove_forbidden_headers(
}
}
-/// Configuration for an outgoing request.
-pub struct OutgoingRequestConfig {
- /// Whether to use TLS for the request.
- pub use_tls: bool,
- /// The timeout for connecting.
- pub connect_timeout: Duration,
- /// The timeout until the first byte.
- pub first_byte_timeout: Duration,
- /// The timeout between chunks of a streaming body
- pub between_bytes_timeout: Duration,
-}
-
impl From<http::Method> for types::Method {
fn from(method: http::Method) -> Self {
if method == http::Method::GET {
@@ -116,11 +103,7 @@ impl WasiHttpCtxView<'_> {
{
let (mut parts, body) = req.into_parts();
let body = body.map_err(Into::into).boxed_unsync();
- let body = HostIncomingBody::new(
- body,
- // TODO: this needs to be plumbed through
- std::time::Duration::from_millis(600 * 1000),
- );
+ let body = HostIncomingBody::new(body);
let authority = match parts.uri.authority() {
Some(authority) => authority.to_string(),
None => match parts.headers.get(http::header::HOST) {
@@ -236,17 +219,6 @@ pub struct HostOutgoingRequest {
pub body: Option<HyperOutgoingBody>,
}
-/// The concrete type behind a `wasi:http/types.request-options` resource.
-#[derive(Debug, Default)]
-pub struct HostRequestOptions {
- /// How long to wait for a connection to be established.
- pub connect_timeout: Option<std::time::Duration>,
- /// How long to wait for the first byte of the response body.
- pub first_byte_timeout: Option<std::time::Duration>,
- /// How long to wait between frames of the response body.
- pub between_bytes_timeout: Option<std::time::Duration>,
-}
-
/// The concrete type behind a `wasi:http/types.incoming-response` resource.
#[derive(Debug)]
pub struct HostIncomingResponse {
@@ -259,8 +231,7 @@ pub struct HostIncomingResponse {
}
/// A handle to a future incoming response.
-pub type FutureIncomingResponseHandle =
- AbortOnDropJoinHandle<wasmtime::Result<Result<IncomingResponse, types::ErrorCode>>>;
+pub type FutureIncomingResponseHandle = AbortOnDropJoinHandle<SendRequestResult>;
/// A response that is in the process of being received.
#[derive(Debug)]
@@ -269,41 +240,25 @@ pub struct IncomingResponse {
pub resp: hyper::Response<HyperIncomingBody>,
/// Optional worker task that continues to process the response.
pub worker: Option<AbortOnDropJoinHandle<()>>,
- /// The timeout between chunks of the response.
- pub between_bytes_timeout: std::time::Duration,
}
+type SendRequestResult = HttpResult<(http::Response<HyperIncomingBody>, AbortOnDropJoinHandle<()>)>;
+
/// The concrete type behind a `wasi:http/types.future-incoming-response` resource.
-#[derive(Debug)]
pub enum HostFutureIncomingResponse {
/// A pending response
Pending(FutureIncomingResponseHandle),
/// The response is ready.
///
/// An outer error will trap while the inner error gets returned to the guest.
- Ready(wasmtime::Result<Result<IncomingResponse, types::ErrorCode>>),
+ Ready(SendRequestResult),
/// The response has been consumed.
Consumed,
}
impl HostFutureIncomingResponse {
- /// Create a new `HostFutureIncomingResponse` that is pending on the provided task handle.
- pub fn pending(handle: FutureIncomingResponseHandle) -> Self {
- Self::Pending(handle)
- }
-
- /// Create a new `HostFutureIncomingResponse` that is ready.
- pub fn ready(result: wasmtime::Result<Result<IncomingResponse, types::ErrorCode>>) -> Self {
- Self::Ready(result)
- }
-
- /// Returns `true` if the response is ready.
- pub fn is_ready(&self) -> bool {
- matches!(self, Self::Ready(_))
- }
-
/// Unwrap the response, panicking if it is not ready.
- pub fn unwrap_ready(self) -> wasmtime::Result<Result<IncomingResponse, types::ErrorCode>> {
+ pub(crate) fn unwrap_ready(self) -> SendRequestResult {
match self {
Self::Ready(res) => res,
Self::Pending(_) | Self::Consumed => {
diff --git a/crates/wasi-http/src/p2/types_impl.rs b/crates/wasi-http/src/p2/types_impl.rs
index 44d1d5eda2..8c16eaf492 100644
--- a/crates/wasi-http/src/p2/types_impl.rs
+++ b/crates/wasi-http/src/p2/types_impl.rs
@@ -639,19 +639,17 @@ impl types::HostFutureIncomingResponse for WasiHttpCtxView<'_> {
HostFutureIncomingResponse::Ready(_) => {}
}
- let resp =
+ let (resp, io) =
match std::mem::replace(resp, HostFutureIncomingResponse::Consumed).unwrap_ready() {
+ Ok(pair) => pair,
Err(e) => {
// Trapping if it's not possible to downcast to an wasi-http error
- let e = e.downcast::<types::ErrorCode>()?;
+ let e = e.downcast()?;
return Ok(Some(Ok(Err(e))));
}
-
- Ok(Ok(resp)) => resp,
- Ok(Err(e)) => return Ok(Some(Ok(Err(e)))),
};
- let (mut parts, body) = resp.resp.into_parts();
+ let (mut parts, body) = resp.into_parts();
remove_forbidden_headers(self.hooks, &mut parts.headers);
let headers = FieldMap::new_immutable(parts.headers);
@@ -659,10 +657,8 @@ impl types::HostFutureIncomingResponse for WasiHttpCtxView<'_> {
status: parts.status.as_u16(),
headers,
body: Some({
- let mut body = HostIncomingBody::new(body, resp.between_bytes_timeout);
- if let Some(worker) = resp.worker {
- body.retain_worker(worker);
- }
+ let mut body = HostIncomingBody::new(body);
+ body.retain_worker(io);
body
}),
})?;
diff --git a/crates/wasi-http/src/p3/mod.rs b/crates/wasi-http/src/p3/mod.rs
index 34223b8051..eb3bcdf982 100644
--- a/crates/wasi-http/src/p3/mod.rs
+++ b/crates/wasi-http/src/p3/mod.rs
@@ -17,13 +17,13 @@ mod proxy;
mod request;
mod response;
+pub use request::Request;
#[cfg(feature = "default-send-request")]
pub use request::default_send_request;
-pub use request::{Request, RequestOptions};
pub use response::Response;
use crate::p3::bindings::http::types::ErrorCode;
-use crate::{DEFAULT_FORBIDDEN_HEADERS, FieldMapError, WasiHttpCtx};
+use crate::{DEFAULT_FORBIDDEN_HEADERS, FieldMapError, RequestOptions, WasiHttpCtx};
use bindings::http::{client, types};
use bytes::Bytes;
use core::ops::Deref;
diff --git a/crates/wasi-http/src/p3/request.rs b/crates/wasi-http/src/p3/request.rs
index 8bdf9d4b7d..1296f5f10c 100644
--- a/crates/wasi-http/src/p3/request.rs
+++ b/crates/wasi-http/src/p3/request.rs
@@ -1,9 +1,8 @@
use crate::p3::bindings::http::types::ErrorCode;
use crate::p3::body::{Body, BodyExt as _, GuestBody};
use crate::p3::{HttpError, HttpResult, WasiHttpCtxView, WasiHttpView};
-use crate::{FieldMap, get_content_length};
+use crate::{FieldMap, RequestOptions, get_content_length};
use bytes::Bytes;
-use core::time::Duration;
use http::header::HOST;
use http::uri::{Authority, PathAndQuery, Scheme};
use http::{HeaderValue, Method, Uri};
@@ -14,17 +13,6 @@ use tokio::sync::oneshot;
use tracing::debug;
use wasmtime::AsContextMut;
-/// The concrete type behind a `wasi:http/types.request-options` resource.
-#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
-pub struct RequestOptions {
- /// How long to wait for a connection to be established.
- pub connect_timeout: Option<Duration>,
- /// How long to wait for the first byte of the response body.
- pub first_byte_timeout: Option<Duration>,
- /// How long to wait between frames of the response body.
- pub between_bytes_timeout: Option<Duration>,
-}
-
/// The concrete type behind a `wasi:http/types.request` resource.
pub struct Request {
/// The method of the request.
@@ -272,6 +260,7 @@ pub async fn default_send_request(
use core::future::poll_fn;
use core::pin::{Pin, pin};
use core::task::{Poll, ready};
+ use core::time::Duration;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio::net::TcpStream;
diff --git a/crates/wasi-http/src/request_options.rs b/crates/wasi-http/src/request_options.rs
new file mode 100644
index 0000000000..a1dff1e922
--- /dev/null
+++ b/crates/wasi-http/src/request_options.rs
@@ -0,0 +1,12 @@
+use std::time::Duration;
+
+/// The concrete type behind a `wasi:http/types.request-options` resource.
+#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
+pub struct RequestOptions {
+ /// How long to wait for a connection to be established.
+ pub connect_timeout: Option<Duration>,
+ /// How long to wait for the first byte of the response body.
+ pub first_byte_timeout: Option<Duration>,
+ /// How long to wait between frames of the response body.
+ pub between_bytes_timeout: Option<Duration>,
+}
diff --git a/crates/wasi-http/tests/all/p2.rs b/crates/wasi-http/tests/all/p2.rs
index e9b59e3f0b..7702d053be 100644
--- a/crates/wasi-http/tests/all/p2.rs
+++ b/crates/wasi-http/tests/all/p2.rs
@@ -15,16 +15,18 @@ use wasmtime::{
};
use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView, p2::pipe::MemoryOutputPipe};
use wasmtime_wasi_http::{
- WasiHttpCtx,
+ RequestOptions, WasiHttpCtx,
io::TokioIo,
p2::bindings::http::types::{ErrorCode, Scheme},
p2::body::HyperOutgoingBody,
- p2::types::{HostFutureIncomingResponse, IncomingResponse, OutgoingRequestConfig},
p2::{HttpResult, WasiHttpCtxView, WasiHttpHooks, WasiHttpView},
};
type RequestSender = Arc<
- dyn Fn(hyper::Request<HyperOutgoingBody>, OutgoingRequestConfig) -> HostFutureIncomingResponse
+ dyn Fn(
+ hyper::Request<HyperOutgoingBody>,
+ Option<RequestOptions>,
+ ) -> HttpResult<http::Response<HyperOutgoingBody>>
+ Send
+ Sync,
>;
@@ -38,6 +40,7 @@ struct Ctx {
hooks: MyHttpHooks,
}
+#[derive(Clone)]
struct MyHttpHooks {
send_request: Option<RequestSender>,
rejected_authority: Option<String>,
@@ -66,21 +69,35 @@ impl WasiHttpHooks for MyHttpHooks {
fn send_request(
&mut self,
request: hyper::Request<HyperOutgoingBody>,
- config: OutgoingRequestConfig,
- ) -> HttpResult<HostFutureIncomingResponse> {
- if let Some(rejected_authority) = &self.rejected_authority {
- let authority = request.uri().authority().map(ToString::to_string).unwrap();
- if &authority == rejected_authority {
- return Err(ErrorCode::HttpRequestDenied.into());
+ config: Option<RequestOptions>,
+ ) -> Box<
+ dyn Future<
+ Output = HttpResult<(
+ http::Response<HyperOutgoingBody>,
+ Box<dyn Future<Output = Result<(), ErrorCode>> + Send>,
+ )>,
+ > + Send,
+ > {
+ let me = self.clone();
+ Box::new(async move {
+ if let Some(rejected_authority) = &me.rejected_authority {
+ let authority = request.uri().authority().map(ToString::to_string).unwrap();
+ if &authority == rejected_authority {
+ return Err(ErrorCode::HttpRequestDenied.into());
+ }
}
- }
- if let Some(send_request) = self.send_request.clone() {
- Ok(send_request(request, config))
- } else {
- Ok(wasmtime_wasi_http::p2::default_send_request(
- request, config,
- ))
- }
+ if let Some(send_request) = me.send_request.clone() {
+ let res = send_request(request, config)?;
+ Ok((
+ res.map(BodyExt::boxed_unsync),
+ Box::new(async { Ok(()) }) as Box<dyn Future<Output = _> + Send>,
+ ))
+ } else {
+ let (res, io) =
+ wasmtime_wasi_http::p2::default_send_request(request, config).await?;
+ Ok((res.map(BodyExt::boxed_unsync), Box::new(io)))
+ }
+ })
}
fn is_forbidden_header(&mut self, name: &hyper::header::HeaderName) -> bool {
@@ -292,37 +309,29 @@ async fn do_wasi_http_hash_all(override_send_request: bool) -> Result<()> {
move |request: http::request::Parts| {
if let (Method::GET, Some(body)) = (request.method, bodies.get(request.uri.path())) {
- Ok::<_, wasmtime::Error>(hyper::Response::new(body::full(Bytes::copy_from_slice(
+ Ok(hyper::Response::new(body::full(Bytes::copy_from_slice(
body.as_bytes(),
))))
} else {
Ok(hyper::Response::builder()
.status(StatusCode::METHOD_NOT_ALLOWED)
- .body(body::empty())?)
+ .body(body::empty())
+ .map_err(wasmtime_wasi_http::p2::http_request_error)?)
}
}
};
let send_request = if override_send_request {
- Some(Arc::new(
- move |request: hyper::Request<HyperOutgoingBody>,
- OutgoingRequestConfig {
- between_bytes_timeout,
- ..
- }| {
- let response = handle(request.into_parts().0).map(|resp| {
- Ok(IncomingResponse {
- resp: resp.map(|body| {
- body.map_err(wasmtime_wasi_http::p2::hyper_response_error)
- .boxed_unsync()
- }),
- worker: None,
- between_bytes_timeout,
+ Some(
+ Arc::new(move |request: hyper::Request<HyperOutgoingBody>, _opts| {
+ handle(request.into_parts().0).map(|resp| {
+ resp.map(|body| {
+ body.map_err(wasmtime_wasi_http::p2::hyper_response_error)
+ .boxed_unsync()
})
- });
- HostFutureIncomingResponse::ready(response)
- },
- ) as RequestSender)
+ })
+ }) as RequestSender,
+ )
} else {
let server = async move {
loop {
@@ -579,32 +588,23 @@ async fn wasi_http_without_port() -> Result<()> {
// Intercept the outgoing request to verify the authority has no port and
// return a synthetic response. This avoids depending on external network.
- let send_request: RequestSender = Arc::new(
- |request: hyper::Request<HyperOutgoingBody>,
- OutgoingRequestConfig {
- between_bytes_timeout,
- ..
- }| {
+ let send_request: RequestSender =
+ Arc::new(|request: hyper::Request<HyperOutgoingBody>, _opts| {
let authority = request.uri().authority().expect("request has authority");
assert!(
authority.port().is_none(),
"expected no port in authority, got: {authority}"
);
- let resp = Ok(Ok(IncomingResponse {
- resp: hyper::Response::builder()
- .status(StatusCode::OK)
- .body(
- body::full(Bytes::from("ok"))
- .map_err(wasmtime_wasi_http::p2::hyper_response_error)
- .boxed_unsync(),
- )
- .unwrap(),
- worker: None,
- between_bytes_timeout,
- }));
- HostFutureIncomingResponse::ready(resp)
- },
- );
+ let resp = hyper::Response::builder()
+ .status(StatusCode::OK)
+ .body(
+ body::full(Bytes::from("ok"))
+ .map_err(wasmtime_wasi_http::p2::hyper_response_error)
+ .boxed_unsync(),
+ )
+ .unwrap();
+ Ok(resp)
+ });
let response = run_wasi_http(
test_programs_artifacts::P2_API_PROXY_FORWARD_REQUEST_COMPONENT,
diff --git a/crates/wasi-http/tests/all/p3/mod.rs b/crates/wasi-http/tests/all/p3/mod.rs
index 532cbfd80d..58aed0fb18 100644
--- a/crates/wasi-http/tests/all/p3/mod.rs
+++ b/crates/wasi-http/tests/all/p3/mod.rs
@@ -21,10 +21,8 @@ use wasmtime_wasi::p3::bindings::Command;
use wasmtime_wasi::{TrappableError, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
use wasmtime_wasi_http::p3::bindings::Service;
use wasmtime_wasi_http::p3::bindings::http::types::ErrorCode;
-use wasmtime_wasi_http::p3::{
- self, Request, RequestOptions, WasiHttpCtxView, WasiHttpHooks, WasiHttpView,
-};
-use wasmtime_wasi_http::{DEFAULT_FORBIDDEN_HEADERS, WasiHttpCtx};
+use wasmtime_wasi_http::p3::{self, Request, WasiHttpCtxView, WasiHttpHooks, WasiHttpView};
+use wasmtime_wasi_http::{DEFAULT_FORBIDDEN_HEADERS, RequestOptions, WasiHttpCtx};
foreach_p3_http!(assert_test_exists);