1
0
mirror of https://github.com/fafhrd91/actix-net synced 2025-08-14 14:30:32 +02:00

Compare commits

...

64 Commits

Author SHA1 Message Date
Nikolay Kim
86f57e5a4a prepare actix-service release 2019-03-09 14:10:02 -08:00
Nikolay Kim
43ad18ccb1 remove get_decoded 2019-03-09 13:58:07 -08:00
Nikolay Kim
34995a8ccf revert re-quoting change 2019-03-09 13:56:09 -08:00
Nikolay Kim
0ff300c40f export ApplyConfig 2019-03-09 09:05:51 -08:00
Nikolay Kim
629ef23371 add .apply_cfg new service combinator 2019-03-09 09:02:23 -08:00
Nikolay Kim
d2b96ff877 add ServerConfig to server services 2019-03-09 07:31:22 -08:00
Nikolay Kim
ac62e2dbf9 revert generic request in actix-utils 2019-03-09 07:27:35 -08:00
Nikolay Kim
6bbbdba921 revert generic Request change 2019-03-09 06:36:23 -08:00
Nikolay Kim
2099629fe3 cleanup ssl services 2019-03-08 22:41:30 -08:00
Nikolay Kim
a4d4770462 remove server config 2019-03-08 22:38:39 -08:00
Nikolay Kim
70ead175b9 IntoService for fn_cfg_factory 2019-03-08 20:51:50 -08:00
Nikolay Kim
49867b5e9d fix IntoService 2019-03-08 20:50:29 -08:00
Nikolay Kim
0f064c43e9 remove uneeded code 2019-03-08 20:10:47 -08:00
Nikolay Kim
7db29544f9 add ServerConfig param for server service 2019-03-08 19:43:13 -08:00
Nikolay Kim
4850cf41ff rename module 2019-03-08 16:26:30 -08:00
Nikolay Kim
046142ffbc added is_prefix_match and resource_path 2019-03-08 15:34:40 -08:00
Nikolay Kim
49e6dbcda2 remove unused ResourceMap 2019-03-08 12:33:44 -08:00
Nikolay Kim
877614a494 add params decoding 2019-03-08 04:43:51 -08:00
Nikolay Kim
ac0e8b9e53 re-enable examples 2019-03-06 23:33:35 -08:00
Nikolay Kim
b407c65f4c add FramedParts::with_read_buf method 2019-03-06 22:53:55 -08:00
Nikolay Kim
51bd7d2721 update actix-rt 2019-03-06 10:39:53 -08:00
Nikolay Kim
c03d869694 return io::Result from run method, remove Handle 2019-03-06 10:24:58 -08:00
Nikolay Kim
25f1eae51f add ResourceDef::root_prefix, insert slash to the beggining of the pattern 2019-03-05 21:03:53 -08:00
Nikolay Kim
1153715149 change generics order for Transform trait 2019-03-05 09:49:08 -08:00
Nikolay Kim
aa2967c653 fix feature gated code 2019-03-05 07:41:41 -08:00
Nikolay Kim
dfbb77f98d make service Request type generic 2019-03-05 07:35:26 -08:00
Nikolay Kim
e8a49801eb revert IntoFuture change 2019-03-04 21:37:06 -08:00
Nikolay Kim
03f2046a42 add ApplyTransform new service 2019-03-04 21:25:50 -08:00
Nikolay Kim
2e18ca805c use IntoFuture 2019-03-04 20:40:38 -08:00
Nikolay Kim
15dafeff3d use IntoFuture instead of Future 2019-03-04 20:37:03 -08:00
Nikolay Kim
ed14e6b8ea change to IntoFuture 2019-03-04 20:29:35 -08:00
Nikolay Kim
700abc997e prepare actix-utils release 2019-03-04 19:45:17 -08:00
Nikolay Kim
8c48bf4de7 simplify transform trait 2019-03-04 19:38:11 -08:00
Nikolay Kim
9bc492cf6c add SslError 2019-03-04 16:16:39 -08:00
Nikolay Kim
d2a223e69e update changes 2019-03-04 15:42:25 -08:00
Nikolay Kim
e9657a399a add maxconnrate 2019-03-04 15:41:16 -08:00
Nikolay Kim
9f25fdf929 rename StreamServiceFactory to ServiceFactory 2019-03-04 14:31:46 -08:00
Nikolay Kim
82930de8e7 use default type for RouterBuilder 2019-03-04 14:03:46 -08:00
Nikolay Kim
04a3e59bd5 update tests 2019-03-04 12:41:39 -08:00
Nikolay Kim
0ff0daa795 allow custom checks for resource selection 2019-03-04 11:47:03 -08:00
Nikolay Kim
fb43940824 allow empty pattern 2019-03-03 21:00:58 -08:00
Nikolay Kim
0410f59cf5 prep release 2019-03-02 14:55:22 -08:00
Nikolay Kim
400023a07b prepare actix-connector release 2019-03-02 14:47:52 -08:00
Nikolay Kim
2e4c84dbb6 prepare actix-server release 2019-03-02 14:42:31 -08:00
Nikolay Kim
672c3936a6 prepare actix-utils release 2019-03-02 14:30:32 -08:00
Nikolay Kim
fbf4444b04 prep release 2019-03-02 14:22:03 -08:00
Nikolay Kim
b5b3168b34 do not use void for now 2019-03-02 13:49:21 -08:00
Nikolay Kim
668e4f9ac4 update utils; add NewTransform::map_init_err 2019-03-02 13:18:01 -08:00
Nikolay Kim
d0b8b6940c add configuration parameter to transform factory 2019-03-02 12:16:30 -08:00
Nikolay Kim
f1bc9d0deb update tests 2019-02-22 18:47:29 -08:00
Nikolay Kim
6ed020565c update service crate 2019-02-22 18:31:25 -08:00
Nikolay Kim
7ee33efdfd moved boxed service and new service to actix-service 2019-02-22 18:20:54 -08:00
Nikolay Kim
83f51b28d7 allow to customize cfg parameter for FnNewService 2019-02-22 17:12:26 -08:00
Nikolay Kim
83a19e9cb3 add IntoConfigurableNewService 2019-02-22 14:30:00 -08:00
Nikolay Kim
6b4010892d add IntoNewService for FnNewService 2019-02-22 14:19:43 -08:00
Nikolay Kim
d2bd9134aa add fn service helpers 2019-02-22 14:13:48 -08:00
Nikolay Kim
a0e2d926e6 add fn_nservice 2019-02-22 13:20:52 -08:00
Nikolay Kim
43d2dd473f update tests 2019-02-22 13:08:31 -08:00
Nikolay Kim
862be49e30 add Config argument to NewService 2019-02-22 12:44:37 -08:00
Nikolay Kim
6ea128fac5 Custom BoxedNewService implementation 2019-02-21 11:19:28 -08:00
Nikolay Kim
a97d7f0ccf add BoxedNewService and BoxedService 2019-02-21 10:41:39 -08:00
Nikolay Kim
3d7daabdd7 add NewService impls for Rc<S> and Arc<S> 2019-02-19 11:31:54 -08:00
Nikolay Kim
32f4718880 Add Display impl for InOrderError 2019-02-11 08:39:28 -08:00
Nikolay Kim
b8f9bf4bc8 Add Display impl for TimeoutError 2019-02-11 08:34:57 -08:00
65 changed files with 2054 additions and 1646 deletions

View File

@@ -1,3 +1,18 @@
[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"
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] [workspace]
members = [ members = [
"actix-codec", "actix-codec",
@@ -5,7 +20,19 @@ members = [
"actix-rt", "actix-rt",
"actix-service", "actix-service",
"actix-server", "actix-server",
"actix-server-config",
"actix-test-server", "actix-test-server",
"actix-utils", "actix-utils",
"router", "router",
] ]
[dev-dependencies]
actix-service = { path="actix-service" }
actix-codec = "0.1.1"
actix-rt = "0.2.0"
actix-server = { path="actix-server", features=["ssl"] }
env_logger = "0.6"
futures = "0.1.25"
openssl = "0.10"
tokio-tcp = "0.1"
tokio-openssl = "0.3"

View File

@@ -1,5 +1,10 @@
# Changes # Changes
## [0.1.0] - 2019-03-06
* Added `FramedParts::with_read_buffer()` method.
## [0.1.0] - 2018-12-09 ## [0.1.0] - 2018-12-09
* Move codec to separate crate * Move codec to separate crate

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-codec" name = "actix-codec"
version = "0.1.0" version = "0.1.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Utilities for encoding and decoding frames" description = "Utilities for encoding and decoding frames"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]

View File

@@ -349,4 +349,17 @@ impl<T, U> FramedParts<T, U> {
_priv: (), _priv: (),
} }
} }
/// Create a new `FramedParts` with read buffer
pub fn with_read_buf(io: T, codec: U, read_buf: BytesMut) -> FramedParts<T, U> {
FramedParts {
io,
codec,
read_buf,
write_buf: BytesMut::new(),
write_buf_lw: LW,
write_buf_hw: HW,
_priv: (),
}
}
} }

View File

@@ -1,8 +1,15 @@
# Changes # Changes
## [0.3.0] - 2019-03-02
### Changed
* Migrate to actix-service 0.3
## [0.2.0] - 2019-02-01 ## [0.2.0] - 2019-02-01
### Changes ### Changed
* Migrate to actix-service 0.2 * Migrate to actix-service 0.2

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-connector" name = "actix-connector"
version = "0.2.0" version = "0.3.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix Connector - tcp connector service" description = "Actix Connector - tcp connector service"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -11,7 +11,7 @@ categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"] exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018" edition = "2018"
workspace = "../" workspace = ".."
[package.metadata.docs.rs] [package.metadata.docs.rs]
features = ["ssl"] features = ["ssl"]
@@ -27,7 +27,8 @@ default = []
ssl = ["openssl", "tokio-openssl"] ssl = ["openssl", "tokio-openssl"]
[dependencies] [dependencies]
actix-service = "0.2.0" #actix-service = "0.3.0"
actix-service = { path="../actix-service" }
actix-codec = "0.1.0" actix-codec = "0.1.0"
futures = "0.1" futures = "0.1"
tokio-tcp = "0.1" tokio-tcp = "0.1"

View File

@@ -4,8 +4,8 @@ use std::net::{IpAddr, SocketAddr};
use std::time::Duration; use std::time::Duration;
use std::{fmt, io}; use std::{fmt, io};
use actix_service::{NewService, Service}; use actix_service::{fn_factory, NewService, Service};
use futures::future::{ok, Either, FutureResult}; use futures::future::{ok, Either};
use futures::{try_ready, Async, Future, Poll}; use futures::{try_ready, Async, Future, Poll};
use tokio_tcp::{ConnectFuture, TcpStream}; use tokio_tcp::{ConnectFuture, TcpStream};
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts}; use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
@@ -177,12 +177,13 @@ impl Connector {
cfg: ResolverConfig, cfg: ResolverConfig,
opts: ResolverOpts, opts: ResolverOpts,
) -> impl NewService< ) -> impl NewService<
(),
Request = Connect, Request = Connect,
Response = (Connect, TcpStream), Response = (Connect, TcpStream),
Error = ConnectorError, Error = ConnectorError,
InitError = E, InitError = E,
> + Clone { > + Clone {
move || -> FutureResult<Connector, E> { ok(Connector::new(cfg.clone(), opts)) } fn_factory(move || ok(Connector::new(cfg.clone(), opts)))
} }
} }

View File

