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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
//! This module provides a context extension `RouterParam` and
//! many endpoint wrappers like `Router`, `Dispatcher` and `Guard`.
//!
//! ### Example
//!
//! ```rust
//! use roa::router::{Router, RouterParam, get, allow};
//! use roa::{App, Context, Status, MiddlewareExt, Next};
//! use roa::http::{StatusCode, Method};
//! use roa::tcp::Listener;
//! use tokio::task::spawn;
//!
//!
//! async fn gate(_ctx: &mut Context, next: Next<'_>) -> Result<(), Status> {
//!     next.await
//! }
//!
//! async fn query(ctx: &mut Context) -> Result<(), Status> {
//!     Ok(())
//! }
//!
//! async fn create(ctx: &mut Context) -> Result<(), Status> {
//!     Ok(())
//! }
//!
//! async fn graphql(ctx: &mut Context) -> Result<(), Status> {
//!     Ok(())
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let router = Router::new()
//!         .gate(gate)
//!         .on("/restful", get(query).post(create))
//!         .on("/graphql", allow([Method::GET, Method::POST], graphql));
//!     let app = App::new()
//!         .end(router.routes("/api")?);
//!     let (addr, server) = app.run()?;
//!     spawn(server);
//!     let resp = reqwest::get(&format!("http://{}/api/restful", addr)).await?;
//!     assert_eq!(StatusCode::OK, resp.status());
//!
//!     let resp = reqwest::get(&format!("http://{}/restful", addr)).await?;
//!     assert_eq!(StatusCode::NOT_FOUND, resp.status());
//!     Ok(())
//! }
//! ```
//!

mod endpoints;
mod err;
mod path;

use std::convert::AsRef;
use std::result::Result as StdResult;

#[doc(inline)]
pub use endpoints::*;
use err::Conflict;
#[doc(inline)]
pub use err::RouterError;
use path::{join_path, standardize_path, Path, RegexPath};
use percent_encoding::percent_decode_str;
use radix_trie::Trie;

use crate::http::StatusCode;
use crate::{
    async_trait, throw, Boxed, Context, Endpoint, EndpointExt, Middleware, MiddlewareExt, Result,
    Shared, Status, Variable,
};

/// A private scope to store and load variables in Context::storage.
struct RouterScope;

/// A context extension.
/// This extension must be used in `Router`,
/// otherwise you cannot get expected router parameters.
///
/// ### Example
///
/// ```rust
/// use roa::router::{Router, RouterParam};
/// use roa::{App, Context, Status};
/// use roa::http::StatusCode;
/// use roa::tcp::Listener;
/// use tokio::task::spawn;
///
/// async fn test(ctx: &mut Context) -> Result<(), Status> {
///     let id: u64 = ctx.must_param("id")?.parse()?;
///     assert_eq!(0, id);
///     Ok(())
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let router = Router::new().on("/:id", test);
///     let app = App::new().end(router.routes("/user")?);
///     let (addr, server) = app.run()?;
///     spawn(server);
///     let resp = reqwest::get(&format!("http://{}/user/0", addr)).await?;
///     assert_eq!(StatusCode::OK, resp.status());
///     Ok(())
/// }
///
///
/// ```
pub trait RouterParam {
    /// Must get a router parameter, throw 500 INTERNAL SERVER ERROR if it not exists.
    fn must_param<'a>(&self, name: &'a str) -> Result<Variable<'a, String>>;

    /// Try to get a router parameter, return `None` if it not exists.
    /// ### Example
    ///
    /// ```rust
    /// use roa::router::{Router, RouterParam};
    /// use roa::{App, Context, Status};
    /// use roa::http::StatusCode;
    /// use roa::tcp::Listener;
    /// use tokio::task::spawn;
    ///
    /// async fn test(ctx: &mut Context) -> Result<(), Status> {
    ///     assert!(ctx.param("name").is_none());
    ///     Ok(())
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let router = Router::new().on("/:id", test);
    ///     let app = App::new().end(router.routes("/user")?);
    ///     let (addr, server) = app.run()?;
    ///     spawn(server);
    ///     let resp = reqwest::get(&format!("http://{}/user/0", addr)).await?;
    ///     assert_eq!(StatusCode::OK, resp.status());
    ///     Ok(())
    /// }
    ///
    ///
    /// ```
    fn param<'a>(&self, name: &'a str) -> Option<Variable<'a, String>>;
}

