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

Compare commits

..

2 Commits
ser ... v0.2.6

Author SHA1 Message Date
Nikolay Kim
ebf8d7fa34 Fix back-pressure handling for concurrent connections 2018-12-21 10:43:18 -08:00
Nikolay Kim
298727dcbd back port bug fixes 2018-12-12 19:01:59 -08:00
39 changed files with 796 additions and 879 deletions

View File

@@ -16,7 +16,7 @@ matrix:
env:
global:
- RUSTFLAGS="-C link-dead-code"
# - RUSTFLAGS="-C link-dead-code"
- OPENSSL_VERSION=openssl-1.0.2
before_install:
@@ -33,7 +33,6 @@ script:
if [[ "$TRAVIS_RUST_VERSION" != "nightly" ]]; then
cargo clean
cargo test --features="ssl,tls,rust-tls" -- --nocapture
cd actix-service && cargo test
fi
- |
if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then
@@ -41,7 +40,6 @@ script:
cargo tarpaulin --features="ssl,tls,rust-tls" --out Xml
bash <(curl -s https://codecov.io/bash)
echo "Uploaded code coverage"
cd actix-service && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash)
fi
# Upload docs

View File

@@ -1,10 +1,19 @@
# Changes
## [0.3.0] - xxx
## [0.2.6] - 2018-12-21
* Split `Service` trait to separate crate
### Fixed
* Use new `Service<Request>` trait
* Fix back-pressure handling for concurrent connections
## [0.2.5] - 2018-12-12
### Fixed
* Fix back-pressure for concurrent ssl handshakes
* Drop completed future for .then and .and_then combinators
## [0.2.4] - 2018-11-21

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-net"
version = "0.3.0"
version = "0.2.6"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix net - framework for the compisible network services for Rust (experimental)"
readme = "README.md"
@@ -11,13 +11,6 @@ documentation = "https://docs.rs/actix-net/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
[workspace]
members = [
"./",
"actix-service",
]
[package.metadata.docs.rs]
features = ["ssl", "tls", "rust-tls"]
@@ -47,7 +40,6 @@ cell = []
[dependencies]
actix = "0.7.6"
actix-service = "0.1.1"
log = "0.4"
num_cpus = "1.0"
@@ -65,8 +57,8 @@ tokio-tcp = "0.1"
tokio-timer = "0.2"
tokio-reactor = "0.1"
tokio-current-thread = "0.1"
trust-dns-proto = "^0.5.0"
trust-dns-resolver = "^0.10.0"
tower-service = "0.1"
trust-dns-resolver = "^0.10.2"
# native-tls
native-tls = { version="0.2", optional = true }

View File

@@ -1,12 +0,0 @@
# Changes
## [0.1.1] - 2018-12-09
### Added
* Added Service impl for Box<S: Service>
## [0.1.0] - 2018-12-09
* Initial import

View File

@@ -1,26 +0,0 @@
[package]
name = "actix-service"
version = "0.1.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix Service"
keywords = ["network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-service/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = "../"
[badges]
travis-ci = { repository = "actix/actix-service", branch = "master" }
# appveyor = { repository = "fafhrd91/actix-web-hdy9d" }
codecov = { repository = "actix/actix-service", branch = "master", service = "github" }
[lib]
name = "actix_service"
path = "src/lib.rs"
[dependencies]
futures = "0.1.24"

View File

@@ -1,32 +0,0 @@
//! Custom cell impl
use std::{cell::UnsafeCell, fmt, rc::Rc};
pub(crate) struct Cell<T> {
inner: Rc<UnsafeCell<T>>,
}
impl<T> Clone for Cell<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T: fmt::Debug> fmt::Debug for Cell<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.inner.fmt(f)
}
}
impl<T> Cell<T> {
pub(crate) fn new(inner: T) -> Self {
Self {
inner: Rc::new(UnsafeCell::new(inner)),
}
}
pub(crate) fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.inner.as_ref().get() }
}
}

View File

@@ -1,5 +1,5 @@
max_width = 96
reorder_imports = true
#wrap_comments = true
#fn_args_density = "Compressed"
wrap_comments = true
fn_args_density = "Compressed"
#use_small_heuristics = false

View File

@@ -30,34 +30,33 @@ impl<T: fmt::Debug> fmt::Debug for Cell<T> {
#[cfg(feature = "cell")]
impl<T> Cell<T> {
pub fn new(inner: T) -> Self {
pub(crate) fn new(inner: T) -> Self {
Self {
inner: Rc::new(UnsafeCell::new(inner)),
}
}
pub fn borrow(&self) -> &T {
pub(crate) fn borrow(&self) -> &T {
unsafe { &*self.inner.as_ref().get() }
}
pub fn borrow_mut(&self) -> &mut T {
pub(crate) fn borrow_mut(&self) -> &mut T {
unsafe { &mut *self.inner.as_ref().get() }
}
}
#[cfg(not(feature = "cell"))]
impl<T> Cell<T> {
pub fn new(inner: T) -> Self {
pub(crate) fn new(inner: T) -> Self {
Self {
inner: Rc::new(RefCell::new(inner)),
}
}
pub fn borrow(&self) -> Ref<T> {
pub(crate) fn borrow(&self) -> Ref<T> {
self.inner.borrow()
}
pub fn borrow_mut(&self) -> RefMut<T> {
pub(crate) fn borrow_mut(&self) -> RefMut<T> {
self.inner.borrow_mut()
}
}

View File

@@ -1,51 +1,40 @@
use std::marker::PhantomData;
use std::rc::Rc;
use actix_service::Service;
use futures::Poll;
use super::cell::Cell;
use super::service::Service;
/// Service that allows to turn non-clone service to a service with `Clone` impl
pub struct CloneableService<T: 'static> {
service: Cell<T>,
_t: PhantomData<Rc<()>>,
pub struct CloneableService<S: Service + 'static> {
service: Cell<S>,
}
impl<T: 'static> CloneableService<T> {
pub fn new<Request>(service: T) -> Self
where
T: Service<Request>,
{
impl<S: Service + 'static> CloneableService<S> {
pub fn new(service: S) -> Self {
Self {
service: Cell::new(service),
_t: PhantomData,
}
}
}
impl<T: 'static> Clone for CloneableService<T> {
impl<S: Service + 'static> Clone for CloneableService<S> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
_t: PhantomData,
}
}
}
impl<T: 'static, Request> Service<Request> for CloneableService<T>
where
T: Service<Request>,
{
type Response = T::Response;
type Error = T::Error;
type Future = T::Future;
impl<S: Service + 'static> Service for CloneableService<S> {
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.borrow_mut().poll_ready()
}
fn call(&mut self, req: Request) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
self.service.borrow_mut().call(req)
}
}

View File

@@ -1,8 +1,7 @@
use std::fmt;
use bytes::BytesMut;
use futures::{try_ready, Async, Poll, Sink, StartSend, Stream};
use log::trace;
use futures::{Async, Poll, Sink, StartSend, Stream};
use tokio_codec::Decoder;
use tokio_io::AsyncRead;
@@ -134,7 +133,7 @@ where
pub fn framed_read2<T>(inner: T) -> FramedRead2<T> {
FramedRead2 {
inner,
inner: inner,
eof: false,
is_readable: false,
buffer: BytesMut::with_capacity(INITIAL_CAPACITY),
@@ -147,9 +146,9 @@ pub fn framed_read2_with_buffer<T>(inner: T, mut buf: BytesMut) -> FramedRead2<T
buf.reserve(bytes_to_reserve);
}
FramedRead2 {
inner,
inner: inner,
eof: false,
is_readable: !buf.is_empty(),
is_readable: buf.len() > 0,
buffer: buf,
}
}
@@ -188,13 +187,13 @@ where
// readable again, at which point the stream is terminated.
if self.is_readable {
if self.eof {
let frame = self.inner.decode_eof(&mut self.buffer)?;
let frame = try!(self.inner.decode_eof(&mut self.buffer));
return Ok(Async::Ready(frame));
}
trace!("attempting to decode a frame");
if let Some(frame) = self.inner.decode(&mut self.buffer)? {
if let Some(frame) = try!(self.inner.decode(&mut self.buffer)) {
trace!("frame decoded from buffer");
return Ok(Async::Ready(Some(frame)));
}

View File

@@ -2,8 +2,7 @@ use std::fmt;
use std::io::{self, Read};
use bytes::BytesMut;
use futures::{try_ready, Async, AsyncSink, Poll, Sink, StartSend, Stream};
use log::trace;
use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream};
use tokio_codec::{Decoder, Encoder};
use tokio_io::{AsyncRead, AsyncWrite};
@@ -112,7 +111,7 @@ where
}
fn close(&mut self) -> Poll<(), Self::SinkError> {
Ok(self.inner.close()?)
Ok(try!(self.inner.close()))
}
}
@@ -268,12 +267,12 @@ where
try_ready!(self.inner.poll_flush());
trace!("framed transport flushed");
Ok(Async::Ready(()))
return Ok(Async::Ready(()));
}
fn close(&mut self) -> Poll<(), Self::SinkError> {
try_ready!(self.poll_complete());
Ok(self.inner.shutdown()?)
Ok(try!(self.inner.shutdown()))
}
}

View File

