Skip to main content

wasmtime_wasi_http/p3/
response.rs

1use crate::p3::bindings::http::types::ErrorCode;
2use crate::p3::body::{Body, BodyExt as _, GuestBody};
3use crate::{Error, FieldMap, WasiHttpCtxView, WasiHttpHooks, WasiHttpView, get_content_length};
4use bytes::Bytes;
5use http::StatusCode;
6use http_body_util::BodyExt as _;
7use http_body_util::combinators::UnsyncBoxBody;
8use tokio::sync::oneshot;
9use wasmtime::AsContextMut;
10use wasmtime::error::Context as _;
11
12/// The concrete type behind a `wasi:http/types.response` resource.
13pub struct Response {
14    /// The status of the response.
15    pub status: StatusCode,
16    /// The headers of the response.
17    pub headers: FieldMap,
18    /// Data associated with this response. Cannot be read by the guest, but can
19    /// be forwarded by the guest.
20    pub extensions: http::Extensions,
21    /// Response body.
22    pub(crate) body: Body,
23}
24
25impl TryFrom<Response> for http::Response<Body> {
26    type Error = http::Error;
27
28    fn try_from(
29        Response {
30            status,
31            headers,
32            extensions,
33            body,
34        }: Response,
35    ) -> Result<Self, Self::Error> {
36        let mut res = http::Response::builder().status(status);
37        *res.headers_mut().unwrap() = headers.into();
38        *res.extensions_mut().unwrap() = extensions;
39        res.body(body)
40    }
41}
42
43impl Response {
44    /// Convert [Response] into [http::Response].
45    ///
46    /// The specified [Future] `fut` can be used to communicate
47    /// a response processing error, if any, to the constructor of the response.
48    /// For example, if the response was constructed via `wasi:http/types.response#new`,
49    /// a result sent on `fut` will be forwarded to the guest on the future handle returned.
50    pub fn into_http<T: WasiHttpView + 'static>(
51        self,
52        store: impl AsContextMut<Data = T>,
53        fut: impl Future<Output = Result<(), Error>> + Send + 'static,
54    ) -> wasmtime::Result<http::Response<UnsyncBoxBody<Bytes, Error>>> {
55        self.into_http_with_getter(store, fut, T::http)
56    }
57
58    /// Like [`Self::into_http`], but with a custom function for converting `T`
59    /// to a [`WasiHttpCtxView`].
60    pub fn into_http_with_getter<T: 'static>(
61        self,
62        mut store: impl AsContextMut<Data = T>,
63        fut: impl Future<Output = Result<(), Error>> + Send + 'static,
64        mut getter: impl FnMut(&mut T) -> WasiHttpCtxView<'_> + Clone + Unpin + Send + 'static,
65    ) -> wasmtime::Result<http::Response<UnsyncBoxBody<Bytes, Error>>> {
66        let res = http::Response::try_from(self)?;
67        let (res, body) = res.into_parts();
68        // `Content-Length` header value is validated in `fields` implementation
69        let content_length =
70            get_content_length(&res.headers).context("failed to parse `content-length`")?;
71        let body = match body {
72            Body::Guest {
73                contents_rx,
74                trailers_rx,
75                result_tx,
76            } => GuestBody::new(
77                &mut store,
78                contents_rx,
79                trailers_rx,
80                result_tx,
81                fut,
82                content_length,
83                ErrorCode::HttpResponseBodySize,
84                getter,
85            )?
86            .boxed_unsync(),
87            Body::Host { body, result_tx } => {
88                let is_forbidden = getter(store.as_context_mut().data_mut())
89                    .hooks
90                    .forbidden_header_filter();
91                let body = body.with_filtered_trailers(is_forbidden);
92                if let Some(limit) = content_length {
93                    let (http_result_tx, http_result_rx) = oneshot::channel();
94                    _ = result_tx.send(Box::new(async move {
95                        if let Ok(err) = http_result_rx.await {
96                            return Err(err);
97                        };
98                        fut.await
99                    }));
100                    body.with_content_length(limit, http_result_tx, Error::HttpResponseBodySize)
101                        .boxed_unsync()
102                } else {
103                    _ = result_tx.send(Box::new(fut));
104                    body.boxed_unsync()
105                }
106            }
107        };
108        Ok(http::Response::from_parts(res, body))
109    }
110
111    /// Convert [http::Response] into [Response].
112    pub fn from_http<T>(
113        hooks: &mut dyn WasiHttpHooks,
114        res: http::Response<T>,
115    ) -> (
116        Self,
117        impl Future<Output = Result<(), Error>> + Send + 'static + use<T>,
118    )
119    where
120        T: http_body::Body<Data = Bytes> + Send + 'static,
121        T::Error: Into<Error>,
122    {
123        let (parts, body) = res.into_parts();
124        let (result_tx, result_rx) = tokio::sync::oneshot::channel();
125
126        let wasi_response = Response {
127            status: parts.status,
128            headers: FieldMap::new_immutable(hooks, parts.headers),
129            extensions: parts.extensions,
130            body: Body::Host {
131                body: body.map_err(Into::into).boxed_unsync(),
132                result_tx,
133            },
134        };
135
136        let io_future = async {
137            let Ok(fut) = result_rx.await else {
138                return Ok(());
139            };
140            Box::into_pin(fut).await
141        };
142
143        (wasi_response, io_future)
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150    use crate::default_hooks;
151    use core::future::Future;
152    use core::pin::pin;
153    use core::task::{Context, Poll, Waker};
154    use http_body_util::Full;
155
156    #[tokio::test]
157    async fn test_response_from_http() {
158        let http_response = http::Response::builder()
159            .status(StatusCode::OK)
160            .header("x-custom-header", "value123")
161            .body(Full::new(Bytes::from_static(b"hello wasm")))
162            .unwrap();
163
164        let (wasi_resp, io_future) = Response::from_http(default_hooks(), http_response);
165        assert_eq!(wasi_resp.status, StatusCode::OK);
166        assert_eq!(
167            wasi_resp.headers.get("x-custom-header").unwrap(),
168            "value123"
169        );
170        match wasi_resp.body {
171            Body::Host { body, result_tx } => {
172                let collected = body.collect().await;
173                assert!(collected.is_ok(), "Body stream failed unexpectedly");
174                let chunks = collected.unwrap().to_bytes();
175                assert_eq!(chunks, &b"hello wasm"[..]);
176                _ = result_tx.send(Box::new(async { Ok(()) }));
177            }
178            _ => panic!("Response body should be of type Host"),
179        }
180
181        let mut cx = Context::from_waker(Waker::noop());
182        let result = pin!(io_future).poll(&mut cx);
183        assert!(matches!(result, Poll::Ready(Ok(_))));
184    }
185}