Skip to main content

waveless_runtime/services/http_facade/
execute_wrapper.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 ExecuteWrapper<S>
9where
10    S: Service<RequestCx, Error = RequestError>,
11{
12    inner: S,
13}
14
15pub struct ExecuteWrapperLayer;
16
17impl<S> Layer<S> for ExecuteWrapperLayer
18where
19    S: Service<RequestCx, Response = ResponseCx, Error = RequestError>,
20{
21    type Service = ExecuteWrapper<S>;
22
23    fn layer(&self, inner: S) -> Self::Service {
24        ExecuteWrapper { inner }
25    }
26}
27
28impl<S> Service<RequestCx> for ExecuteWrapper<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 = Response<ConnBody>;
36
37    type Error = Infallible;
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).map_err(|_| unreachable!())
43    }
44
45    /// Handles endpoints requests.
46    #[instrument(skip_all)]
47    fn call(&mut self, cx: RequestCx) -> Self::Future {
48        let RequestCx { request, .. } = &cx;
49
50        info!(
51            "`{}` request at `{}` {}",
52            request.method(),
53            request.uri().path(),
54            request
55                .headers()
56                .get("host")
57                .map(|val| format!("from `{}`", val.to_str().unwrap_or_default()))
58                .unwrap_or_default()
59        );
60
61        let fut = self.inner.call(cx);
62
63        Box::pin(async move {
64            let mut response = Response::builder()
65                .header("Content-Type", "application/json; charset=utf-8")
66                .header(
67                    "Cache-Control",
68                    format!(
69                        "max-age={}",
70                        (*RuntimeCx::acquire()
71                            .build()
72                            .read()
73                            .await
74                            .executor()
75                            .http_cache_time()) as u32
76                    ),
77                );
78
79            match fut.await {
80                Ok(execute_response) => {
81                    let headers = response.headers_mut().unwrap();
82
83                    for (key, value) in execute_response.headers() {
84                        headers.insert(HeaderName::from_bytes(key.as_bytes()).unwrap(), HeaderValue::from_bytes(value.as_bytes()).unwrap());
85                    }
86
87                    match execute_response.body() {
88                        Some(BodyValue::Json(value)) => {
89                            Ok(response
90                                .status(execute_response.status())
91                                .body(json_conn_body(value))
92                                .unwrap()
93                            )
94                        }
95                        Some(BodyValue::Any(encode)) => {
96                                Ok(response
97                                    .status(execute_response.status())
98                                    .body(json_conn_body(&json!({
99                                        "data": encode.encode().unwrap()
100                                    })))
101                                    .unwrap())
102                            },
103                        _ => Ok(response.status(execute_response.status()).body(empty_body()).unwrap())
104                    }
105                },
106                Err(err) => Ok(response
107                    .status({
108                        match err {
109                            RequestError::Expected(status, _) => status,
110                            RequestError::Other(_) => StatusCode::INTERNAL_SERVER_ERROR,
111                        }
112                    })
113                    .body(json_conn_body(&json!({
114                        "error": match err {
115                            RequestError::Expected(_, err) => err,
116                            RequestError::Other(err) => format!("Unexpected error: {}", err).into(),
117                        }
118                    }))
119                    .map_err(|err| eyre!(err)).boxed())
120                    .unwrap()
121                ),
122            }
123        })
124    }
125}