mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-12 08:47:05 +02:00
Compare commits
59 Commits
codec-0.1.
...
service-v0
Author | SHA1 | Date | |
---|---|---|---|
|
158482cd2f | ||
|
7051888289 | ||
|
0caa47fc47 | ||
|
6d1cbb2d2f | ||
|
ca289ddf7f | ||
|
ad9a197916 | ||
|
c1b183e1ce | ||
|
87bc3dacd9 | ||
|
0156f479a0 | ||
|
139fa3b9a2 | ||
|
a14f612382 | ||
|
059e2ad042 | ||
|
fdf2a6f422 | ||
|
fc2631c852 | ||
|
d51b210ae7 | ||
|
0a6cded975 | ||
|
14e3933d8b | ||
|
837504c10f | ||
|
802d808aca | ||
|
7712de3d8e | ||
|
f1d0d5f6f9 | ||
|
a76fcaf4d8 | ||
|
a2134035d6 | ||
|
5f8599faf1 | ||
|
f0776fca94 | ||
|
c7676df697 | ||
|
ecf7a11a20 | ||
|
686958fe0c | ||
|
49ade171f6 | ||
|
0a2a520c35 | ||
|
b0c37dfc87 | ||
|
91e28a4312 | ||
|
508dce8bf1 | ||
|
8ed1099a2e | ||
|
83544bd971 | ||
|
76c317e0b2 | ||
|
3b314e4c8c | ||
|
ae27b87641 | ||
|
fc2dcadc7a | ||
|
54f62b5035 | ||
|
d3208bf7a8 | ||
|
21507d3da1 | ||
|
b9d8a215b4 | ||
|
51c4dfe5cb | ||
|
a60112c71e | ||
|
bd814d6f80 | ||
|
a4e0c71baa | ||
|
b9ea445e70 | ||
|
ba2901269d | ||
|
5cbc29306a | ||
|
810fa869ae | ||
|
33cd51aabf | ||
|
629ed05f82 | ||
|
5e8ae210f7 | ||
|
3add90628f | ||
|
02ab804e0b | ||
|
feac0b43d9 | ||
|
1441355d4f | ||
|
7c5afc09a6 |
@@ -22,15 +22,17 @@ members = [
|
||||
"actix-server",
|
||||
"actix-server-config",
|
||||
"actix-test-server",
|
||||
"actix-threadpool",
|
||||
"actix-tower",
|
||||
"actix-utils",
|
||||
"router",
|
||||
]
|
||||
|
||||
[dev-dependencies]
|
||||
actix-service = "0.3.3"
|
||||
actix-service = "0.4.0"
|
||||
actix-codec = "0.1.1"
|
||||
actix-rt = "0.2.0"
|
||||
actix-server = { path="actix-server", features=["ssl"] }
|
||||
actix-server = { version="0.5.0", features=["ssl"] }
|
||||
env_logger = "0.6"
|
||||
futures = "0.1.25"
|
||||
openssl = "0.10"
|
||||
|
1
actix-codec/LICENSE-APACHE
Symbolic link
1
actix-codec/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-codec/LICENSE-MIT
Symbolic link
1
actix-codec/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -1,5 +1,47 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
### Changed
|
||||
|
||||
* Upgrade to actix-service 0.4
|
||||
|
||||
|
||||
## [0.1.5] - 2019-04-19
|
||||
|
||||
### Added
|
||||
|
||||
* `Connect::set_addr()`
|
||||
|
||||
### Changed
|
||||
|
||||
* Use trust-dns-resolver 0.11.0
|
||||
|
||||
|
||||
## [0.1.4] - 2019-04-12
|
||||
|
||||
### Changed
|
||||
|
||||
* Do not start default resolver immediately for default connector.
|
||||
|
||||
|
||||
## [0.1.3] - 2019-04-11
|
||||
|
||||
### Changed
|
||||
|
||||
* Start trust-dns default resolver on first use
|
||||
|
||||
## [0.1.2] - 2019-04-04
|
||||
|
||||
### Added
|
||||
|
||||
* Log error if dns system config could not be loaded.
|
||||
|
||||
### Changed
|
||||
|
||||
* Rename connect Connector to TcpConnector #10
|
||||
|
||||
|
||||
## [0.1.1] - 2019-03-15
|
||||
|
||||
### Fixed
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-connect"
|
||||
version = "0.1.1"
|
||||
version = "0.2.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix Connector - tcp connector service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -30,17 +30,17 @@ ssl = ["openssl", "tokio-openssl"]
|
||||
uri = ["http"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.3.4"
|
||||
actix-codec = "0.1.1"
|
||||
actix-utils = "0.3.4"
|
||||
actix-service = "0.4.0"
|
||||
actix-codec = "0.1.2"
|
||||
actix-utils = "0.4.0"
|
||||
derive_more = "0.14.0"
|
||||
either = "1.5.1"
|
||||
either = "1.5.2"
|
||||
futures = "0.1.25"
|
||||
http = { version = "0.1.16", optional = true }
|
||||
http = { version = "0.1.17", optional = true }
|
||||
log = "0.4"
|
||||
tokio-tcp = "0.1.3"
|
||||
tokio-current-thread = "0.1.5"
|
||||
trust-dns-resolver = { version="0.11.0-alpha.2", default-features = false }
|
||||
trust-dns-resolver = { version="0.11.0", default-features = false }
|
||||
|
||||
# openssl
|
||||
openssl = { version="0.10", optional = true }
|
||||
@@ -48,8 +48,5 @@ tokio-openssl = { version="0.3", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
bytes = "0.4"
|
||||
actix-connect = { path=".", features=["ssl"] }
|
||||
actix-test-server = { version="0.2.0", features=["ssl"] }
|
||||
actix-test-server = { version="0.2.2", features=["ssl"] }
|
||||
actix-server-config = "0.1.0"
|
||||
actix-utils = "0.3.4"
|
||||
tokio-tcp = "0.1"
|
1
actix-connect/LICENSE-APACHE
Symbolic link
1
actix-connect/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-connect/LICENSE-MIT
Symbolic link
1
actix-connect/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -69,6 +69,14 @@ impl<T: Address> Connect<T> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Use address.
|
||||
pub fn set_addr(mut self, addr: Option<SocketAddr>) -> Self {
|
||||
if let Some(addr) = addr {
|
||||
self.addr = Some(Either::Left(addr));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Host name
|
||||
pub fn host(&self) -> &str {
|
||||
self.req.host()
|
||||
|
@@ -12,54 +12,55 @@ use super::error::ConnectError;
|
||||
|
||||
/// Tcp connector service factory
|
||||
#[derive(Debug)]
|
||||
pub struct ConnectorFactory<T>(PhantomData<T>);
|
||||
pub struct TcpConnectorFactory<T>(PhantomData<T>);
|
||||
|
||||
impl<T> ConnectorFactory<T> {
|
||||
impl<T> TcpConnectorFactory<T> {
|
||||
pub fn new() -> Self {
|
||||
ConnectorFactory(PhantomData)
|
||||
TcpConnectorFactory(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for ConnectorFactory<T> {
|
||||
impl<T> Clone for TcpConnectorFactory<T> {
|
||||
fn clone(&self) -> Self {
|
||||
ConnectorFactory(PhantomData)
|
||||
TcpConnectorFactory(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> NewService for ConnectorFactory<T> {
|
||||
impl<T: Address> NewService for TcpConnectorFactory<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
type Service = Connector<T>;
|
||||
type Config = ();
|
||||
type Service = TcpConnector<T>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(Connector(PhantomData))
|
||||
ok(TcpConnector(PhantomData))
|
||||
}
|
||||
}
|
||||
|
||||
/// Tcp connector service
|
||||
#[derive(Debug)]
|
||||
pub struct Connector<T>(PhantomData<T>);
|
||||
pub struct TcpConnector<T>(PhantomData<T>);
|
||||
|
||||
impl<T> Connector<T> {
|
||||
impl<T> TcpConnector<T> {
|
||||
pub fn new() -> Self {
|
||||
Connector(PhantomData)
|
||||
TcpConnector(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for Connector<T> {
|
||||
impl<T> Clone for TcpConnector<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Connector(PhantomData)
|
||||
TcpConnector(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> Service for Connector<T> {
|
||||
impl<T: Address> Service for TcpConnector<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
type Future = Either<ConnectorResponse<T>, FutureResult<Self::Response, Self::Error>>;
|
||||
type Future = Either<TcpConnectorResponse<T>, FutureResult<Self::Response, Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
@@ -70,7 +71,7 @@ impl<T: Address> Service for Connector<T> {
|
||||
let Connect { req, addr, .. } = req;
|
||||
|
||||
if let Some(addr) = addr {
|
||||
Either::A(ConnectorResponse::new(req, port, addr))
|
||||
Either::A(TcpConnectorResponse::new(req, port, addr))
|
||||
} else {
|
||||
error!("TCP connector: got unresolved address");
|
||||
Either::B(err(ConnectError::Unresolverd))
|
||||
@@ -80,19 +81,19 @@ impl<T: Address> Service for Connector<T> {
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Tcp stream connector response future
|
||||
pub struct ConnectorResponse<T> {
|
||||
pub struct TcpConnectorResponse<T> {
|
||||
req: Option<T>,
|
||||
port: u16,
|
||||
addrs: Option<VecDeque<SocketAddr>>,
|
||||
stream: Option<ConnectFuture>,
|
||||
}
|
||||
|
||||
impl<T: Address> ConnectorResponse<T> {
|
||||
impl<T: Address> TcpConnectorResponse<T> {
|
||||
pub fn new(
|
||||
req: T,
|
||||
port: u16,
|
||||
addr: either::Either<SocketAddr, VecDeque<SocketAddr>>,
|
||||
) -> ConnectorResponse<T> {
|
||||
) -> TcpConnectorResponse<T> {
|
||||
trace!(
|
||||
"TCP connector - connecting to {:?} port:{}",
|
||||
req.host(),
|
||||
@@ -100,13 +101,13 @@ impl<T: Address> ConnectorResponse<T> {
|
||||
);
|
||||
|
||||
match addr {
|
||||
either::Either::Left(addr) => ConnectorResponse {
|
||||
either::Either::Left(addr) => TcpConnectorResponse {
|
||||
req: Some(req),
|
||||
port,
|
||||
addrs: None,
|
||||
stream: Some(TcpStream::connect(&addr)),
|
||||
},
|
||||
either::Either::Right(addrs) => ConnectorResponse {
|
||||
either::Either::Right(addrs) => TcpConnectorResponse {
|
||||
req: Some(req),
|
||||
port,
|
||||
addrs: Some(addrs),
|
||||
@@ -116,7 +117,7 @@ impl<T: Address> ConnectorResponse<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> Future for ConnectorResponse<T> {
|
||||
impl<T: Address> Future for TcpConnectorResponse<T> {
|
||||
type Item = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
|
||||
|
@@ -5,9 +5,13 @@
|
||||
//! * `ssl` - enables ssl support via `openssl` crate
|
||||
//! * `rust-tls` - enables ssl support via `rustls` crate
|
||||
|
||||
#![recursion_limit = "128"]
|
||||
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
mod connect;
|
||||
mod connector;
|
||||
mod error;
|
||||
@@ -17,17 +21,17 @@ pub mod ssl;
|
||||
#[cfg(feature = "uri")]
|
||||
mod uri;
|
||||
|
||||
pub use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||
pub use trust_dns_resolver::system_conf::read_system_conf;
|
||||
pub use trust_dns_resolver::{error::ResolveError, AsyncResolver};
|
||||
|
||||
pub use self::connect::{Address, Connect, Connection};
|
||||
pub use self::connector::{Connector, ConnectorFactory};
|
||||
pub use self::connector::{TcpConnector, TcpConnectorFactory};
|
||||
pub use self::error::ConnectError;
|
||||
pub use self::resolver::{Resolver, ResolverFactory};
|
||||
|
||||
use actix_service::{NewService, Service, ServiceExt};
|
||||
use tokio_tcp::TcpStream;
|
||||
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||
use trust_dns_resolver::system_conf::read_system_conf;
|
||||
|
||||
pub fn start_resolver(cfg: ResolverConfig, opts: ResolverOpts) -> AsyncResolver {
|
||||
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
||||
@@ -35,16 +39,34 @@ pub fn start_resolver(cfg: ResolverConfig, opts: ResolverOpts) -> AsyncResolver
|
||||
resolver
|
||||
}
|
||||
|
||||
pub fn start_default_resolver() -> AsyncResolver {
|
||||
let (cfg, opts) = if let Ok((cfg, opts)) = read_system_conf() {
|
||||
(cfg, opts)
|
||||
} else {
|
||||
(ResolverConfig::default(), ResolverOpts::default())
|
||||
};
|
||||
thread_local! {
|
||||
static DEFAULT_RESOLVER: RefCell<Option<AsyncResolver>> = RefCell::new(None);
|
||||
}
|
||||
|
||||
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
||||
tokio_current_thread::spawn(bg);
|
||||
resolver
|
||||
pub(crate) fn get_default_resolver() -> AsyncResolver {
|
||||
DEFAULT_RESOLVER.with(|cell| {
|
||||
if let Some(ref resolver) = *cell.borrow() {
|
||||
return resolver.clone();
|
||||
}
|
||||
|
||||
let (cfg, opts) = match read_system_conf() {
|
||||
Ok((cfg, opts)) => (cfg, opts),
|
||||
Err(e) => {
|
||||
log::error!("TRust-DNS can not load system config: {}", e);
|
||||
(ResolverConfig::default(), ResolverOpts::default())
|
||||
}
|
||||
};
|
||||
|
||||
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
||||
tokio_current_thread::spawn(bg);
|
||||
|
||||
*cell.borrow_mut() = Some(resolver.clone());
|
||||
resolver
|
||||
})
|
||||
}
|
||||
|
||||
pub fn start_default_resolver() -> AsyncResolver {
|
||||
get_default_resolver()
|
||||
}
|
||||
|
||||
/// Create tcp connector service
|
||||
@@ -52,34 +74,36 @@ pub fn new_connector<T: Address>(
|
||||
resolver: AsyncResolver,
|
||||
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
|
||||
+ Clone {
|
||||
Resolver::new(resolver).and_then(Connector::new())
|
||||
Resolver::new(resolver).and_then(TcpConnector::new())
|
||||
}
|
||||
|
||||
/// Create tcp connector service
|
||||
pub fn new_connector_factory<T: Address>(
|
||||
resolver: AsyncResolver,
|
||||
) -> impl NewService<
|
||||
Config = (),
|
||||
Request = Connect<T>,
|
||||
Response = Connection<T, TcpStream>,
|
||||
Error = ConnectError,
|
||||
InitError = (),
|
||||
> + Clone {
|
||||
ResolverFactory::new(resolver).and_then(ConnectorFactory::new())
|
||||
ResolverFactory::new(resolver).and_then(TcpConnectorFactory::new())
|
||||
}
|
||||
|
||||
/// Create connector service with default parameters
|
||||
pub fn default_connector<T: Address>(
|
||||
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
|
||||
+ Clone {
|
||||
Resolver::new(start_default_resolver()).and_then(Connector::new())
|
||||
Resolver::default().and_then(TcpConnector::new())
|
||||
}
|
||||
|
||||
/// Create connector service factory with default parameters
|
||||
pub fn default_connector_factory<T: Address>() -> impl NewService<
|
||||
Config = (),
|
||||
Request = Connect<T>,
|
||||
Response = Connection<T, TcpStream>,
|
||||
Error = ConnectError,
|
||||
InitError = (),
|
||||
> + Clone {
|
||||
ResolverFactory::new(start_default_resolver()).and_then(ConnectorFactory::new())
|
||||
ResolverFactory::default().and_then(TcpConnectorFactory::new())
|
||||
}
|
||||
|
@@ -10,10 +10,11 @@ use trust_dns_resolver::{AsyncResolver, Background};
|
||||
|
||||
use crate::connect::{Address, Connect};
|
||||
use crate::error::ConnectError;
|
||||
use crate::get_default_resolver;
|
||||
|
||||
/// DNS Resolver Service factory
|
||||
pub struct ResolverFactory<T> {
|
||||
resolver: AsyncResolver,
|
||||
resolver: Option<AsyncResolver>,
|
||||
_t: PhantomData<T>,
|
||||
}
|
||||
|
||||
@@ -21,13 +22,18 @@ impl<T> ResolverFactory<T> {
|
||||
/// Create new resolver instance with custom configuration and options.
|
||||
pub fn new(resolver: AsyncResolver) -> Self {
|
||||
ResolverFactory {
|
||||
resolver,
|
||||
resolver: Some(resolver),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolver(&self) -> &AsyncResolver {
|
||||
&self.resolver
|
||||
impl<T> Default for ResolverFactory<T> {
|
||||
fn default() -> Self {
|
||||
ResolverFactory {
|
||||
resolver: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +50,7 @@ impl<T: Address> NewService for ResolverFactory<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = Connect<T>;
|
||||
type Error = ConnectError;
|
||||
type Config = ();
|
||||
type Service = Resolver<T>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
@@ -58,7 +65,7 @@ impl<T: Address> NewService for ResolverFactory<T> {
|
||||
|
||||
/// DNS Resolver Service
|
||||
pub struct Resolver<T> {
|
||||
resolver: AsyncResolver,
|
||||
resolver: Option<AsyncResolver>,
|
||||
_t: PhantomData<T>,
|
||||
}
|
||||
|
||||
@@ -66,7 +73,16 @@ impl<T> Resolver<T> {
|
||||
/// Create new resolver instance with custom configuration and options.
|
||||
pub fn new(resolver: AsyncResolver) -> Self {
|
||||
Resolver {
|
||||
resolver,
|
||||
resolver: Some(resolver),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for Resolver<T> {
|
||||
fn default() -> Self {
|
||||
Resolver {
|
||||
resolver: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -100,7 +116,10 @@ impl<T: Address> Service for Resolver<T> {
|
||||
Either::B(ok(req))
|
||||
} else {
|
||||
trace!("DNS resolver: resolving host {:?}", req.host());
|
||||
Either::A(ResolverFuture::new(req, &self.resolver))
|
||||
if self.resolver.is_none() {
|
||||
self.resolver = Some(get_default_resolver());
|
||||
}
|
||||
Either::A(ResolverFuture::new(req, self.resolver.as_ref().unwrap()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -52,13 +52,14 @@ impl<T, U> Clone for OpensslConnector<T, U> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address, U> NewService<()> for OpensslConnector<T, U>
|
||||
impl<T: Address, U> NewService for OpensslConnector<T, U>
|
||||
where
|
||||
U: AsyncRead + AsyncWrite + fmt::Debug,
|
||||
{
|
||||
type Request = Connection<T, U>;
|
||||
type Response = Connection<T, SslStream<U>>;
|
||||
type Error = HandshakeError<U>;
|
||||
type Config = ();
|
||||
type Service = OpensslConnectorService<T, U>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
@@ -1,6 +1,6 @@
|
||||
use actix_codec::{BytesCodec, Framed};
|
||||
use actix_server_config::Io;
|
||||
use actix_service::{fn_service, NewService, Service};
|
||||
use actix_service::{service_fn, NewService, Service};
|
||||
use actix_test_server::TestServer;
|
||||
use bytes::Bytes;
|
||||
use futures::{future::lazy, Future, Sink};
|
||||
@@ -9,28 +9,27 @@ use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||
|
||||
use actix_connect::{default_connector, Connect};
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_string() {
|
||||
let mut srv = TestServer::with(|| {
|
||||
fn_service(|io: Io<tokio_tcp::TcpStream>| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
})
|
||||
});
|
||||
|
||||
let mut conn = srv
|
||||
.block_on(lazy(|| Ok::<_, ()>(default_connector())))
|
||||
.unwrap();
|
||||
let mut conn = default_connector();
|
||||
let addr = format!("localhost:{}", srv.port());
|
||||
let con = srv.block_on(conn.call(addr.into())).unwrap();
|
||||
let con = srv.run_on(move || conn.call(addr.into())).unwrap();
|
||||
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_static_str() {
|
||||
let mut srv = TestServer::with(|| {
|
||||
fn_service(|io: Io<tokio_tcp::TcpStream>| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
@@ -64,7 +63,7 @@ fn test_static_str() {
|
||||
#[test]
|
||||
fn test_new_service() {
|
||||
let mut srv = TestServer::with(|| {
|
||||
fn_service(|io: Io<tokio_tcp::TcpStream>| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
@@ -92,20 +91,19 @@ fn test_new_service() {
|
||||
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_uri() {
|
||||
let mut srv = TestServer::with(|| {
|
||||
fn_service(|io: Io<tokio_tcp::TcpStream>| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
})
|
||||
});
|
||||
|
||||
let mut conn = srv
|
||||
.block_on(lazy(|| Ok::<_, ()>(default_connector())))
|
||||
.unwrap();
|
||||
let mut conn = default_connector();
|
||||
let addr = Uri::try_from(format!("https://localhost:{}", srv.port())).unwrap();
|
||||
let con = srv.block_on(conn.call(addr.into())).unwrap();
|
||||
let con = srv.run_on(move || conn.call(addr.into())).unwrap();
|
||||
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
||||
}
|
||||
|
@@ -1,5 +1,11 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.2] - 2019-03-28
|
||||
|
||||
### Changed
|
||||
|
||||
* Moved `blocking` module to `actix-threadpool` crate
|
||||
|
||||
## [0.2.1] - 2019-03-11
|
||||
|
||||
### Added
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-rt"
|
||||
version = "0.2.1"
|
||||
version = "0.2.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix runtime"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -11,21 +11,15 @@ categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "actix_rt"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
actix-threadpool = "0.1.0"
|
||||
futures = "0.1.25"
|
||||
parking_lot = "0.7"
|
||||
lazy_static = "1.2"
|
||||
log = "0.4"
|
||||
num_cpus = "1.10"
|
||||
threadpool = "1.7"
|
||||
tokio-current-thread = "0.1"
|
||||
tokio-executor = "0.1.5"
|
||||
tokio-reactor = "0.1.7"
|
||||
|
1
actix-rt/LICENSE-APACHE
Symbolic link
1
actix-rt/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-rt/LICENSE-MIT
Symbolic link
1
actix-rt/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -1,7 +1,6 @@
|
||||
//! A runtime implementation that runs everything on the current thread.
|
||||
|
||||
mod arbiter;
|
||||
pub mod blocking;
|
||||
mod builder;
|
||||
mod runtime;
|
||||
mod system;
|
||||
@@ -11,6 +10,9 @@ pub use self::builder::{Builder, SystemRunner};
|
||||
pub use self::runtime::Runtime;
|
||||
pub use self::system::System;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use actix_threadpool as blocking;
|
||||
|
||||
/// Spawns a future on the current arbiter.
|
||||
///
|
||||
/// # Panics
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-server-config"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix server config utils"
|
||||
homepage = "https://actix.rs"
|
||||
@@ -13,5 +13,22 @@ workspace = ".."
|
||||
name = "actix_server_config"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "rust-tls"]
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
# openssl
|
||||
ssl = ["tokio-openssl"]
|
||||
|
||||
# rustls
|
||||
rust-tls = ["rustls", "tokio-rustls"]
|
||||
|
||||
[dependencies]
|
||||
futures = "0.1.25"
|
||||
tokio-io = "0.1.12"
|
||||
tokio-tcp = "0.1"
|
||||
tokio-openssl = { version="0.3.0", optional = true }
|
||||
rustls = { version = "0.15.2", optional = true }
|
||||
tokio-rustls = { version = "0.9.1", optional = true }
|
||||
|
1
actix-server-config/LICENSE-APACHE
Symbolic link
1
actix-server-config/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-server-config/LICENSE-MIT
Symbolic link
1
actix-server-config/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
7
actix-server-config/changes.md
Normal file
7
actix-server-config/changes.md
Normal file
@@ -0,0 +1,7 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.1] - 2019-04-16
|
||||
|
||||
### Added
|
||||
|
||||
* `IoStream` trait and impls for TcpStream, SslStream and TlsStream
|
@@ -1,7 +1,10 @@
|
||||
use std::cell::Cell;
|
||||
use std::fmt;
|
||||
use std::net::SocketAddr;
|
||||
use std::rc::Rc;
|
||||
use std::{fmt, io, net, time};
|
||||
|
||||
use tokio_io::{AsyncRead, AsyncWrite};
|
||||
use tokio_tcp::TcpStream;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ServerConfig {
|
||||
@@ -130,3 +133,86 @@ impl<T: fmt::Debug, P> fmt::Debug for Io<T, P> {
|
||||
write!(f, "Io {{{:?}}}", self.io)
|
||||
}
|
||||
}
|
||||
|
||||
/// Low-level io stream operations
|
||||
pub trait IoStream: AsyncRead + AsyncWrite {
|
||||
/// Returns the socket address of the remote peer of this TCP connection.
|
||||
fn peer_addr(&self) -> Option<SocketAddr> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Sets the value of the TCP_NODELAY option on this socket.
|
||||
fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()>;
|
||||
|
||||
fn set_linger(&mut self, dur: Option<time::Duration>) -> io::Result<()>;
|
||||
|
||||
fn set_keepalive(&mut self, dur: Option<time::Duration>) -> io::Result<()>;
|
||||
}
|
||||
|
||||
impl IoStream for TcpStream {
|
||||
#[inline]
|
||||
fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
TcpStream::peer_addr(self).ok()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()> {
|
||||
TcpStream::set_nodelay(self, nodelay)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_linger(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
TcpStream::set_linger(self, dur)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_keepalive(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
TcpStream::set_keepalive(self, dur)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "ssl"))]
|
||||
impl<T: IoStream> IoStream for tokio_openssl::SslStream<T> {
|
||||
#[inline]
|
||||
fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
self.get_ref().get_ref().peer_addr()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()> {
|
||||
self.get_mut().get_mut().set_nodelay(nodelay)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_linger(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
self.get_mut().get_mut().set_linger(dur)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_keepalive(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
self.get_mut().get_mut().set_keepalive(dur)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "rust-tls"))]
|
||||
impl<T: IoStream> IoStream for tokio_rustls::TlsStream<T, rustls::ServerSession> {
|
||||
#[inline]
|
||||
fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
self.get_ref().0.peer_addr()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()> {
|
||||
self.get_mut().0.set_nodelay(nodelay)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_linger(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
self.get_mut().0.set_linger(dur)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_keepalive(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
self.get_mut().0.set_keepalive(dur)
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,43 @@
|
||||
# Changes
|
||||
|
||||
## [0.5.1] - 2019-05-18
|
||||
|
||||
### Changed
|
||||
|
||||
* ServerBuilder::shutdown_timeout() accepts u64
|
||||
|
||||
|
||||
## [0.5.0] - 2019-05-12
|
||||
|
||||
### Added
|
||||
|
||||
* Add `Debug` impl for `SslError`
|
||||
|
||||
* Derive debug for `Server` and `ServerCommand`
|
||||
|
||||
### Changed
|
||||
|
||||
* Upgrade to actix-service 0.4
|
||||
|
||||
|
||||
## [0.4.3] - 2019-04-16
|
||||
|
||||
### Added
|
||||
|
||||
* Re-export `IoStream` trait
|
||||
|
||||
### Changed
|
||||
|
||||
* Deppend on `ssl` and `rust-tls` features from actix-server-config
|
||||
|
||||
|
||||
## [0.4.2] - 2019-03-30
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix SIGINT force shutdown
|
||||
|
||||
|
||||
## [0.4.1] - 2019-03-14
|
||||
|
||||
### Added
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-server"
|
||||
version = "0.4.1"
|
||||
version = "0.5.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix server - General purpose tcp server"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -27,20 +27,20 @@ default = []
|
||||
tls = ["native-tls"]
|
||||
|
||||
# openssl
|
||||
ssl = ["openssl", "tokio-openssl"]
|
||||
ssl = ["openssl", "tokio-openssl", "actix-server-config/ssl"]
|
||||
|
||||
# rustls
|
||||
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
|
||||
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots", "actix-server-config/rust-tls"]
|
||||
|
||||
[dependencies]
|
||||
actix-rt = "0.2.1"
|
||||
actix-service = "0.3.4"
|
||||
actix-server-config = "0.1.0"
|
||||
actix-service = "0.4.0"
|
||||
actix-server-config = "0.1.1"
|
||||
|
||||
log = "0.4"
|
||||
num_cpus = "1.0"
|
||||
|
||||
mio = "^0.6.13"
|
||||
mio = "0.6.13"
|
||||
net2 = "0.2"
|
||||
futures = "0.1"
|
||||
slab = "0.4"
|
||||
@@ -58,12 +58,12 @@ openssl = { version="0.10", optional = true }
|
||||
tokio-openssl = { version="0.3", optional = true }
|
||||
|
||||
#rustls
|
||||
rustls = { version = "^0.15", optional = true }
|
||||
tokio-rustls = { version = "^0.9", optional = true }
|
||||
rustls = { version = "0.15.2", optional = true }
|
||||
tokio-rustls = { version = "0.9.1", optional = true }
|
||||
webpki = { version = "0.19", optional = true }
|
||||
webpki-roots = { version = "0.16", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
bytes = "0.4"
|
||||
actix-codec = "0.1.0"
|
||||
actix-codec = "0.1.2"
|
||||
env_logger = "0.6"
|
||||
|
1
actix-server/LICENSE-APACHE
Symbolic link
1
actix-server/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-server/LICENSE-MIT
Symbolic link
1
actix-server/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -128,8 +128,8 @@ impl ServerBuilder {
|
||||
/// dropped.
|
||||
///
|
||||
/// By default shutdown timeout sets to 30 seconds.
|
||||
pub fn shutdown_timeout(mut self, sec: u16) -> Self {
|
||||
self.shutdown_timeout = Duration::from_secs(u64::from(sec));
|
||||
pub fn shutdown_timeout(mut self, sec: u64) -> Self {
|
||||
self.shutdown_timeout = Duration::from_secs(sec);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -328,7 +328,7 @@ impl ServerBuilder {
|
||||
self.accept.send(Command::Stop);
|
||||
|
||||
// stop workers
|
||||
if !self.workers.is_empty() {
|
||||
if !self.workers.is_empty() && graceful {
|
||||
spawn(
|
||||
futures_unordered(
|
||||
self.workers
|
||||
|
@@ -207,8 +207,8 @@ impl ServiceRuntime {
|
||||
/// *ServiceConfig::bind()* or *ServiceConfig::listen()* methods.
|
||||
pub fn service<T, F>(&mut self, name: &str, service: F)
|
||||
where
|
||||
F: IntoNewService<T, ServerConfig>,
|
||||
T: NewService<ServerConfig, Request = Io<TcpStream>> + 'static,
|
||||
F: IntoNewService<T>,
|
||||
T: NewService<Config = ServerConfig, Request = Io<TcpStream>> + 'static,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
T::InitError: fmt::Debug,
|
||||
@@ -237,11 +237,11 @@ impl ServiceRuntime {
|
||||
|
||||
type BoxedNewService = Box<
|
||||
NewService<
|
||||
ServerConfig,
|
||||
Request = (Option<CounterGuard>, ServerMessage),
|
||||
Response = (),
|
||||
Error = (),
|
||||
InitError = (),
|
||||
Config = ServerConfig,
|
||||
Service = BoxedServerService,
|
||||
Future = Box<Future<Item = BoxedServerService, Error = ()>>,
|
||||
>,
|
||||
@@ -251,9 +251,9 @@ struct ServiceFactory<T> {
|
||||
inner: T,
|
||||
}
|
||||
|
||||
impl<T> NewService<ServerConfig> for ServiceFactory<T>
|
||||
impl<T> NewService for ServiceFactory<T>
|
||||
where
|
||||
T: NewService<ServerConfig, Request = Io<TcpStream>>,
|
||||
T: NewService<Config = ServerConfig, Request = Io<TcpStream>>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
T::Error: 'static,
|
||||
@@ -263,6 +263,7 @@ where
|
||||
type Response = ();
|
||||
type Error = ();
|
||||
type InitError = ();
|
||||
type Config = ServerConfig;
|
||||
type Service = BoxedServerService;
|
||||
type Future = Box<Future<Item = BoxedServerService, Error = ()>>;
|
||||
|
||||
|
@@ -10,7 +10,7 @@ mod signals;
|
||||
pub mod ssl;
|
||||
mod worker;
|
||||
|
||||
pub use actix_server_config::{Io, Protocol, ServerConfig};
|
||||
pub use actix_server_config::{Io, IoStream, Protocol, ServerConfig};
|
||||
|
||||
pub use self::builder::ServerBuilder;
|
||||
pub use self::config::{ServiceConfig, ServiceRuntime};
|
||||
|
@@ -5,6 +5,7 @@ use futures::Future;
|
||||
use crate::builder::ServerBuilder;
|
||||
use crate::signals::Signal;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum ServerCommand {
|
||||
WorkerDied(usize),
|
||||
Pause(oneshot::Sender<()>),
|
||||
@@ -17,7 +18,7 @@ pub(crate) enum ServerCommand {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Server(UnboundedSender<ServerCommand>);
|
||||
|
||||
impl Server {
|
||||
|
@@ -24,7 +24,7 @@ pub(crate) enum ServerMessage {
|
||||
}
|
||||
|
||||
pub trait ServiceFactory: Send + Clone + 'static {
|
||||
type NewService: NewService<ServerConfig, Request = Io<TcpStream>>;
|
||||
type NewService: NewService<Config = ServerConfig, Request = Io<TcpStream>>;
|
||||
|
||||
fn create(&self) -> Self::NewService;
|
||||
}
|
||||
@@ -169,7 +169,7 @@ impl InternalServiceFactory for Box<InternalServiceFactory> {
|
||||
impl<F, T> ServiceFactory for F
|
||||
where
|
||||
F: Fn() -> T + Send + Clone + 'static,
|
||||
T: NewService<ServerConfig, Request = Io<TcpStream>>,
|
||||
T: NewService<Config = ServerConfig, Request = Io<TcpStream>>,
|
||||
{
|
||||
type NewService = T;
|
||||
|
||||
|
@@ -35,6 +35,7 @@ thread_local! {
|
||||
}
|
||||
|
||||
/// Ssl error combinded with service error.
|
||||
#[derive(Debug)]
|
||||
pub enum SslError<E1, E2> {
|
||||
Ssl(E1),
|
||||
Service(E2),
|
||||
|
@@ -37,10 +37,12 @@ impl<T: AsyncRead + AsyncWrite, P> Clone for NativeTlsAcceptor<T, P> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService<ServerConfig> for NativeTlsAcceptor<T, P> {
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService for NativeTlsAcceptor<T, P> {
|
||||
type Request = Io<T, P>;
|
||||
type Response = Io<TlsStream<T>, P>;
|
||||
type Error = Error;
|
||||
|
||||
type Config = ServerConfig;
|
||||
type Service = NativeTlsAcceptorService<T, P>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
@@ -37,10 +37,11 @@ impl<T: AsyncRead + AsyncWrite, P> Clone for OpensslAcceptor<T, P> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService<ServerConfig> for OpensslAcceptor<T, P> {
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService for OpensslAcceptor<T, P> {
|
||||
type Request = Io<T, P>;
|
||||
type Response = Io<SslStream<T>, P>;
|
||||
type Error = HandshakeError<T>;
|
||||
type Config = ServerConfig;
|
||||
type Service = OpensslAcceptorService<T, P>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
@@ -39,10 +39,12 @@ impl<T, P> Clone for RustlsAcceptor<T, P> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService<SrvConfig> for RustlsAcceptor<T, P> {
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService for RustlsAcceptor<T, P> {
|
||||
type Request = Io<T, P>;
|
||||
type Response = Io<TlsStream<T, ServerSession>, P>;
|
||||
type Error = io::Error;
|
||||
|
||||
type Config = SrvConfig;
|
||||
type Service = RustlsAcceptorService<T, P>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
@@ -4,7 +4,7 @@ use std::{net, thread, time};
|
||||
|
||||
use actix_codec::{BytesCodec, Framed};
|
||||
use actix_server::{Io, Server, ServerConfig};
|
||||
use actix_service::{fn_cfg_factory, fn_service, IntoService};
|
||||
use actix_service::{new_service_cfg, service_fn, IntoService};
|
||||
use bytes::Bytes;
|
||||
use futures::{Future, Sink};
|
||||
use net2::TcpBuilder;
|
||||
@@ -28,7 +28,7 @@ fn test_bind() {
|
||||
let sys = actix_rt::System::new("test");
|
||||
let srv = Server::build()
|
||||
.bind("test", addr, move || {
|
||||
fn_cfg_factory(move |cfg: &ServerConfig| {
|
||||
new_service_cfg(move |cfg: &ServerConfig| {
|
||||
assert_eq!(cfg.local_addr(), addr);
|
||||
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
|
||||
})
|
||||
@@ -54,7 +54,7 @@ fn test_bind_no_config() {
|
||||
let h = thread::spawn(move || {
|
||||
let sys = actix_rt::System::new("test");
|
||||
let srv = Server::build()
|
||||
.bind("test", addr, move || fn_service(|_| Ok::<_, ()>(())))
|
||||
.bind("test", addr, move || service_fn(|_| Ok::<_, ()>(())))
|
||||
.unwrap()
|
||||
.start();
|
||||
let _ = tx.send((srv, actix_rt::System::current()));
|
||||
@@ -76,7 +76,7 @@ fn test_listen() {
|
||||
let lst = net::TcpListener::bind(addr).unwrap();
|
||||
let srv = Server::build()
|
||||
.listen("test", lst, move || {
|
||||
fn_cfg_factory(move |cfg: &ServerConfig| {
|
||||
new_service_cfg(move |cfg: &ServerConfig| {
|
||||
assert_eq!(cfg.local_addr(), addr);
|
||||
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
|
||||
})
|
||||
@@ -105,7 +105,7 @@ fn test_start() {
|
||||
let srv = Server::build()
|
||||
.backlog(100)
|
||||
.bind("test", addr, move || {
|
||||
fn_cfg_factory(move |cfg: &ServerConfig| {
|
||||
new_service_cfg(move |cfg: &ServerConfig| {
|
||||
assert_eq!(cfg.local_addr(), addr);
|
||||
Ok::<_, ()>(
|
||||
(|io: Io<TcpStream>| {
|
||||
|
@@ -1,5 +1,40 @@
|
||||
# Changes
|
||||
|
||||
## [0.4.1] - 2019-06-06
|
||||
|
||||
### Added
|
||||
|
||||
* Add `new_apply_cfg` function
|
||||
|
||||
## [0.4.0] - 2019-05-12
|
||||
|
||||
### Changed
|
||||
|
||||
* Use associated type for `NewService` config
|
||||
|
||||
* Change `apply_cfg` function
|
||||
|
||||
* Renamed helper functions
|
||||
|
||||
### Added
|
||||
|
||||
* Add `NewService::map_config` and `NewService::unit_config` combinators
|
||||
|
||||
|
||||
## [0.3.6] - 2019-04-07
|
||||
|
||||
### Changed
|
||||
|
||||
* Poll boxed service call result immediately
|
||||
|
||||
|
||||
## [0.3.5] - 2019-03-29
|
||||
|
||||
### Added
|
||||
|
||||
* Add `impl<S: Service> Service for Rc<RefCell<S>>`
|
||||
|
||||
|
||||
## [0.3.4] - 2019-03-12
|
||||
|
||||
### Added
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-service"
|
||||
version = "0.3.4"
|
||||
version = "0.4.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix Service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -23,8 +23,7 @@ name = "actix_service"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
futures = "0.1.24"
|
||||
void = "1.0.2"
|
||||
futures = "0.1.25"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2"
|
1
actix-service/LICENSE-APACHE
Symbolic link
1
actix-service/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-service/LICENSE-MIT
Symbolic link
1
actix-service/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -1,5 +1,3 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::{IntoNewService, NewService, Service};
|
||||
@@ -111,67 +109,75 @@ where
|
||||
}
|
||||
|
||||
/// `AndThenNewService` new service combinator
|
||||
pub struct AndThenNewService<A, B, C>
|
||||
pub struct AndThenNewService<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService,
|
||||
{
|
||||
a: A,
|
||||
b: B,
|
||||
_t: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<A, B, C> AndThenNewService<A, B, C>
|
||||
impl<A, B> AndThenNewService<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
Config = A::Config,
|
||||
Request = A::Response,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
{
|
||||
/// Create new `AndThen` combinator
|
||||
pub fn new<F: IntoNewService<B, C>>(a: A, f: F) -> Self {
|
||||
pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self {
|
||||
Self {
|
||||
a,
|
||||
b: f.into_new_service(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> NewService<C> for AndThenNewService<A, B, C>
|
||||
impl<A, B> NewService for AndThenNewService<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
Config = A::Config,
|
||||
Request = A::Response,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = B::Response;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = AndThen<A::Service, B::Service>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = AndThenNewServiceFuture<A, B, C>;
|
||||
type Future = AndThenNewServiceFuture<A, B>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
AndThenNewServiceFuture::new(self.a.new_service(cfg), self.b.new_service(cfg))
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> Clone for AndThenNewService<A, B, C>
|
||||
impl<A, B> Clone for AndThenNewService<A, B>
|
||||
where
|
||||
A: NewService<C> + Clone,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError> + Clone,
|
||||
A: NewService + Clone,
|
||||
B: NewService + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenNewServiceFuture<A, B, C>
|
||||
pub struct AndThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response>,
|
||||
A: NewService,
|
||||
B: NewService<Request = A::Response>,
|
||||
{
|
||||
fut_b: B::Future,
|
||||
fut_a: A::Future,
|
||||
@@ -179,10 +185,10 @@ where
|
||||
b: Option<B::Service>,
|
||||
}
|
||||
|
||||
impl<A, B, C> AndThenNewServiceFuture<A, B, C>
|
||||
impl<A, B> AndThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response>,
|
||||
A: NewService,
|
||||
B: NewService<Request = A::Response>,
|
||||
{
|
||||
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
|
||||
AndThenNewServiceFuture {
|
||||
@@ -194,10 +200,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> Future for AndThenNewServiceFuture<A, B, C>
|
||||
impl<A, B> Future for AndThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
type Item = AndThen<A::Service, B::Service>;
|
||||
type Error = A::InitError;
|
||||
|
@@ -7,17 +7,16 @@ use crate::from_err::FromErr;
|
||||
use crate::{NewService, Transform};
|
||||
|
||||
/// `Apply` new service combinator
|
||||
pub struct AndThenTransform<T, A, B, C> {
|
||||
pub struct AndThenTransform<T, A, B> {
|
||||
a: A,
|
||||
b: B,
|
||||
t: Rc<T>,
|
||||
_t: std::marker::PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<T, A, B, C> AndThenTransform<T, A, B, C>
|
||||
impl<T, A, B> AndThenTransform<T, A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Config = A::Config, InitError = A::InitError>,
|
||||
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
@@ -27,12 +26,11 @@ where
|
||||
a,
|
||||
b,
|
||||
t: Rc::new(t),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A, B, C> Clone for AndThenTransform<T, A, B, C>
|
||||
impl<T, A, B> Clone for AndThenTransform<T, A, B>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
@@ -42,15 +40,14 @@ where
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
t: self.t.clone(),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A, B, C> NewService<C> for AndThenTransform<T, A, B, C>
|
||||
impl<T, A, B> NewService for AndThenTransform<T, A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Config = A::Config, InitError = A::InitError>,
|
||||
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
@@ -58,11 +55,12 @@ where
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
|
||||
type Config = A::Config;
|
||||
type InitError = T::InitError;
|
||||
type Service = AndThen<FromErr<A::Service, T::Error>, T::Transform>;
|
||||
type Future = AndThenTransformFuture<T, A, B, C>;
|
||||
type Future = AndThenTransformFuture<T, A, B>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
AndThenTransformFuture {
|
||||
a: None,
|
||||
t: None,
|
||||
@@ -74,10 +72,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenTransformFuture<T, A, B, C>
|
||||
pub struct AndThenTransformFuture<T, A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<InitError = A::InitError>,
|
||||
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
@@ -89,10 +87,10 @@ where
|
||||
t_cell: Rc<T>,
|
||||
}
|
||||
|
||||
impl<T, A, B, C> Future for AndThenTransformFuture<T, A, B, C>
|
||||
impl<T, A, B> Future for AndThenTransformFuture<T, A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<InitError = A::InitError>,
|
||||
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
|
@@ -133,27 +133,23 @@ where
|
||||
}
|
||||
|
||||
/// `ApplyNewService` new service combinator
|
||||
pub struct AndThenApplyNewService<A, B, F, Out, Cfg> {
|
||||
pub struct AndThenApplyNewService<A, B, F, Out> {
|
||||
a: A,
|
||||
b: B,
|
||||
f: Cell<F>,
|
||||
r: PhantomData<(Out, Cfg)>,
|
||||
r: PhantomData<Out>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, Cfg> AndThenApplyNewService<A, B, F, Out, Cfg>
|
||||
impl<A, B, F, Out> AndThenApplyNewService<A, B, F, Out>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Config = A::Config, Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
/// Create new `ApplyNewService` new service instance
|
||||
pub fn new<A1: IntoNewService<A, Cfg>, B1: IntoNewService<B, Cfg>>(
|
||||
a: A1,
|
||||
b: B1,
|
||||
f: F,
|
||||
) -> Self {
|
||||
pub fn new<A1: IntoNewService<A>, B1: IntoNewService<B>>(a: A1, b: B1, f: F) -> Self {
|
||||
Self {
|
||||
f: Cell::new(f),
|
||||
a: a.into_new_service(),
|
||||
@@ -163,7 +159,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, Cfg> Clone for AndThenApplyNewService<A, B, F, Out, Cfg>
|
||||
impl<A, B, F, Out> Clone for AndThenApplyNewService<A, B, F, Out>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
@@ -178,10 +174,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, Cfg> NewService<Cfg> for AndThenApplyNewService<A, B, F, Out, Cfg>
|
||||
impl<A, B, F, Out> NewService for AndThenApplyNewService<A, B, F, Out>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Config = A::Config, Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
@@ -190,11 +186,11 @@ where
|
||||
type Response = Out::Item;
|
||||
type Error = A::Error;
|
||||
type Service = AndThenApply<A::Service, B::Service, F, Out>;
|
||||
|
||||
type Config = A::Config;
|
||||
type InitError = A::InitError;
|
||||
type Future = AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>;
|
||||
type Future = AndThenApplyNewServiceFuture<A, B, F, Out>;
|
||||
|
||||
fn new_service(&self, cfg: &Cfg) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
AndThenApplyNewServiceFuture {
|
||||
a: None,
|
||||
b: None,
|
||||
@@ -205,10 +201,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>
|
||||
pub struct AndThenApplyNewServiceFuture<A, B, F, Out>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
@@ -220,10 +216,10 @@ where
|
||||
b: Option<B::Service>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, Cfg> Future for AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>
|
||||
impl<A, B, F, Out> Future for AndThenApplyNewServiceFuture<A, B, F, Out>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
|
@@ -16,17 +16,14 @@ where
|
||||
Apply::new(service.into_service(), f)
|
||||
}
|
||||
|
||||
/// Create fractory for `apply_fn` service.
|
||||
pub fn apply_fn_factory<T, F, In, Out, Cfg, U>(
|
||||
service: U,
|
||||
f: F,
|
||||
) -> ApplyNewService<T, F, In, Out, Cfg>
|
||||
/// Create factory for `apply` service.
|
||||
pub fn new_apply_fn<T, F, In, Out, U>(service: U, f: F) -> ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
U: IntoNewService<T, Cfg>,
|
||||
U: IntoNewService<T>,
|
||||
{
|
||||
ApplyNewService::new(service.into_new_service(), f)
|
||||
}
|
||||
@@ -50,7 +47,7 @@ where
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
/// Create new `Apply` combinator
|
||||
pub fn new<I: IntoService<T>>(service: I, f: F) -> Self {
|
||||
pub(crate) fn new<I: IntoService<T>>(service: I, f: F) -> Self {
|
||||
Self {
|
||||
service: service.into_service(),
|
||||
f,
|
||||
@@ -95,24 +92,24 @@ where
|
||||
}
|
||||
|
||||
/// `ApplyNewService` new service combinator
|
||||
pub struct ApplyNewService<T, F, In, Out, Cfg>
|
||||
pub struct ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
{
|
||||
service: T,
|
||||
f: F,
|
||||
r: PhantomData<(In, Out, Cfg)>,
|
||||
r: PhantomData<(In, Out)>,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Cfg> ApplyNewService<T, F, In, Out, Cfg>
|
||||
impl<T, F, In, Out> ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
/// Create new `ApplyNewService` new service instance
|
||||
pub fn new<F1: IntoNewService<T, Cfg>>(service: F1, f: F) -> Self {
|
||||
pub(crate) fn new<F1: IntoNewService<T>>(service: F1, f: F) -> Self {
|
||||
Self {
|
||||
f,
|
||||
service: service.into_new_service(),
|
||||
@@ -121,9 +118,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Cfg> Clone for ApplyNewService<T, F, In, Out, Cfg>
|
||||
impl<T, F, In, Out> Clone for ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg> + Clone,
|
||||
T: NewService + Clone,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
@@ -136,9 +133,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Cfg> NewService<Cfg> for ApplyNewService<T, F, In, Out, Cfg>
|
||||
impl<T, F, In, Out> NewService for ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
@@ -146,19 +143,20 @@ where
|
||||
type Request = In;
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
|
||||
type Config = T::Config;
|
||||
type Service = Apply<T::Service, F, In, Out>;
|
||||
|
||||
type InitError = T::InitError;
|
||||
type Future = ApplyNewServiceFuture<T, F, In, Out, Cfg>;
|
||||
type Future = ApplyNewServiceFuture<T, F, In, Out>;
|
||||
|
||||
fn new_service(&self, cfg: &Cfg) -> Self::Future {
|
||||
fn new_service(&self, cfg: &T::Config) -> Self::Future {
|
||||
ApplyNewServiceFuture::new(self.service.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ApplyNewServiceFuture<T, F, In, Out, Cfg>
|
||||
pub struct ApplyNewServiceFuture<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
@@ -167,9 +165,9 @@ where
|
||||
r: PhantomData<(In, Out)>,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Cfg> ApplyNewServiceFuture<T, F, In, Out, Cfg>
|
||||
impl<T, F, In, Out> ApplyNewServiceFuture<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
@@ -182,9 +180,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Cfg> Future for ApplyNewServiceFuture<T, F, In, Out, Cfg>
|
||||
impl<T, F, In, Out> Future for ApplyNewServiceFuture<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
|
@@ -1,112 +1,252 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use crate::{IntoNewService, NewService};
|
||||
use futures::future::Future;
|
||||
use futures::{try_ready, Async, IntoFuture, Poll};
|
||||
|
||||
/// Create new ApplyConfig` service factory combinator
|
||||
pub fn apply_cfg<F, S, C1, C2, U>(f: F, service: U) -> ApplyConfig<F, S, C1, C2>
|
||||
where
|
||||
S: NewService<C2>,
|
||||
F: Fn(&C1) -> C2,
|
||||
U: IntoNewService<S, C2>,
|
||||
{
|
||||
ApplyConfig::new(service.into_new_service(), f)
|
||||
}
|
||||
use crate::cell::Cell;
|
||||
use crate::{IntoService, NewService, Service};
|
||||
|
||||
/// `ApplyConfig` service factory combinator
|
||||
pub struct ApplyConfig<F, S, C1, C2> {
|
||||
s: S,
|
||||
/// Convert `Fn(&Config, &mut Service) -> Future<Service>` fn to a NewService
|
||||
pub fn apply_cfg<F, C, T, R, S>(
|
||||
srv: T,
|
||||
f: F,
|
||||
r: PhantomData<(C1, C2)>,
|
||||
}
|
||||
|
||||
impl<F, S, C1, C2> ApplyConfig<F, S, C1, C2>
|
||||
) -> impl NewService<
|
||||
Config = C,
|
||||
Request = S::Request,
|
||||
Response = S::Response,
|
||||
Error = S::Error,
|
||||
Service = S,
|
||||
InitError = R::Error,
|
||||
> + Clone
|
||||
where
|
||||
S: NewService<C2>,
|
||||
F: Fn(&C1) -> C2,
|
||||
F: FnMut(&C, &mut T) -> R,
|
||||
T: Service,
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
/// Create new ApplyConfig` service factory combinator
|
||||
pub fn new<U: IntoNewService<S, C2>>(a: U, f: F) -> Self {
|
||||
Self {
|
||||
f,
|
||||
s: a.into_new_service(),
|
||||
r: PhantomData,
|
||||
}
|
||||
ApplyConfigService {
|
||||
f: Cell::new(f),
|
||||
srv: Cell::new(srv.into_service()),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, C1, C2> Clone for ApplyConfig<F, S, C1, C2>
|
||||
/// Convert `Fn(&Config, &mut Service) -> Future<Service>` fn to a NewService
|
||||
/// Service get constructor from NewService.
|
||||
pub fn new_apply_cfg<F, C, T, R, S>(
|
||||
srv: T,
|
||||
f: F,
|
||||
) -> impl NewService<
|
||||
Config = C,
|
||||
Request = S::Request,
|
||||
Response = S::Response,
|
||||
Error = S::Error,
|
||||
Service = S,
|
||||
InitError = T::InitError,
|
||||
> + Clone
|
||||
where
|
||||
S: Clone,
|
||||
F: Clone,
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
ApplyConfigNewService {
|
||||
f: Cell::new(f),
|
||||
srv: Cell::new(srv),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
|
||||
struct ApplyConfigService<F, C, T, R, S>
|
||||
where
|
||||
F: FnMut(&C, &mut T) -> R,
|
||||
T: Service,
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
f: Cell<F>,
|
||||
srv: Cell<T>,
|
||||
_t: PhantomData<(C, R, S)>,
|
||||
}
|
||||
|
||||
impl<F, C, T, R, S> Clone for ApplyConfigService<F, C, T, R, S>
|
||||
where
|
||||
F: FnMut(&C, &mut T) -> R,
|
||||
T: Service,
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
s: self.s.clone(),
|
||||
ApplyConfigService {
|
||||
f: self.f.clone(),
|
||||
r: PhantomData,
|
||||
srv: self.srv.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, C1, C2> NewService<C1> for ApplyConfig<F, S, C1, C2>
|
||||
impl<F, C, T, R, S> NewService for ApplyConfigService<F, C, T, R, S>
|
||||
where
|
||||
S: NewService<C2>,
|
||||
F: Fn(&C1) -> C2,
|
||||
F: FnMut(&C, &mut T) -> R,
|
||||
T: Service,
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
type Config = C;
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S::Service;
|
||||
type Service = S;
|
||||
|
||||
type InitError = S::InitError;
|
||||
type Future = S::Future;
|
||||
type InitError = R::Error;
|
||||
type Future = FnNewServiceConfigFut<R, S>;
|
||||
|
||||
fn new_service(&self, cfg: &C1) -> Self::Future {
|
||||
let cfg2 = (self.f)(cfg);
|
||||
|
||||
self.s.new_service(&cfg2)
|
||||
}
|
||||
}
|
||||
|
||||
#[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());
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
FnNewServiceConfigFut {
|
||||
fut: unsafe { (self.f.get_mut_unsafe())(cfg, self.srv.get_mut_unsafe()) }
|
||||
.into_future(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FnNewServiceConfigFut<R, S>
|
||||
where
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
fut: R::Future,
|
||||
_t: PhantomData<(S,)>,
|
||||
}
|
||||
|
||||
impl<R, S> Future for FnNewServiceConfigFut<R, S>
|
||||
where
|
||||
R: IntoFuture,
|
||||
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()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
|
||||
struct ApplyConfigNewService<F, C, T, R, S>
|
||||
where
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
f: Cell<F>,
|
||||
srv: Cell<T>,
|
||||
_t: PhantomData<(C, R, S)>,
|
||||
}
|
||||
|
||||
impl<F, C, T, R, S> Clone for ApplyConfigNewService<F, C, T, R, S>
|
||||
where
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
ApplyConfigNewService {
|
||||
f: self.f.clone(),
|
||||
srv: self.srv.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, T, R, S> NewService for ApplyConfigNewService<F, C, T, R, S>
|
||||
where
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
type Config = C;
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S;
|
||||
|
||||
type InitError = R::Error;
|
||||
type Future = ApplyConfigNewServiceFut<F, C, T, R, S>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
ApplyConfigNewServiceFut {
|
||||
f: self.f.clone(),
|
||||
cfg: cfg.clone(),
|
||||
srv: Some(self.srv.get_ref().new_service(&())),
|
||||
fut: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ApplyConfigNewServiceFut<F, C, T, R, S>
|
||||
where
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
cfg: C,
|
||||
f: Cell<F>,
|
||||
srv: Option<T::Future>,
|
||||
fut: Option<R::Future>,
|
||||
_t: PhantomData<(S,)>,
|
||||
}
|
||||
|
||||
impl<F, C, T, R, S> Future for ApplyConfigNewServiceFut<F, C, T, R, S>
|
||||
where
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
type Item = S;
|
||||
type Error = R::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.srv {
|
||||
match fut.poll()? {
|
||||
Async::NotReady => return Ok(Async::NotReady),
|
||||
Async::Ready(mut srv) => {
|
||||
let _ = self.srv.take();
|
||||
self.fut = Some(self.f.get_mut()(&self.cfg, &mut srv).into_future());
|
||||
return self.poll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref mut fut) = self.fut {
|
||||
Ok(Async::Ready(try_ready!(fut.poll()).into_service()))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -68,12 +68,13 @@ 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 Response = R;
|
||||
type Error = E1;
|
||||
type Service = Blank<R, E1>;
|
||||
|
||||
type Config = ();
|
||||
type Service = Blank<R, E1>;
|
||||
type InitError = E2;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
|
@@ -1,22 +1,28 @@
|
||||
use futures::future::{err, ok, Either, FutureResult};
|
||||
use futures::{Async, Future, IntoFuture, Poll};
|
||||
|
||||
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>>,
|
||||
Future = BoxedServiceResponse<Res, Err>,
|
||||
>,
|
||||
>;
|
||||
|
||||
pub type BoxedServiceResponse<Res, Err> =
|
||||
Either<FutureResult<Res, Err>, Box<Future<Item = Res, Error = Err>>>;
|
||||
|
||||
pub struct BoxedNewService<C, Req, Res, Err, InitErr>(Inner<C, Req, Res, Err, InitErr>);
|
||||
|
||||
/// Create boxed new service
|
||||
pub fn new_service<T, C>(
|
||||
pub fn new_service<T>(
|
||||
service: T,
|
||||
) -> BoxedNewService<C, T::Request, T::Response, T::Error, T::InitError>
|
||||
) -> BoxedNewService<T::Config, T::Request, T::Response, T::Error, T::InitError>
|
||||
where
|
||||
C: 'static,
|
||||
T: NewService<C> + 'static,
|
||||
T: NewService + 'static,
|
||||
T::Request: 'static,
|
||||
T::Response: 'static,
|
||||
T::Service: 'static,
|
||||
@@ -41,7 +47,7 @@ where
|
||||
|
||||
type Inner<C, Req, Res, Err, InitErr> = Box<
|
||||
NewService<
|
||||
C,
|
||||
Config = C,
|
||||
Request = Req,
|
||||
Response = Res,
|
||||
Error = Err,
|
||||
@@ -51,9 +57,7 @@ type Inner<C, Req, Res, Err, InitErr> = Box<
|
||||
>,
|
||||
>;
|
||||
|
||||
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>
|
||||
impl<C, Req, Res, Err, InitErr> NewService for BoxedNewService<C, Req, Res, Err, InitErr>
|
||||
where
|
||||
Req: 'static,
|
||||
Res: 'static,
|
||||
@@ -64,6 +68,7 @@ where
|
||||
type Response = Res;
|
||||
type Error = Err;
|
||||
type InitError = InitErr;
|
||||
type Config = C;
|
||||
type Service = BoxedService<Req, Res, Err>;
|
||||
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
@@ -72,18 +77,18 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
struct NewServiceWrapper<C, T: NewService<C>> {
|
||||
struct NewServiceWrapper<C, T: NewService> {
|
||||
service: T,
|
||||
_t: std::marker::PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<C, T, Req, Res, Err, InitErr> NewService<C> for NewServiceWrapper<C, T>
|
||||
impl<C, T, Req, Res, Err, InitErr> NewService 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: NewService<Config = C, Request = Req, Response = Res, Error = Err, InitError = InitErr>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
@@ -92,6 +97,7 @@ where
|
||||
type Response = Res;
|
||||
type Error = Err;
|
||||
type InitError = InitErr;
|
||||
type Config = C;
|
||||
type Service = BoxedService<Req, Res, Err>;
|
||||
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
@@ -125,13 +131,21 @@ where
|
||||
type Request = Req;
|
||||
type Response = Res;
|
||||
type Error = Err;
|
||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||
type Future = Either<
|
||||
FutureResult<Self::Response, Self::Error>,
|
||||
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))
|
||||
let mut fut = self.0.call(req);
|
||||
match fut.poll() {
|
||||
Ok(Async::Ready(res)) => Either::A(ok(res)),
|
||||
Err(e) => Either::A(err(e)),
|
||||
Ok(Async::NotReady) => Either::B(Box::new(fut)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -26,7 +26,15 @@ impl<T> Cell<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_ref(&self) -> &T {
|
||||
unsafe { &*self.inner.as_ref().get() }
|
||||
}
|
||||
|
||||
pub(crate) fn get_mut(&mut self) -> &mut T {
|
||||
unsafe { &mut *self.inner.as_ref().get() }
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn get_mut_unsafe(&self) -> &mut T {
|
||||
&mut *self.inner.as_ref().get()
|
||||
}
|
||||
}
|
||||
|
@@ -3,29 +3,30 @@ use std::marker::PhantomData;
|
||||
use futures::future::{ok, Future, FutureResult};
|
||||
use futures::{try_ready, Async, IntoFuture, Poll};
|
||||
|
||||
use crate::{IntoConfigurableNewService, IntoNewService, IntoService, NewService, Service};
|
||||
use crate::{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>
|
||||
/// Create `NewService` for function that can act as a Service
|
||||
pub fn service_fn<F, Req, Out, Cfg>(f: F) -> NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
FnNewService::new(f)
|
||||
NewServiceFn::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>
|
||||
pub fn new_service_fn<F, C, R, S, E>(f: F) -> FnNewServiceNoConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
R::Item: IntoService<S>,
|
||||
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>
|
||||
pub fn new_service_cfg<F, C, R, S, E>(f: F) -> FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Error = E>,
|
||||
@@ -35,39 +36,36 @@ where
|
||||
FnNewServiceConfig::new(f)
|
||||
}
|
||||
|
||||
pub struct FnService<F, Req, Out>
|
||||
pub struct ServiceFn<F, Req, Out>
|
||||
where
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(Req,)>,
|
||||
_t: PhantomData<Req>,
|
||||
}
|
||||
|
||||
impl<F, Req, Out> FnService<F, Req, Out>
|
||||
impl<F, Req, Out> ServiceFn<F, Req, Out>
|
||||
where
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnService { f, _t: PhantomData }
|
||||
pub(crate) fn new(f: F) -> Self {
|
||||
ServiceFn { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out> Clone for FnService<F, Req, Out>
|
||||
impl<F, Req, Out> Clone for ServiceFn<F, Req, Out>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
FnService {
|
||||
f: self.f.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
ServiceFn::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out> Service for FnService<F, Req, Out>
|
||||
impl<F, Req, Out> Service for ServiceFn<F, Req, Out>
|
||||
where
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
@@ -86,17 +84,17 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out> IntoService<FnService<F, Req, Out>> for F
|
||||
impl<F, Req, Out> IntoService<ServiceFn<F, Req, Out>> for F
|
||||
where
|
||||
F: FnMut(Req) -> Out + 'static,
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn into_service(self) -> FnService<F, Req, Out> {
|
||||
FnService::new(self)
|
||||
fn into_service(self) -> ServiceFn<F, Req, Out> {
|
||||
ServiceFn::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FnNewService<F, Req, Out, Cfg>
|
||||
pub struct NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
@@ -105,17 +103,27 @@ where
|
||||
_t: PhantomData<(Req, Cfg)>,
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> FnNewService<F, Req, Out, Cfg>
|
||||
impl<F, Req, Out, Cfg> NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewService { f, _t: PhantomData }
|
||||
pub(crate) fn new(f: F) -> Self {
|
||||
NewServiceFn { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> NewService<Cfg> for FnNewService<F, Req, Out, Cfg>
|
||||
impl<F, Req, Out, Cfg> Clone for NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
NewServiceFn::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> NewService for NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
@@ -123,95 +131,34 @@ where
|
||||
type Request = Req;
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
type Service = FnService<F, Req, Out>;
|
||||
|
||||
type Config = Cfg;
|
||||
type Service = ServiceFn<F, Req, Out>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &Cfg) -> Self::Future {
|
||||
ok(FnService::new(self.f.clone()))
|
||||
ok(ServiceFn::new(self.f.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> Clone for FnNewService<F, Req, Out, Cfg>
|
||||
impl<F, Req, Out, Cfg> IntoService<ServiceFn<F, Req, Out>> for NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
fn into_service(self) -> ServiceFn<F, Req, Out> {
|
||||
ServiceFn::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> IntoNewService<FnNewService<F, Req, Out, Cfg>, Cfg> for F
|
||||
impl<F, Req, Out, Cfg> IntoNewService<NewServiceFn<F, Req, Out, 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)
|
||||
fn into_new_service(self) -> NewServiceFn<F, Req, Out, Cfg> {
|
||||
NewServiceFn::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,7 +186,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> NewService<C> for FnNewServiceConfig<F, C, R, S, E>
|
||||
impl<F, C, R, S, E> NewService for FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Error = E>,
|
||||
@@ -249,8 +196,9 @@ where
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S;
|
||||
|
||||
type Config = C;
|
||||
type Service = S;
|
||||
type InitError = E;
|
||||
type Future = FnNewServiceConfigFut<R, S, E>;
|
||||
|
||||
@@ -298,14 +246,65 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> IntoConfigurableNewService<FnNewServiceConfig<F, C, R, S, E>, C> for F
|
||||
/// Converter for `Fn() -> Future<Service>` fn
|
||||
pub struct FnNewServiceNoConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Error = E>,
|
||||
R::Item: IntoService<S>,
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewServiceConfig<F, C, R, S, E> {
|
||||
FnNewServiceConfig::new(self)
|
||||
f: F,
|
||||
_t: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> FnNewServiceNoConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewServiceNoConfig { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> NewService for FnNewServiceNoConfig<F, C, 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 Config = C;
|
||||
type InitError = E;
|
||||
type Future = R::Future;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
(self.f)().into_future()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> Clone for FnNewServiceNoConfig<F, C, 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, C, R, S, E> IntoNewService<FnNewServiceNoConfig<F, C, R, S, E>> for F
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewServiceNoConfig<F, C, R, S, E> {
|
||||
FnNewServiceNoConfig::new(self)
|
||||
}
|
||||
}
|
||||
|
@@ -3,10 +3,11 @@ use std::marker::PhantomData;
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::IntoFuture;
|
||||
|
||||
use crate::{Apply, IntoTransform, Service, Transform};
|
||||
use crate::apply::Apply;
|
||||
use crate::{IntoTransform, Service, Transform};
|
||||
|
||||
/// Use function as transform service
|
||||
pub fn fn_transform<F, S, In, Out, Err>(
|
||||
pub fn transform_fn<F, S, In, Out, Err>(
|
||||
f: F,
|
||||
) -> impl Transform<S, Request = In, Response = Out::Item, Error = Out::Error, InitError = Err>
|
||||
where
|
||||
|
@@ -81,23 +81,23 @@ where
|
||||
/// service's error.
|
||||
///
|
||||
/// This is created by the `NewServiceExt::from_err` method.
|
||||
pub struct FromErrNewService<A, E, C> {
|
||||
pub struct FromErrNewService<A, E> {
|
||||
a: A,
|
||||
e: PhantomData<(E, C)>,
|
||||
e: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<A, E, C> FromErrNewService<A, E, C> {
|
||||
impl<A, E> FromErrNewService<A, E> {
|
||||
/// Create new `FromErr` new service instance
|
||||
pub fn new(a: A) -> Self
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
Self { a, e: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, E, C> Clone for FromErrNewService<A, E, C>
|
||||
impl<A, E> Clone for FromErrNewService<A, E>
|
||||
where
|
||||
A: Clone,
|
||||
{
|
||||
@@ -109,20 +109,21 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, E, C> NewService<C> for FromErrNewService<A, E, C>
|
||||
impl<A, E> NewService for FromErrNewService<A, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = A::Response;
|
||||
type Error = E;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = FromErr<A::Service, E>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = FromErrNewServiceFuture<A, E, C>;
|
||||
type Future = FromErrNewServiceFuture<A, E>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
FromErrNewServiceFuture {
|
||||
fut: self.a.new_service(cfg),
|
||||
e: PhantomData,
|
||||
@@ -130,18 +131,18 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FromErrNewServiceFuture<A, E, C>
|
||||
pub struct FromErrNewServiceFuture<A, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
fut: A::Future,
|
||||
e: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<A, E, C> Future for FromErrNewServiceFuture<A, E, C>
|
||||
impl<A, E> Future for FromErrNewServiceFuture<A, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
type Item = FromErr<A::Service, E>;
|
||||
|
@@ -1,10 +1,9 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures::{Future, IntoFuture, Poll};
|
||||
|
||||
pub use void::Void;
|
||||
|
||||
mod and_then;
|
||||
mod and_then_apply;
|
||||
mod and_then_apply_fn;
|
||||
@@ -17,40 +16,29 @@ mod fn_service;
|
||||
mod fn_transform;
|
||||
mod from_err;
|
||||
mod map;
|
||||
mod map_config;
|
||||
mod map_err;
|
||||
mod map_init_err;
|
||||
mod then;
|
||||
mod transform;
|
||||
mod transform_err;
|
||||
|
||||
#[doc(hidden)]
|
||||
#[deprecated(since = "0.3.4", note = "please use `apply_fn` instead")]
|
||||
pub use self::apply::Apply;
|
||||
#[doc(hidden)]
|
||||
#[deprecated(since = "0.3.4", note = "please use `apply_fn_factory` instead")]
|
||||
pub use self::apply::ApplyNewService;
|
||||
#[doc(hidden)]
|
||||
#[deprecated(since = "0.3.4", note = "please use `fn_transform` instead")]
|
||||
pub use self::fn_transform::FnTransform;
|
||||
#[doc(hidden)]
|
||||
#[deprecated(since = "0.3.4", note = "please use `apply_transform` instead")]
|
||||
pub use self::transform::ApplyTransform;
|
||||
|
||||
pub use self::and_then::{AndThen, AndThenNewService};
|
||||
use self::and_then_apply::AndThenTransform;
|
||||
use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService};
|
||||
pub use self::apply::{apply_fn, apply_fn_factory};
|
||||
pub use self::apply_cfg::apply_cfg;
|
||||
use self::apply_cfg::ApplyConfig;
|
||||
pub use self::fn_service::{fn_cfg_factory, fn_factory, fn_service, FnService};
|
||||
pub use self::fn_transform::fn_transform;
|
||||
pub use self::apply::{apply_fn, new_apply_fn, Apply, ApplyNewService};
|
||||
pub use self::apply_cfg::{apply_cfg, new_apply_cfg};
|
||||
pub use self::fn_service::{new_service_cfg, new_service_fn, service_fn, ServiceFn};
|
||||
pub use self::fn_transform::transform_fn;
|
||||
pub use self::from_err::{FromErr, FromErrNewService};
|
||||
pub use self::map::{Map, MapNewService};
|
||||
pub use self::map_config::{MapConfig, MappedConfig, UnitConfig};
|
||||
pub use self::map_err::{MapErr, MapErrNewService};
|
||||
pub use self::map_init_err::MapInitErr;
|
||||
pub use self::then::{Then, ThenNewService};
|
||||
pub use self::transform::{apply_transform, IntoTransform, Transform};
|
||||
|
||||
use self::and_then_apply::AndThenTransform;
|
||||
use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService};
|
||||
|
||||
/// An asynchronous function from `Request` to a `Response`.
|
||||
pub trait Service {
|
||||
/// Requests handled by the service.
|
||||
@@ -194,7 +182,7 @@ impl<T: ?Sized> ServiceExt for T where T: Service {}
|
||||
/// requests on that new TCP stream.
|
||||
///
|
||||
/// `Config` is a service factory configuration type.
|
||||
pub trait NewService<Config = ()> {
|
||||
pub trait NewService {
|
||||
/// Requests handled by the service.
|
||||
type Request;
|
||||
|
||||
@@ -204,6 +192,9 @@ pub trait NewService<Config = ()> {
|
||||
/// Errors produced by the service
|
||||
type Error;
|
||||
|
||||
/// Service factory configuration
|
||||
type Config;
|
||||
|
||||
/// The `Service` value created by this factory
|
||||
type Service: Service<
|
||||
Request = Self::Request,
|
||||
@@ -218,37 +209,29 @@ pub trait NewService<Config = ()> {
|
||||
type Future: Future<Item = Self::Service, Error = Self::InitError>;
|
||||
|
||||
/// Create and return a new service value asynchronously.
|
||||
fn new_service(&self, cfg: &Config) -> Self::Future;
|
||||
fn new_service(&self, cfg: &Self::Config) -> Self::Future;
|
||||
|
||||
/// Apply transform service 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, Config>
|
||||
fn apply<T, T1, B, B1>(self, transform: T1, service: B1) -> AndThenTransform<T, Self, B>
|
||||
where
|
||||
Self: Sized,
|
||||
T: Transform<B::Service, Request = Self::Response, InitError = Self::InitError>,
|
||||
T::Error: From<Self::Error>,
|
||||
T1: IntoTransform<T, B::Service>,
|
||||
B: NewService<Config, InitError = Self::InitError>,
|
||||
B1: IntoNewService<B, Config>,
|
||||
B: NewService<Config = Self::Config, InitError = Self::InitError>,
|
||||
B1: IntoNewService<B>,
|
||||
{
|
||||
AndThenTransform::new(transform.into_transform(), self, service.into_new_service())
|
||||
}
|
||||
|
||||
/// Apply function to specified service and use it as a next service in
|
||||
/// chain.
|
||||
fn apply_fn<B, I, F, Out>(
|
||||
self,
|
||||
service: I,
|
||||
f: F,
|
||||
) -> AndThenApplyNewService<Self, B, F, Out, Config>
|
||||
fn apply_fn<B, I, F, Out>(self, service: I, f: F) -> AndThenApplyNewService<Self, B, F, Out>
|
||||
where
|
||||
Self: Sized,
|
||||
B: NewService<Config, Error = Self::Error, InitError = Self::InitError>,
|
||||
I: IntoNewService<B, Config>,
|
||||
B: NewService<Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,
|
||||
I: IntoNewService<B>,
|
||||
F: FnMut(Self::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<Self::Error>,
|
||||
@@ -256,34 +239,13 @@ pub trait NewService<Config = ()> {
|
||||
AndThenApplyNewService::new(self, service, f)
|
||||
}
|
||||
|
||||
/// Map this service's config type to a different config,
|
||||
/// and use for nested service
|
||||
fn apply_cfg<F, C, S, U>(
|
||||
self,
|
||||
service: U,
|
||||
f: F,
|
||||
) -> AndThenNewService<Self, ApplyConfig<F, S, Config, C>, Config>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(&Config) -> C,
|
||||
U: IntoNewService<S, C>,
|
||||
S: NewService<
|
||||
C,
|
||||
Request = Self::Response,
|
||||
Error = Self::Error,
|
||||
InitError = Self::InitError,
|
||||
>,
|
||||
{
|
||||
self.and_then(ApplyConfig::new(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>
|
||||
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B>
|
||||
where
|
||||
Self: Sized,
|
||||
F: IntoNewService<B, Config>,
|
||||
F: IntoNewService<B>,
|
||||
B: NewService<
|
||||
Config,
|
||||
Config = Self::Config,
|
||||
Request = Self::Response,
|
||||
Error = Self::Error,
|
||||
InitError = Self::InitError,
|
||||
@@ -298,7 +260,7 @@ pub trait NewService<Config = ()> {
|
||||
///
|
||||
/// Note that this function consumes the receiving new service and returns a
|
||||
/// wrapped version of it.
|
||||
fn from_err<E>(self) -> FromErrNewService<Self, E, Config>
|
||||
fn from_err<E>(self) -> FromErrNewService<Self, E>
|
||||
where
|
||||
Self: Sized,
|
||||
E: From<Self::Error>,
|
||||
@@ -312,12 +274,12 @@ pub trait NewService<Config = ()> {
|
||||
///
|
||||
/// Note that this function consumes the receiving future and returns a
|
||||
/// wrapped version of it.
|
||||
fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B, Config>
|
||||
fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B>
|
||||
where
|
||||
Self: Sized,
|
||||
F: IntoNewService<B, Config>,
|
||||
F: IntoNewService<B>,
|
||||
B: NewService<
|
||||
Config,
|
||||
Config = Self::Config,
|
||||
Request = Result<Self::Response, Self::Error>,
|
||||
Error = Self::Error,
|
||||
InitError = Self::InitError,
|
||||
@@ -328,7 +290,7 @@ pub trait NewService<Config = ()> {
|
||||
|
||||
/// Map this service's output to a different type, returning a new service
|
||||
/// of the resulting type.
|
||||
fn map<F, R>(self, f: F) -> MapNewService<Self, F, R, Config>
|
||||
fn map<F, R>(self, f: F) -> MapNewService<Self, F, R>
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnMut(Self::Response) -> R,
|
||||
@@ -337,7 +299,7 @@ pub trait NewService<Config = ()> {
|
||||
}
|
||||
|
||||
/// 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, Config>
|
||||
fn map_err<F, E>(self, f: F) -> MapErrNewService<Self, F, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::Error) -> E + Clone,
|
||||
@@ -345,14 +307,31 @@ pub trait NewService<Config = ()> {
|
||||
MapErrNewService::new(self, f)
|
||||
}
|
||||
|
||||
/// 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, Config>
|
||||
/// Map this factory's init error to a different error, returning a new service.
|
||||
fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::InitError) -> E,
|
||||
{
|
||||
MapInitErr::new(self, f)
|
||||
}
|
||||
|
||||
/// Map config to a different error, returning a new service.
|
||||
fn map_config<F, C>(self, f: F) -> MapConfig<Self, F, C>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(&C) -> MappedConfig<Self::Config>,
|
||||
{
|
||||
MapConfig::new(self, f)
|
||||
}
|
||||
|
||||
/// Replace config with unit
|
||||
fn unit_config<C>(self) -> UnitConfig<Self, C>
|
||||
where
|
||||
Self: NewService<Config = ()> + Sized,
|
||||
{
|
||||
UnitConfig::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, S> Service for &'a mut S
|
||||
@@ -391,34 +370,54 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, C> NewService<C> for Rc<S>
|
||||
impl<S> Service for Rc<RefCell<S>>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: Service,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Future = S::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), S::Error> {
|
||||
self.borrow_mut().poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Self::Request) -> S::Future {
|
||||
self.borrow_mut().call(request)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> NewService for Rc<S>
|
||||
where
|
||||
S: NewService,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Config = S::Config;
|
||||
type Service = S::Service;
|
||||
type InitError = S::InitError;
|
||||
type Future = S::Future;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> S::Future {
|
||||
fn new_service(&self, cfg: &S::Config) -> S::Future {
|
||||
self.as_ref().new_service(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, C> NewService<C> for Arc<S>
|
||||
impl<S> NewService for Arc<S>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Config = S::Config;
|
||||
type Service = S::Service;
|
||||
type InitError = S::InitError;
|
||||
type Future = S::Future;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> S::Future {
|
||||
fn new_service(&self, cfg: &S::Config) -> S::Future {
|
||||
self.as_ref().new_service(cfg)
|
||||
}
|
||||
}
|
||||
@@ -433,9 +432,9 @@ where
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a `NewService`
|
||||
pub trait IntoNewService<T, C = ()>
|
||||
pub trait IntoNewService<T>
|
||||
where
|
||||
T: NewService<C>,
|
||||
T: NewService,
|
||||
{
|
||||
/// Convert to an `NewService`
|
||||
fn into_new_service(self) -> T;
|
||||
@@ -450,27 +449,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, C> IntoNewService<T, C> for T
|
||||
impl<T> IntoNewService<T> for T
|
||||
where
|
||||
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>,
|
||||
T: NewService,
|
||||
{
|
||||
fn into_new_service(self) -> T {
|
||||
self
|
||||
|
@@ -97,17 +97,17 @@ where
|
||||
}
|
||||
|
||||
/// `MapNewService` new service combinator
|
||||
pub struct MapNewService<A, F, Res, Cfg> {
|
||||
pub struct MapNewService<A, F, Res> {
|
||||
a: A,
|
||||
f: F,
|
||||
r: PhantomData<(Res, Cfg)>,
|
||||
r: PhantomData<Res>,
|
||||
}
|
||||
|
||||
impl<A, F, Res, Cfg> MapNewService<A, F, Res, Cfg> {
|
||||
impl<A, F, Res> MapNewService<A, F, Res> {
|
||||
/// Create new `Map` new service instance
|
||||
pub fn new(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
Self {
|
||||
@@ -118,7 +118,7 @@ impl<A, F, Res, Cfg> MapNewService<A, F, Res, Cfg> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Res, Cfg> Clone for MapNewService<A, F, Res, Cfg>
|
||||
impl<A, F, Res> Clone for MapNewService<A, F, Res>
|
||||
where
|
||||
A: Clone,
|
||||
F: Clone,
|
||||
@@ -132,36 +132,37 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Res, Cfg> NewService<Cfg> for MapNewService<A, F, Res, Cfg>
|
||||
impl<A, F, Res> NewService for MapNewService<A, F, Res>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Res + Clone,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = Res;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = Map<A::Service, F, Res>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = MapNewServiceFuture<A, F, Res, Cfg>;
|
||||
type Future = MapNewServiceFuture<A, F, Res>;
|
||||
|
||||
fn new_service(&self, cfg: &Cfg) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
MapNewServiceFuture::new(self.a.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapNewServiceFuture<A, F, Res, Cfg>
|
||||
pub struct MapNewServiceFuture<A, F, Res>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
fut: A::Future,
|
||||
f: Option<F>,
|
||||
}
|
||||
|
||||
impl<A, F, Res, Cfg> MapNewServiceFuture<A, F, Res, Cfg>
|
||||
impl<A, F, Res> MapNewServiceFuture<A, F, Res>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
@@ -169,9 +170,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Res, Cfg> Future for MapNewServiceFuture<A, F, Res, Cfg>
|
||||
impl<A, F, Res> Future for MapNewServiceFuture<A, F, Res>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
type Item = Map<A::Service, F, Res>;
|
||||
|
112
actix-service/src/map_config.rs
Normal file
112
actix-service/src/map_config.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use super::NewService;
|
||||
|
||||
pub enum MappedConfig<'a, T> {
|
||||
Ref(&'a T),
|
||||
Owned(T),
|
||||
}
|
||||
|
||||
/// `MapInitErr` service combinator
|
||||
pub struct MapConfig<A, F, C> {
|
||||
a: A,
|
||||
f: F,
|
||||
e: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<A, F, C> MapConfig<A, F, C> {
|
||||
/// Create new `MapConfig` combinator
|
||||
pub fn new(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService,
|
||||
F: Fn(&C) -> MappedConfig<A::Config>,
|
||||
{
|
||||
Self {
|
||||
a,
|
||||
f,
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, C> Clone for MapConfig<A, F, C>
|
||||
where
|
||||
A: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
f: self.f.clone(),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, C> NewService for MapConfig<A, F, C>
|
||||
where
|
||||
A: NewService,
|
||||
F: Fn(&C) -> MappedConfig<A::Config>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = A::Response;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = C;
|
||||
type Service = A::Service;
|
||||
type InitError = A::InitError;
|
||||
type Future = A::Future;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
match (self.f)(cfg) {
|
||||
MappedConfig::Ref(cfg) => self.a.new_service(cfg),
|
||||
MappedConfig::Owned(cfg) => self.a.new_service(&cfg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `MapInitErr` service combinator
|
||||
pub struct UnitConfig<A, C> {
|
||||
a: A,
|
||||
e: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<A, C> UnitConfig<A, C> {
|
||||
/// Create new `UnitConfig` combinator
|
||||
pub fn new(a: A) -> Self
|
||||
where
|
||||
A: NewService<Config = ()>,
|
||||
{
|
||||
Self { a, e: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, C> Clone for UnitConfig<A, C>
|
||||
where
|
||||
A: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, C> NewService for UnitConfig<A, C>
|
||||
where
|
||||
A: NewService<Config = ()>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = A::Response;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = C;
|
||||
type Service = A::Service;
|
||||
type InitError = A::InitError;
|
||||
type Future = A::Future;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
self.a.new_service(&())
|
||||
}
|
||||
}
|
@@ -98,19 +98,19 @@ where
|
||||
/// service's error.
|
||||
///
|
||||
/// This is created by the `NewServiceExt::map_err` method.
|
||||
pub struct MapErrNewService<A, F, E, C>
|
||||
pub struct MapErrNewService<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
a: A,
|
||||
f: F,
|
||||
e: PhantomData<(E, C)>,
|
||||
e: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<A, F, E, C> MapErrNewService<A, F, E, C>
|
||||
impl<A, F, E> MapErrNewService<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
/// Create new `MapErr` new service instance
|
||||
@@ -123,9 +123,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> Clone for MapErrNewService<A, F, E, C>
|
||||
impl<A, F, E> Clone for MapErrNewService<A, F, E>
|
||||
where
|
||||
A: NewService<C> + Clone,
|
||||
A: NewService + Clone,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
@@ -137,36 +137,37 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> NewService<C> for MapErrNewService<A, F, E, C>
|
||||
impl<A, F, E> NewService for MapErrNewService<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = A::Response;
|
||||
type Error = E;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = MapErr<A::Service, F, E>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = MapErrNewServiceFuture<A, F, E, C>;
|
||||
type Future = MapErrNewServiceFuture<A, F, E>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
MapErrNewServiceFuture::new(self.a.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapErrNewServiceFuture<A, F, E, C>
|
||||
pub struct MapErrNewServiceFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
fut: A::Future,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<A, F, E, C> MapErrNewServiceFuture<A, F, E, C>
|
||||
impl<A, F, E> MapErrNewServiceFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
@@ -174,9 +175,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> Future for MapErrNewServiceFuture<A, F, E, C>
|
||||
impl<A, F, E> Future for MapErrNewServiceFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
type Item = MapErr<A::Service, F, E>;
|
||||
|
@@ -5,17 +5,17 @@ use futures::{Future, Poll};
|
||||
use super::NewService;
|
||||
|
||||
/// `MapInitErr` service combinator
|
||||
pub struct MapInitErr<A, F, E, C> {
|
||||
pub struct MapInitErr<A, F, E> {
|
||||
a: A,
|
||||
f: F,
|
||||
e: PhantomData<(E, C)>,
|
||||
e: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<A, F, E, C> MapInitErr<A, F, E, C> {
|
||||
impl<A, F, E> MapInitErr<A, F, E> {
|
||||
/// Create new `MapInitErr` combinator
|
||||
pub fn new(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
Self {
|
||||
@@ -26,7 +26,7 @@ impl<A, F, E, C> MapInitErr<A, F, E, C> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> Clone for MapInitErr<A, F, E, C>
|
||||
impl<A, F, E> Clone for MapInitErr<A, F, E>
|
||||
where
|
||||
A: Clone,
|
||||
F: Clone,
|
||||
@@ -40,36 +40,37 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> NewService<C> for MapInitErr<A, F, E, C>
|
||||
impl<A, F, E> NewService for MapInitErr<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::InitError) -> E + Clone,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = A::Response;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = A::Service;
|
||||
|
||||
type InitError = E;
|
||||
type Future = MapInitErrFuture<A, F, E, C>;
|
||||
type Future = MapInitErrFuture<A, F, E>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
MapInitErrFuture::new(self.a.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapInitErrFuture<A, F, E, C>
|
||||
pub struct MapInitErrFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
f: F,
|
||||
fut: A::Future,
|
||||
}
|
||||
|
||||
impl<A, F, E, C> MapInitErrFuture<A, F, E, C>
|
||||
impl<A, F, E> MapInitErrFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
@@ -77,9 +78,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> Future for MapInitErrFuture<A, F, E, C>
|
||||
impl<A, F, E> Future for MapInitErrFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
type Item = A::Service;
|
||||
|
@@ -1,5 +1,3 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::{IntoNewService, NewService, Service};
|
||||
@@ -115,38 +113,36 @@ where
|
||||
}
|
||||
|
||||
/// `ThenNewService` new service combinator
|
||||
pub struct ThenNewService<A, B, C> {
|
||||
pub struct ThenNewService<A, B> {
|
||||
a: A,
|
||||
b: B,
|
||||
_t: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<A, B, C> ThenNewService<A, B, C> {
|
||||
impl<A, B> ThenNewService<A, B> {
|
||||
/// Create new `AndThen` combinator
|
||||
pub fn new<F>(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Config = A::Config,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
F: IntoNewService<B, C>,
|
||||
F: IntoNewService<B>,
|
||||
{
|
||||
Self {
|
||||
a,
|
||||
b: f.into_new_service(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> NewService<C> for ThenNewService<A, B, C>
|
||||
impl<A, B> NewService for ThenNewService<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Config = A::Config,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
@@ -155,17 +151,18 @@ where
|
||||
type Request = A::Request;
|
||||
type Response = B::Response;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = Then<A::Service, B::Service>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = ThenNewServiceFuture<A, B, C>;
|
||||
type Future = ThenNewServiceFuture<A, B>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
ThenNewServiceFuture::new(self.a.new_service(cfg), self.b.new_service(cfg))
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> Clone for ThenNewService<A, B, C>
|
||||
impl<A, B> Clone for ThenNewService<A, B>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
@@ -174,16 +171,15 @@ where
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ThenNewServiceFuture<A, B, C>
|
||||
pub struct ThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Config = A::Config,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
@@ -195,11 +191,11 @@ where
|
||||
b: Option<B::Service>,
|
||||
}
|
||||
|
||||
impl<A, B, C> ThenNewServiceFuture<A, B, C>
|
||||
impl<A, B> ThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Config = A::Config,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
@@ -215,11 +211,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> Future for ThenNewServiceFuture<A, B, C>
|
||||
impl<A, B> Future for ThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Config = A::Config,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
|
@@ -6,9 +6,16 @@ use futures::{Async, Future, IntoFuture, Poll};
|
||||
use crate::transform_err::{TransformFromErr, TransformMapInitErr};
|
||||
use crate::{IntoNewService, NewService, Service};
|
||||
|
||||
/// `Transform` service factory.
|
||||
/// The `Transform` trait defines the interface of a Service factory. `Transform`
|
||||
/// is often implemented for middleware, defining how to manufacture a
|
||||
/// middleware Service. A Service that is manufactured by the factory takes
|
||||
/// the Service that follows it during execution as a parameter, assuming
|
||||
/// ownership of the next Service. A Service can be a variety of types, such
|
||||
/// as (but not limited to) another middleware Service, an extractor Service,
|
||||
/// other helper Services, or the request handler endpoint Service.
|
||||
///
|
||||
/// A Service is created by the factory during server initialization.
|
||||
///
|
||||
/// Transform factory creates service that wraps other services.
|
||||
/// `Config` is a service factory configuration type.
|
||||
pub trait Transform<S> {
|
||||
/// Requests handled by the service.
|
||||
@@ -33,7 +40,7 @@ pub trait Transform<S> {
|
||||
/// The future response value.
|
||||
type Future: Future<Item = Self::Transform, Error = Self::InitError>;
|
||||
|
||||
/// Create and return a new service value asynchronously.
|
||||
/// Creates and returns a new Service component, asynchronously
|
||||
fn new_transform(&self, service: S) -> Self::Future;
|
||||
|
||||
/// Map this service's factory error to a different error,
|
||||
@@ -126,11 +133,11 @@ where
|
||||
/// Apply transform to service factory. Function returns
|
||||
/// services factory that in initialization creates
|
||||
/// service and applies transform to this service.
|
||||
pub fn apply_transform<T, S, C, F, U>(
|
||||
pub fn apply_transform<T, S, F, U>(
|
||||
t: F,
|
||||
service: U,
|
||||
) -> impl NewService<
|
||||
C,
|
||||
Config = S::Config,
|
||||
Request = T::Request,
|
||||
Response = T::Response,
|
||||
Error = T::Error,
|
||||
@@ -138,24 +145,23 @@ pub fn apply_transform<T, S, C, F, U>(
|
||||
InitError = S::InitError,
|
||||
> + Clone
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
F: IntoTransform<T, S::Service>,
|
||||
U: IntoNewService<S, C>,
|
||||
U: IntoNewService<S>,
|
||||
{
|
||||
ApplyTransform::new(t.into_transform(), service.into_new_service())
|
||||
}
|
||||
|
||||
/// `Apply` transform to new service
|
||||
pub struct ApplyTransform<T, S, C> {
|
||||
pub struct ApplyTransform<T, S> {
|
||||
s: Rc<S>,
|
||||
t: Rc<T>,
|
||||
_t: std::marker::PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<T, S, C> ApplyTransform<T, S, C>
|
||||
impl<T, S> ApplyTransform<T, S>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
{
|
||||
/// Create new `ApplyTransform` new service instance
|
||||
@@ -163,35 +169,34 @@ where
|
||||
Self {
|
||||
s: Rc::new(service),
|
||||
t: Rc::new(t.into_transform()),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C> Clone for ApplyTransform<T, S, C> {
|
||||
impl<T, S> Clone for ApplyTransform<T, S> {
|
||||
fn clone(&self) -> Self {
|
||||
ApplyTransform {
|
||||
s: self.s.clone(),
|
||||
t: self.t.clone(),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C> NewService<C> for ApplyTransform<T, S, C>
|
||||
impl<T, S> NewService for ApplyTransform<T, S>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
|
||||
type Config = S::Config;
|
||||
type Service = T::Transform;
|
||||
type InitError = T::InitError;
|
||||
type Future = ApplyTransformFuture<T, S, C>;
|
||||
type Future = ApplyTransformFuture<T, S>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &S::Config) -> Self::Future {
|
||||
ApplyTransformFuture {
|
||||
t_cell: self.t.clone(),
|
||||
fut_a: self.s.new_service(cfg).into_future(),
|
||||
@@ -200,9 +205,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ApplyTransformFuture<T, S, C>
|
||||
pub struct ApplyTransformFuture<T, S>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
{
|
||||
fut_a: S::Future,
|
||||
@@ -210,9 +215,9 @@ where
|
||||
t_cell: Rc<T>,
|
||||
}
|
||||
|
||||
impl<T, S, C> Future for ApplyTransformFuture<T, S, C>
|
||||
impl<T, S> Future for ApplyTransformFuture<T, S>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
{
|
||||
type Item = T::Transform;
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-test-server"
|
||||
version = "0.2.0"
|
||||
version = "0.2.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix test server"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -11,7 +11,7 @@ categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
workspace = ".."
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "tls", "rust-tls"]
|
||||
@@ -34,7 +34,7 @@ rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
|
||||
|
||||
[dependencies]
|
||||
actix-rt = "0.2.1"
|
||||
actix-server = "0.4.0"
|
||||
actix-server = "0.5.0"
|
||||
actix-server-config = "0.1.0"
|
||||
|
||||
log = "0.4"
|
||||
@@ -56,4 +56,4 @@ webpki = { version = "0.19", optional = true }
|
||||
webpki-roots = { version = "0.16", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-service = "0.3.4"
|
||||
actix-service = "0.4.0"
|
||||
|
1
actix-test-server/LICENSE-APACHE
Symbolic link
1
actix-test-server/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-test-server/LICENSE-MIT
Symbolic link
1
actix-test-server/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -6,7 +6,7 @@ use actix_rt::{Runtime, System};
|
||||
use actix_server::{Server, StreamServiceFactory};
|
||||
pub use actix_server_config::{Io, ServerConfig};
|
||||
|
||||
use futures::Future;
|
||||
use futures::future::{lazy, Future, IntoFuture};
|
||||
use net2::TcpBuilder;
|
||||
use tokio_reactor::Handle;
|
||||
use tokio_tcp::TcpStream;
|
||||
@@ -19,11 +19,11 @@ use tokio_tcp::TcpStream;
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_service::{fn_service, IntoNewService};
|
||||
/// use actix_service::{service_fn, IntoNewService};
|
||||
/// use actix_test_server::TestServer;
|
||||
///
|
||||
/// fn main() {
|
||||
/// let srv = TestServer::with(|| fn_service(
|
||||
/// let srv = TestServer::with(|| service_fn(
|
||||
/// |sock| {
|
||||
/// println!("New connection: {:?}", sock);
|
||||
/// Ok::<_, ()>(())
|
||||
@@ -99,6 +99,15 @@ impl TestServerRuntime {
|
||||
self.rt.block_on(fut)
|
||||
}
|
||||
|
||||
/// Runs the provided function, with runtime enabled.
|
||||
pub fn run_on<F, R>(&mut self, f: F) -> Result<R::Item, R::Error>
|
||||
where
|
||||
F: FnOnce() -> R,
|
||||
R: IntoFuture,
|
||||
{
|
||||
self.rt.block_on(lazy(|| f().into_future()))
|
||||
}
|
||||
|
||||
/// Spawn future to the current runtime
|
||||
pub fn spawn<F>(&mut self, fut: F)
|
||||
where
|
||||
|
9
actix-threadpool/CHANGES.md
Normal file
9
actix-threadpool/CHANGES.md
Normal file
@@ -0,0 +1,9 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.1] - 2019-06-05
|
||||
|
||||
* Update parking_lot
|
||||
|
||||
## [0.1.0] - 2019-03-28
|
||||
|
||||
* Move threadpool to separate crate
|
27
actix-threadpool/Cargo.toml
Normal file
27
actix-threadpool/Cargo.toml
Normal file
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "actix-threadpool"
|
||||
version = "0.1.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix thread pool for sync code"
|
||||
keywords = ["actix", "network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-threadpool/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "actix_threadpool"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
derive_more = "0.14"
|
||||
futures = "0.1.25"
|
||||
parking_lot = "0.8"
|
||||
lazy_static = "1.2"
|
||||
log = "0.4"
|
||||
num_cpus = "1.10"
|
||||
threadpool = "1.7"
|
1
actix-threadpool/LICENSE-APACHE
Symbolic link
1
actix-threadpool/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-threadpool/LICENSE-MIT
Symbolic link
1
actix-threadpool/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -9,7 +9,7 @@ use parking_lot::Mutex;
|
||||
use threadpool::ThreadPool;
|
||||
|
||||
/// Env variable for default cpu pool size
|
||||
const ENV_CPU_POOL_VAR: &str = "ACTIX_CPU_POOL";
|
||||
const ENV_CPU_POOL_VAR: &str = "ACTIX_THREADPOOL";
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub(crate) static ref DEFAULT_POOL: Mutex<ThreadPool> = {
|
||||
@@ -18,7 +18,7 @@ lazy_static::lazy_static! {
|
||||
if let Ok(val) = val.parse() {
|
||||
val
|
||||
} else {
|
||||
log::error!("Can not parse ACTIX_CPU_POOL value");
|
||||
log::error!("Can not parse ACTIX_THREADPOOL value");
|
||||
num_cpus::get() * 5
|
||||
}
|
||||
}
|
2
actix-tower/CHANGES.md
Normal file
2
actix-tower/CHANGES.md
Normal file
@@ -0,0 +1,2 @@
|
||||
# Changes
|
||||
|
29
actix-tower/Cargo.toml
Normal file
29
actix-tower/Cargo.toml
Normal file
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "actix-tower"
|
||||
version = "0.1.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>", "Marcus Griep <marcus@griep.us>"]
|
||||
description = "Actix Tower"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-tower/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "actix/actix-tower", branch = "master" }
|
||||
appveyor = { repository = "actix/actix-net" }
|
||||
codecov = { repository = "actix/actix-tower", branch = "master", service = "github" }
|
||||
|
||||
[lib]
|
||||
name = "actix_tower"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.3.6"
|
||||
futures = "0.1.24"
|
||||
tower-service = "0.2.0"
|
||||
|
1
actix-tower/LICENSE-APACHE
Symbolic link
1
actix-tower/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-tower/LICENSE-MIT
Symbolic link
1
actix-tower/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
587
actix-tower/src/lib.rs
Normal file
587
actix-tower/src/lib.rs
Normal file
@@ -0,0 +1,587 @@
|
||||
//! Utilities to provide interoperability between services based on the
|
||||
//! `actix-service` and `tower-service` crates.
|
||||
//!
|
||||
//! ## Example
|
||||
//!
|
||||
//! In the following example, we take a `RandomService`—which will always
|
||||
//! return 4—and wraps it with a middleware that will always add 1 to the
|
||||
//! result. This pattern can be further used to wrap services from either
|
||||
//! `tower-service` or `actix-service` with middleware provided by the other.
|
||||
//!
|
||||
//! ```
|
||||
//! use actix_tower::ActixServiceExt;
|
||||
//! # use futures::{Async, Future};
|
||||
//! use actix_service::Service;
|
||||
//!
|
||||
//! struct RandomService;
|
||||
//! impl Service for RandomService {
|
||||
//! // …
|
||||
//! # type Request = ();
|
||||
//! # type Response = u32;
|
||||
//! # type Error = ();
|
||||
//! # type Future = futures::future::FutureResult<Self::Response, Self::Error>;
|
||||
//! #
|
||||
//! # fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
//! # Ok(Async::Ready(()))
|
||||
//! # }
|
||||
//! #
|
||||
//! # fn call(&mut self, _req: Self::Request) -> Self::Future {
|
||||
//! # futures::finished(4)
|
||||
//! # }
|
||||
//! }
|
||||
//!
|
||||
//! struct AddOneMiddleware<S>(S);
|
||||
//! impl<S, R> tower_service::Service<R> for AddOneMiddleware<S>
|
||||
//! where
|
||||
//! S: tower_service::Service<R, Response = u32>,
|
||||
//! S::Future: 'static,
|
||||
//! {
|
||||
//! /// …
|
||||
//! # type Response = u32;
|
||||
//! # type Error = S::Error;
|
||||
//! # type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
||||
//! #
|
||||
//! # fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
//! # self.0.poll_ready()
|
||||
//! # }
|
||||
//! #
|
||||
//! # fn call(&mut self, req: R) -> Self::Future {
|
||||
//! # let fut = self.0.call(req).map(|x| x + 1);
|
||||
//! # Box::new(fut)
|
||||
//! # }
|
||||
//! }
|
||||
//!
|
||||
//! let mut s = RandomService.wrap_with_tower_middleware(AddOneMiddleware);
|
||||
//! assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
//! assert_eq!(Ok(Async::Ready(5)), s.call(()).poll());
|
||||
//! ```
|
||||
|
||||
use actix_service::Service as ActixService;
|
||||
use std::marker::PhantomData;
|
||||
use tower_service::Service as TowerService;
|
||||
|
||||
/// Compatibility wrapper associating a `tower_service::Service` with a particular
|
||||
/// `Request` type, so that it can be used as an `actix_service::Service`.
|
||||
///
|
||||
/// Generally created through convenience methods on the `TowerServiceExt<R>` trait.
|
||||
pub struct ActixCompat<S, R> {
|
||||
inner: S,
|
||||
_phantom: PhantomData<R>,
|
||||
}
|
||||
|
||||
impl<S, R> ActixCompat<S, R> {
|
||||
/// Wraps a `tower_service::Service` in a compatibility wrapper.
|
||||
pub fn new(inner: S) -> Self {
|
||||
ActixCompat {
|
||||
inner,
|
||||
_phantom: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension trait for wrapping a `tower_service::Service` instance for use as
|
||||
/// an `actix_service::Service`.
|
||||
pub trait TowerServiceExt<R> : TowerService<R> + Sized {
|
||||
/// Wraps a `tower_service::Service` in a compatibility wrapper.
|
||||
///
|
||||
/// ```
|
||||
/// use actix_service::Service;
|
||||
/// use actix_tower::TowerServiceExt;
|
||||
/// # use futures::{Async, Future};
|
||||
///
|
||||
/// struct RandomService;
|
||||
/// impl<R> tower_service::Service<R> for RandomService {
|
||||
/// // …
|
||||
/// # type Response = u32;
|
||||
/// # type Error = ();
|
||||
/// # type Future = futures::future::FutureResult<Self::Response, Self::Error>;
|
||||
/// #
|
||||
/// # fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
/// # Ok(Async::Ready(()))
|
||||
/// # }
|
||||
/// #
|
||||
/// # fn call(&mut self, _req: R) -> Self::Future {
|
||||
/// # futures::finished(4)
|
||||
/// # }
|
||||
/// }
|
||||
///
|
||||
/// let mut s = RandomService.into_actix_service();
|
||||
/// assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
/// assert_eq!(Ok(Async::Ready(4)), s.call(()).poll());
|
||||
/// ```
|
||||
fn into_actix_service(self) -> ActixCompat<Self, R> {
|
||||
ActixCompat::new(self)
|
||||
}
|
||||
|
||||
/// Takes a function that, when provided with an `actix_service::Service` wraps it
|
||||
/// and returns a new service. Useful for wrapping a `tower_service::Service` with
|
||||
/// middleware built for `actix_service`.
|
||||
///
|
||||
/// ```
|
||||
/// use actix_tower::TowerServiceExt;
|
||||
/// # use futures::{Async, Future};
|
||||
/// use tower_service::Service;
|
||||
///
|
||||
/// struct RandomService;
|
||||
/// impl<R> Service<R> for RandomService {
|
||||
/// // …
|
||||
/// # type Response = u32;
|
||||
/// # type Error = ();
|
||||
/// # type Future = futures::future::FutureResult<Self::Response, Self::Error>;
|
||||
/// #
|
||||
/// # fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
/// # Ok(Async::Ready(()))
|
||||
/// # }
|
||||
/// #
|
||||
/// # fn call(&mut self, _req: R) -> Self::Future {
|
||||
/// # futures::finished(4)
|
||||
/// # }
|
||||
/// }
|
||||
///
|
||||
/// struct AddOneTransform<S>(S);
|
||||
/// impl<S> actix_service::Service for AddOneTransform<S>
|
||||
/// where
|
||||
/// S: actix_service::Service<Response = u32>,
|
||||
/// S::Future: 'static,
|
||||
/// {
|
||||
/// /// …
|
||||
/// # type Request = S::Request;
|
||||
/// # type Response = u32;
|
||||
/// # type Error = S::Error;
|
||||
/// # type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
||||
/// #
|
||||
/// # fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
/// # self.0.poll_ready()
|
||||
/// # }
|
||||
/// #
|
||||
/// # fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
/// # let fut = self.0.call(req).map(|x| x + 1);
|
||||
/// # Box::new(fut)
|
||||
/// # }
|
||||
/// }
|
||||
///
|
||||
/// let mut s = RandomService.wrap_with_actix_middleware(AddOneTransform);
|
||||
/// assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
/// assert_eq!(Ok(Async::Ready(5)), s.call(()).poll());
|
||||
/// ```
|
||||
fn wrap_with_actix_middleware<F, U>(self, f: F) -> TowerCompat<U>
|
||||
where
|
||||
F: FnOnce(ActixCompat<Self, R>) -> U,
|
||||
U: ActixService<Request = R>
|
||||
{
|
||||
f(self.into_actix_service()).into_tower_service()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, R> TowerServiceExt<R> for S
|
||||
where
|
||||
S: TowerService<R> + Sized
|
||||
{}
|
||||
|
||||
impl<S, R> ActixService for ActixCompat<S, R>
|
||||
where
|
||||
S: TowerService<R>,
|
||||
{
|
||||
type Request = R;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Future = S::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
TowerService::poll_ready(&mut self.inner)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
TowerService::call(&mut self.inner, req)
|
||||
}
|
||||
}
|
||||
|
||||
/// Compatibility wrapper associating an `actix_service::Service` with a particular
|
||||
/// `Request` type, so that it can be used as a `tower_service::Service`.
|
||||
///
|
||||
/// Generally created through convenience methods on the `ActixServiceExt<R>` trait.
|
||||
pub struct TowerCompat<S> {
|
||||
inner: S,
|
||||
}
|
||||
|
||||
impl<S> TowerCompat<S> {
|
||||
/// Wraps an `actix_service::Service` in a compatibility wrapper.
|
||||
pub fn new(inner: S) -> Self {
|
||||
TowerCompat {
|
||||
inner,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension trait for wrapping an `actix_service::Service` instance for use as
|
||||
/// a `tower_service::Service`.
|
||||
pub trait ActixServiceExt: ActixService + Sized {
|
||||
/// Wraps a `tower_service::Service` in a compatibility wrapper.
|
||||
///
|
||||
/// ```
|
||||
/// use actix_tower::ActixServiceExt;
|
||||
/// # use futures::{Async, Future};
|
||||
/// use tower_service::Service;
|
||||
///
|
||||
/// struct RandomService;
|
||||
/// impl actix_service::Service for RandomService {
|
||||
/// // …
|
||||
/// # type Request = ();
|
||||
/// # type Response = u32;
|
||||
/// # type Error = ();
|
||||
/// # type Future = futures::future::FutureResult<Self::Response, Self::Error>;
|
||||
/// #
|
||||
/// # fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
/// # Ok(Async::Ready(()))
|
||||
/// # }
|
||||
/// #
|
||||
/// # fn call(&mut self, _req: Self::Request) -> Self::Future {
|
||||
/// # futures::finished(4)
|
||||
/// # }
|
||||
/// }
|
||||
///
|
||||
/// let mut s = RandomService.into_tower_service();
|
||||
/// assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
/// assert_eq!(Ok(Async::Ready(4)), s.call(()).poll());
|
||||
/// ```
|
||||
fn into_tower_service(self) -> TowerCompat<Self> {
|
||||
TowerCompat::new(self)
|
||||
}
|
||||
|
||||
/// Takes a function that, when provided with a `tower_service::Service` wraps it
|
||||
/// and returns a new service. Useful for wrapping an `actix_service::Service` with
|
||||
/// middleware built for `tower_service`.
|
||||
///
|
||||
/// ```
|
||||
/// use actix_tower::ActixServiceExt;
|
||||
/// # use futures::{Async, Future};
|
||||
/// use actix_service::Service;
|
||||
///
|
||||
/// struct RandomService;
|
||||
/// impl Service for RandomService {
|
||||
/// // …
|
||||
/// # type Request = ();
|
||||
/// # type Response = u32;
|
||||
/// # type Error = ();
|
||||
/// # type Future = futures::future::FutureResult<Self::Response, Self::Error>;
|
||||
/// #
|
||||
/// # fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
/// # Ok(Async::Ready(()))
|
||||
/// # }
|
||||
/// #
|
||||
/// # fn call(&mut self, _req: Self::Request) -> Self::Future {
|
||||
/// # futures::finished(4)
|
||||
/// # }
|
||||
/// }
|
||||
///
|
||||
/// struct AddOneMiddleware<S>(S);
|
||||
/// impl<S, R> tower_service::Service<R> for AddOneMiddleware<S>
|
||||
/// where
|
||||
/// S: tower_service::Service<R, Response = u32>,
|
||||
/// S::Future: 'static,
|
||||
/// {
|
||||
/// /// …
|
||||
/// # type Response = u32;
|
||||
/// # type Error = S::Error;
|
||||
/// # type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
||||
/// #
|
||||
/// # fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
/// # self.0.poll_ready()
|
||||
/// # }
|
||||
/// #
|
||||
/// # fn call(&mut self, req: R) -> Self::Future {
|
||||
/// # let fut = self.0.call(req).map(|x| x + 1);
|
||||
/// # Box::new(fut)
|
||||
/// # }
|
||||
/// }
|
||||
///
|
||||
/// let mut s = RandomService.wrap_with_tower_middleware(AddOneMiddleware);
|
||||
/// assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
/// assert_eq!(Ok(Async::Ready(5)), s.call(()).poll());
|
||||
/// ```
|
||||
fn wrap_with_tower_middleware<F, U>(self, f: F) -> ActixCompat<U, Self::Request>
|
||||
where
|
||||
F: FnOnce(TowerCompat<Self>) -> U,
|
||||
U: TowerService<Self::Request>
|
||||
{
|
||||
f(self.into_tower_service()).into_actix_service()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> ActixServiceExt for S
|
||||
where
|
||||
S: ActixService + Sized
|
||||
{}
|
||||
|
||||
impl<S> TowerService<S::Request> for TowerCompat<S>
|
||||
where
|
||||
S: ActixService,
|
||||
{
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Future = S::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
|
||||
ActixService::poll_ready(&mut self.inner)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: S::Request) -> Self::Future {
|
||||
ActixService::call(&mut self.inner, req)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod tower_service_into_actix_service {
|
||||
use crate::TowerServiceExt;
|
||||
use actix_service::{Service as ActixService, ServiceExt, Transform};
|
||||
use futures::{future::FutureResult, Async, Poll, Future};
|
||||
use tower_service::Service as TowerService;
|
||||
|
||||
|
||||
#[test]
|
||||
fn random_service_returns_4() {
|
||||
let mut s = RandomService.into_actix_service();
|
||||
|
||||
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
|
||||
assert_eq!(Ok(Async::Ready(4)), s.call(()).poll());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_service_can_combine() {
|
||||
let mut s = RandomService.into_actix_service().map(|x| x + 1);
|
||||
|
||||
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
|
||||
assert_eq!(Ok(Async::Ready(5)), s.call(()).poll());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_service_can_use_actix_middleware() {
|
||||
let mut s = RandomService.wrap_with_actix_middleware(DoMathTransform);
|
||||
|
||||
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
|
||||
assert_eq!(Ok(Async::Ready(68)), s.call(()).poll());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_service_and_add_service_chained() {
|
||||
let s1 = RandomService.into_actix_service();
|
||||
let s2 = AddOneService.into_actix_service();
|
||||
let s3 = AddOneService.into_actix_service();
|
||||
|
||||
let mut s = s1.and_then(s2).and_then(s3);
|
||||
|
||||
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
|
||||
assert_eq!(Ok(Async::Ready(6)), s.call(()).poll());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_service_and_add_service_and_ignoring_service_chained() {
|
||||
let s1 = RandomService.into_actix_service();
|
||||
let s2 = AddOneService.into_actix_service();
|
||||
let s3 = AddOneService.into_actix_service();
|
||||
let s4 = RandomService.into_actix_service();
|
||||
|
||||
let mut s = s1.and_then(s2).and_then(s3).and_then(s4);
|
||||
|
||||
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
|
||||
assert_eq!(Ok(Async::Ready(4)), s.call(()).poll());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_service_can_be_transformed_to_do_math() {
|
||||
let transform = DoMath;
|
||||
|
||||
let mut s = transform.new_transform(RandomService.into_actix_service()).wait().unwrap();
|
||||
|
||||
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
|
||||
assert_eq!(Ok(Async::Ready(68)), s.call(()).poll());
|
||||
}
|
||||
|
||||
struct RandomService;
|
||||
impl<R> TowerService<R> for RandomService {
|
||||
type Response = u32;
|
||||
type Error = ();
|
||||
type Future = FutureResult<Self::Response, Self::Error>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, _req: R) -> Self::Future {
|
||||
futures::finished(4)
|
||||
}
|
||||
}
|
||||
|
||||
struct AddOneService;
|
||||
impl TowerService<u32> for AddOneService {
|
||||
type Response = u32;
|
||||
type Error = ();
|
||||
type Future = FutureResult<Self::Response, Self::Error>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: u32) -> Self::Future {
|
||||
futures::finished(req + 1)
|
||||
}
|
||||
}
|
||||
|
||||
struct DoMathTransform<S>(S);
|
||||
impl<S> ActixService for DoMathTransform<S>
|
||||
where
|
||||
S: ActixService<Response = u32>,
|
||||
S::Future: 'static,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = u32;
|
||||
type Error = S::Error;
|
||||
type Future = Box<dyn 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 {
|
||||
let fut = self.0.call(req).map(|x| x * 17);
|
||||
Box::new(fut)
|
||||
}
|
||||
}
|
||||
|
||||
struct DoMath;
|
||||
impl<S> Transform<S> for DoMath
|
||||
where
|
||||
S: ActixService<Response = u32>,
|
||||
S::Future: 'static,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = u32;
|
||||
type Error = S::Error;
|
||||
type Transform = DoMathTransform<S>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
futures::finished(DoMathTransform(service))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod actix_service_into_tower_service {
|
||||
use crate::{ActixServiceExt, TowerServiceExt};
|
||||
use actix_service::{Service as ActixService, ServiceExt};
|
||||
use futures::{future::FutureResult, Async, Poll, Future};
|
||||
use tower_service::Service as TowerService;
|
||||
|
||||
|
||||
#[test]
|
||||
fn random_service_returns_4() {
|
||||
let mut s = RandomService.into_tower_service();
|
||||
|
||||
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
|
||||
assert_eq!(Ok(Async::Ready(4)), s.call(()).poll());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_service_can_use_tower_middleware() {
|
||||
let mut s = AddOneService::wrap(RandomService.into_tower_service()).into_actix_service();
|
||||
|
||||
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
|
||||
assert_eq!(Ok(Async::Ready(5)), s.call(()).poll());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn do_math_service_can_use_tower_middleware() {
|
||||
let mut s = AddOneService::wrap(DoMathService.into_tower_service()).into_actix_service();
|
||||
|
||||
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
|
||||
assert_eq!(Ok(Async::Ready(188)), s.call(11).poll());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_service_and_add_service_and_ignoring_service_chained() {
|
||||
let s1 = RandomService.wrap_with_tower_middleware(AddOneService::wrap);
|
||||
let s2 = DoMathService.wrap_with_tower_middleware(AddOneService::wrap);
|
||||
|
||||
let mut s = s1.and_then(s2);
|
||||
|
||||
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
|
||||
|
||||
assert_eq!(Ok(Async::Ready(86)), s.call(()).poll());
|
||||
}
|
||||
|
||||
struct RandomService;
|
||||
impl ActixService for RandomService {
|
||||
type Request = ();
|
||||
type Response = u32;
|
||||
type Error = ();
|
||||
type Future = FutureResult<Self::Response, Self::Error>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, _req: Self::Request) -> Self::Future {
|
||||
futures::finished(4)
|
||||
}
|
||||
}
|
||||
|
||||
struct AddOneService<S> {
|
||||
inner: S
|
||||
}
|
||||
|
||||
impl<S> AddOneService<S> {
|
||||
fn wrap(inner: S) -> Self {
|
||||
AddOneService {
|
||||
inner,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, R> TowerService<R> for AddOneService<S>
|
||||
where
|
||||
S: TowerService<R, Response = u32>,
|
||||
S::Future: 'static,
|
||||
{
|
||||
type Response = u32;
|
||||
type Error = S::Error;
|
||||
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.inner.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: R) -> Self::Future {
|
||||
let fut = self.inner.call(req)
|
||||
.map(|x| x + 1);
|
||||
|
||||
Box::new(fut)
|
||||
}
|
||||
}
|
||||
|
||||
struct DoMathService;
|
||||
impl ActixService for DoMathService {
|
||||
type Request = u32;
|
||||
type Response = u32;
|
||||
type Error = ();
|
||||
type Future = FutureResult<Self::Response, Self::Error>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
futures::finished(req * 17)
|
||||
}
|
||||
}}
|
||||
}
|
@@ -1,9 +1,36 @@
|
||||
# Changes
|
||||
|
||||
##[0.4.1] - 2019-05-15
|
||||
|
||||
### Changed
|
||||
|
||||
* Change `Either` constructor
|
||||
|
||||
|
||||
## [0.4.0] - 2019-05-11
|
||||
|
||||
### Changed
|
||||
|
||||
* Change `Either` to handle two nexted services
|
||||
|
||||
* Upgrade actix-service 0.4
|
||||
|
||||
### Deleted
|
||||
|
||||
* Framed related services
|
||||
|
||||
* Stream related services
|
||||
|
||||
## [0.3.5] - 2019-04-04
|
||||
|
||||
### Added
|
||||
|
||||
* Allow to send messages to `FramedTransport` via mpsc channel.
|
||||
|
||||
### Changed
|
||||
|
||||
* Remove 'static constraint from Clonable service
|
||||
|
||||
|
||||
## [0.3.4] - 2019-03-12
|
||||
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-utils"
|
||||
version = "0.3.4"
|
||||
version = "0.4.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix utils - various actix net related services"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -18,13 +18,14 @@ name = "actix_utils"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.3.3"
|
||||
actix-service = "0.4.0"
|
||||
actix-codec = "0.1.1"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.24"
|
||||
either = "1.5.2"
|
||||
futures = "0.1.25"
|
||||
tokio-timer = "0.2.8"
|
||||
tokio-current-thread = "0.1.4"
|
||||
log = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.1"
|
||||
actix-rt = "0.2.2"
|
||||
|
1
actix-utils/LICENSE-APACHE
Symbolic link
1
actix-utils/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-utils/LICENSE-MIT
Symbolic link
1
actix-utils/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -7,12 +7,12 @@ use futures::Poll;
|
||||
use super::cell::Cell;
|
||||
|
||||
/// Service that allows to turn non-clone service to a service with `Clone` impl
|
||||
pub struct CloneableService<T: 'static> {
|
||||
pub struct CloneableService<T> {
|
||||
service: Cell<T>,
|
||||
_t: PhantomData<Rc<()>>,
|
||||
}
|
||||
|
||||
impl<T: 'static> CloneableService<T> {
|
||||
impl<T> CloneableService<T> {
|
||||
pub fn new(service: T) -> Self
|
||||
where
|
||||
T: Service,
|
||||
@@ -24,7 +24,7 @@ impl<T: 'static> CloneableService<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static> Clone for CloneableService<T> {
|
||||
impl<T> Clone for CloneableService<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
service: self.service.clone(),
|
||||
@@ -35,7 +35,7 @@ impl<T: 'static> Clone for CloneableService<T> {
|
||||
|
||||
impl<T> Service for CloneableService<T>
|
||||
where
|
||||
T: Service + 'static,
|
||||
T: Service,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
|
@@ -1,5 +1,5 @@
|
||||
//! Contains `Either` service and related types and functions.
|
||||
use actix_service::{NewService, Service};
|
||||
use actix_service::{IntoNewService, NewService, Service};
|
||||
use futures::{future, try_ready, Async, Future, IntoFuture, Poll};
|
||||
|
||||
/// Combine two different service types into a single type.
|
||||
@@ -7,16 +7,16 @@ use futures::{future, try_ready, Async, Future, IntoFuture, Poll};
|
||||
/// Both services must be of the same request, response, and error types.
|
||||
/// `EitherService` is useful for handling conditional branching in service
|
||||
/// middleware to different inner service types.
|
||||
pub enum EitherService<A, B> {
|
||||
A(A),
|
||||
B(B),
|
||||
pub struct EitherService<A, B> {
|
||||
left: A,
|
||||
right: B,
|
||||
}
|
||||
|
||||
impl<A: Clone, B: Clone> Clone for EitherService<A, B> {
|
||||
fn clone(&self) -> Self {
|
||||
match self {
|
||||
EitherService::A(srv) => EitherService::A(srv.clone()),
|
||||
EitherService::B(srv) => EitherService::B(srv.clone()),
|
||||
EitherService {
|
||||
left: self.left.clone(),
|
||||
right: self.right.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,129 +24,126 @@ impl<A: Clone, B: Clone> Clone for EitherService<A, B> {
|
||||
impl<A, B> Service for EitherService<A, B>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Request = A::Request, Response = A::Response, Error = A::Error>,
|
||||
B: Service<Response = A::Response, Error = A::Error>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Request = either::Either<A::Request, B::Request>;
|
||||
type Response = A::Response;
|
||||
type Error = A::Error;
|
||||
type Future = future::Either<A::Future, B::Future>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
match self {
|
||||
EitherService::A(ref mut inner) => inner.poll_ready(),
|
||||
EitherService::B(ref mut inner) => inner.poll_ready(),
|
||||
let left = self.left.poll_ready()?;
|
||||
let right = self.right.poll_ready()?;
|
||||
|
||||
if left.is_ready() && right.is_ready() {
|
||||
Ok(Async::Ready(()))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||
match self {
|
||||
EitherService::A(ref mut inner) => future::Either::A(inner.call(req)),
|
||||
EitherService::B(ref mut inner) => future::Either::B(inner.call(req)),
|
||||
fn call(&mut self, req: either::Either<A::Request, B::Request>) -> Self::Future {
|
||||
match req {
|
||||
either::Either::Left(req) => future::Either::A(self.left.call(req)),
|
||||
either::Either::Right(req) => future::Either::B(self.right.call(req)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Combine two different new service types into a single type.
|
||||
pub enum Either<A, B> {
|
||||
A(A),
|
||||
B(B),
|
||||
/// Combine two different new service types into a single service.
|
||||
pub struct Either<A, B> {
|
||||
left: A,
|
||||
right: B,
|
||||
}
|
||||
|
||||
impl<A, B> Either<A, B> {
|
||||
pub fn new_a<C>(srv: A) -> Self
|
||||
pub fn new<F1, F2>(srv_a: F1, srv_b: F2) -> Either<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = A::Request,
|
||||
Config = A::Config,
|
||||
Response = A::Response,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
F1: IntoNewService<A>,
|
||||
F2: IntoNewService<B>,
|
||||
{
|
||||
Either::A(srv)
|
||||
}
|
||||
|
||||
pub fn new_b<C>(srv: B) -> Self
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = A::Request,
|
||||
Response = A::Response,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
{
|
||||
Either::B(srv)
|
||||
Either {
|
||||
left: srv_a.into_new_service(),
|
||||
right: srv_b.into_new_service(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> NewService<C> for Either<A, B>
|
||||
impl<A, B> NewService for Either<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = A::Request,
|
||||
Config = A::Config,
|
||||
Response = A::Response,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Request = either::Either<A::Request, B::Request>;
|
||||
type Response = A::Response;
|
||||
type Error = A::Error;
|
||||
type InitError = A::InitError;
|
||||
type Config = A::Config;
|
||||
type Service = EitherService<A::Service, B::Service>;
|
||||
type Future = EitherNewService<A, B, C>;
|
||||
type Future = EitherNewService<A, B>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
match self {
|
||||
Either::A(ref inner) => EitherNewService::A(inner.new_service(cfg)),
|
||||
Either::B(ref inner) => EitherNewService::B(inner.new_service(cfg)),
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
EitherNewService {
|
||||
left: None,
|
||||
right: None,
|
||||
left_fut: self.left.new_service(cfg),
|
||||
right_fut: self.right.new_service(cfg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A: Clone, B: Clone> Clone for Either<A, B> {
|
||||
fn clone(&self) -> Self {
|
||||
match self {
|
||||
Either::A(srv) => Either::A(srv.clone()),
|
||||
Either::B(srv) => Either::B(srv.clone()),
|
||||
Self {
|
||||
left: self.left.clone(),
|
||||
right: self.right.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub enum EitherNewService<A: NewService<C>, B: NewService<C>, C> {
|
||||
A(<A::Future as IntoFuture>::Future),
|
||||
B(<B::Future as IntoFuture>::Future),
|
||||
pub struct EitherNewService<A: NewService, B: NewService> {
|
||||
left: Option<A::Service>,
|
||||
right: Option<B::Service>,
|
||||
left_fut: <A::Future as IntoFuture>::Future,
|
||||
right_fut: <B::Future as IntoFuture>::Future,
|
||||
}
|
||||
|
||||
impl<A, B, C> Future for EitherNewService<A, B, C>
|
||||
impl<A, B> Future for EitherNewService<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = A::Request,
|
||||
Response = A::Response,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
A: NewService,
|
||||
B: NewService<Response = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
type Item = EitherService<A::Service, B::Service>;
|
||||
type Error = A::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self {
|
||||
EitherNewService::A(ref mut fut) => {
|
||||
let service = try_ready!(fut.poll());
|
||||
Ok(Async::Ready(EitherService::A(service)))
|
||||
}
|
||||
EitherNewService::B(ref mut fut) => {
|
||||
let service = try_ready!(fut.poll());
|
||||
Ok(Async::Ready(EitherService::B(service)))
|
||||
}
|
||||
if self.left.is_none() {
|
||||
self.left = Some(try_ready!(self.left_fut.poll()));
|
||||
}
|
||||
if self.right.is_none() {
|
||||
self.right = Some(try_ready!(self.right_fut.poll()));
|
||||
}
|
||||
|
||||
if self.left.is_some() && self.right.is_some() {
|
||||
Ok(Async::Ready(EitherService {
|
||||
left: self.left.take().unwrap(),
|
||||
right: self.right.take().unwrap(),
|
||||
}))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,14 +1,12 @@
|
||||
//! Framed dispatcher service and related utilities
|
||||
use std::collections::VecDeque;
|
||||
use std::marker::PhantomData;
|
||||
use std::mem;
|
||||
use std::{fmt, mem};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||
use actix_service::{IntoNewService, IntoService, NewService, Service};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use actix_service::{IntoService, Service};
|
||||
use futures::task::AtomicTask;
|
||||
use futures::unsync::mpsc;
|
||||
use futures::{Async, Future, IntoFuture, Poll, Sink, Stream};
|
||||
use futures::{Async, Future, Poll, Sink, Stream};
|
||||
use log::debug;
|
||||
|
||||
use crate::cell::Cell;
|
||||
@@ -16,156 +14,6 @@ use crate::cell::Cell;
|
||||
type Request<U> = <U as Decoder>::Item;
|
||||
type Response<U> = <U as Encoder>::Item;
|
||||
|
||||
pub struct FramedNewService<S, T, U, C> {
|
||||
factory: S,
|
||||
_t: PhantomData<(T, U, C)>,
|
||||
}
|
||||
|
||||
impl<S, T, U, C> FramedNewService<S, T, U, C>
|
||||
where
|
||||
C: Clone,
|
||||
S: NewService<C, Request = Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
pub fn new<F1: IntoNewService<S, C>>(factory: F1) -> Self {
|
||||
Self {
|
||||
factory: factory.into_new_service(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, U, C> Clone for FramedNewService<S, T, U, C>
|
||||
where
|
||||
S: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
factory: self.factory.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, U, C> NewService<C> for FramedNewService<S, T, U, C>
|
||||
where
|
||||
C: Clone,
|
||||
S: NewService<C, Request = Request<U>, Response = Response<U>> + Clone,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
type Request = Framed<T, U>;
|
||||
type Response = FramedTransport<S::Service, T, U>;
|
||||
type Error = S::InitError;
|
||||
type InitError = S::InitError;
|
||||
type Service = FramedService<S, T, U, C>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
ok(FramedService {
|
||||
factory: self.factory.clone(),
|
||||
config: cfg.clone(),
|
||||
_t: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FramedService<S, T, U, C> {
|
||||
factory: S,
|
||||
config: C,
|
||||
_t: PhantomData<(T, U)>,
|
||||
}
|
||||
|
||||
impl<S, T, U, C> Clone for FramedService<S, T, U, C>
|
||||
where
|
||||
S: Clone,
|
||||
C: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
factory: self.factory.clone(),
|
||||
config: self.config.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, U, C> Service for FramedService<S, T, U, C>
|
||||
where
|
||||
S: NewService<C, Request = Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
C: Clone,
|
||||
{
|
||||
type Request = Framed<T, U>;
|
||||
type Response = FramedTransport<S::Service, T, U>;
|
||||
type Error = S::InitError;
|
||||
type Future = FramedServiceResponseFuture<S, T, U, C>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Framed<T, U>) -> Self::Future {
|
||||
FramedServiceResponseFuture {
|
||||
fut: self.factory.new_service(&self.config),
|
||||
framed: Some(req),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct FramedServiceResponseFuture<S, T, U, C>
|
||||
where
|
||||
S: NewService<C, Request = Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
fut: <S::Future as IntoFuture>::Future,
|
||||
framed: Option<Framed<T, U>>,
|
||||
}
|
||||
|
||||
impl<S, T, U, C> Future for FramedServiceResponseFuture<S, T, U, C>
|
||||
where
|
||||
S: NewService<C, Request = Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
type Item = FramedTransport<S::Service, T, U>;
|
||||
type Error = S::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.fut.poll()? {
|
||||
Async::NotReady => Ok(Async::NotReady),
|
||||
Async::Ready(service) => Ok(Async::Ready(FramedTransport::new(
|
||||
self.framed.take().unwrap(),
|
||||
service,
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Framed transport errors
|
||||
pub enum FramedTransportError<E, U: Encoder + Decoder> {
|
||||
Service(E),
|
||||
@@ -179,6 +27,42 @@ impl<E, U: Encoder + Decoder> From<E> for FramedTransportError<E, U> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, U: Encoder + Decoder> fmt::Debug for FramedTransportError<E, U>
|
||||
where
|
||||
E: fmt::Debug,
|
||||
<U as Encoder>::Error: fmt::Debug,
|
||||
<U as Decoder>::Error: fmt::Debug,
|
||||
{
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
FramedTransportError::Service(ref e) => {
|
||||
write!(fmt, "FramedTransportError::Service({:?})", e)
|
||||
}
|
||||
FramedTransportError::Encoder(ref e) => {
|
||||
write!(fmt, "FramedTransportError::Encoder({:?})", e)
|
||||
}
|
||||
FramedTransportError::Decoder(ref e) => {
|
||||
write!(fmt, "FramedTransportError::Encoder({:?})", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, U: Encoder + Decoder> fmt::Display for FramedTransportError<E, U>
|
||||
where
|
||||
E: fmt::Display,
|
||||
<U as Encoder>::Error: fmt::Debug,
|
||||
<U as Decoder>::Error: fmt::Debug,
|
||||
{
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
FramedTransportError::Service(ref e) => write!(fmt, "{}", e),
|
||||
FramedTransportError::Encoder(ref e) => write!(fmt, "{:?}", e),
|
||||
FramedTransportError::Decoder(ref e) => write!(fmt, "{:?}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum FramedMessage<T> {
|
||||
Message(T),
|
||||
Close,
|
||||
@@ -444,78 +328,3 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct IntoFramed<T, U, F>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
F: Fn() -> U + Send + Clone + 'static,
|
||||
U: Encoder + Decoder,
|
||||
{
|
||||
factory: F,
|
||||
_t: PhantomData<(T,)>,
|
||||
}
|
||||
|
||||
impl<T, U, F> IntoFramed<T, U, F>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
F: Fn() -> U + Send + Clone + 'static,
|
||||
U: Encoder + Decoder,
|
||||
{
|
||||
pub fn new(factory: F) -> Self {
|
||||
IntoFramed {
|
||||
factory,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, C, U, F> NewService<C> for IntoFramed<T, U, F>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
F: Fn() -> U + Send + Clone + 'static,
|
||||
U: Encoder + Decoder,
|
||||
{
|
||||
type Request = T;
|
||||
type Response = Framed<T, U>;
|
||||
type Error = ();
|
||||
type InitError = ();
|
||||
type Service = IntoFramedService<T, U, F>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
ok(IntoFramedService {
|
||||
factory: self.factory.clone(),
|
||||
_t: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct IntoFramedService<T, U, F>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
F: Fn() -> U + Send + Clone + 'static,
|
||||
U: Encoder + Decoder,
|
||||
{
|
||||
factory: F,
|
||||
_t: PhantomData<(T,)>,
|
||||
}
|
||||
|
||||
impl<T, U, F> Service for IntoFramedService<T, U, F>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
F: Fn() -> U + Send + Clone + 'static,
|
||||
U: Encoder + Decoder,
|
||||
{
|
||||
type Request = T;
|
||||
type Response = Framed<T, U>;
|
||||
type Error = ();
|
||||
type Future = FutureResult<Self::Response, Self::Error>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T) -> Self::Future {
|
||||
ok(Framed::new(req, (self.factory)()))
|
||||
}
|
||||
}
|
||||
|
@@ -1,4 +1,6 @@
|
||||
use actix_service::{IntoService, Service, Transform, Void};
|
||||
use std::convert::Infallible;
|
||||
|
||||
use actix_service::{IntoService, Service, Transform};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
@@ -28,7 +30,7 @@ impl<S: Service> Transform<S> for InFlight {
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type InitError = Void;
|
||||
type InitError = Infallible;
|
||||
type Transform = InFlightService<S>;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
|
@@ -1,7 +1,8 @@
|
||||
use std::convert::Infallible;
|
||||
use std::marker::PhantomData;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use actix_service::{NewService, Service, Void};
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
use tokio_timer::Delay;
|
||||
@@ -43,14 +44,15 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, E, F> NewService<()> for KeepAlive<R, E, F>
|
||||
impl<R, E, F> NewService for KeepAlive<R, E, F>
|
||||
where
|
||||
F: Fn() -> E + Clone,
|
||||
{
|
||||
type Request = R;
|
||||
type Response = R;
|
||||
type Error = E;
|
||||
type InitError = Void;
|
||||
type InitError = Infallible;
|
||||
type Config = ();
|
||||
type Service = KeepAliveService<R, E, F>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
|
@@ -1,9 +1,10 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::convert::Infallible;
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_service::{IntoService, Service, Transform, Void};
|
||||
use actix_service::{IntoService, Service, Transform};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::task::AtomicTask;
|
||||
use futures::unsync::oneshot;
|
||||
@@ -90,7 +91,7 @@ where
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = InOrderError<S::Error>;
|
||||
type InitError = Void;
|
||||
type InitError = Infallible;
|
||||
type Transform = InOrderService<S>;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
|
@@ -1,10 +1,9 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_service::{IntoNewService, IntoService, NewService, Service};
|
||||
use futures::future::{ok, Future, FutureResult};
|
||||
use actix_service::{IntoService, NewService, Service};
|
||||
use futures::unsync::mpsc;
|
||||
use futures::{Async, Poll, Stream};
|
||||
use futures::{Async, Future, Poll, Stream};
|
||||
|
||||
type Request<T> = Result<<T as IntoStream>::Item, <T as IntoStream>::Error>;
|
||||
|
||||
@@ -29,76 +28,19 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct StreamNewService<S, T, E, C> {
|
||||
pub struct StreamService<S, T: NewService, E> {
|
||||
factory: Rc<T>,
|
||||
_t: PhantomData<(S, E, C)>,
|
||||
}
|
||||
|
||||
impl<S, T, E, C> StreamNewService<S, T, E, C>
|
||||
where
|
||||
C: Clone,
|
||||
S: IntoStream,
|
||||
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
pub fn new<F: IntoNewService<T, C>>(factory: F) -> Self {
|
||||
Self {
|
||||
factory: Rc::new(factory.into_new_service()),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, E, C> Clone for StreamNewService<S, T, E, C> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
factory: self.factory.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, E, C> NewService<C> for StreamNewService<S, T, E, C>
|
||||
where
|
||||
C: Clone,
|
||||
S: IntoStream + 'static,
|
||||
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
type Request = S;
|
||||
type Response = ();
|
||||
type Error = E;
|
||||
type InitError = E;
|
||||
type Service = StreamService<S, T, E, C>;
|
||||
type Future = FutureResult<Self::Service, E>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
ok(StreamService {
|
||||
factory: self.factory.clone(),
|
||||
config: cfg.clone(),
|
||||
_t: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct StreamService<S, T, E, C = ()> {
|
||||
factory: Rc<T>,
|
||||
config: C,
|
||||
config: T::Config,
|
||||
_t: PhantomData<(S, E)>,
|
||||
}
|
||||
|
||||
impl<S, T, E, C> Service for StreamService<S, T, E, C>
|
||||
impl<S, T, E> Service for StreamService<S, T, E>
|
||||
where
|
||||
S: IntoStream + 'static,
|
||||
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
|
||||
T: NewService<Request = Request<S>, Response = (), Error = E, InitError = E>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
C: Clone,
|
||||
{
|
||||
type Request = S;
|
||||
type Response = ();
|
||||
@@ -207,83 +149,3 @@ impl<F: Future> Future for StreamDispatcherService<F> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `NewService` that implements, read one item from the stream.
|
||||
pub struct TakeItem<T> {
|
||||
_t: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> TakeItem<T> {
|
||||
/// Create new `TakeRequest` instance.
|
||||
pub fn new() -> Self {
|
||||
TakeItem { _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for TakeItem<T> {
|
||||
fn default() -> Self {
|
||||
TakeItem { _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for TakeItem<T> {
|
||||
fn clone(&self) -> TakeItem<T> {
|
||||
TakeItem { _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Stream, C> NewService<C> for TakeItem<T> {
|
||||
type Request = T;
|
||||
type Response = (Option<T::Item>, T);
|
||||
type Error = T::Error;
|
||||
type InitError = ();
|
||||
type Service = TakeItemService<T>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
ok(TakeItemService { _t: PhantomData })
|
||||
}
|
||||
}
|
||||
|
||||
/// `NewService` that implements, read one request from framed object feature.
|
||||
pub struct TakeItemService<T> {
|
||||
_t: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> Clone for TakeItemService<T> {
|
||||
fn clone(&self) -> TakeItemService<T> {
|
||||
TakeItemService { _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Stream> Service for TakeItemService<T> {
|
||||
type Request = T;
|
||||
type Response = (Option<T::Item>, T);
|
||||
type Error = T::Error;
|
||||
type Future = TakeItemServiceResponse<T>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T) -> Self::Future {
|
||||
TakeItemServiceResponse { stream: Some(req) }
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct TakeItemServiceResponse<T: Stream> {
|
||||
stream: Option<T>,
|
||||
}
|
||||
|
||||
impl<T: Stream> Future for TakeItemServiceResponse<T> {
|
||||
type Item = (Option<T::Item>, T);
|
||||
type Error = T::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.stream.as_mut().expect("Use after finish").poll()? {
|
||||
Async::Ready(item) => Ok(Async::Ready((item, self.stream.take().unwrap()))),
|
||||
Async::NotReady => Ok(Async::NotReady),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
use std::convert::Infallible;
|
||||
use std::time::{self, Duration, Instant};
|
||||
|
||||
use actix_service::{NewService, Service, Void};
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
use tokio_timer::sleep;
|
||||
@@ -41,11 +42,12 @@ impl Default for LowResTime {
|
||||
}
|
||||
}
|
||||
|
||||
impl NewService<()> for LowResTime {
|
||||
impl NewService for LowResTime {
|
||||
type Request = ();
|
||||
type Response = Instant;
|
||||
type Error = Void;
|
||||
type InitError = Void;
|
||||
type Error = Infallible;
|
||||
type InitError = Infallible;
|
||||
type Config = ();
|
||||
type Service = LowResTimeService;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
@@ -91,7 +93,7 @@ impl LowResTimeService {
|
||||
impl Service for LowResTimeService {
|
||||
type Request = ();
|
||||
type Response = Instant;
|
||||
type Error = Void;
|
||||
type Error = Infallible;
|
||||
type Future = FutureResult<Self::Response, Self::Error>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
|
@@ -10,7 +10,7 @@ use std::{env, fmt, io};
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_rt::System;
|
||||
use actix_server::{Io, Server};
|
||||
use actix_service::{fn_service, NewService};
|
||||
use actix_service::{service_fn, NewService};
|
||||
use futures::{future, Future};
|
||||
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
|
||||
use tokio_openssl::SslAcceptorExt;
|
||||
@@ -54,14 +54,14 @@ fn main() -> io::Result<()> {
|
||||
let acceptor = acceptor.clone();
|
||||
|
||||
// service for converting incoming TcpStream to a SslStream<TcpStream>
|
||||
fn_service(move |stream: Io<tokio_tcp::TcpStream>| {
|
||||
service_fn(move |stream: Io<tokio_tcp::TcpStream>| {
|
||||
SslAcceptorExt::accept_async(&acceptor, stream.into_parts().0)
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
})
|
||||
// .and_then() combinator uses other service to convert incoming `Request` to a
|
||||
// `Response` and then uses that response as an input for next
|
||||
// service. in this case, on success we use `logger` service
|
||||
.and_then(fn_service(logger))
|
||||
.and_then(logger)
|
||||
// Next service counts number of connections
|
||||
.and_then(move |_| {
|
||||
let num = num.fetch_add(1, Ordering::Relaxed);
|
||||
|
@@ -1,5 +1,27 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.5] - 2019-05-15
|
||||
|
||||
* Remove debug prints
|
||||
|
||||
## [0.1.4] - 2019-05-15
|
||||
|
||||
* Fix checked resource match
|
||||
|
||||
## [0.1.3] - 2019-04-22
|
||||
|
||||
* Added support for `remainder match` (i.e "/path/{tail}*")
|
||||
|
||||
## [0.1.2] - 2019-04-07
|
||||
|
||||
* Export `Quoter` type
|
||||
|
||||
* Allow to reset `Path` instance
|
||||
|
||||
## [0.1.1] - 2019-04-03
|
||||
|
||||
* Get dynamic segment by name instead of iterator.
|
||||
|
||||
## [0.1.0] - 2019-03-09
|
||||
|
||||
* Initial release
|
||||
|
@@ -1,16 +1,16 @@
|
||||
[package]
|
||||
name = "actix-router"
|
||||
version = "0.1.0"
|
||||
version = "0.1.5"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Path router"
|
||||
keywords = ["actix"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://actix.rs/api/actix-net/stable/actix_router/"
|
||||
documentation = "https://docs.rs/actix-router/"
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "actix_router"
|
||||
@@ -23,7 +23,8 @@ default = ["http"]
|
||||
bytes = "0.4"
|
||||
regex = "1.0"
|
||||
serde = "1.0.80"
|
||||
string = "0.1.3"
|
||||
string = "0.2.0"
|
||||
log = "0.4"
|
||||
http = { version="0.1.14", optional=true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
1
router/LICENSE-APACHE
Symbolic link
1
router/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
router/LICENSE-MIT
Symbolic link
1
router/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -39,7 +39,7 @@ impl<T: AsRef<[u8]>> ResourcePath for string::String<T> {
|
||||
mod url;
|
||||
|
||||
#[cfg(feature = "http")]
|
||||
pub use self::url::Url;
|
||||
pub use self::url::{Quoter, Url};
|
||||
|
||||
#[cfg(feature = "http")]
|
||||
mod http_support {
|
||||
|
@@ -51,16 +51,19 @@ impl<T: ResourcePath> Path<T> {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Get reference to inner path instance
|
||||
pub fn get_ref(&self) -> &T {
|
||||
&self.path
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Get mutable reference to inner path instance
|
||||
pub fn get_mut(&mut self) -> &mut T {
|
||||
&mut self.path
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Path
|
||||
pub fn path(&self) -> &str {
|
||||
let skip = self.skip as usize;
|
||||
@@ -72,13 +75,22 @@ impl<T: ResourcePath> Path<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset inner path
|
||||
#[inline]
|
||||
/// Set new path
|
||||
pub fn set(&mut self, path: T) {
|
||||
self.skip = 0;
|
||||
self.path = path;
|
||||
self.segments.clear();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Reset state
|
||||
pub fn reset(&mut self) {
|
||||
self.skip = 0;
|
||||
self.segments.clear();
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Skip first `n` chars in path
|
||||
pub fn skip(&mut self, n: u16) {
|
||||
self.skip = self.skip + n;
|
||||
@@ -99,11 +111,13 @@ impl<T: ResourcePath> Path<T> {
|
||||
.push((Rc::new(name.to_string()), PathItem::Static(value)));
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Check if there are any matched patterns
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.segments.is_empty()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Check number of extracted parameters
|
||||
pub fn len(&self) -> usize {
|
||||
self.segments.len()
|
||||
|
@@ -5,7 +5,7 @@ use std::rc::Rc;
|
||||
use regex::{escape, Regex};
|
||||
|
||||
use crate::path::{Path, PathItem};
|
||||
use crate::ResourcePath;
|
||||
use crate::{Resource, ResourcePath};
|
||||
|
||||
const MAX_DYNAMIC_SEGMENTS: usize = 16;
|
||||
|
||||
@@ -118,6 +118,7 @@ impl ResourceDef {
|
||||
&self.pattern
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Check if path matchs this pattern?
|
||||
pub fn is_match(&self, path: &str) -> bool {
|
||||
match self.tp {
|
||||
@@ -196,18 +197,17 @@ impl ResourceDef {
|
||||
[PathItem::Static(""); MAX_DYNAMIC_SEGMENTS];
|
||||
|
||||
if let Some(captures) = re.captures(path.path()) {
|
||||
let mut passed = false;
|
||||
|
||||
for capture in captures.iter() {
|
||||
if let Some(ref m) = capture {
|
||||
if !passed {
|
||||
passed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
segments[idx] = PathItem::Segment(m.start() as u16, m.end() as u16);
|
||||
for (no, name) in names.iter().enumerate() {
|
||||
if let Some(m) = captures.name(&name) {
|
||||
idx += 1;
|
||||
pos = m.end();
|
||||
segments[no] = PathItem::Segment(m.start() as u16, m.end() as u16);
|
||||
} else {
|
||||
log::error!(
|
||||
"Dynamic path match but not all segments found: {}",
|
||||
name
|
||||
);
|
||||
false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -240,6 +240,90 @@ impl ResourceDef {
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the given path and parameters a match against this pattern?
|
||||
pub fn match_path_checked<R, T, F, U>(
|
||||
&self,
|
||||
res: &mut R,
|
||||
check: &F,
|
||||
user_data: &Option<U>,
|
||||
) -> bool
|
||||
where
|
||||
T: ResourcePath,
|
||||
R: Resource<T>,
|
||||
F: Fn(&R, &Option<U>) -> bool,
|
||||
{
|
||||
match self.tp {
|
||||
PatternType::Static(ref s) => {
|
||||
if s == res.resource_path().path() && check(res, user_data) {
|
||||
let path = res.resource_path();
|
||||
path.skip(path.len() as u16);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
PatternType::Dynamic(ref re, ref names, len) => {
|
||||
let mut idx = 0;
|
||||
let mut pos = 0;
|
||||
let mut segments: [PathItem; MAX_DYNAMIC_SEGMENTS] =
|
||||
[PathItem::Static(""); MAX_DYNAMIC_SEGMENTS];
|
||||
|
||||
if let Some(captures) = re.captures(res.resource_path().path()) {
|
||||
for (no, name) in names.iter().enumerate() {
|
||||
if let Some(m) = captures.name(&name) {
|
||||
idx += 1;
|
||||
pos = m.end();
|
||||
segments[no] = PathItem::Segment(m.start() as u16, m.end() as u16);
|
||||
} else {
|
||||
log::error!(
|
||||
"Dynamic path match but not all segments found: {}",
|
||||
name
|
||||
);
|
||||
false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
if !check(res, user_data) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let path = res.resource_path();
|
||||
for idx in 0..idx {
|
||||
path.add(names[idx].clone(), segments[idx]);
|
||||
}
|
||||
path.skip((pos + len) as u16);
|
||||
true
|
||||
}
|
||||
PatternType::Prefix(ref s) => {
|
||||
let len = {
|
||||
let rpath = res.resource_path().path();
|
||||
if s == rpath {
|
||||
s.len()
|
||||
} else if rpath.starts_with(s)
|
||||
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
|
||||
{
|
||||
if s.ends_with('/') {
|
||||
s.len() - 1
|
||||
} else {
|
||||
s.len()
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
if !check(res, user_data) {
|
||||
return false;
|
||||
}
|
||||
let path = res.resource_path();
|
||||
path.skip(min(path.path().len(), len) as u16);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build resource path from elements. Returns `true` on success.
|
||||
pub fn resource_path<U, I>(&self, path: &mut String, elements: &mut U) -> bool
|
||||
where
|
||||
@@ -267,8 +351,9 @@ impl ResourceDef {
|
||||
true
|
||||
}
|
||||
|
||||
fn parse_param(pattern: &str) -> (PatternElement, String, &str) {
|
||||
fn parse_param(pattern: &str) -> (PatternElement, String, &str, bool) {
|
||||
const DEFAULT_PATTERN: &str = "[^/]+";
|
||||
const DEFAULT_PATTERN_TAIL: &str = ".*";
|
||||
let mut params_nesting = 0usize;
|
||||
let close_idx = pattern
|
||||
.find(|c| match c {
|
||||
@@ -283,34 +368,54 @@ impl ResourceDef {
|
||||
_ => false,
|
||||
})
|
||||
.expect("malformed dynamic segment");
|
||||
let (mut param, rem) = pattern.split_at(close_idx + 1);
|
||||
let (mut param, mut rem) = pattern.split_at(close_idx + 1);
|
||||
param = ¶m[1..param.len() - 1]; // Remove outer brackets
|
||||
let tail = rem == "*";
|
||||
|
||||
let (name, pattern) = match param.find(':') {
|
||||
Some(idx) => {
|
||||
if tail {
|
||||
panic!("Custom regex is not supported for remainder match");
|
||||
}
|
||||
let (name, pattern) = param.split_at(idx);
|
||||
(name, &pattern[1..])
|
||||
}
|
||||
None => (param, DEFAULT_PATTERN),
|
||||
None => (
|
||||
param,
|
||||
if tail {
|
||||
rem = &rem[1..];
|
||||
DEFAULT_PATTERN_TAIL
|
||||
} else {
|
||||
DEFAULT_PATTERN
|
||||
},
|
||||
),
|
||||
};
|
||||
(
|
||||
PatternElement::Var(name.to_string()),
|
||||
format!(r"(?P<{}>{})", &name, &pattern),
|
||||
rem,
|
||||
tail,
|
||||
)
|
||||
}
|
||||
|
||||
fn parse(
|
||||
mut pattern: &str,
|
||||
for_prefix: bool,
|
||||
mut for_prefix: bool,
|
||||
) -> (String, Vec<PatternElement>, bool, usize) {
|
||||
if pattern.find('{').is_none() {
|
||||
return (
|
||||
String::from(pattern),
|
||||
vec![PatternElement::Str(String::from(pattern))],
|
||||
false,
|
||||
pattern.chars().count(),
|
||||
);
|
||||
};
|
||||
return if pattern.ends_with('*') {
|
||||
let path = &pattern[..pattern.len() - 1];
|
||||
let re = String::from("^") + path + "(.*)";
|
||||
(re, vec![PatternElement::Str(String::from(path))], true, 0)
|
||||
} else {
|
||||
(
|
||||
String::from(pattern),
|
||||
vec![PatternElement::Str(String::from(pattern))],
|
||||
false,
|
||||
pattern.chars().count(),
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
let mut elems = Vec::new();
|
||||
let mut re = String::from("^");
|
||||
@@ -320,7 +425,11 @@ impl ResourceDef {
|
||||
let (prefix, rem) = pattern.split_at(idx);
|
||||
elems.push(PatternElement::Str(String::from(prefix)));
|
||||
re.push_str(&escape(prefix));
|
||||
let (param_pattern, re_part, rem) = Self::parse_param(rem);
|
||||
let (param_pattern, re_part, rem, tail) = Self::parse_param(rem);
|
||||
if tail {
|
||||
for_prefix = true;
|
||||
}
|
||||
|
||||
elems.push(param_pattern);
|
||||
re.push_str(&re_part);
|
||||
pattern = rem;
|
||||
@@ -340,7 +449,6 @@ impl ResourceDef {
|
||||
if !for_prefix {
|
||||
re.push_str("$");
|
||||
}
|
||||
|
||||
(re, elems, true, pattern.chars().count())
|
||||
}
|
||||
}
|
||||
@@ -448,6 +556,42 @@ mod tests {
|
||||
assert_eq!(path.get("id").unwrap(), "012345");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_tail() {
|
||||
let re = ResourceDef::new("/user/-{id}*");
|
||||
|
||||
let mut path = Path::new("/user/-profile");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "profile");
|
||||
|
||||
let mut path = Path::new("/user/-2345");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "2345");
|
||||
|
||||
let mut path = Path::new("/user/-2345/");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "2345/");
|
||||
|
||||
let mut path = Path::new("/user/-2345/sdg");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "2345/sdg");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_static_tail() {
|
||||
let re = ResourceDef::new("/user*");
|
||||
assert!(re.is_match("/user/profile"));
|
||||
assert!(re.is_match("/user/2345"));
|
||||
assert!(re.is_match("/user/2345/"));
|
||||
assert!(re.is_match("/user/2345/sdg"));
|
||||
|
||||
let re = ResourceDef::new("/user/*");
|
||||
assert!(re.is_match("/user/profile"));
|
||||
assert!(re.is_match("/user/2345"));
|
||||
assert!(re.is_match("/user/2345/"));
|
||||
assert!(re.is_match("/user/2345/sdg"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_urlencoded_param() {
|
||||
let re = ResourceDef::new("/user/{id}/test");
|
||||
|
@@ -19,26 +19,26 @@ impl<T, U> Router<T, U> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn recognize<R, P>(&self, path: &mut R) -> Option<(&T, ResourceId)>
|
||||
pub fn recognize<R, P>(&self, resource: &mut R) -> Option<(&T, ResourceId)>
|
||||
where
|
||||
R: Resource<P>,
|
||||
P: ResourcePath,
|
||||
{
|
||||
for item in self.0.iter() {
|
||||
if item.0.match_path(path.resource_path()) {
|
||||
if item.0.match_path(resource.resource_path()) {
|
||||
return Some((&item.1, ResourceId(item.0.id())));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn recognize_mut<R, P>(&mut self, res: &mut R) -> Option<(&mut T, ResourceId)>
|
||||
pub fn recognize_mut<R, P>(&mut self, resource: &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()) {
|
||||
if item.0.match_path(resource.resource_path()) {
|
||||
return Some((&mut item.1, ResourceId(item.0.id())));
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,7 @@ impl<T, U> Router<T, U> {
|
||||
|
||||
pub fn recognize_mut_checked<R, P, F>(
|
||||
&mut self,
|
||||
res: &mut R,
|
||||
resource: &mut R,
|
||||
check: F,
|
||||
) -> Option<(&mut T, ResourceId)>
|
||||
where
|
||||
@@ -56,7 +56,7 @@ impl<T, U> Router<T, U> {
|
||||
P: ResourcePath,
|
||||
{
|
||||
for item in self.0.iter_mut() {
|
||||
if item.0.match_path(res.resource_path()) && check(res, &item.2) {
|
||||
if item.0.match_path_checked(resource, &check, &item.2) {
|
||||
return Some((&mut item.1, ResourceId(item.0.id())));
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,3 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::ResourcePath;
|
||||
|
||||
#[allow(dead_code)]
|
||||
@@ -39,7 +37,7 @@ thread_local! {
|
||||
#[derive(Default, Clone, Debug)]
|
||||
pub struct Url {
|
||||
uri: http::Uri,
|
||||
path: Option<Rc<String>>,
|
||||
path: Option<String>,
|
||||
}
|
||||
|
||||
impl Url {
|
||||
@@ -49,6 +47,13 @@ impl Url {
|
||||
Url { uri, path }
|
||||
}
|
||||
|
||||
pub fn with_quoter(uri: http::Uri, quoter: &Quoter) -> Url {
|
||||
Url {
|
||||
path: quoter.requote(uri.path().as_bytes()),
|
||||
uri,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn uri(&self) -> &http::Uri {
|
||||
&self.uri
|
||||
}
|
||||
@@ -61,19 +66,27 @@ impl Url {
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn update(&mut self, uri: &http::Uri) {
|
||||
self.uri = uri.clone();
|
||||
self.path = DEFAULT_QUOTER.with(|q| q.requote(uri.path().as_bytes()));
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn update_with_quoter(&mut self, uri: &http::Uri, quoter: &Quoter) {
|
||||
self.uri = uri.clone();
|
||||
self.path = quoter.requote(uri.path().as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourcePath for Url {
|
||||
#[inline]
|
||||
fn path(&self) -> &str {
|
||||
self.path()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Quoter {
|
||||
pub struct Quoter {
|
||||
safe_table: [u8; 16],
|
||||
protected_table: [u8; 16],
|
||||
}
|
||||
@@ -108,7 +121,7 @@ impl Quoter {
|
||||
q
|
||||
}
|
||||
|
||||
pub fn requote(&self, val: &[u8]) -> Option<Rc<String>> {
|
||||
pub fn requote(&self, val: &[u8]) -> Option<String> {
|
||||
let mut has_pct = 0;
|
||||
let mut pct = [b'%', 0, 0];
|
||||
let mut idx = 0;
|
||||
@@ -160,7 +173,7 @@ impl Quoter {
|
||||
if let Some(data) = cloned {
|
||||
// Unsafe: we get data from http::Uri, which does utf-8 checks already
|
||||
// this code only decodes valid pct encoded values
|
||||
Some(Rc::new(unsafe { String::from_utf8_unchecked(data) }))
|
||||
Some(unsafe { String::from_utf8_unchecked(data) })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
Reference in New Issue
Block a user