@@ -44,7 +44,9 @@ impl<R, T, E> Clone for OpensslConnector<R, T, E> {
} }
} }
impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService for OpensslConnector<R, T, E> { impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService<()>
for OpensslConnector<R, T, E>
{
type Request = (R, T); type Request = (R, T);
type Response = (R, SslStream<T>); type Response = (R, SslStream<T>);
type Error = HandshakeError<T>; type Error = HandshakeError<T>;
@@ -52,7 +54,7 @@ impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService for OpensslConnect
type InitError = E; type InitError = E;
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
ok(OpensslConnectorService { ok(OpensslConnectorService {
connector: self.connector.clone(), connector: self.connector.clone(),
_t: PhantomData, _t: PhantomData,

View File

@@ -1,5 +1,11 @@
# Changes # Changes
## [0.2.0] - 2019-03-06
* `run` method returns `io::Result<()>`
* Removed `Handle`
## [0.1.0] - 2018-12-09 ## [0.1.0] - 2018-12-09
* Initial release * Initial release

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-rt" name = "actix-rt"
version = "0.1.0" version = "0.2.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix runtime" description = "Actix runtime"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -20,7 +20,7 @@ path = "src/lib.rs"
[dependencies] [dependencies]
log = "0.4" log = "0.4"
bytes = "0.4" bytes = "0.4"
futures = "0.1.24" futures = "0.1.25"
tokio-current-thread = "0.1" tokio-current-thread = "0.1"
tokio-executor = "0.1.5" tokio-executor = "0.1.5"
tokio-reactor = "0.1.7" tokio-reactor = "0.1.7"

View File

@@ -72,7 +72,7 @@ impl Builder {
/// This function will start tokio runtime and will finish once the /// This function will start tokio runtime and will finish once the
/// `System::stop()` message get called. /// `System::stop()` message get called.
/// Function `f` get called within tokio runtime context. /// Function `f` get called within tokio runtime context.
pub fn run<F>(self, f: F) -> i32 pub fn run<F>(self, f: F) -> io::Result<()>
where where
F: FnOnce() + 'static, F: FnOnce() + 'static,
{ {
@@ -140,7 +140,7 @@ pub struct SystemRunner {
impl SystemRunner { impl SystemRunner {
/// This function will start event loop and will finish once the /// This function will start event loop and will finish once the
/// `System::stop()` function is called. /// `System::stop()` function is called.
pub fn run(self) -> i32 { pub fn run(self) -> io::Result<()> {
let SystemRunner { mut rt, stop, .. } = self; let SystemRunner { mut rt, stop, .. } = self;
// run loop // run loop
@@ -148,12 +148,21 @@ impl SystemRunner {
Arbiter::run_system(); Arbiter::run_system();
Ok::<_, ()>(()) Ok::<_, ()>(())
})); }));
let code = match rt.block_on(stop) { let result = match rt.block_on(stop) {
Ok(code) => code, Ok(code) => {
Err(_) => 1, if code != 0 {
Err(io::Error::new(
io::ErrorKind::Other,
format!("Non-zero exit code: {}", code),
))
} else {
Ok(())
}
}
Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)),
}; };
Arbiter::stop_system(); Arbiter::stop_system();
code result
} }
/// Execute a future and wait for result. /// Execute a future and wait for result.

View File

@@ -7,7 +7,7 @@ mod system;
pub use self::arbiter::Arbiter; pub use self::arbiter::Arbiter;
pub use self::builder::{Builder, SystemRunner}; pub use self::builder::{Builder, SystemRunner};
pub use self::runtime::{Handle, Runtime}; pub use self::runtime::Runtime;
pub use self::system::System; pub use self::system::System;
/// Spawns a future on the current arbiter. /// Spawns a future on the current arbiter.

View File

@@ -1,9 +1,7 @@
use std::error::Error; use std::error::Error;
use std::fmt; use std::{fmt, io};
use std::io;
use futures::{future, Future}; use futures::Future;
use tokio_current_thread::Handle as ExecutorHandle;
use tokio_current_thread::{self as current_thread, CurrentThread}; use tokio_current_thread::{self as current_thread, CurrentThread};
use tokio_executor; use tokio_executor;
use tokio_reactor::{self, Reactor}; use tokio_reactor::{self, Reactor};
@@ -26,58 +24,6 @@ pub struct Runtime {
executor: CurrentThread<Timer<Reactor>>, executor: CurrentThread<Timer<Reactor>>,
} }
/// Handle to spawn a future on the corresponding `CurrentThread` runtime instance
#[derive(Debug, Clone)]
pub struct Handle(ExecutorHandle);
impl Handle {
/// Spawn a future onto the `CurrentThread` runtime instance corresponding to this handle
///
/// # Panics
///
/// This function panics if the spawn fails. Failure occurs if the `CurrentThread`
/// instance of the `Handle` does not exist anymore.
pub fn spawn<F>(&self, future: F) -> Result<(), tokio_executor::SpawnError>
where
F: Future<Item = (), Error = ()> + Send + 'static,
{
self.0.spawn(future)
}
/// Provides a best effort **hint** to whether or not `spawn` will succeed.
///
/// This function may return both false positives **and** false negatives.
/// If `status` returns `Ok`, then a call to `spawn` will *probably*
/// succeed, but may fail. If `status` returns `Err`, a call to `spawn` will
/// *probably* fail, but may succeed.
///
/// This allows a caller to avoid creating the task if the call to `spawn`
/// has a high likelihood of failing.
pub fn status(&self) -> Result<(), tokio_executor::SpawnError> {
self.0.status()
}
}
impl<T> future::Executor<T> for Handle
where
T: Future<Item = (), Error = ()> + Send + 'static,
{
fn execute(&self, future: T) -> Result<(), future::ExecuteError<T>> {
if let Err(e) = self.status() {
let kind = if e.is_at_capacity() {
future::ExecuteErrorKind::NoCapacity
} else {
future::ExecuteErrorKind::Shutdown
};
return Err(future::ExecuteError::new(kind, future));
}
let _ = self.spawn(future);
Ok(())
}
}
/// Error returned by the `run` function. /// Error returned by the `run` function.
#[derive(Debug)] #[derive(Debug)]
pub struct RunError { pub struct RunError {
@@ -120,14 +66,6 @@ impl Runtime {
} }
} }
/// Get a new handle to spawn futures on the single-threaded Tokio runtime
///
/// Different to the runtime itself, the handle can be sent to different
/// threads.
pub fn handle(&self) -> Handle {
Handle(self.executor.handle().clone())
}
/// Spawn a future onto the single-threaded Tokio runtime. /// Spawn a future onto the single-threaded Tokio runtime.
/// ///
/// See [module level][mod] documentation for more details. /// See [module level][mod] documentation for more details.

View File

@@ -1,4 +1,5 @@
use std::cell::RefCell; use std::cell::RefCell;
use std::io;
use futures::sync::mpsc::UnboundedSender; use futures::sync::mpsc::UnboundedSender;
@@ -109,7 +110,7 @@ impl System {
/// This function will start tokio runtime and will finish once the /// This function will start tokio runtime and will finish once the
/// `System::stop()` message get called. /// `System::stop()` message get called.
/// Function `f` get called within tokio runtime context. /// Function `f` get called within tokio runtime context.
pub fn run<F>(f: F) -> i32 pub fn run<F>(f: F) -> io::Result<()>
where where
F: FnOnce() + 'static, F: FnOnce() + 'static,
{ {

View File

@@ -0,0 +1,18 @@
[package]
name = "actix-server-config"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix server config utils"
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
license = "MIT/Apache-2.0"
edition = "2018"
workspace = ".."
[lib]
name = "actix_server_config"
path = "src/lib.rs"
[dependencies]
actix-service = { path="../actix-service" }
futures = "0.1.25"

View File

@@ -0,0 +1,33 @@
use std::cell::Cell;
use std::net::SocketAddr;
use std::rc::Rc;
#[derive(Debug, Clone)]
pub struct ServerConfig {
addr: SocketAddr,
secure: Rc<Cell<bool>>,
}
impl ServerConfig {
pub fn new(addr: SocketAddr) -> Self {
ServerConfig {
addr,
secure: Rc::new(Cell::new(false)),
}
}
/// Returns the address of the local half of this TCP server socket
pub fn local_addr(&self) -> SocketAddr {
self.addr
}
/// Returns true if connection is secure (tls enabled)
pub fn secure(&self) -> bool {
self.secure.as_ref().get()
}
/// Set secure flag
pub fn set_secure(&self) {
self.secure.as_ref().set(true)
}
}

View File

@@ -1,15 +1,43 @@
# Changes # Changes
## [0.4.0] - 2019-03-xx
* Upgrade actix-service
## [0.3.1] - 2019-03-04
### Added
* Add `ServerBuilder::maxconnrate` sets the maximum per-worker number of concurrent connections
* Add helper ssl error `SslError`
### Changed
* Rename `StreamServiceFactory` to `ServiceFactory`
* Deprecate `StreamServiceFactory`
## [0.3.0] - 2019-03-02
### Changed
* Use new `NewService` trait
## [0.2.1] - 2019-02-09 ## [0.2.1] - 2019-02-09
### Changes ### Changed
* Drop service response * Drop service response
## [0.2.0] - 2019-02-01 ## [0.2.0] - 2019-02-01
### Changes ### Changed
* Migrate to actix-service 0.2 * Migrate to actix-service 0.2

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-server" name = "actix-server"
version = "0.2.1" version = "0.3.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix server - General purpose tcp server" description = "Actix server - General purpose tcp server"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -11,7 +11,7 @@ categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"] exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018" edition = "2018"
workspace = "../" workspace = ".."
[package.metadata.docs.rs] [package.metadata.docs.rs]
features = ["ssl", "tls", "rust-tls"] features = ["ssl", "tls", "rust-tls"]
@@ -33,16 +33,16 @@ ssl = ["openssl", "tokio-openssl"]
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"] rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
[dependencies] [dependencies]
actix-service = "0.2.1" actix-rt = "0.2.0"
actix-rt = "0.1.0" #actix-service = "0.3.2"
actix-service = { path="../actix-service" }
actix-server-config = { path="../actix-server-config" }
log = "0.4" log = "0.4"
num_cpus = "1.0" num_cpus = "1.0"
# io
mio = "^0.6.13" mio = "^0.6.13"
net2 = "0.2" net2 = "0.2"
bytes = "0.4"
futures = "0.1" futures = "0.1"
slab = "0.4" slab = "0.4"
tokio-io = "0.1" tokio-io = "0.1"

View File

@@ -12,13 +12,12 @@ use num_cpus;
use tokio_timer::sleep; use tokio_timer::sleep;
use crate::accept::{AcceptLoop, AcceptNotify, Command}; use crate::accept::{AcceptLoop, AcceptNotify, Command};
use crate::config::{ConfiguredService, ServiceConfig};
use crate::server::{Server, ServerCommand}; use crate::server::{Server, ServerCommand};
use crate::services::{InternalServiceFactory, StreamNewService, StreamServiceFactory}; use crate::service_config::{ConfiguredService, ServiceConfig};
use crate::services::{ServiceFactory, ServiceNewService}; use crate::services::{InternalServiceFactory, ServiceFactory, StreamNewService};
use crate::signals::{Signal, Signals}; use crate::signals::{Signal, Signals};
use crate::worker::{self, Worker, WorkerAvailability, WorkerClient}; use crate::worker::{self, Worker, WorkerAvailability, WorkerClient};
use crate::Token; use crate::{ssl, Token};
/// Server builder /// Server builder
pub struct ServerBuilder { pub struct ServerBuilder {
@@ -82,9 +81,18 @@ impl ServerBuilder {
self self
} }
/// Stop actix system. /// Sets the maximum per-worker concurrent connection establish process.
/// ///
/// `SystemExit` message stops currently running system. /// All listeners will stop accepting connections when this limit is reached. It
/// can be used to limit the global SSL CPU usage.
///
/// By default max connections is set to a 256.
pub fn maxconnrate(self, num: usize) -> Self {
ssl::max_concurrent_ssl_connect(num);
self
}
/// Stop actix system.
pub fn system_exit(mut self) -> Self { pub fn system_exit(mut self) -> Self {
self.exit = true; self.exit = true;
self self
@@ -138,19 +146,19 @@ impl ServerBuilder {
/// Add new service to the server. /// Add new service to the server.
pub fn bind<F, U, N: AsRef<str>>(mut self, name: N, addr: U, factory: F) -> io::Result<Self> pub fn bind<F, U, N: AsRef<str>>(mut self, name: N, addr: U, factory: F) -> io::Result<Self>
where where
F: StreamServiceFactory, F: ServiceFactory,
U: net::ToSocketAddrs, U: net::ToSocketAddrs,
{ {
let sockets = bind_addr(addr)?; let sockets = bind_addr(addr)?;
let token = self.token.next();
self.services.push(StreamNewService::create(
name.as_ref().to_string(),
token,
factory,
));
for lst in sockets { for lst in sockets {
let token = self.token.next();
self.services.push(StreamNewService::create(
name.as_ref().to_string(),
token,
factory.clone(),
lst.local_addr()?,
));
self.sockets.push((token, lst)); self.sockets.push((token, lst));
} }
Ok(self) Ok(self)
@@ -162,38 +170,19 @@ impl ServerBuilder {
name: N, name: N,
lst: net::TcpListener, lst: net::TcpListener,
factory: F, factory: F,
) -> Self ) -> io::Result<Self>
where where
F: StreamServiceFactory, F: ServiceFactory,
{ {
let token = self.token.next(); let token = self.token.next();
self.services.push(StreamNewService::create( self.services.push(StreamNewService::create(
name.as_ref().to_string(), name.as_ref().to_string(),
token, token,
factory, factory,
lst.local_addr()?,
)); ));
self.sockets.push((token, lst)); self.sockets.push((token, lst));
self Ok(self)
}
/// Add new service to the server.
pub fn listen2<F, N: AsRef<str>>(
mut self,
name: N,
lst: net::TcpListener,
factory: F,
) -> Self
where
F: ServiceFactory,
{
let token = self.token.next();
self.services.push(ServiceNewService::create(
name.as_ref().to_string(),
token,
factory,
));
self.sockets.push((token, lst));
self
} }
/// Spawn new thread and start listening for incoming connections. /// Spawn new thread and start listening for incoming connections.
@@ -204,24 +193,20 @@ impl ServerBuilder {
/// This methods panics if no socket addresses get bound. /// This methods panics if no socket addresses get bound.
/// ///
/// ```rust,ignore /// ```rust,ignore
/// # extern crate futures;
/// # extern crate actix_web;
/// # use futures::Future;
/// use actix_web::*; /// use actix_web::*;
/// ///
/// fn main() { /// fn main() -> std::io::Result<()> {
/// Server::new(). /// Server::new().
/// .service( /// .service(
/// HttpServer::new(|| App::new().resource("/", |r| r.h(|_| HttpResponse::Ok()))) /// HttpServer::new(|| App::new().service(web::service("/").to(|| HttpResponse::Ok())))
/// .bind("127.0.0.1:0") /// .bind("127.0.0.1:0")
/// .expect("Can not bind to 127.0.0.1:0")) /// .run()
/// .run();
/// } /// }
/// ``` /// ```
pub fn run(self) { pub fn run(self) -> io::Result<()> {
let sys = System::new("http-server"); let sys = System::new("http-server");
self.start(); self.start();
sys.run(); sys.run()
} }
/// Starts processing incoming connections and return server controller. /// Starts processing incoming connections and return server controller.

View File

@@ -2,18 +2,23 @@
mod accept; mod accept;
mod builder; mod builder;
mod config;
mod counter; mod counter;
mod server; mod server;
mod service_config;
mod services; mod services;
mod signals; mod signals;
pub mod ssl; pub mod ssl;
mod worker; mod worker;
pub use actix_server_config::ServerConfig;
pub use self::builder::ServerBuilder; pub use self::builder::ServerBuilder;
pub use self::config::{ServiceConfig, ServiceRuntime};
pub use self::server::Server; pub use self::server::Server;
pub use self::services::{ServerMessage, ServiceFactory, StreamServiceFactory}; pub use self::service_config::{ServiceConfig, ServiceRuntime};
pub use self::services::ServiceFactory;
#[doc(hidden)]
pub use self::services::ServiceFactory as StreamServiceFactory;
/// Socket id token /// Socket id token
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
@@ -28,6 +33,6 @@ impl Token {
} }
/// Start server building process /// Start server building process
pub fn build() -> ServerBuilder { pub fn new() -> ServerBuilder {
ServerBuilder::default() ServerBuilder::default()
} }

View File

@@ -114,7 +114,7 @@ impl InternalServiceFactory for ConfiguredService {
// construct services // construct services
let mut fut = Vec::new(); let mut fut = Vec::new();
for (token, ns) in rt.services { for (token, ns) in rt.services {
fut.push(ns.new_service().map(move |service| (token, service))); fut.push(ns.new_service(&()).map(move |service| (token, service)));
} }
Box::new(join_all(fut).map_err(|e| { Box::new(join_all(fut).map_err(|e| {
@@ -219,8 +219,8 @@ where
type Service = BoxedServerService; type Service = BoxedServerService;
type Future = Box<Future<Item = BoxedServerService, Error = ()>>; type Future = Box<Future<Item = BoxedServerService, Error = ()>>;
fn new_service(&self) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
Box::new(self.inner.new_service().map_err(|_| ()).map(|s| { Box::new(self.inner.new_service(&()).map_err(|_| ()).map(|s| {
let service: BoxedServerService = Box::new(StreamService::new(s)); let service: BoxedServerService = Box::new(StreamService::new(s));
service service
})) }))

View File

@@ -1,35 +1,30 @@
use std::net; use std::net::{SocketAddr, TcpStream};
use std::time::Duration; use std::time::Duration;
use actix_rt::spawn; use actix_rt::spawn;
use actix_server_config::ServerConfig;
use actix_service::{NewService, Service}; use actix_service::{NewService, Service};
use futures::future::{err, ok, FutureResult}; use futures::future::{err, ok, FutureResult};
use futures::{Future, Poll}; use futures::{Future, Poll};
use log::error; use log::error;
use tokio_reactor::Handle; use tokio_reactor::Handle;
use tokio_tcp::TcpStream; use tokio_tcp::TcpStream as TokioTcpStream;
use super::Token; use super::Token;
use crate::counter::CounterGuard; use crate::counter::CounterGuard;
/// Server message /// Server message
pub enum ServerMessage { pub(crate) enum ServerMessage {
/// New stream /// New stream
Connect(net::TcpStream), Connect(TcpStream),
/// Gracefull shutdown /// Gracefull shutdown
Shutdown(Duration), Shutdown(Duration),
/// Force shutdown /// Force shutdown
ForceShutdown, ForceShutdown,
} }
pub trait StreamServiceFactory: Send + Clone + 'static {
type NewService: NewService<Request = TcpStream>;
fn create(&self) -> Self::NewService;
}
pub trait ServiceFactory: Send + Clone + 'static { pub trait ServiceFactory: Send + Clone + 'static {
type NewService: NewService<Request = ServerMessage>; type NewService: NewService<ServerConfig, Request = TokioTcpStream>;
fn create(&self) -> Self::NewService; fn create(&self) -> Self::NewService;
} }
@@ -63,7 +58,7 @@ impl<T> StreamService<T> {
impl<T> Service for StreamService<T> impl<T> Service for StreamService<T>
where where
T: Service<Request = TcpStream>, T: Service<Request = TokioTcpStream>,
T::Future: 'static, T::Future: 'static,
T::Error: 'static, T::Error: 'static,
{ {
@@ -79,9 +74,10 @@ where
fn call(&mut self, (guard, req): (Option<CounterGuard>, ServerMessage)) -> Self::Future { fn call(&mut self, (guard, req): (Option<CounterGuard>, ServerMessage)) -> Self::Future {
match req { match req {
ServerMessage::Connect(stream) => { ServerMessage::Connect(stream) => {
let stream = TcpStream::from_std(stream, &Handle::default()).map_err(|e| { let stream =
error!("Can not convert to an async tcp stream: {}", e); TokioTcpStream::from_std(stream, &Handle::default()).map_err(|e| {
}); error!("Can not convert to an async tcp stream: {}", e);
});
if let Ok(stream) = stream { if let Ok(stream) = stream {
spawn(self.service.call(stream).then(move |res| { spawn(self.service.call(stream).then(move |res| {
@@ -98,104 +94,35 @@ where
} }
} }
pub(crate) struct ServerService<T> { pub(crate) struct StreamNewService<F: ServiceFactory> {
service: T,
}
impl<T> ServerService<T> {
fn new(service: T) -> Self {
ServerService { service }
}
}
impl<T> Service for ServerService<T>
where
T: Service<Request = ServerMessage>,
T::Future: 'static,
T::Error: 'static,
{
type Request = (Option<CounterGuard>, ServerMessage);
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready().map_err(|_| ())
}
fn call(&mut self, (guard, req): (Option<CounterGuard>, ServerMessage)) -> Self::Future {
spawn(self.service.call(req).then(move |res| {
drop(guard);
res.map_err(|_| ()).map(|_| ())
}));
ok(())
}
}
pub(crate) struct ServiceNewService<F: ServiceFactory> {
name: String,
inner: F,
token: Token,
}
impl<F> ServiceNewService<F>
where
F: ServiceFactory,
{
pub(crate) fn create(name: String, token: Token, inner: F) -> Box<InternalServiceFactory> {
Box::new(Self { name, inner, token })
}
}
impl<F> InternalServiceFactory for ServiceNewService<F>
where
F: ServiceFactory,
{
fn name(&self, _: Token) -> &str {
&self.name
}
fn clone_factory(&self) -> Box<InternalServiceFactory> {
Box::new(Self {
name: self.name.clone(),
inner: self.inner.clone(),
token: self.token,
})
}
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
let token = self.token;
Box::new(
self.inner
.create()
.new_service()
.map_err(|_| ())
.map(move |inner| {
let service: BoxedServerService = Box::new(ServerService::new(inner));
vec![(token, service)]
}),
)
}
}
pub(crate) struct StreamNewService<F: StreamServiceFactory> {
name: String, name: String,
inner: F, inner: F,
token: Token, token: Token,
addr: SocketAddr,
} }
impl<F> StreamNewService<F> impl<F> StreamNewService<F>
where where
F: StreamServiceFactory, F: ServiceFactory,
{ {
pub(crate) fn create(name: String, token: Token, inner: F) -> Box<InternalServiceFactory> { pub(crate) fn create(
Box::new(Self { name, token, inner }) name: String,
token: Token,
inner: F,
addr: SocketAddr,
) -> Box<InternalServiceFactory> {
Box::new(Self {
name,
token,
inner,
addr,
})
} }
} }
impl<F> InternalServiceFactory for StreamNewService<F> impl<F> InternalServiceFactory for StreamNewService<F>
where where
F: StreamServiceFactory, F: ServiceFactory,
{ {
fn name(&self, _: Token) -> &str { fn name(&self, _: Token) -> &str {
&self.name &self.name
@@ -206,15 +133,17 @@ where
name: self.name.clone(), name: self.name.clone(),
inner: self.inner.clone(), inner: self.inner.clone(),
token: self.token, token: self.token,
addr: self.addr,
}) })
} }
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> { fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
let token = self.token; let token = self.token;
let config = ServerConfig::new(self.addr);
Box::new( Box::new(
self.inner self.inner
.create() .create()
.new_service() .new_service(&config)
.map_err(|_| ()) .map_err(|_| ())
.map(move |inner| { .map(move |inner| {
let service: BoxedServerService = Box::new(StreamService::new(inner)); let service: BoxedServerService = Box::new(StreamService::new(inner));
@@ -241,19 +170,7 @@ impl InternalServiceFactory for Box<InternalServiceFactory> {
impl<F, T> ServiceFactory for F impl<F, T> ServiceFactory for F
where where
F: Fn() -> T + Send + Clone + 'static, F: Fn() -> T + Send + Clone + 'static,
T: NewService<Request = ServerMessage>, T: NewService<ServerConfig, Request = TokioTcpStream>,
{
type NewService = T;
fn create(&self) -> T {
(self)()
}
}
impl<F, T> StreamServiceFactory for F
where
F: Fn() -> T + Send + Clone + 'static,
T: NewService<Request = TcpStream>,
{ {
type NewService = T; type NewService = T;

View File

@@ -33,3 +33,9 @@ pub(crate) static MAX_CONN: AtomicUsize = AtomicUsize::new(256);
thread_local! { thread_local! {
static MAX_CONN_COUNTER: Counter = Counter::new(MAX_CONN.load(Ordering::Relaxed)); static MAX_CONN_COUNTER: Counter = Counter::new(MAX_CONN.load(Ordering::Relaxed));
} }
/// Ssl error combinded with service error.
pub enum SslError<E1, E2> {
Ssl(E1),
Service(E2),
}

View File

@@ -1,13 +1,14 @@
use std::io; use std::io;
use std::marker::PhantomData; use std::marker::PhantomData;
use actix_server_config::ServerConfig;
use actix_service::{NewService, Service}; use actix_service::{NewService, Service};
use futures::{future::ok, future::FutureResult, Async, Future, Poll}; use futures::{future::ok, future::FutureResult, Async, Future, Poll};
use native_tls::{self, Error, HandshakeError, TlsAcceptor}; use native_tls::{self, Error, HandshakeError, TlsAcceptor};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use super::MAX_CONN_COUNTER;
use crate::counter::{Counter, CounterGuard}; use crate::counter::{Counter, CounterGuard};
use crate::ssl::MAX_CONN_COUNTER;
/// Support `SSL` connections via native-tls package /// Support `SSL` connections via native-tls package
/// ///
@@ -36,7 +37,7 @@ impl<T: AsyncRead + AsyncWrite> Clone for NativeTlsAcceptor<T> {
} }
} }
impl<T: AsyncRead + AsyncWrite> NewService for NativeTlsAcceptor<T> { impl<T: AsyncRead + AsyncWrite> NewService<ServerConfig> for NativeTlsAcceptor<T> {
type Request = T; type Request = T;
type Response = TlsStream<T>; type Response = TlsStream<T>;
type Error = Error; type Error = Error;
@@ -44,7 +45,9 @@ impl<T: AsyncRead + AsyncWrite> NewService for NativeTlsAcceptor<T> {
type InitError = (); type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
cfg.set_secure();
MAX_CONN_COUNTER.with(|conns| { MAX_CONN_COUNTER.with(|conns| {
ok(NativeTlsAcceptorService { ok(NativeTlsAcceptorService {
acceptor: self.acceptor.clone(), acceptor: self.acceptor.clone(),

View File

@@ -6,8 +6,9 @@ use openssl::ssl::{HandshakeError, SslAcceptor};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use tokio_openssl::{AcceptAsync, SslAcceptorExt, SslStream}; use tokio_openssl::{AcceptAsync, SslAcceptorExt, SslStream};
use super::MAX_CONN_COUNTER;
use crate::counter::{Counter, CounterGuard}; use crate::counter::{Counter, CounterGuard};
use crate::ssl::MAX_CONN_COUNTER;
use crate::ServerConfig;
/// Support `SSL` connections via openssl package /// Support `SSL` connections via openssl package
/// ///
@@ -36,7 +37,7 @@ impl<T: AsyncRead + AsyncWrite> Clone for OpensslAcceptor<T> {
} }
} }
impl<T: AsyncRead + AsyncWrite> NewService for OpensslAcceptor<T> { impl<T: AsyncRead + AsyncWrite> NewService<ServerConfig> for OpensslAcceptor<T> {
type Request = T; type Request = T;
type Response = SslStream<T>; type Response = SslStream<T>;
type Error = HandshakeError<T>; type Error = HandshakeError<T>;
@@ -44,7 +45,9 @@ impl<T: AsyncRead + AsyncWrite> NewService for OpensslAcceptor<T> {
type InitError = (); type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
cfg.set_secure();
MAX_CONN_COUNTER.with(|conns| { MAX_CONN_COUNTER.with(|conns| {
ok(OpensslAcceptorService { ok(OpensslAcceptorService {
acceptor: self.acceptor.clone(), acceptor: self.acceptor.clone(),

View File

@@ -8,8 +8,9 @@ use rustls::{ServerConfig, ServerSession};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
use tokio_rustls::{Accept, TlsAcceptor, TlsStream}; use tokio_rustls::{Accept, TlsAcceptor, TlsStream};
use super::MAX_CONN_COUNTER;
use crate::counter::{Counter, CounterGuard}; use crate::counter::{Counter, CounterGuard};
use crate::ssl::MAX_CONN_COUNTER;
use crate::ServerConfig as SrvConfig;
/// Support `SSL` connections via rustls package /// Support `SSL` connections via rustls package
/// ///
@@ -38,7 +39,7 @@ impl<T> Clone for RustlsAcceptor<T> {
} }
} }
impl<T: AsyncRead + AsyncWrite> NewService for RustlsAcceptor<T> { impl<T: AsyncRead + AsyncWrite> NewService<SrvConfig> for RustlsAcceptor<T> {
type Request = T; type Request = T;
type Response = TlsStream<T, ServerSession>; type Response = TlsStream<T, ServerSession>;
type Error = io::Error; type Error = io::Error;
@@ -46,7 +47,9 @@ impl<T: AsyncRead + AsyncWrite> NewService for RustlsAcceptor<T> {
type InitError = (); type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
cfg.set_secure();
MAX_CONN_COUNTER.with(|conns| { MAX_CONN_COUNTER.with(|conns| {
ok(RustlsAcceptorService { ok(RustlsAcceptorService {
acceptor: self.config.clone().into(), acceptor: self.config.clone().into(),

View File

@@ -0,0 +1,70 @@
use std::{net, thread, time};
use actix_server::{Server, ServerConfig};
use actix_service::{fn_cfg_factory, fn_service, IntoService};
use net2::TcpBuilder;
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()
}
#[test]
fn test_bind() {
let addr = unused_addr();
thread::spawn(move || {
Server::build()
.bind("test", addr, move || {
fn_cfg_factory(move |cfg: &ServerConfig| {
assert_eq!(cfg.local_addr(), addr);
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
})
})
.unwrap()
.run()
});
thread::sleep(time::Duration::from_millis(500));
assert!(net::TcpStream::connect(addr).is_ok());
}
#[test]
fn test_bind_no_config() {
let addr = unused_addr();
thread::spawn(move || {
Server::build()
.bind("test", addr, move || fn_service(|_| Ok::<_, ()>(())))
.unwrap()
.run()
});
thread::sleep(time::Duration::from_millis(500));
assert!(net::TcpStream::connect(addr).is_ok());
}
#[test]
fn test_listen() {
let addr = unused_addr();
thread::spawn(move || {
let lst = net::TcpListener::bind(addr).unwrap();
Server::build()
.listen("test", lst, move || {
fn_cfg_factory(move |cfg: &ServerConfig| {
assert_eq!(cfg.local_addr(), addr);
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
})
})
.unwrap()
.run()
});
thread::sleep(time::Duration::from_millis(500));
assert!(net::TcpStream::connect(addr).is_ok());
}

View File

@@ -1,5 +1,57 @@
# Changes # Changes
## [0.3.3] - 2019-03-09
### Added
* Add `ApplyTransform` new service for transform and new service.
* Add `NewService::apply_cfg()` combinator, allows to use
nested `NewService` with different config parameter.
### Changed
* Revert IntoFuture change
## [0.3.2] - 2019-03-04
### Changed
* Change `NewService::Future` and `Transform::Future` to the `IntoFuture` trait.
* Export `AndThenTransform` type
## [0.3.1] - 2019-03-04
### Changed
* Simplify Transform trait
## [0.3.0] - 2019-03-02
## Added
* Added boxed NewService and Service.
## Changed
* Added `Config` parameter to `NewService` trait.
* Added `Config` parameter to `NewTransform` trait.
## [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 ## [0.2.1] - 2019-02-03
### Changed ### Changed

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-service" name = "actix-service"
version = "0.2.1" version = "0.3.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix Service" description = "Actix Service"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -11,7 +11,7 @@ categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"] exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018" edition = "2018"
workspace = "../" workspace = ".."
[badges] [badges]
travis-ci = { repository = "actix/actix-service", branch = "master" } travis-ci = { repository = "actix/actix-service", branch = "master" }
@@ -24,3 +24,7 @@ path = "src/lib.rs"
[dependencies] [dependencies]
futures = "0.1.24" futures = "0.1.24"
void = "1.0.2"
[dev-dependencies]
actix-rt = "0.1"

View File

@@ -1,3 +1,5 @@
use std::marker::PhantomData;
use futures::{try_ready, Async, Future, Poll}; use futures::{try_ready, Async, Future, Poll};
use super::{IntoNewService, NewService, Service}; use super::{IntoNewService, NewService, Service};
@@ -105,29 +107,31 @@ where
} }
/// `AndThenNewService` new service combinator /// `AndThenNewService` new service combinator
pub struct AndThenNewService<A, B> { pub struct AndThenNewService<A, B, C> {
a: A, a: A,
b: B, b: B,
_t: PhantomData<C>,
} }
impl<A, B> AndThenNewService<A, B> { impl<A, B, C> AndThenNewService<A, B, C> {
/// Create new `AndThen` combinator /// Create new `AndThen` combinator
pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self pub fn new<F: IntoNewService<B, C>>(a: A, f: F) -> Self
where where
A: NewService, A: NewService<C>,
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>, B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
{ {
Self { Self {
a, a,
b: f.into_new_service(), b: f.into_new_service(),
_t: PhantomData,
} }
} }
} }
impl<A, B> NewService for AndThenNewService<A, B> impl<A, B, C> NewService<C> for AndThenNewService<A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>, B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
{ {
type Request = A::Request; type Request = A::Request;
type Response = B::Response; type Response = B::Response;
@@ -135,14 +139,14 @@ where
type Service = AndThen<A::Service, B::Service>; type Service = AndThen<A::Service, B::Service>;
type InitError = A::InitError; type InitError = A::InitError;
type Future = AndThenNewServiceFuture<A, B>; type Future = AndThenNewServiceFuture<A, B, C>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &C) -> Self::Future {
AndThenNewServiceFuture::new(self.a.new_service(), self.b.new_service()) AndThenNewServiceFuture::new(self.a.new_service(cfg), self.b.new_service(cfg))
} }
} }
impl<A, B> Clone for AndThenNewService<A, B> impl<A, B, C> Clone for AndThenNewService<A, B, C>
where where
A: Clone, A: Clone,
B: Clone, B: Clone,
@@ -151,14 +155,15 @@ where
Self { Self {
a: self.a.clone(), a: self.a.clone(),
b: self.b.clone(), b: self.b.clone(),
_t: PhantomData,
} }
} }
} }
pub struct AndThenNewServiceFuture<A, B> pub struct AndThenNewServiceFuture<A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService<Request = A::Response>, B: NewService<C, Request = A::Response>,
{ {
fut_b: B::Future, fut_b: B::Future,
fut_a: A::Future, fut_a: A::Future,
@@ -166,10 +171,10 @@ where
b: Option<B::Service>, b: Option<B::Service>,
} }
impl<A, B> AndThenNewServiceFuture<A, B> impl<A, B, C> AndThenNewServiceFuture<A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService<Request = A::Response>, B: NewService<C, Request = A::Response>,
{ {
fn new(fut_a: A::Future, fut_b: B::Future) -> Self { fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
AndThenNewServiceFuture { AndThenNewServiceFuture {
@@ -181,10 +186,10 @@ where
} }
} }
impl<A, B> Future for AndThenNewServiceFuture<A, B> impl<A, B, C> Future for AndThenNewServiceFuture<A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>, B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
{ {
type Item = AndThen<A::Service, B::Service>; type Item = AndThen<A::Service, B::Service>;
type Error = A::InitError; type Error = A::InitError;
@@ -286,7 +291,7 @@ mod tests {
let new_srv = blank let new_srv = blank
.into_new_service() .into_new_service()
.and_then(move || Ok(Srv2(cnt.clone()))); .and_then(move || Ok(Srv2(cnt.clone())));
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() { if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
let res = srv.call("srv1").poll(); let res = srv.call("srv1").poll();
assert!(res.is_ok()); assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv1", "srv2"))); assert_eq!(res.unwrap(), Async::Ready(("srv1", "srv2")));

View File

@@ -1,168 +1,57 @@
use std::rc::Rc;
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
use super::{NewService, NewTransform, Service, Transform}; use crate::and_then::AndThen;
use crate::cell::Cell; use crate::from_err::FromErr;
use crate::{NewService, Transform};
/// `Apply` service combinator
pub struct AndThenTransform<T, A, B>
where
A: Service,
B: Service<Error = A::Error>,
T: Transform<B, Request = A::Response>,
T::Error: From<A::Error>,
{
a: A,
b: Cell<B>,
t: Cell<T>,
}
impl<T, A, B> AndThenTransform<T, A, B>
where
A: Service,
B: Service<Error = A::Error>,
T: Transform<B, Request = A::Response>,
T::Error: From<A::Error>,
{
/// Create new `Apply` combinator
pub fn new(t: T, a: A, b: B) -> Self {
Self {
a,
b: Cell::new(b),
t: Cell::new(t),
}
}
}
impl<T, A, B> Clone for AndThenTransform<T, A, B>
where
A: Service + Clone,
B: Service<Error = A::Error>,
T: Transform<B, Request = A::Response>,
T::Error: From<A::Error>,
{
fn clone(&self) -> Self {
AndThenTransform {
a: self.a.clone(),
b: self.b.clone(),
t: self.t.clone(),
}
}
}
impl<T, A, B> Service for AndThenTransform<T, A, B>
where
A: Service,
B: Service<Error = A::Error>,
T: Transform<B, Request = A::Response>,
T::Error: From<A::Error>,
{
type Request = A::Request;
type Response = T::Response;
type Error = T::Error;
type Future = AndThenTransformFuture<T, A, B>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
let notready = Async::NotReady == self.a.poll_ready()?;
let notready = Async::NotReady == self.b.get_mut().poll_ready()? || notready;
let notready = Async::NotReady == self.t.get_mut().poll_ready()? || notready;
if notready {
Ok(Async::NotReady)
} else {
Ok(Async::Ready(()))
}
}
fn call(&mut self, req: A::Request) -> Self::Future {
AndThenTransformFuture {
b: self.b.clone(),
t: self.t.clone(),
fut_t: None,
fut_a: Some(self.a.call(req)),
}
}
}
pub struct AndThenTransformFuture<T, A, B>
where
A: Service,
B: Service<Error = A::Error>,
T: Transform<B, Request = A::Response>,
T::Error: From<A::Error>,
{
b: Cell<B>,
t: Cell<T>,
fut_a: Option<A::Future>,
fut_t: Option<T::Future>,
}
impl<T, A, B> Future for AndThenTransformFuture<T, A, B>
where
A: Service,
B: Service<Error = A::Error>,
T: Transform<B, Request = A::Response>,
T::Error: From<A::Error>,
{
type Item = T::Response;
type Error = T::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Some(ref mut fut) = self.fut_t {
return fut.poll();
}
match self.fut_a.as_mut().expect("Bug in actix-service").poll() {
Ok(Async::Ready(resp)) => {
let _ = self.fut_a.take();
self.fut_t = Some(self.t.get_mut().call(resp, self.b.get_mut()));
self.poll()
}
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(err) => Err(err.into()),
}
}
}
/// `Apply` new service combinator /// `Apply` new service combinator
pub struct AndThenTransformNewService<T, A, B> { pub struct AndThenTransform<T, A, B, C> {
a: A, a: A,
b: B, b: B,
t: T, t: Rc<T>,
_t: std::marker::PhantomData<C>,
} }
impl<T, A, B> AndThenTransformNewService<T, A, B> impl<T, A, B, C> AndThenTransform<T, A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService<Error = A::Error, InitError = A::InitError>, B: NewService<C, InitError = A::InitError>,
T: NewTransform<B::Service, Request = A::Response, InitError = A::InitError>, T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>, T::Error: From<A::Error>,
{ {
/// Create new `ApplyNewService` new service instance /// Create new `ApplyNewService` new service instance
pub fn new(t: T, a: A, b: B) -> Self { pub fn new(t: T, a: A, b: B) -> Self {
Self { a, b, t } Self {
a,
b,
t: Rc::new(t),
_t: std::marker::PhantomData,
}
} }
} }
impl<T, A, B> Clone for AndThenTransformNewService<T, A, B> impl<T, A, B, C> Clone for AndThenTransform<T, A, B, C>
where where
A: Clone, A: Clone,
B: Clone, B: Clone,
T: Clone,
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Self { Self {
a: self.a.clone(), a: self.a.clone(),
b: self.b.clone(), b: self.b.clone(),
t: self.t.clone(), t: self.t.clone(),
_t: std::marker::PhantomData,
} }
} }
} }
impl<T, A, B> NewService for AndThenTransformNewService<T, A, B> impl<T, A, B, C> NewService<C> for AndThenTransform<T, A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService<Error = A::Error, InitError = A::InitError>, B: NewService<C, InitError = A::InitError>,
T: NewTransform<B::Service, Request = A::Response, InitError = A::InitError>, T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>, T::Error: From<A::Error>,
{ {
type Request = A::Request; type Request = A::Request;
@@ -170,50 +59,50 @@ where
type Error = T::Error; type Error = T::Error;
type InitError = T::InitError; type InitError = T::InitError;
type Service = AndThenTransform<T::Transform, A::Service, B::Service>; type Service = AndThen<FromErr<A::Service, T::Error>, T::Transform>;
type Future = AndThenTransformNewServiceFuture<T, A, B>; type Future = AndThenTransformFuture<T, A, B, C>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &C) -> Self::Future {
AndThenTransformNewServiceFuture { AndThenTransformFuture {
a: None, a: None,
b: None,
t: None, t: None,
fut_a: self.a.new_service(), t_cell: self.t.clone(),
fut_b: self.b.new_service(), fut_a: self.a.new_service(cfg),
fut_t: self.t.new_transform(), fut_b: self.b.new_service(cfg),
fut_t: None,
} }
} }
} }
pub struct AndThenTransformNewServiceFuture<T, A, B> pub struct AndThenTransformFuture<T, A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService<Error = A::Error, InitError = A::InitError>, B: NewService<C, InitError = A::InitError>,
T: NewTransform<B::Service, Request = A::Response, InitError = A::InitError>, T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>, T::Error: From<A::Error>,
{ {
fut_b: B::Future,
fut_a: A::Future, fut_a: A::Future,
fut_t: T::Future, fut_b: B::Future,
fut_t: Option<T::Future>,
a: Option<A::Service>, a: Option<A::Service>,
b: Option<B::Service>,
t: Option<T::Transform>, t: Option<T::Transform>,
t_cell: Rc<T>,
} }
impl<T, A, B> Future for AndThenTransformNewServiceFuture<T, A, B> impl<T, A, B, C> Future for AndThenTransformFuture<T, A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService<Error = A::Error, InitError = A::InitError>, B: NewService<C, InitError = A::InitError>,
T: NewTransform<B::Service, Request = A::Response, InitError = A::InitError>, T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>, T::Error: From<A::Error>,
{ {
type Item = AndThenTransform<T::Transform, A::Service, B::Service>; type Item = AndThen<FromErr<A::Service, T::Error>, T::Transform>;
type Error = T::InitError; type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if self.t.is_none() { if self.fut_t.is_none() {
if let Async::Ready(transform) = self.fut_t.poll()? { if let Async::Ready(service) = self.fut_b.poll()? {
self.t = Some(transform); self.fut_t = Some(self.t_cell.new_transform(service));
} }
} }
@@ -223,18 +112,17 @@ where
} }
} }
if self.b.is_none() { if let Some(ref mut fut) = self.fut_t {
if let Async::Ready(service) = self.fut_b.poll()? { if let Async::Ready(transform) = fut.poll()? {
self.b = Some(service); self.t = Some(transform);
} }
} }
if self.a.is_some() && self.b.is_some() && self.t.is_some() { if self.a.is_some() && self.t.is_some() {
Ok(Async::Ready(AndThenTransform { Ok(Async::Ready(AndThen::new(
a: self.a.take().unwrap(), FromErr::new(self.a.take().unwrap()),
t: Cell::new(self.t.take().unwrap()), self.t.take().unwrap(),
b: Cell::new(self.b.take().unwrap()), )))
}))
} else { } else {
Ok(Async::NotReady) Ok(Async::NotReady)
} }
@@ -269,10 +157,11 @@ mod tests {
fn test_apply() { fn test_apply() {
let blank = |req| Ok(req); let blank = |req| Ok(req);
let mut srv = blank.into_service().apply( let mut srv = blank
|req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)), .into_service()
Srv, .apply_fn(Srv, |req: &'static str, srv: &mut Srv| {
); srv.call(()).map(move |res| (req, res))
});
assert!(srv.poll_ready().is_ok()); assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll(); let res = srv.call("srv").poll();
assert!(res.is_ok()); assert!(res.is_ok());
@@ -287,7 +176,7 @@ mod tests {
|req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)), |req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)),
|| Ok(Srv), || Ok(Srv),
); );
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() { if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
assert!(srv.poll_ready().is_ok()); assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll(); let res = srv.call("srv").poll();
assert!(res.is_ok()); assert!(res.is_ok());

View File

@@ -129,23 +129,27 @@ where
} }
/// `ApplyNewService` new service combinator /// `ApplyNewService` new service combinator
pub struct AndThenApplyNewService<A, B, F, Out> { pub struct AndThenApplyNewService<A, B, F, Out, Cfg> {
a: A, a: A,
b: B, b: B,
f: Cell<F>, f: Cell<F>,
r: PhantomData<(Out)>, r: PhantomData<(Out, Cfg)>,
} }
impl<A, B, F, Out> AndThenApplyNewService<A, B, F, Out> impl<A, B, F, Out, Cfg> AndThenApplyNewService<A, B, F, Out, Cfg>
where where
A: NewService, A: NewService<Cfg>,
B: NewService<Error = A::Error, InitError = A::InitError>, B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out, F: FnMut(A::Response, &mut B::Service) -> Out,
Out: IntoFuture, Out: IntoFuture,
Out::Error: Into<A::Error>, Out::Error: Into<A::Error>,
{ {
/// Create new `ApplyNewService` new service instance /// Create new `ApplyNewService` new service instance
pub fn new<A1: IntoNewService<A>, B1: IntoNewService<B>>(a: A1, b: B1, f: F) -> Self { pub fn new<A1: IntoNewService<A, Cfg>, B1: IntoNewService<B, Cfg>>(
a: A1,
b: B1,
f: F,
) -> Self {
Self { Self {
f: Cell::new(f), f: Cell::new(f),
a: a.into_new_service(), a: a.into_new_service(),
@@ -155,7 +159,7 @@ where
} }
} }
impl<A, B, F, Out> Clone for AndThenApplyNewService<A, B, F, Out> impl<A, B, F, Out, Cfg> Clone for AndThenApplyNewService<A, B, F, Out, Cfg>
where where
A: Clone, A: Clone,
B: Clone, B: Clone,
@@ -170,10 +174,10 @@ where
} }
} }
impl<A, B, F, Out> NewService for AndThenApplyNewService<A, B, F, Out> impl<A, B, F, Out, Cfg> NewService<Cfg> for AndThenApplyNewService<A, B, F, Out, Cfg>
where where
A: NewService, A: NewService<Cfg>,
B: NewService<Error = A::Error, InitError = A::InitError>, B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out, F: FnMut(A::Response, &mut B::Service) -> Out,
Out: IntoFuture, Out: IntoFuture,
Out::Error: Into<A::Error>, Out::Error: Into<A::Error>,
@@ -181,26 +185,26 @@ where
type Request = A::Request; type Request = A::Request;
type Response = Out::Item; type Response = Out::Item;
type Error = A::Error; type Error = A::Error;
type Service = AndThenApply<A::Service, B::Service, F, Out>;
type InitError = A::InitError; type InitError = A::InitError;
type Service = AndThenApply<A::Service, B::Service, F, Out>; type Future = AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>;
type Future = AndThenApplyNewServiceFuture<A, B, F, Out>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &Cfg) -> Self::Future {
AndThenApplyNewServiceFuture { AndThenApplyNewServiceFuture {
a: None, a: None,
b: None, b: None,
f: self.f.clone(), f: self.f.clone(),
fut_a: self.a.new_service(), fut_a: self.a.new_service(cfg).into_future(),
fut_b: self.b.new_service(), fut_b: self.b.new_service(cfg).into_future(),
} }
} }
} }
pub struct AndThenApplyNewServiceFuture<A, B, F, Out> pub struct AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>
where where
A: NewService, A: NewService<Cfg>,
B: NewService<Error = A::Error, InitError = A::InitError>, B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out, F: FnMut(A::Response, &mut B::Service) -> Out,
Out: IntoFuture, Out: IntoFuture,
Out::Error: Into<A::Error>, Out::Error: Into<A::Error>,
@@ -212,10 +216,10 @@ where
b: Option<B::Service>, b: Option<B::Service>,
} }
impl<A, B, F, Out> Future for AndThenApplyNewServiceFuture<A, B, F, Out> impl<A, B, F, Out, Cfg> Future for AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>
where where
A: NewService, A: NewService<Cfg>,
B: NewService<Error = A::Error, InitError = A::InitError>, B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out, F: FnMut(A::Response, &mut B::Service) -> Out,
Out: IntoFuture, Out: IntoFuture,
Out::Error: Into<A::Error>, Out::Error: Into<A::Error>,
@@ -254,7 +258,8 @@ mod tests {
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
use crate::{Blank, BlankNewService, NewService, Service, ServiceExt}; use crate::blank::{Blank, BlankNewService};
use crate::{NewService, Service, ServiceExt};
#[derive(Clone)] #[derive(Clone)]
struct Srv; struct Srv;
@@ -290,7 +295,7 @@ mod tests {
|| Ok(Srv), || Ok(Srv),
|req: &'static str, srv| srv.call(()).map(move |res| (req, res)), |req: &'static str, srv| srv.call(()).map(move |res| (req, res)),
); );
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() { if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
assert!(srv.poll_ready().is_ok()); assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll(); let res = srv.call("srv").poll();
assert!(res.is_ok()); assert!(res.is_ok());

View File

@@ -1,213 +1,172 @@
use futures::{try_ready, Async, Future, IntoFuture, Poll}; use std::marker::PhantomData;
use super::{FnNewTransform, FnTransform}; use futures::{Async, Future, IntoFuture, Poll};
use super::{
IntoNewService, IntoNewTransform, IntoService, IntoTransform, NewService, NewTransform, use super::{IntoNewService, IntoService, NewService, Service};
Service, Transform,
};
/// `Apply` service combinator /// `Apply` service combinator
pub struct Apply<T, S> pub struct Apply<T, F, In, Out>
where where
T: Transform<S>, T: Service,
T::Error: From<S::Error>,
S: Service,
{ {
transform: T, service: T,
service: S, f: F,
r: PhantomData<(In, Out)>,
} }
impl<T, S> Apply<T, S> impl<T, F, In, Out> Apply<T, F, In, Out>
where where
T: Transform<S>, T: Service,
T::Error: From<S::Error>, F: FnMut(In, &mut T) -> Out,
S: Service,
{
/// Create new `Apply` combinator
pub fn new<T1: IntoTransform<T, S>, S1: IntoService<S>>(
transform: T1,
service: S1,
) -> Self {
Self {
transform: transform.into_transform(),
service: service.into_service(),
}
}
}
impl<F, S, Req, Out> Apply<FnTransform<F, S, Req, Out>, S>
where
F: FnMut(Req, &mut S) -> Out,
Out: IntoFuture, Out: IntoFuture,
Out::Error: From<S::Error>, Out::Error: From<T::Error>,
S: Service,
{ {
/// Create new `Apply` combinator /// Create new `Apply` combinator
pub fn new_fn<S1: IntoService<S>>(service: S1, transform: F) -> Self { pub fn new<I: IntoService<T>>(service: I, f: F) -> Self {
Self { Self {
service: service.into_service(), service: service.into_service(),
transform: transform.into_transform(), f,
r: PhantomData,
} }
} }
} }
impl<T, S> Clone for Apply<T, S> impl<T, F, In, Out> Clone for Apply<T, F, In, Out>
where where
S: Service + Clone, T: Service + Clone,
T::Error: From<S::Error>, F: Clone,
T: Transform<S> + Clone,
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Apply { Apply {
service: self.service.clone(), service: self.service.clone(),
transform: self.transform.clone(), f: self.f.clone(),
r: PhantomData,
} }
} }
} }
impl<T, S> Service for Apply<T, S> impl<T, F, In, Out> Service for Apply<T, F, In, Out>
where where
T: Transform<S>, T: Service,
T::Error: From<S::Error>, F: FnMut(In, &mut T) -> Out,
S: Service, Out: IntoFuture,
Out::Error: From<T::Error>,
{ {
type Request = T::Request; type Request = In;
type Response = T::Response; type Response = Out::Item;
type Error = T::Error; type Error = Out::Error;
type Future = T::Future; type Future = Out::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
try_ready!(self.service.poll_ready()); self.service.poll_ready().map_err(|e| e.into())
self.transform.poll_ready()
} }
fn call(&mut self, req: Self::Request) -> Self::Future { fn call(&mut self, req: In) -> Self::Future {
self.transform.call(req, &mut self.service).into_future() (self.f)(req, &mut self.service).into_future()
} }
} }
/// `ApplyNewService` new service combinator /// `ApplyNewService` new service combinator
pub struct ApplyNewService<T, S> pub struct ApplyNewService<T, F, In, Out, Cfg>
where where
T: NewTransform<S::Service, InitError = S::InitError>, T: NewService<Cfg>,
T::Error: From<S::Error>,
S: NewService,
{ {
transform: T, service: T,
service: S, f: F,
r: PhantomData<(In, Out, Cfg)>,
} }
impl<T, S> ApplyNewService<T, S> impl<T, F, In, Out, Cfg> ApplyNewService<T, F, In, Out, Cfg>
where where
T: NewTransform<S::Service, InitError = S::InitError>, T: NewService<Cfg>,
T::Error: From<S::Error>, F: FnMut(In, &mut T::Service) -> Out + Clone,
S: NewService, Out: IntoFuture,
Out::Error: From<T::Error>,
{ {
/// Create new `ApplyNewService` new service instance /// Create new `ApplyNewService` new service instance
pub fn new<T1: IntoNewTransform<T, S::Service>, S1: IntoNewService<S>>( pub fn new<F1: IntoNewService<T, Cfg>>(service: F1, f: F) -> Self {
transform: T1,
service: S1,
) -> Self {
Self { Self {
transform: transform.into_new_transform(), f,
service: service.into_new_service(), service: service.into_new_service(),
r: PhantomData,
} }
} }
} }
impl<F, S, In, Out> ApplyNewService<FnNewTransform<F, S::Service, In, Out, S::InitError>, S> impl<T, F, In, Out, Cfg> Clone for ApplyNewService<T, F, In, Out, Cfg>
where where
F: FnMut(In, &mut S::Service) -> Out + Clone, T: NewService<Cfg> + Clone,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture, Out: IntoFuture,
Out::Error: From<S::Error>,
S: NewService,
{
/// Create new `Apply` combinator factory
pub fn new_fn<S1: IntoNewService<S>>(service: S1, transform: F) -> Self {
Self {
service: service.into_new_service(),
transform: FnNewTransform::new(transform),
}
}
}
impl<T, S> Clone for ApplyNewService<T, S>
where
T: NewTransform<S::Service, InitError = S::InitError> + Clone,
T::Error: From<S::Error>,
S: NewService + Clone,
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Self { Self {
service: self.service.clone(), service: self.service.clone(),
transform: self.transform.clone(), f: self.f.clone(),
r: PhantomData,
} }
} }
} }
impl<T, S> NewService for ApplyNewService<T, S> impl<T, F, In, Out, Cfg> NewService<Cfg> for ApplyNewService<T, F, In, Out, Cfg>
where where
T: NewTransform<S::Service, InitError = S::InitError>, T: NewService<Cfg>,
T::Error: From<S::Error>, F: FnMut(In, &mut T::Service) -> Out + Clone,
S: NewService, Out: IntoFuture,
Out::Error: From<T::Error>,
{ {
type Request = T::Request; type Request = In;
type Response = T::Response; type Response = Out::Item;
type Error = T::Error; type Error = Out::Error;
type Service = Apply<T::Transform, S::Service>; type Service = Apply<T::Service, F, In, Out>;
type InitError = T::InitError; type InitError = T::InitError;
type Future = ApplyNewServiceFuture<T, S>; type Future = ApplyNewServiceFuture<T, F, In, Out, Cfg>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &Cfg) -> Self::Future {
ApplyNewServiceFuture::new(self.service.new_service(cfg), self.f.clone())
}
}
pub struct ApplyNewServiceFuture<T, F, In, Out, Cfg>
where
T: NewService<Cfg>,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
{
fut: T::Future,
f: Option<F>,
r: PhantomData<(In, Out)>,
}
impl<T, F, In, Out, Cfg> ApplyNewServiceFuture<T, F, In, Out, Cfg>
where
T: NewService<Cfg>,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
{
fn new(fut: T::Future, f: F) -> Self {
ApplyNewServiceFuture { ApplyNewServiceFuture {
fut_t: self.transform.new_transform(), f: Some(f),
fut_s: self.service.new_service(), fut,
service: None, r: PhantomData,
transform: None,
} }
} }
} }
pub struct ApplyNewServiceFuture<T, S> impl<T, F, In, Out, Cfg> Future for ApplyNewServiceFuture<T, F, In, Out, Cfg>
where where
T: NewTransform<S::Service, InitError = S::InitError>, T: NewService<Cfg>,
T::Error: From<S::Error>, F: FnMut(In, &mut T::Service) -> Out + Clone,
S: NewService, Out: IntoFuture,
Out::Error: From<T::Error>,
{ {
fut_s: S::Future, type Item = Apply<T::Service, F, In, Out>;
fut_t: T::Future,
service: Option<S::Service>,
transform: Option<T::Transform>,
}
impl<T, S> Future for ApplyNewServiceFuture<T, S>
where
T: NewTransform<S::Service, InitError = S::InitError>,
T::Error: From<S::Error>,
S: NewService,
{
type Item = Apply<T::Transform, S::Service>;
type Error = T::InitError; type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if self.transform.is_none() { if let Async::Ready(service) = self.fut.poll()? {
if let Async::Ready(transform) = self.fut_t.poll()? { Ok(Async::Ready(Apply::new(service, self.f.take().unwrap())))
self.transform = Some(transform);
}
}
if self.service.is_none() {
if let Async::Ready(service) = self.fut_s.poll()? {
self.service = Some(service);
}
}
if self.transform.is_some() && self.service.is_some() {
Ok(Async::Ready(Apply {
service: self.service.take().unwrap(),
transform: self.transform.take().unwrap(),
}))
} else { } else {
Ok(Async::NotReady) Ok(Async::NotReady)
} }
@@ -220,7 +179,7 @@ mod tests {
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
use super::*; use super::*;
use crate::{NewService, Service}; use crate::{IntoService, NewService, Service, ServiceExt};
#[derive(Clone)] #[derive(Clone)]
struct Srv; struct Srv;
@@ -240,10 +199,14 @@ mod tests {
} }
#[test] #[test]
fn test_apply() { fn test_call() {
let mut srv = Apply::new_fn(Srv, |req: &'static str, srv| { let blank = |req| Ok(req);
srv.call(()).map(move |res| (req, res))
}); let mut srv = blank
.into_service()
.apply_fn(Srv, |req: &'static str, srv| {
srv.call(()).map(move |res| (req, res))
});
assert!(srv.poll_ready().is_ok()); assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll(); let res = srv.call("srv").poll();
assert!(res.is_ok()); assert!(res.is_ok());
@@ -253,26 +216,10 @@ mod tests {
#[test] #[test]
fn test_new_service() { fn test_new_service() {
let new_srv = ApplyNewService::new( let new_srv = ApplyNewService::new(
|req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)),
|| Ok::<_, ()>(Srv),
);
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
} else {
panic!()
}
}
#[test]
fn test_new_service_fn() {
let new_srv = ApplyNewService::new_fn(
|| Ok::<_, ()>(Srv), || Ok::<_, ()>(Srv),
|req: &'static str, srv| srv.call(()).map(move |res| (req, res)), |req: &'static str, srv| srv.call(()).map(move |res| (req, res)),
); );
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() { if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
assert!(srv.poll_ready().is_ok()); assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll(); let res = srv.call("srv").poll();
assert!(res.is_ok()); assert!(res.is_ok());

View File

@@ -0,0 +1,163 @@
use std::marker::PhantomData;
use futures::{Async, Future, Poll};
use crate::and_then::AndThen;
use crate::{IntoNewService, NewService};
/// `ApplyNewService` new service combinator
pub struct ApplyConfig<F, A, B, C1, C2> {
a: A,
b: B,
f: F,
r: PhantomData<(C1, C2)>,
}
impl<F, A, B, C1, C2> ApplyConfig<F, A, B, C1, C2>
where
A: NewService<C1>,
B: NewService<C2, Request = A::Response, Error = A::Error, InitError = A::InitError>,
F: Fn(&C1) -> C2,
{
/// Create new `ApplyNewService` new service instance
pub fn new<A1: IntoNewService<A, C1>, B1: IntoNewService<B, C2>>(
a: A1,
b: B1,
f: F,
) -> Self {
Self {
f,
a: a.into_new_service(),
b: b.into_new_service(),
r: PhantomData,
}
}
}
impl<F, A, B, C1, C2> Clone for ApplyConfig<F, A, B, C1, C2>
where
A: Clone,
B: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
b: self.b.clone(),
f: self.f.clone(),
r: PhantomData,
}
}
}
impl<F, A, B, C1, C2> NewService<C1> for ApplyConfig<F, A, B, C1, C2>
where
A: NewService<C1>,
B: NewService<C2, Request = A::Response, Error = A::Error, InitError = A::InitError>,
F: Fn(&C1) -> C2,
{
type Request = A::Request;
type Response = B::Response;
type Error = A::Error;
type Service = AndThen<A::Service, B::Service>;
type InitError = A::InitError;
type Future = ApplyConfigResponse<A, B, C1, C2>;
fn new_service(&self, cfg: &C1) -> Self::Future {
let cfg2 = (self.f)(cfg);
ApplyConfigResponse {
a: None,
b: None,
fut_a: self.a.new_service(cfg),
fut_b: self.b.new_service(&cfg2),
}
}
}
pub struct ApplyConfigResponse<A, B, C1, C2>
where
A: NewService<C1>,
B: NewService<C2>,
{
fut_b: B::Future,
fut_a: A::Future,
a: Option<A::Service>,
b: Option<B::Service>,
}
impl<A, B, C1, C2> Future for ApplyConfigResponse<A, B, C1, C2>
where
A: NewService<C1>,
B: NewService<C2, Request = A::Response, Error = A::Error, InitError = A::InitError>,
{
type Item = AndThen<A::Service, B::Service>;
type Error = A::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if self.a.is_none() {
if let Async::Ready(service) = self.fut_a.poll()? {
self.a = Some(service);
}
}
if self.b.is_none() {
if let Async::Ready(service) = self.fut_b.poll()? {
self.b = Some(service);
}
}
if self.a.is_some() && self.b.is_some() {
Ok(Async::Ready(AndThen::new(
self.a.take().unwrap(),
self.b.take().unwrap(),
)))
} else {
Ok(Async::NotReady)
}
}
}
#[cfg(test)]
mod tests {
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use crate::{fn_cfg_factory, NewService, Service};
#[derive(Clone)]
struct Srv;
impl Service for Srv {
type Request = ();
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
ok(())
}
}
#[test]
fn test_new_service() {
let new_srv = fn_cfg_factory(|_: &usize| Ok::<_, ()>(Srv)).apply_cfg(
fn_cfg_factory(|s: &String| {
assert_eq!(s, "test");
Ok::<_, ()>(Srv)
}),
|cfg: &usize| {
assert_eq!(*cfg, 1);
"test".to_string()
},
);
if let Async::Ready(mut srv) = new_srv.new_service(&1).poll().unwrap() {
assert!(srv.poll_ready().is_ok());
}
}
}

View File

@@ -68,15 +68,16 @@ impl<R, E1, E2> Default for BlankNewService<R, E1, E2> {
} }
} }
impl<R, E1, E2> NewService for BlankNewService<R, E1, E2> { impl<R, E1, E2> NewService<()> for BlankNewService<R, E1, E2> {
type Request = R; type Request = R;
type Response = R; type Response = R;
type Error = E1; type Error = E1;
type InitError = E2;
type Service = Blank<R, E1>; type Service = Blank<R, E1>;
type InitError = E2;
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
ok(Blank::default()) ok(Blank::default())
} }
} }

137
actix-service/src/boxed.rs Normal file
View File

@@ -0,0 +1,137 @@
use crate::{NewService, Service};
use futures::{Future, IntoFuture, Poll};
pub type BoxedService<Req, Res, Err> = Box<
Service<
Request = Req,
Response = Res,
Error = Err,
Future = Box<Future<Item = Res, Error = Err>>,
>,
>;
/// Create boxed new service
pub fn new_service<T, C>(
service: T,
) -> BoxedNewService<C, T::Request, T::Response, T::Error, T::InitError>
where
C: 'static,
T: NewService<C> + 'static,
T::Request: 'static,
T::Response: 'static,
T::Service: 'static,
T::Future: 'static,
T::Error: 'static,
T::InitError: 'static,
{
BoxedNewService(Box::new(NewServiceWrapper {
service,
_t: std::marker::PhantomData,
}))
}
/// 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))
}
type Inner<C, Req, Res, Err, InitErr> = Box<
NewService<
C,
Request = Req,
Response = Res,
Error = Err,
InitError = InitErr,
Service = BoxedService<Req, Res, Err>,
Future = Box<Future<Item = BoxedService<Req, Res, Err>, Error = InitErr>>,
>,
>;
pub struct BoxedNewService<C, Req, Res, Err, InitErr>(Inner<C, Req, Res, Err, InitErr>);
impl<C, Req, Res, Err, InitErr> NewService<C> for BoxedNewService<C, Req, Res, Err, InitErr>
where
Req: 'static,
Res: 'static,
Err: 'static,
InitErr: '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, cfg: &C) -> Self::Future {
self.0.new_service(cfg)
}
}
struct NewServiceWrapper<C, T: NewService<C>> {
service: T,
_t: std::marker::PhantomData<C>,
}
impl<C, T, Req, Res, Err, InitErr> NewService<C> for NewServiceWrapper<C, T>
where
Req: 'static,
Res: 'static,
Err: 'static,
InitErr: 'static,
T: NewService<C, 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, cfg: &C) -> Self::Future {
Box::new(
self.service
.new_service(cfg)
.into_future()
.map(ServiceWrapper::boxed),
)
}
}
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))
}
}

View File

@@ -1,9 +1,39 @@
use std::marker::PhantomData; use std::marker::PhantomData;
use futures::future::{ok, FutureResult}; use futures::future::{ok, Future, FutureResult};
use futures::{Async, IntoFuture, Poll}; use futures::{try_ready, Async, IntoFuture, Poll};
use super::{IntoNewService, IntoService, NewService, Service}; use crate::{IntoConfigurableNewService, IntoNewService, IntoService, NewService, Service};
/// Create `NewService` for function that can act as Service
pub fn fn_service<F, Req, Out, Cfg>(f: F) -> FnNewService<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
{
FnNewService::new(f)
}
/// Create `NewService` for function that can produce services
pub fn fn_factory<F, R, S, E>(f: F) -> FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
FnNewServiceNoConfig::new(f)
}
/// Create `NewService` for function that can produce services with configuration
pub fn fn_cfg_factory<F, C, R, S, E>(f: F) -> FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
FnNewServiceConfig::new(f)
}
pub struct FnService<F, Req, Out> pub struct FnService<F, Req, Out>
where where
@@ -66,16 +96,16 @@ where
} }
} }
pub struct FnNewService<F, Req, Out> pub struct FnNewService<F, Req, Out, Cfg>
where where
F: FnMut(Req) -> Out, F: FnMut(Req) -> Out,
Out: IntoFuture, Out: IntoFuture,
{ {
f: F, f: F,
_t: PhantomData<(Req,)>, _t: PhantomData<(Req, Cfg)>,
} }
impl<F, Req, Out> FnNewService<F, Req, Out> impl<F, Req, Out, Cfg> FnNewService<F, Req, Out, Cfg>
where where
F: FnMut(Req) -> Out + Clone, F: FnMut(Req) -> Out + Clone,
Out: IntoFuture, Out: IntoFuture,
@@ -85,7 +115,7 @@ where
} }
} }
impl<F, Req, Out> NewService for FnNewService<F, Req, Out> impl<F, Req, Out, Cfg> NewService<Cfg> for FnNewService<F, Req, Out, Cfg>
where where
F: FnMut(Req) -> Out + Clone, F: FnMut(Req) -> Out + Clone,
Out: IntoFuture, Out: IntoFuture,
@@ -94,25 +124,16 @@ where
type Response = Out::Item; type Response = Out::Item;
type Error = Out::Error; type Error = Out::Error;
type Service = FnService<F, Req, Out>; type Service = FnService<F, Req, Out>;
type InitError = (); type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_service(&self, _: &Cfg) -> Self::Future {
ok(FnService::new(self.f.clone())) ok(FnService::new(self.f.clone()))
} }
} }
impl<F, Req, Out> IntoNewService<FnNewService<F, Req, Out>> for F impl<F, Req, Out, Cfg> Clone for FnNewService<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out + Clone + 'static,
Out: IntoFuture,
{
fn into_new_service(self) -> FnNewService<F, Req, Out> {
FnNewService::new(self)
}
}
impl<F, Req, Out> Clone for FnNewService<F, Req, Out>
where where
F: FnMut(Req) -> Out + Clone, F: FnMut(Req) -> Out + Clone,
Out: IntoFuture, Out: IntoFuture,
@@ -121,3 +142,170 @@ where
Self::new(self.f.clone()) Self::new(self.f.clone())
} }
} }
impl<F, Req, Out, Cfg> IntoNewService<FnNewService<F, Req, Out, Cfg>, Cfg> for F
where
F: Fn(Req) -> Out + Clone,
Out: IntoFuture,
{
fn into_new_service(self) -> FnNewService<F, Req, Out, Cfg> {
FnNewService::new(self)
}
}
/// Converter for `Fn() -> Future<Service>` fn
pub struct FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
f: F,
}
impl<F, R, S, E> FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
pub fn new(f: F) -> Self {
FnNewServiceNoConfig { f }
}
}
impl<F, R, S, E> NewService<()> for FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S;
type InitError = E;
type Future = R::Future;
fn new_service(&self, _: &()) -> Self::Future {
(self.f)().into_future()
}
}
impl<F, R, S, E> Clone for FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R + Clone,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
fn clone(&self) -> Self {
Self::new(self.f.clone())
}
}
impl<F, R, S, E> IntoNewService<FnNewServiceNoConfig<F, R, S, E>, ()> for F
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
fn into_new_service(self) -> FnNewServiceNoConfig<F, R, S, E> {
FnNewServiceNoConfig::new(self)
}
}
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
pub struct FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
f: F,
_t: PhantomData<(C, R, S, E)>,
}
impl<F, C, R, S, E> FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
pub fn new(f: F) -> Self {
FnNewServiceConfig { f, _t: PhantomData }
}
}
impl<F, C, R, S, E> NewService<C> for FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S;
type InitError = E;
type Future = FnNewServiceConfigFut<R, S, E>;
fn new_service(&self, cfg: &C) -> Self::Future {
FnNewServiceConfigFut {
fut: (self.f)(cfg).into_future(),
_t: PhantomData,
}
}
}
pub struct FnNewServiceConfigFut<R, S, E>
where
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
fut: R::Future,
_t: PhantomData<(S,)>,
}
impl<R, S, E> Future for FnNewServiceConfigFut<R, S, E>
where
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
type Item = S;
type Error = R::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
Ok(Async::Ready(try_ready!(self.fut.poll()).into_service()))
}
}
impl<F, C, R, S, E> Clone for FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R + Clone,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
fn clone(&self) -> Self {
Self::new(self.f.clone())
}
}
impl<F, C, R, S, E> IntoConfigurableNewService<FnNewServiceConfig<F, C, R, S, E>, C> for F
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
S: Service,
{
fn into_new_service(self) -> FnNewServiceConfig<F, C, R, S, E> {
FnNewServiceConfig::new(self)
}
}

