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

Compare commits

...

21 Commits

Author SHA1 Message Date
Nikolay Kim
0063a26aab prepare actix-service release 2019-02-03 13:32:51 -08:00
Nikolay Kim
bcc466f6ab update tests 2019-02-03 11:48:11 -08:00
Nikolay Kim
663ae53954 fix Clone impl for Timeout 2019-02-03 11:37:34 -08:00
Nikolay Kim
406088524e depend on git repo 2019-02-03 11:33:26 -08:00
Nikolay Kim
5b8446105f depend on repo 2019-02-03 11:16:24 -08:00
Nikolay Kim
429ad453d3 change Apply::new_fn to old args order 2019-02-03 10:52:44 -08:00
Nikolay Kim
bd977373bc generalize apply combinator with transform trait 2019-02-03 10:42:27 -08:00
Nikolay Kim
d45fb9521f update deps 2019-02-01 20:11:30 -08:00
Nikolay Kim
94a0da3659 prepare actix-connector release 2019-02-01 20:06:53 -08:00
Nikolay Kim
8d62ac4b2f prepare actix-server release 2019-02-01 20:03:31 -08:00
Nikolay Kim
442163690e prepare actix-utils release 2019-02-01 20:00:12 -08:00
Nikolay Kim
d83bf95304 Use associated type instead of generic for Service definition 2019-02-01 19:53:13 -08:00
Nikolay Kim
8cdbf49187 better inflight readiness check 2019-02-01 15:15:53 -08:00
Nikolay Kim
132be0baa1 better naming 2019-02-01 14:48:09 -08:00
Nikolay Kim
cedba24a36 add Url type from actix web 2019-02-01 13:25:56 -08:00
Nikolay Kim
aa20b304ec more refactorings for framed transport 2019-01-26 22:07:27 -08:00
Nikolay Kim
9f0a288e4b refactor FramedTransport 2019-01-26 21:41:28 -08:00
Nikolay Kim
cabebb6b3f add time services tests 2019-01-26 13:21:56 -08:00
Nikolay Kim
84bd257b86 update deps 2019-01-26 13:15:17 -08:00
Nikolay Kim
ff6ac0a67f add System time service 2019-01-26 13:14:37 -08:00
Nikolay Kim
c1c989034d Added Clone impl for Timeout service factory 2019-01-25 14:31:27 -08:00
45 changed files with 2465 additions and 945 deletions

View File

@@ -26,10 +26,10 @@ members = [
] ]
[dev-dependencies] [dev-dependencies]
actix-service = "0.1.1" actix-service = "0.2.0"
actix-codec = "0.1.0" actix-codec = "0.1.0"
actix-rt = { path="actix-rt" } actix-rt = { version="0.1.0" }
actix-server = { path="actix-server", features=["ssl"] } actix-server = { version="0.2.0", features=["ssl"] }
env_logger = "0.5" env_logger = "0.5"
futures = "0.1.24" futures = "0.1.24"
openssl = { version="0.10" } openssl = { version="0.10" }

View File

@@ -1,5 +1,16 @@
# Changes # Changes
## [0.2.0] - 2019-02-01
### Changes
* Migrate to actix-service 0.2
* Upgrade trust-dns-resolver
* Use tokio-current-thread instead of direct actix-rt dipendency
## [0.1.1] - 2019-01-13 ## [0.1.1] - 2019-01-13
* Upgrade trust-dns-proto * Upgrade trust-dns-proto

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-connector" name = "actix-connector"
version = "0.1.1" version = "0.2.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix Connector - tcp connector service" description = "Actix Connector - tcp connector service"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -27,13 +27,12 @@ default = []
ssl = ["openssl", "tokio-openssl"] ssl = ["openssl", "tokio-openssl"]
[dependencies] [dependencies]
actix-service = "0.1.1" actix-service = "0.2.0"
actix-codec = "0.1.0" actix-codec = "0.1.0"
actix-rt = "0.1.0"
futures = "0.1" futures = "0.1"
tokio-tcp = "0.1" tokio-tcp = "0.1"
trust-dns-proto = "0.6.2" tokio-current-thread = "0.1"
trust-dns-resolver = "0.10.2" trust-dns-resolver = { version="0.11.0-alpha.2", default-features = false }
# openssl # openssl
openssl = { version="0.10", optional = true } openssl = { version="0.10", optional = true }

View File

