Skip to main content

waveless_runtime/services/
router.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4use crate::*;
5
6pub type RouterServiceInner = BoxCloneService<Request<ConnBody>, Response<ConnBody>, Infallible>;
7
8/// TODO: add documentation.
9#[derive(Clone, Constructor)]
10pub struct RouterService<S: Clone> {
11    endpoints: S,
12    frontend: Option<RouterServiceInner>,
13}
14
15impl<S> Service<Request<Incoming>> for RouterService<S>
16where
17    S: Service<RequestCx, Response = Response<ConnBody>, Error = Infallible>
18        + Clone
19        + Send
20        + 'static,
21    S::Future: Send + 'static,
22    S::Response: Send + 'static,
23    S::Error: Send + 'static,
24{
25    type Response = Response<ConnBody>;
26
27    type Error = Infallible;
28
29    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
30
31    fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
32        let frontend_ready = match &mut self.frontend {
33            Some(frontend) => frontend.poll_ready(cx).is_ready(),
34            None => true,
35        };
36
37        if self.endpoints.poll_ready(cx).is_ready() && frontend_ready {
38            Poll::Ready(Ok(()))
39        } else {
40            Poll::Pending
41        }
42    }
43
44    fn call(&mut self, request: Request<Incoming>) -> Self::Future {
45        let request = request.map(|body| body.map_err(|err| eyre!(err)).boxed());
46
47        let method = HttpMethod::from(request.method().as_str());
48
49        let mut force_endpoint_id = Option::<CompactString>::None;
50
51        // Check whether a connection upgrade to WebSockets is requested to steer the request to the connection handler.
52        if hyper_tungstenite::is_upgrade_request(&request) {
53            force_endpoint_id = Some(CONN_UPGRADE_WEBSOCKETS_ENDPOINT_ID.into());
54        }
55
56        let (endpoint, request_params) = {
57            match force_endpoint_id {
58                Some(target_endpoint_id) => {
59                    let mut inner_endpoint_handler = self.to_owned().endpoints;
60
61                    return Box::pin(async move {
62                        let _build_lock = RuntimeCx::acquire().build().read().await;
63
64                        let mut endpoints = _build_lock.endpoints().to_owned();
65
66                        // Also add filtered internal endpoints.
67                        endpoints.inner_mut().append(
68                            &mut INTERNAL_ENDPOINTS
69                                .iter()
70                                .filter(|(kind, _)| {
71                                    *kind == InternalEndpointKind::ConnectionUpgrade
72                                })
73                                .map(|(_, endpoint)| endpoint)
74                                .cloned()
75                                .collect::<CheapVec<_>>(),
76                        );
77
78                        // Search for endpoints that matches the given id.
79                        let Some(endpoint) = endpoints
80                            .inner()
81                            .iter()
82                            .find(|endpoint| endpoint.id() == target_endpoint_id)
83                        else {
84                            unreachable!()
85                        };
86
87                        inner_endpoint_handler
88                            .call(RequestCx {
89                                request,
90                                method,
91                                request_params: HashMap::new(),
92                                endpoint: endpoint.to_owned(),
93                            })
94                            .await
95                            .map_err(|_| unreachable!())
96                    });
97                }
98                None => {
99                    // Tries to match the route.
100                    let route = request.uri().path().trim_matches('/').to_owned();
101
102                    // Extracts the route from the method-aware router.
103                    let Some(router) = RuntimeCx::acquire().router().get(&method) else {
104                        if let Some(mut frontend_inner) = self.frontend.to_owned() {
105                            return Box::pin(async move {
106                                frontend_inner
107                                    .call(request)
108                                    .await
109                                    .map_err(|_| unreachable!())
110                            });
111                        } else {
112                            return Box::pin(async move {
113                                let response = Response::builder()
114                                    .header("Content-Type", "application/json; charset=utf-8")
115                                    .header(
116                                        "Cache-Control",
117                                        format!(
118                                            "max-age={}",
119                                            (*RuntimeCx::acquire()
120                                                .build()
121                                                .read()
122                                                .await
123                                                .executor()
124                                                .http_cache_time())
125                                                as u32
126                                        ),
127                                    );
128
129                                Ok(response
130                                    .status(404)
131                                    .body(json_conn_body(&json!({
132                                            "error": format!(
133                                                "There is no route that accepts {}.",
134                                                method
135                                            )
136                                        }
137                                    )))
138                                    .unwrap())
139                            });
140                        }
141                    };
142
143                    let Ok(matched) = router.at(&route) else {
144                        if let Some(mut frontend_inner) = self.frontend.to_owned() {
145                            debug!(
146                                "Route `{}` is not defined, using the frontend service as a fallback.",
147                                route
148                            );
149
150                            return Box::pin(async move {
151                                frontend_inner
152                                    .call(request)
153                                    .await
154                                    .map_err(|_| unreachable!())
155                            });
156                        } else {
157                            return Box::pin(async move {
158                                let response = Response::builder()
159                                    .header("Content-Type", "application/json; charset=utf-8")
160                                    .header(
161                                        "Cache-Control",
162                                        format!(
163                                            "max-age={}",
164                                            (*RuntimeCx::acquire()
165                                                .build()
166                                                .read()
167                                                .await
168                                                .executor()
169                                                .http_cache_time())
170                                                as u32
171                                        ),
172                                    );
173
174                                Ok(response
175                                        .status(404)
176                                        .body(
177                                            json_conn_body(&json!({
178                                                "error": format!(
179                                                    "Route `{}` is not defined. HINT: Go to your project's endpoints folder and check the endpoint's routes.",
180                                                    route)
181                                            }))
182                                    ).unwrap()
183                                )
184                            });
185                        }
186                    };
187
188                    // Extracts the path's params.
189                    let mut path_params = HashMap::<CompactString, ParamValue>::new();
190
191                    for (key, value) in matched.params.iter() {
192                        path_params.insert(key.into(), ParamValue::Client(Some(value.into())));
193                    }
194
195                    (matched.value.to_owned(), path_params)
196                }
197            }
198        };
199
200        let endpoint_fut = self.endpoints.call(RequestCx {
201            request,
202            method,
203            request_params,
204            endpoint,
205        });
206
207        return Box::pin(async move { endpoint_fut.await.map_err(|_| unreachable!()) });
208    }
209}