mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-12 20:07:06 +02:00
Compare commits
12 Commits
service-v0
...
utils-0.2.
Author | SHA1 | Date | |
---|---|---|---|
|
a97d7f0ccf | ||
|
3d7daabdd7 | ||
|
32f4718880 | ||
|
b8f9bf4bc8 | ||
|
e354c6df92 | ||
|
a53f06a1a4 | ||
|
9979bfb3ef | ||
|
17d0f84f63 | ||
|
08bc328826 | ||
|
7dca264546 | ||
|
3bddba5da5 | ||
|
4be025926c |
25
Cargo.toml
25
Cargo.toml
@@ -1,18 +1,3 @@
|
||||
[package]
|
||||
name = "actix-net"
|
||||
version = "0.3.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix net - framework for the compisible network services for Rust (experimental)"
|
||||
readme = "README.md"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-net/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
"actix-codec",
|
||||
@@ -24,13 +9,3 @@ members = [
|
||||
"actix-utils",
|
||||
"router",
|
||||
]
|
||||
|
||||
[dev-dependencies]
|
||||
actix-service = "0.2.0"
|
||||
actix-codec = "0.1.0"
|
||||
actix-rt = { version="0.1.0" }
|
||||
actix-server = { version="0.2.0", features=["ssl"] }
|
||||
env_logger = "0.5"
|
||||
futures = "0.1.24"
|
||||
openssl = { version="0.10" }
|
||||
tokio-openssl = { version="0.3" }
|
||||
|
@@ -1,8 +1,15 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.1] - 2019-02-09
|
||||
|
||||
### Changes
|
||||
|
||||
* Drop service response
|
||||
|
||||
|
||||
## [0.2.0] - 2019-02-01
|
||||
|
||||
## Changes
|
||||
### Changes
|
||||
|
||||
* Migrate to actix-service 0.2
|
||||
|
||||
@@ -11,14 +18,14 @@
|
||||
|
||||
## [0.1.3] - 2018-12-21
|
||||
|
||||
## Fixed
|
||||
### Fixed
|
||||
|
||||
* Fix max concurrent connections handling
|
||||
|
||||
|
||||
## [0.1.2] - 2018-12-12
|
||||
|
||||
## Changed
|
||||
### Changed
|
||||
|
||||
* rename ServiceConfig::rt() to ServiceConfig::apply()
|
||||
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-server"
|
||||
version = "0.2.0"
|
||||
version = "0.2.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix server - General purpose tcp server"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -33,7 +33,7 @@ ssl = ["openssl", "tokio-openssl"]
|
||||
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.2.0"
|
||||
actix-service = "0.2.1"
|
||||
actix-rt = "0.1.0"
|
||||
|
||||
log = "0.4"
|
||||
|
@@ -23,13 +23,13 @@ pub enum ServerMessage {
|
||||
}
|
||||
|
||||
pub trait StreamServiceFactory: Send + Clone + 'static {
|
||||
type NewService: NewService<Request = TcpStream, Response = ()>;
|
||||
type NewService: NewService<Request = TcpStream>;
|
||||
|
||||
fn create(&self) -> Self::NewService;
|
||||
}
|
||||
|
||||
pub trait ServiceFactory: Send + Clone + 'static {
|
||||
type NewService: NewService<Request = ServerMessage, Response = ()>;
|
||||
type NewService: NewService<Request = ServerMessage>;
|
||||
|
||||
fn create(&self) -> Self::NewService;
|
||||
}
|
||||
@@ -63,7 +63,7 @@ impl<T> StreamService<T> {
|
||||
|
||||
impl<T> Service for StreamService<T>
|
||||
where
|
||||
T: Service<Request = TcpStream, Response = ()>,
|
||||
T: Service<Request = TcpStream>,
|
||||
T::Future: 'static,
|
||||
T::Error: 'static,
|
||||
{
|
||||
@@ -86,7 +86,7 @@ where
|
||||
if let Ok(stream) = stream {
|
||||
spawn(self.service.call(stream).then(move |res| {
|
||||
drop(guard);
|
||||
res.map_err(|_| ())
|
||||
res.map_err(|_| ()).map(|_| ())
|
||||
}));
|
||||
ok(())
|
||||
} else {
|
||||
@@ -110,7 +110,7 @@ impl<T> ServerService<T> {
|
||||
|
||||
impl<T> Service for ServerService<T>
|
||||
where
|
||||
T: Service<Request = ServerMessage, Response = ()>,
|
||||
T: Service<Request = ServerMessage>,
|
||||
T::Future: 'static,
|
||||
T::Error: 'static,
|
||||
{
|
||||
@@ -126,7 +126,7 @@ where
|
||||
fn call(&mut self, (guard, req): (Option<CounterGuard>, ServerMessage)) -> Self::Future {
|
||||
spawn(self.service.call(req).then(move |res| {
|
||||
drop(guard);
|
||||
res.map_err(|_| ())
|
||||
res.map_err(|_| ()).map(|_| ())
|
||||
}));
|
||||
ok(())
|
||||
}
|
||||
@@ -241,7 +241,7 @@ impl InternalServiceFactory for Box<InternalServiceFactory> {
|
||||
impl<F, T> ServiceFactory for F
|
||||
where
|
||||
F: Fn() -> T + Send + Clone + 'static,
|
||||
T: NewService<Request = ServerMessage, Response = ()>,
|
||||
T: NewService<Request = ServerMessage>,
|
||||
{
|
||||
type NewService = T;
|
||||
|
||||
@@ -253,7 +253,7 @@ where
|
||||
impl<F, T> StreamServiceFactory for F
|
||||
where
|
||||
F: Fn() -> T + Send + Clone + 'static,
|
||||
T: NewService<Request = TcpStream, Response = ()>,
|
||||
T: NewService<Request = TcpStream>,
|
||||
{
|
||||
type NewService = T;
|
||||
|
||||
|
@@ -1,5 +1,14 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.2] - 2019-02-19
|
||||
|
||||
### Added
|
||||
|
||||
* Added `NewService` impl for `Rc<S> where S: NewService`
|
||||
|
||||
* Added `NewService` impl for `Arc<S> where S: NewService`
|
||||
|
||||
|
||||
## [0.2.1] - 2019-02-03
|
||||
|
||||
### Changed
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-service"
|
||||
version = "0.2.1"
|
||||
version = "0.2.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix Service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
|
@@ -108,7 +108,7 @@ where
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.fut_t {
|
||||
return fut.poll().map_err(|e| e.into());
|
||||
return fut.poll();
|
||||
}
|
||||
|
||||
match self.fut_a.as_mut().expect("Bug in actix-service").poll() {
|
||||
|
@@ -72,7 +72,7 @@ where
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
try_ready!(self.a.poll_ready());
|
||||
self.b.get_mut().poll_ready().map_err(|e| e.into())
|
||||
self.b.get_mut().poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||
@@ -123,7 +123,7 @@ where
|
||||
self.poll()
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(err) => Err(err.into()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -78,7 +78,7 @@ where
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
try_ready!(self.service.poll_ready());
|
||||
self.transform.poll_ready().map_err(|e| e.into())
|
||||
self.transform.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
@@ -89,7 +89,6 @@ where
|
||||
/// `ApplyNewService` new service combinator
|
||||
pub struct ApplyNewService<T, S>
|
||||
where
|
||||
// T::InitError: From<S::InitError>,
|
||||
T: NewTransform<S::Service, InitError = S::InitError>,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService,
|
||||
|
@@ -18,6 +18,7 @@ impl<R, E> Blank<R, E> {
|
||||
}
|
||||
|
||||
impl<R> Blank<R, ()> {
|
||||
#[allow(clippy::new_ret_no_self)]
|
||||
pub fn new<E>() -> Blank<R, E> {
|
||||
Blank { _t: PhantomData }
|
||||
}
|
||||
|
@@ -1,3 +1,6 @@
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures::{Future, IntoFuture, Poll};
|
||||
|
||||
mod and_then;
|
||||
@@ -14,6 +17,7 @@ mod map_err;
|
||||
mod map_init_err;
|
||||
mod then;
|
||||
mod transform;
|
||||
mod transform_map_err;
|
||||
|
||||
pub use self::and_then::{AndThen, AndThenNewService};
|
||||
use self::and_then_apply::{AndThenTransform, AndThenTransformNewService};
|
||||
@@ -376,6 +380,38 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> NewService for Rc<S>
|
||||
where
|
||||
S: NewService,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S::Service;
|
||||
type InitError = S::InitError;
|
||||
type Future = S::Future;
|
||||
|
||||
fn new_service(&self) -> S::Future {
|
||||
self.as_ref().new_service()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> NewService for Arc<S>
|
||||
where
|
||||
S: NewService,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S::Service;
|
||||
type InitError = S::InitError;
|
||||
type Future = S::Future;
|
||||
|
||||
fn new_service(&self) -> S::Future {
|
||||
self.as_ref().new_service()
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a `Service`
|
||||
pub trait IntoService<T>
|
||||
where
|
||||
|
@@ -1,8 +1,7 @@
|
||||
use std::marker::PhantomData;
|
||||
use futures::{Future, Poll};
|
||||
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::Service;
|
||||
use crate::transform_map_err::{TransformMapErr, TransformMapErrNewTransform};
|
||||
use crate::Service;
|
||||
|
||||
/// An asynchronous function for transforming service call result.
|
||||
pub trait Transform<Service> {
|
||||
@@ -156,186 +155,3 @@ where
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Service for the `map_err` combinator, changing the type of a transform's
|
||||
/// error.
|
||||
///
|
||||
/// This is created by the `Transform::map_err` method.
|
||||
pub struct TransformMapErr<T, S, F, E> {
|
||||
transform: T,
|
||||
f: F,
|
||||
_t: PhantomData<(S, E)>,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErr<T, S, F, E> {
|
||||
/// Create new `MapErr` combinator
|
||||
pub fn new(transform: T, f: F) -> Self
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
Self {
|
||||
transform,
|
||||
f,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Clone for TransformMapErr<T, S, F, E>
|
||||
where
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
TransformMapErr {
|
||||
transform: self.transform.clone(),
|
||||
f: self.f.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Transform<S> for TransformMapErr<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = E;
|
||||
type Future = TransformMapErrFuture<T, S, F, E>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.transform.poll_ready().map_err(&self.f)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T::Request, service: &mut S) -> Self::Future {
|
||||
TransformMapErrFuture::new(self.transform.call(req, service), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
f: F,
|
||||
fut: T::Future,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
TransformMapErrFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Future for TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
type Item = T::Response;
|
||||
type Error = E;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
self.fut.poll().map_err(&self.f)
|
||||
}
|
||||
}
|
||||
|
||||
/// NewTransform for the `map_err` combinator, changing the type of a new
|
||||
/// transform's error.
|
||||
///
|
||||
/// This is created by the `NewTransform::map_err` method.
|
||||
pub struct TransformMapErrNewTransform<T, S, F, E> {
|
||||
t: T,
|
||||
f: F,
|
||||
e: PhantomData<(S, E)>,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErrNewTransform<T, S, F, E> {
|
||||
/// Create new `MapErr` new service instance
|
||||
pub fn new(t: T, f: F) -> Self
|
||||
where
|
||||
T: NewTransform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
Self {
|
||||
t,
|
||||
f,
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Clone for TransformMapErrNewTransform<T, S, F, E>
|
||||
where
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
t: self.t.clone(),
|
||||
f: self.f.clone(),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> NewTransform<S> for TransformMapErrNewTransform<T, S, F, E>
|
||||
where
|
||||
T: NewTransform<S>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = E;
|
||||
type Transform = TransformMapErr<T::Transform, S, F, E>;
|
||||
|
||||
type InitError = T::InitError;
|
||||
type Future = TransformMapErrNewTransformFuture<T, S, F, E>;
|
||||
|
||||
fn new_transform(&self) -> Self::Future {
|
||||
TransformMapErrNewTransformFuture::new(self.t.new_transform(), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformMapErrNewTransformFuture<T, S, F, E>
|
||||
where
|
||||
T: NewTransform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fut: T::Future,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErrNewTransformFuture<T, S, F, E>
|
||||
where
|
||||
T: NewTransform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
TransformMapErrNewTransformFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Future for TransformMapErrNewTransformFuture<T, S, F, E>
|
||||
where
|
||||
T: NewTransform<S>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Item = TransformMapErr<T::Transform, S, F, E>;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Async::Ready(tr) = self.fut.poll()? {
|
||||
Ok(Async::Ready(TransformMapErr::new(tr, self.f.clone())))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
188
actix-service/src/transform_map_err.rs
Normal file
188
actix-service/src/transform_map_err.rs
Normal file
@@ -0,0 +1,188 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::{NewTransform, Transform};
|
||||
|
||||
/// Service for the `map_err` combinator, changing the type of a transform's
|
||||
/// error.
|
||||
///
|
||||
/// This is created by the `Transform::map_err` method.
|
||||
pub struct TransformMapErr<T, S, F, E> {
|
||||
transform: T,
|
||||
f: F,
|
||||
_t: PhantomData<(S, E)>,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErr<T, S, F, E> {
|
||||
/// Create new `MapErr` combinator
|
||||
pub fn new(transform: T, f: F) -> Self
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
Self {
|
||||
transform,
|
||||
f,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Clone for TransformMapErr<T, S, F, E>
|
||||
where
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
TransformMapErr {
|
||||
transform: self.transform.clone(),
|
||||
f: self.f.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Transform<S> for TransformMapErr<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = E;
|
||||
type Future = TransformMapErrFuture<T, S, F, E>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.transform.poll_ready().map_err(&self.f)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T::Request, service: &mut S) -> Self::Future {
|
||||
TransformMapErrFuture::new(self.transform.call(req, service), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
f: F,
|
||||
fut: T::Future,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
TransformMapErrFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Future for TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
type Item = T::Response;
|
||||
type Error = E;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
self.fut.poll().map_err(&self.f)
|
||||
}
|
||||
}
|
||||
|
||||
/// NewTransform for the `map_err` combinator, changing the type of a new
|
||||
/// transform's error.
|
||||
///
|
||||
/// This is created by the `NewTransform::map_err` method.
|
||||
pub struct TransformMapErrNewTransform<T, S, F, E> {
|
||||
t: T,
|
||||
f: F,
|
||||
e: PhantomData<(S, E)>,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErrNewTransform<T, S, F, E> {
|
||||
/// Create new `MapErr` new service instance
|
||||
pub fn new(t: T, f: F) -> Self
|
||||
where
|
||||
T: NewTransform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
Self {
|
||||
t,
|
||||
f,
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Clone for TransformMapErrNewTransform<T, S, F, E>
|
||||
where
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
t: self.t.clone(),
|
||||
f: self.f.clone(),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> NewTransform<S> for TransformMapErrNewTransform<T, S, F, E>
|
||||
where
|
||||
T: NewTransform<S>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = E;
|
||||
type Transform = TransformMapErr<T::Transform, S, F, E>;
|
||||
|
||||
type InitError = T::InitError;
|
||||
type Future = TransformMapErrNewTransformFuture<T, S, F, E>;
|
||||
|
||||
fn new_transform(&self) -> Self::Future {
|
||||
TransformMapErrNewTransformFuture::new(self.t.new_transform(), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformMapErrNewTransformFuture<T, S, F, E>
|
||||
where
|
||||
T: NewTransform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fut: T::Future,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErrNewTransformFuture<T, S, F, E>
|
||||
where
|
||||
T: NewTransform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
TransformMapErrNewTransformFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Future for TransformMapErrNewTransformFuture<T, S, F, E>
|
||||
where
|
||||
T: NewTransform<S>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Item = TransformMapErr<T::Transform, S, F, E>;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Async::Ready(tr) = self.fut.poll()? {
|
||||
Ok(Async::Ready(TransformMapErr::new(tr, self.f.clone())))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,6 +1,27 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.1] - 2019-02-xx
|
||||
## [0.2.3] - 2019-02-21
|
||||
|
||||
### Added
|
||||
|
||||
* Add `BoxedNewService` and `BoxedService`
|
||||
|
||||
|
||||
## [0.2.2] - 2019-02-11
|
||||
|
||||
### Added
|
||||
|
||||
* Add `Display` impl for `TimeoutError`
|
||||
|
||||
* Add `Display` impl for `InOrderError`
|
||||
|
||||
|
||||
## [0.2.1] - 2019-02-06
|
||||
|
||||
### Added
|
||||
|
||||
* Add `InOrder` service. the service yields responses as they become available,
|
||||
in the order that their originating requests were submitted to the service.
|
||||
|
||||
### Changed
|
||||
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-utils"
|
||||
version = "0.2.1"
|
||||
version = "0.2.3"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix utils - various actix net related services"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -18,7 +18,7 @@ name = "actix_utils"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.2.0"
|
||||
actix-service = "0.2.1"
|
||||
actix-codec = "0.1.0"
|
||||
bytes = "0.4"
|
||||
futures = "0.1"
|
||||
@@ -28,6 +28,3 @@ log = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.1"
|
||||
|
||||
[patch.crates-io]
|
||||
actix-service = { git = "https://github.com/actix/actix-net.git" }
|
||||
|
102
actix-utils/src/boxed.rs
Normal file
102
actix-utils/src/boxed.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::{Future, Poll};
|
||||
|
||||
pub type BoxedService<Req, Res, Err> = Box<
|
||||
Service<
|
||||
Request = Req,
|
||||
Response = Res,
|
||||
Error = Err,
|
||||
Future = Box<Future<Item = Res, Error = Err>>,
|
||||
>,
|
||||
>;
|
||||
|
||||
pub type BoxedNewService<Req, Res, Err, InitErr> = Box<
|
||||
NewService<
|
||||
Request = Req,
|
||||
Response = Res,
|
||||
Error = Err,
|
||||
InitError = InitErr,
|
||||
Service = BoxedService<Req, Res, Err>,
|
||||
Future = Box<Future<Item = BoxedService<Req, Res, Err>, Error = InitErr>>,
|
||||
>,
|
||||
>;
|
||||
|
||||
/// Create boxed new service
|
||||
pub fn new_service<T>(
|
||||
service: T,
|
||||
) -> BoxedNewService<T::Request, T::Response, T::Error, T::InitError>
|
||||
where
|
||||
T: NewService + 'static,
|
||||
T::Service: 'static,
|
||||
{
|
||||
Box::new(NewServiceWrapper(service))
|
||||
}
|
||||
|
||||
/// Create boxed service
|
||||
pub fn service<T>(service: T) -> BoxedService<T::Request, T::Response, T::Error>
|
||||
where
|
||||
T: Service + 'static,
|
||||
T::Future: 'static,
|
||||
{
|
||||
Box::new(ServiceWrapper(service))
|
||||
}
|
||||
|
||||
struct NewServiceWrapper<T: NewService>(T);
|
||||
|
||||
impl<T, Req, Res, Err, InitErr> NewService for NewServiceWrapper<T>
|
||||
where
|
||||
Req: 'static,
|
||||
Res: 'static,
|
||||
Err: 'static,
|
||||
InitErr: 'static,
|
||||
T: NewService<Request = Req, Response = Res, Error = Err, InitError = InitErr>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
type Request = Req;
|
||||
type Response = Res;
|
||||
type Error = Err;
|
||||
type InitError = InitErr;
|
||||
type Service = BoxedService<Req, Res, Err>;
|
||||
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
Box::new(
|
||||
self.0
|
||||
.new_service()
|
||||
.map(|service| ServiceWrapper::boxed(service)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct ServiceWrapper<T: Service>(T);
|
||||
|
||||
impl<T> ServiceWrapper<T>
|
||||
where
|
||||
T: Service + 'static,
|
||||
T::Future: 'static,
|
||||
{
|
||||
fn boxed(service: T) -> BoxedService<T::Request, T::Response, T::Error> {
|
||||
Box::new(ServiceWrapper(service))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Req, Res, Err> Service for ServiceWrapper<T>
|
||||
where
|
||||
T: Service<Request = Req, Response = Res, Error = Err>,
|
||||
T::Future: 'static,
|
||||
{
|
||||
type Request = Req;
|
||||
type Response = Res;
|
||||
type Error = Err;
|
||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.0.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
Box::new(self.0.call(req))
|
||||
}
|
||||
}
|
@@ -61,9 +61,9 @@ where
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
if !self.count.available() {
|
||||
log::trace!("InFlight limit exceeded");
|
||||
return Ok(Async::NotReady);
|
||||
Ok(Async::NotReady)
|
||||
} else {
|
||||
return Ok(Async::Ready(()));
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -112,7 +112,7 @@ where
|
||||
}
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::Ready(())),
|
||||
Err(_) => panic!(),
|
||||
Err(_e) => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -1,4 +1,5 @@
|
||||
//! Actix utils - various helper services
|
||||
pub mod boxed;
|
||||
mod cell;
|
||||
pub mod cloneable;
|
||||
pub mod counter;
|
||||
@@ -6,6 +7,7 @@ pub mod either;
|
||||
pub mod framed;
|
||||
pub mod inflight;
|
||||
pub mod keepalive;
|
||||
pub mod order;
|
||||
pub mod stream;
|
||||
pub mod time;
|
||||
pub mod timeout;
|
||||
|
283
actix-utils/src/order.rs
Normal file
283
actix-utils/src/order.rs
Normal file
@@ -0,0 +1,283 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_service::{NewTransform, Service, Transform};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::task::AtomicTask;
|
||||
use futures::unsync::oneshot;
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
struct Record<I, E> {
|
||||
rx: oneshot::Receiver<Result<I, E>>,
|
||||
tx: oneshot::Sender<Result<I, E>>,
|
||||
}
|
||||
|
||||
/// Timeout error
|
||||
pub enum InOrderError<E> {
|
||||
/// Service error
|
||||
Service(E),
|
||||
/// Service call dropped
|
||||
Disconnected,
|
||||
}
|
||||
|
||||
impl<E> From<E> for InOrderError<E> {
|
||||
fn from(err: E) -> Self {
|
||||
InOrderError::Service(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: fmt::Debug> fmt::Debug for InOrderError<E> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
InOrderError::Service(e) => write!(f, "InOrderError::Service({:?})", e),
|
||||
InOrderError::Disconnected => write!(f, "InOrderError::Disconnected"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: fmt::Display> fmt::Display for InOrderError<E> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
InOrderError::Service(e) => e.fmt(f),
|
||||
InOrderError::Disconnected => write!(f, "InOrder service disconnected"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// InOrder - The service will yield responses as they become available,
|
||||
/// in the order that their originating requests were submitted to the service.
|
||||
pub struct InOrder<S> {
|
||||
_t: PhantomData<S>,
|
||||
}
|
||||
|
||||
impl<S> InOrder<S>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self { _t: PhantomData }
|
||||
}
|
||||
|
||||
pub fn service() -> impl Transform<
|
||||
S,
|
||||
Request = S::Request,
|
||||
Response = S::Response,
|
||||
Error = InOrderError<S::Error>,
|
||||
> {
|
||||
InOrderService::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Default for InOrder<S>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> NewTransform<S> for InOrder<S>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = InOrderError<S::Error>;
|
||||
type InitError = ();
|
||||
type Transform = InOrderService<S>;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn new_transform(&self) -> Self::Future {
|
||||
ok(InOrderService::new())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InOrderService<S: Service> {
|
||||
task: Rc<AtomicTask>,
|
||||
acks: VecDeque<Record<S::Response, S::Error>>,
|
||||
}
|
||||
|
||||
impl<S> InOrderService<S>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
acks: VecDeque::new(),
|
||||
task: Rc::new(AtomicTask::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Default for InOrderService<S>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Transform<S> for InOrderService<S>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = InOrderError<S::Error>;
|
||||
type Future = InOrderServiceResponse<S>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.task.register();
|
||||
|
||||
// check acks
|
||||
while !self.acks.is_empty() {
|
||||
let rec = self.acks.front_mut().unwrap();
|
||||
match rec.rx.poll() {
|
||||
Ok(Async::Ready(res)) => {
|
||||
let rec = self.acks.pop_front().unwrap();
|
||||
let _ = rec.tx.send(res);
|
||||
}
|
||||
Ok(Async::NotReady) => break,
|
||||
Err(oneshot::Canceled) => return Err(InOrderError::Disconnected),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, request: S::Request, service: &mut S) -> Self::Future {
|
||||
let (tx1, rx1) = oneshot::channel();
|
||||
let (tx2, rx2) = oneshot::channel();
|
||||
self.acks.push_back(Record { rx: rx1, tx: tx2 });
|
||||
|
||||
let task = self.task.clone();
|
||||
tokio_current_thread::spawn(service.call(request).then(move |res| {
|
||||
task.notify();
|
||||
let _ = tx1.send(res);
|
||||
Ok(())
|
||||
}));
|
||||
|
||||
InOrderServiceResponse { rx: rx2 }
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct InOrderServiceResponse<S: Service> {
|
||||
rx: oneshot::Receiver<Result<S::Response, S::Error>>,
|
||||
}
|
||||
|
||||
impl<S: Service> Future for InOrderServiceResponse<S> {
|
||||
type Item = S::Response;
|
||||
type Error = InOrderError<S::Error>;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.rx.poll() {
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Ok(Async::Ready(Ok(res))) => Ok(Async::Ready(res)),
|
||||
Ok(Async::Ready(Err(e))) => Err(e.into()),
|
||||
Err(oneshot::Canceled) => Err(InOrderError::Disconnected),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use futures::future::{lazy, Future};
|
||||
use futures::{stream::futures_unordered, sync::oneshot, Async, Poll, Stream};
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
use actix_service::{Blank, Service, ServiceExt};
|
||||
|
||||
struct Srv;
|
||||
|
||||
impl Service for Srv {
|
||||
type Request = oneshot::Receiver<usize>;
|
||||
type Response = usize;
|
||||
type Error = ();
|
||||
type Future = Box<Future<Item = usize, Error = ()>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: oneshot::Receiver<usize>) -> Self::Future {
|
||||
Box::new(req.map_err(|_| ()))
|
||||
}
|
||||
}
|
||||
|
||||
struct SrvPoll<S: Service> {
|
||||
s: S,
|
||||
}
|
||||
|
||||
impl<S: Service> Future for SrvPoll<S> {
|
||||
type Item = ();
|
||||
type Error = ();
|
||||
|
||||
fn poll(&mut self) -> Poll<(), ()> {
|
||||
let _ = self.s.poll_ready();
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inorder() {
|
||||
let (tx1, rx1) = oneshot::channel();
|
||||
let (tx2, rx2) = oneshot::channel();
|
||||
let (tx3, rx3) = oneshot::channel();
|
||||
let (tx_stop, rx_stop) = oneshot::channel();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let rx1 = rx1;
|
||||
let rx2 = rx2;
|
||||
let rx3 = rx3;
|
||||
let tx_stop = tx_stop;
|
||||
let _ = actix_rt::System::new("test").block_on(lazy(move || {
|
||||
let mut srv = Blank::new().apply(InOrderService::new(), Srv);
|
||||
|
||||
let res1 = srv.call(rx1);
|
||||
let res2 = srv.call(rx2);
|
||||
let res3 = srv.call(rx3);
|
||||
tokio_current_thread::spawn(SrvPoll { s: srv });
|
||||
|
||||
futures_unordered(vec![res1, res2, res3])
|
||||
.collect()
|
||||
.and_then(move |res: Vec<_>| {
|
||||
assert_eq!(res, vec![1, 2, 3]);
|
||||
let _ = tx_stop.send(());
|
||||
Ok(())
|
||||
})
|
||||
}));
|
||||
});
|
||||
|
||||
let _ = tx3.send(3);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let _ = tx2.send(2);
|
||||
let _ = tx1.send(1);
|
||||
|
||||
let _ = rx_stop.wait();
|
||||
}
|
||||
}
|
@@ -133,7 +133,7 @@ impl SystemTimeService {
|
||||
/// Get current time. This function has to be called from
|
||||
/// future's poll method, otherwise it panics.
|
||||
pub fn now(&self) -> time::SystemTime {
|
||||
let cur = self.0.get_ref().current.clone();
|
||||
let cur = self.0.get_ref().current;
|
||||
if let Some(cur) = cur {
|
||||
cur
|
||||
} else {
|
||||
|
@@ -41,6 +41,15 @@ impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: fmt::Display> fmt::Display for TimeoutError<E> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
TimeoutError::Service(e) => e.fmt(f),
|
||||
TimeoutError::Timeout => write!(f, "Service call timeout"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: PartialEq> PartialEq for TimeoutError<E> {
|
||||
fn eq(&self, other: &TimeoutError<E>) -> bool {
|
||||
match self {
|
||||
@@ -212,7 +221,7 @@ mod tests {
|
||||
let wait_time = Duration::from_millis(150);
|
||||
|
||||
let res = actix_rt::System::new("test").block_on(lazy(|| {
|
||||
let timeout = BlankNewService::default()
|
||||
let timeout = BlankNewService::<_, _, ()>::default()
|
||||
.apply(Timeout::new(resolution), || Ok(SleepService(wait_time)));
|
||||
if let Async::Ready(mut to) = timeout.new_service().poll().unwrap() {
|
||||
to.call(())
|
||||
|
@@ -2,7 +2,7 @@ use serde::de::{self, Deserializer, Error as DeError, Visitor};
|
||||
use serde::forward_to_deserialize_any;
|
||||
|
||||
use crate::path::{Path, PathIter};
|
||||
use crate::RequestPath;
|
||||
use crate::ResourcePath;
|
||||
|
||||
macro_rules! unsupported_type {
|
||||
($trait_fn:ident, $name:expr) => {
|
||||
@@ -33,17 +33,17 @@ macro_rules! parse_single_value {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PathDeserializer<'de, T: RequestPath + 'de> {
|
||||
pub struct PathDeserializer<'de, T: ResourcePath + 'de> {
|
||||
path: &'de Path<T>,
|
||||
}
|
||||
|
||||
impl<'de, T: RequestPath + 'de> PathDeserializer<'de, T> {
|
||||
impl<'de, T: ResourcePath + '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> {
|
||||
impl<'de, T: ResourcePath + 'de> Deserializer<'de> for PathDeserializer<'de, T> {
|
||||
type Error = de::value::Error;
|
||||
|
||||
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
@@ -206,12 +206,12 @@ impl<'de, T: RequestPath + 'de> Deserializer<'de> for PathDeserializer<'de, T> {
|
||||
parse_single_value!(deserialize_char, visit_char, "char");
|
||||
}
|
||||
|
||||
struct ParamsDeserializer<'de, T: RequestPath> {
|
||||
struct ParamsDeserializer<'de, T: ResourcePath> {
|
||||
params: PathIter<'de, T>,
|
||||
current: Option<(&'de str, &'de str)>,
|
||||
}
|
||||
|
||||
impl<'de, T: RequestPath> de::MapAccess<'de> for ParamsDeserializer<'de, T> {
|
||||
impl<'de, T: ResourcePath> 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>
|
||||
@@ -406,11 +406,11 @@ impl<'de> Deserializer<'de> for Value<'de> {
|
||||
unsupported_type!(deserialize_identifier, "identifier");
|
||||
}
|
||||
|
||||
struct ParamsSeq<'de, T: RequestPath> {
|
||||
struct ParamsSeq<'de, T: ResourcePath> {
|
||||
params: PathIter<'de, T>,
|
||||
}
|
||||
|
||||
impl<'de, T: RequestPath> de::SeqAccess<'de> for ParamsSeq<'de, T> {
|
||||
impl<'de, T: ResourcePath> 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>
|
||||
|
@@ -1,31 +1,31 @@
|
||||
//! Resource path matching library.
|
||||
mod de;
|
||||
mod path;
|
||||
mod pattern;
|
||||
mod resource;
|
||||
mod router;
|
||||
|
||||
pub use self::de::PathDeserializer;
|
||||
pub use self::path::Path;
|
||||
pub use self::pattern::Pattern;
|
||||
pub use self::resource::ResourceDef;
|
||||
pub use self::router::{ResourceInfo, Router, RouterBuilder};
|
||||
|
||||
pub trait RequestPath {
|
||||
pub trait ResourcePath {
|
||||
fn path(&self) -> &str;
|
||||
}
|
||||
|
||||
impl RequestPath for String {
|
||||
impl ResourcePath for String {
|
||||
fn path(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> RequestPath for &'a str {
|
||||
impl<'a> ResourcePath for &'a str {
|
||||
fn path(&self) -> &str {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<[u8]>> RequestPath for string::String<T> {
|
||||
impl<T: AsRef<[u8]>> ResourcePath for string::String<T> {
|
||||
fn path(&self) -> &str {
|
||||
&*self
|
||||
}
|
||||
@@ -39,10 +39,10 @@ pub use self::url::Url;
|
||||
|
||||
#[cfg(feature = "http")]
|
||||
mod http_support {
|
||||
use super::RequestPath;
|
||||
use super::ResourcePath;
|
||||
use http::Uri;
|
||||
|
||||
impl RequestPath for Uri {
|
||||
impl ResourcePath for Uri {
|
||||
fn path(&self) -> &str {
|
||||
self.path()
|
||||
}
|
||||
|
@@ -4,7 +4,7 @@ use std::rc::Rc;
|
||||
use serde::de;
|
||||
|
||||
use crate::de::PathDeserializer;
|
||||
use crate::RequestPath;
|
||||
use crate::ResourcePath;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum PathItem {
|
||||
@@ -42,7 +42,7 @@ impl<T: Clone> Clone for Path<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RequestPath> Path<T> {
|
||||
impl<T: ResourcePath> Path<T> {
|
||||
pub fn new(path: T) -> Path<T> {
|
||||
Path {
|
||||
path,
|
||||
@@ -165,7 +165,7 @@ pub struct PathIter<'a, T> {
|
||||
params: &'a Path<T>,
|
||||
}
|
||||
|
||||
impl<'a, T: RequestPath> Iterator for PathIter<'a, T> {
|
||||
impl<'a, T: ResourcePath> Iterator for PathIter<'a, T> {
|
||||
type Item = (&'a str, &'a str);
|
||||
|
||||
#[inline]
|
||||
@@ -183,7 +183,7 @@ impl<'a, T: RequestPath> Iterator for PathIter<'a, T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: RequestPath> Index<&'a str> for Path<T> {
|
||||
impl<'a, T: ResourcePath> Index<&'a str> for Path<T> {
|
||||
type Output = str;
|
||||
|
||||
fn index(&self, name: &'a str) -> &str {
|
||||
@@ -192,7 +192,7 @@ impl<'a, T: RequestPath> Index<&'a str> for Path<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RequestPath> Index<usize> for Path<T> {
|
||||
impl<T: ResourcePath> Index<usize> for Path<T> {
|
||||
type Output = str;
|
||||
|
||||
fn index(&self, idx: usize) -> &str {
|
||||
|
@@ -5,20 +5,35 @@ use std::rc::Rc;
|
||||
use regex::{escape, Regex};
|
||||
|
||||
use crate::path::{Path, PathItem};
|
||||
use crate::RequestPath;
|
||||
use crate::ResourcePath;
|
||||
|
||||
const MAX_DYNAMIC_SEGMENTS: usize = 16;
|
||||
|
||||
/// Resource type describes an entry in resources table
|
||||
/// ResourceDef describes an entry in resources table
|
||||
///
|
||||
/// Resource pattern can contain only 16 dynamic segments
|
||||
/// Resource definition can contain only 16 dynamic segments
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Pattern {
|
||||
pub struct ResourceDef {
|
||||
tp: PatternType,
|
||||
rtp: ResourceType,
|
||||
name: String,
|
||||
pattern: String,
|
||||
elements: Vec<PatternElement>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
/// Resource type
|
||||
pub enum ResourceType {
|
||||
/// Normal resource
|
||||
Normal,
|
||||
/// Resource for application default handler
|
||||
Default,
|
||||
/// External resource
|
||||
External,
|
||||
/// Unknown resource type
|
||||
Unset,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum PatternElement {
|
||||
Str(String),
|
||||
@@ -32,12 +47,12 @@ enum PatternType {
|
||||
Dynamic(Regex, Vec<Rc<String>>, usize),
|
||||
}
|
||||
|
||||
impl Pattern {
|
||||
impl ResourceDef {
|
||||
/// 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)
|
||||
ResourceDef::with_prefix(path, false)
|
||||
}
|
||||
|
||||
/// Parse path pattern and create new `Pattern` instance.
|
||||
@@ -46,13 +61,22 @@ impl Pattern {
|
||||
///
|
||||
/// Panics if path regex pattern is wrong.
|
||||
pub fn prefix(path: &str) -> Self {
|
||||
Pattern::with_prefix(path, true)
|
||||
ResourceDef::with_prefix(path, true)
|
||||
}
|
||||
|
||||
/// Construct external resource def
|
||||
///
|
||||
/// Panics if path pattern is malformed.
|
||||
pub fn external(path: &str) -> Self {
|
||||
let mut resource = ResourceDef::with_prefix(path, false);
|
||||
resource.rtp = ResourceType::External;
|
||||
resource
|
||||
}
|
||||
|
||||
/// 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 (pattern, elements, is_dynamic, len) = ResourceDef::parse(&path, for_prefix);
|
||||
|
||||
let tp = if is_dynamic {
|
||||
let re = match Regex::new(&pattern) {
|
||||
@@ -71,9 +95,11 @@ impl Pattern {
|
||||
PatternType::Static(pattern.clone())
|
||||
};
|
||||
|
||||
Pattern {
|
||||
ResourceDef {
|
||||
tp,
|
||||
elements,
|
||||
name: String::new(),
|
||||
rtp: ResourceType::Normal,
|
||||
pattern: path.to_owned(),
|
||||
}
|
||||
}
|
||||
@@ -93,7 +119,7 @@ impl Pattern {
|
||||
}
|
||||
|
||||
/// Is the given path and parameters a match against this pattern?
|
||||
pub fn match_path<T: RequestPath>(&self, path: &mut Path<T>) -> bool {
|
||||
pub fn match_path<T: ResourcePath>(&self, path: &mut Path<T>) -> bool {
|
||||
match self.tp {
|
||||
PatternType::Static(ref s) => {
|
||||
if s == path.path() {
|
||||
@@ -261,20 +287,32 @@ impl Pattern {
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Pattern {
|
||||
fn eq(&self, other: &Pattern) -> bool {
|
||||
impl Eq for ResourceDef {}
|
||||
|
||||
impl PartialEq for ResourceDef {
|
||||
fn eq(&self, other: &ResourceDef) -> bool {
|
||||
self.pattern == other.pattern
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Pattern {}
|
||||
|
||||
impl Hash for Pattern {
|
||||
impl Hash for ResourceDef {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.pattern.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a str> for ResourceDef {
|
||||
fn from(path: &'a str) -> ResourceDef {
|
||||
ResourceDef::new(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for ResourceDef {
|
||||
fn from(path: String) -> ResourceDef {
|
||||
ResourceDef::new(&path)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -282,29 +320,29 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_parse_static() {
|
||||
let re = Pattern::new("/");
|
||||
let re = ResourceDef::new("/");
|
||||
assert!(re.is_match("/"));
|
||||
assert!(!re.is_match("/a"));
|
||||
|
||||
let re = Pattern::new("/name");
|
||||
let re = ResourceDef::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/");
|
||||
let re = ResourceDef::new("/name/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(!re.is_match("/name"));
|
||||
assert!(!re.is_match("/name/gs"));
|
||||
|
||||
let re = Pattern::new("/user/profile");
|
||||
let re = ResourceDef::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}");
|
||||
let re = ResourceDef::new("/user/{id}");
|
||||
assert!(re.is_match("/user/profile"));
|
||||
assert!(re.is_match("/user/2345"));
|
||||
assert!(!re.is_match("/user/2345/"));
|
||||
@@ -318,7 +356,7 @@ mod tests {
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "1245125");
|
||||
|
||||
let re = Pattern::new("/v{version}/resource/{id}");
|
||||
let re = ResourceDef::new("/v{version}/resource/{id}");
|
||||
assert!(re.is_match("/v1/resource/320120"));
|
||||
assert!(!re.is_match("/v/resource/1"));
|
||||
assert!(!re.is_match("/resource"));
|
||||
@@ -328,7 +366,7 @@ mod tests {
|
||||
assert_eq!(path.get("version").unwrap(), "151");
|
||||
assert_eq!(path.get("id").unwrap(), "adahg32");
|
||||
|
||||
let re = Pattern::new("/{id:[[:digit:]]{6}}");
|
||||
let re = ResourceDef::new("/{id:[[:digit:]]{6}}");
|
||||
assert!(re.is_match("/012345"));
|
||||
assert!(!re.is_match("/012"));
|
||||
assert!(!re.is_match("/01234567"));
|
||||
@@ -341,7 +379,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_parse_urlencoded_param() {
|
||||
let re = Pattern::new("/user/{id}/test");
|
||||
let re = ResourceDef::new("/user/{id}/test");
|
||||
|
||||
let mut path = Path::new("/user/2345/test");
|
||||
assert!(re.match_path(&mut path));
|
||||
@@ -359,14 +397,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_resource_prefix() {
|
||||
let re = Pattern::prefix("/name");
|
||||
let re = ResourceDef::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/");
|
||||
let re = ResourceDef::prefix("/name/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(re.is_match("/name/gs"));
|
||||
assert!(!re.is_match("/name"));
|
||||
@@ -374,7 +412,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_reousrce_prefix_dynamic() {
|
||||
let re = Pattern::prefix("/{name}/");
|
||||
let re = ResourceDef::prefix("/{name}/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(re.is_match("/name/gs"));
|
||||
assert!(!re.is_match("/name"));
|
@@ -2,8 +2,8 @@ use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::path::Path;
|
||||
use crate::pattern::Pattern;
|
||||
use crate::RequestPath;
|
||||
use crate::resource::ResourceDef;
|
||||
use crate::ResourcePath;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
pub(crate) enum ResourceId {
|
||||
@@ -20,15 +20,15 @@ pub struct ResourceInfo {
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub(crate) struct ResourceMap {
|
||||
root: Option<Pattern>,
|
||||
named: HashMap<String, Pattern>,
|
||||
patterns: Vec<Pattern>,
|
||||
root: Option<ResourceDef>,
|
||||
named: HashMap<String, ResourceDef>,
|
||||
patterns: Vec<ResourceDef>,
|
||||
}
|
||||
|
||||
/// Resource router.
|
||||
pub struct Router<T> {
|
||||
rmap: Rc<ResourceMap>,
|
||||
named: HashMap<String, Pattern>,
|
||||
named: HashMap<String, ResourceDef>,
|
||||
resources: Vec<T>,
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ impl<T> Router<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn recognize<U: RequestPath>(&self, path: &mut Path<U>) -> Option<(&T, ResourceInfo)> {
|
||||
pub fn recognize<U: ResourcePath>(&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) {
|
||||
@@ -56,7 +56,7 @@ impl<T> Router<T> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn recognize_mut<U: RequestPath>(
|
||||
pub fn recognize_mut<U: ResourcePath>(
|
||||
&mut self,
|
||||
path: &mut Path<U>,
|
||||
) -> Option<(&mut T, ResourceInfo)> {
|
||||
@@ -94,11 +94,11 @@ impl<'a, T> IntoIterator for &'a mut Router<T> {
|
||||
}
|
||||
|
||||
impl ResourceMap {
|
||||
fn register(&mut self, pattern: Pattern) {
|
||||
fn register(&mut self, pattern: ResourceDef) {
|
||||
self.patterns.push(pattern);
|
||||
}
|
||||
|
||||
fn register_named(&mut self, name: String, pattern: Pattern) {
|
||||
fn register_named(&mut self, name: String, pattern: ResourceDef) {
|
||||
self.patterns.push(pattern.clone());
|
||||
self.named.insert(name, pattern);
|
||||
}
|
||||
@@ -110,21 +110,30 @@ impl ResourceMap {
|
||||
|
||||
pub struct RouterBuilder<T> {
|
||||
rmap: ResourceMap,
|
||||
named: HashMap<String, Pattern>,
|
||||
named: HashMap<String, ResourceDef>,
|
||||
resources: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T> RouterBuilder<T> {
|
||||
/// Register resource for specified path.
|
||||
pub fn path(&mut self, path: &str, resource: T) {
|
||||
self.rmap.register(Pattern::new(path));
|
||||
self.rmap.register(ResourceDef::new(path));
|
||||
self.resources.push(resource);
|
||||
}
|
||||
|
||||
/// Register resource for specified path prefix.
|
||||
pub fn prefix(&mut self, prefix: &str, resource: T) {
|
||||
self.rmap.register(Pattern::prefix(prefix));
|
||||
self.rmap.register(ResourceDef::prefix(prefix));
|
||||
self.resources.push(resource);
|
||||
}
|
||||
|
||||
/// Register resource for ResourceDef
|
||||
pub fn rdef(&mut self, rdef: ResourceDef, resource: T) {
|
||||
self.rmap.register(rdef);
|
||||
self.resources.push(resource);
|
||||
}
|
||||
|
||||
/// Finish configuration and create router instance.
|
||||
pub fn finish(self) -> Router<T> {
|
||||
Router {
|
||||
rmap: Rc::new(self.rmap),
|
||||
|
@@ -1,6 +1,6 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::RequestPath;
|
||||
use crate::ResourcePath;
|
||||
|
||||
#[allow(dead_code)]
|
||||
const GEN_DELIMS: &[u8] = b":/?#[]@";
|
||||
@@ -67,7 +67,7 @@ impl Url {
|
||||
}
|
||||
}
|
||||
|
||||
impl RequestPath for Url {
|
||||
impl ResourcePath for Url {
|
||||
fn path(&self) -> &str {
|
||||
self.path()
|
||||
}
|
||||
@@ -190,11 +190,11 @@ mod tests {
|
||||
use http::{HttpTryFrom, Uri};
|
||||
|
||||
use super::*;
|
||||
use crate::{Path, Pattern};
|
||||
use crate::{Path, ResourceDef};
|
||||
|
||||
#[test]
|
||||
fn test_parse_url() {
|
||||
let re = Pattern::new("/user/{id}/test");
|
||||
let re = ResourceDef::new("/user/{id}/test");
|
||||
|
||||
let url = Uri::try_from("/user/2345/test").unwrap();
|
||||
let mut path = Path::new(Url::new(url));
|
||||
|
Reference in New Issue
Block a user