//! # Wasmtime's WASI HTTP Implementation1//!2//! This crate is Wasmtime's host implementation of the `wasi:http` package as3//! part of WASIp2. This crate's implementation is primarily built on top of4//! [`hyper`] and [`tokio`].5//!6//! # WASI HTTP Interfaces7//!8//! This crate contains implementations of the following interfaces:9//!10//! * [`wasi:http/incoming-handler`]11//! * [`wasi:http/outgoing-handler`]12//! * [`wasi:http/types`]13//!14//! The crate also contains an implementation of the [`wasi:http/proxy`] world.15//!16//! [`wasi:http/proxy`]: crate::bindings::Proxy17//! [`wasi:http/outgoing-handler`]: crate::bindings::http::outgoing_handler::Host18//! [`wasi:http/types`]: crate::bindings::http::types::Host19//! [`wasi:http/incoming-handler`]: crate::bindings::exports::wasi::http::incoming_handler::Guest20//!21//! This crate is very similar to [`wasmtime-wasi`] in the it uses the22//! `bindgen!` macro in Wasmtime to generate bindings to interfaces. Bindings23//! are located in the [`bindings`] module.24//!25//! # The `WasiHttpView` trait26//!27//! All `bindgen!`-generated `Host` traits are implemented in terms of a28//! [`WasiHttpView`] trait which provides basic access to [`WasiHttpCtx`],29//! configuration for WASI HTTP, and a [`wasmtime_wasi::ResourceTable`], the30//! state for all host-defined component model resources.31//!32//! The [`WasiHttpView`] trait additionally offers a few other configuration33//! methods such as [`WasiHttpView::send_request`] to customize how outgoing34//! HTTP requests are handled.35//!36//! # Async and Sync37//!38//! There are both asynchronous and synchronous bindings in this crate. For39//! example [`add_to_linker_async`] is for asynchronous embedders and40//! [`add_to_linker_sync`] is for synchronous embedders. Note that under the41//! hood both versions are implemented with `async` on top of [`tokio`].42//!43//! # Examples44//!45//! Usage of this crate is done through a few steps to get everything hooked up:46//!47//! 1. First implement [`WasiHttpView`] for your type which is the `T` in48//! [`wasmtime::Store<T>`].49//! 2. Add WASI HTTP interfaces to a [`wasmtime::component::Linker<T>`]. There50//! are a few options of how to do this:51//! * Use [`add_to_linker_async`] to bundle all interfaces in52//! `wasi:http/proxy` together53//! * Use [`add_only_http_to_linker_async`] to add only HTTP interfaces but54//! no others. This is useful when working with55//! [`wasmtime_wasi::p2::add_to_linker_async`] for example.56//! * Add individual interfaces such as with the57//! [`bindings::http::outgoing_handler::add_to_linker`] function.58//! 3. Use [`ProxyPre`](bindings::ProxyPre) to pre-instantiate a component59//! before serving requests.60//! 4. When serving requests use61//! [`ProxyPre::instantiate_async`](bindings::ProxyPre::instantiate_async)62//! to create instances and handle HTTP requests.63//!64//! A standalone example of doing all this looks like:65//!66//! ```no_run67//! use anyhow::bail;68//! use hyper::server::conn::http1;69//! use std::sync::Arc;70//! use tokio::net::TcpListener;71//! use wasmtime::component::{Component, Linker, ResourceTable};72//! use wasmtime::{Config, Engine, Result, Store};73//! use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};74//! use wasmtime_wasi_http::bindings::ProxyPre;75//! use wasmtime_wasi_http::bindings::http::types::Scheme;76//! use wasmtime_wasi_http::body::HyperOutgoingBody;77//! use wasmtime_wasi_http::io::TokioIo;78//! use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView};79//!80//! #[tokio::main]81//! async fn main() -> Result<()> {82//! let component = std::env::args().nth(1).unwrap();83//!84//! // Prepare the `Engine` for Wasmtime85//! let mut config = Config::new();86//! config.async_support(true);87//! let engine = Engine::new(&config)?;88//!89//! // Compile the component on the command line to machine code90//! let component = Component::from_file(&engine, &component)?;91//!92//! // Prepare the `ProxyPre` which is a pre-instantiated version of the93//! // component that we have. This will make per-request instantiation94//! // much quicker.95//! let mut linker = Linker::new(&engine);96//! wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;97//! wasmtime_wasi_http::add_only_http_to_linker_async(&mut linker)?;98//! let pre = ProxyPre::new(linker.instantiate_pre(&component)?)?;99//!100//! // Prepare our server state and start listening for connections.101//! let server = Arc::new(MyServer { pre });102//! let listener = TcpListener::bind("127.0.0.1:8000").await?;103//! println!("Listening on {}", listener.local_addr()?);104//!105//! loop {106//! // Accept a TCP connection and serve all of its requests in a separate107//! // tokio task. Note that for now this only works with HTTP/1.1.108//! let (client, addr) = listener.accept().await?;109//! println!("serving new client from {addr}");110//!111//! let server = server.clone();112//! tokio::task::spawn(async move {113//! if let Err(e) = http1::Builder::new()114//! .keep_alive(true)115//! .serve_connection(116//! TokioIo::new(client),117//! hyper::service::service_fn(move |req| {118//! let server = server.clone();119//! async move { server.handle_request(req).await }120//! }),121//! )122//! .await123//! {124//! eprintln!("error serving client[{addr}]: {e:?}");125//! }126//! });127//! }128//! }129//!130//! struct MyServer {131//! pre: ProxyPre<MyClientState>,132//! }133//!134//! impl MyServer {135//! async fn handle_request(136//! &self,137//! req: hyper::Request<hyper::body::Incoming>,138//! ) -> Result<hyper::Response<HyperOutgoingBody>> {139//! // Create per-http-request state within a `Store` and prepare the140//! // initial resources passed to the `handle` function.141//! let mut store = Store::new(142//! self.pre.engine(),143//! MyClientState {144//! table: ResourceTable::new(),145//! wasi: WasiCtx::builder().inherit_stdio().build(),146//! http: WasiHttpCtx::new(),147//! },148//! );149//! let (sender, receiver) = tokio::sync::oneshot::channel();150//! let req = store.data_mut().new_incoming_request(Scheme::Http, req)?;151//! let out = store.data_mut().new_response_outparam(sender)?;152//! let pre = self.pre.clone();153//!154//! // Run the http request itself in a separate task so the task can155//! // optionally continue to execute beyond after the initial156//! // headers/response code are sent.157//! let task = tokio::task::spawn(async move {158//! let proxy = pre.instantiate_async(&mut store).await?;159//!160//! if let Err(e) = proxy161//! .wasi_http_incoming_handler()162//! .call_handle(store, req, out)163//! .await164//! {165//! return Err(e);166//! }167//!168//! Ok(())169//! });170//!171//! match receiver.await {172//! // If the client calls `response-outparam::set` then one of these173//! // methods will be called.174//! Ok(Ok(resp)) => Ok(resp),175//! Ok(Err(e)) => Err(e.into()),176//!177//! // Otherwise the `sender` will get dropped along with the `Store`178//! // meaning that the oneshot will get disconnected and here we can179//! // inspect the `task` result to see what happened180//! Err(_) => {181//! let e = match task.await {182//! Ok(Ok(())) => {183//! bail!("guest never invoked `response-outparam::set` method")184//! }185//! Ok(Err(e)) => e,186//! Err(e) => e.into(),187//! };188//! return Err(e.context("guest never invoked `response-outparam::set` method"));189//! }190//! }191//! }192//! }193//!194//! struct MyClientState {195//! wasi: WasiCtx,196//! http: WasiHttpCtx,197//! table: ResourceTable,198//! }199//!200//! impl WasiView for MyClientState {201//! fn ctx(&mut self) -> WasiCtxView<'_> {202//! WasiCtxView { ctx: &mut self.wasi, table: &mut self.table }203//! }204//! }205//!206//! impl WasiHttpView for MyClientState {207//! fn ctx(&mut self) -> &mut WasiHttpCtx {208//! &mut self.http209//! }210//!211//! fn table(&mut self) -> &mut ResourceTable {212//! &mut self.table213//! }214//! }215//! ```216217#![deny(missing_docs)]218#![doc(test(attr(deny(warnings))))]219#![doc(test(attr(allow(dead_code, unused_variables, unused_mut))))]220221mod error;222mod http_impl;223mod types_impl;224225pub mod body;226pub mod io;227pub mod types;228229pub mod bindings;230231#[cfg(feature = "p3")]232#[expect(missing_docs, reason = "work in progress")] // TODO: add docs233pub mod p3;234235pub use crate::error::{236HttpError, HttpResult, http_request_error, hyper_request_error, hyper_response_error,237};238#[doc(inline)]239pub use crate::types::{240DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS, DEFAULT_OUTGOING_BODY_CHUNK_SIZE, WasiHttpCtx,241WasiHttpImpl, WasiHttpView,242};243use wasmtime::component::{HasData, Linker};244245/// Add all of the `wasi:http/proxy` world's interfaces to a [`wasmtime::component::Linker`].246///247/// This function will add the `async` variant of all interfaces into the248/// `Linker` provided. By `async` this means that this function is only249/// compatible with [`Config::async_support(true)`][async]. For embeddings with250/// async support disabled see [`add_to_linker_sync`] instead.251///252/// [async]: wasmtime::Config::async_support253///254/// # Example255///256/// ```257/// use wasmtime::{Engine, Result, Config};258/// use wasmtime::component::{ResourceTable, Linker};259/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};260/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView};261///262/// fn main() -> Result<()> {263/// let mut config = Config::new();264/// config.async_support(true);265/// let engine = Engine::new(&config)?;266///267/// let mut linker = Linker::<MyState>::new(&engine);268/// wasmtime_wasi_http::add_to_linker_async(&mut linker)?;269/// // ... add any further functionality to `linker` if desired ...270///271/// Ok(())272/// }273///274/// struct MyState {275/// ctx: WasiCtx,276/// http_ctx: WasiHttpCtx,277/// table: ResourceTable,278/// }279///280/// impl WasiHttpView for MyState {281/// fn ctx(&mut self) -> &mut WasiHttpCtx { &mut self.http_ctx }282/// fn table(&mut self) -> &mut ResourceTable { &mut self.table }283/// }284///285/// impl WasiView for MyState {286/// fn ctx(&mut self) -> WasiCtxView<'_> {287/// WasiCtxView { ctx: &mut self.ctx, table: &mut self.table }288/// }289/// }290/// ```291pub fn add_to_linker_async<T>(l: &mut wasmtime::component::Linker<T>) -> anyhow::Result<()>292where293T: WasiHttpView + wasmtime_wasi::WasiView + 'static,294{295wasmtime_wasi::p2::add_to_linker_proxy_interfaces_async(l)?;296add_only_http_to_linker_async(l)297}298299/// A slimmed down version of [`add_to_linker_async`] which only adds300/// `wasi:http` interfaces to the linker.301///302/// This is useful when using [`wasmtime_wasi::p2::add_to_linker_async`] for303/// example to avoid re-adding the same interfaces twice.304pub fn add_only_http_to_linker_async<T>(305l: &mut wasmtime::component::Linker<T>,306) -> anyhow::Result<()>307where308T: WasiHttpView + 'static,309{310let options = crate::bindings::LinkOptions::default(); // FIXME: Thread through to the CLI options.311crate::bindings::http::outgoing_handler::add_to_linker::<_, WasiHttp<T>>(l, |x| {312WasiHttpImpl(x)313})?;314crate::bindings::http::types::add_to_linker::<_, WasiHttp<T>>(l, &options.into(), |x| {315WasiHttpImpl(x)316})?;317318Ok(())319}320321struct WasiHttp<T>(T);322323impl<T: 'static> HasData for WasiHttp<T> {324type Data<'a> = WasiHttpImpl<&'a mut T>;325}326327/// Add all of the `wasi:http/proxy` world's interfaces to a [`wasmtime::component::Linker`].328///329/// This function will add the `sync` variant of all interfaces into the330/// `Linker` provided. For embeddings with async support see331/// [`add_to_linker_async`] instead.332///333/// # Example334///335/// ```336/// use wasmtime::{Engine, Result, Config};337/// use wasmtime::component::{ResourceTable, Linker};338/// use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};339/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView};340///341/// fn main() -> Result<()> {342/// let config = Config::default();343/// let engine = Engine::new(&config)?;344///345/// let mut linker = Linker::<MyState>::new(&engine);346/// wasmtime_wasi_http::add_to_linker_sync(&mut linker)?;347/// // ... add any further functionality to `linker` if desired ...348///349/// Ok(())350/// }351///352/// struct MyState {353/// ctx: WasiCtx,354/// http_ctx: WasiHttpCtx,355/// table: ResourceTable,356/// }357/// impl WasiHttpView for MyState {358/// fn ctx(&mut self) -> &mut WasiHttpCtx { &mut self.http_ctx }359/// fn table(&mut self) -> &mut ResourceTable { &mut self.table }360/// }361/// impl WasiView for MyState {362/// fn ctx(&mut self) -> WasiCtxView<'_> {363/// WasiCtxView { ctx: &mut self.ctx, table: &mut self.table }364/// }365/// }366/// ```367pub fn add_to_linker_sync<T>(l: &mut Linker<T>) -> anyhow::Result<()>368where369T: WasiHttpView + wasmtime_wasi::WasiView + 'static,370{371wasmtime_wasi::p2::add_to_linker_proxy_interfaces_sync(l)?;372add_only_http_to_linker_sync(l)373}374375/// A slimmed down version of [`add_to_linker_sync`] which only adds376/// `wasi:http` interfaces to the linker.377///378/// This is useful when using [`wasmtime_wasi::p2::add_to_linker_sync`] for379/// example to avoid re-adding the same interfaces twice.380pub fn add_only_http_to_linker_sync<T>(l: &mut Linker<T>) -> anyhow::Result<()>381where382T: WasiHttpView + 'static,383{384let options = crate::bindings::LinkOptions::default(); // FIXME: Thread through to the CLI options.385crate::bindings::sync::http::outgoing_handler::add_to_linker::<_, WasiHttp<T>>(l, |x| {386WasiHttpImpl(x)387})?;388crate::bindings::sync::http::types::add_to_linker::<_, WasiHttp<T>>(l, &options.into(), |x| {389WasiHttpImpl(x)390})?;391392Ok(())393}394395396