Skip to main content

waveless_runtime/services/http_facade/
request_extractor.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4use crate::*;
5
6/// TODO: add documentation.
7#[derive(Clone, Constructor, Debug)]
8pub struct RequestExtractor<S>
9where
10    S: Service<RequestCx, Response = ResponseCx, Error = RequestError>,
11{
12    inner: S,
13}
14
15pub struct RequestExtractorLayer;
16
17impl<S> Layer<S> for RequestExtractorLayer
18where
19    S: Service<RequestCx, Response = ResponseCx, Error = RequestError>,
20{
21    type Service = RequestExtractor<S>;
22
23    fn layer(&self, inner: S) -> Self::Service {
24        RequestExtractor { inner }
25    }
26}
27
28impl<S> Service<RequestCx> for RequestExtractor<S>
29where
30    S: Service<RequestCx, Response = ResponseCx, Error = RequestError> + Clone + Send + 'static,
31    S::Future: Send + 'static,
32    S::Response: Send + 'static,
33    S::Error: Send + 'static,
34{
35    type Response = S::Response;
36
37    type Error = S::Error;
38
39    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
40
41    fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
42        self.inner.poll_ready(cx)
43    }
44
45    fn call(&mut self, mut cx: RequestCx) -> Self::Future {
46        let mut inner = self.inner.to_owned();
47
48        let future: Pin<_> = Box::pin(async move {
49            let RequestCx {
50                request,
51                request_params,
52                endpoint,
53                ..
54            } = &mut cx;
55
56            let ExecutionTarget::Http(http_target) = endpoint.execution_target().to_owned() else {
57                unreachable!()
58            };
59
60            // Searches for query params.
61            if let Some(queries) = request.uri().query() {
62                let queries = queries.split('&').map(|elem| {
63                    elem.split_once('=')
64                        .ok_or(eyre!("Cannot parse request's query."))
65                        .unwrap()
66                });
67                if *http_target.capture_all_params() {
68                    for (key, value) in queries {
69                        request_params.insert(key.into(), ParamValue::Client(Some(value.into())));
70                    }
71                } else {
72                    for key in http_target.query_params() {
73                        let mut owned_iterator = queries.to_owned();
74                        match owned_iterator.find(|elem| elem.0 == key) {
75                            Some((key, value)) => request_params
76                                .insert(key.into(), ParamValue::Client(Some(value.into()))),
77                            None => request_params
78                                .insert(key.to_compact_string(), ParamValue::Client(None)),
79                        };
80                    }
81                }
82            }
83
84            // Searches for body params.
85            if !http_target.body_params().is_empty() || *http_target.capture_all_params() {
86                debug!("Request's body stream consumed. HINT: if you want to keep the TCP socket alive unset `capture_all_params` and empty `body_params`.");
87
88                let body_bytes = Bytes::from_iter(
89                    request
90                        .collect()
91                        .await
92                        .map_err(|err| {
93                            RequestError::Expected(
94                                StatusCode::INTERNAL_SERVER_ERROR,
95                                format!("Cannot get request's body. {}", err).into(),
96                            )
97                        })?
98                        .to_bytes(),
99                );
100
101                if !body_bytes.is_empty() {
102                    let Ok(json_body) = (match body_bytes.is_empty() {
103                        true => Ok(serde_json::Value::Array(vec![])),
104                        false => serde_json::from_slice::<serde_json::Value>(
105                            body_bytes.iter().as_slice(),
106                        ),
107                    }) else {
108                        return Err(RequestError::Expected(
109                            StatusCode::BAD_REQUEST,
110                            "Invalid request's body. The provided JSON's format is unsupported."
111                                .into(),
112                        ));
113                    };
114
115                    if *http_target.capture_all_params() {
116                        for (key, value) in json_body.as_object().ok_or(RequestError::Expected(
117                            StatusCode::BAD_REQUEST,
118                            "Cannot extract the parameters from the request's body.".into(),
119                        ))? {
120                            request_params.insert(
121                                key.into(),
122                                ParamValue::Client(Some(
123                                    value
124                                        .as_str()
125                                        .map(|s| s.to_string())
126                                        .unwrap_or(value.to_string())
127                                        .into(),
128                                )),
129                            );
130                        }
131                    } else {
132                        for key in http_target.body_params() {
133                            let value = {
134                                match json_body
135                                    .as_object()
136                                    .ok_or(RequestError::Expected(
137                                        StatusCode::BAD_REQUEST,
138                                        "Cannot extract the parameters from the request's body."
139                                            .into(),
140                                    ))?
141                                    .get(key.as_str())
142                                {
143                                    Some(res) => Some(
144                                        res.as_str()
145                                            .map(|s| s.to_string())
146                                            .unwrap_or(res.to_string())
147                                            .into(),
148                                    ),
149                                    None => None,
150                                }
151                            };
152
153                            request_params.insert(key.to_owned(), ParamValue::Client(value));
154                        }
155                    }
156
157                    // Reconstruct the request's body.
158                    *request.body_mut() = BoxBody::new(
159                        Full::new(ConnBytes::from_iter(body_bytes)).map_err(|_| unreachable!()),
160                    );
161                } else if !http_target.body_params().is_empty() {
162                    return Err(RequestError::Expected(
163                        StatusCode::BAD_REQUEST,
164                        "The request's body for this endpoint cannot be empty.".into(),
165                    ));
166                }
167            }
168
169            inner.call(cx).await
170        })
171        .into();
172
173        future as Self::Future // `rust-analyzer` complains here.
174    }
175}