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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
pub mod ext;
pub mod prelude;

use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use hyper::service::Service;
use hyper::{Body, Method, Request, Response};
use route_recognizer::Router as InnerRouter;

pub struct Router<E, State> {
    inner: HashMap<Method, InnerRouter<Box<dyn Handler<E>>>>,
    not_found: Option<Box<dyn Handler<E>>>,
    state: State,
}

impl<E> Default for Router<E, ()>
where
    E: Into<Box<dyn Error + Send + Sync>> + 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<E> Router<E, ()>
where
    E: Into<Box<dyn Error + Send + Sync>> + 'static,
{
    pub fn new() -> Self {
        Router::with_state(())
    }
}

impl<E, State> Router<E, State>
where
    E: Into<Box<dyn Error + Send + Sync>> + 'static,
    State: Clone + Send + Sync + 'static,
{
    pub fn with_state(state: State) -> Self {
        Self {
            inner: HashMap::new(),
            not_found: None,
            state,
        }
    }

    /// Register a handler for GET requests
    pub fn get<H, R>(&mut self, path: &str, handler: H)
    where
        H: Fn(Request<Body>) -> R + Send + Sync + 'static,
        R: Future<Output = Result<Response<Body>, E>> + Send + Sync + 'static,
        E: Into<Box<dyn Error + Send + Sync>> + 'static,
    {
        let h = move |req| Box::pin(handler(req));
        let entry = self
            .inner
            .entry(Method::GET)
            .or_insert_with(InnerRouter::new);
        entry.add(path, Box::new(h));
    }

    /// Register a handler for POST requests
    pub fn post<H, R>(&mut self, path: &str, handler: H)
    where
        H: Fn(Request<Body>) -> R + Send + Sync + 'static,
        R: Future<Output = Result<Response<Body>, E>> + Send + Sync + 'static,
        E: Into<Box<dyn Error + Send + Sync>> + 'static,
    {
        let h = move |req| Box::pin(handler(req));
        let entry = self
            .inner
            .entry(Method::POST)
            .or_insert_with(InnerRouter::new);
        entry.add(path, Box::new(h));
    }

    /// Register a handler for PUT requests
    pub fn put<H, R>(&mut self, path: &str, handler: H)
    where
        H: Fn(Request<Body>) -> R + Send + Sync + 'static,
        R: Future<Output = Result<Response<Body>, E>> + Send + Sync + 'static,
        E: Into<Box<dyn Error + Send + Sync>> + 'static,
    {
        let h = move |req| Box::pin(handler(req));
        let entry = self
            .inner
            .entry(Method::PUT)
            .or_insert_with(InnerRouter::new);
        entry.add(path, Box::new(h));
    }

    /// Register a handler for DELETE requests
    pub fn delete<H, R>(&mut self, path: &str, handler: H)
    where
        H: Fn(Request<Body>) -> R + Send + Sync + 'static,
        R: Future<Output = Result<Response<Body>, E>> + Send + Sync + 'static,
        E: Into<Box<dyn Error + Send + Sync>> + 'static,
    {
        let h = move |req| Box::pin(handler(req));
        let entry = self
            .inner
            .entry(Method::DELETE)
            .or_insert_with(InnerRouter::new);
        entry.add(path, Box::new(h));
    }

    /// Register a handler for PATCH requests
    pub fn patch<H, R>(&mut self, path: &str, handler: H)
    where
        H: Fn(Request<Body>) -> R + Send + Sync + 'static,
        R: Future<Output = Result<Response<Body>, E>> + Send + Sync + 'static,
        E: Into<Box<dyn Error + Send + Sync>> + 'static,
    {
        let h = move |req| Box::pin(handler(req));
        let entry = self
            .inner
            .entry(Method::PATCH)
            .or_insert_with(InnerRouter::new);
        entry.add(path, Box::new(h));
    }

    /// Register a handler when no routes are matched
    pub fn not_found<H, R>(&mut self, handler: H)
    where
        H: Fn(Request<Body>) -> R + Send + Sync + 'static,
        R: Future<Output = Result<Response<Body>, E>> + Send + Sync + 'static,
        E: Into<Box<dyn Error + Send + Sync>> + 'static,
    {
        self.not_found = Some(Box::new(handler));
    }

    pub fn serve(
        &self,
        mut req: Request<Body>,
    ) -> Pin<Box<dyn Future<Output = Result<Response<Body>, E>> + Send + Sync>>
    where
        E: Into<Box<dyn Error + Send + Sync>> + 'static,
    {
        match self.inner.get(req.method()) {
            Some(inner_router) => match inner_router.recognize(req.uri().path()) {
                Ok(matcher) => {
                    let handler = matcher.handler();
                    let params = matcher.params().clone();
                    req.extensions_mut().insert(Params(Box::new(params)));
                    req.extensions_mut().insert(self.state.clone());
                    handler.call(req)
                }
                Err(_) => match &self.not_found {
                    Some(handler) => handler.call(req),
                    None => Box::pin(async {
                        Ok(Response::builder().status(404).body(Body::empty()).unwrap())
                    }),
                },
            },
            None => {
                Box::pin(async { Ok(Response::builder().status(404).body(Body::empty()).unwrap()) })
            }
        }
    }

    pub fn into_service(self) -> MakeRouterService<RouterService<E, State>> {
        MakeRouterService {
            inner: RouterService::new(self),
        }
    }
}

