Skip to content

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

wasip3: Add support to `wasmtime serve` (#11646)

Alex Crichton84e249978f92
diff --git a/Cargo.toml b/Cargo.toml
index de388fc9fe..7e206c0871 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -491,6 +491,7 @@ component-model-async = [
"wasmtime-cli-flags/component-model-async",
"component-model",
"wasmtime-wasi?/p3",
+ "wasmtime-wasi-http?/p3",
]
# This feature, when enabled, will statically compile out all logging statements
diff --git a/crates/test-programs/src/bin/cli_serve_p3_hello_world.rs b/crates/test-programs/src/bin/cli_serve_p3_hello_world.rs
new file mode 100644
index 0000000000..86cefcdcd3
--- /dev/null
+++ b/crates/test-programs/src/bin/cli_serve_p3_hello_world.rs
@@ -0,0 +1,26 @@
+use test_programs::p3::wasi::http::types::{ErrorCode, Fields, Request, Response};
+use test_programs::p3::{proxy, wit_future, wit_stream};
+
+struct T;
+
+proxy::export!(T);
+
+impl proxy::exports::wasi::http::handler::Guest for T {
+ async fn handle(_request: Request) -> Result<Response, ErrorCode> {
+ let (mut body_tx, body_rx) = wit_stream::new();
+ let (body_result_tx, body_result_rx) = wit_future::new(|| Ok(None));
+ let (response, _future_result) =
+ Response::new(Fields::new(), Some(body_rx), body_result_rx);
+ drop(body_result_tx);
+
+ wit_bindgen::spawn(async move {
+ let remaining = body_tx.write_all(b"Hello, WASI!".to_vec()).await;
+ assert!(remaining.is_empty());
+ });
+ Ok(response)
+ }
+}
+
+fn main() {
+ unreachable!()
+}
diff --git a/crates/wasi-http/src/p3/bindings.rs b/crates/wasi-http/src/p3/bindings.rs
index b7fec724c1..f467df417b 100644
--- a/crates/wasi-http/src/p3/bindings.rs
+++ b/crates/wasi-http/src/p3/bindings.rs
@@ -15,7 +15,7 @@ mod generated {
"wasi:http/types/[static]response.new": async | store | trappable | tracing,
default: trappable | tracing,
},
- exports: { default: async | store },
+ exports: { default: async | store | task_exit },
with: {
"wasi:http/types/fields": with::Fields,
"wasi:http/types/request": crate::p3::Request,
diff --git a/crates/wasi-http/src/p3/conv.rs b/crates/wasi-http/src/p3/conv.rs
index ef4587fb78..f625148824 100644
--- a/crates/wasi-http/src/p3/conv.rs
+++ b/crates/wasi-http/src/p3/conv.rs
@@ -11,7 +11,7 @@ impl From<Infallible> for ErrorCode {
impl ErrorCode {
/// Translate a [`hyper::Error`] to a wasi-http [ErrorCode] in the context of a request.
- pub(crate) fn from_hyper_request_error(err: hyper::Error) -> Self {
+ 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>() {
diff --git a/crates/wasi-http/src/p3/proxy.rs b/crates/wasi-http/src/p3/proxy.rs
index d0fd2a0d36..74c2eb1564 100644
--- a/crates/wasi-http/src/p3/proxy.rs
+++ b/crates/wasi-http/src/p3/proxy.rs
@@ -2,7 +2,7 @@ use crate::p3::WasiHttpView;
use crate::p3::bindings::Proxy;
use crate::p3::bindings::http::types::{ErrorCode, Request, Response};
use anyhow::Context as _;
-use wasmtime::component::Accessor;
+use wasmtime::component::{Accessor, TaskExit};
impl Proxy {
/// Call `wasi:http/handler#handle` on [Proxy] getting a [Response] back.
@@ -10,7 +10,7 @@ impl Proxy {
&self,
store: &Accessor<impl WasiHttpView>,
req: impl Into<Request>,
- ) -> wasmtime::Result<Result<Response, ErrorCode>> {
+ ) -> wasmtime::Result<Result<(Response, TaskExit), ErrorCode>> {
let req = store.with(|mut store| {
store
.data_mut()
@@ -20,7 +20,7 @@ impl Proxy {
.context("failed to push request to table")
})?;
match self.wasi_http_handler().call_handle(store, req).await? {
- Ok(res) => {
+ (Ok(res), task) => {
let res = store.with(|mut store| {
store
.data_mut()
@@ -29,9 +29,9 @@ impl Proxy {
.delete(res)
.context("failed to delete response from table")
})?;
- Ok(Ok(res))
+ Ok(Ok((res, task)))
}
- Err(err) => Ok(Err(err)),
+ (Err(err), _) => Ok(Err(err)),
}
}
}
diff --git a/crates/wasi-http/tests/all/p3/mod.rs b/crates/wasi-http/tests/all/p3/mod.rs
index d87b6dadfd..10171b17b3 100644
--- a/crates/wasi-http/tests/all/p3/mod.rs
+++ b/crates/wasi-http/tests/all/p3/mod.rs
@@ -127,13 +127,14 @@ async fn run_http<E: Into<ErrorCode> + 'static>(
.run_concurrent(&mut store, async |store| {
try_join!(
async {
- let res = match proxy.handle(store, req).await? {
- Ok(res) => res,
+ let (res, task) = match proxy.handle(store, req).await? {
+ Ok(pair) => pair,
Err(err) => return Ok(Err(Some(err))),
};
let res = store.with(|store| res.into_http(store, async { Ok(()) }))?;
let (parts, body) = res.into_parts();
let body = body.collect().await.context("failed to collect body")?;
+ task.block(store).await;
Ok(Ok(http::Response::from_parts(parts, body)))
},
async { io.await.context("failed to consume request body") }
diff --git a/src/commands/serve.rs b/src/commands/serve.rs
index dcb59c5137..e308f7de71 100644
--- a/src/commands/serve.rs
+++ b/src/commands/serve.rs
@@ -1,7 +1,10 @@
use crate::common::{Profile, RunCommon, RunTarget};
use anyhow::{Result, bail};
+use bytes::Bytes;
use clap::Parser;
use http::{Response, StatusCode};
+use http_body_util::BodyExt as _;
+use http_body_util::combinators::BoxBody;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::pin::Pin;
@@ -21,12 +24,11 @@ use wasmtime::component::{Component, Linker, ResourceTable};
use wasmtime::{Engine, Store, StoreLimits, UpdateDeadline};
use wasmtime_wasi::p2::{StreamError, StreamResult};
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};
-use wasmtime_wasi_http::bindings::ProxyPre;
-use wasmtime_wasi_http::bindings::http::types::{ErrorCode, Scheme};
+use wasmtime_wasi_http::bindings as p2;
use wasmtime_wasi_http::io::TokioIo;
use wasmtime_wasi_http::{
DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS, DEFAULT_OUTGOING_BODY_CHUNK_SIZE, WasiHttpCtx,
- WasiHttpView, body::HyperOutgoingBody,
+ WasiHttpView,
};
#[cfg(feature = "wasi-config")]
@@ -43,6 +45,9 @@ struct Host {
http_outgoing_body_buffer_chunks: Option<usize>,
http_outgoing_body_chunk_size: Option<usize>,
+ #[cfg(feature = "component-model-async")]
+ p3_http: DefaultP3Ctx,
+
limits: StoreLimits,
#[cfg(feature = "wasi-nn")]
@@ -86,6 +91,21 @@ impl WasiHttpView for Host {
}
}
+#[cfg(feature = "component-model-async")]
+struct DefaultP3Ctx;
+#[cfg(feature = "component-model-async")]
+impl wasmtime_wasi_http::p3::WasiHttpCtx for DefaultP3Ctx {}
+
+#[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.p3_http,
+ }
+ }
+}
+
const DEFAULT_ADDR: std::net::SocketAddr = std::net::SocketAddr::new(
std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
8080,
@@ -191,6 +211,8 @@ impl ServeCommand {
wasi_keyvalue: None,
#[cfg(feature = "profiling")]
guest_profiler: None,
+ #[cfg(feature = "component-model-async")]
+ p3_http: DefaultP3Ctx,
};
if self.run.common.wasi.nn == Some(true) {
@@ -270,8 +292,19 @@ impl ServeCommand {
if cli == Some(true) {
self.run.add_wasmtime_wasi_to_linker(linker)?;
wasmtime_wasi_http::add_only_http_to_linker_async(linker)?;
+ #[cfg(feature = "component-model-async")]
+ if self.run.common.wasi.p3.unwrap_or(crate::common::P3_DEFAULT) {
+ wasmtime_wasi_http::p3::add_to_linker(linker)?;
+ }
} else {
wasmtime_wasi_http::add_to_linker_async(linker)?;
+ #[cfg(feature = "component-model-async")]
+ if self.run.common.wasi.p3.unwrap_or(crate::common::P3_DEFAULT) {
+ wasmtime_wasi_http::p3::add_to_linker(linker)?;
+ wasmtime_wasi::p3::clocks::add_to_linker(linker)?;
+ wasmtime_wasi::p3::random::add_to_linker(linker)?;
+ wasmtime_wasi::p3::cli::add_to_linker(linker)?;
+ }
}
if self.run.common.wasi.nn == Some(true) {
@@ -360,7 +393,13 @@ impl ServeCommand {
};
let instance = linker.instantiate_pre(&component)?;
- let instance = ProxyPre::new(instance)?;
+ #[cfg(feature = "component-model-async")]
+ let instance = match wasmtime_wasi_http::p3::bindings::ProxyIndices::new(&instance) {
+ Ok(indices) => ProxyPre::P3(indices, instance),
+ Err(_) => ProxyPre::P2(p2::ProxyPre::new(instance)?),
+ };
+ #[cfg(not(feature = "component-model-async"))]
+ let instance = ProxyPre::P2(p2::ProxyPre::new(instance)?);
// Spawn background task(s) waiting for graceful shutdown signals. This
// always listens for ctrl-c but additionally can listen for a TCP
@@ -430,9 +469,6 @@ impl ServeCommand {
let h = h.clone();
async move {
use http_body_util::{BodyExt, Full};
- fn to_errorcode(_: Infallible) -> ErrorCode {
- unreachable!()
- }
match handle_request(h, req, comp).await {
Ok(r) => Ok::<_, Infallible>(r),
Err(e) => {
@@ -456,7 +492,7 @@ impl ServeCommand {
.header("Content-Type", "text/html; charset=UTF-8")
.body(
Full::new(bytes::Bytes::from(error_html))
- .map_err(to_errorcode)
+ .map_err(|_| unreachable!())
.boxed(),
)
.unwrap())
@@ -696,10 +732,42 @@ fn setup_guest_profiler(
struct ProxyHandlerInner {
cmd: ServeCommand,
engine: Engine,
- instance_pre: ProxyPre<Host>,
+ instance_pre: ProxyPre,
next_id: AtomicU64,
}
+enum ProxyPre {
+ P2(p2::ProxyPre<Host>),
+ #[cfg(feature = "component-model-async")]
+ P3(
+ wasmtime_wasi_http::p3::bindings::ProxyIndices,
+ wasmtime::component::InstancePre<Host>,
+ ),
+}
+
+impl ProxyPre {
+ async fn instantiate(&self, store: &mut Store<Host>) -> Result<Proxy> {
+ Ok(match self {
+ ProxyPre::P2(pre) => Proxy::P2(pre.instantiate_async(store).await?),
+ #[cfg(feature = "component-model-async")]
+ ProxyPre::P3(indices, pre) => {
+ let instance = pre.instantiate_async(&mut *store).await?;
+ let proxy = indices.load(&mut *store, &instance)?;
+ Proxy::P3(proxy, instance)
+ }
+ })
+ }
+}
+
+enum Proxy {
+ P2(p2::Proxy),
+ #[cfg(feature = "component-model-async")]
+ P3(
+ wasmtime_wasi_http::p3::bindings::Proxy,
+ wasmtime::component::Instance,
+ ),
+}
+
impl ProxyHandlerInner {
fn next_req_id(&self) -> u64 {
self.next_id.fetch_add(1, Ordering::Relaxed)
@@ -710,7 +778,7 @@ impl ProxyHandlerInner {
struct ProxyHandler(Arc<ProxyHandlerInner>);
impl ProxyHandler {
- fn new(cmd: ServeCommand, engine: Engine, instance_pre: ProxyPre<Host>) -> Self {
+ fn new(cmd: ServeCommand, engine: Engine, instance_pre: ProxyPre) -> Self {
Self(Arc::new(ProxyHandlerInner {
cmd,
engine,
@@ -726,7 +794,7 @@ async fn handle_request(
ProxyHandler(inner): ProxyHandler,
req: Request,
component: Component,
-) -> Result<hyper::Response<HyperOutgoingBody>> {
+) -> Result<hyper::Response<BoxBody<Bytes, anyhow::Error>>> {
let (sender, receiver) = tokio::sync::oneshot::channel();
let req_id = inner.next_req_id();
@@ -739,52 +807,91 @@ async fn handle_request(
let mut store = inner.cmd.new_store(&inner.engine, req_id)?;
- let req = store.data_mut().new_incoming_request(Scheme::Http, req)?;
- let out = store.data_mut().new_response_outparam(sender)?;
- let proxy = inner.instance_pre.instantiate_async(&mut store).await?;
-
- let comp = component.clone();
- let task = tokio::task::spawn(async move {
- let (write_profile, epoch_thread) = setup_epoch_handler(&inner.cmd, &mut store, comp)?;
-
- if let Err(e) = proxy
- .wasi_http_incoming_handler()
- .call_handle(&mut store, req, out)
- .await
- {
- log::error!("[{req_id}] :: {e:?}");
- return Err(e);
- }
+ let (write_profile, epoch_thread) =
+ setup_epoch_handler(&inner.cmd, &mut store, component.clone())?;
+
+ match inner.instance_pre.instantiate(&mut store).await? {
+ Proxy::P2(proxy) => {
+ let req = store
+ .data_mut()
+ .new_incoming_request(p2::http::types::Scheme::Http, req)?;
+ let out = store.data_mut().new_response_outparam(sender)?;
+ let task = tokio::task::spawn(async move {
+ if let Err(e) = proxy
+ .wasi_http_incoming_handler()
+ .call_handle(&mut store, req, out)
+ .await
+ {
+ log::error!("[{req_id}] :: {e:?}");
+ return Err(e);
+ }
- write_profile(&mut store);
- drop(epoch_thread);
+ write_profile(&mut store);
+ drop(epoch_thread);
- Ok(())
- });
+ Ok(())
+ });
- let result = match receiver.await {
- Ok(Ok(resp)) => Ok(resp),
- Ok(Err(e)) => Err(e.into()),
- Err(_) => {
- // An error in the receiver (`RecvError`) only indicates that the
- // task exited before a response was sent (i.e., the sender was
- // dropped); it does not describe the underlying cause of failure.
- // Instead we retrieve and propagate the error from inside the task
- // which should more clearly tell the user what went wrong. Note
- // that we assume the task has already exited at this point so the
- // `await` should resolve immediately.
- let e = match task.await {
- Ok(Ok(())) => {
- bail!("guest never invoked `response-outparam::set` method")
+ let result = match receiver.await {
+ Ok(Ok(resp)) => resp,
+ Ok(Err(e)) => bail!(e),
+ Err(_) => {
+ // An error in the receiver (`RecvError`) only indicates that the
+ // task exited before a response was sent (i.e., the sender was
+ // dropped); it does not describe the underlying cause of failure.
+ // Instead we retrieve and propagate the error from inside the task
+ // which should more clearly tell the user what went wrong. Note
+ // that we assume the task has already exited at this point so the
+ // `await` should resolve immediately.
+ let e = match task.await {
+ Ok(Ok(())) => {
+ bail!("guest never invoked `response-outparam::set` method")
+ }
+ Ok(Err(e)) => e,
+ Err(e) => e.into(),
+ };
+ bail!(e.context("guest never invoked `response-outparam::set` method"))
}
- Ok(Err(e)) => e,
- Err(e) => e.into(),
};
- Err(e.context("guest never invoked `response-outparam::set` method"))
+
+ Ok(result.map(|body| body.map_err(|e| e.into()).boxed()))
}
- };
+ #[cfg(feature = "component-model-async")]
+ Proxy::P3(proxy, instance) => {
+ use wasmtime_wasi_http::p3::bindings::http::types::{ErrorCode, Request};
+
+ let (tx, rx) = tokio::sync::oneshot::channel();
+
+ tokio::task::spawn(async move {
+ let guest_result = instance
+ .run_concurrent(&mut store, async move |store| {
+ let (req, body) = req.into_parts();
+ let body = body.map_err(ErrorCode::from_hyper_request_error);
+ let req = http::Request::from_parts(req, body);
+ let (request, request_io_result) = Request::from_http(req);
+ let (res, task) = proxy.handle(store, request).await??;
+ let res =
+ store.with(|mut store| res.into_http(&mut store, request_io_result))?;
+
+ _ = tx.send(res);
+
+ task.block(store).await;
+ anyhow::Ok(())
+ })
+ .await?;
+ if let Err(e) = guest_result {
+ log::error!("[{req_id}] :: {e:?}");
+ return Err(e);
+ }
- result
+ write_profile(&mut store);
+ drop(epoch_thread);
+
+ anyhow::Ok(())
+ });
+ Ok(rx.await?.map(|body| body.map_err(|err| err.into()).boxed()))
+ }
+ }
}
#[derive(Clone)]
diff --git a/tests/all/cli_tests.rs b/tests/all/cli_tests.rs
index 29f899972b..800c5f9e6b 100644
--- a/tests/all/cli_tests.rs
+++ b/tests/all/cli_tests.rs
@@ -2220,6 +2220,30 @@ start a print 1234
&["-Wcomponent-model-async", "-Sp3"],
)
}
+
+ #[tokio::test]
+ #[cfg_attr(not(feature = "component-model-async"), ignore)]
+ async fn cli_serve_p3_hello_world() -> Result<()> {
+ let server = WasmtimeServe::new(CLI_SERVE_P3_HELLO_WORLD_COMPONENT, |cmd| {
+ cmd.arg("-Wcomponent-model-async");
+ cmd.arg("-Sp3,cli");
+ })?;
+
+ let result = server
+ .send_request(
+ hyper::Request::builder()
+ .uri("http://localhost/")
+ .body(String::new())
+ .context("failed to make request")?,
+ )
+ .await?;
+
+ assert!(result.status().is_success());
+ assert_eq!(result.body(), "Hello, WASI!");
+
+ server.finish()?;
+ Ok(())
+ }
}
#[test]