mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-25 02:05:37 +02:00
Compare commits
42 Commits
v0.1.0
...
service-v0
Author | SHA1 | Date | |
---|---|---|---|
|
5f37d85f9b | ||
|
e8aa73a44b | ||
|
8fe7ce533c | ||
|
42a4679635 | ||
|
36a15efeac | ||
|
5937a06ebe | ||
|
a16ad6b2cd | ||
|
8108f19580 | ||
|
1b1ae01b5a | ||
|
c62567f85f | ||
|
410204a41e | ||
|
29fe995a02 | ||
|
741b3fb1c0 | ||
|
dba86fbbf8 | ||
|
c29501fcf3 | ||
|
9a3321b153 | ||
|
f13a0925f7 | ||
|
8886672ae6 | ||
|
8f20f69559 | ||
|
9b9599500a | ||
|
a4b81a256c | ||
|
38235c14bb | ||
|
bf9269de9a | ||
|
bb34df8c1b | ||
|
1ac018dc79 | ||
|
0e3d1068da | ||
|
60144a3cb8 | ||
|
6c25becd3f | ||
|
dc19a9f862 | ||
|
67961f8a36 | ||
|
3d51aa7115 | ||
|
a8a831a098 | ||
|
4b16af29c7 | ||
|
c15e4b92a8 | ||
|
e1418018c6 | ||
|
ff914f79fc | ||
|
3a133e3974 | ||
|
0b0d14d1ea | ||
|
099ebbfaa3 | ||
|
afe15ba44f | ||
|
4eabf3994a | ||
|
e32961a897 |
@@ -16,7 +16,7 @@ matrix:
|
|||||||
|
|
||||||
env:
|
env:
|
||||||
global:
|
global:
|
||||||
# - RUSTFLAGS="-C link-dead-code"
|
- RUSTFLAGS="-C link-dead-code"
|
||||||
- OPENSSL_VERSION=openssl-1.0.2
|
- OPENSSL_VERSION=openssl-1.0.2
|
||||||
|
|
||||||
before_install:
|
before_install:
|
||||||
@@ -33,6 +33,7 @@ script:
|
|||||||
if [[ "$TRAVIS_RUST_VERSION" != "nightly" ]]; then
|
if [[ "$TRAVIS_RUST_VERSION" != "nightly" ]]; then
|
||||||
cargo clean
|
cargo clean
|
||||||
cargo test --features="ssl,tls,rust-tls" -- --nocapture
|
cargo test --features="ssl,tls,rust-tls" -- --nocapture
|
||||||
|
cd actix-service && cargo test
|
||||||
fi
|
fi
|
||||||
- |
|
- |
|
||||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then
|
if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then
|
||||||
@@ -40,6 +41,7 @@ script:
|
|||||||
cargo tarpaulin --features="ssl,tls,rust-tls" --out Xml
|
cargo tarpaulin --features="ssl,tls,rust-tls" --out Xml
|
||||||
bash <(curl -s https://codecov.io/bash)
|
bash <(curl -s https://codecov.io/bash)
|
||||||
echo "Uploaded code coverage"
|
echo "Uploaded code coverage"
|
||||||
|
cd actix-service && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash)
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Upload docs
|
# Upload docs
|
||||||
|
61
CHANGES.md
61
CHANGES.md
@@ -1,5 +1,66 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
|
## [0.3.0] - xxx
|
||||||
|
|
||||||
|
* Use new `Service<Request>` trait
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.4] - 2018-11-21
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Allow to skip name resolution stage in Connector
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.3] - 2018-11-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Framed::is_write_buf_empty() checks if write buffer is flushed
|
||||||
|
|
||||||
|
## [0.2.2] - 2018-11-14
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Add low/high caps to Framed
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Refactor Connector and Resolver services
|
||||||
|
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
* Fix wrong service to socket binding
|
||||||
|
|
||||||
|
|
||||||
|
## [0.2.0] - 2018-11-08
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
* Timeout service
|
||||||
|
|
||||||
|
* Added ServiceConfig and ServiceRuntime for server service configuration
|
||||||
|
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
* Connector has been refactored
|
||||||
|
|
||||||
|
* timer and LowResTimer renamed to time and LowResTime
|
||||||
|
|
||||||
|
* Refactored `Server::configure()` method
|
||||||
|
|
||||||
|
|
||||||
|
## [0.1.1] - 2018-10-10
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Set actix min version - 0.7.5
|
||||||
|
|
||||||
|
- Set trust-dns min version
|
||||||
|
|
||||||
|
|
||||||
## [0.1.0] - 2018-10-08
|
## [0.1.0] - 2018-10-08
|
||||||
|
|
||||||
* Initial impl
|
* Initial impl
|
||||||
|
20
Cargo.toml
20
Cargo.toml
@@ -1,16 +1,23 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-net"
|
name = "actix-net"
|
||||||
version = "0.1.0"
|
version = "0.3.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||||
description = "Actix net - framework for the compisible network services for Rust (experimental)"
|
description = "Actix net - framework for the compisible network services for Rust (experimental)"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
keywords = ["network", "framework", "async", "futures"]
|
keywords = ["network", "framework", "async", "futures"]
|
||||||
homepage = "https://actix.rs"
|
homepage = "https://actix.rs"
|
||||||
repository = "https://github.com/actix/actix-net.git"
|
repository = "https://github.com/actix/actix-net.git"
|
||||||
documentation = "https://actix.rs/api/actix-net/stable/actix_net/"
|
documentation = "https://docs.rs/actix-net/"
|
||||||
categories = ["network-programming", "asynchronous"]
|
categories = ["network-programming", "asynchronous"]
|
||||||
license = "MIT/Apache-2.0"
|
license = "MIT/Apache-2.0"
|
||||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
|
[workspace]
|
||||||
|
members = [
|
||||||
|
"./",
|
||||||
|
"actix-service",
|
||||||
|
]
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
features = ["ssl", "tls", "rust-tls"]
|
features = ["ssl", "tls", "rust-tls"]
|
||||||
@@ -39,7 +46,9 @@ rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
|
|||||||
cell = []
|
cell = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix = "0.7.0"
|
actix = "0.7.6"
|
||||||
|
# actix-service = "0.1"
|
||||||
|
actix-service = { path="./actix-service" }
|
||||||
|
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
num_cpus = "1.0"
|
num_cpus = "1.0"
|
||||||
@@ -57,8 +66,9 @@ tokio-tcp = "0.1"
|
|||||||
tokio-timer = "0.2"
|
tokio-timer = "0.2"
|
||||||
tokio-reactor = "0.1"
|
tokio-reactor = "0.1"
|
||||||
tokio-current-thread = "0.1"
|
tokio-current-thread = "0.1"
|
||||||
tower-service = "0.1"
|
tower-service = { git = "https://github.com/tower-rs/tower.git" }
|
||||||
trust-dns-resolver = "0.10.0-alpha.2"
|
trust-dns-proto = "^0.5.0"
|
||||||
|
trust-dns-resolver = "^0.10.0"
|
||||||
|
|
||||||
# native-tls
|
# native-tls
|
||||||
native-tls = { version="0.2", optional = true }
|
native-tls = { version="0.2", optional = true }
|
||||||
|
26
actix-service/Cargo.toml
Normal file
26
actix-service/Cargo.toml
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
[package]
|
||||||
|
name = "actix-service"
|
||||||
|
version = "0.1.0"
|
||||||
|
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"
|
@@ -1,7 +1,7 @@
|
|||||||
use futures::{Async, Future, Poll};
|
use futures::{try_ready, Async, Future, Poll};
|
||||||
|
|
||||||
use super::{IntoNewService, NewService, Service};
|
use super::{IntoNewService, NewService, Service};
|
||||||
use cell::Cell;
|
use crate::cell::Cell;
|
||||||
|
|
||||||
/// Service for the `and_then` combinator, chaining a computation onto the end
|
/// Service for the `and_then` combinator, chaining a computation onto the end
|
||||||
/// of another service which completes successfully.
|
/// of another service which completes successfully.
|
||||||
@@ -12,21 +12,20 @@ pub struct AndThen<A, B> {
|
|||||||
b: Cell<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
|
/// Create new `AndThen` combinator
|
||||||
pub fn new(a: A, b: B) -> Self {
|
pub fn new<Request>(a: A, b: B) -> Self
|
||||||
|
where
|
||||||
|
A: Service<Request>,
|
||||||
|
B: Service<A::Response, Error = A::Error>,
|
||||||
|
{
|
||||||
Self { a, b: Cell::new(b) }
|
Self { a, b: Cell::new(b) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Clone for AndThen<A, B>
|
impl<A, B> Clone for AndThen<A, B>
|
||||||
where
|
where
|
||||||
A: Service + Clone,
|
A: Clone,
|
||||||
B: Service<Request = A::Response, Error = A::Error>,
|
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
AndThen {
|
AndThen {
|
||||||
@@ -36,40 +35,39 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Service for AndThen<A, B>
|
impl<A, B, Request> Service<Request> for AndThen<A, B>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
B: Service<Request = A::Response, Error = A::Error>,
|
B: Service<A::Response, Error = A::Error>,
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
|
||||||
type Response = B::Response;
|
type Response = B::Response;
|
||||||
type Error = A::Error;
|
type Error = A::Error;
|
||||||
type Future = AndThenFuture<A, B>;
|
type Future = AndThenFuture<A, B, Request>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
let _ = try_ready!(self.a.poll_ready());
|
try_ready!(self.a.poll_ready());
|
||||||
self.b.borrow_mut().poll_ready()
|
self.b.get_mut().poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Request) -> Self::Future {
|
||||||
AndThenFuture::new(self.a.call(req), self.b.clone())
|
AndThenFuture::new(self.a.call(req), self.b.clone())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct AndThenFuture<A, B>
|
pub struct AndThenFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
B: Service<Request = A::Response, Error = A::Error>,
|
B: Service<A::Response, Error = A::Error>,
|
||||||
{
|
{
|
||||||
b: Cell<B>,
|
b: Cell<B>,
|
||||||
fut_b: Option<B::Future>,
|
fut_b: Option<B::Future>,
|
||||||
fut_a: A::Future,
|
fut_a: A::Future,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> AndThenFuture<A, B>
|
impl<A, B, Request> AndThenFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
B: Service<Request = A::Response, Error = A::Error>,
|
B: Service<A::Response, Error = A::Error>,
|
||||||
{
|
{
|
||||||
fn new(fut_a: A::Future, b: Cell<B>) -> Self {
|
fn new(fut_a: A::Future, b: Cell<B>) -> Self {
|
||||||
AndThenFuture {
|
AndThenFuture {
|
||||||
@@ -80,11 +78,10 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Future for AndThenFuture<A, B>
|
impl<A, B, Request> Future for AndThenFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
B: Service<Request = A::Response, Error = A::Error>,
|
B: Service<A::Response, Error = A::Error>,
|
||||||
B::Error: Into<A::Error>,
|
|
||||||
{
|
{
|
||||||
type Item = B::Response;
|
type Item = B::Response;
|
||||||
type Error = A::Error;
|
type Error = A::Error;
|
||||||
@@ -96,7 +93,7 @@ where
|
|||||||
|
|
||||||
match self.fut_a.poll() {
|
match self.fut_a.poll() {
|
||||||
Ok(Async::Ready(resp)) => {
|
Ok(Async::Ready(resp)) => {
|
||||||
self.fut_b = Some(self.b.borrow_mut().call(resp));
|
self.fut_b = Some(self.b.get_mut().call(resp));
|
||||||
self.poll()
|
self.poll()
|
||||||
}
|
}
|
||||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||||
@@ -111,13 +108,13 @@ pub struct AndThenNewService<A, B> {
|
|||||||
b: B,
|
b: B,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> AndThenNewService<A, B>
|
impl<A, B> AndThenNewService<A, B> {
|
||||||
where
|
|
||||||
A: NewService,
|
|
||||||
B: NewService,
|
|
||||||
{
|
|
||||||
/// Create new `AndThen` combinator
|
/// Create new `AndThen` combinator
|
||||||
pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self {
|
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>,
|
||||||
|
{
|
||||||
Self {
|
Self {
|
||||||
a,
|
a,
|
||||||
b: f.into_new_service(),
|
b: f.into_new_service(),
|
||||||
@@ -125,18 +122,17 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> NewService for AndThenNewService<A, B>
|
impl<A, B, Request> NewService<Request> for AndThenNewService<A, B>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
B: NewService<A::Response, Error = A::Error, InitError = A::InitError>,
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
|
||||||
type Response = B::Response;
|
type Response = B::Response;
|
||||||
type Error = A::Error;
|
type Error = A::Error;
|
||||||
type Service = AndThen<A::Service, B::Service>;
|
type Service = AndThen<A::Service, B::Service>;
|
||||||
|
|
||||||
type InitError = A::InitError;
|
type InitError = A::InitError;
|
||||||
type Future = AndThenNewServiceFuture<A, B>;
|
type Future = AndThenNewServiceFuture<A, B, Request>;
|
||||||
|
|
||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
AndThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
|
AndThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
|
||||||
@@ -145,8 +141,8 @@ where
|
|||||||
|
|
||||||
impl<A, B> Clone for AndThenNewService<A, B>
|
impl<A, B> Clone for AndThenNewService<A, B>
|
||||||
where
|
where
|
||||||
A: NewService + Clone,
|
A: Clone,
|
||||||
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError> + Clone,
|
B: Clone,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -156,10 +152,10 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct AndThenNewServiceFuture<A, B>
|
pub struct AndThenNewServiceFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
B: NewService,
|
B: NewService<A::Response>,
|
||||||
{
|
{
|
||||||
fut_b: B::Future,
|
fut_b: B::Future,
|
||||||
fut_a: A::Future,
|
fut_a: A::Future,
|
||||||
@@ -167,10 +163,10 @@ where
|
|||||||
b: Option<B::Service>,
|
b: Option<B::Service>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> AndThenNewServiceFuture<A, B>
|
impl<A, B, Request> AndThenNewServiceFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
B: NewService,
|
B: NewService<A::Response>,
|
||||||
{
|
{
|
||||||
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
|
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
|
||||||
AndThenNewServiceFuture {
|
AndThenNewServiceFuture {
|
||||||
@@ -182,10 +178,10 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Future for AndThenNewServiceFuture<A, B>
|
impl<A, B, Request> Future for AndThenNewServiceFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
B: NewService<A::Response, Error = A::Error, InitError = A::InitError>,
|
||||||
{
|
{
|
||||||
type Item = AndThen<A::Service, B::Service>;
|
type Item = AndThen<A::Service, B::Service>;
|
||||||
type Error = A::InitError;
|
type Error = A::InitError;
|
||||||
@@ -222,11 +218,10 @@ mod tests {
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use service::{NewServiceExt, Service, ServiceExt};
|
use crate::{NewService, Service};
|
||||||
|
|
||||||
struct Srv1(Rc<Cell<usize>>);
|
struct Srv1(Rc<Cell<usize>>);
|
||||||
impl Service for Srv1 {
|
impl Service<&'static str> for Srv1 {
|
||||||
type Request = &'static str;
|
|
||||||
type Response = &'static str;
|
type Response = &'static str;
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type Future = FutureResult<Self::Response, ()>;
|
type Future = FutureResult<Self::Response, ()>;
|
||||||
@@ -236,7 +231,7 @@ mod tests {
|
|||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: &'static str) -> Self::Future {
|
||||||
ok(req)
|
ok(req)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -244,8 +239,7 @@ mod tests {
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct Srv2(Rc<Cell<usize>>);
|
struct Srv2(Rc<Cell<usize>>);
|
||||||
|
|
||||||
impl Service for Srv2 {
|
impl Service<&'static str> for Srv2 {
|
||||||
type Request = &'static str;
|
|
||||||
type Response = (&'static str, &'static str);
|
type Response = (&'static str, &'static str);
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type Future = FutureResult<Self::Response, ()>;
|
type Future = FutureResult<Self::Response, ()>;
|
||||||
@@ -255,7 +249,7 @@ mod tests {
|
|||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: &'static str) -> Self::Future {
|
||||||
ok((req, "srv2"))
|
ok((req, "srv2"))
|
||||||
}
|
}
|
||||||
}
|
}
|
@@ -5,21 +5,23 @@ use futures::{Async, Future, IntoFuture, Poll};
|
|||||||
use super::{IntoNewService, IntoService, NewService, Service};
|
use super::{IntoNewService, IntoService, NewService, Service};
|
||||||
|
|
||||||
/// `Apply` service combinator
|
/// `Apply` service combinator
|
||||||
pub struct Apply<T, F, R, Req> {
|
pub struct Apply<T, F, In, Out, Request>
|
||||||
|
where
|
||||||
|
T: Service<Request>,
|
||||||
|
{
|
||||||
service: T,
|
service: T,
|
||||||
f: F,
|
f: F,
|
||||||
r: PhantomData<(Req, R)>,
|
r: PhantomData<(In, Out, Request)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, F, R, Req> Apply<T, F, R, Req>
|
impl<T, F, In, Out, Request> Apply<T, F, In, Out, Request>
|
||||||
where
|
where
|
||||||
T: Service,
|
T: Service<Request>,
|
||||||
T::Error: Into<<R::Future as Future>::Error>,
|
F: Fn(In, &mut T) -> Out,
|
||||||
F: Fn(Req, &mut T) -> R,
|
Out: IntoFuture,
|
||||||
R: IntoFuture,
|
|
||||||
{
|
{
|
||||||
/// Create new `Apply` combinator
|
/// Create new `Apply` combinator
|
||||||
pub fn new<I: IntoService<T>>(service: I, f: F) -> Self {
|
pub fn new<I: IntoService<T, Request>>(service: I, f: F) -> Self {
|
||||||
Self {
|
Self {
|
||||||
service: service.into_service(),
|
service: service.into_service(),
|
||||||
f,
|
f,
|
||||||
@@ -28,12 +30,10 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, F, R, Req> Clone for Apply<T, F, R, Req>
|
impl<T, F, In, Out, Request> Clone for Apply<T, F, In, Out, Request>
|
||||||
where
|
where
|
||||||
T: Service + Clone,
|
T: Service<Request> + Clone,
|
||||||
T::Error: Into<<R::Future as Future>::Error>,
|
F: Clone,
|
||||||
F: Fn(Req, &mut T) -> R + Clone,
|
|
||||||
R: IntoFuture,
|
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Apply {
|
Apply {
|
||||||
@@ -44,42 +44,43 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, F, R, Req> Service for Apply<T, F, R, Req>
|
impl<T, F, In, Out, Request> Service<In> for Apply<T, F, In, Out, Request>
|
||||||
where
|
where
|
||||||
T: Service,
|
T: Service<Request, Error = Out::Error>,
|
||||||
T::Error: Into<<R::Future as Future>::Error>,
|
F: Fn(In, &mut T) -> Out,
|
||||||
F: Fn(Req, &mut T) -> R,
|
Out: IntoFuture,
|
||||||
R: IntoFuture,
|
|
||||||
{
|
{
|
||||||
type Request = Req;
|
type Response = Out::Item;
|
||||||
type Response = <R::Future as Future>::Item;
|
type Error = Out::Error;
|
||||||
type Error = <R::Future as Future>::Error;
|
type Future = Out::Future;
|
||||||
type Future = R::Future;
|
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
self.service.poll_ready().map_err(|e| e.into())
|
self.service.poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: In) -> Self::Future {
|
||||||
(self.f)(req, &mut self.service).into_future()
|
(self.f)(req, &mut self.service).into_future()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `ApplyNewService` new service combinator
|
/// `ApplyNewService` new service combinator
|
||||||
pub struct ApplyNewService<T, F, R, Req> {
|
pub struct ApplyNewService<T, F, In, Out, Request>
|
||||||
|
where
|
||||||
|
T: NewService<Request>,
|
||||||
|
{
|
||||||
service: T,
|
service: T,
|
||||||
f: F,
|
f: F,
|
||||||
r: PhantomData<Fn(Req) -> R>,
|
r: PhantomData<(In, Out, Request)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, F, R, Req> ApplyNewService<T, F, R, Req>
|
impl<T, F, In, Out, Request> ApplyNewService<T, F, In, Out, Request>
|
||||||
where
|
where
|
||||||
T: NewService,
|
T: NewService<Request>,
|
||||||
F: Fn(Req, &mut T::Service) -> R,
|
F: Fn(In, &mut T::Service) -> Out,
|
||||||
R: IntoFuture,
|
Out: IntoFuture,
|
||||||
{
|
{
|
||||||
/// Create new `ApplyNewService` new service instance
|
/// Create new `ApplyNewService` new service instance
|
||||||
pub fn new<F1: IntoNewService<T>>(service: F1, f: F) -> Self {
|
pub fn new<F1: IntoNewService<T, Request>>(service: F1, f: F) -> Self {
|
||||||
Self {
|
Self {
|
||||||
f,
|
f,
|
||||||
service: service.into_new_service(),
|
service: service.into_new_service(),
|
||||||
@@ -88,11 +89,11 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, F, R, Req> Clone for ApplyNewService<T, F, R, Req>
|
impl<T, F, In, Out, Request> Clone for ApplyNewService<T, F, In, Out, Request>
|
||||||
where
|
where
|
||||||
T: NewService + Clone,
|
T: NewService<Request> + Clone,
|
||||||
F: Fn(Req, &mut T::Service) -> R + Clone,
|
F: Fn(Out, &mut T::Service) -> Out + Clone,
|
||||||
R: IntoFuture,
|
Out: IntoFuture,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -103,42 +104,40 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, F, R, Req> NewService for ApplyNewService<T, F, R, Req>
|
impl<T, F, In, Out, Request> NewService<In> for ApplyNewService<T, F, In, Out, Request>
|
||||||
where
|
where
|
||||||
T: NewService,
|
T: NewService<Request, Error = Out::Error>,
|
||||||
T::Error: Into<<R::Future as Future>::Error>,
|
F: Fn(In, &mut T::Service) -> Out + Clone,
|
||||||
F: Fn(Req, &mut T::Service) -> R + Clone,
|
Out: IntoFuture,
|
||||||
R: IntoFuture,
|
|
||||||
{
|
{
|
||||||
type Request = Req;
|
type Response = Out::Item;
|
||||||
type Response = <R::Future as Future>::Item;
|
type Error = Out::Error;
|
||||||
type Error = <R::Future as Future>::Error;
|
type Service = Apply<T::Service, F, In, Out, Request>;
|
||||||
type Service = Apply<T::Service, F, R, Req>;
|
|
||||||
|
|
||||||
type InitError = T::InitError;
|
type InitError = T::InitError;
|
||||||
type Future = ApplyNewServiceFuture<T, F, R, Req>;
|
type Future = ApplyNewServiceFuture<T, F, In, Out, Request>;
|
||||||
|
|
||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
ApplyNewServiceFuture::new(self.service.new_service(), self.f.clone())
|
ApplyNewServiceFuture::new(self.service.new_service(), self.f.clone())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ApplyNewServiceFuture<T, F, R, Req>
|
pub struct ApplyNewServiceFuture<T, F, In, Out, Request>
|
||||||
where
|
where
|
||||||
T: NewService,
|
T: NewService<Request>,
|
||||||
F: Fn(Req, &mut T::Service) -> R,
|
F: Fn(In, &mut T::Service) -> Out,
|
||||||
R: IntoFuture,
|
Out: IntoFuture,
|
||||||
{
|
{
|
||||||
fut: T::Future,
|
fut: T::Future,
|
||||||
f: Option<F>,
|
f: Option<F>,
|
||||||
r: PhantomData<Fn(Req) -> R>,
|
r: PhantomData<(In, Out)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, F, R, Req> ApplyNewServiceFuture<T, F, R, Req>
|
impl<T, F, In, Out, Request> ApplyNewServiceFuture<T, F, In, Out, Request>
|
||||||
where
|
where
|
||||||
T: NewService,
|
T: NewService<Request>,
|
||||||
F: Fn(Req, &mut T::Service) -> R,
|
F: Fn(In, &mut T::Service) -> Out,
|
||||||
R: IntoFuture,
|
Out: IntoFuture,
|
||||||
{
|
{
|
||||||
fn new(fut: T::Future, f: F) -> Self {
|
fn new(fut: T::Future, f: F) -> Self {
|
||||||
ApplyNewServiceFuture {
|
ApplyNewServiceFuture {
|
||||||
@@ -149,14 +148,13 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, F, R, Req> Future for ApplyNewServiceFuture<T, F, R, Req>
|
impl<T, F, In, Out, Request> Future for ApplyNewServiceFuture<T, F, In, Out, Request>
|
||||||
where
|
where
|
||||||
T: NewService,
|
T: NewService<Request>,
|
||||||
T::Error: Into<<R::Future as Future>::Error>,
|
F: Fn(In, &mut T::Service) -> Out,
|
||||||
F: Fn(Req, &mut T::Service) -> R,
|
Out: IntoFuture,
|
||||||
R: IntoFuture,
|
|
||||||
{
|
{
|
||||||
type Item = Apply<T::Service, F, R, Req>;
|
type Item = Apply<T::Service, F, In, Out, Request>;
|
||||||
type Error = T::InitError;
|
type Error = T::InitError;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
@@ -173,14 +171,11 @@ mod tests {
|
|||||||
use futures::future::{ok, FutureResult};
|
use futures::future::{ok, FutureResult};
|
||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
|
|
||||||
use service::{
|
use crate::{IntoNewService, IntoService, NewService, Service};
|
||||||
IntoNewService, IntoService, NewService, NewServiceExt, Service, ServiceExt,
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct Srv;
|
struct Srv;
|
||||||
impl Service for Srv {
|
impl Service<()> for Srv {
|
||||||
type Request = ();
|
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type Future = FutureResult<(), ()>;
|
type Future = FutureResult<(), ()>;
|
32
actix-service/src/cell.rs
Normal file
32
actix-service/src/cell.rs
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
//! 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() }
|
||||||
|
}
|
||||||
|
}
|
@@ -42,12 +42,11 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F, Req, Resp, E, Fut> Service for FnService<F, Req, Resp, E, Fut>
|
impl<F, Req, Resp, E, Fut> Service<Req> for FnService<F, Req, Resp, E, Fut>
|
||||||
where
|
where
|
||||||
F: Fn(Req) -> Fut,
|
F: Fn(Req) -> Fut,
|
||||||
Fut: IntoFuture<Item = Resp, Error = E>,
|
Fut: IntoFuture<Item = Resp, Error = E>,
|
||||||
{
|
{
|
||||||
type Request = Req;
|
|
||||||
type Response = Resp;
|
type Response = Resp;
|
||||||
type Error = E;
|
type Error = E;
|
||||||
type Future = Fut::Future;
|
type Future = Fut::Future;
|
||||||
@@ -61,7 +60,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F, Req, Resp, Err, Fut> IntoService<FnService<F, Req, Resp, Err, Fut>> for F
|
impl<F, Req, Resp, Err, Fut> IntoService<FnService<F, Req, Resp, Err, Fut>, Req> for F
|
||||||
where
|
where
|
||||||
F: Fn(Req) -> Fut + 'static,
|
F: Fn(Req) -> Fut + 'static,
|
||||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||||
@@ -93,12 +92,11 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F, Req, Resp, Err, Fut> NewService for FnNewService<F, Req, Resp, Err, Fut>
|
impl<F, Req, Resp, Err, Fut> NewService<Req> for FnNewService<F, Req, Resp, Err, Fut>
|
||||||
where
|
where
|
||||||
F: Fn(Req) -> Fut + Clone,
|
F: Fn(Req) -> Fut + Clone,
|
||||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||||
{
|
{
|
||||||
type Request = Req;
|
|
||||||
type Response = Resp;
|
type Response = Resp;
|
||||||
type Error = Err;
|
type Error = Err;
|
||||||
type Service = FnService<F, Req, Resp, Err, Fut>;
|
type Service = FnService<F, Req, Resp, Err, Fut>;
|
||||||
@@ -110,7 +108,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F, Req, Resp, Err, Fut> IntoNewService<FnNewService<F, Req, Resp, Err, Fut>> for F
|
impl<F, Req, Resp, Err, Fut> IntoNewService<FnNewService<F, Req, Resp, Err, Fut>, Req> for F
|
||||||
where
|
where
|
||||||
F: Fn(Req) -> Fut + Clone + 'static,
|
F: Fn(Req) -> Fut + Clone + 'static,
|
||||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
Fut: IntoFuture<Item = Resp, Error = Err>,
|
@@ -7,16 +7,17 @@ use super::{NewService, Service};
|
|||||||
/// Service for the `from_err` combinator, changing the error type of a service.
|
/// Service for the `from_err` combinator, changing the error type of a service.
|
||||||
///
|
///
|
||||||
/// This is created by the `ServiceExt::from_err` method.
|
/// This is created by the `ServiceExt::from_err` method.
|
||||||
pub struct FromErr<A, E>
|
pub struct FromErr<A, E> {
|
||||||
where
|
|
||||||
A: Service,
|
|
||||||
{
|
|
||||||
service: A,
|
service: A,
|
||||||
f: PhantomData<E>,
|
f: PhantomData<E>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A: Service, E: From<A::Error>> FromErr<A, E> {
|
impl<A, E> FromErr<A, E> {
|
||||||
pub(crate) fn new(service: A) -> Self {
|
pub(crate) fn new<Request>(service: A) -> Self
|
||||||
|
where
|
||||||
|
A: Service<Request>,
|
||||||
|
E: From<A::Error>,
|
||||||
|
{
|
||||||
FromErr {
|
FromErr {
|
||||||
service,
|
service,
|
||||||
f: PhantomData,
|
f: PhantomData,
|
||||||
@@ -26,8 +27,7 @@ impl<A: Service, E: From<A::Error>> FromErr<A, E> {
|
|||||||
|
|
||||||
impl<A, E> Clone for FromErr<A, E>
|
impl<A, E> Clone for FromErr<A, E>
|
||||||
where
|
where
|
||||||
A: Service + Clone,
|
A: Clone,
|
||||||
E: From<A::Error>,
|
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
FromErr {
|
FromErr {
|
||||||
@@ -37,21 +37,20 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, E> Service for FromErr<A, E>
|
impl<A, E, Request> Service<Request> for FromErr<A, E>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
E: From<A::Error>,
|
E: From<A::Error>,
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
|
||||||
type Response = A::Response;
|
type Response = A::Response;
|
||||||
type Error = E;
|
type Error = E;
|
||||||
type Future = FromErrFuture<A, E>;
|
type Future = FromErrFuture<A, E, Request>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), E> {
|
fn poll_ready(&mut self) -> Poll<(), E> {
|
||||||
Ok(self.service.poll_ready().map_err(E::from)?)
|
Ok(self.service.poll_ready().map_err(E::from)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Request) -> Self::Future {
|
||||||
FromErrFuture {
|
FromErrFuture {
|
||||||
fut: self.service.call(req),
|
fut: self.service.call(req),
|
||||||
f: PhantomData,
|
f: PhantomData,
|
||||||
@@ -59,14 +58,14 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FromErrFuture<A: Service, E> {
|
pub struct FromErrFuture<A: Service<Request>, E, Request> {
|
||||||
fut: A::Future,
|
fut: A::Future,
|
||||||
f: PhantomData<E>,
|
f: PhantomData<E>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, E> Future for FromErrFuture<A, E>
|
impl<A, E, Request> Future for FromErrFuture<A, E, Request>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
E: From<A::Error>,
|
E: From<A::Error>,
|
||||||
{
|
{
|
||||||
type Item = A::Response;
|
type Item = A::Response;
|
||||||
@@ -86,21 +85,20 @@ pub struct FromErrNewService<A, E> {
|
|||||||
e: PhantomData<E>,
|
e: PhantomData<E>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, E> FromErrNewService<A, E>
|
impl<A, E> FromErrNewService<A, E> {
|
||||||
|
/// Create new `FromErr` new service instance
|
||||||
|
pub fn new<Request>(a: A) -> Self
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
E: From<A::Error>,
|
E: From<A::Error>,
|
||||||
{
|
{
|
||||||
/// Create new `FromErr` new service instance
|
|
||||||
pub fn new(a: A) -> Self {
|
|
||||||
Self { a, e: PhantomData }
|
Self { a, e: PhantomData }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, E> Clone for FromErrNewService<A, E>
|
impl<A, E> Clone for FromErrNewService<A, E>
|
||||||
where
|
where
|
||||||
A: NewService + Clone,
|
A: Clone,
|
||||||
E: From<A::Error>,
|
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -110,18 +108,17 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, E> NewService for FromErrNewService<A, E>
|
impl<A, E, Request> NewService<Request> for FromErrNewService<A, E>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
E: From<A::Error>,
|
E: From<A::Error>,
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
|
||||||
type Response = A::Response;
|
type Response = A::Response;
|
||||||
type Error = E;
|
type Error = E;
|
||||||
type Service = FromErr<A::Service, E>;
|
type Service = FromErr<A::Service, E>;
|
||||||
|
|
||||||
type InitError = A::InitError;
|
type InitError = A::InitError;
|
||||||
type Future = FromErrNewServiceFuture<A, E>;
|
type Future = FromErrNewServiceFuture<A, E, Request>;
|
||||||
|
|
||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
FromErrNewServiceFuture {
|
FromErrNewServiceFuture {
|
||||||
@@ -131,18 +128,18 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct FromErrNewServiceFuture<A, E>
|
pub struct FromErrNewServiceFuture<A, E, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
E: From<A::Error>,
|
E: From<A::Error>,
|
||||||
{
|
{
|
||||||
fut: A::Future,
|
fut: A::Future,
|
||||||
e: PhantomData<E>,
|
e: PhantomData<E>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, E> Future for FromErrNewServiceFuture<A, E>
|
impl<A, E, Request> Future for FromErrNewServiceFuture<A, E, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
E: From<A::Error>,
|
E: From<A::Error>,
|
||||||
{
|
{
|
||||||
type Item = FromErr<A::Service, E>;
|
type Item = FromErr<A::Service, E>;
|
||||||
@@ -162,11 +159,10 @@ mod tests {
|
|||||||
use futures::future::{err, FutureResult};
|
use futures::future::{err, FutureResult};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use service::{IntoNewService, NewServiceExt, Service, ServiceExt};
|
use crate::{IntoNewService, NewService, Service};
|
||||||
|
|
||||||
struct Srv;
|
struct Srv;
|
||||||
impl Service for Srv {
|
impl Service<()> for Srv {
|
||||||
type Request = ();
|
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type Future = FutureResult<(), ()>;
|
type Future = FutureResult<(), ()>;
|
@@ -1,10 +1,7 @@
|
|||||||
use futures::{Future, IntoFuture};
|
use futures::{Future, IntoFuture, Poll};
|
||||||
|
|
||||||
/// re-export for convinience
|
|
||||||
pub use tower_service::{NewService, Service};
|
|
||||||
|
|
||||||
mod and_then;
|
mod and_then;
|
||||||
mod apply;
|
mod apply;
|
||||||
|
mod cell;
|
||||||
mod fn_service;
|
mod fn_service;
|
||||||
mod from_err;
|
mod from_err;
|
||||||
mod map;
|
mod map;
|
||||||
@@ -21,21 +18,52 @@ pub use self::map_err::{MapErr, MapErrNewService};
|
|||||||
pub use self::map_init_err::MapInitErr;
|
pub use self::map_init_err::MapInitErr;
|
||||||
pub use self::then::{Then, ThenNewService};
|
pub use self::then::{Then, ThenNewService};
|
||||||
|
|
||||||
/// An extension trait for `Service`s that provides a variety of convenient
|
/// An asynchronous function from `Request` to a `Response`.
|
||||||
/// adapters
|
pub trait Service<Request> {
|
||||||
pub trait ServiceExt: Service {
|
/// 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;
|
||||||
|
|
||||||
/// Apply function to specified service and use it as a next service in
|
/// Apply function to specified service and use it as a next service in
|
||||||
/// chain.
|
/// chain.
|
||||||
fn apply<S, I, F, R>(
|
fn apply<T, I, F, Out, Req>(
|
||||||
self, service: I, f: F,
|
self,
|
||||||
) -> AndThen<Self, Apply<S, F, R, Self::Response>>
|
service: I,
|
||||||
|
f: F,
|
||||||
|
) -> AndThen<Self, Apply<T, F, Self::Response, Out, Req>>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
S: Service,
|
T: Service<Req, Error = Self::Error>,
|
||||||
S::Error: Into<<R::Future as Future>::Error>,
|
I: IntoService<T, Req>,
|
||||||
I: IntoService<S>,
|
F: Fn(Self::Response, &mut T) -> Out,
|
||||||
F: Fn(Self::Response, &mut S) -> R,
|
Out: IntoFuture<Error = Self::Error>,
|
||||||
R: IntoFuture<Error = Self::Error>,
|
|
||||||
{
|
{
|
||||||
self.and_then(Apply::new(service.into_service(), f))
|
self.and_then(Apply::new(service.into_service(), f))
|
||||||
}
|
}
|
||||||
@@ -52,8 +80,8 @@ pub trait ServiceExt: Service {
|
|||||||
fn and_then<F, B>(self, service: F) -> AndThen<Self, B>
|
fn and_then<F, B>(self, service: F) -> AndThen<Self, B>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
F: IntoService<B>,
|
F: IntoService<B, Self::Response>,
|
||||||
B: Service<Request = Self::Response, Error = Self::Error>,
|
B: Service<Self::Response, Error = Self::Error>,
|
||||||
{
|
{
|
||||||
AndThen::new(self, service.into_service())
|
AndThen::new(self, service.into_service())
|
||||||
}
|
}
|
||||||
@@ -74,12 +102,12 @@ pub trait ServiceExt: Service {
|
|||||||
/// Chain on a computation for when a call to the service finished,
|
/// Chain on a computation for when a call to the service finished,
|
||||||
/// passing the result of the call to the next service `B`.
|
/// passing the result of the call to the next service `B`.
|
||||||
///
|
///
|
||||||
/// Note that this function consumes the receiving future and returns a
|
/// Note that this function consumes the receiving service and returns a
|
||||||
/// wrapped version of it.
|
/// wrapped version of it.
|
||||||
fn then<B>(self, service: B) -> Then<Self, B>
|
fn then<B>(self, service: B) -> Then<Self, B>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
B: Service<Request = Result<Self::Response, Self::Error>, Error = Self::Error>,
|
B: Service<Result<Self::Response, Self::Error>, Error = Self::Error>,
|
||||||
{
|
{
|
||||||
Then::new(self, service)
|
Then::new(self, service)
|
||||||
}
|
}
|
||||||
@@ -118,30 +146,57 @@ pub trait ServiceExt: Service {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait NewServiceExt: NewService {
|
/// Creates new `Service` values.
|
||||||
fn apply<S, I, F, R>(
|
///
|
||||||
self, service: I, f: F,
|
/// Acts as a service factory. This is useful for cases where new `Service`
|
||||||
) -> AndThenNewService<Self, ApplyNewService<S, F, R, Self::Response>>
|
/// 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>(
|
||||||
|
self,
|
||||||
|
service: I,
|
||||||
|
f: F,
|
||||||
|
) -> AndThenNewService<Self, ApplyNewService<T, F, Self::Response, Out, Req>>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
S: NewService<InitError = Self::InitError>,
|
T: NewService<Req, InitError = Self::InitError, Error = Self::Error>,
|
||||||
S::Error: Into<<R::Future as Future>::Error>,
|
I: IntoNewService<T, Req>,
|
||||||
I: IntoNewService<S>,
|
F: Fn(Self::Response, &mut T::Service) -> Out + Clone,
|
||||||
F: Fn(Self::Response, &mut S::Service) -> R + Clone,
|
Out: IntoFuture<Error = Self::Error>,
|
||||||
R: IntoFuture<Error = Self::Error>,
|
|
||||||
{
|
{
|
||||||
self.and_then(ApplyNewService::new(service, f))
|
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>
|
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
F: IntoNewService<B>,
|
F: IntoNewService<B, Self::Response>,
|
||||||
B: NewService<
|
B: NewService<Self::Response, Error = Self::Error, InitError = Self::InitError>,
|
||||||
Request = Self::Response,
|
|
||||||
Error = Self::Error,
|
|
||||||
InitError = Self::InitError,
|
|
||||||
>,
|
|
||||||
{
|
{
|
||||||
AndThenNewService::new(self, new_service)
|
AndThenNewService::new(self, new_service)
|
||||||
}
|
}
|
||||||
@@ -169,9 +224,9 @@ pub trait NewServiceExt: NewService {
|
|||||||
fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B>
|
fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
F: IntoNewService<B>,
|
F: IntoNewService<B, Result<Self::Response, Self::Error>>,
|
||||||
B: NewService<
|
B: NewService<
|
||||||
Request = Result<Self::Response, Self::Error>,
|
Result<Self::Response, Self::Error>,
|
||||||
Error = Self::Error,
|
Error = Self::Error,
|
||||||
InitError = Self::InitError,
|
InitError = Self::InitError,
|
||||||
>,
|
>,
|
||||||
@@ -179,6 +234,8 @@ pub trait NewServiceExt: NewService {
|
|||||||
ThenNewService::new(self, new_service)
|
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>
|
fn map<F, R>(self, f: F) -> MapNewService<Self, F, R>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
@@ -187,6 +244,7 @@ pub trait NewServiceExt: NewService {
|
|||||||
MapNewService::new(self, f)
|
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>
|
fn map_err<F, E>(self, f: F) -> MapErrNewService<Self, F, E>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
@@ -195,6 +253,7 @@ pub trait NewServiceExt: NewService {
|
|||||||
MapErrNewService::new(self, f)
|
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>
|
fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, E>
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
@@ -204,39 +263,70 @@ pub trait NewServiceExt: NewService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: ?Sized> ServiceExt for T where T: Service {}
|
impl<'a, S, Request> Service<Request> for &'a mut S
|
||||||
impl<T: ?Sized> NewServiceExt for T where T: NewService {}
|
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<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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Trait for types that can be converted to a `Service`
|
/// Trait for types that can be converted to a `Service`
|
||||||
pub trait IntoService<T>
|
pub trait IntoService<T, Request>
|
||||||
where
|
where
|
||||||
T: Service,
|
T: Service<Request>,
|
||||||
{
|
{
|
||||||
/// Convert to a `Service`
|
/// Convert to a `Service`
|
||||||
fn into_service(self) -> T;
|
fn into_service(self) -> T;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Trait for types that can be converted to a Service
|
/// Trait for types that can be converted to a Service
|
||||||
pub trait IntoNewService<T>
|
pub trait IntoNewService<T, Request>
|
||||||
where
|
where
|
||||||
T: NewService,
|
T: NewService<Request>,
|
||||||
{
|
{
|
||||||
/// Convert to an `NewService`
|
/// Convert to an `NewService`
|
||||||
fn into_new_service(self) -> T;
|
fn into_new_service(self) -> T;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> IntoService<T> for T
|
impl<T, Request> IntoService<T, Request> for T
|
||||||
where
|
where
|
||||||
T: Service,
|
T: Service<Request>,
|
||||||
{
|
{
|
||||||
fn into_service(self) -> T {
|
fn into_service(self) -> T {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> IntoNewService<T> for T
|
impl<T, Request> IntoNewService<T, Request> for T
|
||||||
where
|
where
|
||||||
T: NewService,
|
T: NewService<Request>,
|
||||||
{
|
{
|
||||||
fn into_new_service(self) -> T {
|
fn into_new_service(self) -> T {
|
||||||
self
|
self
|
@@ -1,4 +1,4 @@
|
|||||||
use std::marker;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
|
|
||||||
@@ -7,83 +7,84 @@ use super::{NewService, Service};
|
|||||||
/// Service for the `map` combinator, changing the type of a service's response.
|
/// Service for the `map` combinator, changing the type of a service's response.
|
||||||
///
|
///
|
||||||
/// This is created by the `ServiceExt::map` method.
|
/// This is created by the `ServiceExt::map` method.
|
||||||
pub struct Map<A, F, R>
|
pub struct Map<A, F, Response> {
|
||||||
where
|
|
||||||
A: Service,
|
|
||||||
F: Fn(A::Response) -> R,
|
|
||||||
{
|
|
||||||
service: A,
|
service: A,
|
||||||
f: F,
|
f: F,
|
||||||
|
_t: PhantomData<Response>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, R> Map<A, F, R>
|
impl<A, F, Response> Map<A, F, Response> {
|
||||||
where
|
|
||||||
A: Service,
|
|
||||||
F: Fn(A::Response) -> R,
|
|
||||||
{
|
|
||||||
/// Create new `Map` combinator
|
/// Create new `Map` combinator
|
||||||
pub fn new(service: A, f: F) -> Self {
|
pub fn new<Request>(service: A, f: F) -> Self
|
||||||
Self { service, f }
|
where
|
||||||
|
A: Service<Request>,
|
||||||
|
F: Fn(A::Response) -> Response,
|
||||||
|
{
|
||||||
|
Self {
|
||||||
|
service,
|
||||||
|
f,
|
||||||
|
_t: PhantomData,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, R> Clone for Map<A, F, R>
|
impl<A, F, Response> Clone for Map<A, F, Response>
|
||||||
where
|
where
|
||||||
A: Service + Clone,
|
A: Clone,
|
||||||
F: Fn(A::Response) -> R + Clone,
|
F: Clone,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Map {
|
Map {
|
||||||
service: self.service.clone(),
|
service: self.service.clone(),
|
||||||
f: self.f.clone(),
|
f: self.f.clone(),
|
||||||
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, R> Service for Map<A, F, R>
|
impl<A, F, Request, Response> Service<Request> for Map<A, F, Response>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
F: Fn(A::Response) -> R + Clone,
|
F: Fn(A::Response) -> Response + Clone,
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
type Response = Response;
|
||||||
type Response = R;
|
|
||||||
type Error = A::Error;
|
type Error = A::Error;
|
||||||
type Future = MapFuture<A, F, R>;
|
type Future = MapFuture<A, F, Request, Response>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
self.service.poll_ready()
|
self.service.poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Request) -> Self::Future {
|
||||||
MapFuture::new(self.service.call(req), self.f.clone())
|
MapFuture::new(self.service.call(req), self.f.clone())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct MapFuture<A, F, R>
|
pub struct MapFuture<A, F, Request, Response>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
F: Fn(A::Response) -> R,
|
F: Fn(A::Response) -> Response,
|
||||||
{
|
{
|
||||||
f: F,
|
f: F,
|
||||||
fut: A::Future,
|
fut: A::Future,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, R> MapFuture<A, F, R>
|
impl<A, F, Request, Response> MapFuture<A, F, Request, Response>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
F: Fn(A::Response) -> R,
|
F: Fn(A::Response) -> Response,
|
||||||
{
|
{
|
||||||
fn new(fut: A::Future, f: F) -> Self {
|
fn new(fut: A::Future, f: F) -> Self {
|
||||||
MapFuture { f, fut }
|
MapFuture { f, fut }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, R> Future for MapFuture<A, F, R>
|
impl<A, F, Request, Response> Future for MapFuture<A, F, Request, Response>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
F: Fn(A::Response) -> R,
|
F: Fn(A::Response) -> Response,
|
||||||
{
|
{
|
||||||
type Item = R;
|
type Item = Response;
|
||||||
type Error = A::Error;
|
type Error = A::Error;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
@@ -95,84 +96,83 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// `MapNewService` new service combinator
|
/// `MapNewService` new service combinator
|
||||||
pub struct MapNewService<A, F, R> {
|
pub struct MapNewService<A, F, Response> {
|
||||||
a: A,
|
a: A,
|
||||||
f: F,
|
f: F,
|
||||||
r: marker::PhantomData<R>,
|
r: PhantomData<Response>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, R> MapNewService<A, F, R>
|
impl<A, F, Response> MapNewService<A, F, Response> {
|
||||||
where
|
|
||||||
A: NewService,
|
|
||||||
F: Fn(A::Response) -> R,
|
|
||||||
{
|
|
||||||
/// Create new `Map` new service instance
|
/// Create new `Map` new service instance
|
||||||
pub fn new(a: A, f: F) -> Self {
|
pub fn new<Request>(a: A, f: F) -> Self
|
||||||
|
where
|
||||||
|
A: NewService<Request>,
|
||||||
|
F: Fn(A::Response) -> Response,
|
||||||
|
{
|
||||||
Self {
|
Self {
|
||||||
a,
|
a,
|
||||||
f,
|
f,
|
||||||
r: marker::PhantomData,
|
r: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, R> Clone for MapNewService<A, F, R>
|
impl<A, F, Response> Clone for MapNewService<A, F, Response>
|
||||||
where
|
where
|
||||||
A: NewService + Clone,
|
A: Clone,
|
||||||
F: Fn(A::Response) -> R + Clone,
|
F: Clone,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
a: self.a.clone(),
|
a: self.a.clone(),
|
||||||
f: self.f.clone(),
|
f: self.f.clone(),
|
||||||
r: marker::PhantomData,
|
r: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, R> NewService for MapNewService<A, F, R>
|
impl<A, F, Request, Response> NewService<Request> for MapNewService<A, F, Response>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::Response) -> R + Clone,
|
F: Fn(A::Response) -> Response + Clone,
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
type Response = Response;
|
||||||
type Response = R;
|
|
||||||
type Error = A::Error;
|
type Error = A::Error;
|
||||||
type Service = Map<A::Service, F, R>;
|
type Service = Map<A::Service, F, Response>;
|
||||||
|
|
||||||
type InitError = A::InitError;
|
type InitError = A::InitError;
|
||||||
type Future = MapNewServiceFuture<A, F, R>;
|
type Future = MapNewServiceFuture<A, F, Request, Response>;
|
||||||
|
|
||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
MapNewServiceFuture::new(self.a.new_service(), self.f.clone())
|
MapNewServiceFuture::new(self.a.new_service(), self.f.clone())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct MapNewServiceFuture<A, F, R>
|
pub struct MapNewServiceFuture<A, F, Request, Response>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::Response) -> R,
|
F: Fn(A::Response) -> Response,
|
||||||
{
|
{
|
||||||
fut: A::Future,
|
fut: A::Future,
|
||||||
f: Option<F>,
|
f: Option<F>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, R> MapNewServiceFuture<A, F, R>
|
impl<A, F, Request, Response> MapNewServiceFuture<A, F, Request, Response>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::Response) -> R,
|
F: Fn(A::Response) -> Response,
|
||||||
{
|
{
|
||||||
fn new(fut: A::Future, f: F) -> Self {
|
fn new(fut: A::Future, f: F) -> Self {
|
||||||
MapNewServiceFuture { f: Some(f), fut }
|
MapNewServiceFuture { f: Some(f), fut }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, R> Future for MapNewServiceFuture<A, F, R>
|
impl<A, F, Request, Response> Future for MapNewServiceFuture<A, F, Request, Response>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::Response) -> R,
|
F: Fn(A::Response) -> Response,
|
||||||
{
|
{
|
||||||
type Item = Map<A::Service, F, R>;
|
type Item = Map<A::Service, F, Response>;
|
||||||
type Error = A::InitError;
|
type Error = A::InitError;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
@@ -189,11 +189,10 @@ mod tests {
|
|||||||
use futures::future::{ok, FutureResult};
|
use futures::future::{ok, FutureResult};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use service::{IntoNewService, NewServiceExt, Service, ServiceExt};
|
use crate::{IntoNewService, Service};
|
||||||
|
|
||||||
struct Srv;
|
struct Srv;
|
||||||
impl Service for Srv {
|
impl Service<()> for Srv {
|
||||||
type Request = ();
|
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type Future = FutureResult<(), ()>;
|
type Future = FutureResult<(), ()>;
|
@@ -1,4 +1,4 @@
|
|||||||
use std::marker;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
|
|
||||||
@@ -8,71 +8,71 @@ use super::{NewService, Service};
|
|||||||
/// error.
|
/// error.
|
||||||
///
|
///
|
||||||
/// This is created by the `ServiceExt::map_err` method.
|
/// 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,
|
service: A,
|
||||||
f: F,
|
f: F,
|
||||||
|
_t: PhantomData<E>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> MapErr<A, F, E>
|
impl<A, F, E> MapErr<A, F, E> {
|
||||||
|
/// Create new `MapErr` combinator
|
||||||
|
pub fn new<Request>(service: A, f: F) -> Self
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
F: Fn(A::Error) -> E,
|
F: Fn(A::Error) -> E,
|
||||||
{
|
{
|
||||||
/// Create new `MapErr` combinator
|
Self {
|
||||||
pub fn new(service: A, f: F) -> Self {
|
service,
|
||||||
Self { service, f }
|
f,
|
||||||
|
_t: PhantomData,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> Clone for MapErr<A, F, E>
|
impl<A, F, E> Clone for MapErr<A, F, E>
|
||||||
where
|
where
|
||||||
A: Service + Clone,
|
A: Clone,
|
||||||
F: Fn(A::Error) -> E + Clone,
|
F: Clone,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
MapErr {
|
MapErr {
|
||||||
service: self.service.clone(),
|
service: self.service.clone(),
|
||||||
f: self.f.clone(),
|
f: self.f.clone(),
|
||||||
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> Service for MapErr<A, F, E>
|
impl<A, F, E, Request> Service<Request> for MapErr<A, F, E>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
F: Fn(A::Error) -> E,
|
F: Fn(A::Error) -> E + Clone,
|
||||||
F: Clone,
|
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
|
||||||
type Response = A::Response;
|
type Response = A::Response;
|
||||||
type Error = E;
|
type Error = E;
|
||||||
type Future = MapErrFuture<A, F, E>;
|
type Future = MapErrFuture<A, F, E, Request>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
self.service.poll_ready().map_err(&self.f)
|
self.service.poll_ready().map_err(&self.f)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Request) -> Self::Future {
|
||||||
MapErrFuture::new(self.service.call(req), self.f.clone())
|
MapErrFuture::new(self.service.call(req), self.f.clone())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct MapErrFuture<A, F, E>
|
pub struct MapErrFuture<A, F, E, Request>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
F: Fn(A::Error) -> E,
|
F: Fn(A::Error) -> E,
|
||||||
{
|
{
|
||||||
f: F,
|
f: F,
|
||||||
fut: A::Future,
|
fut: A::Future,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> MapErrFuture<A, F, E>
|
impl<A, F, E, Request> MapErrFuture<A, F, E, Request>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
F: Fn(A::Error) -> E,
|
F: Fn(A::Error) -> E,
|
||||||
{
|
{
|
||||||
fn new(fut: A::Future, f: F) -> Self {
|
fn new(fut: A::Future, f: F) -> Self {
|
||||||
@@ -80,9 +80,9 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> Future for MapErrFuture<A, F, E>
|
impl<A, F, E, Request> Future for MapErrFuture<A, F, E, Request>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
F: Fn(A::Error) -> E,
|
F: Fn(A::Error) -> E,
|
||||||
{
|
{
|
||||||
type Item = A::Response;
|
type Item = A::Response;
|
||||||
@@ -100,68 +100,67 @@ where
|
|||||||
pub struct MapErrNewService<A, F, E> {
|
pub struct MapErrNewService<A, F, E> {
|
||||||
a: A,
|
a: A,
|
||||||
f: F,
|
f: F,
|
||||||
e: marker::PhantomData<E>,
|
e: PhantomData<E>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> MapErrNewService<A, F, E>
|
impl<A, F, E> MapErrNewService<A, F, E> {
|
||||||
|
/// Create new `MapErr` new service instance
|
||||||
|
pub fn new<Request>(a: A, f: F) -> Self
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::Error) -> E,
|
F: Fn(A::Error) -> E,
|
||||||
{
|
{
|
||||||
/// Create new `MapErr` new service instance
|
|
||||||
pub fn new(a: A, f: F) -> Self {
|
|
||||||
Self {
|
Self {
|
||||||
a,
|
a,
|
||||||
f,
|
f,
|
||||||
e: marker::PhantomData,
|
e: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> Clone for MapErrNewService<A, F, E>
|
impl<A, F, E> Clone for MapErrNewService<A, F, E>
|
||||||
where
|
where
|
||||||
A: NewService + Clone,
|
A: Clone,
|
||||||
F: Fn(A::Error) -> E + Clone,
|
F: Clone,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
a: self.a.clone(),
|
a: self.a.clone(),
|
||||||
f: self.f.clone(),
|
f: self.f.clone(),
|
||||||
e: marker::PhantomData,
|
e: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> NewService for MapErrNewService<A, F, E>
|
impl<A, F, E, Request> NewService<Request> for MapErrNewService<A, F, E>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::Error) -> E + Clone,
|
F: Fn(A::Error) -> E + Clone,
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
|
||||||
type Response = A::Response;
|
type Response = A::Response;
|
||||||
type Error = E;
|
type Error = E;
|
||||||
type Service = MapErr<A::Service, F, E>;
|
type Service = MapErr<A::Service, F, E>;
|
||||||
|
|
||||||
type InitError = A::InitError;
|
type InitError = A::InitError;
|
||||||
type Future = MapErrNewServiceFuture<A, F, E>;
|
type Future = MapErrNewServiceFuture<A, F, E, Request>;
|
||||||
|
|
||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
MapErrNewServiceFuture::new(self.a.new_service(), self.f.clone())
|
MapErrNewServiceFuture::new(self.a.new_service(), self.f.clone())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct MapErrNewServiceFuture<A, F, E>
|
pub struct MapErrNewServiceFuture<A, F, E, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::Error) -> E,
|
F: Fn(A::Error) -> E,
|
||||||
{
|
{
|
||||||
fut: A::Future,
|
fut: A::Future,
|
||||||
f: F,
|
f: F,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> MapErrNewServiceFuture<A, F, E>
|
impl<A, F, E, Request> MapErrNewServiceFuture<A, F, E, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::Error) -> E,
|
F: Fn(A::Error) -> E,
|
||||||
{
|
{
|
||||||
fn new(fut: A::Future, f: F) -> Self {
|
fn new(fut: A::Future, f: F) -> Self {
|
||||||
@@ -169,9 +168,9 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> Future for MapErrNewServiceFuture<A, F, E>
|
impl<A, F, E, Request> Future for MapErrNewServiceFuture<A, F, E, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::Error) -> E + Clone,
|
F: Fn(A::Error) -> E + Clone,
|
||||||
{
|
{
|
||||||
type Item = MapErr<A::Service, F, E>;
|
type Item = MapErr<A::Service, F, E>;
|
||||||
@@ -191,12 +190,11 @@ mod tests {
|
|||||||
use futures::future::{err, FutureResult};
|
use futures::future::{err, FutureResult};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use service::{IntoNewService, NewServiceExt, Service, ServiceExt};
|
use crate::{IntoNewService, NewService, Service};
|
||||||
|
|
||||||
struct Srv;
|
struct Srv;
|
||||||
|
|
||||||
impl Service for Srv {
|
impl Service<()> for Srv {
|
||||||
type Request = ();
|
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type Future = FutureResult<(), ()>;
|
type Future = FutureResult<(), ()>;
|
@@ -1,4 +1,4 @@
|
|||||||
use std::marker;
|
use std::marker::PhantomData;
|
||||||
|
|
||||||
use futures::{Future, Poll};
|
use futures::{Future, Poll};
|
||||||
|
|
||||||
@@ -8,68 +8,67 @@ use super::NewService;
|
|||||||
pub struct MapInitErr<A, F, E> {
|
pub struct MapInitErr<A, F, E> {
|
||||||
a: A,
|
a: A,
|
||||||
f: F,
|
f: F,
|
||||||
e: marker::PhantomData<E>,
|
e: PhantomData<E>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> MapInitErr<A, F, E>
|
impl<A, F, E> MapInitErr<A, F, E> {
|
||||||
|
/// Create new `MapInitErr` combinator
|
||||||
|
pub fn new<Request>(a: A, f: F) -> Self
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::InitError) -> E,
|
F: Fn(A::InitError) -> E,
|
||||||
{
|
{
|
||||||
/// Create new `MapInitErr` combinator
|
|
||||||
pub fn new(a: A, f: F) -> Self {
|
|
||||||
Self {
|
Self {
|
||||||
a,
|
a,
|
||||||
f,
|
f,
|
||||||
e: marker::PhantomData,
|
e: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> Clone for MapInitErr<A, F, E>
|
impl<A, F, E> Clone for MapInitErr<A, F, E>
|
||||||
where
|
where
|
||||||
A: NewService + Clone,
|
A: Clone,
|
||||||
F: Fn(A::InitError) -> E + Clone,
|
F: Clone,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
a: self.a.clone(),
|
a: self.a.clone(),
|
||||||
f: self.f.clone(),
|
f: self.f.clone(),
|
||||||
e: marker::PhantomData,
|
e: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> NewService for MapInitErr<A, F, E>
|
impl<A, F, E, Request> NewService<Request> for MapInitErr<A, F, E>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::InitError) -> E + Clone,
|
F: Fn(A::InitError) -> E + Clone,
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
|
||||||
type Response = A::Response;
|
type Response = A::Response;
|
||||||
type Error = A::Error;
|
type Error = A::Error;
|
||||||
type Service = A::Service;
|
type Service = A::Service;
|
||||||
|
|
||||||
type InitError = E;
|
type InitError = E;
|
||||||
type Future = MapInitErrFuture<A, F, E>;
|
type Future = MapInitErrFuture<A, F, E, Request>;
|
||||||
|
|
||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
MapInitErrFuture::new(self.a.new_service(), self.f.clone())
|
MapInitErrFuture::new(self.a.new_service(), self.f.clone())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct MapInitErrFuture<A, F, E>
|
pub struct MapInitErrFuture<A, F, E, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::InitError) -> E,
|
F: Fn(A::InitError) -> E,
|
||||||
{
|
{
|
||||||
f: F,
|
f: F,
|
||||||
fut: A::Future,
|
fut: A::Future,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> MapInitErrFuture<A, F, E>
|
impl<A, F, E, Request> MapInitErrFuture<A, F, E, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::InitError) -> E,
|
F: Fn(A::InitError) -> E,
|
||||||
{
|
{
|
||||||
fn new(fut: A::Future, f: F) -> Self {
|
fn new(fut: A::Future, f: F) -> Self {
|
||||||
@@ -77,9 +76,9 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, F, E> Future for MapInitErrFuture<A, F, E>
|
impl<A, F, E, Request> Future for MapInitErrFuture<A, F, E, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
F: Fn(A::InitError) -> E,
|
F: Fn(A::InitError) -> E,
|
||||||
{
|
{
|
||||||
type Item = A::Service;
|
type Item = A::Service;
|
@@ -1,7 +1,7 @@
|
|||||||
use futures::{Async, Future, Poll};
|
use futures::{try_ready, Async, Future, Poll};
|
||||||
|
|
||||||
use super::{IntoNewService, NewService, Service};
|
use super::{IntoNewService, NewService, Service};
|
||||||
use cell::Cell;
|
use crate::cell::Cell;
|
||||||
|
|
||||||
/// Service for the `then` combinator, chaining a computation onto the end of
|
/// Service for the `then` combinator, chaining a computation onto the end of
|
||||||
/// another service.
|
/// another service.
|
||||||
@@ -12,21 +12,20 @@ pub struct Then<A, B> {
|
|||||||
b: Cell<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
|
/// Create new `Then` combinator
|
||||||
pub fn new(a: A, b: B) -> Then<A, B> {
|
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>,
|
||||||
|
{
|
||||||
Then { a, b: Cell::new(b) }
|
Then { a, b: Cell::new(b) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Clone for Then<A, B>
|
impl<A, B> Clone for Then<A, B>
|
||||||
where
|
where
|
||||||
A: Service + Clone,
|
A: Clone,
|
||||||
B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
|
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Then {
|
Then {
|
||||||
@@ -36,40 +35,39 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Service for Then<A, B>
|
impl<A, B, Request> Service<Request> for Then<A, B>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
B: Service<Request = Result<A::Response, A::Error>, Error = A::Error>,
|
B: Service<Result<A::Response, A::Error>, Error = A::Error>,
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
|
||||||
type Response = B::Response;
|
type Response = B::Response;
|
||||||
type Error = B::Error;
|
type Error = B::Error;
|
||||||
type Future = ThenFuture<A, B>;
|
type Future = ThenFuture<A, B, Request>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
let _ = try_ready!(self.a.poll_ready());
|
try_ready!(self.a.poll_ready());
|
||||||
self.b.borrow_mut().poll_ready()
|
self.b.get_mut().poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Request) -> Self::Future {
|
||||||
ThenFuture::new(self.a.call(req), self.b.clone())
|
ThenFuture::new(self.a.call(req), self.b.clone())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ThenFuture<A, B>
|
pub struct ThenFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
B: Service<Request = Result<A::Response, A::Error>>,
|
B: Service<Result<A::Response, A::Error>>,
|
||||||
{
|
{
|
||||||
b: Cell<B>,
|
b: Cell<B>,
|
||||||
fut_b: Option<B::Future>,
|
fut_b: Option<B::Future>,
|
||||||
fut_a: A::Future,
|
fut_a: A::Future,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> ThenFuture<A, B>
|
impl<A, B, Request> ThenFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
B: Service<Request = Result<A::Response, A::Error>>,
|
B: Service<Result<A::Response, A::Error>>,
|
||||||
{
|
{
|
||||||
fn new(fut_a: A::Future, b: Cell<B>) -> Self {
|
fn new(fut_a: A::Future, b: Cell<B>) -> Self {
|
||||||
ThenFuture {
|
ThenFuture {
|
||||||
@@ -80,10 +78,10 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Future for ThenFuture<A, B>
|
impl<A, B, Request> Future for ThenFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
B: Service<Request = Result<A::Response, A::Error>>,
|
B: Service<Result<A::Response, A::Error>>,
|
||||||
{
|
{
|
||||||
type Item = B::Response;
|
type Item = B::Response;
|
||||||
type Error = B::Error;
|
type Error = B::Error;
|
||||||
@@ -95,11 +93,11 @@ where
|
|||||||
|
|
||||||
match self.fut_a.poll() {
|
match self.fut_a.poll() {
|
||||||
Ok(Async::Ready(resp)) => {
|
Ok(Async::Ready(resp)) => {
|
||||||
self.fut_b = Some(self.b.borrow_mut().call(Ok(resp)));
|
self.fut_b = Some(self.b.get_mut().call(Ok(resp)));
|
||||||
self.poll()
|
self.poll()
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
self.fut_b = Some(self.b.borrow_mut().call(Err(err)));
|
self.fut_b = Some(self.b.get_mut().call(Err(err)));
|
||||||
self.poll()
|
self.poll()
|
||||||
}
|
}
|
||||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||||
@@ -113,13 +111,18 @@ pub struct ThenNewService<A, B> {
|
|||||||
b: B,
|
b: B,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> ThenNewService<A, B>
|
impl<A, B> ThenNewService<A, B> {
|
||||||
where
|
|
||||||
A: NewService,
|
|
||||||
B: NewService,
|
|
||||||
{
|
|
||||||
/// Create new `AndThen` combinator
|
/// Create new `AndThen` combinator
|
||||||
pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self {
|
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>>,
|
||||||
|
{
|
||||||
Self {
|
Self {
|
||||||
a,
|
a,
|
||||||
b: f.into_new_service(),
|
b: f.into_new_service(),
|
||||||
@@ -127,22 +130,17 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> NewService for ThenNewService<A, B>
|
impl<A, B, Request> NewService<Request> for ThenNewService<A, B>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
B: NewService<
|
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
|
||||||
Request = Result<A::Response, A::Error>,
|
|
||||||
Error = A::Error,
|
|
||||||
InitError = A::InitError,
|
|
||||||
>,
|
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
|
||||||
type Response = B::Response;
|
type Response = B::Response;
|
||||||
type Error = A::Error;
|
type Error = A::Error;
|
||||||
type Service = Then<A::Service, B::Service>;
|
type Service = Then<A::Service, B::Service>;
|
||||||
|
|
||||||
type InitError = A::InitError;
|
type InitError = A::InitError;
|
||||||
type Future = ThenNewServiceFuture<A, B>;
|
type Future = ThenNewServiceFuture<A, B, Request>;
|
||||||
|
|
||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
ThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
|
ThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
|
||||||
@@ -151,12 +149,8 @@ where
|
|||||||
|
|
||||||
impl<A, B> Clone for ThenNewService<A, B>
|
impl<A, B> Clone for ThenNewService<A, B>
|
||||||
where
|
where
|
||||||
A: NewService + Clone,
|
A: Clone,
|
||||||
B: NewService<
|
B: Clone,
|
||||||
Request = Result<A::Response, A::Error>,
|
|
||||||
Error = A::Error,
|
|
||||||
InitError = A::InitError,
|
|
||||||
> + Clone,
|
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@@ -166,10 +160,10 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ThenNewServiceFuture<A, B>
|
pub struct ThenNewServiceFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
B: NewService,
|
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
|
||||||
{
|
{
|
||||||
fut_b: B::Future,
|
fut_b: B::Future,
|
||||||
fut_a: A::Future,
|
fut_a: A::Future,
|
||||||
@@ -177,10 +171,10 @@ where
|
|||||||
b: Option<B::Service>,
|
b: Option<B::Service>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> ThenNewServiceFuture<A, B>
|
impl<A, B, Request> ThenNewServiceFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
B: NewService,
|
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
|
||||||
{
|
{
|
||||||
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
|
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
|
||||||
ThenNewServiceFuture {
|
ThenNewServiceFuture {
|
||||||
@@ -192,14 +186,10 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Future for ThenNewServiceFuture<A, B>
|
impl<A, B, Request> Future for ThenNewServiceFuture<A, B, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
B: NewService<
|
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
|
||||||
Request = Result<A::Response, A::Error>,
|
|
||||||
Error = A::Error,
|
|
||||||
InitError = A::InitError,
|
|
||||||
>,
|
|
||||||
{
|
{
|
||||||
type Item = Then<A::Service, B::Service>;
|
type Item = Then<A::Service, B::Service>;
|
||||||
type Error = A::InitError;
|
type Error = A::InitError;
|
||||||
@@ -236,12 +226,10 @@ mod tests {
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use service::{NewServiceExt, ServiceExt};
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct Srv1(Rc<Cell<usize>>);
|
struct Srv1(Rc<Cell<usize>>);
|
||||||
impl Service for Srv1 {
|
impl Service<Result<&'static str, &'static str>> for Srv1 {
|
||||||
type Request = Result<&'static str, &'static str>;
|
|
||||||
type Response = &'static str;
|
type Response = &'static str;
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type Future = FutureResult<Self::Response, Self::Error>;
|
type Future = FutureResult<Self::Response, Self::Error>;
|
||||||
@@ -251,7 +239,7 @@ mod tests {
|
|||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Result<&'static str, &'static str>) -> Self::Future {
|
||||||
match req {
|
match req {
|
||||||
Ok(msg) => ok(msg),
|
Ok(msg) => ok(msg),
|
||||||
Err(_) => err(()),
|
Err(_) => err(()),
|
||||||
@@ -261,8 +249,7 @@ mod tests {
|
|||||||
|
|
||||||
struct Srv2(Rc<Cell<usize>>);
|
struct Srv2(Rc<Cell<usize>>);
|
||||||
|
|
||||||
impl Service for Srv2 {
|
impl Service<Result<&'static str, ()>> for Srv2 {
|
||||||
type Request = Result<&'static str, ()>;
|
|
||||||
type Response = (&'static str, &'static str);
|
type Response = (&'static str, &'static str);
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type Future = FutureResult<Self::Response, ()>;
|
type Future = FutureResult<Self::Response, ()>;
|
||||||
@@ -272,7 +259,7 @@ mod tests {
|
|||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Result<&'static str, ()>) -> Self::Future {
|
||||||
match req {
|
match req {
|
||||||
Ok(msg) => ok((msg, "ok")),
|
Ok(msg) => ok((msg, "ok")),
|
||||||
Err(()) => ok(("srv2", "err")),
|
Err(()) => ok(("srv2", "err")),
|
@@ -80,7 +80,8 @@ fn main() {
|
|||||||
future::ok(())
|
future::ok(())
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
).unwrap()
|
)
|
||||||
|
.unwrap()
|
||||||
.start();
|
.start();
|
||||||
|
|
||||||
sys.run();
|
sys.run();
|
||||||
|
@@ -24,7 +24,8 @@ struct ServiceState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn service<T: AsyncRead + AsyncWrite>(
|
fn service<T: AsyncRead + AsyncWrite>(
|
||||||
st: &mut ServiceState, _: T,
|
st: &mut ServiceState,
|
||||||
|
_: T,
|
||||||
) -> impl Future<Item = (), Error = ()> {
|
) -> impl Future<Item = (), Error = ()> {
|
||||||
let num = st.num.fetch_add(1, Ordering::Relaxed);
|
let num = st.num.fetch_add(1, Ordering::Relaxed);
|
||||||
println!("got ssl connection {:?}", num);
|
println!("got ssl connection {:?}", num);
|
||||||
@@ -60,7 +61,8 @@ fn main() {
|
|||||||
println!("got ssl connection {:?}", num);
|
println!("got ssl connection {:?}", num);
|
||||||
future::ok(())
|
future::ok(())
|
||||||
})
|
})
|
||||||
}).unwrap()
|
})
|
||||||
|
.unwrap()
|
||||||
.start();
|
.start();
|
||||||
|
|
||||||
sys.run();
|
sys.run();
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
max_width = 96
|
max_width = 96
|
||||||
reorder_imports = true
|
reorder_imports = true
|
||||||
wrap_comments = true
|
#wrap_comments = true
|
||||||
fn_args_density = "Compressed"
|
#fn_args_density = "Compressed"
|
||||||
#use_small_heuristics = false
|
#use_small_heuristics = false
|
||||||
|
13
src/cell.rs
13
src/cell.rs
@@ -30,33 +30,34 @@ impl<T: fmt::Debug> fmt::Debug for Cell<T> {
|
|||||||
|
|
||||||
#[cfg(feature = "cell")]
|
#[cfg(feature = "cell")]
|
||||||
impl<T> Cell<T> {
|
impl<T> Cell<T> {
|
||||||
pub(crate) fn new(inner: T) -> Self {
|
pub fn new(inner: T) -> Self {
|
||||||
Self {
|
Self {
|
||||||
inner: Rc::new(UnsafeCell::new(inner)),
|
inner: Rc::new(UnsafeCell::new(inner)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn borrow(&self) -> &T {
|
pub fn borrow(&self) -> &T {
|
||||||
unsafe { &*self.inner.as_ref().get() }
|
unsafe { &*self.inner.as_ref().get() }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn borrow_mut(&self) -> &mut T {
|
pub fn borrow_mut(&self) -> &mut T {
|
||||||
unsafe { &mut *self.inner.as_ref().get() }
|
unsafe { &mut *self.inner.as_ref().get() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(feature = "cell"))]
|
#[cfg(not(feature = "cell"))]
|
||||||
impl<T> Cell<T> {
|
impl<T> Cell<T> {
|
||||||
pub(crate) fn new(inner: T) -> Self {
|
pub fn new(inner: T) -> Self {
|
||||||
Self {
|
Self {
|
||||||
inner: Rc::new(RefCell::new(inner)),
|
inner: Rc::new(RefCell::new(inner)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn borrow(&self) -> Ref<T> {
|
pub fn borrow(&self) -> Ref<T> {
|
||||||
self.inner.borrow()
|
self.inner.borrow()
|
||||||
}
|
}
|
||||||
pub(crate) fn borrow_mut(&self) -> RefMut<T> {
|
|
||||||
|
pub fn borrow_mut(&self) -> RefMut<T> {
|
||||||
self.inner.borrow_mut()
|
self.inner.borrow_mut()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,40 +1,51 @@
|
|||||||
|
use std::marker::PhantomData;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use futures::Poll;
|
use futures::Poll;
|
||||||
|
|
||||||
use super::cell::Cell;
|
use super::cell::Cell;
|
||||||
use super::service::Service;
|
use super::service::Service;
|
||||||
|
|
||||||
/// Service that allows to turn non-clone service to a service with `Clone` impl
|
/// Service that allows to turn non-clone service to a service with `Clone` impl
|
||||||
pub struct CloneableService<S: Service + 'static> {
|
pub struct CloneableService<T: 'static> {
|
||||||
service: Cell<S>,
|
service: Cell<T>,
|
||||||
|
_t: PhantomData<Rc<()>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: Service + 'static> CloneableService<S> {
|
impl<T: 'static> CloneableService<T> {
|
||||||
pub fn new(service: S) -> Self {
|
pub fn new<Request>(service: T) -> Self
|
||||||
|
where
|
||||||
|
T: Service<Request>,
|
||||||
|
{
|
||||||
Self {
|
Self {
|
||||||
service: Cell::new(service),
|
service: Cell::new(service),
|
||||||
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: Service + 'static> Clone for CloneableService<S> {
|
impl<T: 'static> Clone for CloneableService<T> {
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
service: self.service.clone(),
|
service: self.service.clone(),
|
||||||
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S: Service + 'static> Service for CloneableService<S> {
|
impl<T: 'static, Request> Service<Request> for CloneableService<T>
|
||||||
type Request = S::Request;
|
where
|
||||||
type Response = S::Response;
|
T: Service<Request>,
|
||||||
type Error = S::Error;
|
{
|
||||||
type Future = S::Future;
|
type Response = T::Response;
|
||||||
|
type Error = T::Error;
|
||||||
|
type Future = T::Future;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
self.service.borrow_mut().poll_ready()
|
self.service.borrow_mut().poll_ready()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Request) -> Self::Future {
|
||||||
self.service.borrow_mut().call(req)
|
self.service.borrow_mut().call(req)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
33
src/codec/bcodec.rs
Normal file
33
src/codec/bcodec.rs
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
use std::io;
|
||||||
|
|
||||||
|
use bytes::{Bytes, BytesMut};
|
||||||
|
use tokio_codec::{Decoder, Encoder};
|
||||||
|
|
||||||
|
/// Bytes codec.
|
||||||
|
///
|
||||||
|
/// Reads/Writes chunks of bytes from a stream.
|
||||||
|
#[derive(Debug, Copy, Clone)]
|
||||||
|
pub struct BytesCodec;
|
||||||
|
|
||||||
|
impl Encoder for BytesCodec {
|
||||||
|
type Item = Bytes;
|
||||||
|
type Error = io::Error;
|
||||||
|
|
||||||
|
fn encode(&mut self, item: Bytes, dst: &mut BytesMut) -> Result<(), Self::Error> {
|
||||||
|
dst.extend_from_slice(&item[..]);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Decoder for BytesCodec {
|
||||||
|
type Item = BytesMut;
|
||||||
|
type Error = io::Error;
|
||||||
|
|
||||||
|
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
|
||||||
|
if src.is_empty() {
|
||||||
|
Ok(None)
|
||||||
|
} else {
|
||||||
|
Ok(Some(src.take()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@@ -11,6 +11,9 @@ use tokio_io::{AsyncRead, AsyncWrite};
|
|||||||
use super::framed_read::{framed_read2, framed_read2_with_buffer, FramedRead2};
|
use super::framed_read::{framed_read2, framed_read2_with_buffer, FramedRead2};
|
||||||
use super::framed_write::{framed_write2, framed_write2_with_buffer, FramedWrite2};
|
use super::framed_write::{framed_write2, framed_write2_with_buffer, FramedWrite2};
|
||||||
|
|
||||||
|
const LW: usize = 1024;
|
||||||
|
const HW: usize = 8 * 1024;
|
||||||
|
|
||||||
/// A unified `Stream` and `Sink` interface to an underlying I/O object, using
|
/// A unified `Stream` and `Sink` interface to an underlying I/O object, using
|
||||||
/// the `Encoder` and `Decoder` traits to encode and decode frames.
|
/// the `Encoder` and `Decoder` traits to encode and decode frames.
|
||||||
///
|
///
|
||||||
@@ -45,9 +48,25 @@ where
|
|||||||
/// break them into separate objects, allowing them to interact more easily.
|
/// break them into separate objects, allowing them to interact more easily.
|
||||||
pub fn new(inner: T, codec: U) -> Framed<T, U> {
|
pub fn new(inner: T, codec: U) -> Framed<T, U> {
|
||||||
Framed {
|
Framed {
|
||||||
inner: framed_read2(framed_write2(Fuse(inner, codec))),
|
inner: framed_read2(framed_write2(Fuse(inner, codec), LW, HW)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Same as `Framed::new()` with ability to specify write buffer low/high capacity watermarks.
|
||||||
|
pub fn new_with_caps(inner: T, codec: U, lw: usize, hw: usize) -> Framed<T, U> {
|
||||||
|
debug_assert!((lw < hw) && hw != 0);
|
||||||
|
Framed {
|
||||||
|
inner: framed_read2(framed_write2(Fuse(inner, codec), lw, hw)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Force send item
|
||||||
|
pub fn force_send(
|
||||||
|
&mut self,
|
||||||
|
item: <U as Encoder>::Item,
|
||||||
|
) -> Result<(), <U as Encoder>::Error> {
|
||||||
|
self.inner.get_mut().force_send(item)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, U> Framed<T, U> {
|
impl<T, U> Framed<T, U> {
|
||||||
@@ -75,7 +94,12 @@ impl<T, U> Framed<T, U> {
|
|||||||
pub fn from_parts(parts: FramedParts<T, U>) -> Framed<T, U> {
|
pub fn from_parts(parts: FramedParts<T, U>) -> Framed<T, U> {
|
||||||
Framed {
|
Framed {
|
||||||
inner: framed_read2_with_buffer(
|
inner: framed_read2_with_buffer(
|
||||||
framed_write2_with_buffer(Fuse(parts.io, parts.codec), parts.write_buf),
|
framed_write2_with_buffer(
|
||||||
|
Fuse(parts.io, parts.codec),
|
||||||
|
parts.write_buf,
|
||||||
|
parts.write_buf_lw,
|
||||||
|
parts.write_buf_hw,
|
||||||
|
),
|
||||||
parts.read_buf,
|
parts.read_buf,
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@@ -111,6 +135,16 @@ impl<T, U> Framed<T, U> {
|
|||||||
&mut self.inner.get_mut().get_mut().0
|
&mut self.inner.get_mut().get_mut().0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Check if write buffer is empty.
|
||||||
|
pub fn is_write_buf_empty(&self) -> bool {
|
||||||
|
self.inner.get_ref().is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if write buffer is full.
|
||||||
|
pub fn is_write_buf_full(&self) -> bool {
|
||||||
|
self.inner.get_ref().is_full()
|
||||||
|
}
|
||||||
|
|
||||||
/// Consumes the `Frame`, returning its underlying I/O stream.
|
/// Consumes the `Frame`, returning its underlying I/O stream.
|
||||||
///
|
///
|
||||||
/// Note that care should be taken to not tamper with the underlying stream
|
/// Note that care should be taken to not tamper with the underlying stream
|
||||||
@@ -123,11 +157,27 @@ impl<T, U> Framed<T, U> {
|
|||||||
/// Consume the `Frame`, returning `Frame` with different codec.
|
/// Consume the `Frame`, returning `Frame` with different codec.
|
||||||
pub fn into_framed<U2>(self, codec: U2) -> Framed<T, U2> {
|
pub fn into_framed<U2>(self, codec: U2) -> Framed<T, U2> {
|
||||||
let (inner, read_buf) = self.inner.into_parts();
|
let (inner, read_buf) = self.inner.into_parts();
|
||||||
let (inner, write_buf) = inner.into_parts();
|
let (inner, write_buf, lw, hw) = inner.into_parts();
|
||||||
|
|
||||||
Framed {
|
Framed {
|
||||||
inner: framed_read2_with_buffer(
|
inner: framed_read2_with_buffer(
|
||||||
framed_write2_with_buffer(Fuse(inner.0, codec), write_buf),
|
framed_write2_with_buffer(Fuse(inner.0, codec), write_buf, lw, hw),
|
||||||
|
read_buf,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Consume the `Frame`, returning `Frame` with different codec.
|
||||||
|
pub fn map_codec<F, U2>(self, f: F) -> Framed<T, U2>
|
||||||
|
where
|
||||||
|
F: Fn(U) -> U2,
|
||||||
|
{
|
||||||
|
let (inner, read_buf) = self.inner.into_parts();
|
||||||
|
let (inner, write_buf, lw, hw) = inner.into_parts();
|
||||||
|
|
||||||
|
Framed {
|
||||||
|
inner: framed_read2_with_buffer(
|
||||||
|
framed_write2_with_buffer(Fuse(inner.0, f(inner.1)), write_buf, lw, hw),
|
||||||
read_buf,
|
read_buf,
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
@@ -141,13 +191,15 @@ impl<T, U> Framed<T, U> {
|
|||||||
/// being worked with.
|
/// being worked with.
|
||||||
pub fn into_parts(self) -> FramedParts<T, U> {
|
pub fn into_parts(self) -> FramedParts<T, U> {
|
||||||
let (inner, read_buf) = self.inner.into_parts();
|
let (inner, read_buf) = self.inner.into_parts();
|
||||||
let (inner, write_buf) = inner.into_parts();
|
let (inner, write_buf, write_buf_lw, write_buf_hw) = inner.into_parts();
|
||||||
|
|
||||||
FramedParts {
|
FramedParts {
|
||||||
io: inner.0,
|
io: inner.0,
|
||||||
codec: inner.1,
|
codec: inner.1,
|
||||||
read_buf: read_buf,
|
read_buf,
|
||||||
write_buf: write_buf,
|
write_buf,
|
||||||
|
write_buf_lw,
|
||||||
|
write_buf_hw,
|
||||||
_priv: (),
|
_priv: (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -176,7 +228,8 @@ where
|
|||||||
type SinkError = U::Error;
|
type SinkError = U::Error;
|
||||||
|
|
||||||
fn start_send(
|
fn start_send(
|
||||||
&mut self, item: Self::SinkItem,
|
&mut self,
|
||||||
|
item: Self::SinkItem,
|
||||||
) -> StartSend<Self::SinkItem, Self::SinkError> {
|
) -> StartSend<Self::SinkItem, Self::SinkError> {
|
||||||
self.inner.get_mut().start_send(item)
|
self.inner.get_mut().start_send(item)
|
||||||
}
|
}
|
||||||
@@ -272,6 +325,12 @@ pub struct FramedParts<T, U> {
|
|||||||
/// A buffer with unprocessed data which are not written yet.
|
/// A buffer with unprocessed data which are not written yet.
|
||||||
pub write_buf: BytesMut,
|
pub write_buf: BytesMut,
|
||||||
|
|
||||||
|
/// A buffer low watermark capacity
|
||||||
|
pub write_buf_lw: usize,
|
||||||
|
|
||||||
|
/// A buffer high watermark capacity
|
||||||
|
pub write_buf_hw: usize,
|
||||||
|
|
||||||
/// This private field allows us to add additional fields in the future in a
|
/// This private field allows us to add additional fields in the future in a
|
||||||
/// backwards compatible way.
|
/// backwards compatible way.
|
||||||
_priv: (),
|
_priv: (),
|
||||||
@@ -285,6 +344,8 @@ impl<T, U> FramedParts<T, U> {
|
|||||||
codec,
|
codec,
|
||||||
read_buf: BytesMut::new(),
|
read_buf: BytesMut::new(),
|
||||||
write_buf: BytesMut::new(),
|
write_buf: BytesMut::new(),
|
||||||
|
write_buf_lw: LW,
|
||||||
|
write_buf_hw: HW,
|
||||||
_priv: (),
|
_priv: (),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -191,7 +191,8 @@ where
|
|||||||
type SinkError = E::Error;
|
type SinkError = E::Error;
|
||||||
|
|
||||||
fn start_send(
|
fn start_send(
|
||||||
&mut self, item: Self::SinkItem,
|
&mut self,
|
||||||
|
item: Self::SinkItem,
|
||||||
) -> StartSend<Self::SinkItem, Self::SinkError> {
|
) -> StartSend<Self::SinkItem, Self::SinkError> {
|
||||||
self.inner.get_mut().start_send(item)
|
self.inner.get_mut().start_send(item)
|
||||||
}
|
}
|
||||||
|
@@ -1,7 +1,8 @@
|
|||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
use bytes::BytesMut;
|
use bytes::BytesMut;
|
||||||
use futures::{Async, Poll, Sink, StartSend, Stream};
|
use futures::{try_ready, Async, Poll, Sink, StartSend, Stream};
|
||||||
|
use log::trace;
|
||||||
use tokio_codec::Decoder;
|
use tokio_codec::Decoder;
|
||||||
use tokio_io::AsyncRead;
|
use tokio_io::AsyncRead;
|
||||||
|
|
||||||
@@ -98,7 +99,8 @@ where
|
|||||||
type SinkError = T::SinkError;
|
type SinkError = T::SinkError;
|
||||||
|
|
||||||
fn start_send(
|
fn start_send(
|
||||||
&mut self, item: Self::SinkItem,
|
&mut self,
|
||||||
|
item: Self::SinkItem,
|
||||||
) -> StartSend<Self::SinkItem, Self::SinkError> {
|
) -> StartSend<Self::SinkItem, Self::SinkError> {
|
||||||
self.inner.inner.0.start_send(item)
|
self.inner.inner.0.start_send(item)
|
||||||
}
|
}
|
||||||
@@ -132,7 +134,7 @@ where
|
|||||||
|
|
||||||
pub fn framed_read2<T>(inner: T) -> FramedRead2<T> {
|
pub fn framed_read2<T>(inner: T) -> FramedRead2<T> {
|
||||||
FramedRead2 {
|
FramedRead2 {
|
||||||
inner: inner,
|
inner,
|
||||||
eof: false,
|
eof: false,
|
||||||
is_readable: false,
|
is_readable: false,
|
||||||
buffer: BytesMut::with_capacity(INITIAL_CAPACITY),
|
buffer: BytesMut::with_capacity(INITIAL_CAPACITY),
|
||||||
@@ -145,9 +147,9 @@ pub fn framed_read2_with_buffer<T>(inner: T, mut buf: BytesMut) -> FramedRead2<T
|
|||||||
buf.reserve(bytes_to_reserve);
|
buf.reserve(bytes_to_reserve);
|
||||||
}
|
}
|
||||||
FramedRead2 {
|
FramedRead2 {
|
||||||
inner: inner,
|
inner,
|
||||||
eof: false,
|
eof: false,
|
||||||
is_readable: buf.len() > 0,
|
is_readable: !buf.is_empty(),
|
||||||
buffer: buf,
|
buffer: buf,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -186,13 +188,13 @@ where
|
|||||||
// readable again, at which point the stream is terminated.
|
// readable again, at which point the stream is terminated.
|
||||||
if self.is_readable {
|
if self.is_readable {
|
||||||
if self.eof {
|
if self.eof {
|
||||||
let frame = try!(self.inner.decode_eof(&mut self.buffer));
|
let frame = self.inner.decode_eof(&mut self.buffer)?;
|
||||||
return Ok(Async::Ready(frame));
|
return Ok(Async::Ready(frame));
|
||||||
}
|
}
|
||||||
|
|
||||||
trace!("attempting to decode a frame");
|
trace!("attempting to decode a frame");
|
||||||
|
|
||||||
if let Some(frame) = try!(self.inner.decode(&mut self.buffer)) {
|
if let Some(frame) = self.inner.decode(&mut self.buffer)? {
|
||||||
trace!("frame decoded from buffer");
|
trace!("frame decoded from buffer");
|
||||||
return Ok(Async::Ready(Some(frame)));
|
return Ok(Async::Ready(Some(frame)));
|
||||||
}
|
}
|
||||||
|
@@ -2,7 +2,8 @@ use std::fmt;
|
|||||||
use std::io::{self, Read};
|
use std::io::{self, Read};
|
||||||
|
|
||||||
use bytes::BytesMut;
|
use bytes::BytesMut;
|
||||||
use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream};
|
use futures::{try_ready, Async, AsyncSink, Poll, Sink, StartSend, Stream};
|
||||||
|
use log::trace;
|
||||||
use tokio_codec::{Decoder, Encoder};
|
use tokio_codec::{Decoder, Encoder};
|
||||||
use tokio_io::{AsyncRead, AsyncWrite};
|
use tokio_io::{AsyncRead, AsyncWrite};
|
||||||
|
|
||||||
@@ -16,20 +17,19 @@ pub struct FramedWrite<T, E> {
|
|||||||
pub struct FramedWrite2<T> {
|
pub struct FramedWrite2<T> {
|
||||||
inner: T,
|
inner: T,
|
||||||
buffer: BytesMut,
|
buffer: BytesMut,
|
||||||
|
low_watermark: usize,
|
||||||
|
high_watermark: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
const INITIAL_CAPACITY: usize = 8 * 1024;
|
|
||||||
const BACKPRESSURE_BOUNDARY: usize = INITIAL_CAPACITY;
|
|
||||||
|
|
||||||
impl<T, E> FramedWrite<T, E>
|
impl<T, E> FramedWrite<T, E>
|
||||||
where
|
where
|
||||||
T: AsyncWrite,
|
T: AsyncWrite,
|
||||||
E: Encoder,
|
E: Encoder,
|
||||||
{
|
{
|
||||||
/// Creates a new `FramedWrite` with the given `encoder`.
|
/// Creates a new `FramedWrite` with the given `encoder`.
|
||||||
pub fn new(inner: T, encoder: E) -> FramedWrite<T, E> {
|
pub fn new(inner: T, encoder: E, lw: usize, hw: usize) -> FramedWrite<T, E> {
|
||||||
FramedWrite {
|
FramedWrite {
|
||||||
inner: framed_write2(Fuse(inner, encoder)),
|
inner: framed_write2(Fuse(inner, encoder), lw, hw),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,6 +73,26 @@ impl<T, E> FramedWrite<T, E> {
|
|||||||
pub fn encoder_mut(&mut self) -> &mut E {
|
pub fn encoder_mut(&mut self) -> &mut E {
|
||||||
&mut self.inner.inner.1
|
&mut self.inner.inner.1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Check if write buffer is full
|
||||||
|
pub fn is_full(&self) -> bool {
|
||||||
|
self.inner.is_full()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if write buffer is empty.
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.inner.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, E> FramedWrite<T, E>
|
||||||
|
where
|
||||||
|
E: Encoder,
|
||||||
|
{
|
||||||
|
/// Force send item
|
||||||
|
pub fn force_send(&mut self, item: E::Item) -> Result<(), E::Error> {
|
||||||
|
self.inner.force_send(item)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, E> Sink for FramedWrite<T, E>
|
impl<T, E> Sink for FramedWrite<T, E>
|
||||||
@@ -92,7 +112,7 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn close(&mut self) -> Poll<(), Self::SinkError> {
|
fn close(&mut self) -> Poll<(), Self::SinkError> {
|
||||||
Ok(try!(self.inner.close()))
|
Ok(self.inner.close()?)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,21 +144,34 @@ where
|
|||||||
|
|
||||||
// ===== impl FramedWrite2 =====
|
// ===== impl FramedWrite2 =====
|
||||||
|
|
||||||
pub fn framed_write2<T>(inner: T) -> FramedWrite2<T> {
|
pub fn framed_write2<T>(
|
||||||
|
inner: T,
|
||||||
|
low_watermark: usize,
|
||||||
|
high_watermark: usize,
|
||||||
|
) -> FramedWrite2<T> {
|
||||||
FramedWrite2 {
|
FramedWrite2 {
|
||||||
inner: inner,
|
inner,
|
||||||
buffer: BytesMut::with_capacity(INITIAL_CAPACITY),
|
low_watermark,
|
||||||
|
high_watermark,
|
||||||
|
buffer: BytesMut::with_capacity(high_watermark),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn framed_write2_with_buffer<T>(inner: T, mut buf: BytesMut) -> FramedWrite2<T> {
|
pub fn framed_write2_with_buffer<T>(
|
||||||
if buf.capacity() < INITIAL_CAPACITY {
|
inner: T,
|
||||||
let bytes_to_reserve = INITIAL_CAPACITY - buf.capacity();
|
mut buffer: BytesMut,
|
||||||
buf.reserve(bytes_to_reserve);
|
low_watermark: usize,
|
||||||
|
high_watermark: usize,
|
||||||
|
) -> FramedWrite2<T> {
|
||||||
|
if buffer.capacity() < high_watermark {
|
||||||
|
let bytes_to_reserve = high_watermark - buffer.capacity();
|
||||||
|
buffer.reserve(bytes_to_reserve);
|
||||||
}
|
}
|
||||||
FramedWrite2 {
|
FramedWrite2 {
|
||||||
inner: inner,
|
inner,
|
||||||
buffer: buf,
|
buffer,
|
||||||
|
low_watermark,
|
||||||
|
high_watermark,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -151,13 +184,40 @@ impl<T> FramedWrite2<T> {
|
|||||||
self.inner
|
self.inner
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn into_parts(self) -> (T, BytesMut) {
|
pub fn into_parts(self) -> (T, BytesMut, usize, usize) {
|
||||||
(self.inner, self.buffer)
|
(
|
||||||
|
self.inner,
|
||||||
|
self.buffer,
|
||||||
|
self.low_watermark,
|
||||||
|
self.high_watermark,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_mut(&mut self) -> &mut T {
|
pub fn get_mut(&mut self) -> &mut T {
|
||||||
&mut self.inner
|
&mut self.inner
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn is_full(&self) -> bool {
|
||||||
|
self.buffer.len() >= self.high_watermark
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.buffer.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> FramedWrite2<T>
|
||||||
|
where
|
||||||
|
T: Encoder,
|
||||||
|
{
|
||||||
|
pub fn force_send(&mut self, item: T::Item) -> Result<(), T::Error> {
|
||||||
|
let len = self.buffer.len();
|
||||||
|
if len < self.low_watermark {
|
||||||
|
self.buffer.reserve(self.high_watermark - len)
|
||||||
|
}
|
||||||
|
self.inner.encode(item, &mut self.buffer)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Sink for FramedWrite2<T>
|
impl<T> Sink for FramedWrite2<T>
|
||||||
@@ -168,18 +228,16 @@ where
|
|||||||
type SinkError = T::Error;
|
type SinkError = T::Error;
|
||||||
|
|
||||||
fn start_send(&mut self, item: T::Item) -> StartSend<T::Item, T::Error> {
|
fn start_send(&mut self, item: T::Item) -> StartSend<T::Item, T::Error> {
|
||||||
// If the buffer is already over 8KiB, then attempt to flush it. If after
|
// Check the buffer capacity
|
||||||
// flushing it's *still* over 8KiB, then apply backpressure (reject the
|
let len = self.buffer.len();
|
||||||
// send).
|
if len >= self.high_watermark {
|
||||||
if self.buffer.len() >= BACKPRESSURE_BOUNDARY {
|
|
||||||
try!(self.poll_complete());
|
|
||||||
|
|
||||||
if self.buffer.len() >= BACKPRESSURE_BOUNDARY {
|
|
||||||
return Ok(AsyncSink::NotReady(item));
|
return Ok(AsyncSink::NotReady(item));
|
||||||
}
|
}
|
||||||
|
if len < self.low_watermark {
|
||||||
|
self.buffer.reserve(self.high_watermark - len)
|
||||||
}
|
}
|
||||||
|
|
||||||
try!(self.inner.encode(item, &mut self.buffer));
|
self.inner.encode(item, &mut self.buffer)?;
|
||||||
|
|
||||||
Ok(AsyncSink::Ready)
|
Ok(AsyncSink::Ready)
|
||||||
}
|
}
|
||||||
@@ -197,7 +255,8 @@ where
|
|||||||
io::ErrorKind::WriteZero,
|
io::ErrorKind::WriteZero,
|
||||||
"failed to \
|
"failed to \
|
||||||
write frame to transport",
|
write frame to transport",
|
||||||
).into());
|
)
|
||||||
|
.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Add a way to `bytes` to do this w/o returning the drained
|
// TODO: Add a way to `bytes` to do this w/o returning the drained
|
||||||
@@ -209,12 +268,12 @@ where
|
|||||||
try_ready!(self.inner.poll_flush());
|
try_ready!(self.inner.poll_flush());
|
||||||
|
|
||||||
trace!("framed transport flushed");
|
trace!("framed transport flushed");
|
||||||
return Ok(Async::Ready(()));
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn close(&mut self) -> Poll<(), Self::SinkError> {
|
fn close(&mut self) -> Poll<(), Self::SinkError> {
|
||||||
try_ready!(self.poll_complete());
|
try_ready!(self.poll_complete());
|
||||||
Ok(try!(self.inner.shutdown()))
|
Ok(self.inner.shutdown()?)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -12,12 +12,14 @@
|
|||||||
|
|
||||||
#![deny(missing_docs, missing_debug_implementations, warnings)]
|
#![deny(missing_docs, missing_debug_implementations, warnings)]
|
||||||
|
|
||||||
|
mod bcodec;
|
||||||
mod framed;
|
mod framed;
|
||||||
mod framed2;
|
// mod framed2;
|
||||||
mod framed_read;
|
mod framed_read;
|
||||||
mod framed_write;
|
mod framed_write;
|
||||||
|
|
||||||
|
pub use self::bcodec::BytesCodec;
|
||||||
pub use self::framed::{Framed, FramedParts};
|
pub use self::framed::{Framed, FramedParts};
|
||||||
pub use self::framed2::{Framed2, FramedParts2};
|
// pub use self::framed2::{Framed2, FramedParts2};
|
||||||
pub use self::framed_read::FramedRead;
|
pub use self::framed_read::FramedRead;
|
||||||
pub use self::framed_write::FramedWrite;
|
pub use self::framed_write::FramedWrite;
|
||||||
|
358
src/connector.rs
358
src/connector.rs
@@ -1,50 +1,151 @@
|
|||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
use std::io;
|
use std::marker::PhantomData;
|
||||||
use std::net::SocketAddr;
|
use std::net::{IpAddr, SocketAddr};
|
||||||
|
use std::time::Duration;
|
||||||
|
use std::{fmt, io};
|
||||||
|
|
||||||
|
use futures::future::{ok, Either, FutureResult};
|
||||||
|
use futures::{try_ready, Async, Future, Poll};
|
||||||
|
|
||||||
use futures::{
|
|
||||||
future::{ok, FutureResult},
|
|
||||||
Async, Future, Poll,
|
|
||||||
};
|
|
||||||
use tokio_tcp::{ConnectFuture, TcpStream};
|
use tokio_tcp::{ConnectFuture, TcpStream};
|
||||||
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||||
use trust_dns_resolver::system_conf::read_system_conf;
|
use trust_dns_resolver::system_conf::read_system_conf;
|
||||||
|
|
||||||
use super::resolver::{HostAware, Resolver, ResolverError, ResolverFuture};
|
use super::resolver::{RequestHost, ResolveError, Resolver, ResolverFuture};
|
||||||
use super::service::{NewService, Service};
|
use super::service::{NewService, Service};
|
||||||
|
|
||||||
|
/// Port of the request
|
||||||
|
pub trait RequestPort {
|
||||||
|
fn port(&self) -> u16;
|
||||||
|
}
|
||||||
|
|
||||||
// #[derive(Fail, Debug)]
|
// #[derive(Fail, Debug)]
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum ConnectorError {
|
pub enum ConnectorError {
|
||||||
/// Failed to resolve the hostname
|
/// Failed to resolve the hostname
|
||||||
// #[fail(display = "Failed resolving hostname: {}", _0)]
|
// #[fail(display = "Failed resolving hostname: {}", _0)]
|
||||||
Resolver(ResolverError),
|
Resolver(ResolveError),
|
||||||
|
|
||||||
/// Not dns records
|
/// No dns records
|
||||||
// #[fail(display = "Invalid input: {}", _0)]
|
// #[fail(display = "No dns records found for the input")]
|
||||||
NoRecords,
|
NoRecords,
|
||||||
|
|
||||||
|
/// Connecting took too long
|
||||||
|
// #[fail(display = "Timeout out while establishing connection")]
|
||||||
|
Timeout,
|
||||||
|
|
||||||
|
/// Invalid input
|
||||||
|
InvalidInput,
|
||||||
|
|
||||||
/// Connection io error
|
/// Connection io error
|
||||||
// #[fail(display = "{}", _0)]
|
// #[fail(display = "{}", _0)]
|
||||||
IoError(io::Error),
|
IoError(io::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<ResolverError> for ConnectorError {
|
impl From<ResolveError> for ConnectorError {
|
||||||
fn from(err: ResolverError) -> Self {
|
fn from(err: ResolveError) -> Self {
|
||||||
ConnectorError::Resolver(err)
|
ConnectorError::Resolver(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ConnectionInfo {
|
impl From<io::Error> for ConnectorError {
|
||||||
pub host: String,
|
fn from(err: io::Error) -> Self {
|
||||||
pub addr: SocketAddr,
|
ConnectorError::IoError(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Connector<T = String> {
|
/// Connect request
|
||||||
resolver: Resolver<T>,
|
#[derive(Eq, PartialEq, Debug, Hash)]
|
||||||
|
pub struct Connect {
|
||||||
|
pub kind: ConnectKind,
|
||||||
|
pub timeout: Duration,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: HostAware> Default for Connector<T> {
|
#[derive(Eq, PartialEq, Debug, Hash)]
|
||||||
|
pub enum ConnectKind {
|
||||||
|
Host { host: String, port: u16 },
|
||||||
|
Addr { host: String, addr: SocketAddr },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Connect {
|
||||||
|
/// Create new `Connect` instance.
|
||||||
|
pub fn new<T: AsRef<str>>(host: T, port: u16) -> Connect {
|
||||||
|
Connect {
|
||||||
|
kind: ConnectKind::Host {
|
||||||
|
host: host.as_ref().to_owned(),
|
||||||
|
port,
|
||||||
|
},
|
||||||
|
timeout: Duration::from_secs(1),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create `Connect` instance by spliting the string by ':' and convert the second part to u16
|
||||||
|
pub fn with<T: AsRef<str>>(host: T) -> Result<Connect, ConnectorError> {
|
||||||
|
let mut parts_iter = host.as_ref().splitn(2, ':');
|
||||||
|
let host = parts_iter.next().ok_or(ConnectorError::InvalidInput)?;
|
||||||
|
let port_str = parts_iter.next().unwrap_or("");
|
||||||
|
let port = port_str
|
||||||
|
.parse::<u16>()
|
||||||
|
.map_err(|_| ConnectorError::InvalidInput)?;
|
||||||
|
Ok(Connect {
|
||||||
|
kind: ConnectKind::Host {
|
||||||
|
host: host.to_owned(),
|
||||||
|
port,
|
||||||
|
},
|
||||||
|
timeout: Duration::from_secs(1),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create new `Connect` instance from host and address. Connector skips name resolution stage for such connect messages.
|
||||||
|
pub fn with_address<T: Into<String>>(host: T, addr: SocketAddr) -> Connect {
|
||||||
|
Connect {
|
||||||
|
kind: ConnectKind::Addr {
|
||||||
|
addr,
|
||||||
|
host: host.into(),
|
||||||
|
},
|
||||||
|
timeout: Duration::from_secs(1),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set connect timeout
|
||||||
|
///
|
||||||
|
/// By default timeout is set to a 1 second.
|
||||||
|
pub fn timeout(mut self, timeout: Duration) -> Connect {
|
||||||
|
self.timeout = timeout;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RequestHost for Connect {
|
||||||
|
fn host(&self) -> &str {
|
||||||
|
match self.kind {
|
||||||
|
ConnectKind::Host { ref host, .. } => host,
|
||||||
|
ConnectKind::Addr { ref host, .. } => host,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RequestPort for Connect {
|
||||||
|
fn port(&self) -> u16 {
|
||||||
|
match self.kind {
|
||||||
|
ConnectKind::Host { port, .. } => port,
|
||||||
|
ConnectKind::Addr { addr, .. } => addr.port(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Connect {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
write!(f, "{}:{}", self.host(), self.port())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tcp connector
|
||||||
|
pub struct Connector {
|
||||||
|
resolver: Resolver<Connect>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Connector {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
let (cfg, opts) = if let Ok((cfg, opts)) = read_system_conf() {
|
let (cfg, opts) = if let Ok((cfg, opts)) = read_system_conf() {
|
||||||
(cfg, opts)
|
(cfg, opts)
|
||||||
@@ -56,51 +157,37 @@ impl<T: HostAware> Default for Connector<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: HostAware> Connector<T> {
|
impl Connector {
|
||||||
|
/// Create new connector with resolver configuration
|
||||||
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
|
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
|
||||||
Connector {
|
Connector {
|
||||||
resolver: Resolver::new(cfg, opts),
|
resolver: Resolver::new(cfg, opts),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Create new connector with custom resolver
|
||||||
pub fn with_resolver(
|
pub fn with_resolver(
|
||||||
resolver: Resolver<T>,
|
resolver: Resolver<Connect>,
|
||||||
) -> impl Service<
|
) -> impl Service<Connect, Response = (Connect, TcpStream), Error = ConnectorError> + Clone
|
||||||
Request = T,
|
{
|
||||||
Response = (T, ConnectionInfo, TcpStream),
|
|
||||||
Error = ConnectorError,
|
|
||||||
> + Clone {
|
|
||||||
Connector { resolver }
|
Connector { resolver }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new_service<E>() -> impl NewService<
|
/// Create new default connector service
|
||||||
Request = T,
|
|
||||||
Response = (T, ConnectionInfo, TcpStream),
|
|
||||||
Error = ConnectorError,
|
|
||||||
InitError = E,
|
|
||||||
> + Clone {
|
|
||||||
|| -> FutureResult<Connector<T>, E> { ok(Connector::default()) }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn new_service_with_config<E>(
|
pub fn new_service_with_config<E>(
|
||||||
cfg: ResolverConfig, opts: ResolverOpts,
|
cfg: ResolverConfig,
|
||||||
|
opts: ResolverOpts,
|
||||||
) -> impl NewService<
|
) -> impl NewService<
|
||||||
Request = T,
|
Connect,
|
||||||
Response = (T, ConnectionInfo, TcpStream),
|
Response = (Connect, TcpStream),
|
||||||
Error = ConnectorError,
|
Error = ConnectorError,
|
||||||
InitError = E,
|
InitError = E,
|
||||||
> + Clone {
|
> + Clone {
|
||||||
move || -> FutureResult<Connector<T>, E> { ok(Connector::new(cfg.clone(), opts)) }
|
move || -> FutureResult<Connector, E> { ok(Connector::new(cfg.clone(), opts)) }
|
||||||
}
|
|
||||||
|
|
||||||
pub fn change_request<T2: HostAware>(&self) -> Connector<T2> {
|
|
||||||
Connector {
|
|
||||||
resolver: self.resolver.change_request(),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Clone for Connector<T> {
|
impl Clone for Connector {
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Connector {
|
Connector {
|
||||||
resolver: self.resolver.clone(),
|
resolver: self.resolver.clone(),
|
||||||
@@ -108,44 +195,52 @@ impl<T> Clone for Connector<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: HostAware> Service for Connector<T> {
|
impl Service<Connect> for Connector {
|
||||||
type Request = T;
|
type Response = (Connect, TcpStream);
|
||||||
type Response = (T, ConnectionInfo, TcpStream);
|
|
||||||
type Error = ConnectorError;
|
type Error = ConnectorError;
|
||||||
type Future = ConnectorFuture<T>;
|
type Future = Either<ConnectorFuture, ConnectorTcpFuture>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Connect) -> Self::Future {
|
||||||
ConnectorFuture {
|
match req.kind {
|
||||||
|
ConnectKind::Host { .. } => Either::A(ConnectorFuture {
|
||||||
fut: self.resolver.call(req),
|
fut: self.resolver.call(req),
|
||||||
fut2: None,
|
fut2: None,
|
||||||
|
}),
|
||||||
|
ConnectKind::Addr { addr, .. } => {
|
||||||
|
let mut addrs = VecDeque::new();
|
||||||
|
addrs.push_back(addr.ip());
|
||||||
|
Either::B(ConnectorTcpFuture {
|
||||||
|
fut: TcpConnectorResponse::new(req, addrs),
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct ConnectorFuture<T: HostAware> {
|
pub struct ConnectorFuture {
|
||||||
fut: ResolverFuture<T>,
|
fut: ResolverFuture<Connect>,
|
||||||
fut2: Option<TcpConnector<T>>,
|
fut2: Option<TcpConnectorResponse<Connect>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: HostAware> Future for ConnectorFuture<T> {
|
impl Future for ConnectorFuture {
|
||||||
type Item = (T, ConnectionInfo, TcpStream);
|
type Item = (Connect, TcpStream);
|
||||||
type Error = ConnectorError;
|
type Error = ConnectorError;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
if let Some(ref mut fut) = self.fut2 {
|
if let Some(ref mut fut) = self.fut2 {
|
||||||
return fut.poll();
|
return fut.poll().map_err(ConnectorError::from);
|
||||||
}
|
}
|
||||||
match self.fut.poll().map_err(ConnectorError::from)? {
|
match self.fut.poll().map_err(ConnectorError::from)? {
|
||||||
Async::Ready((req, host, addrs)) => {
|
Async::Ready((req, addrs)) => {
|
||||||
if addrs.is_empty() {
|
if addrs.is_empty() {
|
||||||
Err(ConnectorError::NoRecords)
|
Err(ConnectorError::NoRecords)
|
||||||
} else {
|
} else {
|
||||||
self.fut2 = Some(TcpConnector::new(req, host, addrs));
|
self.fut2 = Some(TcpConnectorResponse::new(req, addrs));
|
||||||
self.poll()
|
self.poll()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -154,77 +249,68 @@ impl<T: HostAware> Future for ConnectorFuture<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct DefaultConnector<T: HostAware>(Connector<T>);
|
|
||||||
|
|
||||||
impl<T: HostAware> Default for DefaultConnector<T> {
|
|
||||||
fn default() -> Self {
|
|
||||||
DefaultConnector(Connector::default())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: HostAware> DefaultConnector<T> {
|
|
||||||
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
|
|
||||||
DefaultConnector(Connector::new(cfg, opts))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: HostAware> Service for DefaultConnector<T> {
|
|
||||||
type Request = T;
|
|
||||||
type Response = TcpStream;
|
|
||||||
type Error = ConnectorError;
|
|
||||||
type Future = DefaultConnectorFuture<T>;
|
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
|
||||||
self.0.poll_ready()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
|
||||||
DefaultConnectorFuture {
|
|
||||||
fut: self.0.call(req),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct DefaultConnectorFuture<T: HostAware> {
|
pub struct ConnectorTcpFuture {
|
||||||
fut: ConnectorFuture<T>,
|
fut: TcpConnectorResponse<Connect>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: HostAware> Future for DefaultConnectorFuture<T> {
|
impl Future for ConnectorTcpFuture {
|
||||||
type Item = TcpStream;
|
type Item = (Connect, TcpStream);
|
||||||
type Error = ConnectorError;
|
type Error = ConnectorError;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
Ok(Async::Ready(try_ready!(self.fut.poll()).2))
|
self.fut.poll().map_err(ConnectorError::IoError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tcp stream connector service
|
||||||
|
pub struct TcpConnector<T: RequestPort>(PhantomData<T>);
|
||||||
|
|
||||||
|
impl<T: RequestPort> Default for TcpConnector<T> {
|
||||||
|
fn default() -> TcpConnector<T> {
|
||||||
|
TcpConnector(PhantomData)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: RequestPort> Service<(T, VecDeque<IpAddr>)> for TcpConnector<T> {
|
||||||
|
type Response = (T, TcpStream);
|
||||||
|
type Error = io::Error;
|
||||||
|
type Future = TcpConnectorResponse<T>;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
|
Ok(Async::Ready(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, (req, addrs): (T, VecDeque<IpAddr>)) -> Self::Future {
|
||||||
|
TcpConnectorResponse::new(req, addrs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
/// Tcp stream connector
|
/// Tcp stream connector response future
|
||||||
pub struct TcpConnector<T> {
|
pub struct TcpConnectorResponse<T: RequestPort> {
|
||||||
|
port: u16,
|
||||||
req: Option<T>,
|
req: Option<T>,
|
||||||
host: Option<String>,
|
|
||||||
addr: Option<SocketAddr>,
|
addr: Option<SocketAddr>,
|
||||||
addrs: VecDeque<SocketAddr>,
|
addrs: VecDeque<IpAddr>,
|
||||||
stream: Option<ConnectFuture>,
|
stream: Option<ConnectFuture>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> TcpConnector<T> {
|
impl<T: RequestPort> TcpConnectorResponse<T> {
|
||||||
pub fn new(req: T, host: String, addrs: VecDeque<SocketAddr>) -> TcpConnector<T> {
|
pub fn new(req: T, addrs: VecDeque<IpAddr>) -> TcpConnectorResponse<T> {
|
||||||
TcpConnector {
|
TcpConnectorResponse {
|
||||||
addrs,
|
addrs,
|
||||||
|
port: req.port(),
|
||||||
req: Some(req),
|
req: Some(req),
|
||||||
host: Some(host),
|
|
||||||
addr: None,
|
addr: None,
|
||||||
stream: None,
|
stream: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Future for TcpConnector<T> {
|
impl<T: RequestPort> Future for TcpConnectorResponse<T> {
|
||||||
type Item = (T, ConnectionInfo, TcpStream);
|
type Item = (T, TcpStream);
|
||||||
type Error = ConnectorError;
|
type Error = io::Error;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
// connect
|
// connect
|
||||||
@@ -232,28 +318,66 @@ impl<T> Future for TcpConnector<T> {
|
|||||||
if let Some(new) = self.stream.as_mut() {
|
if let Some(new) = self.stream.as_mut() {
|
||||||
match new.poll() {
|
match new.poll() {
|
||||||
Ok(Async::Ready(sock)) => {
|
Ok(Async::Ready(sock)) => {
|
||||||
return Ok(Async::Ready((
|
return Ok(Async::Ready((self.req.take().unwrap(), sock)))
|
||||||
self.req.take().unwrap(),
|
|
||||||
ConnectionInfo {
|
|
||||||
host: self.host.take().unwrap(),
|
|
||||||
addr: self.addr.take().unwrap(),
|
|
||||||
},
|
|
||||||
sock,
|
|
||||||
)))
|
|
||||||
}
|
}
|
||||||
Ok(Async::NotReady) => return Ok(Async::NotReady),
|
Ok(Async::NotReady) => return Ok(Async::NotReady),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
if self.addrs.is_empty() {
|
if self.addrs.is_empty() {
|
||||||
return Err(ConnectorError::IoError(err));
|
return Err(err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// try to connect
|
// try to connect
|
||||||
let addr = self.addrs.pop_front().unwrap();
|
let addr = SocketAddr::new(self.addrs.pop_front().unwrap(), self.port);
|
||||||
self.stream = Some(TcpStream::connect(&addr));
|
self.stream = Some(TcpStream::connect(&addr));
|
||||||
self.addr = Some(addr)
|
self.addr = Some(addr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct DefaultConnector(Connector);
|
||||||
|
|
||||||
|
impl Default for DefaultConnector {
|
||||||
|
fn default() -> Self {
|
||||||
|
DefaultConnector(Connector::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DefaultConnector {
|
||||||
|
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
|
||||||
|
DefaultConnector(Connector::new(cfg, opts))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Service<Connect> for DefaultConnector {
|
||||||
|
type Response = TcpStream;
|
||||||
|
type Error = ConnectorError;
|
||||||
|
type Future = DefaultConnectorFuture;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
|
self.0.poll_ready()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, req: Connect) -> Self::Future {
|
||||||
|
DefaultConnectorFuture {
|
||||||
|
fut: self.0.call(req),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub struct DefaultConnectorFuture {
|
||||||
|
fut: Either<ConnectorFuture, ConnectorTcpFuture>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Future for DefaultConnectorFuture {
|
||||||
|
type Item = TcpStream;
|
||||||
|
type Error = ConnectorError;
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
|
Ok(Async::Ready(try_ready!(self.fut.poll()).1))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -1,5 +1,5 @@
|
|||||||
//! Contains `Either` service and related types and functions.
|
//! Contains `Either` service and related types and functions.
|
||||||
use futures::{future, Async, Future, Poll};
|
use futures::{future, try_ready, Async, Future, Poll};
|
||||||
|
|
||||||
use super::service::{NewService, Service};
|
use super::service::{NewService, Service};
|
||||||
|
|
||||||
@@ -13,12 +13,11 @@ pub enum EitherService<A, B> {
|
|||||||
B(B),
|
B(B),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Service for EitherService<A, B>
|
impl<A, B, Request> Service<Request> for EitherService<A, B>
|
||||||
where
|
where
|
||||||
A: Service,
|
A: Service<Request>,
|
||||||
B: Service<Request = A::Request, Response = A::Response, Error = A::Error>,
|
B: Service<Request, Response = A::Response, Error = A::Error>,
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
|
||||||
type Response = A::Response;
|
type Response = A::Response;
|
||||||
type Error = A::Error;
|
type Error = A::Error;
|
||||||
type Future = future::Either<A::Future, B::Future>;
|
type Future = future::Either<A::Future, B::Future>;
|
||||||
@@ -30,7 +29,7 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Request) -> Self::Future {
|
||||||
match self {
|
match self {
|
||||||
EitherService::A(ref mut inner) => future::Either::A(inner.call(req)),
|
EitherService::A(ref mut inner) => future::Either::A(inner.call(req)),
|
||||||
EitherService::B(ref mut inner) => future::Either::B(inner.call(req)),
|
EitherService::B(ref mut inner) => future::Either::B(inner.call(req)),
|
||||||
@@ -44,22 +43,16 @@ pub enum Either<A, B> {
|
|||||||
B(B),
|
B(B),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> NewService for Either<A, B>
|
impl<A, B, Request> NewService<Request> for Either<A, B>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
B: NewService<
|
B: NewService<Request, Response = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||||
Request = A::Request,
|
|
||||||
Response = A::Response,
|
|
||||||
Error = A::Error,
|
|
||||||
InitError = A::InitError,
|
|
||||||
>,
|
|
||||||
{
|
{
|
||||||
type Request = A::Request;
|
|
||||||
type Response = A::Response;
|
type Response = A::Response;
|
||||||
type Error = A::Error;
|
type Error = A::Error;
|
||||||
type InitError = A::InitError;
|
type InitError = A::InitError;
|
||||||
type Service = EitherService<A::Service, B::Service>;
|
type Service = EitherService<A::Service, B::Service>;
|
||||||
type Future = EitherNewService<A, B>;
|
type Future = EitherNewService<A, B, Request>;
|
||||||
|
|
||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
match self {
|
match self {
|
||||||
@@ -70,20 +63,15 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub enum EitherNewService<A: NewService, B: NewService> {
|
pub enum EitherNewService<A: NewService<R>, B: NewService<R>, R> {
|
||||||
A(A::Future),
|
A(A::Future),
|
||||||
B(B::Future),
|
B(B::Future),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<A, B> Future for EitherNewService<A, B>
|
impl<A, B, Request> Future for EitherNewService<A, B, Request>
|
||||||
where
|
where
|
||||||
A: NewService,
|
A: NewService<Request>,
|
||||||
B: NewService<
|
B: NewService<Request, Response = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||||
Request = A::Request,
|
|
||||||
Response = A::Response,
|
|
||||||
Error = A::Error,
|
|
||||||
InitError = A::InitError,
|
|
||||||
>,
|
|
||||||
{
|
{
|
||||||
type Item = EitherService<A::Service, B::Service>;
|
type Item = EitherService<A::Service, B::Service>;
|
||||||
type Error = A::InitError;
|
type Error = A::InitError;
|
||||||
|
@@ -9,8 +9,8 @@ use futures::{Async, AsyncSink, Future, Poll, Sink, Stream};
|
|||||||
use tokio_codec::{Decoder, Encoder};
|
use tokio_codec::{Decoder, Encoder};
|
||||||
use tokio_io::{AsyncRead, AsyncWrite};
|
use tokio_io::{AsyncRead, AsyncWrite};
|
||||||
|
|
||||||
use codec::Framed;
|
use crate::codec::Framed;
|
||||||
use service::{IntoNewService, IntoService, NewService, Service};
|
use crate::service::{IntoNewService, IntoService, NewService, Service};
|
||||||
|
|
||||||
type Request<U> = <U as Decoder>::Item;
|
type Request<U> = <U as Decoder>::Item;
|
||||||
type Response<U> = <U as Encoder>::Item;
|
type Response<U> = <U as Encoder>::Item;
|
||||||
@@ -24,13 +24,13 @@ impl<S, T, U> FramedNewService<S, T, U>
|
|||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
S: NewService<Request = Request<U>, Response = Response<U>> + Clone,
|
S: NewService<Request<U>, Response = Response<U>>,
|
||||||
<<S as NewService>::Service as Service>::Future: 'static,
|
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
|
||||||
<<S as NewService>::Service as Service>::Error: 'static,
|
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: 'static,
|
<U as Encoder>::Error: 'static,
|
||||||
{
|
{
|
||||||
pub fn new<F1: IntoNewService<S>>(factory: F1) -> Self {
|
pub fn new<F1: IntoNewService<S, Request<U>>>(factory: F1) -> Self {
|
||||||
Self {
|
Self {
|
||||||
factory: factory.into_new_service(),
|
factory: factory.into_new_service(),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
@@ -50,17 +50,16 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, T, U> NewService for FramedNewService<S, T, U>
|
impl<S, T, U> NewService<Framed<T, U>> for FramedNewService<S, T, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
S: NewService<Request = Request<U>, Response = Response<U>> + Clone,
|
S: NewService<Request<U>, Response = Response<U>> + Clone,
|
||||||
<<S as NewService>::Service as Service>::Future: 'static,
|
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
|
||||||
<<S as NewService>::Service as Service>::Error: 'static,
|
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: 'static,
|
<U as Encoder>::Error: 'static,
|
||||||
{
|
{
|
||||||
type Request = Framed<T, U>;
|
|
||||||
type Response = FramedTransport<S::Service, T, U>;
|
type Response = FramedTransport<S::Service, T, U>;
|
||||||
type Error = S::InitError;
|
type Error = S::InitError;
|
||||||
type InitError = S::InitError;
|
type InitError = S::InitError;
|
||||||
@@ -92,17 +91,16 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, T, U> Service for FramedService<S, T, U>
|
impl<S, T, U> Service<Framed<T, U>> for FramedService<S, T, U>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
S: NewService<Request = Request<U>, Response = Response<U>>,
|
S: NewService<Request<U>, Response = Response<U>>,
|
||||||
<<S as NewService>::Service as Service>::Future: 'static,
|
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
|
||||||
<<S as NewService>::Service as Service>::Error: 'static,
|
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: 'static,
|
<U as Encoder>::Error: 'static,
|
||||||
{
|
{
|
||||||
type Request = Framed<T, U>;
|
|
||||||
type Response = FramedTransport<S::Service, T, U>;
|
type Response = FramedTransport<S::Service, T, U>;
|
||||||
type Error = S::InitError;
|
type Error = S::InitError;
|
||||||
type Future = FramedServiceResponseFuture<S, T, U>;
|
type Future = FramedServiceResponseFuture<S, T, U>;
|
||||||
@@ -111,7 +109,7 @@ where
|
|||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Framed<T, U>) -> Self::Future {
|
||||||
FramedServiceResponseFuture {
|
FramedServiceResponseFuture {
|
||||||
fut: self.factory.new_service(),
|
fut: self.factory.new_service(),
|
||||||
|
|
||||||
@@ -125,9 +123,9 @@ pub struct FramedServiceResponseFuture<S, T, U>
|
|||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
S: NewService<Request = Request<U>, Response = Response<U>>,
|
S: NewService<Request<U>, Response = Response<U>>,
|
||||||
<<S as NewService>::Service as Service>::Future: 'static,
|
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
|
||||||
<<S as NewService>::Service as Service>::Error: 'static,
|
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: 'static,
|
<U as Encoder>::Error: 'static,
|
||||||
{
|
{
|
||||||
@@ -139,9 +137,9 @@ impl<S, T, U> Future for FramedServiceResponseFuture<S, T, U>
|
|||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
S: NewService<Request = Request<U>, Response = Response<U>>,
|
S: NewService<Request<U>, Response = Response<U>>,
|
||||||
<<S as NewService>::Service as Service>::Future: 'static,
|
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
|
||||||
<<S as NewService>::Service as Service>::Error: 'static,
|
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
<U as Encoder>::Error: 'static,
|
<U as Encoder>::Error: 'static,
|
||||||
{
|
{
|
||||||
@@ -176,7 +174,7 @@ impl<E, U: Encoder + Decoder> From<E> for FramedTransportError<E, U> {
|
|||||||
/// and pass then to the service.
|
/// and pass then to the service.
|
||||||
pub struct FramedTransport<S, T, U>
|
pub struct FramedTransport<S, T, U>
|
||||||
where
|
where
|
||||||
S: Service,
|
S: Service<Request<U>, Response = Response<U>>,
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Encoder + Decoder,
|
U: Encoder + Decoder,
|
||||||
{
|
{
|
||||||
@@ -190,7 +188,7 @@ where
|
|||||||
flushed: bool,
|
flushed: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
enum TransportState<S: Service, U: Encoder + Decoder> {
|
enum TransportState<S: Service<Request<U>>, U: Encoder + Decoder> {
|
||||||
Processing,
|
Processing,
|
||||||
Error(FramedTransportError<S::Error, U>),
|
Error(FramedTransportError<S::Error, U>),
|
||||||
EncoderError(FramedTransportError<S::Error, U>),
|
EncoderError(FramedTransportError<S::Error, U>),
|
||||||
@@ -201,12 +199,12 @@ impl<S, T, U> FramedTransport<S, T, U>
|
|||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
S: Service<Request = Request<U>, Response = Response<U>>,
|
S: Service<Request<U>, Response = Response<U>>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
<U as Encoder>::Error: 'static,
|
<U as Encoder>::Error: 'static,
|
||||||
{
|
{
|
||||||
pub fn new<F: IntoService<S>>(framed: Framed<T, U>, service: F) -> Self {
|
pub fn new<F: IntoService<S, Request<U>>>(framed: Framed<T, U>, service: F) -> Self {
|
||||||
let (write_tx, write_rx) = mpsc::channel(16);
|
let (write_tx, write_rx) = mpsc::channel(16);
|
||||||
FramedTransport {
|
FramedTransport {
|
||||||
framed,
|
framed,
|
||||||
@@ -248,7 +246,7 @@ impl<S, T, U> FramedTransport<S, T, U>
|
|||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
S: Service<Request = Request<U>, Response = Response<U>>,
|
S: Service<Request<U>, Response = Response<U>>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
@@ -302,10 +300,10 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Async::NotReady) => return false,
|
Ok(Async::NotReady) => false,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
self.state = TransportState::Error(FramedTransportError::Service(err));
|
self.state = TransportState::Error(FramedTransportError::Service(err));
|
||||||
return true;
|
true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -377,7 +375,7 @@ impl<S, T, U> Future for FramedTransport<S, T, U>
|
|||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
U: Decoder + Encoder,
|
U: Decoder + Encoder,
|
||||||
S: Service<Request = Request<U>, Response = Response<U>>,
|
S: Service<Request<U>, Response = Response<U>>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
S::Error: 'static,
|
S::Error: 'static,
|
||||||
<U as Encoder>::Item: 'static,
|
<U as Encoder>::Item: 'static,
|
||||||
@@ -389,26 +387,22 @@ where
|
|||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
match mem::replace(&mut self.state, TransportState::Processing) {
|
match mem::replace(&mut self.state, TransportState::Processing) {
|
||||||
TransportState::Processing => {
|
TransportState::Processing => {
|
||||||
if self.poll_service() {
|
if self.poll_service() || self.poll_response() {
|
||||||
return self.poll();
|
self.poll()
|
||||||
|
} else {
|
||||||
|
Ok(Async::NotReady)
|
||||||
}
|
}
|
||||||
if self.poll_response() {
|
|
||||||
return self.poll();
|
|
||||||
}
|
|
||||||
return Ok(Async::NotReady);
|
|
||||||
}
|
}
|
||||||
TransportState::Error(err) => {
|
TransportState::Error(err) => {
|
||||||
if self.poll_response() {
|
if self.poll_response() || self.flushed {
|
||||||
return Err(err);
|
Err(err)
|
||||||
}
|
} else {
|
||||||
if self.flushed {
|
|
||||||
return Err(err);
|
|
||||||
}
|
|
||||||
self.state = TransportState::Error(err);
|
self.state = TransportState::Error(err);
|
||||||
return Ok(Async::NotReady);
|
Ok(Async::NotReady)
|
||||||
}
|
}
|
||||||
TransportState::EncoderError(err) => return Err(err),
|
}
|
||||||
TransportState::Stopping => return Ok(Async::Ready(())),
|
TransportState::EncoderError(err) => Err(err),
|
||||||
|
TransportState::Stopping => Ok(Async::Ready(())),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -437,13 +431,12 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, U, F> NewService for IntoFramed<T, U, F>
|
impl<T, U, F> NewService<T> for IntoFramed<T, U, F>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
F: Fn() -> U + Send + Clone + 'static,
|
F: Fn() -> U + Send + Clone + 'static,
|
||||||
U: Encoder + Decoder,
|
U: Encoder + Decoder,
|
||||||
{
|
{
|
||||||
type Request = T;
|
|
||||||
type Response = Framed<T, U>;
|
type Response = Framed<T, U>;
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
@@ -468,13 +461,12 @@ where
|
|||||||
_t: PhantomData<(T,)>,
|
_t: PhantomData<(T,)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, U, F> Service for IntoFramedService<T, U, F>
|
impl<T, U, F> Service<T> for IntoFramedService<T, U, F>
|
||||||
where
|
where
|
||||||
T: AsyncRead + AsyncWrite,
|
T: AsyncRead + AsyncWrite,
|
||||||
F: Fn() -> U + Send + Clone + 'static,
|
F: Fn() -> U + Send + Clone + 'static,
|
||||||
U: Encoder + Decoder,
|
U: Encoder + Decoder,
|
||||||
{
|
{
|
||||||
type Request = T;
|
|
||||||
type Response = Framed<T, U>;
|
type Response = Framed<T, U>;
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type Future = FutureResult<Self::Response, Self::Error>;
|
type Future = FutureResult<Self::Response, Self::Error>;
|
||||||
@@ -483,7 +475,7 @@ where
|
|||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: T) -> Self::Future {
|
||||||
ok(Framed::new(req, (self.factory)()))
|
ok(Framed::new(req, (self.factory)()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -1,4 +1,4 @@
|
|||||||
use futures::{Async, Future, Poll};
|
use futures::{try_ready, Async, Future, Poll};
|
||||||
|
|
||||||
use super::counter::{Counter, CounterGuard};
|
use super::counter::{Counter, CounterGuard};
|
||||||
use super::service::{IntoNewService, IntoService, NewService, Service};
|
use super::service::{IntoNewService, IntoService, NewService, Service};
|
||||||
@@ -12,11 +12,12 @@ pub struct InFlight<T> {
|
|||||||
max_inflight: usize,
|
max_inflight: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> InFlight<T>
|
impl<T> InFlight<T> {
|
||||||
|
pub fn new<F, Request>(factory: F) -> Self
|
||||||
where
|
where
|
||||||
T: NewService,
|
T: NewService<Request>,
|
||||||
|
F: IntoNewService<T, Request>,
|
||||||
{
|
{
|
||||||
pub fn new<F: IntoNewService<T>>(factory: F) -> Self {
|
|
||||||
Self {
|
Self {
|
||||||
factory: factory.into_new_service(),
|
factory: factory.into_new_service(),
|
||||||
max_inflight: 15,
|
max_inflight: 15,
|
||||||
@@ -32,16 +33,15 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> NewService for InFlight<T>
|
impl<T, Request> NewService<Request> for InFlight<T>
|
||||||
where
|
where
|
||||||
T: NewService,
|
T: NewService<Request>,
|
||||||
{
|
{
|
||||||
type Request = T::Request;
|
|
||||||
type Response = T::Response;
|
type Response = T::Response;
|
||||||
type Error = T::Error;
|
type Error = T::Error;
|
||||||
type InitError = T::InitError;
|
type InitError = T::InitError;
|
||||||
type Service = InFlightService<T::Service>;
|
type Service = InFlightService<T::Service>;
|
||||||
type Future = InFlightResponseFuture<T>;
|
type Future = InFlightResponseFuture<T, Request>;
|
||||||
|
|
||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
InFlightResponseFuture {
|
InFlightResponseFuture {
|
||||||
@@ -51,12 +51,12 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct InFlightResponseFuture<T: NewService> {
|
pub struct InFlightResponseFuture<T: NewService<Request>, Request> {
|
||||||
fut: T::Future,
|
fut: T::Future,
|
||||||
max_inflight: usize,
|
max_inflight: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: NewService> Future for InFlightResponseFuture<T> {
|
impl<T: NewService<Request>, Request> Future for InFlightResponseFuture<T, Request> {
|
||||||
type Item = InFlightService<T::Service>;
|
type Item = InFlightService<T::Service>;
|
||||||
type Error = T::InitError;
|
type Error = T::InitError;
|
||||||
|
|
||||||
@@ -73,15 +73,23 @@ pub struct InFlightService<T> {
|
|||||||
count: Counter,
|
count: Counter,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Service> InFlightService<T> {
|
impl<T> InFlightService<T> {
|
||||||
pub fn new<F: IntoService<T>>(service: F) -> Self {
|
pub fn new<F, Request>(service: F) -> Self
|
||||||
|
where
|
||||||
|
T: Service<Request>,
|
||||||
|
F: IntoService<T, Request>,
|
||||||
|
{
|
||||||
Self {
|
Self {
|
||||||
service: service.into_service(),
|
service: service.into_service(),
|
||||||
count: Counter::new(15),
|
count: Counter::new(15),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_max_inflight<F: IntoService<T>>(max: usize, service: F) -> Self {
|
pub fn with_max_inflight<F, Request>(max: usize, service: F) -> Self
|
||||||
|
where
|
||||||
|
T: Service<Request>,
|
||||||
|
F: IntoService<T, Request>,
|
||||||
|
{
|
||||||
Self {
|
Self {
|
||||||
service: service.into_service(),
|
service: service.into_service(),
|
||||||
count: Counter::new(max),
|
count: Counter::new(max),
|
||||||
@@ -89,11 +97,13 @@ impl<T: Service> InFlightService<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Service> Service for InFlightService<T> {
|
impl<T, Request> Service<Request> for InFlightService<T>
|
||||||
type Request = T::Request;
|
where
|
||||||
|
T: Service<Request>,
|
||||||
|
{
|
||||||
type Response = T::Response;
|
type Response = T::Response;
|
||||||
type Error = T::Error;
|
type Error = T::Error;
|
||||||
type Future = InFlightServiceResponse<T>;
|
type Future = InFlightServiceResponse<T, Request>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
let res = self.service.poll_ready();
|
let res = self.service.poll_ready();
|
||||||
@@ -103,22 +113,21 @@ impl<T: Service> Service for InFlightService<T> {
|
|||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: Request) -> Self::Future {
|
||||||
InFlightServiceResponse {
|
InFlightServiceResponse {
|
||||||
fut: self.service.call(req),
|
fut: self.service.call(req),
|
||||||
guard: self.count.get(),
|
_guard: self.count.get(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)]
|
||||||
pub struct InFlightServiceResponse<T: Service> {
|
pub struct InFlightServiceResponse<T: Service<Request>, Request> {
|
||||||
fut: T::Future,
|
fut: T::Future,
|
||||||
#[allow(dead_code)]
|
_guard: CounterGuard,
|
||||||
guard: CounterGuard,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Service> Future for InFlightServiceResponse<T> {
|
impl<T: Service<Request>, Request> Future for InFlightServiceResponse<T, Request> {
|
||||||
type Item = T::Response;
|
type Item = T::Response;
|
||||||
type Error = T::Error;
|
type Error = T::Error;
|
||||||
|
|
||||||
|
@@ -6,13 +6,13 @@ use futures::{Async, Future, Poll};
|
|||||||
use tokio_timer::Delay;
|
use tokio_timer::Delay;
|
||||||
|
|
||||||
use super::service::{NewService, Service};
|
use super::service::{NewService, Service};
|
||||||
use super::timer::{LowResTimer, LowResTimerService};
|
use super::time::{LowResTime, LowResTimeService};
|
||||||
use super::Never;
|
use super::Never;
|
||||||
|
|
||||||
pub struct KeepAlive<R, E, F> {
|
pub struct KeepAlive<R, E, F> {
|
||||||
f: F,
|
f: F,
|
||||||
ka: Duration,
|
ka: Duration,
|
||||||
timer: LowResTimer,
|
time: LowResTime,
|
||||||
_t: PhantomData<(R, E)>,
|
_t: PhantomData<(R, E)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -20,11 +20,11 @@ impl<R, E, F> KeepAlive<R, E, F>
|
|||||||
where
|
where
|
||||||
F: Fn() -> E + Clone,
|
F: Fn() -> E + Clone,
|
||||||
{
|
{
|
||||||
pub fn new(ka: Duration, timer: LowResTimer, f: F) -> Self {
|
pub fn new(ka: Duration, time: LowResTime, f: F) -> Self {
|
||||||
KeepAlive {
|
KeepAlive {
|
||||||
f,
|
f,
|
||||||
ka,
|
ka,
|
||||||
timer,
|
time,
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -32,23 +32,22 @@ where
|
|||||||
|
|
||||||
impl<R, E, F> Clone for KeepAlive<R, E, F>
|
impl<R, E, F> Clone for KeepAlive<R, E, F>
|
||||||
where
|
where
|
||||||
F: Fn() -> E + Clone,
|
F: Clone,
|
||||||
{
|
{
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
KeepAlive {
|
KeepAlive {
|
||||||
f: self.f.clone(),
|
f: self.f.clone(),
|
||||||
ka: self.ka,
|
ka: self.ka,
|
||||||
timer: self.timer.clone(),
|
time: self.time.clone(),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R, E, F> NewService for KeepAlive<R, E, F>
|
impl<R, E, F> NewService<R> for KeepAlive<R, E, F>
|
||||||
where
|
where
|
||||||
F: Fn() -> E + Clone,
|
F: Fn() -> E + Clone,
|
||||||
{
|
{
|
||||||
type Request = R;
|
|
||||||
type Response = R;
|
type Response = R;
|
||||||
type Error = E;
|
type Error = E;
|
||||||
type InitError = Never;
|
type InitError = Never;
|
||||||
@@ -58,7 +57,7 @@ where
|
|||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
ok(KeepAliveService::new(
|
ok(KeepAliveService::new(
|
||||||
self.ka,
|
self.ka,
|
||||||
self.timer.timer(),
|
self.time.timer(),
|
||||||
self.f.clone(),
|
self.f.clone(),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
@@ -67,7 +66,7 @@ where
|
|||||||
pub struct KeepAliveService<R, E, F> {
|
pub struct KeepAliveService<R, E, F> {
|
||||||
f: F,
|
f: F,
|
||||||
ka: Duration,
|
ka: Duration,
|
||||||
timer: LowResTimerService,
|
time: LowResTimeService,
|
||||||
delay: Delay,
|
delay: Delay,
|
||||||
expire: Instant,
|
expire: Instant,
|
||||||
_t: PhantomData<(R, E)>,
|
_t: PhantomData<(R, E)>,
|
||||||
@@ -77,24 +76,23 @@ impl<R, E, F> KeepAliveService<R, E, F>
|
|||||||
where
|
where
|
||||||
F: Fn() -> E,
|
F: Fn() -> E,
|
||||||
{
|
{
|
||||||
pub fn new(ka: Duration, mut timer: LowResTimerService, f: F) -> Self {
|
pub fn new(ka: Duration, time: LowResTimeService, f: F) -> Self {
|
||||||
let expire = timer.now() + ka;
|
let expire = time.now() + ka;
|
||||||
KeepAliveService {
|
KeepAliveService {
|
||||||
f,
|
f,
|
||||||
ka,
|
ka,
|
||||||
timer,
|
time,
|
||||||
delay: Delay::new(expire),
|
|
||||||
expire,
|
expire,
|
||||||
|
delay: Delay::new(expire),
|
||||||
_t: PhantomData,
|
_t: PhantomData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R, E, F> Service for KeepAliveService<R, E, F>
|
impl<R, E, F> Service<R> for KeepAliveService<R, E, F>
|
||||||
where
|
where
|
||||||
F: Fn() -> E,
|
F: Fn() -> E,
|
||||||
{
|
{
|
||||||
type Request = R;
|
|
||||||
type Response = R;
|
type Response = R;
|
||||||
type Error = E;
|
type Error = E;
|
||||||
type Future = FutureResult<R, E>;
|
type Future = FutureResult<R, E>;
|
||||||
@@ -102,11 +100,11 @@ where
|
|||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
match self.delay.poll() {
|
match self.delay.poll() {
|
||||||
Ok(Async::Ready(_)) => {
|
Ok(Async::Ready(_)) => {
|
||||||
let now = self.timer.now();
|
let now = self.time.now();
|
||||||
if self.expire <= now {
|
if self.expire <= now {
|
||||||
Err((self.f)())
|
Err((self.f)())
|
||||||
} else {
|
} else {
|
||||||
self.delay = Delay::new(self.expire);
|
self.delay.reset(self.expire);
|
||||||
let _ = self.delay.poll();
|
let _ = self.delay.poll();
|
||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
@@ -116,8 +114,8 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: R) -> Self::Future {
|
||||||
self.expire = self.timer.now() + self.ka;
|
self.expire = self.time.now() + self.ka;
|
||||||
ok(req)
|
ok(req)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
53
src/lib.rs
53
src/lib.rs
@@ -7,54 +7,11 @@
|
|||||||
//! * `rust-tls` - enables ssl support via `rustls` crate
|
//! * `rust-tls` - enables ssl support via `rustls` crate
|
||||||
// #![warn(missing_docs)]
|
// #![warn(missing_docs)]
|
||||||
|
|
||||||
#![cfg_attr(
|
#![allow(
|
||||||
feature = "cargo-clippy",
|
clippy::declare_interior_mutable_const,
|
||||||
allow(
|
clippy::borrow_interior_mutable_const
|
||||||
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;
|
mod cell;
|
||||||
pub mod cloneable;
|
pub mod cloneable;
|
||||||
pub mod codec;
|
pub mod codec;
|
||||||
@@ -66,10 +23,10 @@ pub mod inflight;
|
|||||||
pub mod keepalive;
|
pub mod keepalive;
|
||||||
pub mod resolver;
|
pub mod resolver;
|
||||||
pub mod server;
|
pub mod server;
|
||||||
pub mod service;
|
|
||||||
pub mod ssl;
|
pub mod ssl;
|
||||||
pub mod stream;
|
pub mod stream;
|
||||||
pub mod timer;
|
pub mod time;
|
||||||
|
pub mod timeout;
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug)]
|
#[derive(Copy, Clone, Debug)]
|
||||||
pub enum Never {}
|
pub enum Never {}
|
||||||
|
101
src/resolver.rs
101
src/resolver.rs
@@ -1,29 +1,24 @@
|
|||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
use std::marker::PhantomData;
|
use std::marker::PhantomData;
|
||||||
use std::net::SocketAddr;
|
use std::net::IpAddr;
|
||||||
|
|
||||||
use futures::{Async, Future, Poll};
|
use futures::{Async, Future, Poll};
|
||||||
|
|
||||||
use tokio_current_thread::spawn;
|
use tokio_current_thread::spawn;
|
||||||
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||||
use trust_dns_resolver::error::ResolveError;
|
pub use trust_dns_resolver::error::ResolveError;
|
||||||
use trust_dns_resolver::lookup_ip::LookupIpFuture;
|
use trust_dns_resolver::lookup_ip::LookupIpFuture;
|
||||||
use trust_dns_resolver::system_conf::read_system_conf;
|
use trust_dns_resolver::system_conf::read_system_conf;
|
||||||
use trust_dns_resolver::{AsyncResolver, Background};
|
use trust_dns_resolver::{AsyncResolver, Background};
|
||||||
|
|
||||||
use super::service::Service;
|
use super::service::Service;
|
||||||
|
|
||||||
#[derive(Debug)]
|
/// Host name of the request
|
||||||
pub enum ResolverError {
|
pub trait RequestHost {
|
||||||
Resolve(ResolveError),
|
|
||||||
InvalidInput,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub trait HostAware {
|
|
||||||
fn host(&self) -> &str;
|
fn host(&self) -> &str;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HostAware for String {
|
impl RequestHost for String {
|
||||||
fn host(&self) -> &str {
|
fn host(&self) -> &str {
|
||||||
self.as_ref()
|
self.as_ref()
|
||||||
}
|
}
|
||||||
@@ -34,7 +29,7 @@ pub struct Resolver<T = String> {
|
|||||||
req: PhantomData<T>,
|
req: PhantomData<T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: HostAware> Default for Resolver<T> {
|
impl<T: RequestHost> Default for Resolver<T> {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
let (cfg, opts) = if let Ok((cfg, opts)) = read_system_conf() {
|
let (cfg, opts) = if let Ok((cfg, opts)) = read_system_conf() {
|
||||||
(cfg, opts)
|
(cfg, opts)
|
||||||
@@ -46,7 +41,8 @@ impl<T: HostAware> Default for Resolver<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: HostAware> Resolver<T> {
|
impl<T: RequestHost> Resolver<T> {
|
||||||
|
/// Create new resolver instance with custom configuration and options.
|
||||||
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
|
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
|
||||||
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
||||||
spawn(bg);
|
spawn(bg);
|
||||||
@@ -56,7 +52,8 @@ impl<T: HostAware> Resolver<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn change_request<T2: HostAware>(&self) -> Resolver<T2> {
|
/// Change type of resolver request.
|
||||||
|
pub fn into_request<T2: RequestHost>(&self) -> Resolver<T2> {
|
||||||
Resolver {
|
Resolver {
|
||||||
resolver: self.resolver.clone(),
|
resolver: self.resolver.clone(),
|
||||||
req: PhantomData,
|
req: PhantomData,
|
||||||
@@ -73,18 +70,17 @@ impl<T> Clone for Resolver<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: HostAware> Service for Resolver<T> {
|
impl<T: RequestHost> Service<T> for Resolver<T> {
|
||||||
type Request = T;
|
type Response = (T, VecDeque<IpAddr>);
|
||||||
type Response = (T, String, VecDeque<SocketAddr>);
|
type Error = ResolveError;
|
||||||
type Error = ResolverError;
|
|
||||||
type Future = ResolverFuture<T>;
|
type Future = ResolverFuture<T>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: T) -> Self::Future {
|
||||||
ResolverFuture::new(req, 0, &self.resolver)
|
ResolverFuture::new(req, &self.resolver)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,78 +88,37 @@ impl<T: HostAware> Service for Resolver<T> {
|
|||||||
/// Resolver future
|
/// Resolver future
|
||||||
pub struct ResolverFuture<T> {
|
pub struct ResolverFuture<T> {
|
||||||
req: Option<T>,
|
req: Option<T>,
|
||||||
port: u16,
|
|
||||||
lookup: Option<Background<LookupIpFuture>>,
|
lookup: Option<Background<LookupIpFuture>>,
|
||||||
addrs: Option<VecDeque<SocketAddr>>,
|
addrs: Option<VecDeque<IpAddr>>,
|
||||||
error: Option<ResolverError>,
|
|
||||||
host: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: HostAware> ResolverFuture<T> {
|
impl<T: RequestHost> ResolverFuture<T> {
|
||||||
pub fn new(addr: T, port: u16, resolver: &AsyncResolver) -> Self {
|
pub fn new(addr: T, resolver: &AsyncResolver) -> Self {
|
||||||
// we need to do dns resolution
|
// we need to do dns resolution
|
||||||
match ResolverFuture::<T>::parse(addr.host(), port) {
|
let lookup = Some(resolver.lookup_ip(addr.host()));
|
||||||
Ok((host, port)) => {
|
|
||||||
let lookup = Some(resolver.lookup_ip(host.as_str()));
|
|
||||||
ResolverFuture {
|
ResolverFuture {
|
||||||
port,
|
|
||||||
lookup,
|
lookup,
|
||||||
req: Some(addr),
|
req: Some(addr),
|
||||||
host: Some(host.to_owned()),
|
|
||||||
addrs: None,
|
addrs: None,
|
||||||
error: None,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(err) => ResolverFuture {
|
|
||||||
port,
|
|
||||||
req: None,
|
|
||||||
host: None,
|
|
||||||
lookup: None,
|
|
||||||
addrs: None,
|
|
||||||
error: Some(err),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse(addr: &str, port: u16) -> Result<(String, u16), ResolverError> {
|
impl<T: RequestHost> Future for ResolverFuture<T> {
|
||||||
// split the string by ':' and convert the second part to u16
|
type Item = (T, VecDeque<IpAddr>);
|
||||||
let mut parts_iter = addr.splitn(2, ':');
|
type Error = ResolveError;
|
||||||
let host = parts_iter.next().ok_or(ResolverError::InvalidInput)?;
|
|
||||||
let port_str = parts_iter.next().unwrap_or("");
|
|
||||||
let port: u16 = port_str.parse().unwrap_or(port);
|
|
||||||
|
|
||||||
Ok((host.to_owned(), port))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: HostAware> Future for ResolverFuture<T> {
|
|
||||||
type Item = (T, String, VecDeque<SocketAddr>);
|
|
||||||
type Error = ResolverError;
|
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
if let Some(err) = self.error.take() {
|
if let Some(addrs) = self.addrs.take() {
|
||||||
Err(err)
|
Ok(Async::Ready((self.req.take().unwrap(), addrs)))
|
||||||
} else if let Some(addrs) = self.addrs.take() {
|
|
||||||
Ok(Async::Ready((
|
|
||||||
self.req.take().unwrap(),
|
|
||||||
self.host.take().unwrap(),
|
|
||||||
addrs,
|
|
||||||
)))
|
|
||||||
} else {
|
} else {
|
||||||
match self.lookup.as_mut().unwrap().poll() {
|
match self.lookup.as_mut().unwrap().poll() {
|
||||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||||
Ok(Async::Ready(ips)) => {
|
Ok(Async::Ready(ips)) => Ok(Async::Ready((
|
||||||
let addrs: VecDeque<_> = ips
|
|
||||||
.iter()
|
|
||||||
.map(|ip| SocketAddr::new(ip, self.port))
|
|
||||||
.collect();
|
|
||||||
Ok(Async::Ready((
|
|
||||||
self.req.take().unwrap(),
|
self.req.take().unwrap(),
|
||||||
self.host.take().unwrap(),
|
ips.iter().collect(),
|
||||||
addrs,
|
))),
|
||||||
)))
|
Err(err) => Err(err),
|
||||||
}
|
|
||||||
Err(err) => Err(ResolverError::Resolve(err)),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -3,6 +3,7 @@ use std::time::{Duration, Instant};
|
|||||||
use std::{io, net, thread};
|
use std::{io, net, thread};
|
||||||
|
|
||||||
use futures::{sync::mpsc, Future};
|
use futures::{sync::mpsc, Future};
|
||||||
|
use log::{error, info};
|
||||||
use mio;
|
use mio;
|
||||||
use slab::Slab;
|
use slab::Slab;
|
||||||
use tokio_timer::Delay;
|
use tokio_timer::Delay;
|
||||||
@@ -23,7 +24,6 @@ pub(crate) enum Command {
|
|||||||
struct ServerSocketInfo {
|
struct ServerSocketInfo {
|
||||||
addr: net::SocketAddr,
|
addr: net::SocketAddr,
|
||||||
token: Token,
|
token: Token,
|
||||||
handler: Token,
|
|
||||||
sock: mio::net::TcpListener,
|
sock: mio::net::TcpListener,
|
||||||
timeout: Option<Instant>,
|
timeout: Option<Instant>,
|
||||||
}
|
}
|
||||||
@@ -87,7 +87,9 @@ impl AcceptLoop {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn start(
|
pub(crate) fn start(
|
||||||
&mut self, socks: Vec<(Token, net::TcpListener)>, workers: Vec<WorkerClient>,
|
&mut self,
|
||||||
|
socks: Vec<(Token, net::TcpListener)>,
|
||||||
|
workers: Vec<WorkerClient>,
|
||||||
) -> mpsc::UnboundedReceiver<ServerCommand> {
|
) -> mpsc::UnboundedReceiver<ServerCommand> {
|
||||||
let (tx, rx) = self.srv.take().expect("Can not re-use AcceptInfo");
|
let (tx, rx) = self.srv.take().expect("Can not re-use AcceptInfo");
|
||||||
|
|
||||||
@@ -133,11 +135,14 @@ fn connection_error(e: &io::Error) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Accept {
|
impl Accept {
|
||||||
#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))]
|
#![allow(clippy::too_many_arguments)]
|
||||||
pub(crate) fn start(
|
pub(crate) fn start(
|
||||||
rx: sync_mpsc::Receiver<Command>, cmd_reg: mio::Registration,
|
rx: sync_mpsc::Receiver<Command>,
|
||||||
notify_reg: mio::Registration, socks: Vec<(Token, net::TcpListener)>,
|
cmd_reg: mio::Registration,
|
||||||
srv: mpsc::UnboundedSender<ServerCommand>, workers: Vec<WorkerClient>,
|
notify_reg: mio::Registration,
|
||||||
|
socks: Vec<(Token, net::TcpListener)>,
|
||||||
|
srv: mpsc::UnboundedSender<ServerCommand>,
|
||||||
|
workers: Vec<WorkerClient>,
|
||||||
) {
|
) {
|
||||||
let sys = System::current();
|
let sys = System::current();
|
||||||
|
|
||||||
@@ -173,8 +178,10 @@ impl Accept {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn new(
|
fn new(
|
||||||
rx: sync_mpsc::Receiver<Command>, socks: Vec<(Token, net::TcpListener)>,
|
rx: sync_mpsc::Receiver<Command>,
|
||||||
workers: Vec<WorkerClient>, srv: mpsc::UnboundedSender<ServerCommand>,
|
socks: Vec<(Token, net::TcpListener)>,
|
||||||
|
workers: Vec<WorkerClient>,
|
||||||
|
srv: mpsc::UnboundedSender<ServerCommand>,
|
||||||
) -> Accept {
|
) -> Accept {
|
||||||
// Create a poll instance
|
// Create a poll instance
|
||||||
let poll = match mio::Poll::new() {
|
let poll = match mio::Poll::new() {
|
||||||
@@ -184,7 +191,7 @@ impl Accept {
|
|||||||
|
|
||||||
// Start accept
|
// Start accept
|
||||||
let mut sockets = Slab::new();
|
let mut sockets = Slab::new();
|
||||||
for (idx, (hnd_token, lst)) in socks.into_iter().enumerate() {
|
for (hnd_token, lst) in socks.into_iter() {
|
||||||
let addr = lst.local_addr().unwrap();
|
let addr = lst.local_addr().unwrap();
|
||||||
let server = mio::net::TcpListener::from_std(lst)
|
let server = mio::net::TcpListener::from_std(lst)
|
||||||
.expect("Can not create mio::net::TcpListener");
|
.expect("Can not create mio::net::TcpListener");
|
||||||
@@ -205,7 +212,6 @@ impl Accept {
|
|||||||
entry.insert(ServerSocketInfo {
|
entry.insert(ServerSocketInfo {
|
||||||
addr,
|
addr,
|
||||||
token: hnd_token,
|
token: hnd_token,
|
||||||
handler: Token(idx),
|
|
||||||
sock: server,
|
sock: server,
|
||||||
timeout: None,
|
timeout: None,
|
||||||
});
|
});
|
||||||
@@ -243,9 +249,11 @@ impl Accept {
|
|||||||
for event in events.iter() {
|
for event in events.iter() {
|
||||||
let token = event.token();
|
let token = event.token();
|
||||||
match token {
|
match token {
|
||||||
CMD => if !self.process_cmd() {
|
CMD => {
|
||||||
|
if !self.process_cmd() {
|
||||||
return;
|
return;
|
||||||
},
|
}
|
||||||
|
}
|
||||||
TIMER => self.process_timer(),
|
TIMER => self.process_timer(),
|
||||||
NOTIFY => self.backpressure(false),
|
NOTIFY => self.backpressure(false),
|
||||||
_ => {
|
_ => {
|
||||||
@@ -427,7 +435,6 @@ impl Accept {
|
|||||||
Ok((io, addr)) => Conn {
|
Ok((io, addr)) => Conn {
|
||||||
io,
|
io,
|
||||||
token: info.token,
|
token: info.token,
|
||||||
handler: info.handler,
|
|
||||||
peer: Some(addr),
|
peer: Some(addr),
|
||||||
},
|
},
|
||||||
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => return,
|
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => return,
|
||||||
|
213
src/server/config.rs
Normal file
213
src/server/config.rs
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
use std::collections::HashMap;
|
||||||
|
use std::{fmt, io, net};
|
||||||
|
|
||||||
|
use futures::future::{join_all, Future};
|
||||||
|
use log::error;
|
||||||
|
use tokio_tcp::TcpStream;
|
||||||
|
|
||||||
|
use crate::counter::CounterGuard;
|
||||||
|
use crate::service::{IntoNewService, NewService};
|
||||||
|
|
||||||
|
use super::server::bind_addr;
|
||||||
|
use super::services::{
|
||||||
|
BoxedServerService, InternalServiceFactory, ServerMessage, StreamService,
|
||||||
|
};
|
||||||
|
use super::Token;
|
||||||
|
|
||||||
|
pub struct ServiceConfig {
|
||||||
|
pub(super) services: Vec<(String, net::TcpListener)>,
|
||||||
|
pub(super) rt: Box<ServiceRuntimeConfiguration>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ServiceConfig {
|
||||||
|
pub(super) fn new() -> ServiceConfig {
|
||||||
|
ServiceConfig {
|
||||||
|
services: Vec::new(),
|
||||||
|
rt: Box::new(not_configured),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add new service to server
|
||||||
|
pub fn bind<U, N: AsRef<str>>(&mut self, name: N, addr: U) -> io::Result<&mut Self>
|
||||||
|
where
|
||||||
|
U: net::ToSocketAddrs,
|
||||||
|
{
|
||||||
|
let sockets = bind_addr(addr)?;
|
||||||
|
|
||||||
|
for lst in sockets {
|
||||||
|
self.listen(name.as_ref(), lst);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add new service to server
|
||||||
|
pub fn listen<N: AsRef<str>>(&mut self, name: N, lst: net::TcpListener) -> &mut Self {
|
||||||
|
self.services.push((name.as_ref().to_string(), lst));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Register service configuration function
|
||||||
|
pub fn rt<F>(&mut self, f: F) -> io::Result<()>
|
||||||
|
where
|
||||||
|
F: Fn(&mut ServiceRuntime) + Send + Clone + 'static,
|
||||||
|
{
|
||||||
|
self.rt = Box::new(f);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct ConfiguredService {
|
||||||
|
rt: Box<ServiceRuntimeConfiguration>,
|
||||||
|
names: HashMap<Token, String>,
|
||||||
|
services: HashMap<String, Token>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ConfiguredService {
|
||||||
|
pub(super) fn new(rt: Box<ServiceRuntimeConfiguration>) -> Self {
|
||||||
|
ConfiguredService {
|
||||||
|
rt,
|
||||||
|
names: HashMap::new(),
|
||||||
|
services: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn stream(&mut self, token: Token, name: String) {
|
||||||
|
self.names.insert(token, name.clone());
|
||||||
|
self.services.insert(name, token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl InternalServiceFactory for ConfiguredService {
|
||||||
|
fn name(&self, token: Token) -> &str {
|
||||||
|
&self.names[&token]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clone_factory(&self) -> Box<InternalServiceFactory> {
|
||||||
|
Box::new(Self {
|
||||||
|
rt: self.rt.clone(),
|
||||||
|
names: self.names.clone(),
|
||||||
|
services: self.services.clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
|
||||||
|
// configure services
|
||||||
|
let mut rt = ServiceRuntime::new(self.services.clone());
|
||||||
|
self.rt.configure(&mut rt);
|
||||||
|
rt.validate();
|
||||||
|
|
||||||
|
// construct services
|
||||||
|
let mut fut = Vec::new();
|
||||||
|
for (token, ns) in rt.services {
|
||||||
|
fut.push(ns.new_service().map(move |service| (token, service)));
|
||||||
|
}
|
||||||
|
|
||||||
|
Box::new(join_all(fut).map_err(|e| {
|
||||||
|
error!("Can not construct service: {:?}", e);
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) trait ServiceRuntimeConfiguration: Send {
|
||||||
|
fn clone(&self) -> Box<ServiceRuntimeConfiguration>;
|
||||||
|
|
||||||
|
fn configure(&self, rt: &mut ServiceRuntime);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F> ServiceRuntimeConfiguration for F
|
||||||
|
where
|
||||||
|
F: Fn(&mut ServiceRuntime) + Send + Clone + 'static,
|
||||||
|
{
|
||||||
|
fn clone(&self) -> Box<ServiceRuntimeConfiguration> {
|
||||||
|
Box::new(self.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure(&self, rt: &mut ServiceRuntime) {
|
||||||
|
(self)(rt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn not_configured(_: &mut ServiceRuntime) {
|
||||||
|
error!("Service is not configured");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ServiceRuntime {
|
||||||
|
names: HashMap<String, Token>,
|
||||||
|
services: HashMap<Token, BoxedNewService>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ServiceRuntime {
|
||||||
|
fn new(names: HashMap<String, Token>) -> Self {
|
||||||
|
ServiceRuntime {
|
||||||
|
names,
|
||||||
|
services: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate(&self) {
|
||||||
|
for (name, token) in &self.names {
|
||||||
|
if !self.services.contains_key(&token) {
|
||||||
|
error!("Service {:?} is not configured", name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn service<T, F>(&mut self, name: &str, service: F)
|
||||||
|
where
|
||||||
|
F: IntoNewService<T, TcpStream>,
|
||||||
|
T: NewService<TcpStream, Response = ()> + 'static,
|
||||||
|
T::Future: 'static,
|
||||||
|
T::Service: 'static,
|
||||||
|
T::InitError: fmt::Debug,
|
||||||
|
{
|
||||||
|
// let name = name.to_owned();
|
||||||
|
if let Some(token) = self.names.get(name) {
|
||||||
|
self.services.insert(
|
||||||
|
token.clone(),
|
||||||
|
Box::new(ServiceFactory {
|
||||||
|
inner: service.into_new_service(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
panic!("Unknown service: {:?}", name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type BoxedNewService = Box<
|
||||||
|
NewService<
|
||||||
|
(Option<CounterGuard>, ServerMessage),
|
||||||
|
Response = (),
|
||||||
|
Error = (),
|
||||||
|
InitError = (),
|
||||||
|
Service = BoxedServerService,
|
||||||
|
Future = Box<Future<Item = BoxedServerService, Error = ()>>,
|
||||||
|
>,
|
||||||
|
>;
|
||||||
|
|
||||||
|
struct ServiceFactory<T> {
|
||||||
|
inner: T,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> NewService<(Option<CounterGuard>, ServerMessage)> for ServiceFactory<T>
|
||||||
|
where
|
||||||
|
T: NewService<TcpStream, Response = ()>,
|
||||||
|
T::Future: 'static,
|
||||||
|
T::Service: 'static,
|
||||||
|
T::Error: 'static,
|
||||||
|
T::InitError: fmt::Debug + 'static,
|
||||||
|
{
|
||||||
|
type Response = ();
|
||||||
|
type Error = ();
|
||||||
|
type InitError = ();
|
||||||
|
type Service = BoxedServerService;
|
||||||
|
type Future = Box<Future<Item = BoxedServerService, Error = ()>>;
|
||||||
|
|
||||||
|
fn new_service(&self) -> Self::Future {
|
||||||
|
Box::new(self.inner.new_service().map_err(|_| ()).map(|s| {
|
||||||
|
let service: BoxedServerService = Box::new(StreamService::new(s));
|
||||||
|
service
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
@@ -3,10 +3,12 @@
|
|||||||
use actix::Message;
|
use actix::Message;
|
||||||
|
|
||||||
mod accept;
|
mod accept;
|
||||||
|
mod config;
|
||||||
mod server;
|
mod server;
|
||||||
mod services;
|
mod services;
|
||||||
mod worker;
|
mod worker;
|
||||||
|
|
||||||
|
pub use self::config::{ServiceConfig, ServiceRuntime};
|
||||||
pub use self::server::Server;
|
pub use self::server::Server;
|
||||||
pub use self::services::{ServerMessage, ServiceFactory, StreamServiceFactory};
|
pub use self::services::{ServerMessage, ServiceFactory, StreamServiceFactory};
|
||||||
|
|
||||||
@@ -34,5 +36,13 @@ impl Message for StopServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Socket id token
|
/// Socket id token
|
||||||
#[derive(Clone, Copy, Debug)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
pub(crate) struct Token(usize);
|
pub(crate) struct Token(usize);
|
||||||
|
|
||||||
|
impl Token {
|
||||||
|
pub(crate) fn next(&mut self) -> Token {
|
||||||
|
let token = Token(self.0 + 1);
|
||||||
|
self.0 += 1;
|
||||||
|
token
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@@ -3,6 +3,7 @@ use std::{io, mem, net};
|
|||||||
|
|
||||||
use futures::sync::{mpsc, mpsc::unbounded};
|
use futures::sync::{mpsc, mpsc::unbounded};
|
||||||
use futures::{Future, Sink, Stream};
|
use futures::{Future, Sink, Stream};
|
||||||
|
use log::{error, info};
|
||||||
use net2::TcpBuilder;
|
use net2::TcpBuilder;
|
||||||
use num_cpus;
|
use num_cpus;
|
||||||
|
|
||||||
@@ -12,6 +13,7 @@ use actix::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use super::accept::{AcceptLoop, AcceptNotify, Command};
|
use super::accept::{AcceptLoop, AcceptNotify, Command};
|
||||||
|
use super::config::{ConfiguredService, ServiceConfig};
|
||||||
use super::services::{InternalServiceFactory, StreamNewService, StreamServiceFactory};
|
use super::services::{InternalServiceFactory, StreamNewService, StreamServiceFactory};
|
||||||
use super::services::{ServiceFactory, ServiceNewService};
|
use super::services::{ServiceFactory, ServiceNewService};
|
||||||
use super::worker::{self, Worker, WorkerAvailability, WorkerClient};
|
use super::worker::{self, Worker, WorkerAvailability, WorkerClient};
|
||||||
@@ -24,6 +26,7 @@ pub(crate) enum ServerCommand {
|
|||||||
/// Server
|
/// Server
|
||||||
pub struct Server {
|
pub struct Server {
|
||||||
threads: usize,
|
threads: usize,
|
||||||
|
token: Token,
|
||||||
workers: Vec<(usize, WorkerClient)>,
|
workers: Vec<(usize, WorkerClient)>,
|
||||||
services: Vec<Box<InternalServiceFactory>>,
|
services: Vec<Box<InternalServiceFactory>>,
|
||||||
sockets: Vec<(Token, net::TcpListener)>,
|
sockets: Vec<(Token, net::TcpListener)>,
|
||||||
@@ -45,6 +48,7 @@ impl Server {
|
|||||||
pub fn new() -> Server {
|
pub fn new() -> Server {
|
||||||
Server {
|
Server {
|
||||||
threads: num_cpus::get(),
|
threads: num_cpus::get(),
|
||||||
|
token: Token(0),
|
||||||
workers: Vec::new(),
|
workers: Vec::new(),
|
||||||
services: Vec::new(),
|
services: Vec::new(),
|
||||||
sockets: Vec::new(),
|
sockets: Vec::new(),
|
||||||
@@ -113,12 +117,24 @@ impl Server {
|
|||||||
/// process
|
/// process
|
||||||
///
|
///
|
||||||
/// This function is useful for moving parts of configuration to a
|
/// This function is useful for moving parts of configuration to a
|
||||||
/// different module or event library.
|
/// different module or even library.
|
||||||
pub fn configure<F>(self, cfg: F) -> Server
|
pub fn configure<F>(mut self, f: F) -> io::Result<Server>
|
||||||
where
|
where
|
||||||
F: Fn(Server) -> Server,
|
F: Fn(&mut ServiceConfig) -> io::Result<()>,
|
||||||
{
|
{
|
||||||
cfg(self)
|
let mut cfg = ServiceConfig::new();
|
||||||
|
|
||||||
|
f(&mut cfg)?;
|
||||||
|
|
||||||
|
let mut srv = ConfiguredService::new(cfg.rt);
|
||||||
|
for (name, lst) in cfg.services {
|
||||||
|
let token = self.token.next();
|
||||||
|
srv.stream(token, name);
|
||||||
|
self.sockets.push((token, lst));
|
||||||
|
}
|
||||||
|
self.services.push(Box::new(srv));
|
||||||
|
|
||||||
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add new service to server
|
/// Add new service to server
|
||||||
@@ -129,36 +145,53 @@ impl Server {
|
|||||||
{
|
{
|
||||||
let sockets = bind_addr(addr)?;
|
let sockets = bind_addr(addr)?;
|
||||||
|
|
||||||
|
let token = self.token.next();
|
||||||
|
self.services.push(StreamNewService::create(
|
||||||
|
name.as_ref().to_string(),
|
||||||
|
token,
|
||||||
|
factory,
|
||||||
|
));
|
||||||
|
|
||||||
for lst in sockets {
|
for lst in sockets {
|
||||||
self = self.listen(name.as_ref(), lst, factory.clone())
|
self.sockets.push((token, lst));
|
||||||
}
|
}
|
||||||
Ok(self)
|
Ok(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add new service to server
|
/// Add new service to server
|
||||||
pub fn listen<F, N: AsRef<str>>(
|
pub fn listen<F, N: AsRef<str>>(
|
||||||
mut self, name: N, lst: net::TcpListener, factory: F,
|
mut self,
|
||||||
|
name: N,
|
||||||
|
lst: net::TcpListener,
|
||||||
|
factory: F,
|
||||||
) -> Self
|
) -> Self
|
||||||
where
|
where
|
||||||
F: StreamServiceFactory,
|
F: StreamServiceFactory,
|
||||||
{
|
{
|
||||||
let token = Token(self.services.len());
|
let token = self.token.next();
|
||||||
self.services
|
self.services.push(StreamNewService::create(
|
||||||
.push(StreamNewService::create(name.as_ref().to_string(), factory));
|
name.as_ref().to_string(),
|
||||||
|
token,
|
||||||
|
factory,
|
||||||
|
));
|
||||||
self.sockets.push((token, lst));
|
self.sockets.push((token, lst));
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add new service to server
|
/// Add new service to server
|
||||||
pub fn listen2<F, N: AsRef<str>>(
|
pub fn listen2<F, N: AsRef<str>>(
|
||||||
mut self, name: N, lst: net::TcpListener, factory: F,
|
mut self,
|
||||||
|
name: N,
|
||||||
|
lst: net::TcpListener,
|
||||||
|
factory: F,
|
||||||
) -> Self
|
) -> Self
|
||||||
where
|
where
|
||||||
F: ServiceFactory,
|
F: ServiceFactory,
|
||||||
{
|
{
|
||||||
let token = Token(self.services.len());
|
let token = self.token.next();
|
||||||
self.services.push(ServiceNewService::create(
|
self.services.push(ServiceNewService::create(
|
||||||
name.as_ref().to_string(),
|
name.as_ref().to_string(),
|
||||||
|
token,
|
||||||
factory,
|
factory,
|
||||||
));
|
));
|
||||||
self.sockets.push((token, lst));
|
self.sockets.push((token, lst));
|
||||||
@@ -243,15 +276,16 @@ impl Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn start_worker(&self, idx: usize, notify: AcceptNotify) -> WorkerClient {
|
fn start_worker(&self, idx: usize, notify: AcceptNotify) -> WorkerClient {
|
||||||
let (tx, rx) = unbounded();
|
let (tx1, rx1) = unbounded();
|
||||||
|
let (tx2, rx2) = unbounded();
|
||||||
let timeout = self.shutdown_timeout;
|
let timeout = self.shutdown_timeout;
|
||||||
let avail = WorkerAvailability::new(notify);
|
let avail = WorkerAvailability::new(notify);
|
||||||
let worker = WorkerClient::new(idx, tx, avail.clone());
|
let worker = WorkerClient::new(idx, tx1, tx2, avail.clone());
|
||||||
let services: Vec<Box<InternalServiceFactory>> =
|
let services: Vec<Box<InternalServiceFactory>> =
|
||||||
self.services.iter().map(|v| v.clone_factory()).collect();
|
self.services.iter().map(|v| v.clone_factory()).collect();
|
||||||
|
|
||||||
Arbiter::new(format!("actix-net-worker-{}", idx)).do_send(Execute::new(move || {
|
Arbiter::new(format!("actix-net-worker-{}", idx)).do_send(Execute::new(move || {
|
||||||
Worker::start(rx, services, avail, timeout.clone());
|
Worker::start(rx1, rx2, services, avail, timeout);
|
||||||
Ok::<_, ()>(())
|
Ok::<_, ()>(())
|
||||||
}));
|
}));
|
||||||
|
|
||||||
@@ -343,7 +377,7 @@ impl Handler<StopServer> for Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !self.workers.is_empty() {
|
if !self.workers.is_empty() {
|
||||||
Response::async(rx.into_future().map(|_| ()).map_err(|_| ()))
|
Response::r#async(rx.into_future().map(|_| ()).map_err(|_| ()))
|
||||||
} else {
|
} else {
|
||||||
// we need to stop system if server was spawned
|
// we need to stop system if server was spawned
|
||||||
if self.exit {
|
if self.exit {
|
||||||
@@ -395,7 +429,7 @@ impl StreamHandler<ServerCommand, ()> for Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn bind_addr<S: net::ToSocketAddrs>(addr: S) -> io::Result<Vec<net::TcpListener>> {
|
pub(super) fn bind_addr<S: net::ToSocketAddrs>(addr: S) -> io::Result<Vec<net::TcpListener>> {
|
||||||
let mut err = None;
|
let mut err = None;
|
||||||
let mut succ = false;
|
let mut succ = false;
|
||||||
let mut sockets = Vec::new();
|
let mut sockets = Vec::new();
|
||||||
|
@@ -3,12 +3,14 @@ use std::time::Duration;
|
|||||||
|
|
||||||
use futures::future::{err, ok, FutureResult};
|
use futures::future::{err, ok, FutureResult};
|
||||||
use futures::{Future, Poll};
|
use futures::{Future, Poll};
|
||||||
|
use log::error;
|
||||||
use tokio_current_thread::spawn;
|
use tokio_current_thread::spawn;
|
||||||
use tokio_reactor::Handle;
|
use tokio_reactor::Handle;
|
||||||
use tokio_tcp::TcpStream;
|
use tokio_tcp::TcpStream;
|
||||||
|
|
||||||
use counter::CounterGuard;
|
use super::Token;
|
||||||
use service::{NewService, Service};
|
use crate::counter::CounterGuard;
|
||||||
|
use crate::service::{NewService, Service};
|
||||||
|
|
||||||
/// Server message
|
/// Server message
|
||||||
pub enum ServerMessage {
|
pub enum ServerMessage {
|
||||||
@@ -21,28 +23,28 @@ pub enum ServerMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub trait StreamServiceFactory: Send + Clone + 'static {
|
pub trait StreamServiceFactory: Send + Clone + 'static {
|
||||||
type NewService: NewService<Request = TcpStream, Response = ()>;
|
type NewService: NewService<TcpStream, Response = ()>;
|
||||||
|
|
||||||
fn create(&self) -> Self::NewService;
|
fn create(&self) -> Self::NewService;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait ServiceFactory: Send + Clone + 'static {
|
pub trait ServiceFactory: Send + Clone + 'static {
|
||||||
type NewService: NewService<Request = ServerMessage, Response = ()>;
|
type NewService: NewService<ServerMessage, Response = ()>;
|
||||||
|
|
||||||
fn create(&self) -> Self::NewService;
|
fn create(&self) -> Self::NewService;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) trait InternalServiceFactory: Send {
|
pub(crate) trait InternalServiceFactory: Send {
|
||||||
fn name(&self) -> &str;
|
fn name(&self, token: Token) -> &str;
|
||||||
|
|
||||||
fn clone_factory(&self) -> Box<InternalServiceFactory>;
|
fn clone_factory(&self) -> Box<InternalServiceFactory>;
|
||||||
|
|
||||||
fn create(&self) -> Box<Future<Item = BoxedServerService, Error = ()>>;
|
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) type BoxedServerService = Box<
|
pub(crate) type BoxedServerService = Box<
|
||||||
Service<
|
Service<
|
||||||
Request = (Option<CounterGuard>, ServerMessage),
|
(Option<CounterGuard>, ServerMessage),
|
||||||
Response = (),
|
Response = (),
|
||||||
Error = (),
|
Error = (),
|
||||||
Future = FutureResult<(), ()>,
|
Future = FutureResult<(), ()>,
|
||||||
@@ -54,18 +56,17 @@ pub(crate) struct StreamService<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<T> StreamService<T> {
|
impl<T> StreamService<T> {
|
||||||
fn new(service: T) -> Self {
|
pub(crate) fn new(service: T) -> Self {
|
||||||
StreamService { service }
|
StreamService { service }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Service for StreamService<T>
|
impl<T> Service<(Option<CounterGuard>, ServerMessage)> for StreamService<T>
|
||||||
where
|
where
|
||||||
T: Service<Request = TcpStream, Response = ()>,
|
T: Service<TcpStream, Response = ()>,
|
||||||
T::Future: 'static,
|
T::Future: 'static,
|
||||||
T::Error: 'static,
|
T::Error: 'static,
|
||||||
{
|
{
|
||||||
type Request = (Option<CounterGuard>, ServerMessage);
|
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type Future = FutureResult<(), ()>;
|
type Future = FutureResult<(), ()>;
|
||||||
@@ -106,13 +107,12 @@ impl<T> ServerService<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Service for ServerService<T>
|
impl<T> Service<(Option<CounterGuard>, ServerMessage)> for ServerService<T>
|
||||||
where
|
where
|
||||||
T: Service<Request = ServerMessage, Response = ()>,
|
T: Service<ServerMessage, Response = ()>,
|
||||||
T::Future: 'static,
|
T::Future: 'static,
|
||||||
T::Error: 'static,
|
T::Error: 'static,
|
||||||
{
|
{
|
||||||
type Request = (Option<CounterGuard>, ServerMessage);
|
|
||||||
type Response = ();
|
type Response = ();
|
||||||
type Error = ();
|
type Error = ();
|
||||||
type Future = FutureResult<(), ()>;
|
type Future = FutureResult<(), ()>;
|
||||||
@@ -133,14 +133,15 @@ where
|
|||||||
pub(crate) struct ServiceNewService<F: ServiceFactory> {
|
pub(crate) struct ServiceNewService<F: ServiceFactory> {
|
||||||
name: String,
|
name: String,
|
||||||
inner: F,
|
inner: F,
|
||||||
|
token: Token,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F> ServiceNewService<F>
|
impl<F> ServiceNewService<F>
|
||||||
where
|
where
|
||||||
F: ServiceFactory,
|
F: ServiceFactory,
|
||||||
{
|
{
|
||||||
pub(crate) fn create(name: String, inner: F) -> Box<InternalServiceFactory> {
|
pub(crate) fn create(name: String, token: Token, inner: F) -> Box<InternalServiceFactory> {
|
||||||
Box::new(Self { name, inner })
|
Box::new(Self { name, inner, token })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,7 +149,7 @@ impl<F> InternalServiceFactory for ServiceNewService<F>
|
|||||||
where
|
where
|
||||||
F: ServiceFactory,
|
F: ServiceFactory,
|
||||||
{
|
{
|
||||||
fn name(&self) -> &str {
|
fn name(&self, _: Token) -> &str {
|
||||||
&self.name
|
&self.name
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,10 +157,12 @@ where
|
|||||||
Box::new(Self {
|
Box::new(Self {
|
||||||
name: self.name.clone(),
|
name: self.name.clone(),
|
||||||
inner: self.inner.clone(),
|
inner: self.inner.clone(),
|
||||||
|
token: self.token,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create(&self) -> Box<Future<Item = BoxedServerService, Error = ()>> {
|
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
|
||||||
|
let token = self.token;
|
||||||
Box::new(
|
Box::new(
|
||||||
self.inner
|
self.inner
|
||||||
.create()
|
.create()
|
||||||
@@ -167,7 +170,7 @@ where
|
|||||||
.map_err(|_| ())
|
.map_err(|_| ())
|
||||||
.map(move |inner| {
|
.map(move |inner| {
|
||||||
let service: BoxedServerService = Box::new(ServerService::new(inner));
|
let service: BoxedServerService = Box::new(ServerService::new(inner));
|
||||||
service
|
vec![(token, service)]
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -176,14 +179,15 @@ where
|
|||||||
pub(crate) struct StreamNewService<F: StreamServiceFactory> {
|
pub(crate) struct StreamNewService<F: StreamServiceFactory> {
|
||||||
name: String,
|
name: String,
|
||||||
inner: F,
|
inner: F,
|
||||||
|
token: Token,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<F> StreamNewService<F>
|
impl<F> StreamNewService<F>
|
||||||
where
|
where
|
||||||
F: StreamServiceFactory,
|
F: StreamServiceFactory,
|
||||||
{
|
{
|
||||||
pub(crate) fn create(name: String, inner: F) -> Box<InternalServiceFactory> {
|
pub(crate) fn create(name: String, token: Token, inner: F) -> Box<InternalServiceFactory> {
|
||||||
Box::new(Self { name, inner })
|
Box::new(Self { name, token, inner })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,7 +195,7 @@ impl<F> InternalServiceFactory for StreamNewService<F>
|
|||||||
where
|
where
|
||||||
F: StreamServiceFactory,
|
F: StreamServiceFactory,
|
||||||
{
|
{
|
||||||
fn name(&self) -> &str {
|
fn name(&self, _: Token) -> &str {
|
||||||
&self.name
|
&self.name
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -199,10 +203,12 @@ where
|
|||||||
Box::new(Self {
|
Box::new(Self {
|
||||||
name: self.name.clone(),
|
name: self.name.clone(),
|
||||||
inner: self.inner.clone(),
|
inner: self.inner.clone(),
|
||||||
|
token: self.token,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create(&self) -> Box<Future<Item = BoxedServerService, Error = ()>> {
|
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
|
||||||
|
let token = self.token;
|
||||||
Box::new(
|
Box::new(
|
||||||
self.inner
|
self.inner
|
||||||
.create()
|
.create()
|
||||||
@@ -210,22 +216,22 @@ where
|
|||||||
.map_err(|_| ())
|
.map_err(|_| ())
|
||||||
.map(move |inner| {
|
.map(move |inner| {
|
||||||
let service: BoxedServerService = Box::new(StreamService::new(inner));
|
let service: BoxedServerService = Box::new(StreamService::new(inner));
|
||||||
service
|
vec![(token, service)]
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl InternalServiceFactory for Box<InternalServiceFactory> {
|
impl InternalServiceFactory for Box<InternalServiceFactory> {
|
||||||
fn name(&self) -> &str {
|
fn name(&self, token: Token) -> &str {
|
||||||
self.as_ref().name()
|
self.as_ref().name(token)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn clone_factory(&self) -> Box<InternalServiceFactory> {
|
fn clone_factory(&self) -> Box<InternalServiceFactory> {
|
||||||
self.as_ref().clone_factory()
|
self.as_ref().clone_factory()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create(&self) -> Box<Future<Item = BoxedServerService, Error = ()>> {
|
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
|
||||||
self.as_ref().create()
|
self.as_ref().create()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -233,7 +239,7 @@ impl InternalServiceFactory for Box<InternalServiceFactory> {
|
|||||||
impl<F, T> ServiceFactory for F
|
impl<F, T> ServiceFactory for F
|
||||||
where
|
where
|
||||||
F: Fn() -> T + Send + Clone + 'static,
|
F: Fn() -> T + Send + Clone + 'static,
|
||||||
T: NewService<Request = ServerMessage, Response = ()>,
|
T: NewService<ServerMessage, Response = ()>,
|
||||||
{
|
{
|
||||||
type NewService = T;
|
type NewService = T;
|
||||||
|
|
||||||
@@ -245,7 +251,7 @@ where
|
|||||||
impl<F, T> StreamServiceFactory for F
|
impl<F, T> StreamServiceFactory for F
|
||||||
where
|
where
|
||||||
F: Fn() -> T + Send + Clone + 'static,
|
F: Fn() -> T + Send + Clone + 'static,
|
||||||
T: NewService<Request = TcpStream, Response = ()>,
|
T: NewService<TcpStream, Response = ()>,
|
||||||
{
|
{
|
||||||
type NewService = T;
|
type NewService = T;
|
||||||
|
|
||||||
|
@@ -5,6 +5,7 @@ use std::{mem, net, time};
|
|||||||
use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender};
|
use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender};
|
||||||
use futures::sync::oneshot;
|
use futures::sync::oneshot;
|
||||||
use futures::{future, Async, Future, Poll, Stream};
|
use futures::{future, Async, Future, Poll, Stream};
|
||||||
|
use log::{error, info, trace};
|
||||||
use tokio_current_thread::spawn;
|
use tokio_current_thread::spawn;
|
||||||
use tokio_timer::{sleep, Delay};
|
use tokio_timer::{sleep, Delay};
|
||||||
|
|
||||||
@@ -14,19 +15,20 @@ use actix::{Arbiter, Message};
|
|||||||
use super::accept::AcceptNotify;
|
use super::accept::AcceptNotify;
|
||||||
use super::services::{BoxedServerService, InternalServiceFactory, ServerMessage};
|
use super::services::{BoxedServerService, InternalServiceFactory, ServerMessage};
|
||||||
use super::Token;
|
use super::Token;
|
||||||
use counter::Counter;
|
use crate::counter::Counter;
|
||||||
|
|
||||||
|
pub(crate) struct WorkerCommand(Conn);
|
||||||
|
|
||||||
pub(crate) enum WorkerCommand {
|
|
||||||
Message(Conn),
|
|
||||||
/// Stop worker message. Returns `true` on successful shutdown
|
/// Stop worker message. Returns `true` on successful shutdown
|
||||||
/// and `false` if some connections still alive.
|
/// and `false` if some connections still alive.
|
||||||
Stop(bool, oneshot::Sender<bool>),
|
pub(crate) struct StopCommand {
|
||||||
|
graceful: bool,
|
||||||
|
result: oneshot::Sender<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Message)]
|
#[derive(Debug, Message)]
|
||||||
pub(crate) struct Conn {
|
pub(crate) struct Conn {
|
||||||
pub io: net::TcpStream,
|
pub io: net::TcpStream,
|
||||||
pub handler: Token,
|
|
||||||
pub token: Token,
|
pub token: Token,
|
||||||
pub peer: Option<net::SocketAddr>,
|
pub peer: Option<net::SocketAddr>,
|
||||||
}
|
}
|
||||||
@@ -55,24 +57,30 @@ thread_local! {
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub(crate) struct WorkerClient {
|
pub(crate) struct WorkerClient {
|
||||||
pub idx: usize,
|
pub idx: usize,
|
||||||
tx: UnboundedSender<WorkerCommand>,
|
tx1: UnboundedSender<WorkerCommand>,
|
||||||
|
tx2: UnboundedSender<StopCommand>,
|
||||||
avail: WorkerAvailability,
|
avail: WorkerAvailability,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WorkerClient {
|
impl WorkerClient {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
idx: usize, tx: UnboundedSender<WorkerCommand>, avail: WorkerAvailability,
|
idx: usize,
|
||||||
|
tx1: UnboundedSender<WorkerCommand>,
|
||||||
|
tx2: UnboundedSender<StopCommand>,
|
||||||
|
avail: WorkerAvailability,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
WorkerClient { idx, tx, avail }
|
WorkerClient {
|
||||||
|
idx,
|
||||||
|
tx1,
|
||||||
|
tx2,
|
||||||
|
avail,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn send(&self, msg: Conn) -> Result<(), Conn> {
|
pub fn send(&self, msg: Conn) -> Result<(), Conn> {
|
||||||
self.tx
|
self.tx1
|
||||||
.unbounded_send(WorkerCommand::Message(msg))
|
.unbounded_send(WorkerCommand(msg))
|
||||||
.map_err(|e| match e.into_inner() {
|
.map_err(|msg| msg.into_inner().0)
|
||||||
WorkerCommand::Message(msg) => msg,
|
|
||||||
_ => panic!(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn available(&self) -> bool {
|
pub fn available(&self) -> bool {
|
||||||
@@ -80,8 +88,8 @@ impl WorkerClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn stop(&self, graceful: bool) -> oneshot::Receiver<bool> {
|
pub fn stop(&self, graceful: bool) -> oneshot::Receiver<bool> {
|
||||||
let (tx, rx) = oneshot::channel();
|
let (result, rx) = oneshot::channel();
|
||||||
let _ = self.tx.unbounded_send(WorkerCommand::Stop(graceful, tx));
|
let _ = self.tx2.unbounded_send(StopCommand { graceful, result });
|
||||||
rx
|
rx
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -118,7 +126,8 @@ impl WorkerAvailability {
|
|||||||
/// processing.
|
/// processing.
|
||||||
pub(crate) struct Worker {
|
pub(crate) struct Worker {
|
||||||
rx: UnboundedReceiver<WorkerCommand>,
|
rx: UnboundedReceiver<WorkerCommand>,
|
||||||
services: Vec<BoxedServerService>,
|
rx2: UnboundedReceiver<StopCommand>,
|
||||||
|
services: Vec<Option<(usize, BoxedServerService)>>,
|
||||||
availability: WorkerAvailability,
|
availability: WorkerAvailability,
|
||||||
conns: Counter,
|
conns: Counter,
|
||||||
factories: Vec<Box<InternalServiceFactory>>,
|
factories: Vec<Box<InternalServiceFactory>>,
|
||||||
@@ -128,12 +137,16 @@ pub(crate) struct Worker {
|
|||||||
|
|
||||||
impl Worker {
|
impl Worker {
|
||||||
pub(crate) fn start(
|
pub(crate) fn start(
|
||||||
rx: UnboundedReceiver<WorkerCommand>, factories: Vec<Box<InternalServiceFactory>>,
|
rx: UnboundedReceiver<WorkerCommand>,
|
||||||
availability: WorkerAvailability, shutdown_timeout: time::Duration,
|
rx2: UnboundedReceiver<StopCommand>,
|
||||||
|
factories: Vec<Box<InternalServiceFactory>>,
|
||||||
|
availability: WorkerAvailability,
|
||||||
|
shutdown_timeout: time::Duration,
|
||||||
) {
|
) {
|
||||||
availability.set(false);
|
availability.set(false);
|
||||||
let mut wrk = MAX_CONNS_COUNTER.with(|conns| Worker {
|
let mut wrk = MAX_CONNS_COUNTER.with(|conns| Worker {
|
||||||
rx,
|
rx,
|
||||||
|
rx2,
|
||||||
availability,
|
availability,
|
||||||
factories,
|
factories,
|
||||||
shutdown_timeout,
|
shutdown_timeout,
|
||||||
@@ -143,16 +156,28 @@ impl Worker {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let mut fut = Vec::new();
|
let mut fut = Vec::new();
|
||||||
for factory in &wrk.factories {
|
for (idx, factory) in wrk.factories.iter().enumerate() {
|
||||||
fut.push(factory.create());
|
fut.push(factory.create().map(move |res| {
|
||||||
|
res.into_iter()
|
||||||
|
.map(|(t, s)| (idx, t, s))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
spawn(
|
spawn(
|
||||||
future::join_all(fut)
|
future::join_all(fut)
|
||||||
.map_err(|e| {
|
.map_err(|e| {
|
||||||
error!("Can not start worker: {:?}", e);
|
error!("Can not start worker: {:?}", e);
|
||||||
Arbiter::current().do_send(StopArbiter(0));
|
Arbiter::current().do_send(StopArbiter(0));
|
||||||
}).and_then(move |services| {
|
})
|
||||||
wrk.services.extend(services);
|
.and_then(move |services| {
|
||||||
|
for item in services {
|
||||||
|
for (idx, token, service) in item {
|
||||||
|
while token.0 >= wrk.services.len() {
|
||||||
|
wrk.services.push(None);
|
||||||
|
}
|
||||||
|
wrk.services[token.0] = Some((idx, service));
|
||||||
|
}
|
||||||
|
}
|
||||||
wrk
|
wrk
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -161,33 +186,42 @@ impl Worker {
|
|||||||
fn shutdown(&mut self, force: bool) {
|
fn shutdown(&mut self, force: bool) {
|
||||||
if force {
|
if force {
|
||||||
self.services.iter_mut().for_each(|h| {
|
self.services.iter_mut().for_each(|h| {
|
||||||
let _ = h.call((None, ServerMessage::ForceShutdown));
|
if let Some(h) = h {
|
||||||
|
let _ = h.1.call((None, ServerMessage::ForceShutdown));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
let timeout = self.shutdown_timeout;
|
let timeout = self.shutdown_timeout;
|
||||||
self.services.iter_mut().for_each(move |h| {
|
self.services.iter_mut().for_each(move |h| {
|
||||||
let _ = h.call((None, ServerMessage::Shutdown(timeout.clone())));
|
if let Some(h) = h {
|
||||||
|
let _ = h.1.call((None, ServerMessage::Shutdown(timeout)));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_readiness(&mut self, trace: bool) -> Result<bool, usize> {
|
fn check_readiness(&mut self, trace: bool) -> Result<bool, (Token, usize)> {
|
||||||
let mut ready = self.conns.available();
|
let mut ready = self.conns.available();
|
||||||
let mut failed = None;
|
let mut failed = None;
|
||||||
for (idx, service) in self.services.iter_mut().enumerate() {
|
for (token, service) in &mut self.services.iter_mut().enumerate() {
|
||||||
match service.poll_ready() {
|
if let Some(service) = service {
|
||||||
|
match service.1.poll_ready() {
|
||||||
Ok(Async::Ready(_)) => {
|
Ok(Async::Ready(_)) => {
|
||||||
if trace {
|
if trace {
|
||||||
trace!("Service {:?} is available", self.factories[idx].name());
|
trace!(
|
||||||
|
"Service {:?} is available",
|
||||||
|
self.factories[service.0].name(Token(token))
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Async::NotReady) => ready = false,
|
Ok(Async::NotReady) => ready = false,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
error!(
|
error!(
|
||||||
"Service {:?} readiness check returned error, restarting",
|
"Service {:?} readiness check returned error, restarting",
|
||||||
self.factories[idx].name()
|
self.factories[service.0].name(Token(token))
|
||||||
);
|
);
|
||||||
failed = Some(idx);
|
failed = Some((Token(token), service.0));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -203,7 +237,11 @@ enum WorkerState {
|
|||||||
None,
|
None,
|
||||||
Available,
|
Available,
|
||||||
Unavailable(Vec<Conn>),
|
Unavailable(Vec<Conn>),
|
||||||
Restarting(usize, Box<Future<Item = BoxedServerService, Error = ()>>),
|
Restarting(
|
||||||
|
usize,
|
||||||
|
Token,
|
||||||
|
Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>>,
|
||||||
|
),
|
||||||
Shutdown(Delay, Delay, oneshot::Sender<bool>),
|
Shutdown(Delay, Delay, oneshot::Sender<bool>),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -212,6 +250,36 @@ impl Future for Worker {
|
|||||||
type Error = ();
|
type Error = ();
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
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);
|
||||||
|
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(()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let state = mem::replace(&mut self.state, WorkerState::None);
|
let state = mem::replace(&mut self.state, WorkerState::None);
|
||||||
|
|
||||||
match state {
|
match state {
|
||||||
@@ -225,7 +293,10 @@ impl Future for Worker {
|
|||||||
match self.check_readiness(false) {
|
match self.check_readiness(false) {
|
||||||
Ok(true) => {
|
Ok(true) => {
|
||||||
let guard = self.conns.get();
|
let guard = self.conns.get();
|
||||||
let _ = self.services[msg.handler.0]
|
let _ = self.services[msg.token.0]
|
||||||
|
.as_mut()
|
||||||
|
.expect("actix net bug")
|
||||||
|
.1
|
||||||
.call((Some(guard), ServerMessage::Connect(msg.io)));
|
.call((Some(guard), ServerMessage::Connect(msg.io)));
|
||||||
}
|
}
|
||||||
Ok(false) => {
|
Ok(false) => {
|
||||||
@@ -233,13 +304,14 @@ impl Future for Worker {
|
|||||||
self.state = WorkerState::Unavailable(conns);
|
self.state = WorkerState::Unavailable(conns);
|
||||||
return self.poll();
|
return self.poll();
|
||||||
}
|
}
|
||||||
Err(idx) => {
|
Err((token, idx)) => {
|
||||||
trace!(
|
trace!(
|
||||||
"Service {:?} failed, restarting",
|
"Service {:?} failed, restarting",
|
||||||
self.factories[idx].name()
|
self.factories[idx].name(token)
|
||||||
);
|
);
|
||||||
self.state = WorkerState::Restarting(
|
self.state = WorkerState::Restarting(
|
||||||
idx,
|
idx,
|
||||||
|
token,
|
||||||
self.factories[idx].create(),
|
self.factories[idx].create(),
|
||||||
);
|
);
|
||||||
return self.poll();
|
return self.poll();
|
||||||
@@ -253,32 +325,38 @@ impl Future for Worker {
|
|||||||
self.state = WorkerState::Unavailable(conns);
|
self.state = WorkerState::Unavailable(conns);
|
||||||
return Ok(Async::NotReady);
|
return Ok(Async::NotReady);
|
||||||
}
|
}
|
||||||
Err(idx) => {
|
Err((token, idx)) => {
|
||||||
trace!(
|
trace!(
|
||||||
"Service {:?} failed, restarting",
|
"Service {:?} failed, restarting",
|
||||||
self.factories[idx].name()
|
self.factories[idx].name(token)
|
||||||
);
|
);
|
||||||
self.state = WorkerState::Restarting(idx, self.factories[idx].create());
|
self.state =
|
||||||
|
WorkerState::Restarting(idx, token, self.factories[idx].create());
|
||||||
return self.poll();
|
return self.poll();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
WorkerState::Restarting(idx, mut fut) => {
|
WorkerState::Restarting(idx, token, mut fut) => {
|
||||||
match fut.poll() {
|
match fut.poll() {
|
||||||
Ok(Async::Ready(service)) => {
|
Ok(Async::Ready(item)) => {
|
||||||
|
for (token, service) in item {
|
||||||
trace!(
|
trace!(
|
||||||
"Service {:?} has been restarted",
|
"Service {:?} has been restarted",
|
||||||
self.factories[idx].name()
|
self.factories[idx].name(token)
|
||||||
);
|
);
|
||||||
self.services[idx] = service;
|
self.services[token.0] = Some((idx, service));
|
||||||
self.state = WorkerState::Unavailable(Vec::new());
|
self.state = WorkerState::Unavailable(Vec::new());
|
||||||
}
|
}
|
||||||
|
}
|
||||||
Ok(Async::NotReady) => {
|
Ok(Async::NotReady) => {
|
||||||
self.state = WorkerState::Restarting(idx, fut);
|
self.state = WorkerState::Restarting(idx, token, fut);
|
||||||
return Ok(Async::NotReady);
|
return Ok(Async::NotReady);
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
panic!("Can not restart {:?} service", self.factories[idx].name());
|
panic!(
|
||||||
|
"Can not restart {:?} service",
|
||||||
|
self.factories[idx].name(token)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return self.poll();
|
return self.poll();
|
||||||
@@ -317,11 +395,14 @@ impl Future for Worker {
|
|||||||
loop {
|
loop {
|
||||||
match self.rx.poll() {
|
match self.rx.poll() {
|
||||||
// handle incoming tcp stream
|
// handle incoming tcp stream
|
||||||
Ok(Async::Ready(Some(WorkerCommand::Message(msg)))) => {
|
Ok(Async::Ready(Some(WorkerCommand(msg)))) => {
|
||||||
match self.check_readiness(false) {
|
match self.check_readiness(false) {
|
||||||
Ok(true) => {
|
Ok(true) => {
|
||||||
let guard = self.conns.get();
|
let guard = self.conns.get();
|
||||||
let _ = self.services[msg.handler.0]
|
let _ = self.services[msg.token.0]
|
||||||
|
.as_mut()
|
||||||
|
.expect("actix net bug")
|
||||||
|
.1
|
||||||
.call((Some(guard), ServerMessage::Connect(msg.io)));
|
.call((Some(guard), ServerMessage::Connect(msg.io)));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -330,49 +411,21 @@ impl Future for Worker {
|
|||||||
self.availability.set(false);
|
self.availability.set(false);
|
||||||
self.state = WorkerState::Unavailable(vec![msg]);
|
self.state = WorkerState::Unavailable(vec![msg]);
|
||||||
}
|
}
|
||||||
Err(idx) => {
|
Err((token, idx)) => {
|
||||||
trace!(
|
trace!(
|
||||||
"Service {:?} failed, restarting",
|
"Service {:?} failed, restarting",
|
||||||
self.factories[idx].name()
|
self.factories[idx].name(token)
|
||||||
);
|
);
|
||||||
self.availability.set(false);
|
self.availability.set(false);
|
||||||
self.state = WorkerState::Restarting(
|
self.state = WorkerState::Restarting(
|
||||||
idx,
|
idx,
|
||||||
|
token,
|
||||||
self.factories[idx].create(),
|
self.factories[idx].create(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return self.poll();
|
return self.poll();
|
||||||
}
|
}
|
||||||
// `StopWorker` message handler
|
|
||||||
Ok(Async::Ready(Some(WorkerCommand::Stop(graceful, tx)))) => {
|
|
||||||
self.availability.set(false);
|
|
||||||
let num = num_connections();
|
|
||||||
if num == 0 {
|
|
||||||
info!("Shutting down worker, 0 connections");
|
|
||||||
let _ = tx.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);
|
|
||||||
break Some(WorkerState::Shutdown(
|
|
||||||
sleep(time::Duration::from_secs(1)),
|
|
||||||
sleep(self.shutdown_timeout),
|
|
||||||
tx,
|
|
||||||
));
|
|
||||||
} else {
|
|
||||||
let _ = tx.send(true);
|
|
||||||
return Ok(Async::Ready(()));
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
info!("Force shutdown worker, {} connections", num);
|
|
||||||
self.shutdown(true);
|
|
||||||
let _ = tx.send(false);
|
|
||||||
return Ok(Async::Ready(()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(Async::NotReady) => {
|
Ok(Async::NotReady) => {
|
||||||
self.state = WorkerState::Available;
|
self.state = WorkerState::Available;
|
||||||
return Ok(Async::NotReady);
|
return Ok(Async::NotReady);
|
||||||
@@ -383,7 +436,5 @@ impl Future for Worker {
|
|||||||
}
|
}
|
||||||
WorkerState::None => panic!(),
|
WorkerState::None => panic!(),
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(Async::NotReady)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -6,8 +6,8 @@ use native_tls::{self, Error, HandshakeError, TlsAcceptor};
|
|||||||
use tokio_io::{AsyncRead, AsyncWrite};
|
use tokio_io::{AsyncRead, AsyncWrite};
|
||||||
|
|
||||||
use super::MAX_CONN_COUNTER;
|
use super::MAX_CONN_COUNTER;
|
||||||
use counter::{Counter, CounterGuard};
|
use crate::counter::{Counter, CounterGuard};
|
||||||
use service::{NewService, Service};
|
use crate::service::{NewService, Service};
|
||||||
|
|
||||||
/// Support `SSL` connections via native-tls package
|
/// Support `SSL` connections via native-tls package
|
||||||
///
|
///
|
||||||
@@ -36,8 +36,7 @@ impl<T: AsyncRead + AsyncWrite> Clone for NativeTlsAcceptor<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AsyncRead + AsyncWrite> NewService for NativeTlsAcceptor<T> {
|
impl<T: AsyncRead + AsyncWrite> NewService<T> for NativeTlsAcceptor<T> {
|
||||||
type Request = T;
|
|
||||||
type Response = TlsStream<T>;
|
type Response = TlsStream<T>;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Service = NativeTlsAcceptorService<T>;
|
type Service = NativeTlsAcceptorService<T>;
|
||||||
@@ -61,8 +60,7 @@ pub struct NativeTlsAcceptorService<T> {
|
|||||||
conns: Counter,
|
conns: Counter,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AsyncRead + AsyncWrite> Service for NativeTlsAcceptorService<T> {
|
impl<T: AsyncRead + AsyncWrite> Service<T> for NativeTlsAcceptorService<T> {
|
||||||
type Request = T;
|
|
||||||
type Response = TlsStream<T>;
|
type Response = TlsStream<T>;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = Accept<T>;
|
type Future = Accept<T>;
|
||||||
@@ -75,7 +73,7 @@ impl<T: AsyncRead + AsyncWrite> Service for NativeTlsAcceptorService<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: T) -> Self::Future {
|
||||||
Accept {
|
Accept {
|
||||||
_guard: self.conns.get(),
|
_guard: self.conns.get(),
|
||||||
inner: Some(self.acceptor.accept(req)),
|
inner: Some(self.acceptor.accept(req)),
|
||||||
|
@@ -6,9 +6,9 @@ use tokio_io::{AsyncRead, AsyncWrite};
|
|||||||
use tokio_openssl::{AcceptAsync, ConnectAsync, SslAcceptorExt, SslConnectorExt, SslStream};
|
use tokio_openssl::{AcceptAsync, ConnectAsync, SslAcceptorExt, SslConnectorExt, SslStream};
|
||||||
|
|
||||||
use super::MAX_CONN_COUNTER;
|
use super::MAX_CONN_COUNTER;
|
||||||
use connector::ConnectionInfo;
|
use crate::counter::{Counter, CounterGuard};
|
||||||
use counter::{Counter, CounterGuard};
|
use crate::resolver::RequestHost;
|
||||||
use service::{NewService, Service};
|
use crate::service::{NewService, Service};
|
||||||
|
|
||||||
/// Support `SSL` connections via openssl package
|
/// Support `SSL` connections via openssl package
|
||||||
///
|
///
|
||||||
@@ -37,8 +37,7 @@ impl<T: AsyncRead + AsyncWrite> Clone for OpensslAcceptor<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AsyncRead + AsyncWrite> NewService for OpensslAcceptor<T> {
|
impl<T: AsyncRead + AsyncWrite> NewService<T> for OpensslAcceptor<T> {
|
||||||
type Request = T;
|
|
||||||
type Response = SslStream<T>;
|
type Response = SslStream<T>;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Service = OpensslAcceptorService<T>;
|
type Service = OpensslAcceptorService<T>;
|
||||||
@@ -62,8 +61,7 @@ pub struct OpensslAcceptorService<T> {
|
|||||||
conns: Counter,
|
conns: Counter,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AsyncRead + AsyncWrite> Service for OpensslAcceptorService<T> {
|
impl<T: AsyncRead + AsyncWrite> Service<T> for OpensslAcceptorService<T> {
|
||||||
type Request = T;
|
|
||||||
type Response = SslStream<T>;
|
type Response = SslStream<T>;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = OpensslAcceptorServiceFut<T>;
|
type Future = OpensslAcceptorServiceFut<T>;
|
||||||
@@ -76,7 +74,7 @@ impl<T: AsyncRead + AsyncWrite> Service for OpensslAcceptorService<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: T) -> Self::Future {
|
||||||
OpensslAcceptorServiceFut {
|
OpensslAcceptorServiceFut {
|
||||||
_guard: self.conns.get(),
|
_guard: self.conns.get(),
|
||||||
fut: SslAcceptorExt::accept_async(&self.acceptor, req),
|
fut: SslAcceptorExt::accept_async(&self.acceptor, req),
|
||||||
@@ -102,113 +100,97 @@ impl<T: AsyncRead + AsyncWrite> Future for OpensslAcceptorServiceFut<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Openssl connector factory
|
/// Openssl connector factory
|
||||||
pub struct OpensslConnector<T, Io, E> {
|
pub struct OpensslConnector<R, T, E> {
|
||||||
connector: SslConnector,
|
connector: SslConnector,
|
||||||
t: PhantomData<T>,
|
_t: PhantomData<(R, T, E)>,
|
||||||
io: PhantomData<Io>,
|
|
||||||
_e: PhantomData<E>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, Io, E> OpensslConnector<T, Io, E> {
|
impl<R, T, E> OpensslConnector<R, T, E> {
|
||||||
pub fn new(connector: SslConnector) -> Self {
|
pub fn new(connector: SslConnector) -> Self {
|
||||||
OpensslConnector {
|
OpensslConnector {
|
||||||
connector,
|
connector,
|
||||||
t: PhantomData,
|
_t: PhantomData,
|
||||||
io: PhantomData,
|
|
||||||
_e: PhantomData,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, Io: AsyncRead + AsyncWrite> OpensslConnector<T, Io, ()> {
|
impl<R: RequestHost, T: AsyncRead + AsyncWrite> OpensslConnector<R, T, ()> {
|
||||||
pub fn service(
|
pub fn service(
|
||||||
connector: SslConnector,
|
connector: SslConnector,
|
||||||
) -> impl Service<
|
) -> impl Service<(R, T), Response = (R, SslStream<T>), Error = Error> {
|
||||||
Request = (T, ConnectionInfo, Io),
|
|
||||||
Response = (T, ConnectionInfo, SslStream<Io>),
|
|
||||||
Error = Error,
|
|
||||||
> {
|
|
||||||
OpensslConnectorService {
|
OpensslConnectorService {
|
||||||
connector: connector,
|
connector: connector,
|
||||||
t: PhantomData,
|
_t: PhantomData,
|
||||||
io: PhantomData,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, Io, E> Clone for OpensslConnector<T, Io, E> {
|
impl<R, T, E> Clone for OpensslConnector<R, T, E> {
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
connector: self.connector.clone(),
|
connector: self.connector.clone(),
|
||||||
t: PhantomData,
|
_t: PhantomData,
|
||||||
io: PhantomData,
|
|
||||||
_e: PhantomData,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, Io: AsyncRead + AsyncWrite, E> NewService for OpensslConnector<T, Io, E> {
|
impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService<(R, T)>
|
||||||
type Request = (T, ConnectionInfo, Io);
|
for OpensslConnector<R, T, E>
|
||||||
type Response = (T, ConnectionInfo, SslStream<Io>);
|
{
|
||||||
|
type Response = (R, SslStream<T>);
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Service = OpensslConnectorService<T, Io>;
|
type Service = OpensslConnectorService<R, T>;
|
||||||
type InitError = E;
|
type InitError = E;
|
||||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||||
|
|
||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
ok(OpensslConnectorService {
|
ok(OpensslConnectorService {
|
||||||
connector: self.connector.clone(),
|
connector: self.connector.clone(),
|
||||||
t: PhantomData,
|
_t: PhantomData,
|
||||||
io: PhantomData,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct OpensslConnectorService<T, Io> {
|
pub struct OpensslConnectorService<R, T> {
|
||||||
connector: SslConnector,
|
connector: SslConnector,
|
||||||
t: PhantomData<T>,
|
_t: PhantomData<(R, T)>,
|
||||||
io: PhantomData<Io>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, Io: AsyncRead + AsyncWrite> Service for OpensslConnectorService<T, Io> {
|
impl<R: RequestHost, T: AsyncRead + AsyncWrite> Service<(R, T)>
|
||||||
type Request = (T, ConnectionInfo, Io);
|
for OpensslConnectorService<R, T>
|
||||||
type Response = (T, ConnectionInfo, SslStream<Io>);
|
{
|
||||||
|
type Response = (R, SslStream<T>);
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = ConnectAsyncExt<T, Io>;
|
type Future = ConnectAsyncExt<R, T>;
|
||||||
|
|
||||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, (req, info, stream): Self::Request) -> Self::Future {
|
fn call(&mut self, (req, stream): (R, T)) -> Self::Future {
|
||||||
ConnectAsyncExt {
|
ConnectAsyncExt {
|
||||||
fut: SslConnectorExt::connect_async(&self.connector, &info.host, stream),
|
fut: SslConnectorExt::connect_async(&self.connector, req.host(), stream),
|
||||||
req: Some(req),
|
req: Some(req),
|
||||||
host: Some(info),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct ConnectAsyncExt<T, Io> {
|
pub struct ConnectAsyncExt<R, T> {
|
||||||
fut: ConnectAsync<Io>,
|
req: Option<R>,
|
||||||
req: Option<T>,
|
fut: ConnectAsync<T>,
|
||||||
host: Option<ConnectionInfo>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, Io> Future for ConnectAsyncExt<T, Io>
|
impl<R, T> Future for ConnectAsyncExt<R, T>
|
||||||
where
|
where
|
||||||
Io: AsyncRead + AsyncWrite,
|
R: RequestHost,
|
||||||
|
T: AsyncRead + AsyncWrite,
|
||||||
{
|
{
|
||||||
type Item = (T, ConnectionInfo, SslStream<Io>);
|
type Item = (R, SslStream<T>);
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
match self.fut.poll()? {
|
match self.fut.poll()? {
|
||||||
Async::Ready(stream) => Ok(Async::Ready((
|
Async::Ready(stream) => Ok(Async::Ready((self.req.take().unwrap(), stream))),
|
||||||
self.req.take().unwrap(),
|
|
||||||
self.host.take().unwrap(),
|
|
||||||
stream,
|
|
||||||
))),
|
|
||||||
Async::NotReady => Ok(Async::NotReady),
|
Async::NotReady => Ok(Async::NotReady),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -8,8 +8,8 @@ use tokio_io::{AsyncRead, AsyncWrite};
|
|||||||
use tokio_rustls::{Accept, TlsAcceptor, TlsStream};
|
use tokio_rustls::{Accept, TlsAcceptor, TlsStream};
|
||||||
|
|
||||||
use super::MAX_CONN_COUNTER;
|
use super::MAX_CONN_COUNTER;
|
||||||
use counter::{Counter, CounterGuard};
|
use crate::counter::{Counter, CounterGuard};
|
||||||
use service::{NewService, Service};
|
use crate::service::{NewService, Service};
|
||||||
|
|
||||||
/// Support `SSL` connections via rustls package
|
/// Support `SSL` connections via rustls package
|
||||||
///
|
///
|
||||||
@@ -38,8 +38,7 @@ impl<T> Clone for RustlsAcceptor<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AsyncRead + AsyncWrite> NewService for RustlsAcceptor<T> {
|
impl<T: AsyncRead + AsyncWrite> NewService<T> for RustlsAcceptor<T> {
|
||||||
type Request = T;
|
|
||||||
type Response = TlsStream<T, ServerSession>;
|
type Response = TlsStream<T, ServerSession>;
|
||||||
type Error = io::Error;
|
type Error = io::Error;
|
||||||
type Service = RustlsAcceptorService<T>;
|
type Service = RustlsAcceptorService<T>;
|
||||||
@@ -63,8 +62,7 @@ pub struct RustlsAcceptorService<T> {
|
|||||||
conns: Counter,
|
conns: Counter,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: AsyncRead + AsyncWrite> Service for RustlsAcceptorService<T> {
|
impl<T: AsyncRead + AsyncWrite> Service<T> for RustlsAcceptorService<T> {
|
||||||
type Request = T;
|
|
||||||
type Response = TlsStream<T, ServerSession>;
|
type Response = TlsStream<T, ServerSession>;
|
||||||
type Error = io::Error;
|
type Error = io::Error;
|
||||||
type Future = RustlsAcceptorServiceFut<T>;
|
type Future = RustlsAcceptorServiceFut<T>;
|
||||||
@@ -77,7 +75,7 @@ impl<T: AsyncRead + AsyncWrite> Service for RustlsAcceptorService<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: T) -> Self::Future {
|
||||||
RustlsAcceptorServiceFut {
|
RustlsAcceptorServiceFut {
|
||||||
_guard: self.conns.get(),
|
_guard: self.conns.get(),
|
||||||
fut: self.acceptor.accept(req),
|
fut: self.acceptor.accept(req),
|
||||||
|
@@ -2,7 +2,7 @@ use std::marker::PhantomData;
|
|||||||
|
|
||||||
use futures::unsync::mpsc;
|
use futures::unsync::mpsc;
|
||||||
use futures::{future, Async, Future, Poll, Stream};
|
use futures::{future, Async, Future, Poll, Stream};
|
||||||
use tokio::executor::current_thread::spawn;
|
use tokio_current_thread::spawn;
|
||||||
|
|
||||||
use super::service::{IntoService, NewService, Service};
|
use super::service::{IntoService, NewService, Service};
|
||||||
|
|
||||||
@@ -17,10 +17,13 @@ pub struct StreamDispatcher<S: Stream, T> {
|
|||||||
impl<S, T> StreamDispatcher<S, T>
|
impl<S, T> StreamDispatcher<S, T>
|
||||||
where
|
where
|
||||||
S: Stream,
|
S: Stream,
|
||||||
T: Service<Request = Result<S::Item, S::Error>, Response = (), Error = ()>,
|
T: Service<Result<S::Item, S::Error>, Response = (), Error = ()>,
|
||||||
T::Future: 'static,
|
T::Future: 'static,
|
||||||
{
|
{
|
||||||
pub fn new<F: IntoService<T>>(stream: S, service: F) -> Self {
|
pub fn new<F>(stream: S, service: F) -> Self
|
||||||
|
where
|
||||||
|
F: IntoService<T, Result<S::Item, S::Error>>,
|
||||||
|
{
|
||||||
let (stop_tx, stop_rx) = mpsc::unbounded();
|
let (stop_tx, stop_rx) = mpsc::unbounded();
|
||||||
StreamDispatcher {
|
StreamDispatcher {
|
||||||
stream,
|
stream,
|
||||||
@@ -35,7 +38,7 @@ where
|
|||||||
impl<S, T> Future for StreamDispatcher<S, T>
|
impl<S, T> Future for StreamDispatcher<S, T>
|
||||||
where
|
where
|
||||||
S: Stream,
|
S: Stream,
|
||||||
T: Service<Request = Result<S::Item, S::Error>, Response = (), Error = ()>,
|
T: Service<Result<S::Item, S::Error>, Response = (), Error = ()>,
|
||||||
T::Future: 'static,
|
T::Future: 'static,
|
||||||
{
|
{
|
||||||
type Item = ();
|
type Item = ();
|
||||||
@@ -103,8 +106,19 @@ impl<T> TakeItem<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Stream> NewService for TakeItem<T> {
|
impl<T> Default for TakeItem<T> {
|
||||||
type Request = 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> {
|
||||||
type Response = (Option<T::Item>, T);
|
type Response = (Option<T::Item>, T);
|
||||||
type Error = T::Error;
|
type Error = T::Error;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
@@ -121,8 +135,13 @@ pub struct TakeItemService<T> {
|
|||||||
_t: PhantomData<T>,
|
_t: PhantomData<T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Stream> Service for TakeItemService<T> {
|
impl<T> Clone for TakeItemService<T> {
|
||||||
type Request = T;
|
fn clone(&self) -> TakeItemService<T> {
|
||||||
|
TakeItemService { _t: PhantomData }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Stream> Service<T> for TakeItemService<T> {
|
||||||
type Response = (Option<T::Item>, T);
|
type Response = (Option<T::Item>, T);
|
||||||
type Error = T::Error;
|
type Error = T::Error;
|
||||||
type Future = TakeItemServiceResponse<T>;
|
type Future = TakeItemServiceResponse<T>;
|
||||||
@@ -131,7 +150,7 @@ impl<T: Stream> Service for TakeItemService<T> {
|
|||||||
Ok(Async::Ready(()))
|
Ok(Async::Ready(()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
fn call(&mut self, req: T) -> Self::Future {
|
||||||
TakeItemServiceResponse { stream: Some(req) }
|
TakeItemServiceResponse { stream: Some(req) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -10,7 +10,7 @@ use super::service::{NewService, Service};
|
|||||||
use super::Never;
|
use super::Never;
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct LowResTimer(Cell<Inner>);
|
pub struct LowResTime(Cell<Inner>);
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct Inner {
|
struct Inner {
|
||||||
@@ -27,28 +27,27 @@ impl Inner {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl LowResTimer {
|
impl LowResTime {
|
||||||
pub fn with(resolution: Duration) -> LowResTimer {
|
pub fn with(resolution: Duration) -> LowResTime {
|
||||||
LowResTimer(Cell::new(Inner::new(resolution)))
|
LowResTime(Cell::new(Inner::new(resolution)))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn timer(&self) -> LowResTimerService {
|
pub fn timer(&self) -> LowResTimeService {
|
||||||
LowResTimerService(self.0.clone())
|
LowResTimeService(self.0.clone())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for LowResTimer {
|
impl Default for LowResTime {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
LowResTimer(Cell::new(Inner::new(Duration::from_secs(1))))
|
LowResTime(Cell::new(Inner::new(Duration::from_secs(1))))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NewService for LowResTimer {
|
impl NewService<()> for LowResTime {
|
||||||
type Request = ();
|
|
||||||
type Response = Instant;
|
type Response = Instant;
|
||||||
type Error = Never;
|
type Error = Never;
|
||||||
type InitError = Never;
|
type InitError = Never;
|
||||||
type Service = LowResTimerService;
|
type Service = LowResTimeService;
|
||||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||||
|
|
||||||
fn new_service(&self) -> Self::Future {
|
fn new_service(&self) -> Self::Future {
|
||||||
@@ -57,17 +56,17 @@ impl NewService for LowResTimer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct LowResTimerService(Cell<Inner>);
|
pub struct LowResTimeService(Cell<Inner>);
|
||||||
|
|
||||||
impl LowResTimerService {
|
impl LowResTimeService {
|
||||||
pub fn with(resolution: Duration) -> LowResTimerService {
|
pub fn with(resolution: Duration) -> LowResTimeService {
|
||||||
LowResTimerService(Cell::new(Inner::new(resolution)))
|
LowResTimeService(Cell::new(Inner::new(resolution)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get current time. This function has to be called from
|
/// Get current time. This function has to be called from
|
||||||
/// future's poll method, otherwise it panics.
|
/// future's poll method, otherwise it panics.
|
||||||
pub fn now(&mut self) -> Instant {
|
pub fn now(&self) -> Instant {
|
||||||
let cur = self.0.borrow().current.clone();
|
let cur = self.0.borrow().current;
|
||||||
if let Some(cur) = cur {
|
if let Some(cur) = cur {
|
||||||
cur
|
cur
|
||||||
} else {
|
} else {
|
||||||
@@ -88,8 +87,7 @@ impl LowResTimerService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Service for LowResTimerService {
|
impl Service<()> for LowResTimeService {
|
||||||
type Request = ();
|
|
||||||
type Response = Instant;
|
type Response = Instant;
|
||||||
type Error = Never;
|
type Error = Never;
|
||||||
type Future = FutureResult<Self::Response, Self::Error>;
|
type Future = FutureResult<Self::Response, Self::Error>;
|
159
src/timeout.rs
Normal file
159
src/timeout.rs
Normal file
@@ -0,0 +1,159 @@
|
|||||||
|
//! Service that applies a timeout to requests.
|
||||||
|
//!
|
||||||
|
//! If the response does not complete within the specified timeout, the response
|
||||||
|
//! will be aborted.
|
||||||
|
use std::fmt;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use futures::try_ready;
|
||||||
|
use futures::{Async, Future, Poll};
|
||||||
|
use tokio_timer::{clock, Delay};
|
||||||
|
|
||||||
|
use crate::service::{NewService, Service};
|
||||||
|
|
||||||
|
/// Applies a timeout to requests.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Timeout<T> {
|
||||||
|
inner: T,
|
||||||
|
timeout: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Timeout error
|
||||||
|
pub enum TimeoutError<E> {
|
||||||
|
/// Service error
|
||||||
|
Service(E),
|
||||||
|
/// Service call timeout
|
||||||
|
Timeout,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
TimeoutError::Service(e) => write!(f, "TimeoutError::Service({:?})", e),
|
||||||
|
TimeoutError::Timeout => write!(f, "TimeoutError::Timeout"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Timeout<T> {
|
||||||
|
pub fn new<Request>(timeout: Duration, inner: T) -> Self
|
||||||
|
where
|
||||||
|
T: NewService<Request> + Clone,
|
||||||
|
{
|
||||||
|
Timeout { inner, timeout }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, Request> NewService<Request> for Timeout<T>
|
||||||
|
where
|
||||||
|
T: NewService<Request> + Clone,
|
||||||
|
{
|
||||||
|
type Response = T::Response;
|
||||||
|
type Error = TimeoutError<T::Error>;
|
||||||
|
type InitError = T::InitError;
|
||||||
|
type Service = TimeoutService<T::Service>;
|
||||||
|
type Future = TimeoutFut<T, Request>;
|
||||||
|
|
||||||
|
fn new_service(&self) -> Self::Future {
|
||||||
|
TimeoutFut {
|
||||||
|
fut: self.inner.new_service(),
|
||||||
|
timeout: self.timeout,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Timeout` response future
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct TimeoutFut<T: NewService<Request>, Request> {
|
||||||
|
fut: T::Future,
|
||||||
|
timeout: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, Request> Future for TimeoutFut<T, Request>
|
||||||
|
where
|
||||||
|
T: NewService<Request>,
|
||||||
|
{
|
||||||
|
type Item = TimeoutService<T::Service>;
|
||||||
|
type Error = T::InitError;
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
|
let service = try_ready!(self.fut.poll());
|
||||||
|
Ok(Async::Ready(TimeoutService::new(self.timeout, service)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies a timeout to requests.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct TimeoutService<T> {
|
||||||
|
inner: T,
|
||||||
|
timeout: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> TimeoutService<T> {
|
||||||
|
pub fn new<Request>(timeout: Duration, inner: T) -> Self
|
||||||
|
where
|
||||||
|
T: Service<Request>,
|
||||||
|
{
|
||||||
|
TimeoutService { inner, timeout }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Clone> Clone for TimeoutService<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
TimeoutService {
|
||||||
|
inner: self.inner.clone(),
|
||||||
|
timeout: self.timeout,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, Request> Service<Request> for TimeoutService<T>
|
||||||
|
where
|
||||||
|
T: Service<Request>,
|
||||||
|
{
|
||||||
|
type Response = T::Response;
|
||||||
|
type Error = TimeoutError<T::Error>;
|
||||||
|
type Future = TimeoutServiceResponse<T, Request>;
|
||||||
|
|
||||||
|
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||||
|
self.inner.poll_ready().map_err(TimeoutError::Service)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn call(&mut self, request: Request) -> Self::Future {
|
||||||
|
TimeoutServiceResponse {
|
||||||
|
fut: self.inner.call(request),
|
||||||
|
sleep: Delay::new(clock::now() + self.timeout),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `TimeoutService` response future
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct TimeoutServiceResponse<T: Service<Request>, Request> {
|
||||||
|
fut: T::Future,
|
||||||
|
sleep: Delay,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, Request> Future for TimeoutServiceResponse<T, Request>
|
||||||
|
where
|
||||||
|
T: Service<Request>,
|
||||||
|
{
|
||||||
|
type Item = T::Response;
|
||||||
|
type Error = TimeoutError<T::Error>;
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
|
// First, try polling the future
|
||||||
|
match self.fut.poll() {
|
||||||
|
Ok(Async::Ready(v)) => return Ok(Async::Ready(v)),
|
||||||
|
Ok(Async::NotReady) => {}
|
||||||
|
Err(e) => return Err(TimeoutError::Service(e)),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now check the sleep
|
||||||
|
match self.sleep.poll() {
|
||||||
|
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||||
|
Ok(Async::Ready(_)) => Err(TimeoutError::Timeout),
|
||||||
|
Err(_) => Err(TimeoutError::Timeout),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user