@@ -4,14 +4,15 @@ use std::net::{IpAddr, SocketAddr};
use std::time::Duration;
use std::{fmt, io};
use actix_service::{NewService, Service};
use futures::future::{ok, Either, FutureResult};
use futures::{try_ready, Async, Future, Poll};
use futures::{Async, Future, Poll};
use tokio_tcp::{ConnectFuture, TcpStream};
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
use trust_dns_resolver::system_conf::read_system_conf;
use super::resolver::{RequestHost, ResolveError, Resolver, ResolverFuture};
use super::service::{NewService, Service};
/// Port of the request
pub trait RequestPort {
@@ -118,8 +119,8 @@ impl Connect {
impl RequestHost for Connect {
fn host(&self) -> &str {
match self.kind {
ConnectKind::Host { ref host, .. } => host,
ConnectKind::Addr { ref host, .. } => host,
ConnectKind::Host { ref host, port: _ } => host,
ConnectKind::Addr { ref host, addr: _ } => host,
}
}
}
@@ -127,8 +128,8 @@ impl RequestHost for Connect {
impl RequestPort for Connect {
fn port(&self) -> u16 {
match self.kind {
ConnectKind::Host { port, .. } => port,
ConnectKind::Addr { addr, .. } => addr.port(),
ConnectKind::Host { host: _, port } => port,
ConnectKind::Addr { host: _, addr } => addr.port(),
}
}
}
@@ -167,8 +168,8 @@ impl Connector {
/// Create new connector with custom resolver
pub fn with_resolver(
resolver: Resolver<Connect>,
) -> impl Service<Connect, Response = (Connect, TcpStream), Error = ConnectorError> + Clone
{
) -> impl Service<Request = Connect, Response = (Connect, TcpStream), Error = ConnectorError>
+ Clone {
Connector { resolver }
}
@@ -177,7 +178,7 @@ impl Connector {
cfg: ResolverConfig,
opts: ResolverOpts,
) -> impl NewService<
Connect,
Request = Connect,
Response = (Connect, TcpStream),
Error = ConnectorError,
InitError = E,
@@ -194,7 +195,8 @@ impl Clone for Connector {
}
}
impl Service<Connect> for Connector {
impl Service for Connector {
type Request = Connect;
type Response = (Connect, TcpStream);
type Error = ConnectorError;
type Future = Either<ConnectorFuture, ConnectorTcpFuture>;
@@ -203,13 +205,13 @@ impl Service<Connect> for Connector {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Connect) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
match req.kind {
ConnectKind::Host { .. } => Either::A(ConnectorFuture {
ConnectKind::Host { host: _, port: _ } => Either::A(ConnectorFuture {
fut: self.resolver.call(req),
fut2: None,
}),
ConnectKind::Addr { addr, .. } => {
ConnectKind::Addr { host: _, addr } => {
let mut addrs = VecDeque::new();
addrs.push_back(addr.ip());
Either::B(ConnectorTcpFuture {
@@ -271,7 +273,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 Error = io::Error;
type Future = TcpConnectorResponse<T>;
@@ -280,7 +283,7 @@ impl<T: RequestPort> Service<(T, VecDeque<IpAddr>)> for TcpConnector<T> {
Ok(Async::Ready(()))
}
fn call(&mut self, (req, addrs): (T, VecDeque<IpAddr>)) -> Self::Future {
fn call(&mut self, (req, addrs): Self::Request) -> Self::Future {
TcpConnectorResponse::new(req, addrs)
}
}
@@ -351,7 +354,8 @@ impl DefaultConnector {
}
}
impl Service<Connect> for DefaultConnector {
impl Service for DefaultConnector {
type Request = Connect;
type Response = TcpStream;
type Error = ConnectorError;
type Future = DefaultConnectorFuture;
@@ -360,7 +364,7 @@ impl Service<Connect> for DefaultConnector {
self.0.poll_ready()
}
fn call(&mut self, req: Connect) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
DefaultConnectorFuture {
fut: self.0.call(req),
}

View File

@@ -9,6 +9,7 @@ use futures::task::AtomicTask;
/// Counter could be cloned, total ncount is shared across all clones.
pub struct Counter(Rc<CounterInner>);
#[derive(Debug)]
struct CounterInner {
count: Cell<usize>,
capacity: usize,
@@ -40,6 +41,7 @@ impl Counter {
}
}
#[derive(Debug)]
pub struct CounterGuard(Rc<CounterInner>);
impl CounterGuard {
@@ -57,11 +59,7 @@ impl Drop for CounterGuard {
impl CounterInner {
fn inc(&self) {
let num = self.count.get() + 1;
self.count.set(num);
if num == self.capacity {
self.task.register();
}
self.count.set(self.count.get() + 1);
}
fn dec(&self) {
@@ -73,6 +71,10 @@ impl CounterInner {
}
fn available(&self) -> bool {
self.count.get() < self.capacity
let avail = self.count.get() < self.capacity;
if !avail {
self.task.register();
}
avail
}
}

View File

@@ -1,6 +1,7 @@
//! Contains `Either` service and related types and functions.
use actix_service::{NewService, Service};
use futures::{future, try_ready, Async, Future, Poll};
use futures::{future, Async, Future, Poll};
use super::service::{NewService, Service};
/// Combine two different service types into a single type.
///
@@ -12,11 +13,12 @@ pub enum EitherService<A, B> {
B(B),
}
impl<A, B, Request> Service<Request> for EitherService<A, B>
impl<A, B> Service for EitherService<A, B>
where
A: Service<Request>,
B: Service<Request, Response = A::Response, Error = A::Error>,
A: Service,
B: Service<Request = A::Request, Response = A::Response, Error = A::Error>,
{
type Request = A::Request;
type Response = A::Response;
type Error = A::Error;
type Future = future::Either<A::Future, B::Future>;
@@ -28,7 +30,7 @@ where
}
}
fn call(&mut self, req: Request) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
match self {
EitherService::A(ref mut inner) => future::Either::A(inner.call(req)),
EitherService::B(ref mut inner) => future::Either::B(inner.call(req)),
@@ -42,16 +44,22 @@ pub enum Either<A, B> {
B(B),
}
impl<A, B, Request> NewService<Request> for Either<A, B>
impl<A, B> NewService for Either<A, B>
where
A: NewService<Request>,
B: NewService<Request, Response = A::Response, Error = A::Error, InitError = A::InitError>,
A: NewService,
B: NewService<
Request = A::Request,
Response = A::Response,
Error = A::Error,
InitError = A::InitError,
>,
{
type Request = A::Request;
type Response = A::Response;
type Error = A::Error;
type InitError = A::InitError;
type Service = EitherService<A::Service, B::Service>;
type Future = EitherNewService<A, B, Request>;
type Future = EitherNewService<A, B>;
fn new_service(&self) -> Self::Future {
match self {
@@ -62,15 +70,20 @@ where
}
#[doc(hidden)]
pub enum EitherNewService<A: NewService<R>, B: NewService<R>, R> {
pub enum EitherNewService<A: NewService, B: NewService> {
A(A::Future),
B(B::Future),
}
impl<A, B, Request> Future for EitherNewService<A, B, Request>
impl<A, B> Future for EitherNewService<A, B>
where
A: NewService<Request>,
B: NewService<Request, Response = A::Response, Error = A::Error, InitError = A::InitError>,
A: NewService,
B: NewService<
Request = A::Request,
Response = A::Response,
Error = A::Error,
InitError = A::InitError,
>,
{
type Item = EitherService<A::Service, B::Service>;
type Error = A::InitError;

View File

@@ -3,14 +3,14 @@ use std::marker::PhantomData;
use std::mem;
use actix;
use actix_service::{IntoNewService, IntoService, NewService, Service};
use futures::future::{ok, FutureResult};
use futures::unsync::mpsc;
use futures::{Async, AsyncSink, Future, Poll, Sink, Stream};
use tokio_codec::{Decoder, Encoder};
use tokio_io::{AsyncRead, AsyncWrite};
use crate::codec::Framed;
use codec::Framed;
use service::{IntoNewService, IntoService, NewService, Service};
type Request<U> = <U as Decoder>::Item;
type Response<U> = <U as Encoder>::Item;
@@ -24,13 +24,13 @@ impl<S, T, U> FramedNewService<S, T, U>
where
T: AsyncRead + AsyncWrite,
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,
S: NewService<Request = Request<U>, Response = Response<U>> + Clone,
<<S as NewService>::Service as Service>::Future: 'static,
<<S as NewService>::Service as Service>::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
{
pub fn new<F1: IntoNewService<S, Request<U>>>(factory: F1) -> Self {
pub fn new<F1: IntoNewService<S>>(factory: F1) -> Self {
Self {
factory: factory.into_new_service(),
_t: PhantomData,
@@ -50,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
T: AsyncRead + AsyncWrite,
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,
S: NewService<Request = Request<U>, Response = Response<U>> + Clone,
<<S as NewService>::Service as Service>::Future: 'static,
<<S as NewService>::Service as Service>::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
{
type Request = Framed<T, U>;
type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError;
type InitError = S::InitError;
@@ -91,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
T: AsyncRead + AsyncWrite,
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,
S: NewService<Request = Request<U>, Response = Response<U>>,
<<S as NewService>::Service as Service>::Future: 'static,
<<S as NewService>::Service as Service>::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
{
type Request = Framed<T, U>;
type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError;
type Future = FramedServiceResponseFuture<S, T, U>;
@@ -109,7 +111,7 @@ where
Ok(Async::Ready(()))
}
fn call(&mut self, req: Framed<T, U>) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
FramedServiceResponseFuture {
fut: self.factory.new_service(),
@@ -123,9 +125,9 @@ pub struct FramedServiceResponseFuture<S, T, U>
where
T: AsyncRead + AsyncWrite,
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,
S: NewService<Request = Request<U>, Response = Response<U>>,
<<S as NewService>::Service as Service>::Future: 'static,
<<S as NewService>::Service as Service>::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
{
@@ -137,9 +139,9 @@ impl<S, T, U> Future for FramedServiceResponseFuture<S, T, U>
where
T: AsyncRead + AsyncWrite,
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,
S: NewService<Request = Request<U>, Response = Response<U>>,
<<S as NewService>::Service as Service>::Future: 'static,
<<S as NewService>::Service as Service>::Error: 'static,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: 'static,
{
@@ -174,7 +176,7 @@ impl<E, U: Encoder + Decoder> From<E> for FramedTransportError<E, U> {
/// and pass then to the service.
pub struct FramedTransport<S, T, U>
where
S: Service<Request<U>, Response = Response<U>>,
S: Service,
T: AsyncRead + AsyncWrite,
U: Encoder + Decoder,
{
@@ -188,7 +190,7 @@ where
flushed: bool,
}
enum TransportState<S: Service<Request<U>>, U: Encoder + Decoder> {
enum TransportState<S: Service, U: Encoder + Decoder> {
Processing,
Error(FramedTransportError<S::Error, U>),
EncoderError(FramedTransportError<S::Error, U>),
@@ -199,12 +201,12 @@ impl<S, T, U> FramedTransport<S, T, U>
where
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
S: Service<Request<U>, Response = Response<U>>,
S: Service<Request = Request<U>, Response = Response<U>>,
S::Future: 'static,
S::Error: 'static,
<U as Encoder>::Error: 'static,
{
pub fn new<F: IntoService<S, Request<U>>>(framed: Framed<T, U>, service: F) -> Self {
pub fn new<F: IntoService<S>>(framed: Framed<T, U>, service: F) -> Self {
let (write_tx, write_rx) = mpsc::channel(16);
FramedTransport {
framed,
@@ -246,7 +248,7 @@ impl<S, T, U> FramedTransport<S, T, U>
where
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
S: Service<Request<U>, Response = Response<U>>,
S: Service<Request = Request<U>, Response = Response<U>>,
S::Future: 'static,
S::Error: 'static,
<U as Encoder>::Item: 'static,
@@ -300,10 +302,10 @@ where
}
}
}
Ok(Async::NotReady) => false,
Ok(Async::NotReady) => return false,
Err(err) => {
self.state = TransportState::Error(FramedTransportError::Service(err));
true
return true;
}
}
}
@@ -375,7 +377,7 @@ impl<S, T, U> Future for FramedTransport<S, T, U>
where
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
S: Service<Request<U>, Response = Response<U>>,
S: Service<Request = Request<U>, Response = Response<U>>,
S::Future: 'static,
S::Error: 'static,
<U as Encoder>::Item: 'static,
@@ -387,22 +389,26 @@ where
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match mem::replace(&mut self.state, TransportState::Processing) {
TransportState::Processing => {
if self.poll_service() || self.poll_response() {
self.poll()
} else {
Ok(Async::NotReady)
if self.poll_service() {
return self.poll();
}
if self.poll_response() {
return self.poll();
}
return Ok(Async::NotReady);
}
TransportState::Error(err) => {
if self.poll_response() || self.flushed {
Err(err)
} else {
self.state = TransportState::Error(err);
Ok(Async::NotReady)
if self.poll_response() {
return Err(err);
}
if self.flushed {
return Err(err);
}
self.state = TransportState::Error(err);
return Ok(Async::NotReady);
}
TransportState::EncoderError(err) => Err(err),
TransportState::Stopping => Ok(Async::Ready(())),
TransportState::EncoderError(err) => return Err(err),
TransportState::Stopping => return Ok(Async::Ready(())),
}
}
}
@@ -431,12 +437,13 @@ where
}
}
impl<T, U, F> NewService<T> for IntoFramed<T, U, F>
impl<T, U, F> NewService for IntoFramed<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
type Request = T;
type Response = Framed<T, U>;
type Error = ();
type InitError = ();
@@ -461,12 +468,13 @@ where
_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
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
type Request = T;
type Response = Framed<T, U>;
type Error = ();
type Future = FutureResult<Self::Response, Self::Error>;
@@ -475,7 +483,7 @@ where
Ok(Async::Ready(()))
}
fn call(&mut self, req: T) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
ok(Framed::new(req, (self.factory)()))
}
}

View File

@@ -1,7 +1,7 @@
use actix_service::{IntoNewService, IntoService, NewService, Service};
use futures::{try_ready, Async, Future, Poll};
use futures::{Async, Future, Poll};
use super::counter::{Counter, CounterGuard};
use super::service::{IntoNewService, IntoService, NewService, Service};
/// InFlight - new service for service that can limit number of in-flight
/// async requests.
@@ -12,12 +12,11 @@ pub struct InFlight<T> {
max_inflight: usize,
}
impl<T> InFlight<T> {
pub fn new<F, Request>(factory: F) -> Self
where
T: NewService<Request>,
F: IntoNewService<T, Request>,
{
impl<T> InFlight<T>
where
T: NewService,
{
pub fn new<F: IntoNewService<T>>(factory: F) -> Self {
Self {
factory: factory.into_new_service(),
max_inflight: 15,
@@ -33,15 +32,16 @@ impl<T> InFlight<T> {
}
}
impl<T, Request> NewService<Request> for InFlight<T>
impl<T> NewService for InFlight<T>
where
T: NewService<Request>,
T: NewService,
{
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type InitError = T::InitError;
type Service = InFlightService<T::Service>;
type Future = InFlightResponseFuture<T, Request>;
type Future = InFlightResponseFuture<T>;
fn new_service(&self) -> Self::Future {
InFlightResponseFuture {
@@ -51,12 +51,12 @@ where
}
}
pub struct InFlightResponseFuture<T: NewService<Request>, Request> {
pub struct InFlightResponseFuture<T: NewService> {
fut: T::Future,
max_inflight: usize,
}
impl<T: NewService<Request>, Request> Future for InFlightResponseFuture<T, Request> {
impl<T: NewService> Future for InFlightResponseFuture<T> {
type Item = InFlightService<T::Service>;
type Error = T::InitError;
@@ -73,23 +73,15 @@ pub struct InFlightService<T> {
count: Counter,
}
impl<T> InFlightService<T> {
pub fn new<F, Request>(service: F) -> Self
where
T: Service<Request>,
F: IntoService<T, Request>,
{
impl<T: Service> InFlightService<T> {
pub fn new<F: IntoService<T>>(service: F) -> 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>,
{
pub fn with_max_inflight<F: IntoService<T>>(max: usize, service: F) -> Self {
Self {
service: service.into_service(),
count: Counter::new(max),
@@ -97,13 +89,11 @@ impl<T> InFlightService<T> {
}
}
impl<T, Request> Service<Request> for InFlightService<T>
where
T: Service<Request>,
{
impl<T: Service> Service for InFlightService<T> {
type Request = T::Request;
type Response = T::Response;
type Error = T::Error;
type Future = InFlightServiceResponse<T, Request>;
type Future = InFlightServiceResponse<T>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
let res = self.service.poll_ready();
@@ -113,21 +103,22 @@ where
res
}
fn call(&mut self, req: Request) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
InFlightServiceResponse {
fut: self.service.call(req),
_guard: self.count.get(),
guard: self.count.get(),
}
}
}
#[doc(hidden)]
pub struct InFlightServiceResponse<T: Service<Request>, Request> {
pub struct InFlightServiceResponse<T: Service> {
fut: T::Future,
_guard: CounterGuard,
#[allow(dead_code)]
guard: CounterGuard,
}
impl<T: Service<Request>, Request> Future for InFlightServiceResponse<T, Request> {
impl<T: Service> Future for InFlightServiceResponse<T> {
type Item = T::Response;
type Error = T::Error;

View File

@@ -1,11 +1,11 @@
use std::marker::PhantomData;
use std::time::{Duration, Instant};
use actix_service::{NewService, Service};
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use tokio_timer::Delay;
use super::service::{NewService, Service};
use super::time::{LowResTime, LowResTimeService};
use super::Never;
@@ -32,7 +32,7 @@ where
impl<R, E, F> Clone for KeepAlive<R, E, F>
where
F: Clone,
F: Fn() -> E + Clone,
{
fn clone(&self) -> Self {
KeepAlive {
@@ -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
F: Fn() -> E + Clone,
{
type Request = R;
type Response = R;
type Error = E;
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
F: Fn() -> E,
{
type Request = R;
type Response = R;
type Error = E;
type Future = FutureResult<R, E>;
@@ -114,7 +116,7 @@ where
}
}
fn call(&mut self, req: R) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
self.expire = self.time.now() + self.ka;
ok(req)
}

View File

@@ -7,11 +7,51 @@
//! * `rust-tls` - enables ssl support via `rustls` crate
// #![warn(missing_docs)]
#![allow(
clippy::declare_interior_mutable_const,
clippy::borrow_interior_mutable_const
#![cfg_attr(
feature = "cargo-clippy",
allow(declare_interior_mutable_const, borrow_interior_mutable_const)
)]
#[macro_use]
extern crate log;
extern crate bytes;
#[macro_use]
extern crate futures;
extern crate mio;
extern crate net2;
extern crate num_cpus;
extern crate slab;
extern crate tokio;
extern crate tokio_codec;
extern crate tokio_current_thread;
extern crate tokio_io;
extern crate tokio_reactor;
extern crate tokio_tcp;
extern crate tokio_timer;
extern crate tower_service;
extern crate trust_dns_resolver;
#[allow(unused_imports)]
#[macro_use]
extern crate actix;
#[cfg(feature = "tls")]
extern crate native_tls;
#[cfg(feature = "ssl")]
extern crate openssl;
#[cfg(feature = "ssl")]
extern crate tokio_openssl;
#[cfg(feature = "rust-tls")]
extern crate rustls;
#[cfg(feature = "rust-tls")]
extern crate tokio_rustls;
#[cfg(feature = "rust-tls")]
extern crate webpki;
#[cfg(feature = "rust-tls")]
extern crate webpki_roots;
mod cell;
pub mod cloneable;
pub mod codec;
@@ -23,6 +63,7 @@ pub mod inflight;
pub mod keepalive;
pub mod resolver;
pub mod server;
pub mod service;
pub mod ssl;
pub mod stream;
pub mod time;

View File

@@ -4,7 +4,6 @@ use std::net::IpAddr;
use futures::{Async, Future, Poll};
use actix_service::Service;
use tokio_current_thread::spawn;
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
pub use trust_dns_resolver::error::ResolveError;
@@ -12,6 +11,8 @@ use trust_dns_resolver::lookup_ip::LookupIpFuture;
use trust_dns_resolver::system_conf::read_system_conf;
use trust_dns_resolver::{AsyncResolver, Background};
use super::service::Service;
/// Host name of the request
pub trait RequestHost {
fn host(&self) -> &str;
@@ -69,7 +70,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 Error = ResolveError;
type Future = ResolverFuture<T>;
@@ -78,7 +80,7 @@ impl<T: RequestHost> Service<T> for Resolver<T> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: T) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
ResolverFuture::new(req, &self.resolver)
}
}

View File

@@ -3,7 +3,6 @@ use std::time::{Duration, Instant};
use std::{io, net, thread};
use futures::{sync::mpsc, Future};
use log::{error, info};
use mio;
use slab::Slab;
use tokio_timer::Delay;
@@ -135,7 +134,7 @@ fn connection_error(e: &io::Error) -> bool {
}
impl Accept {
#![allow(clippy::too_many_arguments)]
#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
pub(crate) fn start(
rx: sync_mpsc::Receiver<Command>,
cmd_reg: mio::Registration,

View File

@@ -1,12 +1,11 @@
use std::collections::HashMap;
use std::{fmt, io, net};
use actix_service::{IntoNewService, NewService};
use futures::future::{join_all, Future};
use log::error;
use tokio_tcp::TcpStream;
use crate::counter::CounterGuard;
use counter::CounterGuard;
use service::{IntoNewService, NewService};
use super::server::bind_addr;
use super::services::{
@@ -112,7 +111,7 @@ impl InternalServiceFactory for ConfiguredService {
pub(super) trait ServiceRuntimeConfiguration: Send {
fn clone(&self) -> Box<ServiceRuntimeConfiguration>;
fn configure(&self, rt: &mut ServiceRuntime);
fn configure(&self, &mut ServiceRuntime);
}
impl<F> ServiceRuntimeConfiguration for F
@@ -155,8 +154,8 @@ impl ServiceRuntime {
pub fn service<T, F>(&mut self, name: &str, service: F)
where
F: IntoNewService<T, TcpStream>,
T: NewService<TcpStream, Response = ()> + 'static,
F: IntoNewService<T>,
T: NewService<Request = TcpStream, Response = ()> + 'static,
T::Future: 'static,
T::Service: 'static,
T::InitError: fmt::Debug,
@@ -177,7 +176,7 @@ impl ServiceRuntime {
type BoxedNewService = Box<
NewService<
(Option<CounterGuard>, ServerMessage),
Request = (Option<CounterGuard>, ServerMessage),
Response = (),
Error = (),
InitError = (),
@@ -190,14 +189,15 @@ struct ServiceFactory<T> {
inner: T,
}
impl<T> NewService<(Option<CounterGuard>, ServerMessage)> for ServiceFactory<T>
impl<T> NewService for ServiceFactory<T>
where
T: NewService<TcpStream, Response = ()>,
T: NewService<Request = TcpStream, Response = ()>,
T::Future: 'static,
T::Service: 'static,
T::Error: 'static,
T::InitError: fmt::Debug + 'static,
{
type Request = (Option<CounterGuard>, ServerMessage);
type Response = ();
type Error = ();
type InitError = ();

View File

@@ -3,7 +3,6 @@ use std::{io, mem, net};
use futures::sync::{mpsc, mpsc::unbounded};
use futures::{Future, Sink, Stream};
use log::{error, info};
use net2::TcpBuilder;
use num_cpus;
@@ -285,7 +284,7 @@ impl Server {
self.services.iter().map(|v| v.clone_factory()).collect();
Arbiter::new(format!("actix-net-worker-{}", idx)).do_send(Execute::new(move || {
Worker::start(rx1, rx2, services, avail, timeout);
Worker::start(rx1, rx2, services, avail, timeout.clone());
Ok::<_, ()>(())
}));
@@ -377,7 +376,7 @@ impl Handler<StopServer> for Server {
}
if !self.workers.is_empty() {
Response::r#async(rx.into_future().map(|_| ()).map_err(|_| ()))
Response::async(rx.into_future().map(|_| ()).map_err(|_| ()))
} else {
// we need to stop system if server was spawned
if self.exit {

View File

@@ -1,16 +1,15 @@
use std::net;
use std::time::Duration;
use actix_service::{NewService, Service};
use futures::future::{err, ok, FutureResult};
use futures::{Future, Poll};
use log::error;
use tokio_current_thread::spawn;
use tokio_reactor::Handle;
use tokio_tcp::TcpStream;
use super::Token;
use crate::counter::CounterGuard;
use counter::CounterGuard;
use service::{NewService, Service};
/// Server message
pub enum ServerMessage {
@@ -23,13 +22,13 @@ pub enum ServerMessage {
}
pub trait StreamServiceFactory: Send + Clone + 'static {
type NewService: NewService<TcpStream, Response = ()>;
type NewService: NewService<Request = TcpStream, Response = ()>;
fn create(&self) -> Self::NewService;
}
pub trait ServiceFactory: Send + Clone + 'static {
type NewService: NewService<ServerMessage, Response = ()>;
type NewService: NewService<Request = ServerMessage, Response = ()>;
fn create(&self) -> Self::NewService;
}
@@ -44,7 +43,7 @@ pub(crate) trait InternalServiceFactory: Send {
pub(crate) type BoxedServerService = Box<
Service<
(Option<CounterGuard>, ServerMessage),
Request = (Option<CounterGuard>, ServerMessage),
Response = (),
Error = (),
Future = FutureResult<(), ()>,
@@ -61,12 +60,13 @@ impl<T> StreamService<T> {
}
}
impl<T> Service<(Option<CounterGuard>, ServerMessage)> for StreamService<T>
impl<T> Service for StreamService<T>
where
T: Service<TcpStream, Response = ()>,
T: Service<Request = TcpStream, Response = ()>,
T::Future: 'static,
T::Error: 'static,
{
type Request = (Option<CounterGuard>, ServerMessage);
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;
@@ -83,9 +83,9 @@ where
});
if let Ok(stream) = stream {
spawn(self.service.call(stream).map_err(|_| ()).map(move |val| {
spawn(self.service.call(stream).then(move |res| {
drop(guard);
val
res.map_err(|_| ())
}));
ok(())
} else {
@@ -107,12 +107,13 @@ impl<T> ServerService<T> {
}
}
impl<T> Service<(Option<CounterGuard>, ServerMessage)> for ServerService<T>
impl<T> Service for ServerService<T>
where
T: Service<ServerMessage, Response = ()>,
T: Service<Request = ServerMessage, Response = ()>,
T::Future: 'static,
T::Error: 'static,
{
type Request = (Option<CounterGuard>, ServerMessage);
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;
@@ -122,9 +123,9 @@ where
}
fn call(&mut self, (guard, req): (Option<CounterGuard>, ServerMessage)) -> Self::Future {
spawn(self.service.call(req).map_err(|_| ()).map(move |val| {
spawn(self.service.call(req).then(move |res| {
drop(guard);
val
res.map_err(|_| ())
}));
ok(())
}
@@ -239,7 +240,7 @@ impl InternalServiceFactory for Box<InternalServiceFactory> {
impl<F, T> ServiceFactory for F
where
F: Fn() -> T + Send + Clone + 'static,
T: NewService<ServerMessage, Response = ()>,
T: NewService<Request = ServerMessage, Response = ()>,
{
type NewService = T;
@@ -251,7 +252,7 @@ where
impl<F, T> StreamServiceFactory for F
where
F: Fn() -> T + Send + Clone + 'static,
T: NewService<TcpStream, Response = ()>,
T: NewService<Request = TcpStream, Response = ()>,
{
type NewService = T;

View File

@@ -5,7 +5,6 @@ use std::{mem, net, time};
use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use futures::sync::oneshot;
use futures::{future, Async, Future, Poll, Stream};
use log::{error, info, trace};
use tokio_current_thread::spawn;
use tokio_timer::{sleep, Delay};
@@ -15,7 +14,7 @@ use actix::{Arbiter, Message};
use super::accept::AcceptNotify;
use super::services::{BoxedServerService, InternalServiceFactory, ServerMessage};
use super::Token;
use crate::counter::Counter;
use counter::Counter;
pub(crate) struct WorkerCommand(Conn);
@@ -194,7 +193,7 @@ impl Worker {
let timeout = self.shutdown_timeout;
self.services.iter_mut().for_each(move |h| {
if let Some(h) = h {
let _ = h.1.call((None, ServerMessage::Shutdown(timeout)));
let _ = h.1.call((None, ServerMessage::Shutdown(timeout.clone())));
}
});
}
@@ -251,33 +250,36 @@ impl Future for Worker {
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
// `StopWorker` message handler
if let Ok(Async::Ready(Some(StopCommand { graceful, result }))) = self.rx2.poll() {
self.availability.set(false);
let num = num_connections();
if num == 0 {
info!("Shutting down worker, 0 connections");
let _ = result.send(true);
return Ok(Async::Ready(()));
} else if graceful {
self.shutdown(false);
match self.rx2.poll() {
Ok(Async::Ready(Some(StopCommand { graceful, result }))) => {
self.availability.set(false);
let num = num_connections();
if num != 0 {
info!("Graceful worker shutdown, {} connections", num);
self.state = WorkerState::Shutdown(
sleep(time::Duration::from_secs(1)),
sleep(self.shutdown_timeout),
result,
);
} else {
if num == 0 {
info!("Shutting down worker, 0 connections");
let _ = result.send(true);
return Ok(Async::Ready(()));
} else if graceful {
self.shutdown(false);
let num = num_connections();
if num != 0 {
info!("Graceful worker shutdown, {} connections", num);
self.state = WorkerState::Shutdown(
sleep(time::Duration::from_secs(1)),
sleep(self.shutdown_timeout),
result,
);
} else {
let _ = result.send(true);
return Ok(Async::Ready(()));
}
} else {
info!("Force shutdown worker, {} connections", num);
self.shutdown(true);
let _ = result.send(false);
return Ok(Async::Ready(()));
}
} else {
info!("Force shutdown worker, {} connections", num);
self.shutdown(true);
let _ = result.send(false);
return Ok(Async::Ready(()));
}
_ => (),
}
let state = mem::replace(&mut self.state, WorkerState::None);

View File

@@ -1,7 +1,7 @@
use futures::{try_ready, Async, Future, Poll};
use futures::{Async, Future, Poll};
use super::{IntoNewService, NewService, Service};
use crate::cell::Cell;
use cell::Cell;
/// Service for the `and_then` combinator, chaining a computation onto the end
/// of another service which completes successfully.
@@ -12,20 +12,21 @@ pub struct AndThen<A, B> {
b: Cell<B>,
}
impl<A, B> AndThen<A, B> {
impl<A, B> AndThen<A, B>
where
A: Service,
B: Service<Request = A::Response, Error = A::Error>,
{
/// Create new `AndThen` combinator
pub fn new<Request>(a: A, b: B) -> Self
where
A: Service<Request>,
B: Service<A::Response, Error = A::Error>,
{
pub fn new(a: A, b: B) -> Self {
Self { a, b: Cell::new(b) }
}
}
impl<A, B> Clone for AndThen<A, B>
where
A: Clone,
A: Service + Clone,
B: Service<Request = A::Response, Error = A::Error>,
{
fn clone(&self) -> Self {
AndThen {
@@ -35,53 +36,55 @@ where
}
}
impl<A, B, Request> Service<Request> for AndThen<A, B>
impl<A, B> Service for AndThen<A, B>
where
A: Service<Request>,
B: Service<A::Response, Error = A::Error>,
A: Service,
B: Service<Request = A::Response, Error = A::Error>,
{
type Request = A::Request;
type Response = B::Response;
type Error = A::Error;
type Future = AndThenFuture<A, B, Request>;
type Future = AndThenFuture<A, B>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
try_ready!(self.a.poll_ready());
self.b.get_mut().poll_ready()
let _ = try_ready!(self.a.poll_ready());
self.b.borrow_mut().poll_ready()
}
fn call(&mut self, req: Request) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
AndThenFuture::new(self.a.call(req), self.b.clone())
}
}
pub struct AndThenFuture<A, B, Request>
pub struct AndThenFuture<A, B>
where
A: Service<Request>,
B: Service<A::Response, Error = A::Error>,
A: Service,
B: Service<Request = A::Response, Error = A::Error>,
{
b: Cell<B>,
fut_b: Option<B::Future>,
fut_a: A::Future,
fut_a: Option<A::Future>,
}
impl<A, B, Request> AndThenFuture<A, B, Request>
impl<A, B> AndThenFuture<A, B>
where
A: Service<Request>,
B: Service<A::Response, Error = A::Error>,
A: Service,
B: Service<Request = A::Response, Error = A::Error>,
{
fn new(fut_a: A::Future, b: Cell<B>) -> Self {
fn new(a: A::Future, b: Cell<B>) -> Self {
AndThenFuture {
b,
fut_a,
fut_a: Some(a),
fut_b: None,
}
}
}
impl<A, B, Request> Future for AndThenFuture<A, B, Request>
impl<A, B> Future for AndThenFuture<A, B>
where
A: Service<Request>,
B: Service<A::Response, Error = A::Error>,
A: Service,
B: Service<Request = A::Response, Error = A::Error>,
B::Error: Into<A::Error>,
{
type Item = B::Response;
type Error = A::Error;
@@ -91,9 +94,10 @@ where
return fut.poll();
}
match self.fut_a.poll() {
match self.fut_a.as_mut().expect("actix-net bug").poll() {
Ok(Async::Ready(resp)) => {
self.fut_b = Some(self.b.get_mut().call(resp));
let _ = self.fut_a.take();
self.fut_b = Some(self.b.borrow_mut().call(resp));
self.poll()
}
Ok(Async::NotReady) => Ok(Async::NotReady),
@@ -108,13 +112,13 @@ pub struct AndThenNewService<A, B> {
b: B,
}
impl<A, B> AndThenNewService<A, B> {
impl<A, B> AndThenNewService<A, B>
where
A: NewService,
B: NewService,
{
/// Create new `AndThen` combinator
pub fn new<Request, F: IntoNewService<B, A::Response>>(a: A, f: F) -> Self
where
A: NewService<Request>,
B: NewService<A::Response, Error = A::Error, InitError = A::InitError>,
{
pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self {
Self {
a,
b: f.into_new_service(),
@@ -122,17 +126,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
A: NewService<Request>,
B: NewService<A::Response, Error = A::Error, InitError = A::InitError>,
A: NewService,
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
{
type Request = A::Request;
type Response = B::Response;
type Error = A::Error;
type Service = AndThen<A::Service, B::Service>;
type InitError = A::InitError;
type Future = AndThenNewServiceFuture<A, B, Request>;
type Future = AndThenNewServiceFuture<A, B>;
fn new_service(&self) -> Self::Future {
AndThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
@@ -141,8 +146,8 @@ where
impl<A, B> Clone for AndThenNewService<A, B>
where
A: Clone,
B: Clone,
A: NewService + Clone,
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError> + Clone,
{
fn clone(&self) -> Self {
Self {
@@ -152,10 +157,10 @@ where
}
}
pub struct AndThenNewServiceFuture<A, B, Request>
pub struct AndThenNewServiceFuture<A, B>
where
A: NewService<Request>,
B: NewService<A::Response>,
A: NewService,
B: NewService,
{
fut_b: B::Future,
fut_a: A::Future,
@@ -163,10 +168,10 @@ where
b: Option<B::Service>,
}
impl<A, B, Request> AndThenNewServiceFuture<A, B, Request>
impl<A, B> AndThenNewServiceFuture<A, B>
where
A: NewService<Request>,
B: NewService<A::Response>,
A: NewService,
B: NewService,
{
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
AndThenNewServiceFuture {
@@ -178,10 +183,10 @@ where
}
}
impl<A, B, Request> Future for AndThenNewServiceFuture<A, B, Request>
impl<A, B> Future for AndThenNewServiceFuture<A, B>
where
A: NewService<Request>,
B: NewService<A::Response, Error = A::Error, InitError = A::InitError>,
A: NewService,
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
{
type Item = AndThen<A::Service, B::Service>;
type Error = A::InitError;
@@ -218,10 +223,11 @@ mod tests {
use std::rc::Rc;
use super::*;
use crate::{NewService, Service};
use service::{NewServiceExt, Service, ServiceExt};
struct Srv1(Rc<Cell<usize>>);
impl Service<&'static str> for Srv1 {
impl Service for Srv1 {
type Request = &'static str;
type Response = &'static str;
type Error = ();
type Future = FutureResult<Self::Response, ()>;
@@ -231,7 +237,7 @@ mod tests {
Ok(Async::Ready(()))
}
fn call(&mut self, req: &'static str) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
ok(req)
}
}
@@ -239,7 +245,8 @@ mod tests {
#[derive(Clone)]
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 Error = ();
type Future = FutureResult<Self::Response, ()>;
@@ -249,7 +256,7 @@ mod tests {
Ok(Async::Ready(()))
}
fn call(&mut self, req: &'static str) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
ok((req, "srv2"))
}
}

View File

@@ -5,23 +5,21 @@ use futures::{Async, Future, IntoFuture, Poll};
use super::{IntoNewService, IntoService, NewService, Service};
/// `Apply` service combinator
pub struct Apply<T, F, In, Out, Request>
where
T: Service<Request>,
{
pub struct Apply<T, F, R, Req> {
service: T,
f: F,
r: PhantomData<(In, Out, Request)>,
r: PhantomData<(Req, R)>,
}
impl<T, F, In, Out, Request> Apply<T, F, In, Out, Request>
impl<T, F, R, Req> Apply<T, F, R, Req>
where
T: Service<Request>,
F: Fn(In, &mut T) -> Out,
Out: IntoFuture,
T: Service,
T::Error: Into<<R::Future as Future>::Error>,
F: Fn(Req, &mut T) -> R,
R: IntoFuture,
{
/// Create new `Apply` combinator
pub fn new<I: IntoService<T, Request>>(service: I, f: F) -> Self {
pub fn new<I: IntoService<T>>(service: I, f: F) -> Self {
Self {
service: service.into_service(),
f,
@@ -30,10 +28,12 @@ where
}
}
impl<T, F, In, Out, Request> Clone for Apply<T, F, In, Out, Request>
impl<T, F, R, Req> Clone for Apply<T, F, R, Req>
where
T: Service<Request> + Clone,
F: Clone,
T: Service + Clone,
T::Error: Into<<R::Future as Future>::Error>,
F: Fn(Req, &mut T) -> R + Clone,
R: IntoFuture,
{
fn clone(&self) -> Self {
Apply {
@@ -44,43 +44,42 @@ where
}
}
impl<T, F, In, Out, Request> Service<In> for Apply<T, F, In, Out, Request>
impl<T, F, R, Req> Service for Apply<T, F, R, Req>
where
T: Service<Request, Error = Out::Error>,
F: Fn(In, &mut T) -> Out,
Out: IntoFuture,
T: Service,
T::Error: Into<<R::Future as Future>::Error>,
F: Fn(Req, &mut T) -> R,
R: IntoFuture,
{
type Response = Out::Item;
type Error = Out::Error;
type Future = Out::Future;
type Request = Req;
type Response = <R::Future as Future>::Item;
type Error = <R::Future as Future>::Error;
type Future = R::Future;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready()
self.service.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()
}
}
/// `ApplyNewService` new service combinator
pub struct ApplyNewService<T, F, In, Out, Request>
where
T: NewService<Request>,
{
pub struct ApplyNewService<T, F, R, Req> {
service: T,
f: F,
r: PhantomData<(In, Out, Request)>,
r: PhantomData<Fn(Req) -> R>,
}
impl<T, F, In, Out, Request> ApplyNewService<T, F, In, Out, Request>
impl<T, F, R, Req> ApplyNewService<T, F, R, Req>
where
T: NewService<Request>,
F: Fn(In, &mut T::Service) -> Out,
Out: IntoFuture,
T: NewService,
F: Fn(Req, &mut T::Service) -> R,
R: IntoFuture,
{
/// Create new `ApplyNewService` new service instance
pub fn new<F1: IntoNewService<T, Request>>(service: F1, f: F) -> Self {
pub fn new<F1: IntoNewService<T>>(service: F1, f: F) -> Self {
Self {
f,
service: service.into_new_service(),
@@ -89,11 +88,11 @@ where
}
}
impl<T, F, In, Out, Request> Clone for ApplyNewService<T, F, In, Out, Request>
impl<T, F, R, Req> Clone for ApplyNewService<T, F, R, Req>
where
T: NewService<Request> + Clone,
F: Fn(Out, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
T: NewService + Clone,
F: Fn(Req, &mut T::Service) -> R + Clone,
R: IntoFuture,
{
fn clone(&self) -> Self {
Self {
@@ -104,40 +103,42 @@ where
}
}
impl<T, F, In, Out, Request> NewService<In> for ApplyNewService<T, F, In, Out, Request>
impl<T, F, R, Req> NewService for ApplyNewService<T, F, R, Req>
where
T: NewService<Request, Error = Out::Error>,
F: Fn(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
T: NewService,
T::Error: Into<<R::Future as Future>::Error>,
F: Fn(Req, &mut T::Service) -> R + Clone,
R: IntoFuture,
{
type Response = Out::Item;
type Error = Out::Error;
type Service = Apply<T::Service, F, In, Out, Request>;
type Request = Req;
type Response = <R::Future as Future>::Item;
type Error = <R::Future as Future>::Error;
type Service = Apply<T::Service, F, R, Req>;
type InitError = T::InitError;
type Future = ApplyNewServiceFuture<T, F, In, Out, Request>;
type Future = ApplyNewServiceFuture<T, F, R, Req>;
fn new_service(&self) -> Self::Future {
ApplyNewServiceFuture::new(self.service.new_service(), self.f.clone())
}
}
pub struct ApplyNewServiceFuture<T, F, In, Out, Request>
pub struct ApplyNewServiceFuture<T, F, R, Req>
where
T: NewService<Request>,
F: Fn(In, &mut T::Service) -> Out,
Out: IntoFuture,
T: NewService,
F: Fn(Req, &mut T::Service) -> R,
R: IntoFuture,
{
fut: T::Future,
f: Option<F>,
r: PhantomData<(In, Out)>,
r: PhantomData<Fn(Req) -> R>,
}
impl<T, F, In, Out, Request> ApplyNewServiceFuture<T, F, In, Out, Request>
impl<T, F, R, Req> ApplyNewServiceFuture<T, F, R, Req>
where
T: NewService<Request>,
F: Fn(In, &mut T::Service) -> Out,
Out: IntoFuture,
T: NewService,
F: Fn(Req, &mut T::Service) -> R,
R: IntoFuture,
{
fn new(fut: T::Future, f: F) -> Self {
ApplyNewServiceFuture {
@@ -148,13 +149,14 @@ where
}
}
impl<T, F, In, Out, Request> Future for ApplyNewServiceFuture<T, F, In, Out, Request>
impl<T, F, R, Req> Future for ApplyNewServiceFuture<T, F, R, Req>
where
T: NewService<Request>,
F: Fn(In, &mut T::Service) -> Out,
Out: IntoFuture,
T: NewService,
T::Error: Into<<R::Future as Future>::Error>,
F: Fn(Req, &mut T::Service) -> R,
R: IntoFuture,
{
type Item = Apply<T::Service, F, In, Out, Request>;
type Item = Apply<T::Service, F, R, Req>;
type Error = T::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@@ -171,11 +173,14 @@ mod tests {
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use crate::{IntoNewService, IntoService, NewService, Service};
use service::{
IntoNewService, IntoService, NewService, NewServiceExt, Service, ServiceExt,
};
#[derive(Clone)]
struct Srv;
impl Service<()> for Srv {
impl Service for Srv {
type Request = ();
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;

View File

@@ -42,11 +42,12 @@ where
}
}
impl<F, Req, Resp, E, Fut> Service<Req> for FnService<F, Req, Resp, E, Fut>
impl<F, Req, Resp, E, Fut> Service for FnService<F, Req, Resp, E, Fut>
where
F: Fn(Req) -> Fut,
Fut: IntoFuture<Item = Resp, Error = E>,
{
type Request = Req;
type Response = Resp;
type Error = E;
type Future = Fut::Future;
@@ -60,7 +61,7 @@ where
}
}
impl<F, Req, Resp, Err, Fut> IntoService<FnService<F, Req, Resp, Err, Fut>, Req> for F
impl<F, Req, Resp, Err, Fut> IntoService<FnService<F, Req, Resp, Err, Fut>> for F
where
F: Fn(Req) -> Fut + 'static,
Fut: IntoFuture<Item = Resp, Error = Err>,
@@ -92,11 +93,12 @@ where
}
}
impl<F, Req, Resp, Err, Fut> NewService<Req> for FnNewService<F, Req, Resp, Err, Fut>
impl<F, Req, Resp, Err, Fut> NewService for FnNewService<F, Req, Resp, Err, Fut>
where
F: Fn(Req) -> Fut + Clone,
Fut: IntoFuture<Item = Resp, Error = Err>,
{
type Request = Req;
type Response = Resp;
type Error = Err;
type Service = FnService<F, Req, Resp, Err, Fut>;
@@ -108,7 +110,7 @@ where
}
}
impl<F, Req, Resp, Err, Fut> IntoNewService<FnNewService<F, Req, Resp, Err, Fut>, Req> for F
impl<F, Req, Resp, Err, Fut> IntoNewService<FnNewService<F, Req, Resp, Err, Fut>> for F
where
F: Fn(Req) -> Fut + Clone + 'static,
Fut: IntoFuture<Item = Resp, Error = Err>,

View File

@@ -7,17 +7,16 @@ use super::{NewService, Service};
/// Service for the `from_err` combinator, changing the error type of a service.
///
/// This is created by the `ServiceExt::from_err` method.
pub struct FromErr<A, E> {
pub struct FromErr<A, E>
where
A: Service,
{
service: A,
f: PhantomData<E>,
}
impl<A, E> FromErr<A, E> {
pub(crate) fn new<Request>(service: A) -> Self
where
A: Service<Request>,
E: From<A::Error>,
{
impl<A: Service, E: From<A::Error>> FromErr<A, E> {
pub(crate) fn new(service: A) -> Self {
FromErr {
service,
f: PhantomData,
@@ -27,7 +26,8 @@ impl<A, E> FromErr<A, E> {
impl<A, E> Clone for FromErr<A, E>
where
A: Clone,
A: Service + Clone,
E: From<A::Error>,
{
fn clone(&self) -> Self {
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
A: Service<Request>,
A: Service,
E: From<A::Error>,
{
type Request = A::Request;
type Response = A::Response;
type Error = E;
type Future = FromErrFuture<A, E, Request>;
type Future = FromErrFuture<A, E>;
fn poll_ready(&mut self) -> Poll<(), E> {
Ok(self.service.poll_ready().map_err(E::from)?)
}
fn call(&mut self, req: Request) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
FromErrFuture {
fut: self.service.call(req),
f: PhantomData,
@@ -58,14 +59,14 @@ where
}
}
pub struct FromErrFuture<A: Service<Request>, E, Request> {
pub struct FromErrFuture<A: Service, E> {
fut: A::Future,
f: PhantomData<E>,
}
impl<A, E, Request> Future for FromErrFuture<A, E, Request>
impl<A, E> Future for FromErrFuture<A, E>
where
A: Service<Request>,
A: Service,
E: From<A::Error>,
{
type Item = A::Response;
@@ -85,20 +86,21 @@ pub struct FromErrNewService<A, E> {
e: PhantomData<E>,
}
impl<A, E> FromErrNewService<A, E> {
impl<A, E> FromErrNewService<A, E>
where
A: NewService,
E: From<A::Error>,
{
/// Create new `FromErr` new service instance
pub fn new<Request>(a: A) -> Self
where
A: NewService<Request>,
E: From<A::Error>,
{
pub fn new(a: A) -> Self {
Self { a, e: PhantomData }
}
}
impl<A, E> Clone for FromErrNewService<A, E>
where
A: Clone,
A: NewService + Clone,
E: From<A::Error>,
{
fn clone(&self) -> Self {
Self {
@@ -108,17 +110,18 @@ where
}
}
impl<A, E, Request> NewService<Request> for FromErrNewService<A, E>
impl<A, E> NewService for FromErrNewService<A, E>
where
A: NewService<Request>,
A: NewService,
E: From<A::Error>,
{
type Request = A::Request;
type Response = A::Response;
type Error = E;
type Service = FromErr<A::Service, E>;
type InitError = A::InitError;
type Future = FromErrNewServiceFuture<A, E, Request>;
type Future = FromErrNewServiceFuture<A, E>;
fn new_service(&self) -> Self::Future {
FromErrNewServiceFuture {
@@ -128,18 +131,18 @@ where
}
}
pub struct FromErrNewServiceFuture<A, E, Request>
pub struct FromErrNewServiceFuture<A, E>
where
A: NewService<Request>,
A: NewService,
E: From<A::Error>,
{
fut: A::Future,
e: PhantomData<E>,
}
impl<A, E, Request> Future for FromErrNewServiceFuture<A, E, Request>
impl<A, E> Future for FromErrNewServiceFuture<A, E>
where
A: NewService<Request>,
A: NewService,
E: From<A::Error>,
{
type Item = FromErr<A::Service, E>;
@@ -159,10 +162,11 @@ mod tests {
use futures::future::{err, FutureResult};
use super::*;
use crate::{IntoNewService, NewService, Service};
use service::{IntoNewService, NewServiceExt, Service, ServiceExt};
struct Srv;
impl Service<()> for Srv {
impl Service for Srv {
type Request = ();
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;

View File

@@ -1,4 +1,4 @@
use std::marker::PhantomData;
use std::marker;
use futures::{Async, Future, Poll};
@@ -7,84 +7,83 @@ use super::{NewService, Service};
/// Service for the `map` combinator, changing the type of a service's response.
///
/// This is created by the `ServiceExt::map` method.
pub struct Map<A, F, Response> {
pub struct Map<A, F, R>
where
A: Service,
F: Fn(A::Response) -> R,
{
service: A,
f: F,
_t: PhantomData<Response>,
}
impl<A, F, Response> Map<A, F, Response> {
impl<A, F, R> Map<A, F, R>
where
A: Service,
F: Fn(A::Response) -> R,
{
/// Create new `Map` combinator
pub fn new<Request>(service: A, f: F) -> Self
where
A: Service<Request>,
F: Fn(A::Response) -> Response,
{
Self {
service,
f,
_t: PhantomData,
}
pub fn new(service: A, f: F) -> Self {
Self { service, f }
}
}
impl<A, F, Response> Clone for Map<A, F, Response>
impl<A, F, R> Clone for Map<A, F, R>
where
A: Clone,
F: Clone,
A: Service + Clone,
F: Fn(A::Response) -> R + Clone,
{
fn clone(&self) -> Self {
Map {
service: self.service.clone(),
f: self.f.clone(),
_t: PhantomData,
}
}
}
impl<A, F, Request, Response> Service<Request> for Map<A, F, Response>
impl<A, F, R> Service for Map<A, F, R>
where
A: Service<Request>,
F: Fn(A::Response) -> Response + Clone,
A: Service,
F: Fn(A::Response) -> R + Clone,
{
type Response = Response;
type Request = A::Request;
type Response = R;
type Error = A::Error;
type Future = MapFuture<A, F, Request, Response>;
type Future = MapFuture<A, F, R>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready()
}
fn call(&mut self, req: Request) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
MapFuture::new(self.service.call(req), self.f.clone())
}
}
pub struct MapFuture<A, F, Request, Response>
pub struct MapFuture<A, F, R>
where
A: Service<Request>,
F: Fn(A::Response) -> Response,
A: Service,
F: Fn(A::Response) -> R,
{
f: F,
fut: A::Future,
}
impl<A, F, Request, Response> MapFuture<A, F, Request, Response>
impl<A, F, R> MapFuture<A, F, R>
where
A: Service<Request>,
F: Fn(A::Response) -> Response,
A: Service,
F: Fn(A::Response) -> R,
{
fn new(fut: A::Future, f: F) -> Self {
MapFuture { f, fut }
}
}
impl<A, F, Request, Response> Future for MapFuture<A, F, Request, Response>
impl<A, F, R> Future for MapFuture<A, F, R>
where
A: Service<Request>,
F: Fn(A::Response) -> Response,
A: Service,
F: Fn(A::Response) -> R,
{
type Item = Response;
type Item = R;
type Error = A::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@@ -96,83 +95,84 @@ where
}
/// `MapNewService` new service combinator
pub struct MapNewService<A, F, Response> {
pub struct MapNewService<A, F, R> {
a: A,
f: F,
r: PhantomData<Response>,
r: marker::PhantomData<R>,
}
impl<A, F, Response> MapNewService<A, F, Response> {
impl<A, F, R> MapNewService<A, F, R>
where
A: NewService,
F: Fn(A::Response) -> R,
{
/// Create new `Map` new service instance
pub fn new<Request>(a: A, f: F) -> Self
where
A: NewService<Request>,
F: Fn(A::Response) -> Response,
{
pub fn new(a: A, f: F) -> Self {
Self {
a,
f,
r: PhantomData,
r: marker::PhantomData,
}
}
}
impl<A, F, Response> Clone for MapNewService<A, F, Response>
impl<A, F, R> Clone for MapNewService<A, F, R>
where
A: Clone,
F: Clone,
A: NewService + Clone,
F: Fn(A::Response) -> R + Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
f: self.f.clone(),
r: PhantomData,
r: marker::PhantomData,
}
}
}
impl<A, F, Request, Response> NewService<Request> for MapNewService<A, F, Response>
impl<A, F, R> NewService for MapNewService<A, F, R>
where
A: NewService<Request>,
F: Fn(A::Response) -> Response + Clone,
A: NewService,
F: Fn(A::Response) -> R + Clone,
{
type Response = Response;
type Request = A::Request;
type Response = R;
type Error = A::Error;
type Service = Map<A::Service, F, Response>;
type Service = Map<A::Service, F, R>;
type InitError = A::InitError;
type Future = MapNewServiceFuture<A, F, Request, Response>;
type Future = MapNewServiceFuture<A, F, R>;
fn new_service(&self) -> Self::Future {
MapNewServiceFuture::new(self.a.new_service(), self.f.clone())
}
}
pub struct MapNewServiceFuture<A, F, Request, Response>
pub struct MapNewServiceFuture<A, F, R>
where
A: NewService<Request>,
F: Fn(A::Response) -> Response,
A: NewService,
F: Fn(A::Response) -> R,
{
fut: A::Future,
f: Option<F>,
}
impl<A, F, Request, Response> MapNewServiceFuture<A, F, Request, Response>
impl<A, F, R> MapNewServiceFuture<A, F, R>
where
A: NewService<Request>,
F: Fn(A::Response) -> Response,
A: NewService,
F: Fn(A::Response) -> R,
{
fn new(fut: A::Future, f: F) -> Self {
MapNewServiceFuture { f: Some(f), fut }
}
}
impl<A, F, Request, Response> Future for MapNewServiceFuture<A, F, Request, Response>
impl<A, F, R> Future for MapNewServiceFuture<A, F, R>
where
A: NewService<Request>,
F: Fn(A::Response) -> Response,
A: NewService,
F: Fn(A::Response) -> R,
{
type Item = Map<A::Service, F, Response>;
type Item = Map<A::Service, F, R>;
type Error = A::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@@ -189,10 +189,11 @@ mod tests {
use futures::future::{ok, FutureResult};
use super::*;
use crate::{IntoNewService, Service};
use service::{IntoNewService, NewServiceExt, Service, ServiceExt};
struct Srv;
impl Service<()> for Srv {
impl Service for Srv {
type Request = ();
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;

View File

@@ -1,4 +1,4 @@
use std::marker::PhantomData;
use std::marker;
use futures::{Async, Future, Poll};
@@ -8,71 +8,71 @@ use super::{NewService, Service};
/// error.
///
/// This is created by the `ServiceExt::map_err` method.
pub struct MapErr<A, F, E> {
pub struct MapErr<A, F, E>
where
A: Service,
F: Fn(A::Error) -> E,
{
service: A,
f: F,
_t: PhantomData<E>,
}
impl<A, F, E> MapErr<A, F, E> {
impl<A, F, E> MapErr<A, F, E>
where
A: Service,
F: Fn(A::Error) -> E,
{
/// Create new `MapErr` combinator
pub fn new<Request>(service: A, f: F) -> Self
where
A: Service<Request>,
F: Fn(A::Error) -> E,
{
Self {
service,
f,
_t: PhantomData,
}
pub fn new(service: A, f: F) -> Self {
Self { service, f }
}
}
impl<A, F, E> Clone for MapErr<A, F, E>
where
A: Clone,
F: Clone,
A: Service + Clone,
F: Fn(A::Error) -> E + Clone,
{
fn clone(&self) -> Self {
MapErr {
service: self.service.clone(),
f: self.f.clone(),
_t: PhantomData,
}
}
}
impl<A, F, E, Request> Service<Request> for MapErr<A, F, E>
impl<A, F, E> Service for MapErr<A, F, E>
where
A: Service<Request>,
F: Fn(A::Error) -> E + Clone,
A: Service,
F: Fn(A::Error) -> E,
F: Clone,
{
type Request = A::Request;
type Response = A::Response;
type Error = E;
type Future = MapErrFuture<A, F, E, Request>;
type Future = MapErrFuture<A, F, E>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready().map_err(&self.f)
}
fn call(&mut self, req: Request) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
MapErrFuture::new(self.service.call(req), self.f.clone())
}
}
pub struct MapErrFuture<A, F, E, Request>
pub struct MapErrFuture<A, F, E>
where
A: Service<Request>,
A: Service,
F: Fn(A::Error) -> E,
{
f: F,
fut: A::Future,
}
impl<A, F, E, Request> MapErrFuture<A, F, E, Request>
impl<A, F, E> MapErrFuture<A, F, E>
where
A: Service<Request>,
A: Service,
F: Fn(A::Error) -> E,
{
fn new(fut: A::Future, f: F) -> Self {
@@ -80,9 +80,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
A: Service<Request>,
A: Service,
F: Fn(A::Error) -> E,
{
type Item = A::Response;
@@ -100,67 +100,68 @@ where
pub struct MapErrNewService<A, F, E> {
a: A,
f: F,
e: PhantomData<E>,
e: marker::PhantomData<E>,
}
impl<A, F, E> MapErrNewService<A, F, E> {
impl<A, F, E> MapErrNewService<A, F, E>
where
A: NewService,
F: Fn(A::Error) -> E,
{
/// Create new `MapErr` new service instance
pub fn new<Request>(a: A, f: F) -> Self
where
A: NewService<Request>,
F: Fn(A::Error) -> E,
{
pub fn new(a: A, f: F) -> Self {
Self {
a,
f,
e: PhantomData,
e: marker::PhantomData,
}
}
}
impl<A, F, E> Clone for MapErrNewService<A, F, E>
where
A: Clone,
F: Clone,
A: NewService + Clone,
F: Fn(A::Error) -> E + Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
f: self.f.clone(),
e: PhantomData,
e: marker::PhantomData,
}
}
}
impl<A, F, E, Request> NewService<Request> for MapErrNewService<A, F, E>
impl<A, F, E> NewService for MapErrNewService<A, F, E>
where
A: NewService<Request>,
A: NewService,
F: Fn(A::Error) -> E + Clone,
{
type Request = A::Request;
type Response = A::Response;
type Error = E;
type Service = MapErr<A::Service, F, E>;
type InitError = A::InitError;
type Future = MapErrNewServiceFuture<A, F, E, Request>;
type Future = MapErrNewServiceFuture<A, F, E>;
fn new_service(&self) -> Self::Future {
MapErrNewServiceFuture::new(self.a.new_service(), self.f.clone())
}
}
pub struct MapErrNewServiceFuture<A, F, E, Request>
pub struct MapErrNewServiceFuture<A, F, E>
where
A: NewService<Request>,
A: NewService,
F: Fn(A::Error) -> E,
{
fut: A::Future,
f: F,
}
impl<A, F, E, Request> MapErrNewServiceFuture<A, F, E, Request>
impl<A, F, E> MapErrNewServiceFuture<A, F, E>
where
A: NewService<Request>,
A: NewService,
F: Fn(A::Error) -> E,
{
fn new(fut: A::Future, f: F) -> Self {
@@ -168,9 +169,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
A: NewService<Request>,
A: NewService,
F: Fn(A::Error) -> E + Clone,
{
type Item = MapErr<A::Service, F, E>;
@@ -190,11 +191,12 @@ mod tests {
use futures::future::{err, FutureResult};
use super::*;
use crate::{IntoNewService, NewService, Service};
use service::{IntoNewService, NewServiceExt, Service, ServiceExt};
struct Srv;
impl Service<()> for Srv {
impl Service for Srv {
type Request = ();
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;

View File

@@ -1,4 +1,4 @@
use std::marker::PhantomData;
use std::marker;
use futures::{Future, Poll};
@@ -8,67 +8,68 @@ use super::NewService;
pub struct MapInitErr<A, F, E> {
a: A,
f: F,
e: PhantomData<E>,
e: marker::PhantomData<E>,
}
impl<A, F, E> MapInitErr<A, F, E> {
impl<A, F, E> MapInitErr<A, F, E>
where
A: NewService,
F: Fn(A::InitError) -> E,
{
/// Create new `MapInitErr` combinator
pub fn new<Request>(a: A, f: F) -> Self
where
A: NewService<Request>,
F: Fn(A::InitError) -> E,
{
pub fn new(a: A, f: F) -> Self {
Self {
a,
f,
e: PhantomData,
e: marker::PhantomData,
}
}
}
impl<A, F, E> Clone for MapInitErr<A, F, E>
where
A: Clone,
F: Clone,
A: NewService + Clone,
F: Fn(A::InitError) -> E + Clone,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
f: self.f.clone(),
e: PhantomData,
e: marker::PhantomData,
}
}
}
impl<A, F, E, Request> NewService<Request> for MapInitErr<A, F, E>
impl<A, F, E> NewService for MapInitErr<A, F, E>
where
A: NewService<Request>,
A: NewService,
F: Fn(A::InitError) -> E + Clone,
{
type Request = A::Request;
type Response = A::Response;
type Error = A::Error;
type Service = A::Service;
type InitError = E;
type Future = MapInitErrFuture<A, F, E, Request>;
type Future = MapInitErrFuture<A, F, E>;
fn new_service(&self) -> Self::Future {
MapInitErrFuture::new(self.a.new_service(), self.f.clone())
}
}
pub struct MapInitErrFuture<A, F, E, Request>
pub struct MapInitErrFuture<A, F, E>
where
A: NewService<Request>,
A: NewService,
F: Fn(A::InitError) -> E,
{
f: F,
fut: A::Future,
}
impl<A, F, E, Request> MapInitErrFuture<A, F, E, Request>
impl<A, F, E> MapInitErrFuture<A, F, E>
where
A: NewService<Request>,
A: NewService,
F: Fn(A::InitError) -> E,
{
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
A: NewService<Request>,
A: NewService,
F: Fn(A::InitError) -> E,
{
type Item = A::Service;

View File

@@ -1,7 +1,10 @@
use futures::{Future, IntoFuture, Poll};
use futures::{Future, IntoFuture};
/// re-export for convinience
pub use tower_service::{NewService, Service};
mod and_then;
mod apply;
mod cell;
mod fn_service;
mod from_err;
mod map;
@@ -18,52 +21,23 @@ pub use self::map_err::{MapErr, MapErrNewService};
pub use self::map_init_err::MapInitErr;
pub use self::then::{Then, ThenNewService};
/// An asynchronous function from `Request` to a `Response`.
pub trait Service<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.
///
/// If the service is at capacity, then `NotReady` is returned and the task
/// is notified when the service becomes ready again. This function is
/// expected to be called while on a task.
///
/// This is a **best effort** implementation. False positives are permitted.
/// It is permitted for the service to return `Ready` from a `poll_ready`
/// call and the next invocation of `call` results in an error.
fn poll_ready(&mut self) -> Poll<(), Self::Error>;
/// Process the request and return the response asynchronously.
///
/// This function is expected to be callable off task. As such,
/// implementations should take care to not call `poll_ready`. If the
/// service is at capacity and the request is unable to be handled, the
/// returned `Future` should resolve to an error.
///
/// Calling `call` without calling `poll_ready` is permitted. The
/// implementation must be resilient to this fact.
fn call(&mut self, req: Request) -> Self::Future;
/// An extension trait for `Service`s that provides a variety of convenient
/// adapters
pub trait ServiceExt: Service {
/// Apply function to specified service and use it as a next service in
/// chain.
fn apply<T, I, F, Out, Req>(
fn apply<S, I, F, R>(
self,
service: I,
f: F,
) -> AndThen<Self, Apply<T, F, Self::Response, Out, Req>>
) -> AndThen<Self, Apply<S, F, R, Self::Response>>
where
Self: Sized,
T: Service<Req, Error = Self::Error>,
I: IntoService<T, Req>,
F: Fn(Self::Response, &mut T) -> Out,
Out: IntoFuture<Error = Self::Error>,
S: Service,
S::Error: Into<<R::Future as Future>::Error>,
I: IntoService<S>,
F: Fn(Self::Response, &mut S) -> R,
R: IntoFuture<Error = Self::Error>,
{
self.and_then(Apply::new(service.into_service(), f))
}
@@ -80,8 +54,8 @@ pub trait Service<Request> {
fn and_then<F, B>(self, service: F) -> AndThen<Self, B>
where
Self: Sized,
F: IntoService<B, Self::Response>,
B: Service<Self::Response, Error = Self::Error>,
F: IntoService<B>,
B: Service<Request = Self::Response, Error = Self::Error>,
{
AndThen::new(self, service.into_service())
}
@@ -102,12 +76,12 @@ pub trait Service<Request> {
/// Chain on a computation for when a call to the service finished,
/// passing the result of the call to the next service `B`.
///
/// Note that this function consumes the receiving service and returns a
/// Note that this function consumes the receiving future and returns a
/// wrapped version of it.
fn then<B>(self, service: B) -> Then<Self, B>
where
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)
}
@@ -146,57 +120,32 @@ pub trait Service<Request> {
}
}
/// Creates new `Service` values.
///
/// Acts as a service factory. This is useful for cases where new `Service`
/// values must be produced. One case is a TCP servier listener. The listner
/// accepts new TCP streams, obtains a new `Service` value using the
/// `NewService` trait, and uses that new `Service` value to process inbound
/// requests on that new TCP stream.
///
/// Request - request handled by the service
pub trait NewService<Request> {
/// Responses given by the service
type Response;
/// Errors produced by the service
type Error;
/// The `Service` value created by this factory
type Service: Service<Request, Response = Self::Response, Error = Self::Error>;
/// Errors produced while building a service.
type InitError;
/// The future of the `Service` instance.
type Future: Future<Item = Self::Service, Error = Self::InitError>;
/// Create and return a new service value asynchronously.
fn new_service(&self) -> Self::Future;
/// Apply function to specified service and use it as a next service in
/// chain.
fn apply<T, I, F, Out, Req>(
pub trait NewServiceExt: NewService {
fn apply<S, I, F, R>(
self,
service: I,
f: F,
) -> AndThenNewService<Self, ApplyNewService<T, F, Self::Response, Out, Req>>
) -> AndThenNewService<Self, ApplyNewService<S, F, R, Self::Response>>
where
Self: Sized,
T: NewService<Req, InitError = Self::InitError, Error = Self::Error>,
I: IntoNewService<T, Req>,
F: Fn(Self::Response, &mut T::Service) -> Out + Clone,
Out: IntoFuture<Error = Self::Error>,
S: NewService<InitError = Self::InitError>,
S::Error: Into<<R::Future as Future>::Error>,
I: IntoNewService<S>,
F: Fn(Self::Response, &mut S::Service) -> R + Clone,
R: IntoFuture<Error = Self::Error>,
{
self.and_then(ApplyNewService::new(service, f))
}
/// Call another service after call to this one has resolved successfully.
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B>
where
Self: Sized,
F: IntoNewService<B, Self::Response>,
B: NewService<Self::Response, Error = Self::Error, InitError = Self::InitError>,
F: IntoNewService<B>,
B: NewService<
Request = Self::Response,
Error = Self::Error,
InitError = Self::InitError,
>,
{
AndThenNewService::new(self, new_service)
}
@@ -224,9 +173,9 @@ pub trait NewService<Request> {
fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B>
where
Self: Sized,
F: IntoNewService<B, Result<Self::Response, Self::Error>>,
F: IntoNewService<B>,
B: NewService<
Result<Self::Response, Self::Error>,
Request = Result<Self::Response, Self::Error>,
Error = Self::Error,
InitError = Self::InitError,
>,
@@ -234,8 +183,6 @@ pub trait NewService<Request> {
ThenNewService::new(self, new_service)
}
/// Map this service's output to a different type, returning a new service
/// of the resulting type.
fn map<F, R>(self, f: F) -> MapNewService<Self, F, R>
where
Self: Sized,
@@ -244,7 +191,6 @@ pub trait NewService<Request> {
MapNewService::new(self, f)
}
/// Map this service's error to a different error, returning a new service.
fn map_err<F, E>(self, f: F) -> MapErrNewService<Self, F, E>
where
Self: Sized,
@@ -253,7 +199,6 @@ pub trait NewService<Request> {
MapErrNewService::new(self, f)
}
/// Map this service's init error to a different error, returning a new service.
fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, E>
where
Self: Sized,
@@ -263,87 +208,39 @@ pub trait NewService<Request> {
}
}
impl<'a, S, Request> Service<Request> for &'a mut S
where
S: Service<Request> + 'a,
{
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
fn poll_ready(&mut self) -> Poll<(), S::Error> {
(**self).poll_ready()
}
fn call(&mut self, request: Request) -> S::Future {
(**self).call(request)
}
}
impl<S, Request> Service<Request> for Box<S>
where
S: Service<Request> + ?Sized,
{
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
fn poll_ready(&mut self) -> Poll<(), S::Error> {
(**self).poll_ready()
}
fn call(&mut self, request: Request) -> S::Future {
(**self).call(request)
}
}
impl<F, R, E, S, Request> NewService<Request> for F
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service<Request>,
{
type Response = S::Response;
type Error = S::Error;
type Service = S;
type InitError = E;
type Future = R::Future;
fn new_service(&self) -> Self::Future {
(*self)().into_future()
}
}
impl<T: ?Sized> ServiceExt for T where T: Service {}
impl<T: ?Sized> NewServiceExt for T where T: NewService {}
/// Trait for types that can be converted to a `Service`
pub trait IntoService<T, Request>
pub trait IntoService<T>
where
T: Service<Request>,
T: Service,
{
/// Convert to a `Service`
fn into_service(self) -> T;
}
/// Trait for types that can be converted to a Service
pub trait IntoNewService<T, Request>
pub trait IntoNewService<T>
where
T: NewService<Request>,
T: NewService,
{
/// Convert to an `NewService`
fn into_new_service(self) -> T;
}
impl<T, Request> IntoService<T, Request> for T
impl<T> IntoService<T> for T
where
T: Service<Request>,
T: Service,
{
fn into_service(self) -> T {
self
}
}
impl<T, Request> IntoNewService<T, Request> for T
impl<T> IntoNewService<T> for T
where
T: NewService<Request>,
T: NewService,
{
fn into_new_service(self) -> T {
self

View File

@@ -1,7 +1,7 @@
use futures::{try_ready, Async, Future, Poll};
use futures::{Async, Future, Poll};
use super::{IntoNewService, NewService, Service};
use crate::cell::Cell;
use cell::Cell;
/// Service for the `then` combinator, chaining a computation onto the end of
/// another service.
@@ -12,20 +12,21 @@ pub struct Then<A, B> {
b: Cell<B>,
}
impl<A, B> Then<A, B> {
impl<A, B> Then<A, B>
where
A: Service,
B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
{
/// Create new `Then` combinator
pub fn new<Request>(a: A, b: B) -> Then<A, B>
where
A: Service<Request>,
B: Service<Result<A::Response, A::Error>, Error = A::Error>,
{
pub fn new(a: A, b: B) -> Then<A, B> {
Then { a, b: Cell::new(b) }
}
}
impl<A, B> Clone for Then<A, B>
where
A: Clone,
A: Service + Clone,
B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
{
fn clone(&self) -> Self {
Then {
@@ -35,53 +36,54 @@ where
}
}
impl<A, B, Request> Service<Request> for Then<A, B>
impl<A, B> Service for Then<A, B>
where
A: Service<Request>,
B: Service<Result<A::Response, A::Error>, Error = A::Error>,
A: Service,
B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
{
type Request = A::Request;
type Response = B::Response;
type Error = B::Error;
type Future = ThenFuture<A, B, Request>;
type Future = ThenFuture<A, B>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
try_ready!(self.a.poll_ready());
self.b.get_mut().poll_ready()
let _ = try_ready!(self.a.poll_ready());
self.b.borrow_mut().poll_ready()
}
fn call(&mut self, req: Request) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
ThenFuture::new(self.a.call(req), self.b.clone())
}
}
pub struct ThenFuture<A, B, Request>
pub struct ThenFuture<A, B>
where
A: Service<Request>,
B: Service<Result<A::Response, A::Error>>,
A: Service,
B: Service<Request = Result<A::Response, A::Error>>,
{
b: Cell<B>,
fut_b: Option<B::Future>,
fut_a: A::Future,
fut_a: Option<A::Future>,
}
impl<A, B, Request> ThenFuture<A, B, Request>
impl<A, B> ThenFuture<A, B>
where
A: Service<Request>,
B: Service<Result<A::Response, A::Error>>,
A: Service,
B: Service<Request = Result<A::Response, A::Error>>,
{
fn new(fut_a: A::Future, b: Cell<B>) -> Self {
fn new(a: A::Future, b: Cell<B>) -> Self {
ThenFuture {
b,
fut_a,
fut_a: Some(a),
fut_b: None,
}
}
}
impl<A, B, Request> Future for ThenFuture<A, B, Request>
impl<A, B> Future for ThenFuture<A, B>
where
A: Service<Request>,
B: Service<Result<A::Response, A::Error>>,
A: Service,
B: Service<Request = Result<A::Response, A::Error>>,
{
type Item = B::Response;
type Error = B::Error;
@@ -91,13 +93,15 @@ where
return fut.poll();
}
match self.fut_a.poll() {
match self.fut_a.as_mut().expect("actix-net bug").poll() {
Ok(Async::Ready(resp)) => {
self.fut_b = Some(self.b.get_mut().call(Ok(resp)));
let _ = self.fut_a.take();
self.fut_b = Some(self.b.borrow_mut().call(Ok(resp)));
self.poll()
}
Err(err) => {
self.fut_b = Some(self.b.get_mut().call(Err(err)));
let _ = self.fut_a.take();
self.fut_b = Some(self.b.borrow_mut().call(Err(err)));
self.poll()
}
Ok(Async::NotReady) => Ok(Async::NotReady),
@@ -111,18 +115,13 @@ pub struct ThenNewService<A, B> {
b: B,
}
impl<A, B> ThenNewService<A, B> {
impl<A, B> ThenNewService<A, B>
where
A: NewService,
B: NewService,
{
/// Create new `AndThen` combinator
pub fn new<F, Request>(a: A, f: F) -> Self
where
A: NewService<Request>,
B: NewService<
Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
>,
F: IntoNewService<B, Result<A::Response, A::Error>>,
{
pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self {
Self {
a,
b: f.into_new_service(),
@@ -130,17 +129,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
A: NewService<Request>,
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
A: NewService,
B: NewService<
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
>,
{
type Request = A::Request;
type Response = B::Response;
type Error = A::Error;
type Service = Then<A::Service, B::Service>;
type InitError = A::InitError;
type Future = ThenNewServiceFuture<A, B, Request>;
type Future = ThenNewServiceFuture<A, B>;
fn new_service(&self) -> Self::Future {
ThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
@@ -149,8 +153,12 @@ where
impl<A, B> Clone for ThenNewService<A, B>
where
A: Clone,
B: Clone,
A: NewService + Clone,
B: NewService<
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
> + Clone,
{
fn clone(&self) -> Self {
Self {
@@ -160,10 +168,10 @@ where
}
}
pub struct ThenNewServiceFuture<A, B, Request>
pub struct ThenNewServiceFuture<A, B>
where
A: NewService<Request>,
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
A: NewService,
B: NewService,
{
fut_b: B::Future,
fut_a: A::Future,
@@ -171,10 +179,10 @@ where
b: Option<B::Service>,
}
impl<A, B, Request> ThenNewServiceFuture<A, B, Request>
impl<A, B> ThenNewServiceFuture<A, B>
where
A: NewService<Request>,
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
A: NewService,
B: NewService,
{
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
ThenNewServiceFuture {
@@ -186,10 +194,14 @@ where
}
}
impl<A, B, Request> Future for ThenNewServiceFuture<A, B, Request>
impl<A, B> Future for ThenNewServiceFuture<A, B>
where
A: NewService<Request>,
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
A: NewService,
B: NewService<
Request = Result<A::Response, A::Error>,
Error = A::Error,
InitError = A::InitError,
>,
{
type Item = Then<A::Service, B::Service>;
type Error = A::InitError;
@@ -226,10 +238,12 @@ mod tests {
use std::rc::Rc;
use super::*;
use service::{NewServiceExt, ServiceExt};
#[derive(Clone)]
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 Error = ();
type Future = FutureResult<Self::Response, Self::Error>;
@@ -239,7 +253,7 @@ mod tests {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Result<&'static str, &'static str>) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
match req {
Ok(msg) => ok(msg),
Err(_) => err(()),
@@ -249,7 +263,8 @@ mod tests {
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 Error = ();
type Future = FutureResult<Self::Response, ()>;
@@ -259,7 +274,7 @@ mod tests {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Result<&'static str, ()>) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
match req {
Ok(msg) => ok((msg, "ok")),
Err(()) => ok(("srv2", "err")),

View File

@@ -1,13 +1,13 @@
use std::io;
use std::marker::PhantomData;
use actix_service::{NewService, Service};
use futures::{future::ok, future::FutureResult, Async, Future, Poll};
use native_tls::{self, Error, HandshakeError, TlsAcceptor};
use tokio_io::{AsyncRead, AsyncWrite};
use super::MAX_CONN_COUNTER;
use crate::counter::{Counter, CounterGuard};
use counter::{Counter, CounterGuard};
use service::{NewService, Service};
/// Support `SSL` connections via native-tls package
///
@@ -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 Error = Error;
type Service = NativeTlsAcceptorService<T>;
@@ -60,7 +61,8 @@ pub struct NativeTlsAcceptorService<T> {
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 Error = Error;
type Future = Accept<T>;
@@ -73,7 +75,7 @@ impl<T: AsyncRead + AsyncWrite> Service<T> for NativeTlsAcceptorService<T> {
}
}
fn call(&mut self, req: T) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
Accept {
_guard: self.conns.get(),
inner: Some(self.acceptor.accept(req)),

View File

@@ -1,14 +1,14 @@
use std::marker::PhantomData;
use actix_service::{NewService, Service};
use futures::{future::ok, future::FutureResult, Async, Future, Poll};
use openssl::ssl::{Error, SslAcceptor, SslConnector};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_openssl::{AcceptAsync, ConnectAsync, SslAcceptorExt, SslConnectorExt, SslStream};
use super::MAX_CONN_COUNTER;
use crate::counter::{Counter, CounterGuard};
use crate::resolver::RequestHost;
use counter::{Counter, CounterGuard};
use resolver::RequestHost;
use service::{NewService, Service};
/// Support `SSL` connections via openssl package
///
@@ -37,7 +37,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 Error = Error;
type Service = OpensslAcceptorService<T>;
@@ -61,7 +62,8 @@ pub struct OpensslAcceptorService<T> {
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 Error = Error;
type Future = OpensslAcceptorServiceFut<T>;
@@ -74,7 +76,7 @@ impl<T: AsyncRead + AsyncWrite> Service<T> for OpensslAcceptorService<T> {
}
}
fn call(&mut self, req: T) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
OpensslAcceptorServiceFut {
_guard: self.conns.get(),
fut: SslAcceptorExt::accept_async(&self.acceptor, req),
@@ -117,7 +119,7 @@ impl<R, T, E> OpensslConnector<R, T, E> {
impl<R: RequestHost, T: AsyncRead + AsyncWrite> OpensslConnector<R, T, ()> {
pub fn service(
connector: SslConnector,
) -> impl Service<(R, T), Response = (R, SslStream<T>), Error = Error> {
) -> impl Service<Request = (R, T), Response = (R, SslStream<T>), Error = Error> {
OpensslConnectorService {
connector: connector,
_t: PhantomData,
@@ -134,9 +136,8 @@ impl<R, T, E> Clone for OpensslConnector<R, T, E> {
}
}
impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService<(R, T)>
for OpensslConnector<R, T, E>
{
impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService for OpensslConnector<R, T, E> {
type Request = (R, T);
type Response = (R, SslStream<T>);
type Error = Error;
type Service = OpensslConnectorService<R, T>;
@@ -156,9 +157,8 @@ pub struct OpensslConnectorService<R, T> {
_t: PhantomData<(R, T)>,
}
impl<R: RequestHost, T: AsyncRead + AsyncWrite> Service<(R, T)>
for OpensslConnectorService<R, T>
{
impl<R: RequestHost, T: AsyncRead + AsyncWrite> Service for OpensslConnectorService<R, T> {
type Request = (R, T);
type Response = (R, SslStream<T>);
type Error = Error;
type Future = ConnectAsyncExt<R, T>;
@@ -167,7 +167,7 @@ impl<R: RequestHost, T: AsyncRead + AsyncWrite> Service<(R, T)>
Ok(Async::Ready(()))
}
fn call(&mut self, (req, stream): (R, T)) -> Self::Future {
fn call(&mut self, (req, stream): Self::Request) -> Self::Future {
ConnectAsyncExt {
fut: SslConnectorExt::connect_async(&self.connector, req.host(), stream),
req: Some(req),

View File

@@ -2,14 +2,14 @@ use std::io;
use std::marker::PhantomData;
use std::sync::Arc;
use actix_service::{NewService, Service};
use futures::{future::ok, future::FutureResult, Async, Future, Poll};
use rustls::{ServerConfig, ServerSession};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_rustls::{Accept, TlsAcceptor, TlsStream};
use super::MAX_CONN_COUNTER;
use crate::counter::{Counter, CounterGuard};
use counter::{Counter, CounterGuard};
use service::{NewService, Service};
/// Support `SSL` connections via rustls package
///
@@ -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 Error = io::Error;
type Service = RustlsAcceptorService<T>;
@@ -62,7 +63,8 @@ pub struct RustlsAcceptorService<T> {
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 Error = io::Error;
type Future = RustlsAcceptorServiceFut<T>;
@@ -75,7 +77,7 @@ impl<T: AsyncRead + AsyncWrite> Service<T> for RustlsAcceptorService<T> {
}
}
fn call(&mut self, req: T) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
RustlsAcceptorServiceFut {
_guard: self.conns.get(),
fut: self.acceptor.accept(req),

View File

@@ -1,10 +1,11 @@
use std::marker::PhantomData;
use actix_service::{IntoService, NewService, Service};
use futures::unsync::mpsc;
use futures::{future, Async, Future, Poll, Stream};
use tokio_current_thread::spawn;
use super::service::{IntoService, NewService, Service};
pub struct StreamDispatcher<S: Stream, T> {
stream: S,
service: T,
@@ -16,13 +17,10 @@ pub struct StreamDispatcher<S: Stream, T> {
impl<S, T> StreamDispatcher<S, T>
where
S: Stream,
T: Service<Result<S::Item, S::Error>, Response = (), Error = ()>,
T: Service<Request = Result<S::Item, S::Error>, Response = (), Error = ()>,
T::Future: 'static,
{
pub fn new<F>(stream: S, service: F) -> Self
where
F: IntoService<T, Result<S::Item, S::Error>>,
{
pub fn new<F: IntoService<T>>(stream: S, service: F) -> Self {
let (stop_tx, stop_rx) = mpsc::unbounded();
StreamDispatcher {
stream,
@@ -37,7 +35,7 @@ where
impl<S, T> Future for StreamDispatcher<S, T>
where
S: Stream,
T: Service<Result<S::Item, S::Error>, Response = (), Error = ()>,
T: Service<Request = Result<S::Item, S::Error>, Response = (), Error = ()>,
T::Future: 'static,
{
type Item = ();
@@ -105,19 +103,14 @@ impl<T> TakeItem<T> {
}
}
impl<T> Default for TakeItem<T> {
fn default() -> Self {
TakeItem { _t: PhantomData }
}
}
impl<T> Clone for TakeItem<T> {
fn clone(&self) -> TakeItem<T> {
TakeItem { _t: PhantomData }
}
}
impl<T: Stream> NewService<T> for TakeItem<T> {
impl<T: Stream> NewService for TakeItem<T> {
type Request = T;
type Response = (Option<T::Item>, T);
type Error = T::Error;
type InitError = ();
@@ -140,7 +133,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 Error = T::Error;
type Future = TakeItemServiceResponse<T>;
@@ -149,7 +143,7 @@ impl<T: Stream> Service<T> for TakeItemService<T> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: T) -> Self::Future {
fn call(&mut self, req: Self::Request) -> Self::Future {
TakeItemServiceResponse { stream: Some(req) }
}
}

View File

@@ -1,12 +1,12 @@
use std::time::{Duration, Instant};
use actix_service::{NewService, Service};
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use tokio_current_thread::spawn;
use tokio_timer::sleep;
use super::cell::Cell;
use super::service::{NewService, Service};
use super::Never;
#[derive(Clone, Debug)]
@@ -43,7 +43,8 @@ impl Default for LowResTime {
}
}
impl NewService<()> for LowResTime {
impl NewService for LowResTime {
type Request = ();
type Response = Instant;
type Error = Never;
type InitError = Never;
@@ -66,7 +67,7 @@ impl LowResTimeService {
/// Get current time. This function has to be called from
/// future's poll method, otherwise it panics.
pub fn now(&self) -> Instant {
let cur = self.0.borrow().current;
let cur = self.0.borrow().current.clone();
if let Some(cur) = cur {
cur
} else {
@@ -87,7 +88,8 @@ impl LowResTimeService {
}
}
impl Service<()> for LowResTimeService {
impl Service for LowResTimeService {
type Request = ();
type Response = Instant;
type Error = Never;
type Future = FutureResult<Self::Response, Self::Error>;

View File

@@ -5,14 +5,14 @@
use std::fmt;
use std::time::Duration;
use actix_service::{NewService, Service};
use futures::try_ready;
use futures::{Async, Future, Poll};
use tokio_timer::{clock, Delay};
use service::{NewService, Service};
/// Applies a timeout to requests.
#[derive(Debug)]
pub struct Timeout<T> {
pub struct Timeout<T: NewService + Clone> {
inner: T,
timeout: Duration,
}
@@ -34,43 +34,44 @@ impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> {
}
}
impl<T> Timeout<T> {
pub fn new<Request>(timeout: Duration, inner: T) -> Self
where
T: NewService<Request> + Clone,
{
impl<T> Timeout<T>
where
T: NewService + Clone,
{
pub fn new(timeout: Duration, inner: T) -> Self {
Timeout { inner, timeout }
}
}
impl<T, Request> NewService<Request> for Timeout<T>
impl<T> NewService for Timeout<T>
where
T: NewService<Request> + Clone,
T: NewService + Clone,
{
type Request = T::Request;
type Response = T::Response;
type Error = TimeoutError<T::Error>;
type InitError = T::InitError;
type Service = TimeoutService<T::Service>;
type Future = TimeoutFut<T, Request>;
type Future = TimeoutFut<T>;
fn new_service(&self) -> Self::Future {
TimeoutFut {
fut: self.inner.new_service(),
timeout: self.timeout,
timeout: self.timeout.clone(),
}
}
}
/// `Timeout` response future
#[derive(Debug)]
pub struct TimeoutFut<T: NewService<Request>, Request> {
pub struct TimeoutFut<T: NewService> {
fut: T::Future,
timeout: Duration,
}
impl<T, Request> Future for TimeoutFut<T, Request>
impl<T> Future for TimeoutFut<T>
where
T: NewService<Request>,
T: NewService,
{
type Item = TimeoutService<T::Service>;
type Error = T::InitError;
@@ -89,15 +90,15 @@ pub struct TimeoutService<T> {
}
impl<T> TimeoutService<T> {
pub fn new<Request>(timeout: Duration, inner: T) -> Self
where
T: Service<Request>,
{
pub fn new(timeout: Duration, inner: T) -> Self {
TimeoutService { inner, timeout }
}
}
impl<T: Clone> Clone for TimeoutService<T> {
impl<T> Clone for TimeoutService<T>
where
T: Clone,
{
fn clone(&self) -> Self {
TimeoutService {
inner: self.inner.clone(),
@@ -106,19 +107,22 @@ impl<T: Clone> Clone for TimeoutService<T> {
}
}
impl<T, Request> Service<Request> for TimeoutService<T>
impl<T> Service for TimeoutService<T>
where
T: Service<Request>,
T: Service,
{
type Request = T::Request;
type Response = T::Response;
type Error = TimeoutError<T::Error>;
type Future = TimeoutServiceResponse<T, Request>;
type Future = TimeoutServiceResponse<T>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.inner.poll_ready().map_err(TimeoutError::Service)
self.inner
.poll_ready()
.map_err(|e| TimeoutError::Service(e))
}
fn call(&mut self, request: Request) -> Self::Future {
fn call(&mut self, request: Self::Request) -> Self::Future {
TimeoutServiceResponse {
fut: self.inner.call(request),
sleep: Delay::new(clock::now() + self.timeout),
@@ -128,14 +132,14 @@ where
/// `TimeoutService` response future
#[derive(Debug)]
pub struct TimeoutServiceResponse<T: Service<Request>, Request> {
pub struct TimeoutServiceResponse<T: Service> {
fut: T::Future,
sleep: Delay,
}
impl<T, Request> Future for TimeoutServiceResponse<T, Request>
impl<T> Future for TimeoutServiceResponse<T>
where
T: Service<Request>,
T: Service,
{
type Item = T::Response;
type Error = TimeoutError<T::Error>;