View File

@@ -1,121 +1,64 @@
use std::marker::PhantomData; use std::marker::PhantomData;
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{Async, IntoFuture, Poll}; use futures::IntoFuture;
use super::{IntoNewTransform, IntoTransform, NewTransform, Transform}; use crate::{Apply, IntoTransform, Service, Transform};
pub struct FnTransform<F, S, Req, Res> pub struct FnTransform<F, S, In, Out, Err>
where where
F: FnMut(Req, &mut S) -> Res, F: FnMut(In, &mut S) -> Out + Clone,
Res: IntoFuture, Out: IntoFuture,
{ {
f: F, f: F,
_t: PhantomData<(S, Req, Res)>, _t: PhantomData<(S, In, Out, Err)>,
} }
impl<F, S, Req, Res> FnTransform<F, S, Req, Res> impl<F, S, In, Out, Err> FnTransform<F, S, In, Out, Err>
where where
F: FnMut(Req, &mut S) -> Res, F: FnMut(In, &mut S) -> Out + Clone,
Res: IntoFuture, Out: IntoFuture,
{ {
pub fn new(f: F) -> Self { pub fn new(f: F) -> Self {
FnTransform { f, _t: PhantomData } FnTransform { f, _t: PhantomData }
} }
} }
impl<F, S, Req, Res> Clone for FnTransform<F, S, Req, Res> impl<F, S, In, Out, Err> Transform<S> for FnTransform<F, S, In, Out, Err>
where where
F: FnMut(Req, &mut S) -> Res + Clone, S: Service,
Res: IntoFuture, F: FnMut(In, &mut S) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<S::Error>,
{ {
fn clone(&self) -> Self { type Request = In;
FnTransform { type Response = Out::Item;
f: self.f.clone(), type Error = Out::Error;
_t: PhantomData, type Transform = Apply<S, F, In, Out>;
} type InitError = Err;
type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self, service: S) -> Self::Future {
ok(Apply::new(service, self.f.clone()))
} }
} }
impl<F, S, Req, Res> Transform<S> for FnTransform<F, S, Req, Res> impl<F, S, In, Out, Err> IntoTransform<FnTransform<F, S, In, Out, Err>, S> for F
where where
F: FnMut(Req, &mut S) -> Res, S: Service,
Res: IntoFuture, F: FnMut(In, &mut S) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<S::Error>,
{ {
type Request = Req; fn into_transform(self) -> FnTransform<F, S, In, Out, Err> {
type Response = Res::Item;
type Error = Res::Error;
type Future = Res::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, request: Req, service: &mut S) -> Self::Future {
(self.f)(request, service).into_future()
}
}
impl<F, S, Req, Res> IntoTransform<FnTransform<F, S, Req, Res>, S> for F
where
F: FnMut(Req, &mut S) -> Res,
Res: IntoFuture,
{
fn into_transform(self) -> FnTransform<F, S, Req, Res> {
FnTransform::new(self) FnTransform::new(self)
} }
} }
pub struct FnNewTransform<F, S, Req, Out, Err> impl<F, S, In, Out, Err> Clone for FnTransform<F, S, In, Out, Err>
where where
F: FnMut(Req, &mut S) -> Out + Clone, F: FnMut(In, &mut S) -> Out + Clone,
Out: IntoFuture, Out: IntoFuture,
{
f: F,
_t: PhantomData<(S, Req, Out, Err)>,
}
impl<F, S, Req, Res, Err> FnNewTransform<F, S, Req, Res, Err>
where
F: FnMut(Req, &mut S) -> Res + Clone,
Res: IntoFuture,
{
pub fn new(f: F) -> Self {
FnNewTransform { f, _t: PhantomData }
}
}
impl<F, S, Req, Res, Err> NewTransform<S> for FnNewTransform<F, S, Req, Res, Err>
where
F: FnMut(Req, &mut S) -> Res + Clone,
Res: IntoFuture,
{
type Request = Req;
type Response = Res::Item;
type Error = Res::Error;
type Transform = FnTransform<F, S, Req, Res>;
type InitError = Err;
type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self) -> Self::Future {
ok(FnTransform::new(self.f.clone()))
}
}
impl<F, S, Req, Res, Err> IntoNewTransform<FnNewTransform<F, S, Req, Res, Err>, S> for F
where
F: FnMut(Req, &mut S) -> Res + Clone,
Res: IntoFuture,
{
fn into_new_transform(self) -> FnNewTransform<F, S, Req, Res, Err> {
FnNewTransform::new(self)
}
}
impl<F, S, Req, Res, Err> Clone for FnNewTransform<F, S, Req, Res, Err>
where
F: FnMut(Req, &mut S) -> Res + Clone,
Res: IntoFuture,
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Self::new(self.f.clone()) Self::new(self.f.clone())

