Skip to main content

oxidite_core/
router.rs

1use crate::error::{Error, Result};
2use crate::types::{OxiditeRequest, OxiditeResponse};
3use crate::extract::FromRequest;
4use hyper::Method;
5use std::collections::HashMap;
6use std::future::Future;
7use std::pin::Pin;
8use std::sync::Arc;
9use std::task::{Context, Poll};
10use tower_service::Service;
11use regex::Regex;
12
13/// Trait for type-erased handlers stored in the router
14pub trait Endpoint: Send + Sync + 'static {
15    fn call(&self, req: OxiditeRequest) -> Pin<Box<dyn Future<Output = Result<OxiditeResponse>> + Send>>;
16}
17
18/// Trait for async functions that can be used as handlers
19pub trait Handler<Args>: Clone + Send + Sync + 'static {
20    fn call(&self, req: OxiditeRequest) -> Pin<Box<dyn Future<Output = Result<OxiditeResponse>> + Send>>;
21}
22
23// Wrapper to convert Handler<Args> into Endpoint
24struct HandlerService<H, Args> {
25    handler: H,
26    _marker: std::marker::PhantomData<Args>,
27}
28
29impl<H, Args> Endpoint for HandlerService<H, Args>
30where
31    H: Handler<Args>,
32    Args: Send + Sync + 'static,
33{
34    fn call(&self, req: OxiditeRequest) -> Pin<Box<dyn Future<Output = Result<OxiditeResponse>> + Send>> {
35        self.handler.call(req)
36    }
37}
38
39// Implement Handler for Fn(OxiditeRequest) -> Fut
40impl<F, Fut> Handler<OxiditeRequest> for F
41where
42    F: Fn(OxiditeRequest) -> Fut + Clone + Send + Sync + 'static,
43    Fut: Future<Output = Result<OxiditeResponse>> + Send + 'static,
44{
45    fn call(&self, req: OxiditeRequest) -> Pin<Box<dyn Future<Output = Result<OxiditeResponse>> + Send>> {
46        let fut = self(req);
47        Box::pin(async move { fut.await })
48    }
49}
50
51// Implement Handler for Fn() -> Fut
52impl<F, Fut> Handler<()> for F
53where
54    F: Fn() -> Fut + Clone + Send + Sync + 'static,
55    Fut: Future<Output = Result<OxiditeResponse>> + Send + 'static,
56{
57    fn call(&self, _req: OxiditeRequest) -> Pin<Box<dyn Future<Output = Result<OxiditeResponse>> + Send>> {
58        let fut = self();
59        Box::pin(async move { fut.await })
60    }
61}
62
63// Implement Handler for Fn(T1) -> Fut
64impl<F, Fut, T1> Handler<(T1,)> for F
65where
66    F: Fn(T1) -> Fut + Clone + Send + Sync + 'static,
67    Fut: Future<Output = Result<OxiditeResponse>> + Send + 'static,
68    T1: FromRequest + Send + 'static,
69{
70    fn call(&self, mut req: OxiditeRequest) -> Pin<Box<dyn Future<Output = Result<OxiditeResponse>> + Send>> {
71        let handler = self.clone();
72        Box::pin(async move {
73            let t1 = T1::from_request(&mut req).await?;
74            handler(t1).await
75        })
76    }
77}
78
79// Implement Handler for Fn(T1, T2) -> Fut
80impl<F, Fut, T1, T2> Handler<(T1, T2)> for F
81where
82    F: Fn(T1, T2) -> Fut + Clone + Send + Sync + 'static,
83    Fut: Future<Output = Result<OxiditeResponse>> + Send + 'static,
84    T1: FromRequest + Send + 'static,
85    T2: FromRequest + Send + 'static,
86{
87    fn call(&self, mut req: OxiditeRequest) -> Pin<Box<dyn Future<Output = Result<OxiditeResponse>> + Send>> {
88        let handler = self.clone();
89        Box::pin(async move {
90            let t1 = T1::from_request(&mut req).await?;
91            let t2 = T2::from_request(&mut req).await?;
92            handler(t1, t2).await
93        })
94    }
95}
96
97// Implement Handler for Fn(T1, T2, T3) -> Fut
98impl<F, Fut, T1, T2, T3> Handler<(T1, T2, T3)> for F
99where
100    F: Fn(T1, T2, T3) -> Fut + Clone + Send + Sync + 'static,
101    Fut: Future<Output = Result<OxiditeResponse>> + Send + 'static,
102    T1: FromRequest + Send + 'static,
103    T2: FromRequest + Send + 'static,
104    T3: FromRequest + Send + 'static,
105{
106    fn call(&self, mut req: OxiditeRequest) -> Pin<Box<dyn Future<Output = Result<OxiditeResponse>> + Send>> {
107        let handler = self.clone();
108        Box::pin(async move {
109            let t1 = T1::from_request(&mut req).await?;
110            let t2 = T2::from_request(&mut req).await?;
111            let t3 = T3::from_request(&mut req).await?;
112            handler(t1, t2, t3).await
113        })
114    }
115}
116
117struct Route {
118    pattern: Regex,
119    param_names: Vec<String>,
120    handler: Arc<dyn Endpoint>,
121}
122
123#[derive(Clone)]
124pub struct Router {
125    routes: HashMap<Method, Vec<Arc<Route>>>,
126    extensions: Arc<std::sync::RwLock<http::Extensions>>,
127}
128
129impl Router {
130    pub fn new() -> Self {
131        Self {
132            routes: HashMap::new(),
133            extensions: Arc::new(std::sync::RwLock::new(http::Extensions::new())),
134        }
135    }
136
137    /// Add a shared state to the router that will be available in all handlers
138    pub fn with_state<T: Clone + Send + Sync + 'static>(&mut self, state: T) {
139        if let Ok(mut exts) = self.extensions.write() {
140            exts.insert(state);
141        }
142    }
143
144    pub fn get<H, Args>(&mut self, path: &str, handler: H)
145    where
146        H: Handler<Args>,
147        Args: Send + Sync + 'static,
148    {
149        self.add_route(Method::GET, path, handler);
150    }
151    
152    pub fn post<H, Args>(&mut self, path: &str, handler: H)
153    where
154        H: Handler<Args>,
155        Args: Send + Sync + 'static,
156    {
157        self.add_route(Method::POST, path, handler);
158    }
159
160    pub fn put<H, Args>(&mut self, path: &str, handler: H)
161    where
162        H: Handler<Args>,
163        Args: Send + Sync + 'static,
164    {
165        self.add_route(Method::PUT, path, handler);
166    }
167
168    pub fn delete<H, Args>(&mut self, path: &str, handler: H)
169    where
170        H: Handler<Args>,
171        Args: Send + Sync + 'static,
172    {
173        self.add_route(Method::DELETE, path, handler);
174    }
175
176    pub fn patch<H, Args>(&mut self, path: &str, handler: H)
177    where
178        H: Handler<Args>,
179        Args: Send + Sync + 'static,
180    {
181        self.add_route(Method::PATCH, path, handler);
182    }
183
184    fn add_route<H, Args>(&mut self, method: Method, path: &str, handler: H)
185    where
186        H: Handler<Args>,
187        Args: Send + Sync + 'static,
188    {
189        let (pattern, param_names) = compile_path(path);
190        let endpoint = HandlerService {
191            handler,
192            _marker: std::marker::PhantomData,
193        };
194        
195        let route = Arc::new(Route {
196            pattern,
197            param_names,
198            handler: Arc::new(endpoint),
199        });
200        
201        self.routes
202            .entry(method)
203            .or_insert_with(Vec::new)
204            .push(route);
205    }
206
207    pub async fn handle(&self, mut req: OxiditeRequest) -> Result<OxiditeResponse> {
208        let method = req.method().clone();
209        let path = req.uri().path().to_string();
210
211        // Helper to try matching routes for a specific method
212        let try_match = |target_method: &Method, req: &mut OxiditeRequest| -> Option<Arc<Route>> {
213            if let Some(routes) = self.routes.get(target_method) {
214                for route in routes {
215                    if let Some(captures) = route.pattern.captures(&path) {
216                        // Extract path parameters
217                        let mut params = serde_json::Map::new();
218                        for (i, name) in route.param_names.iter().enumerate() {
219                            if let Some(value) = captures.get(i + 1) {
220                                params.insert(
221                                    name.clone(),
222                                    serde_json::Value::String(value.as_str().to_string()),
223                                );
224                            }
225                        }
226
227                        // Store params in request extensions
228                        if !params.is_empty() {
229                            req.extensions_mut().insert(crate::extract::PathParams(
230                                serde_json::Value::Object(params),
231                            ));
232                        }
233                        
234                        return Some(route.clone());
235                    }
236                }
237            }
238            None
239        };
240
241        // 1. Try exact method match
242        if let Some(route) = try_match(&method, &mut req) {
243            return route.handler.call(req).await;
244        }
245
246        // 2. If HEAD, try GET
247        if method == Method::HEAD {
248            if let Some(route) = try_match(&Method::GET, &mut req) {
249                // For HEAD requests, we execute the GET handler but the server/hyper 
250                // will strip the body automatically since it's a HEAD response.
251                return route.handler.call(req).await;
252            }
253        }
254
255        // 3. Path exists for other methods => method not allowed
256        let allowed_methods: Vec<String> = self
257            .routes
258            .iter()
259            .filter(|(route_method, _)| **route_method != method)
260            .filter_map(|(route_method, routes)| {
261                if routes.iter().any(|route| route.pattern.is_match(&path)) {
262                    Some(route_method.as_str().to_string())
263                } else {
264                    None
265                }
266            })
267            .collect();
268        if !allowed_methods.is_empty() {
269            return Err(Error::MethodNotAllowed(format!(
270                "{} {} (allowed: {})",
271                method,
272                path,
273                allowed_methods.join(", ")
274            )));
275        }
276
277        Err(Error::NotFound("Route not found".to_string()))
278    }
279}
280
281impl Service<OxiditeRequest> for Router {
282    type Response = OxiditeResponse;
283    type Error = Error;
284    type Future = Pin<Box<dyn Future<Output = Result<Self::Response>> + Send>>;
285
286    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>> {
287        Poll::Ready(Ok(()))
288    }
289
290    fn call(&mut self, req: OxiditeRequest) -> Self::Future {
291        let router = self.clone();
292        Box::pin(async move {
293            router.handle(req).await
294        })
295    }
296}
297
298impl Default for Router {
299    fn default() -> Self {
300        Self::new()
301    }
302}
303
304/// Compile a route path pattern into a regex
305/// Converts `/users/:id` to `^/users/([^/]+)$` and returns param names
306fn compile_path(path: &str) -> (Regex, Vec<String>) {
307    let mut pattern = String::from("^");
308    let mut param_names = Vec::new();
309    let mut chars = path.chars().peekable();
310
311    while let Some(ch) = chars.next() {
312        match ch {
313            ':' => {
314                // Extract parameter name
315                let mut param_name = String::new();
316                while let Some(&next_ch) = chars.peek() {
317                    if next_ch.is_alphanumeric() || next_ch == '_' {
318                        param_name.push(next_ch);
319                        chars.next();
320                    } else {
321                        break;
322                    }
323                }
324                param_names.push(param_name);
325                pattern.push_str("([^/]+)");
326            }
327            '*' => {
328                // Wildcard
329                pattern.push_str("(.*)");
330            }
331            '.' | '+' | '?' | '^' | '$' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '\\' => {
332                // Escape regex special characters
333                pattern.push('\\');
334                pattern.push(ch);
335            }
336            _ => {
337                pattern.push(ch);
338            }
339        }
340    }
341
342    pattern.push('$');
343    let regex = Regex::new(&pattern).expect("Invalid route pattern");
344    (regex, param_names)
345}
346
347/// Trait that provides compile-time verification that a function is a valid handler.
348///
349/// This is used by the [`handler_fn`] function to give clear, readable error messages
350/// when a function doesn't satisfy the handler requirements, rather than the cryptic
351/// trait-bound errors that would otherwise surface from the router.
352///
353/// # Example
354///
355/// ```rust,ignore
356/// use oxidite::prelude::*;
357///
358/// // This compiles because the function matches Handler<(State<Arc<AppState>>,)>
359/// let h = handler_fn(my_handler);
360/// router.get("/users", h);
361///
362/// // This would fail at compile time with a clear error if the function
363/// // has extractors that don't implement FromRequest.
364/// ```
365pub trait IntoHandler<Args>: Handler<Args> + Sized {
366    fn into_handler(self) -> Self {
367        self
368    }
369}
370
371impl<H, Args> IntoHandler<Args> for H where H: Handler<Args> {}
372
373/// Compile-time handler verification helper.
374///
375/// Wraps a handler function and ensures at compile time that all its extractors
376/// implement `FromRequest`. Provides clearer error messages than raw trait bounds.
377///
378/// # Example
379///
380/// ```rust,ignore
381/// use oxidite::prelude::*;
382///
383/// async fn index(State(s): State<Arc<AppState>>) -> Result<OxiditeResponse> {
384///     Ok(response::json(serde_json::json!({"ok": true})))
385/// }
386///
387/// // Verified at compile time:
388/// router.get("/", handler_fn(index));
389/// ```
390pub fn handler_fn<H, Args>(handler: H) -> H
391where
392    H: IntoHandler<Args>,
393    Args: Send + Sync + 'static,
394{
395    handler
396}
397
398#[cfg(test)]
399mod tests {
400    use super::*;
401    use crate::types::BoxBody;
402
403    #[test]
404    fn test_compile_path() {
405        let (regex, params) = compile_path("/users/:id");
406        assert_eq!(params, vec!["id"]);
407        assert!(regex.is_match("/users/123"));
408        assert!(!regex.is_match("/users/123/posts"));
409
410        let (regex, params) = compile_path("/users/:user_id/posts/:post_id");
411        assert_eq!(params, vec!["user_id", "post_id"]);
412        assert!(regex.is_match("/users/1/posts/2"));
413    }
414
415    #[test]
416    fn test_exact_match() {
417        let (regex, params) = compile_path("/users");
418        assert_eq!(params.len(), 0);
419        assert!(regex.is_match("/users"));
420        assert!(!regex.is_match("/users/123"));
421    }
422
423    #[tokio::test]
424    async fn test_method_not_allowed_when_path_exists() {
425        let mut router = Router::new();
426        router.get("/users", || async { Ok(crate::OxiditeResponse::text("ok")) });
427        let req = http::Request::builder()
428            .method(Method::POST)
429            .uri("/users")
430            .body(BoxBody::default())
431            .expect("request");
432
433        let result = router.handle(req).await;
434        assert!(matches!(result, Err(Error::MethodNotAllowed(_))));
435    }
436
437    #[tokio::test]
438    async fn test_not_found_when_path_missing() {
439        let router = Router::new();
440        let req = http::Request::builder()
441            .method(Method::GET)
442            .uri("/missing")
443            .body(BoxBody::default())
444            .expect("request");
445
446        let result = router.handle(req).await;
447        assert!(matches!(result, Err(Error::NotFound(_))));
448    }
449}