@@ -167,8 +167,8 @@ impl Connector {
/// Create new connector with custom resolver /// Create new connector with custom resolver
pub fn with_resolver( pub fn with_resolver(
resolver: Resolver<Connect>, resolver: Resolver<Connect>,
) -> impl Service<Connect, Response = (Connect, TcpStream), Error = ConnectorError> + Clone ) -> impl Service<Request = Connect, Response = (Connect, TcpStream), Error = ConnectorError>
{ + Clone {
Connector { resolver } Connector { resolver }
} }
@@ -177,7 +177,7 @@ impl Connector {
cfg: ResolverConfig, cfg: ResolverConfig,
opts: ResolverOpts, opts: ResolverOpts,
) -> impl NewService< ) -> impl NewService<
Connect, Request = Connect,
Response = (Connect, TcpStream), Response = (Connect, TcpStream),
Error = ConnectorError, Error = ConnectorError,
InitError = E, InitError = E,
@@ -194,7 +194,8 @@ impl Clone for Connector {
} }
} }
impl Service<Connect> for Connector { impl Service for Connector {
type Request = Connect;
type Response = (Connect, TcpStream); type Response = (Connect, TcpStream);
type Error = ConnectorError; type Error = ConnectorError;
type Future = Either<ConnectorFuture, ConnectorTcpFuture>; type Future = Either<ConnectorFuture, ConnectorTcpFuture>;
@@ -271,7 +272,8 @@ impl<T: RequestPort> Default for TcpConnector<T> {
} }
} }
impl<T: RequestPort> Service<(T, VecDeque<IpAddr>)> for TcpConnector<T> { impl<T: RequestPort> Service for TcpConnector<T> {
type Request = (T, VecDeque<IpAddr>);
type Response = (T, TcpStream); type Response = (T, TcpStream);
type Error = io::Error; type Error = io::Error;
type Future = TcpConnectorResponse<T>; type Future = TcpConnectorResponse<T>;
@@ -317,7 +319,7 @@ impl<T: RequestPort> Future for TcpConnectorResponse<T> {
if let Some(new) = self.stream.as_mut() { if let Some(new) = self.stream.as_mut() {
match new.poll() { match new.poll() {
Ok(Async::Ready(sock)) => { Ok(Async::Ready(sock)) => {
return Ok(Async::Ready((self.req.take().unwrap(), sock))) return Ok(Async::Ready((self.req.take().unwrap(), sock)));
} }
Ok(Async::NotReady) => return Ok(Async::NotReady), Ok(Async::NotReady) => return Ok(Async::NotReady),
Err(err) => { Err(err) => {
@@ -351,7 +353,8 @@ impl DefaultConnector {
} }
} }
impl Service<Connect> for DefaultConnector { impl Service for DefaultConnector {
type Request = Connect;
type Response = TcpStream; type Response = TcpStream;
type Error = ConnectorError; type Error = ConnectorError;
type Future = DefaultConnectorFuture; type Future = DefaultConnectorFuture;

View File

@@ -42,7 +42,7 @@ impl<T: RequestHost> Resolver<T> {
/// Create new resolver instance with custom configuration and options. /// Create new resolver instance with custom configuration and options.
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self { pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
let (resolver, bg) = AsyncResolver::new(cfg, opts); let (resolver, bg) = AsyncResolver::new(cfg, opts);
actix_rt::Arbiter::spawn(bg); tokio_current_thread::spawn(bg);
Resolver { Resolver {
resolver, resolver,
req: PhantomData, req: PhantomData,
@@ -67,7 +67,8 @@ impl<T> Clone for Resolver<T> {
} }
} }
impl<T: RequestHost> Service<T> for Resolver<T> { impl<T: RequestHost> Service for Resolver<T> {
type Request = T;
type Response = (T, VecDeque<IpAddr>); type Response = (T, VecDeque<IpAddr>);
type Error = ResolveError; type Error = ResolveError;
type Future = ResolverFuture<T>; type Future = ResolverFuture<T>;

View File

@@ -26,7 +26,8 @@ impl<R, T, E> OpensslConnector<R, T, E> {
impl<R: RequestHost, T: AsyncRead + AsyncWrite> OpensslConnector<R, T, ()> { impl<R: RequestHost, T: AsyncRead + AsyncWrite> OpensslConnector<R, T, ()> {
pub fn service( pub fn service(
connector: SslConnector, connector: SslConnector,
) -> impl Service<(R, T), Response = (R, SslStream<T>), Error = HandshakeError<T>> { ) -> impl Service<Request = (R, T), Response = (R, SslStream<T>), Error = HandshakeError<T>>
{
OpensslConnectorService { OpensslConnectorService {
connector: connector, connector: connector,
_t: PhantomData, _t: PhantomData,
@@ -43,9 +44,8 @@ impl<R, T, E> Clone for OpensslConnector<R, T, E> {
} }
} }
impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService<(R, T)> impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService for OpensslConnector<R, T, E> {
for OpensslConnector<R, T, E> type Request = (R, T);
{
type Response = (R, SslStream<T>); type Response = (R, SslStream<T>);
type Error = HandshakeError<T>; type Error = HandshakeError<T>;
type Service = OpensslConnectorService<R, T>; type Service = OpensslConnectorService<R, T>;
@@ -65,9 +65,8 @@ pub struct OpensslConnectorService<R, T> {
_t: PhantomData<(R, T)>, _t: PhantomData<(R, T)>,
} }
impl<R: RequestHost, T: AsyncRead + AsyncWrite> Service<(R, T)> impl<R: RequestHost, T: AsyncRead + AsyncWrite> Service for OpensslConnectorService<R, T> {
for OpensslConnectorService<R, T> type Request = (R, T);
{
type Response = (R, SslStream<T>); type Response = (R, SslStream<T>);
type Error = HandshakeError<T>; type Error = HandshakeError<T>;
type Future = ConnectAsyncExt<R, T>; type Future = ConnectAsyncExt<R, T>;

View File

@@ -1,5 +1,14 @@
# Changes # Changes
## [0.2.0] - 2019-02-01
## Changes
* Migrate to actix-service 0.2
* Updated rustls dependency
## [0.1.3] - 2018-12-21 ## [0.1.3] - 2018-12-21
## Fixed ## Fixed

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-server" name = "actix-server"
version = "0.1.3" version = "0.2.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix server - General purpose tcp server" description = "Actix server - General purpose tcp server"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -33,7 +33,7 @@ ssl = ["openssl", "tokio-openssl"]
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"] rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
[dependencies] [dependencies]
actix-service = "0.1.1" actix-service = "0.2.0"
actix-rt = "0.1.0" actix-rt = "0.1.0"
log = "0.4" log = "0.4"
@@ -47,7 +47,7 @@ futures = "0.1"
slab = "0.4" slab = "0.4"
tokio-io = "0.1" tokio-io = "0.1"
tokio-tcp = "0.1" tokio-tcp = "0.1"
tokio-timer = "0.2" tokio-timer = "0.2.8"
tokio-reactor = "0.1" tokio-reactor = "0.1"
tokio-signal = "0.2" tokio-signal = "0.2"
@@ -59,13 +59,11 @@ openssl = { version="0.10", optional = true }
tokio-openssl = { version="0.3", optional = true } tokio-openssl = { version="0.3", optional = true }
#rustls #rustls
rustls = { version = "^0.14", optional = true } rustls = { version = "^0.15", optional = true }
tokio-rustls = { version = "^0.8", optional = true } tokio-rustls = { version = "^0.9", optional = true }
webpki = { version = "0.18", optional = true } webpki = { version = "0.19", optional = true }
webpki-roots = { version = "0.15", optional = true } webpki-roots = { version = "0.16", optional = true }
[dev-dependencies] [dev-dependencies]
env_logger = "0.5" env_logger = "0.6"
actix-service = "0.1.1"
actix-codec = "0.1.0" actix-codec = "0.1.0"
actix-rt = "0.1.0"

View File

@@ -169,8 +169,8 @@ impl ServiceRuntime {
pub fn service<T, F>(&mut self, name: &str, service: F) pub fn service<T, F>(&mut self, name: &str, service: F)
where where
F: IntoNewService<T, TcpStream>, F: IntoNewService<T>,
T: NewService<TcpStream, Response = ()> + 'static, T: NewService<Request = TcpStream, Response = ()> + 'static,
T::Future: 'static, T::Future: 'static,
T::Service: 'static, T::Service: 'static,
T::InitError: fmt::Debug, T::InitError: fmt::Debug,
@@ -191,7 +191,7 @@ impl ServiceRuntime {
type BoxedNewService = Box< type BoxedNewService = Box<
NewService< NewService<
(Option<CounterGuard>, ServerMessage), Request = (Option<CounterGuard>, ServerMessage),
Response = (), Response = (),
Error = (), Error = (),
InitError = (), InitError = (),
@@ -204,14 +204,15 @@ struct ServiceFactory<T> {
inner: T, inner: T,
} }
impl<T> NewService<(Option<CounterGuard>, ServerMessage)> for ServiceFactory<T> impl<T> NewService for ServiceFactory<T>
where where
T: NewService<TcpStream, Response = ()>, T: NewService<Request = TcpStream, Response = ()>,
T::Future: 'static, T::Future: 'static,
T::Service: 'static, T::Service: 'static,
T::Error: 'static, T::Error: 'static,
T::InitError: fmt::Debug + 'static, T::InitError: fmt::Debug + 'static,
{ {
type Request = (Option<CounterGuard>, ServerMessage);
type Response = (); type Response = ();
type Error = (); type Error = ();
type InitError = (); type InitError = ();

View File

@@ -23,13 +23,13 @@ pub enum ServerMessage {
} }
pub trait StreamServiceFactory: Send + Clone + 'static { pub trait StreamServiceFactory: Send + Clone + 'static {
type NewService: NewService<TcpStream, Response = ()>; type NewService: NewService<Request = TcpStream, Response = ()>;
fn create(&self) -> Self::NewService; fn create(&self) -> Self::NewService;
} }
pub trait ServiceFactory: Send + Clone + 'static { pub trait ServiceFactory: Send + Clone + 'static {
type NewService: NewService<ServerMessage, Response = ()>; type NewService: NewService<Request = ServerMessage, Response = ()>;
fn create(&self) -> Self::NewService; fn create(&self) -> Self::NewService;
} }
@@ -44,7 +44,7 @@ pub(crate) trait InternalServiceFactory: Send {
pub(crate) type BoxedServerService = Box< pub(crate) type BoxedServerService = Box<
Service< Service<
(Option<CounterGuard>, ServerMessage), Request = (Option<CounterGuard>, ServerMessage),
Response = (), Response = (),
Error = (), Error = (),
Future = FutureResult<(), ()>, Future = FutureResult<(), ()>,
@@ -61,12 +61,13 @@ impl<T> StreamService<T> {
} }
} }
impl<T> Service<(Option<CounterGuard>, ServerMessage)> for StreamService<T> impl<T> Service for StreamService<T>
where where
T: Service<TcpStream, Response = ()>, T: Service<Request = TcpStream, Response = ()>,
T::Future: 'static, T::Future: 'static,
T::Error: 'static, T::Error: 'static,
{ {
type Request = (Option<CounterGuard>, ServerMessage);
type Response = (); type Response = ();
type Error = (); type Error = ();
type Future = FutureResult<(), ()>; type Future = FutureResult<(), ()>;
@@ -107,12 +108,13 @@ impl<T> ServerService<T> {
} }
} }
impl<T> Service<(Option<CounterGuard>, ServerMessage)> for ServerService<T> impl<T> Service for ServerService<T>
where where
T: Service<ServerMessage, Response = ()>, T: Service<Request = ServerMessage, Response = ()>,
T::Future: 'static, T::Future: 'static,
T::Error: 'static, T::Error: 'static,
{ {
type Request = (Option<CounterGuard>, ServerMessage);
type Response = (); type Response = ();
type Error = (); type Error = ();
type Future = FutureResult<(), ()>; type Future = FutureResult<(), ()>;
@@ -239,7 +241,7 @@ impl InternalServiceFactory for Box<InternalServiceFactory> {
impl<F, T> ServiceFactory for F impl<F, T> ServiceFactory for F
where where
F: Fn() -> T + Send + Clone + 'static, F: Fn() -> T + Send + Clone + 'static,
T: NewService<ServerMessage, Response = ()>, T: NewService<Request = ServerMessage, Response = ()>,
{ {
type NewService = T; type NewService = T;
@@ -251,7 +253,7 @@ where
impl<F, T> StreamServiceFactory for F impl<F, T> StreamServiceFactory for F
where where
F: Fn() -> T + Send + Clone + 'static, F: Fn() -> T + Send + Clone + 'static,
T: NewService<TcpStream, Response = ()>, T: NewService<Request = TcpStream, Response = ()>,
{ {
type NewService = T; type NewService = T;

View File

@@ -36,7 +36,8 @@ impl<T: AsyncRead + AsyncWrite> Clone for NativeTlsAcceptor<T> {
} }
} }
impl<T: AsyncRead + AsyncWrite> NewService<T> for NativeTlsAcceptor<T> { impl<T: AsyncRead + AsyncWrite> NewService for NativeTlsAcceptor<T> {
type Request = T;
type Response = TlsStream<T>; type Response = TlsStream<T>;
type Error = Error; type Error = Error;
type Service = NativeTlsAcceptorService<T>; type Service = NativeTlsAcceptorService<T>;
@@ -60,7 +61,8 @@ pub struct NativeTlsAcceptorService<T> {
conns: Counter, conns: Counter,
} }
impl<T: AsyncRead + AsyncWrite> Service<T> for NativeTlsAcceptorService<T> { impl<T: AsyncRead + AsyncWrite> Service for NativeTlsAcceptorService<T> {
type Request = T;
type Response = TlsStream<T>; type Response = TlsStream<T>;
type Error = Error; type Error = Error;
type Future = Accept<T>; type Future = Accept<T>;

View File

@@ -36,7 +36,8 @@ impl<T: AsyncRead + AsyncWrite> Clone for OpensslAcceptor<T> {
} }
} }
impl<T: AsyncRead + AsyncWrite> NewService<T> for OpensslAcceptor<T> { impl<T: AsyncRead + AsyncWrite> NewService for OpensslAcceptor<T> {
type Request = T;
type Response = SslStream<T>; type Response = SslStream<T>;
type Error = HandshakeError<T>; type Error = HandshakeError<T>;
type Service = OpensslAcceptorService<T>; type Service = OpensslAcceptorService<T>;
@@ -60,7 +61,8 @@ pub struct OpensslAcceptorService<T> {
conns: Counter, conns: Counter,
} }
impl<T: AsyncRead + AsyncWrite> Service<T> for OpensslAcceptorService<T> { impl<T: AsyncRead + AsyncWrite> Service for OpensslAcceptorService<T> {
type Request = T;
type Response = SslStream<T>; type Response = SslStream<T>;
type Error = HandshakeError<T>; type Error = HandshakeError<T>;
type Future = OpensslAcceptorServiceFut<T>; type Future = OpensslAcceptorServiceFut<T>;

View File

@@ -38,7 +38,8 @@ impl<T> Clone for RustlsAcceptor<T> {
} }
} }
impl<T: AsyncRead + AsyncWrite> NewService<T> for RustlsAcceptor<T> { impl<T: AsyncRead + AsyncWrite> NewService for RustlsAcceptor<T> {
type Request = T;
type Response = TlsStream<T, ServerSession>; type Response = TlsStream<T, ServerSession>;
type Error = io::Error; type Error = io::Error;
type Service = RustlsAcceptorService<T>; type Service = RustlsAcceptorService<T>;
@@ -62,7 +63,8 @@ pub struct RustlsAcceptorService<T> {
conns: Counter, conns: Counter,
} }
impl<T: AsyncRead + AsyncWrite> Service<T> for RustlsAcceptorService<T> { impl<T: AsyncRead + AsyncWrite> Service for RustlsAcceptorService<T> {
type Request = T;
type Response = TlsStream<T, ServerSession>; type Response = TlsStream<T, ServerSession>;
type Error = io::Error; type Error = io::Error;
type Future = RustlsAcceptorServiceFut<T>; type Future = RustlsAcceptorServiceFut<T>;

View File

@@ -1,5 +1,37 @@
# Changes # Changes
## [0.2.1] - 2019-02-03
### Changed
* Generalize `.apply` combinator with Transform trait
## [0.2.0] - 2019-02-01
### Changed
* Use associated type instead of generic for Service definition.
* Before:
```rust
impl Service<Request> for Client {
type Response = Response;
// ...
}
```
* After:
```rust
impl Service for Client {
type Request = Request;
type Response = Response;
// ...
}
```
## [0.1.6] - 2019-01-24 ## [0.1.6] - 2019-01-24
### Changed ### Changed

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-service" name = "actix-service"
version = "0.1.6" version = "0.2.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix Service" description = "Actix Service"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -15,7 +15,7 @@ workspace = "../"
[badges] [badges]
travis-ci = { repository = "actix/actix-service", branch = "master" } travis-ci = { repository = "actix/actix-service", branch = "master" }
# appveyor = { repository = "fafhrd91/actix-web-hdy9d" } appveyor = { repository = "actix/actix-net" }
codecov = { repository = "actix/actix-service", branch = "master", service = "github" } codecov = { repository = "actix/actix-service", branch = "master", service = "github" }
[lib] [lib]

View File

@@ -14,10 +14,10 @@ pub struct AndThen<A, B> {
impl<A, B> AndThen<A, B> { impl<A, B> AndThen<A, B> {
/// Create new `AndThen` combinator /// Create new `AndThen` combinator
pub fn new<Request>(a: A, b: B) -> Self pub fn new(a: A, b: B) -> Self
where where
A: Service<Request>, A: Service,
B: Service<A::Response, Error = A::Error>, B: Service<Request = A::Response, Error = A::Error>,
{ {
Self { a, b: Cell::new(b) } Self { a, b: Cell::new(b) }
} }
@@ -35,39 +35,40 @@ where
} }
} }
impl<A, B, Request> Service<Request> for AndThen<A, B> impl<A, B> Service for AndThen<A, B>
where where
A: Service<Request>, A: Service,
B: Service<A::Response, Error = A::Error>, B: Service<Request = A::Response, Error = A::Error>,
{ {
type Request = A::Request;
type Response = B::Response; type Response = B::Response;
type Error = A::Error; type Error = A::Error;
type Future = AndThenFuture<A, B, Request>; type Future = AndThenFuture<A, B>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
try_ready!(self.a.poll_ready()); try_ready!(self.a.poll_ready());
self.b.get_mut().poll_ready() self.b.get_mut().poll_ready()
} }
fn call(&mut self, req: Request) -> Self::Future { fn call(&mut self, req: A::Request) -> Self::Future {
AndThenFuture::new(self.a.call(req), self.b.clone()) AndThenFuture::new(self.a.call(req), self.b.clone())
} }
} }
pub struct AndThenFuture<A, B, Request> pub struct AndThenFuture<A, B>
where where
A: Service<Request>, A: Service,
B: Service<A::Response, Error = A::Error>, B: Service<Request = A::Response, Error = A::Error>,
{ {
b: Cell<B>, b: Cell<B>,
fut_b: Option<B::Future>, fut_b: Option<B::Future>,
fut_a: Option<A::Future>, fut_a: Option<A::Future>,
} }
impl<A, B, Request> AndThenFuture<A, B, Request> impl<A, B> AndThenFuture<A, B>
where where
A: Service<Request>, A: Service,
B: Service<A::Response, Error = A::Error>, B: Service<Request = A::Response, Error = A::Error>,
{ {
fn new(a: A::Future, b: Cell<B>) -> Self { fn new(a: A::Future, b: Cell<B>) -> Self {
AndThenFuture { AndThenFuture {
@@ -78,10 +79,10 @@ where
} }
} }
impl<A, B, Request> Future for AndThenFuture<A, B, Request> impl<A, B> Future for AndThenFuture<A, B>
where where
A: Service<Request>, A: Service,
B: Service<A::Response, Error = A::Error>, B: Service<Request = A::Response, Error = A::Error>,
{ {
type Item = B::Response; type Item = B::Response;
type Error = A::Error; type Error = A::Error;
@@ -111,10 +112,10 @@ pub struct AndThenNewService<A, B> {
impl<A, B> AndThenNewService<A, B> { impl<A, B> AndThenNewService<A, B> {
/// Create new `AndThen` combinator /// Create new `AndThen` combinator
pub fn new<Request, F: IntoNewService<B, A::Response>>(a: A, f: F) -> Self pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self
where where
A: NewService<Request>, A: NewService,
B: NewService<A::Response, Error = A::Error, InitError = A::InitError>, B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
{ {
Self { Self {
a, a,
@@ -123,17 +124,18 @@ impl<A, B> AndThenNewService<A, B> {
} }
} }
impl<A, B, Request> NewService<Request> for AndThenNewService<A, B> impl<A, B> NewService for AndThenNewService<A, B>
where where
A: NewService<Request>, A: NewService,
B: NewService<A::Response, Error = A::Error, InitError = A::InitError>, B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
{ {
type Request = A::Request;
type Response = B::Response; type Response = B::Response;
type Error = A::Error; type Error = A::Error;
type Service = AndThen<A::Service, B::Service>; type Service = AndThen<A::Service, B::Service>;
type InitError = A::InitError; type InitError = A::InitError;
type Future = AndThenNewServiceFuture<A, B, Request>; type Future = AndThenNewServiceFuture<A, B>;
fn new_service(&self) -> Self::Future { fn new_service(&self) -> Self::Future {
AndThenNewServiceFuture::new(self.a.new_service(), self.b.new_service()) AndThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
@@ -153,10 +155,10 @@ where
} }
} }
pub struct AndThenNewServiceFuture<A, B, Request> pub struct AndThenNewServiceFuture<A, B>
where where
A: NewService<Request>, A: NewService,
B: NewService<A::Response>, B: NewService<Request = A::Response>,
{ {
fut_b: B::Future, fut_b: B::Future,
fut_a: A::Future, fut_a: A::Future,
@@ -164,10 +166,10 @@ where
b: Option<B::Service>, b: Option<B::Service>,
} }
impl<A, B, Request> AndThenNewServiceFuture<A, B, Request> impl<A, B> AndThenNewServiceFuture<A, B>
where where
A: NewService<Request>, A: NewService,
B: NewService<A::Response>, B: NewService<Request = A::Response>,
{ {
fn new(fut_a: A::Future, fut_b: B::Future) -> Self { fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
AndThenNewServiceFuture { AndThenNewServiceFuture {
@@ -179,10 +181,10 @@ where
} }
} }
impl<A, B, Request> Future for AndThenNewServiceFuture<A, B, Request> impl<A, B> Future for AndThenNewServiceFuture<A, B>
where where
A: NewService<Request>, A: NewService,
B: NewService<A::Response, Error = A::Error, InitError = A::InitError>, B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
{ {
type Item = AndThen<A::Service, B::Service>; type Item = AndThen<A::Service, B::Service>;
type Error = A::InitError; type Error = A::InitError;
@@ -222,7 +224,8 @@ mod tests {
use crate::{NewService, Service, ServiceExt}; use crate::{NewService, Service, ServiceExt};
struct Srv1(Rc<Cell<usize>>); struct Srv1(Rc<Cell<usize>>);
impl Service<&'static str> for Srv1 { impl Service for Srv1 {
type Request = &'static str;
type Response = &'static str; type Response = &'static str;
type Error = (); type Error = ();
type Future = FutureResult<Self::Response, ()>; type Future = FutureResult<Self::Response, ()>;
@@ -240,7 +243,8 @@ mod tests {
#[derive(Clone)] #[derive(Clone)]
struct Srv2(Rc<Cell<usize>>); struct Srv2(Rc<Cell<usize>>);
impl Service<&'static str> for Srv2 { impl Service for Srv2 {
type Request = &'static str;
type Response = (&'static str, &'static str); type Response = (&'static str, &'static str);
type Error = (); type Error = ();
type Future = FutureResult<Self::Response, ()>; type Future = FutureResult<Self::Response, ()>;

View File

@@ -1,126 +1,120 @@
use std::marker::PhantomData; use futures::{Async, Future, Poll};
use futures::{try_ready, Async, Future, IntoFuture, Poll}; use super::{NewService, NewTransform, Service, Transform};
use super::{IntoNewService, IntoService, NewService, Service};
use crate::cell::Cell; use crate::cell::Cell;
/// `Apply` service combinator /// `Apply` service combinator
pub struct AndThenApply<A, B, F, Out, Req1, Req2> pub struct AndThenTransform<T, A, B>
where where
A: Service<Req1>, A: Service,
B: Service<Req2, Error = A::Error>, B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out, T: Transform<B, Request = A::Response>,
Out: IntoFuture, T::Error: From<A::Error>,
Out::Error: Into<A::Error>,
{ {
a: A, a: A,
b: Cell<B>, b: Cell<B>,
f: Cell<F>, t: Cell<T>,
r: PhantomData<(Out, Req1, Req2)>,
} }
impl<A, B, F, Out, Req1, Req2> AndThenApply<A, B, F, Out, Req1, Req2> impl<T, A, B> AndThenTransform<T, A, B>
where where
A: Service<Req1>, A: Service,
B: Service<Req2, Error = A::Error>, B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out, T: Transform<B, Request = A::Response>,
Out: IntoFuture, T::Error: From<A::Error>,
Out::Error: Into<A::Error>,
{ {
/// Create new `Apply` combinator /// Create new `Apply` combinator
pub fn new<A1: IntoService<A, Req1>, B1: IntoService<B, Req2>>(a: A1, b: B1, f: F) -> Self { pub fn new(t: T, a: A, b: B) -> Self {
Self { Self {
f: Cell::new(f), a,
a: a.into_service(), b: Cell::new(b),
b: Cell::new(b.into_service()), t: Cell::new(t),
r: PhantomData,
} }
} }
} }
impl<A, B, F, Out, Req1, Req2> Clone for AndThenApply<A, B, F, Out, Req1, Req2> impl<T, A, B> Clone for AndThenTransform<T, A, B>
where where
A: Service<Req1> + Clone, A: Service + Clone,
B: Service<Req2, Error = A::Error>, B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out, T: Transform<B, Request = A::Response>,
Out: IntoFuture, T::Error: From<A::Error>,
Out::Error: Into<A::Error>,
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
AndThenApply { AndThenTransform {
a: self.a.clone(), a: self.a.clone(),
b: self.b.clone(), b: self.b.clone(),
f: self.f.clone(), t: self.t.clone(),
r: PhantomData,
} }
} }
} }
impl<A, B, F, Out, Req1, Req2> Service<Req1> for AndThenApply<A, B, F, Out, Req1, Req2> impl<T, A, B> Service for AndThenTransform<T, A, B>
where where
A: Service<Req1>, A: Service,
B: Service<Req2, Error = A::Error>, B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out, T: Transform<B, Request = A::Response>,
Out: IntoFuture, T::Error: From<A::Error>,
Out::Error: Into<A::Error>,
{ {
type Response = Out::Item; type Request = A::Request;
type Error = A::Error; type Response = T::Response;
type Future = AndThenApplyFuture<A, B, F, Out, Req1, Req2>; type Error = T::Error;
type Future = AndThenTransformFuture<T, A, B>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
try_ready!(self.a.poll_ready()); let notready = Async::NotReady == self.a.poll_ready()?;
self.b.get_mut().poll_ready().map_err(|e| e.into()) let notready = Async::NotReady == self.b.get_mut().poll_ready()? || notready;
let notready = Async::NotReady == self.t.get_mut().poll_ready()? || notready;
if notready {
Ok(Async::NotReady)
} else {
Ok(Async::Ready(()))
}
} }
fn call(&mut self, req: Req1) -> Self::Future { fn call(&mut self, req: A::Request) -> Self::Future {
AndThenApplyFuture { AndThenTransformFuture {
b: self.b.clone(), b: self.b.clone(),
f: self.f.clone(), t: self.t.clone(),
fut_b: None, fut_t: None,
fut_a: Some(self.a.call(req)), fut_a: Some(self.a.call(req)),
_t: PhantomData,
} }
} }
} }
pub struct AndThenApplyFuture<A, B, F, Out, Req1, Req2> pub struct AndThenTransformFuture<T, A, B>
where where
A: Service<Req1>, A: Service,
B: Service<Req2, Error = A::Error>, B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out, T: Transform<B, Request = A::Response>,
Out: IntoFuture, T::Error: From<A::Error>,
Out::Error: Into<A::Error>,
{ {
b: Cell<B>, b: Cell<B>,
f: Cell<F>, t: Cell<T>,
fut_a: Option<A::Future>, fut_a: Option<A::Future>,
fut_b: Option<Out::Future>, fut_t: Option<T::Future>,
_t: PhantomData<Req2>,
} }
impl<A, B, F, Out, Req1, Req2> Future for AndThenApplyFuture<A, B, F, Out, Req1, Req2> impl<T, A, B> Future for AndThenTransformFuture<T, A, B>
where where
A: Service<Req1>, A: Service,
B: Service<Req2, Error = A::Error>, B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out, T: Transform<B, Request = A::Response>,
Out: IntoFuture, T::Error: From<A::Error>,
Out::Error: Into<A::Error>,
{ {
type Item = Out::Item; type Item = T::Response;
type Error = A::Error; type Error = T::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Some(ref mut fut) = self.fut_b { if let Some(ref mut fut) = self.fut_t {
return fut.poll().map_err(|e| e.into()); return fut.poll().map_err(|e| e.into());
} }
match self.fut_a.as_mut().expect("Bug in actix-service").poll() { match self.fut_a.as_mut().expect("Bug in actix-service").poll() {
Ok(Async::Ready(resp)) => { Ok(Async::Ready(resp)) => {
let _ = self.fut_a.take(); let _ = self.fut_a.take();
self.fut_b = self.fut_t = Some(self.t.get_mut().call(resp, self.b.get_mut()));
Some((&mut *self.f.get_mut())(resp, self.b.get_mut()).into_future());
self.poll() self.poll()
} }
Ok(Async::NotReady) => Ok(Async::NotReady), Ok(Async::NotReady) => Ok(Async::NotReady),
@@ -129,106 +123,100 @@ where
} }
} }
/// `ApplyNewService` new service combinator /// `Apply` new service combinator
pub struct AndThenApplyNewService<A, B, F, Out, Req1, Req2> { pub struct AndThenTransformNewService<T, A, B> {
a: A, a: A,
b: B, b: B,
f: Cell<F>, t: T,
r: PhantomData<(Out, Req1, Req2)>,
} }
impl<A, B, F, Out, Req1, Req2> AndThenApplyNewService<A, B, F, Out, Req1, Req2> impl<T, A, B> AndThenTransformNewService<T, A, B>
where where
A: NewService<Req1>, A: NewService,
B: NewService<Req2, Error = A::Error, InitError = A::InitError>, B: NewService<Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out, T: NewTransform<B::Service, Request = A::Response, InitError = A::InitError>,
Out: IntoFuture, T::Error: From<A::Error>,
Out::Error: Into<A::Error>,
{ {
/// Create new `ApplyNewService` new service instance /// Create new `ApplyNewService` new service instance
pub fn new<A1: IntoNewService<A, Req1>, B1: IntoNewService<B, Req2>>( pub fn new(t: T, a: A, b: B) -> Self {
a: A1, Self { a, b, t }
b: B1,
f: F,
) -> Self {
Self {
f: Cell::new(f),
a: a.into_new_service(),
b: b.into_new_service(),
r: PhantomData,
}
} }
} }
impl<A, B, F, Out, Req1, Req2> Clone for AndThenApplyNewService<A, B, F, Out, Req1, Req2> impl<T, A, B> Clone for AndThenTransformNewService<T, A, B>
where where
A: Clone, A: Clone,
B: Clone, B: Clone,
T: Clone,
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Self { Self {
a: self.a.clone(), a: self.a.clone(),
b: self.b.clone(), b: self.b.clone(),
f: self.f.clone(), t: self.t.clone(),
r: PhantomData,
} }
} }
} }
impl<A, B, F, Out, Req1, Req2> NewService<Req1> impl<T, A, B> NewService for AndThenTransformNewService<T, A, B>
for AndThenApplyNewService<A, B, F, Out, Req1, Req2>
where where
A: NewService<Req1>, A: NewService,
B: NewService<Req2, Error = A::Error, InitError = A::InitError>, B: NewService<Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out, T: NewTransform<B::Service, Request = A::Response, InitError = A::InitError>,
Out: IntoFuture, T::Error: From<A::Error>,
Out::Error: Into<A::Error>,
{ {
type Response = Out::Item; type Request = A::Request;
type Error = A::Error; type Response = T::Response;
type Error = T::Error;
type InitError = A::InitError; type InitError = T::InitError;
type Service = AndThenApply<A::Service, B::Service, F, Out, Req1, Req2>; type Service = AndThenTransform<T::Transform, A::Service, B::Service>;
type Future = AndThenApplyNewServiceFuture<A, B, F, Out, Req1, Req2>; type Future = AndThenTransformNewServiceFuture<T, A, B>;
fn new_service(&self) -> Self::Future { fn new_service(&self) -> Self::Future {
AndThenApplyNewServiceFuture { AndThenTransformNewServiceFuture {
a: None, a: None,
b: None, b: None,
f: self.f.clone(), t: None,
fut_a: self.a.new_service(), fut_a: self.a.new_service(),
fut_b: self.b.new_service(), fut_b: self.b.new_service(),
fut_t: self.t.new_transform(),
} }
} }
} }
pub struct AndThenApplyNewServiceFuture<A, B, F, Out, Req1, Req2> pub struct AndThenTransformNewServiceFuture<T, A, B>
where where
A: NewService<Req1>, A: NewService,
B: NewService<Req2, Error = A::Error, InitError = A::InitError>, B: NewService<Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out, T: NewTransform<B::Service, Request = A::Response, InitError = A::InitError>,
Out: IntoFuture, T::Error: From<A::Error>,
Out::Error: Into<A::Error>,
{ {
fut_b: B::Future, fut_b: B::Future,
fut_a: A::Future, fut_a: A::Future,
f: Cell<F>, fut_t: T::Future,
a: Option<A::Service>, a: Option<A::Service>,
b: Option<B::Service>, b: Option<B::Service>,
t: Option<T::Transform>,
} }
impl<A, B, F, Out, Req1, Req2> Future for AndThenApplyNewServiceFuture<A, B, F, Out, Req1, Req2> impl<T, A, B> Future for AndThenTransformNewServiceFuture<T, A, B>
where where
A: NewService<Req1>, A: NewService,
B: NewService<Req2, Error = A::Error, InitError = A::InitError>, B: NewService<Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out, T: NewTransform<B::Service, Request = A::Response, InitError = A::InitError>,
Out: IntoFuture, T::Error: From<A::Error>,
Out::Error: Into<A::Error>,
{ {
type Item = AndThenApply<A::Service, B::Service, F, Out, Req1, Req2>; type Item = AndThenTransform<T::Transform, A::Service, B::Service>;
type Error = A::InitError; type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if self.t.is_none() {
if let Async::Ready(transform) = self.fut_t.poll()? {
self.t = Some(transform);
}
}
if self.a.is_none() { if self.a.is_none() {
if let Async::Ready(service) = self.fut_a.poll()? { if let Async::Ready(service) = self.fut_a.poll()? {
self.a = Some(service); self.a = Some(service);
@@ -241,12 +229,11 @@ where
} }
} }
if self.a.is_some() && self.b.is_some() { if self.a.is_some() && self.b.is_some() && self.t.is_some() {
Ok(Async::Ready(AndThenApply { Ok(Async::Ready(AndThenTransform {
f: self.f.clone(),
a: self.a.take().unwrap(), a: self.a.take().unwrap(),
t: Cell::new(self.t.take().unwrap()),
b: Cell::new(self.b.take().unwrap()), b: Cell::new(self.b.take().unwrap()),
r: PhantomData,
})) }))
} else { } else {
Ok(Async::NotReady) Ok(Async::NotReady)
@@ -263,7 +250,8 @@ mod tests {
#[derive(Clone)] #[derive(Clone)]
struct Srv; struct Srv;
impl Service<()> for Srv { impl Service for Srv {
type Request = ();
type Response = (); type Response = ();
type Error = (); type Error = ();
type Future = FutureResult<(), ()>; type Future = FutureResult<(), ()>;
@@ -278,12 +266,13 @@ mod tests {
} }
#[test] #[test]
fn test_call() { fn test_apply() {
let blank = |req| Ok(req); let blank = |req| Ok(req);
let mut srv = blank.into_service().apply(Srv, |req: &'static str, srv| { let mut srv = blank.into_service().apply(
srv.call(()).map(move |res| (req, res)) |req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)),
}); Srv,
);
assert!(srv.poll_ready().is_ok()); assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll(); let res = srv.call("srv").poll();
assert!(res.is_ok()); assert!(res.is_ok());
@@ -295,8 +284,8 @@ mod tests {
let blank = || Ok::<_, ()>((|req| Ok(req)).into_service()); let blank = || Ok::<_, ()>((|req| Ok(req)).into_service());
let new_srv = blank.into_new_service().apply( let new_srv = blank.into_new_service().apply(
|req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)),
|| Ok(Srv), || Ok(Srv),
|req: &'static str, srv| srv.call(()).map(move |res| (req, res)),
); );
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() { if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
assert!(srv.poll_ready().is_ok()); assert!(srv.poll_ready().is_ok());

View File

@@ -0,0 +1,302 @@
use std::marker::PhantomData;
use futures::{try_ready, Async, Future, IntoFuture, Poll};
use super::{IntoNewService, IntoService, NewService, Service};
use crate::cell::Cell;
/// `Apply` service combinator
pub struct AndThenApply<A, B, F, Out>
where
A: Service,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
a: A,
b: Cell<B>,
f: Cell<F>,
r: PhantomData<(Out,)>,
}
impl<A, B, F, Out> AndThenApply<A, B, F, Out>
where
A: Service,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
/// Create new `Apply` combinator
pub fn new<A1: IntoService<A>, B1: IntoService<B>>(a: A1, b: B1, f: F) -> Self {
Self {
f: Cell::new(f),
a: a.into_service(),
b: Cell::new(b.into_service()),
r: PhantomData,
}
}
}
impl<A, B, F, Out> Clone for AndThenApply<A, B, F, Out>
where
A: Service + Clone,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
fn clone(&self) -> Self {
AndThenApply {
a: self.a.clone(),
b: self.b.clone(),
f: self.f.clone(),
r: PhantomData,
}
}
}
impl<A, B, F, Out> Service for AndThenApply<A, B, F, Out>
where
A: Service,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
type Request = A::Request;
type Response = Out::Item;
type Error = A::Error;
type Future = AndThenApplyFuture<A, B, F, Out>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
try_ready!(self.a.poll_ready());
self.b.get_mut().poll_ready().map_err(|e| e.into())
}
fn call(&mut self, req: A::Request) -> Self::Future {
AndThenApplyFuture {
b: self.b.clone(),
f: self.f.clone(),
fut_b: None,
fut_a: Some(self.a.call(req)),
}
}
}
pub struct AndThenApplyFuture<A, B, F, Out>
where
A: Service,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
b: Cell<B>,
f: Cell<F>,
fut_a: Option<A::Future>,
fut_b: Option<Out::Future>,
}
impl<A, B, F, Out> Future for AndThenApplyFuture<A, B, F, Out>
where
A: Service,
B: Service<Error = A::Error>,
F: FnMut(A::Response, &mut B) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
{
type Item = Out::Item;
type Error = A::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Some(ref mut fut) = self.fut_b {
return fut.poll().map_err(|e| e.into());
}
match self.fut_a.as_mut().expect("Bug in actix-service").poll() {
Ok(Async::Ready(resp)) => {
let _ = self.fut_a.take();
self.fut_b =
Some((&mut *self.f.get_mut())(resp, self.b.get_mut()).into_future());
self.poll()
}
Ok(Async::NotReady) => Ok(Async::NotReady),
Err(err) => Err(err.into()),
}
}
}
/// `ApplyNewService` new service combinator
pub struct AndThenApplyNewService<A, B, F, Out> {
a: A,
b: B,
f: Cell<F>,
r: PhantomData<(Out)>,
}
impl<A, B, F, Out> AndThenApplyNewService<A, B, F, Out>
where
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>,
{
/// Create new `ApplyNewService` new service instance
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(),
b: b.into_new_service(),
r: PhantomData,
}
}
}
impl<A, B, F, Out> Clone for AndThenApplyNewService<A, B, F, Out>
where
A: Clone,
B: Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
b: self.b.clone(),
f: self.f.clone(),
r: PhantomData,
}
}
}
impl<A, B, F, Out> NewService for AndThenApplyNewService<A, B, F, Out>
where
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>,
{
type Request = A::Request;
type Response = Out::Item;
type Error = A::Error;
type InitError = A::InitError;
type Service = AndThenApply<A::Service, B::Service, F, Out>;
type Future = AndThenApplyNewServiceFuture<A, B, F, Out>;
fn new_service(&self) -> Self::Future {
AndThenApplyNewServiceFuture {
a: None,
b: None,
f: self.f.clone(),
fut_a: self.a.new_service(),
fut_b: self.b.new_service(),
}
}
}
pub struct AndThenApplyNewServiceFuture<A, B, F, Out>
where
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>,
{
fut_b: B::Future,
fut_a: A::Future,
f: Cell<F>,
a: Option<A::Service>,
b: Option<B::Service>,
}
impl<A, B, F, Out> Future for AndThenApplyNewServiceFuture<A, B, F, Out>
where
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>,
{
type Item = AndThenApply<A::Service, B::Service, F, Out>;
type Error = A::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if self.a.is_none() {
if let Async::Ready(service) = self.fut_a.poll()? {
self.a = Some(service);
}
}
if self.b.is_none() {
if let Async::Ready(service) = self.fut_b.poll()? {
self.b = Some(service);
}
}
if self.a.is_some() && self.b.is_some() {
Ok(Async::Ready(AndThenApply {
f: self.f.clone(),
a: self.a.take().unwrap(),
b: Cell::new(self.b.take().unwrap()),
r: PhantomData,
}))
} else {
Ok(Async::NotReady)
}
}
}
#[cfg(test)]
mod tests {
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use crate::{Blank, BlankNewService, NewService, Service, ServiceExt};
#[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_call() {
let mut srv = Blank::new().apply_fn(Srv, |req: &'static str, srv| {
srv.call(()).map(move |res| (req, res))
});
assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
}
#[test]
fn test_new_service() {
let new_srv = BlankNewService::new_unit().apply_fn(
|| Ok(Srv),
|req: &'static str, srv| srv.call(()).map(move |res| (req, res)),
);
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
assert!(srv.poll_ready().is_ok());
let res = srv.call("srv").poll();
assert!(res.is_ok());
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
} else {
panic!()
}
}
}

View File

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

View File

@@ -0,0 +1,81 @@
use std::marker::PhantomData;
use futures::future::{ok, FutureResult};
use futures::{Async, Poll};
use super::{NewService, Service};
/// Empty service
#[derive(Clone)]
pub struct Blank<R, E> {
_t: PhantomData<(R, E)>,
}
impl<R, E> Blank<R, E> {
pub fn err<E1>(self) -> Blank<R, E1> {
Blank { _t: PhantomData }
}
}
impl<R> Blank<R, ()> {
pub fn new<E>() -> Blank<R, E> {
Blank { _t: PhantomData }
}
}
impl<R, E> Default for Blank<R, E> {
fn default() -> Blank<R, E> {
Blank { _t: PhantomData }
}
}
impl<R, E> Service for Blank<R, E> {
type Request = R;
type Response = R;
type Error = E;
type Future = FutureResult<R, E>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: R) -> Self::Future {
ok(req)
}
}
/// Empty service factory
pub struct BlankNewService<R, E1, E2 = ()> {
_t: PhantomData<(R, E1, E2)>,
}
impl<R, E1, E2> BlankNewService<R, E1, E2> {
pub fn new() -> BlankNewService<R, E1, E2> {
BlankNewService { _t: PhantomData }
}
}
impl<R, E1> BlankNewService<R, E1, ()> {
pub fn new_unit() -> BlankNewService<R, E1, ()> {
BlankNewService { _t: PhantomData }
}
}
impl<R, E1, E2> Default for BlankNewService<R, E1, E2> {
fn default() -> BlankNewService<R, E1, E2> {
Self::new()
}
}
impl<R, E1, E2> NewService for BlankNewService<R, E1, E2> {
type Request = R;
type Response = R;
type Error = E1;
type InitError = E2;
type Service = Blank<R, E1>;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future {
ok(Blank::default())
}
}

View File

@@ -1,55 +1,51 @@
use std::marker; use std::marker::PhantomData;
use futures::{ use futures::future::{ok, FutureResult};
future::{ok, FutureResult}, use futures::{Async, IntoFuture, Poll};
Async, IntoFuture, Poll,
};
use super::{IntoNewService, IntoService, NewService, Service}; use super::{IntoNewService, IntoService, NewService, Service};
pub struct FnService<F, Req, Resp, E, Fut> pub struct FnService<F, Req, Out>
where where
F: FnMut(Req) -> Fut, F: FnMut(Req) -> Out,
Fut: IntoFuture<Item = Resp, Error = E>, Out: IntoFuture,
{ {
f: F, f: F,
_t: marker::PhantomData<(Req, Resp, E)>, _t: PhantomData<(Req,)>,
} }
impl<F, Req, Resp, E, Fut> FnService<F, Req, Resp, E, Fut> impl<F, Req, Out> FnService<F, Req, Out>
where where
F: FnMut(Req) -> Fut, F: FnMut(Req) -> Out,
Fut: IntoFuture<Item = Resp, Error = E>, Out: IntoFuture,
{ {
pub fn new(f: F) -> Self { pub fn new(f: F) -> Self {
FnService { FnService { f, _t: PhantomData }
f,
_t: marker::PhantomData,
}
} }
} }
impl<F, Req, Resp, E, Fut> Clone for FnService<F, Req, Resp, E, Fut> impl<F, Req, Out> Clone for FnService<F, Req, Out>
where where
F: FnMut(Req) -> Fut + Clone, F: FnMut(Req) -> Out + Clone,
Fut: IntoFuture<Item = Resp, Error = E>, Out: IntoFuture,
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
FnService { FnService {
f: self.f.clone(), f: self.f.clone(),
_t: marker::PhantomData, _t: PhantomData,
} }
} }
} }
impl<F, Req, Resp, E, Fut> Service<Req> for FnService<F, Req, Resp, E, Fut> impl<F, Req, Out> Service for FnService<F, Req, Out>
where where
F: FnMut(Req) -> Fut, F: FnMut(Req) -> Out,
Fut: IntoFuture<Item = Resp, Error = E>, Out: IntoFuture,
{ {
type Response = Resp; type Request = Req;
type Error = E; type Response = Out::Item;
type Future = Fut::Future; type Error = Out::Error;
type Future = Out::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(())) Ok(Async::Ready(()))
@@ -60,46 +56,44 @@ where
} }
} }
impl<F, Req, Resp, Err, Fut> IntoService<FnService<F, Req, Resp, Err, Fut>, Req> for F impl<F, Req, Out> IntoService<FnService<F, Req, Out>> for F
where where
F: FnMut(Req) -> Fut + 'static, F: FnMut(Req) -> Out + 'static,
Fut: IntoFuture<Item = Resp, Error = Err>, Out: IntoFuture,
{ {
fn into_service(self) -> FnService<F, Req, Resp, Err, Fut> { fn into_service(self) -> FnService<F, Req, Out> {
FnService::new(self) FnService::new(self)
} }
} }
pub struct FnNewService<F, Req, Resp, Err, Fut> pub struct FnNewService<F, Req, Out>
where where
F: FnMut(Req) -> Fut, F: FnMut(Req) -> Out,
Fut: IntoFuture<Item = Resp, Error = Err>, Out: IntoFuture,
{ {
f: F, f: F,
_t: marker::PhantomData<(Req, Resp, Err)>, _t: PhantomData<(Req,)>,
} }
impl<F, Req, Resp, Err, Fut> FnNewService<F, Req, Resp, Err, Fut> impl<F, Req, Out> FnNewService<F, Req, Out>
where where
F: FnMut(Req) -> Fut + Clone, F: FnMut(Req) -> Out + Clone,
Fut: IntoFuture<Item = Resp, Error = Err>, Out: IntoFuture,
{ {
pub fn new(f: F) -> Self { pub fn new(f: F) -> Self {
FnNewService { FnNewService { f, _t: PhantomData }
f,
_t: marker::PhantomData,
}
} }
} }
impl<F, Req, Resp, Err, Fut> NewService<Req> for FnNewService<F, Req, Resp, Err, Fut> impl<F, Req, Out> NewService for FnNewService<F, Req, Out>
where where
F: FnMut(Req) -> Fut + Clone, F: FnMut(Req) -> Out + Clone,
Fut: IntoFuture<Item = Resp, Error = Err>, Out: IntoFuture,
{ {
type Response = Resp; type Request = Req;
type Error = Err; type Response = Out::Item;
type Service = FnService<F, Req, Resp, Err, Fut>; type Error = Out::Error;
type Service = FnService<F, Req, Out>;
type InitError = (); type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>; type Future = FutureResult<Self::Service, Self::InitError>;
@@ -108,20 +102,20 @@ where
} }
} }
impl<F, Req, Resp, Err, Fut> IntoNewService<FnNewService<F, Req, Resp, Err, Fut>, Req> for F impl<F, Req, Out> IntoNewService<FnNewService<F, Req, Out>> for F
where where
F: FnMut(Req) -> Fut + Clone + 'static, F: FnMut(Req) -> Out + Clone + 'static,
Fut: IntoFuture<Item = Resp, Error = Err>, Out: IntoFuture,
{ {
fn into_new_service(self) -> FnNewService<F, Req, Resp, Err, Fut> { fn into_new_service(self) -> FnNewService<F, Req, Out> {
FnNewService::new(self) FnNewService::new(self)
} }
} }
impl<F, Req, Resp, Err, Fut> Clone for FnNewService<F, Req, Resp, Err, Fut> impl<F, Req, Out> Clone for FnNewService<F, Req, Out>
where where
F: FnMut(Req) -> Fut + Clone, F: FnMut(Req) -> Out + Clone,
Fut: IntoFuture<Item = Resp, Error = Err>, Out: IntoFuture,
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Self::new(self.f.clone()) Self::new(self.f.clone())