View File

@@ -81,23 +81,23 @@ where
/// service's error. /// service's error.
/// ///
/// This is created by the `NewServiceExt::from_err` method. /// This is created by the `NewServiceExt::from_err` method.
pub struct FromErrNewService<A, E> { pub struct FromErrNewService<A, E, C> {
a: A, a: A,
e: PhantomData<E>, e: PhantomData<(E, C)>,
} }
impl<A, E> FromErrNewService<A, E> { impl<A, E, C> FromErrNewService<A, E, C> {
/// Create new `FromErr` new service instance /// Create new `FromErr` new service instance
pub fn new(a: A) -> Self pub fn new(a: A) -> Self
where where
A: NewService, A: NewService<C>,
E: From<A::Error>, E: From<A::Error>,
{ {
Self { a, e: PhantomData } Self { a, e: PhantomData }
} }
} }
impl<A, E> Clone for FromErrNewService<A, E> impl<A, E, C> Clone for FromErrNewService<A, E, C>
where where
A: Clone, A: Clone,
{ {
@@ -109,9 +109,9 @@ where
} }
} }
impl<A, E> NewService for FromErrNewService<A, E> impl<A, E, C> NewService<C> for FromErrNewService<A, E, C>
where where
A: NewService, A: NewService<C>,
E: From<A::Error>, E: From<A::Error>,
{ {
type Request = A::Request; type Request = A::Request;
@@ -120,28 +120,28 @@ where
type Service = FromErr<A::Service, E>; type Service = FromErr<A::Service, E>;
type InitError = A::InitError; type InitError = A::InitError;
type Future = FromErrNewServiceFuture<A, E>; type Future = FromErrNewServiceFuture<A, E, C>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &C) -> Self::Future {
FromErrNewServiceFuture { FromErrNewServiceFuture {
fut: self.a.new_service(), fut: self.a.new_service(cfg),
e: PhantomData, e: PhantomData,
} }
} }
} }
pub struct FromErrNewServiceFuture<A, E> pub struct FromErrNewServiceFuture<A, E, C>
where where
A: NewService, A: NewService<C>,
E: From<A::Error>, E: From<A::Error>,
{ {
fut: A::Future, fut: A::Future,
e: PhantomData<E>, e: PhantomData<E>,
} }
impl<A, E> Future for FromErrNewServiceFuture<A, E> impl<A, E, C> Future for FromErrNewServiceFuture<A, E, C>
where where
A: NewService, A: NewService<C>,
E: From<A::Error>, E: From<A::Error>,
{ {
type Item = FromErr<A::Service, E>; type Item = FromErr<A::Service, E>;
@@ -208,7 +208,7 @@ mod tests {
fn test_new_service() { fn test_new_service() {
let blank = || Ok::<_, ()>(Srv); let blank = || Ok::<_, ()>(Srv);
let new_srv = blank.into_new_service().from_err::<Error>(); let new_srv = blank.into_new_service().from_err::<Error>();
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() { if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
let res = srv.call(()).poll(); let res = srv.call(()).poll();
assert!(res.is_err()); assert!(res.is_err());
assert_eq!(res.err().unwrap(), Error); assert_eq!(res.err().unwrap(), Error);

View File

@@ -1,10 +1,17 @@
use std::rc::Rc;
use std::sync::Arc;
use futures::{Future, IntoFuture, Poll}; use futures::{Future, IntoFuture, Poll};
pub use void::Void;
mod and_then; mod and_then;
mod and_then_apply; mod and_then_apply;
mod and_then_apply_fn; mod and_then_apply_fn;
mod apply; mod apply;
mod blank; mod apply_cfg;
pub mod blank;
pub mod boxed;
mod cell; mod cell;
mod fn_service; mod fn_service;
mod fn_transform; mod fn_transform;
@@ -14,21 +21,21 @@ mod map_err;
mod map_init_err; mod map_init_err;
mod then; mod then;
mod transform; mod transform;
mod transform_map_err; mod transform_map_init_err;
pub use self::and_then::{AndThen, AndThenNewService}; pub use self::and_then::{AndThen, AndThenNewService};
use self::and_then_apply::{AndThenTransform, AndThenTransformNewService}; use self::and_then_apply::AndThenTransform;
use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService}; use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService};
pub use self::apply::{Apply, ApplyNewService}; pub use self::apply::{Apply, ApplyNewService};
pub use self::blank::{Blank, BlankNewService}; pub use self::apply_cfg::ApplyConfig;
pub use self::fn_service::{FnNewService, FnService}; pub use self::fn_service::{fn_cfg_factory, fn_factory, fn_service, FnService};
pub use self::fn_transform::{FnNewTransform, FnTransform}; pub use self::fn_transform::FnTransform;
pub use self::from_err::{FromErr, FromErrNewService}; pub use self::from_err::{FromErr, FromErrNewService};
pub use self::map::{Map, MapNewService}; pub use self::map::{Map, MapNewService};
pub use self::map_err::{MapErr, MapErrNewService}; pub use self::map_err::{MapErr, MapErrNewService};
pub use self::map_init_err::MapInitErr; pub use self::map_init_err::MapInitErr;
pub use self::then::{Then, ThenNewService}; pub use self::then::{Then, ThenNewService};
pub use self::transform::{IntoNewTransform, IntoTransform, NewTransform, Transform}; pub use self::transform::{ApplyTransform, IntoTransform, Transform};
/// An asynchronous function from `Request` to a `Response`. /// An asynchronous function from `Request` to a `Response`.
pub trait Service { pub trait Service {
@@ -70,20 +77,6 @@ pub trait Service {
/// An extension trait for `Service`s that provides a variety of convenient /// An extension trait for `Service`s that provides a variety of convenient
/// adapters /// adapters
pub trait ServiceExt: Service { pub trait ServiceExt: Service {
/// Apply tranformation to specified service and use it as a next service in
/// chain.
fn apply<T, T1, B, B1>(self, transform: T1, service: B1) -> AndThenTransform<T, Self, B>
where
Self: Sized,
T: Transform<B, Request = Self::Response>,
T::Error: From<Self::Error>,
T1: IntoTransform<T, B>,
B: Service<Error = Self::Error>,
B1: IntoService<B>,
{
AndThenTransform::new(transform.into_transform(), self, service.into_service())
}
/// Apply function to specified service and use it as a next service in /// Apply function to specified service and use it as a next service in
/// chain. /// chain.
fn apply_fn<F, B, B1, Out>(self, service: B1, f: F) -> AndThenApply<Self, B, F, Out> fn apply_fn<F, B, B1, Out>(self, service: B1, f: F) -> AndThenApply<Self, B, F, Out>
@@ -185,7 +178,9 @@ impl<T: ?Sized> ServiceExt for T where T: Service {}
/// accepts new TCP streams, obtains a new `Service` value using the /// accepts new TCP streams, obtains a new `Service` value using the
/// `NewService` trait, and uses that new `Service` value to process inbound /// `NewService` trait, and uses that new `Service` value to process inbound
/// requests on that new TCP stream. /// requests on that new TCP stream.
pub trait NewService { ///
/// `Config` is a service factory configuration type.
pub trait NewService<Config = ()> {
/// Requests handled by the service. /// Requests handled by the service.
type Request; type Request;
@@ -209,37 +204,37 @@ pub trait NewService {
type Future: Future<Item = Self::Service, Error = Self::InitError>; type Future: Future<Item = Self::Service, Error = Self::InitError>;
/// Create and return a new service value asynchronously. /// Create and return a new service value asynchronously.
fn new_service(&self) -> Self::Future; fn new_service(&self, cfg: &Config) -> Self::Future;
/// Apply function to specified service and use it as a next service in /// Apply transform service to specified service and use it as a next service in
/// chain. /// chain.
fn apply<T, T1, B, B1>( fn apply<T, T1, B, B1>(
self, self,
transform: T1, transform: T1,
service: B1, service: B1,
) -> AndThenTransformNewService<T, Self, B> ) -> AndThenTransform<T, Self, B, Config>
where where
Self: Sized, Self: Sized,
T: NewTransform<B::Service, Request = Self::Response, InitError = Self::InitError>, T: Transform<B::Service, Request = Self::Response, InitError = Self::InitError>,
T::Error: From<Self::Error>, T::Error: From<Self::Error>,
T1: IntoNewTransform<T, B::Service>, T1: IntoTransform<T, B::Service>,
B: NewService<Error = Self::Error, InitError = Self::InitError>, B: NewService<Config, InitError = Self::InitError>,
B1: IntoNewService<B>, B1: IntoNewService<B, Config>,
{ {
AndThenTransformNewService::new( AndThenTransform::new(transform.into_transform(), self, service.into_new_service())
transform.into_new_transform(),
self,
service.into_new_service(),
)
} }
/// Apply function to specified service and use it as a next service in /// Apply function to specified service and use it as a next service in
/// chain. /// chain.
fn apply_fn<B, I, F, Out>(self, service: I, f: F) -> AndThenApplyNewService<Self, B, F, Out> fn apply_fn<B, I, F, Out>(
self,
service: I,
f: F,
) -> AndThenApplyNewService<Self, B, F, Out, Config>
where where
Self: Sized, Self: Sized,
B: NewService<Error = Self::Error, InitError = Self::InitError>, B: NewService<Config, Error = Self::Error, InitError = Self::InitError>,
I: IntoNewService<B>, I: IntoNewService<B, Config>,
F: FnMut(Self::Response, &mut B::Service) -> Out, F: FnMut(Self::Response, &mut B::Service) -> Out,
Out: IntoFuture, Out: IntoFuture,
Out::Error: Into<Self::Error>, Out::Error: Into<Self::Error>,
@@ -247,12 +242,30 @@ pub trait NewService {
AndThenApplyNewService::new(self, service, f) AndThenApplyNewService::new(self, service, f)
} }
/// Call another service after call to this one has resolved successfully. /// Map this service's config type to a different config,
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B> /// and use for nested service
fn apply_cfg<F, C, B, B1>(self, service: B1, f: F) -> ApplyConfig<F, Self, B, Config, C>
where where
Self: Sized, Self: Sized,
F: IntoNewService<B>, F: Fn(&Config) -> C,
B1: IntoNewService<B, C>,
B: NewService< B: NewService<
C,
Request = Self::Response,
Error = Self::Error,
InitError = Self::InitError,
>,
{
ApplyConfig::new(self, service, f)
}
/// Call another service after call to this one has resolved successfully.
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B, Config>
where
Self: Sized,
F: IntoNewService<B, Config>,
B: NewService<
Config,
Request = Self::Response, Request = Self::Response,
Error = Self::Error, Error = Self::Error,
InitError = Self::InitError, InitError = Self::InitError,
@@ -267,7 +280,7 @@ pub trait NewService {
/// ///
/// Note that this function consumes the receiving new service and returns a /// Note that this function consumes the receiving new service and returns a
/// wrapped version of it. /// wrapped version of it.
fn from_err<E>(self) -> FromErrNewService<Self, E> fn from_err<E>(self) -> FromErrNewService<Self, E, Config>
where where
Self: Sized, Self: Sized,
E: From<Self::Error>, E: From<Self::Error>,
@@ -281,11 +294,12 @@ pub trait NewService {
/// ///
/// Note that this function consumes the receiving future and returns a /// Note that this function consumes the receiving future and returns a
/// wrapped version of it. /// wrapped version of it.
fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B> fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B, Config>
where where
Self: Sized, Self: Sized,
F: IntoNewService<B>, F: IntoNewService<B, Config>,
B: NewService< B: NewService<
Config,
Request = Result<Self::Response, Self::Error>, Request = Result<Self::Response, Self::Error>,
Error = Self::Error, Error = Self::Error,
InitError = Self::InitError, InitError = Self::InitError,
@@ -296,7 +310,7 @@ pub trait NewService {
/// Map this service's output to a different type, returning a new service /// Map this service's output to a different type, returning a new service
/// of the resulting type. /// of the resulting type.
fn map<F, R>(self, f: F) -> MapNewService<Self, F, R> fn map<F, R>(self, f: F) -> MapNewService<Self, F, R, Config>
where where
Self: Sized, Self: Sized,
F: FnMut(Self::Response) -> R, F: FnMut(Self::Response) -> R,
@@ -305,7 +319,7 @@ pub trait NewService {
} }
/// Map this service's error to a different error, returning a new service. /// Map this service's error to a different error, returning a new service.
fn map_err<F, E>(self, f: F) -> MapErrNewService<Self, F, E> fn map_err<F, E>(self, f: F) -> MapErrNewService<Self, F, E, Config>
where where
Self: Sized, Self: Sized,
F: Fn(Self::Error) -> E, F: Fn(Self::Error) -> E,
@@ -314,7 +328,7 @@ pub trait NewService {
} }
/// Map this service's init error to a different error, returning a new service. /// Map this service's init error to a different error, returning a new service.
fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, E> fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, E, Config>
where where
Self: Sized, Self: Sized,
F: Fn(Self::InitError) -> E, F: Fn(Self::InitError) -> E,
@@ -359,21 +373,35 @@ where
} }
} }
impl<F, R, E, S> NewService for F impl<S, C> NewService<C> for Rc<S>
where where
F: Fn() -> R, S: NewService<C>,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{ {
type Request = S::Request; type Request = S::Request;
type Response = S::Response; type Response = S::Response;
type Error = S::Error; type Error = S::Error;
type Service = S; type Service = S::Service;
type InitError = E; type InitError = S::InitError;
type Future = R::Future; type Future = S::Future;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &C) -> S::Future {
(*self)().into_future() self.as_ref().new_service(cfg)
}
}
impl<S, C> NewService<C> for Arc<S>
where
S: NewService<C>,
{
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, cfg: &C) -> S::Future {
self.as_ref().new_service(cfg)
} }
} }
@@ -387,9 +415,9 @@ where
} }
/// Trait for types that can be converted to a `NewService` /// Trait for types that can be converted to a `NewService`
pub trait IntoNewService<T> pub trait IntoNewService<T, C = ()>
where where
T: NewService, T: NewService<C>,
{ {
/// Convert to an `NewService` /// Convert to an `NewService`
fn into_new_service(self) -> T; fn into_new_service(self) -> T;
@@ -404,9 +432,27 @@ where
} }
} }
impl<T> IntoNewService<T> for T impl<T, C> IntoNewService<T, C> for T
where where
T: NewService, T: NewService<C>,
{
fn into_new_service(self) -> T {
self
}
}
/// Trait for types that can be converted to a configurable `NewService`
pub trait IntoConfigurableNewService<T, C>
where
T: NewService<C>,
{
/// Convert to an `NewService`
fn into_new_service(self) -> T;
}
impl<T, C> IntoConfigurableNewService<T, C> for T
where
T: NewService<C>,
{ {
fn into_new_service(self) -> T { fn into_new_service(self) -> T {
self self

View File

@@ -97,18 +97,18 @@ where
} }
/// `MapNewService` new service combinator /// `MapNewService` new service combinator
pub struct MapNewService<A, F, Response> { pub struct MapNewService<A, F, Res, Cfg> {
a: A, a: A,
f: F, f: F,
r: PhantomData<Response>, r: PhantomData<(Res, Cfg)>,
} }
impl<A, F, Response> MapNewService<A, F, Response> { impl<A, F, Res, Cfg> MapNewService<A, F, Res, Cfg> {
/// Create new `Map` new service instance /// Create new `Map` new service instance
pub fn new(a: A, f: F) -> Self pub fn new(a: A, f: F) -> Self
where where
A: NewService, A: NewService<Cfg>,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Res,
{ {
Self { Self {
a, a,
@@ -118,7 +118,7 @@ impl<A, F, Response> MapNewService<A, F, Response> {
} }
} }
impl<A, F, Response> Clone for MapNewService<A, F, Response> impl<A, F, Res, Cfg> Clone for MapNewService<A, F, Res, Cfg>
where where
A: Clone, A: Clone,
F: Clone, F: Clone,
@@ -132,49 +132,49 @@ where
} }
} }
impl<A, F, Response> NewService for MapNewService<A, F, Response> impl<A, F, Res, Cfg> NewService<Cfg> for MapNewService<A, F, Res, Cfg>
where where
A: NewService, A: NewService<Cfg>,
F: FnMut(A::Response) -> Response + Clone, F: FnMut(A::Response) -> Res + Clone,
{ {
type Request = A::Request; type Request = A::Request;
type Response = Response; type Response = Res;
type Error = A::Error; type Error = A::Error;
type Service = Map<A::Service, F, Response>; type Service = Map<A::Service, F, Res>;
type InitError = A::InitError; type InitError = A::InitError;
type Future = MapNewServiceFuture<A, F, Response>; type Future = MapNewServiceFuture<A, F, Res, Cfg>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &Cfg) -> Self::Future {
MapNewServiceFuture::new(self.a.new_service(), self.f.clone()) MapNewServiceFuture::new(self.a.new_service(cfg), self.f.clone())
} }
} }
pub struct MapNewServiceFuture<A, F, Response> pub struct MapNewServiceFuture<A, F, Res, Cfg>
where where
A: NewService, A: NewService<Cfg>,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Res,
{ {
fut: A::Future, fut: A::Future,
f: Option<F>, f: Option<F>,
} }
impl<A, F, Response> MapNewServiceFuture<A, F, Response> impl<A, F, Res, Cfg> MapNewServiceFuture<A, F, Res, Cfg>
where where
A: NewService, A: NewService<Cfg>,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Res,
{ {
fn new(fut: A::Future, f: F) -> Self { fn new(fut: A::Future, f: F) -> Self {
MapNewServiceFuture { f: Some(f), fut } MapNewServiceFuture { f: Some(f), fut }
} }
} }
impl<A, F, Response> Future for MapNewServiceFuture<A, F, Response> impl<A, F, Res, Cfg> Future for MapNewServiceFuture<A, F, Res, Cfg>
where where
A: NewService, A: NewService<Cfg>,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Res,
{ {
type Item = Map<A::Service, F, Response>; type Item = Map<A::Service, F, Res>;
type Error = A::InitError; type Error = A::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@@ -229,7 +229,7 @@ mod tests {
fn test_new_service() { fn test_new_service() {
let blank = || Ok::<_, ()>(Srv); let blank = || Ok::<_, ()>(Srv);
let new_srv = blank.into_new_service().map(|_| "ok"); let new_srv = blank.into_new_service().map(|_| "ok");
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() { if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
let res = srv.call(()).poll(); let res = srv.call(()).poll();
assert!(res.is_ok()); assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready("ok")); assert_eq!(res.unwrap(), Async::Ready("ok"));

View File

@@ -98,17 +98,17 @@ where
/// service's error. /// service's error.
/// ///
/// This is created by the `NewServiceExt::map_err` method. /// This is created by the `NewServiceExt::map_err` method.
pub struct MapErrNewService<A, F, E> { pub struct MapErrNewService<A, F, E, C> {
a: A, a: A,
f: F, f: F,
e: PhantomData<E>, e: PhantomData<(E, C)>,
} }
impl<A, F, E> MapErrNewService<A, F, E> { impl<A, F, E, C> MapErrNewService<A, F, E, C> {
/// Create new `MapErr` new service instance /// Create new `MapErr` new service instance
pub fn new(a: A, f: F) -> Self pub fn new(a: A, f: F) -> Self
where where
A: NewService, A: NewService<C>,
F: Fn(A::Error) -> E, F: Fn(A::Error) -> E,
{ {
Self { Self {
@@ -119,7 +119,7 @@ impl<A, F, E> MapErrNewService<A, F, E> {
} }
} }
impl<A, F, E> Clone for MapErrNewService<A, F, E> impl<A, F, E, C> Clone for MapErrNewService<A, F, E, C>
where where
A: Clone, A: Clone,
F: Clone, F: Clone,
@@ -133,9 +133,9 @@ where
} }
} }
impl<A, F, E> NewService for MapErrNewService<A, F, E> impl<A, F, E, C> NewService<C> for MapErrNewService<A, F, E, C>
where where
A: NewService, A: NewService<C>,
F: Fn(A::Error) -> E + Clone, F: Fn(A::Error) -> E + Clone,
{ {
type Request = A::Request; type Request = A::Request;
@@ -144,25 +144,25 @@ where
type Service = MapErr<A::Service, F, E>; type Service = MapErr<A::Service, F, E>;
type InitError = A::InitError; type InitError = A::InitError;
type Future = MapErrNewServiceFuture<A, F, E>; type Future = MapErrNewServiceFuture<A, F, E, C>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &C) -> Self::Future {
MapErrNewServiceFuture::new(self.a.new_service(), self.f.clone()) MapErrNewServiceFuture::new(self.a.new_service(cfg), self.f.clone())
} }
} }
pub struct MapErrNewServiceFuture<A, F, E> pub struct MapErrNewServiceFuture<A, F, E, C>
where where
A: NewService, A: NewService<C>,
F: Fn(A::Error) -> E, F: Fn(A::Error) -> E,
{ {
fut: A::Future, fut: A::Future,
f: F, f: F,
} }
impl<A, F, E> MapErrNewServiceFuture<A, F, E> impl<A, F, E, C> MapErrNewServiceFuture<A, F, E, C>
where where
A: NewService, A: NewService<C>,
F: Fn(A::Error) -> E, F: Fn(A::Error) -> E,
{ {
fn new(fut: A::Future, f: F) -> Self { fn new(fut: A::Future, f: F) -> Self {
@@ -170,9 +170,9 @@ where
} }
} }
impl<A, F, E> Future for MapErrNewServiceFuture<A, F, E> impl<A, F, E, C> Future for MapErrNewServiceFuture<A, F, E, C>
where where
A: NewService, A: NewService<C>,
F: Fn(A::Error) -> E + Clone, F: Fn(A::Error) -> E + Clone,
{ {
type Item = MapErr<A::Service, F, E>; type Item = MapErr<A::Service, F, E>;
@@ -231,7 +231,7 @@ mod tests {
fn test_new_service() { fn test_new_service() {
let blank = || Ok::<_, ()>(Srv); let blank = || Ok::<_, ()>(Srv);
let new_srv = blank.into_new_service().map_err(|_| "error"); let new_srv = blank.into_new_service().map_err(|_| "error");
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() { if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
let res = srv.call(()).poll(); let res = srv.call(()).poll();
assert!(res.is_err()); assert!(res.is_err());
assert_eq!(res.err().unwrap(), "error"); assert_eq!(res.err().unwrap(), "error");

View File

@@ -5,17 +5,17 @@ use futures::{Future, Poll};
use super::NewService; use super::NewService;
/// `MapInitErr` service combinator /// `MapInitErr` service combinator
pub struct MapInitErr<A, F, E> { pub struct MapInitErr<A, F, E, C> {
a: A, a: A,
f: F, f: F,
e: PhantomData<E>, e: PhantomData<(E, C)>,
} }
impl<A, F, E> MapInitErr<A, F, E> { impl<A, F, E, C> MapInitErr<A, F, E, C> {
/// Create new `MapInitErr` combinator /// Create new `MapInitErr` combinator
pub fn new(a: A, f: F) -> Self pub fn new(a: A, f: F) -> Self
where where
A: NewService, A: NewService<C>,
F: Fn(A::InitError) -> E, F: Fn(A::InitError) -> E,
{ {
Self { Self {
@@ -26,7 +26,7 @@ impl<A, F, E> MapInitErr<A, F, E> {
} }
} }
impl<A, F, E> Clone for MapInitErr<A, F, E> impl<A, F, E, C> Clone for MapInitErr<A, F, E, C>
where where
A: Clone, A: Clone,
F: Clone, F: Clone,
@@ -40,9 +40,9 @@ where
} }
} }
impl<A, F, E> NewService for MapInitErr<A, F, E> impl<A, F, E, C> NewService<C> for MapInitErr<A, F, E, C>
where where
A: NewService, A: NewService<C>,
F: Fn(A::InitError) -> E + Clone, F: Fn(A::InitError) -> E + Clone,
{ {
type Request = A::Request; type Request = A::Request;
@@ -51,25 +51,25 @@ where
type Service = A::Service; type Service = A::Service;
type InitError = E; type InitError = E;
type Future = MapInitErrFuture<A, F, E>; type Future = MapInitErrFuture<A, F, E, C>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &C) -> Self::Future {
MapInitErrFuture::new(self.a.new_service(), self.f.clone()) MapInitErrFuture::new(self.a.new_service(cfg), self.f.clone())
} }
} }
pub struct MapInitErrFuture<A, F, E> pub struct MapInitErrFuture<A, F, E, C>
where where
A: NewService, A: NewService<C>,
F: Fn(A::InitError) -> E, F: Fn(A::InitError) -> E,
{ {
f: F, f: F,
fut: A::Future, fut: A::Future,
} }
impl<A, F, E> MapInitErrFuture<A, F, E> impl<A, F, E, C> MapInitErrFuture<A, F, E, C>
where where
A: NewService, A: NewService<C>,
F: Fn(A::InitError) -> E, F: Fn(A::InitError) -> E,
{ {
fn new(fut: A::Future, f: F) -> Self { fn new(fut: A::Future, f: F) -> Self {
@@ -77,9 +77,9 @@ where
} }
} }
impl<A, F, E> Future for MapInitErrFuture<A, F, E> impl<A, F, E, C> Future for MapInitErrFuture<A, F, E, C>
where where
A: NewService, A: NewService<C>,
F: Fn(A::InitError) -> E, F: Fn(A::InitError) -> E,
{ {
type Item = A::Service; type Item = A::Service;

View File

@@ -1,3 +1,5 @@
use std::marker::PhantomData;
use futures::{try_ready, Async, Future, Poll}; use futures::{try_ready, Async, Future, Poll};
use super::{IntoNewService, NewService, Service}; use super::{IntoNewService, NewService, Service};
@@ -109,34 +111,38 @@ where
} }
/// `ThenNewService` new service combinator /// `ThenNewService` new service combinator
pub struct ThenNewService<A, B> { pub struct ThenNewService<A, B, C> {
a: A, a: A,
b: B, b: B,
_t: PhantomData<C>,
} }
impl<A, B> ThenNewService<A, B> { impl<A, B, C> ThenNewService<A, B, C> {
/// Create new `AndThen` combinator /// Create new `AndThen` combinator
pub fn new<F>(a: A, f: F) -> Self pub fn new<F>(a: A, f: F) -> Self
where where
A: NewService, A: NewService<C>,
B: NewService< B: NewService<
C,
Request = Result<A::Response, A::Error>, Request = Result<A::Response, A::Error>,
Error = A::Error, Error = A::Error,
InitError = A::InitError, InitError = A::InitError,
>, >,
F: IntoNewService<B>, F: IntoNewService<B, C>,
{ {
Self { Self {
a, a,
b: f.into_new_service(), b: f.into_new_service(),
_t: PhantomData,
} }
} }
} }
impl<A, B> NewService for ThenNewService<A, B> impl<A, B, C> NewService<C> for ThenNewService<A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService< B: NewService<
C,
Request = Result<A::Response, A::Error>, Request = Result<A::Response, A::Error>,
Error = A::Error, Error = A::Error,
InitError = A::InitError, InitError = A::InitError,
@@ -148,14 +154,14 @@ where
type Service = Then<A::Service, B::Service>; type Service = Then<A::Service, B::Service>;
type InitError = A::InitError; type InitError = A::InitError;
type Future = ThenNewServiceFuture<A, B>; type Future = ThenNewServiceFuture<A, B, C>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &C) -> Self::Future {
ThenNewServiceFuture::new(self.a.new_service(), self.b.new_service()) ThenNewServiceFuture::new(self.a.new_service(cfg), self.b.new_service(cfg))
} }
} }
impl<A, B> Clone for ThenNewService<A, B> impl<A, B, C> Clone for ThenNewService<A, B, C>
where where
A: Clone, A: Clone,
B: Clone, B: Clone,
@@ -164,14 +170,16 @@ where
Self { Self {
a: self.a.clone(), a: self.a.clone(),
b: self.b.clone(), b: self.b.clone(),
_t: PhantomData,
} }
} }
} }
pub struct ThenNewServiceFuture<A, B> pub struct ThenNewServiceFuture<A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService< B: NewService<
C,
Request = Result<A::Response, A::Error>, Request = Result<A::Response, A::Error>,
Error = A::Error, Error = A::Error,
InitError = A::InitError, InitError = A::InitError,
@@ -183,10 +191,11 @@ where
b: Option<B::Service>, b: Option<B::Service>,
} }
impl<A, B> ThenNewServiceFuture<A, B> impl<A, B, C> ThenNewServiceFuture<A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService< B: NewService<
C,
Request = Result<A::Response, A::Error>, Request = Result<A::Response, A::Error>,
Error = A::Error, Error = A::Error,
InitError = A::InitError, InitError = A::InitError,
@@ -202,10 +211,11 @@ where
} }
} }
impl<A, B> Future for ThenNewServiceFuture<A, B> impl<A, B, C> Future for ThenNewServiceFuture<A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService< B: NewService<
C,
Request = Result<A::Response, A::Error>, Request = Result<A::Response, A::Error>,
Error = A::Error, Error = A::Error,
InitError = A::InitError, InitError = A::InitError,
@@ -319,7 +329,7 @@ mod tests {
let cnt2 = cnt.clone(); let cnt2 = cnt.clone();
let blank = move || Ok::<_, ()>(Srv1(cnt2.clone())); let blank = move || Ok::<_, ()>(Srv1(cnt2.clone()));
let new_srv = blank.into_new_service().then(move || Ok(Srv2(cnt.clone()))); let new_srv = blank.into_new_service().then(move || Ok(Srv2(cnt.clone())));
if let Async::Ready(mut srv) = new_srv.clone().new_service().poll().unwrap() { if let Async::Ready(mut srv) = new_srv.clone().new_service(&()).poll().unwrap() {
let res = srv.call(Ok("srv1")).poll(); let res = srv.call(Ok("srv1")).poll();
assert!(res.is_ok()); assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv1", "ok"))); assert_eq!(res.unwrap(), Async::Ready(("srv1", "ok")));

View File

@@ -1,50 +1,16 @@
use futures::{Future, Poll}; use std::rc::Rc;
use std::sync::Arc;
use crate::transform_map_err::{TransformMapErr, TransformMapErrNewTransform}; use futures::{Async, Future, IntoFuture, Poll};
use crate::Service;
/// An asynchronous function for transforming service call result. use crate::transform_map_init_err::TransformMapInitErr;
pub trait Transform<Service> { use crate::{NewService, Service};
/// Requests handled by the service.
type Request;
/// Responses given by the service. /// `Transform` service factory.
type Response; ///
/// Transform factory creates service that wraps other services.
/// Errors produced by the service. /// `Config` is a service factory configuration type.
type Error; pub trait Transform<S> {
/// The future response value.
type Future: Future<Item = Self::Response, Error = Self::Error>;
/// Returns `Ready` when the service is able to process requests.
///
/// This method is similar to `Service::poll_ready` method.
fn poll_ready(&mut self) -> Poll<(), Self::Error>;
/// Process the request and apply it to provided service,
/// return the response asynchronously.
fn call(&mut self, request: Self::Request, service: &mut Service) -> Self::Future;
/// Map this transform's error to a different error, returning a new transform.
///
/// This function is similar to the `Result::map_err` where it will change
/// the error type of the underlying transform. This is useful for example to
/// ensure that services and transforms have the same error type.
///
/// Note that this function consumes the receiving transform and returns a
/// wrapped version of it.
fn map_err<F, E>(self, f: F) -> TransformMapErr<Self, Service, F, E>
where
Self: Sized,
F: Fn(Self::Error) -> E,
{
TransformMapErr::new(self, f)
}
}
/// `Transform` service factory
pub trait NewTransform<Service> {
/// Requests handled by the service. /// Requests handled by the service.
type Request; type Request;
@@ -55,8 +21,7 @@ pub trait NewTransform<Service> {
type Error; type Error;
/// The `TransformService` value created by this factory /// The `TransformService` value created by this factory
type Transform: Transform< type Transform: Service<
Service,
Request = Self::Request, Request = Self::Request,
Response = Self::Response, Response = Self::Response,
Error = Self::Error, Error = Self::Error,
@@ -69,58 +34,52 @@ pub trait NewTransform<Service> {
type Future: Future<Item = Self::Transform, Error = Self::InitError>; type Future: Future<Item = Self::Transform, Error = Self::InitError>;
/// Create and return a new service value asynchronously. /// Create and return a new service value asynchronously.
fn new_transform(&self) -> Self::Future; fn new_transform(&self, service: S) -> Self::Future;
/// Map this transforms's output to a different type, returning a new transform /// Map this service's factory init error to a different error,
/// of the resulting type. /// returning a new transform service factory.
fn map_err<F, E>(self, f: F) -> TransformMapErrNewTransform<Self, Service, F, E> fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, S, F, E>
where where
Self: Sized, Self: Sized,
F: Fn(Self::Error) -> E, F: Fn(Self::InitError) -> E,
{ {
TransformMapErrNewTransform::new(self, f) TransformMapInitErr::new(self, f)
} }
} }
impl<'a, T, S> Transform<S> for &'a mut T impl<T, S> Transform<S> for Rc<T>
where where
T: Transform<S> + 'a, T: Transform<S>,
S: Service<Error = T::Error>,
{ {
type Request = T::Request; type Request = T::Request;
type Response = T::Response; type Response = T::Response;
type Error = T::Error; type Error = T::Error;
type InitError = T::InitError;
type Transform = T::Transform;
type Future = T::Future; type Future = T::Future;
fn poll_ready(&mut self) -> Poll<(), T::Error> { fn new_transform(&self, service: S) -> T::Future {
(**self).poll_ready() self.as_ref().new_transform(service)
}
fn call(&mut self, request: Self::Request, service: &mut S) -> T::Future {
(**self).call(request, service)
} }
} }
impl<T, S> Transform<S> for Box<T> impl<T, S> Transform<S> for Arc<T>
where where
T: Transform<S> + ?Sized, T: Transform<S>,
S: Service<Error = T::Error>,
{ {
type Request = T::Request; type Request = T::Request;
type Response = T::Response; type Response = T::Response;
type Error = T::Error; type Error = T::Error;
type InitError = T::InitError;
type Transform = T::Transform;
type Future = T::Future; type Future = T::Future;
fn poll_ready(&mut self) -> Poll<(), S::Error> { fn new_transform(&self, service: S) -> T::Future {
(**self).poll_ready() self.as_ref().new_transform(service)
}
fn call(&mut self, request: Self::Request, service: &mut S) -> T::Future {
(**self).call(request, service)
} }
} }
/// Trait for types that can be converted to a `TransformService` /// Trait for types that can be converted to a *transform service*
pub trait IntoTransform<T, S> pub trait IntoTransform<T, S>
where where
T: Transform<S>, T: Transform<S>,
@@ -129,15 +88,6 @@ where
fn into_transform(self) -> T; fn into_transform(self) -> T;
} }
/// Trait for types that can be converted to a TransfromNewService
pub trait IntoNewTransform<T, S>
where
T: NewTransform<S>,
{
/// Convert to an `TranformNewService`
fn into_new_transform(self) -> T;
}
impl<T, S> IntoTransform<T, S> for T impl<T, S> IntoTransform<T, S> for T
where where
T: Transform<S>, T: Transform<S>,
@@ -147,11 +97,79 @@ where
} }
} }
impl<T, S> IntoNewTransform<T, S> for T /// `Apply` transform new service
#[derive(Clone)]
pub struct ApplyTransform<T, A, C> {
a: A,
t: Rc<T>,
_t: std::marker::PhantomData<C>,
}
impl<T, A, C> ApplyTransform<T, A, C>
where where
T: NewTransform<S>, A: NewService<C>,
T: Transform<A::Service, Error = A::Error, InitError = A::InitError>,
{ {
fn into_new_transform(self) -> T { /// Create new `ApplyNewService` new service instance
self pub fn new<F: IntoTransform<T, A::Service>>(t: F, a: A) -> Self {
Self {
a,
t: Rc::new(t.into_transform()),
_t: std::marker::PhantomData,
}
}
}
impl<T, A, C> NewService<C> for ApplyTransform<T, A, C>
where
A: NewService<C>,
T: Transform<A::Service, Error = A::Error, InitError = A::InitError>,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type Service = T::Transform;
type InitError = T::InitError;
type Future = ApplyTransformFuture<T, A, C>;
fn new_service(&self, cfg: &C) -> Self::Future {
ApplyTransformFuture {
t_cell: self.t.clone(),
fut_a: self.a.new_service(cfg).into_future(),
fut_t: None,
}
}
}
pub struct ApplyTransformFuture<T, A, C>
where
A: NewService<C>,
T: Transform<A::Service, Error = A::Error, InitError = A::InitError>,
{
fut_a: A::Future,
fut_t: Option<<T::Future as IntoFuture>::Future>,
t_cell: Rc<T>,
}
impl<T, A, C> Future for ApplyTransformFuture<T, A, C>
where
A: NewService<C>,
T: Transform<A::Service, Error = A::Error, InitError = A::InitError>,
{
type Item = T::Transform;
type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if self.fut_t.is_none() {
if let Async::Ready(service) = self.fut_a.poll()? {
self.fut_t = Some(self.t_cell.new_transform(service).into_future());
}
}
if let Some(ref mut fut) = self.fut_t {
fut.poll()
} else {
Ok(Async::NotReady)
}
} }
} }

