1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
use crate::{Chain, Constraint, Handler, MiddlewareItem, Request, Router, INTERNAL_ERR};
use hyper::{
    http::Error as HttpError, Body, Request as HyperRequest, Response as HyperResponse, StatusCode,
};
use log::{debug, error};
use regex::{Regex, RegexSet};
use std::{collections::HashMap as Map, net::SocketAddr, sync::Arc};

pub(crate) struct RouteRef {
    pub(crate) handler: Option<Arc<Handler>>,
    pub(crate) middlewares: Vec<Arc<MiddlewareItem>>,
    pub(crate) constraints: Vec<Option<Arc<Constraint>>>,
}

#[derive(Clone)]
pub struct Service<'a> {
    router: Arc<Router<'a>>,
    regexes: Arc<Vec<Regex>>,
    regex_set: Arc<RegexSet>,
    refs: Arc<Vec<RouteRef>>,
}

impl<'a> Service<'a> {
    pub(crate) fn new(router: Router<'a>) -> Self {
        let refs = router.refs();

        let regexes = router
            .regex()
            .iter()
            .map(|x| format!("{}{}", x.0, x.1))
            .collect::<Vec<_>>();

        debug!("Route regexes: {:?}", regexes);

        Self {
            router: Arc::new(router),
            regexes: Arc::new(
                regexes
                    .iter()
                    .map(|x| Regex::new(x).expect(INTERNAL_ERR))
                    .collect(),
            ),
            regex_set: Arc::new(RegexSet::new(regexes).expect(INTERNAL_ERR)),
            refs: Arc::new(refs),
        }
    }

    pub async fn call(
        self,
        req: HyperRequest<Body>,
        ip: SocketAddr,
    ) -> Result<HyperResponse<Body>, HttpError> {
        let to_match = format!("{}{}", req.method().as_str(), req.uri().path());
        let to_match = to_match.trim_end_matches('/');
        let matches = self.regex_set.matches(to_match);

        let mut request = Request::new(ip, req);

        for m in matches {
            let regex = self.regexes.get(m).expect(INTERNAL_ERR);

            debug!("Checking regex: {:?}", regex);

            let mut params = Map::new();
            let captures = regex.captures(to_match).expect(INTERNAL_ERR);

            for name in regex.capture_names() {
                if let Some(name) = name {
                    if let Some(value) = captures.name(name) {
                        params.insert(name.to_string(), value.as_str().to_string());
                    }
                }
            }

            debug!("Params extracted: {:?}", params);

            request.params = params;

            if let Some(route) = self.refs.get(m) {
                let mut matched = true;

                for constraint in &route.constraints {
                    if let Some(constraint) = constraint {
                        matched = constraint(&request);

                        if !matched {
                            break;
                        }
                    }
                }

                if !matched {
                    continue;
                }

                if let Some(handler) = &route.handler {
                    return Self::run(handler, request, route).await;
                }
            }
        }

        // TODO:(router:404) Check for 405 and support custom error handler through post middleware
        Ok(HyperResponse::builder()
            .status(StatusCode::NOT_FOUND)
            .body(Body::empty())?)
    }

    async fn run(
        handler: &Arc<Handler>,
        mut request: Request,
        route: &RouteRef,
    ) -> Result<HyperResponse<Body>, HttpError> {
        let chain = Chain {
            handler,
            middlewares: &route.middlewares,
        };

        match chain.run(&mut request).await {
            Ok(r) => Ok(r),
            Err(err) => {
                error!("{}", err);
                err.respond()
            }
        }
    }
}

pub fn service<'a, R>(f: R) -> Service<'a>
where
    R: Fn(&mut Router),
{
    let mut router = Router::default();
    f(&mut router);

    Service::new(router)
}