Skip to main content

wasmtime_wasi_http/p3/
mod.rs

1//! Experimental, unstable and incomplete implementation of wasip3 version of `wasi:http`.
2//!
3//! This module is under heavy development.
4//! It is not compliant with semver and is not ready
5//! for production use.
6//!
7//! Bug and security fixes limited to wasip3 will not be given patch releases.
8//!
9//! Documentation of this module may be incorrect or out-of-sync with the implementation.
10
11pub mod bindings;
12mod body;
13mod conv;
14mod helpers;
15mod host;
16mod proxy;
17mod request;
18mod response;
19
20pub use request::Request;
21pub use response::Response;
22
23/// The default value configured for [`WasiHttpHooks::p3_outgoing_body_buffer_chunks`].
24///
25/// [`WasiHttpHooks::p3_outgoing_body_buffer_chunks`]: crate::WasiHttpHooks::p3_outgoing_body_buffer_chunks
26pub const DEFAULT_OUTGOING_BODY_BUFFER_CHUNKS: usize = 1;
27
28/// The default value configured for [`WasiHttpHooks::p3_outgoing_body_chunk_size`].
29///
30/// [`WasiHttpHooks::p3_outgoing_body_chunk_size`]: crate::WasiHttpHooks::p3_outgoing_body_chunk_size
31pub const DEFAULT_OUTGOING_BODY_CHUNK_SIZE: usize = 1024 * 1024;
32
33use crate::{FieldMapError, WasiHttp, WasiHttpNamed, WasiHttpNamedView, WasiHttpView};
34use bindings::http::{client, types};
35use core::ops::Deref;
36use std::sync::Arc;
37use wasmtime::component::{Component, Linker};
38use wasmtime_wasi::{NamedId, TrappableError, WasiCtxNamedView};
39
40pub(crate) type HttpResult<T> = Result<T, HttpError>;
41pub(crate) type HttpError = TrappableError<types::ErrorCode>;
42
43pub(crate) type HeaderResult<T> = Result<T, HeaderError>;
44pub(crate) type HeaderError = TrappableError<types::HeaderError>;
45
46impl From<FieldMapError> for HeaderError {
47    fn from(e: FieldMapError) -> Self {
48        match e {
49            FieldMapError::Immutable => types::HeaderError::Immutable.into(),
50            FieldMapError::InvalidHeaderName | FieldMapError::InvalidHeaderValue => {
51                types::HeaderError::InvalidSyntax.into()
52            }
53            FieldMapError::TooManyFields | FieldMapError::TotalSizeTooBig => {
54                types::HeaderError::SizeExceeded.into()
55            }
56            FieldMapError::Forbidden => types::HeaderError::Forbidden.into(),
57        }
58    }
59}
60
61pub(crate) type RequestOptionsResult<T> = Result<T, RequestOptionsError>;
62pub(crate) type RequestOptionsError = TrappableError<types::RequestOptionsError>;
63
64/// Add all interfaces from this module into the `linker` provided.
65///
66/// This function will add all interfaces implemented by this module to the
67/// [`Linker`], which corresponds to the `wasi:http/imports` world supported by
68/// this module.
69///
70/// # Example
71///
72/// ```
73/// use wasmtime::{Engine, Result, Store, Config};
74/// use wasmtime::component::{Linker, ResourceTable};
75/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpCtxView, WasiHttpView};
76///
77/// fn main() -> Result<()> {
78///     let mut config = Config::new();
79///     config.wasm_component_model_async(true);
80///     let engine = Engine::new(&config)?;
81///
82///     let mut linker = Linker::<MyState>::new(&engine);
83///     wasmtime_wasi_http::p3::add_to_linker(&mut linker)?;
84///     // ... add any further functionality to `linker` if desired ...
85///
86///     let mut store = Store::new(
87///         &engine,
88///         MyState::default(),
89///     );
90///
91///     // ... use `linker` to instantiate within `store` ...
92///
93///     Ok(())
94/// }
95///
96/// #[derive(Default)]
97/// struct MyState {
98///     http: WasiHttpCtx,
99///     table: ResourceTable,
100/// }
101///
102/// impl WasiHttpView for MyState {
103///     fn http(&mut self) -> WasiHttpCtxView<'_> {
104///         WasiHttpCtxView {
105///             ctx: &mut self.http,
106///             table: &mut self.table,
107///             hooks: Default::default(),
108///         }
109///     }
110/// }
111/// ```
112pub fn add_to_linker<T>(linker: &mut Linker<T>) -> wasmtime::Result<()>
113where
114    T: WasiHttpView + 'static,
115{
116    client::add_to_linker::<_, WasiHttp>(linker, T::http)?;
117    types::add_to_linker::<_, WasiHttp>(linker, T::http)?;
118    Ok(())
119}
120
121/// Interfaces that are added via [`add_named_to_linker`].
122#[derive(Copy, Clone, PartialEq, Eq, Debug)]
123pub enum Interface {
124    /// `wasi:http/client`
125    HttpClient,
126    /// `wasi:http/types`
127    HttpTypes,
128}
129
130/// Add all interfaces from this module into the `linker` provided for any
131/// named imports that a component has.
132///
133/// This function is similar to [`add_to_linker`] except that it's specifically
134/// designed to work with named imports of `wasi:http` interfaces that
135/// components may have. This requires a [`Component`] parameter to be passed in
136/// when populating the [`Linker`] provided to see what the [`Component`]
137/// actually imports.
138///
139/// If this isn't low level enough you can invoke the bindgen-generated
140/// `add_to_linker` functions within the [`named_imports`] module directly
141/// instead.
142///
143/// [`named_imports`]: crate::p3::bindings::named_imports
144///
145/// The `lookup` function provided here is invoked for every named import found
146/// for a particular interface. The [`Interface`] given is what's being bound,
147/// and the `&str` argument is the name that the component imports it as. The
148/// embedder can then decide how it would like to allocate a [`NamedId`] for
149/// this import. If `Ok` is returned then the linker is populated with this
150/// name, and imported functions will pass the [`NamedId`] later to the
151/// implementation of [`WasiHttpNamedView`] on `T` when invoked. If `Err` is
152/// returned then the error will cause this entire function to fail and this
153/// function call will return the same error.
154///
155/// # Example
156///
157/// ```
158/// use std::collections::HashMap;
159/// use wasmtime::component::{Component, Linker, ResourceTable};
160/// use wasmtime::{Engine, Result, Store, Config};
161/// use wasmtime_wasi::NamedId;
162/// use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpCtxView, WasiHttpNamedView};
163///
164/// fn main() -> Result<()> {
165///     let mut config = Config::new();
166///     config.wasm_component_model_async(true);
167///     let engine = Engine::new(&config)?;
168///     let component = Component::new(&engine, "(component)")?;
169///
170///     let mut linker = Linker::<MyState>::new(&engine);
171///
172///     // ... add default functionality to `linker` as needed ...
173///
174///     // and then additionally fill in any specific named imports `component`
175///     // might have for `wasi:http` interfaces.
176///     let mut name_map = HashMap::new();
177///     wasmtime_wasi_http::p3::add_named_to_linker(&mut linker, &component, |_i, name| {
178///         let len = name_map.len();
179///         Ok(NamedId(*name_map.entry(name.to_string()).or_insert(len)))
180///     })?;
181///
182///     // Here a `WasiHttpCtx` is allocated per-named-import and will then be
183///     // referred to internally by the [`NamedId`] allocated above. You could
184///     // also use `name_map` to configure each context differently.
185///     let mut my_state = MyState::default();
186///     for _ in 0..name_map.len() {
187///         my_state.contexts.push(WasiHttpCtx::default());
188///     }
189///     let mut store = Store::new(&engine, my_state);
190///
191///     // ... use `linker` to instantiate within `store` ...
192///
193///     Ok(())
194/// }
195///
196/// #[derive(Default)]
197/// struct MyState {
198///     table: ResourceTable,
199///     contexts: Vec<WasiHttpCtx>,
200/// }
201///
202/// impl WasiHttpNamedView for MyState {
203///     fn http(&mut self, id: NamedId) -> WasiHttpCtxView<'_> {
204///         WasiHttpCtxView {
205///             ctx: &mut self.contexts[id.0],
206///             table: &mut self.table,
207///             hooks: Default::default(),
208///         }
209///     }
210/// }
211/// ```
212pub fn add_named_to_linker<T>(
213    linker: &mut Linker<T>,
214    component: &Component,
215    mut lookup: impl FnMut(Interface, &str) -> wasmtime::Result<NamedId>,
216) -> wasmtime::Result<()>
217where
218    T: WasiHttpNamedView,
219{
220    use crate::p3::bindings::named_imports::wasi::http::{client, types};
221    client::add_to_linker::<_, WasiHttpNamed<T>>(
222        linker,
223        component,
224        |name| lookup(Interface::HttpClient, name),
225        |x| WasiCtxNamedView(x),
226    )?;
227    types::add_to_linker::<_, WasiHttpNamed<T>>(
228        linker,
229        component,
230        |name| lookup(Interface::HttpTypes, name),
231        |x| WasiCtxNamedView(x),
232    )?;
233    Ok(())
234}
235
236/// An [Arc], which may be immutable.
237///
238/// In `wasi:http` resources like `fields` or `request-options` may be
239/// mutable or immutable. This construct is used to model them efficiently.
240pub enum MaybeMutable<T> {
241    /// Clone-on-write, mutable [Arc]
242    Mutable(Arc<T>),
243    /// Immutable [Arc]
244    Immutable(Arc<T>),
245}
246
247impl<T> From<MaybeMutable<T>> for Arc<T> {
248    fn from(v: MaybeMutable<T>) -> Self {
249        v.into_arc()
250    }
251}
252
253impl<T> Deref for MaybeMutable<T> {
254    type Target = Arc<T>;
255
256    fn deref(&self) -> &Self::Target {
257        match self {
258            Self::Mutable(v) | Self::Immutable(v) => v,
259        }
260    }
261}
262
263impl<T> MaybeMutable<T> {
264    /// Construct a mutable [`MaybeMutable`].
265    pub fn new_mutable(v: impl Into<Arc<T>>) -> Self {
266        Self::Mutable(v.into())
267    }
268
269    /// Construct a mutable [`MaybeMutable`] filling it with default `T`.
270    pub fn new_mutable_default() -> Self
271    where
272        T: Default,
273    {
274        Self::new_mutable(T::default())
275    }
276
277    /// Construct an immutable [`MaybeMutable`].
278    pub fn new_immutable(v: impl Into<Arc<T>>) -> Self {
279        Self::Immutable(v.into())
280    }
281
282    /// Unwrap [`MaybeMutable`] into [`Arc`].
283    pub fn into_arc(self) -> Arc<T> {
284        match self {
285            Self::Mutable(v) | Self::Immutable(v) => v,
286        }
287    }
288
289    /// If this [`MaybeMutable`] is [`Mutable`](MaybeMutable::Mutable),
290    /// return a mutable reference to it, otherwise return `None`.
291    ///
292    /// Internally, this will use [`Arc::make_mut`] and will clone the underlying
293    /// value, if multiple strong references to the inner [`Arc`] exist.
294    pub fn get_mut(&mut self) -> Option<&mut T>
295    where
296        T: Clone,
297    {
298        match self {
299            Self::Mutable(v) => Some(Arc::make_mut(v)),
300            Self::Immutable(..) => None,
301        }
302    }
303}