View File

@@ -1,188 +0,0 @@
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)
}
}
}

View File

@@ -0,0 +1,94 @@
use std::marker::PhantomData;
use futures::{Future, Poll};
use super::Transform;
/// NewTransform for the `map_init_err` combinator, changing the type of a new
/// transform's error.
///
/// This is created by the `NewTransform::map_init_err` method.
pub struct TransformMapInitErr<T, S, F, E> {
t: T,
f: F,
e: PhantomData<(S, E)>,
}
impl<T, S, F, E> TransformMapInitErr<T, S, F, E> {
/// Create new `MapInitErr` new transform instance
pub fn new(t: T, f: F) -> Self
where
T: Transform<S>,
F: Fn(T::InitError) -> E,
{
Self {
t,
f,
e: PhantomData,
}
}
}
impl<T, S, F, E> Clone for TransformMapInitErr<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> Transform<S> for TransformMapInitErr<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::InitError) -> E + Clone,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type Transform = T::Transform;
type InitError = E;
type Future = TransformMapInitErrFuture<T, S, F, E>;
fn new_transform(&self, service: S) -> Self::Future {
TransformMapInitErrFuture::new(self.t.new_transform(service), self.f.clone())
}
}
pub struct TransformMapInitErrFuture<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::InitError) -> E,
{
fut: T::Future,
f: F,
}
impl<T, S, F, E> TransformMapInitErrFuture<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::InitError) -> E,
{
fn new(fut: T::Future, f: F) -> Self {
TransformMapInitErrFuture { f, fut }
}
}
impl<T, S, F, E> Future for TransformMapInitErrFuture<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::InitError) -> E + Clone,
{
type Item = T::Transform;
type Error = E;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.fut.poll().map_err(&self.f)
}
}

