Skip to main content

wasip3/http_compat/
mod.rs

1//! Extension types for wasip3::http
2
3pub use body_writer::*;
4mod body_writer;
5
6pub use conversions::*;
7mod conversions;
8
9use crate::{
10    http::types::{self, ErrorCode},
11    wit_bindgen::{self, StreamResult},
12    wit_future,
13};
14use bytes::Bytes;
15use http_body::SizeHint;
16use std::prelude::v1::*;
17use std::{
18    pin::Pin,
19    task::{self, Poll},
20};
21
22const READ_FRAME_SIZE: usize = 16 * 1024;
23
24/// The body type used for incoming HTTP requests.
25///
26/// This is a type alias for [`IncomingBody`] specialized with
27/// [`types::Request`], representing the structured payload of an
28/// inbound request as it is received and processed.
29///
30/// This type is typically used by components that consume HTTP
31/// requests and need to read or stream the request body.
32pub type IncomingRequestBody = IncomingBody<types::Request>;
33
34/// The body type used for incoming HTTP responses.
35///
36/// This is a type alias for [`IncomingBody`] specialized with
37/// [`types::Response`], representing the structured payload of an
38/// inbound response as it is received and processed.
39///
40/// This type is typically used by components that handle HTTP
41/// responses and need to read or stream the response body.
42pub type IncomingResponseBody = IncomingBody<types::Response>;
43
44/// A type alias for an HTTP request with a customizable body type.
45///
46/// This is a convenience wrapper around [`http::Request`], parameterized
47/// by the body type `T`. By default, it uses [`IncomingRequestBody`],
48/// which represents the standard incoming body used by this runtime.
49///
50/// # See also
51/// - [`IncomingRequestBody`]: The body type for inbound HTTP requests.
52/// - [`http::Request`]: The standard HTTP request type from the `http` crate.
53pub type Request<T = IncomingRequestBody> = http::Request<T>;
54
55/// A type alias for an HTTP response with a customizable body type.
56///
57/// This is a convenience wrapper around [`http::Response`], parameterized
58/// by the body type `T`. By default, it uses [`IncomingResponseBody`],
59/// which represents the standard incoming body type used by this runtime.
60///
61/// # See also
62/// - [`IncomingResponseBody`]: The body type for inbound HTTP responses.
63/// - [`http::Response`]: The standard HTTP response type from the `http` crate.
64pub type Response<T = IncomingResponseBody> = http::Response<T>;
65
66/// A wrapper around [`types::RequestOptions`] that implements [`Clone`]
67pub struct RequestOptionsExtension(pub types::RequestOptions);
68
69impl Clone for RequestOptionsExtension {
70    fn clone(&self) -> Self {
71        Self(self.0.clone())
72    }
73}
74
75/// Internal trait representing a readable inbound HTTP message.
76///
77/// Implemented by types that expose request or response headers
78/// and provide mechanisms to consume the message body.
79pub trait IncomingMessage: Unpin {
80    fn get_headers(&self) -> types::Headers;
81
82    fn consume_body(
83        self,
84        res: wit_bindgen::FutureReader<Result<(), ErrorCode>>,
85    ) -> (
86        wit_bindgen::StreamReader<u8>,
87        wit_bindgen::FutureReader<Result<Option<types::Trailers>, ErrorCode>>,
88    );
89}
90
91impl IncomingMessage for types::Request {
92    fn get_headers(&self) -> types::Headers {
93        self.get_headers()
94    }
95
96    fn consume_body(
97        self,
98        res: wit_bindgen::FutureReader<Result<(), ErrorCode>>,
99    ) -> (
100        wit_bindgen::StreamReader<u8>,
101        wit_bindgen::FutureReader<Result<Option<types::Trailers>, ErrorCode>>,
102    ) {
103        Self::consume_body(self, res)
104    }
105}
106
107impl IncomingMessage for types::Response {
108    fn get_headers(&self) -> types::Headers {
109        self.get_headers()
110    }
111
112    fn consume_body(
113        self,
114        res: wit_bindgen::FutureReader<Result<(), ErrorCode>>,
115    ) -> (
116        wit_bindgen::StreamReader<u8>,
117        wit_bindgen::FutureReader<Result<Option<types::Trailers>, ErrorCode>>,
118    ) {
119        Self::consume_body(self, res)
120    }
121}
122
123/// A stream of Bytes, used when receiving bodies from the network.
124pub struct IncomingBody<T> {
125    state: StartedState<T>,
126    content_length: Option<u64>,
127}
128
129enum StartedState<T> {
130    Unstarted(T),
131    Started {
132        #[allow(dead_code)]
133        result: wit_bindgen::FutureWriter<Result<(), ErrorCode>>,
134        state: IncomingState,
135    },
136    Empty,
137}
138
139impl<T: IncomingMessage> IncomingBody<T> {
140    /// Creates a new [`IncomingBody`] from the given incoming message.
141    ///
142    /// This initializes the body in an *unstarted* state and extracts the
143    /// `Content-Length` header if present. The resulting instance can later
144    /// transition into a streaming or consumed state.
145    ///
146    /// Returns an [`ErrorCode`] if the content length is invalid or cannot
147    /// be determined.
148    pub fn new(msg: T) -> Result<Self, ErrorCode> {
149        let content_length = get_content_length(msg.get_headers())?;
150        Ok(Self {
151            state: StartedState::Unstarted(msg),
152            content_length,
153        })
154    }
155
156    /// Takes ownership of the inner message if the body has not yet been started.
157    ///
158    /// This method replaces the internal state with [`StartedState::Empty`]
159    /// and returns the contained message if it was still in the
160    /// *unstarted* state. Returns `None` otherwise.
161    pub fn take_unstarted(&mut self) -> Option<T> {
162        match self.state {
163            StartedState::Unstarted(_) => {
164                let StartedState::Unstarted(msg) =
165                    std::mem::replace(&mut self.state, StartedState::Empty)
166                else {
167                    unreachable!();
168                };
169                Some(msg)
170            }
171            _ => None,
172        }
173    }
174
175    fn ensure_started(&mut self) -> Result<&mut IncomingState, ErrorCode> {
176        if let StartedState::Unstarted(_) = self.state {
177            let msg = self.take_unstarted().unwrap();
178            let (result, reader) = wit_future::new(|| Ok(()));
179            let (stream, trailers) = msg.consume_body(reader);
180            self.state = StartedState::Started {
181                result,
182                state: IncomingState::Ready { stream, trailers },
183            };
184        };
185        match &mut self.state {
186            StartedState::Started { state, .. } => Ok(state),
187            StartedState::Unstarted(_) => unreachable!(),
188            StartedState::Empty => Err(to_internal_error_code(
189                "cannot use IncomingBody after call to take_unstarted",
190            )),
191        }
192    }
193}
194
195enum IncomingState {
196    Ready {
197        stream: wit_bindgen::StreamReader<u8>,
198        trailers: wit_bindgen::FutureReader<Result<Option<types::Trailers>, ErrorCode>>,
199    },
200    Reading(Pin<Box<dyn std::future::Future<Output = ReadResult> + 'static + Send>>),
201    Done,
202}
203
204enum ReadResult {
205    Trailers(Result<Option<types::Trailers>, ErrorCode>),
206    BodyChunk {
207        chunk: Vec<u8>,
208        stream: wit_bindgen::StreamReader<u8>,
209        trailers: wit_bindgen::FutureReader<Result<Option<types::Trailers>, ErrorCode>>,
210    },
211}
212
213impl<T: IncomingMessage> http_body::Body for IncomingBody<T> {
214    type Data = Bytes;
215    type Error = ErrorCode;
216
217    fn poll_frame(
218        mut self: Pin<&mut Self>,
219        cx: &mut task::Context<'_>,
220    ) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
221        let state = self.ensure_started()?;
222        loop {
223            match state {
224                IncomingState::Ready { .. } => {
225                    let IncomingState::Ready {
226                        mut stream,
227                        trailers,
228                    } = std::mem::replace(state, IncomingState::Done)
229                    else {
230                        unreachable!();
231                    };
232                    *state = IncomingState::Reading(Box::pin(async move {
233                        let (result, chunk) =
234                            stream.read(Vec::with_capacity(READ_FRAME_SIZE)).await;
235                        match result {
236                            StreamResult::Complete(_n) => ReadResult::BodyChunk {
237                                chunk,
238                                stream,
239                                trailers,
240                            },
241                            StreamResult::Cancelled => unreachable!(),
242                            StreamResult::Dropped => ReadResult::Trailers(trailers.await),
243                        }
244                    }));
245                }
246                IncomingState::Reading(future) => {
247                    match std::task::ready!(future.as_mut().poll(cx)) {
248                        ReadResult::BodyChunk {
249                            chunk,
250                            stream,
251                            trailers,
252                        } => {
253                            *state = IncomingState::Ready { stream, trailers };
254                            break Poll::Ready(Some(Ok(http_body::Frame::data(chunk.into()))));
255                        }
256                        ReadResult::Trailers(trailers) => {
257                            *state = IncomingState::Done;
258                            match trailers {
259                                Ok(Some(fields)) => {
260                                    let trailers = fields.try_into()?;
261                                    break Poll::Ready(Some(Ok(http_body::Frame::trailers(
262                                        trailers,
263                                    ))));
264                                }
265                                Ok(None) => {}
266                                Err(e) => {
267                                    break Poll::Ready(Some(Err(e)));
268                                }
269                            }
270                        }
271                    }
272                }
273                IncomingState::Done => break Poll::Ready(None),
274            }
275        }
276    }
277
278    fn is_end_stream(&self) -> bool {
279        matches!(
280            self.state,
281            StartedState::Started {
282                state: IncomingState::Done,
283                ..
284            }
285        )
286    }
287
288    fn size_hint(&self) -> SizeHint {
289        let Some(n) = self.content_length else {
290            return SizeHint::default();
291        };
292        let mut size_hint = SizeHint::new();
293        size_hint.set_lower(0);
294        size_hint.set_upper(n);
295        size_hint
296    }
297}
298
299fn get_content_length(headers: types::Headers) -> Result<Option<u64>, ErrorCode> {
300    let values = headers.get(http::header::CONTENT_LENGTH.as_str());
301    if values.len() > 1 {
302        return Err(to_internal_error_code("multiple content-length values"));
303    }
304    let Some(value_bytes) = values.into_iter().next() else {
305        return Ok(None);
306    };
307    let value_str = std::str::from_utf8(&value_bytes).map_err(to_internal_error_code)?;
308    let value_i64: i64 = value_str.parse().map_err(to_internal_error_code)?;
309    let value = value_i64.try_into().map_err(to_internal_error_code)?;
310    Ok(Some(value))
311}
312
313fn to_internal_error_code(e: impl ::std::fmt::Display) -> ErrorCode {
314    ErrorCode::InternalError(Some(e.to_string()))
315}