pub trait Handler<E: Into<Box<dyn Error + Send + Sync>>>: Send + Sync + 'static {
    fn call(
        &self,
        req: Request<Body>,
    ) -> Pin<Box<dyn Future<Output = Result<Response<Body>, E>> + Send + Sync>>;
}

impl<F: Send + Sync + 'static, R, E> Handler<E> for F
where
    F: Fn(Request<Body>) -> R + Send + Sync,
    R: Future<Output = Result<Response<Body>, E>> + Send + Sync + 'static,
    E: Into<Box<dyn Error + Send + Sync>>,
{
    fn call(
        &self,
        req: Request<Body>,
    ) -> Pin<Box<dyn Future<Output = Result<Response<Body>, E>> + Send + Sync>> {
        Box::pin(self(req))
    }
}

impl<E> fmt::Debug for dyn Handler<E> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        writeln!(f, "keiro::Handler")
    }
}

#[derive(Clone)]
pub struct RouterService<E, State>(Arc<Router<E, State>>);

impl<E, State> Service<Request<Body>> for RouterService<E, State>
where
    E: Into<Box<dyn Error + Send + Sync>> + 'static,
    State: Clone + Send + Sync + 'static,
{
    type Response = Response<Body>;
    type Error = Box<dyn Error + Send + Sync>;
    #[allow(clippy::type_complexity)]
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + Sync>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        let router = self.0.clone();
        let fut = router.serve(req);
        let fut = async { fut.await.map_err(Into::into) };
        Box::pin(fut)
    }
}

impl<E, State> RouterService<E, State>
where
    E: Into<Box<dyn Error + Send + Sync>> + 'static,
    State: Clone + Send + Sync + 'static,
{
    pub fn new(router: Router<E, State>) -> Self {
        Self(Arc::new(router))
    }
}

pub struct MakeRouterService<Svc> {
    pub inner: Svc,
}

impl<T, Svc> Service<T> for MakeRouterService<Svc>
where
    Svc: Service<Request<Body>> + Clone,
    Svc::Response: 'static,
    Svc::Error: Into<Box<dyn Error + Send + Sync>>,
    Svc::Future: 'static,
{
    type Response = Svc;
    type Error = Box<dyn Error + Send + Sync>;
    type Future = futures_util::future::Ready<Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, _req: T) -> Self::Future {
        futures_util::future::ok(self.inner.clone())
    }
}

pub struct Params(Box<route_recognizer::Params>);

impl Params {
    pub fn find(&self, key: &str) -> Option<&str> {
        self.0.find(key)
    }
}