mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-03 01:34:32 +02:00
Compare commits
23 Commits
utils-0.1.
...
remove
Author | SHA1 | Date | |
---|---|---|---|
31f0a96c20 | |||
66a7c59aaf | |||
316974616a | |||
b5d84bd980 | |||
e969429e2c | |||
6fe741025f | |||
f8e170fdaf | |||
474fed4dfe | |||
2b8f41e9e4 | |||
3484007e4e | |||
58ba1d8269 | |||
7017bad4bb | |||
112a7b6b1b | |||
48a1c7320c | |||
37d28304c9 | |||
640c39fdc8 | |||
cd5435e5ee | |||
bf9bd97173 | |||
61939c7af2 | |||
e8a1664c15 | |||
d1bfae7414 | |||
5ca00dc798 | |||
fd3e77ea83 |
@ -39,6 +39,7 @@ script:
|
||||
cd actix-rt && cargo test && cd ..
|
||||
cd actix-connector && cargo test && cd ..
|
||||
cd actix-utils && cargo test && cd ..
|
||||
cd router && cargo test && cd ..
|
||||
fi
|
||||
- |
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then
|
||||
@ -52,4 +53,5 @@ script:
|
||||
cd actix-codec && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash) && cd ..
|
||||
cd actix-server && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash) && cd ..
|
||||
cd actix-utils && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash) && cd ..
|
||||
cd router && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash) && cd ..
|
||||
fi
|
||||
|
@ -17,10 +17,12 @@ edition = "2018"
|
||||
members = [
|
||||
"actix-codec",
|
||||
"actix-connector",
|
||||
"actix-rt",
|
||||
"actix-service",
|
||||
"actix-server",
|
||||
"actix-rt",
|
||||
"actix-test-server",
|
||||
"actix-utils",
|
||||
"router",
|
||||
]
|
||||
|
||||
[dev-dependencies]
|
||||
|
@ -1,5 +1,10 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.1] - 2019-01-13
|
||||
|
||||
* Upgrade trust-dns-proto
|
||||
|
||||
|
||||
## [0.1.0] - 2018-12-09
|
||||
|
||||
* Move server to separate crate
|
||||
|
@ -32,8 +32,8 @@ actix-codec = "0.1.0"
|
||||
actix-rt = "0.1.0"
|
||||
futures = "0.1"
|
||||
tokio-tcp = "0.1"
|
||||
trust-dns-proto = "^0.5.0"
|
||||
trust-dns-resolver = "^0.10.0"
|
||||
trust-dns-proto = "0.6.2"
|
||||
trust-dns-resolver = "0.10.2"
|
||||
|
||||
# openssl
|
||||
openssl = { version="0.10", optional = true }
|
||||
|
@ -1,5 +1,29 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.3] - 2018-12-21
|
||||
|
||||
## Fixed
|
||||
|
||||
* Fix max concurrent connections handling
|
||||
|
||||
|
||||
## [0.1.2] - 2018-12-12
|
||||
|
||||
## Changed
|
||||
|
||||
* rename ServiceConfig::rt() to ServiceConfig::apply()
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix back-pressure for concurrent ssl handshakes
|
||||
|
||||
|
||||
## [0.1.1] - 2018-12-11
|
||||
|
||||
* Fix signal handling on windows
|
||||
|
||||
|
||||
## [0.1.0] - 2018-12-09
|
||||
|
||||
* Move server to separate crate
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-server"
|
||||
version = "0.1.0"
|
||||
version = "0.1.3"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix server - General purpose tcp server"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@ -66,3 +66,6 @@ webpki-roots = { version = "0.15", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger = "0.5"
|
||||
actix-service = "0.1.1"
|
||||
actix-codec = "0.1.0"
|
||||
actix-rt = "0.1.0"
|
||||
|
@ -64,7 +64,7 @@ impl ServerBuilder {
|
||||
|
||||
/// Set number of workers to start.
|
||||
///
|
||||
/// By default server uses number of available logical cpu as threads
|
||||
/// By default server uses number of available logical cpu as workers
|
||||
/// count.
|
||||
pub fn workers(mut self, num: usize) -> Self {
|
||||
self.threads = num;
|
||||
@ -108,8 +108,8 @@ impl ServerBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Run external configuration as part of the server building
|
||||
/// process
|
||||
/// Execute external configuration as part of the server building
|
||||
/// process.
|
||||
///
|
||||
/// This function is useful for moving parts of configuration to a
|
||||
/// different module or even library.
|
||||
@ -117,17 +117,20 @@ impl ServerBuilder {
|
||||
where
|
||||
F: Fn(&mut ServiceConfig) -> io::Result<()>,
|
||||
{
|
||||
let mut cfg = ServiceConfig::new();
|
||||
let mut cfg = ServiceConfig::new(self.threads);
|
||||
|
||||
f(&mut cfg)?;
|
||||
|
||||
let mut srv = ConfiguredService::new(cfg.rt);
|
||||
for (name, lst) in cfg.services {
|
||||
let token = self.token.next();
|
||||
srv.stream(token, name);
|
||||
self.sockets.push((token, lst));
|
||||
if let Some(apply) = cfg.apply {
|
||||
let mut srv = ConfiguredService::new(apply);
|
||||
for (name, lst) in cfg.services {
|
||||
let token = self.token.next();
|
||||
srv.stream(token, name);
|
||||
self.sockets.push((token, lst));
|
||||
}
|
||||
self.services.push(Box::new(srv));
|
||||
}
|
||||
self.services.push(Box::new(srv));
|
||||
self.threads = cfg.threads;
|
||||
|
||||
Ok(self)
|
||||
}
|
||||
|
@ -15,18 +15,28 @@ use super::services::{
|
||||
use super::Token;
|
||||
|
||||
pub struct ServiceConfig {
|
||||
pub(super) services: Vec<(String, net::TcpListener)>,
|
||||
pub(super) rt: Box<ServiceRuntimeConfiguration>,
|
||||
pub(crate) services: Vec<(String, net::TcpListener)>,
|
||||
pub(crate) apply: Option<Box<ServiceRuntimeConfiguration>>,
|
||||
pub(crate) threads: usize,
|
||||
}
|
||||
|
||||
impl ServiceConfig {
|
||||
pub(super) fn new() -> ServiceConfig {
|
||||
pub(super) fn new(threads: usize) -> ServiceConfig {
|
||||
ServiceConfig {
|
||||
threads,
|
||||
services: Vec::new(),
|
||||
rt: Box::new(not_configured),
|
||||
apply: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set number of workers to start.
|
||||
///
|
||||
/// By default server uses number of available logical cpu as workers
|
||||
/// count.
|
||||
pub fn workers(&mut self, num: usize) {
|
||||
self.threads = num;
|
||||
}
|
||||
|
||||
/// Add new service to server
|
||||
pub fn bind<U, N: AsRef<str>>(&mut self, name: N, addr: U) -> io::Result<&mut Self>
|
||||
where
|
||||
@ -43,16 +53,20 @@ impl ServiceConfig {
|
||||
|
||||
/// Add new service to server
|
||||
pub fn listen<N: AsRef<str>>(&mut self, name: N, lst: net::TcpListener) -> &mut Self {
|
||||
if self.apply.is_none() {
|
||||
self.apply = Some(Box::new(not_configured));
|
||||
}
|
||||
self.services.push((name.as_ref().to_string(), lst));
|
||||
self
|
||||
}
|
||||
|
||||
/// Register service configuration function
|
||||
pub fn rt<F>(&mut self, f: F) -> io::Result<()>
|
||||
/// Register service configuration function. This function get called
|
||||
/// during worker runtime configuration. It get executed in worker thread.
|
||||
pub fn apply<F>(&mut self, f: F) -> io::Result<()>
|
||||
where
|
||||
F: Fn(&mut ServiceRuntime) + Send + Clone + 'static,
|
||||
{
|
||||
self.rt = Box::new(f);
|
||||
self.apply = Some(Box::new(f));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
@ -9,6 +9,7 @@ use futures::task::AtomicTask;
|
||||
/// Counter could be cloned, total ncount is shared across all clones.
|
||||
pub struct Counter(Rc<CounterInner>);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CounterInner {
|
||||
count: Cell<usize>,
|
||||
capacity: usize,
|
||||
@ -40,6 +41,7 @@ impl Counter {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CounterGuard(Rc<CounterInner>);
|
||||
|
||||
impl CounterGuard {
|
||||
@ -57,11 +59,7 @@ impl Drop for CounterGuard {
|
||||
|
||||
impl CounterInner {
|
||||
fn inc(&self) {
|
||||
let num = self.count.get() + 1;
|
||||
self.count.set(num);
|
||||
if num == self.capacity {
|
||||
self.task.register();
|
||||
}
|
||||
self.count.set(self.count.get() + 1);
|
||||
}
|
||||
|
||||
fn dec(&self) {
|
||||
@ -73,6 +71,10 @@ impl CounterInner {
|
||||
}
|
||||
|
||||
fn available(&self) -> bool {
|
||||
self.count.get() < self.capacity
|
||||
let avail = self.count.get() < self.capacity;
|
||||
if !avail {
|
||||
self.task.register();
|
||||
}
|
||||
avail
|
||||
}
|
||||
}
|
||||
|
@ -83,9 +83,9 @@ where
|
||||
});
|
||||
|
||||
if let Ok(stream) = stream {
|
||||
spawn(self.service.call(stream).map_err(|_| ()).map(move |val| {
|
||||
spawn(self.service.call(stream).then(move |res| {
|
||||
drop(guard);
|
||||
val
|
||||
res.map_err(|_| ())
|
||||
}));
|
||||
ok(())
|
||||
} else {
|
||||
@ -122,9 +122,9 @@ where
|
||||
}
|
||||
|
||||
fn call(&mut self, (guard, req): (Option<CounterGuard>, ServerMessage)) -> Self::Future {
|
||||
spawn(self.service.call(req).map_err(|_| ()).map(move |val| {
|
||||
spawn(self.service.call(req).then(move |res| {
|
||||
drop(guard);
|
||||
val
|
||||
res.map_err(|_| ())
|
||||
}));
|
||||
ok(())
|
||||
}
|
||||
|
@ -34,10 +34,12 @@ impl Signals {
|
||||
let fut = {
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
tokio_signal::ctrl_c().and_then(move |stream| Signals {
|
||||
srv,
|
||||
stream: Box::new(stream.map(|_| Signal::Int)),
|
||||
})
|
||||
tokio_signal::ctrl_c()
|
||||
.map_err(|_| ())
|
||||
.and_then(move |stream| Signals {
|
||||
srv,
|
||||
stream: Box::new(stream.map(|_| Signal::Int)),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
@ -398,7 +398,7 @@ impl Future for Worker {
|
||||
let guard = self.conns.get();
|
||||
let _ = self.services[msg.token.0]
|
||||
.as_mut()
|
||||
.expect("actix net bug")
|
||||
.expect("actix-server bug")
|
||||
.1
|
||||
.call((Some(guard), ServerMessage::Connect(msg.io)));
|
||||
continue;
|
||||
|
@ -1,5 +1,26 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.4] - 2019-01-11
|
||||
|
||||
### Changed
|
||||
|
||||
* Use `FnMut` instead of `Fn` for `FnService`
|
||||
|
||||
|
||||
## [0.1.3] - 2018-12-12
|
||||
|
||||
### Changed
|
||||
|
||||
* Split service combinators to separate trait
|
||||
|
||||
|
||||
## [0.1.2] - 2018-12-12
|
||||
|
||||
### Fixed
|
||||
|
||||
* Release future early for `.and_then()` and `.then()` combinators
|
||||
|
||||
|
||||
## [0.1.1] - 2018-12-09
|
||||
|
||||
### Added
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-service"
|
||||
version = "0.1.1"
|
||||
version = "0.1.4"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix Service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
|
@ -61,7 +61,7 @@ where
|
||||
{
|
||||
b: Cell<B>,
|
||||
fut_b: Option<B::Future>,
|
||||
fut_a: A::Future,
|
||||
fut_a: Option<A::Future>,
|
||||
}
|
||||
|
||||
impl<A, B, Request> AndThenFuture<A, B, Request>
|
||||
@ -69,10 +69,10 @@ where
|
||||
A: Service<Request>,
|
||||
B: Service<A::Response, Error = A::Error>,
|
||||
{
|
||||
fn new(fut_a: A::Future, b: Cell<B>) -> Self {
|
||||
fn new(a: A::Future, b: Cell<B>) -> Self {
|
||||
AndThenFuture {
|
||||
b,
|
||||
fut_a,
|
||||
fut_a: Some(a),
|
||||
fut_b: None,
|
||||
}
|
||||
}
|
||||
@ -91,8 +91,9 @@ where
|
||||
return fut.poll();
|
||||
}
|
||||
|
||||
match self.fut_a.poll() {
|
||||
match self.fut_a.as_mut().expect("Bug in actix-service").poll() {
|
||||
Ok(Async::Ready(resp)) => {
|
||||
let _ = self.fut_a.take();
|
||||
self.fut_b = Some(self.b.get_mut().call(resp));
|
||||
self.poll()
|
||||
}
|
||||
@ -218,7 +219,7 @@ mod tests {
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::*;
|
||||
use crate::{NewService, Service};
|
||||
use crate::{NewService, Service, ServiceExt};
|
||||
|
||||
struct Srv1(Rc<Cell<usize>>);
|
||||
impl Service<&'static str> for Srv1 {
|
||||
|
@ -171,7 +171,7 @@ mod tests {
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::{IntoNewService, IntoService, NewService, Service};
|
||||
use crate::{IntoNewService, IntoService, NewService, Service, ServiceExt};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Srv;
|
||||
|
@ -9,7 +9,7 @@ use super::{IntoNewService, IntoService, NewService, Service};
|
||||
|
||||
pub struct FnService<F, Req, Resp, E, Fut>
|
||||
where
|
||||
F: Fn(Req) -> Fut,
|
||||
F: FnMut(Req) -> Fut,
|
||||
Fut: IntoFuture<Item = Resp, Error = E>,
|
||||
{
|
||||
f: F,
|
||||
@ -18,7 +18,7 @@ where
|
||||
|
||||
impl<F, Req, Resp, E, Fut> FnService<F, Req, Resp, E, Fut>
|
||||
where
|
||||
F: Fn(Req) -> Fut,
|
||||
F: FnMut(Req) -> Fut,
|
||||
Fut: IntoFuture<Item = Resp, Error = E>,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
@ -31,7 +31,7 @@ where
|
||||
|
||||
impl<F, Req, Resp, E, Fut> Clone for FnService<F, Req, Resp, E, Fut>
|
||||
where
|
||||
F: Fn(Req) -> Fut + Clone,
|
||||
F: FnMut(Req) -> Fut + Clone,
|
||||
Fut: IntoFuture<Item = Resp, Error = E>,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
@ -44,7 +44,7 @@ where
|
||||
|
||||
impl<F, Req, Resp, E, Fut> Service<Req> for FnService<F, Req, Resp, E, Fut>
|
||||
where
|
||||
F: Fn(Req) -> Fut,
|
||||
F: FnMut(Req) -> Fut,
|
||||
Fut: IntoFuture<Item = Resp, Error = E>,
|
||||
{
|
||||
type Response = Resp;
|
||||
@ -62,7 +62,7 @@ where
|
||||
|
||||
impl<F, Req, Resp, Err, Fut> IntoService<FnService<F, Req, Resp, Err, Fut>, Req> for F
|
||||
where
|
||||
F: Fn(Req) -> Fut + 'static,
|
||||
F: FnMut(Req) -> Fut + 'static,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
{
|
||||
fn into_service(self) -> FnService<F, Req, Resp, Err, Fut> {
|
||||
@ -72,7 +72,7 @@ where
|
||||
|
||||
pub struct FnNewService<F, Req, Resp, Err, Fut>
|
||||
where
|
||||
F: Fn(Req) -> Fut,
|
||||
F: FnMut(Req) -> Fut,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
{
|
||||
f: F,
|
||||
@ -81,7 +81,7 @@ where
|
||||
|
||||
impl<F, Req, Resp, Err, Fut> FnNewService<F, Req, Resp, Err, Fut>
|
||||
where
|
||||
F: Fn(Req) -> Fut + Clone,
|
||||
F: FnMut(Req) -> Fut + Clone,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
@ -94,7 +94,7 @@ where
|
||||
|
||||
impl<F, Req, Resp, Err, Fut> NewService<Req> for FnNewService<F, Req, Resp, Err, Fut>
|
||||
where
|
||||
F: Fn(Req) -> Fut + Clone,
|
||||
F: FnMut(Req) -> Fut + Clone,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
{
|
||||
type Response = Resp;
|
||||
@ -110,7 +110,7 @@ where
|
||||
|
||||
impl<F, Req, Resp, Err, Fut> IntoNewService<FnNewService<F, Req, Resp, Err, Fut>, Req> for F
|
||||
where
|
||||
F: Fn(Req) -> Fut + Clone + 'static,
|
||||
F: FnMut(Req) -> Fut + Clone + 'static,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewService<F, Req, Resp, Err, Fut> {
|
||||
@ -120,7 +120,7 @@ where
|
||||
|
||||
impl<F, Req, Resp, Err, Fut> Clone for FnNewService<F, Req, Resp, Err, Fut>
|
||||
where
|
||||
F: Fn(Req) -> Fut + Clone,
|
||||
F: FnMut(Req) -> Fut + Clone,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
|
@ -159,7 +159,7 @@ mod tests {
|
||||
use futures::future::{err, FutureResult};
|
||||
|
||||
use super::*;
|
||||
use crate::{IntoNewService, NewService, Service};
|
||||
use crate::{IntoNewService, NewService, Service, ServiceExt};
|
||||
|
||||
struct Srv;
|
||||
impl Service<()> for Srv {
|
||||
|
@ -50,7 +50,11 @@ pub trait Service<Request> {
|
||||
/// Calling `call` without calling `poll_ready` is permitted. The
|
||||
/// implementation must be resilient to this fact.
|
||||
fn call(&mut self, req: Request) -> Self::Future;
|
||||
}
|
||||
|
||||
/// An extension trait for `Service`s that provides a variety of convenient
|
||||
/// adapters
|
||||
pub trait ServiceExt<Request>: Service<Request> {
|
||||
/// Apply function to specified service and use it as a next service in
|
||||
/// chain.
|
||||
fn apply<T, I, F, Out, Req>(
|
||||
@ -146,6 +150,8 @@ pub trait Service<Request> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ?Sized, Request> ServiceExt<Request> for T where T: Service<Request> {}
|
||||
|
||||
/// Creates new `Service` values.
|
||||
///
|
||||
/// Acts as a service factory. This is useful for cases where new `Service`
|
||||
|
@ -189,7 +189,7 @@ mod tests {
|
||||
use futures::future::{ok, FutureResult};
|
||||
|
||||
use super::*;
|
||||
use crate::{IntoNewService, Service};
|
||||
use crate::{IntoNewService, Service, ServiceExt};
|
||||
|
||||
struct Srv;
|
||||
impl Service<()> for Srv {
|
||||
|
@ -190,7 +190,7 @@ mod tests {
|
||||
use futures::future::{err, FutureResult};
|
||||
|
||||
use super::*;
|
||||
use crate::{IntoNewService, NewService, Service};
|
||||
use crate::{IntoNewService, NewService, Service, ServiceExt};
|
||||
|
||||
struct Srv;
|
||||
|
||||
|
@ -61,7 +61,7 @@ where
|
||||
{
|
||||
b: Cell<B>,
|
||||
fut_b: Option<B::Future>,
|
||||
fut_a: A::Future,
|
||||
fut_a: Option<A::Future>,
|
||||
}
|
||||
|
||||
impl<A, B, Request> ThenFuture<A, B, Request>
|
||||
@ -69,10 +69,10 @@ where
|
||||
A: Service<Request>,
|
||||
B: Service<Result<A::Response, A::Error>>,
|
||||
{
|
||||
fn new(fut_a: A::Future, b: Cell<B>) -> Self {
|
||||
fn new(a: A::Future, b: Cell<B>) -> Self {
|
||||
ThenFuture {
|
||||
b,
|
||||
fut_a,
|
||||
fut_a: Some(a),
|
||||
fut_b: None,
|
||||
}
|
||||
}
|
||||
@ -91,12 +91,14 @@ where
|
||||
return fut.poll();
|
||||
}
|
||||
|
||||
match self.fut_a.poll() {
|
||||
match self.fut_a.as_mut().expect("bug in actix-service").poll() {
|
||||
Ok(Async::Ready(resp)) => {
|
||||
let _ = self.fut_a.take();
|
||||
self.fut_b = Some(self.b.get_mut().call(Ok(resp)));
|
||||
self.poll()
|
||||
}
|
||||
Err(err) => {
|
||||
let _ = self.fut_a.take();
|
||||
self.fut_b = Some(self.b.get_mut().call(Err(err)));
|
||||
self.poll()
|
||||
}
|
||||
@ -221,11 +223,11 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use futures::future::{err, ok, FutureResult};
|
||||
use futures::{Async, Poll};
|
||||
use futures::{Async, Future, Poll};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::*;
|
||||
use crate::{IntoNewService, NewService, Service, ServiceExt};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Srv1(Rc<Cell<usize>>);
|
||||
|
57
actix-test-server/Cargo.toml
Normal file
57
actix-test-server/Cargo.toml
Normal file
@ -0,0 +1,57 @@
|
||||
[package]
|
||||
name = "actix-test-server"
|
||||
version = "0.1.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix test server"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-test-server/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "tls", "rust-tls"]
|
||||
|
||||
[lib]
|
||||
name = "actix_test_server"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
# tls
|
||||
tls = ["native-tls", "actix-server/tls"]
|
||||
|
||||
# openssl
|
||||
ssl = ["openssl", "actix-server/ssl"]
|
||||
|
||||
# rustls
|
||||
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
|
||||
|
||||
[dependencies]
|
||||
actix-rt = "0.1.0"
|
||||
actix-server = "0.1.0"
|
||||
|
||||
log = "0.4"
|
||||
|
||||
# io
|
||||
net2 = "0.2"
|
||||
futures = "0.1"
|
||||
tokio-tcp = "0.1"
|
||||
tokio-reactor = "0.1"
|
||||
|
||||
# native-tls
|
||||
native-tls = { version="0.2", optional = true }
|
||||
|
||||
# openssl
|
||||
openssl = { version="0.10", optional = true }
|
||||
|
||||
#rustls
|
||||
rustls = { version = "^0.14", optional = true }
|
||||
tokio-rustls = { version = "^0.8", optional = true }
|
||||
webpki = { version = "0.18", optional = true }
|
||||
webpki-roots = { version = "0.15", optional = true }
|
142
actix-test-server/src/lib.rs
Normal file
142
actix-test-server/src/lib.rs
Normal file
@ -0,0 +1,142 @@
|
||||
//! Various helpers for Actix applications to use during testing.
|
||||
use std::sync::mpsc;
|
||||
use std::{net, thread};
|
||||
|
||||
use actix_rt::{Runtime, System};
|
||||
use actix_server::{Server, StreamServiceFactory};
|
||||
|
||||
use futures::Future;
|
||||
use net2::TcpBuilder;
|
||||
use tokio_reactor::Handle;
|
||||
use tokio_tcp::TcpStream;
|
||||
|
||||
/// The `TestServer` type.
|
||||
///
|
||||
/// `TestServer` is very simple test server that simplify process of writing
|
||||
/// integration tests cases for actix applications.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_test_server;
|
||||
/// # use actix_web::*;
|
||||
/// #
|
||||
/// # fn my_handler(req: &HttpRequest) -> HttpResponse {
|
||||
/// # HttpResponse::Ok().into()
|
||||
/// # }
|
||||
/// #
|
||||
/// # fn main() {
|
||||
/// use actix_test_server::TestServer;
|
||||
///
|
||||
/// let mut srv = TestServer::new(|app| app.handler(my_handler));
|
||||
///
|
||||
/// let req = srv.get().finish().unwrap();
|
||||
/// let response = srv.execute(req.send()).unwrap();
|
||||
/// assert!(response.status().is_success());
|
||||
/// # }
|
||||
/// ```
|
||||
pub struct TestServer;
|
||||
|
||||
/// Test server runstime
|
||||
pub struct TestServerRuntime {
|
||||
addr: net::SocketAddr,
|
||||
host: String,
|
||||
port: u16,
|
||||
rt: Runtime,
|
||||
}
|
||||
|
||||
impl TestServer {
|
||||
/// Start new test server with application factory
|
||||
pub fn with<F: StreamServiceFactory>(factory: F) -> TestServerRuntime {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
|
||||
// run server in separate thread
|
||||
thread::spawn(move || {
|
||||
let sys = System::new("actix-test-server");
|
||||
let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let local_addr = tcp.local_addr().unwrap();
|
||||
|
||||
Server::build()
|
||||
.listen("test", tcp, factory)
|
||||
.workers(1)
|
||||
.disable_signals()
|
||||
.start();
|
||||
|
||||
tx.send((System::current(), local_addr)).unwrap();
|
||||
sys.run();
|
||||
});
|
||||
|
||||
let (system, addr) = rx.recv().unwrap();
|
||||
System::set_current(system);
|
||||
|
||||
let rt = Runtime::new().unwrap();
|
||||
let host = format!("{}", addr.ip());
|
||||
let port = addr.port();
|
||||
|
||||
TestServerRuntime {
|
||||
addr,
|
||||
rt,
|
||||
host,
|
||||
port,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get firat available unused local address
|
||||
pub fn unused_addr() -> net::SocketAddr {
|
||||
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
|
||||
let socket = TcpBuilder::new_v4().unwrap();
|
||||
socket.bind(&addr).unwrap();
|
||||
socket.reuse_address(true).unwrap();
|
||||
let tcp = socket.to_tcp_listener().unwrap();
|
||||
tcp.local_addr().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl TestServerRuntime {
|
||||
/// Execute future on current runtime
|
||||
pub fn block_on<F, I, E>(&mut self, fut: F) -> Result<I, E>
|
||||
where
|
||||
F: Future<Item = I, Error = E>,
|
||||
{
|
||||
self.rt.block_on(fut)
|
||||
}
|
||||
|
||||
/// Spawn future to the current runtime
|
||||
pub fn spawn<F>(&mut self, fut: F)
|
||||
where
|
||||
F: Future<Item = (), Error = ()> + 'static,
|
||||
{
|
||||
self.rt.spawn(fut);
|
||||
}
|
||||
|
||||
/// Test server host
|
||||
pub fn host(&self) -> &str {
|
||||
&self.host
|
||||
}
|
||||
|
||||
/// Test server port
|
||||
pub fn port(&self) -> u16 {
|
||||
self.port
|
||||
}
|
||||
|
||||
/// Get test server address
|
||||
pub fn addr(&self) -> net::SocketAddr {
|
||||
self.addr
|
||||
}
|
||||
|
||||
/// Stop http server
|
||||
fn stop(&mut self) {
|
||||
System::current().stop();
|
||||
}
|
||||
|
||||
/// Connect to server, return tokio TcpStream
|
||||
pub fn connect(&self) -> std::io::Result<TcpStream> {
|
||||
TcpStream::from_std(net::TcpStream::connect(self.addr)?, &Handle::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestServerRuntime {
|
||||
fn drop(&mut self) {
|
||||
self.stop()
|
||||
}
|
||||
}
|
@ -1,5 +1,10 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.1] - 2018-xx-xx
|
||||
|
||||
* Fix framed transport error handling
|
||||
|
||||
|
||||
## [0.1.0] - 2018-12-09
|
||||
|
||||
* Move utils services to separate crate
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-utils"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix utils - various actix net related services"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@ -18,11 +18,10 @@ name = "actix_utils"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.1.1"
|
||||
actix-service = "0.1.2"
|
||||
actix-codec = "0.1.0"
|
||||
actix-rt = "0.1.0"
|
||||
|
||||
# io
|
||||
bytes = "0.4"
|
||||
futures = "0.1"
|
||||
tokio-timer = "0.2.8"
|
||||
log = "0.4"
|
@ -7,7 +7,8 @@ use actix_rt::Arbiter;
|
||||
use actix_service::{IntoNewService, IntoService, NewService, Service};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::unsync::mpsc;
|
||||
use futures::{Async, AsyncSink, Future, Poll, Sink, Stream};
|
||||
use futures::{Async, Future, Poll, Sink, Stream};
|
||||
use log::debug;
|
||||
|
||||
type Request<U> = <U as Decoder>::Item;
|
||||
type Response<U> = <U as Encoder>::Item;
|
||||
@ -179,16 +180,14 @@ where
|
||||
state: TransportState<S, U>,
|
||||
framed: Framed<T, U>,
|
||||
request: Option<Request<U>>,
|
||||
response: Option<Response<U>>,
|
||||
write_rx: mpsc::Receiver<Result<Response<U>, S::Error>>,
|
||||
write_tx: mpsc::Sender<Result<Response<U>, S::Error>>,
|
||||
flushed: bool,
|
||||
}
|
||||
|
||||
enum TransportState<S: Service<Request<U>>, U: Encoder + Decoder> {
|
||||
Processing,
|
||||
Error(FramedTransportError<S::Error, U>),
|
||||
EncoderError(FramedTransportError<S::Error, U>),
|
||||
FramedError(FramedTransportError<S::Error, U>),
|
||||
Stopping,
|
||||
}
|
||||
|
||||
@ -210,8 +209,6 @@ where
|
||||
service: service.into_service(),
|
||||
state: TransportState::Processing,
|
||||
request: None,
|
||||
response: None,
|
||||
flushed: true,
|
||||
}
|
||||
}
|
||||
|
||||
@ -247,7 +244,7 @@ where
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug + 'static,
|
||||
{
|
||||
fn poll_service(&mut self) -> bool {
|
||||
match self.service.poll_ready() {
|
||||
@ -266,7 +263,7 @@ where
|
||||
Ok(Async::Ready(Some(el))) => el,
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::Error(FramedTransportError::Decoder(err));
|
||||
TransportState::FramedError(FramedTransportError::Decoder(err));
|
||||
return true;
|
||||
}
|
||||
Ok(Async::NotReady) => return false,
|
||||
@ -307,59 +304,42 @@ where
|
||||
|
||||
/// write to sink
|
||||
fn poll_response(&mut self) -> bool {
|
||||
let mut item = self.response.take();
|
||||
loop {
|
||||
item = if let Some(msg) = item {
|
||||
self.flushed = false;
|
||||
match self.framed.start_send(msg) {
|
||||
Ok(AsyncSink::Ready) => None,
|
||||
Ok(AsyncSink::NotReady(item)) => Some(item),
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::EncoderError(FramedTransportError::Encoder(err));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// flush sink
|
||||
if !self.flushed {
|
||||
match self.framed.poll_complete() {
|
||||
Ok(Async::Ready(_)) => {
|
||||
self.flushed = true;
|
||||
}
|
||||
while !self.framed.is_write_buf_full() {
|
||||
match self.write_rx.poll() {
|
||||
Ok(Async::Ready(Some(msg))) => match msg {
|
||||
Ok(msg) => {
|
||||
if let Err(err) = self.framed.force_send(msg) {
|
||||
self.state = TransportState::FramedError(
|
||||
FramedTransportError::Encoder(err),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::Error(FramedTransportError::Service(err));
|
||||
return true;
|
||||
}
|
||||
},
|
||||
Ok(Async::NotReady) => break,
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::EncoderError(FramedTransportError::Encoder(err));
|
||||
return true;
|
||||
}
|
||||
Err(_) => panic!("Bug in actix-net code"),
|
||||
Ok(Async::Ready(None)) => panic!("Bug in actix-net code"),
|
||||
}
|
||||
}
|
||||
|
||||
// check channel
|
||||
if self.flushed {
|
||||
if item.is_none() {
|
||||
match self.write_rx.poll() {
|
||||
Ok(Async::Ready(Some(msg))) => match msg {
|
||||
Ok(msg) => item = Some(msg),
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::Error(FramedTransportError::Service(err));
|
||||
return true;
|
||||
}
|
||||
},
|
||||
Ok(Async::NotReady) => break,
|
||||
Err(_) => panic!("Bug in gw code"),
|
||||
Ok(Async::Ready(None)) => panic!("Bug in gw code"),
|
||||
if !self.framed.is_write_buf_empty() {
|
||||
match self.framed.poll_complete() {
|
||||
Ok(Async::NotReady) => break,
|
||||
Err(err) => {
|
||||
debug!("Error sending data: {:?}", err);
|
||||
self.state =
|
||||
TransportState::FramedError(FramedTransportError::Encoder(err));
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
Ok(Async::Ready(_)) => (),
|
||||
}
|
||||
} else {
|
||||
self.response = item;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@ -376,7 +356,7 @@ where
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug + 'static,
|
||||
{
|
||||
type Item = ();
|
||||
type Error = FramedTransportError<S::Error, U>;
|
||||
@ -391,14 +371,16 @@ where
|
||||
}
|
||||
}
|
||||
TransportState::Error(err) => {
|
||||
if self.poll_response() || self.flushed {
|
||||
if self.framed.is_write_buf_empty()
|
||||
|| (self.poll_response() || self.framed.is_write_buf_empty())
|
||||
{
|
||||
Err(err)
|
||||
} else {
|
||||
self.state = TransportState::Error(err);
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
TransportState::EncoderError(err) => Err(err),
|
||||
TransportState::FramedError(err) => Err(err),
|
||||
TransportState::Stopping => Ok(Async::Ready(())),
|
||||
}
|
||||
}
|
||||
|
@ -5,18 +5,22 @@ use actix_service::{IntoService, NewService, Service};
|
||||
use futures::unsync::mpsc;
|
||||
use futures::{future, Async, Future, Poll, Stream};
|
||||
|
||||
pub struct StreamDispatcher<S: Stream, T> {
|
||||
pub struct StreamDispatcher<S, T>
|
||||
where
|
||||
S: Stream,
|
||||
T: Service<Result<S::Item, S::Error>>,
|
||||
{
|
||||
stream: S,
|
||||
service: T,
|
||||
item: Option<Result<S::Item, S::Error>>,
|
||||
stop_rx: mpsc::UnboundedReceiver<()>,
|
||||
stop_tx: mpsc::UnboundedSender<()>,
|
||||
stop_rx: mpsc::UnboundedReceiver<T::Error>,
|
||||
stop_tx: mpsc::UnboundedSender<T::Error>,
|
||||
}
|
||||
|
||||
impl<S, T> StreamDispatcher<S, T>
|
||||
where
|
||||
S: Stream,
|
||||
T: Service<Result<S::Item, S::Error>, Response = (), Error = ()>,
|
||||
T: Service<Result<S::Item, S::Error>, Response = ()>,
|
||||
T::Future: 'static,
|
||||
{
|
||||
pub fn new<F>(stream: S, service: F) -> Self
|
||||
@ -37,15 +41,15 @@ where
|
||||
impl<S, T> Future for StreamDispatcher<S, T>
|
||||
where
|
||||
S: Stream,
|
||||
T: Service<Result<S::Item, S::Error>, Response = (), Error = ()>,
|
||||
T: Service<Result<S::Item, S::Error>, Response = ()>,
|
||||
T::Future: 'static,
|
||||
{
|
||||
type Item = ();
|
||||
type Error = ();
|
||||
type Error = T::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Ok(Async::Ready(Some(_))) = self.stop_rx.poll() {
|
||||
return Ok(Async::Ready(()));
|
||||
if let Ok(Async::Ready(Some(e))) = self.stop_rx.poll() {
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let mut item = self.item.take();
|
||||
@ -74,7 +78,7 @@ where
|
||||
|
||||
struct StreamDispatcherService<F: Future> {
|
||||
fut: F,
|
||||
stop: mpsc::UnboundedSender<()>,
|
||||
stop: mpsc::UnboundedSender<F::Error>,
|
||||
}
|
||||
|
||||
impl<F: Future> Future for StreamDispatcherService<F> {
|
||||
@ -85,8 +89,8 @@ impl<F: Future> Future for StreamDispatcherService<F> {
|
||||
match self.fut.poll() {
|
||||
Ok(Async::Ready(_)) => Ok(Async::Ready(())),
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(_) => {
|
||||
let _ = self.stop.unbounded_send(());
|
||||
Err(e) => {
|
||||
let _ = self.stop.unbounded_send(e);
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
}
|
||||
|
30
router/Cargo.toml
Normal file
30
router/Cargo.toml
Normal file
@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "actix-router"
|
||||
version = "0.1.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Path router"
|
||||
keywords = ["actix"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://actix.rs/api/actix-net/stable/actix_router/"
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
|
||||
[lib]
|
||||
name = "actix_router"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[features]
|
||||
default = ["http"]
|
||||
|
||||
[dependencies]
|
||||
bytes = "0.4"
|
||||
regex = "1.0"
|
||||
serde = "1.0.80"
|
||||
string = "0.1.3"
|
||||
http = { version="0.1.14", optional=true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_derive = "1.0"
|
709
router/src/de.rs
Normal file
709
router/src/de.rs
Normal file
@ -0,0 +1,709 @@
|
||||
use serde::de::{self, Deserializer, Error as DeError, Visitor};
|
||||
use serde::forward_to_deserialize_any;
|
||||
|
||||
use crate::path::{Path, PathIter};
|
||||
use crate::RequestPath;
|
||||
|
||||
macro_rules! unsupported_type {
|
||||
($trait_fn:ident, $name:expr) => {
|
||||
fn $trait_fn<V>(self, _: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor<'de>
|
||||
{
|
||||
Err(de::value::Error::custom(concat!("unsupported type: ", $name)))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! parse_single_value {
|
||||
($trait_fn:ident, $visit_fn:ident, $tp:tt) => {
|
||||
fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor<'de>
|
||||
{
|
||||
if self.path.len() != 1 {
|
||||
Err(de::value::Error::custom(
|
||||
format!("wrong number of parameters: {} expected 1",
|
||||
self.path.len()).as_str()))
|
||||
} else {
|
||||
let v = self.path[0].parse().map_err(
|
||||
|_| de::value::Error::custom(
|
||||
format!("can not parse {:?} to a {}", &self.path[0], $tp)))?;
|
||||
visitor.$visit_fn(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PathDeserializer<'de, T: RequestPath + 'de> {
|
||||
path: &'de Path<T>,
|
||||
}
|
||||
|
||||
impl<'de, T: RequestPath + 'de> PathDeserializer<'de, T> {
|
||||
pub fn new(path: &'de Path<T>) -> Self {
|
||||
PathDeserializer { path }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, T: RequestPath + 'de> Deserializer<'de> for PathDeserializer<'de, T> {
|
||||
type Error = de::value::Error;
|
||||
|
||||
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_map(ParamsDeserializer {
|
||||
params: self.path.iter(),
|
||||
current: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn deserialize_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.deserialize_map(visitor)
|
||||
}
|
||||
|
||||
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_unit_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.deserialize_unit(visitor)
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
if self.path.len() < len {
|
||||
Err(de::value::Error::custom(
|
||||
format!(
|
||||
"wrong number of parameters: {} expected {}",
|
||||
self.path.len(),
|
||||
len
|
||||
)
|
||||
.as_str(),
|
||||
))
|
||||
} else {
|
||||
visitor.visit_seq(ParamsSeq {
|
||||
params: self.path.iter(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_tuple_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
len: usize,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
if self.path.len() < len {
|
||||
Err(de::value::Error::custom(
|
||||
format!(
|
||||
"wrong number of parameters: {} expected {}",
|
||||
self.path.len(),
|
||||
len
|
||||
)
|
||||
.as_str(),
|
||||
))
|
||||
} else {
|
||||
visitor.visit_seq(ParamsSeq {
|
||||
params: self.path.iter(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
if self.path.len() < 1 {
|
||||
Err(de::value::Error::custom(
|
||||
"expeceted at least one parameters",
|
||||
))
|
||||
} else {
|
||||
visitor.visit_enum(ValueEnum {
|
||||
value: &self.path[0],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
if self.path.len() != 1 {
|
||||
Err(de::value::Error::custom(
|
||||
format!("wrong number of parameters: {} expected 1", self.path.len()).as_str(),
|
||||
))
|
||||
} else {
|
||||
visitor.visit_str(&self.path[0])
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_seq(ParamsSeq {
|
||||
params: self.path.iter(),
|
||||
})
|
||||
}
|
||||
|
||||
unsupported_type!(deserialize_any, "'any'");
|
||||
unsupported_type!(deserialize_bytes, "bytes");
|
||||
unsupported_type!(deserialize_option, "Option<T>");
|
||||
unsupported_type!(deserialize_identifier, "identifier");
|
||||
unsupported_type!(deserialize_ignored_any, "ignored_any");
|
||||
|
||||
parse_single_value!(deserialize_bool, visit_bool, "bool");
|
||||
parse_single_value!(deserialize_i8, visit_i8, "i8");
|
||||
parse_single_value!(deserialize_i16, visit_i16, "i16");
|
||||
parse_single_value!(deserialize_i32, visit_i32, "i32");
|
||||
parse_single_value!(deserialize_i64, visit_i64, "i64");
|
||||
parse_single_value!(deserialize_u8, visit_u8, "u8");
|
||||
parse_single_value!(deserialize_u16, visit_u16, "u16");
|
||||
parse_single_value!(deserialize_u32, visit_u32, "u32");
|
||||
parse_single_value!(deserialize_u64, visit_u64, "u64");
|
||||
parse_single_value!(deserialize_f32, visit_f32, "f32");
|
||||
parse_single_value!(deserialize_f64, visit_f64, "f64");
|
||||
parse_single_value!(deserialize_string, visit_string, "String");
|
||||
parse_single_value!(deserialize_byte_buf, visit_string, "String");
|
||||
parse_single_value!(deserialize_char, visit_char, "char");
|
||||
}
|
||||
|
||||
struct ParamsDeserializer<'de, T: RequestPath> {
|
||||
params: PathIter<'de, T>,
|
||||
current: Option<(&'de str, &'de str)>,
|
||||
}
|
||||
|
||||
impl<'de, T: RequestPath> de::MapAccess<'de> for ParamsDeserializer<'de, T> {
|
||||
type Error = de::value::Error;
|
||||
|
||||
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
|
||||
where
|
||||
K: de::DeserializeSeed<'de>,
|
||||
{
|
||||
self.current = self.params.next().map(|ref item| (item.0, item.1));
|
||||
match self.current {
|
||||
Some((key, _)) => Ok(Some(seed.deserialize(Key { key })?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: de::DeserializeSeed<'de>,
|
||||
{
|
||||
if let Some((_, value)) = self.current.take() {
|
||||
seed.deserialize(Value { value })
|
||||
} else {
|
||||
Err(de::value::Error::custom("unexpected item"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Key<'de> {
|
||||
key: &'de str,
|
||||
}
|
||||
|
||||
impl<'de> Deserializer<'de> for Key<'de> {
|
||||
type Error = de::value::Error;
|
||||
|
||||
fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_str(self.key)
|
||||
}
|
||||
|
||||
fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("Unexpected"))
|
||||
}
|
||||
|
||||
forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
|
||||
byte_buf option unit unit_struct newtype_struct seq tuple
|
||||
tuple_struct map struct enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! parse_value {
|
||||
($trait_fn:ident, $visit_fn:ident, $tp:tt) => {
|
||||
fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor<'de>
|
||||
{
|
||||
let v = self.value.parse().map_err(
|
||||
|_| de::value::Error::custom(
|
||||
format!("can not parse {:?} to a {}", self.value, $tp)))?;
|
||||
visitor.$visit_fn(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Value<'de> {
|
||||
value: &'de str,
|
||||
}
|
||||
|
||||
impl<'de> Deserializer<'de> for Value<'de> {
|
||||
type Error = de::value::Error;
|
||||
|
||||
parse_value!(deserialize_bool, visit_bool, "bool");
|
||||
parse_value!(deserialize_i8, visit_i8, "i8");
|
||||
parse_value!(deserialize_i16, visit_i16, "i16");
|
||||
parse_value!(deserialize_i32, visit_i32, "i16");
|
||||
parse_value!(deserialize_i64, visit_i64, "i64");
|
||||
parse_value!(deserialize_u8, visit_u8, "u8");
|
||||
parse_value!(deserialize_u16, visit_u16, "u16");
|
||||
parse_value!(deserialize_u32, visit_u32, "u32");
|
||||
parse_value!(deserialize_u64, visit_u64, "u64");
|
||||
parse_value!(deserialize_f32, visit_f32, "f32");
|
||||
parse_value!(deserialize_f64, visit_f64, "f64");
|
||||
parse_value!(deserialize_string, visit_string, "String");
|
||||
parse_value!(deserialize_byte_buf, visit_string, "String");
|
||||
parse_value!(deserialize_char, visit_char, "char");
|
||||
|
||||
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_unit_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_borrowed_bytes(self.value.as_bytes())
|
||||
}
|
||||
|
||||
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_borrowed_str(self.value)
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_some(self)
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_enum(ValueEnum { value: self.value })
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
fn deserialize_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("unsupported type: tuple"))
|
||||
}
|
||||
|
||||
fn deserialize_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: &'static [&'static str],
|
||||
_: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("unsupported type: struct"))
|
||||
}
|
||||
|
||||
fn deserialize_tuple_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
_: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("unsupported type: tuple struct"))
|
||||
}
|
||||
|
||||
unsupported_type!(deserialize_any, "any");
|
||||
unsupported_type!(deserialize_seq, "seq");
|
||||
unsupported_type!(deserialize_map, "map");
|
||||
unsupported_type!(deserialize_identifier, "identifier");
|
||||
}
|
||||
|
||||
struct ParamsSeq<'de, T: RequestPath> {
|
||||
params: PathIter<'de, T>,
|
||||
}
|
||||
|
||||
impl<'de, T: RequestPath> de::SeqAccess<'de> for ParamsSeq<'de, T> {
|
||||
type Error = de::value::Error;
|
||||
|
||||
fn next_element_seed<U>(&mut self, seed: U) -> Result<Option<U::Value>, Self::Error>
|
||||
where
|
||||
U: de::DeserializeSeed<'de>,
|
||||
{
|
||||
match self.params.next() {
|
||||
Some(item) => Ok(Some(seed.deserialize(Value { value: item.1 })?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ValueEnum<'de> {
|
||||
value: &'de str,
|
||||
}
|
||||
|
||||
impl<'de> de::EnumAccess<'de> for ValueEnum<'de> {
|
||||
type Error = de::value::Error;
|
||||
type Variant = UnitVariant;
|
||||
|
||||
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
|
||||
where
|
||||
V: de::DeserializeSeed<'de>,
|
||||
{
|
||||
Ok((seed.deserialize(Key { key: self.value })?, UnitVariant))
|
||||
}
|
||||
}
|
||||
|
||||
struct UnitVariant;
|
||||
|
||||
impl<'de> de::VariantAccess<'de> for UnitVariant {
|
||||
type Error = de::value::Error;
|
||||
|
||||
fn unit_variant(self) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
|
||||
where
|
||||
T: de::DeserializeSeed<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("not supported"))
|
||||
}
|
||||
|
||||
fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("not supported"))
|
||||
}
|
||||
|
||||
fn struct_variant<V>(
|
||||
self,
|
||||
_: &'static [&'static str],
|
||||
_: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("not supported"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde::de;
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
use super::*;
|
||||
use crate::path::Path;
|
||||
use crate::router::Router;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MyStruct {
|
||||
key: String,
|
||||
value: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Id {
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Test1(String, u32);
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Test2 {
|
||||
key: String,
|
||||
value: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum TestEnum {
|
||||
Val1,
|
||||
Val2,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Test3 {
|
||||
val: TestEnum,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_request_extract() {
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{key}/{value}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/name/user1/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
|
||||
let s: MyStruct = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(s.key, "name");
|
||||
assert_eq!(s.value, "user1");
|
||||
|
||||
let s: (String, String) =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(s.0, "name");
|
||||
assert_eq!(s.1, "user1");
|
||||
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{key}/{value}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/name/32/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
|
||||
let s: Test1 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(s.0, "name");
|
||||
assert_eq!(s.1, 32);
|
||||
|
||||
let s: Test2 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(s.key, "name");
|
||||
assert_eq!(s.value, 32);
|
||||
|
||||
let s: (String, u8) =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(s.0, "name");
|
||||
assert_eq!(s.1, 32);
|
||||
|
||||
let res: Vec<String> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(res[0], "name".to_owned());
|
||||
assert_eq!(res[1], "32".to_owned());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_path_single() {
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{value}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/32/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
let i: i8 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(i, 32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_enum() {
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{val}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/val1/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
let i: TestEnum = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(i, TestEnum::Val1);
|
||||
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{val1}/{val2}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/val1/val2/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
let i: (TestEnum, TestEnum) =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(i, (TestEnum::Val1, TestEnum::Val2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_enum_value() {
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{val}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/val1/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
let i: Test3 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(i.val, TestEnum::Val1);
|
||||
|
||||
let mut path = Path::new("/val3/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
let i: Result<Test3, de::value::Error> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path));
|
||||
assert!(i.is_err());
|
||||
assert!(format!("{:?}", i).contains("unknown variant"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_errors() {
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{value}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/name/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
|
||||
let s: Result<Test1, de::value::Error> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path));
|
||||
assert!(s.is_err());
|
||||
assert!(format!("{:?}", s).contains("wrong number of parameters"));
|
||||
|
||||
let s: Result<Test2, de::value::Error> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path));
|
||||
assert!(s.is_err());
|
||||
assert!(format!("{:?}", s).contains("can not parse"));
|
||||
|
||||
let s: Result<(String, String), de::value::Error> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path));
|
||||
assert!(s.is_err());
|
||||
assert!(format!("{:?}", s).contains("wrong number of parameters"));
|
||||
|
||||
let s: Result<u32, de::value::Error> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path));
|
||||
assert!(s.is_err());
|
||||
assert!(format!("{:?}", s).contains("can not parse"));
|
||||
}
|
||||
|
||||
// #[test]
|
||||
// fn test_extract_path_decode() {
|
||||
// let mut router = Router::<()>::default();
|
||||
// router.register_resource(Resource::new(ResourceDef::new("/{value}/")));
|
||||
|
||||
// macro_rules! test_single_value {
|
||||
// ($value:expr, $expected:expr) => {{
|
||||
// let req = TestRequest::with_uri($value).finish();
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// let req = req.with_route_info(info);
|
||||
// assert_eq!(
|
||||
// *Path::<String>::from_request(&req, &PathConfig::default()).unwrap(),
|
||||
// $expected
|
||||
// );
|
||||
// }};
|
||||
// }
|
||||
|
||||
// test_single_value!("/%25/", "%");
|
||||
// test_single_value!("/%40%C2%A3%24%25%5E%26%2B%3D/", "@£$%^&+=");
|
||||
// test_single_value!("/%2B/", "+");
|
||||
// test_single_value!("/%252B/", "%2B");
|
||||
// test_single_value!("/%2F/", "/");
|
||||
// test_single_value!("/%252F/", "%2F");
|
||||
// test_single_value!(
|
||||
// "/http%3A%2F%2Flocalhost%3A80%2Ffoo/",
|
||||
// "http://localhost:80/foo"
|
||||
// );
|
||||
// test_single_value!("/%2Fvar%2Flog%2Fsyslog/", "/var/log/syslog");
|
||||
// test_single_value!(
|
||||
// "/http%3A%2F%2Flocalhost%3A80%2Ffile%2F%252Fvar%252Flog%252Fsyslog/",
|
||||
// "http://localhost:80/file/%2Fvar%2Flog%2Fsyslog"
|
||||
// );
|
||||
|
||||
// let req = TestRequest::with_uri("/%25/7/?id=test").finish();
|
||||
|
||||
// let mut router = Router::<()>::default();
|
||||
// router.register_resource(Resource::new(ResourceDef::new("/{key}/{value}/")));
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// let req = req.with_route_info(info);
|
||||
|
||||
// let s = Path::<Test2>::from_request(&req, &PathConfig::default()).unwrap();
|
||||
// assert_eq!(s.key, "%");
|
||||
// assert_eq!(s.value, 7);
|
||||
|
||||
// let s = Path::<(String, String)>::from_request(&req, &PathConfig::default()).unwrap();
|
||||
// assert_eq!(s.0, "%");
|
||||
// assert_eq!(s.1, "7");
|
||||
// }
|
||||
|
||||
// #[test]
|
||||
// fn test_extract_path_no_decode() {
|
||||
// let mut router = Router::<()>::default();
|
||||
// router.register_resource(Resource::new(ResourceDef::new("/{value}/")));
|
||||
|
||||
// let req = TestRequest::with_uri("/%25/").finish();
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// let req = req.with_route_info(info);
|
||||
// assert_eq!(
|
||||
// *Path::<String>::from_request(&req, &&PathConfig::default().disable_decoding())
|
||||
// .unwrap(),
|
||||
// "%25"
|
||||
// );
|
||||
// }
|
||||
}
|
44
router/src/lib.rs
Normal file
44
router/src/lib.rs
Normal file
@ -0,0 +1,44 @@
|
||||
//! Resource path matching library.
|
||||
mod de;
|
||||
mod path;
|
||||
mod pattern;
|
||||
mod router;
|
||||
|
||||
pub use self::de::PathDeserializer;
|
||||
pub use self::path::Path;
|
||||
pub use self::pattern::Pattern;
|
||||
pub use self::router::{ResourceInfo, Router, RouterBuilder};
|
||||
|
||||
pub trait RequestPath {
|
||||
fn path(&self) -> &str;
|
||||
}
|
||||
|
||||
impl RequestPath for String {
|
||||
fn path(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> RequestPath for &'a str {
|
||||
fn path(&self) -> &str {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<[u8]>> RequestPath for string::String<T> {
|
||||
fn path(&self) -> &str {
|
||||
&*self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "http")]
|
||||
mod http_support {
|
||||
use super::RequestPath;
|
||||
use http::Uri;
|
||||
|
||||
impl RequestPath for Uri {
|
||||
fn path(&self) -> &str {
|
||||
self.path()
|
||||
}
|
||||
}
|
||||
}
|
196
router/src/path.rs
Normal file
196
router/src/path.rs
Normal file
@ -0,0 +1,196 @@
|
||||
use std::ops::Index;
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::RequestPath;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum PathItem {
|
||||
Static(&'static str),
|
||||
Segment(u16, u16),
|
||||
}
|
||||
|
||||
/// Resource path match information
|
||||
///
|
||||
/// If resource path contains variable patterns, `Path` stores them.
|
||||
#[derive(Debug)]
|
||||
pub struct Path<T> {
|
||||
path: T,
|
||||
pub(crate) skip: u16,
|
||||
pub(crate) segments: Vec<(Rc<String>, PathItem)>,
|
||||
}
|
||||
|
||||
impl<T: Default> Default for Path<T> {
|
||||
fn default() -> Self {
|
||||
Path {
|
||||
path: T::default(),
|
||||
skip: 0,
|
||||
segments: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> Clone for Path<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Path {
|
||||
path: self.path.clone(),
|
||||
skip: self.skip,
|
||||
segments: self.segments.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RequestPath> Path<T> {
|
||||
pub fn new(path: T) -> Path<T> {
|
||||
Path {
|
||||
path,
|
||||
skip: 0,
|
||||
segments: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get reference to inner path instance
|
||||
pub fn get_ref(&self) -> &T {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// Get mutable reference to inner path instance
|
||||
pub fn get_mut(&mut self) -> &mut T {
|
||||
&mut self.path
|
||||
}
|
||||
|
||||
/// Path
|
||||
pub fn path(&self) -> &str {
|
||||
let skip = self.skip as usize;
|
||||
let path = self.path.path();
|
||||
if skip <= path.len() {
|
||||
&path[skip..]
|
||||
} else {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset inner path
|
||||
pub fn set(&mut self, path: T) {
|
||||
self.skip = 0;
|
||||
self.path = path;
|
||||
self.segments.clear();
|
||||
}
|
||||
|
||||
/// Skip first `n` chars in path
|
||||
pub fn skip(&mut self, n: u16) {
|
||||
self.skip = self.skip + n;
|
||||
}
|
||||
|
||||
pub(crate) fn add(&mut self, name: Rc<String>, value: PathItem) {
|
||||
match value {
|
||||
PathItem::Static(s) => self.segments.push((name, PathItem::Static(s))),
|
||||
PathItem::Segment(begin, end) => self
|
||||
.segments
|
||||
.push((name, PathItem::Segment(self.skip + begin, self.skip + end))),
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn add_static(&mut self, name: &str, value: &'static str) {
|
||||
self.segments
|
||||
.push((Rc::new(name.to_string()), PathItem::Static(value)));
|
||||
}
|
||||
|
||||
/// Check if there are any matched patterns
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.segments.is_empty()
|
||||
}
|
||||
|
||||
/// Check number of extracted parameters
|
||||
pub fn len(&self) -> usize {
|
||||
self.segments.len()
|
||||
}
|
||||
|
||||
/// Get matched parameter by name without type conversion
|
||||
pub fn get(&self, key: &str) -> Option<&str> {
|
||||
for item in self.segments.iter() {
|
||||
if key == item.0.as_str() {
|
||||
return match item.1 {
|
||||
PathItem::Static(ref s) => Some(&s),
|
||||
PathItem::Segment(s, e) => {
|
||||
Some(&self.path.path()[(s as usize)..(e as usize)])
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
if key == "tail" {
|
||||
Some(&self.path.path()[(self.skip as usize)..])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get unprocessed part of the path
|
||||
pub fn unprocessed(&self) -> &str {
|
||||
&self.path.path()[(self.skip as usize)..]
|
||||
}
|
||||
|
||||
/// Get matched parameter by name.
|
||||
///
|
||||
/// If keyed parameter is not available empty string is used as default
|
||||
/// value.
|
||||
pub fn query(&self, key: &str) -> &str {
|
||||
if let Some(s) = self.get(key) {
|
||||
s
|
||||
} else {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
/// Return iterator to items in parameter container
|
||||
pub fn iter(&self) -> PathIter<T> {
|
||||
PathIter {
|
||||
idx: 0,
|
||||
params: self,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PathIter<'a, T> {
|
||||
idx: usize,
|
||||
params: &'a Path<T>,
|
||||
}
|
||||
|
||||
impl<'a, T: RequestPath> Iterator for PathIter<'a, T> {
|
||||
type Item = (&'a str, &'a str);
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<(&'a str, &'a str)> {
|
||||
if self.idx < self.params.len() {
|
||||
let idx = self.idx;
|
||||
let res = match self.params.segments[idx].1 {
|
||||
PathItem::Static(ref s) => &s,
|
||||
PathItem::Segment(s, e) => &self.params.path.path()[(s as usize)..(e as usize)],
|
||||
};
|
||||
self.idx += 1;
|
||||
return Some((&self.params.segments[idx].0, res));
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: RequestPath> Index<&'a str> for Path<T> {
|
||||
type Output = str;
|
||||
|
||||
fn index(&self, name: &'a str) -> &str {
|
||||
self.get(name)
|
||||
.expect("Value for parameter is not available")
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RequestPath> Index<usize> for Path<T> {
|
||||
type Output = str;
|
||||
|
||||
fn index(&self, idx: usize) -> &str {
|
||||
match self.segments[idx].1 {
|
||||
PathItem::Static(ref s) => &s,
|
||||
PathItem::Segment(s, e) => &self.path.path()[(s as usize)..(e as usize)],
|
||||
}
|
||||
}
|
||||
}
|
373
router/src/pattern.rs
Normal file
373
router/src/pattern.rs
Normal file
@ -0,0 +1,373 @@
|
||||
use std::cmp::min;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::rc::Rc;
|
||||
|
||||
use regex::{escape, Regex};
|
||||
|
||||
use crate::path::{Path, PathItem};
|
||||
use crate::RequestPath;
|
||||
|
||||
const MAX_DYNAMIC_SEGMENTS: usize = 16;
|
||||
|
||||
/// Resource type describes an entry in resources table
|
||||
///
|
||||
/// Resource pattern can contain only 16 dynamic segments
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Pattern {
|
||||
tp: PatternType,
|
||||
pattern: String,
|
||||
elements: Vec<PatternElement>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum PatternElement {
|
||||
Str(String),
|
||||
Var(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum PatternType {
|
||||
Static(String),
|
||||
Prefix(String),
|
||||
Dynamic(Regex, Vec<Rc<String>>, usize),
|
||||
}
|
||||
|
||||
impl Pattern {
|
||||
/// Parse path pattern and create new `Pattern` instance.
|
||||
///
|
||||
/// Panics if path pattern is wrong.
|
||||
pub fn new(path: &str) -> Self {
|
||||
Pattern::with_prefix(path, false)
|
||||
}
|
||||
|
||||
/// Parse path pattern and create new `Pattern` instance.
|
||||
///
|
||||
/// Use `prefix` type instead of `static`.
|
||||
///
|
||||
/// Panics if path regex pattern is wrong.
|
||||
pub fn prefix(path: &str) -> Self {
|
||||
Pattern::with_prefix(path, true)
|
||||
}
|
||||
|
||||
/// Parse path pattern and create new `Pattern` instance with custom prefix
|
||||
fn with_prefix(path: &str, for_prefix: bool) -> Self {
|
||||
let path = path.to_owned();
|
||||
let (pattern, elements, is_dynamic, len) = Pattern::parse(&path, for_prefix);
|
||||
|
||||
let tp = if is_dynamic {
|
||||
let re = match Regex::new(&pattern) {
|
||||
Ok(re) => re,
|
||||
Err(err) => panic!("Wrong path pattern: \"{}\" {}", path, err),
|
||||
};
|
||||
// actix creates one router per thread
|
||||
let names = re
|
||||
.capture_names()
|
||||
.filter_map(|name| name.map(|name| Rc::new(name.to_owned())))
|
||||
.collect();
|
||||
PatternType::Dynamic(re, names, len)
|
||||
} else if for_prefix {
|
||||
PatternType::Prefix(pattern.clone())
|
||||
} else {
|
||||
PatternType::Static(pattern.clone())
|
||||
};
|
||||
|
||||
Pattern {
|
||||
tp,
|
||||
elements,
|
||||
pattern: path.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Path pattern of the resource
|
||||
pub fn pattern(&self) -> &str {
|
||||
&self.pattern
|
||||
}
|
||||
|
||||
/// Check if path matchs this pattern?
|
||||
pub fn is_match(&self, path: &str) -> bool {
|
||||
match self.tp {
|
||||
PatternType::Static(ref s) => s == path,
|
||||
PatternType::Dynamic(ref re, _, _) => re.is_match(path),
|
||||
PatternType::Prefix(ref s) => path.starts_with(s),
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the given path and parameters a match against this pattern?
|
||||
pub fn match_path<T: RequestPath>(&self, path: &mut Path<T>) -> bool {
|
||||
match self.tp {
|
||||
PatternType::Static(ref s) => {
|
||||
if s == path.path() {
|
||||
path.skip(path.len() as u16);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
PatternType::Dynamic(ref re, ref names, len) => {
|
||||
let mut idx = 0;
|
||||
let mut pos = 0;
|
||||
let mut segments: [PathItem; MAX_DYNAMIC_SEGMENTS] =
|
||||
[PathItem::Static(""); MAX_DYNAMIC_SEGMENTS];
|
||||
|
||||
if let Some(captures) = re.captures(path.path()) {
|
||||
let mut passed = false;
|
||||
|
||||
for capture in captures.iter() {
|
||||
if let Some(ref m) = capture {
|
||||
if !passed {
|
||||
passed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
segments[idx] = PathItem::Segment(m.start() as u16, m.end() as u16);
|
||||
idx += 1;
|
||||
pos = m.end();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
for idx in 0..idx {
|
||||
path.add(names[idx].clone(), segments[idx]);
|
||||
}
|
||||
path.skip((pos + len) as u16);
|
||||
true
|
||||
}
|
||||
PatternType::Prefix(ref s) => {
|
||||
let rpath = path.path();
|
||||
let len = if s == rpath {
|
||||
s.len()
|
||||
} else if rpath.starts_with(s)
|
||||
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
|
||||
{
|
||||
if s.ends_with('/') {
|
||||
s.len() - 1
|
||||
} else {
|
||||
s.len()
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
path.skip(min(rpath.len(), len) as u16);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// /// Build resource path.
|
||||
// pub fn resource_path<U, I>(
|
||||
// &self, path: &mut String, elements: &mut U,
|
||||
// ) -> Result<(), UrlGenerationError>
|
||||
// where
|
||||
// U: Iterator<Item = I>,
|
||||
// I: AsRef<str>,
|
||||
// {
|
||||
// match self.tp {
|
||||
// PatternType::Prefix(ref p) => path.push_str(p),
|
||||
// PatternType::Static(ref p) => path.push_str(p),
|
||||
// PatternType::Dynamic(..) => {
|
||||
// for el in &self.elements {
|
||||
// match *el {
|
||||
// PatternElement::Str(ref s) => path.push_str(s),
|
||||
// PatternElement::Var(_) => {
|
||||
// if let Some(val) = elements.next() {
|
||||
// path.push_str(val.as_ref())
|
||||
// } else {
|
||||
// return Err(UrlGenerationError::NotEnoughElements);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// };
|
||||
// Ok(())
|
||||
// }
|
||||
|
||||
fn parse_param(pattern: &str) -> (PatternElement, String, &str) {
|
||||
const DEFAULT_PATTERN: &str = "[^/]+";
|
||||
let mut params_nesting = 0usize;
|
||||
let close_idx = pattern
|
||||
.find(|c| match c {
|
||||
'{' => {
|
||||
params_nesting += 1;
|
||||
false
|
||||
}
|
||||
'}' => {
|
||||
params_nesting -= 1;
|
||||
params_nesting == 0
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
.expect("malformed dynamic segment");
|
||||
let (mut param, rem) = pattern.split_at(close_idx + 1);
|
||||
param = ¶m[1..param.len() - 1]; // Remove outer brackets
|
||||
let (name, pattern) = match param.find(':') {
|
||||
Some(idx) => {
|
||||
let (name, pattern) = param.split_at(idx);
|
||||
(name, &pattern[1..])
|
||||
}
|
||||
None => (param, DEFAULT_PATTERN),
|
||||
};
|
||||
(
|
||||
PatternElement::Var(name.to_string()),
|
||||
format!(r"(?P<{}>{})", &name, &pattern),
|
||||
rem,
|
||||
)
|
||||
}
|
||||
|
||||
fn parse(
|
||||
mut pattern: &str,
|
||||
for_prefix: bool,
|
||||
) -> (String, Vec<PatternElement>, bool, usize) {
|
||||
if pattern.find('{').is_none() {
|
||||
return (
|
||||
String::from(pattern),
|
||||
vec![PatternElement::Str(String::from(pattern))],
|
||||
false,
|
||||
pattern.chars().count(),
|
||||
);
|
||||
};
|
||||
|
||||
let mut elems = Vec::new();
|
||||
let mut re = String::from("^");
|
||||
let mut dyn_elems = 0;
|
||||
|
||||
while let Some(idx) = pattern.find('{') {
|
||||
let (prefix, rem) = pattern.split_at(idx);
|
||||
elems.push(PatternElement::Str(String::from(prefix)));
|
||||
re.push_str(&escape(prefix));
|
||||
let (param_pattern, re_part, rem) = Self::parse_param(rem);
|
||||
elems.push(param_pattern);
|
||||
re.push_str(&re_part);
|
||||
pattern = rem;
|
||||
dyn_elems += 1;
|
||||
}
|
||||
|
||||
elems.push(PatternElement::Str(String::from(pattern)));
|
||||
re.push_str(&escape(pattern));
|
||||
|
||||
if dyn_elems > MAX_DYNAMIC_SEGMENTS {
|
||||
panic!(
|
||||
"Only {} dynanic segments are allowed, provided: {}",
|
||||
MAX_DYNAMIC_SEGMENTS, dyn_elems
|
||||
);
|
||||
}
|
||||
|
||||
if !for_prefix {
|
||||
re.push_str("$");
|
||||
}
|
||||
|
||||
(re, elems, true, pattern.chars().count())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Pattern {
|
||||
fn eq(&self, other: &Pattern) -> bool {
|
||||
self.pattern == other.pattern
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Pattern {}
|
||||
|
||||
impl Hash for Pattern {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.pattern.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_static() {
|
||||
let re = Pattern::new("/");
|
||||
assert!(re.is_match("/"));
|
||||
assert!(!re.is_match("/a"));
|
||||
|
||||
let re = Pattern::new("/name");
|
||||
assert!(re.is_match("/name"));
|
||||
assert!(!re.is_match("/name1"));
|
||||
assert!(!re.is_match("/name/"));
|
||||
assert!(!re.is_match("/name~"));
|
||||
|
||||
let re = Pattern::new("/name/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(!re.is_match("/name"));
|
||||
assert!(!re.is_match("/name/gs"));
|
||||
|
||||
let re = Pattern::new("/user/profile");
|
||||
assert!(re.is_match("/user/profile"));
|
||||
assert!(!re.is_match("/user/profile/profile"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_param() {
|
||||
let re = Pattern::new("/user/{id}");
|
||||
assert!(re.is_match("/user/profile"));
|
||||
assert!(re.is_match("/user/2345"));
|
||||
assert!(!re.is_match("/user/2345/"));
|
||||
assert!(!re.is_match("/user/2345/sdg"));
|
||||
|
||||
let mut path = Path::new("/user/profile");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "profile");
|
||||
|
||||
let mut path = Path::new("/user/1245125");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "1245125");
|
||||
|
||||
let re = Pattern::new("/v{version}/resource/{id}");
|
||||
assert!(re.is_match("/v1/resource/320120"));
|
||||
assert!(!re.is_match("/v/resource/1"));
|
||||
assert!(!re.is_match("/resource"));
|
||||
|
||||
let mut path = Path::new("/v151/resource/adahg32");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("version").unwrap(), "151");
|
||||
assert_eq!(path.get("id").unwrap(), "adahg32");
|
||||
|
||||
let re = Pattern::new("/{id:[[:digit:]]{6}}");
|
||||
assert!(re.is_match("/012345"));
|
||||
assert!(!re.is_match("/012"));
|
||||
assert!(!re.is_match("/01234567"));
|
||||
assert!(!re.is_match("/XXXXXX"));
|
||||
|
||||
let mut path = Path::new("/012345");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "012345");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resource_prefix() {
|
||||
let re = Pattern::prefix("/name");
|
||||
assert!(re.is_match("/name"));
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(re.is_match("/name/test/test"));
|
||||
assert!(re.is_match("/name1"));
|
||||
assert!(re.is_match("/name~"));
|
||||
|
||||
let re = Pattern::prefix("/name/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(re.is_match("/name/gs"));
|
||||
assert!(!re.is_match("/name"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reousrce_prefix_dynamic() {
|
||||
let re = Pattern::prefix("/{name}/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(re.is_match("/name/gs"));
|
||||
assert!(!re.is_match("/name"));
|
||||
|
||||
let mut path = Path::new("/test2/");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(&path["name"], "test2");
|
||||
assert_eq!(&path[0], "test2");
|
||||
|
||||
let mut path = Path::new("/test2/subpath1/subpath2/index.html");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(&path["name"], "test2");
|
||||
assert_eq!(&path[0], "test2");
|
||||
}
|
||||
}
|
405
router/src/router.rs
Normal file
405
router/src/router.rs
Normal file
@ -0,0 +1,405 @@
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::path::Path;
|
||||
use crate::pattern::Pattern;
|
||||
use crate::RequestPath;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
pub(crate) enum ResourceId {
|
||||
Default,
|
||||
Normal(u16),
|
||||
}
|
||||
|
||||
/// Information about current resource
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ResourceInfo {
|
||||
rmap: Rc<ResourceMap>,
|
||||
resource: ResourceId,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub(crate) struct ResourceMap {
|
||||
root: Option<Pattern>,
|
||||
named: HashMap<String, Pattern>,
|
||||
patterns: Vec<Pattern>,
|
||||
}
|
||||
|
||||
/// Resource router.
|
||||
pub struct Router<T> {
|
||||
rmap: Rc<ResourceMap>,
|
||||
named: HashMap<String, Pattern>,
|
||||
resources: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T> Router<T> {
|
||||
pub fn build() -> RouterBuilder<T> {
|
||||
RouterBuilder {
|
||||
rmap: ResourceMap::default(),
|
||||
named: HashMap::new(),
|
||||
resources: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn recognize<U: RequestPath>(&self, path: &mut Path<U>) -> Option<(&T, ResourceInfo)> {
|
||||
if !path.path().is_empty() {
|
||||
for (idx, resource) in self.rmap.patterns.iter().enumerate() {
|
||||
if resource.match_path(path) {
|
||||
let info = ResourceInfo {
|
||||
rmap: self.rmap.clone(),
|
||||
resource: ResourceId::Normal(idx as u16),
|
||||
};
|
||||
return Some((&self.resources[idx], info));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn recognize_mut<U: RequestPath>(
|
||||
&mut self,
|
||||
path: &mut Path<U>,
|
||||
) -> Option<(&mut T, ResourceInfo)> {
|
||||
if !path.path().is_empty() {
|
||||
for (idx, resource) in self.rmap.patterns.iter().enumerate() {
|
||||
if resource.match_path(path) {
|
||||
let info = ResourceInfo {
|
||||
rmap: self.rmap.clone(),
|
||||
resource: ResourceId::Normal(idx as u16),
|
||||
};
|
||||
return Some((&mut self.resources[idx], info));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> IntoIterator for &'a Router<T> {
|
||||
type Item = &'a T;
|
||||
type IntoIter = std::slice::Iter<'a, T>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.resources.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> IntoIterator for &'a mut Router<T> {
|
||||
type Item = &'a mut T;
|
||||
type IntoIter = std::slice::IterMut<'a, T>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.resources.iter_mut()
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourceMap {
|
||||
fn register(&mut self, pattern: Pattern) {
|
||||
self.patterns.push(pattern);
|
||||
}
|
||||
|
||||
fn register_named(&mut self, name: String, pattern: Pattern) {
|
||||
self.patterns.push(pattern.clone());
|
||||
self.named.insert(name, pattern);
|
||||
}
|
||||
|
||||
fn has_resource(&self, path: &str) -> bool {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RouterBuilder<T> {
|
||||
rmap: ResourceMap,
|
||||
named: HashMap<String, Pattern>,
|
||||
resources: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T> RouterBuilder<T> {
|
||||
pub fn path(&mut self, path: &str, resource: T) {
|
||||
self.rmap.register(Pattern::new(path));
|
||||
self.resources.push(resource);
|
||||
}
|
||||
|
||||
pub fn prefix(&mut self, prefix: &str, resource: T) {
|
||||
self.rmap.register(Pattern::prefix(prefix));
|
||||
self.resources.push(resource);
|
||||
}
|
||||
|
||||
pub fn finish(self) -> Router<T> {
|
||||
Router {
|
||||
rmap: Rc::new(self.rmap),
|
||||
named: self.named,
|
||||
resources: self.resources,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::path::Path;
|
||||
use crate::router::{ResourceId, Router};
|
||||
|
||||
#[test]
|
||||
fn test_recognizer_1() {
|
||||
let mut router = Router::<usize>::build();
|
||||
router.path("/name", 10);
|
||||
router.path("/name/{val}", 11);
|
||||
router.path("/name/{val}/index.html", 12);
|
||||
router.path("/file/{file}.{ext}", 13);
|
||||
router.path("/v{val}/{val2}/index.html", 14);
|
||||
router.path("/v/{tail:.*}", 15);
|
||||
router.path("/test2/{test}.html", 16);
|
||||
router.path("/{test}/index.html", 17);
|
||||
let mut router = router.finish();
|
||||
|
||||
let mut path = Path::new("/unknown");
|
||||
assert!(router.recognize_mut(&mut path).is_none());
|
||||
|
||||
let mut path = Path::new("/name");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 10);
|
||||
assert_eq!(info.resource, ResourceId::Normal(0));
|
||||
assert!(path.is_empty());
|
||||
|
||||
let mut path = Path::new("/name/value");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 11);
|
||||
assert_eq!(info.resource, ResourceId::Normal(1));
|
||||
assert_eq!(path.get("val").unwrap(), "value");
|
||||
assert_eq!(&path["val"], "value");
|
||||
|
||||
let mut path = Path::new("/name/value2/index.html");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 12);
|
||||
assert_eq!(info.resource, ResourceId::Normal(2));
|
||||
assert_eq!(path.get("val").unwrap(), "value2");
|
||||
|
||||
let mut path = Path::new("/file/file.gz");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 13);
|
||||
assert_eq!(info.resource, ResourceId::Normal(3));
|
||||
assert_eq!(path.get("file").unwrap(), "file");
|
||||
assert_eq!(path.get("ext").unwrap(), "gz");
|
||||
|
||||
let mut path = Path::new("/vtest/ttt/index.html");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 14);
|
||||
assert_eq!(info.resource, ResourceId::Normal(4));
|
||||
assert_eq!(path.get("val").unwrap(), "test");
|
||||
assert_eq!(path.get("val2").unwrap(), "ttt");
|
||||
|
||||
let mut path = Path::new("/v/blah-blah/index.html");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 15);
|
||||
assert_eq!(info.resource, ResourceId::Normal(5));
|
||||
assert_eq!(path.get("tail").unwrap(), "blah-blah/index.html");
|
||||
|
||||
let mut path = Path::new("/test2/index.html");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 16);
|
||||
assert_eq!(info.resource, ResourceId::Normal(6));
|
||||
assert_eq!(path.get("test").unwrap(), "index");
|
||||
|
||||
let mut path = Path::new("/bbb/index.html");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 17);
|
||||
assert_eq!(info.resource, ResourceId::Normal(7));
|
||||
assert_eq!(path.get("test").unwrap(), "bbb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_recognizer_2() {
|
||||
let mut router = Router::<usize>::build();
|
||||
router.path("/index.json", 10);
|
||||
router.path("/{source}.json", 11);
|
||||
let mut router = router.finish();
|
||||
|
||||
let mut path = Path::new("/index.json");
|
||||
let (h, _) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 10);
|
||||
|
||||
let mut path = Path::new("/test.json");
|
||||
let (h, _) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_recognizer_with_prefix() {
|
||||
let mut router = Router::<usize>::build();
|
||||
router.path("/name", 10);
|
||||
router.path("/name/{val}", 11);
|
||||
let mut router = router.finish();
|
||||
|
||||
let mut path = Path::new("/name");
|
||||
path.skip(5);
|
||||
assert!(router.recognize_mut(&mut path).is_none());
|
||||
|
||||
let mut path = Path::new("/test/name");
|
||||
path.skip(5);
|
||||
let (h, _) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 10);
|
||||
|
||||
let mut path = Path::new("/test/name/value");
|
||||
path.skip(5);
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 11);
|
||||
assert_eq!(info.resource, ResourceId::Normal(1));
|
||||
assert_eq!(path.get("val").unwrap(), "value");
|
||||
assert_eq!(&path["val"], "value");
|
||||
|
||||
// same patterns
|
||||
let mut router = Router::<usize>::build();
|
||||
router.path("/name", 10);
|
||||
router.path("/name/{val}", 11);
|
||||
let mut router = router.finish();
|
||||
|
||||
let mut path = Path::new("/name");
|
||||
path.skip(6);
|
||||
assert!(router.recognize_mut(&mut path).is_none());
|
||||
|
||||
let mut path = Path::new("/test2/name");
|
||||
path.skip(6);
|
||||
let (h, _) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 10);
|
||||
|
||||
let mut path = Path::new("/test2/name-test");
|
||||
path.skip(6);
|
||||
assert!(router.recognize_mut(&mut path).is_none());
|
||||
|
||||
let mut path = Path::new("/test2/name/ttt");
|
||||
path.skip(6);
|
||||
let (h, _) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 11);
|
||||
assert_eq!(&path["val"], "ttt");
|
||||
}
|
||||
|
||||
// #[test]
|
||||
// fn test_request_resource() {
|
||||
// let mut router = Router::<()>::default();
|
||||
// let mut resource = Resource::new(ResourcePattern::new("/index.json"));
|
||||
// resource.name("r1");
|
||||
// router.register_resource(resource);
|
||||
// let mut resource = Resource::new(ResourcePattern::new("/test.json"));
|
||||
// resource.name("r2");
|
||||
// router.register_resource(resource);
|
||||
|
||||
// let req = TestRequest::with_uri("/index.json").finish();
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// assert_eq!(info.resource, ResourceId::Normal(0));
|
||||
|
||||
// assert_eq!(info.name(), "r1");
|
||||
|
||||
// let req = TestRequest::with_uri("/test.json").finish();
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// assert_eq!(info.resource, ResourceId::Normal(1));
|
||||
// assert_eq!(info.name(), "r2");
|
||||
// }
|
||||
|
||||
// #[test]
|
||||
// fn test_has_resource() {
|
||||
// let mut router = Router::<()>::default();
|
||||
// let scope = Scope::new("/test").resource("/name", |_| "done");
|
||||
// router.register_scope(scope);
|
||||
|
||||
// {
|
||||
// let info = router.default_route_info();
|
||||
// assert!(!info.has_resource("/test"));
|
||||
// assert!(info.has_resource("/test/name"));
|
||||
// }
|
||||
|
||||
// let scope = Scope::new("/test2").nested("/test10", |s| s.resource("/name", |_| "done"));
|
||||
// router.register_scope(scope);
|
||||
|
||||
// let info = router.default_route_info();
|
||||
// assert!(info.has_resource("/test2/test10/name"));
|
||||
// }
|
||||
|
||||
// #[test]
|
||||
// fn test_url_for() {
|
||||
// let mut router = Router::<()>::new(ResourcePattern::prefix(""));
|
||||
|
||||
// let mut resource = Resource::new(ResourcePattern::new("/tttt"));
|
||||
// resource.name("r0");
|
||||
// router.register_resource(resource);
|
||||
|
||||
// let scope = Scope::new("/test").resource("/name", |r| {
|
||||
// r.name("r1");
|
||||
// });
|
||||
// router.register_scope(scope);
|
||||
|
||||
// let scope =
|
||||
// Scope::new("/test2").nested("/test10", |s| s.resource("/name", |r| r.name("r2")));
|
||||
// router.register_scope(scope);
|
||||
// router.finish();
|
||||
|
||||
// let req = TestRequest::with_uri("/test").request();
|
||||
// {
|
||||
// let info = router.default_route_info();
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r0", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/tttt");
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r1", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/test/name");
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r2", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/test2/test10/name");
|
||||
// }
|
||||
|
||||
// let req = TestRequest::with_uri("/test/name").request();
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// assert_eq!(info.resource, ResourceId::Normal(1));
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r0", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/tttt");
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r1", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/test/name");
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r2", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/test2/test10/name");
|
||||
// }
|
||||
|
||||
// #[test]
|
||||
// fn test_url_for_dynamic() {
|
||||
// let mut router = Router::<()>::new(ResourcePattern::prefix(""));
|
||||
|
||||
// let mut resource = Resource::new(ResourcePattern::new("/{name}/test/index.{ext}"));
|
||||
// resource.name("r0");
|
||||
// router.register_resource(resource);
|
||||
|
||||
// let scope = Scope::new("/{name1}").nested("/{name2}", |s| {
|
||||
// s.resource("/{name3}/test/index.{ext}", |r| r.name("r2"))
|
||||
// });
|
||||
// router.register_scope(scope);
|
||||
// router.finish();
|
||||
|
||||
// let req = TestRequest::with_uri("/test").request();
|
||||
// {
|
||||
// let info = router.default_route_info();
|
||||
|
||||
// let res = info.url_for(&req, "r0", vec!["sec1", "html"]).unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/sec1/test/index.html");
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r2", vec!["sec1", "sec2", "sec3", "html"])
|
||||
// .unwrap();
|
||||
// assert_eq!(
|
||||
// res.as_str(),
|
||||
// "http://localhost:8080/sec1/sec2/sec3/test/index.html"
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
}
|
Reference in New Issue
Block a user