Skip to content

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

Unify more of the p2/p3 paths in the wasmtime-wasi-http crate (#13812)

Alex Crichton41a902e50fcb
diff --git a/Cargo.lock b/Cargo.lock
index 7b79b05cad..6bfe33539d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5213,6 +5213,7 @@ dependencies = [
"http-body",
"http-body-util",
"hyper",
+ "pin-project-lite",
"rustls",
"sha2",
"tempfile",
diff --git a/crates/c-api/src/store.rs b/crates/c-api/src/store.rs
index 7d5c65b099..44f8c673ee 100644
--- a/crates/c-api/src/store.rs
+++ b/crates/c-api/src/store.rs
@@ -107,15 +107,15 @@ impl wasmtime_wasi::WasiView for WasmtimeStoreData {
}
#[cfg(all(feature = "component-model", feature = "wasi-http"))]
-impl wasmtime_wasi_http::p2::WasiHttpView for WasmtimeStoreData {
- fn http(&mut self) -> wasmtime_wasi_http::p2::WasiHttpCtxView<'_> {
+impl wasmtime_wasi_http::WasiHttpView for WasmtimeStoreData {
+ fn http(&mut self) -> wasmtime_wasi_http::WasiHttpCtxView<'_> {
use wasmtime_wasi::WasiView;
let ctx = self.wasi_http.as_mut().unwrap();
let table = self.wasi.as_mut().unwrap().ctx().table;
- wasmtime_wasi_http::p2::WasiHttpCtxView {
+ wasmtime_wasi_http::WasiHttpCtxView {
ctx,
table,
- hooks: wasmtime_wasi_http::p2::default_hooks(),
+ hooks: wasmtime_wasi_http::default_hooks(),
}
}
}
diff --git a/crates/wasi-http/Cargo.toml b/crates/wasi-http/Cargo.toml
index 79942ec5f1..5ec07df25c 100644
--- a/crates/wasi-http/Cargo.toml
+++ b/crates/wasi-http/Cargo.toml
@@ -42,6 +42,7 @@ wasmtime = { workspace = true, features = ['component-model'] }
tokio-rustls = { workspace = true, optional = true }
rustls = { workspace = true, optional = true }
webpki-roots = { workspace = true, optional = true }
+pin-project-lite = { workspace = true }
[dev-dependencies]
wasmtime-wasi-http = { path = ".", features = ['default-send-request'] }
diff --git a/crates/wasi-http/src/ctx.rs b/crates/wasi-http/src/ctx.rs
index 0ae1a9678e..c5baf3b33a 100644
--- a/crates/wasi-http/src/ctx.rs
+++ b/crates/wasi-http/src/ctx.rs
@@ -1,3 +1,114 @@
+#[cfg(feature = "p2")]
+use crate::p2::bindings::http::types as p2;
+#[cfg(feature = "p3")]
+use crate::p3::bindings::http::types as p3;
+use crate::{DEFAULT_FORBIDDEN_HEADERS, Error, RequestOptions, Result};
+use bytes::Bytes;
+use http::{HeaderName, uri::Scheme};
+use http_body_util::combinators::UnsyncBoxBody;
+use wasmtime::component::{HasData, ResourceTable};
+
+/// A helper struct which implements [`HasData`] for the `wasi:http` APIs.
+///
+/// This can be useful when directly calling `add_to_linker` functions directly,
+/// such as [`wasmtime_wasi_http::p3::bindings::http::types::add_to_linker`] as
+/// the `D` type parameter. See [`HasData`] for more information about the type
+/// parameter's purpose.
+///
+/// When using this type you can skip the [`WasiHttpView`] trait, for example.
+///
+/// [`wasmtime_wasi_http::p3::bindings::http::types::add_to_linker`]: crate::p3::bindings::http::types::add_to_linker
+///
+/// # Examples
+///
+/// ```
+/// use wasmtime::component::Linker;
+/// use wasmtime::{Engine, Result};
+/// use wasmtime_wasi_http::{WasiHttp, WasiHttpCtxView};
+///
+/// struct MyStoreState {
+/// // ...
+/// }
+///
+/// impl MyStoreState {
+/// fn http(&mut self) -> WasiHttpCtxView<'_> {
+/// // ...
+/// # todo!()
+/// }
+/// }
+///
+/// fn main() -> Result<()> {
+/// let engine = Engine::default();
+/// let mut linker = Linker::new(&engine);
+///
+/// wasmtime_wasi_http::p3::bindings::http::types::add_to_linker::<MyStoreState, WasiHttp>(
+/// &mut linker,
+/// |state| state.http(),
+/// )?;
+/// Ok(())
+/// }
+/// ```
+pub struct WasiHttp;
+
+impl HasData for WasiHttp {
+ type Data<'a> = WasiHttpCtxView<'a>;
+}
+
+/// A trait which provides internal WASI HTTP state.
+///
+/// This trait is used by the [`add_to_linker`] convenience functions of this
+/// crate. This trait can be implemented for the `T` in `Store<T>` to provide
+/// access to wasi:http information at runtime.
+///
+/// [`add_to_linker`]: crate::p3::add_to_linker
+///
+/// # Example
+///
+/// ```
+/// use wasmtime::component::ResourceTable;
+/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView, WasiHttpCtxView};
+///
+/// struct MyState {
+/// http_ctx: WasiHttpCtx,
+/// table: ResourceTable,
+/// }
+///
+/// impl WasiHttpView for MyState {
+/// fn http(&mut self) -> WasiHttpCtxView<'_> {
+/// WasiHttpCtxView {
+/// ctx: &mut self.http_ctx,
+/// table: &mut self.table,
+/// hooks: Default::default(),
+/// }
+/// }
+/// }
+/// ```
+pub trait WasiHttpView: Send {
+ /// Return a [WasiHttpCtxView] from mutable reference to self.
+ fn http(&mut self) -> WasiHttpCtxView<'_>;
+}
+
+/// Basis of implementation of all `wasi:http` APIs in this crate.
+///
+/// This type provides a temporary view into information such as a WASI
+/// resource table, HTTP context information, and embedder-provided hooks if
+/// so desired. THe fields in this structure are typically stored within the
+/// `T` of `Store<T>` and this struct borrows from there. All `Host` traits
+/// generated by `bindgen!` are implemented for this type.
+pub struct WasiHttpCtxView<'a> {
+ /// Mutable reference to the WASI HTTP hooks.
+ ///
+ /// Note that [`default_hooks`] or [`Default::default()`] can be used if
+ /// you don't want or need to customize this.
+ pub hooks: &'a mut dyn WasiHttpHooks,
+
+ /// Mutable reference to table used to manage resources.
+ pub table: &'a mut ResourceTable,
+
+ /// Mutable reference to the WASI HTTP context.
+ pub ctx: &'a mut WasiHttpCtx,
+}
+
/// Default maximum size for the contents of a fields resource.
///
/// Typically, HTTP proxies limit headers to 8k. This number is higher than that
@@ -39,3 +150,250 @@ impl Default for WasiHttpCtx {
Self::new()
}
}
+
+/// Convenience type definition for the bodies used in this crate.
+pub type WasiBody = UnsyncBoxBody<Bytes, Error>;
+
+/// A trait which provides hooks into internal WASI HTTP operations.
+///
+/// Note that when using this type if state is needed to implement the methods
+/// the state will need to be stored separately in a distinct structure to
+/// implement this trait as the same type can't implement both [`WasiHttpView`]
+/// and [`WasiHttpHooks`] and be usable.
+///
+/// # Example
+///
+/// ```
+/// use wasmtime::component::ResourceTable;
+/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView, WasiHttpCtxView, WasiHttpHooks};
+///
+/// struct MyState {
+/// http_ctx: WasiHttpCtx,
+/// table: ResourceTable,
+/// hooks: MyHooks,
+/// }
+///
+/// impl MyState {
+/// fn new() -> MyState {
+/// MyState {
+/// table: ResourceTable::new(),
+/// http_ctx: WasiHttpCtx::new(),
+/// hooks: MyHooks,
+/// }
+/// }
+/// }
+///
+/// impl WasiHttpView for MyState {
+/// fn http(&mut self) -> WasiHttpCtxView<'_> {
+/// WasiHttpCtxView {
+/// ctx: &mut self.http_ctx,
+/// table: &mut self.table,
+/// hooks: &mut self.hooks,
+/// }
+/// }
+/// }
+///
+/// struct MyHooks;
+///
+/// impl WasiHttpHooks for MyHooks {
+/// fn is_forbidden_header(&mut self, name: &http::HeaderName) -> bool {
+/// *name == http::header::AUTHORIZATION ||
+/// wasmtime_wasi_http::DEFAULT_FORBIDDEN_HEADERS.contains(name)
+/// }
+/// }
+/// ```
+pub trait WasiHttpHooks: Send {
+ /// Whether a given header should be considered forbidden and not allowed.
+ fn is_forbidden_header(&mut self, name: &HeaderName) -> bool {
+ DEFAULT_FORBIDDEN_HEADERS.contains(name)
+ }
+
+ /// Whether a given scheme should be considered supported.
+ ///
+ /// `handle` will return [Error::HttpProtocolError] for unsupported schemes.
+ fn is_supported_scheme(&mut self, scheme: &Scheme) -> bool {
+ *scheme == Scheme::HTTP || *scheme == Scheme::HTTPS
+ }
+
+ /// Whether to set `host` header in the request passed to `send_request`.
+ fn set_host_header(&mut self) -> bool {
+ true
+ }
+
+ /// Scheme to default to, when not set by the guest.
+ ///
+ /// If [None], `handle` will return [Error::HttpProtocolError]
+ /// for requests missing a scheme.
+ fn default_scheme(&mut self) -> Option<Scheme> {
+ Some(Scheme::HTTPS)
+ }
+
+ /// Send an outgoing request.
+ ///
+ /// This function will be used by the `wasi:http/handler#handle` implementation.
+ ///
+ /// The specified [Future] `fut` will be used to communicate
+ /// a response processing error, if any.
+ /// For example, if the response body is consumed via `wasi:http/types.response#consume-body`,
+ /// a result will be sent on `fut`.
+ ///
+ /// The returned [Future] can be used to communicate
+ /// a request processing error, if any, to the constructor of the request.
+ /// For example, if the request was constructed via `wasi:http/types.request#new`,
+ /// a result resolved from it will be forwarded to the guest on the future handle returned.
+ ///
+ /// `Content-Length` of the request passed to this function will be validated, however no
+ /// `Content-Length` validation will be performed for the received response.
+ #[cfg(feature = "default-send-request")]
+ fn send_request(
+ &mut self,
+ request: http::Request<WasiBody>,
+ options: Option<RequestOptions>,
+ fut: Box<dyn Future<Output = Result<(), Error>> + Send>,
+ ) -> Box<
+ dyn Future<
+ Output = Result<(
+ http::Response<WasiBody>,
+ Box<dyn Future<Output = Result<(), Error>> + Send>,
+ )>,
+ > + Send,
+ > {
+ _ = fut;
+ Box::new(async move {
+ use http_body_util::BodyExt;
+
+ let (res, io) = crate::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.
+ ///
+ /// This function will be used by the `wasi:http/handler#handle` implementation.
+ ///
+ /// The specified [Future] `fut` will be used to communicate
+ /// a response processing error, if any.
+ /// For example, if the response body is consumed via `wasi:http/types.response#consume-body`,
+ /// a result will be sent on `fut`.
+ ///
+ /// The returned [Future] can be used to communicate
+ /// a request processing error, if any, to the constructor of the request.
+ /// For example, if the request was constructed via `wasi:http/types.request#new`,
+ /// a result resolved from it will be forwarded to the guest on the future handle returned.
+ ///
+ /// `Content-Length` of the request passed to this function will be validated, however no
+ /// `Content-Length` validation will be performed for the received response.
+ #[cfg(not(feature = "default-send-request"))]
+ fn send_request(
+ &mut self,
+ request: http::Request<WasiBody>,
+ options: Option<RequestOptions>,
+ fut: Box<dyn Future<Output = Result<(), Error>> + Send>,
+ ) -> Box<
+ dyn Future<
+ Output = Result<(
+ http::Response<WasiBody>,
+ Box<dyn Future<Output = Result<(), Error>> + Send>,
+ )>,
+ > + Send,
+ >;
+
+ /// Number of distinct write calls to the outgoing body's output-stream
+ /// that the implementation will buffer.
+ /// Default: 1.
+ #[cfg(feature = "p2")]
+ fn p2_outgoing_body_buffer_chunks(&mut self) -> usize {
+ crate::p2::DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS
+ }
+
+ /// Maximum size allowed in a write call to the outgoing body's
+ /// output-stream. Default: 1024 * 1024.
+ #[cfg(feature = "p2")]
+ fn p2_outgoing_body_chunk_size(&mut self) -> usize {
+ crate::p2::DEFAULT_OUTGOING_BODY_CHUNK_SIZE
+ }
+
+ /// Optional hook to configure the error code for hyper errors.
+ #[cfg(feature = "p2")]
+ fn p2_error_from_hyper(&mut self, err: &hyper::Error) -> p2::ErrorCode {
+ tracing::warn!("hyper error: {err:?}");
+ p2::ErrorCode::HttpProtocolError
+ }
+
+ /// Optional hook to configure the error code for connect I/O errors.
+ #[cfg(feature = "p2")]
+ fn p2_error_from_connect(&mut self, err: &std::io::Error) -> p2::ErrorCode {
+ tracing::warn!("connect error: {err:?}");
+ p2::ErrorCode::ConnectionRefused
+ }
+
+ /// Optional hook to configure the error code for TLS I/O errors.
+ #[cfg(feature = "p2")]
+ fn p2_error_from_tls(&mut self, err: &std::io::Error) -> p2::ErrorCode {
+ tracing::warn!("tls error: {err:?}");
+ p2::ErrorCode::TlsProtocolError
+ }
+
+ /// Optional hook to configure the error code for DNS errors.
+ #[cfg(all(feature = "p2", feature = "default-send-request"))]
+ fn p2_error_from_dns(&mut self, err: &rustls::pki_types::InvalidDnsNameError) -> p2::ErrorCode {
+ tracing::warn!("dns lookup error: {err:?}");
+ p2::ErrorCode::DnsError(p2::DnsErrorPayload {
+ rcode: Some("invalid dns name".to_string()),
+ info_code: None,
+ })
+ }
+
+ /// Optional hook to configure the error code for hyper errors.
+ #[cfg(feature = "p3")]
+ fn p3_error_from_hyper(&mut self, err: &hyper::Error) -> p3::ErrorCode {
+ tracing::warn!("hyper error: {err:?}");
+ p3::ErrorCode::HttpProtocolError
+ }
+
+ /// Optional hook to configure the error code for connect I/O errors.
+ #[cfg(feature = "p3")]
+ fn p3_error_from_connect(&mut self, err: &std::io::Error) -> p3::ErrorCode {
+ tracing::warn!("connect error: {err:?}");
+ p3::ErrorCode::ConnectionRefused
+ }
+
+ /// Optional hook to configure the error code for TLS I/O errors.
+ #[cfg(feature = "p3")]
+ fn p3_error_from_tls(&mut self, err: &std::io::Error) -> p3::ErrorCode {
+ tracing::warn!("tls error: {err:?}");
+ p3::ErrorCode::TlsProtocolError
+ }
+
+ /// Optional hook to configure the error code for DNS errors.
+ #[cfg(all(feature = "p3", feature = "default-send-request"))]
+ fn p3_error_from_dns(&mut self, err: &rustls::pki_types::InvalidDnsNameError) -> p3::ErrorCode {
+ tracing::warn!("dns lookup error: {err:?}");
+ p3::ErrorCode::DnsError(p3::DnsErrorPayload {
+ rcode: Some("invalid dns name".to_string()),
+ info_code: None,
+ })
+ }
+}
+
+/// Returns a value suitable for the `WasiHttpCtxView::hooks` field which has
+/// the default behavior for `wasi:http`.
+#[cfg(feature = "default-send-request")]
+pub fn default_hooks() -> &'static mut dyn WasiHttpHooks {
+ Default::default()
+}
+
+#[cfg(feature = "default-send-request")]
+impl<'a> Default for &'a mut dyn WasiHttpHooks {
+ fn default() -> Self {
+ let x: &mut [(); 0] = &mut [];
+ x
+ }
+}
+
+#[doc(hidden)]
+#[cfg(feature = "default-send-request")]
+impl WasiHttpHooks for [(); 0] {}
diff --git a/crates/wasi-http/src/default_send_request.rs b/crates/wasi-http/src/default_send_request.rs
new file mode 100644
index 0000000000..afed96215e
--- /dev/null
+++ b/crates/wasi-http/src/default_send_request.rs
@@ -0,0 +1,260 @@
+use crate::{Error, RequestOptions};
+use bytes::Bytes;
+use core::future::poll_fn;
+use core::pin::{Pin, pin};
+use core::task::{Poll, ready};
+use http::uri::Scheme;
+use http::{Request, Response};
+use http_body::Body;
+use std::time::Duration;
+use tokio::io::{AsyncRead, AsyncWrite};
+use tokio::net::TcpStream;
+
+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 {}
+
+/// The default implementation of how an outgoing request is sent.
+///
+/// This implementation is used by the `wasi:http/handler` interface
+/// default implementation.
+///
+/// The returned [Future] can be used to communicate
+/// a request processing error, if any, to the constructor of the request.
+/// For example, if the request was constructed via `wasi:http/types.request#new`,
+/// a result resolved from it will be forwarded to the guest on the future handle returned.
+///
+/// This function performs no `Content-Length` validation.
+pub async fn default_send_request(
+ mut req: Request<impl Body<Data = Bytes, Error = Error> + Send + 'static>,
+ options: Option<RequestOptions>,
+) -> Result<
+ (
+ Response<impl Body<Data = Bytes, Error = Error>>,
+ impl Future<Output = Result<(), Error>> + Send,
+ ),
+ Error,
+> {
+ let uri = req.uri();
+ let authority = uri.authority().ok_or(Error::HttpRequestUriInvalid)?;
+ let use_tls = uri.scheme() == Some(&Scheme::HTTPS);
+ let authority = if authority.port().is_some() {
+ authority.to_string()
+ } else {
+ let port = if use_tls { 443 } else { 80 };
+ format!("{authority}:{port}")
+ };
+
+ let connect_timeout = options
+ .and_then(|r| r.connect_timeout)
+ .unwrap_or(Duration::from_secs(600));
+
+ let first_byte_timeout = options
+ .and_then(|r| r.first_byte_timeout)
+ .unwrap_or(Duration::from_secs(600));
+
+ let between_bytes_timeout = options
+ .and_then(|r| r.between_bytes_timeout)
+ .unwrap_or(Duration::from_secs(600));
+
+ let stream = match tokio::time::timeout(connect_timeout, TcpStream::connect(&authority)).await {
+ Ok(stream) => stream.map_err(Error::Connect)?,
+ Err(..) => return Err(Error::ConnectionTimeout),
+ };
+ 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(),
+ };
+ let config = rustls::ClientConfig::builder()
+ .with_root_certificates(root_cert_store)
+ .with_no_client_auth();
+ let connector = tokio_rustls::TlsConnector::from(std::sync::Arc::new(config));
+ let domain = tls_server_name(&authority)?;
+ let stream = connector
+ .connect(domain, stream)
+ .await
+ .map_err(Error::Tls)?;
+ stream.boxed()
+ } else {
+ stream.boxed()
+ };
+ let (mut sender, conn) = tokio::time::timeout(
+ connect_timeout,
+ // TODO: we should plumb the builder through the http context, and use it here
+ hyper::client::conn::http1::Builder::new().handshake(crate::io::TokioIo::new(stream)),
+ )
+ .await
+ .map_err(|_| Error::ConnectionTimeout)??;
+
+ // 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
+ *req.uri_mut() = http::Uri::builder()
+ .path_and_query(
+ req.uri()
+ .path_and_query()
+ .map(|p| p.as_str())
+ .unwrap_or("/"),
+ )
+ .build()
+ .expect("comes from valid request");
+
+ let send = async move {
+ use core::task::Context;
+
+ /// Wrapper around [hyper::body::Incoming] used to
+ /// account for request option timeout configuration
+ struct IncomingResponseBody {
+ incoming: hyper::body::Incoming,
+ timeout: tokio::time::Interval,
+ }
+ impl http_body::Body for IncomingResponseBody {
+ type Data = <hyper::body::Incoming as http_body::Body>::Data;
+ type Error = Error;
+
+ fn poll_frame(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ ) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
+ match Pin::new(&mut self.as_mut().incoming).poll_frame(cx) {
+ Poll::Ready(None) => Poll::Ready(None),
+ Poll::Ready(Some(Err(err))) => {
+ let err = if err.is_timeout() {
+ Error::HttpResponseTimeout
+ } else {
+ Error::from(err)
+ };
+ Poll::Ready(Some(Err(err)))
+ }
+ Poll::Ready(Some(Ok(frame))) => {
+ self.timeout.reset();
+ Poll::Ready(Some(Ok(frame)))
+ }
+ Poll::Pending => {
+ ready!(self.timeout.poll_tick(cx));
+ Poll::Ready(Some(Err(Error::ConnectionReadTimeout)))
+ }
+ }
+ }
+ fn is_end_stream(&self) -> bool {
+ self.incoming.is_end_stream()
+ }
+ fn size_hint(&self) -> http_body::SizeHint {
+ self.incoming.size_hint()
+ }
+ }
+
+ let res = tokio::time::timeout(first_byte_timeout, sender.send_request(req))
+ .await
+ .map_err(|_| Error::ConnectionReadTimeout)?
+ .map_err(Error::from)?;
+ let mut timeout = tokio::time::interval(between_bytes_timeout);
+ timeout.reset();
+ Ok(res.map(|incoming| IncomingResponseBody { incoming, timeout }))
+ };
+ let mut send = pin!(send);
+ let mut conn = Some(conn);
+ // Wait for response while driving connection I/O
+ let res = poll_fn(|cx| match send.as_mut().poll(cx) {
+ Poll::Ready(Ok(res)) => Poll::Ready(Ok(res)),
+ Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
+ Poll::Pending => {
+ // Response is not ready, poll `hyper` connection to drive I/O if it has not completed yet
+ let Some(fut) = conn.as_mut() else {
+ // `hyper` connection already completed
+ return Poll::Pending;
+ };
+ let res = ready!(Pin::new(fut).poll(cx));
+ // `hyper` connection completed, record that to prevent repeated poll
+ conn = None;
+ match res {
+ // `hyper` connection has successfully completed, optimistically poll for response
+ Ok(()) => send.as_mut().poll(cx),
+ // `hyper` connection has failed, return the error
+ Err(err) => Poll::Ready(Err(Error::from(err))),
+ }
+ }
+ })
+ .await?;
+ Ok((res, async move {
+ let Some(conn) = conn.take() else {
+ // `hyper` connection has already completed
+ return Ok(());
+ };
+ if let Err(err) = conn.await {
+ if err.is_timeout() {
+ return Err(Error::HttpResponseTimeout);
+ }
+ return Err(err.into());
+ }
+ Ok(())
+ }))
+}
+
+/// Resolve the rustls [`ServerName`] used for TLS certificate verification from
+/// an outbound request `authority`.
+///
+/// `authority` is in `host:port` form, where an IPv6 `host` is wrapped in
+/// brackets (for example `[::1]:443`). An IP literal is recognized by parsing
+/// the whole authority as a [`SocketAddr`]; this handles the bracketed IPv6
+/// form, which splitting on the first `:` would truncate. Anything else is
+/// treated as a host name, with the port stripped off before it is handed to
+/// rustls.
+///
+/// [`ServerName`]: rustls::pki_types::ServerName
+/// [`SocketAddr`]: std::net::SocketAddr
+pub(crate) fn tls_server_name(
+ authority: &str,
+) -> Result<rustls::pki_types::ServerName<'static>, rustls::pki_types::InvalidDnsNameError> {
+ use rustls::pki_types::ServerName;
+
+ if let Ok(addr) = authority.parse::<std::net::SocketAddr>() {
+ return Ok(ServerName::from(addr.ip()));
+ }
+ let host = match authority.split_once(':') {
+ Some((host, _port)) => host,
+ None => authority,
+ };
+ Ok(ServerName::try_from(host)?.to_owned())
+}
+
+#[cfg(test)]
+mod tls_server_name_tests {
+ use super::tls_server_name;
+ use rustls::pki_types::ServerName;
+
+ #[test]
+ fn resolves_server_name_from_authority() {
+ // Host names keep their host and drop the port.
+ assert_eq!(
+ tls_server_name("example.com:443").unwrap(),
+ ServerName::try_from("example.com").unwrap()
+ );
+ assert_eq!(
+ tls_server_name("example.com").unwrap(),
+ ServerName::try_from("example.com").unwrap()
+ );
+
+ // IP literals resolve to an `IpAddress` server name. The bracketed IPv6
+ // form must not be truncated at the first `:`.
+ assert_eq!(
+ tls_server_name("127.0.0.1:80").unwrap(),
+ ServerName::from(std::net::Ipv4Addr::LOCALHOST)
+ );
+ assert_eq!(
+ tls_server_name("[::1]:443").unwrap(),
+ ServerName::from(std::net::Ipv6Addr::LOCALHOST)
+ );
+ assert_eq!(
+ tls_server_name("[2001:db8::1]:8443").unwrap(),
+ ServerName::from("2001:db8::1".parse::<std::net::Ipv6Addr>().unwrap())
+ );
+ }
+}
diff --git a/crates/wasi-http/src/error.rs b/crates/wasi-http/src/error.rs
new file mode 100644
index 0000000000..ac85e32be7
--- /dev/null
+++ b/crates/wasi-http/src/error.rs
@@ -0,0 +1,267 @@
+use std::fmt;
+use std::io;
+
+/// Error type for `wasi:http` embedder interactions.
+///
+/// This error type is a superset of the wasip2/wasip3 error types for example
+/// and is the error that the embedder interacts with for all operations.
+#[derive(Debug)]
+#[non_exhaustive]
+#[expect(missing_docs, reason = "too cluttered")]
+pub enum Error {
+ Hyper(hyper::Error),
+ Connect(io::Error),
+ Tls(io::Error),
+ #[cfg(feature = "default-send-request")]
+ InvalidDnsNameError(rustls::pki_types::InvalidDnsNameError),
+ HttpRequestBodySize(Option<u64>),
+
+ DnsTimeout,
+ DnsError {
+ rcode: Option<String>,
+ info_code: Option<u16>,
+ },
+ DestinationNotFound,
+ DestinationUnavailable,
+ DestinationIpProhibited,
+ DestinationIpUnroutable,
+ ConnectionRefused,
+ ConnectionTerminated,
+ ConnectionTimeout,
+ ConnectionReadTimeout,
+ ConnectionWriteTimeout,
+ ConnectionLimitReached,
+ TlsProtocolError,
+ TlsCertificateError,
+ TlsAlertReceived {
+ alert_id: Option<u8>,
+ alert_message: Option<String>,
+ },
+ HttpRequestDenied,
+ HttpRequestLengthRequired,
+ HttpRequestMethodInvalid,
+ HttpRequestUriInvalid,
+ HttpRequestUriTooLong,
+ HttpRequestHeaderSectionSize(Option<u32>),
+ HttpRequestHeaderSize {
+ field_name: Option<String>,
+ field_size: Option<u32>,
+ },
+ HttpRequestTrailerSectionSize(Option<u32>),
+ HttpRequestTrailerSize {
+ field_name: Option<String>,
+ field_size: Option<u32>,
+ },
+ HttpResponseIncomplete,
+ HttpResponseHeaderSectionSize(Option<u32>),
+ HttpResponseHeaderSize {
+ field_name: Option<String>,
+ field_size: Option<u32>,
+ },
+ HttpResponseBodySize(Option<u64>),
+ HttpResponseTrailerSectionSize(Option<u32>),
+ HttpResponseTrailerSize {
+ field_name: Option<String>,
+ field_size: Option<u32>,
+ },
+ HttpResponseTransferCoding(Option<String>),
+ HttpResponseContentCoding(Option<String>),
+ HttpResponseTimeout,
+ HttpUpgradeFailed,
+ HttpProtocolError,
+ LoopDetected,
+ ConfigurationError,
+ InternalError(Option<String>),
+}
+
+/// Convenience type for a result with [`Error`]
+pub type Result<T, E = Error> = std::result::Result<T, E>;
+
+impl From<hyper::Error> for Error {
+ fn from(err: hyper::Error) -> Self {
+ Self::Hyper(err)
+ }
+}
+
+impl From<std::convert::Infallible> for Error {
+ fn from(e: std::convert::Infallible) -> Self {
+ match e {}
+ }
+}
+
+#[cfg(feature = "default-send-request")]
+impl From<rustls::pki_types::InvalidDnsNameError> for Error {
+ fn from(err: rustls::pki_types::InvalidDnsNameError) -> Self {
+ Self::InvalidDnsNameError(err)
+ }
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Hyper(err) => write!(f, "hyper error: {err}"),
+ Self::Connect(err) => write!(f, "connection error: {err}"),
+ Self::Tls(err) => write!(f, "TLS error: {err}"),
+ #[cfg(feature = "default-send-request")]
+ Self::InvalidDnsNameError(err) => write!(f, "invalid DNS name: {err}"),
+ Self::HttpRequestBodySize(None) => {
+ write!(f, "HTTP request body size exceeds limit")
+ }
+ Self::HttpRequestBodySize(Some(size)) => {
+ write!(f, "HTTP request body size exceeds limit: {size} bytes")
+ }
+ Self::DnsTimeout => write!(f, "DNS lookup timed out"),
+ Self::DnsError { rcode, info_code } => {
+ write!(f, "DNS error")?;
+ if let Some(rcode) = rcode {
+ write!(f, ": rcode {rcode}")?;
+ }
+ if let Some(info_code) = info_code {
+ write!(f, " (info code {info_code})")?;
+ }
+ Ok(())
+ }
+ Self::DestinationNotFound => write!(f, "destination not found"),
+ Self::DestinationUnavailable => write!(f, "destination unavailable"),
+ Self::DestinationIpProhibited => write!(f, "destination IP address is prohibited"),
+ Self::DestinationIpUnroutable => write!(f, "destination IP address is unroutable"),
+ Self::ConnectionRefused => write!(f, "connection refused"),
+ Self::ConnectionTerminated => write!(f, "connection terminated"),
+ Self::ConnectionTimeout => write!(f, "connection timeout"),
+ Self::ConnectionReadTimeout => write!(f, "connection read timeout"),
+ Self::ConnectionWriteTimeout => write!(f, "connection write timeout"),
+ Self::ConnectionLimitReached => write!(f, "connection limit reached"),
+ Self::TlsProtocolError => write!(f, "TLS protocol error"),
+ Self::TlsCertificateError => write!(f, "TLS certificate error"),
+ Self::TlsAlertReceived {
+ alert_id,
+ alert_message,
+ } => {
+ write!(f, "TLS alert received")?;
+ if let Some(id) = alert_id {
+ write!(f, ": alert id {id}")?;
+ }
+ if let Some(msg) = alert_message {
+ write!(f, ": {msg}")?;
+ }
+ Ok(())
+ }
+ Self::HttpRequestDenied => write!(f, "HTTP request denied"),
+ Self::HttpRequestLengthRequired => write!(f, "HTTP request length required"),
+ Self::HttpRequestMethodInvalid => write!(f, "invalid HTTP request method"),
+ Self::HttpRequestUriInvalid => write!(f, "invalid HTTP request URI"),
+ Self::HttpRequestUriTooLong => write!(f, "HTTP request URI too long"),
+ Self::HttpRequestHeaderSectionSize(size) => {
+ write!(f, "HTTP request header section size exceeds limit")?;
+ if let Some(size) = size {
+ write!(f, ": {size} bytes")?;
+ }
+ Ok(())
+ }
+ Self::HttpRequestHeaderSize {
+ field_name,
+ field_size,
+ } => {
+ write!(f, "HTTP request header size exceeds limit")?;
+ if let Some(name) = field_name {
+ write!(f, ": field {name:?}")?;
+ }
+ if let Some(size) = field_size {
+ write!(f, " ({size} bytes)")?;
+ }
+ Ok(())
+ }
+ Self::HttpRequestTrailerSectionSize(size) => {
+ write!(f, "HTTP request trailer section size exceeds limit")?;
+ if let Some(size) = size {
+ write!(f, ": {size} bytes")?;
+ }
+ Ok(())
+ }
+ Self::HttpRequestTrailerSize {
+ field_name,
+ field_size,
+ } => {
+ write!(f, "HTTP request trailer size exceeds limit")?;
+ if let Some(name) = field_name {
+ write!(f, ": field {name:?}")?;
+ }
+ if let Some(size) = field_size {
+ write!(f, " ({size} bytes)")?;
+ }
+ Ok(())
+ }
+ Self::HttpResponseIncomplete => write!(f, "incomplete HTTP response"),
+ Self::HttpResponseHeaderSectionSize(size) => {
+ write!(f, "HTTP response header section size exceeds limit")?;
+ if let Some(size) = size {
+ write!(f, ": {size} bytes")?;
+ }
+ Ok(())
+ }
+ Self::HttpResponseHeaderSize {
+ field_name,
+ field_size,
+ } => {
+ write!(f, "HTTP response header size exceeds limit")?;
+ if let Some(name) = field_name {
+ write!(f, ": field {name:?}")?;
+ }
+ if let Some(size) = field_size {
+ write!(f, " ({size} bytes)")?;
+ }
+ Ok(())
+ }
+ Self::HttpResponseBodySize(size) => {
+ write!(f, "HTTP response body size exceeds limit")?;
+ if let Some(size) = size {
+ write!(f, ": {size} bytes")?;
+ }
+ Ok(())
+ }
+ Self::HttpResponseTrailerSectionSize(size) => {
+ write!(f, "HTTP response trailer section size exceeds limit")?;
+ if let Some(size) = size {
+ write!(f, ": {size} bytes")?;
+ }
+ Ok(())
+ }
+ Self::HttpResponseTrailerSize {
+ field_name,
+ field_size,
+ } => {
+ write!(f, "HTTP response trailer size exceeds limit")?;
+ if let Some(name) = field_name {
+ write!(f, ": field {name:?}")?;
+ }
+ if let Some(size) = field_size {
+ write!(f, " ({size} bytes)")?;
+ }
+ Ok(())
+ }
+ Self::HttpResponseTransferCoding(coding) => {
+ write!(f, "unsupported HTTP response transfer coding")?;
+ if let Some(coding) = coding {
+ write!(f, ": {coding:?}")?;
+ }
+ Ok(())
+ }
+ Self::HttpResponseContentCoding(coding) => {
+ write!(f, "unsupported HTTP response content coding")?;
+ if let Some(coding) = coding {
+ write!(f, ": {coding:?}")?;
+ }
+ Ok(())
+ }
+ Self::HttpResponseTimeout => write!(f, "HTTP response timeout"),
+ Self::HttpUpgradeFailed => write!(f, "HTTP upgrade failed"),
+ Self::HttpProtocolError => write!(f, "HTTP protocol error"),
+ Self::LoopDetected => write!(f, "request loop detected"),
+ Self::ConfigurationError => write!(f, "configuration error"),
+ Self::InternalError(None) => write!(f, "internal error"),
+ Self::InternalError(Some(msg)) => write!(f, "internal error: {msg}"),
+ }
+ }
+}
+
+impl std::error::Error for Error {}
diff --git a/crates/wasi-http/src/handler.rs b/crates/wasi-http/src/handler.rs
index 236bdf8d4c..d1bc2a0121 100644
--- a/crates/wasi-http/src/handler.rs
+++ b/crates/wasi-http/src/handler.rs
@@ -7,13 +7,12 @@ use crate::p2;
use crate::p2::bindings::http::types as p2_types;
#[cfg(feature = "p3")]
use crate::p3;
-use bytes::Bytes;
+use crate::{WasiBody, WasiHttpCtxView};
use futures::{
channel::oneshot,
future::{Either, FutureExt},
stream::{FuturesUnordered, Stream},
};
-use http_body_util::{BodyExt, combinators::UnsyncBoxBody};
#[cfg(feature = "p3")]
use p3::bindings::http::types as p3_types;
use std::collections::VecDeque;
@@ -36,258 +35,11 @@ use wasmtime::component::{Accessor, GuestTaskId, Resource, TypedFuncCallConcurre
use wasmtime::error::Context as _;
use wasmtime::{AsContextMut, Result, Store, StoreContextMut, format_err};
-/// Represents either a `wasi:http/[email protected]` or `wasi:http/[email protected]` `error-code`.
-pub enum ErrorCode {
- /// A `wasi:http/[email protected]` `error-code`.
- #[cfg(feature = "p2")]
- P2(p2_types::ErrorCode),
- /// A `wasi:http/[email protected]` `error-code`.
- #[cfg(feature = "p3")]
- P3(p3_types::ErrorCode),
-}
-
-#[cfg(feature = "p2")]
-impl From<p2_types::ErrorCode> for ErrorCode {
- fn from(code: p2_types::ErrorCode) -> Self {
- Self::P2(code)
- }
-}
-
-#[cfg(feature = "p3")]
-impl From<p3_types::ErrorCode> for ErrorCode {
- fn from(code: p3_types::ErrorCode) -> Self {
- Self::P3(code)
- }
-}
-
-#[cfg(feature = "p2")]
-impl From<ErrorCode> for p2_types::ErrorCode {
- fn from(code: ErrorCode) -> p2_types::ErrorCode {
- match code {
- ErrorCode::P2(code) => code,
- #[cfg(feature = "p3")]
- ErrorCode::P3(code) => code.into(),
- }
- }
-}
-
-#[cfg(feature = "p3")]
-impl From<ErrorCode> for p3_types::ErrorCode {
- fn from(code: ErrorCode) -> p3_types::ErrorCode {
- match code {
- #[cfg(feature = "p2")]
- ErrorCode::P2(code) => code.into(),
- ErrorCode::P3(code) => code,
- }
- }
-}
-
-#[cfg(all(feature = "p2", feature = "p3"))]
-impl From<p2_types::ErrorCode> for p3_types::ErrorCode {
- fn from(code: p2_types::ErrorCode) -> Self {
- match code {
- p2_types::ErrorCode::DnsTimeout => Self::DnsTimeout,
- p2_types::ErrorCode::DnsError(payload) => Self::DnsError(p3_types::DnsErrorPayload {
- rcode: payload.rcode,
- info_code: payload.info_code,
- }),
- p2_types::ErrorCode::DestinationNotFound => Self::DestinationNotFound,
- p2_types::ErrorCode::DestinationUnavailable => Self::DestinationUnavailable,
- p2_types::ErrorCode::DestinationIpProhibited => Self::DestinationIpProhibited,
- p2_types::ErrorCode::DestinationIpUnroutable => Self::DestinationIpUnroutable,
- p2_types::ErrorCode::ConnectionRefused => Self::ConnectionRefused,
- p2_types::ErrorCode::ConnectionTerminated => Self::ConnectionTerminated,
- p2_types::ErrorCode::ConnectionTimeout => Self::ConnectionTimeout,
- p2_types::ErrorCode::ConnectionReadTimeout => Self::ConnectionReadTimeout,
- p2_types::ErrorCode::ConnectionWriteTimeout => Self::ConnectionWriteTimeout,
- p2_types::ErrorCode::ConnectionLimitReached => Self::ConnectionLimitReached,
- p2_types::ErrorCode::TlsProtocolError => Self::TlsProtocolError,
- p2_types::ErrorCode::TlsCertificateError => Self::TlsCertificateError,
- p2_types::ErrorCode::TlsAlertReceived(payload) => {
- Self::TlsAlertReceived(p3_types::TlsAlertReceivedPayload {
- alert_id: payload.alert_id,
- alert_message: payload.alert_message,
- })
- }
- p2_types::ErrorCode::HttpRequestDenied => Self::HttpRequestDenied,
- p2_types::ErrorCode::HttpRequestLengthRequired => Self::HttpRequestLengthRequired,
- p2_types::ErrorCode::HttpRequestBodySize(payload) => Self::HttpRequestBodySize(payload),
- p2_types::ErrorCode::HttpRequestMethodInvalid => Self::HttpRequestMethodInvalid,
- p2_types::ErrorCode::HttpRequestUriInvalid => Self::HttpRequestUriInvalid,
- p2_types::ErrorCode::HttpRequestUriTooLong => Self::HttpRequestUriTooLong,
- p2_types::ErrorCode::HttpRequestHeaderSectionSize(payload) => {
- Self::HttpRequestHeaderSectionSize(payload)
- }
- p2_types::ErrorCode::HttpRequestHeaderSize(payload) => {
- Self::HttpRequestHeaderSize(payload.map(|payload| p3_types::FieldSizePayload {
- field_name: payload.field_name,
- field_size: payload.field_size,
- }))
- }
- p2_types::ErrorCode::HttpRequestTrailerSectionSize(payload) => {
- Self::HttpRequestTrailerSectionSize(payload)
- }
- p2_types::ErrorCode::HttpRequestTrailerSize(payload) => {
- Self::HttpRequestTrailerSize(p3_types::FieldSizePayload {
- field_name: payload.field_name,
- field_size: payload.field_size,
- })
- }
- p2_types::ErrorCode::HttpResponseIncomplete => Self::HttpResponseIncomplete,
- p2_types::ErrorCode::HttpResponseHeaderSectionSize(payload) => {
- Self::HttpResponseHeaderSectionSize(payload)
- }
- p2_types::ErrorCode::HttpResponseHeaderSize(payload) => {
- Self::HttpResponseHeaderSize(p3_types::FieldSizePayload {
- field_name: payload.field_name,
- field_size: payload.field_size,
- })
- }
- p2_types::ErrorCode::HttpResponseBodySize(payload) => {
- Self::HttpResponseBodySize(payload)
- }
- p2_types::ErrorCode::HttpResponseTrailerSectionSize(payload) => {
- Self::HttpResponseTrailerSectionSize(payload)
- }
- p2_types::ErrorCode::HttpResponseTrailerSize(payload) => {
- Self::HttpResponseTrailerSize(p3_types::FieldSizePayload {
- field_name: payload.field_name,
- field_size: payload.field_size,
- })
- }
- p2_types::ErrorCode::HttpResponseTransferCoding(payload) => {
- Self::HttpResponseTransferCoding(payload)
- }
- p2_types::ErrorCode::HttpResponseContentCoding(payload) => {
- Self::HttpResponseContentCoding(payload)
- }
- p2_types::ErrorCode::HttpResponseTimeout => Self::HttpResponseTimeout,
- p2_types::ErrorCode::HttpUpgradeFailed => Self::HttpUpgradeFailed,
- p2_types::ErrorCode::HttpProtocolError => Self::HttpProtocolError,
- p2_types::ErrorCode::LoopDetected => Self::LoopDetected,
- p2_types::ErrorCode::ConfigurationError => Self::ConfigurationError,
- p2_types::ErrorCode::InternalError(payload) => Self::InternalError(payload),
- }
- }
-}
-
-#[cfg(all(feature = "p2", feature = "p3"))]
-impl From<p3_types::ErrorCode> for p2_types::ErrorCode {
- fn from(code: p3_types::ErrorCode) -> Self {
- match code {
- p3_types::ErrorCode::DnsTimeout => Self::DnsTimeout,
- p3_types::ErrorCode::DnsError(payload) => Self::DnsError(p2_types::DnsErrorPayload {
- rcode: payload.rcode,
- info_code: payload.info_code,
- }),
- p3_types::ErrorCode::DestinationNotFound => Self::DestinationNotFound,
- p3_types::ErrorCode::DestinationUnavailable => Self::DestinationUnavailable,
- p3_types::ErrorCode::DestinationIpProhibited => Self::DestinationIpProhibited,
- p3_types::ErrorCode::DestinationIpUnroutable => Self::DestinationIpUnroutable,
- p3_types::ErrorCode::ConnectionRefused => Self::ConnectionRefused,
- p3_types::ErrorCode::ConnectionTerminated => Self::ConnectionTerminated,
- p3_types::ErrorCode::ConnectionTimeout => Self::ConnectionTimeout,
- p3_types::ErrorCode::ConnectionReadTimeout => Self::ConnectionReadTimeout,
- p3_types::ErrorCode::ConnectionWriteTimeout => Self::ConnectionWriteTimeout,
- p3_types::ErrorCode::ConnectionLimitReached => Self::ConnectionLimitReached,
- p3_types::ErrorCode::TlsProtocolError => Self::TlsProtocolError,
- p3_types::ErrorCode::TlsCertificateError => Self::TlsCertificateError,
- p3_types::ErrorCode::TlsAlertReceived(payload) => {
- Self::TlsAlertReceived(p2_types::TlsAlertReceivedPayload {
- alert_id: payload.alert_id,
- alert_message: payload.alert_message,
- })
- }
- p3_types::ErrorCode::HttpRequestDenied => Self::HttpRequestDenied,
- p3_types::ErrorCode::HttpRequestLengthRequired => Self::HttpRequestLengthRequired,
- p3_types::ErrorCode::HttpRequestBodySize(payload) => Self::HttpRequestBodySize(payload),
- p3_types::ErrorCode::HttpRequestMethodInvalid => Self::HttpRequestMethodInvalid,
- p3_types::ErrorCode::HttpRequestUriInvalid => Self::HttpRequestUriInvalid,
- p3_types::ErrorCode::HttpRequestUriTooLong => Self::HttpRequestUriTooLong,
- p3_types::ErrorCode::HttpRequestHeaderSectionSize(payload) => {
- Self::HttpRequestHeaderSectionSize(payload)
- }
- p3_types::ErrorCode::HttpRequestHeaderSize(payload) => {
- Self::HttpRequestHeaderSize(payload.map(|payload| p2_types::FieldSizePayload {
- field_name: payload.field_name,
- field_size: payload.field_size,
- }))
- }
- p3_types::ErrorCode::HttpRequestTrailerSectionSize(payload) => {
- Self::HttpRequestTrailerSectionSize(payload)
- }
- p3_types::ErrorCode::HttpRequestTrailerSize(payload) => {
- Self::HttpRequestTrailerSize(p2_types::FieldSizePayload {
- field_name: payload.field_name,
- field_size: payload.field_size,
- })
- }
- p3_types::ErrorCode::HttpResponseIncomplete => Self::HttpResponseIncomplete,
- p3_types::ErrorCode::HttpResponseHeaderSectionSize(payload) => {
- Self::HttpResponseHeaderSectionSize(payload)
- }
- p3_types::ErrorCode::HttpResponseHeaderSize(payload) => {
- Self::HttpResponseHeaderSize(p2_types::FieldSizePayload {
- field_name: payload.field_name,
- field_size: payload.field_size,
- })
- }
- p3_types::ErrorCode::HttpResponseBodySize(payload) => {
- Self::HttpResponseBodySize(payload)
- }
- p3_types::ErrorCode::HttpResponseTrailerSectionSize(payload) => {
- Self::HttpResponseTrailerSectionSize(payload)
- }
- p3_types::ErrorCode::HttpResponseTrailerSize(payload) => {
- Self::HttpResponseTrailerSize(p2_types::FieldSizePayload {
- field_name: payload.field_name,
- field_size: payload.field_size,
- })
- }
- p3_types::ErrorCode::HttpResponseTransferCoding(payload) => {
- Self::HttpResponseTransferCoding(payload)
- }
- p3_types::ErrorCode::HttpResponseContentCoding(payload) => {
- Self::HttpResponseContentCoding(payload)
- }
- p3_types::ErrorCode::HttpResponseTimeout => Self::HttpResponseTimeout,
- p3_types::ErrorCode::HttpUpgradeFailed => Self::HttpUpgradeFailed,
- p3_types::ErrorCode::HttpProtocolError => Self::HttpProtocolError,
- p3_types::ErrorCode::LoopDetected => Self::LoopDetected,
- p3_types::ErrorCode::ConfigurationError => Self::ConfigurationError,
- p3_types::ErrorCode::InternalError(payload) => Self::InternalError(payload),
- }
- }
-}
-
-/// Represents either a p2 or p3 `WasiHttpCtxView` getter.
-pub enum ViewFn<T> {
- /// A p2 getter.
- #[cfg(feature = "p2")]
- P2(fn(&mut T) -> crate::p2::WasiHttpCtxView),
- /// A p3 getter.
- #[cfg(feature = "p3")]
- P3(fn(&mut T) -> p3::WasiHttpCtxView),
-}
-
-impl<T> Clone for ViewFn<T> {
- fn clone(&self) -> Self {
- match self {
- #[cfg(feature = "p2")]
- &Self::P2(view) => Self::P2(view),
- #[cfg(feature = "p3")]
- &Self::P3(view) => Self::P3(view),
- }
- }
-}
-
-impl<T> Copy for ViewFn<T> {}
-
/// A Request to be handled using `ProxyHandler::handle`.
-pub type Request = http::Request<UnsyncBoxBody<Bytes, ErrorCode>>;
+pub type Request = http::Request<WasiBody>;
/// A Response returned by `ProxyHandler::handle`.
-pub type Response = http::Response<UnsyncBoxBody<Bytes, wasmtime::Error>>;
+pub type Response = http::Response<WasiBody>;
/// Represents either a `wasi:http/[email protected]` or
/// `wasi:http/[email protected]` pre-instance.
@@ -488,7 +240,7 @@ pub struct Instance<T: 'static, E: WorkerExpiration, S: WorkerState> {
/// The instance to use to handle requests.
pub proxy: Proxy,
/// `WasiHttpCtxView` getter function.
- pub view: ViewFn<T>,
+ pub view: fn(&mut T) -> WasiHttpCtxView<'_>,
/// See [`WorkerExpiration`].
pub expiration: E,
/// See [`WorkerState`].
@@ -661,7 +413,7 @@ where
mut self,
store: Store<S::StoreData>,
proxy: Proxy,
- view: ViewFn<S::StoreData>,
+ view: fn(&mut S::StoreData) -> WasiHttpCtxView<'_>,
expiration: S::WorkerExpiration,
state: S::WorkerState,
request: Option<WorkerRequest<S>>,
@@ -1226,8 +978,8 @@ pub enum Prepared<'a, T: 'static> {
(Result<Resource<p3_types::Response>, p3_types::ErrorCode>,),
>,
tx: oneshot::Sender<Result<Response, wasmtime::Error>>,
- request_io_result: Pin<Box<dyn Future<Output = Result<(), p3_types::ErrorCode>> + Send>>,
- view: fn(&mut T) -> p3::WasiHttpCtxView,
+ request_io_result: Pin<Box<dyn Future<Output = Result<(), crate::Error>> + Send>>,
+ view: fn(&mut T) -> crate::WasiHttpCtxView,
},
}
@@ -1237,14 +989,13 @@ impl<'a, T: Send> Prepared<'a, T> {
mut store: StoreContextMut<'_, T>,
proxy: &'a Proxy,
request: Request,
- view: ViewFn<T>,
+ view: fn(&mut T) -> WasiHttpCtxView<'_>,
tx: oneshot::Sender<Result<Response, wasmtime::Error>>,
) -> Result<Prepared<'a, T>> {
- match (proxy, view) {
+ match proxy {
#[cfg(feature = "p3")]
- (Proxy::P3(guest), ViewFn::P3(view)) => {
+ Proxy::P3(guest) => {
let (request, body) = request.into_parts();
- let body = body.map_err(p3_types::ErrorCode::from);
let request = http::Request::from_parts(request, body);
let (request, request_io_result) = p3::Request::from_http(request);
let request = view(store.data_mut()).table.push(request)?;
@@ -1261,7 +1012,7 @@ impl<'a, T: Send> Prepared<'a, T> {
})
}
#[cfg(feature = "p2")]
- (Proxy::P2(guest), ViewFn::P2(view)) => {
+ Proxy::P2(guest) => {
// Here we wrap the sender in an `Arc<Mutex<Option<_>>>`, with one
// clone used in the `response-outparam` and the other used to send
// an error if the request expires or the handler returns without
@@ -1275,15 +1026,7 @@ impl<'a, T: Send> Prepared<'a, T> {
let tx = tx.clone();
move |value| {
if let Some(tx) = tx.lock().unwrap().take() {
- _ = tx.send(
- value
- .map(|v| {
- v.map(move |body| {
- body.map_err(wasmtime::Error::from).boxed_unsync()
- })
- })
- .map_err(wasmtime::Error::from),
- );
+ _ = tx.send(value.map_err(|e| e.into()));
}
}
})?;
@@ -1297,8 +1040,6 @@ impl<'a, T: Send> Prepared<'a, T> {
.start_call_concurrent(store, (request, out))?,
})
}
- #[cfg(all(feature = "p2", feature = "p3"))]
- _ => unreachable!(),
}
}
@@ -1328,27 +1069,19 @@ impl<'a, T: Send> Prepared<'a, T> {
request_io_result,
view,
} => {
- let handle =
- pin!(async move {
- let response = guest
- .wasi_http_handler()
- .func_handle()
- .finish_call_concurrent(accessor, call)
- .await?
- .0?;
-
- let response = accessor.with(|mut store| {
- let response = view(store.get()).table.delete(response)?;
- Ok::<_, wasmtime::Error>(response.into_http_with_getter(
- &mut store,
- request_io_result,
- view,
- )?)
- })?;
-
- Ok(response
- .map(move |body| body.map_err(wasmtime::Error::from).boxed_unsync()))
- });
+ let handle = pin!(async move {
+ let response = guest
+ .wasi_http_handler()
+ .func_handle()
+ .finish_call_concurrent(accessor, call)
+ .await?
+ .0?;
+
+ accessor.with(|mut store| {
+ let response = view(store.get()).table.delete(response)?;
+ response.into_http_with_getter(&mut store, request_io_result, view)
+ })
+ });
// TODO: We should also use `oneshot::Sender::poll_close` to be
// notified when the receiver is dropped, in which case we should
diff --git a/crates/wasi-http/src/lib.rs b/crates/wasi-http/src/lib.rs
index 04f12bc285..2d48ef195a 100644
--- a/crates/wasi-http/src/lib.rs
+++ b/crates/wasi-http/src/lib.rs
@@ -12,6 +12,9 @@
use http::{HeaderName, header};
mod ctx;
+#[cfg(feature = "default-send-request")]
+mod default_send_request;
+mod error;
mod field_map;
#[cfg(feature = "component-model-async")]
pub mod handler;
@@ -23,6 +26,9 @@ pub mod p3;
mod request_options;
pub use ctx::*;
+#[cfg(feature = "default-send-request")]
+pub use default_send_request::*;
+pub use error::*;
pub use field_map::*;
pub use request_options::*;
@@ -73,72 +79,6 @@ mod content_length_tests {
}
}
-/// Resolve the rustls [`ServerName`] used for TLS certificate verification from
-/// an outbound request `authority`.
-///
-/// `authority` is in `host:port` form, where an IPv6 `host` is wrapped in
-/// brackets (for example `[::1]:443`). An IP literal is recognized by parsing
-/// the whole authority as a [`SocketAddr`]; this handles the bracketed IPv6
-/// form, which splitting on the first `:` would truncate. Anything else is
-/// treated as a host name, with the port stripped off before it is handed to
-/// rustls.
-///
-/// [`ServerName`]: rustls::pki_types::ServerName
-/// [`SocketAddr`]: std::net::SocketAddr
-#[cfg(all(feature = "default-send-request", any(feature = "p2", feature = "p3")))]
-fn tls_server_name(
- authority: &str,
-) -> Result<rustls::pki_types::ServerName<'static>, rustls::pki_types::InvalidDnsNameError> {
- use rustls::pki_types::ServerName;
-
- if let Ok(addr) = authority.parse::<std::net::SocketAddr>() {
- return Ok(ServerName::from(addr.ip()));
- }
- let host = match authority.split_once(':') {
- Some((host, _port)) => host,
- None => authority,
- };
- Ok(ServerName::try_from(host)?.to_owned())
-}
-
-#[cfg(all(
- test,
- feature = "default-send-request",
- any(feature = "p2", feature = "p3")
-))]
-mod tls_server_name_tests {
- use super::tls_server_name;
- use rustls::pki_types::ServerName;
-
- #[test]
- fn resolves_server_name_from_authority() {
- // Host names keep their host and drop the port.
- assert_eq!(
- tls_server_name("example.com:443").unwrap(),
- ServerName::try_from("example.com").unwrap()
- );
- assert_eq!(
- tls_server_name("example.com").unwrap(),
- ServerName::try_from("example.com").unwrap()
- );
-
- // IP literals resolve to an `IpAddress` server name. The bracketed IPv6
- // form must not be truncated at the first `:`.
- assert_eq!(
- tls_server_name("127.0.0.1:80").unwrap(),
- ServerName::from(std::net::Ipv4Addr::LOCALHOST)
- );
- assert_eq!(
- tls_server_name("[::1]:443").unwrap(),
- ServerName::from(std::net::Ipv6Addr::LOCALHOST)
- );
- assert_eq!(
- tls_server_name("[2001:db8::1]:8443").unwrap(),
- ServerName::from("2001:db8::1".parse::<std::net::Ipv6Addr>().unwrap())
- );
- }
-}
-
/// Set of [http::header::HeaderName], that are forbidden by default
/// for requests and responses originating in the guest.
pub const DEFAULT_FORBIDDEN_HEADERS: [HeaderName; 9] = [
diff --git a/crates/wasi-http/src/p2/body.rs b/crates/wasi-http/src/p2/body.rs
index 5b1b543694..75d305c4b9 100644
--- a/crates/wasi-http/src/p2/body.rs
+++ b/crates/wasi-http/src/p2/body.rs
@@ -1,7 +1,7 @@
//! Implementation of the `wasi:http/types` interface's various body types.
-use crate::FieldMap;
use crate::p2::bindings::http::types;
+use crate::{Error, FieldMap};
use bytes::Bytes;
use http_body::{Body, Frame};
use http_body_util::BodyExt;
@@ -9,8 +9,6 @@ use http_body_util::combinators::UnsyncBoxBody;
use std::future::Future;
use std::mem;
use std::task::{Context, Poll};
-#[cfg(feature = "default-send-request")]
-use std::time::Duration;
use std::{pin::Pin, sync::Arc};
use tokio::sync::{mpsc, oneshot};
use wasmtime::format_err;
@@ -18,10 +16,10 @@ use wasmtime_wasi::p2::{InputStream, OutputStream, Pollable, StreamError};
use wasmtime_wasi::runtime::{AbortOnDropJoinHandle, poll_noop};
/// Common type for incoming bodies.
-pub type HyperIncomingBody = UnsyncBoxBody<Bytes, types::ErrorCode>;
+pub type HyperIncomingBody = UnsyncBoxBody<Bytes, Error>;
/// Common type for outgoing bodies.
-pub type HyperOutgoingBody = UnsyncBoxBody<Bytes, types::ErrorCode>;
+pub type HyperOutgoingBody = UnsyncBoxBody<Bytes, Error>;
/// The concrete type behind a `was:http/types.incoming-body` resource.
#[derive(Debug)]
@@ -85,74 +83,6 @@ enum IncomingBodyState {
InBodyStream(oneshot::Receiver<StreamEnd>),
}
-/// Small wrapper around [`HyperIncomingBody`] which adds a timeout to every frame.
-#[derive(Debug)]
-#[cfg(feature = "default-send-request")]
-pub(crate) struct BodyWithTimeout<B> {
- /// Underlying stream that frames are coming from.
- 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
- /// `poll_frame`.
- reset_sleep: bool,
- /// Maximal duration between when a frame is first requested and when it's
- /// allowed to arrive.
- between_bytes_timeout: Duration,
-}
-
-#[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,
- reset_sleep: true,
- timeout: Box::pin(wasmtime_wasi::runtime::with_ambient_tokio_runtime(|| {
- tokio::time::sleep(Duration::new(0, 0))
- })),
- }
- }
-}
-
-#[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<B::Data>, types::ErrorCode>>> {
- let me = Pin::into_inner(self);
-
- // If the timeout timer needs to be reset, do that now relative to the
- // current instant. Otherwise test the timeout timer and see if it's
- // fired yet and if so we've timed out and return an error.
- if me.reset_sleep {
- me.timeout
- .as_mut()
- .reset(tokio::time::Instant::now() + me.between_bytes_timeout);
- me.reset_sleep = false;
- }
-
- // Register interest in this context on the sleep timer, and if the
- // sleep elapsed that means that we've timed out.
- if let Poll::Ready(()) = me.timeout.as_mut().poll(cx) {
- return Poll::Ready(Some(Err(types::ErrorCode::ConnectionReadTimeout)));
- }
-
- // Without timeout business now handled check for the frame. If a frame
- // arrives then the sleep timer will be reset on the next frame.
- let result = Pin::new(&mut me.inner).poll_frame(cx);
- me.reset_sleep = result.is_ready();
- result
- }
-}
-
/// Message sent when a `HostIncomingBodyStream` is done to the
/// `HostFutureTrailers` state.
#[derive(Debug)]
@@ -172,11 +102,11 @@ enum StreamEnd {
pub struct HostIncomingBodyStream {
state: IncomingBodyStreamState,
buffer: Bytes,
- error: Option<wasmtime::Error>,
+ error: Option<Error>,
}
impl HostIncomingBodyStream {
- fn record_frame(&mut self, frame: Option<Result<Frame<Bytes>, types::ErrorCode>>) {
+ fn record_frame(&mut self, frame: Option<Result<Frame<Bytes>, Error>>) {
match frame {
Some(Ok(frame)) => match frame.into_data() {
// A data frame was received, so queue up the buffered data for
@@ -206,7 +136,7 @@ impl HostIncomingBodyStream {
// Destroy the body to terminate the stream while enqueueing the
// error to get returned from the next call to `read`.
Some(Err(e)) => {
- self.error = Some(e.into());
+ self.error = Some(e);
self.state = IncomingBodyStreamState::Closed;
}
@@ -251,7 +181,7 @@ impl InputStream for HostIncomingBodyStream {
}
if let Some(e) = self.error.take() {
- return Err(StreamError::LastOperationFailed(e));
+ return Err(StreamError::LastOperationFailed(e.into()));
}
// Extract the body that we're reading from. If present perform a
@@ -326,7 +256,7 @@ pub enum HostFutureTrailers {
///
/// Note that `Ok(None)` means that there were no trailers for this request
/// while `Ok(Some(_))` means that trailers were found in the request.
- Done(Result<Option<http::HeaderMap>, types::ErrorCode>),
+ Done(Result<Option<http::HeaderMap>, Error>),
/// Trailers have been consumed by `future-trailers.get`.
Consumed,
@@ -447,7 +377,7 @@ impl HostOutgoingBody {
}
impl Body for BodyImpl {
type Data = Bytes;
- type Error = types::ErrorCode;
+ type Error = Error;
fn poll_frame(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
@@ -470,7 +400,7 @@ impl HostOutgoingBody {
Poll::Ready(Some(Ok(Frame::trailers(trailers))))
}
FinishMessage::Abort => {
- Poll::Ready(Some(Err(types::ErrorCode::HttpProtocolError)))
+ Poll::Ready(Some(Err(Error::HttpProtocolError)))
}
},
Poll::Ready(Err(RecvError { .. })) => Poll::Ready(None),
diff --git a/crates/wasi-http/src/p2/error.rs b/crates/wasi-http/src/p2/error.rs
index 7dae4ee30f..d018e16846 100644
--- a/crates/wasi-http/src/p2/error.rs
+++ b/crates/wasi-http/src/p2/error.rs
@@ -1,7 +1,8 @@
-use crate::FieldMapError;
use crate::p2::bindings::http::types::{self, ErrorCode};
-use std::error::Error;
+use crate::{Error, FieldMapError, WasiHttpCtxView};
+use std::error::Error as _;
use std::fmt;
+use std::io::ErrorKind;
use wasmtime::component::ResourceTableError;
/// A [`Result`] type where the error type defaults to [`HttpError`].
@@ -57,7 +58,7 @@ impl fmt::Display for HttpError {
}
}
-impl Error for HttpError {}
+impl std::error::Error for HttpError {}
/// A [`Result`] type where the error type defaults to [`HeaderError`].
pub type HeaderResult<T, E = HeaderError> = Result<T, E>;
@@ -134,14 +135,6 @@ impl fmt::Display for HeaderError {
}
}
-#[cfg(feature = "default-send-request")]
-pub(crate) fn dns_error(rcode: String, info_code: u16) -> ErrorCode {
- ErrorCode::DnsError(crate::p2::bindings::http::types::DnsErrorPayload {
- rcode: Some(rcode),
- info_code: Some(info_code),
- })
-}
-
pub(crate) fn internal_error(msg: String) -> ErrorCode {
ErrorCode::InternalError(Some(msg))
}
@@ -194,3 +187,208 @@ impl From<hyper::Error> for ErrorCode {
hyper_response_error(err)
}
}
+
+impl From<ErrorCode> for Error {
+ fn from(e: ErrorCode) -> Self {
+ match e {
+ ErrorCode::DnsTimeout => Self::DnsTimeout,
+ ErrorCode::DnsError(payload) => Self::DnsError {
+ rcode: payload.rcode,
+ info_code: payload.info_code,
+ },
+ ErrorCode::DestinationNotFound => Self::DestinationNotFound,
+ ErrorCode::DestinationUnavailable => Self::DestinationUnavailable,
+ ErrorCode::DestinationIpProhibited => Self::DestinationIpProhibited,
+ ErrorCode::DestinationIpUnroutable => Self::DestinationIpUnroutable,
+ ErrorCode::ConnectionRefused => Self::ConnectionRefused,
+ ErrorCode::ConnectionTerminated => Self::ConnectionTerminated,
+ ErrorCode::ConnectionTimeout => Self::ConnectionTimeout,
+ ErrorCode::ConnectionReadTimeout => Self::ConnectionReadTimeout,
+ ErrorCode::ConnectionWriteTimeout => Self::ConnectionWriteTimeout,
+ ErrorCode::ConnectionLimitReached => Self::ConnectionLimitReached,
+ ErrorCode::TlsProtocolError => Self::TlsProtocolError,
+ ErrorCode::TlsCertificateError => Self::TlsCertificateError,
+ ErrorCode::TlsAlertReceived(payload) => Self::TlsAlertReceived {
+ alert_id: payload.alert_id,
+ alert_message: payload.alert_message,
+ },
+ ErrorCode::HttpRequestDenied => Self::HttpRequestDenied,
+ ErrorCode::HttpRequestLengthRequired => Self::HttpRequestLengthRequired,
+ ErrorCode::HttpRequestBodySize(payload) => Self::HttpRequestBodySize(payload),
+ ErrorCode::HttpRequestMethodInvalid => Self::HttpRequestMethodInvalid,
+ ErrorCode::HttpRequestUriInvalid => Self::HttpRequestUriInvalid,
+ ErrorCode::HttpRequestUriTooLong => Self::HttpRequestUriTooLong,
+ ErrorCode::HttpRequestHeaderSectionSize(payload) => {
+ Self::HttpRequestHeaderSectionSize(payload)
+ }
+ ErrorCode::HttpRequestHeaderSize(payload) => {
+ let (field_name, field_size) = match payload {
+ Some(p) => (p.field_name, p.field_size),
+ None => (None, None),
+ };
+ Self::HttpRequestHeaderSize {
+ field_name,
+ field_size,
+ }
+ }
+ ErrorCode::HttpRequestTrailerSectionSize(payload) => {
+ Self::HttpRequestTrailerSectionSize(payload)
+ }
+ ErrorCode::HttpRequestTrailerSize(payload) => Self::HttpRequestTrailerSize {
+ field_name: payload.field_name,
+ field_size: payload.field_size,
+ },
+ ErrorCode::HttpResponseIncomplete => Self::HttpResponseIncomplete,
+ ErrorCode::HttpResponseHeaderSectionSize(payload) => {
+ Self::HttpResponseHeaderSectionSize(payload)
+ }
+ ErrorCode::HttpResponseHeaderSize(payload) => Self::HttpRequestHeaderSize {
+ field_name: payload.field_name,
+ field_size: payload.field_size,
+ },
+ ErrorCode::HttpResponseBodySize(payload) => Self::HttpResponseBodySize(payload),
+ ErrorCode::HttpResponseTrailerSectionSize(payload) => {
+ Self::HttpResponseTrailerSectionSize(payload)
+ }
+ ErrorCode::HttpResponseTrailerSize(payload) => Self::HttpResponseTrailerSize {
+ field_name: payload.field_name,
+ field_size: payload.field_size,
+ },
+ ErrorCode::HttpResponseTransferCoding(payload) => {
+ Self::HttpResponseTransferCoding(payload)
+ }
+ ErrorCode::HttpResponseContentCoding(payload) => {
+ Self::HttpResponseContentCoding(payload)
+ }
+ ErrorCode::HttpResponseTimeout => Self::HttpResponseTimeout,
+ ErrorCode::HttpUpgradeFailed => Self::HttpUpgradeFailed,
+ ErrorCode::HttpProtocolError => Self::HttpProtocolError,
+ ErrorCode::LoopDetected => Self::LoopDetected,
+ ErrorCode::ConfigurationError => Self::ConfigurationError,
+ ErrorCode::InternalError(payload) => Self::InternalError(payload),
+ }
+ }
+}
+
+impl WasiHttpCtxView<'_> {
+ pub(crate) fn error_to_p2(&mut self, e: Error) -> ErrorCode {
+ match e {
+ Error::Hyper(err) => {
+ // If there's a source, we might be able to extract a wasi-http error from it.
+ if let Some(cause) = err.source() {
+ if let Some(err) = cause.downcast_ref::<ErrorCode>() {
+ return err.clone();
+ }
+ }
+
+ self.hooks.p2_error_from_hyper(&err)
+ }
+ Error::Connect(err) => {
+ if err.kind() == ErrorKind::AddrNotAvailable {
+ return ErrorCode::DnsError(types::DnsErrorPayload {
+ rcode: Some("address not available".to_string()),
+ info_code: None,
+ });
+ }
+
+ if err
+ .to_string()
+ .starts_with("failed to lookup address information")
+ {
+ return ErrorCode::DnsError(types::DnsErrorPayload {
+ rcode: Some("address not available".to_string()),
+ info_code: None,
+ });
+ }
+
+ self.hooks.p2_error_from_connect(&err)
+ }
+ Error::Tls(err) => self.hooks.p2_error_from_tls(&err),
+ #[cfg(feature = "default-send-request")]
+ Error::InvalidDnsNameError(err) => self.hooks.p2_error_from_dns(&err),
+ Error::DnsTimeout => ErrorCode::DnsTimeout,
+ Error::DnsError { rcode, info_code } => {
+ ErrorCode::DnsError(types::DnsErrorPayload { rcode, info_code })
+ }
+ Error::DestinationNotFound => ErrorCode::DestinationNotFound,
+ Error::DestinationUnavailable => ErrorCode::DestinationUnavailable,
+ Error::DestinationIpProhibited => ErrorCode::DestinationIpProhibited,
+ Error::DestinationIpUnroutable => ErrorCode::DestinationIpUnroutable,
+ Error::ConnectionRefused => ErrorCode::ConnectionRefused,
+ Error::ConnectionTerminated => ErrorCode::ConnectionTerminated,
+ Error::ConnectionTimeout => ErrorCode::ConnectionTimeout,
+ Error::ConnectionReadTimeout => ErrorCode::ConnectionReadTimeout,
+ Error::ConnectionWriteTimeout => ErrorCode::ConnectionWriteTimeout,
+ Error::ConnectionLimitReached => ErrorCode::ConnectionLimitReached,
+ Error::TlsProtocolError => ErrorCode::TlsProtocolError,
+ Error::TlsCertificateError => ErrorCode::TlsCertificateError,
+ Error::TlsAlertReceived {
+ alert_id,
+ alert_message,
+ } => ErrorCode::TlsAlertReceived(types::TlsAlertReceivedPayload {
+ alert_id,
+ alert_message,
+ }),
+ Error::HttpRequestDenied => ErrorCode::HttpRequestDenied,
+ Error::HttpRequestLengthRequired => ErrorCode::HttpRequestLengthRequired,
+ Error::HttpRequestBodySize(payload) => ErrorCode::HttpRequestBodySize(payload),
+ Error::HttpRequestMethodInvalid => ErrorCode::HttpRequestMethodInvalid,
+ Error::HttpRequestUriInvalid => ErrorCode::HttpRequestUriInvalid,
+ Error::HttpRequestUriTooLong => ErrorCode::HttpRequestUriTooLong,
+ Error::HttpRequestHeaderSectionSize(payload) => {
+ ErrorCode::HttpRequestHeaderSectionSize(payload)
+ }
+ Error::HttpRequestHeaderSize {
+ field_name,
+ field_size,
+ } => ErrorCode::HttpRequestHeaderSize(Some(types::FieldSizePayload {
+ field_name,
+ field_size,
+ })),
+ Error::HttpRequestTrailerSectionSize(payload) => {
+ ErrorCode::HttpRequestTrailerSectionSize(payload)
+ }
+ Error::HttpRequestTrailerSize {
+ field_name,
+ field_size,
+ } => ErrorCode::HttpRequestTrailerSize(types::FieldSizePayload {
+ field_name,
+ field_size,
+ }),
+ Error::HttpResponseIncomplete => ErrorCode::HttpResponseIncomplete,
+ Error::HttpResponseHeaderSectionSize(payload) => {
+ ErrorCode::HttpResponseHeaderSectionSize(payload)
+ }
+ Error::HttpResponseHeaderSize {
+ field_name,
+ field_size,
+ } => ErrorCode::HttpResponseHeaderSize(types::FieldSizePayload {
+ field_name,
+ field_size,
+ }),
+ Error::HttpResponseBodySize(payload) => ErrorCode::HttpResponseBodySize(payload),
+ Error::HttpResponseTrailerSectionSize(payload) => {
+ ErrorCode::HttpResponseTrailerSectionSize(payload)
+ }
+ Error::HttpResponseTrailerSize {
+ field_name,
+ field_size,
+ } => ErrorCode::HttpResponseTrailerSize(types::FieldSizePayload {
+ field_name,
+ field_size,
+ }),
+ Error::HttpResponseTransferCoding(payload) => {
+ ErrorCode::HttpResponseTransferCoding(payload)
+ }
+ Error::HttpResponseContentCoding(payload) => {
+ ErrorCode::HttpResponseContentCoding(payload)
+ }
+ Error::HttpResponseTimeout => ErrorCode::HttpResponseTimeout,
+ Error::HttpUpgradeFailed => ErrorCode::HttpUpgradeFailed,
+ Error::HttpProtocolError => ErrorCode::HttpProtocolError,
+ Error::LoopDetected => ErrorCode::LoopDetected,
+ Error::ConfigurationError => ErrorCode::ConfigurationError,
+ Error::InternalError(payload) => ErrorCode::InternalError(payload),
+ }
+ }
+}
diff --git a/crates/wasi-http/src/p2/http_impl.rs b/crates/wasi-http/src/p2/http_impl.rs
index cdf83d63ea..8ae075eadb 100644
--- a/crates/wasi-http/src/p2/http_impl.rs
+++ b/crates/wasi-http/src/p2/http_impl.rs
@@ -1,7 +1,8 @@
//! Implementation of the `wasi:http/outgoing-handler` interface.
+use crate::WasiHttpCtxView;
use crate::p2::{
- HttpResult, WasiHttpCtxView,
+ HttpResult,
bindings::http::{
outgoing_handler,
types::{self, Scheme},
@@ -72,12 +73,15 @@ impl outgoing_handler::Host for WasiHttpCtxView<'_> {
.map_err(|_| unreachable!("Infallible error"))
.boxed_unsync()
});
+ let body = body.map_err(Into::into).boxed_unsync();
let request = builder
.body(body)
.map_err(|err| internal_error(err.to_string()))?;
- let future = self.hooks.send_request(request, opts);
+ let future = self
+ .hooks
+ .send_request(request, opts, Box::new(async { Ok(()) }));
let future = wasmtime_wasi::runtime::spawn(async move {
let (res, io) = Pin::from(future).await?;
let io = wasmtime_wasi::runtime::spawn(async move {
@@ -88,6 +92,7 @@ impl outgoing_handler::Host for WasiHttpCtxView<'_> {
Err(e) => tracing::warn!("dropping error {e}"),
}
});
+ let res = res.map(|b| b.boxed_unsync());
Ok((res, io))
});
diff --git a/crates/wasi-http/src/p2/mod.rs b/crates/wasi-http/src/p2/mod.rs
index ba8661d2fe..587be8d1d8 100644
--- a/crates/wasi-http/src/p2/mod.rs
+++ b/crates/wasi-http/src/p2/mod.rs
@@ -82,7 +82,7 @@
//! use wasmtime_wasi_http::p2::bindings::http::types::Scheme;
//! use wasmtime_wasi_http::p2::body::HyperOutgoingBody;
//! use wasmtime_wasi_http::io::TokioIo;
-//! use wasmtime_wasi_http::{WasiHttpCtx, p2::{WasiHttpView, WasiHttpCtxView}};
+//! use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView, WasiHttpCtxView};
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
@@ -218,12 +218,16 @@
//! }
//! }
//! ```
+//!
+//! [`WasiHttpCtx`]: crate::WasiHttpCtx
+//! [`WasiHttpCtxView`]: crate::WasiHttpCtxView
+//! [`WasiHttpHooks`]: crate::WasiHttpHooks
+//! [`WasiHttpHooks::send_request`]: crate::WasiHttpHooks::send_request
+//! [`ResourceTable`]: wasmtime::component::ResourceTable
+//! [`default_hooks`]: crate::default_hooks
-use self::bindings::http::types::ErrorCode;
-use crate::RequestOptions;
-use crate::{DEFAULT_FORBIDDEN_HEADERS, WasiHttpCtx};
-use http::HeaderName;
-use wasmtime::component::{HasData, Linker, ResourceTable};
+use crate::{WasiHttp, WasiHttpView};
+use wasmtime::component::Linker;
mod error;
mod http_impl;
@@ -235,197 +239,14 @@ pub mod types;
pub use self::error::*;
-/// A trait which provides hooks into internal WASI HTTP operations.
-///
-/// # Example
-///
-/// ```
-/// use wasmtime::component::ResourceTable;
-/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
-/// use wasmtime_wasi_http::WasiHttpCtx;
-/// use wasmtime_wasi_http::p2::{WasiHttpView, WasiHttpCtxView};
-///
-/// struct MyState {
-/// ctx: WasiCtx,
-/// http_ctx: WasiHttpCtx,
-/// table: ResourceTable,
-/// }
-///
-/// impl WasiHttpView for MyState {
-/// fn http(&mut self) -> WasiHttpCtxView<'_> {
-/// WasiHttpCtxView {
-/// ctx: &mut self.http_ctx,
-/// table: &mut self.table,
-/// hooks: Default::default(),
-/// }
-/// }
-/// }
+/// The default value configured for [`WasiHttpHooks::p2_outgoing_body_buffer_chunks`] in [`WasiHttpView`].
///
-/// impl WasiView for MyState {
-/// fn ctx(&mut self) -> WasiCtxView<'_> {
-/// WasiCtxView { ctx: &mut self.ctx, table: &mut self.table }
-/// }
-/// }
-///
-/// impl MyState {
-/// fn new() -> MyState {
-/// let mut wasi = WasiCtx::builder();
-/// wasi.arg("./foo.wasm");
-/// wasi.arg("--help");
-/// wasi.env("FOO", "bar");
-///
-/// MyState {
-/// ctx: wasi.build(),
-/// table: ResourceTable::new(),
-/// http_ctx: WasiHttpCtx::new(),
-/// }
-/// }
-/// }
-/// ```
-pub trait WasiHttpHooks: Send {
- /// Send an outgoing request.
- #[cfg(feature = "default-send-request")]
- fn send_request(
- &mut self,
- 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: 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 {
- DEFAULT_FORBIDDEN_HEADERS.contains(name)
- }
-
- /// Number of distinct write calls to the outgoing body's output-stream
- /// that the implementation will buffer.
- /// Default: 1.
- fn outgoing_body_buffer_chunks(&mut self) -> usize {
- DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS
- }
-
- /// Maximum size allowed in a write call to the outgoing body's output-stream.
- /// Default: 1024 * 1024.
- fn outgoing_body_chunk_size(&mut self) -> usize {
- DEFAULT_OUTGOING_BODY_CHUNK_SIZE
- }
-}
-
-#[cfg(feature = "default-send-request")]
-impl<'a> Default for &'a mut dyn WasiHttpHooks {
- fn default() -> Self {
- let x: &mut [(); 0] = &mut [];
- x
- }
-}
-
-#[doc(hidden)]
-#[cfg(feature = "default-send-request")]
-impl WasiHttpHooks for [(); 0] {}
-
-/// Returns a value suitable for the `WasiHttpCtxView::hooks` field which has
-/// the default behavior for `wasi:http`.
-#[cfg(feature = "default-send-request")]
-pub fn default_hooks() -> &'static mut dyn WasiHttpHooks {
- Default::default()
-}
-
-/// The default value configured for [`WasiHttpHooks::outgoing_body_buffer_chunks`] in [`WasiHttpView`].
+/// [`WasiHttpHooks::p2_outgoing_body_buffer_chunks`]: crate::WasiHttpHooks::p2_outgoing_body_buffer_chunks
pub const DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS: usize = 1;
-/// The default value configured for [`WasiHttpHooks::outgoing_body_chunk_size`] in [`WasiHttpView`].
-pub const DEFAULT_OUTGOING_BODY_CHUNK_SIZE: usize = 1024 * 1024;
-
-/// Structure which `wasi:http` `Host`-style traits are implemented for.
-///
-/// This structure is used by embedders with the [`WasiHttpView`] trait's return
-/// value and is used to provide access to this crate all internals necessary to
-/// implement `wasi:http`. This is similar to [`wasmtime_wasi::WasiCtxView`]
-/// for example.
-pub struct WasiHttpCtxView<'a> {
- /// A reference to a per-store [`WasiHttpCtx`].
- pub ctx: &'a mut WasiHttpCtx,
- /// A reference to a per-store table of resources to store host structures
- /// within.
- pub table: &'a mut ResourceTable,
- /// A reference to a per-store set of hooks that can be used to customize
- /// `wasi:http` behavior.
- pub hooks: &'a mut dyn WasiHttpHooks,
-}
-
-/// The type for which this crate implements the `wasi:http` interfaces.
-pub struct WasiHttp;
-
-impl HasData for WasiHttp {
- type Data<'a> = WasiHttpCtxView<'a>;
-}
-
-/// A trait used to project state that this crate needs to implement `wasi:http`
-/// from the `self` type.
-///
-/// This trait is used in [`add_to_linker_sync`] and [`add_to_linker_async`] for
-/// example as a bound on `T` in `Store<T>`. This is used to access data from
-/// `T`, the data within a `Store`, an instance of [`WasiHttpCtxView`]. The
-/// [`WasiHttpCtxView`] contains contextual information such as the
-/// [`ResourceTable`] for the store, HTTP context info in [`WasiHttpCtx`], and
-/// any hooks via [`WasiHttpHooks`] if the embedder desires.
-///
-/// # Example
-///
-/// ```
-/// use wasmtime::component::ResourceTable;
-/// use wasmtime_wasi_http::WasiHttpCtx;
-/// use wasmtime_wasi_http::p2::{WasiHttpView, WasiHttpCtxView};
+/// The default value configured for [`WasiHttpHooks::p2_outgoing_body_chunk_size`] in [`WasiHttpView`].
///
-/// struct MyState {
-/// http_ctx: WasiHttpCtx,
-/// table: ResourceTable,
-/// }
-///
-/// impl WasiHttpView for MyState {
-/// fn http(&mut self) -> WasiHttpCtxView<'_> {
-/// WasiHttpCtxView {
-/// ctx: &mut self.http_ctx,
-/// table: &mut self.table,
-/// hooks: Default::default(),
-/// }
-/// }
-/// }
-/// ```
-pub trait WasiHttpView {
- /// Returns an instance of [`WasiHttpCtxView`] projected out of `self`.
- fn http(&mut self) -> WasiHttpCtxView<'_>;
-}
+/// [`WasiHttpHooks::p2_outgoing_body_chunk_size`]: crate::WasiHttpHooks::p2_outgoing_body_chunk_size
+pub const DEFAULT_OUTGOING_BODY_CHUNK_SIZE: usize = 1024 * 1024;
/// Add all of the `wasi:http/proxy` world's interfaces to a [`wasmtime::component::Linker`].
///
@@ -439,7 +260,7 @@ pub trait WasiHttpView {
/// use wasmtime::{Engine, Result};
/// use wasmtime::component::{ResourceTable, Linker};
/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
-/// use wasmtime_wasi_http::{WasiHttpCtx, p2::{WasiHttpView, WasiHttpCtxView}};
+/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView, WasiHttpCtxView};
///
/// fn main() -> Result<()> {
/// let engine = Engine::default();
@@ -511,8 +332,7 @@ where
/// use wasmtime::{Engine, Result, Config};
/// use wasmtime::component::{ResourceTable, Linker};
/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
-/// use wasmtime_wasi_http::WasiHttpCtx;
-/// use wasmtime_wasi_http::p2::{WasiHttpView, WasiHttpCtxView};
+/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView, WasiHttpCtxView};
///
/// fn main() -> Result<()> {
/// let config = Config::default();
@@ -568,172 +388,3 @@ where
Ok(())
}
-
-/// The default implementation of how an outgoing request is sent.
-///
-/// This implementation is used by the `wasi:http/outgoing-handler` interface
-/// default implementation.
-#[cfg(feature = "default-send-request")]
-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()) {
- request.headers_mut().insert(hyper::header::HOST, value);
- }
- }
- }
-
- let authority = if let Some(authority) = request.uri().authority() {
- if authority.port().is_some() {
- authority.to_string()
- } else {
- let port = if use_tls { 443 } else { 80 };
- format!("{}:{port}", authority.to_string())
- }
- } else {
- return Err(ErrorCode::HttpRequestUriInvalid);
- };
- let tcp_stream = timeout(connect_timeout, TcpStream::connect(&authority))
- .await
- .map_err(|_| ErrorCode::ConnectionTimeout)?
- .map_err(|e| match e.kind() {
- std::io::ErrorKind::AddrNotAvailable => {
- dns_error("address not available".to_string(), 0)
- }
-
- _ => {
- if e.to_string()
- .starts_with("failed to lookup address information")
- {
- dns_error("address not available".to_string(), 0)
- } else {
- ErrorCode::ConnectionRefused
- }
- }
- })?;
-
- 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(),
- };
- let config = rustls::ClientConfig::builder()
- .with_root_certificates(root_cert_store)
- .with_no_client_auth();
- let connector = tokio_rustls::TlsConnector::from(std::sync::Arc::new(config));
- let domain = crate::tls_server_name(&authority).map_err(|e| {
- tracing::warn!("dns lookup error: {e:?}");
- dns_error("invalid dns name".to_string(), 0)
- })?;
- let stream = connector.connect(domain, tcp_stream).await.map_err(|e| {
- tracing::warn!("tls protocol error: {e:?}");
- ErrorCode::TlsProtocolError
- })?;
- TokioIo::new(stream.boxed())
- } else {
- 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
- *request.uri_mut() = http::Uri::builder()
- .path_and_query(
- request
- .uri()
- .path_and_query()
- .map(|p| p.as_str())
- .unwrap_or("/"),
- )
- .build()
- .expect("comes from valid request");
-
- 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 4dda336cbd..2f9081bcde 100644
--- a/crates/wasi-http/src/p2/types.rs
+++ b/crates/wasi-http/src/p2/types.rs
@@ -1,12 +1,11 @@
//! Implements the base structure that will provide the implementation of the
//! wasi-http API.
-use crate::FieldMap;
use crate::p2::{
- HttpResult, WasiHttpCtxView, WasiHttpHooks,
- bindings::http::types::{self, ErrorCode, Method, Scheme},
+ bindings::http::types::{self, Method, Scheme},
body::{HostIncomingBody, HyperIncomingBody, HyperOutgoingBody},
};
+use crate::{Error, FieldMap, WasiHttpCtxView, WasiHttpHooks};
use bytes::Bytes;
use http_body_util::BodyExt;
use hyper::body::Body;
@@ -99,7 +98,7 @@ impl WasiHttpCtxView<'_> {
) -> wasmtime::Result<Resource<HostIncomingRequest>>
where
B: Body<Data = Bytes> + Send + 'static,
- B::Error: Into<ErrorCode>,
+ B::Error: Into<Error>,
{
let (mut parts, body) = req.into_parts();
let body = body.map_err(Into::into).boxed_unsync();
@@ -242,7 +241,8 @@ pub struct IncomingResponse {
pub worker: Option<AbortOnDropJoinHandle<()>>,
}
-type SendRequestResult = HttpResult<(http::Response<HyperIncomingBody>, AbortOnDropJoinHandle<()>)>;
+type SendRequestResult =
+ crate::Result<(http::Response<HyperIncomingBody>, AbortOnDropJoinHandle<()>)>;
/// The concrete type behind a `wasi:http/types.future-incoming-response` resource.
pub enum HostFutureIncomingResponse {
diff --git a/crates/wasi-http/src/p2/types_impl.rs b/crates/wasi-http/src/p2/types_impl.rs
index 8c16eaf492..47597125cf 100644
--- a/crates/wasi-http/src/p2/types_impl.rs
+++ b/crates/wasi-http/src/p2/types_impl.rs
@@ -1,14 +1,13 @@
//! Implementation for the `wasi:http/types` interface.
-use crate::FieldMap;
-use crate::get_content_length;
use crate::p2::bindings::http::types::{self, Method, Scheme, StatusCode, Trailers};
use crate::p2::body::{HostFutureTrailers, HostIncomingBody, HostOutgoingBody, StreamContext};
use crate::p2::types::{
HostFutureIncomingResponse, HostIncomingRequest, HostIncomingResponse, HostOutgoingRequest,
HostOutgoingResponse, HostResponseOutparam, remove_forbidden_headers,
};
-use crate::p2::{HeaderError, HeaderResult, HttpError, HttpResult, WasiHttpCtxView};
+use crate::p2::{HeaderError, HeaderResult, HttpError, HttpResult};
+use crate::{FieldMap, WasiHttpCtxView, get_content_length};
use http::{HeaderName, HeaderValue};
use std::str::FromStr;
use wasmtime::component::Resource;
@@ -242,8 +241,8 @@ impl types::HostOutgoingRequest for WasiHttpCtxView<'_> {
&mut self,
request: Resource<HostOutgoingRequest>,
) -> wasmtime::Result<Result<Resource<HostOutgoingBody>, ()>> {
- let buffer_chunks = self.hooks.outgoing_body_buffer_chunks();
- let chunk_size = self.hooks.outgoing_body_chunk_size();
+ let buffer_chunks = self.hooks.p2_outgoing_body_buffer_chunks();
+ let chunk_size = self.hooks.p2_outgoing_body_chunk_size();
let req = self
.table
.get_mut(&request)
@@ -497,7 +496,10 @@ impl types::HostFutureTrailers for WasiHttpCtxView<'_> {
let mut fields = match res {
Ok(Some(fields)) => fields,
Ok(None) => return Ok(Some(Ok(Ok(None)))),
- Err(e) => return Ok(Some(Ok(Err(e)))),
+ Err(e) => {
+ let e = self.error_to_p2(e);
+ return Ok(Some(Ok(Err(e))));
+ }
};
remove_forbidden_headers(self.hooks, &mut fields);
@@ -560,8 +562,8 @@ impl types::HostOutgoingResponse for WasiHttpCtxView<'_> {
&mut self,
id: Resource<HostOutgoingResponse>,
) -> wasmtime::Result<Result<Resource<HostOutgoingBody>, ()>> {
- let buffer_chunks = self.hooks.outgoing_body_buffer_chunks();
- let chunk_size = self.hooks.outgoing_body_chunk_size();
+ let buffer_chunks = self.hooks.p2_outgoing_body_buffer_chunks();
+ let chunk_size = self.hooks.p2_outgoing_body_chunk_size();
let resp = self.table.get_mut(&id)?;
if resp.body.is_some() {
@@ -643,8 +645,7 @@ impl types::HostFutureIncomingResponse for WasiHttpCtxView<'_> {
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()?;
+ let e = self.error_to_p2(e);
return Ok(Some(Ok(Err(e))));
}
};
diff --git a/crates/wasi-http/src/p3/bindings.rs b/crates/wasi-http/src/p3/bindings.rs
index 2e7804ce72..340b2cb7f8 100644
--- a/crates/wasi-http/src/p3/bindings.rs
+++ b/crates/wasi-http/src/p3/bindings.rs
@@ -31,7 +31,7 @@ mod generated {
mod with {
pub type Fields = crate::FieldMap;
- pub type RequestOptions = crate::p3::MaybeMutable<crate::p3::RequestOptions>;
+ pub type RequestOptions = crate::p3::MaybeMutable<crate::RequestOptions>;
}
}
diff --git a/crates/wasi-http/src/p3/body.rs b/crates/wasi-http/src/p3/body.rs
index de4236b1fe..ff6b943bc9 100644
--- a/crates/wasi-http/src/p3/body.rs
+++ b/crates/wasi-http/src/p3/body.rs
@@ -1,7 +1,6 @@
-use crate::FieldMap;
use crate::p3::bindings::http::types::{ErrorCode, Trailers};
use crate::p3::helpers::FutureReaderExt;
-use crate::p3::{WasiHttp, WasiHttpCtxView};
+use crate::{Error, FieldMap, WasiHttp, WasiHttpCtxView};
use bytes::Bytes;
use core::iter;
use core::num::NonZeroUsize;
@@ -10,6 +9,7 @@ use core::task::{Context, Poll, ready};
use http_body::Body as _;
use http_body_util::combinators::UnsyncBoxBody;
use std::any::{Any, TypeId};
+use std::mem;
use std::sync::Arc;
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::PollSender;
@@ -29,18 +29,74 @@ pub(crate) enum Body {
/// Future, on which guest will write result and optional trailers
trailers_rx: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,
/// Channel, on which transmission result will be written
- result_tx: oneshot::Sender<Box<dyn Future<Output = Result<(), ErrorCode>> + Send>>,
+ result_tx: oneshot::Sender<Box<dyn Future<Output = Result<(), Error>> + Send>>,
},
/// Body constructed by the host.
Host {
/// The [`http_body::Body`]
- body: UnsyncBoxBody<Bytes, ErrorCode>,
+ body: UnsyncBoxBody<Bytes, Error>,
/// Channel, on which transmission result will be written
- result_tx: oneshot::Sender<Box<dyn Future<Output = Result<(), ErrorCode>> + Send>>,
+ result_tx: oneshot::Sender<Box<dyn Future<Output = Result<(), Error>> + Send>>,
},
}
+async fn guest_body_result<E>(
+ rx: oneshot::Receiver<Box<dyn Future<Output = Result<(), E>> + Send>>,
+) -> wasmtime::Result<Result<(), E>> {
+ match rx.await {
+ Ok(fut) => Ok(Pin::from(fut).await),
+ // oneshot sender dropped, treat as success
+ Err(..) => Ok(Ok(())),
+ }
+}
+
impl Body {
+ pub(crate) fn new_guest<T>(
+ store: &mut Access<'_, T, WasiHttp>,
+ contents: Option<StreamReader<u8>>,
+ mut trailers: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,
+ ) -> wasmtime::Result<(Self, FutureReader<Result<(), ErrorCode>>)> {
+ let getter = store.getter();
+ // Attempt to unwrap this guest-specified body stream as a host-owned
+ // stream. That helps bypass a layer of indirection where possible.
+ let contents = match contents
+ .map(|rx| rx.try_into::<HostBodyStreamProducer<T>>(&mut *store))
+ {
+ Some(Ok(mut producer)) => {
+ trailers.close(&mut *store)?;
+ let (result_tx, result_rx) = oneshot::channel();
+ let body = Body::Host {
+ body: mem::take(&mut producer.body),
+ result_tx,
+ };
+ return Ok((
+ body,
+ FutureReader::new_cb(
+ &mut *store,
+ guest_body_result(result_rx),
+ move |d, res: Result<_, Error>| res.map_err(|e| getter(d).error_to_p3(&e)),
+ )?,
+ ));
+ }
+ Some(Err(rx)) => Some(rx),
+ None => None,
+ };
+ let (result_tx, result_rx) = oneshot::channel();
+ let body = Body::Guest {
+ contents_rx: contents,
+ trailers_rx: trailers,
+ result_tx,
+ };
+ Ok((
+ body,
+ FutureReader::new_cb(
+ &mut *store,
+ guest_body_result(result_rx),
+ move |d, res: Result<_, Error>| res.map_err(|e| getter(d).error_to_p3(&e)),
+ )?,
+ ))
+ }
+
/// Implementation of `consume-body` shared between requests and responses
pub(crate) fn consume<T>(
self,
@@ -51,22 +107,27 @@ impl Body {
StreamReader<u8>,
FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,
)> {
- let (contents_rx, trailers_rx, result_tx) = match self {
+ let (contents_rx, trailers_rx) = match self {
Body::Guest {
- contents_rx: Some(contents_rx),
+ contents_rx,
trailers_rx,
result_tx,
- } => (contents_rx, trailers_rx, result_tx),
- Body::Guest {
- contents_rx: None,
- trailers_rx,
- result_tx,
- } => (
- StreamReader::new(&mut store, iter::empty())?,
- trailers_rx,
- result_tx,
- ),
+ } => {
+ let body = match contents_rx {
+ Some(stream) => stream,
+ None => StreamReader::new(&mut store, iter::empty())?,
+ };
+ fut.pipe_cb(&mut store, |_, res| {
+ _ = result_tx.send(Box::new(async { res.map_err(|e| e.into()) }));
+ Ok(())
+ })?;
+ (body, trailers_rx)
+ }
Body::Host { body, result_tx } => {
+ fut.pipe_cb(&mut store, |_, res| {
+ _ = result_tx.send(Box::new(async { res.map_err(|e| e.into()) }));
+ Ok(())
+ })?;
let (trailers_tx, trailers_rx) = oneshot::channel();
(
StreamReader::new(
@@ -77,16 +138,15 @@ impl Body {
getter,
},
)?,
- FutureReader::new(&mut store, trailers_rx)?,
- result_tx,
+ FutureReader::new_cb(
+ &mut store,
+ trailers_rx,
+ move |d, res: Result<_, Error>| res.map_err(|e| getter(d).error_to_p3(&e)),
+ )?,
)
}
};
- fut.pipe_cb(&mut store, |_, res| {
- _ = result_tx.send(Box::new(async { res }));
- Ok(())
- })?;
Ok((contents_rx, trailers_rx))
}
@@ -246,8 +306,8 @@ impl GuestBody {
mut store: impl AsContextMut<Data = T>,
contents_rx: Option<StreamReader<u8>>,
trailers_rx: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,
- result_tx: oneshot::Sender<Box<dyn Future<Output = Result<(), ErrorCode>> + Send>>,
- result_fut: impl Future<Output = Result<(), ErrorCode>> + Send + 'static,
+ result_tx: oneshot::Sender<Box<dyn Future<Output = Result<(), Error>> + Send>>,
+ result_fut: impl Future<Output = Result<(), Error>> + Send + 'static,
content_length: Option<u64>,
make_error: fn(Option<u64>) -> ErrorCode,
getter: fn(&mut T) -> WasiHttpCtxView<'_>,
@@ -276,7 +336,7 @@ impl GuestBody {
let (error_tx, error_rx) = oneshot::channel();
_ = result_tx.send(Box::new(async move {
if let Ok(err) = error_rx.await {
- return Err(err);
+ return Err(Error::from(err));
};
result_fut.await
}));
@@ -310,7 +370,7 @@ impl GuestBody {
impl http_body::Body for GuestBody {
type Data = Bytes;
- type Error = ErrorCode;
+ type Error = Error;
fn poll_frame(
mut self: Pin<&mut Self>,
@@ -331,7 +391,7 @@ impl http_body::Body for GuestBody {
return Poll::Ready(Some(Ok(http_body::Frame::data(buf))));
}
Err(err) => {
- return Poll::Ready(Some(Err(err)));
+ return Poll::Ready(Some(Err(err.into())));
}
}
}
@@ -352,7 +412,7 @@ impl http_body::Body for GuestBody {
Arc::unwrap_or_clone(trailers).into(),
)))),
Ok(Ok(None)) => Poll::Ready(None),
- Ok(Err(err)) => Poll::Ready(Some(Err(err))),
+ Ok(Err(err)) => Poll::Ready(Some(Err(err.into()))),
Err(..) => Poll::Ready(None),
}
}
@@ -389,8 +449,8 @@ impl http_body::Body for GuestBody {
/// [StreamProducer] implementation for bodies originating in the host.
pub(crate) struct HostBodyStreamProducer<T> {
- pub(crate) body: UnsyncBoxBody<Bytes, ErrorCode>,
- trailers: Option<oneshot::Sender<Result<Option<Resource<Trailers>>, ErrorCode>>>,
+ pub(crate) body: UnsyncBoxBody<Bytes, Error>,
+ trailers: Option<oneshot::Sender<Result<Option<Resource<Trailers>>, Error>>>,
getter: fn(&mut T) -> WasiHttpCtxView<'_>,
}
@@ -401,7 +461,7 @@ impl<T> Drop for HostBodyStreamProducer<T> {
}
impl<T> HostBodyStreamProducer<T> {
- fn close(&mut self, res: Result<Option<Resource<Trailers>>, ErrorCode>) {
+ fn close(&mut self, res: Result<Option<Resource<Trailers>>, Error>) {
if let Some(tx) = self.trailers.take() {
_ = tx.send(res);
}
@@ -484,7 +544,7 @@ where
.context("failed to push trailers to table")?;
break 'result Ok(Some(trailers));
}
- Err(Err(..)) => break 'result Err(ErrorCode::HttpProtocolError),
+ Err(Err(..)) => break 'result Err(Error::HttpProtocolError),
}
}
Poll::Ready(Some(Err(err))) => break 'result Err(err),
diff --git a/crates/wasi-http/src/p3/conv.rs b/crates/wasi-http/src/p3/conv.rs
index 073380b0e7..1753b4872e 100644
--- a/crates/wasi-http/src/p3/conv.rs
+++ b/crates/wasi-http/src/p3/conv.rs
@@ -1,7 +1,8 @@
-use crate::p3::bindings::http::types::{ErrorCode, Method, Scheme};
+use crate::p3::bindings::http::types::{self, ErrorCode, Method, Scheme};
+use crate::{Error, WasiHttpCtxView};
use core::convert::Infallible;
use core::error::Error as _;
-use tracing::warn;
+use std::io::ErrorKind;
impl From<Infallible> for ErrorCode {
fn from(x: Infallible) -> Self {
@@ -9,38 +10,213 @@ impl From<Infallible> for ErrorCode {
}
}
-impl ErrorCode {
- /// Translate a [`hyper::Error`] to a wasi-http [ErrorCode] in the context of a request.
- pub fn from_hyper_request_error(err: hyper::Error) -> Self {
- // If there's a source, we might be able to extract a wasi-http error from it.
- if let Some(cause) = err.source() {
- if let Some(err) = cause.downcast_ref::<Self>() {
- return err.clone();
+impl From<ErrorCode> for Error {
+ fn from(e: ErrorCode) -> Self {
+ match e {
+ ErrorCode::DnsTimeout => Self::DnsTimeout,
+ ErrorCode::DnsError(payload) => Self::DnsError {
+ rcode: payload.rcode,
+ info_code: payload.info_code,
+ },
+ ErrorCode::DestinationNotFound => Self::DestinationNotFound,
+ ErrorCode::DestinationUnavailable => Self::DestinationUnavailable,
+ ErrorCode::DestinationIpProhibited => Self::DestinationIpProhibited,
+ ErrorCode::DestinationIpUnroutable => Self::DestinationIpUnroutable,
+ ErrorCode::ConnectionRefused => Self::ConnectionRefused,
+ ErrorCode::ConnectionTerminated => Self::ConnectionTerminated,
+ ErrorCode::ConnectionTimeout => Self::ConnectionTimeout,
+ ErrorCode::ConnectionReadTimeout => Self::ConnectionReadTimeout,
+ ErrorCode::ConnectionWriteTimeout => Self::ConnectionWriteTimeout,
+ ErrorCode::ConnectionLimitReached => Self::ConnectionLimitReached,
+ ErrorCode::TlsProtocolError => Self::TlsProtocolError,
+ ErrorCode::TlsCertificateError => Self::TlsCertificateError,
+ ErrorCode::TlsAlertReceived(payload) => Self::TlsAlertReceived {
+ alert_id: payload.alert_id,
+ alert_message: payload.alert_message,
+ },
+ ErrorCode::HttpRequestDenied => Self::HttpRequestDenied,
+ ErrorCode::HttpRequestLengthRequired => Self::HttpRequestLengthRequired,
+ ErrorCode::HttpRequestBodySize(payload) => Self::HttpRequestBodySize(payload),
+ ErrorCode::HttpRequestMethodInvalid => Self::HttpRequestMethodInvalid,
+ ErrorCode::HttpRequestUriInvalid => Self::HttpRequestUriInvalid,
+ ErrorCode::HttpRequestUriTooLong => Self::HttpRequestUriTooLong,
+ ErrorCode::HttpRequestHeaderSectionSize(payload) => {
+ Self::HttpRequestHeaderSectionSize(payload)
}
+ ErrorCode::HttpRequestHeaderSize(payload) => {
+ let (field_name, field_size) = match payload {
+ Some(p) => (p.field_name, p.field_size),
+ None => (None, None),
+ };
+ Self::HttpRequestHeaderSize {
+ field_name,
+ field_size,
+ }
+ }
+ ErrorCode::HttpRequestTrailerSectionSize(payload) => {
+ Self::HttpRequestTrailerSectionSize(payload)
+ }
+ ErrorCode::HttpRequestTrailerSize(payload) => Self::HttpRequestTrailerSize {
+ field_name: payload.field_name,
+ field_size: payload.field_size,
+ },
+ ErrorCode::HttpResponseIncomplete => Self::HttpResponseIncomplete,
+ ErrorCode::HttpResponseHeaderSectionSize(payload) => {
+ Self::HttpResponseHeaderSectionSize(payload)
+ }
+ ErrorCode::HttpResponseHeaderSize(payload) => Self::HttpRequestHeaderSize {
+ field_name: payload.field_name,
+ field_size: payload.field_size,
+ },
+ ErrorCode::HttpResponseBodySize(payload) => Self::HttpResponseBodySize(payload),
+ ErrorCode::HttpResponseTrailerSectionSize(payload) => {
+ Self::HttpResponseTrailerSectionSize(payload)
+ }
+ ErrorCode::HttpResponseTrailerSize(payload) => Self::HttpResponseTrailerSize {
+ field_name: payload.field_name,
+ field_size: payload.field_size,
+ },
+ ErrorCode::HttpResponseTransferCoding(payload) => {
+ Self::HttpResponseTransferCoding(payload)
+ }
+ ErrorCode::HttpResponseContentCoding(payload) => {
+ Self::HttpResponseContentCoding(payload)
+ }
+ ErrorCode::HttpResponseTimeout => Self::HttpResponseTimeout,
+ ErrorCode::HttpUpgradeFailed => Self::HttpUpgradeFailed,
+ ErrorCode::HttpProtocolError => Self::HttpProtocolError,
+ ErrorCode::LoopDetected => Self::LoopDetected,
+ ErrorCode::ConfigurationError => Self::ConfigurationError,
+ ErrorCode::InternalError(payload) => Self::InternalError(payload),
}
-
- warn!("hyper request error: {err:?}");
-
- Self::HttpProtocolError
}
+}
- /// Translate a [`hyper::Error`] to a wasi-http [ErrorCode] in the context of a response.
- #[cfg(feature = "default-send-request")]
- pub(crate) fn from_hyper_response_error(err: hyper::Error) -> Self {
- if err.is_timeout() {
- return ErrorCode::HttpResponseTimeout;
- }
+impl WasiHttpCtxView<'_> {
+ pub(crate) fn error_to_p3(&mut self, e: &Error) -> ErrorCode {
+ match e {
+ Error::Hyper(err) => {
+ // If there's a source, we might be able to extract a wasi-http
+ // error from it.
+ if let Some(cause) = err.source() {
+ if let Some(err) = cause.downcast_ref::<ErrorCode>() {
+ return err.clone();
+ }
+ if let Some(err) = cause.downcast_ref::<Error>() {
+ return self.error_to_p3(err);
+ }
+ }
- // If there's a source, we might be able to extract a wasi-http error from it.
- if let Some(cause) = err.source() {
- if let Some(err) = cause.downcast_ref::<Self>() {
- return err.clone();
+ self.hooks.p3_error_from_hyper(err)
}
- }
+ Error::Connect(err) => {
+ if err.kind() == ErrorKind::AddrNotAvailable {
+ return ErrorCode::DnsError(types::DnsErrorPayload {
+ rcode: Some("address not available".to_string()),
+ info_code: None,
+ });
+ }
- warn!("hyper response error: {err:?}");
+ if err
+ .to_string()
+ .starts_with("failed to lookup address information")
+ {
+ return ErrorCode::DnsError(types::DnsErrorPayload {
+ rcode: Some("address not available".to_string()),
+ info_code: None,
+ });
+ }
- ErrorCode::HttpProtocolError
+ self.hooks.p3_error_from_connect(err)
+ }
+ Error::Tls(err) => self.hooks.p3_error_from_tls(err),
+ #[cfg(feature = "default-send-request")]
+ Error::InvalidDnsNameError(err) => self.hooks.p3_error_from_dns(err),
+ Error::DnsTimeout => ErrorCode::DnsTimeout,
+ Error::DnsError { rcode, info_code } => ErrorCode::DnsError(types::DnsErrorPayload {
+ rcode: rcode.clone(),
+ info_code: *info_code,
+ }),
+ Error::DestinationNotFound => ErrorCode::DestinationNotFound,
+ Error::DestinationUnavailable => ErrorCode::DestinationUnavailable,
+ Error::DestinationIpProhibited => ErrorCode::DestinationIpProhibited,
+ Error::DestinationIpUnroutable => ErrorCode::DestinationIpUnroutable,
+ Error::ConnectionRefused => ErrorCode::ConnectionRefused,
+ Error::ConnectionTerminated => ErrorCode::ConnectionTerminated,
+ Error::ConnectionTimeout => ErrorCode::ConnectionTimeout,
+ Error::ConnectionReadTimeout => ErrorCode::ConnectionReadTimeout,
+ Error::ConnectionWriteTimeout => ErrorCode::ConnectionWriteTimeout,
+ Error::ConnectionLimitReached => ErrorCode::ConnectionLimitReached,
+ Error::TlsProtocolError => ErrorCode::TlsProtocolError,
+ Error::TlsCertificateError => ErrorCode::TlsCertificateError,
+ Error::TlsAlertReceived {
+ alert_id,
+ alert_message,
+ } => ErrorCode::TlsAlertReceived(types::TlsAlertReceivedPayload {
+ alert_id: *alert_id,
+ alert_message: alert_message.clone(),
+ }),
+ Error::HttpRequestDenied => ErrorCode::HttpRequestDenied,
+ Error::HttpRequestLengthRequired => ErrorCode::HttpRequestLengthRequired,
+ Error::HttpRequestBodySize(payload) => ErrorCode::HttpRequestBodySize(*payload),
+ Error::HttpRequestMethodInvalid => ErrorCode::HttpRequestMethodInvalid,
+ Error::HttpRequestUriInvalid => ErrorCode::HttpRequestUriInvalid,
+ Error::HttpRequestUriTooLong => ErrorCode::HttpRequestUriTooLong,
+ Error::HttpRequestHeaderSectionSize(payload) => {
+ ErrorCode::HttpRequestHeaderSectionSize(*payload)
+ }
+ Error::HttpRequestHeaderSize {
+ field_name,
+ field_size,
+ } => ErrorCode::HttpRequestHeaderSize(Some(types::FieldSizePayload {
+ field_name: field_name.clone(),
+ field_size: *field_size,
+ })),
+ Error::HttpRequestTrailerSectionSize(payload) => {
+ ErrorCode::HttpRequestTrailerSectionSize(*payload)
+ }
+ Error::HttpRequestTrailerSize {
+ field_name,
+ field_size,
+ } => ErrorCode::HttpRequestTrailerSize(types::FieldSizePayload {
+ field_name: field_name.clone(),
+ field_size: *field_size,
+ }),
+ Error::HttpResponseIncomplete => ErrorCode::HttpResponseIncomplete,
+ Error::HttpResponseHeaderSectionSize(payload) => {
+ ErrorCode::HttpResponseHeaderSectionSize(*payload)
+ }
+ Error::HttpResponseHeaderSize {
+ field_name,
+ field_size,
+ } => ErrorCode::HttpResponseHeaderSize(types::FieldSizePayload {
+ field_name: field_name.clone(),
+ field_size: *field_size,
+ }),
+ Error::HttpResponseBodySize(payload) => ErrorCode::HttpResponseBodySize(*payload),
+ Error::HttpResponseTrailerSectionSize(payload) => {
+ ErrorCode::HttpResponseTrailerSectionSize(*payload)
+ }
+ Error::HttpResponseTrailerSize {
+ field_name,
+ field_size,
+ } => ErrorCode::HttpResponseTrailerSize(types::FieldSizePayload {
+ field_name: field_name.clone(),
+ field_size: *field_size,
+ }),
+ Error::HttpResponseTransferCoding(payload) => {
+ ErrorCode::HttpResponseTransferCoding(payload.clone())
+ }
+ Error::HttpResponseContentCoding(payload) => {
+ ErrorCode::HttpResponseContentCoding(payload.clone())
+ }
+ Error::HttpResponseTimeout => ErrorCode::HttpResponseTimeout,
+ Error::HttpUpgradeFailed => ErrorCode::HttpUpgradeFailed,
+ Error::HttpProtocolError => ErrorCode::HttpProtocolError,
+ Error::LoopDetected => ErrorCode::LoopDetected,
+ Error::ConfigurationError => ErrorCode::ConfigurationError,
+ Error::InternalError(payload) => ErrorCode::InternalError(payload.clone()),
+ }
}
}
diff --git a/crates/wasi-http/src/p3/helpers.rs b/crates/wasi-http/src/p3/helpers.rs
index 662256a5dc..35e59ff574 100644
--- a/crates/wasi-http/src/p3/helpers.rs
+++ b/crates/wasi-http/src/p3/helpers.rs
@@ -1,6 +1,7 @@
+use pin_project_lite::pin_project;
use std::pin::Pin;
use std::task::{Context, Poll};
-use wasmtime::component::{FutureConsumer, FutureReader, Lift, Source};
+use wasmtime::component::{FutureConsumer, FutureProducer, FutureReader, Lift, Lower, Source};
use wasmtime::error::Context as _;
use wasmtime::{AsContextMut, StoreContextMut};
@@ -61,6 +62,73 @@ pub trait FutureReaderExt<T> {
},
)
}
+
+ /// Creates a new `FutureReader<T>` which is the combination of waiting for
+ /// `future` to resolved followed by invoking the `cb` provided.
+ ///
+ /// Note that `cb` gets access to the store's data.
+ fn new_cb<U, S, E>(
+ store: S,
+ future: impl Future<Output = Result<U, E>> + Send + 'static,
+ cb: impl FnOnce(&mut S::Data, U) -> T + Send + 'static,
+ ) -> wasmtime::Result<FutureReader<T>>
+ where
+ S: AsContextMut,
+ E: Into<wasmtime::Error>,
+ T: Lift + Lower + 'static,
+ {
+ pin_project! {
+ struct Producer<F, C, D, T> {
+ cb: Option<C>,
+ #[pin]
+ future: F,
+ _marker: std::marker::PhantomData<fn(D, T)>,
+ }
+ }
+
+ impl<F, C, D, T, U, E> FutureProducer<D> for Producer<F, C, D, T>
+ where
+ F: Future<Output = Result<U, E>> + Send + 'static,
+ C: FnOnce(&mut D, U) -> T + Send + 'static,
+ D: 'static,
+ T: 'static,
+ E: Into<wasmtime::Error>,
+ {
+ type Item = T;
+
+ fn poll_produce(
+ self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ mut store: StoreContextMut<D>,
+ finish: bool,
+ ) -> Poll<wasmtime::Result<Option<T>>> {
+ let this = self.project();
+ let res = match this.future.poll(cx) {
+ Poll::Ready(Ok(res)) => res,
+ Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())),
+ Poll::Pending => {
+ return if finish {
+ Poll::Ready(Ok(None))
+ } else {
+ Poll::Pending
+ };
+ }
+ };
+ let cb = this.cb.take().context("polled after returning `Ready`")?;
+ let res = cb(store.data_mut(), res);
+ Poll::Ready(Ok(Some(res)))
+ }
+ }
+
+ FutureReader::new(
+ store,
+ Producer::<_, _, S::Data, T> {
+ cb: Some(cb),
+ future,
+ _marker: std::marker::PhantomData,
+ },
+ )
+ }
}
impl<T> FutureReaderExt<T> for FutureReader<T> {
diff --git a/crates/wasi-http/src/p3/host/handler.rs b/crates/wasi-http/src/p3/host/handler.rs
index ff07ae8a9b..f5ca3cb720 100644
--- a/crates/wasi-http/src/p3/host/handler.rs
+++ b/crates/wasi-http/src/p3/host/handler.rs
@@ -1,8 +1,9 @@
use crate::FieldMap;
use crate::p3::bindings::http::client::{Host, HostWithStore};
-use crate::p3::bindings::http::types::{ErrorCode, Request, Response};
+use crate::p3::bindings::http::types::{Request, Response};
use crate::p3::body::{Body, BodyExt as _};
-use crate::p3::{HttpError, HttpResult, WasiHttp, WasiHttpCtxView};
+use crate::p3::{HttpError, HttpResult};
+use crate::{Error, WasiHttp, WasiHttpCtxView};
use core::task::{Context, Poll, Waker};
use http_body_util::BodyExt as _;
use std::sync::Arc;
@@ -25,9 +26,9 @@ impl Drop for AbortOnDropJoinHandle {
async fn io_task_result(
rx: oneshot::Receiver<(
Arc<AbortOnDropJoinHandle>,
- oneshot::Receiver<Result<(), ErrorCode>>,
+ oneshot::Receiver<Result<(), Error>>,
)>,
-) -> Result<(), ErrorCode> {
+) -> Result<(), Error> {
let Ok((_io, io_result_rx)) = rx.await else {
return Ok(());
};
@@ -71,7 +72,9 @@ impl<T> HostWithStore<T> for WasiHttp {
}),
))
})?;
- let (res, io) = Box::into_pin(fut).await?;
+ let (res, io) = Box::into_pin(fut)
+ .await
+ .map_err(|e| store.with(|mut store| store.get().error_to_p3(&e)))?;
let (
http::response::Parts {
status, headers, ..
@@ -80,8 +83,11 @@ impl<T> HostWithStore<T> for WasiHttp {
) = res.into_parts();
let mut io = Box::into_pin(io);
- let body = match io.as_mut().poll(&mut Context::from_waker(Waker::noop()))? {
- Poll::Ready(()) => body,
+ let body = match io.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
+ Poll::Ready(Ok(())) => body,
+ Poll::Ready(Err(e)) => {
+ return Err(store.with(|mut store| store.get().error_to_p3(&e)).into());
+ }
Poll::Pending => {
// I/O driver still needs to be polled, spawn a task and send handles to it
let (tx, rx) = oneshot::channel();
diff --git a/crates/wasi-http/src/p3/host/types.rs b/crates/wasi-http/src/p3/host/types.rs
index 0bfa27cefe..777608bb2c 100644
--- a/crates/wasi-http/src/p3/host/types.rs
+++ b/crates/wasi-http/src/p3/host/types.rs
@@ -5,14 +5,11 @@ use crate::p3::bindings::http::types::{
HostRequestOptions, HostRequestWithStore, HostResponse, HostResponseWithStore, Method, Request,
RequestOptions, RequestOptionsError, Response, Scheme, StatusCode, Trailers,
};
-use crate::p3::body::{Body, HostBodyStreamProducer};
-use crate::p3::{HeaderResult, HttpError, RequestOptionsResult, WasiHttp, WasiHttpCtxView};
-use core::mem;
-use core::pin::Pin;
+use crate::p3::body::Body;
+use crate::p3::{HeaderResult, HttpError, RequestOptionsResult};
+use crate::{WasiHttp, WasiHttpCtxView};
use http::header::CONTENT_LENGTH;
use std::sync::Arc;
-use tokio::sync::oneshot;
-use wasmtime::AsContextMut;
use wasmtime::component::{Access, FutureReader, Resource, ResourceTable, StreamReader};
use wasmtime::error::Context as _;
@@ -158,16 +155,6 @@ fn parse_header_value(
}
}
-async fn guest_body_result(
- rx: oneshot::Receiver<Box<dyn Future<Output = Result<(), ErrorCode>> + Send>>,
-) -> wasmtime::Result<Result<(), ErrorCode>> {
- match rx.await {
- Ok(fut) => Ok(Pin::from(fut).await),
- // oneshot sender dropped, treat as success
- Err(..) => Ok(Ok(())),
- }
-}
-
impl HostFields for WasiHttpCtxView<'_> {
fn new(&mut self) -> wasmtime::Result<Resource<Fields>> {
push_fields(self.table, FieldMap::new_mutable(self.ctx.field_size_limit))
@@ -298,25 +285,7 @@ impl<T> HostRequestWithStore<T> for WasiHttp {
trailers: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,
options: Option<Resource<RequestOptions>>,
) -> wasmtime::Result<(Resource<Request>, FutureReader<Result<(), ErrorCode>>)> {
- 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 (body, body_result) = Body::new_guest(&mut store, contents, trailers)?;
let WasiHttpCtxView { table, .. } = store.get();
let headers = delete_fields(table, headers)?;
let options = options
@@ -332,10 +301,7 @@ impl<T> HostRequestWithStore<T> for WasiHttp {
body,
};
let req = table.push(req).context("failed to push request to table")?;
- Ok((
- req,
- FutureReader::new(&mut store, guest_body_result(result_rx))?,
- ))
+ Ok((req, body_result))
}
fn consume_body(
@@ -576,25 +542,7 @@ impl<T> HostResponseWithStore<T> for WasiHttp {
contents: Option<StreamReader<u8>>,
trailers: FutureReader<Result<Option<Resource<Trailers>>, ErrorCode>>,
) -> wasmtime::Result<(Resource<Response>, FutureReader<Result<(), ErrorCode>>)> {
- 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 (body, body_result) = Body::new_guest(&mut store, contents, trailers)?;
let WasiHttpCtxView { table, .. } = store.get();
let headers = delete_fields(table, headers)?;
let res = Response {
@@ -605,10 +553,7 @@ impl<T> HostResponseWithStore<T> for WasiHttp {
let res = table
.push(res)
.context("failed to push response to table")?;
- Ok((
- res,
- FutureReader::new(&mut store, guest_body_result(result_rx))?,
- ))
+ Ok((res, body_result))
}
fn consume_body(
diff --git a/crates/wasi-http/src/p3/mod.rs b/crates/wasi-http/src/p3/mod.rs
index eb3bcdf982..07f02d5da5 100644
--- a/crates/wasi-http/src/p3/mod.rs
+++ b/crates/wasi-http/src/p3/mod.rs
@@ -18,20 +18,13 @@ mod request;
mod response;
pub use request::Request;
-#[cfg(feature = "default-send-request")]
-pub use request::default_send_request;
pub use response::Response;
-use crate::p3::bindings::http::types::ErrorCode;
-use crate::{DEFAULT_FORBIDDEN_HEADERS, FieldMapError, RequestOptions, WasiHttpCtx};
+use crate::{FieldMapError, WasiHttp, WasiHttpView};
use bindings::http::{client, types};
-use bytes::Bytes;
use core::ops::Deref;
-use http::HeaderName;
-use http::uri::Scheme;
-use http_body_util::combinators::UnsyncBoxBody;
use std::sync::Arc;
-use wasmtime::component::{HasData, Linker, ResourceTable};
+use wasmtime::component::Linker;
use wasmtime_wasi::TrappableError;
pub(crate) type HttpResult<T> = Result<T, HttpError>;
@@ -55,151 +48,6 @@ impl From<FieldMapError> for HeaderError {
pub(crate) type RequestOptionsResult<T> = Result<T, RequestOptionsError>;
pub(crate) type RequestOptionsError = TrappableError<types::RequestOptionsError>;
-/// The type for which this crate implements the `wasi:http` interfaces.
-pub struct WasiHttp;
-
-impl HasData for WasiHttp {
- type Data<'a> = WasiHttpCtxView<'a>;
-}
-
-/// A trait which provides internal WASI HTTP state.
-pub trait WasiHttpHooks: Send {
- /// Whether a given header should be considered forbidden and not allowed.
- fn is_forbidden_header(&mut self, name: &HeaderName) -> bool {
- DEFAULT_FORBIDDEN_HEADERS.contains(name)
- }
-
- /// Whether a given scheme should be considered supported.
- ///
- /// `handle` will return [ErrorCode::HttpProtocolError] for unsupported schemes.
- fn is_supported_scheme(&mut self, scheme: &Scheme) -> bool {
- *scheme == Scheme::HTTP || *scheme == Scheme::HTTPS
- }
-
- /// Whether to set `host` header in the request passed to `send_request`.
- fn set_host_header(&mut self) -> bool {
- true
- }
-
- /// Scheme to default to, when not set by the guest.
- ///
- /// If [None], `handle` will return [ErrorCode::HttpProtocolError]
- /// for requests missing a scheme.
- fn default_scheme(&mut self) -> Option<Scheme> {
- Some(Scheme::HTTPS)
- }
-
- /// Send an outgoing request.
- ///
- /// This function will be used by the `wasi:http/handler#handle` implementation.
- ///
- /// The specified [Future] `fut` will be used to communicate
- /// a response processing error, if any.
- /// For example, if the response body is consumed via `wasi:http/types.response#consume-body`,
- /// a result will be sent on `fut`.
- ///
- /// The returned [Future] can be used to communicate
- /// a request processing error, if any, to the constructor of the request.
- /// For example, if the request was constructed via `wasi:http/types.request#new`,
- /// a result resolved from it will be forwarded to the guest on the future handle returned.
- ///
- /// `Content-Length` of the request passed to this function will be validated, however no
- /// `Content-Length` validation will be performed for the received response.
- #[cfg(feature = "default-send-request")]
- fn send_request(
- &mut self,
- request: http::Request<UnsyncBoxBody<Bytes, ErrorCode>>,
- options: Option<RequestOptions>,
- fut: Box<dyn Future<Output = Result<(), ErrorCode>> + Send>,
- ) -> Box<
- dyn Future<
- Output = HttpResult<(
- http::Response<UnsyncBoxBody<Bytes, ErrorCode>>,
- Box<dyn Future<Output = Result<(), ErrorCode>> + Send>,
- )>,
- > + Send,
- > {
- _ = fut;
- 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.
- ///
- /// This function will be used by the `wasi:http/handler#handle` implementation.
- ///
- /// The specified [Future] `fut` will be used to communicate
- /// a response processing error, if any.
- /// For example, if the response body is consumed via `wasi:http/types.response#consume-body`,
- /// a result will be sent on `fut`.
- ///
- /// The returned [Future] can be used to communicate
- /// a request processing error, if any, to the constructor of the request.
- /// For example, if the request was constructed via `wasi:http/types.request#new`,
- /// a result resolved from it will be forwarded to the guest on the future handle returned.
- ///
- /// `Content-Length` of the request passed to this function will be validated, however no
- /// `Content-Length` validation will be performed for the received response.
- #[cfg(not(feature = "default-send-request"))]
- fn send_request(
- &mut self,
- request: http::Request<UnsyncBoxBody<Bytes, ErrorCode>>,
- options: Option<RequestOptions>,
- fut: Box<dyn Future<Output = Result<(), ErrorCode>> + Send>,
- ) -> Box<
- dyn Future<
- Output = HttpResult<(
- http::Response<UnsyncBoxBody<Bytes, ErrorCode>>,
- Box<dyn Future<Output = Result<(), ErrorCode>> + Send>,
- )>,
- > + Send,
- >;
-}
-
-#[cfg(feature = "default-send-request")]
-impl<'a> Default for &'a mut dyn WasiHttpHooks {
- fn default() -> Self {
- let x: &mut [(); 0] = &mut [];
- x
- }
-}
-
-#[doc(hidden)]
-#[cfg(feature = "default-send-request")]
-impl WasiHttpHooks for [(); 0] {}
-
-/// Returns a value suitable for the `WasiHttpCtxView::hooks` field which has
-/// the default behavior for `wasi:http`.
-#[cfg(feature = "default-send-request")]
-pub fn default_hooks() -> &'static mut dyn WasiHttpHooks {
- Default::default()
-}
-
-/// View into [WasiHttpCtx] implementation and [ResourceTable].
-pub struct WasiHttpCtxView<'a> {
- /// Mutable reference to the WASI HTTP hooks.
- pub hooks: &'a mut dyn WasiHttpHooks,
-
- /// Mutable reference to table used to manage resources.
- pub table: &'a mut ResourceTable,
-
- /// Mutable reference to the WASI HTTP context.
- pub ctx: &'a mut WasiHttpCtx,
-}
-
-/// A trait which provides internal WASI HTTP state.
-pub trait WasiHttpView: Send {
- /// Return a [WasiHttpCtxView] from mutable reference to self.
- fn http(&mut self) -> WasiHttpCtxView<'_>;
-}
-
/// Add all interfaces from this module into the `linker` provided.
///
/// This function will add all interfaces implemented by this module to the
@@ -211,7 +59,7 @@ pub trait WasiHttpView: Send {
/// ```
/// use wasmtime::{Engine, Result, Store, Config};
/// use wasmtime::component::{Linker, ResourceTable};
-/// use wasmtime_wasi_http::{WasiHttpCtx, p3::{WasiHttpCtxView, WasiHttpView}};
+/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpCtxView, WasiHttpView};
///
/// fn main() -> Result<()> {
/// let mut config = Config::new();
diff --git a/crates/wasi-http/src/p3/proxy.rs b/crates/wasi-http/src/p3/proxy.rs
index 374c7564ba..58aa095208 100644
--- a/crates/wasi-http/src/p3/proxy.rs
+++ b/crates/wasi-http/src/p3/proxy.rs
@@ -1,4 +1,4 @@
-use crate::p3::WasiHttpView;
+use crate::WasiHttpView;
use crate::p3::bindings::Service;
use crate::p3::bindings::http::types::{ErrorCode, Request, Response};
use wasmtime::component::Accessor;
diff --git a/crates/wasi-http/src/p3/request.rs b/crates/wasi-http/src/p3/request.rs
index 1296f5f10c..9bb529e325 100644
--- a/crates/wasi-http/src/p3/request.rs
+++ b/crates/wasi-http/src/p3/request.rs
@@ -1,7 +1,7 @@
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, RequestOptions, get_content_length};
+use crate::p3::{HttpError, HttpResult};
+use crate::{Error, FieldMap, RequestOptions, WasiHttpCtxView, WasiHttpView, get_content_length};
use bytes::Bytes;
use http::header::HOST;
use http::uri::{Authority, PathAndQuery, Scheme};
@@ -38,18 +38,22 @@ impl Request {
/// a request processing error, if any.
///
/// Requests constructed this way will not perform any `Content-Length` validation.
- pub fn new(
+ pub fn new<B>(
method: Method,
scheme: Option<Scheme>,
authority: Option<Authority>,
path_with_query: Option<PathAndQuery>,
headers: impl Into<FieldMap>,
options: Option<Arc<RequestOptions>>,
- body: impl Into<UnsyncBoxBody<Bytes, ErrorCode>>,
+ body: B,
) -> (
Self,
- impl Future<Output = Result<(), ErrorCode>> + Send + 'static,
- ) {
+ impl Future<Output = Result<(), Error>> + Send + 'static,
+ )
+ where
+ B: http_body::Body<Data = Bytes> + Send + 'static,
+ B::Error: Into<Error>,
+ {
let (tx, rx) = oneshot::channel();
(
Self {
@@ -60,7 +64,7 @@ impl Request {
headers: headers.into(),
options,
body: Body::Host {
- body: body.into(),
+ body: body.map_err(Into::into).boxed_unsync(),
result_tx: tx,
},
},
@@ -81,11 +85,11 @@ impl Request {
req: http::Request<T>,
) -> (
Self,
- impl Future<Output = Result<(), ErrorCode>> + Send + 'static,
+ impl Future<Output = Result<(), Error>> + Send + 'static,
)
where
T: http_body::Body<Data = Bytes> + Send + 'static,
- T::Error: Into<ErrorCode>,
+ T::Error: Into<Error>,
{
let (
http::request::Parts {
@@ -109,7 +113,7 @@ impl Request {
path_and_query,
FieldMap::new_immutable(headers),
None,
- body.map_err(Into::into).boxed_unsync(),
+ body,
)
}
@@ -121,9 +125,9 @@ impl Request {
pub fn into_http<T: WasiHttpView + 'static>(
self,
store: impl AsContextMut<Data = T>,
- fut: impl Future<Output = Result<(), ErrorCode>> + Send + 'static,
+ fut: impl Future<Output = Result<(), Error>> + Send + 'static,
) -> HttpResult<(
- http::Request<UnsyncBoxBody<Bytes, ErrorCode>>,
+ http::Request<UnsyncBoxBody<Bytes, Error>>,
Option<Arc<RequestOptions>>,
)> {
self.into_http_with_getter(store, fut, T::http)
@@ -133,10 +137,10 @@ impl Request {
pub fn into_http_with_getter<T: 'static>(
self,
mut store: impl AsContextMut<Data = T>,
- fut: impl Future<Output = Result<(), ErrorCode>> + Send + 'static,
+ fut: impl Future<Output = Result<(), Error>> + Send + 'static,
getter: fn(&mut T) -> WasiHttpCtxView<'_>,
) -> HttpResult<(
- http::Request<UnsyncBoxBody<Bytes, ErrorCode>>,
+ http::Request<UnsyncBoxBody<Bytes, Error>>,
Option<Arc<RequestOptions>>,
)> {
let Request {
@@ -187,7 +191,7 @@ impl Request {
};
fut.await
}));
- body.with_content_length(limit, http_result_tx, ErrorCode::HttpRequestBodySize)
+ body.with_content_length(limit, http_result_tx, Error::HttpRequestBodySize)
.boxed_unsync()
} else {
_ = result_tx.send(Box::new(fut));
@@ -230,232 +234,8 @@ impl Request {
.uri(uri)
.body(body)
.map_err(|err| ErrorCode::InternalError(Some(err.to_string())))?;
- let (req, body) = req.into_parts();
- Ok((http::Request::from_parts(req, body), options))
- }
-}
-
-/// The default implementation of how an outgoing request is sent.
-///
-/// This implementation is used by the `wasi:http/handler` interface
-/// default implementation.
-///
-/// The returned [Future] can be used to communicate
-/// a request processing error, if any, to the constructor of the request.
-/// For example, if the request was constructed via `wasi:http/types.request#new`,
-/// a result resolved from it will be forwarded to the guest on the future handle returned.
-///
-/// This function performs no `Content-Length` validation.
-#[cfg(feature = "default-send-request")]
-pub async fn default_send_request(
- mut req: http::Request<impl http_body::Body<Data = Bytes, Error = ErrorCode> + Send + 'static>,
- options: Option<RequestOptions>,
-) -> Result<
- (
- http::Response<impl http_body::Body<Data = Bytes, Error = ErrorCode>>,
- impl Future<Output = Result<(), ErrorCode>> + Send,
- ),
- ErrorCode,
-> {
- 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;
-
- 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 {}
-
- fn dns_error(rcode: String, info_code: u16) -> ErrorCode {
- ErrorCode::DnsError(crate::p3::bindings::http::types::DnsErrorPayload {
- rcode: Some(rcode),
- info_code: Some(info_code),
- })
+ Ok((req, options))
}
-
- let uri = req.uri();
- let authority = uri.authority().ok_or(ErrorCode::HttpRequestUriInvalid)?;
- let use_tls = uri.scheme() == Some(&Scheme::HTTPS);
- let authority = if authority.port().is_some() {
- authority.to_string()
- } else {
- let port = if use_tls { 443 } else { 80 };
- format!("{authority}:{port}")
- };
-
- let connect_timeout = options
- .and_then(
- |RequestOptions {
- connect_timeout, ..
- }| connect_timeout,
- )
- .unwrap_or(Duration::from_secs(600));
-
- let first_byte_timeout = options
- .and_then(
- |RequestOptions {
- first_byte_timeout, ..
- }| first_byte_timeout,
- )
- .unwrap_or(Duration::from_secs(600));
-
- let between_bytes_timeout = options
- .and_then(
- |RequestOptions {
- between_bytes_timeout,
- ..
- }| between_bytes_timeout,
- )
- .unwrap_or(Duration::from_secs(600));
-
- let stream = match tokio::time::timeout(connect_timeout, TcpStream::connect(&authority)).await {
- Ok(Ok(stream)) => stream,
- Ok(Err(err)) if err.kind() == std::io::ErrorKind::AddrNotAvailable => {
- return Err(dns_error("address not available".to_string(), 0));
- }
- Ok(Err(err))
- if err
- .to_string()
- .starts_with("failed to lookup address information") =>
- {
- return Err(dns_error("address not available".to_string(), 0));
- }
- Ok(Err(err)) => {
- tracing::warn!(?err, "connection refused");
- return Err(ErrorCode::ConnectionRefused);
- }
- Err(..) => return Err(ErrorCode::ConnectionTimeout),
- };
- 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(),
- };
- let config = rustls::ClientConfig::builder()
- .with_root_certificates(root_cert_store)
- .with_no_client_auth();
- let connector = tokio_rustls::TlsConnector::from(std::sync::Arc::new(config));
- let domain = crate::tls_server_name(&authority).map_err(|e| {
- tracing::warn!("dns lookup error: {e:?}");
- dns_error("invalid dns name".to_string(), 0)
- })?;
- let stream = connector.connect(domain, stream).await.map_err(|e| {
- tracing::warn!("tls protocol error: {e:?}");
- ErrorCode::TlsProtocolError
- })?;
- stream.boxed()
- } else {
- stream.boxed()
- };
- let (mut sender, conn) = tokio::time::timeout(
- connect_timeout,
- // TODO: we should plumb the builder through the http context, and use it here
- hyper::client::conn::http1::Builder::new().handshake(crate::io::TokioIo::new(stream)),
- )
- .await
- .map_err(|_| ErrorCode::ConnectionTimeout)?
- .map_err(ErrorCode::from_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
- *req.uri_mut() = http::Uri::builder()
- .path_and_query(
- req.uri()
- .path_and_query()
- .map(|p| p.as_str())
- .unwrap_or("/"),
- )
- .build()
- .expect("comes from valid request");
-
- let send = async move {
- use core::task::Context;
-
- /// Wrapper around [hyper::body::Incoming] used to
- /// account for request option timeout configuration
- struct IncomingResponseBody {
- incoming: hyper::body::Incoming,
- timeout: tokio::time::Interval,
- }
- impl http_body::Body for IncomingResponseBody {
- type Data = <hyper::body::Incoming as http_body::Body>::Data;
- type Error = ErrorCode;
-
- fn poll_frame(
- mut self: Pin<&mut Self>,
- cx: &mut Context<'_>,
- ) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
- match Pin::new(&mut self.as_mut().incoming).poll_frame(cx) {
- Poll::Ready(None) => Poll::Ready(None),
- Poll::Ready(Some(Err(err))) => {
- Poll::Ready(Some(Err(ErrorCode::from_hyper_response_error(err))))
- }
- Poll::Ready(Some(Ok(frame))) => {
- self.timeout.reset();
- Poll::Ready(Some(Ok(frame)))
- }
- Poll::Pending => {
- ready!(self.timeout.poll_tick(cx));
- Poll::Ready(Some(Err(ErrorCode::ConnectionReadTimeout)))
- }
- }
- }
- fn is_end_stream(&self) -> bool {
- self.incoming.is_end_stream()
- }
- fn size_hint(&self) -> http_body::SizeHint {
- self.incoming.size_hint()
- }
- }
-
- let res = tokio::time::timeout(first_byte_timeout, sender.send_request(req))
- .await
- .map_err(|_| ErrorCode::ConnectionReadTimeout)?
- .map_err(ErrorCode::from_hyper_request_error)?;
- let mut timeout = tokio::time::interval(between_bytes_timeout);
- timeout.reset();
- Ok(res.map(|incoming| IncomingResponseBody { incoming, timeout }))
- };
- let mut send = pin!(send);
- let mut conn = Some(conn);
- // Wait for response while driving connection I/O
- let res = poll_fn(|cx| match send.as_mut().poll(cx) {
- Poll::Ready(Ok(res)) => Poll::Ready(Ok(res)),
- Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
- Poll::Pending => {
- // Response is not ready, poll `hyper` connection to drive I/O if it has not completed yet
- let Some(fut) = conn.as_mut() else {
- // `hyper` connection already completed
- return Poll::Pending;
- };
- let res = ready!(Pin::new(fut).poll(cx));
- // `hyper` connection completed, record that to prevent repeated poll
- conn = None;
- match res {
- // `hyper` connection has successfully completed, optimistically poll for response
- Ok(()) => send.as_mut().poll(cx),
- // `hyper` connection has failed, return the error
- Err(err) => Poll::Ready(Err(ErrorCode::from_hyper_request_error(err))),
- }
- }
- })
- .await?;
- Ok((res, async move {
- let Some(conn) = conn.take() else {
- // `hyper` connection has already completed
- return Ok(());
- };
- conn.await.map_err(ErrorCode::from_hyper_response_error)
- }))
}
#[cfg(test)]
@@ -501,7 +281,7 @@ mod tests {
WasiHttpCtxView {
ctx: &mut self.http,
table: &mut self.table,
- hooks: crate::p3::default_hooks(),
+ hooks: crate::default_hooks(),
}
}
}
@@ -519,9 +299,7 @@ mod tests {
Some(PathAndQuery::from_static("/path?query=1")),
FieldMap::default(),
None,
- Full::new(Bytes::from_static(b"body"))
- .map_err(|x| match x {})
- .boxed_unsync(),
+ Full::new(Bytes::from_static(b"body")).boxed_unsync(),
);
let mut store = Store::new(&engine, TestCtx::new());
let (http_req, options) = req.into_http(&mut store, async { Ok(()) }).unwrap();
@@ -555,12 +333,12 @@ mod tests {
None, // <-- should fail, must be Some(_) when authority is set
FieldMap::default(),
None,
- Empty::new().map_err(|x| match x {}).boxed_unsync(),
+ Empty::new().boxed_unsync(),
);
let mut store = Store::new(&Engine::default(), TestCtx::new());
let result = req
.into_http(&mut store, async {
- Err(ErrorCode::InternalError(Some("uh oh".to_string())))
+ Err(Error::InternalError(Some("uh oh".to_string())))
})
.unwrap_err();
assert!(matches!(
@@ -571,7 +349,7 @@ mod tests {
let result = pin!(fut).poll(&mut cx);
assert!(matches!(
result,
- Poll::Ready(Err(ErrorCode::InternalError(Some(_))))
+ Poll::Ready(Err(Error::InternalError(Some(_))))
));
Ok(())
diff --git a/crates/wasi-http/src/p3/response.rs b/crates/wasi-http/src/p3/response.rs
index 6776faf052..750a5a816a 100644
--- a/crates/wasi-http/src/p3/response.rs
+++ b/crates/wasi-http/src/p3/response.rs
@@ -1,7 +1,6 @@
use crate::p3::bindings::http::types::ErrorCode;
use crate::p3::body::{Body, GuestBody};
-use crate::p3::{WasiHttpCtxView, WasiHttpView};
-use crate::{FieldMap, get_content_length};
+use crate::{Error, FieldMap, WasiHttpCtxView, WasiHttpView, get_content_length};
use bytes::Bytes;
use http::StatusCode;
use http_body_util::BodyExt as _;
@@ -45,8 +44,8 @@ impl Response {
pub fn into_http<T: WasiHttpView + 'static>(
self,
store: impl AsContextMut<Data = T>,
- fut: impl Future<Output = Result<(), ErrorCode>> + Send + 'static,
- ) -> wasmtime::Result<http::Response<UnsyncBoxBody<Bytes, ErrorCode>>> {
+ fut: impl Future<Output = Result<(), Error>> + Send + 'static,
+ ) -> wasmtime::Result<http::Response<UnsyncBoxBody<Bytes, Error>>> {
self.into_http_with_getter(store, fut, T::http)
}
@@ -55,9 +54,9 @@ impl Response {
pub fn into_http_with_getter<T: 'static>(
self,
store: impl AsContextMut<Data = T>,
- fut: impl Future<Output = Result<(), ErrorCode>> + Send + 'static,
+ fut: impl Future<Output = Result<(), Error>> + Send + 'static,
getter: fn(&mut T) -> WasiHttpCtxView<'_>,
- ) -> wasmtime::Result<http::Response<UnsyncBoxBody<Bytes, ErrorCode>>> {
+ ) -> wasmtime::Result<http::Response<UnsyncBoxBody<Bytes, Error>>> {
let res = http::Response::try_from(self)?;
let (res, body) = res.into_parts();
let body = match body {
@@ -94,11 +93,11 @@ impl Response {
res: http::Response<T>,
) -> (
Self,
- impl Future<Output = Result<(), ErrorCode>> + Send + 'static,
+ impl Future<Output = Result<(), Error>> + Send + 'static,
)
where
T: http_body::Body<Data = Bytes> + Send + 'static,
- T::Error: Into<ErrorCode>,
+ T::Error: Into<Error>,
{
let (parts, body) = res.into_parts();
let (result_tx, result_rx) = tokio::sync::oneshot::channel();
diff --git a/crates/wasi-http/tests/all/p2.rs b/crates/wasi-http/tests/all/p2.rs
index 7702d053be..a6731c8cf5 100644
--- a/crates/wasi-http/tests/all/p2.rs
+++ b/crates/wasi-http/tests/all/p2.rs
@@ -15,18 +15,16 @@ use wasmtime::{
};
use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView, p2::pipe::MemoryOutputPipe};
use wasmtime_wasi_http::{
- RequestOptions, WasiHttpCtx,
+ Error, RequestOptions, WasiBody, WasiHttpCtx, WasiHttpCtxView, WasiHttpHooks, WasiHttpView,
io::TokioIo,
p2::bindings::http::types::{ErrorCode, Scheme},
- p2::body::HyperOutgoingBody,
- p2::{HttpResult, WasiHttpCtxView, WasiHttpHooks, WasiHttpView},
};
type RequestSender = Arc<
dyn Fn(
- hyper::Request<HyperOutgoingBody>,
+ hyper::Request<WasiBody>,
Option<RequestOptions>,
- ) -> HttpResult<http::Response<HyperOutgoingBody>>
+ ) -> Result<http::Response<WasiBody>, Error>
+ Send
+ Sync,
>;
@@ -68,14 +66,18 @@ impl WasiHttpView for Ctx {
impl WasiHttpHooks for MyHttpHooks {
fn send_request(
&mut self,
- request: hyper::Request<HyperOutgoingBody>,
+ request: http::Request<WasiBody>,
config: Option<RequestOptions>,
+ _io: Box<dyn Future<Output = Result<(), Error>> + Send>,
) -> Box<
dyn Future<
- Output = HttpResult<(
- http::Response<HyperOutgoingBody>,
- Box<dyn Future<Output = Result<(), ErrorCode>> + Send>,
- )>,
+ Output = Result<
+ (
+ http::Response<WasiBody>,
+ Box<dyn Future<Output = Result<(), Error>> + Send>,
+ ),
+ Error,
+ >,
> + Send,
> {
let me = self.clone();
@@ -83,7 +85,7 @@ impl WasiHttpHooks for MyHttpHooks {
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());
+ return Err(Error::HttpRequestDenied);
}
}
if let Some(send_request) = me.send_request.clone() {
@@ -93,8 +95,7 @@ impl WasiHttpHooks for MyHttpHooks {
Box::new(async { Ok(()) }) as Box<dyn Future<Output = _> + Send>,
))
} else {
- let (res, io) =
- wasmtime_wasi_http::p2::default_send_request(request, config).await?;
+ let (res, io) = wasmtime_wasi_http::default_send_request(request, config).await?;
Ok((res.map(BodyExt::boxed_unsync), Box::new(io)))
}
})
@@ -322,16 +323,10 @@ async fn do_wasi_http_hash_all(override_send_request: bool) -> Result<()> {
};
let send_request = if override_send_request {
- 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()
- })
- })
- }) as RequestSender,
- )
+ Some(Arc::new(move |request: hyper::Request<WasiBody>, _opts| {
+ handle(request.into_parts().0)
+ .map(|resp| resp.map(|body| body.map_err(|e| e.into()).boxed_unsync()))
+ }) as RequestSender)
} else {
let server = async move {
loop {
@@ -588,23 +583,22 @@ 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>, _opts| {
- let authority = request.uri().authority().expect("request has authority");
- assert!(
- authority.port().is_none(),
- "expected no port in authority, got: {authority}"
- );
- 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 send_request: RequestSender = Arc::new(|request: hyper::Request<WasiBody>, _opts| {
+ let authority = request.uri().authority().expect("request has authority");
+ assert!(
+ authority.port().is_none(),
+ "expected no port in authority, got: {authority}"
+ );
+ let resp = hyper::Response::builder()
+ .status(StatusCode::OK)
+ .body(
+ body::full(Bytes::from("ok"))
+ .map_err(|e| e.into())
+ .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 58aed0fb18..b71a06521a 100644
--- a/crates/wasi-http/tests/all/p3/mod.rs
+++ b/crates/wasi-http/tests/all/p3/mod.rs
@@ -6,7 +6,7 @@ use futures::SinkExt;
use futures::channel::oneshot;
use http::HeaderValue;
use http_body::Body;
-use http_body_util::{BodyExt as _, Collected, Empty, combinators::UnsyncBoxBody};
+use http_body_util::{BodyExt as _, Collected, Empty};
use std::io::Write;
use std::path::Path;
use std::pin::Pin;
@@ -18,16 +18,19 @@ use wasm_compose::config::{Config, Dependency, Instantiation, InstantiationArg};
use wasmtime::component::{Component, Linker, ResourceTable};
use wasmtime::{Result, Store, ToWasmtimeResult as _, error::Context as _, format_err};
use wasmtime_wasi::p3::bindings::Command;
-use wasmtime_wasi::{TrappableError, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
+use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
+use wasmtime_wasi_http::p3::Request;
use wasmtime_wasi_http::p3::bindings::Service;
use wasmtime_wasi_http::p3::bindings::http::types::ErrorCode;
-use wasmtime_wasi_http::p3::{self, Request, WasiHttpCtxView, WasiHttpHooks, WasiHttpView};
-use wasmtime_wasi_http::{DEFAULT_FORBIDDEN_HEADERS, RequestOptions, WasiHttpCtx};
+use wasmtime_wasi_http::{
+ DEFAULT_FORBIDDEN_HEADERS, Error, RequestOptions, WasiBody, WasiHttpCtx, WasiHttpCtxView,
+ WasiHttpHooks, WasiHttpView, default_send_request,
+};
foreach_p3_http!(assert_test_exists);
struct TestHooks {
- request_body_tx: Option<oneshot::Sender<UnsyncBoxBody<Bytes, ErrorCode>>>,
+ request_body_tx: Option<oneshot::Sender<WasiBody>>,
}
impl WasiHttpHooks for TestHooks {
@@ -37,17 +40,17 @@ impl WasiHttpHooks for TestHooks {
fn send_request(
&mut self,
- request: http::Request<UnsyncBoxBody<Bytes, ErrorCode>>,
+ request: http::Request<WasiBody>,
options: Option<RequestOptions>,
- fut: Box<dyn Future<Output = Result<(), ErrorCode>> + Send>,
+ fut: Box<dyn Future<Output = Result<(), Error>> + Send>,
) -> Box<
dyn Future<
Output = Result<
(
- http::Response<UnsyncBoxBody<Bytes, ErrorCode>>,
- Box<dyn Future<Output = Result<(), ErrorCode>> + Send>,
+ http::Response<WasiBody>,
+ Box<dyn Future<Output = Result<(), Error>> + Send>,
),
- TrappableError<ErrorCode>,
+ Error,
>,
> + Send,
> {
@@ -68,7 +71,7 @@ impl WasiHttpHooks for TestHooks {
Box::new(async move {
use http_body_util::BodyExt;
- let (res, io) = p3::default_send_request(request, options).await?;
+ let (res, io) = default_send_request(request, options).await?;
Ok((
res.map(BodyExt::boxed_unsync),
Box::new(io) as Box<dyn Future<Output = _> + Send>,
@@ -86,7 +89,7 @@ struct Ctx {
}
impl Ctx {
- fn new(request_body_tx: oneshot::Sender<UnsyncBoxBody<Bytes, ErrorCode>>) -> Self {
+ fn new(request_body_tx: oneshot::Sender<WasiBody>) -> Self {
Self {
table: ResourceTable::default(),
wasi: WasiCtxBuilder::new().inherit_stdio().build(),
@@ -147,10 +150,10 @@ async fn run_cli(path: &str, server: &Server) -> wasmtime::Result<()> {
.map_err(|()| format_err!("`wasi:cli/run#run` failed"))
}
-async fn run_http<E: Into<ErrorCode> + 'static>(
+async fn run_http<E: Into<Error> + 'static>(
component_filename: &str,
req: http::Request<impl Body<Data = Bytes, Error = E> + Send + Sync + 'static>,
- request_body_tx: oneshot::Sender<UnsyncBoxBody<Bytes, ErrorCode>>,
+ request_body_tx: oneshot::Sender<WasiBody>,
) -> wasmtime::Result<Result<http::Response<Collected<Bytes>>, Option<ErrorCode>>> {
let engine = test_programs_artifacts::engine(|config| {
config.wasm_backtrace_details(wasmtime::WasmBacktraceDetails::Enable);
diff --git a/src/commands/run.rs b/src/commands/run.rs
index 5689aa0089..4ab21df2a6 100644
--- a/src/commands/run.rs
+++ b/src/commands/run.rs
@@ -1426,22 +1426,10 @@ impl WasiView for Host {
}
#[cfg(feature = "wasi-http")]
-impl wasmtime_wasi_http::p2::WasiHttpView for Host {
- fn http(&mut self) -> wasmtime_wasi_http::p2::WasiHttpCtxView<'_> {
+impl wasmtime_wasi_http::WasiHttpView for Host {
+ fn http(&mut self) -> wasmtime_wasi_http::WasiHttpCtxView<'_> {
let ctx = self.wasi_http.as_mut().unwrap();
- wasmtime_wasi_http::p2::WasiHttpCtxView {
- table: WasiView::ctx(self.wasip1_ctx.as_mut().unwrap()).table,
- ctx,
- hooks: &mut self.wasi_http_hooks,
- }
- }
-}
-
-#[cfg(all(feature = "wasi-http", feature = "component-model-async"))]
-impl wasmtime_wasi_http::p3::WasiHttpView for Host {
- fn http(&mut self) -> wasmtime_wasi_http::p3::WasiHttpCtxView<'_> {
- let ctx = self.wasi_http.as_mut().unwrap();
- wasmtime_wasi_http::p3::WasiHttpCtxView {
+ wasmtime_wasi_http::WasiHttpCtxView {
table: WasiView::ctx(self.wasip1_ctx.as_mut().unwrap()).table,
ctx,
hooks: &mut self.wasi_http_hooks,
diff --git a/src/commands/serve.rs b/src/commands/serve.rs
index 4bc291fb50..45b12096d9 100644
--- a/src/commands/serve.rs
+++ b/src/commands/serve.rs
@@ -1,8 +1,6 @@
use crate::common::{HttpHooks, Profile, RunCommon, RunTarget};
-use bytes::Bytes;
use clap::Parser;
use http::{HeaderMap, HeaderName, HeaderValue, Response, StatusCode};
-use http_body_util::combinators::UnsyncBoxBody;
use http_body_util::{BodyExt as _, Full};
use hyper::server::conn::http1;
use pin_project_lite::pin_project;
@@ -31,7 +29,7 @@ use wasmtime_wasi::p2::{StreamError, StreamResult};
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
use wasmtime_wasi_http::WasiHttpCtx;
use wasmtime_wasi_http::handler::{
- self, HandlerState, Instance, Prepared, Proxy, ProxyHandler, ProxyPre, ShouldAccept, ViewFn,
+ HandlerState, Instance, Prepared, Proxy, ProxyHandler, ProxyPre, ShouldAccept,
WorkerExpiration, WorkerState, WorkerStatus,
};
use wasmtime_wasi_http::io::TokioIo;
@@ -82,9 +80,9 @@ impl WasiView for Host {
}
}
-impl wasmtime_wasi_http::p2::WasiHttpView for Host {
- fn http(&mut self) -> wasmtime_wasi_http::p2::WasiHttpCtxView<'_> {
- wasmtime_wasi_http::p2::WasiHttpCtxView {
+impl wasmtime_wasi_http::WasiHttpView for Host {
+ fn http(&mut self) -> wasmtime_wasi_http::WasiHttpCtxView<'_> {
+ wasmtime_wasi_http::WasiHttpCtxView {
ctx: &mut self.http,
table: &mut self.table,
hooks: &mut self.hooks,
@@ -92,17 +90,6 @@ impl wasmtime_wasi_http::p2::WasiHttpView for Host {
}
}
-#[cfg(feature = "component-model-async")]
-impl wasmtime_wasi_http::p3::WasiHttpView for Host {
- fn http(&mut self) -> wasmtime_wasi_http::p3::WasiHttpCtxView<'_> {
- wasmtime_wasi_http::p3::WasiHttpCtxView {
- table: &mut self.table,
- ctx: &mut self.http,
- hooks: &mut self.hooks,
- }
- }
-}
-
const DEFAULT_ADDR: std::net::SocketAddr = std::net::SocketAddr::new(
std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
8080,
@@ -888,13 +875,6 @@ impl HostHandlerState {
store.data_mut().write_profile = Some(write_profile);
self.instance.instantiate_async(&mut *store).await
}
-
- fn view(&self) -> ViewFn<Host> {
- match &self.instance {
- ProxyPre::P2(_) => ViewFn::P2(wasmtime_wasi_http::p2::WasiHttpView::http),
- ProxyPre::P3(_) => ViewFn::P3(wasmtime_wasi_http::p3::WasiHttpView::http),
- }
- }
}
impl HandlerState for HostHandlerState {
@@ -914,7 +894,7 @@ impl HandlerState for HostHandlerState {
Ok(Instance {
store,
proxy,
- view: self.view(),
+ view: wasmtime_wasi_http::WasiHttpView::http,
expiration: HostWorkerExpiration {
idle_timeout: self.cmd.idle_instance_timeout,
request_timeout: self.cmd.run.common.wasm.timeout.unwrap_or(Duration::MAX),
@@ -1172,9 +1152,7 @@ async fn handle_request(
handler: &ProxyHandler<HostHandlerState>,
debuggee_store: Option<&mut Store<Host>>,
mut req: Request,
-) -> Result<hyper::Response<UnsyncBoxBody<Bytes, wasmtime::Error>>> {
- use wasmtime_wasi_http::p3::bindings::http::types::ErrorCode;
-
+) -> Result<hyper::Response<wasmtime_wasi_http::WasiBody>> {
// This is used to throttle the maximum number of concurrent requests that
// can be processed at any one point in time before delegating to
// `handler.handle(...)` below.
@@ -1192,11 +1170,7 @@ async fn handle_request(
req.uri()
);
- let req = req.map(|body| {
- body.map_err(ErrorCode::from_hyper_request_error)
- .map_err(handler::ErrorCode::from)
- .boxed_unsync()
- });
+ let req = req.map(|body| body.map_err(|e| e.into()).boxed_unsync());
match debuggee_store {
// For debugging go ahead and synchronously execute the instance here
@@ -1209,7 +1183,7 @@ async fn handle_request(
store.as_context_mut(),
&instance,
req,
- handler.state().view(),
+ wasmtime_wasi_http::WasiHttpView::http,
tx,
)?;
store
diff --git a/src/common.rs b/src/common.rs
index 15c0bcea6b..07c74ca1aa 100644
--- a/src/common.rs
+++ b/src/common.rs
@@ -547,15 +547,12 @@ impl Default for HttpHooks {
}
#[cfg(feature = "wasi-http")]
-impl wasmtime_wasi_http::p2::WasiHttpHooks for HttpHooks {
- fn outgoing_body_buffer_chunks(&mut self) -> usize {
+impl wasmtime_wasi_http::WasiHttpHooks for HttpHooks {
+ fn p2_outgoing_body_buffer_chunks(&mut self) -> usize {
self.p2_outgoing_body_buffer_chunks
}
- fn outgoing_body_chunk_size(&mut self) -> usize {
+ fn p2_outgoing_body_chunk_size(&mut self) -> usize {
self.p2_outgoing_body_chunk_size
}
}
-
-#[cfg(feature = "wasi-http")]
-impl wasmtime_wasi_http::p3::WasiHttpHooks for HttpHooks {}