Skip to main content

wasmtime_wasi_http/
lib.rs

1//! # Wasmtime's WASI HTTP Implementation
2//!
3//! This crate is Wasmtime's host implementation of the `wasi:http` package as
4//! part of WASIp2. This crate's implementation is primarily built on top of
5//! [`hyper`] and [`tokio`].
6//!
7//! # WASI HTTP Interfaces
8//!
9//! This crate contains implementations of the following interfaces:
10//!
11//! * [`wasi:http/incoming-handler`]
12//! * [`wasi:http/outgoing-handler`]
13//! * [`wasi:http/types`]
14//!
15//! The crate also contains an implementation of the [`wasi:http/proxy`] world.
16//!
17//! [`wasi:http/proxy`]: crate::bindings::Proxy
18//! [`wasi:http/outgoing-handler`]: crate::bindings::http::outgoing_handler::Host
19//! [`wasi:http/types`]: crate::bindings::http::types::Host
20//! [`wasi:http/incoming-handler`]: crate::bindings::exports::wasi::http::incoming_handler::Guest
21//!
22//! This crate is very similar to [`wasmtime-wasi`] in the it uses the
23//! `bindgen!` macro in Wasmtime to generate bindings to interfaces. Bindings
24//! are located in the [`bindings`] module.
25//!
26//! # The `WasiHttpView` trait
27//!
28//! All `bindgen!`-generated `Host` traits are implemented in terms of a
29//! [`WasiHttpView`] trait which provides basic access to [`WasiHttpCtx`],
30//! configuration for WASI HTTP, and a [`wasmtime_wasi::ResourceTable`], the
31//! state for all host-defined component model resources.
32//!
33//! The [`WasiHttpView`] trait additionally offers a few other configuration
34//! methods such as [`WasiHttpView::send_request`] to customize how outgoing
35//! HTTP requests are handled.
36//!
37//! # Async and Sync
38//!
39//! There are both asynchronous and synchronous bindings in this crate. For
40//! example [`add_to_linker_async`] is for asynchronous embedders and
41//! [`add_to_linker_sync`] is for synchronous embedders. Note that under the
42//! hood both versions are implemented with `async` on top of [`tokio`].
43//!
44//! # Examples
45//!
46//! Usage of this crate is done through a few steps to get everything hooked up:
47//!
48//! 1. First implement [`WasiHttpView`] for your type which is the `T` in
49//!    [`wasmtime::Store<T>`].
50//! 2. Add WASI HTTP interfaces to a [`wasmtime::component::Linker<T>`]. There
51//!    are a few options of how to do this:
52//!    * Use [`add_to_linker_async`] to bundle all interfaces in
53//!      `wasi:http/proxy` together
54//!    * Use [`add_only_http_to_linker_async`] to add only HTTP interfaces but
55//!      no others. This is useful when working with
56//!      [`wasmtime_wasi::add_to_linker_async`] for example.
57//!    * Add individual interfaces such as with the
58//!      [`bindings::http::outgoing_handler::add_to_linker_get_host`] function.
59//! 3. Use [`ProxyPre`](bindings::ProxyPre) to pre-instantiate a component
60//!    before serving requests.
61//! 4. When serving requests use
62//!    [`ProxyPre::instantiate_async`](bindings::ProxyPre::instantiate_async)
63//!    to create instances and handle HTTP requests.
64//!
65//! A standalone example of doing all this looks like:
66//!
67//! ```no_run
68//! use anyhow::bail;
69//! use hyper::server::conn::http1;
70//! use std::sync::Arc;
71//! use tokio::net::TcpListener;
72//! use wasmtime::component::{Component, Linker, ResourceTable};
73//! use wasmtime::{Config, Engine, Result, Store};
74//! use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiView};
75//! use wasmtime_wasi_http::bindings::ProxyPre;
76//! use wasmtime_wasi_http::bindings::http::types::Scheme;
77//! use wasmtime_wasi_http::body::HyperOutgoingBody;
78//! use wasmtime_wasi_http::io::TokioIo;
79//! use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView};
80//!
81//! #[tokio::main]
82//! async fn main() -> Result<()> {
83//!     let component = std::env::args().nth(1).unwrap();
84//!
85//!     // Prepare the `Engine` for Wasmtime
86//!     let mut config = Config::new();
87//!     config.async_support(true);
88//!     let engine = Engine::new(&config)?;
89//!
90//!     // Compile the component on the command line to machine code
91//!     let component = Component::from_file(&engine, &component)?;
92//!
93//!     // Prepare the `ProxyPre` which is a pre-instantiated version of the
94//!     // component that we have. This will make per-request instantiation
95//!     // much quicker.
96//!     let mut linker = Linker::new(&engine);
97//!     wasmtime_wasi_http::add_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 separate
107//!         // 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//!                 .await
123//!             {
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 the
140//!         // 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: WasiCtxBuilder::new().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 can
155//!         // optionally continue to execute beyond after the initial
156//!         // 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) = proxy
161//!                 .wasi_http_incoming_handler()
162//!                 .call_handle(store, req, out)
163//!                 .await
164//!             {
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 these
173//!             // 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 can
179//!             // inspect the `task` result to see what happened
180//!             Err(_) => {
181//!                 let e = match task.await {
182//!                     Ok(r) => r.unwrap_err(),
183//!                     Err(e) => e.into(),
184//!                 };
185//!                 bail!("guest never invoked `response-outparam::set` method: {e:?}")
186//!             }
187//!         }
188//!     }
189//! }
190//!
191//! struct MyClientState {
192//!     wasi: WasiCtx,
193//!     http: WasiHttpCtx,
194//!     table: ResourceTable,
195//! }
196//!
197//! impl WasiView for MyClientState {
198//!     fn ctx(&mut self) -> &mut WasiCtx {
199//!         &mut self.wasi
200//!     }
201//!     fn table(&mut self) -> &mut ResourceTable {
202//!         &mut self.table
203//!     }
204//! }
205//!
206//! impl WasiHttpView for MyClientState {
207//!     fn ctx(&mut self) -> &mut WasiHttpCtx {
208//!         &mut self.http
209//!     }
210//!     fn table(&mut self) -> &mut ResourceTable {
211//!         &mut self.table
212//!     }
213//! }
214//! ```
215
216#![deny(missing_docs)]
217#![doc(test(attr(deny(warnings))))]
218#![doc(test(attr(allow(dead_code, unused_variables, unused_mut))))]
219
220mod error;
221mod http_impl;
222mod types_impl;
223
224pub mod body;
225pub mod io;
226pub mod types;
227
228pub mod bindings;
229
230pub use crate::error::{
231    http_request_error, hyper_request_error, hyper_response_error, HttpError, HttpResult,
232};
233#[doc(inline)]
234pub use crate::types::{WasiHttpCtx, WasiHttpImpl, WasiHttpView};
235
236/// Add all of the `wasi:http/proxy` world's interfaces to a [`wasmtime::component::Linker`].
237///
238/// This function will add the `async` variant of all interfaces into the
239/// `Linker` provided. By `async` this means that this function is only
240/// compatible with [`Config::async_support(true)`][async]. For embeddings with
241/// async support disabled see [`add_to_linker_sync`] instead.
242///
243/// [async]: wasmtime::Config::async_support
244///
245/// # Example
246///
247/// ```
248/// use wasmtime::{Engine, Result, Config};
249/// use wasmtime::component::{ResourceTable, Linker};
250/// use wasmtime_wasi::{WasiCtx, WasiView};
251/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView};
252///
253/// fn main() -> Result<()> {
254///     let mut config = Config::new();
255///     config.async_support(true);
256///     let engine = Engine::new(&config)?;
257///
258///     let mut linker = Linker::<MyState>::new(&engine);
259///     wasmtime_wasi_http::add_to_linker_async(&mut linker)?;
260///     // ... add any further functionality to `linker` if desired ...
261///
262///     Ok(())
263/// }
264///
265/// struct MyState {
266///     ctx: WasiCtx,
267///     http_ctx: WasiHttpCtx,
268///     table: ResourceTable,
269/// }
270///
271/// impl WasiHttpView for MyState {
272///     fn ctx(&mut self) -> &mut WasiHttpCtx { &mut self.http_ctx }
273///     fn table(&mut self) -> &mut ResourceTable { &mut self.table }
274/// }
275/// impl WasiView for MyState {
276///     fn ctx(&mut self) -> &mut WasiCtx { &mut self.ctx }
277///     fn table(&mut self) -> &mut ResourceTable { &mut self.table }
278/// }
279/// ```
280pub fn add_to_linker_async<T>(l: &mut wasmtime::component::Linker<T>) -> anyhow::Result<()>
281where
282    T: WasiHttpView + wasmtime_wasi::WasiView,
283{
284    let closure = type_annotate_wasi::<T, _>(|t| wasmtime_wasi::WasiImpl(t));
285    wasmtime_wasi::bindings::clocks::wall_clock::add_to_linker_get_host(l, closure)?;
286    wasmtime_wasi::bindings::clocks::monotonic_clock::add_to_linker_get_host(l, closure)?;
287    wasmtime_wasi::bindings::io::poll::add_to_linker_get_host(l, closure)?;
288    wasmtime_wasi::bindings::io::error::add_to_linker_get_host(l, closure)?;
289    wasmtime_wasi::bindings::io::streams::add_to_linker_get_host(l, closure)?;
290    wasmtime_wasi::bindings::cli::stdin::add_to_linker_get_host(l, closure)?;
291    wasmtime_wasi::bindings::cli::stdout::add_to_linker_get_host(l, closure)?;
292    wasmtime_wasi::bindings::cli::stderr::add_to_linker_get_host(l, closure)?;
293    wasmtime_wasi::bindings::random::random::add_to_linker_get_host(l, closure)?;
294
295    add_only_http_to_linker_async(l)
296}
297
298// NB: workaround some rustc inference - a future refactoring may make this
299// obsolete.
300fn type_annotate_http<T, F>(val: F) -> F
301where
302    F: Fn(&mut T) -> WasiHttpImpl<&mut T>,
303{
304    val
305}
306fn type_annotate_wasi<T, F>(val: F) -> F
307where
308    F: Fn(&mut T) -> wasmtime_wasi::WasiImpl<&mut T>,
309{
310    val
311}
312
313/// A slimmed down version of [`add_to_linker_async`] which only adds
314/// `wasi:http` interfaces to the linker.
315///
316/// This is useful when using [`wasmtime_wasi::add_to_linker_async`] for
317/// example to avoid re-adding the same interfaces twice.
318pub fn add_only_http_to_linker_async<T>(
319    l: &mut wasmtime::component::Linker<T>,
320) -> anyhow::Result<()>
321where
322    T: WasiHttpView,
323{
324    let closure = type_annotate_http::<T, _>(|t| WasiHttpImpl(t));
325    crate::bindings::http::outgoing_handler::add_to_linker_get_host(l, closure)?;
326    crate::bindings::http::types::add_to_linker_get_host(l, closure)?;
327
328    Ok(())
329}
330
331/// Add all of the `wasi:http/proxy` world's interfaces to a [`wasmtime::component::Linker`].
332///
333/// This function will add the `sync` variant of all interfaces into the
334/// `Linker` provided. For embeddings with async support see
335/// [`add_to_linker_async`] instead.
336///
337/// # Example
338///
339/// ```
340/// use wasmtime::{Engine, Result, Config};
341/// use wasmtime::component::{ResourceTable, Linker};
342/// use wasmtime_wasi::{WasiCtx, WasiView};
343/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpView};
344///
345/// fn main() -> Result<()> {
346///     let config = Config::default();
347///     let engine = Engine::new(&config)?;
348///
349///     let mut linker = Linker::<MyState>::new(&engine);
350///     wasmtime_wasi_http::add_to_linker_sync(&mut linker)?;
351///     // ... add any further functionality to `linker` if desired ...
352///
353///     Ok(())
354/// }
355///
356/// struct MyState {
357///     ctx: WasiCtx,
358///     http_ctx: WasiHttpCtx,
359///     table: ResourceTable,
360/// }
361///
362/// impl WasiHttpView for MyState {
363///     fn ctx(&mut self) -> &mut WasiHttpCtx { &mut self.http_ctx }
364///     fn table(&mut self) -> &mut ResourceTable { &mut self.table }
365/// }
366/// impl WasiView for MyState {
367///     fn ctx(&mut self) -> &mut WasiCtx { &mut self.ctx }
368///     fn table(&mut self) -> &mut ResourceTable { &mut self.table }
369/// }
370/// ```
371pub fn add_to_linker_sync<T>(l: &mut wasmtime::component::Linker<T>) -> anyhow::Result<()>
372where
373    T: WasiHttpView + wasmtime_wasi::WasiView,
374{
375    let closure = type_annotate_wasi::<T, _>(|t| wasmtime_wasi::WasiImpl(t));
376
377    wasmtime_wasi::bindings::clocks::wall_clock::add_to_linker_get_host(l, closure)?;
378    wasmtime_wasi::bindings::clocks::monotonic_clock::add_to_linker_get_host(l, closure)?;
379    wasmtime_wasi::bindings::sync::io::poll::add_to_linker_get_host(l, closure)?;
380    wasmtime_wasi::bindings::sync::io::streams::add_to_linker_get_host(l, closure)?;
381    wasmtime_wasi::bindings::io::error::add_to_linker_get_host(l, closure)?;
382    wasmtime_wasi::bindings::cli::stdin::add_to_linker_get_host(l, closure)?;
383    wasmtime_wasi::bindings::cli::stdout::add_to_linker_get_host(l, closure)?;
384    wasmtime_wasi::bindings::cli::stderr::add_to_linker_get_host(l, closure)?;
385    wasmtime_wasi::bindings::random::random::add_to_linker_get_host(l, closure)?;
386
387    add_only_http_to_linker_sync(l)?;
388
389    Ok(())
390}
391
392/// A slimmed down version of [`add_to_linker_sync`] which only adds
393/// `wasi:http` interfaces to the linker.
394///
395/// This is useful when using [`wasmtime_wasi::add_to_linker_sync`] for
396/// example to avoid re-adding the same interfaces twice.
397pub fn add_only_http_to_linker_sync<T>(l: &mut wasmtime::component::Linker<T>) -> anyhow::Result<()>
398where
399    T: WasiHttpView,
400{
401    let closure = type_annotate_http::<T, _>(|t| WasiHttpImpl(t));
402
403    crate::bindings::http::outgoing_handler::add_to_linker_get_host(l, closure)?;
404    crate::bindings::http::types::add_to_linker_get_host(l, closure)?;
405
406    Ok(())
407}