View File

@@ -34,11 +34,10 @@ rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
[dependencies] [dependencies]
actix-rt = "0.1.0" actix-rt = "0.1.0"
actix-server = "0.2.0" #actix-server = "0.3.0"
actix-server = { path="../actix-server" }
log = "0.4" log = "0.4"
# io
net2 = "0.2" net2 = "0.2"
futures = "0.1" futures = "0.1"
tokio-tcp = "0.1" tokio-tcp = "0.1"

View File

@@ -1,5 +1,56 @@
# Changes # Changes
## [0.4.0] - 2019-03-xx
* Upgrade actix-service
## [0.3.2] - 2019-03-04
### Changed
* Use IntoFuture for new services
## [0.3.1] - 2019-03-04
### Changed
* Use new type of transform trait
## [0.3.0] - 2019-03-02
### Changed
* Use new `NewService` trait
* BoxedNewService` and `BoxedService` types moved to actix-service crate.
## [0.2.4] - 2019-02-21
### Changed
* Custom `BoxedNewService` implementation.
## [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 ## [0.2.1] - 2019-02-06
### Added ### Added

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-utils" name = "actix-utils"
version = "0.2.1" version = "0.3.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix utils - various actix net related services" description = "Actix utils - various actix net related services"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -11,19 +11,20 @@ categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0" license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"] exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018" edition = "2018"
workspace = "../" workspace = ".."
[lib] [lib]
name = "actix_utils" name = "actix_utils"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-service = "0.2.1" #actix-service = "0.3.2"
actix-service = { path="../actix-service" }
actix-codec = "0.1.0" actix-codec = "0.1.0"
bytes = "0.4" bytes = "0.4"
futures = "0.1" futures = "0.1.24"
tokio-timer = "0.2.8" tokio-timer = "0.2.8"
tokio-current-thread = "0.1" tokio-current-thread = "0.1.4"
log = "0.4" log = "0.4"
[dev-dependencies] [dev-dependencies]

View File

@@ -1,6 +1,6 @@
//! Contains `Either` service and related types and functions. //! Contains `Either` service and related types and functions.
use actix_service::{NewService, Service}; use actix_service::{NewService, Service};
use futures::{future, try_ready, Async, Future, Poll}; use futures::{future, try_ready, Async, Future, IntoFuture, Poll};
/// Combine two different service types into a single type. /// Combine two different service types into a single type.
/// ///
@@ -53,10 +53,11 @@ pub enum Either<A, B> {
} }
impl<A, B> Either<A, B> { impl<A, B> Either<A, B> {
pub fn new_a(srv: A) -> Self pub fn new_a<C>(srv: A) -> Self
where where
A: NewService, A: NewService<C>,
B: NewService< B: NewService<
C,
Request = A::Request, Request = A::Request,
Response = A::Response, Response = A::Response,
Error = A::Error, Error = A::Error,
@@ -66,10 +67,11 @@ impl<A, B> Either<A, B> {
Either::A(srv) Either::A(srv)
} }
pub fn new_b(srv: B) -> Self pub fn new_b<C>(srv: B) -> Self
where where
A: NewService, A: NewService<C>,
B: NewService< B: NewService<
C,
Request = A::Request, Request = A::Request,
Response = A::Response, Response = A::Response,
Error = A::Error, Error = A::Error,
@@ -80,10 +82,11 @@ impl<A, B> Either<A, B> {
} }
} }
impl<A, B> NewService for Either<A, B> impl<A, B, C> NewService<C> for Either<A, B>
where where
A: NewService, A: NewService<C>,
B: NewService< B: NewService<
C,
Request = A::Request, Request = A::Request,
Response = A::Response, Response = A::Response,
Error = A::Error, Error = A::Error,
@@ -95,12 +98,12 @@ where
type Error = A::Error; type Error = A::Error;
type InitError = A::InitError; type InitError = A::InitError;
type Service = EitherService<A::Service, B::Service>; type Service = EitherService<A::Service, B::Service>;
type Future = EitherNewService<A, B>; type Future = EitherNewService<A, B, C>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &C) -> Self::Future {
match self { match self {
Either::A(ref inner) => EitherNewService::A(inner.new_service()), Either::A(ref inner) => EitherNewService::A(inner.new_service(cfg)),
Either::B(ref inner) => EitherNewService::B(inner.new_service()), Either::B(ref inner) => EitherNewService::B(inner.new_service(cfg)),
} }
} }
} }
@@ -115,15 +118,16 @@ impl<A: Clone, B: Clone> Clone for Either<A, B> {
} }
#[doc(hidden)] #[doc(hidden)]
pub enum EitherNewService<A: NewService, B: NewService> { pub enum EitherNewService<A: NewService<C>, B: NewService<C>, C> {
A(A::Future), A(<A::Future as IntoFuture>::Future),
B(B::Future), B(<B::Future as IntoFuture>::Future),
} }
impl<A, B> Future for EitherNewService<A, B> impl<A, B, C> Future for EitherNewService<A, B, C>
where where
A: NewService, A: NewService<C>,
B: NewService< B: NewService<
C,
Request = A::Request, Request = A::Request,
Response = A::Response, Response = A::Response,
Error = A::Error, Error = A::Error,

View File

@@ -7,7 +7,7 @@ use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_service::{IntoNewService, IntoService, NewService, Service}; use actix_service::{IntoNewService, IntoService, NewService, Service};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::task::AtomicTask; use futures::task::AtomicTask;
use futures::{Async, Future, Poll, Sink, Stream}; use futures::{Async, Future, IntoFuture, Poll, Sink, Stream};
use log::debug; use log::debug;
use crate::cell::Cell; use crate::cell::Cell;
@@ -15,14 +15,15 @@ use crate::cell::Cell;
type Request<U> = <U as Decoder>::Item; type Request<U> = <U as Decoder>::Item;
type Response<U> = <U as Encoder>::Item; type Response<U> = <U as Encoder>::Item;
pub struct FramedNewService<S, T, U> { pub struct FramedNewService<S, T, U, C> {
factory: S, factory: S,
_t: PhantomData<(T, U)>, _t: PhantomData<(T, U, C)>,
} }
impl<S, T, U> FramedNewService<S, T, U> impl<S, T, U, C> FramedNewService<S, T, U, C>
where where
S: NewService<Request = Request<U>, Response = Response<U>>, C: Clone,
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static, S::Error: 'static,
<S::Service as Service>::Future: 'static, <S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
@@ -30,7 +31,7 @@ where
<U as Encoder>::Item: 'static, <U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug, <U as Encoder>::Error: std::fmt::Debug,
{ {
pub fn new<F1: IntoNewService<S>>(factory: F1) -> Self { pub fn new<F1: IntoNewService<S, C>>(factory: F1) -> Self {
Self { Self {
factory: factory.into_new_service(), factory: factory.into_new_service(),
_t: PhantomData, _t: PhantomData,
@@ -38,7 +39,7 @@ where
} }
} }
impl<S, T, U> Clone for FramedNewService<S, T, U> impl<S, T, U, C> Clone for FramedNewService<S, T, U, C>
where where
S: Clone, S: Clone,
{ {
@@ -50,9 +51,10 @@ where
} }
} }
impl<S, T, U> NewService for FramedNewService<S, T, U> impl<S, T, U, C> NewService<C> for FramedNewService<S, T, U, C>
where where
S: NewService<Request = Request<U>, Response = Response<U>> + Clone, C: Clone,
S: NewService<C, Request = Request<U>, Response = Response<U>> + Clone,
S::Error: 'static, S::Error: 'static,
<S::Service as Service>::Future: 'static, <S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
@@ -64,48 +66,53 @@ where
type Response = FramedTransport<S::Service, T, U>; type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError; type Error = S::InitError;
type InitError = S::InitError; type InitError = S::InitError;
type Service = FramedService<S, T, U>; type Service = FramedService<S, T, U, C>;
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &C) -> Self::Future {
ok(FramedService { ok(FramedService {
factory: self.factory.clone(), factory: self.factory.clone(),
config: cfg.clone(),
_t: PhantomData, _t: PhantomData,
}) })
} }
} }
pub struct FramedService<S, T, U> { pub struct FramedService<S, T, U, C> {
factory: S, factory: S,
config: C,
_t: PhantomData<(T, U)>, _t: PhantomData<(T, U)>,
} }
impl<S, T, U> Clone for FramedService<S, T, U> impl<S, T, U, C> Clone for FramedService<S, T, U, C>
where where
S: Clone, S: Clone,
C: Clone,
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Self { Self {
factory: self.factory.clone(), factory: self.factory.clone(),
config: self.config.clone(),
_t: PhantomData, _t: PhantomData,
} }
} }
} }
impl<S, T, U> Service for FramedService<S, T, U> impl<S, T, U, C> Service for FramedService<S, T, U, C>
where where
S: NewService<Request = Request<U>, Response = Response<U>>, S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static, S::Error: 'static,
<S::Service as Service>::Future: 'static, <S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
U: Decoder + Encoder, U: Decoder + Encoder,
<U as Encoder>::Item: 'static, <U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug, <U as Encoder>::Error: std::fmt::Debug,
C: Clone,
{ {
type Request = Framed<T, U>; type Request = Framed<T, U>;
type Response = FramedTransport<S::Service, T, U>; type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError; type Error = S::InitError;
type Future = FramedServiceResponseFuture<S, T, U>; type Future = FramedServiceResponseFuture<S, T, U, C>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(())) Ok(Async::Ready(()))
@@ -113,17 +120,16 @@ where
fn call(&mut self, req: Framed<T, U>) -> Self::Future { fn call(&mut self, req: Framed<T, U>) -> Self::Future {
FramedServiceResponseFuture { FramedServiceResponseFuture {
fut: self.factory.new_service(), fut: self.factory.new_service(&self.config),
framed: Some(req), framed: Some(req),
} }
} }
} }
#[doc(hidden)] #[doc(hidden)]
pub struct FramedServiceResponseFuture<S, T, U> pub struct FramedServiceResponseFuture<S, T, U, C>
where where
S: NewService<Request = Request<U>, Response = Response<U>>, S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static, S::Error: 'static,
<S::Service as Service>::Future: 'static, <S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
@@ -131,13 +137,13 @@ where
<U as Encoder>::Item: 'static, <U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug, <U as Encoder>::Error: std::fmt::Debug,
{ {
fut: S::Future, fut: <S::Future as IntoFuture>::Future,
framed: Option<Framed<T, U>>, framed: Option<Framed<T, U>>,
} }
impl<S, T, U> Future for FramedServiceResponseFuture<S, T, U> impl<S, T, U, C> Future for FramedServiceResponseFuture<S, T, U, C>
where where
S: NewService<Request = Request<U>, Response = Response<U>>, S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static, S::Error: 'static,
<S::Service as Service>::Future: 'static, <S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
@@ -402,7 +408,7 @@ where
} }
} }
impl<T, U, F> NewService for IntoFramed<T, U, F> impl<T, C, U, F> NewService<C> for IntoFramed<T, U, F>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static, F: Fn() -> U + Send + Clone + 'static,
@@ -415,7 +421,7 @@ where
type Service = IntoFramedService<T, U, F>; type Service = IntoFramedService<T, U, F>;
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_service(&self, _: &C) -> Self::Future {
ok(IntoFramedService { ok(IntoFramedService {
factory: self.factory.clone(), factory: self.factory.clone(),
_t: PhantomData, _t: PhantomData,

View File

@@ -1,4 +1,4 @@
use actix_service::{NewTransform, Service, Transform}; use actix_service::{Service, Transform, Void};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
@@ -24,32 +24,34 @@ impl Default for InFlight {
} }
} }
impl<T: Service> NewTransform<T> for InFlight { impl<S: Service> Transform<S> for InFlight {
type Request = T::Request; type Request = S::Request;
type Response = T::Response; type Response = S::Response;
type Error = T::Error; type Error = S::Error;
type InitError = (); type InitError = Void;
type Transform = InFlightService; type Transform = InFlightService<S>;
type Future = FutureResult<Self::Transform, Self::InitError>; type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self) -> Self::Future { fn new_transform(&self, service: S) -> Self::Future {
ok(InFlightService::new(self.max_inflight)) ok(InFlightService::new(self.max_inflight, service))
} }
} }
pub struct InFlightService { pub struct InFlightService<S> {
count: Counter, count: Counter,
service: S,
} }
impl InFlightService { impl<S> InFlightService<S> {
pub fn new(max: usize) -> Self { pub fn new(max: usize, service: S) -> Self {
Self { Self {
service,
count: Counter::new(max), count: Counter::new(max),
} }
} }
} }
impl<T> Transform<T> for InFlightService impl<T> Service for InFlightService<T>
where where
T: Service, T: Service,
{ {
@@ -59,6 +61,8 @@ where
type Future = InFlightServiceResponse<T>; type Future = InFlightServiceResponse<T>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready()?;
if !self.count.available() { if !self.count.available() {
log::trace!("InFlight limit exceeded"); log::trace!("InFlight limit exceeded");
Ok(Async::NotReady) Ok(Async::NotReady)
@@ -67,9 +71,9 @@ where
} }
} }
fn call(&mut self, req: T::Request, service: &mut T) -> Self::Future { fn call(&mut self, req: T::Request) -> Self::Future {
InFlightServiceResponse { InFlightServiceResponse {
fut: service.call(req), fut: self.service.call(req),
_guard: self.count.get(), _guard: self.count.get(),
} }
} }
@@ -98,7 +102,8 @@ mod tests {
use std::time::Duration; use std::time::Duration;
use super::*; use super::*;
use actix_service::{Blank, BlankNewService, NewService, Service, ServiceExt}; use actix_service::blank::{Blank, BlankNewService};
use actix_service::{NewService, Service, ServiceExt};
struct SleepService(Duration); struct SleepService(Duration);
@@ -121,7 +126,8 @@ mod tests {
fn test_transform() { fn test_transform() {
let wait_time = Duration::from_millis(50); let wait_time = Duration::from_millis(50);
let _ = actix_rt::System::new("test").block_on(lazy(|| { let _ = actix_rt::System::new("test").block_on(lazy(|| {
let mut srv = Blank::new().apply(InFlightService::new(1), SleepService(wait_time)); let mut srv =
Blank::new().and_then(InFlightService::new(1, SleepService(wait_time)));
assert_eq!(srv.poll_ready(), Ok(Async::Ready(()))); assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
let mut res = srv.call(()); let mut res = srv.call(());
@@ -142,7 +148,7 @@ mod tests {
let srv = let srv =
BlankNewService::new().apply(InFlight::new(1), || Ok(SleepService(wait_time))); BlankNewService::new().apply(InFlight::new(1), || Ok(SleepService(wait_time)));
if let Async::Ready(mut srv) = srv.new_service().poll().unwrap() { if let Async::Ready(mut srv) = srv.new_service(&()).poll().unwrap() {
assert_eq!(srv.poll_ready(), Ok(Async::Ready(()))); assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
let mut res = srv.call(()); let mut res = srv.call(());

View File

@@ -1,13 +1,12 @@
use std::marker::PhantomData; use std::marker::PhantomData;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use actix_service::{NewService, Service}; use actix_service::{NewService, Service, Void};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
use tokio_timer::Delay; use tokio_timer::Delay;
use super::time::{LowResTime, LowResTimeService}; use super::time::{LowResTime, LowResTimeService};
use super::Never;
pub struct KeepAlive<R, E, F> { pub struct KeepAlive<R, E, F> {
f: F, f: F,
@@ -44,18 +43,18 @@ where
} }
} }
impl<R, E, F> NewService for KeepAlive<R, E, F> impl<R, E, F> NewService<()> for KeepAlive<R, E, F>
where where
F: Fn() -> E + Clone, F: Fn() -> E + Clone,
{ {
type Request = R; type Request = R;
type Response = R; type Response = R;
type Error = E; type Error = E;
type InitError = Never; type InitError = Void;
type Service = KeepAliveService<R, E, F>; type Service = KeepAliveService<R, E, F>;
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
ok(KeepAliveService::new( ok(KeepAliveService::new(
self.ka, self.ka,
self.time.timer(), self.time.timer(),

View File

@@ -10,6 +10,3 @@ pub mod order;
pub mod stream; pub mod stream;
pub mod time; pub mod time;
pub mod timeout; pub mod timeout;
#[derive(Copy, Clone, Debug)]
pub enum Never {}

View File

@@ -3,7 +3,7 @@ use std::fmt;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::rc::Rc; use std::rc::Rc;
use actix_service::{NewTransform, Service, Transform}; use actix_service::{Service, Transform, Void};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::task::AtomicTask; use futures::task::AtomicTask;
use futures::unsync::oneshot; use futures::unsync::oneshot;
@@ -37,6 +37,15 @@ impl<E: fmt::Debug> fmt::Debug for InOrderError<E> {
} }
} }
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, /// InOrder - The service will yield responses as they become available,
/// in the order that their originating requests were submitted to the service. /// in the order that their originating requests were submitted to the service.
pub struct InOrder<S> { pub struct InOrder<S> {
@@ -54,13 +63,8 @@ where
Self { _t: PhantomData } Self { _t: PhantomData }
} }
pub fn service() -> impl Transform< pub fn service(service: S) -> InOrderService<S> {
S, InOrderService::new(service)
Request = S::Request,
Response = S::Response,
Error = InOrderError<S::Error>,
> {
InOrderService::new()
} }
} }
@@ -76,7 +80,7 @@ where
} }
} }
impl<S> NewTransform<S> for InOrder<S> impl<S> Transform<S> for InOrder<S>
where where
S: Service, S: Service,
S::Response: 'static, S::Response: 'static,
@@ -86,16 +90,17 @@ where
type Request = S::Request; type Request = S::Request;
type Response = S::Response; type Response = S::Response;
type Error = InOrderError<S::Error>; type Error = InOrderError<S::Error>;
type InitError = (); type InitError = Void;
type Transform = InOrderService<S>; type Transform = InOrderService<S>;
type Future = FutureResult<Self::Transform, Self::InitError>; type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self) -> Self::Future { fn new_transform(&self, service: S) -> Self::Future {
ok(InOrderService::new()) ok(InOrderService::new(service))
} }
} }
pub struct InOrderService<S: Service> { pub struct InOrderService<S: Service> {
service: S,
task: Rc<AtomicTask>, task: Rc<AtomicTask>,
acks: VecDeque<Record<S::Response, S::Error>>, acks: VecDeque<Record<S::Response, S::Error>>,
} }
@@ -107,27 +112,16 @@ where
S::Future: 'static, S::Future: 'static,
S::Error: 'static, S::Error: 'static,
{ {
pub fn new() -> Self { pub fn new(service: S) -> Self {
Self { Self {
service,
acks: VecDeque::new(), acks: VecDeque::new(),
task: Rc::new(AtomicTask::new()), task: Rc::new(AtomicTask::new()),
} }
} }
} }
impl<S> Default for InOrderService<S> impl<S> Service 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 where
S: Service, S: Service,
S::Response: 'static, S::Response: 'static,
@@ -140,8 +134,12 @@ where
type Future = InOrderServiceResponse<S>; type Future = InOrderServiceResponse<S>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
// poll_ready could be called from different task
self.task.register(); self.task.register();
// check nested service
self.service.poll_ready().map_err(InOrderError::Service)?;
// check acks // check acks
while !self.acks.is_empty() { while !self.acks.is_empty() {
let rec = self.acks.front_mut().unwrap(); let rec = self.acks.front_mut().unwrap();
@@ -158,13 +156,13 @@ where
Ok(Async::Ready(())) Ok(Async::Ready(()))
} }
fn call(&mut self, request: S::Request, service: &mut S) -> Self::Future { fn call(&mut self, request: S::Request) -> Self::Future {
let (tx1, rx1) = oneshot::channel(); let (tx1, rx1) = oneshot::channel();
let (tx2, rx2) = oneshot::channel(); let (tx2, rx2) = oneshot::channel();
self.acks.push_back(Record { rx: rx1, tx: tx2 }); self.acks.push_back(Record { rx: rx1, tx: tx2 });
let task = self.task.clone(); let task = self.task.clone();
tokio_current_thread::spawn(service.call(request).then(move |res| { tokio_current_thread::spawn(self.service.call(request).then(move |res| {
task.notify(); task.notify();
let _ = tx1.send(res); let _ = tx1.send(res);
Ok(()) Ok(())
@@ -201,7 +199,8 @@ mod tests {
use std::time::Duration; use std::time::Duration;
use super::*; use super::*;
use actix_service::{Blank, Service, ServiceExt}; use actix_service::blank::Blank;
use actix_service::{Service, ServiceExt};
struct Srv; struct Srv;
@@ -247,7 +246,7 @@ mod tests {
let rx3 = rx3; let rx3 = rx3;
let tx_stop = tx_stop; let tx_stop = tx_stop;
let _ = actix_rt::System::new("test").block_on(lazy(move || { let _ = actix_rt::System::new("test").block_on(lazy(move || {
let mut srv = Blank::new().apply(InOrderService::new(), Srv); let mut srv = Blank::new().and_then(InOrderService::new(Srv));
let res1 = srv.call(rx1); let res1 = srv.call(rx1);
let res2 = srv.call(rx2); let res2 = srv.call(rx2);

View File

@@ -29,20 +29,21 @@ where
} }
} }
pub struct StreamNewService<S, T, E> { pub struct StreamNewService<S, T, E, C> {
factory: Rc<T>, factory: Rc<T>,
_t: PhantomData<(S, E)>, _t: PhantomData<(S, E, C)>,
} }
impl<S, T, E> StreamNewService<S, T, E> impl<S, T, E, C> StreamNewService<S, T, E, C>
where where
C: Clone,
S: IntoStream, S: IntoStream,
T: NewService<Request = Request<S>, Response = (), Error = E, InitError = E>, T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static, T::Future: 'static,
T::Service: 'static, T::Service: 'static,
<T::Service as Service>::Future: 'static, <T::Service as Service>::Future: 'static,
{ {
pub fn new<F: IntoNewService<T>>(factory: F) -> Self { pub fn new<F: IntoNewService<T, C>>(factory: F) -> Self {
Self { Self {
factory: Rc::new(factory.into_new_service()), factory: Rc::new(factory.into_new_service()),
_t: PhantomData, _t: PhantomData,
@@ -50,7 +51,7 @@ where
} }
} }
impl<S, T, E> Clone for StreamNewService<S, T, E> { impl<S, T, E, C> Clone for StreamNewService<S, T, E, C> {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Self { Self {
factory: self.factory.clone(), factory: self.factory.clone(),
@@ -59,10 +60,11 @@ impl<S, T, E> Clone for StreamNewService<S, T, E> {
} }
} }
impl<S, T, E> NewService for StreamNewService<S, T, E> impl<S, T, E, C> NewService<C> for StreamNewService<S, T, E, C>
where where
C: Clone,
S: IntoStream + 'static, S: IntoStream + 'static,
T: NewService<Request = Request<S>, Response = (), Error = E, InitError = E>, T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static, T::Future: 'static,
T::Service: 'static, T::Service: 'static,
<T::Service as Service>::Future: 'static, <T::Service as Service>::Future: 'static,
@@ -71,29 +73,32 @@ where
type Response = (); type Response = ();
type Error = E; type Error = E;
type InitError = E; type InitError = E;
type Service = StreamService<S, T, E>; type Service = StreamService<S, T, E, C>;
type Future = FutureResult<Self::Service, E>; type Future = FutureResult<Self::Service, E>;
fn new_service(&self) -> Self::Future { fn new_service(&self, cfg: &C) -> Self::Future {
ok(StreamService { ok(StreamService {
factory: self.factory.clone(), factory: self.factory.clone(),
config: cfg.clone(),
_t: PhantomData, _t: PhantomData,
}) })
} }
} }
pub struct StreamService<S, T, E> { pub struct StreamService<S, T, E, C = ()> {
factory: Rc<T>, factory: Rc<T>,
config: C,
_t: PhantomData<(S, E)>, _t: PhantomData<(S, E)>,
} }
impl<S, T, E> Service for StreamService<S, T, E> impl<S, T, E, C> Service for StreamService<S, T, E, C>
where where
S: IntoStream + 'static, S: IntoStream + 'static,
T: NewService<Request = Request<S>, Response = (), Error = E, InitError = E>, T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static, T::Future: 'static,
T::Service: 'static, T::Service: 'static,
<T::Service as Service>::Future: 'static, <T::Service as Service>::Future: 'static,
C: Clone,
{ {
type Request = S; type Request = S;
type Response = (); type Response = ();
@@ -107,7 +112,7 @@ where
fn call(&mut self, req: S) -> Self::Future { fn call(&mut self, req: S) -> Self::Future {
Box::new( Box::new(
self.factory self.factory
.new_service() .new_service(&self.config)
.and_then(move |srv| StreamDispatcher::new(req, srv)), .and_then(move |srv| StreamDispatcher::new(req, srv)),
) )
} }
@@ -227,7 +232,7 @@ impl<T> Clone for TakeItem<T> {
} }
} }
impl<T: Stream> NewService for TakeItem<T> { impl<T: Stream, C> NewService<C> for TakeItem<T> {
type Request = T; type Request = T;
type Response = (Option<T::Item>, T); type Response = (Option<T::Item>, T);
type Error = T::Error; type Error = T::Error;
@@ -235,7 +240,7 @@ impl<T: Stream> NewService for TakeItem<T> {
type Service = TakeItemService<T>; type Service = TakeItemService<T>;
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_service(&self, _: &C) -> Self::Future {
ok(TakeItemService { _t: PhantomData }) ok(TakeItemService { _t: PhantomData })
} }
} }

View File

@@ -1,12 +1,11 @@
use std::time::{self, Duration, Instant}; use std::time::{self, Duration, Instant};
use actix_service::{NewService, Service}; use actix_service::{NewService, Service, Void};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
use tokio_timer::sleep; use tokio_timer::sleep;
use super::cell::Cell; use super::cell::Cell;
use super::Never;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct LowResTime(Cell<Inner>); pub struct LowResTime(Cell<Inner>);
@@ -42,15 +41,15 @@ impl Default for LowResTime {
} }
} }
impl NewService for LowResTime { impl NewService<()> for LowResTime {
type Request = (); type Request = ();
type Response = Instant; type Response = Instant;
type Error = Never; type Error = Void;
type InitError = Never; type InitError = Void;
type Service = LowResTimeService; type Service = LowResTimeService;
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_service(&self, _: &()) -> Self::Future {
ok(self.timer()) ok(self.timer())
} }
} }
@@ -92,7 +91,7 @@ impl LowResTimeService {
impl Service for LowResTimeService { impl Service for LowResTimeService {
type Request = (); type Request = ();
type Response = Instant; type Response = Instant;
type Error = Never; type Error = Void;
type Future = FutureResult<Self::Response, Self::Error>; type Future = FutureResult<Self::Response, Self::Error>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {

View File

@@ -6,7 +6,7 @@ use std::fmt;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::time::Duration; use std::time::Duration;
use actix_service::{NewTransform, Service, Transform}; use actix_service::{Service, Transform};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
use tokio_timer::{clock, Delay}; use tokio_timer::{clock, Delay};
@@ -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> { impl<E: PartialEq> PartialEq for TimeoutError<E> {
fn eq(&self, other: &TimeoutError<E>) -> bool { fn eq(&self, other: &TimeoutError<E>) -> bool {
match self { match self {
@@ -71,7 +80,7 @@ impl<E> Clone for Timeout<E> {
} }
} }
impl<S, E> NewTransform<S> for Timeout<E> impl<S, E> Transform<S> for Timeout<E>
where where
S: Service, S: Service,
{ {
@@ -79,11 +88,12 @@ where
type Response = S::Response; type Response = S::Response;
type Error = TimeoutError<S::Error>; type Error = TimeoutError<S::Error>;
type InitError = E; type InitError = E;
type Transform = TimeoutService; type Transform = TimeoutService<S>;
type Future = FutureResult<Self::Transform, Self::InitError>; type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self) -> Self::Future { fn new_transform(&self, service: S) -> Self::Future {
ok(TimeoutService { ok(TimeoutService {
service,
timeout: self.timeout, timeout: self.timeout,
}) })
} }
@@ -91,17 +101,18 @@ where
/// Applies a timeout to requests. /// Applies a timeout to requests.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct TimeoutService { pub struct TimeoutService<S> {
service: S,
timeout: Duration, timeout: Duration,
} }
impl TimeoutService { impl<S> TimeoutService<S> {
pub fn new(timeout: Duration) -> Self { pub fn new(timeout: Duration, service: S) -> Self {
TimeoutService { timeout } TimeoutService { service, timeout }
} }
} }
impl<S> Transform<S> for TimeoutService impl<S> Service for TimeoutService<S>
where where
S: Service, S: Service,
{ {
@@ -111,12 +122,12 @@ where
type Future = TimeoutServiceResponse<S>; type Future = TimeoutServiceResponse<S>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(())) self.service.poll_ready().map_err(TimeoutError::Service)
} }
fn call(&mut self, request: S::Request, service: &mut S) -> Self::Future { fn call(&mut self, request: S::Request) -> Self::Future {
TimeoutServiceResponse { TimeoutServiceResponse {
fut: service.call(request), fut: self.service.call(request),
sleep: Delay::new(clock::now() + self.timeout), sleep: Delay::new(clock::now() + self.timeout),
} }
} }
@@ -161,7 +172,8 @@ mod tests {
use std::time::Duration; use std::time::Duration;
use super::*; use super::*;
use actix_service::{Blank, BlankNewService, NewService, Service, ServiceExt}; use actix_service::blank::{Blank, BlankNewService};
use actix_service::{NewService, Service, ServiceExt};
struct SleepService(Duration); struct SleepService(Duration);
@@ -187,7 +199,7 @@ mod tests {
let res = actix_rt::System::new("test").block_on(lazy(|| { let res = actix_rt::System::new("test").block_on(lazy(|| {
let mut timeout = Blank::default() let mut timeout = Blank::default()
.apply(TimeoutService::new(resolution), SleepService(wait_time)); .and_then(TimeoutService::new(resolution, SleepService(wait_time)));
timeout.call(()) timeout.call(())
})); }));
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
@@ -200,7 +212,7 @@ mod tests {
let res = actix_rt::System::new("test").block_on(lazy(|| { let res = actix_rt::System::new("test").block_on(lazy(|| {
let mut timeout = Blank::default() let mut timeout = Blank::default()
.apply(TimeoutService::new(resolution), SleepService(wait_time)); .and_then(TimeoutService::new(resolution, SleepService(wait_time)));
timeout.call(()) timeout.call(())
})); }));
assert_eq!(res, Err(TimeoutError::Timeout)); assert_eq!(res, Err(TimeoutError::Timeout));
@@ -212,9 +224,9 @@ mod tests {
let wait_time = Duration::from_millis(150); let wait_time = Duration::from_millis(150);
let res = actix_rt::System::new("test").block_on(lazy(|| { 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))); .apply(Timeout::new(resolution), || Ok(SleepService(wait_time)));
if let Async::Ready(mut to) = timeout.new_service().poll().unwrap() { if let Async::Ready(mut to) = timeout.new_service(&()).poll().unwrap() {
to.call(()) to.call(())
} else { } else {
panic!() panic!()

View File

@@ -5,12 +5,12 @@ use std::sync::{
atomic::{AtomicUsize, Ordering}, atomic::{AtomicUsize, Ordering},
Arc, Arc,
}; };
use std::{env, fmt}; use std::{env, fmt, io};
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_rt::System; use actix_rt::System;
use actix_server::Server; use actix_server::Server;
use actix_service::{IntoNewService, NewService}; use actix_service::{fn_service, NewService};
use futures::{future, Future}; use futures::{future, Future};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
use tokio_openssl::SslAcceptorExt; use tokio_openssl::SslAcceptorExt;
@@ -23,7 +23,7 @@ fn logger<T: AsyncRead + AsyncWrite + fmt::Debug>(
future::ok(stream) future::ok(stream)
} }
fn main() { fn main() -> io::Result<()> {
env::set_var("RUST_LOG", "actix_net=trace"); env::set_var("RUST_LOG", "actix_net=trace");
env_logger::init(); env_logger::init();
@@ -54,16 +54,14 @@ fn main() {
let acceptor = acceptor.clone(); let acceptor = acceptor.clone();
// service for converting incoming TcpStream to a SslStream<TcpStream> // service for converting incoming TcpStream to a SslStream<TcpStream>
(move |stream| { fn_service(move |stream: tokio_tcp::TcpStream| {
SslAcceptorExt::accept_async(&acceptor, stream) SslAcceptorExt::accept_async(&acceptor, stream)
.map_err(|e| println!("Openssl error: {}", e)) .map_err(|e| println!("Openssl error: {}", e))
}) })
// convert closure to a `NewService`
.into_new_service()
// .and_then() combinator uses other service to convert incoming `Request` to a // .and_then() combinator uses other service to convert incoming `Request` to a
// `Response` and then uses that response as an input for next // `Response` and then uses that response as an input for next
// service. in this case, on success we use `logger` service // service. in this case, on success we use `logger` service
.and_then(logger) .and_then(fn_service(logger))
// Next service counts number of connections // Next service counts number of connections
.and_then(move |_| { .and_then(move |_| {
let num = num.fetch_add(1, Ordering::Relaxed); let num = num.fetch_add(1, Ordering::Relaxed);
@@ -75,5 +73,5 @@ fn main() {
.unwrap() .unwrap()
.start(); .start();
sys.run(); sys.run()
} }

View File

@@ -1,13 +1,13 @@
use std::io;
use std::sync::{ use std::sync::{
atomic::{AtomicUsize, Ordering}, atomic::{AtomicUsize, Ordering},
Arc, Arc,
}; };
use actix_codec::{AsyncRead, AsyncWrite};
use actix_rt::System; use actix_rt::System;
use actix_server::{ssl, Server}; use actix_server::{ssl, Server};
use actix_service::NewService; use actix_service::NewService;
use futures::{future, Future}; use futures::future;
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
#[derive(Debug)] #[derive(Debug)]
@@ -15,16 +15,7 @@ struct ServiceState {
num: Arc<AtomicUsize>, num: Arc<AtomicUsize>,
} }
fn service<T: AsyncRead + AsyncWrite>( fn main() -> io::Result<()> {
st: &mut ServiceState,
_: T,
) -> impl Future<Item = (), Error = ()> {
let num = st.num.fetch_add(1, Ordering::Relaxed);
println!("got ssl connection {:?}", num);
future::ok(())
}
fn main() {
let sys = System::new("test"); let sys = System::new("test");
// load ssl keys // load ssl keys
@@ -53,9 +44,8 @@ fn main() {
println!("got ssl connection {:?}", num); println!("got ssl connection {:?}", num);
future::ok(()) future::ok(())
}) })
}) })?
.unwrap()
.start(); .start();
sys.run(); sys.run()
} }

View File

@@ -9,6 +9,10 @@ pub use self::path::Path;
pub use self::resource::ResourceDef; pub use self::resource::ResourceDef;
pub use self::router::{ResourceInfo, Router, RouterBuilder}; pub use self::router::{ResourceInfo, Router, RouterBuilder};
pub trait Resource<T: ResourcePath> {
fn resource_path(&mut self) -> &mut Path<T>;
}
pub trait ResourcePath { pub trait ResourcePath {
fn path(&self) -> &str; fn path(&self) -> &str;
} }

View File

@@ -4,7 +4,7 @@ use std::rc::Rc;
use serde::de; use serde::de;
use crate::de::PathDeserializer; use crate::de::PathDeserializer;
use crate::ResourcePath; use crate::{Resource, ResourcePath};
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub(crate) enum PathItem { pub(crate) enum PathItem {
@@ -202,3 +202,38 @@ impl<T: ResourcePath> Index<usize> for Path<T> {
} }
} }
} }
impl<T: ResourcePath> Resource<T> for Path<T> {
fn resource_path(&mut self) -> &mut Self {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "http")]
#[test]
fn test_get_param_by_name() {
use crate::Url;
use http::{HttpTryFrom, Uri};
let mut params = Path::new(Url::new(Uri::try_from("/").unwrap()));
params.add_static("item1", "path");
params.add_static("item2", "http%3A%2F%2Flocalhost%3A80%2Ffoo");
assert_eq!(params.get("item0"), None);
assert_eq!(params.get_decoded("item0"), None);
assert_eq!(params.get("item1"), Some("path"));
assert_eq!(params.get_decoded("item1").unwrap().to_owned(), "path");
assert_eq!(
params.get("item2"),
Some("http%3A%2F%2Flocalhost%3A80%2Ffoo")
);
assert_eq!(
params.get_decoded("item2").unwrap().to_owned(),
"http://localhost:80/foo"
);
}
}

View File

@@ -14,26 +14,13 @@ const MAX_DYNAMIC_SEGMENTS: usize = 16;
/// Resource definition can contain only 16 dynamic segments /// Resource definition can contain only 16 dynamic segments
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ResourceDef { pub struct ResourceDef {
id: u16,
tp: PatternType, tp: PatternType,
rtp: ResourceType,
name: String, name: String,
pattern: String, pattern: String,
elements: Vec<PatternElement>, 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)] #[derive(Debug, Clone, PartialEq)]
enum PatternElement { enum PatternElement {
Str(String), Str(String),
@@ -64,13 +51,25 @@ impl ResourceDef {
ResourceDef::with_prefix(path, true) ResourceDef::with_prefix(path, true)
} }
/// Construct external resource def /// Parse path pattern and create new `Pattern` instance.
/// Inserts `/` to begging of the pattern.
/// ///
/// Panics if path pattern is malformed. ///
pub fn external(path: &str) -> Self { /// Use `prefix` type instead of `static`.
let mut resource = ResourceDef::with_prefix(path, false); ///
resource.rtp = ResourceType::External; /// Panics if path regex pattern is wrong.
resource pub fn root_prefix(path: &str) -> Self {
ResourceDef::with_prefix(&insert_slash(path), true)
}
/// Resource id
pub fn id(&self) -> u16 {
self.id
}
/// Set resource id
pub fn set_id(&mut self, id: u16) {
self.id = id;
} }
/// Parse path pattern and create new `Pattern` instance with custom prefix /// Parse path pattern and create new `Pattern` instance with custom prefix
@@ -98,12 +97,22 @@ impl ResourceDef {
ResourceDef { ResourceDef {
tp, tp,
elements, elements,
id: 0,
name: String::new(), name: String::new(),
rtp: ResourceType::Normal,
pattern: path.to_owned(), pattern: path.to_owned(),
} }
} }
/// Resource pattern name
pub fn name(&self) -> &str {
&self.name
}
/// Mutable reference to a name of a resource definition.
pub fn name_mut(&mut self) -> &mut String {
&mut self.name
}
/// Path pattern of the resource /// Path pattern of the resource
pub fn pattern(&self) -> &str { pub fn pattern(&self) -> &str {
&self.pattern &self.pattern
@@ -118,6 +127,57 @@ impl ResourceDef {
} }
} }
/// Is prefix path a match against this resource?
pub fn is_prefix_match(&self, path: &str) -> Option<usize> {
let plen = path.len();
let path = if path.is_empty() { "/" } else { path };
match self.tp {
PatternType::Static(ref s) => {
if s == path {
Some(plen)
} else {
None
}
}
PatternType::Dynamic(ref re, _, len) => {
if let Some(captures) = re.captures(path) {
let mut pos = 0;
let mut passed = false;
for capture in captures.iter() {
if let Some(ref m) = capture {
if !passed {
passed = true;
continue;
}
pos = m.end();
}
}
Some(pos + len)
} else {
None
}
}
PatternType::Prefix(ref s) => {
let len = if path == s {
s.len()
} else if path.starts_with(s)
&& (s.ends_with('/') || path.split_at(s.len()).1.starts_with('/'))
{
if s.ends_with('/') {
s.len() - 1
} else {
s.len()
}
} else {
return None;
};
Some(min(plen, len))
}
}
}
/// Is the given path and parameters a match against this pattern? /// Is the given path and parameters a match against this pattern?
pub fn match_path<T: ResourcePath>(&self, path: &mut Path<T>) -> bool { pub fn match_path<T: ResourcePath>(&self, path: &mut Path<T>) -> bool {
match self.tp { match self.tp {
@@ -180,34 +240,32 @@ impl ResourceDef {
} }
} }
// /// Build resource path. /// Build resource path from elements. Returns `true` on success.
// pub fn resource_path<U, I>( pub fn resource_path<U, I>(&self, path: &mut String, elements: &mut U) -> bool
// &self, path: &mut String, elements: &mut U, where
// ) -> Result<(), UrlGenerationError> U: Iterator<Item = I>,
// where I: AsRef<str>,
// U: Iterator<Item = I>, {
// I: AsRef<str>, match self.tp {
// { PatternType::Prefix(ref p) => path.push_str(p),
// match self.tp { PatternType::Static(ref p) => path.push_str(p),
// PatternType::Prefix(ref p) => path.push_str(p), PatternType::Dynamic(..) => {
// PatternType::Static(ref p) => path.push_str(p), for el in &self.elements {
// PatternType::Dynamic(..) => { match *el {
// for el in &self.elements { PatternElement::Str(ref s) => path.push_str(s),
// match *el { PatternElement::Var(_) => {
// PatternElement::Str(ref s) => path.push_str(s), if let Some(val) = elements.next() {
// PatternElement::Var(_) => { path.push_str(val.as_ref())
// if let Some(val) = elements.next() { } else {
// path.push_str(val.as_ref()) return false;
// } else { }
// return Err(UrlGenerationError::NotEnoughElements); }
// } }
// } }
// } }
// } };
// } true
// }; }
// Ok(())
// }
fn parse_param(pattern: &str) -> (PatternElement, String, &str) { fn parse_param(pattern: &str) -> (PatternElement, String, &str) {
const DEFAULT_PATTERN: &str = "[^/]+"; const DEFAULT_PATTERN: &str = "[^/]+";
@@ -313,6 +371,14 @@ impl From<String> for ResourceDef {
} }
} }
pub(crate) fn insert_slash(path: &str) -> String {
let mut path = path.to_owned();
if !path.is_empty() && !path.starts_with('/') {
path.insert(0, '/');
};
path
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -330,6 +396,11 @@ mod tests {
assert!(!re.is_match("/name/")); assert!(!re.is_match("/name/"));
assert!(!re.is_match("/name~")); assert!(!re.is_match("/name~"));
assert_eq!(re.is_prefix_match("/name"), Some(5));
assert_eq!(re.is_prefix_match("/name1"), None);
assert_eq!(re.is_prefix_match("/name/"), None);
assert_eq!(re.is_prefix_match("/name~"), None);
let re = ResourceDef::new("/name/"); let re = ResourceDef::new("/name/");
assert!(re.is_match("/name/")); assert!(re.is_match("/name/"));
assert!(!re.is_match("/name")); assert!(!re.is_match("/name"));
@@ -404,10 +475,21 @@ mod tests {
assert!(re.is_match("/name1")); assert!(re.is_match("/name1"));
assert!(re.is_match("/name~")); assert!(re.is_match("/name~"));
assert_eq!(re.is_prefix_match("/name"), Some(5));
assert_eq!(re.is_prefix_match("/name/"), Some(5));
assert_eq!(re.is_prefix_match("/name/test/test"), Some(5));
assert_eq!(re.is_prefix_match("/name1"), None);
assert_eq!(re.is_prefix_match("/name~"), None);
let re = ResourceDef::prefix("/name/"); let re = ResourceDef::prefix("/name/");
assert!(re.is_match("/name/")); assert!(re.is_match("/name/"));
assert!(re.is_match("/name/gs")); assert!(re.is_match("/name/gs"));
assert!(!re.is_match("/name")); assert!(!re.is_match("/name"));
let re = ResourceDef::root_prefix("name/");
assert!(re.is_match("/name/"));
assert!(re.is_match("/name/gs"));
assert!(!re.is_match("/name"));
} }
#[test] #[test]
@@ -417,6 +499,10 @@ mod tests {
assert!(re.is_match("/name/gs")); assert!(re.is_match("/name/gs"));
assert!(!re.is_match("/name")); assert!(!re.is_match("/name"));
assert_eq!(re.is_prefix_match("/name/"), Some(6));
assert_eq!(re.is_prefix_match("/name/gs"), Some(6));
assert_eq!(re.is_prefix_match("/name"), None);
let mut path = Path::new("/test2/"); let mut path = Path::new("/test2/");
assert!(re.match_path(&mut path)); assert!(re.match_path(&mut path));
assert_eq!(&path["name"], "test2"); assert_eq!(&path["name"], "test2");

View File

@@ -1,145 +1,97 @@
use std::collections::HashMap; use crate::{Resource, ResourceDef, ResourcePath};
use std::rc::Rc;
use crate::path::Path;
use crate::resource::ResourceDef;
use crate::ResourcePath;
#[derive(Debug, Copy, Clone, PartialEq)] #[derive(Debug, Copy, Clone, PartialEq)]
pub(crate) enum ResourceId { pub struct ResourceId(pub u16);
Default,
Normal(u16),
}
/// Information about current resource /// Information about current resource
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct ResourceInfo { pub struct ResourceInfo {
rmap: Rc<ResourceMap>,
resource: ResourceId, resource: ResourceId,
} }
#[derive(Default, Debug)]
pub(crate) struct ResourceMap {
root: Option<ResourceDef>,
named: HashMap<String, ResourceDef>,
patterns: Vec<ResourceDef>,
}
/// Resource router. /// Resource router.
pub struct Router<T> { pub struct Router<T, U = ()>(Vec<(ResourceDef, T, Option<U>)>);
rmap: Rc<ResourceMap>,
named: HashMap<String, ResourceDef>,
resources: Vec<T>,
}
impl<T> Router<T> { impl<T, U> Router<T, U> {
pub fn build() -> RouterBuilder<T> { pub fn build() -> RouterBuilder<T, U> {
RouterBuilder { RouterBuilder {
rmap: ResourceMap::default(),
named: HashMap::new(),
resources: Vec::new(), resources: Vec::new(),
} }
} }
pub fn recognize<U: ResourcePath>(&self, path: &mut Path<U>) -> Option<(&T, ResourceInfo)> { pub fn recognize<R, P>(&self, path: &mut R) -> Option<(&T, ResourceId)>
if !path.path().is_empty() { where
for (idx, resource) in self.rmap.patterns.iter().enumerate() { R: Resource<P>,
if resource.match_path(path) { P: ResourcePath,
let info = ResourceInfo { {
rmap: self.rmap.clone(), for item in self.0.iter() {
resource: ResourceId::Normal(idx as u16), if item.0.match_path(path.resource_path()) {
}; return Some((&item.1, ResourceId(item.0.id())));
return Some((&self.resources[idx], info));
}
} }
} }
None None
} }
pub fn recognize_mut<U: ResourcePath>( pub fn recognize_mut<R, P>(&mut self, res: &mut R) -> Option<(&mut T, ResourceId)>
where
R: Resource<P>,
P: ResourcePath,
{
for item in self.0.iter_mut() {
if item.0.match_path(res.resource_path()) {
return Some((&mut item.1, ResourceId(item.0.id())));
}
}
None
}
pub fn recognize_mut_checked<R, P, F>(
&mut self, &mut self,
path: &mut Path<U>, res: &mut R,
) -> Option<(&mut T, ResourceInfo)> { check: F,
if !path.path().is_empty() { ) -> Option<(&mut T, ResourceId)>
for (idx, resource) in self.rmap.patterns.iter().enumerate() { where
if resource.match_path(path) { F: Fn(&R, &Option<U>) -> bool,
let info = ResourceInfo { R: Resource<P>,
rmap: self.rmap.clone(), P: ResourcePath,
resource: ResourceId::Normal(idx as u16), {
}; for item in self.0.iter_mut() {
return Some((&mut self.resources[idx], info)); if item.0.match_path(res.resource_path()) && check(res, &item.2) {
} return Some((&mut item.1, ResourceId(item.0.id())));
} }
} }
None None
} }
} }
impl<'a, T> IntoIterator for &'a Router<T> { pub struct RouterBuilder<T, U = ()> {
type Item = &'a T; resources: Vec<(ResourceDef, T, Option<U>)>,
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> { impl<T, U> RouterBuilder<T, U> {
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: ResourceDef) {
self.patterns.push(pattern);
}
fn register_named(&mut self, name: String, pattern: ResourceDef) {
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, ResourceDef>,
resources: Vec<T>,
}
impl<T> RouterBuilder<T> {
/// Register resource for specified path. /// Register resource for specified path.
pub fn path(&mut self, path: &str, resource: T) { pub fn path(&mut self, path: &str, resource: T) -> &mut (ResourceDef, T, Option<U>) {
self.rmap.register(ResourceDef::new(path)); self.resources
self.resources.push(resource); .push((ResourceDef::new(path), resource, None));
self.resources.last_mut().unwrap()
} }
/// Register resource for specified path prefix. /// Register resource for specified path prefix.
pub fn prefix(&mut self, prefix: &str, resource: T) { pub fn prefix(&mut self, prefix: &str, resource: T) -> &mut (ResourceDef, T, Option<U>) {
self.rmap.register(ResourceDef::prefix(prefix)); self.resources
self.resources.push(resource); .push((ResourceDef::prefix(prefix), resource, None));
self.resources.last_mut().unwrap()
} }
/// Register resource for ResourceDef /// Register resource for ResourceDef
pub fn rdef(&mut self, rdef: ResourceDef, resource: T) { pub fn rdef(&mut self, rdef: ResourceDef, resource: T) -> &mut (ResourceDef, T, Option<U>) {
self.rmap.register(rdef); self.resources.push((rdef, resource, None));
self.resources.push(resource); self.resources.last_mut().unwrap()
} }
/// Finish configuration and create router instance. /// Finish configuration and create router instance.
pub fn finish(self) -> Router<T> { pub fn finish(self) -> Router<T, U> {
Router { Router(self.resources)
rmap: Rc::new(self.rmap),
named: self.named,
resources: self.resources,
}
} }
} }
@@ -151,14 +103,14 @@ mod tests {
#[test] #[test]
fn test_recognizer_1() { fn test_recognizer_1() {
let mut router = Router::<usize>::build(); let mut router = Router::<usize>::build();
router.path("/name", 10); router.path("/name", 10).0.set_id(0);
router.path("/name/{val}", 11); router.path("/name/{val}", 11).0.set_id(1);
router.path("/name/{val}/index.html", 12); router.path("/name/{val}/index.html", 12).0.set_id(2);
router.path("/file/{file}.{ext}", 13); router.path("/file/{file}.{ext}", 13).0.set_id(3);
router.path("/v{val}/{val2}/index.html", 14); router.path("/v{val}/{val2}/index.html", 14).0.set_id(4);
router.path("/v/{tail:.*}", 15); router.path("/v/{tail:.*}", 15).0.set_id(5);
router.path("/test2/{test}.html", 16); router.path("/test2/{test}.html", 16).0.set_id(6);
router.path("/{test}/index.html", 17); router.path("/{test}/index.html", 17).0.set_id(7);
let mut router = router.finish(); let mut router = router.finish();
let mut path = Path::new("/unknown"); let mut path = Path::new("/unknown");
@@ -167,52 +119,52 @@ mod tests {
let mut path = Path::new("/name"); let mut path = Path::new("/name");
let (h, info) = router.recognize_mut(&mut path).unwrap(); let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 10); assert_eq!(*h, 10);
assert_eq!(info.resource, ResourceId::Normal(0)); assert_eq!(info, ResourceId(0));
assert!(path.is_empty()); assert!(path.is_empty());
let mut path = Path::new("/name/value"); let mut path = Path::new("/name/value");
let (h, info) = router.recognize_mut(&mut path).unwrap(); let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 11); assert_eq!(*h, 11);
assert_eq!(info.resource, ResourceId::Normal(1)); assert_eq!(info, ResourceId(1));
assert_eq!(path.get("val").unwrap(), "value"); assert_eq!(path.get("val").unwrap(), "value");
assert_eq!(&path["val"], "value"); assert_eq!(&path["val"], "value");
let mut path = Path::new("/name/value2/index.html"); let mut path = Path::new("/name/value2/index.html");
let (h, info) = router.recognize_mut(&mut path).unwrap(); let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 12); assert_eq!(*h, 12);
assert_eq!(info.resource, ResourceId::Normal(2)); assert_eq!(info, ResourceId(2));
assert_eq!(path.get("val").unwrap(), "value2"); assert_eq!(path.get("val").unwrap(), "value2");
let mut path = Path::new("/file/file.gz"); let mut path = Path::new("/file/file.gz");
let (h, info) = router.recognize_mut(&mut path).unwrap(); let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 13); assert_eq!(*h, 13);
assert_eq!(info.resource, ResourceId::Normal(3)); assert_eq!(info, ResourceId(3));
assert_eq!(path.get("file").unwrap(), "file"); assert_eq!(path.get("file").unwrap(), "file");
assert_eq!(path.get("ext").unwrap(), "gz"); assert_eq!(path.get("ext").unwrap(), "gz");
let mut path = Path::new("/vtest/ttt/index.html"); let mut path = Path::new("/vtest/ttt/index.html");
let (h, info) = router.recognize_mut(&mut path).unwrap(); let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 14); assert_eq!(*h, 14);
assert_eq!(info.resource, ResourceId::Normal(4)); assert_eq!(info, ResourceId(4));
assert_eq!(path.get("val").unwrap(), "test"); assert_eq!(path.get("val").unwrap(), "test");
assert_eq!(path.get("val2").unwrap(), "ttt"); assert_eq!(path.get("val2").unwrap(), "ttt");
let mut path = Path::new("/v/blah-blah/index.html"); let mut path = Path::new("/v/blah-blah/index.html");
let (h, info) = router.recognize_mut(&mut path).unwrap(); let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 15); assert_eq!(*h, 15);
assert_eq!(info.resource, ResourceId::Normal(5)); assert_eq!(info, ResourceId(5));
assert_eq!(path.get("tail").unwrap(), "blah-blah/index.html"); assert_eq!(path.get("tail").unwrap(), "blah-blah/index.html");
let mut path = Path::new("/test2/index.html"); let mut path = Path::new("/test2/index.html");
let (h, info) = router.recognize_mut(&mut path).unwrap(); let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 16); assert_eq!(*h, 16);
assert_eq!(info.resource, ResourceId::Normal(6)); assert_eq!(info, ResourceId(6));
assert_eq!(path.get("test").unwrap(), "index"); assert_eq!(path.get("test").unwrap(), "index");
let mut path = Path::new("/bbb/index.html"); let mut path = Path::new("/bbb/index.html");
let (h, info) = router.recognize_mut(&mut path).unwrap(); let (h, info) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 17); assert_eq!(*h, 17);
assert_eq!(info.resource, ResourceId::Normal(7)); assert_eq!(info, ResourceId(7));
assert_eq!(path.get("test").unwrap(), "bbb"); assert_eq!(path.get("test").unwrap(), "bbb");
} }
@@ -235,8 +187,8 @@ mod tests {
#[test] #[test]
fn test_recognizer_with_prefix() { fn test_recognizer_with_prefix() {
let mut router = Router::<usize>::build(); let mut router = Router::<usize>::build();
router.path("/name", 10); router.path("/name", 10).0.set_id(0);
router.path("/name/{val}", 11); router.path("/name/{val}", 11).0.set_id(1);
let mut router = router.finish(); let mut router = router.finish();
let mut path = Path::new("/name"); let mut path = Path::new("/name");
@@ -250,9 +202,9 @@ mod tests {
let mut path = Path::new("/test/name/value"); let mut path = Path::new("/test/name/value");
path.skip(5); path.skip(5);
let (h, info) = router.recognize_mut(&mut path).unwrap(); let (h, id) = router.recognize_mut(&mut path).unwrap();
assert_eq!(*h, 11); assert_eq!(*h, 11);
assert_eq!(info.resource, ResourceId::Normal(1)); assert_eq!(id, ResourceId(1));
assert_eq!(path.get("val").unwrap(), "value"); assert_eq!(path.get("val").unwrap(), "value");
assert_eq!(&path["val"], "value"); assert_eq!(&path["val"], "value");
@@ -281,134 +233,4 @@ mod tests {
assert_eq!(*h, 11); assert_eq!(*h, 11);
assert_eq!(&path["val"], "ttt"); 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"
// );
// }
// }
} }