View File

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

View File

@@ -13,9 +13,9 @@ pub struct FromErr<A, E> {
} }
impl<A, E> FromErr<A, E> { impl<A, E> FromErr<A, E> {
pub(crate) fn new<Request>(service: A) -> Self pub(crate) fn new(service: A) -> Self
where where
A: Service<Request>, A: Service,
E: From<A::Error>, E: From<A::Error>,
{ {
FromErr { FromErr {
@@ -37,20 +37,21 @@ where
} }
} }
impl<A, E, Request> Service<Request> for FromErr<A, E> impl<A, E> Service for FromErr<A, E>
where where
A: Service<Request>, A: Service,
E: From<A::Error>, E: From<A::Error>,
{ {
type Request = A::Request;
type Response = A::Response; type Response = A::Response;
type Error = E; type Error = E;
type Future = FromErrFuture<A, E, Request>; type Future = FromErrFuture<A, E>;
fn poll_ready(&mut self) -> Poll<(), E> { fn poll_ready(&mut self) -> Poll<(), E> {
Ok(self.service.poll_ready().map_err(E::from)?) self.service.poll_ready().map_err(E::from)
} }
fn call(&mut self, req: Request) -> Self::Future { fn call(&mut self, req: A::Request) -> Self::Future {
FromErrFuture { FromErrFuture {
fut: self.service.call(req), fut: self.service.call(req),
f: PhantomData, f: PhantomData,
@@ -58,14 +59,14 @@ where
} }
} }
pub struct FromErrFuture<A: Service<Request>, E, Request> { pub struct FromErrFuture<A: Service, E> {
fut: A::Future, fut: A::Future,
f: PhantomData<E>, f: PhantomData<E>,
} }
impl<A, E, Request> Future for FromErrFuture<A, E, Request> impl<A, E> Future for FromErrFuture<A, E>
where where
A: Service<Request>, A: Service,
E: From<A::Error>, E: From<A::Error>,
{ {
type Item = A::Response; type Item = A::Response;
@@ -87,9 +88,9 @@ pub struct FromErrNewService<A, E> {
impl<A, E> FromErrNewService<A, E> { impl<A, E> FromErrNewService<A, E> {
/// Create new `FromErr` new service instance /// Create new `FromErr` new service instance
pub fn new<Request>(a: A) -> Self pub fn new(a: A) -> Self
where where
A: NewService<Request>, A: NewService,
E: From<A::Error>, E: From<A::Error>,
{ {
Self { a, e: PhantomData } Self { a, e: PhantomData }
@@ -108,17 +109,18 @@ where
} }
} }
impl<A, E, Request> NewService<Request> for FromErrNewService<A, E> impl<A, E> NewService for FromErrNewService<A, E>
where where
A: NewService<Request>, A: NewService,
E: From<A::Error>, E: From<A::Error>,
{ {
type Request = A::Request;
type Response = A::Response; type Response = A::Response;
type Error = E; type Error = E;
type Service = FromErr<A::Service, E>; type Service = FromErr<A::Service, E>;
type InitError = A::InitError; type InitError = A::InitError;
type Future = FromErrNewServiceFuture<A, E, Request>; type Future = FromErrNewServiceFuture<A, E>;
fn new_service(&self) -> Self::Future { fn new_service(&self) -> Self::Future {
FromErrNewServiceFuture { FromErrNewServiceFuture {
@@ -128,18 +130,18 @@ where
} }
} }
pub struct FromErrNewServiceFuture<A, E, Request> pub struct FromErrNewServiceFuture<A, E>
where where
A: NewService<Request>, A: NewService,
E: From<A::Error>, E: From<A::Error>,
{ {
fut: A::Future, fut: A::Future,
e: PhantomData<E>, e: PhantomData<E>,
} }
impl<A, E, Request> Future for FromErrNewServiceFuture<A, E, Request> impl<A, E> Future for FromErrNewServiceFuture<A, E>
where where
A: NewService<Request>, A: NewService,
E: From<A::Error>, E: From<A::Error>,
{ {
type Item = FromErr<A::Service, E>; type Item = FromErr<A::Service, E>;
@@ -162,7 +164,8 @@ mod tests {
use crate::{IntoNewService, NewService, Service, ServiceExt}; use crate::{IntoNewService, NewService, Service, ServiceExt};
struct Srv; struct Srv;
impl Service<()> for Srv { impl Service for Srv {
type Request = ();
type Response = (); type Response = ();
type Error = (); type Error = ();
type Future = FutureResult<(), ()>; type Future = FutureResult<(), ()>;

View File

@@ -2,27 +2,38 @@ use futures::{Future, IntoFuture, Poll};
mod and_then; mod and_then;
mod and_then_apply; mod and_then_apply;
mod and_then_apply_fn;
mod apply; mod apply;
mod blank;
mod cell; mod cell;
mod fn_service; mod fn_service;
mod fn_transform;
mod from_err; mod from_err;
mod map; mod map;
mod map_err; mod map_err;
mod map_init_err; mod map_init_err;
mod then; mod then;
mod transform;
pub use self::and_then::{AndThen, AndThenNewService}; pub use self::and_then::{AndThen, AndThenNewService};
pub use self::and_then_apply::{AndThenApply, AndThenApplyNewService}; use self::and_then_apply::{AndThenTransform, AndThenTransformNewService};
use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService};
pub use self::apply::{Apply, ApplyNewService}; pub use self::apply::{Apply, ApplyNewService};
pub use self::blank::{Blank, BlankNewService};
pub use self::fn_service::{FnNewService, FnService}; pub use self::fn_service::{FnNewService, FnService};
pub use self::fn_transform::{FnNewTransform, FnTransform};
pub use self::from_err::{FromErr, FromErrNewService}; pub use self::from_err::{FromErr, FromErrNewService};
pub use self::map::{Map, MapNewService}; pub use self::map::{Map, MapNewService};
pub use self::map_err::{MapErr, MapErrNewService}; pub use self::map_err::{MapErr, MapErrNewService};
pub use self::map_init_err::MapInitErr; pub use self::map_init_err::MapInitErr;
pub use self::then::{Then, ThenNewService}; pub use self::then::{Then, ThenNewService};
pub use self::transform::{IntoNewTransform, IntoTransform, NewTransform, Transform};
/// An asynchronous function from `Request` to a `Response`. /// An asynchronous function from `Request` to a `Response`.
pub trait Service<Request> { pub trait Service {
/// Requests handled by the service.
type Request;
/// Responses given by the service. /// Responses given by the service.
type Response; type Response;
@@ -52,26 +63,36 @@ pub trait Service<Request> {
/// ///
/// Calling `call` without calling `poll_ready` is permitted. The /// Calling `call` without calling `poll_ready` is permitted. The
/// implementation must be resilient to this fact. /// implementation must be resilient to this fact.
fn call(&mut self, req: Request) -> Self::Future; fn call(&mut self, req: Self::Request) -> Self::Future;
} }
/// An extension trait for `Service`s that provides a variety of convenient /// An extension trait for `Service`s that provides a variety of convenient
/// adapters /// adapters
pub trait ServiceExt<Request>: Service<Request> { pub trait ServiceExt: Service {
/// Apply function to specified service and use it as a next service in /// Apply tranformation to specified service and use it as a next service in
/// chain. /// chain.
fn apply<B, I, F, Out, Req>( fn apply<T, T1, B, B1>(self, transform: T1, service: B1) -> AndThenTransform<T, Self, B>
self, where
service: I, Self: Sized,
f: F, T: Transform<B, Request = Self::Response>,
) -> AndThenApply<Self, B, F, Out, Request, Req> T::Error: From<Self::Error>,
T1: IntoTransform<T, B>,
B: Service<Error = Self::Error>,
B1: IntoService<B>,
{
AndThenTransform::new(transform.into_transform(), self, service.into_service())
}
/// Apply function to specified service and use it as a next service in
/// chain.
fn apply_fn<F, B, B1, Out>(self, service: B1, f: F) -> AndThenApply<Self, B, F, Out>
where where
Self: Sized, Self: Sized,
B: Service<Req, Error = Self::Error>,
I: IntoService<B, Req>,
F: FnMut(Self::Response, &mut B) -> Out, F: FnMut(Self::Response, &mut B) -> Out,
Out: IntoFuture, Out: IntoFuture,
Out::Error: Into<Self::Error>, Out::Error: Into<Self::Error>,
B: Service<Error = Self::Error>,
B1: IntoService<B>,
{ {
AndThenApply::new(self, service, f) AndThenApply::new(self, service, f)
} }
@@ -88,8 +109,8 @@ pub trait ServiceExt<Request>: Service<Request> {
fn and_then<F, B>(self, service: F) -> AndThen<Self, B> fn and_then<F, B>(self, service: F) -> AndThen<Self, B>
where where
Self: Sized, Self: Sized,
F: IntoService<B, Self::Response>, F: IntoService<B>,
B: Service<Self::Response, Error = Self::Error>, B: Service<Request = Self::Response, Error = Self::Error>,
{ {
AndThen::new(self, service.into_service()) AndThen::new(self, service.into_service())
} }
@@ -115,7 +136,7 @@ pub trait ServiceExt<Request>: Service<Request> {
fn then<B>(self, service: B) -> Then<Self, B> fn then<B>(self, service: B) -> Then<Self, B>
where where
Self: Sized, Self: Sized,
B: Service<Result<Self::Response, Self::Error>, Error = Self::Error>, B: Service<Request = Result<Self::Response, Self::Error>, Error = Self::Error>,
{ {
Then::new(self, service) Then::new(self, service)
} }
@@ -154,7 +175,7 @@ pub trait ServiceExt<Request>: Service<Request> {
} }
} }
impl<T: ?Sized, Request> ServiceExt<Request> for T where T: Service<Request> {} impl<T: ?Sized> ServiceExt for T where T: Service {}
/// Creates new `Service` values. /// Creates new `Service` values.
/// ///
@@ -163,9 +184,10 @@ impl<T: ?Sized, Request> ServiceExt<Request> for T where T: Service<Request> {}
/// accepts new TCP streams, obtains a new `Service` value using the /// accepts new TCP streams, obtains a new `Service` value using the
/// `NewService` trait, and uses that new `Service` value to process inbound /// `NewService` trait, and uses that new `Service` value to process inbound
/// requests on that new TCP stream. /// requests on that new TCP stream.
/// pub trait NewService {
/// Request - request handled by the service /// Requests handled by the service.
pub trait NewService<Request> { type Request;
/// Responses given by the service /// Responses given by the service
type Response; type Response;
@@ -173,7 +195,11 @@ pub trait NewService<Request> {
type Error; type Error;
/// The `Service` value created by this factory /// The `Service` value created by this factory
type Service: Service<Request, Response = Self::Response, Error = Self::Error>; type Service: Service<
Request = Self::Request,
Response = Self::Response,
Error = Self::Error,
>;
/// Errors produced while building a service. /// Errors produced while building a service.
type InitError; type InitError;
@@ -186,15 +212,33 @@ pub trait NewService<Request> {
/// Apply function to specified service and use it as a next service in /// Apply function to specified service and use it as a next service in
/// chain. /// chain.
fn apply<B, I, F, Out, Req>( fn apply<T, T1, B, B1>(
self, self,
service: I, transform: T1,
f: F, service: B1,
) -> AndThenApplyNewService<Self, B, F, Out, Request, Req> ) -> AndThenTransformNewService<T, Self, B>
where where
Self: Sized, Self: Sized,
B: NewService<Req, Error = Self::Error, InitError = Self::InitError>, T: NewTransform<B::Service, Request = Self::Response, InitError = Self::InitError>,
I: IntoNewService<B, Req>, T::Error: From<Self::Error>,
T1: IntoNewTransform<T, B::Service>,
B: NewService<Error = Self::Error, InitError = Self::InitError>,
B1: IntoNewService<B>,
{
AndThenTransformNewService::new(
transform.into_new_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>
where
Self: Sized,
B: NewService<Error = Self::Error, InitError = Self::InitError>,
I: IntoNewService<B>,
F: FnMut(Self::Response, &mut B::Service) -> Out, F: FnMut(Self::Response, &mut B::Service) -> Out,
Out: IntoFuture, Out: IntoFuture,
Out::Error: Into<Self::Error>, Out::Error: Into<Self::Error>,
@@ -206,8 +250,12 @@ pub trait NewService<Request> {
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B> fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B>
where where
Self: Sized, Self: Sized,
F: IntoNewService<B, Self::Response>, F: IntoNewService<B>,
B: NewService<Self::Response, Error = Self::Error, InitError = Self::InitError>, B: NewService<
Request = Self::Response,
Error = Self::Error,
InitError = Self::InitError,
>,
{ {
AndThenNewService::new(self, new_service) AndThenNewService::new(self, new_service)
} }
@@ -235,9 +283,9 @@ pub trait NewService<Request> {
fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B> fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B>
where where
Self: Sized, Self: Sized,
F: IntoNewService<B, Result<Self::Response, Self::Error>>, F: IntoNewService<B>,
B: NewService< B: NewService<
Result<Self::Response, Self::Error>, Request = Result<Self::Response, Self::Error>,
Error = Self::Error, Error = Self::Error,
InitError = Self::InitError, InitError = Self::InitError,
>, >,
@@ -274,10 +322,11 @@ pub trait NewService<Request> {
} }
} }
impl<'a, S, Request> Service<Request> for &'a mut S impl<'a, S> Service for &'a mut S
where where
S: Service<Request> + 'a, S: Service + 'a,
{ {
type Request = S::Request;
type Response = S::Response; type Response = S::Response;
type Error = S::Error; type Error = S::Error;
type Future = S::Future; type Future = S::Future;
@@ -286,15 +335,16 @@ where
(**self).poll_ready() (**self).poll_ready()
} }
fn call(&mut self, request: Request) -> S::Future { fn call(&mut self, request: Self::Request) -> S::Future {
(**self).call(request) (**self).call(request)
} }
} }
impl<S, Request> Service<Request> for Box<S> impl<S> Service for Box<S>
where where
S: Service<Request> + ?Sized, S: Service + ?Sized,
{ {
type Request = S::Request;
type Response = S::Response; type Response = S::Response;
type Error = S::Error; type Error = S::Error;
type Future = S::Future; type Future = S::Future;
@@ -303,17 +353,18 @@ where
(**self).poll_ready() (**self).poll_ready()
} }
fn call(&mut self, request: Request) -> S::Future { fn call(&mut self, request: Self::Request) -> S::Future {
(**self).call(request) (**self).call(request)
} }
} }
impl<F, R, E, S, Request> NewService<Request> for F impl<F, R, E, S> NewService for F
where where
F: Fn() -> R, F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>, R: IntoFuture<Item = S, Error = E>,
S: Service<Request>, S: Service,
{ {
type Request = S::Request;
type Response = S::Response; type Response = S::Response;
type Error = S::Error; type Error = S::Error;
type Service = S; type Service = S;
@@ -326,35 +377,35 @@ where
} }
/// Trait for types that can be converted to a `Service` /// Trait for types that can be converted to a `Service`
pub trait IntoService<T, Request> pub trait IntoService<T>
where where
T: Service<Request>, T: Service,
{ {
/// Convert to a `Service` /// Convert to a `Service`
fn into_service(self) -> T; fn into_service(self) -> T;
} }
/// Trait for types that can be converted to a Service /// Trait for types that can be converted to a `NewService`
pub trait IntoNewService<T, Request> pub trait IntoNewService<T>
where where
T: NewService<Request>, T: NewService,
{ {
/// Convert to an `NewService` /// Convert to an `NewService`
fn into_new_service(self) -> T; fn into_new_service(self) -> T;
} }
impl<T, Request> IntoService<T, Request> for T impl<T> IntoService<T> for T
where where
T: Service<Request>, T: Service,
{ {
fn into_service(self) -> T { fn into_service(self) -> T {
self self
} }
} }
impl<T, Request> IntoNewService<T, Request> for T impl<T> IntoNewService<T> for T
where where
T: NewService<Request>, T: NewService,
{ {
fn into_new_service(self) -> T { fn into_new_service(self) -> T {
self self

View File

@@ -15,9 +15,9 @@ pub struct Map<A, F, Response> {
impl<A, F, Response> Map<A, F, Response> { impl<A, F, Response> Map<A, F, Response> {
/// Create new `Map` combinator /// Create new `Map` combinator
pub fn new<Request>(service: A, f: F) -> Self pub fn new(service: A, f: F) -> Self
where where
A: Service<Request>, A: Service,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Response,
{ {
Self { Self {
@@ -42,36 +42,37 @@ where
} }
} }
impl<A, F, Request, Response> Service<Request> for Map<A, F, Response> impl<A, F, Response> Service for Map<A, F, Response>
where where
A: Service<Request>, A: Service,
F: FnMut(A::Response) -> Response + Clone, F: FnMut(A::Response) -> Response + Clone,
{ {
type Request = A::Request;
type Response = Response; type Response = Response;
type Error = A::Error; type Error = A::Error;
type Future = MapFuture<A, F, Request, Response>; type Future = MapFuture<A, F, Response>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready() self.service.poll_ready()
} }
fn call(&mut self, req: Request) -> Self::Future { fn call(&mut self, req: A::Request) -> Self::Future {
MapFuture::new(self.service.call(req), self.f.clone()) MapFuture::new(self.service.call(req), self.f.clone())
} }
} }
pub struct MapFuture<A, F, Request, Response> pub struct MapFuture<A, F, Response>
where where
A: Service<Request>, A: Service,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Response,
{ {
f: F, f: F,
fut: A::Future, fut: A::Future,
} }
impl<A, F, Request, Response> MapFuture<A, F, Request, Response> impl<A, F, Response> MapFuture<A, F, Response>
where where
A: Service<Request>, A: Service,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Response,
{ {
fn new(fut: A::Future, f: F) -> Self { fn new(fut: A::Future, f: F) -> Self {
@@ -79,9 +80,9 @@ where
} }
} }
impl<A, F, Request, Response> Future for MapFuture<A, F, Request, Response> impl<A, F, Response> Future for MapFuture<A, F, Response>
where where
A: Service<Request>, A: Service,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Response,
{ {
type Item = Response; type Item = Response;
@@ -104,9 +105,9 @@ pub struct MapNewService<A, F, Response> {
impl<A, F, Response> MapNewService<A, F, Response> { impl<A, F, Response> MapNewService<A, F, Response> {
/// Create new `Map` new service instance /// Create new `Map` new service instance
pub fn new<Request>(a: A, f: F) -> Self pub fn new(a: A, f: F) -> Self
where where
A: NewService<Request>, A: NewService,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Response,
{ {
Self { Self {
@@ -131,35 +132,36 @@ where
} }
} }
impl<A, F, Request, Response> NewService<Request> for MapNewService<A, F, Response> impl<A, F, Response> NewService for MapNewService<A, F, Response>
where where
A: NewService<Request>, A: NewService,
F: FnMut(A::Response) -> Response + Clone, F: FnMut(A::Response) -> Response + Clone,
{ {
type Request = A::Request;
type Response = Response; type Response = Response;
type Error = A::Error; type Error = A::Error;
type Service = Map<A::Service, F, Response>; type Service = Map<A::Service, F, Response>;
type InitError = A::InitError; type InitError = A::InitError;
type Future = MapNewServiceFuture<A, F, Request, Response>; type Future = MapNewServiceFuture<A, F, Response>;
fn new_service(&self) -> Self::Future { fn new_service(&self) -> Self::Future {
MapNewServiceFuture::new(self.a.new_service(), self.f.clone()) MapNewServiceFuture::new(self.a.new_service(), self.f.clone())
} }
} }
pub struct MapNewServiceFuture<A, F, Request, Response> pub struct MapNewServiceFuture<A, F, Response>
where where
A: NewService<Request>, A: NewService,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Response,
{ {
fut: A::Future, fut: A::Future,
f: Option<F>, f: Option<F>,
} }
impl<A, F, Request, Response> MapNewServiceFuture<A, F, Request, Response> impl<A, F, Response> MapNewServiceFuture<A, F, Response>
where where
A: NewService<Request>, A: NewService,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Response,
{ {
fn new(fut: A::Future, f: F) -> Self { fn new(fut: A::Future, f: F) -> Self {
@@ -167,9 +169,9 @@ where
} }
} }
impl<A, F, Request, Response> Future for MapNewServiceFuture<A, F, Request, Response> impl<A, F, Response> Future for MapNewServiceFuture<A, F, Response>
where where
A: NewService<Request>, A: NewService,
F: FnMut(A::Response) -> Response, F: FnMut(A::Response) -> Response,
{ {
type Item = Map<A::Service, F, Response>; type Item = Map<A::Service, F, Response>;
@@ -192,7 +194,8 @@ mod tests {
use crate::{IntoNewService, Service, ServiceExt}; use crate::{IntoNewService, Service, ServiceExt};
struct Srv; struct Srv;
impl Service<()> for Srv { impl Service for Srv {
type Request = ();
type Response = (); type Response = ();
type Error = (); type Error = ();
type Future = FutureResult<(), ()>; type Future = FutureResult<(), ()>;

View File

@@ -16,9 +16,9 @@ pub struct MapErr<A, F, E> {
impl<A, F, E> MapErr<A, F, E> { impl<A, F, E> MapErr<A, F, E> {
/// Create new `MapErr` combinator /// Create new `MapErr` combinator
pub fn new<Request>(service: A, f: F) -> Self pub fn new(service: A, f: F) -> Self
where where
A: Service<Request>, A: Service,
F: Fn(A::Error) -> E, F: Fn(A::Error) -> E,
{ {
Self { Self {
@@ -43,36 +43,37 @@ where
} }
} }
impl<A, F, E, Request> Service<Request> for MapErr<A, F, E> impl<A, F, E> Service for MapErr<A, F, E>
where where
A: Service<Request>, A: Service,
F: Fn(A::Error) -> E + Clone, F: Fn(A::Error) -> E + Clone,
{ {
type Request = A::Request;
type Response = A::Response; type Response = A::Response;
type Error = E; type Error = E;
type Future = MapErrFuture<A, F, E, Request>; type Future = MapErrFuture<A, F, E>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready().map_err(&self.f) self.service.poll_ready().map_err(&self.f)
} }
fn call(&mut self, req: Request) -> Self::Future { fn call(&mut self, req: A::Request) -> Self::Future {
MapErrFuture::new(self.service.call(req), self.f.clone()) MapErrFuture::new(self.service.call(req), self.f.clone())
} }
} }
pub struct MapErrFuture<A, F, E, Request> pub struct MapErrFuture<A, F, E>
where where
A: Service<Request>, A: Service,
F: Fn(A::Error) -> E, F: Fn(A::Error) -> E,
{ {
f: F, f: F,
fut: A::Future, fut: A::Future,
} }
impl<A, F, E, Request> MapErrFuture<A, F, E, Request> impl<A, F, E> MapErrFuture<A, F, E>
where where
A: Service<Request>, A: Service,
F: Fn(A::Error) -> E, F: Fn(A::Error) -> E,
{ {
fn new(fut: A::Future, f: F) -> Self { fn new(fut: A::Future, f: F) -> Self {
@@ -80,9 +81,9 @@ where
} }
} }
impl<A, F, E, Request> Future for MapErrFuture<A, F, E, Request> impl<A, F, E> Future for MapErrFuture<A, F, E>
where where
A: Service<Request>, A: Service,
F: Fn(A::Error) -> E, F: Fn(A::Error) -> E,
{ {
type Item = A::Response; type Item = A::Response;
@@ -105,9 +106,9 @@ pub struct MapErrNewService<A, F, E> {
impl<A, F, E> MapErrNewService<A, F, E> { impl<A, F, E> MapErrNewService<A, F, E> {
/// Create new `MapErr` new service instance /// Create new `MapErr` new service instance
pub fn new<Request>(a: A, f: F) -> Self pub fn new(a: A, f: F) -> Self
where where
A: NewService<Request>, A: NewService,
F: Fn(A::Error) -> E, F: Fn(A::Error) -> E,
{ {
Self { Self {
@@ -132,35 +133,36 @@ where
} }
} }
impl<A, F, E, Request> NewService<Request> for MapErrNewService<A, F, E> impl<A, F, E> NewService for MapErrNewService<A, F, E>
where where
A: NewService<Request>, A: NewService,
F: Fn(A::Error) -> E + Clone, F: Fn(A::Error) -> E + Clone,
{ {
type Request = A::Request;
type Response = A::Response; type Response = A::Response;
type Error = E; type Error = E;
type Service = MapErr<A::Service, F, E>; type Service = MapErr<A::Service, F, E>;
type InitError = A::InitError; type InitError = A::InitError;
type Future = MapErrNewServiceFuture<A, F, E, Request>; type Future = MapErrNewServiceFuture<A, F, E>;
fn new_service(&self) -> Self::Future { fn new_service(&self) -> Self::Future {
MapErrNewServiceFuture::new(self.a.new_service(), self.f.clone()) MapErrNewServiceFuture::new(self.a.new_service(), self.f.clone())
} }
} }
pub struct MapErrNewServiceFuture<A, F, E, Request> pub struct MapErrNewServiceFuture<A, F, E>
where where
A: NewService<Request>, A: NewService,
F: Fn(A::Error) -> E, F: Fn(A::Error) -> E,
{ {
fut: A::Future, fut: A::Future,
f: F, f: F,
} }
impl<A, F, E, Request> MapErrNewServiceFuture<A, F, E, Request> impl<A, F, E> MapErrNewServiceFuture<A, F, E>
where where
A: NewService<Request>, A: NewService,
F: Fn(A::Error) -> E, F: Fn(A::Error) -> E,
{ {
fn new(fut: A::Future, f: F) -> Self { fn new(fut: A::Future, f: F) -> Self {
@@ -168,9 +170,9 @@ where
} }
} }
impl<A, F, E, Request> Future for MapErrNewServiceFuture<A, F, E, Request> impl<A, F, E> Future for MapErrNewServiceFuture<A, F, E>
where where
A: NewService<Request>, A: NewService,
F: Fn(A::Error) -> E + Clone, F: Fn(A::Error) -> E + Clone,
{ {
type Item = MapErr<A::Service, F, E>; type Item = MapErr<A::Service, F, E>;
@@ -194,7 +196,8 @@ mod tests {
struct Srv; struct Srv;
impl Service<()> for Srv { impl Service for Srv {
type Request = ();
type Response = (); type Response = ();
type Error = (); type Error = ();
type Future = FutureResult<(), ()>; type Future = FutureResult<(), ()>;

View File

@@ -13,9 +13,9 @@ pub struct MapInitErr<A, F, E> {
impl<A, F, E> MapInitErr<A, F, E> { impl<A, F, E> MapInitErr<A, F, E> {
/// Create new `MapInitErr` combinator /// Create new `MapInitErr` combinator
pub fn new<Request>(a: A, f: F) -> Self pub fn new(a: A, f: F) -> Self
where where
A: NewService<Request>, A: NewService,
F: Fn(A::InitError) -> E, F: Fn(A::InitError) -> E,
{ {
Self { Self {
@@ -40,35 +40,36 @@ where
} }
} }
impl<A, F, E, Request> NewService<Request> for MapInitErr<A, F, E> impl<A, F, E> NewService for MapInitErr<A, F, E>
where where
A: NewService<Request>, A: NewService,
F: Fn(A::InitError) -> E + Clone, F: Fn(A::InitError) -> E + Clone,
{ {
type Request = A::Request;
type Response = A::Response; type Response = A::Response;
type Error = A::Error; type Error = A::Error;
type Service = A::Service; type Service = A::Service;
type InitError = E; type InitError = E;
type Future = MapInitErrFuture<A, F, E, Request>; type Future = MapInitErrFuture<A, F, E>;
fn new_service(&self) -> Self::Future { fn new_service(&self) -> Self::Future {
MapInitErrFuture::new(self.a.new_service(), self.f.clone()) MapInitErrFuture::new(self.a.new_service(), self.f.clone())
} }
} }
pub struct MapInitErrFuture<A, F, E, Request> pub struct MapInitErrFuture<A, F, E>
where where
A: NewService<Request>, A: NewService,
F: Fn(A::InitError) -> E, F: Fn(A::InitError) -> E,
{ {
f: F, f: F,
fut: A::Future, fut: A::Future,
} }
impl<A, F, E, Request> MapInitErrFuture<A, F, E, Request> impl<A, F, E> MapInitErrFuture<A, F, E>
where where
A: NewService<Request>, A: NewService,
F: Fn(A::InitError) -> E, F: Fn(A::InitError) -> E,
{ {
fn new(fut: A::Future, f: F) -> Self { fn new(fut: A::Future, f: F) -> Self {
@@ -76,9 +77,9 @@ where
} }
} }
impl<A, F, E, Request> Future for MapInitErrFuture<A, F, E, Request> impl<A, F, E> Future for MapInitErrFuture<A, F, E>
where where
A: NewService<Request>, A: NewService,
F: Fn(A::InitError) -> E, F: Fn(A::InitError) -> E,
{ {
type Item = A::Service; type Item = A::Service;

View File

@@ -14,10 +14,10 @@ pub struct Then<A, B> {
impl<A, B> Then<A, B> { impl<A, B> Then<A, B> {
/// Create new `Then` combinator /// Create new `Then` combinator
pub fn new<Request>(a: A, b: B) -> Then<A, B> pub fn new(a: A, b: B) -> Then<A, B>
where where
A: Service<Request>, A: Service,
B: Service<Result<A::Response, A::Error>, Error = A::Error>, B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
{ {
Then { a, b: Cell::new(b) } Then { a, b: Cell::new(b) }
} }
@@ -35,39 +35,40 @@ where
} }
} }
impl<A, B, Request> Service<Request> for Then<A, B> impl<A, B> Service for Then<A, B>
where where
A: Service<Request>, A: Service,
B: Service<Result<A::Response, A::Error>, Error = A::Error>, B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
{ {
type Request = A::Request;
type Response = B::Response; type Response = B::Response;
type Error = B::Error; type Error = B::Error;
type Future = ThenFuture<A, B, Request>; type Future = ThenFuture<A, B>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
try_ready!(self.a.poll_ready()); try_ready!(self.a.poll_ready());
self.b.get_mut().poll_ready() self.b.get_mut().poll_ready()
} }
fn call(&mut self, req: Request) -> Self::Future { fn call(&mut self, req: A::Request) -> Self::Future {
ThenFuture::new(self.a.call(req), self.b.clone()) ThenFuture::new(self.a.call(req), self.b.clone())
} }
} }
pub struct ThenFuture<A, B, Request> pub struct ThenFuture<A, B>
where where
A: Service<Request>, A: Service,
B: Service<Result<A::Response, A::Error>>, B: Service<Request = Result<A::Response, A::Error>>,
{ {
b: Cell<B>, b: Cell<B>,
fut_b: Option<B::Future>, fut_b: Option<B::Future>,
fut_a: Option<A::Future>, fut_a: Option<A::Future>,
} }
impl<A, B, Request> ThenFuture<A, B, Request> impl<A, B> ThenFuture<A, B>
where where
A: Service<Request>, A: Service,
B: Service<Result<A::Response, A::Error>>, B: Service<Request = Result<A::Response, A::Error>>,
{ {
fn new(a: A::Future, b: Cell<B>) -> Self { fn new(a: A::Future, b: Cell<B>) -> Self {
ThenFuture { ThenFuture {
@@ -78,10 +79,10 @@ where
} }
} }
impl<A, B, Request> Future for ThenFuture<A, B, Request> impl<A, B> Future for ThenFuture<A, B>
where where
A: Service<Request>, A: Service,
B: Service<Result<A::Response, A::Error>>, B: Service<Request = Result<A::Response, A::Error>>,
{ {
type Item = B::Response; type Item = B::Response;
type Error = B::Error; type Error = B::Error;
@@ -115,15 +116,15 @@ pub struct ThenNewService<A, B> {
impl<A, B> ThenNewService<A, B> { impl<A, B> ThenNewService<A, B> {
/// Create new `AndThen` combinator /// Create new `AndThen` combinator
pub fn new<F, Request>(a: A, f: F) -> Self pub fn new<F>(a: A, f: F) -> Self
where where
A: NewService<Request>, A: NewService,
B: NewService< B: NewService<
Result<A::Response, A::Error>, Request = Result<A::Response, A::Error>,
Error = A::Error, Error = A::Error,
InitError = A::InitError, InitError = A::InitError,
>, >,
F: IntoNewService<B, Result<A::Response, A::Error>>, F: IntoNewService<B>,
{ {
Self { Self {
a, a,
@@ -132,17 +133,22 @@ impl<A, B> ThenNewService<A, B> {
} }
} }
impl<A, B, Request> NewService<Request> for ThenNewService<A, B> impl<A, B> NewService for ThenNewService<A, B>
where where
A: NewService<Request>, A: NewService,
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>, B: NewService<
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
>,
{ {
type Request = A::Request;
type Response = B::Response; type Response = B::Response;
type Error = A::Error; type Error = A::Error;
type Service = Then<A::Service, B::Service>; type Service = Then<A::Service, B::Service>;
type InitError = A::InitError; type InitError = A::InitError;
type Future = ThenNewServiceFuture<A, B, Request>; type Future = ThenNewServiceFuture<A, B>;
fn new_service(&self) -> Self::Future { fn new_service(&self) -> Self::Future {
ThenNewServiceFuture::new(self.a.new_service(), self.b.new_service()) ThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
@@ -162,10 +168,14 @@ where
} }
} }
pub struct ThenNewServiceFuture<A, B, Request> pub struct ThenNewServiceFuture<A, B>
where where
A: NewService<Request>, A: NewService,
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>, B: NewService<
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
>,
{ {
fut_b: B::Future, fut_b: B::Future,
fut_a: A::Future, fut_a: A::Future,
@@ -173,10 +183,14 @@ where
b: Option<B::Service>, b: Option<B::Service>,
} }
impl<A, B, Request> ThenNewServiceFuture<A, B, Request> impl<A, B> ThenNewServiceFuture<A, B>
where where
A: NewService<Request>, A: NewService,
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>, B: NewService<
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
>,
{ {
fn new(fut_a: A::Future, fut_b: B::Future) -> Self { fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
ThenNewServiceFuture { ThenNewServiceFuture {
@@ -188,10 +202,14 @@ where
} }
} }
impl<A, B, Request> Future for ThenNewServiceFuture<A, B, Request> impl<A, B> Future for ThenNewServiceFuture<A, B>
where where
A: NewService<Request>, A: NewService,
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>, B: NewService<
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
>,
{ {
type Item = Then<A::Service, B::Service>; type Item = Then<A::Service, B::Service>;
type Error = A::InitError; type Error = A::InitError;
@@ -231,7 +249,8 @@ mod tests {
#[derive(Clone)] #[derive(Clone)]
struct Srv1(Rc<Cell<usize>>); struct Srv1(Rc<Cell<usize>>);
impl Service<Result<&'static str, &'static str>> for Srv1 { impl Service for Srv1 {
type Request = Result<&'static str, &'static str>;
type Response = &'static str; type Response = &'static str;
type Error = (); type Error = ();
type Future = FutureResult<Self::Response, Self::Error>; type Future = FutureResult<Self::Response, Self::Error>;
@@ -251,7 +270,8 @@ mod tests {
struct Srv2(Rc<Cell<usize>>); struct Srv2(Rc<Cell<usize>>);
impl Service<Result<&'static str, ()>> for Srv2 { impl Service for Srv2 {
type Request = Result<&'static str, ()>;
type Response = (&'static str, &'static str); type Response = (&'static str, &'static str);
type Error = (); type Error = ();
type Future = FutureResult<Self::Response, ()>; type Future = FutureResult<Self::Response, ()>;

View File

@@ -0,0 +1,341 @@
use std::marker::PhantomData;
use futures::{Async, Future, Poll};
use super::Service;
/// An asynchronous function for transforming service call result.
pub trait Transform<Service> {
/// Requests handled by the service.
type Request;
/// Responses given by the service.
type Response;
/// Errors produced by the service.
type Error;
/// The future response value.
type Future: Future<Item = Self::Response, Error = Self::Error>;
/// Returns `Ready` when the service is able to process requests.
///
/// This method is similar to `Service::poll_ready` method.
fn poll_ready(&mut self) -> Poll<(), Self::Error>;
/// Process the request and apply it to provided service,
/// return the response asynchronously.
fn call(&mut self, request: Self::Request, service: &mut Service) -> Self::Future;
/// Map this transform's error to a different error, returning a new transform.
///
/// This function is similar to the `Result::map_err` where it will change
/// the error type of the underlying transform. This is useful for example to
/// ensure that services and transforms have the same error type.
///
/// Note that this function consumes the receiving transform and returns a
/// wrapped version of it.
fn map_err<F, E>(self, f: F) -> TransformMapErr<Self, Service, F, E>
where
Self: Sized,
F: Fn(Self::Error) -> E,
{
TransformMapErr::new(self, f)
}
}
/// `Transform` service factory
pub trait NewTransform<Service> {
/// Requests handled by the service.
type Request;
/// Responses given by the service.
type Response;
/// Errors produced by the service.
type Error;
/// The `TransformService` value created by this factory
type Transform: Transform<
Service,
Request = Self::Request,
Response = Self::Response,
Error = Self::Error,
>;
/// Errors produced while building a service.
type InitError;
/// The future response value.
type Future: Future<Item = Self::Transform, Error = Self::InitError>;
/// Create and return a new service value asynchronously.
fn new_transform(&self) -> Self::Future;
/// Map this transforms's output to a different type, returning a new transform
/// of the resulting type.
fn map_err<F, E>(self, f: F) -> TransformMapErrNewTransform<Self, Service, F, E>
where
Self: Sized,
F: Fn(Self::Error) -> E,
{
TransformMapErrNewTransform::new(self, f)
}
}
impl<'a, T, S> Transform<S> for &'a mut T
where
T: Transform<S> + 'a,
S: Service<Error = T::Error>,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type Future = T::Future;
fn poll_ready(&mut self) -> Poll<(), T::Error> {
(**self).poll_ready()
}
fn call(&mut self, request: Self::Request, service: &mut S) -> T::Future {
(**self).call(request, service)
}
}
impl<T, S> Transform<S> for Box<T>
where
T: Transform<S> + ?Sized,
S: Service<Error = T::Error>,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type Future = T::Future;
fn poll_ready(&mut self) -> Poll<(), S::Error> {
(**self).poll_ready()
}
fn call(&mut self, request: Self::Request, service: &mut S) -> T::Future {
(**self).call(request, service)
}
}
/// Trait for types that can be converted to a `TransformService`
pub trait IntoTransform<T, S>
where
T: Transform<S>,
{
/// Convert to a `TransformService`
fn into_transform(self) -> T;
}
/// Trait for types that can be converted to a TransfromNewService
pub trait IntoNewTransform<T, S>
where
T: NewTransform<S>,
{
/// Convert to an `TranformNewService`
fn into_new_transform(self) -> T;
}
impl<T, S> IntoTransform<T, S> for T
where
T: Transform<S>,
{
fn into_transform(self) -> T {
self
}
}
impl<T, S> IntoNewTransform<T, S> for T
where
T: NewTransform<S>,
{
fn into_new_transform(self) -> T {
self
}
}
/// Service for the `map_err` combinator, changing the type of a transform's
/// error.
///
/// This is created by the `Transform::map_err` method.
pub struct TransformMapErr<T, S, F, E> {
transform: T,
f: F,
_t: PhantomData<(S, E)>,
}
impl<T, S, F, E> TransformMapErr<T, S, F, E> {
/// Create new `MapErr` combinator
pub fn new(transform: T, f: F) -> Self
where
T: Transform<S>,
F: Fn(T::Error) -> E,
{
Self {
transform,
f,
_t: PhantomData,
}
}
}
impl<T, S, F, E> Clone for TransformMapErr<T, S, F, E>
where
T: Clone,
F: Clone,
{
fn clone(&self) -> Self {
TransformMapErr {
transform: self.transform.clone(),
f: self.f.clone(),
_t: PhantomData,
}
}
}
impl<T, S, F, E> Transform<S> for TransformMapErr<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::Error) -> E + Clone,
{
type Request = T::Request;
type Response = T::Response;
type Error = E;
type Future = TransformMapErrFuture<T, S, F, E>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.transform.poll_ready().map_err(&self.f)
}
fn call(&mut self, req: T::Request, service: &mut S) -> Self::Future {
TransformMapErrFuture::new(self.transform.call(req, service), self.f.clone())
}
}
pub struct TransformMapErrFuture<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::Error) -> E,
{
f: F,
fut: T::Future,
}
impl<T, S, F, E> TransformMapErrFuture<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::Error) -> E,
{
fn new(fut: T::Future, f: F) -> Self {
TransformMapErrFuture { f, fut }
}
}
impl<T, S, F, E> Future for TransformMapErrFuture<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::Error) -> E,
{
type Item = T::Response;
type Error = E;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.fut.poll().map_err(&self.f)
}
}
/// NewTransform for the `map_err` combinator, changing the type of a new
/// transform's error.
///
/// This is created by the `NewTransform::map_err` method.
pub struct TransformMapErrNewTransform<T, S, F, E> {
t: T,
f: F,
e: PhantomData<(S, E)>,
}
impl<T, S, F, E> TransformMapErrNewTransform<T, S, F, E> {
/// Create new `MapErr` new service instance
pub fn new(t: T, f: F) -> Self
where
T: NewTransform<S>,
F: Fn(T::Error) -> E,
{
Self {
t,
f,
e: PhantomData,
}
}
}
impl<T, S, F, E> Clone for TransformMapErrNewTransform<T, S, F, E>
where
T: Clone,
F: Clone,
{
fn clone(&self) -> Self {
Self {
t: self.t.clone(),
f: self.f.clone(),
e: PhantomData,
}
}
}
impl<T, S, F, E> NewTransform<S> for TransformMapErrNewTransform<T, S, F, E>
where
T: NewTransform<S>,
F: Fn(T::Error) -> E + Clone,
{
type Request = T::Request;
type Response = T::Response;
type Error = E;
type Transform = TransformMapErr<T::Transform, S, F, E>;
type InitError = T::InitError;
type Future = TransformMapErrNewTransformFuture<T, S, F, E>;
fn new_transform(&self) -> Self::Future {
TransformMapErrNewTransformFuture::new(self.t.new_transform(), self.f.clone())
}
}
pub struct TransformMapErrNewTransformFuture<T, S, F, E>
where
T: NewTransform<S>,
F: Fn(T::Error) -> E,
{
fut: T::Future,
f: F,
}
impl<T, S, F, E> TransformMapErrNewTransformFuture<T, S, F, E>
where
T: NewTransform<S>,
F: Fn(T::Error) -> E,
{
fn new(fut: T::Future, f: F) -> Self {
TransformMapErrNewTransformFuture { f, fut }
}
}
impl<T, S, F, E> Future for TransformMapErrNewTransformFuture<T, S, F, E>
where
T: NewTransform<S>,
F: Fn(T::Error) -> E + Clone,
{
type Item = TransformMapErr<T::Transform, S, F, E>;
type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Async::Ready(tr) = self.fut.poll()? {
Ok(Async::Ready(TransformMapErr::new(tr, self.f.clone())))
} else {
Ok(Async::NotReady)
}
}
}

View File

@@ -34,7 +34,7 @@ rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
[dependencies] [dependencies]
actix-rt = "0.1.0" actix-rt = "0.1.0"
actix-server = "0.1.0" actix-server = "0.2.0"
log = "0.4" log = "0.4"
@@ -51,7 +51,7 @@ native-tls = { version="0.2", optional = true }
openssl = { version="0.10", optional = true } openssl = { version="0.10", optional = true }
#rustls #rustls
rustls = { version = "^0.14", optional = true } rustls = { version = "^0.15", optional = true }
tokio-rustls = { version = "^0.8", optional = true } tokio-rustls = { version = "^0.9", optional = true }
webpki = { version = "0.18", optional = true } webpki = { version = "0.19", optional = true }
webpki-roots = { version = "0.15", optional = true } webpki-roots = { version = "0.16", optional = true }

View File

@@ -1,13 +1,24 @@
# Changes # Changes
## [0.1.1] - 2018-xx-xx ## [0.2.1] - 2019-02-xx
### Changed
* Convert `Timeout` and `InFlight` services to a transforms
## [0.2.0] - 2019-02-01
* Fix framed transport error handling * Fix framed transport error handling
* Added Clone impl for Either service * Added Clone impl for Either service
* Added Clone impl for Timeout service factory
* Added Service and NewService for Stream dispatcher * Added Service and NewService for Stream dispatcher
* Switch to actix-service 0.2
## [0.1.0] - 2018-12-09 ## [0.1.0] - 2018-12-09

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "actix-utils" name = "actix-utils"
version = "0.1.1" version = "0.2.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"] authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix utils - various actix net related services" description = "Actix utils - various actix net related services"
keywords = ["network", "framework", "async", "futures"] keywords = ["network", "framework", "async", "futures"]
@@ -18,10 +18,16 @@ name = "actix_utils"
path = "src/lib.rs" path = "src/lib.rs"
[dependencies] [dependencies]
actix-service = "0.1.2" actix-service = "0.2.0"
actix-codec = "0.1.0" actix-codec = "0.1.0"
actix-rt = "0.1.0"
bytes = "0.4" bytes = "0.4"
futures = "0.1" futures = "0.1"
tokio-timer = "0.2.8" tokio-timer = "0.2.8"
log = "0.4" tokio-current-thread = "0.1"
log = "0.4"
[dev-dependencies]
actix-rt = "0.1"
[patch.crates-io]
actix-service = { git = "https://github.com/actix/actix-net.git" }

View File

@@ -1,17 +1,11 @@
//! Custom cell impl //! Custom cell impl
#[cfg(feature = "cell")]
use std::cell::UnsafeCell; use std::cell::UnsafeCell;
#[cfg(not(feature = "cell"))]
use std::cell::{Ref, RefCell, RefMut};
use std::fmt; use std::fmt;
use std::rc::Rc; use std::rc::Rc;
pub(crate) struct Cell<T> { pub(crate) struct Cell<T> {
#[cfg(feature = "cell")]
inner: Rc<UnsafeCell<T>>, inner: Rc<UnsafeCell<T>>,
#[cfg(not(feature = "cell"))]
inner: Rc<RefCell<T>>,
} }
impl<T> Clone for Cell<T> { impl<T> Clone for Cell<T> {
@@ -28,7 +22,6 @@ impl<T: fmt::Debug> fmt::Debug for Cell<T> {
} }
} }
#[cfg(feature = "cell")]
impl<T> Cell<T> { impl<T> Cell<T> {
pub fn new(inner: T) -> Self { pub fn new(inner: T) -> Self {
Self { Self {
@@ -36,28 +29,11 @@ impl<T> Cell<T> {
} }
} }
pub fn borrow(&self) -> &T { pub fn get_ref(&self) -> &T {
unsafe { &*self.inner.as_ref().get() } unsafe { &*self.inner.as_ref().get() }
} }
pub fn borrow_mut(&self) -> &mut T { pub fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.inner.as_ref().get() } unsafe { &mut *self.inner.as_ref().get() }
} }
} }
#[cfg(not(feature = "cell"))]
impl<T> Cell<T> {
pub fn new(inner: T) -> Self {
Self {
inner: Rc::new(RefCell::new(inner)),
}
}
pub fn borrow(&self) -> Ref<T> {
self.inner.borrow()
}
pub fn borrow_mut(&self) -> RefMut<T> {
self.inner.borrow_mut()
}
}

View File

@@ -13,9 +13,9 @@ pub struct CloneableService<T: 'static> {
} }
impl<T: 'static> CloneableService<T> { impl<T: 'static> CloneableService<T> {
pub fn new<Request>(service: T) -> Self pub fn new(service: T) -> Self
where where
T: Service<Request>, T: Service,
{ {
Self { Self {
service: Cell::new(service), service: Cell::new(service),
@@ -33,19 +33,20 @@ impl<T: 'static> Clone for CloneableService<T> {
} }
} }
impl<T: 'static, Request> Service<Request> for CloneableService<T> impl<T> Service for CloneableService<T>
where where
T: Service<Request>, T: Service + 'static,
{ {
type Request = T::Request;
type Response = T::Response; type Response = T::Response;
type Error = T::Error; type Error = T::Error;
type Future = T::Future; type Future = T::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.borrow_mut().poll_ready() self.service.get_mut().poll_ready()
} }
fn call(&mut self, req: Request) -> Self::Future { fn call(&mut self, req: T::Request) -> Self::Future {
self.service.borrow_mut().call(req) self.service.get_mut().call(req)
} }
} }

View File

@@ -21,11 +21,12 @@ impl<A: Clone, B: Clone> Clone for EitherService<A, B> {
} }
} }
impl<A, B, Request> Service<Request> for EitherService<A, B> impl<A, B> Service for EitherService<A, B>
where where
A: Service<Request>, A: Service,
B: Service<Request, Response = A::Response, Error = A::Error>, B: Service<Request = A::Request, Response = A::Response, Error = A::Error>,
{ {
type Request = A::Request;
type Response = A::Response; type Response = A::Response;
type Error = A::Error; type Error = A::Error;
type Future = future::Either<A::Future, B::Future>; type Future = future::Either<A::Future, B::Future>;
@@ -37,7 +38,7 @@ where
} }
} }
fn call(&mut self, req: Request) -> Self::Future { fn call(&mut self, req: A::Request) -> Self::Future {
match self { match self {
EitherService::A(ref mut inner) => future::Either::A(inner.call(req)), EitherService::A(ref mut inner) => future::Either::A(inner.call(req)),
EitherService::B(ref mut inner) => future::Either::B(inner.call(req)), EitherService::B(ref mut inner) => future::Either::B(inner.call(req)),
@@ -52,11 +53,11 @@ pub enum Either<A, B> {
} }
impl<A, B> Either<A, B> { impl<A, B> Either<A, B> {
pub fn new_a<Request>(srv: A) -> Self pub fn new_a(srv: A) -> Self
where where
A: NewService<Request>, A: NewService,
B: NewService< B: NewService<
Request, Request = A::Request,
Response = A::Response, Response = A::Response,
Error = A::Error, Error = A::Error,
InitError = A::InitError, InitError = A::InitError,
@@ -65,11 +66,11 @@ impl<A, B> Either<A, B> {
Either::A(srv) Either::A(srv)
} }
pub fn new_b<Request>(srv: B) -> Self pub fn new_b(srv: B) -> Self
where where
A: NewService<Request>, A: NewService,
B: NewService< B: NewService<
Request, Request = A::Request,
Response = A::Response, Response = A::Response,
Error = A::Error, Error = A::Error,
InitError = A::InitError, InitError = A::InitError,
@@ -79,16 +80,22 @@ impl<A, B> Either<A, B> {
} }
} }
impl<A, B, Request> NewService<Request> for Either<A, B> impl<A, B> NewService for Either<A, B>
where where
A: NewService<Request>, A: NewService,
B: NewService<Request, Response = A::Response, Error = A::Error, InitError = A::InitError>, B: NewService<
Request = A::Request,
Response = A::Response,
Error = A::Error,
InitError = A::InitError,
>,
{ {
type Request = A::Request;
type Response = A::Response; type Response = A::Response;
type Error = A::Error; type Error = A::Error;
type InitError = A::InitError; type InitError = A::InitError;
type Service = EitherService<A::Service, B::Service>; type Service = EitherService<A::Service, B::Service>;
type Future = EitherNewService<A, B, Request>; type Future = EitherNewService<A, B>;
fn new_service(&self) -> Self::Future { fn new_service(&self) -> Self::Future {
match self { match self {
@@ -108,15 +115,20 @@ impl<A: Clone, B: Clone> Clone for Either<A, B> {
} }
#[doc(hidden)] #[doc(hidden)]
pub enum EitherNewService<A: NewService<R>, B: NewService<R>, R> { pub enum EitherNewService<A: NewService, B: NewService> {
A(A::Future), A(A::Future),
B(B::Future), B(B::Future),
} }
impl<A, B, Request> Future for EitherNewService<A, B, Request> impl<A, B> Future for EitherNewService<A, B>
where where
A: NewService<Request>, A: NewService,
B: NewService<Request, Response = A::Response, Error = A::Error, InitError = A::InitError>, B: NewService<
Request = A::Request,
Response = A::Response,
Error = A::Error,
InitError = A::InitError,
>,
{ {
type Item = EitherService<A::Service, B::Service>; type Item = EitherService<A::Service, B::Service>;
type Error = A::InitError; type Error = A::InitError;

View File

@@ -1,15 +1,17 @@
//! Framed dispatcher service and related utilities //! Framed dispatcher service and related utilities
use std::collections::VecDeque;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::mem; use std::mem;
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed}; use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_rt::Arbiter;
use actix_service::{IntoNewService, IntoService, NewService, Service}; use actix_service::{IntoNewService, IntoService, NewService, Service};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::unsync::mpsc; use futures::task::AtomicTask;
use futures::{Async, Future, Poll, Sink, Stream}; use futures::{Async, Future, Poll, Sink, Stream};
use log::debug; use log::debug;
use crate::cell::Cell;
type Request<U> = <U as Decoder>::Item; type Request<U> = <U as Decoder>::Item;
type Response<U> = <U as Encoder>::Item; type Response<U> = <U as Encoder>::Item;
@@ -20,15 +22,15 @@ pub struct FramedNewService<S, T, U> {
impl<S, T, U> FramedNewService<S, T, U> impl<S, T, U> FramedNewService<S, T, U>
where where
S: NewService<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
U: Decoder + Encoder, U: Decoder + Encoder,
S: NewService<Request<U>, Response = Response<U>>,
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
<U as Encoder>::Item: 'static, <U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static, <U as Encoder>::Error: std::fmt::Debug,
{ {
pub fn new<F1: IntoNewService<S, Request<U>>>(factory: F1) -> Self { pub fn new<F1: IntoNewService<S>>(factory: F1) -> Self {
Self { Self {
factory: factory.into_new_service(), factory: factory.into_new_service(),
_t: PhantomData, _t: PhantomData,
@@ -48,16 +50,17 @@ where
} }
} }
impl<S, T, U> NewService<Framed<T, U>> for FramedNewService<S, T, U> impl<S, T, U> NewService for FramedNewService<S, T, U>
where where
S: NewService<Request = Request<U>, Response = Response<U>> + Clone,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
U: Decoder + Encoder, U: Decoder + Encoder,
S: NewService<Request<U>, Response = Response<U>> + Clone,
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
<U as Encoder>::Item: 'static, <U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static, <U as Encoder>::Error: std::fmt::Debug,
{ {
type Request = Framed<T, U>;
type Response = FramedTransport<S::Service, T, U>; type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError; type Error = S::InitError;
type InitError = S::InitError; type InitError = S::InitError;
@@ -89,16 +92,17 @@ where
} }
} }
impl<S, T, U> Service<Framed<T, U>> for FramedService<S, T, U> impl<S, T, U> Service for FramedService<S, T, U>
where where
S: NewService<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
U: Decoder + Encoder, U: Decoder + Encoder,
S: NewService<Request<U>, Response = Response<U>>,
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
<U as Encoder>::Item: 'static, <U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static, <U as Encoder>::Error: std::fmt::Debug,
{ {
type Request = Framed<T, U>;
type Response = FramedTransport<S::Service, T, U>; type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError; type Error = S::InitError;
type Future = FramedServiceResponseFuture<S, T, U>; type Future = FramedServiceResponseFuture<S, T, U>;
@@ -119,13 +123,13 @@ where
#[doc(hidden)] #[doc(hidden)]
pub struct FramedServiceResponseFuture<S, T, U> pub struct FramedServiceResponseFuture<S, T, U>
where where
S: NewService<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
U: Decoder + Encoder, U: Decoder + Encoder,
S: NewService<Request<U>, Response = Response<U>>,
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
<U as Encoder>::Item: 'static, <U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static, <U as Encoder>::Error: std::fmt::Debug,
{ {
fut: S::Future, fut: S::Future,
framed: Option<Framed<T, U>>, framed: Option<Framed<T, U>>,
@@ -133,13 +137,13 @@ where
impl<S, T, U> Future for FramedServiceResponseFuture<S, T, U> impl<S, T, U> Future for FramedServiceResponseFuture<S, T, U>
where where
S: NewService<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
U: Decoder + Encoder, U: Decoder + Encoder,
S: NewService<Request<U>, Response = Response<U>>,
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
<U as Encoder>::Item: 'static, <U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static, <U as Encoder>::Error: std::fmt::Debug,
{ {
type Item = FramedTransport<S::Service, T, U>; type Item = FramedTransport<S::Service, T, U>;
type Error = S::InitError; type Error = S::InitError;
@@ -172,43 +176,143 @@ impl<E, U: Encoder + Decoder> From<E> for FramedTransportError<E, U> {
/// and pass then to the service. /// and pass then to the service.
pub struct FramedTransport<S, T, U> pub struct FramedTransport<S, T, U>
where where
S: Service<Request<U>, Response = Response<U>>, S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
U: Encoder + Decoder, U: Encoder + Decoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{ {
service: S, service: S,
state: TransportState<S, U>, state: TransportState<S, U>,
framed: Framed<T, U>, framed: Framed<T, U>,
request: Option<Request<U>>, inner: Cell<FramedTransportInner<<U as Encoder>::Item, S::Error>>,
write_rx: mpsc::Receiver<Result<Response<U>, S::Error>>,
write_tx: mpsc::Sender<Result<Response<U>, S::Error>>,
} }
enum TransportState<S: Service<Request<U>>, U: Encoder + Decoder> { enum TransportState<S: Service, U: Encoder + Decoder> {
Processing, Processing,
Error(FramedTransportError<S::Error, U>), Error(FramedTransportError<S::Error, U>),
FramedError(FramedTransportError<S::Error, U>), FramedError(FramedTransportError<S::Error, U>),
Stopping, Stopping,
} }
struct FramedTransportInner<I, E> {
buf: VecDeque<Result<I, E>>,
task: AtomicTask,
}
impl<S, T, U> FramedTransport<S, T, U> impl<S, T, U> FramedTransport<S, T, U>
where where
S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
U: Decoder + Encoder, U: Decoder + Encoder,
S: Service<Request<U>, Response = Response<U>>, <U as Encoder>::Item: 'static,
S::Future: 'static, <U as Encoder>::Error: std::fmt::Debug,
S::Error: 'static,
<U as Encoder>::Error: 'static,
{ {
pub fn new<F: IntoService<S, Request<U>>>(framed: Framed<T, U>, service: F) -> Self { fn poll_read(&mut self) -> bool {
let (write_tx, write_rx) = mpsc::channel(16); loop {
match self.service.poll_ready() {
Ok(Async::Ready(_)) => loop {
let item = match self.framed.poll() {
Ok(Async::Ready(Some(el))) => el,
Err(err) => {
self.state =
TransportState::FramedError(FramedTransportError::Decoder(err));
return true;
}
Ok(Async::NotReady) => return false,
Ok(Async::Ready(None)) => {
self.state = TransportState::Stopping;
return true;
}
};
let mut cell = self.inner.clone();
cell.get_mut().task.register();
tokio_current_thread::spawn(self.service.call(item).then(move |item| {
let inner = cell.get_mut();
inner.buf.push_back(item);
inner.task.notify();
Ok(())
}));
},
Ok(Async::NotReady) => return false,
Err(err) => {
self.state = TransportState::Error(FramedTransportError::Service(err));
return true;
}
}
}
}
/// write to framed object
fn poll_write(&mut self) -> bool {
let inner = self.inner.get_mut();
loop {
while !self.framed.is_write_buf_full() {
if let Some(msg) = inner.buf.pop_front() {
match msg {
Ok(msg) => {
if let Err(err) = self.framed.force_send(msg) {
self.state = TransportState::FramedError(
FramedTransportError::Encoder(err),
);
return true;
}
}
Err(err) => {
self.state =
TransportState::Error(FramedTransportError::Service(err));
return true;
}
}
} else {
break;
}
}
if !self.framed.is_write_buf_empty() {
match self.framed.poll_complete() {
Ok(Async::NotReady) => break,
Err(err) => {
debug!("Error sending data: {:?}", err);
self.state =
TransportState::FramedError(FramedTransportError::Encoder(err));
return true;
}
Ok(Async::Ready(_)) => (),
}
} else {
break;
}
}
false
}
}
impl<S, T, U> FramedTransport<S, T, U>
where
S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
pub fn new<F: IntoService<S>>(framed: Framed<T, U>, service: F) -> Self {
FramedTransport { FramedTransport {
framed, framed,
write_rx,
write_tx,
service: service.into_service(), service: service.into_service(),
state: TransportState::Processing, state: TransportState::Processing,
request: None, inner: Cell::new(FramedTransportInner {
buf: VecDeque::new(),
task: AtomicTask::new(),
}),
} }
} }
@@ -236,127 +340,15 @@ where
} }
} }
impl<S, T, U> FramedTransport<S, T, U>
where
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
S: Service<Request<U>, Response = Response<U>>,
S::Future: 'static,
S::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug + 'static,
{
fn poll_service(&mut self) -> bool {
match self.service.poll_ready() {
Ok(Async::Ready(_)) => {
if let Some(item) = self.request.take() {
let sender = self.write_tx.clone();
Arbiter::spawn(
self.service
.call(item)
.then(|item| sender.send(item).map(|_| ()).map_err(|_| ())),
);
}
loop {
let item = match self.framed.poll() {
Ok(Async::Ready(Some(el))) => el,
Err(err) => {
self.state =
TransportState::FramedError(FramedTransportError::Decoder(err));
return true;
}
Ok(Async::NotReady) => return false,
Ok(Async::Ready(None)) => {
self.state = TransportState::Stopping;
return true;
}
};
match self.service.poll_ready() {
Ok(Async::Ready(_)) => {
let sender = self.write_tx.clone();
Arbiter::spawn(
self.service
.call(item)
.then(|item| sender.send(item).map(|_| ()).map_err(|_| ())),
);
}
Ok(Async::NotReady) => {
self.request = Some(item);
return false;
}
Err(err) => {
self.state =
TransportState::Error(FramedTransportError::Service(err));
return true;
}
}
}
}
Ok(Async::NotReady) => false,
Err(err) => {
self.state = TransportState::Error(FramedTransportError::Service(err));
true
}
}
}
/// write to sink
fn poll_response(&mut self) -> bool {
loop {
while !self.framed.is_write_buf_full() {
match self.write_rx.poll() {
Ok(Async::Ready(Some(msg))) => match msg {
Ok(msg) => {
if let Err(err) = self.framed.force_send(msg) {
self.state = TransportState::FramedError(
FramedTransportError::Encoder(err),
);
return true;
}
}
Err(err) => {
self.state =
TransportState::Error(FramedTransportError::Service(err));
return true;
}
},
Ok(Async::NotReady) => break,
Err(_) => panic!("Bug in actix-net code"),
Ok(Async::Ready(None)) => panic!("Bug in actix-net code"),
}
}
if !self.framed.is_write_buf_empty() {
match self.framed.poll_complete() {
Ok(Async::NotReady) => break,
Err(err) => {
debug!("Error sending data: {:?}", err);
self.state =
TransportState::FramedError(FramedTransportError::Encoder(err));
return true;
}
Ok(Async::Ready(_)) => (),
}
} else {
break;
}
}
false
}
}
impl<S, T, U> Future for FramedTransport<S, T, U> impl<S, T, U> Future for FramedTransport<S, T, U>
where where
S: Service<Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
S::Future: 'static,
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
U: Decoder + Encoder, U: Decoder + Encoder,
S: Service<Request<U>, Response = Response<U>>,
S::Future: 'static,
S::Error: 'static,
<U as Encoder>::Item: 'static, <U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug + 'static, <U as Encoder>::Error: std::fmt::Debug,
{ {
type Item = (); type Item = ();
type Error = FramedTransportError<S::Error, U>; type Error = FramedTransportError<S::Error, U>;
@@ -364,7 +356,7 @@ where
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match mem::replace(&mut self.state, TransportState::Processing) { match mem::replace(&mut self.state, TransportState::Processing) {
TransportState::Processing => { TransportState::Processing => {
if self.poll_service() || self.poll_response() { if self.poll_read() || self.poll_write() {
self.poll() self.poll()
} else { } else {
Ok(Async::NotReady) Ok(Async::NotReady)
@@ -372,7 +364,7 @@ where
} }
TransportState::Error(err) => { TransportState::Error(err) => {
if self.framed.is_write_buf_empty() if self.framed.is_write_buf_empty()
|| (self.poll_response() || self.framed.is_write_buf_empty()) || (self.poll_write() || self.framed.is_write_buf_empty())
{ {
Err(err) Err(err)
} else { } else {
@@ -410,12 +402,13 @@ where
} }
} }
impl<T, U, F> NewService<T> for IntoFramed<T, U, F> impl<T, U, F> NewService for IntoFramed<T, U, F>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static, F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder, U: Encoder + Decoder,
{ {
type Request = T;
type Response = Framed<T, U>; type Response = Framed<T, U>;
type Error = (); type Error = ();
type InitError = (); type InitError = ();
@@ -440,12 +433,13 @@ where
_t: PhantomData<(T,)>, _t: PhantomData<(T,)>,
} }
impl<T, U, F> Service<T> for IntoFramedService<T, U, F> impl<T, U, F> Service for IntoFramedService<T, U, F>
where where
T: AsyncRead + AsyncWrite, T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static, F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder, U: Encoder + Decoder,
{ {
type Request = T;
type Response = Framed<T, U>; type Response = Framed<T, U>;
type Error = (); type Error = ();
type Future = FutureResult<Self::Response, Self::Error>; type Future = FutureResult<Self::Response, Self::Error>;

View File

@@ -1,5 +1,6 @@
use actix_service::{IntoNewService, IntoService, NewService, Service}; use actix_service::{NewTransform, Service, Transform};
use futures::{try_ready, Async, Future, Poll}; use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use super::counter::{Counter, CounterGuard}; use super::counter::{Counter, CounterGuard};
@@ -7,127 +8,80 @@ use super::counter::{Counter, CounterGuard};
/// async requests. /// async requests.
/// ///
/// Default number of in-flight requests is 15 /// Default number of in-flight requests is 15
pub struct InFlight<T> { pub struct InFlight {
factory: T,
max_inflight: usize, max_inflight: usize,
} }
impl<T> InFlight<T> { impl InFlight {
pub fn new<F, Request>(factory: F) -> Self pub fn new(max: usize) -> Self {
where Self { max_inflight: max }
T: NewService<Request>,
F: IntoNewService<T, Request>,
{
Self {
factory: factory.into_new_service(),
max_inflight: 15,
}
}
/// Set max number of in-flight requests.
///
/// By default max in-flight requests is 15.
pub fn max_inflight(mut self, max: usize) -> Self {
self.max_inflight = max;
self
} }
} }
impl<T, Request> NewService<Request> for InFlight<T> impl Default for InFlight {
where fn default() -> Self {
T: NewService<Request>, Self::new(15)
{ }
}
impl<T: Service> NewTransform<T> for InFlight {
type Request = T::Request;
type Response = T::Response; type Response = T::Response;
type Error = T::Error; type Error = T::Error;
type InitError = T::InitError; type InitError = ();
type Service = InFlightService<T::Service>; type Transform = InFlightService;
type Future = InFlightResponseFuture<T, Request>; type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_service(&self) -> Self::Future { fn new_transform(&self) -> Self::Future {
InFlightResponseFuture { ok(InFlightService::new(self.max_inflight))
fut: self.factory.new_service(),
max_inflight: self.max_inflight,
}
} }
} }
pub struct InFlightResponseFuture<T: NewService<Request>, Request> { pub struct InFlightService {
fut: T::Future,
max_inflight: usize,
}
impl<T: NewService<Request>, Request> Future for InFlightResponseFuture<T, Request> {
type Item = InFlightService<T::Service>;
type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
Ok(Async::Ready(InFlightService::with_max_inflight(
self.max_inflight,
try_ready!(self.fut.poll()),
)))
}
}
pub struct InFlightService<T> {
service: T,
count: Counter, count: Counter,
} }
impl<T> InFlightService<T> { impl InFlightService {
pub fn new<F, Request>(service: F) -> Self pub fn new(max: usize) -> Self {
where
T: Service<Request>,
F: IntoService<T, Request>,
{
Self { Self {
service: service.into_service(),
count: Counter::new(15),
}
}
pub fn with_max_inflight<F, Request>(max: usize, service: F) -> Self
where
T: Service<Request>,
F: IntoService<T, Request>,
{
Self {
service: service.into_service(),
count: Counter::new(max), count: Counter::new(max),
} }
} }
} }
impl<T, Request> Service<Request> for InFlightService<T> impl<T> Transform<T> for InFlightService
where where
T: Service<Request>, T: Service,
{ {
type Request = T::Request;
type Response = T::Response; type Response = T::Response;
type Error = T::Error; type Error = T::Error;
type Future = InFlightServiceResponse<T, Request>; type Future = InFlightServiceResponse<T>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
let res = self.service.poll_ready(); if !self.count.available() {
if res.is_ok() && !self.count.available() { log::trace!("InFlight limit exceeded");
return Ok(Async::NotReady); return Ok(Async::NotReady);
} else {
return Ok(Async::Ready(()));
} }
res
} }
fn call(&mut self, req: Request) -> Self::Future { fn call(&mut self, req: T::Request, service: &mut T) -> Self::Future {
InFlightServiceResponse { InFlightServiceResponse {
fut: self.service.call(req), fut: service.call(req),
_guard: self.count.get(), _guard: self.count.get(),
} }
} }
} }
#[doc(hidden)] #[doc(hidden)]
pub struct InFlightServiceResponse<T: Service<Request>, Request> { pub struct InFlightServiceResponse<T: Service> {
fut: T::Future, fut: T::Future,
_guard: CounterGuard, _guard: CounterGuard,
} }
impl<T: Service<Request>, Request> Future for InFlightServiceResponse<T, Request> { impl<T: Service> Future for InFlightServiceResponse<T> {
type Item = T::Response; type Item = T::Response;
type Error = T::Error; type Error = T::Error;
@@ -135,3 +89,73 @@ impl<T: Service<Request>, Request> Future for InFlightServiceResponse<T, Request
self.fut.poll() self.fut.poll()
} }
} }
#[cfg(test)]
mod tests {
use futures::future::lazy;
use futures::{Async, Poll};
use std::time::Duration;
use super::*;
use actix_service::{Blank, BlankNewService, NewService, Service, ServiceExt};
struct SleepService(Duration);
impl Service for SleepService {
type Request = ();
type Response = ();
type Error = ();
type Future = Box<Future<Item = (), Error = ()>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
Box::new(tokio_timer::sleep(self.0).map_err(|_| ()))
}
}
#[test]
fn test_transform() {
let wait_time = Duration::from_millis(50);
let _ = actix_rt::System::new("test").block_on(lazy(|| {
let mut srv = Blank::new().apply(InFlightService::new(1), SleepService(wait_time));
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
let mut res = srv.call(());
let _ = res.poll();
assert_eq!(srv.poll_ready(), Ok(Async::NotReady));
drop(res);
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
Ok::<_, ()>(())
}));
}
#[test]
fn test_newtransform() {
let wait_time = Duration::from_millis(50);
let _ = actix_rt::System::new("test").block_on(lazy(|| {
let srv =
BlankNewService::new().apply(InFlight::new(1), || Ok(SleepService(wait_time)));
if let Async::Ready(mut srv) = srv.new_service().poll().unwrap() {
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
let mut res = srv.call(());
let _ = res.poll();
assert_eq!(srv.poll_ready(), Ok(Async::NotReady));
drop(res);
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
} else {
panic!()
}
Ok::<_, ()>(())
}));
}
}

View File

@@ -44,10 +44,11 @@ where
} }
} }
impl<R, E, F> NewService<R> for KeepAlive<R, E, F> impl<R, E, F> NewService for KeepAlive<R, E, F>
where where
F: Fn() -> E + Clone, F: Fn() -> E + Clone,
{ {
type Request = R;
type Response = R; type Response = R;
type Error = E; type Error = E;
type InitError = Never; type InitError = Never;
@@ -89,10 +90,11 @@ where
} }
} }
impl<R, E, F> Service<R> for KeepAliveService<R, E, F> impl<R, E, F> Service for KeepAliveService<R, E, F>
where where
F: Fn() -> E, F: Fn() -> E,
{ {
type Request = R;
type Response = R; type Response = R;
type Error = E; type Error = E;
type Future = FutureResult<R, E>; type Future = FutureResult<R, E>;

View File

@@ -1,7 +1,6 @@
use std::marker::PhantomData; use std::marker::PhantomData;
use std::rc::Rc; use std::rc::Rc;
use actix_rt::spawn;
use actix_service::{IntoNewService, IntoService, NewService, Service}; use actix_service::{IntoNewService, IntoService, NewService, Service};
use futures::future::{ok, Future, FutureResult}; use futures::future::{ok, Future, FutureResult};
use futures::unsync::mpsc; use futures::unsync::mpsc;
@@ -38,12 +37,12 @@ pub struct StreamNewService<S, T, E> {
impl<S, T, E> StreamNewService<S, T, E> impl<S, T, E> StreamNewService<S, T, E>
where where
S: IntoStream, S: IntoStream,
T: NewService<Request<S>, Response = (), Error = E, InitError = E>, T: NewService<Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static, T::Future: 'static,
T::Service: 'static, T::Service: 'static,
<T::Service as Service<Request<S>>>::Future: 'static, <T::Service as Service>::Future: 'static,
{ {
pub fn new<F: IntoNewService<T, Request<S>>>(factory: F) -> Self { pub fn new<F: IntoNewService<T>>(factory: F) -> Self {
Self { Self {
factory: Rc::new(factory.into_new_service()), factory: Rc::new(factory.into_new_service()),
_t: PhantomData, _t: PhantomData,
@@ -60,14 +59,15 @@ impl<S, T, E> Clone for StreamNewService<S, T, E> {
} }
} }
impl<S, T, E> NewService<S> for StreamNewService<S, T, E> impl<S, T, E> NewService for StreamNewService<S, T, E>
where where
S: IntoStream + 'static, S: IntoStream + 'static,
T: NewService<Request<S>, Response = (), Error = E, InitError = E>, T: NewService<Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static, T::Future: 'static,
T::Service: 'static, T::Service: 'static,
<T::Service as Service<Request<S>>>::Future: 'static, <T::Service as Service>::Future: 'static,
{ {
type Request = S;
type Response = (); type Response = ();
type Error = E; type Error = E;
type InitError = E; type InitError = E;
@@ -87,14 +87,15 @@ pub struct StreamService<S, T, E> {
_t: PhantomData<(S, E)>, _t: PhantomData<(S, E)>,
} }
impl<S, T, E> Service<S> for StreamService<S, T, E> impl<S, T, E> Service for StreamService<S, T, E>
where where
S: IntoStream + 'static, S: IntoStream + 'static,
T: NewService<Request<S>, Response = (), Error = E, InitError = E>, T: NewService<Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static, T::Future: 'static,
T::Service: 'static, T::Service: 'static,
<T::Service as Service<Request<S>>>::Future: 'static, <T::Service as Service>::Future: 'static,
{ {
type Request = S;
type Response = (); type Response = ();
type Error = E; type Error = E;
type Future = Box<Future<Item = (), Error = E>>; type Future = Box<Future<Item = (), Error = E>>;
@@ -115,7 +116,7 @@ where
pub struct StreamDispatcher<S, T> pub struct StreamDispatcher<S, T>
where where
S: IntoStream + 'static, S: IntoStream + 'static,
T: Service<Request<S>, Response = ()> + 'static, T: Service<Request = Request<S>, Response = ()> + 'static,
T::Future: 'static, T::Future: 'static,
{ {
stream: S, stream: S,
@@ -127,13 +128,13 @@ where
impl<S, T> StreamDispatcher<S, T> impl<S, T> StreamDispatcher<S, T>
where where
S: Stream, S: Stream,
T: Service<Request<S>, Response = ()>, T: Service<Request = Request<S>, Response = ()>,
T::Future: 'static, T::Future: 'static,
{ {
pub fn new<F1, F2>(stream: F1, service: F2) -> Self pub fn new<F1, F2>(stream: F1, service: F2) -> Self
where where
F1: IntoStream<Stream = S, Item = S::Item, Error = S::Error>, F1: IntoStream<Stream = S, Item = S::Item, Error = S::Error>,
F2: IntoService<T, Request<S>>, F2: IntoService<T>,
{ {
let (err_tx, err_rx) = mpsc::unbounded(); let (err_tx, err_rx) = mpsc::unbounded();
StreamDispatcher { StreamDispatcher {
@@ -148,7 +149,7 @@ where
impl<S, T> Future for StreamDispatcher<S, T> impl<S, T> Future for StreamDispatcher<S, T>
where where
S: Stream, S: Stream,
T: Service<Request<S>, Response = ()>, T: Service<Request = Request<S>, Response = ()>,
T::Future: 'static, T::Future: 'static,
{ {
type Item = (); type Item = ();
@@ -162,11 +163,13 @@ where
loop { loop {
match self.service.poll_ready()? { match self.service.poll_ready()? {
Async::Ready(_) => match self.stream.poll() { Async::Ready(_) => match self.stream.poll() {
Ok(Async::Ready(Some(item))) => spawn(StreamDispatcherService { Ok(Async::Ready(Some(item))) => {
fut: self.service.call(Ok(item)), tokio_current_thread::spawn(StreamDispatcherService {
stop: self.err_tx.clone(), fut: self.service.call(Ok(item)),
}), stop: self.err_tx.clone(),
Err(err) => spawn(StreamDispatcherService { })
}
Err(err) => tokio_current_thread::spawn(StreamDispatcherService {
fut: self.service.call(Err(err)), fut: self.service.call(Err(err)),
stop: self.err_tx.clone(), stop: self.err_tx.clone(),
}), }),
@@ -224,7 +227,8 @@ impl<T> Clone for TakeItem<T> {
} }
} }
impl<T: Stream> NewService<T> for TakeItem<T> { impl<T: Stream> NewService for TakeItem<T> {
type Request = T;
type Response = (Option<T::Item>, T); type Response = (Option<T::Item>, T);
type Error = T::Error; type Error = T::Error;
type InitError = (); type InitError = ();
@@ -247,7 +251,8 @@ impl<T> Clone for TakeItemService<T> {
} }
} }
impl<T: Stream> Service<T> for TakeItemService<T> { impl<T: Stream> Service for TakeItemService<T> {
type Request = T;
type Response = (Option<T::Item>, T); type Response = (Option<T::Item>, T);
type Error = T::Error; type Error = T::Error;
type Future = TakeItemServiceResponse<T>; type Future = TakeItemServiceResponse<T>;

View File

@@ -1,6 +1,5 @@
use std::time::{Duration, Instant}; use std::time::{self, Duration, Instant};
use actix_rt::spawn;
use actix_service::{NewService, Service}; use actix_service::{NewService, Service};
use futures::future::{ok, FutureResult}; use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
@@ -43,7 +42,8 @@ impl Default for LowResTime {
} }
} }
impl NewService<()> for LowResTime { impl NewService for LowResTime {
type Request = ();
type Response = Instant; type Response = Instant;
type Error = Never; type Error = Never;
type InitError = Never; type InitError = Never;
@@ -66,28 +66,31 @@ impl LowResTimeService {
/// Get current time. This function has to be called from /// Get current time. This function has to be called from
/// future's poll method, otherwise it panics. /// future's poll method, otherwise it panics.
pub fn now(&self) -> Instant { pub fn now(&self) -> Instant {
let cur = self.0.borrow().current; let cur = self.0.get_ref().current;
if let Some(cur) = cur { if let Some(cur) = cur {
cur cur
} else { } else {
let now = Instant::now(); let now = Instant::now();
let inner = self.0.clone(); let mut inner = self.0.clone();
let interval = { let interval = {
let mut b = inner.borrow_mut(); let mut b = inner.get_mut();
b.current = Some(now); b.current = Some(now);
b.resolution b.resolution
}; };
spawn(sleep(interval).map_err(|_| panic!()).and_then(move |_| { tokio_current_thread::spawn(sleep(interval).map_err(|_| panic!()).and_then(
inner.borrow_mut().current.take(); move |_| {
Ok(()) inner.get_mut().current.take();
})); Ok(())
},
));
now now
} }
} }
} }
impl Service<()> for LowResTimeService { impl Service for LowResTimeService {
type Request = ();
type Response = Instant; type Response = Instant;
type Error = Never; type Error = Never;
type Future = FutureResult<Self::Response, Self::Error>; type Future = FutureResult<Self::Response, Self::Error>;
@@ -100,3 +103,148 @@ impl Service<()> for LowResTimeService {
ok(self.now()) ok(self.now())
} }
} }
#[derive(Clone, Debug)]
pub struct SystemTime(Cell<SystemTimeInner>);
#[derive(Debug)]
struct SystemTimeInner {
resolution: Duration,
current: Option<time::SystemTime>,
}
impl SystemTimeInner {
fn new(resolution: Duration) -> Self {
SystemTimeInner {
resolution,
current: None,
}
}
}
#[derive(Clone, Debug)]
pub struct SystemTimeService(Cell<SystemTimeInner>);
impl SystemTimeService {
pub fn with(resolution: Duration) -> SystemTimeService {
SystemTimeService(Cell::new(SystemTimeInner::new(resolution)))
}
/// Get current time. This function has to be called from
/// future's poll method, otherwise it panics.
pub fn now(&self) -> time::SystemTime {
let cur = self.0.get_ref().current.clone();
if let Some(cur) = cur {
cur
} else {
let now = time::SystemTime::now();
let mut inner = self.0.clone();
let interval = {
let mut b = inner.get_mut();
b.current = Some(now);
b.resolution
};
tokio_current_thread::spawn(sleep(interval).map_err(|_| panic!()).and_then(
move |_| {
inner.get_mut().current.take();
Ok(())
},
));
now
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::future;
use std::time::{Duration, SystemTime};
/// State Under Test: Two calls of `SystemTimeService::now()` return the same value if they are done within resolution interval of `SystemTimeService`.
///
/// Expected Behavior: Two back-to-back calls of `SystemTimeService::now()` return the same value.
#[test]
fn system_time_service_time_does_not_immediately_change() {
let resolution = Duration::from_millis(50);
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
let time_service = SystemTimeService::with(resolution);
assert_eq!(time_service.now(), time_service.now());
Ok::<(), ()>(())
}));
}
/// State Under Test: Two calls of `LowResTimeService::now()` return the same value if they are done within resolution interval of `SystemTimeService`.
///
/// Expected Behavior: Two back-to-back calls of `LowResTimeService::now()` return the same value.
#[test]
fn lowres_time_service_time_does_not_immediately_change() {
let resolution = Duration::from_millis(50);
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
let time_service = LowResTimeService::with(resolution);
assert_eq!(time_service.now(), time_service.now());
Ok::<(), ()>(())
}));
}
/// State Under Test: `SystemTimeService::now()` updates returned value every resolution period.
///
/// Expected Behavior: Two calls of `LowResTimeService::now()` made in subsequent resolution interval return different values
/// and second value is greater than the first one at least by a resolution interval.
#[test]
fn system_time_service_time_updates_after_resolution_interval() {
let resolution = Duration::from_millis(100);
let wait_time = Duration::from_millis(150);
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
let time_service = SystemTimeService::with(resolution);
let first_time = time_service
.now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
sleep(wait_time).then(move |_| {
let second_time = time_service
.now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
assert!(second_time - first_time >= wait_time);
Ok::<(), ()>(())
})
}));
}
/// State Under Test: `LowResTimeService::now()` updates returned value every resolution period.
///
/// Expected Behavior: Two calls of `LowResTimeService::now()` made in subsequent resolution interval return different values
/// and second value is greater than the first one at least by a resolution interval.
#[test]
fn lowres_time_service_time_updates_after_resolution_interval() {
let resolution = Duration::from_millis(100);
let wait_time = Duration::from_millis(150);
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
let time_service = LowResTimeService::with(resolution);
let first_time = time_service.now();
sleep(wait_time).then(move |_| {
let second_time = time_service.now();
assert!(second_time - first_time >= wait_time);
Ok::<(), ()>(())
})
}));
}
}

View File

@@ -3,18 +3,19 @@
//! If the response does not complete within the specified timeout, the response //! If the response does not complete within the specified timeout, the response
//! will be aborted. //! will be aborted.
use std::fmt; use std::fmt;
use std::marker::PhantomData;
use std::time::Duration; use std::time::Duration;
use actix_service::{NewService, Service}; use actix_service::{NewTransform, Service, Transform};
use futures::try_ready; use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll}; use futures::{Async, Future, Poll};
use tokio_timer::{clock, Delay}; use tokio_timer::{clock, Delay};
/// Applies a timeout to requests. /// Applies a timeout to requests.
#[derive(Debug)] #[derive(Debug)]
pub struct Timeout<T> { pub struct Timeout<E = ()> {
inner: T,
timeout: Duration, timeout: Duration,
_t: PhantomData<E>,
} }
/// Timeout error /// Timeout error
@@ -25,6 +26,12 @@ pub enum TimeoutError<E> {
Timeout, Timeout,
} }
impl<E> From<E> for TimeoutError<E> {
fn from(err: E) -> Self {
TimeoutError::Service(err)
}
}
impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> { impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match self {
@@ -34,93 +41,82 @@ impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> {
} }
} }
impl<T> Timeout<T> { impl<E: PartialEq> PartialEq for TimeoutError<E> {
pub fn new<Request>(timeout: Duration, inner: T) -> Self fn eq(&self, other: &TimeoutError<E>) -> bool {
where match self {
T: NewService<Request> + Clone, TimeoutError::Service(e1) => match other {
{ TimeoutError::Service(e2) => e1 == e2,
Timeout { inner, timeout } TimeoutError::Timeout => false,
} },
} TimeoutError::Timeout => match other {
TimeoutError::Service(_) => false,
impl<T, Request> NewService<Request> for Timeout<T> TimeoutError::Timeout => true,
where },
T: NewService<Request> + Clone,
{
type Response = T::Response;
type Error = TimeoutError<T::Error>;
type InitError = T::InitError;
type Service = TimeoutService<T::Service>;
type Future = TimeoutFut<T, Request>;
fn new_service(&self) -> Self::Future {
TimeoutFut {
fut: self.inner.new_service(),
timeout: self.timeout,
} }
} }
} }
/// `Timeout` response future impl<E> Timeout<E> {
#[derive(Debug)] pub fn new(timeout: Duration) -> Self {
pub struct TimeoutFut<T: NewService<Request>, Request> { Timeout {
fut: T::Future, timeout,
timeout: Duration, _t: PhantomData,
}
}
} }
impl<T, Request> Future for TimeoutFut<T, Request> impl<E> Clone for Timeout<E> {
where fn clone(&self) -> Self {
T: NewService<Request>, Timeout::new(self.timeout)
{ }
type Item = TimeoutService<T::Service>; }
type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { impl<S, E> NewTransform<S> for Timeout<E>
let service = try_ready!(self.fut.poll()); where
Ok(Async::Ready(TimeoutService::new(self.timeout, service))) S: Service,
{
type Request = S::Request;
type Response = S::Response;
type Error = TimeoutError<S::Error>;
type InitError = E;
type Transform = TimeoutService;
type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self) -> Self::Future {
ok(TimeoutService {
timeout: self.timeout,
})
} }
} }
/// Applies a timeout to requests. /// Applies a timeout to requests.
#[derive(Debug)] #[derive(Debug, Clone)]
pub struct TimeoutService<T> { pub struct TimeoutService {
inner: T,
timeout: Duration, timeout: Duration,
} }
impl<T> TimeoutService<T> { impl TimeoutService {
pub fn new<Request>(timeout: Duration, inner: T) -> Self pub fn new(timeout: Duration) -> Self {
where TimeoutService { timeout }
T: Service<Request>,
{
TimeoutService { inner, timeout }
} }
} }
impl<T: Clone> Clone for TimeoutService<T> { impl<S> Transform<S> for TimeoutService
fn clone(&self) -> Self {
TimeoutService {
inner: self.inner.clone(),
timeout: self.timeout,
}
}
}
impl<T, Request> Service<Request> for TimeoutService<T>
where where
T: Service<Request>, S: Service,
{ {
type Response = T::Response; type Request = S::Request;
type Error = TimeoutError<T::Error>; type Response = S::Response;
type Future = TimeoutServiceResponse<T, Request>; type Error = TimeoutError<S::Error>;
type Future = TimeoutServiceResponse<S>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.inner.poll_ready().map_err(TimeoutError::Service) Ok(Async::Ready(()))
} }
fn call(&mut self, request: Request) -> Self::Future { fn call(&mut self, request: S::Request, service: &mut S) -> Self::Future {
TimeoutServiceResponse { TimeoutServiceResponse {
fut: self.inner.call(request), fut: service.call(request),
sleep: Delay::new(clock::now() + self.timeout), sleep: Delay::new(clock::now() + self.timeout),
} }
} }
@@ -128,14 +124,14 @@ where
/// `TimeoutService` response future /// `TimeoutService` response future
#[derive(Debug)] #[derive(Debug)]
pub struct TimeoutServiceResponse<T: Service<Request>, Request> { pub struct TimeoutServiceResponse<T: Service> {
fut: T::Future, fut: T::Future,
sleep: Delay, sleep: Delay,
} }
impl<T, Request> Future for TimeoutServiceResponse<T, Request> impl<T> Future for TimeoutServiceResponse<T>
where where
T: Service<Request>, T: Service,
{ {
type Item = T::Response; type Item = T::Response;
type Error = TimeoutError<T::Error>; type Error = TimeoutError<T::Error>;
@@ -156,3 +152,74 @@ where
} }
} }
} }
#[cfg(test)]
mod tests {
use futures::future::lazy;
use futures::{Async, Poll};
use std::time::Duration;
use super::*;
use actix_service::{Blank, BlankNewService, NewService, Service, ServiceExt};
struct SleepService(Duration);
impl Service for SleepService {
type Request = ();
type Response = ();
type Error = ();
type Future = Box<Future<Item = (), Error = ()>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
Box::new(tokio_timer::sleep(self.0).map_err(|_| ()))
}
}
#[test]
fn test_success() {
let resolution = Duration::from_millis(100);
let wait_time = Duration::from_millis(50);
let res = actix_rt::System::new("test").block_on(lazy(|| {
let mut timeout = Blank::default()
.apply(TimeoutService::new(resolution), SleepService(wait_time));
timeout.call(())
}));
assert_eq!(res, Ok(()));
}
#[test]
fn test_timeout() {
let resolution = Duration::from_millis(100);
let wait_time = Duration::from_millis(150);
let res = actix_rt::System::new("test").block_on(lazy(|| {
let mut timeout = Blank::default()
.apply(TimeoutService::new(resolution), SleepService(wait_time));
timeout.call(())
}));
assert_eq!(res, Err(TimeoutError::Timeout));
}
#[test]
fn test_timeout_newservice() {
let resolution = Duration::from_millis(100);
let wait_time = Duration::from_millis(150);
let res = actix_rt::System::new("test").block_on(lazy(|| {
let timeout = BlankNewService::default()
.apply(Timeout::new(resolution), || Ok(SleepService(wait_time)));
if let Async::Ready(mut to) = timeout.new_service().poll().unwrap() {
to.call(())
} else {
panic!()
}
}));
assert_eq!(res, Err(TimeoutError::Timeout));
}
}

View File

@@ -27,4 +27,5 @@ string = "0.1.3"
http = { version="0.1.14", optional=true } http = { version="0.1.14", optional=true }
[dev-dependencies] [dev-dependencies]
http = "0.1.14"
serde_derive = "1.0" serde_derive = "1.0"

View File

@@ -31,6 +31,12 @@ impl<T: AsRef<[u8]>> RequestPath for string::String<T> {
} }
} }
#[cfg(feature = "http")]
mod url;
#[cfg(feature = "http")]
pub use self::url::Url;
#[cfg(feature = "http")] #[cfg(feature = "http")]
mod http_support { mod http_support {
use super::RequestPath; use super::RequestPath;

View File

@@ -278,6 +278,7 @@ impl Hash for Pattern {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use http::{HttpTryFrom, Uri};
#[test] #[test]
fn test_parse_static() { fn test_parse_static() {
@@ -338,6 +339,24 @@ mod tests {
assert_eq!(path.get("id").unwrap(), "012345"); assert_eq!(path.get("id").unwrap(), "012345");
} }
#[test]
fn test_parse_urlencoded_param() {
let re = Pattern::new("/user/{id}/test");
let mut path = Path::new("/user/2345/test");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "2345");
let mut path = Path::new("/user/qwe%25/test");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "qwe%25");
let uri = Uri::try_from("/user/qwe%25/test").unwrap();
let mut path = Path::new(uri);
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "qwe%25");
}
#[test] #[test]
fn test_resource_prefix() { fn test_resource_prefix() {
let re = Pattern::prefix("/name"); let re = Pattern::prefix("/name");

214
router/src/url.rs Normal file
View File

@@ -0,0 +1,214 @@
use std::rc::Rc;
use crate::RequestPath;
#[allow(dead_code)]
const GEN_DELIMS: &[u8] = b":/?#[]@";
#[allow(dead_code)]
const SUB_DELIMS_WITHOUT_QS: &[u8] = b"!$'()*,";
#[allow(dead_code)]
const SUB_DELIMS: &[u8] = b"!$'()*,+?=;";
#[allow(dead_code)]
const RESERVED: &[u8] = b":/?#[]@!$'()*,+?=;";
#[allow(dead_code)]
const UNRESERVED: &[u8] = b"abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
1234567890
-._~";
const ALLOWED: &[u8] = b"abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
1234567890
-._~
!$'()*,";
const QS: &[u8] = b"+&=;b";
#[inline]
fn bit_at(array: &[u8], ch: u8) -> bool {
array[(ch >> 3) as usize] & (1 << (ch & 7)) != 0
}
#[inline]
fn set_bit(array: &mut [u8], ch: u8) {
array[(ch >> 3) as usize] |= 1 << (ch & 7)
}
thread_local! {
static DEFAULT_QUOTER: Quoter = { Quoter::new(b"@:", b"/+") };
}
#[derive(Default, Clone, Debug)]
pub struct Url {
uri: http::Uri,
path: Option<Rc<String>>,
}
impl Url {
pub fn new(uri: http::Uri) -> Url {
let path = DEFAULT_QUOTER.with(|q| q.requote(uri.path().as_bytes()));
Url { uri, path }
}
pub fn uri(&self) -> &http::Uri {
&self.uri
}
pub fn path(&self) -> &str {
if let Some(ref s) = self.path {
s
} else {
self.uri.path()
}
}
pub fn update(&mut self, uri: &http::Uri) {
self.uri = uri.clone();
self.path = DEFAULT_QUOTER.with(|q| q.requote(uri.path().as_bytes()));
}
}
impl RequestPath for Url {
fn path(&self) -> &str {
self.path()
}
}
pub(crate) struct Quoter {
safe_table: [u8; 16],
protected_table: [u8; 16],
}
impl Quoter {
pub fn new(safe: &[u8], protected: &[u8]) -> Quoter {
let mut q = Quoter {
safe_table: [0; 16],
protected_table: [0; 16],
};
// prepare safe table
for i in 0..128 {
if ALLOWED.contains(&i) {
set_bit(&mut q.safe_table, i);
}
if QS.contains(&i) {
set_bit(&mut q.safe_table, i);
}
}
for ch in safe {
set_bit(&mut q.safe_table, *ch)
}
// prepare protected table
for ch in protected {
set_bit(&mut q.safe_table, *ch);
set_bit(&mut q.protected_table, *ch);
}
q
}
pub fn requote(&self, val: &[u8]) -> Option<Rc<String>> {
let mut has_pct = 0;
let mut pct = [b'%', 0, 0];
let mut idx = 0;
let mut cloned: Option<Vec<u8>> = None;
let len = val.len();
while idx < len {
let ch = val[idx];
if has_pct != 0 {
pct[has_pct] = val[idx];
has_pct += 1;
if has_pct == 3 {
has_pct = 0;
let buf = cloned.as_mut().unwrap();
if let Some(ch) = restore_ch(pct[1], pct[2]) {
if ch < 128 {
if bit_at(&self.protected_table, ch) {
buf.extend_from_slice(&pct);
idx += 1;
continue;
}
if bit_at(&self.safe_table, ch) {
buf.push(ch);
idx += 1;
continue;
}
}
buf.push(ch);
} else {
buf.extend_from_slice(&pct[..]);
}
}
} else if ch == b'%' {
has_pct = 1;
if cloned.is_none() {
let mut c = Vec::with_capacity(len);
c.extend_from_slice(&val[..idx]);
cloned = Some(c);
}
} else if let Some(ref mut cloned) = cloned {
cloned.push(ch)
}
idx += 1;
}
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) }))
} else {
None
}
}
}
#[inline]
fn from_hex(v: u8) -> Option<u8> {
if v >= b'0' && v <= b'9' {
Some(v - 0x30) // ord('0') == 0x30
} else if v >= b'A' && v <= b'F' {
Some(v - 0x41 + 10) // ord('A') == 0x41
} else if v > b'a' && v <= b'f' {
Some(v - 0x61 + 10) // ord('a') == 0x61
} else {
None
}
}
#[inline]
fn restore_ch(d1: u8, d2: u8) -> Option<u8> {
from_hex(d1).and_then(|d1| from_hex(d2).and_then(move |d2| Some(d1 << 4 | d2)))
}
#[cfg(test)]
mod tests {
use http::{HttpTryFrom, Uri};
use super::*;
use crate::{Path, Pattern};
#[test]
fn test_parse_url() {
let re = Pattern::new("/user/{id}/test");
let url = Uri::try_from("/user/2345/test").unwrap();
let mut path = Path::new(Url::new(url));
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "2345");
let url = Uri::try_from("/user/qwe%25/test").unwrap();
let mut path = Path::new(Url::new(url));
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "qwe%");
let url = Uri::try_from("/user/qwe%25rty/test").unwrap();
let mut path = Path::new(Url::new(url));
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "qwe%rty");
}
}