/// A builder of `RouteTable`.
pub struct Router<S> {
    middleware: Shared<S>,
    endpoints: Vec<(String, Boxed<S>)>,
}

/// An endpoint to route request by uri path.
pub struct RouteTable<S> {
    static_route: Trie<String, Boxed<S>>,
    dynamic_route: Vec<(RegexPath, Boxed<S>)>,
}

impl<S> Router<S>
where
    S: 'static,
{
    /// Construct a new router.
    pub fn new() -> Self {
        Self {
            middleware: ().shared(),
            endpoints: Vec::new(),
        }
    }

    /// Register a new endpoint.
    pub fn on(mut self, path: &'static str, endpoint: impl for<'a> Endpoint<'a, S>) -> Self {
        self.endpoints
            .push((path.to_string(), self.register(endpoint)));
        self
    }

    /// Chain an endpoint to Router::middleware.
    fn register(&self, endpoint: impl for<'a> Endpoint<'a, S>) -> Boxed<S> {
        self.middleware.clone().end(endpoint).boxed()
    }

    /// Include another router with prefix.
    pub fn include(mut self, prefix: &'static str, router: Router<S>) -> Self {
        for (path, endpoint) in router.endpoints {
            self.endpoints
                .push((join_path([prefix, path.as_str()]), self.register(endpoint)))
        }
        self
    }

    /// Chain a middleware to Router::middleware.
    pub fn gate(self, next: impl for<'a> Middleware<'a, S>) -> Router<S> {
        let Self {
            middleware,
            endpoints,
        } = self;
        Self {
            middleware: middleware.chain(next).shared(),
            endpoints,
        }
    }

    /// Build RouteTable with path prefix.
    pub fn routes(self, prefix: &'static str) -> StdResult<RouteTable<S>, RouterError> {
        let mut route_table = RouteTable::default();
        for (raw_path, endpoint) in self.endpoints {
            route_table.insert(join_path([prefix, raw_path.as_str()]), endpoint)?;
        }
        Ok(route_table)
    }
}

impl<S> RouteTable<S>
where
    S: 'static,
{
    fn new() -> Self {
        Self {
            static_route: Trie::new(),
            dynamic_route: Vec::new(),
        }
    }

    /// Insert endpoint to table.
    fn insert(
        &mut self,
        raw_path: impl AsRef<str>,
        endpoint: Boxed<S>,
    ) -> StdResult<(), RouterError> {
        match raw_path.as_ref().parse()? {
            Path::Static(path) => {
                if self.static_route.insert(path.clone(), endpoint).is_some() {
                    return Err(Conflict::Path(path).into());
                }
            }
            Path::Dynamic(regex_path) => self.dynamic_route.push((regex_path, endpoint)),
        }
        Ok(())
    }
}

impl<S> Default for Router<S>
where
    S: 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<S> Default for RouteTable<S>
where
    S: 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait(?Send)]
impl<'a, S> Endpoint<'a, S> for RouteTable<S>
where
    S: 'static,
{
    #[inline]
    async fn call(&'a self, ctx: &'a mut Context<S>) -> Result {
        let uri = ctx.uri();
        // standardize path
        let path = standardize_path(&percent_decode_str(uri.path()).decode_utf8().map_err(
            |err| {
                Status::new(
                    StatusCode::BAD_REQUEST,
                    format!("{}\npath `{}` is not a valid utf-8 string", err, uri.path()),
                    true,
                )
            },
        )?);

        // search static routes
        if let Some(end) = self.static_route.get(&path) {
            return end.call(ctx).await;
        }

        // search dynamic routes
        for (regexp_path, end) in self.dynamic_route.iter() {
            if let Some(cap) = regexp_path.re.captures(&path) {
                for var in regexp_path.vars.iter() {
                    ctx.store_scoped(RouterScope, var.to_string(), cap[var.as_str()].to_string());
                }
                return end.call(ctx).await;
            }
        }

        // 404 NOT FOUND
        throw!(StatusCode::NOT_FOUND)
    }
}

