mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-12 16:47:05 +02:00
Compare commits
101 Commits
server-v0.
...
threadpool
Author | SHA1 | Date | |
---|---|---|---|
|
3821d511d0 | ||
|
62e429cb0c | ||
|
a2643d475a | ||
|
34c259a8b5 | ||
|
8b398c3386 | ||
|
0baceb0e56 | ||
|
6be1f37f6c | ||
|
a742768feb | ||
|
f913872159 | ||
|
41145040e1 | ||
|
311bb14d97 | ||
|
2955e49d78 | ||
|
9d1b428b34 | ||
|
42d526bced | ||
|
23a230a83b | ||
|
411e31786f | ||
|
b491d373b1 | ||
|
9271b95c87 | ||
|
1b3cd0d88c | ||
|
da302d4b7a | ||
|
922a919572 | ||
|
5a62175b6e | ||
|
5445e341c3 | ||
|
1b17d274a0 | ||
|
9d8b3e6275 | ||
|
27baf03f64 | ||
|
205cac82ce | ||
|
07708c5e9a | ||
|
1c04ad3238 | ||
|
66aa21740c | ||
|
b183cb3324 | ||
|
158482cd2f | ||
|
9e61f62871 | ||
|
7051888289 | ||
|
0caa47fc47 | ||
|
6d1cbb2d2f | ||
|
ca289ddf7f | ||
|
ad9a197916 | ||
|
c4f05e033f | ||
|
048314913c | ||
|
c1b183e1ce | ||
|
87bc3dacd9 | ||
|
0156f479a0 | ||
|
139fa3b9a2 | ||
|
a14f612382 | ||
|
059e2ad042 | ||
|
fdf2a6f422 | ||
|
fc2631c852 | ||
|
d51b210ae7 | ||
|
0a6cded975 | ||
|
14e3933d8b | ||
|
837504c10f | ||
|
802d808aca | ||
|
7712de3d8e | ||
|
f1d0d5f6f9 | ||
|
a76fcaf4d8 | ||
|
a2134035d6 | ||
|
5f8599faf1 | ||
|
f0776fca94 | ||
|
c7676df697 | ||
|
ecf7a11a20 | ||
|
686958fe0c | ||
|
49ade171f6 | ||
|
0a2a520c35 | ||
|
b0c37dfc87 | ||
|
91e28a4312 | ||
|
508dce8bf1 | ||
|
8ed1099a2e | ||
|
83544bd971 | ||
|
76c317e0b2 | ||
|
3b314e4c8c | ||
|
ae27b87641 | ||
|
fc2dcadc7a | ||
|
54f62b5035 | ||
|
d3208bf7a8 | ||
|
21507d3da1 | ||
|
b9d8a215b4 | ||
|
51c4dfe5cb | ||
|
a60112c71e | ||
|
bd814d6f80 | ||
|
a4e0c71baa | ||
|
b9ea445e70 | ||
|
ba2901269d | ||
|
5cbc29306a | ||
|
810fa869ae | ||
|
33cd51aabf | ||
|
629ed05f82 | ||
|
5e8ae210f7 | ||
|
3add90628f | ||
|
02ab804e0b | ||
|
feac0b43d9 | ||
|
1441355d4f | ||
|
7c5afc09a6 | ||
|
16856c7d3f | ||
|
95d02659d5 | ||
|
bcbd7e6ddf | ||
|
e0d3581239 | ||
|
ef1bdb2eb2 | ||
|
10301ff49d | ||
|
27c28d6597 | ||
|
b290273e81 |
39
.travis.yml
39
.travis.yml
@@ -10,9 +10,9 @@ matrix:
|
||||
include:
|
||||
- rust: stable
|
||||
- rust: beta
|
||||
- rust: nightly-2019-03-02
|
||||
- rust: nightly-2019-06-15
|
||||
allow_failures:
|
||||
- rust: nightly-2019-03-02
|
||||
- rust: nightly-2019-06-15
|
||||
|
||||
env:
|
||||
global:
|
||||
@@ -25,8 +25,8 @@ before_install:
|
||||
- sudo apt-get install -y openssl libssl-dev libelf-dev libdw-dev cmake gcc binutils-dev libiberty-dev
|
||||
|
||||
before_cache: |
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-03-02" ]]; then
|
||||
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install cargo-tarpaulin
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-06-15" ]]; then
|
||||
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install --version 0.6.11 cargo-tarpaulin
|
||||
fi
|
||||
|
||||
# Add clippy
|
||||
@@ -35,38 +35,15 @@ before_script:
|
||||
|
||||
script:
|
||||
- |
|
||||
if [[ "$TRAVIS_RUST_VERSION" != "nightly-2019-03-02" ]]; then
|
||||
if [[ "$TRAVIS_RUST_VERSION" != "nightly-2019-06-15" ]]; then
|
||||
cargo clean
|
||||
cargo test --features="ssl,tls,rust-tls" -- --nocapture
|
||||
cd actix-codec && cargo test && cd ..
|
||||
cd actix-service && cargo test && cd ..
|
||||
cd actix-server && cargo test --all-features -- --nocapture && cd ..
|
||||
cd actix-rt && cargo test && cd ..
|
||||
cd actix-connect && cargo test && cd ..
|
||||
cd actix-utils && cargo test && cd ..
|
||||
cd router && cargo test && cd ..
|
||||
cargo test --all --all-features -- --nocapture
|
||||
fi
|
||||
|
||||
after_success:
|
||||
- |
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-03-02" ]]; then
|
||||
#cd actix-service && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash) && cd ..
|
||||
#cd actix-rt && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash) && cd ..
|
||||
#cd actix-connect && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash) && cd ..
|
||||
#cd actix-codec && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash) && cd ..
|
||||
#cd actix-server && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash) && cd ..
|
||||
#cd actix-utils && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash) && cd ..
|
||||
#cd router && cargo tarpaulin --out Xml && bash <(curl -s https://codecov.io/bash) && cd ..
|
||||
|
||||
cd actix-service && cargo tarpaulin --out Xml && cd ..
|
||||
#cd actix-rt && cargo tarpaulin --out Xml && cd ..
|
||||
cd actix-connect && cargo tarpaulin --out Xml && cd ..
|
||||
#cd actix-codec && cargo tarpaulin --out Xml && cd ..
|
||||
#cd actix-server && cargo tarpaulin --out Xml && cd ..
|
||||
cd actix-utils && cargo tarpaulin --out Xml && cd ..
|
||||
cd router && cargo tarpaulin --out Xml && cd ..
|
||||
|
||||
# cargo tarpaulin --all --all-features --out Xml
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-06-15" ]]; then
|
||||
taskset -c 0 cargo tarpaulin --all --all-features --out Xml
|
||||
echo "Uploaded code coverage"
|
||||
bash <(curl -s https://codecov.io/bash)
|
||||
fi
|
||||
|
@@ -2,7 +2,7 @@
|
||||
name = "actix-net"
|
||||
version = "0.3.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix net - framework for the compisible network services for Rust"
|
||||
description = "Actix net - framework for the composable network services for Rust"
|
||||
readme = "README.md"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
@@ -22,15 +22,18 @@ members = [
|
||||
"actix-server",
|
||||
"actix-server-config",
|
||||
"actix-test-server",
|
||||
"actix-threadpool",
|
||||
"actix-tower",
|
||||
"actix-ioframe",
|
||||
"actix-utils",
|
||||
"router",
|
||||
]
|
||||
|
||||
[dev-dependencies]
|
||||
actix-service = "0.3.3"
|
||||
actix-service = "0.4.0"
|
||||
actix-codec = "0.1.1"
|
||||
actix-rt = "0.2.0"
|
||||
actix-server = { path="actix-server", features=["ssl"] }
|
||||
actix-server = { version="0.5.0", features=["ssl"] }
|
||||
env_logger = "0.6"
|
||||
futures = "0.1.25"
|
||||
openssl = "0.10"
|
||||
|
@@ -1,6 +1,11 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0] - 2019-03-06
|
||||
## [0.1.2] - 2019-03-27
|
||||
|
||||
* Added `Framed::map_io()` method.
|
||||
|
||||
|
||||
## [0.1.1] - 2019-03-06
|
||||
|
||||
* Added `FramedParts::with_read_buffer()` method.
|
||||
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-codec"
|
||||
version = "0.1.1"
|
||||
version = "0.1.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Utilities for encoding and decoding frames"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -11,15 +11,15 @@ categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "actix_codec"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
bytes = "0.4"
|
||||
bytes = "0.4.12"
|
||||
futures = "0.1.24"
|
||||
tokio-io = "0.1"
|
||||
tokio-codec = "0.1"
|
||||
tokio-io = "0.1.12"
|
||||
tokio-codec = "0.1.1"
|
||||
log = "0.4"
|
1
actix-codec/LICENSE-APACHE
Symbolic link
1
actix-codec/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-codec/LICENSE-MIT
Symbolic link
1
actix-codec/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -167,6 +167,22 @@ impl<T, U> Framed<T, U> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume the `Frame`, returning `Frame` with different io.
|
||||
pub fn map_io<F, T2>(self, f: F) -> Framed<T2, U>
|
||||
where
|
||||
F: Fn(T) -> T2,
|
||||
{
|
||||
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(f(inner.0), inner.1), 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
|
||||
|
@@ -1,6 +1,74 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0] - 2019-03-xx
|
||||
## [0.2.3] - 2019-08-05
|
||||
|
||||
* Add `ConnectService` and `OpensslConnectService`
|
||||
|
||||
## [0.2.2] - 2019-07-24
|
||||
|
||||
* Add `rustls` support
|
||||
|
||||
## [0.2.1] - 2019-07-17
|
||||
|
||||
### Added
|
||||
|
||||
* Expose Connect addrs #30
|
||||
|
||||
### Changed
|
||||
|
||||
* Update `derive_more` to 0.15
|
||||
|
||||
|
||||
## [0.2.0] - 2019-05-12
|
||||
|
||||
### Changed
|
||||
|
||||
* Upgrade to actix-service 0.4
|
||||
|
||||
|
||||
## [0.1.5] - 2019-04-19
|
||||
|
||||
### Added
|
||||
|
||||
* `Connect::set_addr()`
|
||||
|
||||
### Changed
|
||||
|
||||
* Use trust-dns-resolver 0.11.0
|
||||
|
||||
|
||||
## [0.1.4] - 2019-04-12
|
||||
|
||||
### Changed
|
||||
|
||||
* Do not start default resolver immediately for default connector.
|
||||
|
||||
|
||||
## [0.1.3] - 2019-04-11
|
||||
|
||||
### Changed
|
||||
|
||||
* Start trust-dns default resolver on first use
|
||||
|
||||
## [0.1.2] - 2019-04-04
|
||||
|
||||
### Added
|
||||
|
||||
* Log error if dns system config could not be loaded.
|
||||
|
||||
### Changed
|
||||
|
||||
* Rename connect Connector to TcpConnector #10
|
||||
|
||||
|
||||
## [0.1.1] - 2019-03-15
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix error handling for single address
|
||||
|
||||
|
||||
## [0.1.0] - 2019-03-14
|
||||
|
||||
* Refactor resolver and connector services
|
||||
|
||||
|
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "actix-connect"
|
||||
version = "0.1.0"
|
||||
version = "0.2.3"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix Connector - tcp connector service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-net/"
|
||||
documentation = "https://docs.rs/actix-connect/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
@@ -26,30 +26,35 @@ default = ["uri"]
|
||||
# openssl
|
||||
ssl = ["openssl", "tokio-openssl"]
|
||||
|
||||
#rustls
|
||||
rust-tls = ["rustls", "tokio-rustls", "webpki"]
|
||||
|
||||
# support http::Uri as connect address
|
||||
uri = ["http"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.3.4"
|
||||
actix-codec = "0.1.1"
|
||||
actix-utils = "0.3.4"
|
||||
derive_more = "0.14.0"
|
||||
either = "1.5.1"
|
||||
actix-service = "0.4.0"
|
||||
actix-codec = "0.1.2"
|
||||
actix-utils = "0.4.0"
|
||||
derive_more = "0.15"
|
||||
either = "1.5.2"
|
||||
futures = "0.1.25"
|
||||
http = { version = "0.1.16", optional = true }
|
||||
http = { version = "0.1.17", optional = true }
|
||||
log = "0.4"
|
||||
tokio-tcp = "0.1.3"
|
||||
tokio-current-thread = "0.1.5"
|
||||
trust-dns-resolver = { version="0.11.0-alpha.2", default-features = false }
|
||||
trust-dns-resolver = { version="0.11.0", default-features = false }
|
||||
|
||||
# openssl
|
||||
openssl = { version="0.10", optional = true }
|
||||
tokio-openssl = { version="0.3", optional = true }
|
||||
|
||||
#rustls
|
||||
rustls = { version = "0.15.2", optional = true }
|
||||
tokio-rustls = { version = "0.9.1", optional = true }
|
||||
webpki = { version = "0.19", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
bytes = "0.4"
|
||||
actix-connect = { path=".", features=["ssl"] }
|
||||
actix-test-server = { version="0.2.0", features=["ssl"] }
|
||||
actix-test-server = { version="0.2.2", features=["ssl"] }
|
||||
actix-server-config = "0.1.0"
|
||||
actix-utils = "0.3.4"
|
||||
tokio-tcp = "0.1"
|
1
actix-connect/LICENSE-APACHE
Symbolic link
1
actix-connect/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-connect/LICENSE-MIT
Symbolic link
1
actix-connect/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -1,5 +1,6 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::collections::{vec_deque, VecDeque};
|
||||
use std::fmt;
|
||||
use std::iter::{FromIterator, FusedIterator};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use either::Either;
|
||||
@@ -69,6 +70,28 @@ impl<T: Address> Connect<T> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Use address.
|
||||
pub fn set_addr(mut self, addr: Option<SocketAddr>) -> Self {
|
||||
if let Some(addr) = addr {
|
||||
self.addr = Some(Either::Left(addr));
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Use addresses.
|
||||
pub fn set_addrs<I>(mut self, addrs: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = SocketAddr>,
|
||||
{
|
||||
let mut addrs = VecDeque::from_iter(addrs);
|
||||
self.addr = if addrs.len() < 2 {
|
||||
addrs.pop_front().map(Either::Left)
|
||||
} else {
|
||||
Some(Either::Right(addrs))
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
/// Host name
|
||||
pub fn host(&self) -> &str {
|
||||
self.req.host()
|
||||
@@ -78,6 +101,28 @@ impl<T: Address> Connect<T> {
|
||||
pub fn port(&self) -> u16 {
|
||||
self.req.port().unwrap_or(self.port)
|
||||
}
|
||||
|
||||
/// Preresolved addresses of the request.
|
||||
pub fn addrs(&self) -> ConnectAddrsIter<'_> {
|
||||
let inner = match self.addr {
|
||||
None => Either::Left(None),
|
||||
Some(Either::Left(addr)) => Either::Left(Some(addr)),
|
||||
Some(Either::Right(ref addrs)) => Either::Right(addrs.iter()),
|
||||
};
|
||||
|
||||
ConnectAddrsIter { inner }
|
||||
}
|
||||
|
||||
/// Takes preresolved addresses of the request.
|
||||
pub fn take_addrs(&mut self) -> ConnectTakeAddrsIter {
|
||||
let inner = match self.addr.take() {
|
||||
None => Either::Left(None),
|
||||
Some(Either::Left(addr)) => Either::Left(Some(addr)),
|
||||
Some(Either::Right(addrs)) => Either::Right(addrs.into_iter()),
|
||||
};
|
||||
|
||||
ConnectTakeAddrsIter { inner }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> From<T> for Connect<T> {
|
||||
@@ -92,6 +137,70 @@ impl<T: Address> fmt::Display for Connect<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterator over addresses in a [`Connect`](struct.Connect.html) request.
|
||||
#[derive(Clone)]
|
||||
pub struct ConnectAddrsIter<'a> {
|
||||
inner: Either<Option<SocketAddr>, vec_deque::Iter<'a, SocketAddr>>,
|
||||
}
|
||||
|
||||
impl Iterator for ConnectAddrsIter<'_> {
|
||||
type Item = SocketAddr;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match self.inner {
|
||||
Either::Left(ref mut opt) => opt.take(),
|
||||
Either::Right(ref mut iter) => iter.next().copied(),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
match self.inner {
|
||||
Either::Left(Some(_)) => (1, Some(1)),
|
||||
Either::Left(None) => (0, Some(0)),
|
||||
Either::Right(ref iter) => iter.size_hint(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ConnectAddrsIter<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.debug_list().entries(self.clone()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExactSizeIterator for ConnectAddrsIter<'_> {}
|
||||
|
||||
impl FusedIterator for ConnectAddrsIter<'_> {}
|
||||
|
||||
/// Owned iterator over addresses in a [`Connect`](struct.Connect.html) request.
|
||||
#[derive(Debug)]
|
||||
pub struct ConnectTakeAddrsIter {
|
||||
inner: Either<Option<SocketAddr>, vec_deque::IntoIter<SocketAddr>>,
|
||||
}
|
||||
|
||||
impl Iterator for ConnectTakeAddrsIter {
|
||||
type Item = SocketAddr;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
match self.inner {
|
||||
Either::Left(ref mut opt) => opt.take(),
|
||||
Either::Right(ref mut iter) => iter.next(),
|
||||
}
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
match self.inner {
|
||||
Either::Left(Some(_)) => (1, Some(1)),
|
||||
Either::Left(None) => (0, Some(0)),
|
||||
Either::Right(ref iter) => iter.size_hint(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ExactSizeIterator for ConnectTakeAddrsIter {}
|
||||
|
||||
impl FusedIterator for ConnectTakeAddrsIter {}
|
||||
|
||||
fn parse(host: &str) -> (&str, Option<u16>) {
|
||||
let mut parts_iter = host.splitn(2, ':');
|
||||
if let Some(host) = parts_iter.next() {
|
||||
|
@@ -12,54 +12,66 @@ use super::error::ConnectError;
|
||||
|
||||
/// Tcp connector service factory
|
||||
#[derive(Debug)]
|
||||
pub struct ConnectorFactory<T>(PhantomData<T>);
|
||||
pub struct TcpConnectorFactory<T>(PhantomData<T>);
|
||||
|
||||
impl<T> ConnectorFactory<T> {
|
||||
impl<T> TcpConnectorFactory<T> {
|
||||
pub fn new() -> Self {
|
||||
ConnectorFactory(PhantomData)
|
||||
TcpConnectorFactory(PhantomData)
|
||||
}
|
||||
|
||||
/// Create tcp connector service
|
||||
pub fn service(&self) -> TcpConnector<T> {
|
||||
TcpConnector(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for ConnectorFactory<T> {
|
||||
impl<T> Default for TcpConnectorFactory<T> {
|
||||
fn default() -> Self {
|
||||
TcpConnectorFactory(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for TcpConnectorFactory<T> {
|
||||
fn clone(&self) -> Self {
|
||||
ConnectorFactory(PhantomData)
|
||||
TcpConnectorFactory(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> NewService for ConnectorFactory<T> {
|
||||
impl<T: Address> NewService for TcpConnectorFactory<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
type Service = Connector<T>;
|
||||
type Config = ();
|
||||
type Service = TcpConnector<T>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(Connector(PhantomData))
|
||||
ok(self.service())
|
||||
}
|
||||
}
|
||||
|
||||
/// Tcp connector service
|
||||
#[derive(Debug)]
|
||||
pub struct Connector<T>(PhantomData<T>);
|
||||
pub struct TcpConnector<T>(PhantomData<T>);
|
||||
|
||||
impl<T> Connector<T> {
|
||||
impl<T> TcpConnector<T> {
|
||||
pub fn new() -> Self {
|
||||
Connector(PhantomData)
|
||||
TcpConnector(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for Connector<T> {
|
||||
impl<T> Clone for TcpConnector<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Connector(PhantomData)
|
||||
TcpConnector(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> Service for Connector<T> {
|
||||
impl<T: Address> Service for TcpConnector<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
type Future = Either<ConnectorResponse<T>, FutureResult<Self::Response, Self::Error>>;
|
||||
type Future = Either<TcpConnectorResponse<T>, FutureResult<Self::Response, Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
@@ -70,7 +82,7 @@ impl<T: Address> Service for Connector<T> {
|
||||
let Connect { req, addr, .. } = req;
|
||||
|
||||
if let Some(addr) = addr {
|
||||
Either::A(ConnectorResponse::new(req, port, addr))
|
||||
Either::A(TcpConnectorResponse::new(req, port, addr))
|
||||
} else {
|
||||
error!("TCP connector: got unresolved address");
|
||||
Either::B(err(ConnectError::Unresolverd))
|
||||
@@ -80,19 +92,19 @@ impl<T: Address> Service for Connector<T> {
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Tcp stream connector response future
|
||||
pub struct ConnectorResponse<T> {
|
||||
pub struct TcpConnectorResponse<T> {
|
||||
req: Option<T>,
|
||||
port: u16,
|
||||
addrs: Option<VecDeque<SocketAddr>>,
|
||||
stream: Option<ConnectFuture>,
|
||||
}
|
||||
|
||||
impl<T: Address> ConnectorResponse<T> {
|
||||
impl<T: Address> TcpConnectorResponse<T> {
|
||||
pub fn new(
|
||||
req: T,
|
||||
port: u16,
|
||||
addr: either::Either<SocketAddr, VecDeque<SocketAddr>>,
|
||||
) -> ConnectorResponse<T> {
|
||||
) -> TcpConnectorResponse<T> {
|
||||
trace!(
|
||||
"TCP connector - connecting to {:?} port:{}",
|
||||
req.host(),
|
||||
@@ -100,13 +112,13 @@ impl<T: Address> ConnectorResponse<T> {
|
||||
);
|
||||
|
||||
match addr {
|
||||
either::Either::Left(addr) => ConnectorResponse {
|
||||
either::Either::Left(addr) => TcpConnectorResponse {
|
||||
req: Some(req),
|
||||
port,
|
||||
addrs: None,
|
||||
stream: Some(TcpStream::connect(&addr)),
|
||||
},
|
||||
either::Either::Right(addrs) => ConnectorResponse {
|
||||
either::Either::Right(addrs) => TcpConnectorResponse {
|
||||
req: Some(req),
|
||||
port,
|
||||
addrs: Some(addrs),
|
||||
@@ -116,7 +128,7 @@ impl<T: Address> ConnectorResponse<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> Future for ConnectorResponse<T> {
|
||||
impl<T: Address> Future for TcpConnectorResponse<T> {
|
||||
type Item = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
|
||||
@@ -140,7 +152,7 @@ impl<T: Address> Future for ConnectorResponse<T> {
|
||||
self.req.as_ref().unwrap().host(),
|
||||
self.port,
|
||||
);
|
||||
if self.addrs.as_ref().unwrap().is_empty() {
|
||||
if self.addrs.is_none() || self.addrs.as_ref().unwrap().is_empty() {
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
|
@@ -5,29 +5,35 @@
|
||||
//! * `ssl` - enables ssl support via `openssl` crate
|
||||
//! * `rust-tls` - enables ssl support via `rustls` crate
|
||||
|
||||
#![recursion_limit = "128"]
|
||||
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
use std::cell::RefCell;
|
||||
|
||||
mod connect;
|
||||
mod connector;
|
||||
mod error;
|
||||
mod resolver;
|
||||
mod service;
|
||||
pub mod ssl;
|
||||
|
||||
#[cfg(feature = "uri")]
|
||||
mod uri;
|
||||
|
||||
pub use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||
pub use trust_dns_resolver::system_conf::read_system_conf;
|
||||
pub use trust_dns_resolver::{error::ResolveError, AsyncResolver};
|
||||
|
||||
pub use self::connect::{Address, Connect, Connection};
|
||||
pub use self::connector::{Connector, ConnectorFactory};
|
||||
pub use self::connector::{TcpConnector, TcpConnectorFactory};
|
||||
pub use self::error::ConnectError;
|
||||
pub use self::resolver::{Resolver, ResolverFactory};
|
||||
pub use self::service::{ConnectService, ConnectServiceFactory};
|
||||
|
||||
use actix_service::{NewService, Service, ServiceExt};
|
||||
use tokio_tcp::TcpStream;
|
||||
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||
use trust_dns_resolver::system_conf::read_system_conf;
|
||||
|
||||
pub fn start_resolver(cfg: ResolverConfig, opts: ResolverOpts) -> AsyncResolver {
|
||||
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
||||
@@ -35,16 +41,34 @@ pub fn start_resolver(cfg: ResolverConfig, opts: ResolverOpts) -> AsyncResolver
|
||||
resolver
|
||||
}
|
||||
|
||||
pub fn start_default_resolver() -> AsyncResolver {
|
||||
let (cfg, opts) = if let Ok((cfg, opts)) = read_system_conf() {
|
||||
(cfg, opts)
|
||||
} else {
|
||||
(ResolverConfig::default(), ResolverOpts::default())
|
||||
};
|
||||
thread_local! {
|
||||
static DEFAULT_RESOLVER: RefCell<Option<AsyncResolver>> = RefCell::new(None);
|
||||
}
|
||||
|
||||
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
||||
tokio_current_thread::spawn(bg);
|
||||
resolver
|
||||
pub(crate) fn get_default_resolver() -> AsyncResolver {
|
||||
DEFAULT_RESOLVER.with(|cell| {
|
||||
if let Some(ref resolver) = *cell.borrow() {
|
||||
return resolver.clone();
|
||||
}
|
||||
|
||||
let (cfg, opts) = match read_system_conf() {
|
||||
Ok((cfg, opts)) => (cfg, opts),
|
||||
Err(e) => {
|
||||
log::error!("TRust-DNS can not load system config: {}", e);
|
||||
(ResolverConfig::default(), ResolverOpts::default())
|
||||
}
|
||||
};
|
||||
|
||||
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
||||
tokio_current_thread::spawn(bg);
|
||||
|
||||
*cell.borrow_mut() = Some(resolver.clone());
|
||||
resolver
|
||||
})
|
||||
}
|
||||
|
||||
pub fn start_default_resolver() -> AsyncResolver {
|
||||
get_default_resolver()
|
||||
}
|
||||
|
||||
/// Create tcp connector service
|
||||
@@ -52,34 +76,36 @@ pub fn new_connector<T: Address>(
|
||||
resolver: AsyncResolver,
|
||||
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
|
||||
+ Clone {
|
||||
Resolver::new(resolver).and_then(Connector::new())
|
||||
Resolver::new(resolver).and_then(TcpConnector::new())
|
||||
}
|
||||
|
||||
/// Create tcp connector service
|
||||
pub fn new_connector_factory<T: Address>(
|
||||
resolver: AsyncResolver,
|
||||
) -> impl NewService<
|
||||
Config = (),
|
||||
Request = Connect<T>,
|
||||
Response = Connection<T, TcpStream>,
|
||||
Error = ConnectError,
|
||||
InitError = (),
|
||||
> + Clone {
|
||||
ResolverFactory::new(resolver).and_then(ConnectorFactory::new())
|
||||
ResolverFactory::new(resolver).and_then(TcpConnectorFactory::new())
|
||||
}
|
||||
|
||||
/// Create connector service with default parameters
|
||||
pub fn default_connector<T: Address>(
|
||||
) -> impl Service<Request = Connect<T>, Response = Connection<T, TcpStream>, Error = ConnectError>
|
||||
+ Clone {
|
||||
Resolver::new(start_default_resolver()).and_then(Connector::new())
|
||||
Resolver::default().and_then(TcpConnector::new())
|
||||
}
|
||||
|
||||
/// Create connector service factory with default parameters
|
||||
pub fn default_connector_factory<T: Address>() -> impl NewService<
|
||||
Config = (),
|
||||
Request = Connect<T>,
|
||||
Response = Connection<T, TcpStream>,
|
||||
Error = ConnectError,
|
||||
InitError = (),
|
||||
> + Clone {
|
||||
ResolverFactory::new(start_default_resolver()).and_then(ConnectorFactory::new())
|
||||
ResolverFactory::default().and_then(TcpConnectorFactory::new())
|
||||
}
|
||||
|
@@ -1,4 +1,3 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::marker::PhantomData;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
@@ -10,10 +9,11 @@ use trust_dns_resolver::{AsyncResolver, Background};
|
||||
|
||||
use crate::connect::{Address, Connect};
|
||||
use crate::error::ConnectError;
|
||||
use crate::get_default_resolver;
|
||||
|
||||
/// DNS Resolver Service factory
|
||||
pub struct ResolverFactory<T> {
|
||||
resolver: AsyncResolver,
|
||||
resolver: Option<AsyncResolver>,
|
||||
_t: PhantomData<T>,
|
||||
}
|
||||
|
||||
@@ -21,13 +21,25 @@ impl<T> ResolverFactory<T> {
|
||||
/// Create new resolver instance with custom configuration and options.
|
||||
pub fn new(resolver: AsyncResolver) -> Self {
|
||||
ResolverFactory {
|
||||
resolver,
|
||||
resolver: Some(resolver),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolver(&self) -> &AsyncResolver {
|
||||
&self.resolver
|
||||
pub fn service(&self) -> Resolver<T> {
|
||||
Resolver {
|
||||
resolver: self.resolver.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for ResolverFactory<T> {
|
||||
fn default() -> Self {
|
||||
ResolverFactory {
|
||||
resolver: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,21 +56,19 @@ impl<T: Address> NewService for ResolverFactory<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = Connect<T>;
|
||||
type Error = ConnectError;
|
||||
type Config = ();
|
||||
type Service = Resolver<T>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(Resolver {
|
||||
resolver: self.resolver.clone(),
|
||||
_t: PhantomData,
|
||||
})
|
||||
ok(self.service())
|
||||
}
|
||||
}
|
||||
|
||||
/// DNS Resolver Service
|
||||
pub struct Resolver<T> {
|
||||
resolver: AsyncResolver,
|
||||
resolver: Option<AsyncResolver>,
|
||||
_t: PhantomData<T>,
|
||||
}
|
||||
|
||||
@@ -66,7 +76,16 @@ impl<T> Resolver<T> {
|
||||
/// Create new resolver instance with custom configuration and options.
|
||||
pub fn new(resolver: AsyncResolver) -> Self {
|
||||
Resolver {
|
||||
resolver,
|
||||
resolver: Some(resolver),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for Resolver<T> {
|
||||
fn default() -> Self {
|
||||
Resolver {
|
||||
resolver: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -100,7 +119,10 @@ impl<T: Address> Service for Resolver<T> {
|
||||
Either::B(ok(req))
|
||||
} else {
|
||||
trace!("DNS resolver: resolving host {:?}", req.host());
|
||||
Either::A(ResolverFuture::new(req, &self.resolver))
|
||||
if self.resolver.is_none() {
|
||||
self.resolver = Some(get_default_resolver());
|
||||
}
|
||||
Either::A(ResolverFuture::new(req, self.resolver.as_ref().unwrap()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,21 +165,20 @@ impl<T: Address> Future for ResolverFuture<T> {
|
||||
})? {
|
||||
Async::NotReady => Ok(Async::NotReady),
|
||||
Async::Ready(ips) => {
|
||||
let mut req = self.req.take().unwrap();
|
||||
let mut addrs: VecDeque<_> = ips
|
||||
.iter()
|
||||
.map(|ip| SocketAddr::new(ip, req.port()))
|
||||
.collect();
|
||||
let req = self.req.take().unwrap();
|
||||
|
||||
let port = req.port();
|
||||
let req = req.set_addrs(ips.iter().map(|ip| SocketAddr::new(ip, port)));
|
||||
|
||||
trace!(
|
||||
"DNS resolver: host {:?} resolved to {:?}",
|
||||
req.host(),
|
||||
addrs
|
||||
req.addrs()
|
||||
);
|
||||
if addrs.len() == 1 {
|
||||
req.addr = Some(either::Either::Left(addrs.pop_front().unwrap()));
|
||||
Ok(Async::Ready(req))
|
||||
|
||||
if req.addr.is_none() {
|
||||
Err(ConnectError::NoRecords)
|
||||
} else {
|
||||
req.addr = Some(either::Either::Right(addrs));
|
||||
Ok(Async::Ready(req))
|
||||
}
|
||||
}
|
||||
|
123
actix-connect/src/service.rs
Normal file
123
actix-connect/src/service.rs
Normal file
@@ -0,0 +1,123 @@
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{try_ready, Async, Future, Poll};
|
||||
use tokio_tcp::TcpStream;
|
||||
use trust_dns_resolver::AsyncResolver;
|
||||
|
||||
use crate::connect::{Address, Connect, Connection};
|
||||
use crate::connector::{TcpConnector, TcpConnectorFactory};
|
||||
use crate::error::ConnectError;
|
||||
use crate::resolver::{Resolver, ResolverFactory};
|
||||
|
||||
pub struct ConnectServiceFactory<T> {
|
||||
tcp: TcpConnectorFactory<T>,
|
||||
resolver: ResolverFactory<T>,
|
||||
}
|
||||
|
||||
impl<T> ConnectServiceFactory<T> {
|
||||
/// Construct new ConnectService factory
|
||||
pub fn new() -> Self {
|
||||
ConnectServiceFactory {
|
||||
tcp: TcpConnectorFactory::default(),
|
||||
resolver: ResolverFactory::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct new connect service with custom dns resolver
|
||||
pub fn with_resolver(resolver: AsyncResolver) -> Self {
|
||||
ConnectServiceFactory {
|
||||
tcp: TcpConnectorFactory::default(),
|
||||
resolver: ResolverFactory::new(resolver),
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct new service
|
||||
pub fn service(&self) -> ConnectService<T> {
|
||||
ConnectService {
|
||||
tcp: self.tcp.service(),
|
||||
resolver: self.resolver.service(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for ConnectServiceFactory<T> {
|
||||
fn default() -> Self {
|
||||
ConnectServiceFactory {
|
||||
tcp: TcpConnectorFactory::default(),
|
||||
resolver: ResolverFactory::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for ConnectServiceFactory<T> {
|
||||
fn clone(&self) -> Self {
|
||||
ConnectServiceFactory {
|
||||
tcp: self.tcp.clone(),
|
||||
resolver: self.resolver.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> NewService for ConnectServiceFactory<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
type Config = ();
|
||||
type Service = ConnectService<T>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(self.service())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ConnectService<T> {
|
||||
tcp: TcpConnector<T>,
|
||||
resolver: Resolver<T>,
|
||||
}
|
||||
|
||||
impl<T: Address> Service for ConnectService<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
type Future = ConnectServiceResponse<T>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Connect<T>) -> Self::Future {
|
||||
ConnectServiceResponse {
|
||||
fut1: Some(self.resolver.call(req)),
|
||||
fut2: None,
|
||||
tcp: self.tcp.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ConnectServiceResponse<T: Address> {
|
||||
fut1: Option<<Resolver<T> as Service>::Future>,
|
||||
fut2: Option<<TcpConnector<T> as Service>::Future>,
|
||||
tcp: TcpConnector<T>,
|
||||
}
|
||||
|
||||
impl<T: Address> Future for ConnectServiceResponse<T> {
|
||||
type Item = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.fut1 {
|
||||
let res = try_ready!(fut.poll());
|
||||
let _ = self.fut1.take();
|
||||
self.fut2 = Some(self.tcp.call(res));
|
||||
}
|
||||
|
||||
if let Some(ref mut fut) = self.fut2 {
|
||||
return fut.poll();
|
||||
}
|
||||
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
@@ -3,4 +3,10 @@
|
||||
#[cfg(feature = "ssl")]
|
||||
mod openssl;
|
||||
#[cfg(feature = "ssl")]
|
||||
pub use self::openssl::OpensslConnector;
|
||||
pub use self::openssl::{
|
||||
OpensslConnectService, OpensslConnectServiceFactory, OpensslConnector,
|
||||
};
|
||||
#[cfg(feature = "rust-tls")]
|
||||
mod rustls;
|
||||
#[cfg(feature = "rust-tls")]
|
||||
pub use self::rustls::RustlsConnector;
|
||||
|
@@ -1,13 +1,17 @@
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::{fmt, io};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::{future::ok, future::FutureResult, Async, Future, Poll};
|
||||
use futures::{future::ok, future::FutureResult, try_ready, Async, Future, Poll};
|
||||
use openssl::ssl::{HandshakeError, SslConnector};
|
||||
use tokio_openssl::{ConnectAsync, SslConnectorExt, SslStream};
|
||||
use tokio_tcp::TcpStream;
|
||||
use trust_dns_resolver::AsyncResolver;
|
||||
|
||||
use crate::{Address, Connection};
|
||||
use crate::{
|
||||
Address, Connect, ConnectError, ConnectService, ConnectServiceFactory, Connection,
|
||||
};
|
||||
|
||||
/// Openssl connector factory
|
||||
pub struct OpensslConnector<T, U> {
|
||||
@@ -52,13 +56,14 @@ impl<T, U> Clone for OpensslConnector<T, U> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address, U> NewService<()> for OpensslConnector<T, U>
|
||||
impl<T: Address, U> NewService for OpensslConnector<T, U>
|
||||
where
|
||||
U: AsyncRead + AsyncWrite + fmt::Debug,
|
||||
{
|
||||
type Request = Connection<T, U>;
|
||||
type Response = Connection<T, SslStream<U>>;
|
||||
type Error = HandshakeError<U>;
|
||||
type Config = ();
|
||||
type Service = OpensslConnectorService<T, U>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
@@ -76,6 +81,15 @@ pub struct OpensslConnectorService<T, U> {
|
||||
_t: PhantomData<(T, U)>,
|
||||
}
|
||||
|
||||
impl<T, U> Clone for OpensslConnectorService<T, U> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
connector: self.connector.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address, U> Service for OpensslConnectorService<T, U>
|
||||
where
|
||||
U: AsyncRead + AsyncWrite + fmt::Debug,
|
||||
@@ -125,3 +139,113 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct OpensslConnectServiceFactory<T> {
|
||||
tcp: ConnectServiceFactory<T>,
|
||||
openssl: OpensslConnector<T, TcpStream>,
|
||||
}
|
||||
|
||||
impl<T> OpensslConnectServiceFactory<T> {
|
||||
/// Construct new OpensslConnectService factory
|
||||
pub fn new(connector: SslConnector) -> Self {
|
||||
OpensslConnectServiceFactory {
|
||||
tcp: ConnectServiceFactory::default(),
|
||||
openssl: OpensslConnector::new(connector),
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct new connect service with custom dns resolver
|
||||
pub fn with_resolver(connector: SslConnector, resolver: AsyncResolver) -> Self {
|
||||
OpensslConnectServiceFactory {
|
||||
tcp: ConnectServiceFactory::with_resolver(resolver),
|
||||
openssl: OpensslConnector::new(connector),
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct openssl connect service
|
||||
pub fn service(&self) -> OpensslConnectService<T> {
|
||||
OpensslConnectService {
|
||||
tcp: self.tcp.service(),
|
||||
openssl: OpensslConnectorService {
|
||||
connector: self.openssl.connector.clone(),
|
||||
_t: PhantomData,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for OpensslConnectServiceFactory<T> {
|
||||
fn clone(&self) -> Self {
|
||||
OpensslConnectServiceFactory {
|
||||
tcp: self.tcp.clone(),
|
||||
openssl: self.openssl.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> NewService for OpensslConnectServiceFactory<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = SslStream<TcpStream>;
|
||||
type Error = ConnectError;
|
||||
type Config = ();
|
||||
type Service = OpensslConnectService<T>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(self.service())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct OpensslConnectService<T> {
|
||||
tcp: ConnectService<T>,
|
||||
openssl: OpensslConnectorService<T, TcpStream>,
|
||||
}
|
||||
|
||||
impl<T: Address> Service for OpensslConnectService<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = SslStream<TcpStream>;
|
||||
type Error = ConnectError;
|
||||
type Future = OpensslConnectServiceResponse<T>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Connect<T>) -> Self::Future {
|
||||
OpensslConnectServiceResponse {
|
||||
fut1: Some(self.tcp.call(req)),
|
||||
fut2: None,
|
||||
openssl: self.openssl.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct OpensslConnectServiceResponse<T: Address> {
|
||||
fut1: Option<<ConnectService<T> as Service>::Future>,
|
||||
fut2: Option<<OpensslConnectorService<T, TcpStream> as Service>::Future>,
|
||||
openssl: OpensslConnectorService<T, TcpStream>,
|
||||
}
|
||||
|
||||
impl<T: Address> Future for OpensslConnectServiceResponse<T> {
|
||||
type Item = SslStream<TcpStream>;
|
||||
type Error = ConnectError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.fut1 {
|
||||
let res = try_ready!(fut.poll());
|
||||
let _ = self.fut1.take();
|
||||
self.fut2 = Some(self.openssl.call(res));
|
||||
}
|
||||
|
||||
if let Some(ref mut fut) = self.fut2 {
|
||||
let connect = try_ready!(fut
|
||||
.poll()
|
||||
.map_err(|e| ConnectError::Io(io::Error::new(io::ErrorKind::Other, e))));
|
||||
Ok(Async::Ready(connect.into_parts().0))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
133
actix-connect/src/ssl/rustls.rs
Normal file
133
actix-connect/src/ssl/rustls.rs
Normal file
@@ -0,0 +1,133 @@
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::{future::ok, future::FutureResult, Async, Future, Poll};
|
||||
use std::sync::Arc;
|
||||
use tokio_rustls::{
|
||||
rustls::{ClientConfig, ClientSession},
|
||||
Connect, TlsConnector, TlsStream,
|
||||
};
|
||||
use webpki::DNSNameRef;
|
||||
|
||||
use crate::{Address, Connection};
|
||||
|
||||
/// Rustls connector factory
|
||||
pub struct RustlsConnector<T, U> {
|
||||
connector: Arc<ClientConfig>,
|
||||
_t: PhantomData<(T, U)>,
|
||||
}
|
||||
|
||||
impl<T, U> RustlsConnector<T, U> {
|
||||
pub fn new(connector: Arc<ClientConfig>) -> Self {
|
||||
RustlsConnector {
|
||||
connector,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> RustlsConnector<T, U>
|
||||
where
|
||||
T: Address,
|
||||
U: AsyncRead + AsyncWrite + fmt::Debug,
|
||||
{
|
||||
pub fn service(
|
||||
connector: Arc<ClientConfig>,
|
||||
) -> impl Service<
|
||||
Request = Connection<T, U>,
|
||||
Response = Connection<T, TlsStream<U, ClientSession>>,
|
||||
Error = std::io::Error,
|
||||
> {
|
||||
RustlsConnectorService {
|
||||
connector: connector,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Clone for RustlsConnector<T, U> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
connector: self.connector.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address, U> NewService for RustlsConnector<T, U>
|
||||
where
|
||||
U: AsyncRead + AsyncWrite + fmt::Debug,
|
||||
{
|
||||
type Request = Connection<T, U>;
|
||||
type Response = Connection<T, TlsStream<U, ClientSession>>;
|
||||
type Error = std::io::Error;
|
||||
type Config = ();
|
||||
type Service = RustlsConnectorService<T, U>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(RustlsConnectorService {
|
||||
connector: self.connector.clone(),
|
||||
_t: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RustlsConnectorService<T, U> {
|
||||
connector: Arc<ClientConfig>,
|
||||
_t: PhantomData<(T, U)>,
|
||||
}
|
||||
|
||||
impl<T: Address, U> Service for RustlsConnectorService<T, U>
|
||||
where
|
||||
U: AsyncRead + AsyncWrite + fmt::Debug,
|
||||
{
|
||||
type Request = Connection<T, U>;
|
||||
type Response = Connection<T, TlsStream<U, ClientSession>>;
|
||||
type Error = std::io::Error;
|
||||
type Future = ConnectAsyncExt<T, U>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, stream: Connection<T, U>) -> Self::Future {
|
||||
trace!("SSL Handshake start for: {:?}", stream.host());
|
||||
let (io, stream) = stream.replace(());
|
||||
let host = DNSNameRef::try_from_ascii_str(stream.host()).unwrap();
|
||||
ConnectAsyncExt {
|
||||
fut: TlsConnector::from(self.connector.clone()).connect(host, io),
|
||||
stream: Some(stream),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ConnectAsyncExt<T, U> {
|
||||
fut: Connect<U>,
|
||||
stream: Option<Connection<T, ()>>,
|
||||
}
|
||||
|
||||
impl<T: Address, U> Future for ConnectAsyncExt<T, U>
|
||||
where
|
||||
U: AsyncRead + AsyncWrite + fmt::Debug,
|
||||
{
|
||||
type Item = Connection<T, TlsStream<U, ClientSession>>;
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.fut.poll().map_err(|e| {
|
||||
trace!("SSL Handshake error: {:?}", e);
|
||||
e
|
||||
})? {
|
||||
Async::Ready(stream) => {
|
||||
let s = self.stream.take().unwrap();
|
||||
trace!("SSL Handshake success: {:?}", s.host());
|
||||
Ok(Async::Ready(s.replace(stream).1))
|
||||
}
|
||||
Async::NotReady => Ok(Async::NotReady),
|
||||
}
|
||||
}
|
||||
}
|
@@ -26,6 +26,7 @@ fn port(scheme: Option<&str>) -> Option<u16> {
|
||||
"wss" => Some(443),
|
||||
"amqp" => Some(5672),
|
||||
"amqps" => Some(5671),
|
||||
"sb" => Some(5671),
|
||||
"mqtt" => Some(1883),
|
||||
"mqtts" => Some(8883),
|
||||
_ => None,
|
||||
|
@@ -1,6 +1,6 @@
|
||||
use actix_codec::{BytesCodec, Framed};
|
||||
use actix_server_config::Io;
|
||||
use actix_service::{fn_service, NewService, Service};
|
||||
use actix_service::{service_fn, NewService, Service};
|
||||
use actix_test_server::TestServer;
|
||||
use bytes::Bytes;
|
||||
use futures::{future::lazy, Future, Sink};
|
||||
@@ -9,28 +9,43 @@ use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||
|
||||
use actix_connect::{default_connector, Connect};
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_string() {
|
||||
let mut srv = TestServer::with(|| {
|
||||
fn_service(|io: Io<tokio_tcp::TcpStream>| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
})
|
||||
});
|
||||
|
||||
let mut conn = srv
|
||||
.block_on(lazy(|| Ok::<_, ()>(default_connector())))
|
||||
.unwrap();
|
||||
let mut conn = default_connector();
|
||||
let addr = format!("localhost:{}", srv.port());
|
||||
let con = srv.block_on(conn.call(addr.into())).unwrap();
|
||||
let con = srv.run_on(move || conn.call(addr.into())).unwrap();
|
||||
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-tls")]
|
||||
#[test]
|
||||
fn test_rustls_string() {
|
||||
let mut srv = TestServer::with(|| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
})
|
||||
});
|
||||
|
||||
let mut conn = default_connector();
|
||||
let addr = format!("localhost:{}", srv.port());
|
||||
let con = srv.run_on(move || conn.call(addr.into())).unwrap();
|
||||
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
||||
}
|
||||
#[test]
|
||||
fn test_static_str() {
|
||||
let mut srv = TestServer::with(|| {
|
||||
fn_service(|io: Io<tokio_tcp::TcpStream>| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
@@ -43,19 +58,28 @@ fn test_static_str() {
|
||||
))
|
||||
.unwrap();
|
||||
let mut conn = srv
|
||||
.block_on(lazy(|| Ok::<_, ()>(actix_connect::new_connector(resolver))))
|
||||
.block_on(lazy(|| {
|
||||
Ok::<_, ()>(actix_connect::new_connector(resolver.clone()))
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
let con = srv
|
||||
.block_on(conn.call(Connect::with("10", srv.addr())))
|
||||
.unwrap();
|
||||
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
||||
|
||||
let connect = Connect::new(srv.host().to_owned());
|
||||
let mut conn = srv
|
||||
.block_on(lazy(|| Ok::<_, ()>(actix_connect::new_connector(resolver))))
|
||||
.unwrap();
|
||||
let con = srv.block_on(conn.call(connect));
|
||||
assert!(con.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_service() {
|
||||
let mut srv = TestServer::with(|| {
|
||||
fn_service(|io: Io<tokio_tcp::TcpStream>| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
@@ -83,20 +107,36 @@ fn test_new_service() {
|
||||
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_uri() {
|
||||
let mut srv = TestServer::with(|| {
|
||||
fn_service(|io: Io<tokio_tcp::TcpStream>| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
})
|
||||
});
|
||||
|
||||
let mut conn = srv
|
||||
.block_on(lazy(|| Ok::<_, ()>(default_connector())))
|
||||
.unwrap();
|
||||
let mut conn = default_connector();
|
||||
let addr = Uri::try_from(format!("https://localhost:{}", srv.port())).unwrap();
|
||||
let con = srv.block_on(conn.call(addr.into())).unwrap();
|
||||
let con = srv.run_on(move || conn.call(addr.into())).unwrap();
|
||||
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-tls")]
|
||||
#[test]
|
||||
fn test_rustls_uri() {
|
||||
let mut srv = TestServer::with(|| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
})
|
||||
});
|
||||
|
||||
let mut conn = default_connector();
|
||||
let addr = Uri::try_from(format!("https://localhost:{}", srv.port())).unwrap();
|
||||
let con = srv.run_on(move || conn.call(addr.into())).unwrap();
|
||||
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
||||
}
|
||||
|
5
actix-ioframe/CHANGES.md
Normal file
5
actix-ioframe/CHANGES.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0] - 2019-07-17
|
||||
|
||||
* Initial release
|
35
actix-ioframe/Cargo.toml
Normal file
35
actix-ioframe/Cargo.toml
Normal file
@@ -0,0 +1,35 @@
|
||||
[package]
|
||||
name = "actix-ioframe"
|
||||
version = "0.1.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix framed service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-ioframed/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "actix_ioframe"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.4.1"
|
||||
actix-codec = "0.1.2"
|
||||
bytes = "0.4"
|
||||
either = "1.5.2"
|
||||
futures = "0.1.25"
|
||||
tokio-current-thread = "0.1.4"
|
||||
log = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2.2"
|
||||
actix-connect = "0.2.0"
|
||||
actix-test-server = "0.2.2"
|
||||
actix-server-config = "0.1.1"
|
||||
tokio-tcp = "0.1"
|
||||
tokio-timer = "0.2"
|
1
actix-ioframe/LICENSE-APACHE
Symbolic link
1
actix-ioframe/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-ioframe/LICENSE-MIT
Symbolic link
1
actix-ioframe/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
35
actix-ioframe/src/cell.rs
Normal file
35
actix-ioframe/src/cell.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
//! Custom cell impl
|
||||
|
||||
use std::cell::UnsafeCell;
|
||||
use std::fmt;
|
||||
use std::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 fn new(inner: T) -> Self {
|
||||
Self {
|
||||
inner: Rc::new(UnsafeCell::new(inner)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn get_mut(&mut self) -> &mut T {
|
||||
&mut *self.inner.as_ref().get()
|
||||
}
|
||||
}
|
110
actix-ioframe/src/connect.rs
Normal file
110
actix-ioframe/src/connect.rs
Normal file
@@ -0,0 +1,110 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||
use futures::unsync::mpsc;
|
||||
|
||||
use crate::dispatcher::FramedMessage;
|
||||
use crate::sink::Sink;
|
||||
|
||||
pub struct Connect<Io, St = (), Codec = ()> {
|
||||
io: Io,
|
||||
_t: PhantomData<(St, Codec)>,
|
||||
}
|
||||
|
||||
impl<Io> Connect<Io>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
{
|
||||
pub(crate) fn new(io: Io) -> Self {
|
||||
Self {
|
||||
io,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn codec<Codec>(self, codec: Codec) -> ConnectResult<Io, (), Codec>
|
||||
where
|
||||
Codec: Encoder + Decoder,
|
||||
{
|
||||
let (tx, rx) = mpsc::unbounded();
|
||||
let sink = Sink::new(tx);
|
||||
|
||||
ConnectResult {
|
||||
state: (),
|
||||
framed: Framed::new(self.io, codec),
|
||||
rx,
|
||||
sink,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ConnectResult<Io, St, Codec: Encoder + Decoder> {
|
||||
pub(crate) state: St,
|
||||
pub(crate) framed: Framed<Io, Codec>,
|
||||
pub(crate) rx: mpsc::UnboundedReceiver<FramedMessage<<Codec as Encoder>::Item>>,
|
||||
pub(crate) sink: Sink<<Codec as Encoder>::Item>,
|
||||
}
|
||||
|
||||
impl<Io, St, Codec: Encoder + Decoder> ConnectResult<Io, St, Codec> {
|
||||
#[inline]
|
||||
pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item> {
|
||||
&self.sink
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_ref(&self) -> &Io {
|
||||
self.framed.get_ref()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_mut(&mut self) -> &mut Io {
|
||||
self.framed.get_mut()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn state<S>(self, state: S) -> ConnectResult<Io, S, Codec> {
|
||||
ConnectResult {
|
||||
state,
|
||||
framed: self.framed,
|
||||
rx: self.rx,
|
||||
sink: self.sink,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Io, St, Codec> futures::Stream for ConnectResult<Io, St, Codec>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
Codec: Encoder + Decoder,
|
||||
{
|
||||
type Item = <Codec as Decoder>::Item;
|
||||
type Error = <Codec as Decoder>::Error;
|
||||
|
||||
fn poll(&mut self) -> futures::Poll<Option<Self::Item>, Self::Error> {
|
||||
self.framed.poll()
|
||||
}
|
||||
}
|
||||
|
||||
impl<Io, St, Codec> futures::Sink for ConnectResult<Io, St, Codec>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
Codec: Encoder + Decoder,
|
||||
{
|
||||
type SinkItem = <Codec as Encoder>::Item;
|
||||
type SinkError = <Codec as Encoder>::Error;
|
||||
|
||||
fn start_send(
|
||||
&mut self,
|
||||
item: Self::SinkItem,
|
||||
) -> futures::StartSend<Self::SinkItem, Self::SinkError> {
|
||||
self.framed.start_send(item)
|
||||
}
|
||||
|
||||
fn poll_complete(&mut self) -> futures::Poll<(), Self::SinkError> {
|
||||
self.framed.poll_complete()
|
||||
}
|
||||
|
||||
fn close(&mut self) -> futures::Poll<(), Self::SinkError> {
|
||||
self.framed.close()
|
||||
}
|
||||
}
|
325
actix-ioframe/src/dispatcher.rs
Normal file
325
actix-ioframe/src/dispatcher.rs
Normal file
@@ -0,0 +1,325 @@
|
||||
//! Framed dispatcher service and related utilities
|
||||
use std::collections::VecDeque;
|
||||
use std::mem;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||
use actix_service::{IntoService, Service};
|
||||
use futures::task::AtomicTask;
|
||||
use futures::unsync::{mpsc, oneshot};
|
||||
use futures::{Async, Future, Poll, Sink as FutureSink, Stream};
|
||||
use log::debug;
|
||||
|
||||
use crate::cell::Cell;
|
||||
use crate::error::ServiceError;
|
||||
use crate::item::Item;
|
||||
use crate::sink::Sink;
|
||||
use crate::state::State;
|
||||
|
||||
type Request<S, U> = Item<S, U>;
|
||||
type Response<U> = <U as Encoder>::Item;
|
||||
|
||||
pub(crate) enum FramedMessage<T> {
|
||||
Message(T),
|
||||
Close,
|
||||
WaitClose(oneshot::Sender<()>),
|
||||
}
|
||||
|
||||
/// FramedTransport - is a future that reads frames from Framed object
|
||||
/// and pass then to the service.
|
||||
pub(crate) struct FramedDispatcher<St, S, T, U>
|
||||
where
|
||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
||||
S::Error: 'static,
|
||||
S::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Encoder + Decoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
service: S,
|
||||
sink: Sink<<U as Encoder>::Item>,
|
||||
state: State<St>,
|
||||
dispatch_state: FramedState<S, U>,
|
||||
framed: Framed<T, U>,
|
||||
rx: Option<mpsc::UnboundedReceiver<FramedMessage<<U as Encoder>::Item>>>,
|
||||
inner: Cell<FramedDispatcherInner<<U as Encoder>::Item, S::Error>>,
|
||||
disconnect: Option<Rc<Fn(&mut St, bool)>>,
|
||||
}
|
||||
|
||||
impl<St, S, T, U> FramedDispatcher<St, S, T, U>
|
||||
where
|
||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
||||
S::Error: 'static,
|
||||
S::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
pub(crate) fn new<F: IntoService<S>>(
|
||||
framed: Framed<T, U>,
|
||||
state: State<St>,
|
||||
service: F,
|
||||
rx: mpsc::UnboundedReceiver<FramedMessage<<U as Encoder>::Item>>,
|
||||
sink: Sink<<U as Encoder>::Item>,
|
||||
disconnect: Option<Rc<Fn(&mut St, bool)>>,
|
||||
) -> Self {
|
||||
FramedDispatcher {
|
||||
framed,
|
||||
state,
|
||||
sink,
|
||||
disconnect,
|
||||
rx: Some(rx),
|
||||
service: service.into_service(),
|
||||
dispatch_state: FramedState::Processing,
|
||||
inner: Cell::new(FramedDispatcherInner {
|
||||
buf: VecDeque::new(),
|
||||
task: AtomicTask::new(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum FramedState<S: Service, U: Encoder + Decoder> {
|
||||
Processing,
|
||||
Error(ServiceError<S::Error, U>),
|
||||
FramedError(ServiceError<S::Error, U>),
|
||||
FlushAndStop(Vec<oneshot::Sender<()>>),
|
||||
Stopping,
|
||||
}
|
||||
|
||||
impl<S: Service, U: Encoder + Decoder> FramedState<S, U> {
|
||||
fn stop(&mut self, tx: Option<oneshot::Sender<()>>) {
|
||||
match self {
|
||||
FramedState::FlushAndStop(ref mut vec) => {
|
||||
if let Some(tx) = tx {
|
||||
vec.push(tx)
|
||||
}
|
||||
}
|
||||
FramedState::Processing => {
|
||||
*self = FramedState::FlushAndStop(if let Some(tx) = tx {
|
||||
vec![tx]
|
||||
} else {
|
||||
Vec::new()
|
||||
})
|
||||
}
|
||||
FramedState::Error(_) | FramedState::FramedError(_) | FramedState::Stopping => {
|
||||
if let Some(tx) = tx {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FramedDispatcherInner<I, E> {
|
||||
buf: VecDeque<Result<I, E>>,
|
||||
task: AtomicTask,
|
||||
}
|
||||
|
||||
impl<St, S, T, U> FramedDispatcher<St, S, T, U>
|
||||
where
|
||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
||||
S::Error: 'static,
|
||||
S::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
fn disconnect(&mut self, error: bool) {
|
||||
if let Some(ref disconnect) = self.disconnect {
|
||||
(&*disconnect)(&mut *self.state.get_mut(), error);
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_read(&mut self) -> bool {
|
||||
loop {
|
||||
match self.service.poll_ready() {
|
||||
Ok(Async::Ready(_)) => {
|
||||
let item = match self.framed.poll() {
|
||||
Ok(Async::Ready(Some(el))) => el,
|
||||
Err(err) => {
|
||||
self.dispatch_state =
|
||||
FramedState::FramedError(ServiceError::Decoder(err));
|
||||
return true;
|
||||
}
|
||||
Ok(Async::NotReady) => return false,
|
||||
Ok(Async::Ready(None)) => {
|
||||
self.dispatch_state = FramedState::Stopping;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
let mut cell = self.inner.clone();
|
||||
unsafe { cell.get_mut().task.register() };
|
||||
tokio_current_thread::spawn(
|
||||
self.service
|
||||
.call(Item::new(self.state.clone(), self.sink.clone(), item))
|
||||
.then(move |item| {
|
||||
let item = match item {
|
||||
Ok(Some(item)) => Ok(item),
|
||||
Ok(None) => return Ok(()),
|
||||
Err(err) => Err(err),
|
||||
};
|
||||
unsafe {
|
||||
let inner = cell.get_mut();
|
||||
inner.buf.push_back(item);
|
||||
inner.task.notify();
|
||||
}
|
||||
Ok(())
|
||||
}),
|
||||
);
|
||||
}
|
||||
Ok(Async::NotReady) => return false,
|
||||
Err(err) => {
|
||||
self.dispatch_state = FramedState::Error(ServiceError::Service(err));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// write to framed object
|
||||
fn poll_write(&mut self) -> bool {
|
||||
let inner = unsafe { self.inner.get_mut() };
|
||||
let mut rx_done = self.rx.is_none();
|
||||
let mut buf_empty = inner.buf.is_empty();
|
||||
loop {
|
||||
while !self.framed.is_write_buf_full() {
|
||||
if !buf_empty {
|
||||
match inner.buf.pop_front().unwrap() {
|
||||
Ok(msg) => {
|
||||
if let Err(err) = self.framed.force_send(msg) {
|
||||
self.dispatch_state =
|
||||
FramedState::FramedError(ServiceError::Encoder(err));
|
||||
return true;
|
||||
}
|
||||
buf_empty = inner.buf.is_empty();
|
||||
}
|
||||
Err(err) => {
|
||||
self.dispatch_state =
|
||||
FramedState::Error(ServiceError::Service(err));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !rx_done && self.rx.is_some() {
|
||||
match self.rx.as_mut().unwrap().poll() {
|
||||
Ok(Async::Ready(Some(FramedMessage::Message(msg)))) => {
|
||||
if let Err(err) = self.framed.force_send(msg) {
|
||||
self.dispatch_state =
|
||||
FramedState::FramedError(ServiceError::Encoder(err));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Ok(Async::Ready(Some(FramedMessage::Close))) => {
|
||||
self.dispatch_state.stop(None);
|
||||
return true;
|
||||
}
|
||||
Ok(Async::Ready(Some(FramedMessage::WaitClose(tx)))) => {
|
||||
self.dispatch_state.stop(Some(tx));
|
||||
return true;
|
||||
}
|
||||
Ok(Async::Ready(None)) => {
|
||||
rx_done = true;
|
||||
let _ = self.rx.take();
|
||||
}
|
||||
Ok(Async::NotReady) => rx_done = true,
|
||||
Err(_e) => {
|
||||
rx_done = true;
|
||||
let _ = self.rx.take();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if rx_done && buf_empty {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !self.framed.is_write_buf_empty() {
|
||||
match self.framed.poll_complete() {
|
||||
Ok(Async::NotReady) => break,
|
||||
Err(err) => {
|
||||
debug!("Error sending data: {:?}", err);
|
||||
self.dispatch_state =
|
||||
FramedState::FramedError(ServiceError::Encoder(err));
|
||||
return true;
|
||||
}
|
||||
Ok(Async::Ready(_)) => (),
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl<St, S, T, U> Future for FramedDispatcher<St, S, T, U>
|
||||
where
|
||||
S: Service<Request = Request<St, U>, Response = Option<Response<U>>>,
|
||||
S::Error: 'static,
|
||||
S::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
type Item = ();
|
||||
type Error = ServiceError<S::Error, U>;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match mem::replace(&mut self.dispatch_state, FramedState::Processing) {
|
||||
FramedState::Processing => {
|
||||
if self.poll_read() || self.poll_write() {
|
||||
self.poll()
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
FramedState::Error(err) => {
|
||||
if self.framed.is_write_buf_empty()
|
||||
|| (self.poll_write() || self.framed.is_write_buf_empty())
|
||||
{
|
||||
self.disconnect(true);
|
||||
Err(err)
|
||||
} else {
|
||||
self.dispatch_state = FramedState::Error(err);
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
FramedState::FlushAndStop(mut vec) => {
|
||||
if !self.framed.is_write_buf_empty() {
|
||||
match self.framed.poll_complete() {
|
||||
Err(err) => {
|
||||
debug!("Error sending data: {:?}", err);
|
||||
}
|
||||
Ok(Async::NotReady) => {
|
||||
self.dispatch_state = FramedState::FlushAndStop(vec);
|
||||
return Ok(Async::NotReady);
|
||||
}
|
||||
Ok(Async::Ready(_)) => (),
|
||||
}
|
||||
};
|
||||
for tx in vec.drain(..) {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
self.disconnect(false);
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
FramedState::FramedError(err) => {
|
||||
self.disconnect(true);
|
||||
Err(err)
|
||||
}
|
||||
FramedState::Stopping => {
|
||||
self.disconnect(false);
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
49
actix-ioframe/src/error.rs
Normal file
49
actix-ioframe/src/error.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use std::fmt;
|
||||
|
||||
use actix_codec::{Decoder, Encoder};
|
||||
|
||||
/// Framed service errors
|
||||
pub enum ServiceError<E, U: Encoder + Decoder> {
|
||||
/// Inner service error
|
||||
Service(E),
|
||||
/// Encoder parse error
|
||||
Encoder(<U as Encoder>::Error),
|
||||
/// Decoder parse error
|
||||
Decoder(<U as Decoder>::Error),
|
||||
}
|
||||
|
||||
impl<E, U: Encoder + Decoder> From<E> for ServiceError<E, U> {
|
||||
fn from(err: E) -> Self {
|
||||
ServiceError::Service(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, U: Encoder + Decoder> fmt::Debug for ServiceError<E, U>
|
||||
where
|
||||
E: fmt::Debug,
|
||||
<U as Encoder>::Error: fmt::Debug,
|
||||
<U as Decoder>::Error: fmt::Debug,
|
||||
{
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
ServiceError::Service(ref e) => write!(fmt, "ServiceError::Service({:?})", e),
|
||||
ServiceError::Encoder(ref e) => write!(fmt, "ServiceError::Encoder({:?})", e),
|
||||
ServiceError::Decoder(ref e) => write!(fmt, "ServiceError::Encoder({:?})", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E, U: Encoder + Decoder> fmt::Display for ServiceError<E, U>
|
||||
where
|
||||
E: fmt::Display,
|
||||
<U as Encoder>::Error: fmt::Debug,
|
||||
<U as Decoder>::Error: fmt::Debug,
|
||||
{
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
match *self {
|
||||
ServiceError::Service(ref e) => write!(fmt, "{}", e),
|
||||
ServiceError::Encoder(ref e) => write!(fmt, "{:?}", e),
|
||||
ServiceError::Decoder(ref e) => write!(fmt, "{:?}", e),
|
||||
}
|
||||
}
|
||||
}
|
90
actix-ioframe/src/item.rs
Normal file
90
actix-ioframe/src/item.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
use std::cell::{Ref, RefMut};
|
||||
use std::fmt;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
use actix_codec::{Decoder, Encoder};
|
||||
|
||||
use crate::sink::Sink;
|
||||
use crate::state::State;
|
||||
|
||||
pub struct Item<St, Codec: Encoder + Decoder> {
|
||||
state: State<St>,
|
||||
sink: Sink<<Codec as Encoder>::Item>,
|
||||
item: <Codec as Decoder>::Item,
|
||||
}
|
||||
|
||||
impl<St, Codec> Item<St, Codec>
|
||||
where
|
||||
Codec: Encoder + Decoder,
|
||||
{
|
||||
pub(crate) fn new(
|
||||
state: State<St>,
|
||||
sink: Sink<<Codec as Encoder>::Item>,
|
||||
item: <Codec as Decoder>::Item,
|
||||
) -> Self {
|
||||
Item { state, sink, item }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn state(&self) -> Ref<St> {
|
||||
self.state.get_ref()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn state_mut(&mut self) -> RefMut<St> {
|
||||
self.state.get_mut()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn sink(&self) -> &Sink<<Codec as Encoder>::Item> {
|
||||
&self.sink
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn into_inner(self) -> <Codec as Decoder>::Item {
|
||||
self.item
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn into_parts(
|
||||
self,
|
||||
) -> (
|
||||
State<St>,
|
||||
Sink<<Codec as Encoder>::Item>,
|
||||
<Codec as Decoder>::Item,
|
||||
) {
|
||||
(self.state, self.sink, self.item)
|
||||
}
|
||||
}
|
||||
|
||||
impl<St, Codec> Deref for Item<St, Codec>
|
||||
where
|
||||
Codec: Encoder + Decoder,
|
||||
{
|
||||
type Target = <Codec as Decoder>::Item;
|
||||
|
||||
#[inline]
|
||||
fn deref(&self) -> &<Codec as Decoder>::Item {
|
||||
&self.item
|
||||
}
|
||||
}
|
||||
|
||||
impl<St, Codec> DerefMut for Item<St, Codec>
|
||||
where
|
||||
Codec: Encoder + Decoder,
|
||||
{
|
||||
#[inline]
|
||||
fn deref_mut(&mut self) -> &mut <Codec as Decoder>::Item {
|
||||
&mut self.item
|
||||
}
|
||||
}
|
||||
|
||||
impl<St, Codec> fmt::Debug for Item<St, Codec>
|
||||
where
|
||||
Codec: Encoder + Decoder,
|
||||
<Codec as Decoder>::Item: fmt::Debug,
|
||||
{
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.debug_tuple("FramedItem").field(&self.item).finish()
|
||||
}
|
||||
}
|
15
actix-ioframe/src/lib.rs
Normal file
15
actix-ioframe/src/lib.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
mod cell;
|
||||
mod connect;
|
||||
mod dispatcher;
|
||||
mod error;
|
||||
mod item;
|
||||
mod service;
|
||||
mod sink;
|
||||
mod state;
|
||||
|
||||
pub use self::connect::{Connect, ConnectResult};
|
||||
pub use self::error::ServiceError;
|
||||
pub use self::item::Item;
|
||||
pub use self::service::{Builder, NewServiceBuilder, ServiceBuilder};
|
||||
pub use self::sink::Sink;
|
||||
pub use self::state::State;
|
363
actix-ioframe/src/service.rs
Normal file
363
actix-ioframe/src/service.rs
Normal file
@@ -0,0 +1,363 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder};
|
||||
use actix_service::{IntoNewService, IntoService, NewService, Service};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::connect::{Connect, ConnectResult};
|
||||
use crate::dispatcher::FramedDispatcher;
|
||||
use crate::error::ServiceError;
|
||||
use crate::item::Item;
|
||||
use crate::state::State;
|
||||
|
||||
type RequestItem<S, U> = Item<S, U>;
|
||||
type ResponseItem<U> = Option<<U as Encoder>::Item>;
|
||||
|
||||
/// Service builder - structure that follows the builder pattern
|
||||
/// for building instances for framed services.
|
||||
pub struct Builder<St, Codec>(PhantomData<(St, Codec)>);
|
||||
|
||||
impl<St, Codec> Builder<St, Codec> {
|
||||
pub fn new() -> Builder<St, Codec> {
|
||||
Builder(PhantomData)
|
||||
}
|
||||
|
||||
/// Construct framed handler service with specified connect service
|
||||
pub fn service<Io, C, F>(self, connect: F) -> ServiceBuilder<St, C, Io, Codec>
|
||||
where
|
||||
F: IntoService<C>,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
Codec: Decoder + Encoder,
|
||||
{
|
||||
ServiceBuilder {
|
||||
connect: connect.into_service(),
|
||||
disconnect: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct framed handler new service with specified connect service
|
||||
pub fn factory<Io, C, F>(self, connect: F) -> NewServiceBuilder<St, C, Io, Codec>
|
||||
where
|
||||
F: IntoNewService<C>,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
C: NewService<
|
||||
Config = (),
|
||||
Request = Connect<Io>,
|
||||
Response = ConnectResult<Io, St, Codec>,
|
||||
>,
|
||||
C::Error: 'static,
|
||||
C::Future: 'static,
|
||||
Codec: Decoder + Encoder,
|
||||
{
|
||||
NewServiceBuilder {
|
||||
connect: connect.into_new_service(),
|
||||
disconnect: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ServiceBuilder<St, C, Io, Codec> {
|
||||
connect: C,
|
||||
disconnect: Option<Rc<Fn(&mut St, bool)>>,
|
||||
_t: PhantomData<(St, Io, Codec)>,
|
||||
}
|
||||
|
||||
impl<St, C, Io, Codec> ServiceBuilder<St, C, Io, Codec>
|
||||
where
|
||||
St: 'static,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
Codec: Decoder + Encoder,
|
||||
<Codec as Encoder>::Item: 'static,
|
||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
/// Callback to execute on disconnect
|
||||
///
|
||||
/// Second parameter indicates error occured during disconnect.
|
||||
pub fn disconnect<F, Out>(mut self, disconnect: F) -> Self
|
||||
where
|
||||
F: Fn(&mut St, bool) + 'static,
|
||||
{
|
||||
self.disconnect = Some(Rc::new(disconnect));
|
||||
self
|
||||
}
|
||||
|
||||
/// Provide stream items handler service and construct service factory.
|
||||
pub fn finish<F, T>(
|
||||
self,
|
||||
service: F,
|
||||
) -> impl Service<Request = Io, Response = (), Error = ServiceError<C::Error, Codec>>
|
||||
where
|
||||
F: IntoNewService<T>,
|
||||
T: NewService<
|
||||
Config = St,
|
||||
Request = RequestItem<St, Codec>,
|
||||
Response = ResponseItem<Codec>,
|
||||
Error = C::Error,
|
||||
InitError = C::Error,
|
||||
> + 'static,
|
||||
{
|
||||
FramedServiceImpl {
|
||||
connect: self.connect,
|
||||
handler: Rc::new(service.into_new_service()),
|
||||
disconnect: self.disconnect.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NewServiceBuilder<St, C, Io, Codec> {
|
||||
connect: C,
|
||||
disconnect: Option<Rc<Fn(&mut St, bool)>>,
|
||||
_t: PhantomData<(St, Io, Codec)>,
|
||||
}
|
||||
|
||||
impl<St, C, Io, Codec> NewServiceBuilder<St, C, Io, Codec>
|
||||
where
|
||||
St: 'static,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
C: NewService<Config = (), Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
C::Future: 'static,
|
||||
Codec: Decoder + Encoder,
|
||||
<Codec as Encoder>::Item: 'static,
|
||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
/// Callback to execute on disconnect
|
||||
///
|
||||
/// Second parameter indicates error occured during disconnect.
|
||||
pub fn disconnect<F>(mut self, disconnect: F) -> Self
|
||||
where
|
||||
F: Fn(&mut St, bool) + 'static,
|
||||
{
|
||||
self.disconnect = Some(Rc::new(disconnect));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn finish<F, T, Cfg>(
|
||||
self,
|
||||
service: F,
|
||||
) -> impl NewService<
|
||||
Config = Cfg,
|
||||
Request = Io,
|
||||
Response = (),
|
||||
Error = ServiceError<C::Error, Codec>,
|
||||
>
|
||||
where
|
||||
F: IntoNewService<T>,
|
||||
T: NewService<
|
||||
Config = St,
|
||||
Request = RequestItem<St, Codec>,
|
||||
Response = ResponseItem<Codec>,
|
||||
Error = C::Error,
|
||||
InitError = C::Error,
|
||||
> + 'static,
|
||||
{
|
||||
FramedService {
|
||||
connect: self.connect,
|
||||
handler: Rc::new(service.into_new_service()),
|
||||
disconnect: self.disconnect,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct FramedService<St, C, T, Io, Codec, Cfg> {
|
||||
connect: C,
|
||||
handler: Rc<T>,
|
||||
disconnect: Option<Rc<Fn(&mut St, bool)>>,
|
||||
_t: PhantomData<(St, Io, Codec, Cfg)>,
|
||||
}
|
||||
|
||||
impl<St, C, T, Io, Codec, Cfg> NewService for FramedService<St, C, T, Io, Codec, Cfg>
|
||||
where
|
||||
St: 'static,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
C: NewService<Config = (), Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
C::Future: 'static,
|
||||
T: NewService<
|
||||
Config = St,
|
||||
Request = RequestItem<St, Codec>,
|
||||
Response = ResponseItem<Codec>,
|
||||
Error = C::Error,
|
||||
InitError = C::Error,
|
||||
> + 'static,
|
||||
Codec: Decoder + Encoder,
|
||||
<Codec as Encoder>::Item: 'static,
|
||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
type Config = Cfg;
|
||||
type Request = Io;
|
||||
type Response = ();
|
||||
type Error = ServiceError<C::Error, Codec>;
|
||||
type InitError = C::InitError;
|
||||
type Service = FramedServiceImpl<St, C::Service, T, Io, Codec>;
|
||||
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
fn new_service(&self, _: &Cfg) -> Self::Future {
|
||||
let handler = self.handler.clone();
|
||||
let disconnect = self.disconnect.clone();
|
||||
|
||||
// create connect service and then create service impl
|
||||
Box::new(
|
||||
self.connect
|
||||
.new_service(&())
|
||||
.map(move |connect| FramedServiceImpl {
|
||||
connect,
|
||||
handler,
|
||||
disconnect,
|
||||
_t: PhantomData,
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FramedServiceImpl<St, C, T, Io, Codec> {
|
||||
connect: C,
|
||||
handler: Rc<T>,
|
||||
disconnect: Option<Rc<Fn(&mut St, bool)>>,
|
||||
_t: PhantomData<(St, Io, Codec)>,
|
||||
}
|
||||
|
||||
impl<St, C, T, Io, Codec> Service for FramedServiceImpl<St, C, T, Io, Codec>
|
||||
where
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
T: NewService<
|
||||
Config = St,
|
||||
Request = RequestItem<St, Codec>,
|
||||
Response = ResponseItem<Codec>,
|
||||
Error = C::Error,
|
||||
InitError = C::Error,
|
||||
>,
|
||||
<<T as NewService>::Service as Service>::Future: 'static,
|
||||
Codec: Decoder + Encoder,
|
||||
<Codec as Encoder>::Item: 'static,
|
||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
type Request = Io;
|
||||
type Response = ();
|
||||
type Error = ServiceError<C::Error, Codec>;
|
||||
type Future = FramedServiceImplResponse<St, Io, Codec, C, T>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.connect.poll_ready().map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Io) -> Self::Future {
|
||||
FramedServiceImplResponse {
|
||||
inner: FramedServiceImplResponseInner::Connect(
|
||||
self.connect.call(Connect::new(req)),
|
||||
self.handler.clone(),
|
||||
),
|
||||
disconnect: self.disconnect.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FramedServiceImplResponse<St, Io, Codec, C, T>
|
||||
where
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
T: NewService<
|
||||
Config = St,
|
||||
Request = RequestItem<St, Codec>,
|
||||
Response = ResponseItem<Codec>,
|
||||
Error = C::Error,
|
||||
InitError = C::Error,
|
||||
>,
|
||||
<<T as NewService>::Service as Service>::Future: 'static,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
Codec: Encoder + Decoder,
|
||||
<Codec as Encoder>::Item: 'static,
|
||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
inner: FramedServiceImplResponseInner<St, Io, Codec, C, T>,
|
||||
disconnect: Option<Rc<Fn(&mut St, bool)>>,
|
||||
}
|
||||
|
||||
enum FramedServiceImplResponseInner<St, Io, Codec, C, T>
|
||||
where
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
T: NewService<
|
||||
Config = St,
|
||||
Request = RequestItem<St, Codec>,
|
||||
Response = ResponseItem<Codec>,
|
||||
Error = C::Error,
|
||||
InitError = C::Error,
|
||||
>,
|
||||
<<T as NewService>::Service as Service>::Future: 'static,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
Codec: Encoder + Decoder,
|
||||
<Codec as Encoder>::Item: 'static,
|
||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
Connect(C::Future, Rc<T>),
|
||||
Handler(T::Future, Option<ConnectResult<Io, St, Codec>>),
|
||||
Dispatcher(FramedDispatcher<St, T::Service, Io, Codec>),
|
||||
}
|
||||
|
||||
impl<St, Io, Codec, C, T> Future for FramedServiceImplResponse<St, Io, Codec, C, T>
|
||||
where
|
||||
C: Service<Request = Connect<Io>, Response = ConnectResult<Io, St, Codec>>,
|
||||
C::Error: 'static,
|
||||
T: NewService<
|
||||
Config = St,
|
||||
Request = RequestItem<St, Codec>,
|
||||
Response = ResponseItem<Codec>,
|
||||
Error = C::Error,
|
||||
InitError = C::Error,
|
||||
>,
|
||||
<<T as NewService>::Service as Service>::Future: 'static,
|
||||
Io: AsyncRead + AsyncWrite,
|
||||
Codec: Encoder + Decoder,
|
||||
<Codec as Encoder>::Item: 'static,
|
||||
<Codec as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
type Item = ();
|
||||
type Error = ServiceError<C::Error, Codec>;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.inner {
|
||||
FramedServiceImplResponseInner::Connect(ref mut fut, ref handler) => {
|
||||
match fut.poll()? {
|
||||
Async::Ready(res) => {
|
||||
self.inner = FramedServiceImplResponseInner::Handler(
|
||||
handler.new_service(&res.state),
|
||||
Some(res),
|
||||
);
|
||||
self.poll()
|
||||
}
|
||||
Async::NotReady => Ok(Async::NotReady),
|
||||
}
|
||||
}
|
||||
FramedServiceImplResponseInner::Handler(ref mut fut, ref mut res) => {
|
||||
match fut.poll()? {
|
||||
Async::Ready(handler) => {
|
||||
let res = res.take().unwrap();
|
||||
self.inner =
|
||||
FramedServiceImplResponseInner::Dispatcher(FramedDispatcher::new(
|
||||
res.framed,
|
||||
State::new(res.state),
|
||||
handler,
|
||||
res.rx,
|
||||
res.sink,
|
||||
self.disconnect.clone(),
|
||||
));
|
||||
self.poll()
|
||||
}
|
||||
Async::NotReady => Ok(Async::NotReady),
|
||||
}
|
||||
}
|
||||
FramedServiceImplResponseInner::Dispatcher(ref mut fut) => fut.poll(),
|
||||
}
|
||||
}
|
||||
}
|
44
actix-ioframe/src/sink.rs
Normal file
44
actix-ioframe/src/sink.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use std::fmt;
|
||||
|
||||
use futures::unsync::{mpsc, oneshot};
|
||||
use futures::Future;
|
||||
|
||||
use crate::dispatcher::FramedMessage;
|
||||
|
||||
pub struct Sink<T>(mpsc::UnboundedSender<FramedMessage<T>>);
|
||||
|
||||
impl<T> Clone for Sink<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Sink(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Sink<T> {
|
||||
pub(crate) fn new(tx: mpsc::UnboundedSender<FramedMessage<T>>) -> Self {
|
||||
Sink(tx)
|
||||
}
|
||||
|
||||
/// Close connection
|
||||
pub fn close(&self) {
|
||||
let _ = self.0.unbounded_send(FramedMessage::Close);
|
||||
}
|
||||
|
||||
/// Close connection
|
||||
pub fn wait_close(&self) -> impl Future<Item = (), Error = ()> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let _ = self.0.unbounded_send(FramedMessage::WaitClose(tx));
|
||||
|
||||
rx.map_err(|_| ())
|
||||
}
|
||||
|
||||
/// Send item
|
||||
pub fn send(&self, item: T) {
|
||||
let _ = self.0.unbounded_send(FramedMessage::Message(item));
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> fmt::Debug for Sink<T> {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
fmt.debug_struct("Sink").finish()
|
||||
}
|
||||
}
|
30
actix-ioframe/src/state.rs
Normal file
30
actix-ioframe/src/state.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
use std::cell::{Ref, RefCell, RefMut};
|
||||
use std::rc::Rc;
|
||||
|
||||
/// Connection state
|
||||
///
|
||||
/// Connection state is an arbitrary data attached to the each incoming message.
|
||||
#[derive(Debug)]
|
||||
pub struct State<T>(Rc<RefCell<T>>);
|
||||
|
||||
impl<T> State<T> {
|
||||
pub(crate) fn new(st: T) -> Self {
|
||||
State(Rc::new(RefCell::new(st)))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_ref(&self) -> Ref<T> {
|
||||
self.0.borrow()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_mut(&mut self) -> RefMut<T> {
|
||||
self.0.borrow_mut()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for State<T> {
|
||||
fn clone(&self) -> Self {
|
||||
State(self.0.clone())
|
||||
}
|
||||
}
|
60
actix-ioframe/tests/test_server.rs
Normal file
60
actix-ioframe/tests/test_server.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use actix_codec::BytesCodec;
|
||||
use actix_server_config::Io;
|
||||
use actix_service::{new_apply_fn, Service};
|
||||
use actix_test_server::TestServer;
|
||||
use futures::Future;
|
||||
use tokio_tcp::TcpStream;
|
||||
use tokio_timer::sleep;
|
||||
|
||||
use actix_ioframe::{Builder, Connect};
|
||||
|
||||
struct State;
|
||||
|
||||
#[test]
|
||||
fn test_disconnect() -> std::io::Result<()> {
|
||||
let disconnect = Arc::new(AtomicBool::new(false));
|
||||
let disconnect1 = disconnect.clone();
|
||||
|
||||
let mut srv = TestServer::with(move || {
|
||||
let disconnect1 = disconnect1.clone();
|
||||
|
||||
new_apply_fn(
|
||||
Builder::new()
|
||||
.factory(|conn: Connect<_>| Ok(conn.codec(BytesCodec).state(State)))
|
||||
.disconnect(move |_, _| {
|
||||
disconnect1.store(true, Ordering::Relaxed);
|
||||
})
|
||||
.finish(|_t| Ok(None)),
|
||||
|io: Io<TcpStream>, srv| srv.call(io.into_parts().0),
|
||||
)
|
||||
});
|
||||
|
||||
let mut client = Builder::new()
|
||||
.service(|conn: Connect<_>| {
|
||||
let conn = conn.codec(BytesCodec).state(State);
|
||||
conn.sink().close();
|
||||
Ok(conn)
|
||||
})
|
||||
.finish(|_t| Ok(None));
|
||||
|
||||
let conn = srv
|
||||
.block_on(
|
||||
actix_connect::default_connector()
|
||||
.call(actix_connect::Connect::with(String::new(), srv.addr())),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
srv.block_on(client.call(conn.into_parts().0)).unwrap();
|
||||
let _ = srv.block_on(
|
||||
sleep(Duration::from_millis(100))
|
||||
.map(|_| ())
|
||||
.map_err(|_| ()),
|
||||
);
|
||||
assert!(disconnect.load(Ordering::Relaxed));
|
||||
|
||||
Ok(())
|
||||
}
|
@@ -1,5 +1,26 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.4] - 2019-07-17
|
||||
|
||||
### Changed
|
||||
|
||||
* Avoid a copy of the Future when initializing the Box. #29
|
||||
|
||||
|
||||
## [0.2.3] - 2019-06-22
|
||||
|
||||
### Added
|
||||
|
||||
* Allow to start System using exsiting CurrentThread Handle #22
|
||||
|
||||
|
||||
## [0.2.2] - 2019-03-28
|
||||
|
||||
### Changed
|
||||
|
||||
* Moved `blocking` module to `actix-threadpool` crate
|
||||
|
||||
|
||||
## [0.2.1] - 2019-03-11
|
||||
|
||||
### Added
|
||||
@@ -10,12 +31,14 @@
|
||||
|
||||
* Arbiter::exec - execute fn on the arbiter's thread and wait result
|
||||
|
||||
|
||||
## [0.2.0] - 2019-03-06
|
||||
|
||||
* `run` method returns `io::Result<()>`
|
||||
|
||||
* Removed `Handle`
|
||||
|
||||
|
||||
## [0.1.0] - 2018-12-09
|
||||
|
||||
* Initial release
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-rt"
|
||||
version = "0.2.1"
|
||||
version = "0.2.4"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix runtime"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -11,22 +11,17 @@ categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "actix_rt"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
bytes = "0.4"
|
||||
derive_more = "0.14"
|
||||
actix-threadpool = "0.1.1"
|
||||
futures = "0.1.25"
|
||||
parking_lot = "0.7"
|
||||
lazy_static = "1.2"
|
||||
log = "0.4"
|
||||
num_cpus = "1.10"
|
||||
threadpool = "1.7"
|
||||
tokio-current-thread = "0.1"
|
||||
tokio-executor = "0.1.5"
|
||||
tokio-reactor = "0.1.7"
|
||||
tokio-timer = "0.2.8"
|
||||
copyless = "0.1.4"
|
||||
|
1
actix-rt/LICENSE-APACHE
Symbolic link
1
actix-rt/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-rt/LICENSE-MIT
Symbolic link
1
actix-rt/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -11,6 +11,8 @@ use tokio_current_thread::spawn;
|
||||
use crate::builder::Builder;
|
||||
use crate::system::System;
|
||||
|
||||
use copyless::BoxHelper;
|
||||
|
||||
thread_local!(
|
||||
static ADDR: RefCell<Option<Arbiter>> = RefCell::new(None);
|
||||
static RUNNING: Cell<bool> = Cell::new(false);
|
||||
@@ -141,9 +143,9 @@ impl Arbiter {
|
||||
{
|
||||
RUNNING.with(move |cell| {
|
||||
if cell.get() {
|
||||
spawn(Box::new(future));
|
||||
spawn(Box::alloc().init(future));
|
||||
} else {
|
||||
Q.with(move |cell| cell.borrow_mut().push(Box::new(future)));
|
||||
Q.with(move |cell| cell.borrow_mut().push(Box::alloc().init(future)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
@@ -1,11 +1,12 @@
|
||||
use std::borrow::Cow;
|
||||
use std::io;
|
||||
|
||||
use futures::future;
|
||||
use futures::future::{lazy, Future};
|
||||
use futures::sync::mpsc::unbounded;
|
||||
use futures::sync::oneshot::{channel, Receiver};
|
||||
|
||||
use tokio_current_thread::CurrentThread;
|
||||
use tokio_current_thread::{CurrentThread, Handle};
|
||||
use tokio_reactor::Reactor;
|
||||
use tokio_timer::clock::Clock;
|
||||
use tokio_timer::timer::Timer;
|
||||
@@ -69,6 +70,13 @@ impl Builder {
|
||||
self.create_runtime(|| {})
|
||||
}
|
||||
|
||||
/// Create new System that can run asynchronously.
|
||||
///
|
||||
/// This method panics if it cannot start the system arbiter
|
||||
pub(crate) fn build_async(self, executor: Handle) -> AsyncSystemRunner {
|
||||
self.create_async_runtime(executor)
|
||||
}
|
||||
|
||||
/// This function will start tokio runtime and will finish once the
|
||||
/// `System::stop()` message get called.
|
||||
/// Function `f` get called within tokio runtime context.
|
||||
@@ -79,6 +87,21 @@ impl Builder {
|
||||
self.create_runtime(f).run()
|
||||
}
|
||||
|
||||
fn create_async_runtime(self, executor: Handle) -> AsyncSystemRunner {
|
||||
let (stop_tx, stop) = channel();
|
||||
let (sys_sender, sys_receiver) = unbounded();
|
||||
|
||||
let system = System::construct(sys_sender, Arbiter::new_system(), self.stop_on_panic);
|
||||
|
||||
// system arbiter
|
||||
let arb = SystemArbiter::new(stop_tx, sys_receiver);
|
||||
|
||||
// start the system arbiter
|
||||
executor.spawn(arb).expect("could not start system arbiter");
|
||||
|
||||
AsyncSystemRunner { stop, system }
|
||||
}
|
||||
|
||||
fn create_runtime<F>(self, f: F) -> SystemRunner
|
||||
where
|
||||
F: FnOnce() + 'static,
|
||||
@@ -86,8 +109,7 @@ impl Builder {
|
||||
let (stop_tx, stop) = channel();
|
||||
let (sys_sender, sys_receiver) = unbounded();
|
||||
|
||||
let arbiter = Arbiter::new_system();
|
||||
let system = System::construct(sys_sender, arbiter.clone(), self.stop_on_panic);
|
||||
let system = System::construct(sys_sender, Arbiter::new_system(), self.stop_on_panic);
|
||||
|
||||
// system arbiter
|
||||
let arb = SystemArbiter::new(stop_tx, sys_receiver);
|
||||
@@ -128,6 +150,42 @@ impl Builder {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct AsyncSystemRunner {
|
||||
stop: Receiver<i32>,
|
||||
system: System,
|
||||
}
|
||||
|
||||
impl AsyncSystemRunner {
|
||||
/// This function will start event loop and returns a future that
|
||||
/// resolves once the `System::stop()` function is called.
|
||||
pub(crate) fn run_nonblocking(self) -> impl Future<Item = (), Error = io::Error> + Send {
|
||||
let AsyncSystemRunner { stop, .. } = self;
|
||||
|
||||
// run loop
|
||||
future::lazy(|| {
|
||||
Arbiter::run_system();
|
||||
stop.then(|res| match res {
|
||||
Ok(code) => {
|
||||
if code != 0 {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("Non-zero exit code: {}", code),
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)),
|
||||
})
|
||||
.then(|result| {
|
||||
Arbiter::stop_system();
|
||||
result
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper object that runs System's event loop
|
||||
#[must_use = "SystemRunner must be run"]
|
||||
#[derive(Debug)]
|
||||
|
@@ -1,7 +1,6 @@
|
||||
//! A runtime implementation that runs everything on the current thread.
|
||||
|
||||
mod arbiter;
|
||||
pub mod blocking;
|
||||
mod builder;
|
||||
mod runtime;
|
||||
mod system;
|
||||
@@ -11,6 +10,9 @@ pub use self::builder::{Builder, SystemRunner};
|
||||
pub use self::runtime::Runtime;
|
||||
pub use self::system::System;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use actix_threadpool as blocking;
|
||||
|
||||
/// Spawns a future on the current arbiter.
|
||||
///
|
||||
/// # Panics
|
||||
|
@@ -3,6 +3,8 @@ use std::io;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use futures::sync::mpsc::UnboundedSender;
|
||||
use futures::Future;
|
||||
use tokio_current_thread::Handle;
|
||||
|
||||
use crate::arbiter::{Arbiter, SystemCommand};
|
||||
use crate::builder::{Builder, SystemRunner};
|
||||
@@ -55,6 +57,20 @@ impl System {
|
||||
Self::builder().name(name).build()
|
||||
}
|
||||
|
||||
#[allow(clippy::new_ret_no_self)]
|
||||
/// Create new system using provided CurrentThread Handle.
|
||||
///
|
||||
/// This method panics if it can not spawn system arbiter
|
||||
pub fn run_in_executor<T: Into<String>>(
|
||||
name: T,
|
||||
executor: Handle,
|
||||
) -> impl Future<Item = (), Error = io::Error> + Send {
|
||||
Self::builder()
|
||||
.name(name)
|
||||
.build_async(executor)
|
||||
.run_nonblocking()
|
||||
}
|
||||
|
||||
/// Get current running system.
|
||||
pub fn current() -> System {
|
||||
CURRENT.with(|cell| match *cell.borrow() {
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-server-config"
|
||||
version = "0.1.0"
|
||||
version = "0.1.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix server config utils"
|
||||
homepage = "https://actix.rs"
|
||||
@@ -13,5 +13,26 @@ workspace = ".."
|
||||
name = "actix_server_config"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "rust-tls", "uds"]
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
# openssl
|
||||
ssl = ["tokio-openssl"]
|
||||
|
||||
# rustls
|
||||
rust-tls = ["rustls", "tokio-rustls"]
|
||||
|
||||
# unix domain sockets
|
||||
uds = ["tokio-uds"]
|
||||
|
||||
[dependencies]
|
||||
futures = "0.1.25"
|
||||
tokio-io = "0.1.12"
|
||||
tokio-tcp = "0.1"
|
||||
tokio-openssl = { version="0.3.0", optional = true }
|
||||
rustls = { version = "0.15.2", optional = true }
|
||||
tokio-rustls = { version = "0.9.1", optional = true }
|
||||
tokio-uds = { version="0.2.5", optional = true }
|
||||
|
1
actix-server-config/LICENSE-APACHE
Symbolic link
1
actix-server-config/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-server-config/LICENSE-MIT
Symbolic link
1
actix-server-config/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
14
actix-server-config/changes.md
Normal file
14
actix-server-config/changes.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.2] - 2019-07-18
|
||||
|
||||
### Added
|
||||
|
||||
* Add unix domnain sockets support
|
||||
|
||||
|
||||
## [0.1.1] - 2019-04-16
|
||||
|
||||
### Added
|
||||
|
||||
* `IoStream` trait and impls for TcpStream, SslStream and TlsStream
|
@@ -1,7 +1,10 @@
|
||||
use std::cell::Cell;
|
||||
use std::fmt;
|
||||
use std::net::SocketAddr;
|
||||
use std::rc::Rc;
|
||||
use std::{fmt, io, net, time};
|
||||
|
||||
use tokio_io::{AsyncRead, AsyncWrite};
|
||||
use tokio_tcp::TcpStream;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ServerConfig {
|
||||
@@ -92,9 +95,9 @@ impl<T, P> Io<T, P> {
|
||||
/// Return new Io object with new parameter.
|
||||
pub fn set<U>(self, params: U) -> Io<T, U> {
|
||||
Io {
|
||||
params,
|
||||
io: self.io,
|
||||
proto: self.proto,
|
||||
params: params,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,3 +133,109 @@ impl<T: fmt::Debug, P> fmt::Debug for Io<T, P> {
|
||||
write!(f, "Io {{{:?}}}", self.io)
|
||||
}
|
||||
}
|
||||
|
||||
/// Low-level io stream operations
|
||||
pub trait IoStream: AsyncRead + AsyncWrite {
|
||||
/// Returns the socket address of the remote peer of this TCP connection.
|
||||
fn peer_addr(&self) -> Option<SocketAddr> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Sets the value of the TCP_NODELAY option on this socket.
|
||||
fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()>;
|
||||
|
||||
fn set_linger(&mut self, dur: Option<time::Duration>) -> io::Result<()>;
|
||||
|
||||
fn set_keepalive(&mut self, dur: Option<time::Duration>) -> io::Result<()>;
|
||||
}
|
||||
|
||||
impl IoStream for TcpStream {
|
||||
#[inline]
|
||||
fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
TcpStream::peer_addr(self).ok()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()> {
|
||||
TcpStream::set_nodelay(self, nodelay)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_linger(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
TcpStream::set_linger(self, dur)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_keepalive(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
TcpStream::set_keepalive(self, dur)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "ssl"))]
|
||||
impl<T: IoStream> IoStream for tokio_openssl::SslStream<T> {
|
||||
#[inline]
|
||||
fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
self.get_ref().get_ref().peer_addr()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()> {
|
||||
self.get_mut().get_mut().set_nodelay(nodelay)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_linger(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
self.get_mut().get_mut().set_linger(dur)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_keepalive(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
self.get_mut().get_mut().set_keepalive(dur)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "rust-tls"))]
|
||||
impl<T: IoStream> IoStream for tokio_rustls::TlsStream<T, rustls::ServerSession> {
|
||||
#[inline]
|
||||
fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
self.get_ref().0.peer_addr()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()> {
|
||||
self.get_mut().0.set_nodelay(nodelay)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_linger(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
self.get_mut().0.set_linger(dur)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_keepalive(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
||||
self.get_mut().0.set_keepalive(dur)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
impl IoStream for tokio_uds::UnixStream {
|
||||
#[inline]
|
||||
fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
None
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_nodelay(&mut self, _: bool) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_linger(&mut self, _: Option<time::Duration>) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_keepalive(&mut self, _: Option<time::Duration>) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,50 @@
|
||||
# Changes
|
||||
|
||||
## [0.6.0] - 2019-07-18
|
||||
|
||||
### Added
|
||||
|
||||
* Support Unix domain sockets #3
|
||||
|
||||
|
||||
## [0.5.1] - 2019-05-18
|
||||
|
||||
### Changed
|
||||
|
||||
* ServerBuilder::shutdown_timeout() accepts u64
|
||||
|
||||
|
||||
## [0.5.0] - 2019-05-12
|
||||
|
||||
### Added
|
||||
|
||||
* Add `Debug` impl for `SslError`
|
||||
|
||||
* Derive debug for `Server` and `ServerCommand`
|
||||
|
||||
### Changed
|
||||
|
||||
* Upgrade to actix-service 0.4
|
||||
|
||||
|
||||
## [0.4.3] - 2019-04-16
|
||||
|
||||
### Added
|
||||
|
||||
* Re-export `IoStream` trait
|
||||
|
||||
### Changed
|
||||
|
||||
* Deppend on `ssl` and `rust-tls` features from actix-server-config
|
||||
|
||||
|
||||
## [0.4.2] - 2019-03-30
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix SIGINT force shutdown
|
||||
|
||||
|
||||
## [0.4.1] - 2019-03-14
|
||||
|
||||
### Added
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-server"
|
||||
version = "0.4.1"
|
||||
version = "0.6.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix server - General purpose tcp server"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -14,7 +14,7 @@ edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "tls", "rust-tls"]
|
||||
features = ["ssl", "tls", "rust-tls", "uds"]
|
||||
|
||||
[lib]
|
||||
name = "actix_server"
|
||||
@@ -27,20 +27,23 @@ default = []
|
||||
tls = ["native-tls"]
|
||||
|
||||
# openssl
|
||||
ssl = ["openssl", "tokio-openssl"]
|
||||
ssl = ["openssl", "tokio-openssl", "actix-server-config/ssl"]
|
||||
|
||||
# rustls
|
||||
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
|
||||
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots", "actix-server-config/rust-tls"]
|
||||
|
||||
# uds
|
||||
uds = ["mio-uds", "tokio-uds", "actix-server-config/uds"]
|
||||
|
||||
[dependencies]
|
||||
actix-rt = "0.2.1"
|
||||
actix-service = "0.3.4"
|
||||
actix-server-config = "0.1.0"
|
||||
actix-rt = "0.2.2"
|
||||
actix-service = "0.4.1"
|
||||
actix-server-config = "0.1.2"
|
||||
|
||||
log = "0.4"
|
||||
num_cpus = "1.0"
|
||||
|
||||
mio = "^0.6.13"
|
||||
mio = "0.6.19"
|
||||
net2 = "0.2"
|
||||
futures = "0.1"
|
||||
slab = "0.4"
|
||||
@@ -50,6 +53,10 @@ tokio-timer = "0.2.8"
|
||||
tokio-reactor = "0.1"
|
||||
tokio-signal = "0.2"
|
||||
|
||||
# unix domain sockets
|
||||
mio-uds = { version="0.6.7", optional = true }
|
||||
tokio-uds = { version="0.2.5", optional = true }
|
||||
|
||||
# native-tls
|
||||
native-tls = { version="0.2", optional = true }
|
||||
|
||||
@@ -57,13 +64,13 @@ native-tls = { version="0.2", optional = true }
|
||||
openssl = { version="0.10", optional = true }
|
||||
tokio-openssl = { version="0.3", optional = true }
|
||||
|
||||
#rustls
|
||||
rustls = { version = "^0.15", optional = true }
|
||||
tokio-rustls = { version = "^0.9", optional = true }
|
||||
# rustls
|
||||
rustls = { version = "0.15.2", optional = true }
|
||||
tokio-rustls = { version = "0.9.1", optional = true }
|
||||
webpki = { version = "0.19", optional = true }
|
||||
webpki-roots = { version = "0.16", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
bytes = "0.4"
|
||||
actix-codec = "0.1.0"
|
||||
actix-codec = "0.1.2"
|
||||
env_logger = "0.6"
|
||||
|
1
actix-server/LICENSE-APACHE
Symbolic link
1
actix-server/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-server/LICENSE-MIT
Symbolic link
1
actix-server/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -1,17 +1,17 @@
|
||||
use std::sync::mpsc as sync_mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::{io, net, thread};
|
||||
use std::{io, thread};
|
||||
|
||||
use actix_rt::System;
|
||||
use futures::future::{lazy, Future};
|
||||
use log::{error, info};
|
||||
use mio;
|
||||
use slab::Slab;
|
||||
use tokio_timer::Delay;
|
||||
|
||||
use super::server::Server;
|
||||
use super::worker::{Conn, WorkerClient};
|
||||
use super::Token;
|
||||
use crate::server::Server;
|
||||
use crate::socket::{SocketAddr, SocketListener, StdListener};
|
||||
use crate::worker::{Conn, WorkerClient};
|
||||
use crate::Token;
|
||||
|
||||
pub(crate) enum Command {
|
||||
Pause,
|
||||
@@ -21,9 +21,9 @@ pub(crate) enum Command {
|
||||
}
|
||||
|
||||
struct ServerSocketInfo {
|
||||
addr: net::SocketAddr,
|
||||
addr: SocketAddr,
|
||||
token: Token,
|
||||
sock: mio::net::TcpListener,
|
||||
sock: SocketListener,
|
||||
timeout: Option<Instant>,
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ impl AcceptLoop {
|
||||
|
||||
pub(crate) fn start(
|
||||
&mut self,
|
||||
socks: Vec<(Token, net::TcpListener)>,
|
||||
socks: Vec<(Token, StdListener)>,
|
||||
workers: Vec<WorkerClient>,
|
||||
) {
|
||||
let srv = self.srv.take().expect("Can not re-use AcceptInfo");
|
||||
@@ -135,7 +135,7 @@ impl Accept {
|
||||
rx: sync_mpsc::Receiver<Command>,
|
||||
cmd_reg: mio::Registration,
|
||||
notify_reg: mio::Registration,
|
||||
socks: Vec<(Token, net::TcpListener)>,
|
||||
socks: Vec<(Token, StdListener)>,
|
||||
srv: Server,
|
||||
workers: Vec<WorkerClient>,
|
||||
) {
|
||||
@@ -174,7 +174,7 @@ impl Accept {
|
||||
|
||||
fn new(
|
||||
rx: sync_mpsc::Receiver<Command>,
|
||||
socks: Vec<(Token, net::TcpListener)>,
|
||||
socks: Vec<(Token, StdListener)>,
|
||||
workers: Vec<WorkerClient>,
|
||||
srv: Server,
|
||||
) -> Accept {
|
||||
@@ -187,10 +187,9 @@ impl Accept {
|
||||
// Start accept
|
||||
let mut sockets = Slab::new();
|
||||
for (hnd_token, lst) in socks.into_iter() {
|
||||
let addr = lst.local_addr().unwrap();
|
||||
let server = mio::net::TcpListener::from_std(lst)
|
||||
.expect("Can not create mio::net::TcpListener");
|
||||
let addr = lst.local_addr();
|
||||
|
||||
let server = lst.into_listener();
|
||||
let entry = sockets.vacant_entry();
|
||||
let token = entry.key();
|
||||
|
||||
@@ -422,12 +421,13 @@ impl Accept {
|
||||
fn accept(&mut self, token: usize) {
|
||||
loop {
|
||||
let msg = if let Some(info) = self.sockets.get_mut(token) {
|
||||
match info.sock.accept_std() {
|
||||
Ok((io, addr)) => Conn {
|
||||
match info.sock.accept() {
|
||||
Ok(Some((io, addr))) => Conn {
|
||||
io,
|
||||
token: info.token,
|
||||
peer: Some(addr),
|
||||
},
|
||||
Ok(None) => return,
|
||||
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => return,
|
||||
Err(ref e) if connection_error(e) => continue,
|
||||
Err(e) => {
|
||||
|
@@ -9,6 +9,7 @@ use futures::{Async, Future, Poll, Stream};
|
||||
use log::{error, info};
|
||||
use net2::TcpBuilder;
|
||||
use num_cpus;
|
||||
use tokio_tcp::TcpStream;
|
||||
use tokio_timer::sleep;
|
||||
|
||||
use crate::accept::{AcceptLoop, AcceptNotify, Command};
|
||||
@@ -16,6 +17,7 @@ use crate::config::{ConfiguredService, ServiceConfig};
|
||||
use crate::server::{Server, ServerCommand};
|
||||
use crate::services::{InternalServiceFactory, ServiceFactory, StreamNewService};
|
||||
use crate::signals::{Signal, Signals};
|
||||
use crate::socket::StdListener;
|
||||
use crate::worker::{self, Worker, WorkerAvailability, WorkerClient};
|
||||
use crate::{ssl, Token};
|
||||
|
||||
@@ -25,8 +27,8 @@ pub struct ServerBuilder {
|
||||
token: Token,
|
||||
backlog: i32,
|
||||
workers: Vec<(usize, WorkerClient)>,
|
||||
services: Vec<Box<InternalServiceFactory>>,
|
||||
sockets: Vec<(Token, net::TcpListener)>,
|
||||
services: Vec<Box<dyn InternalServiceFactory>>,
|
||||
sockets: Vec<(Token, StdListener)>,
|
||||
accept: AcceptLoop,
|
||||
exit: bool,
|
||||
shutdown_timeout: Duration,
|
||||
@@ -128,8 +130,8 @@ impl ServerBuilder {
|
||||
/// dropped.
|
||||
///
|
||||
/// By default shutdown timeout sets to 30 seconds.
|
||||
pub fn shutdown_timeout(mut self, sec: u16) -> Self {
|
||||
self.shutdown_timeout = Duration::from_secs(u64::from(sec));
|
||||
pub fn shutdown_timeout(mut self, sec: u64) -> Self {
|
||||
self.shutdown_timeout = Duration::from_secs(sec);
|
||||
self
|
||||
}
|
||||
|
||||
@@ -151,7 +153,7 @@ impl ServerBuilder {
|
||||
for (name, lst) in cfg.services {
|
||||
let token = self.token.next();
|
||||
srv.stream(token, name, lst.local_addr()?);
|
||||
self.sockets.push((token, lst));
|
||||
self.sockets.push((token, StdListener::Tcp(lst)));
|
||||
}
|
||||
self.services.push(Box::new(srv));
|
||||
}
|
||||
@@ -163,7 +165,7 @@ impl ServerBuilder {
|
||||
/// Add new service to the server.
|
||||
pub fn bind<F, U, N: AsRef<str>>(mut self, name: N, addr: U, factory: F) -> io::Result<Self>
|
||||
where
|
||||
F: ServiceFactory,
|
||||
F: ServiceFactory<TcpStream>,
|
||||
U: net::ToSocketAddrs,
|
||||
{
|
||||
let sockets = bind_addr(addr, self.backlog)?;
|
||||
@@ -176,11 +178,39 @@ impl ServerBuilder {
|
||||
factory.clone(),
|
||||
lst.local_addr()?,
|
||||
));
|
||||
self.sockets.push((token, lst));
|
||||
self.sockets.push((token, StdListener::Tcp(lst)));
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
/// Add new unix domain service to the server.
|
||||
pub fn bind_uds<F, U, N>(mut self, name: N, addr: U, factory: F) -> io::Result<Self>
|
||||
where
|
||||
F: ServiceFactory<tokio_uds::UnixStream>,
|
||||
N: AsRef<str>,
|
||||
U: AsRef<std::path::Path>,
|
||||
{
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use std::os::unix::net::UnixListener;
|
||||
|
||||
// TODO: need to do something with existing paths
|
||||
let _ = std::fs::remove_file(addr.as_ref());
|
||||
|
||||
let lst = UnixListener::bind(addr)?;
|
||||
|
||||
let token = self.token.next();
|
||||
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
|
||||
self.services.push(StreamNewService::create(
|
||||
name.as_ref().to_string(),
|
||||
token,
|
||||
factory.clone(),
|
||||
addr,
|
||||
));
|
||||
self.sockets.push((token, StdListener::Uds(lst)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Add new service to the server.
|
||||
pub fn listen<F, N: AsRef<str>>(
|
||||
mut self,
|
||||
@@ -189,7 +219,7 @@ impl ServerBuilder {
|
||||
factory: F,
|
||||
) -> io::Result<Self>
|
||||
where
|
||||
F: ServiceFactory,
|
||||
F: ServiceFactory<TcpStream>,
|
||||
{
|
||||
let token = self.token.next();
|
||||
self.services.push(StreamNewService::create(
|
||||
@@ -198,7 +228,7 @@ impl ServerBuilder {
|
||||
factory,
|
||||
lst.local_addr()?,
|
||||
));
|
||||
self.sockets.push((token, lst));
|
||||
self.sockets.push((token, StdListener::Tcp(lst)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
@@ -243,7 +273,7 @@ impl ServerBuilder {
|
||||
|
||||
// start accept thread
|
||||
for sock in &self.sockets {
|
||||
info!("Starting server on {}", sock.1.local_addr().ok().unwrap());
|
||||
info!("Starting server on {}", sock.1);
|
||||
}
|
||||
self.accept
|
||||
.start(mem::replace(&mut self.sockets, Vec::new()), workers);
|
||||
@@ -266,7 +296,7 @@ impl ServerBuilder {
|
||||
let timeout = self.shutdown_timeout;
|
||||
let avail = WorkerAvailability::new(notify);
|
||||
let worker = WorkerClient::new(idx, tx1, tx2, avail.clone());
|
||||
let services: Vec<Box<InternalServiceFactory>> =
|
||||
let services: Vec<Box<dyn InternalServiceFactory>> =
|
||||
self.services.iter().map(|v| v.clone_factory()).collect();
|
||||
|
||||
Arbiter::new().send(lazy(move || {
|
||||
@@ -328,7 +358,7 @@ impl ServerBuilder {
|
||||
self.accept.send(Command::Stop);
|
||||
|
||||
// stop workers
|
||||
if !self.workers.is_empty() {
|
||||
if !self.workers.is_empty() && graceful {
|
||||
spawn(
|
||||
futures_unordered(
|
||||
self.workers
|
||||
|
@@ -17,7 +17,7 @@ use super::Token;
|
||||
|
||||
pub struct ServiceConfig {
|
||||
pub(crate) services: Vec<(String, net::TcpListener)>,
|
||||
pub(crate) apply: Option<Box<ServiceRuntimeConfiguration>>,
|
||||
pub(crate) apply: Option<Box<dyn ServiceRuntimeConfiguration>>,
|
||||
pub(crate) threads: usize,
|
||||
pub(crate) backlog: i32,
|
||||
}
|
||||
@@ -75,13 +75,13 @@ impl ServiceConfig {
|
||||
}
|
||||
|
||||
pub(super) struct ConfiguredService {
|
||||
rt: Box<ServiceRuntimeConfiguration>,
|
||||
rt: Box<dyn ServiceRuntimeConfiguration>,
|
||||
names: HashMap<Token, (String, net::SocketAddr)>,
|
||||
services: HashMap<String, Token>,
|
||||
}
|
||||
|
||||
impl ConfiguredService {
|
||||
pub(super) fn new(rt: Box<ServiceRuntimeConfiguration>) -> Self {
|
||||
pub(super) fn new(rt: Box<dyn ServiceRuntimeConfiguration>) -> Self {
|
||||
ConfiguredService {
|
||||
rt,
|
||||
names: HashMap::new(),
|
||||
@@ -100,7 +100,7 @@ impl InternalServiceFactory for ConfiguredService {
|
||||
&self.names[&token].0
|
||||
}
|
||||
|
||||
fn clone_factory(&self) -> Box<InternalServiceFactory> {
|
||||
fn clone_factory(&self) -> Box<dyn InternalServiceFactory> {
|
||||
Box::new(Self {
|
||||
rt: self.rt.clone(),
|
||||
names: self.names.clone(),
|
||||
@@ -108,7 +108,7 @@ impl InternalServiceFactory for ConfiguredService {
|
||||
})
|
||||
}
|
||||
|
||||
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
|
||||
fn create(&self) -> Box<dyn Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
|
||||
// configure services
|
||||
let mut rt = ServiceRuntime::new(self.services.clone());
|
||||
self.rt.configure(&mut rt);
|
||||
@@ -156,7 +156,7 @@ impl InternalServiceFactory for ConfiguredService {
|
||||
}
|
||||
|
||||
pub(super) trait ServiceRuntimeConfiguration: Send {
|
||||
fn clone(&self) -> Box<ServiceRuntimeConfiguration>;
|
||||
fn clone(&self) -> Box<dyn ServiceRuntimeConfiguration>;
|
||||
|
||||
fn configure(&self, rt: &mut ServiceRuntime);
|
||||
}
|
||||
@@ -165,7 +165,7 @@ impl<F> ServiceRuntimeConfiguration for F
|
||||
where
|
||||
F: Fn(&mut ServiceRuntime) + Send + Clone + 'static,
|
||||
{
|
||||
fn clone(&self) -> Box<ServiceRuntimeConfiguration> {
|
||||
fn clone(&self) -> Box<dyn ServiceRuntimeConfiguration> {
|
||||
Box::new(self.clone())
|
||||
}
|
||||
|
||||
@@ -181,7 +181,7 @@ fn not_configured(_: &mut ServiceRuntime) {
|
||||
pub struct ServiceRuntime {
|
||||
names: HashMap<String, Token>,
|
||||
services: HashMap<Token, BoxedNewService>,
|
||||
onstart: Vec<Box<Future<Item = (), Error = ()>>>,
|
||||
onstart: Vec<Box<dyn Future<Item = (), Error = ()>>>,
|
||||
}
|
||||
|
||||
impl ServiceRuntime {
|
||||
@@ -207,8 +207,8 @@ impl ServiceRuntime {
|
||||
/// *ServiceConfig::bind()* or *ServiceConfig::listen()* methods.
|
||||
pub fn service<T, F>(&mut self, name: &str, service: F)
|
||||
where
|
||||
F: IntoNewService<T, ServerConfig>,
|
||||
T: NewService<ServerConfig, Request = Io<TcpStream>> + 'static,
|
||||
F: IntoNewService<T>,
|
||||
T: NewService<Config = ServerConfig, Request = Io<TcpStream>> + 'static,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
T::InitError: fmt::Debug,
|
||||
@@ -236,14 +236,14 @@ impl ServiceRuntime {
|
||||
}
|
||||
|
||||
type BoxedNewService = Box<
|
||||
NewService<
|
||||
ServerConfig,
|
||||
dyn NewService<
|
||||
Request = (Option<CounterGuard>, ServerMessage),
|
||||
Response = (),
|
||||
Error = (),
|
||||
InitError = (),
|
||||
Config = ServerConfig,
|
||||
Service = BoxedServerService,
|
||||
Future = Box<Future<Item = BoxedServerService, Error = ()>>,
|
||||
Future = Box<dyn Future<Item = BoxedServerService, Error = ()>>,
|
||||
>,
|
||||
>;
|
||||
|
||||
@@ -251,9 +251,9 @@ struct ServiceFactory<T> {
|
||||
inner: T,
|
||||
}
|
||||
|
||||
impl<T> NewService<ServerConfig> for ServiceFactory<T>
|
||||
impl<T> NewService for ServiceFactory<T>
|
||||
where
|
||||
T: NewService<ServerConfig, Request = Io<TcpStream>>,
|
||||
T: NewService<Config = ServerConfig, Request = Io<TcpStream>>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
T::Error: 'static,
|
||||
@@ -263,8 +263,9 @@ where
|
||||
type Response = ();
|
||||
type Error = ();
|
||||
type InitError = ();
|
||||
type Config = ServerConfig;
|
||||
type Service = BoxedServerService;
|
||||
type Future = Box<Future<Item = BoxedServerService, Error = ()>>;
|
||||
type Future = Box<dyn Future<Item = BoxedServerService, Error = ()>>;
|
||||
|
||||
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
|
||||
Box::new(self.inner.new_service(cfg).map_err(|_| ()).map(|s| {
|
||||
|
@@ -7,16 +7,20 @@ mod counter;
|
||||
mod server;
|
||||
mod services;
|
||||
mod signals;
|
||||
mod socket;
|
||||
pub mod ssl;
|
||||
mod worker;
|
||||
|
||||
pub use actix_server_config::{Io, Protocol, ServerConfig};
|
||||
pub use actix_server_config::{Io, IoStream, Protocol, ServerConfig};
|
||||
|
||||
pub use self::builder::ServerBuilder;
|
||||
pub use self::config::{ServiceConfig, ServiceRuntime};
|
||||
pub use self::server::Server;
|
||||
pub use self::services::ServiceFactory;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use self::socket::FromStream;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use self::services::ServiceFactory as StreamServiceFactory;
|
||||
|
||||
|
@@ -5,6 +5,7 @@ use futures::Future;
|
||||
use crate::builder::ServerBuilder;
|
||||
use crate::signals::Signal;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum ServerCommand {
|
||||
WorkerDied(usize),
|
||||
Pause(oneshot::Sender<()>),
|
||||
@@ -17,7 +18,7 @@ pub(crate) enum ServerCommand {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Server(UnboundedSender<ServerCommand>);
|
||||
|
||||
impl Server {
|
||||
|
@@ -1,4 +1,5 @@
|
||||
use std::net::{self, SocketAddr};
|
||||
use std::marker::PhantomData;
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
use actix_rt::spawn;
|
||||
@@ -7,24 +8,23 @@ use actix_service::{NewService, Service};
|
||||
use futures::future::{err, ok, FutureResult};
|
||||
use futures::{Future, Poll};
|
||||
use log::error;
|
||||
use tokio_reactor::Handle;
|
||||
use tokio_tcp::TcpStream;
|
||||
|
||||
use super::Token;
|
||||
use crate::counter::CounterGuard;
|
||||
use crate::socket::{FromStream, StdStream};
|
||||
|
||||
/// Server message
|
||||
pub(crate) enum ServerMessage {
|
||||
/// New stream
|
||||
Connect(net::TcpStream),
|
||||
Connect(StdStream),
|
||||
/// Gracefull shutdown
|
||||
Shutdown(Duration),
|
||||
/// Force shutdown
|
||||
ForceShutdown,
|
||||
}
|
||||
|
||||
pub trait ServiceFactory: Send + Clone + 'static {
|
||||
type NewService: NewService<ServerConfig, Request = Io<TcpStream>>;
|
||||
pub trait ServiceFactory<Stream: FromStream>: Send + Clone + 'static {
|
||||
type NewService: NewService<Config = ServerConfig, Request = Io<Stream>>;
|
||||
|
||||
fn create(&self) -> Self::NewService;
|
||||
}
|
||||
@@ -32,13 +32,13 @@ pub trait ServiceFactory: Send + Clone + 'static {
|
||||
pub(crate) trait InternalServiceFactory: Send {
|
||||
fn name(&self, token: Token) -> &str;
|
||||
|
||||
fn clone_factory(&self) -> Box<InternalServiceFactory>;
|
||||
fn clone_factory(&self) -> Box<dyn InternalServiceFactory>;
|
||||
|
||||
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>>;
|
||||
fn create(&self) -> Box<dyn Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>>;
|
||||
}
|
||||
|
||||
pub(crate) type BoxedServerService = Box<
|
||||
Service<
|
||||
dyn Service<
|
||||
Request = (Option<CounterGuard>, ServerMessage),
|
||||
Response = (),
|
||||
Error = (),
|
||||
@@ -56,11 +56,12 @@ impl<T> StreamService<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service for StreamService<T>
|
||||
impl<T, I> Service for StreamService<T>
|
||||
where
|
||||
T: Service<Request = Io<TcpStream>>,
|
||||
T: Service<Request = Io<I>>,
|
||||
T::Future: 'static,
|
||||
T::Error: 'static,
|
||||
I: FromStream,
|
||||
{
|
||||
type Request = (Option<CounterGuard>, ServerMessage);
|
||||
type Response = ();
|
||||
@@ -74,7 +75,7 @@ where
|
||||
fn call(&mut self, (guard, req): (Option<CounterGuard>, ServerMessage)) -> Self::Future {
|
||||
match req {
|
||||
ServerMessage::Connect(stream) => {
|
||||
let stream = TcpStream::from_std(stream, &Handle::default()).map_err(|e| {
|
||||
let stream = FromStream::from_stdstream(stream).map_err(|e| {
|
||||
error!("Can not convert to an async tcp stream: {}", e);
|
||||
});
|
||||
|
||||
@@ -93,50 +94,55 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct StreamNewService<F: ServiceFactory> {
|
||||
pub(crate) struct StreamNewService<F: ServiceFactory<Io>, Io: FromStream> {
|
||||
name: String,
|
||||
inner: F,
|
||||
token: Token,
|
||||
addr: SocketAddr,
|
||||
_t: PhantomData<Io>,
|
||||
}
|
||||
|
||||
impl<F> StreamNewService<F>
|
||||
impl<F, Io> StreamNewService<F, Io>
|
||||
where
|
||||
F: ServiceFactory,
|
||||
F: ServiceFactory<Io>,
|
||||
Io: FromStream + Send + 'static,
|
||||
{
|
||||
pub(crate) fn create(
|
||||
name: String,
|
||||
token: Token,
|
||||
inner: F,
|
||||
addr: SocketAddr,
|
||||
) -> Box<InternalServiceFactory> {
|
||||
) -> Box<dyn InternalServiceFactory> {
|
||||
Box::new(Self {
|
||||
name,
|
||||
token,
|
||||
inner,
|
||||
addr,
|
||||
_t: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<F> InternalServiceFactory for StreamNewService<F>
|
||||
impl<F, Io> InternalServiceFactory for StreamNewService<F, Io>
|
||||
where
|
||||
F: ServiceFactory,
|
||||
F: ServiceFactory<Io>,
|
||||
Io: FromStream + Send + 'static,
|
||||
{
|
||||
fn name(&self, _: Token) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn clone_factory(&self) -> Box<InternalServiceFactory> {
|
||||
fn clone_factory(&self) -> Box<dyn InternalServiceFactory> {
|
||||
Box::new(Self {
|
||||
name: self.name.clone(),
|
||||
inner: self.inner.clone(),
|
||||
token: self.token,
|
||||
addr: self.addr,
|
||||
_t: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
|
||||
fn create(&self) -> Box<dyn Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
|
||||
let token = self.token;
|
||||
let config = ServerConfig::new(self.addr);
|
||||
Box::new(
|
||||
@@ -152,24 +158,25 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl InternalServiceFactory for Box<InternalServiceFactory> {
|
||||
impl InternalServiceFactory for Box<dyn InternalServiceFactory> {
|
||||
fn name(&self, token: Token) -> &str {
|
||||
self.as_ref().name(token)
|
||||
}
|
||||
|
||||
fn clone_factory(&self) -> Box<InternalServiceFactory> {
|
||||
fn clone_factory(&self) -> Box<dyn InternalServiceFactory> {
|
||||
self.as_ref().clone_factory()
|
||||
}
|
||||
|
||||
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
|
||||
fn create(&self) -> Box<dyn Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
|
||||
self.as_ref().create()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, T> ServiceFactory for F
|
||||
impl<F, T, I> ServiceFactory<I> for F
|
||||
where
|
||||
F: Fn() -> T + Send + Clone + 'static,
|
||||
T: NewService<ServerConfig, Request = Io<TcpStream>>,
|
||||
T: NewService<Config = ServerConfig, Request = Io<I>>,
|
||||
I: FromStream,
|
||||
{
|
||||
type NewService = T;
|
||||
|
||||
|
@@ -27,7 +27,7 @@ pub(crate) struct Signals {
|
||||
streams: Vec<SigStream>,
|
||||
}
|
||||
|
||||
type SigStream = Box<Stream<Item = Signal, Error = io::Error>>;
|
||||
type SigStream = Box<dyn Stream<Item = Signal, Error = io::Error>>;
|
||||
|
||||
impl Signals {
|
||||
pub(crate) fn start(srv: Server) {
|
||||
@@ -46,7 +46,7 @@ impl Signals {
|
||||
{
|
||||
use tokio_signal::unix;
|
||||
|
||||
let mut sigs: Vec<Box<Future<Item = SigStream, Error = io::Error>>> =
|
||||
let mut sigs: Vec<Box<dyn Future<Item = SigStream, Error = io::Error>>> =
|
||||
Vec::new();
|
||||
sigs.push(Box::new(
|
||||
tokio_signal::unix::Signal::new(tokio_signal::unix::SIGINT).map(|stream| {
|
||||
|
173
actix-server/src/socket.rs
Normal file
173
actix-server/src/socket.rs
Normal file
@@ -0,0 +1,173 @@
|
||||
use std::{fmt, io, net};
|
||||
|
||||
use tokio_io::{AsyncRead, AsyncWrite};
|
||||
use tokio_reactor::Handle;
|
||||
use tokio_tcp::TcpStream;
|
||||
|
||||
pub(crate) enum StdListener {
|
||||
Tcp(net::TcpListener),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
Uds(std::os::unix::net::UnixListener),
|
||||
}
|
||||
|
||||
pub(crate) enum SocketAddr {
|
||||
Tcp(net::SocketAddr),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
Uds(std::os::unix::net::SocketAddr),
|
||||
}
|
||||
|
||||
impl fmt::Display for SocketAddr {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
SocketAddr::Tcp(ref addr) => write!(f, "{}", addr),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
SocketAddr::Uds(ref addr) => write!(f, "{:?}", addr),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for SocketAddr {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
SocketAddr::Tcp(ref addr) => write!(f, "{:?}", addr),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
SocketAddr::Uds(ref addr) => write!(f, "{:?}", addr),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for StdListener {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
StdListener::Tcp(ref lst) => write!(f, "{}", lst.local_addr().ok().unwrap()),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
StdListener::Uds(ref lst) => write!(f, "{:?}", lst.local_addr().ok().unwrap()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StdListener {
|
||||
pub(crate) fn local_addr(&self) -> SocketAddr {
|
||||
match self {
|
||||
StdListener::Tcp(lst) => SocketAddr::Tcp(lst.local_addr().unwrap()),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
StdListener::Uds(lst) => SocketAddr::Uds(lst.local_addr().unwrap()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn into_listener(self) -> SocketListener {
|
||||
match self {
|
||||
StdListener::Tcp(lst) => SocketListener::Tcp(
|
||||
mio::net::TcpListener::from_std(lst)
|
||||
.expect("Can not create mio::net::TcpListener"),
|
||||
),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
StdListener::Uds(lst) => SocketListener::Uds(
|
||||
mio_uds::UnixListener::from_listener(lst)
|
||||
.expect("Can not create mio_uds::UnixListener"),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum StdStream {
|
||||
Tcp(std::net::TcpStream),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
Uds(std::os::unix::net::UnixStream),
|
||||
}
|
||||
|
||||
pub(crate) enum SocketListener {
|
||||
Tcp(mio::net::TcpListener),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
Uds(mio_uds::UnixListener),
|
||||
}
|
||||
|
||||
impl SocketListener {
|
||||
pub(crate) fn accept(&self) -> io::Result<Option<(StdStream, SocketAddr)>> {
|
||||
match *self {
|
||||
SocketListener::Tcp(ref lst) => lst
|
||||
.accept_std()
|
||||
.map(|(stream, addr)| Some((StdStream::Tcp(stream), SocketAddr::Tcp(addr)))),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
SocketListener::Uds(ref lst) => lst.accept_std().map(|res| {
|
||||
res.map(|(stream, addr)| (StdStream::Uds(stream), SocketAddr::Uds(addr)))
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl mio::Evented for SocketListener {
|
||||
fn register(
|
||||
&self,
|
||||
poll: &mio::Poll,
|
||||
token: mio::Token,
|
||||
interest: mio::Ready,
|
||||
opts: mio::PollOpt,
|
||||
) -> io::Result<()> {
|
||||
match *self {
|
||||
SocketListener::Tcp(ref lst) => lst.register(poll, token, interest, opts),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
SocketListener::Uds(ref lst) => lst.register(poll, token, interest, opts),
|
||||
}
|
||||
}
|
||||
|
||||
fn reregister(
|
||||
&self,
|
||||
poll: &mio::Poll,
|
||||
token: mio::Token,
|
||||
interest: mio::Ready,
|
||||
opts: mio::PollOpt,
|
||||
) -> io::Result<()> {
|
||||
match *self {
|
||||
SocketListener::Tcp(ref lst) => lst.reregister(poll, token, interest, opts),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
SocketListener::Uds(ref lst) => lst.reregister(poll, token, interest, opts),
|
||||
}
|
||||
}
|
||||
fn deregister(&self, poll: &mio::Poll) -> io::Result<()> {
|
||||
match *self {
|
||||
SocketListener::Tcp(ref lst) => lst.deregister(poll),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
SocketListener::Uds(ref lst) => {
|
||||
let res = lst.deregister(poll);
|
||||
|
||||
// cleanup file path
|
||||
if let Ok(addr) = lst.local_addr() {
|
||||
if let Some(path) = addr.as_pathname() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
res
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait FromStream: AsyncRead + AsyncWrite + Sized {
|
||||
fn from_stdstream(sock: StdStream) -> io::Result<Self>;
|
||||
}
|
||||
|
||||
impl FromStream for TcpStream {
|
||||
fn from_stdstream(sock: StdStream) -> io::Result<Self> {
|
||||
match sock {
|
||||
StdStream::Tcp(stream) => TcpStream::from_std(stream, &Handle::default()),
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
StdStream::Uds(_) => {
|
||||
panic!("Should not happen, bug in server impl");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, feature = "uds"))]
|
||||
impl FromStream for tokio_uds::UnixStream {
|
||||
fn from_stdstream(sock: StdStream) -> io::Result<Self> {
|
||||
match sock {
|
||||
StdStream::Tcp(_) => panic!("Should not happen, bug in server impl"),
|
||||
StdStream::Uds(stream) => {
|
||||
tokio_uds::UnixStream::from_std(stream, &Handle::default())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -35,6 +35,7 @@ thread_local! {
|
||||
}
|
||||
|
||||
/// Ssl error combinded with service error.
|
||||
#[derive(Debug)]
|
||||
pub enum SslError<E1, E2> {
|
||||
Ssl(E1),
|
||||
Service(E2),
|
||||
|
@@ -37,10 +37,12 @@ impl<T: AsyncRead + AsyncWrite, P> Clone for NativeTlsAcceptor<T, P> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService<ServerConfig> for NativeTlsAcceptor<T, P> {
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService for NativeTlsAcceptor<T, P> {
|
||||
type Request = Io<T, P>;
|
||||
type Response = Io<TlsStream<T>, P>;
|
||||
type Error = Error;
|
||||
|
||||
type Config = ServerConfig;
|
||||
type Service = NativeTlsAcceptorService<T, P>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
@@ -37,10 +37,11 @@ impl<T: AsyncRead + AsyncWrite, P> Clone for OpensslAcceptor<T, P> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService<ServerConfig> for OpensslAcceptor<T, P> {
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService for OpensslAcceptor<T, P> {
|
||||
type Request = Io<T, P>;
|
||||
type Response = Io<SslStream<T>, P>;
|
||||
type Error = HandshakeError<T>;
|
||||
type Config = ServerConfig;
|
||||
type Service = OpensslAcceptorService<T, P>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
@@ -39,10 +39,12 @@ impl<T, P> Clone for RustlsAcceptor<T, P> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService<SrvConfig> for RustlsAcceptor<T, P> {
|
||||
impl<T: AsyncRead + AsyncWrite, P> NewService for RustlsAcceptor<T, P> {
|
||||
type Request = Io<T, P>;
|
||||
type Response = Io<TlsStream<T, ServerSession>, P>;
|
||||
type Error = io::Error;
|
||||
|
||||
type Config = SrvConfig;
|
||||
type Service = RustlsAcceptorService<T, P>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
@@ -1,6 +1,6 @@
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::{mem, net, time};
|
||||
use std::{mem, time};
|
||||
|
||||
use actix_rt::{spawn, Arbiter};
|
||||
use futures::sync::mpsc::{UnboundedReceiver, UnboundedSender};
|
||||
@@ -12,6 +12,7 @@ use tokio_timer::{sleep, Delay};
|
||||
use crate::accept::AcceptNotify;
|
||||
use crate::counter::Counter;
|
||||
use crate::services::{BoxedServerService, InternalServiceFactory, ServerMessage};
|
||||
use crate::socket::{SocketAddr, StdStream};
|
||||
use crate::Token;
|
||||
|
||||
pub(crate) struct WorkerCommand(Conn);
|
||||
@@ -25,9 +26,9 @@ pub(crate) struct StopCommand {
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Conn {
|
||||
pub io: net::TcpStream,
|
||||
pub io: StdStream,
|
||||
pub token: Token,
|
||||
pub peer: Option<net::SocketAddr>,
|
||||
pub peer: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
static MAX_CONNS: AtomicUsize = AtomicUsize::new(25600);
|
||||
@@ -127,7 +128,7 @@ pub(crate) struct Worker {
|
||||
services: Vec<Option<(usize, BoxedServerService)>>,
|
||||
availability: WorkerAvailability,
|
||||
conns: Counter,
|
||||
factories: Vec<Box<InternalServiceFactory>>,
|
||||
factories: Vec<Box<dyn InternalServiceFactory>>,
|
||||
state: WorkerState,
|
||||
shutdown_timeout: time::Duration,
|
||||
}
|
||||
@@ -136,7 +137,7 @@ impl Worker {
|
||||
pub(crate) fn start(
|
||||
rx: UnboundedReceiver<WorkerCommand>,
|
||||
rx2: UnboundedReceiver<StopCommand>,
|
||||
factories: Vec<Box<InternalServiceFactory>>,
|
||||
factories: Vec<Box<dyn InternalServiceFactory>>,
|
||||
availability: WorkerAvailability,
|
||||
shutdown_timeout: time::Duration,
|
||||
) {
|
||||
@@ -237,7 +238,7 @@ enum WorkerState {
|
||||
Restarting(
|
||||
usize,
|
||||
Token,
|
||||
Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>>,
|
||||
Box<dyn Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>>,
|
||||
),
|
||||
Shutdown(Delay, Delay, oneshot::Sender<bool>),
|
||||
}
|
||||
|
@@ -4,7 +4,7 @@ use std::{net, thread, time};
|
||||
|
||||
use actix_codec::{BytesCodec, Framed};
|
||||
use actix_server::{Io, Server, ServerConfig};
|
||||
use actix_service::{fn_cfg_factory, fn_service, IntoService};
|
||||
use actix_service::{new_service_cfg, service_fn, IntoService};
|
||||
use bytes::Bytes;
|
||||
use futures::{Future, Sink};
|
||||
use net2::TcpBuilder;
|
||||
@@ -28,7 +28,7 @@ fn test_bind() {
|
||||
let sys = actix_rt::System::new("test");
|
||||
let srv = Server::build()
|
||||
.bind("test", addr, move || {
|
||||
fn_cfg_factory(move |cfg: &ServerConfig| {
|
||||
new_service_cfg(move |cfg: &ServerConfig| {
|
||||
assert_eq!(cfg.local_addr(), addr);
|
||||
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
|
||||
})
|
||||
@@ -54,7 +54,7 @@ fn test_bind_no_config() {
|
||||
let h = thread::spawn(move || {
|
||||
let sys = actix_rt::System::new("test");
|
||||
let srv = Server::build()
|
||||
.bind("test", addr, move || fn_service(|_| Ok::<_, ()>(())))
|
||||
.bind("test", addr, move || service_fn(|_| Ok::<_, ()>(())))
|
||||
.unwrap()
|
||||
.start();
|
||||
let _ = tx.send((srv, actix_rt::System::current()));
|
||||
@@ -76,7 +76,7 @@ fn test_listen() {
|
||||
let lst = net::TcpListener::bind(addr).unwrap();
|
||||
let srv = Server::build()
|
||||
.listen("test", lst, move || {
|
||||
fn_cfg_factory(move |cfg: &ServerConfig| {
|
||||
new_service_cfg(move |cfg: &ServerConfig| {
|
||||
assert_eq!(cfg.local_addr(), addr);
|
||||
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
|
||||
})
|
||||
@@ -105,7 +105,7 @@ fn test_start() {
|
||||
let srv = Server::build()
|
||||
.backlog(100)
|
||||
.bind("test", addr, move || {
|
||||
fn_cfg_factory(move |cfg: &ServerConfig| {
|
||||
new_service_cfg(move |cfg: &ServerConfig| {
|
||||
assert_eq!(cfg.local_addr(), addr);
|
||||
Ok::<_, ()>(
|
||||
(|io: Io<TcpStream>| {
|
||||
|
@@ -1,5 +1,40 @@
|
||||
# Changes
|
||||
|
||||
## [0.4.1] - 2019-06-06
|
||||
|
||||
### Added
|
||||
|
||||
* Add `new_apply_cfg` function
|
||||
|
||||
## [0.4.0] - 2019-05-12
|
||||
|
||||
### Changed
|
||||
|
||||
* Use associated type for `NewService` config
|
||||
|
||||
* Change `apply_cfg` function
|
||||
|
||||
* Renamed helper functions
|
||||
|
||||
### Added
|
||||
|
||||
* Add `NewService::map_config` and `NewService::unit_config` combinators
|
||||
|
||||
|
||||
## [0.3.6] - 2019-04-07
|
||||
|
||||
### Changed
|
||||
|
||||
* Poll boxed service call result immediately
|
||||
|
||||
|
||||
## [0.3.5] - 2019-03-29
|
||||
|
||||
### Added
|
||||
|
||||
* Add `impl<S: Service> Service for Rc<RefCell<S>>`
|
||||
|
||||
|
||||
## [0.3.4] - 2019-03-12
|
||||
|
||||
### Added
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-service"
|
||||
version = "0.3.4"
|
||||
version = "0.4.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix Service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -23,8 +23,7 @@ name = "actix_service"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
futures = "0.1.24"
|
||||
void = "1.0.2"
|
||||
futures = "0.1.25"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.2"
|
1
actix-service/LICENSE-APACHE
Symbolic link
1
actix-service/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-service/LICENSE-MIT
Symbolic link
1
actix-service/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -1,5 +1,3 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::{IntoNewService, NewService, Service};
|
||||
@@ -111,67 +109,75 @@ where
|
||||
}
|
||||
|
||||
/// `AndThenNewService` new service combinator
|
||||
pub struct AndThenNewService<A, B, C>
|
||||
pub struct AndThenNewService<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService,
|
||||
{
|
||||
a: A,
|
||||
b: B,
|
||||
_t: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<A, B, C> AndThenNewService<A, B, C>
|
||||
impl<A, B> AndThenNewService<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
Config = A::Config,
|
||||
Request = A::Response,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
{
|
||||
/// Create new `AndThen` combinator
|
||||
pub fn new<F: IntoNewService<B, C>>(a: A, f: F) -> Self {
|
||||
pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self {
|
||||
Self {
|
||||
a,
|
||||
b: f.into_new_service(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> NewService<C> for AndThenNewService<A, B, C>
|
||||
impl<A, B> NewService for AndThenNewService<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
Config = A::Config,
|
||||
Request = A::Response,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = B::Response;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = AndThen<A::Service, B::Service>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = AndThenNewServiceFuture<A, B, C>;
|
||||
type Future = AndThenNewServiceFuture<A, B>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
AndThenNewServiceFuture::new(self.a.new_service(cfg), self.b.new_service(cfg))
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> Clone for AndThenNewService<A, B, C>
|
||||
impl<A, B> Clone for AndThenNewService<A, B>
|
||||
where
|
||||
A: NewService<C> + Clone,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError> + Clone,
|
||||
A: NewService + Clone,
|
||||
B: NewService + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenNewServiceFuture<A, B, C>
|
||||
pub struct AndThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response>,
|
||||
A: NewService,
|
||||
B: NewService<Request = A::Response>,
|
||||
{
|
||||
fut_b: B::Future,
|
||||
fut_a: A::Future,
|
||||
@@ -179,10 +185,10 @@ where
|
||||
b: Option<B::Service>,
|
||||
}
|
||||
|
||||
impl<A, B, C> AndThenNewServiceFuture<A, B, C>
|
||||
impl<A, B> AndThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response>,
|
||||
A: NewService,
|
||||
B: NewService<Request = A::Response>,
|
||||
{
|
||||
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
|
||||
AndThenNewServiceFuture {
|
||||
@@ -194,10 +200,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> Future for AndThenNewServiceFuture<A, B, C>
|
||||
impl<A, B> Future for AndThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
type Item = AndThen<A::Service, B::Service>;
|
||||
type Error = A::InitError;
|
||||
|
@@ -7,17 +7,16 @@ use crate::from_err::FromErr;
|
||||
use crate::{NewService, Transform};
|
||||
|
||||
/// `Apply` new service combinator
|
||||
pub struct AndThenTransform<T, A, B, C> {
|
||||
pub struct AndThenTransform<T, A, B> {
|
||||
a: A,
|
||||
b: B,
|
||||
t: Rc<T>,
|
||||
_t: std::marker::PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<T, A, B, C> AndThenTransform<T, A, B, C>
|
||||
impl<T, A, B> AndThenTransform<T, A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Config = A::Config, InitError = A::InitError>,
|
||||
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
@@ -27,12 +26,11 @@ where
|
||||
a,
|
||||
b,
|
||||
t: Rc::new(t),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A, B, C> Clone for AndThenTransform<T, A, B, C>
|
||||
impl<T, A, B> Clone for AndThenTransform<T, A, B>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
@@ -42,15 +40,14 @@ where
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
t: self.t.clone(),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A, B, C> NewService<C> for AndThenTransform<T, A, B, C>
|
||||
impl<T, A, B> NewService for AndThenTransform<T, A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Config = A::Config, InitError = A::InitError>,
|
||||
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
@@ -58,11 +55,12 @@ where
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
|
||||
type Config = A::Config;
|
||||
type InitError = T::InitError;
|
||||
type Service = AndThen<FromErr<A::Service, T::Error>, T::Transform>;
|
||||
type Future = AndThenTransformFuture<T, A, B, C>;
|
||||
type Future = AndThenTransformFuture<T, A, B>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
AndThenTransformFuture {
|
||||
a: None,
|
||||
t: None,
|
||||
@@ -74,10 +72,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenTransformFuture<T, A, B, C>
|
||||
pub struct AndThenTransformFuture<T, A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<InitError = A::InitError>,
|
||||
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
@@ -89,10 +87,10 @@ where
|
||||
t_cell: Rc<T>,
|
||||
}
|
||||
|
||||
impl<T, A, B, C> Future for AndThenTransformFuture<T, A, B, C>
|
||||
impl<T, A, B> Future for AndThenTransformFuture<T, A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<InitError = A::InitError>,
|
||||
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
|
@@ -133,27 +133,23 @@ where
|
||||
}
|
||||
|
||||
/// `ApplyNewService` new service combinator
|
||||
pub struct AndThenApplyNewService<A, B, F, Out, Cfg> {
|
||||
pub struct AndThenApplyNewService<A, B, F, Out> {
|
||||
a: A,
|
||||
b: B,
|
||||
f: Cell<F>,
|
||||
r: PhantomData<(Out, Cfg)>,
|
||||
r: PhantomData<Out>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, Cfg> AndThenApplyNewService<A, B, F, Out, Cfg>
|
||||
impl<A, B, F, Out> AndThenApplyNewService<A, B, F, Out>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Config = A::Config, Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
/// Create new `ApplyNewService` new service instance
|
||||
pub fn new<A1: IntoNewService<A, Cfg>, B1: IntoNewService<B, Cfg>>(
|
||||
a: A1,
|
||||
b: B1,
|
||||
f: F,
|
||||
) -> Self {
|
||||
pub fn new<A1: IntoNewService<A>, B1: IntoNewService<B>>(a: A1, b: B1, f: F) -> Self {
|
||||
Self {
|
||||
f: Cell::new(f),
|
||||
a: a.into_new_service(),
|
||||
@@ -163,7 +159,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, Cfg> Clone for AndThenApplyNewService<A, B, F, Out, Cfg>
|
||||
impl<A, B, F, Out> Clone for AndThenApplyNewService<A, B, F, Out>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
@@ -178,10 +174,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, Cfg> NewService<Cfg> for AndThenApplyNewService<A, B, F, Out, Cfg>
|
||||
impl<A, B, F, Out> NewService for AndThenApplyNewService<A, B, F, Out>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Config = A::Config, Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
@@ -190,11 +186,11 @@ where
|
||||
type Response = Out::Item;
|
||||
type Error = A::Error;
|
||||
type Service = AndThenApply<A::Service, B::Service, F, Out>;
|
||||
|
||||
type Config = A::Config;
|
||||
type InitError = A::InitError;
|
||||
type Future = AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>;
|
||||
type Future = AndThenApplyNewServiceFuture<A, B, F, Out>;
|
||||
|
||||
fn new_service(&self, cfg: &Cfg) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
AndThenApplyNewServiceFuture {
|
||||
a: None,
|
||||
b: None,
|
||||
@@ -205,10 +201,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>
|
||||
pub struct AndThenApplyNewServiceFuture<A, B, F, Out>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
@@ -220,10 +216,10 @@ where
|
||||
b: Option<B::Service>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, Cfg> Future for AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>
|
||||
impl<A, B, F, Out> Future for AndThenApplyNewServiceFuture<A, B, F, Out>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService,
|
||||
B: NewService<Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
|
@@ -16,17 +16,14 @@ where
|
||||
Apply::new(service.into_service(), f)
|
||||
}
|
||||
|
||||
/// Create fractory for `apply_fn` service.
|
||||
pub fn apply_fn_factory<T, F, In, Out, Cfg, U>(
|
||||
service: U,
|
||||
f: F,
|
||||
) -> ApplyNewService<T, F, In, Out, Cfg>
|
||||
/// Create factory for `apply` service.
|
||||
pub fn new_apply_fn<T, F, In, Out, U>(service: U, f: F) -> ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
U: IntoNewService<T, Cfg>,
|
||||
U: IntoNewService<T>,
|
||||
{
|
||||
ApplyNewService::new(service.into_new_service(), f)
|
||||
}
|
||||
@@ -50,7 +47,7 @@ where
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
/// Create new `Apply` combinator
|
||||
pub fn new<I: IntoService<T>>(service: I, f: F) -> Self {
|
||||
pub(crate) fn new<I: IntoService<T>>(service: I, f: F) -> Self {
|
||||
Self {
|
||||
service: service.into_service(),
|
||||
f,
|
||||
@@ -95,24 +92,24 @@ where
|
||||
}
|
||||
|
||||
/// `ApplyNewService` new service combinator
|
||||
pub struct ApplyNewService<T, F, In, Out, Cfg>
|
||||
pub struct ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
{
|
||||
service: T,
|
||||
f: F,
|
||||
r: PhantomData<(In, Out, Cfg)>,
|
||||
r: PhantomData<(In, Out)>,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Cfg> ApplyNewService<T, F, In, Out, Cfg>
|
||||
impl<T, F, In, Out> ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
/// Create new `ApplyNewService` new service instance
|
||||
pub fn new<F1: IntoNewService<T, Cfg>>(service: F1, f: F) -> Self {
|
||||
pub(crate) fn new<F1: IntoNewService<T>>(service: F1, f: F) -> Self {
|
||||
Self {
|
||||
f,
|
||||
service: service.into_new_service(),
|
||||
@@ -121,9 +118,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Cfg> Clone for ApplyNewService<T, F, In, Out, Cfg>
|
||||
impl<T, F, In, Out> Clone for ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg> + Clone,
|
||||
T: NewService + Clone,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
@@ -136,9 +133,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Cfg> NewService<Cfg> for ApplyNewService<T, F, In, Out, Cfg>
|
||||
impl<T, F, In, Out> NewService for ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
@@ -146,19 +143,20 @@ where
|
||||
type Request = In;
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
|
||||
type Config = T::Config;
|
||||
type Service = Apply<T::Service, F, In, Out>;
|
||||
|
||||
type InitError = T::InitError;
|
||||
type Future = ApplyNewServiceFuture<T, F, In, Out, Cfg>;
|
||||
type Future = ApplyNewServiceFuture<T, F, In, Out>;
|
||||
|
||||
fn new_service(&self, cfg: &Cfg) -> Self::Future {
|
||||
fn new_service(&self, cfg: &T::Config) -> Self::Future {
|
||||
ApplyNewServiceFuture::new(self.service.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ApplyNewServiceFuture<T, F, In, Out, Cfg>
|
||||
pub struct ApplyNewServiceFuture<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
@@ -167,9 +165,9 @@ where
|
||||
r: PhantomData<(In, Out)>,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Cfg> ApplyNewServiceFuture<T, F, In, Out, Cfg>
|
||||
impl<T, F, In, Out> ApplyNewServiceFuture<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
@@ -182,9 +180,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Cfg> Future for ApplyNewServiceFuture<T, F, In, Out, Cfg>
|
||||
impl<T, F, In, Out> Future for ApplyNewServiceFuture<T, F, In, Out>
|
||||
where
|
||||
T: NewService<Cfg>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
|
@@ -1,112 +1,252 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use crate::{IntoNewService, NewService};
|
||||
use futures::future::Future;
|
||||
use futures::{try_ready, Async, IntoFuture, Poll};
|
||||
|
||||
/// Create new ApplyConfig` service factory combinator
|
||||
pub fn apply_cfg<F, S, C1, C2, U>(f: F, service: U) -> ApplyConfig<F, S, C1, C2>
|
||||
where
|
||||
S: NewService<C2>,
|
||||
F: Fn(&C1) -> C2,
|
||||
U: IntoNewService<S, C2>,
|
||||
{
|
||||
ApplyConfig::new(service.into_new_service(), f)
|
||||
}
|
||||
use crate::cell::Cell;
|
||||
use crate::{IntoService, NewService, Service};
|
||||
|
||||
/// `ApplyConfig` service factory combinator
|
||||
pub struct ApplyConfig<F, S, C1, C2> {
|
||||
s: S,
|
||||
/// Convert `Fn(&Config, &mut Service) -> Future<Service>` fn to a NewService
|
||||
pub fn apply_cfg<F, C, T, R, S>(
|
||||
srv: T,
|
||||
f: F,
|
||||
r: PhantomData<(C1, C2)>,
|
||||
}
|
||||
|
||||
impl<F, S, C1, C2> ApplyConfig<F, S, C1, C2>
|
||||
) -> impl NewService<
|
||||
Config = C,
|
||||
Request = S::Request,
|
||||
Response = S::Response,
|
||||
Error = S::Error,
|
||||
Service = S,
|
||||
InitError = R::Error,
|
||||
> + Clone
|
||||
where
|
||||
S: NewService<C2>,
|
||||
F: Fn(&C1) -> C2,
|
||||
F: FnMut(&C, &mut T) -> R,
|
||||
T: Service,
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
/// Create new ApplyConfig` service factory combinator
|
||||
pub fn new<U: IntoNewService<S, C2>>(a: U, f: F) -> Self {
|
||||
Self {
|
||||
f,
|
||||
s: a.into_new_service(),
|
||||
r: PhantomData,
|
||||
}
|
||||
ApplyConfigService {
|
||||
f: Cell::new(f),
|
||||
srv: Cell::new(srv.into_service()),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, C1, C2> Clone for ApplyConfig<F, S, C1, C2>
|
||||
/// Convert `Fn(&Config, &mut Service) -> Future<Service>` fn to a NewService
|
||||
/// Service get constructor from NewService.
|
||||
pub fn new_apply_cfg<F, C, T, R, S>(
|
||||
srv: T,
|
||||
f: F,
|
||||
) -> impl NewService<
|
||||
Config = C,
|
||||
Request = S::Request,
|
||||
Response = S::Response,
|
||||
Error = S::Error,
|
||||
Service = S,
|
||||
InitError = T::InitError,
|
||||
> + Clone
|
||||
where
|
||||
S: Clone,
|
||||
F: Clone,
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
ApplyConfigNewService {
|
||||
f: Cell::new(f),
|
||||
srv: Cell::new(srv),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
|
||||
struct ApplyConfigService<F, C, T, R, S>
|
||||
where
|
||||
F: FnMut(&C, &mut T) -> R,
|
||||
T: Service,
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
f: Cell<F>,
|
||||
srv: Cell<T>,
|
||||
_t: PhantomData<(C, R, S)>,
|
||||
}
|
||||
|
||||
impl<F, C, T, R, S> Clone for ApplyConfigService<F, C, T, R, S>
|
||||
where
|
||||
F: FnMut(&C, &mut T) -> R,
|
||||
T: Service,
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
s: self.s.clone(),
|
||||
ApplyConfigService {
|
||||
f: self.f.clone(),
|
||||
r: PhantomData,
|
||||
srv: self.srv.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, C1, C2> NewService<C1> for ApplyConfig<F, S, C1, C2>
|
||||
impl<F, C, T, R, S> NewService for ApplyConfigService<F, C, T, R, S>
|
||||
where
|
||||
S: NewService<C2>,
|
||||
F: Fn(&C1) -> C2,
|
||||
F: FnMut(&C, &mut T) -> R,
|
||||
T: Service,
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
type Config = C;
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S::Service;
|
||||
type Service = S;
|
||||
|
||||
type InitError = S::InitError;
|
||||
type Future = S::Future;
|
||||
type InitError = R::Error;
|
||||
type Future = FnNewServiceConfigFut<R, S>;
|
||||
|
||||
fn new_service(&self, cfg: &C1) -> Self::Future {
|
||||
let cfg2 = (self.f)(cfg);
|
||||
|
||||
self.s.new_service(&cfg2)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::{fn_cfg_factory, NewService, Service};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Srv;
|
||||
impl Service for Srv {
|
||||
type Request = ();
|
||||
type Response = ();
|
||||
type Error = ();
|
||||
type Future = FutureResult<(), ()>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, _: ()) -> Self::Future {
|
||||
ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_service() {
|
||||
let new_srv = fn_cfg_factory(|_: &usize| Ok::<_, ()>(Srv)).apply_cfg(
|
||||
fn_cfg_factory(|s: &String| {
|
||||
assert_eq!(s, "test");
|
||||
Ok::<_, ()>(Srv)
|
||||
}),
|
||||
|cfg: &usize| {
|
||||
assert_eq!(*cfg, 1);
|
||||
"test".to_string()
|
||||
},
|
||||
);
|
||||
|
||||
if let Async::Ready(mut srv) = new_srv.new_service(&1).poll().unwrap() {
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
FnNewServiceConfigFut {
|
||||
fut: unsafe { (self.f.get_mut_unsafe())(cfg, self.srv.get_mut_unsafe()) }
|
||||
.into_future(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FnNewServiceConfigFut<R, S>
|
||||
where
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
fut: R::Future,
|
||||
_t: PhantomData<(S,)>,
|
||||
}
|
||||
|
||||
impl<R, S> Future for FnNewServiceConfigFut<R, S>
|
||||
where
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
type Item = S;
|
||||
type Error = R::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
Ok(Async::Ready(try_ready!(self.fut.poll()).into_service()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
|
||||
struct ApplyConfigNewService<F, C, T, R, S>
|
||||
where
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
f: Cell<F>,
|
||||
srv: Cell<T>,
|
||||
_t: PhantomData<(C, R, S)>,
|
||||
}
|
||||
|
||||
impl<F, C, T, R, S> Clone for ApplyConfigNewService<F, C, T, R, S>
|
||||
where
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
ApplyConfigNewService {
|
||||
f: self.f.clone(),
|
||||
srv: self.srv.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, T, R, S> NewService for ApplyConfigNewService<F, C, T, R, S>
|
||||
where
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
type Config = C;
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S;
|
||||
|
||||
type InitError = R::Error;
|
||||
type Future = ApplyConfigNewServiceFut<F, C, T, R, S>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
ApplyConfigNewServiceFut {
|
||||
f: self.f.clone(),
|
||||
cfg: cfg.clone(),
|
||||
srv: Some(self.srv.get_ref().new_service(&())),
|
||||
fut: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ApplyConfigNewServiceFut<F, C, T, R, S>
|
||||
where
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
cfg: C,
|
||||
f: Cell<F>,
|
||||
srv: Option<T::Future>,
|
||||
fut: Option<R::Future>,
|
||||
_t: PhantomData<(S,)>,
|
||||
}
|
||||
|
||||
impl<F, C, T, R, S> Future for ApplyConfigNewServiceFut<F, C, T, R, S>
|
||||
where
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
type Item = S;
|
||||
type Error = R::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.srv {
|
||||
match fut.poll()? {
|
||||
Async::NotReady => return Ok(Async::NotReady),
|
||||
Async::Ready(mut srv) => {
|
||||
let _ = self.srv.take();
|
||||
self.fut = Some(self.f.get_mut()(&self.cfg, &mut srv).into_future());
|
||||
return self.poll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref mut fut) = self.fut {
|
||||
Ok(Async::Ready(try_ready!(fut.poll()).into_service()))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -68,12 +68,13 @@ impl<R, E1, E2> Default for BlankNewService<R, E1, E2> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, E1, E2> NewService<()> for BlankNewService<R, E1, E2> {
|
||||
impl<R, E1, E2> NewService for BlankNewService<R, E1, E2> {
|
||||
type Request = R;
|
||||
type Response = R;
|
||||
type Error = E1;
|
||||
type Service = Blank<R, E1>;
|
||||
|
||||
type Config = ();
|
||||
type Service = Blank<R, E1>;
|
||||
type InitError = E2;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
|
@@ -1,22 +1,28 @@
|
||||
use futures::future::{err, ok, Either, FutureResult};
|
||||
use futures::{Async, Future, IntoFuture, Poll};
|
||||
|
||||
use crate::{NewService, Service};
|
||||
use futures::{Future, IntoFuture, Poll};
|
||||
|
||||
pub type BoxedService<Req, Res, Err> = Box<
|
||||
Service<
|
||||
Request = Req,
|
||||
Response = Res,
|
||||
Error = Err,
|
||||
Future = Box<Future<Item = Res, Error = Err>>,
|
||||
Future = BoxedServiceResponse<Res, Err>,
|
||||
>,
|
||||
>;
|
||||
|
||||
pub type BoxedServiceResponse<Res, Err> =
|
||||
Either<FutureResult<Res, Err>, Box<Future<Item = Res, Error = Err>>>;
|
||||
|
||||
pub struct BoxedNewService<C, Req, Res, Err, InitErr>(Inner<C, Req, Res, Err, InitErr>);
|
||||
|
||||
/// Create boxed new service
|
||||
pub fn new_service<T, C>(
|
||||
pub fn new_service<T>(
|
||||
service: T,
|
||||
) -> BoxedNewService<C, T::Request, T::Response, T::Error, T::InitError>
|
||||
) -> BoxedNewService<T::Config, T::Request, T::Response, T::Error, T::InitError>
|
||||
where
|
||||
C: 'static,
|
||||
T: NewService<C> + 'static,
|
||||
T: NewService + 'static,
|
||||
T::Request: 'static,
|
||||
T::Response: 'static,
|
||||
T::Service: 'static,
|
||||
@@ -41,7 +47,7 @@ where
|
||||
|
||||
type Inner<C, Req, Res, Err, InitErr> = Box<
|
||||
NewService<
|
||||
C,
|
||||
Config = C,
|
||||
Request = Req,
|
||||
Response = Res,
|
||||
Error = Err,
|
||||
@@ -51,9 +57,7 @@ type Inner<C, Req, Res, Err, InitErr> = Box<
|
||||
>,
|
||||
>;
|
||||
|
||||
pub struct BoxedNewService<C, Req, Res, Err, InitErr>(Inner<C, Req, Res, Err, InitErr>);
|
||||
|
||||
impl<C, Req, Res, Err, InitErr> NewService<C> for BoxedNewService<C, Req, Res, Err, InitErr>
|
||||
impl<C, Req, Res, Err, InitErr> NewService for BoxedNewService<C, Req, Res, Err, InitErr>
|
||||
where
|
||||
Req: 'static,
|
||||
Res: 'static,
|
||||
@@ -64,6 +68,7 @@ where
|
||||
type Response = Res;
|
||||
type Error = Err;
|
||||
type InitError = InitErr;
|
||||
type Config = C;
|
||||
type Service = BoxedService<Req, Res, Err>;
|
||||
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
@@ -72,18 +77,18 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
struct NewServiceWrapper<C, T: NewService<C>> {
|
||||
struct NewServiceWrapper<C, T: NewService> {
|
||||
service: T,
|
||||
_t: std::marker::PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<C, T, Req, Res, Err, InitErr> NewService<C> for NewServiceWrapper<C, T>
|
||||
impl<C, T, Req, Res, Err, InitErr> NewService for NewServiceWrapper<C, T>
|
||||
where
|
||||
Req: 'static,
|
||||
Res: 'static,
|
||||
Err: 'static,
|
||||
InitErr: 'static,
|
||||
T: NewService<C, Request = Req, Response = Res, Error = Err, InitError = InitErr>,
|
||||
T: NewService<Config = C, Request = Req, Response = Res, Error = Err, InitError = InitErr>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
@@ -92,6 +97,7 @@ where
|
||||
type Response = Res;
|
||||
type Error = Err;
|
||||
type InitError = InitErr;
|
||||
type Config = C;
|
||||
type Service = BoxedService<Req, Res, Err>;
|
||||
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
@@ -125,13 +131,21 @@ where
|
||||
type Request = Req;
|
||||
type Response = Res;
|
||||
type Error = Err;
|
||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||
type Future = Either<
|
||||
FutureResult<Self::Response, Self::Error>,
|
||||
Box<Future<Item = Self::Response, Error = Self::Error>>,
|
||||
>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.0.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
Box::new(self.0.call(req))
|
||||
let mut fut = self.0.call(req);
|
||||
match fut.poll() {
|
||||
Ok(Async::Ready(res)) => Either::A(ok(res)),
|
||||
Err(e) => Either::A(err(e)),
|
||||
Ok(Async::NotReady) => Either::B(Box::new(fut)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -26,7 +26,15 @@ impl<T> Cell<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_ref(&self) -> &T {
|
||||
unsafe { &*self.inner.as_ref().get() }
|
||||
}
|
||||
|
||||
pub(crate) fn get_mut(&mut self) -> &mut T {
|
||||
unsafe { &mut *self.inner.as_ref().get() }
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn get_mut_unsafe(&self) -> &mut T {
|
||||
&mut *self.inner.as_ref().get()
|
||||
}
|
||||
}
|
||||
|
@@ -3,29 +3,30 @@ use std::marker::PhantomData;
|
||||
use futures::future::{ok, Future, FutureResult};
|
||||
use futures::{try_ready, Async, IntoFuture, Poll};
|
||||
|
||||
use crate::{IntoConfigurableNewService, IntoNewService, IntoService, NewService, Service};
|
||||
use crate::{IntoNewService, IntoService, NewService, Service};
|
||||
|
||||
/// Create `NewService` for function that can act as Service
|
||||
pub fn fn_service<F, Req, Out, Cfg>(f: F) -> FnNewService<F, Req, Out, Cfg>
|
||||
/// Create `NewService` for function that can act as a Service
|
||||
pub fn service_fn<F, Req, Out, Cfg>(f: F) -> NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
FnNewService::new(f)
|
||||
NewServiceFn::new(f)
|
||||
}
|
||||
|
||||
/// Create `NewService` for function that can produce services
|
||||
pub fn fn_factory<F, R, S, E>(f: F) -> FnNewServiceNoConfig<F, R, S, E>
|
||||
pub fn new_service_fn<F, C, R, S, E>(f: F) -> FnNewServiceNoConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
FnNewServiceNoConfig::new(f)
|
||||
}
|
||||
|
||||
/// Create `NewService` for function that can produce services with configuration
|
||||
pub fn fn_cfg_factory<F, C, R, S, E>(f: F) -> FnNewServiceConfig<F, C, R, S, E>
|
||||
pub fn new_service_cfg<F, C, R, S, E>(f: F) -> FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Error = E>,
|
||||
@@ -35,39 +36,36 @@ where
|
||||
FnNewServiceConfig::new(f)
|
||||
}
|
||||
|
||||
pub struct FnService<F, Req, Out>
|
||||
pub struct ServiceFn<F, Req, Out>
|
||||
where
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(Req,)>,
|
||||
_t: PhantomData<Req>,
|
||||
}
|
||||
|
||||
impl<F, Req, Out> FnService<F, Req, Out>
|
||||
impl<F, Req, Out> ServiceFn<F, Req, Out>
|
||||
where
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnService { f, _t: PhantomData }
|
||||
pub(crate) fn new(f: F) -> Self {
|
||||
ServiceFn { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out> Clone for FnService<F, Req, Out>
|
||||
impl<F, Req, Out> Clone for ServiceFn<F, Req, Out>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
FnService {
|
||||
f: self.f.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
ServiceFn::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out> Service for FnService<F, Req, Out>
|
||||
impl<F, Req, Out> Service for ServiceFn<F, Req, Out>
|
||||
where
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
@@ -86,17 +84,17 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out> IntoService<FnService<F, Req, Out>> for F
|
||||
impl<F, Req, Out> IntoService<ServiceFn<F, Req, Out>> for F
|
||||
where
|
||||
F: FnMut(Req) -> Out + 'static,
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn into_service(self) -> FnService<F, Req, Out> {
|
||||
FnService::new(self)
|
||||
fn into_service(self) -> ServiceFn<F, Req, Out> {
|
||||
ServiceFn::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FnNewService<F, Req, Out, Cfg>
|
||||
pub struct NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
@@ -105,17 +103,27 @@ where
|
||||
_t: PhantomData<(Req, Cfg)>,
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> FnNewService<F, Req, Out, Cfg>
|
||||
impl<F, Req, Out, Cfg> NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewService { f, _t: PhantomData }
|
||||
pub(crate) fn new(f: F) -> Self {
|
||||
NewServiceFn { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> NewService<Cfg> for FnNewService<F, Req, Out, Cfg>
|
||||
impl<F, Req, Out, Cfg> Clone for NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
NewServiceFn::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> NewService for NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
@@ -123,95 +131,34 @@ where
|
||||
type Request = Req;
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
type Service = FnService<F, Req, Out>;
|
||||
|
||||
type Config = Cfg;
|
||||
type Service = ServiceFn<F, Req, Out>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &Cfg) -> Self::Future {
|
||||
ok(FnService::new(self.f.clone()))
|
||||
ok(ServiceFn::new(self.f.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> Clone for FnNewService<F, Req, Out, Cfg>
|
||||
impl<F, Req, Out, Cfg> IntoService<ServiceFn<F, Req, Out>> for NewServiceFn<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
fn into_service(self) -> ServiceFn<F, Req, Out> {
|
||||
ServiceFn::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> IntoNewService<FnNewService<F, Req, Out, Cfg>, Cfg> for F
|
||||
impl<F, Req, Out, Cfg> IntoNewService<NewServiceFn<F, Req, Out, Cfg>> for F
|
||||
where
|
||||
F: Fn(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewService<F, Req, Out, Cfg> {
|
||||
FnNewService::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converter for `Fn() -> Future<Service>` fn
|
||||
pub struct FnNewServiceNoConfig<F, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<F, R, S, E> FnNewServiceNoConfig<F, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewServiceNoConfig { f }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, S, E> NewService<()> for FnNewServiceNoConfig<F, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S;
|
||||
|
||||
type InitError = E;
|
||||
type Future = R::Future;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
(self.f)().into_future()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, S, E> Clone for FnNewServiceNoConfig<F, R, S, E>
|
||||
where
|
||||
F: Fn() -> R + Clone,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, S, E> IntoNewService<FnNewServiceNoConfig<F, R, S, E>, ()> for F
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewServiceNoConfig<F, R, S, E> {
|
||||
FnNewServiceNoConfig::new(self)
|
||||
fn into_new_service(self) -> NewServiceFn<F, Req, Out, Cfg> {
|
||||
NewServiceFn::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,7 +186,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> NewService<C> for FnNewServiceConfig<F, C, R, S, E>
|
||||
impl<F, C, R, S, E> NewService for FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Error = E>,
|
||||
@@ -249,8 +196,9 @@ where
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S;
|
||||
|
||||
type Config = C;
|
||||
type Service = S;
|
||||
type InitError = E;
|
||||
type Future = FnNewServiceConfigFut<R, S, E>;
|
||||
|
||||
@@ -298,14 +246,65 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> IntoConfigurableNewService<FnNewServiceConfig<F, C, R, S, E>, C> for F
|
||||
/// Converter for `Fn() -> Future<Service>` fn
|
||||
pub struct FnNewServiceNoConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Error = E>,
|
||||
R::Item: IntoService<S>,
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewServiceConfig<F, C, R, S, E> {
|
||||
FnNewServiceConfig::new(self)
|
||||
f: F,
|
||||
_t: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> FnNewServiceNoConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewServiceNoConfig { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> NewService for FnNewServiceNoConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S;
|
||||
type Config = C;
|
||||
type InitError = E;
|
||||
type Future = R::Future;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
(self.f)().into_future()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> Clone for FnNewServiceNoConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn() -> R + Clone,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> IntoNewService<FnNewServiceNoConfig<F, C, R, S, E>> for F
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewServiceNoConfig<F, C, R, S, E> {
|
||||
FnNewServiceNoConfig::new(self)
|
||||
}
|
||||
}
|
||||
|
@@ -3,10 +3,11 @@ use std::marker::PhantomData;
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::IntoFuture;
|
||||
|
||||
use crate::{Apply, IntoTransform, Service, Transform};
|
||||
use crate::apply::Apply;
|
||||
use crate::{IntoTransform, Service, Transform};
|
||||
|
||||
/// Use function as transform service
|
||||
pub fn fn_transform<F, S, In, Out, Err>(
|
||||
pub fn transform_fn<F, S, In, Out, Err>(
|
||||
f: F,
|
||||
) -> impl Transform<S, Request = In, Response = Out::Item, Error = Out::Error, InitError = Err>
|
||||
where
|
||||
|
@@ -81,23 +81,23 @@ where
|
||||
/// service's error.
|
||||
///
|
||||
/// This is created by the `NewServiceExt::from_err` method.
|
||||
pub struct FromErrNewService<A, E, C> {
|
||||
pub struct FromErrNewService<A, E> {
|
||||
a: A,
|
||||
e: PhantomData<(E, C)>,
|
||||
e: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<A, E, C> FromErrNewService<A, E, C> {
|
||||
impl<A, E> FromErrNewService<A, E> {
|
||||
/// Create new `FromErr` new service instance
|
||||
pub fn new(a: A) -> Self
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
Self { a, e: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, E, C> Clone for FromErrNewService<A, E, C>
|
||||
impl<A, E> Clone for FromErrNewService<A, E>
|
||||
where
|
||||
A: Clone,
|
||||
{
|
||||
@@ -109,20 +109,21 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, E, C> NewService<C> for FromErrNewService<A, E, C>
|
||||
impl<A, E> NewService for FromErrNewService<A, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = A::Response;
|
||||
type Error = E;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = FromErr<A::Service, E>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = FromErrNewServiceFuture<A, E, C>;
|
||||
type Future = FromErrNewServiceFuture<A, E>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
FromErrNewServiceFuture {
|
||||
fut: self.a.new_service(cfg),
|
||||
e: PhantomData,
|
||||
@@ -130,18 +131,18 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FromErrNewServiceFuture<A, E, C>
|
||||
pub struct FromErrNewServiceFuture<A, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
fut: A::Future,
|
||||
e: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<A, E, C> Future for FromErrNewServiceFuture<A, E, C>
|
||||
impl<A, E> Future for FromErrNewServiceFuture<A, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
type Item = FromErr<A::Service, E>;
|
||||
|
@@ -1,10 +1,9 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures::{Future, IntoFuture, Poll};
|
||||
|
||||
pub use void::Void;
|
||||
|
||||
mod and_then;
|
||||
mod and_then_apply;
|
||||
mod and_then_apply_fn;
|
||||
@@ -17,40 +16,29 @@ mod fn_service;
|
||||
mod fn_transform;
|
||||
mod from_err;
|
||||
mod map;
|
||||
mod map_config;
|
||||
mod map_err;
|
||||
mod map_init_err;
|
||||
mod then;
|
||||
mod transform;
|
||||
mod transform_err;
|
||||
|
||||
#[doc(hidden)]
|
||||
#[deprecated(since = "0.3.4", note = "please use `apply_fn` instead")]
|
||||
pub use self::apply::Apply;
|
||||
#[doc(hidden)]
|
||||
#[deprecated(since = "0.3.4", note = "please use `apply_fn_factory` instead")]
|
||||
pub use self::apply::ApplyNewService;
|
||||
#[doc(hidden)]
|
||||
#[deprecated(since = "0.3.4", note = "please use `fn_transform` instead")]
|
||||
pub use self::fn_transform::FnTransform;
|
||||
#[doc(hidden)]
|
||||
#[deprecated(since = "0.3.4", note = "please use `apply_transform` instead")]
|
||||
pub use self::transform::ApplyTransform;
|
||||
|
||||
pub use self::and_then::{AndThen, AndThenNewService};
|
||||
use self::and_then_apply::AndThenTransform;
|
||||
use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService};
|
||||
pub use self::apply::{apply_fn, apply_fn_factory};
|
||||
pub use self::apply_cfg::apply_cfg;
|
||||
use self::apply_cfg::ApplyConfig;
|
||||
pub use self::fn_service::{fn_cfg_factory, fn_factory, fn_service, FnService};
|
||||
pub use self::fn_transform::fn_transform;
|
||||
pub use self::apply::{apply_fn, new_apply_fn, Apply, ApplyNewService};
|
||||
pub use self::apply_cfg::{apply_cfg, new_apply_cfg};
|
||||
pub use self::fn_service::{new_service_cfg, new_service_fn, service_fn, ServiceFn};
|
||||
pub use self::fn_transform::transform_fn;
|
||||
pub use self::from_err::{FromErr, FromErrNewService};
|
||||
pub use self::map::{Map, MapNewService};
|
||||
pub use self::map_config::{MapConfig, MappedConfig, UnitConfig};
|
||||
pub use self::map_err::{MapErr, MapErrNewService};
|
||||
pub use self::map_init_err::MapInitErr;
|
||||
pub use self::then::{Then, ThenNewService};
|
||||
pub use self::transform::{apply_transform, IntoTransform, Transform};
|
||||
|
||||
use self::and_then_apply::AndThenTransform;
|
||||
use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService};
|
||||
|
||||
/// An asynchronous function from `Request` to a `Response`.
|
||||
pub trait Service {
|
||||
/// Requests handled by the service.
|
||||
@@ -188,13 +176,13 @@ impl<T: ?Sized> ServiceExt for T where T: Service {}
|
||||
/// Creates new `Service` values.
|
||||
///
|
||||
/// Acts as a service factory. This is useful for cases where new `Service`
|
||||
/// values must be produced. One case is a TCP servier listener. The listner
|
||||
/// values must be produced. One case is a TCP server listener. The listener
|
||||
/// 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.
|
||||
///
|
||||
/// `Config` is a service factory configuration type.
|
||||
pub trait NewService<Config = ()> {
|
||||
pub trait NewService {
|
||||
/// Requests handled by the service.
|
||||
type Request;
|
||||
|
||||
@@ -204,6 +192,9 @@ pub trait NewService<Config = ()> {
|
||||
/// Errors produced by the service
|
||||
type Error;
|
||||
|
||||
/// Service factory configuration
|
||||
type Config;
|
||||
|
||||
/// The `Service` value created by this factory
|
||||
type Service: Service<
|
||||
Request = Self::Request,
|
||||
@@ -218,37 +209,29 @@ pub trait NewService<Config = ()> {
|
||||
type Future: Future<Item = Self::Service, Error = Self::InitError>;
|
||||
|
||||
/// Create and return a new service value asynchronously.
|
||||
fn new_service(&self, cfg: &Config) -> Self::Future;
|
||||
fn new_service(&self, cfg: &Self::Config) -> Self::Future;
|
||||
|
||||
/// Apply transform service to specified service and use it as a next service in
|
||||
/// chain.
|
||||
fn apply<T, T1, B, B1>(
|
||||
self,
|
||||
transform: T1,
|
||||
service: B1,
|
||||
) -> AndThenTransform<T, Self, B, Config>
|
||||
fn apply<T, T1, B, B1>(self, transform: T1, service: B1) -> AndThenTransform<T, Self, B>
|
||||
where
|
||||
Self: Sized,
|
||||
T: Transform<B::Service, Request = Self::Response, InitError = Self::InitError>,
|
||||
T::Error: From<Self::Error>,
|
||||
T1: IntoTransform<T, B::Service>,
|
||||
B: NewService<Config, InitError = Self::InitError>,
|
||||
B1: IntoNewService<B, Config>,
|
||||
B: NewService<Config = Self::Config, InitError = Self::InitError>,
|
||||
B1: IntoNewService<B>,
|
||||
{
|
||||
AndThenTransform::new(transform.into_transform(), self, service.into_new_service())
|
||||
}
|
||||
|
||||
/// Apply function to specified service and use it as a next service in
|
||||
/// chain.
|
||||
fn apply_fn<B, I, F, Out>(
|
||||
self,
|
||||
service: I,
|
||||
f: F,
|
||||
) -> AndThenApplyNewService<Self, B, F, Out, Config>
|
||||
fn apply_fn<B, I, F, Out>(self, service: I, f: F) -> AndThenApplyNewService<Self, B, F, Out>
|
||||
where
|
||||
Self: Sized,
|
||||
B: NewService<Config, Error = Self::Error, InitError = Self::InitError>,
|
||||
I: IntoNewService<B, Config>,
|
||||
B: NewService<Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,
|
||||
I: IntoNewService<B>,
|
||||
F: FnMut(Self::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<Self::Error>,
|
||||
@@ -256,34 +239,13 @@ pub trait NewService<Config = ()> {
|
||||
AndThenApplyNewService::new(self, service, f)
|
||||
}
|
||||
|
||||
/// Map this service's config type to a different config,
|
||||
/// and use for nested service
|
||||
fn apply_cfg<F, C, S, U>(
|
||||
self,
|
||||
service: U,
|
||||
f: F,
|
||||
) -> AndThenNewService<Self, ApplyConfig<F, S, Config, C>, Config>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(&Config) -> C,
|
||||
U: IntoNewService<S, C>,
|
||||
S: NewService<
|
||||
C,
|
||||
Request = Self::Response,
|
||||
Error = Self::Error,
|
||||
InitError = Self::InitError,
|
||||
>,
|
||||
{
|
||||
self.and_then(ApplyConfig::new(service, f))
|
||||
}
|
||||
|
||||
/// Call another service after call to this one has resolved successfully.
|
||||
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B, Config>
|
||||
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B>
|
||||
where
|
||||
Self: Sized,
|
||||
F: IntoNewService<B, Config>,
|
||||
F: IntoNewService<B>,
|
||||
B: NewService<
|
||||
Config,
|
||||
Config = Self::Config,
|
||||
Request = Self::Response,
|
||||
Error = Self::Error,
|
||||
InitError = Self::InitError,
|
||||
@@ -298,7 +260,7 @@ pub trait NewService<Config = ()> {
|
||||
///
|
||||
/// Note that this function consumes the receiving new service and returns a
|
||||
/// wrapped version of it.
|
||||
fn from_err<E>(self) -> FromErrNewService<Self, E, Config>
|
||||
fn from_err<E>(self) -> FromErrNewService<Self, E>
|
||||
where
|
||||
Self: Sized,
|
||||
E: From<Self::Error>,
|
||||
@@ -312,12 +274,12 @@ pub trait NewService<Config = ()> {
|
||||
///
|
||||
/// Note that this function consumes the receiving future and returns a
|
||||
/// wrapped version of it.
|
||||
fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B, Config>
|
||||
fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B>
|
||||
where
|
||||
Self: Sized,
|
||||
F: IntoNewService<B, Config>,
|
||||
F: IntoNewService<B>,
|
||||
B: NewService<
|
||||
Config,
|
||||
Config = Self::Config,
|
||||
Request = Result<Self::Response, Self::Error>,
|
||||
Error = Self::Error,
|
||||
InitError = Self::InitError,
|
||||
@@ -328,7 +290,7 @@ pub trait NewService<Config = ()> {
|
||||
|
||||
/// Map this service's output to a different type, returning a new service
|
||||
/// of the resulting type.
|
||||
fn map<F, R>(self, f: F) -> MapNewService<Self, F, R, Config>
|
||||
fn map<F, R>(self, f: F) -> MapNewService<Self, F, R>
|
||||
where
|
||||
Self: Sized,
|
||||
F: FnMut(Self::Response) -> R,
|
||||
@@ -337,7 +299,7 @@ pub trait NewService<Config = ()> {
|
||||
}
|
||||
|
||||
/// Map this service's error to a different error, returning a new service.
|
||||
fn map_err<F, E>(self, f: F) -> MapErrNewService<Self, F, E, Config>
|
||||
fn map_err<F, E>(self, f: F) -> MapErrNewService<Self, F, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::Error) -> E + Clone,
|
||||
@@ -345,14 +307,31 @@ pub trait NewService<Config = ()> {
|
||||
MapErrNewService::new(self, f)
|
||||
}
|
||||
|
||||
/// Map this service's init error to a different error, returning a new service.
|
||||
fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, E, Config>
|
||||
/// Map this factory's init error to a different error, returning a new service.
|
||||
fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::InitError) -> E,
|
||||
{
|
||||
MapInitErr::new(self, f)
|
||||
}
|
||||
|
||||
/// Map config to a different error, returning a new service.
|
||||
fn map_config<F, C>(self, f: F) -> MapConfig<Self, F, C>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(&C) -> MappedConfig<Self::Config>,
|
||||
{
|
||||
MapConfig::new(self, f)
|
||||
}
|
||||
|
||||
/// Replace config with unit
|
||||
fn unit_config<C>(self) -> UnitConfig<Self, C>
|
||||
where
|
||||
Self: NewService<Config = ()> + Sized,
|
||||
{
|
||||
UnitConfig::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, S> Service for &'a mut S
|
||||
@@ -391,34 +370,54 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, C> NewService<C> for Rc<S>
|
||||
impl<S> Service for Rc<RefCell<S>>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: Service,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Future = S::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), S::Error> {
|
||||
self.borrow_mut().poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Self::Request) -> S::Future {
|
||||
self.borrow_mut().call(request)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> NewService for Rc<S>
|
||||
where
|
||||
S: NewService,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Config = S::Config;
|
||||
type Service = S::Service;
|
||||
type InitError = S::InitError;
|
||||
type Future = S::Future;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> S::Future {
|
||||
fn new_service(&self, cfg: &S::Config) -> S::Future {
|
||||
self.as_ref().new_service(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, C> NewService<C> for Arc<S>
|
||||
impl<S> NewService for Arc<S>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Config = S::Config;
|
||||
type Service = S::Service;
|
||||
type InitError = S::InitError;
|
||||
type Future = S::Future;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> S::Future {
|
||||
fn new_service(&self, cfg: &S::Config) -> S::Future {
|
||||
self.as_ref().new_service(cfg)
|
||||
}
|
||||
}
|
||||
@@ -433,9 +432,9 @@ where
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a `NewService`
|
||||
pub trait IntoNewService<T, C = ()>
|
||||
pub trait IntoNewService<T>
|
||||
where
|
||||
T: NewService<C>,
|
||||
T: NewService,
|
||||
{
|
||||
/// Convert to an `NewService`
|
||||
fn into_new_service(self) -> T;
|
||||
@@ -450,27 +449,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, C> IntoNewService<T, C> for T
|
||||
impl<T> IntoNewService<T> for T
|
||||
where
|
||||
T: NewService<C>,
|
||||
{
|
||||
fn into_new_service(self) -> T {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a configurable `NewService`
|
||||
pub trait IntoConfigurableNewService<T, C>
|
||||
where
|
||||
T: NewService<C>,
|
||||
{
|
||||
/// Convert to an `NewService`
|
||||
fn into_new_service(self) -> T;
|
||||
}
|
||||
|
||||
impl<T, C> IntoConfigurableNewService<T, C> for T
|
||||
where
|
||||
T: NewService<C>,
|
||||
T: NewService,
|
||||
{
|
||||
fn into_new_service(self) -> T {
|
||||
self
|
||||
|
@@ -97,17 +97,17 @@ where
|
||||
}
|
||||
|
||||
/// `MapNewService` new service combinator
|
||||
pub struct MapNewService<A, F, Res, Cfg> {
|
||||
pub struct MapNewService<A, F, Res> {
|
||||
a: A,
|
||||
f: F,
|
||||
r: PhantomData<(Res, Cfg)>,
|
||||
r: PhantomData<Res>,
|
||||
}
|
||||
|
||||
impl<A, F, Res, Cfg> MapNewService<A, F, Res, Cfg> {
|
||||
impl<A, F, Res> MapNewService<A, F, Res> {
|
||||
/// Create new `Map` new service instance
|
||||
pub fn new(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
Self {
|
||||
@@ -118,7 +118,7 @@ impl<A, F, Res, Cfg> MapNewService<A, F, Res, Cfg> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Res, Cfg> Clone for MapNewService<A, F, Res, Cfg>
|
||||
impl<A, F, Res> Clone for MapNewService<A, F, Res>
|
||||
where
|
||||
A: Clone,
|
||||
F: Clone,
|
||||
@@ -132,36 +132,37 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Res, Cfg> NewService<Cfg> for MapNewService<A, F, Res, Cfg>
|
||||
impl<A, F, Res> NewService for MapNewService<A, F, Res>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Res + Clone,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = Res;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = Map<A::Service, F, Res>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = MapNewServiceFuture<A, F, Res, Cfg>;
|
||||
type Future = MapNewServiceFuture<A, F, Res>;
|
||||
|
||||
fn new_service(&self, cfg: &Cfg) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
MapNewServiceFuture::new(self.a.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapNewServiceFuture<A, F, Res, Cfg>
|
||||
pub struct MapNewServiceFuture<A, F, Res>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
fut: A::Future,
|
||||
f: Option<F>,
|
||||
}
|
||||
|
||||
impl<A, F, Res, Cfg> MapNewServiceFuture<A, F, Res, Cfg>
|
||||
impl<A, F, Res> MapNewServiceFuture<A, F, Res>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
@@ -169,9 +170,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Res, Cfg> Future for MapNewServiceFuture<A, F, Res, Cfg>
|
||||
impl<A, F, Res> Future for MapNewServiceFuture<A, F, Res>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
type Item = Map<A::Service, F, Res>;
|
||||
|
112
actix-service/src/map_config.rs
Normal file
112
actix-service/src/map_config.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use super::NewService;
|
||||
|
||||
pub enum MappedConfig<'a, T> {
|
||||
Ref(&'a T),
|
||||
Owned(T),
|
||||
}
|
||||
|
||||
/// `MapInitErr` service combinator
|
||||
pub struct MapConfig<A, F, C> {
|
||||
a: A,
|
||||
f: F,
|
||||
e: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<A, F, C> MapConfig<A, F, C> {
|
||||
/// Create new `MapConfig` combinator
|
||||
pub fn new(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService,
|
||||
F: Fn(&C) -> MappedConfig<A::Config>,
|
||||
{
|
||||
Self {
|
||||
a,
|
||||
f,
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, C> Clone for MapConfig<A, F, C>
|
||||
where
|
||||
A: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
f: self.f.clone(),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, C> NewService for MapConfig<A, F, C>
|
||||
where
|
||||
A: NewService,
|
||||
F: Fn(&C) -> MappedConfig<A::Config>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = A::Response;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = C;
|
||||
type Service = A::Service;
|
||||
type InitError = A::InitError;
|
||||
type Future = A::Future;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
match (self.f)(cfg) {
|
||||
MappedConfig::Ref(cfg) => self.a.new_service(cfg),
|
||||
MappedConfig::Owned(cfg) => self.a.new_service(&cfg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `MapInitErr` service combinator
|
||||
pub struct UnitConfig<A, C> {
|
||||
a: A,
|
||||
e: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<A, C> UnitConfig<A, C> {
|
||||
/// Create new `UnitConfig` combinator
|
||||
pub fn new(a: A) -> Self
|
||||
where
|
||||
A: NewService<Config = ()>,
|
||||
{
|
||||
Self { a, e: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, C> Clone for UnitConfig<A, C>
|
||||
where
|
||||
A: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, C> NewService for UnitConfig<A, C>
|
||||
where
|
||||
A: NewService<Config = ()>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = A::Response;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = C;
|
||||
type Service = A::Service;
|
||||
type InitError = A::InitError;
|
||||
type Future = A::Future;
|
||||
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
self.a.new_service(&())
|
||||
}
|
||||
}
|
@@ -98,19 +98,19 @@ where
|
||||
/// service's error.
|
||||
///
|
||||
/// This is created by the `NewServiceExt::map_err` method.
|
||||
pub struct MapErrNewService<A, F, E, C>
|
||||
pub struct MapErrNewService<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
a: A,
|
||||
f: F,
|
||||
e: PhantomData<(E, C)>,
|
||||
e: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<A, F, E, C> MapErrNewService<A, F, E, C>
|
||||
impl<A, F, E> MapErrNewService<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
/// Create new `MapErr` new service instance
|
||||
@@ -123,9 +123,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> Clone for MapErrNewService<A, F, E, C>
|
||||
impl<A, F, E> Clone for MapErrNewService<A, F, E>
|
||||
where
|
||||
A: NewService<C> + Clone,
|
||||
A: NewService + Clone,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
@@ -137,36 +137,37 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> NewService<C> for MapErrNewService<A, F, E, C>
|
||||
impl<A, F, E> NewService for MapErrNewService<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = A::Response;
|
||||
type Error = E;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = MapErr<A::Service, F, E>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = MapErrNewServiceFuture<A, F, E, C>;
|
||||
type Future = MapErrNewServiceFuture<A, F, E>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
MapErrNewServiceFuture::new(self.a.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapErrNewServiceFuture<A, F, E, C>
|
||||
pub struct MapErrNewServiceFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
fut: A::Future,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<A, F, E, C> MapErrNewServiceFuture<A, F, E, C>
|
||||
impl<A, F, E> MapErrNewServiceFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
@@ -174,9 +175,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> Future for MapErrNewServiceFuture<A, F, E, C>
|
||||
impl<A, F, E> Future for MapErrNewServiceFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
type Item = MapErr<A::Service, F, E>;
|
||||
|
@@ -5,17 +5,17 @@ use futures::{Future, Poll};
|
||||
use super::NewService;
|
||||
|
||||
/// `MapInitErr` service combinator
|
||||
pub struct MapInitErr<A, F, E, C> {
|
||||
pub struct MapInitErr<A, F, E> {
|
||||
a: A,
|
||||
f: F,
|
||||
e: PhantomData<(E, C)>,
|
||||
e: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<A, F, E, C> MapInitErr<A, F, E, C> {
|
||||
impl<A, F, E> MapInitErr<A, F, E> {
|
||||
/// Create new `MapInitErr` combinator
|
||||
pub fn new(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
Self {
|
||||
@@ -26,7 +26,7 @@ impl<A, F, E, C> MapInitErr<A, F, E, C> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> Clone for MapInitErr<A, F, E, C>
|
||||
impl<A, F, E> Clone for MapInitErr<A, F, E>
|
||||
where
|
||||
A: Clone,
|
||||
F: Clone,
|
||||
@@ -40,36 +40,37 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> NewService<C> for MapInitErr<A, F, E, C>
|
||||
impl<A, F, E> NewService for MapInitErr<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::InitError) -> E + Clone,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = A::Response;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = A::Service;
|
||||
|
||||
type InitError = E;
|
||||
type Future = MapInitErrFuture<A, F, E, C>;
|
||||
type Future = MapInitErrFuture<A, F, E>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
MapInitErrFuture::new(self.a.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapInitErrFuture<A, F, E, C>
|
||||
pub struct MapInitErrFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
f: F,
|
||||
fut: A::Future,
|
||||
}
|
||||
|
||||
impl<A, F, E, C> MapInitErrFuture<A, F, E, C>
|
||||
impl<A, F, E> MapInitErrFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
@@ -77,9 +78,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> Future for MapInitErrFuture<A, F, E, C>
|
||||
impl<A, F, E> Future for MapInitErrFuture<A, F, E>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
type Item = A::Service;
|
||||
|
@@ -1,5 +1,3 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::{IntoNewService, NewService, Service};
|
||||
@@ -115,38 +113,36 @@ where
|
||||
}
|
||||
|
||||
/// `ThenNewService` new service combinator
|
||||
pub struct ThenNewService<A, B, C> {
|
||||
pub struct ThenNewService<A, B> {
|
||||
a: A,
|
||||
b: B,
|
||||
_t: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<A, B, C> ThenNewService<A, B, C> {
|
||||
impl<A, B> ThenNewService<A, B> {
|
||||
/// Create new `AndThen` combinator
|
||||
pub fn new<F>(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Config = A::Config,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
F: IntoNewService<B, C>,
|
||||
F: IntoNewService<B>,
|
||||
{
|
||||
Self {
|
||||
a,
|
||||
b: f.into_new_service(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> NewService<C> for ThenNewService<A, B, C>
|
||||
impl<A, B> NewService for ThenNewService<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Config = A::Config,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
@@ -155,17 +151,18 @@ where
|
||||
type Request = A::Request;
|
||||
type Response = B::Response;
|
||||
type Error = A::Error;
|
||||
|
||||
type Config = A::Config;
|
||||
type Service = Then<A::Service, B::Service>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = ThenNewServiceFuture<A, B, C>;
|
||||
type Future = ThenNewServiceFuture<A, B>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
ThenNewServiceFuture::new(self.a.new_service(cfg), self.b.new_service(cfg))
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> Clone for ThenNewService<A, B, C>
|
||||
impl<A, B> Clone for ThenNewService<A, B>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
@@ -174,16 +171,15 @@ where
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ThenNewServiceFuture<A, B, C>
|
||||
pub struct ThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Config = A::Config,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
@@ -195,11 +191,11 @@ where
|
||||
b: Option<B::Service>,
|
||||
}
|
||||
|
||||
impl<A, B, C> ThenNewServiceFuture<A, B, C>
|
||||
impl<A, B> ThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Config = A::Config,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
@@ -215,11 +211,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, C> Future for ThenNewServiceFuture<A, B, C>
|
||||
impl<A, B> Future for ThenNewServiceFuture<A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
A: NewService,
|
||||
B: NewService<
|
||||
C,
|
||||
Config = A::Config,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
|
@@ -6,10 +6,11 @@ use futures::{Async, Future, IntoFuture, Poll};
|
||||
use crate::transform_err::{TransformFromErr, TransformMapInitErr};
|
||||
use crate::{IntoNewService, NewService, Service};
|
||||
|
||||
/// `Transform` service factory.
|
||||
///
|
||||
/// Transform factory creates service that wraps other services.
|
||||
/// `Config` is a service factory configuration type.
|
||||
/// The `Transform` trait defines the interface of a Service factory. `Transform`
|
||||
/// is often implemented for middleware, defining how to construct a
|
||||
/// middleware Service. A Service that is constructed by the factory takes
|
||||
/// the Service that follows it during execution as a parameter, assuming
|
||||
/// ownership of the next Service.
|
||||
pub trait Transform<S> {
|
||||
/// Requests handled by the service.
|
||||
type Request;
|
||||
@@ -33,7 +34,7 @@ pub trait Transform<S> {
|
||||
/// The future response value.
|
||||
type Future: Future<Item = Self::Transform, Error = Self::InitError>;
|
||||
|
||||
/// Create and return a new service value asynchronously.
|
||||
/// Creates and returns a new Service component, asynchronously
|
||||
fn new_transform(&self, service: S) -> Self::Future;
|
||||
|
||||
/// Map this service's factory error to a different error,
|
||||
@@ -126,11 +127,11 @@ where
|
||||
/// Apply transform to service factory. Function returns
|
||||
/// services factory that in initialization creates
|
||||
/// service and applies transform to this service.
|
||||
pub fn apply_transform<T, S, C, F, U>(
|
||||
pub fn apply_transform<T, S, F, U>(
|
||||
t: F,
|
||||
service: U,
|
||||
) -> impl NewService<
|
||||
C,
|
||||
Config = S::Config,
|
||||
Request = T::Request,
|
||||
Response = T::Response,
|
||||
Error = T::Error,
|
||||
@@ -138,24 +139,23 @@ pub fn apply_transform<T, S, C, F, U>(
|
||||
InitError = S::InitError,
|
||||
> + Clone
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
F: IntoTransform<T, S::Service>,
|
||||
U: IntoNewService<S, C>,
|
||||
U: IntoNewService<S>,
|
||||
{
|
||||
ApplyTransform::new(t.into_transform(), service.into_new_service())
|
||||
}
|
||||
|
||||
/// `Apply` transform to new service
|
||||
pub struct ApplyTransform<T, S, C> {
|
||||
pub struct ApplyTransform<T, S> {
|
||||
s: Rc<S>,
|
||||
t: Rc<T>,
|
||||
_t: std::marker::PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<T, S, C> ApplyTransform<T, S, C>
|
||||
impl<T, S> ApplyTransform<T, S>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
{
|
||||
/// Create new `ApplyTransform` new service instance
|
||||
@@ -163,35 +163,34 @@ where
|
||||
Self {
|
||||
s: Rc::new(service),
|
||||
t: Rc::new(t.into_transform()),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C> Clone for ApplyTransform<T, S, C> {
|
||||
impl<T, S> Clone for ApplyTransform<T, S> {
|
||||
fn clone(&self) -> Self {
|
||||
ApplyTransform {
|
||||
s: self.s.clone(),
|
||||
t: self.t.clone(),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C> NewService<C> for ApplyTransform<T, S, C>
|
||||
impl<T, S> NewService for ApplyTransform<T, S>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
|
||||
type Config = S::Config;
|
||||
type Service = T::Transform;
|
||||
type InitError = T::InitError;
|
||||
type Future = ApplyTransformFuture<T, S, C>;
|
||||
type Future = ApplyTransformFuture<T, S>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
fn new_service(&self, cfg: &S::Config) -> Self::Future {
|
||||
ApplyTransformFuture {
|
||||
t_cell: self.t.clone(),
|
||||
fut_a: self.s.new_service(cfg).into_future(),
|
||||
@@ -200,9 +199,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ApplyTransformFuture<T, S, C>
|
||||
pub struct ApplyTransformFuture<T, S>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
{
|
||||
fut_a: S::Future,
|
||||
@@ -210,9 +209,9 @@ where
|
||||
t_cell: Rc<T>,
|
||||
}
|
||||
|
||||
impl<T, S, C> Future for ApplyTransformFuture<T, S, C>
|
||||
impl<T, S> Future for ApplyTransformFuture<T, S>
|
||||
where
|
||||
S: NewService<C>,
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
{
|
||||
type Item = T::Transform;
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-test-server"
|
||||
version = "0.2.0"
|
||||
version = "0.2.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix test server"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -11,7 +11,7 @@ categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
workspace = ".."
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "tls", "rust-tls"]
|
||||
@@ -34,7 +34,7 @@ rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
|
||||
|
||||
[dependencies]
|
||||
actix-rt = "0.2.1"
|
||||
actix-server = "0.4.0"
|
||||
actix-server = "0.5.0"
|
||||
actix-server-config = "0.1.0"
|
||||
|
||||
log = "0.4"
|
||||
@@ -56,4 +56,4 @@ webpki = { version = "0.19", optional = true }
|
||||
webpki-roots = { version = "0.16", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-service = "0.3.4"
|
||||
actix-service = "0.4.0"
|
||||
|
1
actix-test-server/LICENSE-APACHE
Symbolic link
1
actix-test-server/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-test-server/LICENSE-MIT
Symbolic link
1
actix-test-server/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -6,7 +6,7 @@ use actix_rt::{Runtime, System};
|
||||
use actix_server::{Server, StreamServiceFactory};
|
||||
pub use actix_server_config::{Io, ServerConfig};
|
||||
|
||||
use futures::Future;
|
||||
use futures::future::{lazy, Future, IntoFuture};
|
||||
use net2::TcpBuilder;
|
||||
use tokio_reactor::Handle;
|
||||
use tokio_tcp::TcpStream;
|
||||
@@ -19,11 +19,11 @@ use tokio_tcp::TcpStream;
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_service::{fn_service, IntoNewService};
|
||||
/// use actix_service::{service_fn, IntoNewService};
|
||||
/// use actix_test_server::TestServer;
|
||||
///
|
||||
/// fn main() {
|
||||
/// let srv = TestServer::with(|| fn_service(
|
||||
/// let srv = TestServer::with(|| service_fn(
|
||||
/// |sock| {
|
||||
/// println!("New connection: {:?}", sock);
|
||||
/// Ok::<_, ()>(())
|
||||
@@ -99,6 +99,15 @@ impl TestServerRuntime {
|
||||
self.rt.block_on(fut)
|
||||
}
|
||||
|
||||
/// Runs the provided function, with runtime enabled.
|
||||
pub fn run_on<F, R>(&mut self, f: F) -> Result<R::Item, R::Error>
|
||||
where
|
||||
F: FnOnce() -> R,
|
||||
R: IntoFuture,
|
||||
{
|
||||
self.rt.block_on(lazy(|| f().into_future()))
|
||||
}
|
||||
|
||||
/// Spawn future to the current runtime
|
||||
pub fn spawn<F>(&mut self, fut: F)
|
||||
where
|
||||
|
17
actix-threadpool/CHANGES.md
Normal file
17
actix-threadpool/CHANGES.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.2] - 2019-08-05
|
||||
|
||||
### Changed
|
||||
|
||||
* Update `derive_more` to 0.15
|
||||
|
||||
* Update `parking_lot` to 0.9
|
||||
|
||||
## [0.1.1] - 2019-06-05
|
||||
|
||||
* Update parking_lot
|
||||
|
||||
## [0.1.0] - 2019-03-28
|
||||
|
||||
* Move threadpool to separate crate
|
27
actix-threadpool/Cargo.toml
Normal file
27
actix-threadpool/Cargo.toml
Normal file
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "actix-threadpool"
|
||||
version = "0.1.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix thread pool for sync code"
|
||||
keywords = ["actix", "network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-threadpool/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "actix_threadpool"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
derive_more = "0.15"
|
||||
futures = "0.1.25"
|
||||
parking_lot = "0.9"
|
||||
lazy_static = "1.2"
|
||||
log = "0.4"
|
||||
num_cpus = "1.10"
|
||||
threadpool = "1.7"
|
1
actix-threadpool/LICENSE-APACHE
Symbolic link
1
actix-threadpool/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
1
actix-threadpool/LICENSE-MIT
Symbolic link
1
actix-threadpool/LICENSE-MIT
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-MIT
|
@@ -9,7 +9,7 @@ use parking_lot::Mutex;
|
||||
use threadpool::ThreadPool;
|
||||
|
||||
/// Env variable for default cpu pool size
|
||||
const ENV_CPU_POOL_VAR: &str = "ACTIX_CPU_POOL";
|
||||
const ENV_CPU_POOL_VAR: &str = "ACTIX_THREADPOOL";
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub(crate) static ref DEFAULT_POOL: Mutex<ThreadPool> = {
|
||||
@@ -18,7 +18,7 @@ lazy_static::lazy_static! {
|
||||
if let Ok(val) = val.parse() {
|
||||
val
|
||||
} else {
|
||||
log::error!("Can not parse ACTIX_CPU_POOL value");
|
||||
log::error!("Can not parse ACTIX_THREADPOOL value");
|
||||
num_cpus::get() * 5
|
||||
}
|
||||
}
|
2
actix-tower/CHANGES.md
Normal file
2
actix-tower/CHANGES.md
Normal file
@@ -0,0 +1,2 @@
|
||||
# Changes
|
||||
|
29
actix-tower/Cargo.toml
Normal file
29
actix-tower/Cargo.toml
Normal file
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "actix-tower"
|
||||
version = "0.1.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>", "Marcus Griep <marcus@griep.us>"]
|
||||
description = "Actix Tower"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-tower/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "actix/actix-tower", branch = "master" }
|
||||
appveyor = { repository = "actix/actix-net" }
|
||||
codecov = { repository = "actix/actix-tower", branch = "master", service = "github" }
|
||||
|
||||
[lib]
|
||||
name = "actix_tower"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.3.6"
|
||||
futures = "0.1.24"
|
||||
tower-service = "0.2.0"
|
||||
|
1
actix-tower/LICENSE-APACHE
Symbolic link
1
actix-tower/LICENSE-APACHE
Symbolic link
@@ -0,0 +1 @@
|
||||
../LICENSE-APACHE
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user