impl<S> RouterParam for Context<S> {
    #[inline]
    fn must_param<'a>(&self, name: &'a str) -> Result<Variable<'a, String>> {
        self.param(name).ok_or_else(|| {
            Status::new(
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("router variable `{}` is required", name),
                false,
            )
        })
    }
    #[inline]
    fn param<'a>(&self, name: &'a str) -> Option<Variable<'a, String>> {
        self.load_scoped::<RouterScope, String>(name)
    }
}

#[cfg(all(test, feature = "tcp"))]
mod tests {
    use encoding::EncoderTrap;
    use percent_encoding::NON_ALPHANUMERIC;
    use tokio::task::spawn;

    use super::Router;
    use crate::http::StatusCode;
    use crate::tcp::Listener;
    use crate::{App, Context, Next, Status};

    async fn gate(ctx: &mut Context, next: Next<'_>) -> Result<(), Status> {
        ctx.store("id", "0".to_string());
        next.await
    }

    async fn test(ctx: &mut Context) -> Result<(), Status> {
        let id: u64 = ctx.load::<String>("id").unwrap().parse()?;
        assert_eq!(0, id);
        Ok(())
    }

    #[tokio::test]
    async fn gate_test() -> Result<(), Box<dyn std::error::Error>> {
        let router = Router::new().gate(gate).on("/", test);
        let app = App::new().end(router.routes("/route")?);
        let (addr, server) = app.run()?;
        spawn(server);
        let resp = reqwest::get(&format!("http://{}/route", addr)).await?;
        assert_eq!(StatusCode::OK, resp.status());
        Ok(())
    }

    #[tokio::test]
    async fn route() -> Result<(), Box<dyn std::error::Error>> {
        let user_router = Router::new().on("/", test);
        let router = Router::new().gate(gate).include("/user", user_router);
        let app = App::new().end(router.routes("/route")?);
        let (addr, server) = app.run()?;
        spawn(server);
        let resp = reqwest::get(&format!("http://{}/route/user", addr)).await?;
        assert_eq!(StatusCode::OK, resp.status());
        Ok(())
    }

    #[test]
    fn conflict_path() -> Result<(), Box<dyn std::error::Error>> {
        let evil_router = Router::new().on("/endpoint", test);
        let router = Router::new()
            .on("/route/endpoint", test)
            .include("/route", evil_router);
        let ret = router.routes("/");
        assert!(ret.is_err());
        Ok(())
    }

    #[tokio::test]
    async fn route_not_found() -> Result<(), Box<dyn std::error::Error>> {
        let app = App::new().end(Router::default().routes("/")?);
        let (addr, server) = app.run()?;
        spawn(server);
        let resp = reqwest::get(&format!("http://{}", addr)).await?;
        assert_eq!(StatusCode::NOT_FOUND, resp.status());
        Ok(())
    }

    #[tokio::test]
    async fn non_utf8_uri() -> Result<(), Box<dyn std::error::Error>> {
        let app = App::new().end(Router::default().routes("/")?);
        let (addr, server) = app.run()?;
        spawn(server);
        let gbk_path = encoding::label::encoding_from_whatwg_label("gbk")
            .unwrap()
            .encode("路由", EncoderTrap::Strict)
            .unwrap();
        let encoded_path =
            percent_encoding::percent_encode(&gbk_path, NON_ALPHANUMERIC).to_string();
        let uri = format!("http://{}/{}", addr, encoded_path);
        let resp = reqwest::get(&uri).await?;
        assert_eq!(StatusCode::BAD_REQUEST, resp.status());
        assert!(resp
            .text()
            .await?
            .ends_with("path `/%C2%B7%D3%C9` is not a valid utf-8 string"));
        Ok(())
    }
}