mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-12 14:27:05 +02:00
Compare commits
208 Commits
server-v0.
...
rt-0.2.5
Author | SHA1 | Date | |
---|---|---|---|
|
94e673b50b | ||
|
1a644c6bb1 | ||
|
aad013f559 | ||
|
7a18d9da26 | ||
|
d59b8ce62e | ||
|
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 | ||
|
720230b852 | ||
|
44c2639fd6 | ||
|
9a5705d1b6 | ||
|
7ff923a58f | ||
|
6659b192d3 | ||
|
1146d9cf30 | ||
|
b7b76c47e5 | ||
|
d23dc6f6af | ||
|
9b6a955da4 | ||
|
f3aa48309f | ||
|
c9b86712e5 | ||
|
0f74f280f9 | ||
|
eb37e15554 | ||
|
ad007b8b42 | ||
|
7c0d1f2273 | ||
|
d82bc7c52b | ||
|
265229b44b | ||
|
38545dedc7 | ||
|
6ebff22601 | ||
|
2c9b91b366 | ||
|
b483200037 | ||
|
a73600fbcd | ||
|
084a28ca07 | ||
|
a7c74c53ea | ||
|
3e7d737e73 | ||
|
87db4bf741 | ||
|
8b0fe6f796 | ||
|
52a45fda53 | ||
|
2c7de7e0fb | ||
|
1fcc0734b5 | ||
|
b6f952b036 | ||
|
0fdac38307 | ||
|
a3c4637372 | ||
|
ae9bc5ae78 | ||
|
21c289d7e4 | ||
|
5e6eed905c | ||
|
6801a38de5 | ||
|
39356690b0 | ||
|
f6f292a678 | ||
|
b3366bc1af | ||
|
2c1f8f0b96 | ||
|
e7465bfa2e | ||
|
755d4958c5 | ||
|
825117fd4c | ||
|
7033b50fed | ||
|
ef9bfb8981 | ||
|
bef199f831 | ||
|
f1d4bcef4b | ||
|
8e13ba7bce | ||
|
9a9b3e9ca9 | ||
|
5567fb41d2 | ||
|
ad50595ece | ||
|
2430c7247b | ||
|
1bf0f1e1a5 | ||
|
9887aef6e8 | ||
|
787255d030 | ||
|
f696914038 | ||
|
3618f542fb | ||
|
1f54ae9051 | ||
|
86f57e5a4a | ||
|
43ad18ccb1 | ||
|
34995a8ccf | ||
|
0ff300c40f | ||
|
629ef23371 | ||
|
d2b96ff877 | ||
|
ac62e2dbf9 | ||
|
6bbbdba921 | ||
|
2099629fe3 | ||
|
a4d4770462 | ||
|
70ead175b9 | ||
|
49867b5e9d | ||
|
0f064c43e9 | ||
|
7db29544f9 | ||
|
4850cf41ff | ||
|
046142ffbc | ||
|
49e6dbcda2 | ||
|
877614a494 | ||
|
ac0e8b9e53 | ||
|
b407c65f4c | ||
|
51bd7d2721 | ||
|
c03d869694 | ||
|
25f1eae51f | ||
|
1153715149 | ||
|
aa2967c653 | ||
|
dfbb77f98d | ||
|
e8a49801eb | ||
|
03f2046a42 | ||
|
2e18ca805c | ||
|
15dafeff3d | ||
|
ed14e6b8ea | ||
|
700abc997e | ||
|
8c48bf4de7 | ||
|
9bc492cf6c | ||
|
d2a223e69e | ||
|
e9657a399a | ||
|
9f25fdf929 | ||
|
82930de8e7 | ||
|
04a3e59bd5 | ||
|
0ff0daa795 | ||
|
fb43940824 | ||
|
0410f59cf5 | ||
|
400023a07b |
37
.travis.yml
37
.travis.yml
@@ -10,9 +10,10 @@ matrix:
|
||||
include:
|
||||
- rust: stable
|
||||
- rust: beta
|
||||
- rust: nightly
|
||||
- rust: 1.36.0
|
||||
- rust: nightly-2019-06-15
|
||||
allow_failures:
|
||||
- rust: nightly
|
||||
- rust: nightly-2019-06-15
|
||||
|
||||
env:
|
||||
global:
|
||||
@@ -24,34 +25,26 @@ before_install:
|
||||
- sudo apt-get update -qq
|
||||
- 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-06-15" ]]; then
|
||||
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install --version 0.6.11 cargo-tarpaulin
|
||||
fi
|
||||
|
||||
# Add clippy
|
||||
before_script:
|
||||
- export PATH=$PATH:~/.cargo/bin
|
||||
|
||||
script:
|
||||
- |
|
||||
if [[ "$TRAVIS_RUST_VERSION" != "nightly" ]]; 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 --features="ssl,tls,rust-tls" -- --nocapture && cd ..
|
||||
cd actix-rt && cargo test && cd ..
|
||||
cd actix-connector && 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" ]]; then
|
||||
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install -f cargo-tarpaulin
|
||||
cargo tarpaulin --features="ssl,tls,rust-tls" --out Xml
|
||||
bash <(curl -s https://codecov.io/bash)
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly-2019-06-15" ]]; then
|
||||
taskset -c 0 cargo tarpaulin --all --all-features --out Xml
|
||||
echo "Uploaded code coverage"
|
||||
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-connector && 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 ..
|
||||
bash <(curl -s https://codecov.io/bash)
|
||||
fi
|
||||
|
32
Cargo.toml
32
Cargo.toml
@@ -1,11 +1,41 @@
|
||||
[package]
|
||||
name = "actix-net"
|
||||
version = "0.3.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix net - framework for the composable network services for Rust"
|
||||
readme = "README.md"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-net/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
"actix-codec",
|
||||
"actix-connector",
|
||||
"actix-connect",
|
||||
"actix-rt",
|
||||
"actix-service",
|
||||
"actix-server",
|
||||
"actix-server-config",
|
||||
"actix-test-server",
|
||||
"actix-threadpool",
|
||||
"actix-tower",
|
||||
"actix-ioframe",
|
||||
"actix-utils",
|
||||
"router",
|
||||
]
|
||||
|
||||
[dev-dependencies]
|
||||
actix-service = "0.4.0"
|
||||
actix-codec = "0.1.1"
|
||||
actix-rt = "0.2.0"
|
||||
actix-server = { version="0.5.0", features=["ssl"] }
|
||||
env_logger = "0.6"
|
||||
futures = "0.1.25"
|
||||
openssl = "0.10"
|
||||
tokio-tcp = "0.1"
|
||||
tokio-openssl = "0.3"
|
||||
|
49
README.md
49
README.md
@@ -1,20 +1,18 @@
|
||||
# Actix net [](https://travis-ci.org/actix/actix-net) [](https://codecov.io/gh/actix/actix-net) [](https://crates.io/crates/actix-net) [](https://gitter.im/actix/actix?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
Actix net - framework for composable network services (experimental)
|
||||
Actix net - framework for composable network services
|
||||
|
||||
## Documentation & community resources
|
||||
|
||||
* [API Documentation (Development)](https://actix.rs/actix-net/actix_net/)
|
||||
* [Chat on gitter](https://gitter.im/actix/actix)
|
||||
* Cargo package: [actix-net](https://crates.io/crates/actix-net)
|
||||
* Minimum supported Rust version: 1.26 or later
|
||||
* Minimum supported Rust version: 1.36 or later
|
||||
|
||||
## Example
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
let sys = actix_rt::System::new("test");
|
||||
|
||||
fn main() -> io::Result<()> {
|
||||
// load ssl keys
|
||||
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
|
||||
builder.set_private_key_file("./examples/key.pem", SslFiletype::PEM).unwrap();
|
||||
@@ -26,7 +24,7 @@ fn main() {
|
||||
// bind socket address and start workers. By default server uses number of
|
||||
// available logical cpu as threads count. actix net start separate
|
||||
// instances of service pipeline in each worker.
|
||||
actix_server::build()
|
||||
Server::build()
|
||||
.bind(
|
||||
// configure service pipeline
|
||||
"basic", "0.0.0.0:8443",
|
||||
@@ -35,28 +33,23 @@ fn main() {
|
||||
let acceptor = acceptor.clone();
|
||||
|
||||
// service for converting incoming TcpStream to a SslStream<TcpStream>
|
||||
(move |stream| {
|
||||
SslAcceptorExt::accept_async(&acceptor, stream)
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
})
|
||||
// convert closure to a `NewService`
|
||||
.into_new_service()
|
||||
|
||||
// .and_then() combinator uses other service to convert incoming `Request` to a `Response`
|
||||
// and then uses that response as an input for next service.
|
||||
// in this case, on success we use `logger` service
|
||||
.and_then(logger)
|
||||
|
||||
// Next service counts number of connections
|
||||
.and_then(move |req| {
|
||||
let num = num.fetch_add(1, Ordering::Relaxed);
|
||||
println!("processed {:?} connections", num);
|
||||
future::ok(())
|
||||
})
|
||||
}).unwrap()
|
||||
.start();
|
||||
|
||||
sys.run();
|
||||
fn_service(move |stream: Io<tokio_tcp::TcpStream>| {
|
||||
SslAcceptorExt::accept_async(&acceptor, stream.into_parts().0)
|
||||
.map_err(|e| println!("Openssl error: {}", e))
|
||||
})
|
||||
// .and_then() combinator uses other service to convert incoming `Request` to a
|
||||
// `Response` and then uses that response as an input for next
|
||||
// service. in this case, on success we use `logger` service
|
||||
.and_then(fn_service(logger))
|
||||
// Next service counts number of connections
|
||||
.and_then(move |_| {
|
||||
let num = num.fetch_add(1, Ordering::Relaxed);
|
||||
println!("got ssl connection {:?}", num);
|
||||
future::ok(())
|
||||
})
|
||||
},
|
||||
)?
|
||||
.run()
|
||||
}
|
||||
```
|
||||
|
||||
|
@@ -1,5 +1,15 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.2] - 2019-03-27
|
||||
|
||||
* Added `Framed::map_io()` method.
|
||||
|
||||
|
||||
## [0.1.1] - 2019-03-06
|
||||
|
||||
* Added `FramedParts::with_read_buffer()` method.
|
||||
|
||||
|
||||
## [0.1.0] - 2018-12-09
|
||||
|
||||
* Move codec to separate crate
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-codec"
|
||||
version = "0.1.0"
|
||||
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
|
||||
@@ -349,4 +365,17 @@ impl<T, U> FramedParts<T, U> {
|
||||
_priv: (),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new `FramedParts` with read buffer
|
||||
pub fn with_read_buf(io: T, codec: U, read_buf: BytesMut) -> FramedParts<T, U> {
|
||||
FramedParts {
|
||||
io,
|
||||
codec,
|
||||
read_buf,
|
||||
write_buf: BytesMut::new(),
|
||||
write_buf_lw: LW,
|
||||
write_buf_hw: HW,
|
||||
_priv: (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
75
actix-connect/CHANGES.md
Normal file
75
actix-connect/CHANGES.md
Normal file
@@ -0,0 +1,75 @@
|
||||
# Changes
|
||||
|
||||
## [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
|
||||
|
||||
* Rename crate
|
60
actix-connect/Cargo.toml
Normal file
60
actix-connect/Cargo.toml
Normal file
@@ -0,0 +1,60 @@
|
||||
[package]
|
||||
name = "actix-connect"
|
||||
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-connect/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "uri"]
|
||||
|
||||
[lib]
|
||||
name = "actix_connect"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[features]
|
||||
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.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.17", optional = true }
|
||||
log = "0.4"
|
||||
tokio-tcp = "0.1.3"
|
||||
tokio-current-thread = "0.1.5"
|
||||
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-test-server = { version="0.2.2", features=["ssl"] }
|
||||
actix-server-config = "0.1.0"
|
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
|
281
actix-connect/src/connect.rs
Normal file
281
actix-connect/src/connect.rs
Normal file
@@ -0,0 +1,281 @@
|
||||
use std::collections::{vec_deque, VecDeque};
|
||||
use std::fmt;
|
||||
use std::iter::{FromIterator, FusedIterator};
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use either::Either;
|
||||
|
||||
/// Connect request
|
||||
pub trait Address {
|
||||
/// Host name of the request
|
||||
fn host(&self) -> &str;
|
||||
|
||||
/// Port of the request
|
||||
fn port(&self) -> Option<u16>;
|
||||
}
|
||||
|
||||
impl Address for String {
|
||||
fn host(&self) -> &str {
|
||||
&self
|
||||
}
|
||||
|
||||
fn port(&self) -> Option<u16> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Address for &'static str {
|
||||
fn host(&self) -> &str {
|
||||
self
|
||||
}
|
||||
|
||||
fn port(&self) -> Option<u16> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect request
|
||||
#[derive(Eq, PartialEq, Debug, Hash)]
|
||||
pub struct Connect<T> {
|
||||
pub(crate) req: T,
|
||||
pub(crate) port: u16,
|
||||
pub(crate) addr: Option<Either<SocketAddr, VecDeque<SocketAddr>>>,
|
||||
}
|
||||
|
||||
impl<T: Address> Connect<T> {
|
||||
/// Create `Connect` instance by spliting the string by ':' and convert the second part to u16
|
||||
pub fn new(req: T) -> Connect<T> {
|
||||
let (_, port) = parse(req.host());
|
||||
Connect {
|
||||
req,
|
||||
port: port.unwrap_or(0),
|
||||
addr: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create new `Connect` instance from host and address. Connector skips name resolution stage for such connect messages.
|
||||
pub fn with(req: T, addr: SocketAddr) -> Connect<T> {
|
||||
Connect {
|
||||
req,
|
||||
port: 0,
|
||||
addr: Some(Either::Left(addr)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Use port if address does not provide one.
|
||||
///
|
||||
/// By default it set to 0
|
||||
pub fn set_port(mut self, port: u16) -> Self {
|
||||
self.port = port;
|
||||
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()
|
||||
}
|
||||
|
||||
/// Port of the request
|
||||
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> {
|
||||
fn from(addr: T) -> Self {
|
||||
Connect::new(addr)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> fmt::Display for Connect<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}:{}", self.host(), self.port())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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() {
|
||||
let port_str = parts_iter.next().unwrap_or("");
|
||||
if let Ok(port) = port_str.parse::<u16>() {
|
||||
(host, Some(port))
|
||||
} else {
|
||||
(host, None)
|
||||
}
|
||||
} else {
|
||||
(host, None)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Connection<T, U> {
|
||||
io: U,
|
||||
req: T,
|
||||
}
|
||||
|
||||
impl<T, U> Connection<T, U> {
|
||||
pub fn new(io: U, req: T) -> Self {
|
||||
Self { io, req }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Connection<T, U> {
|
||||
/// Reconstruct from a parts.
|
||||
pub fn from_parts(io: U, req: T) -> Self {
|
||||
Self { io, req }
|
||||
}
|
||||
|
||||
/// Deconstruct into a parts.
|
||||
pub fn into_parts(self) -> (U, T) {
|
||||
(self.io, self.req)
|
||||
}
|
||||
|
||||
/// Replace inclosed object, return new Stream and old object
|
||||
pub fn replace<Y>(self, io: Y) -> (U, Connection<T, Y>) {
|
||||
(self.io, Connection { io, req: self.req })
|
||||
}
|
||||
|
||||
/// Returns a shared reference to the underlying stream.
|
||||
pub fn get_ref(&self) -> &U {
|
||||
&self.io
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the underlying stream.
|
||||
pub fn get_mut(&mut self) -> &mut U {
|
||||
&mut self.io
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address, U> Connection<T, U> {
|
||||
/// Get request
|
||||
pub fn host(&self) -> &str {
|
||||
&self.req.host()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> std::ops::Deref for Connection<T, U> {
|
||||
type Target = U;
|
||||
|
||||
fn deref(&self) -> &U {
|
||||
&self.io
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> std::ops::DerefMut for Connection<T, U> {
|
||||
fn deref_mut(&mut self) -> &mut U {
|
||||
&mut self.io
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U: fmt::Debug> fmt::Debug for Connection<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "Stream {{{:?}}}", self.io)
|
||||
}
|
||||
}
|
168
actix-connect/src/connector.rs
Normal file
168
actix-connect/src/connector.rs
Normal file
@@ -0,0 +1,168 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::marker::PhantomData;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::{err, ok, Either, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
use tokio_tcp::{ConnectFuture, TcpStream};
|
||||
|
||||
use super::connect::{Address, Connect, Connection};
|
||||
use super::error::ConnectError;
|
||||
|
||||
/// Tcp connector service factory
|
||||
#[derive(Debug)]
|
||||
pub struct TcpConnectorFactory<T>(PhantomData<T>);
|
||||
|
||||
impl<T> TcpConnectorFactory<T> {
|
||||
pub fn new() -> Self {
|
||||
TcpConnectorFactory(PhantomData)
|
||||
}
|
||||
|
||||
/// Create tcp connector service
|
||||
pub fn service(&self) -> TcpConnector<T> {
|
||||
TcpConnector(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for TcpConnectorFactory<T> {
|
||||
fn default() -> Self {
|
||||
TcpConnectorFactory(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for TcpConnectorFactory<T> {
|
||||
fn clone(&self) -> Self {
|
||||
TcpConnectorFactory(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> NewService for TcpConnectorFactory<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
type Config = ();
|
||||
type Service = TcpConnector<T>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(self.service())
|
||||
}
|
||||
}
|
||||
|
||||
/// Tcp connector service
|
||||
#[derive(Default, Debug)]
|
||||
pub struct TcpConnector<T>(PhantomData<T>);
|
||||
|
||||
impl<T> TcpConnector<T> {
|
||||
pub fn new() -> Self {
|
||||
TcpConnector(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for TcpConnector<T> {
|
||||
fn clone(&self) -> Self {
|
||||
TcpConnector(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> Service for TcpConnector<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
type Future = Either<TcpConnectorResponse<T>, FutureResult<Self::Response, Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Connect<T>) -> Self::Future {
|
||||
let port = req.port();
|
||||
let Connect { req, addr, .. } = req;
|
||||
|
||||
if let Some(addr) = addr {
|
||||
Either::A(TcpConnectorResponse::new(req, port, addr))
|
||||
} else {
|
||||
error!("TCP connector: got unresolved address");
|
||||
Either::B(err(ConnectError::Unresolverd))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Tcp stream connector response future
|
||||
pub struct TcpConnectorResponse<T> {
|
||||
req: Option<T>,
|
||||
port: u16,
|
||||
addrs: Option<VecDeque<SocketAddr>>,
|
||||
stream: Option<ConnectFuture>,
|
||||
}
|
||||
|
||||
impl<T: Address> TcpConnectorResponse<T> {
|
||||
pub fn new(
|
||||
req: T,
|
||||
port: u16,
|
||||
addr: either::Either<SocketAddr, VecDeque<SocketAddr>>,
|
||||
) -> TcpConnectorResponse<T> {
|
||||
trace!(
|
||||
"TCP connector - connecting to {:?} port:{}",
|
||||
req.host(),
|
||||
port
|
||||
);
|
||||
|
||||
match addr {
|
||||
either::Either::Left(addr) => TcpConnectorResponse {
|
||||
req: Some(req),
|
||||
port,
|
||||
addrs: None,
|
||||
stream: Some(TcpStream::connect(&addr)),
|
||||
},
|
||||
either::Either::Right(addrs) => TcpConnectorResponse {
|
||||
req: Some(req),
|
||||
port,
|
||||
addrs: Some(addrs),
|
||||
stream: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> Future for TcpConnectorResponse<T> {
|
||||
type Item = Connection<T, TcpStream>;
|
||||
type Error = ConnectError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
// connect
|
||||
loop {
|
||||
if let Some(new) = self.stream.as_mut() {
|
||||
match new.poll() {
|
||||
Ok(Async::Ready(sock)) => {
|
||||
let req = self.req.take().unwrap();
|
||||
trace!(
|
||||
"TCP connector - successfully connected to connecting to {:?} - {:?}",
|
||||
req.host(), sock.peer_addr()
|
||||
);
|
||||
return Ok(Async::Ready(Connection::new(sock, req)));
|
||||
}
|
||||
Ok(Async::NotReady) => return Ok(Async::NotReady),
|
||||
Err(err) => {
|
||||
trace!(
|
||||
"TCP connector - failed to connect to connecting to {:?} port: {}",
|
||||
self.req.as_ref().unwrap().host(),
|
||||
self.port,
|
||||
);
|
||||
if self.addrs.is_none() || self.addrs.as_ref().unwrap().is_empty() {
|
||||
return Err(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// try to connect
|
||||
self.stream = Some(TcpStream::connect(
|
||||
&self.addrs.as_mut().unwrap().pop_front().unwrap(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
26
actix-connect/src/error.rs
Normal file
26
actix-connect/src/error.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use std::io;
|
||||
|
||||
use derive_more::{Display, From};
|
||||
use trust_dns_resolver::error::ResolveError;
|
||||
|
||||
#[derive(Debug, From, Display)]
|
||||
pub enum ConnectError {
|
||||
/// Failed to resolve the hostname
|
||||
#[display(fmt = "Failed resolving hostname: {}", _0)]
|
||||
Resolver(ResolveError),
|
||||
|
||||
/// No dns records
|
||||
#[display(fmt = "No dns records found for the input")]
|
||||
NoRecords,
|
||||
|
||||
/// Invalid input
|
||||
InvalidInput,
|
||||
|
||||
/// Unresolved host name
|
||||
#[display(fmt = "Connector received `Connect` method with unresolved host")]
|
||||
Unresolverd,
|
||||
|
||||
/// Connection io error
|
||||
#[display(fmt = "{}", _0)]
|
||||
Io(io::Error),
|
||||
}
|
111
actix-connect/src/lib.rs
Normal file
111
actix-connect/src/lib.rs
Normal file
@@ -0,0 +1,111 @@
|
||||
//! Actix connect - tcp connector service
|
||||
//!
|
||||
//! ## Package feature
|
||||
//!
|
||||
//! * `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::{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;
|
||||
|
||||
pub fn start_resolver(cfg: ResolverConfig, opts: ResolverOpts) -> AsyncResolver {
|
||||
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
||||
tokio_current_thread::spawn(bg);
|
||||
resolver
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static DEFAULT_RESOLVER: RefCell<Option<AsyncResolver>> = RefCell::new(None);
|
||||
}
|
||||
|
||||
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
|
||||
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(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(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::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::default().and_then(TcpConnectorFactory::new())
|
||||
}
|
185
actix-connect/src/resolver.rs
Normal file
185
actix-connect/src/resolver.rs
Normal file
@@ -0,0 +1,185 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::{ok, Either, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
use trust_dns_resolver::lookup_ip::LookupIpFuture;
|
||||
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: Option<AsyncResolver>,
|
||||
_t: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> ResolverFactory<T> {
|
||||
/// Create new resolver instance with custom configuration and options.
|
||||
pub fn new(resolver: AsyncResolver) -> Self {
|
||||
ResolverFactory {
|
||||
resolver: Some(resolver),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for ResolverFactory<T> {
|
||||
fn clone(&self) -> Self {
|
||||
ResolverFactory {
|
||||
resolver: self.resolver.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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(self.service())
|
||||
}
|
||||
}
|
||||
|
||||
/// DNS Resolver Service
|
||||
pub struct Resolver<T> {
|
||||
resolver: Option<AsyncResolver>,
|
||||
_t: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> Resolver<T> {
|
||||
/// Create new resolver instance with custom configuration and options.
|
||||
pub fn new(resolver: AsyncResolver) -> Self {
|
||||
Resolver {
|
||||
resolver: Some(resolver),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for Resolver<T> {
|
||||
fn default() -> Self {
|
||||
Resolver {
|
||||
resolver: None,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for Resolver<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Resolver {
|
||||
resolver: self.resolver.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> Service for Resolver<T> {
|
||||
type Request = Connect<T>;
|
||||
type Response = Connect<T>;
|
||||
type Error = ConnectError;
|
||||
type Future = Either<ResolverFuture<T>, FutureResult<Connect<T>, Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, mut req: Connect<T>) -> Self::Future {
|
||||
if req.addr.is_some() {
|
||||
Either::B(ok(req))
|
||||
} else if let Ok(ip) = req.host().parse() {
|
||||
req.addr = Some(either::Either::Left(SocketAddr::new(ip, req.port())));
|
||||
Either::B(ok(req))
|
||||
} else {
|
||||
trace!("DNS resolver: resolving host {:?}", req.host());
|
||||
if self.resolver.is_none() {
|
||||
self.resolver = Some(get_default_resolver());
|
||||
}
|
||||
Either::A(ResolverFuture::new(req, self.resolver.as_ref().unwrap()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Resolver future
|
||||
pub struct ResolverFuture<T: Address> {
|
||||
req: Option<Connect<T>>,
|
||||
lookup: Background<LookupIpFuture>,
|
||||
}
|
||||
|
||||
impl<T: Address> ResolverFuture<T> {
|
||||
pub fn new(req: Connect<T>, resolver: &AsyncResolver) -> Self {
|
||||
let lookup = if let Some(host) = req.host().splitn(2, ':').next() {
|
||||
resolver.lookup_ip(host)
|
||||
} else {
|
||||
resolver.lookup_ip(req.host())
|
||||
};
|
||||
|
||||
ResolverFuture {
|
||||
lookup,
|
||||
req: Some(req),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Address> Future for ResolverFuture<T> {
|
||||
type Item = Connect<T>;
|
||||
type Error = ConnectError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.lookup.poll().map_err(|e| {
|
||||
trace!(
|
||||
"DNS resolver: failed to resolve host {:?} err: {}",
|
||||
self.req.as_ref().unwrap().host(),
|
||||
e
|
||||
);
|
||||
e
|
||||
})? {
|
||||
Async::NotReady => Ok(Async::NotReady),
|
||||
Async::Ready(ips) => {
|
||||
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(),
|
||||
req.addrs()
|
||||
);
|
||||
|
||||
if req.addr.is_none() {
|
||||
Err(ConnectError::NoRecords)
|
||||
} else {
|
||||
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)
|
||||
}
|
||||
}
|
12
actix-connect/src/ssl/mod.rs
Normal file
12
actix-connect/src/ssl/mod.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
//! SSL Services
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
mod openssl;
|
||||
#[cfg(feature = "ssl")]
|
||||
pub use self::openssl::{
|
||||
OpensslConnectService, OpensslConnectServiceFactory, OpensslConnector,
|
||||
};
|
||||
#[cfg(feature = "rust-tls")]
|
||||
mod rustls;
|
||||
#[cfg(feature = "rust-tls")]
|
||||
pub use self::rustls::RustlsConnector;
|
251
actix-connect/src/ssl/openssl.rs
Normal file
251
actix-connect/src/ssl/openssl.rs
Normal file
@@ -0,0 +1,251 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::{fmt, io};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_service::{NewService, Service};
|
||||
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, Connect, ConnectError, ConnectService, ConnectServiceFactory, Connection,
|
||||
};
|
||||
|
||||
/// Openssl connector factory
|
||||
pub struct OpensslConnector<T, U> {
|
||||
connector: SslConnector,
|
||||
_t: PhantomData<(T, U)>,
|
||||
}
|
||||
|
||||
impl<T, U> OpensslConnector<T, U> {
|
||||
pub fn new(connector: SslConnector) -> Self {
|
||||
OpensslConnector {
|
||||
connector,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> OpensslConnector<T, U>
|
||||
where
|
||||
T: Address,
|
||||
U: AsyncRead + AsyncWrite + fmt::Debug,
|
||||
{
|
||||
pub fn service(
|
||||
connector: SslConnector,
|
||||
) -> impl Service<
|
||||
Request = Connection<T, U>,
|
||||
Response = Connection<T, SslStream<U>>,
|
||||
Error = HandshakeError<U>,
|
||||
> {
|
||||
OpensslConnectorService {
|
||||
connector: connector,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Clone for OpensslConnector<T, U> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
connector: self.connector.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(OpensslConnectorService {
|
||||
connector: self.connector.clone(),
|
||||
_t: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct OpensslConnectorService<T, U> {
|
||||
connector: SslConnector,
|
||||
_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,
|
||||
{
|
||||
type Request = Connection<T, U>;
|
||||
type Response = Connection<T, SslStream<U>>;
|
||||
type Error = HandshakeError<U>;
|
||||
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(());
|
||||
ConnectAsyncExt {
|
||||
fut: SslConnectorExt::connect_async(&self.connector, stream.host(), io),
|
||||
stream: Some(stream),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ConnectAsyncExt<T, U> {
|
||||
fut: ConnectAsync<U>,
|
||||
stream: Option<Connection<T, ()>>,
|
||||
}
|
||||
|
||||
impl<T: Address, U> Future for ConnectAsyncExt<T, U>
|
||||
where
|
||||
U: AsyncRead + AsyncWrite + fmt::Debug,
|
||||
{
|
||||
type Item = Connection<T, SslStream<U>>;
|
||||
type Error = HandshakeError<U>;
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
37
actix-connect/src/uri.rs
Normal file
37
actix-connect/src/uri.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use http::Uri;
|
||||
|
||||
use crate::Address;
|
||||
|
||||
impl Address for Uri {
|
||||
fn host(&self) -> &str {
|
||||
self.host().unwrap_or("")
|
||||
}
|
||||
|
||||
fn port(&self) -> Option<u16> {
|
||||
if let Some(port) = self.port_u16() {
|
||||
Some(port)
|
||||
} else {
|
||||
port(self.scheme_str())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: load data from file
|
||||
fn port(scheme: Option<&str>) -> Option<u16> {
|
||||
if let Some(scheme) = scheme {
|
||||
match scheme {
|
||||
"http" => Some(80),
|
||||
"https" => Some(443),
|
||||
"ws" => Some(80),
|
||||
"wss" => Some(443),
|
||||
"amqp" => Some(5672),
|
||||
"amqps" => Some(5671),
|
||||
"sb" => Some(5671),
|
||||
"mqtt" => Some(1883),
|
||||
"mqtts" => Some(8883),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
142
actix-connect/tests/test_connect.rs
Normal file
142
actix-connect/tests/test_connect.rs
Normal file
@@ -0,0 +1,142 @@
|
||||
use actix_codec::{BytesCodec, Framed};
|
||||
use actix_server_config::Io;
|
||||
use actix_service::{service_fn, NewService, Service};
|
||||
use actix_test_server::TestServer;
|
||||
use bytes::Bytes;
|
||||
use futures::{future::lazy, Future, Sink};
|
||||
use http::{HttpTryFrom, Uri};
|
||||
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(|| {
|
||||
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());
|
||||
}
|
||||
|
||||
#[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(|| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
})
|
||||
});
|
||||
|
||||
let resolver = srv
|
||||
.block_on(lazy(
|
||||
|| Ok::<_, ()>(actix_connect::start_default_resolver()),
|
||||
))
|
||||
.unwrap();
|
||||
let mut conn = srv
|
||||
.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(|| {
|
||||
service_fn(|io: Io<tokio_tcp::TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
})
|
||||
});
|
||||
|
||||
let resolver = srv
|
||||
.block_on(lazy(|| {
|
||||
Ok::<_, ()>(actix_connect::start_resolver(
|
||||
ResolverConfig::default(),
|
||||
ResolverOpts::default(),
|
||||
))
|
||||
}))
|
||||
.unwrap();
|
||||
let factory = srv
|
||||
.block_on(lazy(|| {
|
||||
Ok::<_, ()>(actix_connect::new_connector_factory(resolver))
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
let mut conn = srv.block_on(factory.new_service(&())).unwrap();
|
||||
let con = srv
|
||||
.block_on(conn.call(Connect::with("10", srv.addr())))
|
||||
.unwrap();
|
||||
assert_eq!(con.peer_addr().unwrap(), srv.addr());
|
||||
}
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
#[test]
|
||||
fn test_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());
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
@@ -1,21 +0,0 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.0] - 2019-02-01
|
||||
|
||||
### Changes
|
||||
|
||||
* Migrate to actix-service 0.2
|
||||
|
||||
* Upgrade trust-dns-resolver
|
||||
|
||||
* Use tokio-current-thread instead of direct actix-rt dipendency
|
||||
|
||||
|
||||
## [0.1.1] - 2019-01-13
|
||||
|
||||
* Upgrade trust-dns-proto
|
||||
|
||||
|
||||
## [0.1.0] - 2018-12-09
|
||||
|
||||
* Move server to separate crate
|
@@ -1,40 +0,0 @@
|
||||
[package]
|
||||
name = "actix-connector"
|
||||
version = "0.2.0"
|
||||
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/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl"]
|
||||
|
||||
[lib]
|
||||
name = "actix_connector"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
# openssl
|
||||
ssl = ["openssl", "tokio-openssl"]
|
||||
|
||||
[dependencies]
|
||||
#actix-service = "0.2.0"
|
||||
actix-service = { path="../actix-service" }
|
||||
actix-codec = "0.1.0"
|
||||
futures = "0.1"
|
||||
tokio-tcp = "0.1"
|
||||
tokio-current-thread = "0.1"
|
||||
trust-dns-resolver = { version="0.11.0-alpha.2", default-features = false }
|
||||
|
||||
# openssl
|
||||
openssl = { version="0.10", optional = true }
|
||||
tokio-openssl = { version="0.3", optional = true }
|
@@ -1,386 +0,0 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::marker::PhantomData;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::time::Duration;
|
||||
use std::{fmt, io};
|
||||
|
||||
use actix_service::{fn_factory, NewService, Service};
|
||||
use futures::future::{ok, Either};
|
||||
use futures::{try_ready, Async, Future, Poll};
|
||||
use tokio_tcp::{ConnectFuture, TcpStream};
|
||||
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||
use trust_dns_resolver::system_conf::read_system_conf;
|
||||
|
||||
use super::resolver::{RequestHost, ResolveError, Resolver, ResolverFuture};
|
||||
|
||||
/// Port of the request
|
||||
pub trait RequestPort {
|
||||
fn port(&self) -> u16;
|
||||
}
|
||||
|
||||
// #[derive(Fail, Debug)]
|
||||
#[derive(Debug)]
|
||||
pub enum ConnectorError {
|
||||
/// Failed to resolve the hostname
|
||||
// #[fail(display = "Failed resolving hostname: {}", _0)]
|
||||
Resolver(ResolveError),
|
||||
|
||||
/// No dns records
|
||||
// #[fail(display = "No dns records found for the input")]
|
||||
NoRecords,
|
||||
|
||||
/// Connecting took too long
|
||||
// #[fail(display = "Timeout out while establishing connection")]
|
||||
Timeout,
|
||||
|
||||
/// Invalid input
|
||||
InvalidInput,
|
||||
|
||||
/// Connection io error
|
||||
// #[fail(display = "{}", _0)]
|
||||
IoError(io::Error),
|
||||
}
|
||||
|
||||
impl From<ResolveError> for ConnectorError {
|
||||
fn from(err: ResolveError) -> Self {
|
||||
ConnectorError::Resolver(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<io::Error> for ConnectorError {
|
||||
fn from(err: io::Error) -> Self {
|
||||
ConnectorError::IoError(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Connect request
|
||||
#[derive(Eq, PartialEq, Debug, Hash)]
|
||||
pub struct Connect {
|
||||
pub kind: ConnectKind,
|
||||
pub timeout: Duration,
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Debug, Hash)]
|
||||
pub enum ConnectKind {
|
||||
Host { host: String, port: u16 },
|
||||
Addr { host: String, addr: SocketAddr },
|
||||
}
|
||||
|
||||
impl Connect {
|
||||
/// Create new `Connect` instance.
|
||||
pub fn new<T: AsRef<str>>(host: T, port: u16) -> Connect {
|
||||
Connect {
|
||||
kind: ConnectKind::Host {
|
||||
host: host.as_ref().to_owned(),
|
||||
port,
|
||||
},
|
||||
timeout: Duration::from_secs(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create `Connect` instance by spliting the string by ':' and convert the second part to u16
|
||||
pub fn with<T: AsRef<str>>(host: T) -> Result<Connect, ConnectorError> {
|
||||
let mut parts_iter = host.as_ref().splitn(2, ':');
|
||||
let host = parts_iter.next().ok_or(ConnectorError::InvalidInput)?;
|
||||
let port_str = parts_iter.next().unwrap_or("");
|
||||
let port = port_str
|
||||
.parse::<u16>()
|
||||
.map_err(|_| ConnectorError::InvalidInput)?;
|
||||
Ok(Connect {
|
||||
kind: ConnectKind::Host {
|
||||
host: host.to_owned(),
|
||||
port,
|
||||
},
|
||||
timeout: Duration::from_secs(1),
|
||||
})
|
||||
}
|
||||
|
||||
/// Create new `Connect` instance from host and address. Connector skips name resolution stage for such connect messages.
|
||||
pub fn with_address<T: Into<String>>(host: T, addr: SocketAddr) -> Connect {
|
||||
Connect {
|
||||
kind: ConnectKind::Addr {
|
||||
addr,
|
||||
host: host.into(),
|
||||
},
|
||||
timeout: Duration::from_secs(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set connect timeout
|
||||
///
|
||||
/// By default timeout is set to a 1 second.
|
||||
pub fn timeout(mut self, timeout: Duration) -> Connect {
|
||||
self.timeout = timeout;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl RequestHost for Connect {
|
||||
fn host(&self) -> &str {
|
||||
match self.kind {
|
||||
ConnectKind::Host { ref host, .. } => host,
|
||||
ConnectKind::Addr { ref host, .. } => host,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RequestPort for Connect {
|
||||
fn port(&self) -> u16 {
|
||||
match self.kind {
|
||||
ConnectKind::Host { port, .. } => port,
|
||||
ConnectKind::Addr { addr, .. } => addr.port(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Connect {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}:{}", self.host(), self.port())
|
||||
}
|
||||
}
|
||||
|
||||
/// Tcp connector
|
||||
pub struct Connector {
|
||||
resolver: Resolver<Connect>,
|
||||
}
|
||||
|
||||
impl Default for Connector {
|
||||
fn default() -> Self {
|
||||
let (cfg, opts) = if let Ok((cfg, opts)) = read_system_conf() {
|
||||
(cfg, opts)
|
||||
} else {
|
||||
(ResolverConfig::default(), ResolverOpts::default())
|
||||
};
|
||||
|
||||
Connector::new(cfg, opts)
|
||||
}
|
||||
}
|
||||
|
||||
impl Connector {
|
||||
/// Create new connector with resolver configuration
|
||||
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
|
||||
Connector {
|
||||
resolver: Resolver::new(cfg, opts),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create new connector with custom resolver
|
||||
pub fn with_resolver(
|
||||
resolver: Resolver<Connect>,
|
||||
) -> impl Service<Request = Connect, Response = (Connect, TcpStream), Error = ConnectorError>
|
||||
+ Clone {
|
||||
Connector { resolver }
|
||||
}
|
||||
|
||||
/// Create new default connector service
|
||||
pub fn new_service_with_config<E>(
|
||||
cfg: ResolverConfig,
|
||||
opts: ResolverOpts,
|
||||
) -> impl NewService<
|
||||
(),
|
||||
Request = Connect,
|
||||
Response = (Connect, TcpStream),
|
||||
Error = ConnectorError,
|
||||
InitError = E,
|
||||
> + Clone {
|
||||
fn_factory(move || ok(Connector::new(cfg.clone(), opts)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Connector {
|
||||
fn clone(&self) -> Self {
|
||||
Connector {
|
||||
resolver: self.resolver.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Service for Connector {
|
||||
type Request = Connect;
|
||||
type Response = (Connect, TcpStream);
|
||||
type Error = ConnectorError;
|
||||
type Future = Either<ConnectorFuture, ConnectorTcpFuture>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Connect) -> Self::Future {
|
||||
match req.kind {
|
||||
ConnectKind::Host { .. } => Either::A(ConnectorFuture {
|
||||
fut: self.resolver.call(req),
|
||||
fut2: None,
|
||||
}),
|
||||
ConnectKind::Addr { addr, .. } => {
|
||||
let mut addrs = VecDeque::new();
|
||||
addrs.push_back(addr.ip());
|
||||
Either::B(ConnectorTcpFuture {
|
||||
fut: TcpConnectorResponse::new(req, addrs),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct ConnectorFuture {
|
||||
fut: ResolverFuture<Connect>,
|
||||
fut2: Option<TcpConnectorResponse<Connect>>,
|
||||
}
|
||||
|
||||
impl Future for ConnectorFuture {
|
||||
type Item = (Connect, TcpStream);
|
||||
type Error = ConnectorError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.fut2 {
|
||||
return fut.poll().map_err(ConnectorError::from);
|
||||
}
|
||||
match self.fut.poll().map_err(ConnectorError::from)? {
|
||||
Async::Ready((req, addrs)) => {
|
||||
if addrs.is_empty() {
|
||||
Err(ConnectorError::NoRecords)
|
||||
} else {
|
||||
self.fut2 = Some(TcpConnectorResponse::new(req, addrs));
|
||||
self.poll()
|
||||
}
|
||||
}
|
||||
Async::NotReady => Ok(Async::NotReady),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct ConnectorTcpFuture {
|
||||
fut: TcpConnectorResponse<Connect>,
|
||||
}
|
||||
|
||||
impl Future for ConnectorTcpFuture {
|
||||
type Item = (Connect, TcpStream);
|
||||
type Error = ConnectorError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
self.fut.poll().map_err(ConnectorError::IoError)
|
||||
}
|
||||
}
|
||||
|
||||
/// Tcp stream connector service
|
||||
pub struct TcpConnector<T: RequestPort>(PhantomData<T>);
|
||||
|
||||
impl<T: RequestPort> Default for TcpConnector<T> {
|
||||
fn default() -> TcpConnector<T> {
|
||||
TcpConnector(PhantomData)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RequestPort> Service for TcpConnector<T> {
|
||||
type Request = (T, VecDeque<IpAddr>);
|
||||
type Response = (T, TcpStream);
|
||||
type Error = io::Error;
|
||||
type Future = TcpConnectorResponse<T>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, (req, addrs): (T, VecDeque<IpAddr>)) -> Self::Future {
|
||||
TcpConnectorResponse::new(req, addrs)
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Tcp stream connector response future
|
||||
pub struct TcpConnectorResponse<T: RequestPort> {
|
||||
port: u16,
|
||||
req: Option<T>,
|
||||
addr: Option<SocketAddr>,
|
||||
addrs: VecDeque<IpAddr>,
|
||||
stream: Option<ConnectFuture>,
|
||||
}
|
||||
|
||||
impl<T: RequestPort> TcpConnectorResponse<T> {
|
||||
pub fn new(req: T, addrs: VecDeque<IpAddr>) -> TcpConnectorResponse<T> {
|
||||
TcpConnectorResponse {
|
||||
addrs,
|
||||
port: req.port(),
|
||||
req: Some(req),
|
||||
addr: None,
|
||||
stream: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RequestPort> Future for TcpConnectorResponse<T> {
|
||||
type Item = (T, TcpStream);
|
||||
type Error = io::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
// connect
|
||||
loop {
|
||||
if let Some(new) = self.stream.as_mut() {
|
||||
match new.poll() {
|
||||
Ok(Async::Ready(sock)) => {
|
||||
return Ok(Async::Ready((self.req.take().unwrap(), sock)));
|
||||
}
|
||||
Ok(Async::NotReady) => return Ok(Async::NotReady),
|
||||
Err(err) => {
|
||||
if self.addrs.is_empty() {
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// try to connect
|
||||
let addr = SocketAddr::new(self.addrs.pop_front().unwrap(), self.port);
|
||||
self.stream = Some(TcpStream::connect(&addr));
|
||||
self.addr = Some(addr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DefaultConnector(Connector);
|
||||
|
||||
impl Default for DefaultConnector {
|
||||
fn default() -> Self {
|
||||
DefaultConnector(Connector::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl DefaultConnector {
|
||||
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
|
||||
DefaultConnector(Connector::new(cfg, opts))
|
||||
}
|
||||
}
|
||||
|
||||
impl Service for DefaultConnector {
|
||||
type Request = Connect;
|
||||
type Response = TcpStream;
|
||||
type Error = ConnectorError;
|
||||
type Future = DefaultConnectorFuture;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.0.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Connect) -> Self::Future {
|
||||
DefaultConnectorFuture {
|
||||
fut: self.0.call(req),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct DefaultConnectorFuture {
|
||||
fut: Either<ConnectorFuture, ConnectorTcpFuture>,
|
||||
}
|
||||
|
||||
impl Future for DefaultConnectorFuture {
|
||||
type Item = TcpStream;
|
||||
type Error = ConnectorError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
Ok(Async::Ready(try_ready!(self.fut.poll()).1))
|
||||
}
|
||||
}
|
@@ -1,16 +0,0 @@
|
||||
//! Actix Connector - tcp connector service
|
||||
//!
|
||||
//! ## Package feature
|
||||
//!
|
||||
//! * `tls` - enables ssl support via `native-tls` crate
|
||||
//! * `ssl` - enables ssl support via `openssl` crate
|
||||
//! * `rust-tls` - enables ssl support via `rustls` crate
|
||||
|
||||
mod connector;
|
||||
mod resolver;
|
||||
pub mod ssl;
|
||||
|
||||
pub use self::connector::{
|
||||
Connect, Connector, ConnectorError, DefaultConnector, RequestPort, TcpConnector,
|
||||
};
|
||||
pub use self::resolver::{RequestHost, Resolver};
|
@@ -1,129 +0,0 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::marker::PhantomData;
|
||||
use std::net::IpAddr;
|
||||
|
||||
use actix_service::Service;
|
||||
use futures::{Async, Future, Poll};
|
||||
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
|
||||
pub use trust_dns_resolver::error::ResolveError;
|
||||
use trust_dns_resolver::lookup_ip::LookupIpFuture;
|
||||
use trust_dns_resolver::system_conf::read_system_conf;
|
||||
use trust_dns_resolver::{AsyncResolver, Background};
|
||||
|
||||
/// Host name of the request
|
||||
pub trait RequestHost {
|
||||
fn host(&self) -> &str;
|
||||
}
|
||||
|
||||
impl RequestHost for String {
|
||||
fn host(&self) -> &str {
|
||||
self.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Resolver<T = String> {
|
||||
resolver: AsyncResolver,
|
||||
req: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: RequestHost> Default for Resolver<T> {
|
||||
fn default() -> Self {
|
||||
let (cfg, opts) = if let Ok((cfg, opts)) = read_system_conf() {
|
||||
(cfg, opts)
|
||||
} else {
|
||||
(ResolverConfig::default(), ResolverOpts::default())
|
||||
};
|
||||
|
||||
Resolver::new(cfg, opts)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RequestHost> Resolver<T> {
|
||||
/// Create new resolver instance with custom configuration and options.
|
||||
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
|
||||
let (resolver, bg) = AsyncResolver::new(cfg, opts);
|
||||
tokio_current_thread::spawn(bg);
|
||||
Resolver {
|
||||
resolver,
|
||||
req: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Change type of resolver request.
|
||||
pub fn into_request<T2: RequestHost>(&self) -> Resolver<T2> {
|
||||
Resolver {
|
||||
resolver: self.resolver.clone(),
|
||||
req: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for Resolver<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Resolver {
|
||||
resolver: self.resolver.clone(),
|
||||
req: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RequestHost> Service for Resolver<T> {
|
||||
type Request = T;
|
||||
type Response = (T, VecDeque<IpAddr>);
|
||||
type Error = ResolveError;
|
||||
type Future = ResolverFuture<T>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T) -> Self::Future {
|
||||
if let Ok(ip) = req.host().parse() {
|
||||
let mut addrs = VecDeque::new();
|
||||
addrs.push_back(ip);
|
||||
ResolverFuture::new(req, &self.resolver, Some(addrs))
|
||||
} else {
|
||||
ResolverFuture::new(req, &self.resolver, None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
/// Resolver future
|
||||
pub struct ResolverFuture<T> {
|
||||
req: Option<T>,
|
||||
lookup: Option<Background<LookupIpFuture>>,
|
||||
addrs: Option<VecDeque<IpAddr>>,
|
||||
}
|
||||
|
||||
impl<T: RequestHost> ResolverFuture<T> {
|
||||
pub fn new(addr: T, resolver: &AsyncResolver, addrs: Option<VecDeque<IpAddr>>) -> Self {
|
||||
// we need to do dns resolution
|
||||
let lookup = Some(resolver.lookup_ip(addr.host()));
|
||||
ResolverFuture {
|
||||
lookup,
|
||||
addrs,
|
||||
req: Some(addr),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RequestHost> Future for ResolverFuture<T> {
|
||||
type Item = (T, VecDeque<IpAddr>);
|
||||
type Error = ResolveError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(addrs) = self.addrs.take() {
|
||||
Ok(Async::Ready((self.req.take().unwrap(), addrs)))
|
||||
} else {
|
||||
match self.lookup.as_mut().unwrap().poll() {
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Ok(Async::Ready(ips)) => Ok(Async::Ready((
|
||||
self.req.take().unwrap(),
|
||||
ips.iter().collect(),
|
||||
))),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,6 +0,0 @@
|
||||
//! SSL Services
|
||||
|
||||
#[cfg(feature = "ssl")]
|
||||
mod openssl;
|
||||
#[cfg(feature = "ssl")]
|
||||
pub use self::openssl::OpensslConnector;
|
@@ -1,107 +0,0 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::{future::ok, future::FutureResult, Async, Future, Poll};
|
||||
use openssl::ssl::{HandshakeError, SslConnector};
|
||||
use tokio_openssl::{ConnectAsync, SslConnectorExt, SslStream};
|
||||
|
||||
use crate::resolver::RequestHost;
|
||||
|
||||
/// Openssl connector factory
|
||||
pub struct OpensslConnector<R, T, E> {
|
||||
connector: SslConnector,
|
||||
_t: PhantomData<(R, T, E)>,
|
||||
}
|
||||
|
||||
impl<R, T, E> OpensslConnector<R, T, E> {
|
||||
pub fn new(connector: SslConnector) -> Self {
|
||||
OpensslConnector {
|
||||
connector,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: RequestHost, T: AsyncRead + AsyncWrite> OpensslConnector<R, T, ()> {
|
||||
pub fn service(
|
||||
connector: SslConnector,
|
||||
) -> impl Service<Request = (R, T), Response = (R, SslStream<T>), Error = HandshakeError<T>>
|
||||
{
|
||||
OpensslConnectorService {
|
||||
connector: connector,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, T, E> Clone for OpensslConnector<R, T, E> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
connector: self.connector.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService<()>
|
||||
for OpensslConnector<R, T, E>
|
||||
{
|
||||
type Request = (R, T);
|
||||
type Response = (R, SslStream<T>);
|
||||
type Error = HandshakeError<T>;
|
||||
type Service = OpensslConnectorService<R, T>;
|
||||
type InitError = E;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(OpensslConnectorService {
|
||||
connector: self.connector.clone(),
|
||||
_t: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct OpensslConnectorService<R, T> {
|
||||
connector: SslConnector,
|
||||
_t: PhantomData<(R, T)>,
|
||||
}
|
||||
|
||||
impl<R: RequestHost, T: AsyncRead + AsyncWrite> Service for OpensslConnectorService<R, T> {
|
||||
type Request = (R, T);
|
||||
type Response = (R, SslStream<T>);
|
||||
type Error = HandshakeError<T>;
|
||||
type Future = ConnectAsyncExt<R, T>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, (req, stream): (R, T)) -> Self::Future {
|
||||
ConnectAsyncExt {
|
||||
fut: SslConnectorExt::connect_async(&self.connector, req.host(), stream),
|
||||
req: Some(req),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ConnectAsyncExt<R, T> {
|
||||
req: Option<R>,
|
||||
fut: ConnectAsync<T>,
|
||||
}
|
||||
|
||||
impl<R, T> Future for ConnectAsyncExt<R, T>
|
||||
where
|
||||
R: RequestHost,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
{
|
||||
type Item = (R, SslStream<T>);
|
||||
type Error = HandshakeError<T>;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.fut.poll()? {
|
||||
Async::Ready(stream) => Ok(Async::Ready((self.req.take().unwrap(), stream))),
|
||||
Async::NotReady => Ok(Async::NotReady),
|
||||
}
|
||||
}
|
||||
}
|
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<dyn 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<dyn 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<dyn 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<dyn 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<dyn 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<dyn 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<dyn 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<dyn 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,51 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.5] - 2019-09-02
|
||||
|
||||
### Added
|
||||
|
||||
* Add arbiter specific storage
|
||||
|
||||
|
||||
## [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
|
||||
|
||||
* Added `blocking` module
|
||||
|
||||
* Arbiter::exec_fn - execute fn on the arbiter's thread
|
||||
|
||||
* 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.1.0"
|
||||
version = "0.2.5"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix runtime"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -11,17 +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]
|
||||
log = "0.4"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.24"
|
||||
actix-threadpool = "0.1.1"
|
||||
futures = "0.1.25"
|
||||
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
|
@@ -1,27 +1,32 @@
|
||||
use std::any::{Any, TypeId};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::{fmt, thread};
|
||||
|
||||
use futures::sync::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
|
||||
use futures::sync::oneshot::{channel, Sender};
|
||||
use futures::sync::oneshot::{channel, Canceled, Sender};
|
||||
use futures::{future, Async, Future, IntoFuture, Poll, Stream};
|
||||
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);
|
||||
static Q: RefCell<Vec<Box<Future<Item = (), Error = ()>>>> = RefCell::new(Vec::new());
|
||||
static Q: RefCell<Vec<Box<dyn Future<Item = (), Error = ()>>>> = RefCell::new(Vec::new());
|
||||
static STORAGE: RefCell<HashMap<TypeId, Box<dyn Any>>> = RefCell::new(HashMap::new());
|
||||
);
|
||||
|
||||
pub(crate) static COUNT: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
pub(crate) enum ArbiterCommand {
|
||||
Stop,
|
||||
Execute(Box<Future<Item = (), Error = ()> + Send>),
|
||||
Execute(Box<dyn Future<Item = (), Error = ()> + Send>),
|
||||
ExecuteFn(Box<dyn FnExec>),
|
||||
}
|
||||
|
||||
impl fmt::Debug for ArbiterCommand {
|
||||
@@ -29,11 +34,15 @@ impl fmt::Debug for ArbiterCommand {
|
||||
match self {
|
||||
ArbiterCommand::Stop => write!(f, "ArbiterCommand::Stop"),
|
||||
ArbiterCommand::Execute(_) => write!(f, "ArbiterCommand::Execute"),
|
||||
ArbiterCommand::ExecuteFn(_) => write!(f, "ArbiterCommand::ExecuteFn"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
/// Arbiters provide an asynchronous execution environment for actors, functions
|
||||
/// and futures. When an Arbiter is created, they spawn a new OS thread, and
|
||||
/// host an event loop. Some Arbiter functions execute on the current thread.
|
||||
pub struct Arbiter(UnboundedSender<ArbiterCommand>);
|
||||
|
||||
impl Default for Arbiter {
|
||||
@@ -49,12 +58,14 @@ impl Arbiter {
|
||||
let arb = Arbiter(tx);
|
||||
ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
|
||||
RUNNING.with(|cell| cell.set(false));
|
||||
STORAGE.with(|cell| cell.borrow_mut().clear());
|
||||
Arbiter::spawn(ArbiterController { stop: None, rx });
|
||||
|
||||
arb
|
||||
}
|
||||
|
||||
/// Returns current arbiter's address
|
||||
/// Returns the current thread's arbiter's address. If no Arbiter is present, then this
|
||||
/// function will panic!
|
||||
pub fn current() -> Arbiter {
|
||||
ADDR.with(|cell| match *cell.borrow() {
|
||||
Some(ref addr) => addr.clone(),
|
||||
@@ -62,7 +73,7 @@ impl Arbiter {
|
||||
})
|
||||
}
|
||||
|
||||
/// Stop arbiter
|
||||
/// Stop arbiter from continuing it's event loop.
|
||||
pub fn stop(&self) {
|
||||
let _ = self.0.unbounded_send(ArbiterCommand::Stop);
|
||||
}
|
||||
@@ -82,6 +93,7 @@ impl Arbiter {
|
||||
|
||||
let (stop, stop_rx) = channel();
|
||||
RUNNING.with(|cell| cell.set(true));
|
||||
STORAGE.with(|cell| cell.borrow_mut().clear());
|
||||
|
||||
System::set_current(sys);
|
||||
|
||||
@@ -126,21 +138,25 @@ impl Arbiter {
|
||||
RUNNING.with(|cell| cell.set(false));
|
||||
}
|
||||
|
||||
/// Spawn a future on the current thread.
|
||||
/// Spawn a future on the current thread. This does not create a new Arbiter
|
||||
/// or Arbiter address, it is simply a helper for spawning futures on the current
|
||||
/// thread.
|
||||
pub fn spawn<F>(future: F)
|
||||
where
|
||||
F: Future<Item = (), Error = ()> + 'static,
|
||||
{
|
||||
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)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Executes a future on the current thread.
|
||||
/// Executes a future on the current thread. This does not create a new Arbiter
|
||||
/// or Arbiter address, it is simply a helper for executing futures on the current
|
||||
/// thread.
|
||||
pub fn spawn_fn<F, R>(f: F)
|
||||
where
|
||||
F: FnOnce() -> R + 'static,
|
||||
@@ -149,7 +165,7 @@ impl Arbiter {
|
||||
Arbiter::spawn(future::lazy(f))
|
||||
}
|
||||
|
||||
/// Send a future on the arbiter's thread and spawn.
|
||||
/// Send a future to the Arbiter's thread, and spawn it.
|
||||
pub fn send<F>(&self, future: F)
|
||||
where
|
||||
F: Future<Item = (), Error = ()> + Send + 'static,
|
||||
@@ -158,6 +174,82 @@ impl Arbiter {
|
||||
.0
|
||||
.unbounded_send(ArbiterCommand::Execute(Box::new(future)));
|
||||
}
|
||||
|
||||
/// Send a function to the Arbiter's thread, and execute it. Any result from the function
|
||||
/// is discarded.
|
||||
pub fn exec_fn<F>(&self, f: F)
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
let _ = self
|
||||
.0
|
||||
.unbounded_send(ArbiterCommand::ExecuteFn(Box::new(move || {
|
||||
f();
|
||||
})));
|
||||
}
|
||||
|
||||
/// Send a function to the Arbiter's thread. This function will be executed asynchronously.
|
||||
/// A future is created, and when resolved will contain the result of the function sent
|
||||
/// to the Arbiters thread.
|
||||
pub fn exec<F, R>(&self, f: F) -> impl Future<Item = R, Error = Canceled>
|
||||
where
|
||||
F: FnOnce() -> R + Send + 'static,
|
||||
R: Send + 'static,
|
||||
{
|
||||
let (tx, rx) = channel();
|
||||
let _ = self
|
||||
.0
|
||||
.unbounded_send(ArbiterCommand::ExecuteFn(Box::new(move || {
|
||||
if !tx.is_canceled() {
|
||||
let _ = tx.send(f());
|
||||
}
|
||||
})));
|
||||
rx
|
||||
}
|
||||
|
||||
/// Set item to arbiter storage
|
||||
pub fn set_item<T: 'static>(item: T) {
|
||||
STORAGE.with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), Box::new(item)));
|
||||
}
|
||||
|
||||
/// Check if arbiter storage contains item
|
||||
pub fn contains_item<T: 'static>() -> bool {
|
||||
STORAGE.with(move |cell| cell.borrow().get(&TypeId::of::<T>()).is_some())
|
||||
}
|
||||
|
||||
/// Get a reference to a type previously inserted on this arbiter's storage.
|
||||
///
|
||||
/// Panics is item is not inserted
|
||||
pub fn get_item<T: 'static, F, R>(mut f: F) -> R
|
||||
where
|
||||
F: FnMut(&T) -> R,
|
||||
{
|
||||
STORAGE.with(move |cell| {
|
||||
let st = cell.borrow();
|
||||
let item = st
|
||||
.get(&TypeId::of::<T>())
|
||||
.and_then(|boxed| (&**boxed as &(dyn Any + 'static)).downcast_ref())
|
||||
.unwrap();
|
||||
f(item)
|
||||
})
|
||||
}
|
||||
|
||||
/// Get a mutable reference to a type previously inserted on this arbiter's storage.
|
||||
///
|
||||
/// Panics is item is not inserted
|
||||
pub fn get_mut_item<T: 'static, F, R>(mut f: F) -> R
|
||||
where
|
||||
F: FnMut(&mut T) -> R,
|
||||
{
|
||||
STORAGE.with(move |cell| {
|
||||
let mut st = cell.borrow_mut();
|
||||
let item = st
|
||||
.get_mut(&TypeId::of::<T>())
|
||||
.and_then(|boxed| (&mut **boxed as &mut (dyn Any + 'static)).downcast_mut())
|
||||
.unwrap();
|
||||
f(item)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct ArbiterController {
|
||||
@@ -194,6 +286,9 @@ impl Future for ArbiterController {
|
||||
ArbiterCommand::Execute(fut) => {
|
||||
spawn(fut);
|
||||
}
|
||||
ArbiterCommand::ExecuteFn(f) => {
|
||||
f.call_box();
|
||||
}
|
||||
},
|
||||
Ok(Async::NotReady) => return Ok(Async::NotReady),
|
||||
}
|
||||
@@ -257,11 +352,16 @@ impl Future for SystemArbiter {
|
||||
}
|
||||
}
|
||||
|
||||
// /// Execute function in arbiter's thread
|
||||
// impl<I: Send, E: Send> Handler<Execute<I, E>> for SystemArbiter {
|
||||
// type Result = Result<I, E>;
|
||||
pub trait FnExec: Send + 'static {
|
||||
fn call_box(self: Box<Self>);
|
||||
}
|
||||
|
||||
// fn handle(&mut self, msg: Execute<I, E>, _: &mut Context<Self>) -> Result<I, E> {
|
||||
// msg.exec()
|
||||
// }
|
||||
// }
|
||||
impl<F> FnExec for F
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
#[allow(clippy::boxed_local)]
|
||||
fn call_box(self: Box<Self>) {
|
||||
(*self)()
|
||||
}
|
||||
}
|
||||
|
@@ -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,16 +70,38 @@ 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.
|
||||
pub fn run<F>(self, f: F) -> i32
|
||||
pub fn run<F>(self, f: F) -> io::Result<()>
|
||||
where
|
||||
F: FnOnce() + 'static,
|
||||
{
|
||||
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)]
|
||||
@@ -140,7 +198,7 @@ pub struct SystemRunner {
|
||||
impl SystemRunner {
|
||||
/// This function will start event loop and will finish once the
|
||||
/// `System::stop()` function is called.
|
||||
pub fn run(self) -> i32 {
|
||||
pub fn run(self) -> io::Result<()> {
|
||||
let SystemRunner { mut rt, stop, .. } = self;
|
||||
|
||||
// run loop
|
||||
@@ -148,12 +206,21 @@ impl SystemRunner {
|
||||
Arbiter::run_system();
|
||||
Ok::<_, ()>(())
|
||||
}));
|
||||
let code = match rt.block_on(stop) {
|
||||
Ok(code) => code,
|
||||
Err(_) => 1,
|
||||
let result = match rt.block_on(stop) {
|
||||
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)),
|
||||
};
|
||||
Arbiter::stop_system();
|
||||
code
|
||||
result
|
||||
}
|
||||
|
||||
/// Execute a future and wait for result.
|
||||
|
@@ -7,9 +7,12 @@ mod system;
|
||||
|
||||
pub use self::arbiter::Arbiter;
|
||||
pub use self::builder::{Builder, SystemRunner};
|
||||
pub use self::runtime::{Handle, Runtime};
|
||||
pub use self::runtime::Runtime;
|
||||
pub use self::system::System;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use actix_threadpool as blocking;
|
||||
|
||||
/// Spawns a future on the current arbiter.
|
||||
///
|
||||
/// # Panics
|
||||
|
@@ -1,9 +1,7 @@
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::{fmt, io};
|
||||
|
||||
use futures::{future, Future};
|
||||
use tokio_current_thread::Handle as ExecutorHandle;
|
||||
use futures::Future;
|
||||
use tokio_current_thread::{self as current_thread, CurrentThread};
|
||||
use tokio_executor;
|
||||
use tokio_reactor::{self, Reactor};
|
||||
@@ -26,58 +24,6 @@ pub struct Runtime {
|
||||
executor: CurrentThread<Timer<Reactor>>,
|
||||
}
|
||||
|
||||
/// Handle to spawn a future on the corresponding `CurrentThread` runtime instance
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Handle(ExecutorHandle);
|
||||
|
||||
impl Handle {
|
||||
/// Spawn a future onto the `CurrentThread` runtime instance corresponding to this handle
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function panics if the spawn fails. Failure occurs if the `CurrentThread`
|
||||
/// instance of the `Handle` does not exist anymore.
|
||||
pub fn spawn<F>(&self, future: F) -> Result<(), tokio_executor::SpawnError>
|
||||
where
|
||||
F: Future<Item = (), Error = ()> + Send + 'static,
|
||||
{
|
||||
self.0.spawn(future)
|
||||
}
|
||||
|
||||
/// Provides a best effort **hint** to whether or not `spawn` will succeed.
|
||||
///
|
||||
/// This function may return both false positives **and** false negatives.
|
||||
/// If `status` returns `Ok`, then a call to `spawn` will *probably*
|
||||
/// succeed, but may fail. If `status` returns `Err`, a call to `spawn` will
|
||||
/// *probably* fail, but may succeed.
|
||||
///
|
||||
/// This allows a caller to avoid creating the task if the call to `spawn`
|
||||
/// has a high likelihood of failing.
|
||||
pub fn status(&self) -> Result<(), tokio_executor::SpawnError> {
|
||||
self.0.status()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> future::Executor<T> for Handle
|
||||
where
|
||||
T: Future<Item = (), Error = ()> + Send + 'static,
|
||||
{
|
||||
fn execute(&self, future: T) -> Result<(), future::ExecuteError<T>> {
|
||||
if let Err(e) = self.status() {
|
||||
let kind = if e.is_at_capacity() {
|
||||
future::ExecuteErrorKind::NoCapacity
|
||||
} else {
|
||||
future::ExecuteErrorKind::Shutdown
|
||||
};
|
||||
|
||||
return Err(future::ExecuteError::new(kind, future));
|
||||
}
|
||||
|
||||
let _ = self.spawn(future);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Error returned by the `run` function.
|
||||
#[derive(Debug)]
|
||||
pub struct RunError {
|
||||
@@ -94,8 +40,8 @@ impl Error for RunError {
|
||||
fn description(&self) -> &str {
|
||||
self.inner.description()
|
||||
}
|
||||
fn cause(&self) -> Option<&Error> {
|
||||
self.inner.cause()
|
||||
fn cause(&self) -> Option<&dyn Error> {
|
||||
self.inner.source()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,14 +66,6 @@ impl Runtime {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a new handle to spawn futures on the single-threaded Tokio runtime
|
||||
///
|
||||
/// Different to the runtime itself, the handle can be sent to different
|
||||
/// threads.
|
||||
pub fn handle(&self) -> Handle {
|
||||
Handle(self.executor.handle().clone())
|
||||
}
|
||||
|
||||
/// Spawn a future onto the single-threaded Tokio runtime.
|
||||
///
|
||||
/// See [module level][mod] documentation for more details.
|
||||
|
@@ -1,13 +1,20 @@
|
||||
use std::cell::RefCell;
|
||||
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};
|
||||
|
||||
static SYSTEM_COUNT: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// System is a runtime manager.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct System {
|
||||
id: usize,
|
||||
sys: UnboundedSender<SystemCommand>,
|
||||
arbiter: Arbiter,
|
||||
stop_on_panic: bool,
|
||||
@@ -28,6 +35,7 @@ impl System {
|
||||
sys,
|
||||
arbiter,
|
||||
stop_on_panic,
|
||||
id: SYSTEM_COUNT.fetch_add(1, Ordering::SeqCst),
|
||||
};
|
||||
System::set_current(sys.clone());
|
||||
sys
|
||||
@@ -49,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() {
|
||||
@@ -81,6 +103,11 @@ impl System {
|
||||
})
|
||||
}
|
||||
|
||||
/// System id
|
||||
pub fn id(&self) -> usize {
|
||||
self.id
|
||||
}
|
||||
|
||||
/// Stop the system
|
||||
pub fn stop(&self) {
|
||||
self.stop_with_code(0)
|
||||
@@ -109,7 +136,7 @@ impl System {
|
||||
/// This function will start tokio runtime and will finish once the
|
||||
/// `System::stop()` message get called.
|
||||
/// Function `f` get called within tokio runtime context.
|
||||
pub fn run<F>(f: F) -> i32
|
||||
pub fn run<F>(f: F) -> io::Result<()>
|
||||
where
|
||||
F: FnOnce() + 'static,
|
||||
{
|
||||
|
38
actix-server-config/Cargo.toml
Normal file
38
actix-server-config/Cargo.toml
Normal file
@@ -0,0 +1,38 @@
|
||||
[package]
|
||||
name = "actix-server-config"
|
||||
version = "0.1.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix server config utils"
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
license = "MIT/Apache-2.0"
|
||||
edition = "2018"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
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
|
241
actix-server-config/src/lib.rs
Normal file
241
actix-server-config/src/lib.rs
Normal file
@@ -0,0 +1,241 @@
|
||||
use std::cell::Cell;
|
||||
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 {
|
||||
addr: SocketAddr,
|
||||
secure: Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
impl ServerConfig {
|
||||
pub fn new(addr: SocketAddr) -> Self {
|
||||
ServerConfig {
|
||||
addr,
|
||||
secure: Rc::new(Cell::new(false)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the address of the local half of this TCP server socket
|
||||
pub fn local_addr(&self) -> SocketAddr {
|
||||
self.addr
|
||||
}
|
||||
|
||||
/// Returns true if connection is secure (tls enabled)
|
||||
pub fn secure(&self) -> bool {
|
||||
self.secure.as_ref().get()
|
||||
}
|
||||
|
||||
/// Set secure flag
|
||||
pub fn set_secure(&self) {
|
||||
self.secure.as_ref().set(true)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Protocol {
|
||||
Unknown,
|
||||
Http10,
|
||||
Http11,
|
||||
Http2,
|
||||
Proto1,
|
||||
Proto2,
|
||||
Proto3,
|
||||
Proto4,
|
||||
Proto5,
|
||||
Proto6,
|
||||
}
|
||||
|
||||
pub struct Io<T, P = ()> {
|
||||
io: T,
|
||||
proto: Protocol,
|
||||
params: P,
|
||||
}
|
||||
|
||||
impl<T> Io<T, ()> {
|
||||
pub fn new(io: T) -> Self {
|
||||
Self {
|
||||
io,
|
||||
proto: Protocol::Unknown,
|
||||
params: (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, P> Io<T, P> {
|
||||
/// Reconstruct from a parts.
|
||||
pub fn from_parts(io: T, params: P, proto: Protocol) -> Self {
|
||||
Self { io, params, proto }
|
||||
}
|
||||
|
||||
/// Deconstruct into a parts.
|
||||
pub fn into_parts(self) -> (T, P, Protocol) {
|
||||
(self.io, self.params, self.proto)
|
||||
}
|
||||
|
||||
/// Returns a shared reference to the underlying stream.
|
||||
pub fn get_ref(&self) -> &T {
|
||||
&self.io
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the underlying stream.
|
||||
pub fn get_mut(&mut self) -> &mut T {
|
||||
&mut self.io
|
||||
}
|
||||
|
||||
/// Get selected protocol
|
||||
pub fn protocol(&self) -> Protocol {
|
||||
self.proto
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps an Io<_, P> to Io<_, U> by applying a function to a contained value.
|
||||
pub fn map<U, F>(self, op: F) -> Io<T, U>
|
||||
where
|
||||
F: FnOnce(P) -> U,
|
||||
{
|
||||
Io {
|
||||
io: self.io,
|
||||
proto: self.proto,
|
||||
params: op(self.params),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, P> std::ops::Deref for Io<T, P> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
&self.io
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, P> std::ops::DerefMut for Io<T, P> {
|
||||
fn deref_mut(&mut self) -> &mut T {
|
||||
&mut self.io
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug, P> fmt::Debug for Io<T, P> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
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,84 @@
|
||||
# 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
|
||||
|
||||
* `SystemRuntime::on_start()` - allow to run future before server service initialization
|
||||
|
||||
|
||||
## [0.4.0] - 2019-03-12
|
||||
|
||||
### Changed
|
||||
|
||||
* Use `ServerConfig` for service factory
|
||||
|
||||
* Wrap tcp socket to `Io` type
|
||||
|
||||
* Upgrade actix-service
|
||||
|
||||
|
||||
## [0.3.1] - 2019-03-04
|
||||
|
||||
### Added
|
||||
|
||||
* Add `ServerBuilder::maxconnrate` sets the maximum per-worker number of concurrent connections
|
||||
|
||||
* Add helper ssl error `SslError`
|
||||
|
||||
|
||||
### Changed
|
||||
|
||||
* Rename `StreamServiceFactory` to `ServiceFactory`
|
||||
|
||||
* Deprecate `StreamServiceFactory`
|
||||
|
||||
|
||||
## [0.3.0] - 2019-03-02
|
||||
|
||||
### Changed
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-server"
|
||||
version = "0.3.0"
|
||||
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,19 +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-service = "0.3.0"
|
||||
actix-rt = "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"
|
||||
@@ -49,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 }
|
||||
|
||||
@@ -56,12 +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.2"
|
||||
env_logger = "0.6"
|
||||
actix-codec = "0.1.0"
|
||||
|
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,23 +9,26 @@ 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};
|
||||
use crate::config::{ConfiguredService, ServiceConfig};
|
||||
use crate::server::{Server, ServerCommand};
|
||||
use crate::services::{InternalServiceFactory, StreamNewService, StreamServiceFactory};
|
||||
use crate::services::{InternalServiceFactory, ServiceFactory, StreamNewService};
|
||||
use crate::signals::{Signal, Signals};
|
||||
use crate::socket::StdListener;
|
||||
use crate::worker::{self, Worker, WorkerAvailability, WorkerClient};
|
||||
use crate::Token;
|
||||
use crate::{ssl, Token};
|
||||
|
||||
/// Server builder
|
||||
pub struct ServerBuilder {
|
||||
threads: usize,
|
||||
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,
|
||||
@@ -53,6 +56,7 @@ impl ServerBuilder {
|
||||
services: Vec::new(),
|
||||
sockets: Vec::new(),
|
||||
accept: AcceptLoop::new(server.clone()),
|
||||
backlog: 2048,
|
||||
exit: false,
|
||||
shutdown_timeout: Duration::from_secs(30),
|
||||
no_signals: false,
|
||||
@@ -70,6 +74,21 @@ impl ServerBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the maximum number of pending connections.
|
||||
///
|
||||
/// This refers to the number of clients that can be waiting to be served.
|
||||
/// Exceeding this number results in the client getting an error when
|
||||
/// attempting to connect. It should only affect servers under significant
|
||||
/// load.
|
||||
///
|
||||
/// Generally set in the 64-2048 range. Default value is 2048.
|
||||
///
|
||||
/// This method should be called before `bind()` method call.
|
||||
pub fn backlog(mut self, num: i32) -> Self {
|
||||
self.backlog = num;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the maximum per-worker number of concurrent connections.
|
||||
///
|
||||
/// All socket listeners will stop accepting connections when this limit is
|
||||
@@ -81,9 +100,18 @@ impl ServerBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Stop actix system.
|
||||
/// Sets the maximum per-worker concurrent connection establish process.
|
||||
///
|
||||
/// `SystemExit` message stops currently running system.
|
||||
/// All listeners will stop accepting connections when this limit is reached. It
|
||||
/// can be used to limit the global SSL CPU usage.
|
||||
///
|
||||
/// By default max connections is set to a 256.
|
||||
pub fn maxconnrate(self, num: usize) -> Self {
|
||||
ssl::max_concurrent_ssl_connect(num);
|
||||
self
|
||||
}
|
||||
|
||||
/// Stop actix system.
|
||||
pub fn system_exit(mut self) -> Self {
|
||||
self.exit = true;
|
||||
self
|
||||
@@ -102,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
|
||||
}
|
||||
|
||||
@@ -116,7 +144,7 @@ impl ServerBuilder {
|
||||
where
|
||||
F: Fn(&mut ServiceConfig) -> io::Result<()>,
|
||||
{
|
||||
let mut cfg = ServiceConfig::new(self.threads);
|
||||
let mut cfg = ServiceConfig::new(self.threads, self.backlog);
|
||||
|
||||
f(&mut cfg)?;
|
||||
|
||||
@@ -124,8 +152,8 @@ impl ServerBuilder {
|
||||
let mut srv = ConfiguredService::new(apply);
|
||||
for (name, lst) in cfg.services {
|
||||
let token = self.token.next();
|
||||
srv.stream(token, name);
|
||||
self.sockets.push((token, lst));
|
||||
srv.stream(token, name, lst.local_addr()?);
|
||||
self.sockets.push((token, StdListener::Tcp(lst)));
|
||||
}
|
||||
self.services.push(Box::new(srv));
|
||||
}
|
||||
@@ -137,21 +165,49 @@ 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: StreamServiceFactory,
|
||||
F: ServiceFactory<TcpStream>,
|
||||
U: net::ToSocketAddrs,
|
||||
{
|
||||
let sockets = bind_addr(addr)?;
|
||||
let sockets = bind_addr(addr, self.backlog)?;
|
||||
|
||||
for lst in sockets {
|
||||
let token = self.token.next();
|
||||
self.services.push(StreamNewService::create(
|
||||
name.as_ref().to_string(),
|
||||
token,
|
||||
factory.clone(),
|
||||
lst.local_addr()?,
|
||||
));
|
||||
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,
|
||||
factory.clone(),
|
||||
addr,
|
||||
));
|
||||
|
||||
for lst in sockets {
|
||||
self.sockets.push((token, lst));
|
||||
}
|
||||
self.sockets.push((token, StdListener::Uds(lst)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
@@ -161,18 +217,19 @@ impl ServerBuilder {
|
||||
name: N,
|
||||
lst: net::TcpListener,
|
||||
factory: F,
|
||||
) -> Self
|
||||
) -> io::Result<Self>
|
||||
where
|
||||
F: StreamServiceFactory,
|
||||
F: ServiceFactory<TcpStream>,
|
||||
{
|
||||
let token = self.token.next();
|
||||
self.services.push(StreamNewService::create(
|
||||
name.as_ref().to_string(),
|
||||
token,
|
||||
factory,
|
||||
lst.local_addr()?,
|
||||
));
|
||||
self.sockets.push((token, lst));
|
||||
self
|
||||
self.sockets.push((token, StdListener::Tcp(lst)));
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Spawn new thread and start listening for incoming connections.
|
||||
@@ -185,19 +242,18 @@ impl ServerBuilder {
|
||||
/// ```rust,ignore
|
||||
/// use actix_web::*;
|
||||
///
|
||||
/// fn main() {
|
||||
/// fn main() -> std::io::Result<()> {
|
||||
/// Server::new().
|
||||
/// .service(
|
||||
/// HttpServer::new(|| App::new().resource("/", |r| r.h(|_| HttpResponse::Ok())))
|
||||
/// HttpServer::new(|| App::new().service(web::service("/").to(|| HttpResponse::Ok())))
|
||||
/// .bind("127.0.0.1:0")
|
||||
/// .expect("Can not bind to 127.0.0.1:0"))
|
||||
/// .run();
|
||||
/// .run()
|
||||
/// }
|
||||
/// ```
|
||||
pub fn run(self) {
|
||||
pub fn run(self) -> io::Result<()> {
|
||||
let sys = System::new("http-server");
|
||||
self.start();
|
||||
sys.run();
|
||||
sys.run()
|
||||
}
|
||||
|
||||
/// Starts processing incoming connections and return server controller.
|
||||
@@ -217,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);
|
||||
@@ -240,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 || {
|
||||
@@ -302,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
|
||||
@@ -384,12 +440,15 @@ impl Future for ServerBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn bind_addr<S: net::ToSocketAddrs>(addr: S) -> io::Result<Vec<net::TcpListener>> {
|
||||
pub(super) fn bind_addr<S: net::ToSocketAddrs>(
|
||||
addr: S,
|
||||
backlog: i32,
|
||||
) -> io::Result<Vec<net::TcpListener>> {
|
||||
let mut err = None;
|
||||
let mut succ = false;
|
||||
let mut sockets = Vec::new();
|
||||
for addr in addr.to_socket_addrs()? {
|
||||
match create_tcp_listener(addr) {
|
||||
match create_tcp_listener(addr, backlog) {
|
||||
Ok(lst) => {
|
||||
succ = true;
|
||||
sockets.push(lst);
|
||||
@@ -412,12 +471,12 @@ pub(super) fn bind_addr<S: net::ToSocketAddrs>(addr: S) -> io::Result<Vec<net::T
|
||||
}
|
||||
}
|
||||
|
||||
fn create_tcp_listener(addr: net::SocketAddr) -> io::Result<net::TcpListener> {
|
||||
fn create_tcp_listener(addr: net::SocketAddr, backlog: i32) -> io::Result<net::TcpListener> {
|
||||
let builder = match addr {
|
||||
net::SocketAddr::V4(_) => TcpBuilder::new_v4()?,
|
||||
net::SocketAddr::V6(_) => TcpBuilder::new_v6()?,
|
||||
};
|
||||
builder.reuse_address(true)?;
|
||||
builder.bind(addr)?;
|
||||
Ok(builder.listen(1024)?)
|
||||
Ok(builder.listen(backlog)?)
|
||||
}
|
||||
|
@@ -1,6 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::{fmt, io, net};
|
||||
|
||||
use actix_server_config::{Io, ServerConfig};
|
||||
use actix_service::{IntoNewService, NewService};
|
||||
use futures::future::{join_all, Future};
|
||||
use log::error;
|
||||
@@ -16,14 +17,16 @@ 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,
|
||||
}
|
||||
|
||||
impl ServiceConfig {
|
||||
pub(super) fn new(threads: usize) -> ServiceConfig {
|
||||
pub(super) fn new(threads: usize, backlog: i32) -> ServiceConfig {
|
||||
ServiceConfig {
|
||||
threads,
|
||||
backlog,
|
||||
services: Vec::new(),
|
||||
apply: None,
|
||||
}
|
||||
@@ -42,7 +45,7 @@ impl ServiceConfig {
|
||||
where
|
||||
U: net::ToSocketAddrs,
|
||||
{
|
||||
let sockets = bind_addr(addr)?;
|
||||
let sockets = bind_addr(addr, self.backlog)?;
|
||||
|
||||
for lst in sockets {
|
||||
self.listen(name.as_ref(), lst);
|
||||
@@ -72,13 +75,13 @@ impl ServiceConfig {
|
||||
}
|
||||
|
||||
pub(super) struct ConfiguredService {
|
||||
rt: Box<ServiceRuntimeConfiguration>,
|
||||
names: HashMap<Token, String>,
|
||||
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(),
|
||||
@@ -86,18 +89,18 @@ impl ConfiguredService {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn stream(&mut self, token: Token, name: String) {
|
||||
self.names.insert(token, name.clone());
|
||||
pub(super) fn stream(&mut self, token: Token, name: String, addr: net::SocketAddr) {
|
||||
self.names.insert(token, (name.clone(), addr));
|
||||
self.services.insert(name, token);
|
||||
}
|
||||
}
|
||||
|
||||
impl InternalServiceFactory for ConfiguredService {
|
||||
fn name(&self, token: Token) -> &str {
|
||||
&self.names[&token]
|
||||
&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(),
|
||||
@@ -105,26 +108,55 @@ 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);
|
||||
rt.validate();
|
||||
|
||||
// construct services
|
||||
let mut fut = Vec::new();
|
||||
for (token, ns) in rt.services {
|
||||
fut.push(ns.new_service(&()).map(move |service| (token, service)));
|
||||
}
|
||||
let services = rt.services;
|
||||
|
||||
Box::new(join_all(fut).map_err(|e| {
|
||||
error!("Can not construct service: {:?}", e);
|
||||
}))
|
||||
// on start futures
|
||||
if rt.onstart.is_empty() {
|
||||
// construct services
|
||||
let mut fut = Vec::new();
|
||||
for (token, ns) in services {
|
||||
let config = ServerConfig::new(self.names[&token].1);
|
||||
fut.push(ns.new_service(&config).map(move |service| (token, service)));
|
||||
}
|
||||
|
||||
Box::new(join_all(fut).map_err(|e| {
|
||||
error!("Can not construct service: {:?}", e);
|
||||
}))
|
||||
} else {
|
||||
let names = self.names.clone();
|
||||
|
||||
// run onstart future and then construct services
|
||||
Box::new(
|
||||
join_all(rt.onstart)
|
||||
.map_err(|e| {
|
||||
error!("Can not construct service: {:?}", e);
|
||||
})
|
||||
.and_then(move |_| {
|
||||
// construct services
|
||||
let mut fut = Vec::new();
|
||||
for (token, ns) in services {
|
||||
let config = ServerConfig::new(names[&token].1);
|
||||
fut.push(
|
||||
ns.new_service(&config).map(move |service| (token, service)),
|
||||
);
|
||||
}
|
||||
join_all(fut).map_err(|e| {
|
||||
error!("Can not construct service: {:?}", e);
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) trait ServiceRuntimeConfiguration: Send {
|
||||
fn clone(&self) -> Box<ServiceRuntimeConfiguration>;
|
||||
fn clone(&self) -> Box<dyn ServiceRuntimeConfiguration>;
|
||||
|
||||
fn configure(&self, rt: &mut ServiceRuntime);
|
||||
}
|
||||
@@ -133,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())
|
||||
}
|
||||
|
||||
@@ -149,6 +181,7 @@ fn not_configured(_: &mut ServiceRuntime) {
|
||||
pub struct ServiceRuntime {
|
||||
names: HashMap<String, Token>,
|
||||
services: HashMap<Token, BoxedNewService>,
|
||||
onstart: Vec<Box<dyn Future<Item = (), Error = ()>>>,
|
||||
}
|
||||
|
||||
impl ServiceRuntime {
|
||||
@@ -156,6 +189,7 @@ impl ServiceRuntime {
|
||||
ServiceRuntime {
|
||||
names,
|
||||
services: HashMap::new(),
|
||||
onstart: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,10 +201,14 @@ impl ServiceRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
/// Register service.
|
||||
///
|
||||
/// Name of the service must be registered during configuration stage with
|
||||
/// *ServiceConfig::bind()* or *ServiceConfig::listen()* methods.
|
||||
pub fn service<T, F>(&mut self, name: &str, service: F)
|
||||
where
|
||||
F: IntoNewService<T>,
|
||||
T: NewService<Request = TcpStream, Response = ()> + 'static,
|
||||
T: NewService<Config = ServerConfig, Request = Io<TcpStream>> + 'static,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
T::InitError: fmt::Debug,
|
||||
@@ -187,16 +225,25 @@ impl ServiceRuntime {
|
||||
panic!("Unknown service: {:?}", name);
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute future before services initialization.
|
||||
pub fn on_start<F>(&mut self, fut: F)
|
||||
where
|
||||
F: Future<Item = (), Error = ()> + 'static,
|
||||
{
|
||||
self.onstart.push(Box::new(fut))
|
||||
}
|
||||
}
|
||||
|
||||
type BoxedNewService = Box<
|
||||
NewService<
|
||||
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 = ()>>,
|
||||
>,
|
||||
>;
|
||||
|
||||
@@ -206,7 +253,7 @@ struct ServiceFactory<T> {
|
||||
|
||||
impl<T> NewService for ServiceFactory<T>
|
||||
where
|
||||
T: NewService<Request = TcpStream, Response = ()>,
|
||||
T: NewService<Config = ServerConfig, Request = Io<TcpStream>>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
T::Error: 'static,
|
||||
@@ -216,11 +263,12 @@ 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, _: &()) -> Self::Future {
|
||||
Box::new(self.inner.new_service(&()).map_err(|_| ()).map(|s| {
|
||||
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
|
||||
Box::new(self.inner.new_service(cfg).map_err(|_| ()).map(|s| {
|
||||
let service: BoxedServerService = Box::new(StreamService::new(s));
|
||||
service
|
||||
}))
|
||||
|
@@ -7,13 +7,22 @@ mod counter;
|
||||
mod server;
|
||||
mod services;
|
||||
mod signals;
|
||||
mod socket;
|
||||
pub mod ssl;
|
||||
mod worker;
|
||||
|
||||
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::StreamServiceFactory;
|
||||
pub use self::services::ServiceFactory;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use self::socket::FromStream;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use self::services::ServiceFactory as StreamServiceFactory;
|
||||
|
||||
/// Socket id token
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
|
@@ -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,29 +1,30 @@
|
||||
use std::net;
|
||||
use std::marker::PhantomData;
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
use actix_rt::spawn;
|
||||
use actix_server_config::{Io, ServerConfig};
|
||||
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 StreamServiceFactory: Send + Clone + 'static {
|
||||
type NewService: NewService<Request = TcpStream>;
|
||||
pub trait ServiceFactory<Stream: FromStream>: Send + Clone + 'static {
|
||||
type NewService: NewService<Config = ServerConfig, Request = Io<Stream>>;
|
||||
|
||||
fn create(&self) -> Self::NewService;
|
||||
}
|
||||
@@ -31,13 +32,13 @@ pub trait StreamServiceFactory: 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 = (),
|
||||
@@ -55,11 +56,12 @@ impl<T> StreamService<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service for StreamService<T>
|
||||
impl<T, I> Service for StreamService<T>
|
||||
where
|
||||
T: Service<Request = TcpStream>,
|
||||
T: Service<Request = Io<I>>,
|
||||
T::Future: 'static,
|
||||
T::Error: 'static,
|
||||
I: FromStream,
|
||||
{
|
||||
type Request = (Option<CounterGuard>, ServerMessage);
|
||||
type Response = ();
|
||||
@@ -73,12 +75,12 @@ 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);
|
||||
});
|
||||
|
||||
if let Ok(stream) = stream {
|
||||
spawn(self.service.call(stream).then(move |res| {
|
||||
spawn(self.service.call(Io::new(stream)).then(move |res| {
|
||||
drop(guard);
|
||||
res.map_err(|_| ()).map(|_| ())
|
||||
}));
|
||||
@@ -92,43 +94,61 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct StreamNewService<F: StreamServiceFactory> {
|
||||
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: StreamServiceFactory,
|
||||
F: ServiceFactory<Io>,
|
||||
Io: FromStream + Send + 'static,
|
||||
{
|
||||
pub(crate) fn create(name: String, token: Token, inner: F) -> Box<InternalServiceFactory> {
|
||||
Box::new(Self { name, token, inner })
|
||||
pub(crate) fn create(
|
||||
name: String,
|
||||
token: Token,
|
||||
inner: F,
|
||||
addr: SocketAddr,
|
||||
) -> 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: StreamServiceFactory,
|
||||
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(
|
||||
self.inner
|
||||
.create()
|
||||
.new_service(&())
|
||||
.new_service(&config)
|
||||
.map_err(|_| ())
|
||||
.map(move |inner| {
|
||||
let service: BoxedServerService = Box::new(StreamService::new(inner));
|
||||
@@ -138,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> StreamServiceFactory for F
|
||||
impl<F, T, I> ServiceFactory<I> for F
|
||||
where
|
||||
F: Fn() -> T + Send + Clone + 'static,
|
||||
T: NewService<Request = 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())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@@ -33,3 +33,10 @@ pub(crate) static MAX_CONN: AtomicUsize = AtomicUsize::new(256);
|
||||
thread_local! {
|
||||
static MAX_CONN_COUNTER: Counter = Counter::new(MAX_CONN.load(Ordering::Relaxed));
|
||||
}
|
||||
|
||||
/// Ssl error combinded with service error.
|
||||
#[derive(Debug)]
|
||||
pub enum SslError<E1, E2> {
|
||||
Ssl(E1),
|
||||
Service(E2),
|
||||
}
|
||||
|
@@ -6,18 +6,19 @@ use futures::{future::ok, future::FutureResult, Async, Future, Poll};
|
||||
use native_tls::{self, Error, HandshakeError, TlsAcceptor};
|
||||
use tokio_io::{AsyncRead, AsyncWrite};
|
||||
|
||||
use super::MAX_CONN_COUNTER;
|
||||
use crate::counter::{Counter, CounterGuard};
|
||||
use crate::ssl::MAX_CONN_COUNTER;
|
||||
use crate::{Io, Protocol, ServerConfig};
|
||||
|
||||
/// Support `SSL` connections via native-tls package
|
||||
///
|
||||
/// `tls` feature enables `NativeTlsAcceptor` type
|
||||
pub struct NativeTlsAcceptor<T> {
|
||||
pub struct NativeTlsAcceptor<T, P = ()> {
|
||||
acceptor: TlsAcceptor,
|
||||
io: PhantomData<T>,
|
||||
io: PhantomData<(T, P)>,
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> NativeTlsAcceptor<T> {
|
||||
impl<T: AsyncRead + AsyncWrite, P> NativeTlsAcceptor<T, P> {
|
||||
/// Create `NativeTlsAcceptor` instance
|
||||
pub fn new(acceptor: TlsAcceptor) -> Self {
|
||||
NativeTlsAcceptor {
|
||||
@@ -27,7 +28,7 @@ impl<T: AsyncRead + AsyncWrite> NativeTlsAcceptor<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> Clone for NativeTlsAcceptor<T> {
|
||||
impl<T: AsyncRead + AsyncWrite, P> Clone for NativeTlsAcceptor<T, P> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
acceptor: self.acceptor.clone(),
|
||||
@@ -36,15 +37,19 @@ impl<T: AsyncRead + AsyncWrite> Clone for NativeTlsAcceptor<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> NewService for NativeTlsAcceptor<T> {
|
||||
type Request = T;
|
||||
type Response = TlsStream<T>;
|
||||
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 Service = NativeTlsAcceptorService<T>;
|
||||
|
||||
type Config = ServerConfig;
|
||||
type Service = NativeTlsAcceptorService<T, P>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
|
||||
cfg.set_secure();
|
||||
|
||||
MAX_CONN_COUNTER.with(|conns| {
|
||||
ok(NativeTlsAcceptorService {
|
||||
acceptor: self.acceptor.clone(),
|
||||
@@ -55,17 +60,17 @@ impl<T: AsyncRead + AsyncWrite> NewService for NativeTlsAcceptor<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NativeTlsAcceptorService<T> {
|
||||
pub struct NativeTlsAcceptorService<T, P> {
|
||||
acceptor: TlsAcceptor,
|
||||
io: PhantomData<T>,
|
||||
io: PhantomData<(T, P)>,
|
||||
conns: Counter,
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> Service for NativeTlsAcceptorService<T> {
|
||||
type Request = T;
|
||||
type Response = TlsStream<T>;
|
||||
impl<T: AsyncRead + AsyncWrite, P> Service for NativeTlsAcceptorService<T, P> {
|
||||
type Request = Io<T, P>;
|
||||
type Response = Io<TlsStream<T>, P>;
|
||||
type Error = Error;
|
||||
type Future = Accept<T>;
|
||||
type Future = Accept<T, P>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
if self.conns.available() {
|
||||
@@ -75,10 +80,12 @@ impl<T: AsyncRead + AsyncWrite> Service for NativeTlsAcceptorService<T> {
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T) -> Self::Future {
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
let (io, params, _) = req.into_parts();
|
||||
Accept {
|
||||
_guard: self.conns.get(),
|
||||
inner: Some(self.acceptor.accept(req)),
|
||||
inner: Some(self.acceptor.accept(io)),
|
||||
params: Some(params),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,21 +104,30 @@ pub struct TlsStream<S> {
|
||||
|
||||
/// Future returned from `NativeTlsAcceptor::accept` which will resolve
|
||||
/// once the accept handshake has finished.
|
||||
pub struct Accept<S> {
|
||||
pub struct Accept<S, P> {
|
||||
inner: Option<Result<native_tls::TlsStream<S>, HandshakeError<S>>>,
|
||||
params: Option<P>,
|
||||
_guard: CounterGuard,
|
||||
}
|
||||
|
||||
impl<Io: AsyncRead + AsyncWrite> Future for Accept<Io> {
|
||||
type Item = TlsStream<Io>;
|
||||
impl<T: AsyncRead + AsyncWrite, P> Future for Accept<T, P> {
|
||||
type Item = Io<TlsStream<T>, P>;
|
||||
type Error = Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.inner.take().expect("cannot poll MidHandshake twice") {
|
||||
Ok(stream) => Ok(TlsStream { inner: stream }.into()),
|
||||
Ok(stream) => Ok(Async::Ready(Io::from_parts(
|
||||
TlsStream { inner: stream },
|
||||
self.params.take().unwrap(),
|
||||
Protocol::Unknown,
|
||||
))),
|
||||
Err(HandshakeError::Failure(e)) => Err(e),
|
||||
Err(HandshakeError::WouldBlock(s)) => match s.handshake() {
|
||||
Ok(stream) => Ok(TlsStream { inner: stream }.into()),
|
||||
Ok(stream) => Ok(Async::Ready(Io::from_parts(
|
||||
TlsStream { inner: stream },
|
||||
self.params.take().unwrap(),
|
||||
Protocol::Unknown,
|
||||
))),
|
||||
Err(HandshakeError::Failure(e)) => Err(e),
|
||||
Err(HandshakeError::WouldBlock(s)) => {
|
||||
self.inner = Some(Err(HandshakeError::WouldBlock(s)));
|
||||
|
@@ -6,18 +6,19 @@ use openssl::ssl::{HandshakeError, SslAcceptor};
|
||||
use tokio_io::{AsyncRead, AsyncWrite};
|
||||
use tokio_openssl::{AcceptAsync, SslAcceptorExt, SslStream};
|
||||
|
||||
use super::MAX_CONN_COUNTER;
|
||||
use crate::counter::{Counter, CounterGuard};
|
||||
use crate::ssl::MAX_CONN_COUNTER;
|
||||
use crate::{Io, Protocol, ServerConfig};
|
||||
|
||||
/// Support `SSL` connections via openssl package
|
||||
///
|
||||
/// `ssl` feature enables `OpensslAcceptor` type
|
||||
pub struct OpensslAcceptor<T> {
|
||||
pub struct OpensslAcceptor<T: AsyncRead + AsyncWrite, P = ()> {
|
||||
acceptor: SslAcceptor,
|
||||
io: PhantomData<T>,
|
||||
io: PhantomData<(T, P)>,
|
||||
}
|
||||
|
||||
impl<T> OpensslAcceptor<T> {
|
||||
impl<T: AsyncRead + AsyncWrite, P> OpensslAcceptor<T, P> {
|
||||
/// Create default `OpensslAcceptor`
|
||||
pub fn new(acceptor: SslAcceptor) -> Self {
|
||||
OpensslAcceptor {
|
||||
@@ -27,7 +28,7 @@ impl<T> OpensslAcceptor<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> Clone for OpensslAcceptor<T> {
|
||||
impl<T: AsyncRead + AsyncWrite, P> Clone for OpensslAcceptor<T, P> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
acceptor: self.acceptor.clone(),
|
||||
@@ -36,15 +37,18 @@ impl<T: AsyncRead + AsyncWrite> Clone for OpensslAcceptor<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> NewService for OpensslAcceptor<T> {
|
||||
type Request = T;
|
||||
type Response = SslStream<T>;
|
||||
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 Service = OpensslAcceptorService<T>;
|
||||
type Config = ServerConfig;
|
||||
type Service = OpensslAcceptorService<T, P>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
fn new_service(&self, cfg: &ServerConfig) -> Self::Future {
|
||||
cfg.set_secure();
|
||||
|
||||
MAX_CONN_COUNTER.with(|conns| {
|
||||
ok(OpensslAcceptorService {
|
||||
acceptor: self.acceptor.clone(),
|
||||
@@ -55,17 +59,17 @@ impl<T: AsyncRead + AsyncWrite> NewService for OpensslAcceptor<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct OpensslAcceptorService<T> {
|
||||
pub struct OpensslAcceptorService<T, P> {
|
||||
acceptor: SslAcceptor,
|
||||
io: PhantomData<T>,
|
||||
conns: Counter,
|
||||
io: PhantomData<(T, P)>,
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> Service for OpensslAcceptorService<T> {
|
||||
type Request = T;
|
||||
type Response = SslStream<T>;
|
||||
impl<T: AsyncRead + AsyncWrite, P> Service for OpensslAcceptorService<T, P> {
|
||||
type Request = Io<T, P>;
|
||||
type Response = Io<SslStream<T>, P>;
|
||||
type Error = HandshakeError<T>;
|
||||
type Future = OpensslAcceptorServiceFut<T>;
|
||||
type Future = OpensslAcceptorServiceFut<T, P>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
if self.conns.available() {
|
||||
@@ -75,27 +79,52 @@ impl<T: AsyncRead + AsyncWrite> Service for OpensslAcceptorService<T> {
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T) -> Self::Future {
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
let (io, params, _) = req.into_parts();
|
||||
OpensslAcceptorServiceFut {
|
||||
_guard: self.conns.get(),
|
||||
fut: SslAcceptorExt::accept_async(&self.acceptor, req),
|
||||
fut: SslAcceptorExt::accept_async(&self.acceptor, io),
|
||||
params: Some(params),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct OpensslAcceptorServiceFut<T>
|
||||
pub struct OpensslAcceptorServiceFut<T, P>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
{
|
||||
fut: AcceptAsync<T>,
|
||||
params: Option<P>,
|
||||
_guard: CounterGuard,
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> Future for OpensslAcceptorServiceFut<T> {
|
||||
type Item = SslStream<T>;
|
||||
impl<T: AsyncRead + AsyncWrite, P> Future for OpensslAcceptorServiceFut<T, P> {
|
||||
type Item = Io<SslStream<T>, P>;
|
||||
type Error = HandshakeError<T>;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
self.fut.poll()
|
||||
let io = futures::try_ready!(self.fut.poll());
|
||||
let proto = if let Some(protos) = io.get_ref().ssl().selected_alpn_protocol() {
|
||||
const H2: &[u8] = b"\x02h2";
|
||||
const HTTP10: &[u8] = b"\x08http/1.0";
|
||||
const HTTP11: &[u8] = b"\x08http/1.1";
|
||||
|
||||
if protos.windows(3).any(|window| window == H2) {
|
||||
Protocol::Http2
|
||||
} else if protos.windows(9).any(|window| window == HTTP11) {
|
||||
Protocol::Http11
|
||||
} else if protos.windows(9).any(|window| window == HTTP10) {
|
||||
Protocol::Http10
|
||||
} else {
|
||||
Protocol::Unknown
|
||||
}
|
||||
} else {
|
||||
Protocol::Unknown
|
||||
};
|
||||
Ok(Async::Ready(Io::from_parts(
|
||||
io,
|
||||
self.params.take().unwrap(),
|
||||
proto,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
@@ -8,18 +8,19 @@ use rustls::{ServerConfig, ServerSession};
|
||||
use tokio_io::{AsyncRead, AsyncWrite};
|
||||
use tokio_rustls::{Accept, TlsAcceptor, TlsStream};
|
||||
|
||||
use super::MAX_CONN_COUNTER;
|
||||
use crate::counter::{Counter, CounterGuard};
|
||||
use crate::ssl::MAX_CONN_COUNTER;
|
||||
use crate::{Io, Protocol, ServerConfig as SrvConfig};
|
||||
|
||||
/// Support `SSL` connections via rustls package
|
||||
///
|
||||
/// `rust-tls` feature enables `RustlsAcceptor` type
|
||||
pub struct RustlsAcceptor<T> {
|
||||
pub struct RustlsAcceptor<T, P = ()> {
|
||||
config: Arc<ServerConfig>,
|
||||
io: PhantomData<T>,
|
||||
io: PhantomData<(T, P)>,
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> RustlsAcceptor<T> {
|
||||
impl<T: AsyncRead + AsyncWrite, P> RustlsAcceptor<T, P> {
|
||||
/// Create `RustlsAcceptor` new service
|
||||
pub fn new(config: ServerConfig) -> Self {
|
||||
RustlsAcceptor {
|
||||
@@ -29,7 +30,7 @@ impl<T: AsyncRead + AsyncWrite> RustlsAcceptor<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for RustlsAcceptor<T> {
|
||||
impl<T, P> Clone for RustlsAcceptor<T, P> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
config: self.config.clone(),
|
||||
@@ -38,15 +39,19 @@ impl<T> Clone for RustlsAcceptor<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> NewService for RustlsAcceptor<T> {
|
||||
type Request = T;
|
||||
type Response = TlsStream<T, ServerSession>;
|
||||
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 Service = RustlsAcceptorService<T>;
|
||||
|
||||
type Config = SrvConfig;
|
||||
type Service = RustlsAcceptorService<T, P>;
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
fn new_service(&self, cfg: &SrvConfig) -> Self::Future {
|
||||
cfg.set_secure();
|
||||
|
||||
MAX_CONN_COUNTER.with(|conns| {
|
||||
ok(RustlsAcceptorService {
|
||||
acceptor: self.config.clone().into(),
|
||||
@@ -57,17 +62,17 @@ impl<T: AsyncRead + AsyncWrite> NewService for RustlsAcceptor<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RustlsAcceptorService<T> {
|
||||
pub struct RustlsAcceptorService<T, P> {
|
||||
acceptor: TlsAcceptor,
|
||||
io: PhantomData<T>,
|
||||
io: PhantomData<(T, P)>,
|
||||
conns: Counter,
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> Service for RustlsAcceptorService<T> {
|
||||
type Request = T;
|
||||
type Response = TlsStream<T, ServerSession>;
|
||||
impl<T: AsyncRead + AsyncWrite, P> Service for RustlsAcceptorService<T, P> {
|
||||
type Request = Io<T, P>;
|
||||
type Response = Io<TlsStream<T, ServerSession>, P>;
|
||||
type Error = io::Error;
|
||||
type Future = RustlsAcceptorServiceFut<T>;
|
||||
type Future = RustlsAcceptorServiceFut<T, P>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
if self.conns.available() {
|
||||
@@ -77,27 +82,35 @@ impl<T: AsyncRead + AsyncWrite> Service for RustlsAcceptorService<T> {
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T) -> Self::Future {
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
let (io, params, _) = req.into_parts();
|
||||
RustlsAcceptorServiceFut {
|
||||
_guard: self.conns.get(),
|
||||
fut: self.acceptor.accept(req),
|
||||
fut: self.acceptor.accept(io),
|
||||
params: Some(params),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RustlsAcceptorServiceFut<T>
|
||||
pub struct RustlsAcceptorServiceFut<T, P>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
{
|
||||
fut: Accept<T>,
|
||||
params: Option<P>,
|
||||
_guard: CounterGuard,
|
||||
}
|
||||
|
||||
impl<T: AsyncRead + AsyncWrite> Future for RustlsAcceptorServiceFut<T> {
|
||||
type Item = TlsStream<T, ServerSession>;
|
||||
impl<T: AsyncRead + AsyncWrite, P> Future for RustlsAcceptorServiceFut<T, P> {
|
||||
type Item = Io<TlsStream<T, ServerSession>, P>;
|
||||
type Error = io::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
self.fut.poll()
|
||||
let io = futures::try_ready!(self.fut.poll());
|
||||
Ok(Async::Ready(Io::from_parts(
|
||||
io,
|
||||
self.params.take().unwrap(),
|
||||
Protocol::Unknown,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
@@ -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>),
|
||||
}
|
||||
|
162
actix-server/tests/test_server.rs
Normal file
162
actix-server/tests/test_server.rs
Normal file
@@ -0,0 +1,162 @@
|
||||
use std::io::Read;
|
||||
use std::sync::mpsc;
|
||||
use std::{net, thread, time};
|
||||
|
||||
use actix_codec::{BytesCodec, Framed};
|
||||
use actix_server::{Io, Server, ServerConfig};
|
||||
use actix_service::{new_service_cfg, service_fn, IntoService};
|
||||
use bytes::Bytes;
|
||||
use futures::{Future, Sink};
|
||||
use net2::TcpBuilder;
|
||||
use tokio_tcp::TcpStream;
|
||||
|
||||
fn unused_addr() -> net::SocketAddr {
|
||||
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
|
||||
let socket = TcpBuilder::new_v4().unwrap();
|
||||
socket.bind(&addr).unwrap();
|
||||
socket.reuse_address(true).unwrap();
|
||||
let tcp = socket.to_tcp_listener().unwrap();
|
||||
tcp.local_addr().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bind() {
|
||||
let addr = unused_addr();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
|
||||
let h = thread::spawn(move || {
|
||||
let sys = actix_rt::System::new("test");
|
||||
let srv = Server::build()
|
||||
.bind("test", addr, move || {
|
||||
new_service_cfg(move |cfg: &ServerConfig| {
|
||||
assert_eq!(cfg.local_addr(), addr);
|
||||
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
|
||||
})
|
||||
})
|
||||
.unwrap()
|
||||
.start();
|
||||
let _ = tx.send((srv, actix_rt::System::current()));
|
||||
let _ = sys.run();
|
||||
});
|
||||
let (_, sys) = rx.recv().unwrap();
|
||||
|
||||
thread::sleep(time::Duration::from_millis(500));
|
||||
assert!(net::TcpStream::connect(addr).is_ok());
|
||||
let _ = sys.stop();
|
||||
let _ = h.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bind_no_config() {
|
||||
let addr = unused_addr();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
|
||||
let h = thread::spawn(move || {
|
||||
let sys = actix_rt::System::new("test");
|
||||
let srv = Server::build()
|
||||
.bind("test", addr, move || service_fn(|_| Ok::<_, ()>(())))
|
||||
.unwrap()
|
||||
.start();
|
||||
let _ = tx.send((srv, actix_rt::System::current()));
|
||||
let _ = sys.run();
|
||||
});
|
||||
let (_, sys) = rx.recv().unwrap();
|
||||
assert!(net::TcpStream::connect(addr).is_ok());
|
||||
let _ = sys.stop();
|
||||
let _ = h.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_listen() {
|
||||
let addr = unused_addr();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
|
||||
let h = thread::spawn(move || {
|
||||
let sys = actix_rt::System::new("test");
|
||||
let lst = net::TcpListener::bind(addr).unwrap();
|
||||
let srv = Server::build()
|
||||
.listen("test", lst, move || {
|
||||
new_service_cfg(move |cfg: &ServerConfig| {
|
||||
assert_eq!(cfg.local_addr(), addr);
|
||||
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
|
||||
})
|
||||
})
|
||||
.unwrap()
|
||||
.start();
|
||||
let _ = tx.send((srv, actix_rt::System::current()));
|
||||
let _ = sys.run();
|
||||
});
|
||||
let (_, sys) = rx.recv().unwrap();
|
||||
|
||||
thread::sleep(time::Duration::from_millis(500));
|
||||
assert!(net::TcpStream::connect(addr).is_ok());
|
||||
let _ = sys.stop();
|
||||
let _ = h.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn test_start() {
|
||||
let addr = unused_addr();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
|
||||
let h = thread::spawn(move || {
|
||||
let sys = actix_rt::System::new("test");
|
||||
let srv = Server::build()
|
||||
.backlog(100)
|
||||
.bind("test", addr, move || {
|
||||
new_service_cfg(move |cfg: &ServerConfig| {
|
||||
assert_eq!(cfg.local_addr(), addr);
|
||||
Ok::<_, ()>(
|
||||
(|io: Io<TcpStream>| {
|
||||
Framed::new(io.into_parts().0, BytesCodec)
|
||||
.send(Bytes::from_static(b"test"))
|
||||
.then(|_| Ok::<_, ()>(()))
|
||||
})
|
||||
.into_service(),
|
||||
)
|
||||
})
|
||||
})
|
||||
.unwrap()
|
||||
.start();
|
||||
|
||||
let _ = tx.send((srv, actix_rt::System::current()));
|
||||
let _ = sys.run();
|
||||
});
|
||||
let (srv, sys) = rx.recv().unwrap();
|
||||
|
||||
let mut buf = [0u8; 4];
|
||||
let mut conn = net::TcpStream::connect(addr).unwrap();
|
||||
let _ = conn.read_exact(&mut buf);
|
||||
assert_eq!(buf, b"test"[..]);
|
||||
|
||||
// pause
|
||||
let _ = srv.pause();
|
||||
thread::sleep(time::Duration::from_millis(200));
|
||||
let mut conn = net::TcpStream::connect(addr).unwrap();
|
||||
conn.set_read_timeout(Some(time::Duration::from_millis(100)))
|
||||
.unwrap();
|
||||
let res = conn.read_exact(&mut buf);
|
||||
assert!(res.is_err());
|
||||
|
||||
// resume
|
||||
let _ = srv.resume();
|
||||
thread::sleep(time::Duration::from_millis(100));
|
||||
assert!(net::TcpStream::connect(addr).is_ok());
|
||||
assert!(net::TcpStream::connect(addr).is_ok());
|
||||
assert!(net::TcpStream::connect(addr).is_ok());
|
||||
|
||||
let mut buf = [0u8; 4];
|
||||
let mut conn = net::TcpStream::connect(addr).unwrap();
|
||||
let _ = conn.read_exact(&mut buf);
|
||||
assert_eq!(buf, b"test"[..]);
|
||||
|
||||
// stop
|
||||
let _ = srv.stop(false);
|
||||
thread::sleep(time::Duration::from_millis(100));
|
||||
assert!(net::TcpStream::connect(addr).is_err());
|
||||
|
||||
thread::sleep(time::Duration::from_millis(100));
|
||||
let _ = sys.stop();
|
||||
let _ = h.join();
|
||||
}
|
@@ -1,5 +1,92 @@
|
||||
# Changes
|
||||
|
||||
## [0.4.2] - 2019-08-27
|
||||
|
||||
### Fixed
|
||||
|
||||
* Check service readiness for `new_apply_cfg` combinator
|
||||
|
||||
|
||||
## [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
|
||||
|
||||
* Add `Transform::from_err()` combinator
|
||||
|
||||
* Add `apply_fn` helper
|
||||
|
||||
* Add `apply_fn_factory` helper
|
||||
|
||||
* Add `apply_transform` helper
|
||||
|
||||
* Add `apply_cfg` helper
|
||||
|
||||
|
||||
## [0.3.3] - 2019-03-09
|
||||
|
||||
### Added
|
||||
|
||||
* Add `ApplyTransform` new service for transform and new service.
|
||||
|
||||
* Add `NewService::apply_cfg()` combinator, allows to use
|
||||
nested `NewService` with different config parameter.
|
||||
|
||||
### Changed
|
||||
|
||||
* Revert IntoFuture change
|
||||
|
||||
|
||||
## [0.3.2] - 2019-03-04
|
||||
|
||||
### Changed
|
||||
|
||||
* Change `NewService::Future` and `Transform::Future` to the `IntoFuture` trait.
|
||||
|
||||
* Export `AndThenTransform` type
|
||||
|
||||
|
||||
## [0.3.1] - 2019-03-04
|
||||
|
||||
### Changed
|
||||
|
||||
* Simplify Transform trait
|
||||
|
||||
|
||||
## [0.3.0] - 2019-03-02
|
||||
|
||||
## Added
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-service"
|
||||
version = "0.3.0"
|
||||
version = "0.4.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix Service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -23,5 +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,6 +1,4 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{try_ready, Async, Future, Poll};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::{IntoNewService, NewService, Service};
|
||||
use crate::cell::Cell;
|
||||
@@ -48,8 +46,12 @@ where
|
||||
type Future = AndThenFuture<A, B>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
try_ready!(self.a.poll_ready());
|
||||
self.b.get_mut().poll_ready()
|
||||
let not_ready = self.a.poll_ready()?.is_not_ready();
|
||||
if self.b.get_mut().poll_ready()?.is_not_ready() || not_ready {
|
||||
Ok(Async::NotReady)
|
||||
} else {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||
@@ -107,63 +109,75 @@ where
|
||||
}
|
||||
|
||||
/// `AndThenNewService` new service combinator
|
||||
pub struct AndThenNewService<A, B, C> {
|
||||
pub struct AndThenNewService<A, B>
|
||||
where
|
||||
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,
|
||||
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
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self {
|
||||
Self {
|
||||
a,
|
||||
b: f.into_new_service(),
|
||||
_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: Clone,
|
||||
B: 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,
|
||||
@@ -171,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 {
|
||||
@@ -186,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;
|
||||
|
@@ -1,141 +1,23 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::{NewService, NewTransform, Service, Transform};
|
||||
use crate::cell::Cell;
|
||||
use crate::and_then::AndThen;
|
||||
use crate::from_err::FromErr;
|
||||
use crate::{NewService, Transform};
|
||||
|
||||
/// `Apply` service combinator
|
||||
pub struct AndThenTransform<T, A, B>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
/// `Apply` new service combinator
|
||||
pub struct AndThenTransform<T, A, B> {
|
||||
a: A,
|
||||
b: Cell<B>,
|
||||
t: Cell<T>,
|
||||
b: B,
|
||||
t: Rc<T>,
|
||||
}
|
||||
|
||||
impl<T, A, B> AndThenTransform<T, A, B>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
/// Create new `Apply` combinator
|
||||
pub fn new(t: T, a: A, b: B) -> Self {
|
||||
Self {
|
||||
a,
|
||||
b: Cell::new(b),
|
||||
t: Cell::new(t),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A, B> Clone for AndThenTransform<T, A, B>
|
||||
where
|
||||
A: Service + Clone,
|
||||
B: Service<Error = A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
AndThenTransform {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
t: self.t.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A, B> Service for AndThenTransform<T, A, B>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = AndThenTransformFuture<T, A, B>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
let notready = Async::NotReady == self.a.poll_ready()?;
|
||||
let notready = Async::NotReady == self.b.get_mut().poll_ready()? || notready;
|
||||
let notready = Async::NotReady == self.t.get_mut().poll_ready()? || notready;
|
||||
|
||||
if notready {
|
||||
Ok(Async::NotReady)
|
||||
} else {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||
AndThenTransformFuture {
|
||||
b: self.b.clone(),
|
||||
t: self.t.clone(),
|
||||
fut_t: None,
|
||||
fut_a: Some(self.a.call(req)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenTransformFuture<T, A, B>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
b: Cell<B>,
|
||||
t: Cell<T>,
|
||||
fut_a: Option<A::Future>,
|
||||
fut_t: Option<T::Future>,
|
||||
}
|
||||
|
||||
impl<T, A, B> Future for AndThenTransformFuture<T, A, B>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
type Item = T::Response;
|
||||
type Error = T::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.fut_t {
|
||||
return fut.poll();
|
||||
}
|
||||
|
||||
match self.fut_a.as_mut().expect("Bug in actix-service").poll() {
|
||||
Ok(Async::Ready(resp)) => {
|
||||
let _ = self.fut_a.take();
|
||||
self.fut_t = Some(self.t.get_mut().call(resp, self.b.get_mut()));
|
||||
self.poll()
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Apply` new service combinator
|
||||
pub struct AndThenTransformNewService<T, A, B, C> {
|
||||
a: A,
|
||||
b: B,
|
||||
t: T,
|
||||
_t: std::marker::PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<T, A, B, C> AndThenTransformNewService<T, A, B, C>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Error = A::Error, InitError = A::InitError>,
|
||||
T: NewTransform<B::Service, Request = A::Response, 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>,
|
||||
{
|
||||
/// Create new `ApplyNewService` new service instance
|
||||
@@ -143,84 +25,82 @@ where
|
||||
Self {
|
||||
a,
|
||||
b,
|
||||
t,
|
||||
_t: std::marker::PhantomData,
|
||||
t: Rc::new(t),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A, B, C> Clone for AndThenTransformNewService<T, A, B, C>
|
||||
impl<T, A, B> Clone for AndThenTransform<T, A, B>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
T: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
t: self.t.clone(),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A, B, C> NewService<C> for AndThenTransformNewService<T, A, B, C>
|
||||
impl<T, A, B> NewService for AndThenTransform<T, A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Error = A::Error, InitError = A::InitError>,
|
||||
T: NewTransform<B::Service, C, Request = A::Response, 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>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
|
||||
type Config = A::Config;
|
||||
type InitError = T::InitError;
|
||||
type Service = AndThenTransform<T::Transform, A::Service, B::Service>;
|
||||
type Future = AndThenTransformNewServiceFuture<T, A, B, C>;
|
||||
type Service = AndThen<FromErr<A::Service, T::Error>, T::Transform>;
|
||||
type Future = AndThenTransformFuture<T, A, B>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
AndThenTransformNewServiceFuture {
|
||||
fn new_service(&self, cfg: &A::Config) -> Self::Future {
|
||||
AndThenTransformFuture {
|
||||
a: None,
|
||||
b: None,
|
||||
t: None,
|
||||
t_cell: self.t.clone(),
|
||||
fut_a: self.a.new_service(cfg),
|
||||
fut_b: self.b.new_service(cfg),
|
||||
fut_t: self.t.new_transform(cfg),
|
||||
fut_t: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenTransformNewServiceFuture<T, A, B, C>
|
||||
pub struct AndThenTransformFuture<T, A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Error = A::Error, InitError = A::InitError>,
|
||||
T: NewTransform<B::Service, C, Request = A::Response, 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>,
|
||||
{
|
||||
fut_b: B::Future,
|
||||
fut_a: A::Future,
|
||||
fut_t: T::Future,
|
||||
fut_b: B::Future,
|
||||
fut_t: Option<T::Future>,
|
||||
a: Option<A::Service>,
|
||||
b: Option<B::Service>,
|
||||
t: Option<T::Transform>,
|
||||
t_cell: Rc<T>,
|
||||
}
|
||||
|
||||
impl<T, A, B, C> Future for AndThenTransformNewServiceFuture<T, A, B, C>
|
||||
impl<T, A, B> Future for AndThenTransformFuture<T, A, B>
|
||||
where
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Error = A::Error, InitError = A::InitError>,
|
||||
T: NewTransform<B::Service, C, Request = A::Response, 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>,
|
||||
{
|
||||
type Item = AndThenTransform<T::Transform, A::Service, B::Service>;
|
||||
type Item = AndThen<FromErr<A::Service, T::Error>, T::Transform>;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if self.t.is_none() {
|
||||
if let Async::Ready(transform) = self.fut_t.poll()? {
|
||||
self.t = Some(transform);
|
||||
if self.fut_t.is_none() {
|
||||
if let Async::Ready(service) = self.fut_b.poll()? {
|
||||
self.fut_t = Some(self.t_cell.new_transform(service));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,18 +110,17 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
if self.b.is_none() {
|
||||
if let Async::Ready(service) = self.fut_b.poll()? {
|
||||
self.b = Some(service);
|
||||
if let Some(ref mut fut) = self.fut_t {
|
||||
if let Async::Ready(transform) = fut.poll()? {
|
||||
self.t = Some(transform);
|
||||
}
|
||||
}
|
||||
|
||||
if self.a.is_some() && self.b.is_some() && self.t.is_some() {
|
||||
Ok(Async::Ready(AndThenTransform {
|
||||
a: self.a.take().unwrap(),
|
||||
t: Cell::new(self.t.take().unwrap()),
|
||||
b: Cell::new(self.b.take().unwrap()),
|
||||
}))
|
||||
if self.a.is_some() && self.t.is_some() {
|
||||
Ok(Async::Ready(AndThen::new(
|
||||
FromErr::new(self.a.take().unwrap()),
|
||||
self.t.take().unwrap(),
|
||||
)))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
@@ -276,10 +155,11 @@ mod tests {
|
||||
fn test_apply() {
|
||||
let blank = |req| Ok(req);
|
||||
|
||||
let mut srv = blank.into_service().apply(
|
||||
|req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)),
|
||||
Srv,
|
||||
);
|
||||
let mut srv = blank
|
||||
.into_service()
|
||||
.apply_fn(Srv, |req: &'static str, srv: &mut Srv| {
|
||||
srv.call(()).map(move |res| (req, res))
|
||||
});
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
let res = srv.call("srv").poll();
|
||||
assert!(res.is_ok());
|
||||
|
@@ -1,6 +1,6 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||
use futures::{Async, Future, IntoFuture, Poll};
|
||||
|
||||
use super::{IntoNewService, IntoService, NewService, Service};
|
||||
use crate::cell::Cell;
|
||||
@@ -71,8 +71,12 @@ where
|
||||
type Future = AndThenApplyFuture<A, B, F, Out>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
try_ready!(self.a.poll_ready());
|
||||
self.b.get_mut().poll_ready()
|
||||
let not_ready = self.a.poll_ready()?.is_not_ready();
|
||||
if self.b.get_mut().poll_ready()?.is_not_ready() || not_ready {
|
||||
Ok(Async::NotReady)
|
||||
} else {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||
@@ -129,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(),
|
||||
@@ -159,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,
|
||||
@@ -174,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>,
|
||||
@@ -186,25 +186,25 @@ 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,
|
||||
f: self.f.clone(),
|
||||
fut_a: self.a.new_service(cfg),
|
||||
fut_b: self.b.new_service(cfg),
|
||||
fut_a: self.a.new_service(cfg).into_future(),
|
||||
fut_b: self.b.new_service(cfg).into_future(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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>,
|
||||
@@ -216,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>,
|
||||
|
@@ -1,218 +1,198 @@
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use super::{FnNewTransform, FnTransform};
|
||||
use super::{
|
||||
IntoNewService, IntoNewTransform, IntoService, IntoTransform, NewService, NewTransform,
|
||||
Service, Transform,
|
||||
};
|
||||
use futures::{Async, Future, IntoFuture, Poll};
|
||||
|
||||
/// `Apply` service combinator
|
||||
pub struct Apply<T, S>
|
||||
use super::{IntoNewService, IntoService, NewService, Service};
|
||||
|
||||
/// Apply tranform function to a service
|
||||
pub fn apply_fn<T, F, In, Out, U>(service: U, f: F) -> Apply<T, F, In, Out>
|
||||
where
|
||||
T: Transform<S>,
|
||||
T::Error: From<S::Error>,
|
||||
S: Service,
|
||||
{
|
||||
transform: T,
|
||||
service: S,
|
||||
}
|
||||
|
||||
impl<T, S> Apply<T, S>
|
||||
where
|
||||
T: Transform<S>,
|
||||
T::Error: From<S::Error>,
|
||||
S: Service,
|
||||
{
|
||||
/// Create new `Apply` combinator
|
||||
pub fn new<T1: IntoTransform<T, S>, S1: IntoService<S>>(
|
||||
transform: T1,
|
||||
service: S1,
|
||||
) -> Self {
|
||||
Self {
|
||||
transform: transform.into_transform(),
|
||||
service: service.into_service(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Out> Apply<FnTransform<F, S, Req, Out>, S>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Out,
|
||||
T: Service,
|
||||
F: FnMut(In, &mut T) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<S::Error>,
|
||||
S: Service,
|
||||
Out::Error: From<T::Error>,
|
||||
U: IntoService<T>,
|
||||
{
|
||||
Apply::new(service.into_service(), f)
|
||||
}
|
||||
|
||||
/// 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,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
U: IntoNewService<T>,
|
||||
{
|
||||
ApplyNewService::new(service.into_new_service(), f)
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
/// `Apply` service combinator
|
||||
pub struct Apply<T, F, In, Out>
|
||||
where
|
||||
T: Service,
|
||||
{
|
||||
service: T,
|
||||
f: F,
|
||||
r: PhantomData<(In, Out)>,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out> Apply<T, F, In, Out>
|
||||
where
|
||||
T: Service,
|
||||
F: FnMut(In, &mut T) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
/// Create new `Apply` combinator
|
||||
pub fn new_fn<S1: IntoService<S>>(service: S1, transform: F) -> Self {
|
||||
pub(crate) fn new<I: IntoService<T>>(service: I, f: F) -> Self {
|
||||
Self {
|
||||
service: service.into_service(),
|
||||
transform: transform.into_transform(),
|
||||
f,
|
||||
r: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> Clone for Apply<T, S>
|
||||
impl<T, F, In, Out> Clone for Apply<T, F, In, Out>
|
||||
where
|
||||
S: Service + Clone,
|
||||
T::Error: From<S::Error>,
|
||||
T: Transform<S> + Clone,
|
||||
T: Service + Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Apply {
|
||||
service: self.service.clone(),
|
||||
transform: self.transform.clone(),
|
||||
f: self.f.clone(),
|
||||
r: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> Service for Apply<T, S>
|
||||
impl<T, F, In, Out> Service for Apply<T, F, In, Out>
|
||||
where
|
||||
T: Transform<S>,
|
||||
T::Error: From<S::Error>,
|
||||
S: Service,
|
||||
T: Service,
|
||||
F: FnMut(In, &mut T) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = T::Future;
|
||||
type Request = In;
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
type Future = Out::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
try_ready!(self.service.poll_ready());
|
||||
self.transform.poll_ready()
|
||||
self.service.poll_ready().map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
self.transform.call(req, &mut self.service).into_future()
|
||||
fn call(&mut self, req: In) -> Self::Future {
|
||||
(self.f)(req, &mut self.service).into_future()
|
||||
}
|
||||
}
|
||||
|
||||
/// `ApplyNewService` new service combinator
|
||||
pub struct ApplyNewService<T, S, C>
|
||||
pub struct ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError>,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C>,
|
||||
T: NewService,
|
||||
{
|
||||
transform: T,
|
||||
service: S,
|
||||
_t: std::marker::PhantomData<C>,
|
||||
service: T,
|
||||
f: F,
|
||||
r: PhantomData<(In, Out)>,
|
||||
}
|
||||
|
||||
impl<T, S, C> ApplyNewService<T, S, C>
|
||||
impl<T, F, In, Out> ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError>,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C>,
|
||||
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<T1: IntoNewTransform<T, S::Service, C>, S1: IntoNewService<S, C>>(
|
||||
transform: T1,
|
||||
service: S1,
|
||||
) -> Self {
|
||||
pub(crate) fn new<F1: IntoNewService<T>>(service: F1, f: F) -> Self {
|
||||
Self {
|
||||
transform: transform.into_new_transform(),
|
||||
f,
|
||||
service: service.into_new_service(),
|
||||
_t: std::marker::PhantomData,
|
||||
r: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, In, Out, Cfg>
|
||||
ApplyNewService<FnNewTransform<F, S::Service, In, Out, S::InitError, Cfg>, S, Cfg>
|
||||
impl<T, F, In, Out> Clone for ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
F: FnMut(In, &mut S::Service) -> Out + Clone,
|
||||
T: NewService + Clone,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<S::Error>,
|
||||
S: NewService<Cfg>,
|
||||
{
|
||||
/// Create new `Apply` combinator factory
|
||||
pub fn new_fn<S1: IntoNewService<S, Cfg>>(service: S1, transform: F) -> Self {
|
||||
Self {
|
||||
service: service.into_new_service(),
|
||||
transform: FnNewTransform::new(transform),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C> Clone for ApplyNewService<T, S, C>
|
||||
where
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError> + Clone,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C> + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
service: self.service.clone(),
|
||||
transform: self.transform.clone(),
|
||||
_t: std::marker::PhantomData,
|
||||
f: self.f.clone(),
|
||||
r: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C> NewService<C> for ApplyNewService<T, S, C>
|
||||
impl<T, F, In, Out> NewService for ApplyNewService<T, F, In, Out>
|
||||
where
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError>,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Service = Apply<T::Transform, S::Service>;
|
||||
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, S, C>;
|
||||
type Future = ApplyNewServiceFuture<T, F, In, Out>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> 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>
|
||||
where
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fut: T::Future,
|
||||
f: Option<F>,
|
||||
r: PhantomData<(In, Out)>,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out> ApplyNewServiceFuture<T, F, In, Out>
|
||||
where
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
ApplyNewServiceFuture {
|
||||
fut_t: self.transform.new_transform(cfg),
|
||||
fut_s: self.service.new_service(cfg),
|
||||
service: None,
|
||||
transform: None,
|
||||
f: Some(f),
|
||||
fut,
|
||||
r: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ApplyNewServiceFuture<T, S, C>
|
||||
impl<T, F, In, Out> Future for ApplyNewServiceFuture<T, F, In, Out>
|
||||
where
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError>,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C>,
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
fut_s: S::Future,
|
||||
fut_t: T::Future,
|
||||
service: Option<S::Service>,
|
||||
transform: Option<T::Transform>,
|
||||
}
|
||||
|
||||
impl<T, S, C> Future for ApplyNewServiceFuture<T, S, C>
|
||||
where
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError>,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C>,
|
||||
{
|
||||
type Item = Apply<T::Transform, S::Service>;
|
||||
type Item = Apply<T::Service, F, In, Out>;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if self.transform.is_none() {
|
||||
if let Async::Ready(transform) = self.fut_t.poll()? {
|
||||
self.transform = Some(transform);
|
||||
}
|
||||
}
|
||||
|
||||
if self.service.is_none() {
|
||||
if let Async::Ready(service) = self.fut_s.poll()? {
|
||||
self.service = Some(service);
|
||||
}
|
||||
}
|
||||
|
||||
if self.transform.is_some() && self.service.is_some() {
|
||||
Ok(Async::Ready(Apply {
|
||||
service: self.service.take().unwrap(),
|
||||
transform: self.transform.take().unwrap(),
|
||||
}))
|
||||
if let Async::Ready(service) = self.fut.poll()? {
|
||||
Ok(Async::Ready(Apply::new(service, self.f.take().unwrap())))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
@@ -225,7 +205,7 @@ mod tests {
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::*;
|
||||
use crate::{NewService, Service};
|
||||
use crate::{IntoService, NewService, Service, ServiceExt};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Srv;
|
||||
@@ -245,10 +225,14 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_apply() {
|
||||
let mut srv = Apply::new_fn(Srv, |req: &'static str, srv| {
|
||||
srv.call(()).map(move |res| (req, res))
|
||||
});
|
||||
fn test_call() {
|
||||
let blank = |req| Ok(req);
|
||||
|
||||
let mut srv = blank
|
||||
.into_service()
|
||||
.apply_fn(Srv, |req: &'static str, srv| {
|
||||
srv.call(()).map(move |res| (req, res))
|
||||
});
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
let res = srv.call("srv").poll();
|
||||
assert!(res.is_ok());
|
||||
@@ -258,22 +242,6 @@ mod tests {
|
||||
#[test]
|
||||
fn test_new_service() {
|
||||
let new_srv = ApplyNewService::new(
|
||||
|req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)),
|
||||
|| Ok::<_, ()>(Srv),
|
||||
);
|
||||
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
let res = srv.call("srv").poll();
|
||||
assert!(res.is_ok());
|
||||
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_service_fn() {
|
||||
let new_srv = ApplyNewService::new_fn(
|
||||
|| Ok::<_, ()>(Srv),
|
||||
|req: &'static str, srv| srv.call(()).map(move |res| (req, res)),
|
||||
);
|
||||
|
266
actix-service/src/apply_cfg.rs
Normal file
266
actix-service/src/apply_cfg.rs
Normal file
@@ -0,0 +1,266 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::future::Future;
|
||||
use futures::{try_ready, Async, IntoFuture, Poll};
|
||||
|
||||
use crate::cell::Cell;
|
||||
use crate::{IntoService, NewService, Service};
|
||||
|
||||
/// Convert `Fn(&Config, &mut Service) -> Future<Service>` fn to a NewService
|
||||
pub fn 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 = R::Error,
|
||||
> + Clone
|
||||
where
|
||||
F: FnMut(&C, &mut T) -> R,
|
||||
T: Service,
|
||||
R: IntoFuture,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
ApplyConfigService {
|
||||
f: Cell::new(f),
|
||||
srv: Cell::new(srv.into_service()),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
T::InitError: From<T::Error>,
|
||||
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 {
|
||||
ApplyConfigService {
|
||||
f: self.f.clone(),
|
||||
srv: self.srv.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, T, R, S> NewService for ApplyConfigService<F, C, T, R, S>
|
||||
where
|
||||
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;
|
||||
|
||||
type InitError = R::Error;
|
||||
type Future = FnNewServiceConfigFut<R, S>;
|
||||
|
||||
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 = ()>,
|
||||
T::InitError: From<T::Error>,
|
||||
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(),
|
||||
fut: None,
|
||||
srv: None,
|
||||
srv_fut: Some(self.srv.get_ref().new_service(&())),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ApplyConfigNewServiceFut<F, C, T, R, S>
|
||||
where
|
||||
C: Clone,
|
||||
F: FnMut(&C, &mut T::Service) -> R,
|
||||
T: NewService<Config = ()>,
|
||||
T::InitError: From<T::Error>,
|
||||
R: IntoFuture<Error = T::InitError>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
cfg: C,
|
||||
f: Cell<F>,
|
||||
srv: Option<T::Service>,
|
||||
srv_fut: 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 = ()>,
|
||||
T::InitError: From<T::Error>,
|
||||
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_fut {
|
||||
match fut.poll()? {
|
||||
Async::NotReady => return Ok(Async::NotReady),
|
||||
Async::Ready(srv) => {
|
||||
let _ = self.srv_fut.take();
|
||||
self.srv = Some(srv);
|
||||
return self.poll();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref mut fut) = self.fut {
|
||||
Ok(Async::Ready(try_ready!(fut.poll()).into_service()))
|
||||
} else if let Some(ref mut srv) = self.srv {
|
||||
match srv.poll_ready()? {
|
||||
Async::NotReady => Ok(Async::NotReady),
|
||||
Async::Ready(_) => {
|
||||
self.fut = Some(self.f.get_mut()(&self.cfg, srv).into_future());
|
||||
return self.poll();
|
||||
}
|
||||
}
|
||||
} 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, Poll};
|
||||
|
||||
pub type BoxedService<Req, Res, Err> = Box<
|
||||
Service<
|
||||
dyn 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<dyn 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,
|
||||
@@ -40,20 +46,18 @@ where
|
||||
}
|
||||
|
||||
type Inner<C, Req, Res, Err, InitErr> = Box<
|
||||
NewService<
|
||||
C,
|
||||
dyn NewService<
|
||||
Config = C,
|
||||
Request = Req,
|
||||
Response = Res,
|
||||
Error = Err,
|
||||
InitError = InitErr,
|
||||
Service = BoxedService<Req, Res, Err>,
|
||||
Future = Box<Future<Item = BoxedService<Req, Res, Err>, Error = InitErr>>,
|
||||
Future = Box<dyn Future<Item = BoxedService<Req, Res, Err>, Error = InitErr>>,
|
||||
>,
|
||||
>;
|
||||
|
||||
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,26 +68,27 @@ 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>>;
|
||||
type Future = Box<dyn Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
self.0.new_service(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
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,14 +97,16 @@ 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>>;
|
||||
type Future = Box<dyn Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
Box::new(
|
||||
self.service
|
||||
.new_service(cfg)
|
||||
.map(|service| ServiceWrapper::boxed(service)),
|
||||
.into_future()
|
||||
.map(ServiceWrapper::boxed),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -124,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<dyn Future<Item = Self::Response, Error = Self::Error>>,
|
||||
>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.0.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
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,16 @@ 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() }
|
||||
}
|
||||
|
||||
#[allow(clippy::mut_from_ref)]
|
||||
pub(crate) unsafe fn get_mut_unsafe(&self) -> &mut T {
|
||||
&mut *self.inner.as_ref().get()
|
||||
}
|
||||
}
|
||||
|
@@ -1,72 +1,71 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, IntoFuture, Poll};
|
||||
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<Item = S, Error = E>,
|
||||
R: IntoFuture<Error = E>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
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,
|
||||
@@ -85,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,
|
||||
@@ -104,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,
|
||||
@@ -122,58 +131,144 @@ 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 into_service(self) -> ServiceFn<F, Req, Out> {
|
||||
ServiceFn::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
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) -> NewServiceFn<F, Req, Out, Cfg> {
|
||||
NewServiceFn::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
|
||||
pub struct FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Error = E>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(C, R, S, E)>,
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Error = E>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewServiceConfig { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> NewService for FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Error = E>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
|
||||
type Config = C;
|
||||
type Service = S;
|
||||
type InitError = E;
|
||||
type Future = FnNewServiceConfigFut<R, S, E>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
FnNewServiceConfigFut {
|
||||
fut: (self.f)(cfg).into_future(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FnNewServiceConfigFut<R, S, E>
|
||||
where
|
||||
R: IntoFuture<Error = E>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
fut: R::Future,
|
||||
_t: PhantomData<(S,)>,
|
||||
}
|
||||
|
||||
impl<R, S, E> Future for FnNewServiceConfigFut<R, S, E>
|
||||
where
|
||||
R: IntoFuture<Error = E>,
|
||||
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()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> Clone for FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R + Clone,
|
||||
R: IntoFuture<Error = E>,
|
||||
R::Item: IntoService<S>,
|
||||
S: Service,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> IntoNewService<FnNewService<F, Req, Out, Cfg>, 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>
|
||||
pub struct FnNewServiceNoConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<F, R, S, E> FnNewServiceNoConfig<F, R, S, E>
|
||||
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 }
|
||||
FnNewServiceNoConfig { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, S, E> NewService<()> for FnNewServiceNoConfig<F, R, S, E>
|
||||
impl<F, C, R, S, E> NewService for FnNewServiceNoConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
@@ -183,16 +278,16 @@ where
|
||||
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, _: &()) -> Self::Future {
|
||||
fn new_service(&self, _: &C) -> Self::Future {
|
||||
(self.f)().into_future()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, S, E> Clone for FnNewServiceNoConfig<F, R, S, E>
|
||||
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>,
|
||||
@@ -203,76 +298,13 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, S, E> IntoNewService<FnNewServiceNoConfig<F, R, S, E>, ()> for F
|
||||
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, R, S, E> {
|
||||
fn into_new_service(self) -> FnNewServiceNoConfig<F, C, R, S, E> {
|
||||
FnNewServiceNoConfig::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
|
||||
pub struct FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(C, R, S, E)>,
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewServiceConfig { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> NewService<C> for FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> 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, cfg: &C) -> Self::Future {
|
||||
(self.f)(cfg).into_future()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> Clone for FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> 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> IntoConfigurableNewService<FnNewServiceConfig<F, C, R, S, E>, C> for F
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewServiceConfig<F, C, R, S, E> {
|
||||
FnNewServiceConfig::new(self)
|
||||
}
|
||||
}
|
||||
|
@@ -1,122 +1,78 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, IntoFuture, Poll};
|
||||
use futures::IntoFuture;
|
||||
|
||||
use crate::{IntoNewTransform, IntoTransform, NewTransform, Transform};
|
||||
use crate::apply::Apply;
|
||||
use crate::{IntoTransform, Service, Transform};
|
||||
|
||||
pub struct FnTransform<F, S, Req, Res>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
/// Use function as transform service
|
||||
pub fn transform_fn<F, S, In, Out, Err>(
|
||||
f: F,
|
||||
_t: PhantomData<(S, Req, Res)>,
|
||||
) -> impl Transform<S, Request = In, Response = Out::Item, Error = Out::Error, InitError = Err>
|
||||
where
|
||||
S: Service,
|
||||
F: FnMut(In, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<S::Error>,
|
||||
{
|
||||
FnTransform::new(f)
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res> FnTransform<F, S, Req, Res>
|
||||
pub struct FnTransform<F, S, In, Out, Err>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res,
|
||||
Res: IntoFuture,
|
||||
F: FnMut(In, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(S, In, Out, Err)>,
|
||||
}
|
||||
|
||||
impl<F, S, In, Out, Err> FnTransform<F, S, In, Out, Err>
|
||||
where
|
||||
F: FnMut(In, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnTransform { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res> Clone for FnTransform<F, S, Req, Res>
|
||||
impl<F, S, In, Out, Err> Transform<S> for FnTransform<F, S, In, Out, Err>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res + Clone,
|
||||
Res: IntoFuture,
|
||||
S: Service,
|
||||
F: FnMut(In, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<S::Error>,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
FnTransform {
|
||||
f: self.f.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
type Request = In;
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
type Transform = Apply<S, F, In, Out>;
|
||||
type InitError = Err;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ok(Apply::new(service, self.f.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res> Transform<S> for FnTransform<F, S, Req, Res>
|
||||
impl<F, S, In, Out, Err> IntoTransform<FnTransform<F, S, In, Out, Err>, S> for F
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res,
|
||||
Res: IntoFuture,
|
||||
S: Service,
|
||||
F: FnMut(In, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<S::Error>,
|
||||
{
|
||||
type Request = Req;
|
||||
type Response = Res::Item;
|
||||
type Error = Res::Error;
|
||||
type Future = Res::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Req, service: &mut S) -> Self::Future {
|
||||
(self.f)(request, service).into_future()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res> IntoTransform<FnTransform<F, S, Req, Res>, S> for F
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
fn into_transform(self) -> FnTransform<F, S, Req, Res> {
|
||||
fn into_transform(self) -> FnTransform<F, S, In, Out, Err> {
|
||||
FnTransform::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FnNewTransform<F, S, Req, Out, Err, Cfg>
|
||||
impl<F, S, In, Out, Err> Clone for FnTransform<F, S, In, Out, Err>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Out + Clone,
|
||||
F: FnMut(In, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(S, Req, Out, Err, Cfg)>,
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res, Err, Cfg> FnNewTransform<F, S, Req, Res, Err, Cfg>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res + Clone,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewTransform { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res, Err, Cfg> NewTransform<S, Cfg> for FnNewTransform<F, S, Req, Res, Err, Cfg>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res + Clone,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
type Request = Req;
|
||||
type Response = Res::Item;
|
||||
type Error = Res::Error;
|
||||
type Transform = FnTransform<F, S, Req, Res>;
|
||||
type InitError = Err;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn new_transform(&self, _: &Cfg) -> Self::Future {
|
||||
ok(FnTransform::new(self.f.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res, Err, Cfg>
|
||||
IntoNewTransform<FnNewTransform<F, S, Req, Res, Err, Cfg>, S, Cfg> for F
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res + Clone,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
fn into_new_transform(self) -> FnNewTransform<F, S, Req, Res, Err, Cfg> {
|
||||
FnNewTransform::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res, Err, Cfg> Clone for FnNewTransform<F, S, Req, Res, Err, Cfg>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res + Clone,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
|
@@ -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,14 +1,14 @@
|
||||
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;
|
||||
mod apply;
|
||||
mod apply_cfg;
|
||||
pub mod blank;
|
||||
pub mod boxed;
|
||||
mod cell;
|
||||
@@ -16,25 +16,28 @@ 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_map_err;
|
||||
mod transform_map_init_err;
|
||||
mod transform_err;
|
||||
|
||||
pub use self::and_then::{AndThen, AndThenNewService};
|
||||
use self::and_then_apply::{AndThenTransform, AndThenTransformNewService};
|
||||
use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService};
|
||||
pub use self::apply::{Apply, ApplyNewService};
|
||||
pub use self::fn_service::{fn_cfg_factory, fn_factory, fn_service, FnService};
|
||||
pub use self::fn_transform::{FnNewTransform, FnTransform};
|
||||
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::{IntoNewTransform, IntoTransform, NewTransform, Transform};
|
||||
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 {
|
||||
@@ -76,20 +79,6 @@ pub trait Service {
|
||||
/// An extension trait for `Service`s that provides a variety of convenient
|
||||
/// adapters
|
||||
pub trait ServiceExt: Service {
|
||||
/// Apply tranformation 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>
|
||||
where
|
||||
Self: Sized,
|
||||
T: Transform<B, Request = Self::Response>,
|
||||
T::Error: From<Self::Error>,
|
||||
T1: IntoTransform<T, B>,
|
||||
B: Service<Error = Self::Error>,
|
||||
B1: IntoService<B>,
|
||||
{
|
||||
AndThenTransform::new(transform.into_transform(), self, service.into_service())
|
||||
}
|
||||
|
||||
/// Apply function to specified service and use it as a next service in
|
||||
/// chain.
|
||||
fn apply_fn<F, B, B1, Out>(self, service: B1, f: F) -> AndThenApply<Self, B, F, Out>
|
||||
@@ -187,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;
|
||||
|
||||
@@ -203,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,
|
||||
@@ -217,41 +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 function to specified service and use it as a next service in
|
||||
/// 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,
|
||||
) -> AndThenTransformNewService<T, Self, B, Config>
|
||||
fn apply<T, T1, B, B1>(self, transform: T1, service: B1) -> AndThenTransform<T, Self, B>
|
||||
where
|
||||
Self: Sized,
|
||||
T: NewTransform<B::Service, Request = Self::Response, InitError = Self::InitError>,
|
||||
T: Transform<B::Service, Request = Self::Response, InitError = Self::InitError>,
|
||||
T::Error: From<Self::Error>,
|
||||
T1: IntoNewTransform<T, B::Service>,
|
||||
B: NewService<Config, Error = Self::Error, InitError = Self::InitError>,
|
||||
B1: IntoNewService<B, Config>,
|
||||
T1: IntoTransform<T, B::Service>,
|
||||
B: NewService<Config = Self::Config, InitError = Self::InitError>,
|
||||
B1: IntoNewService<B>,
|
||||
{
|
||||
AndThenTransformNewService::new(
|
||||
transform.into_new_transform(),
|
||||
self,
|
||||
service.into_new_service(),
|
||||
)
|
||||
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>,
|
||||
@@ -260,12 +240,12 @@ pub trait NewService<Config = ()> {
|
||||
}
|
||||
|
||||
/// 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,
|
||||
@@ -280,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>,
|
||||
@@ -294,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,
|
||||
@@ -310,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,
|
||||
@@ -319,22 +299,39 @@ 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,
|
||||
F: Fn(Self::Error) -> E + Clone,
|
||||
{
|
||||
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
|
||||
@@ -373,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)
|
||||
}
|
||||
}
|
||||
@@ -415,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;
|
||||
@@ -432,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,23 @@ 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,
|
||||
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,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
/// Create new `MapErr` new service instance
|
||||
pub fn new(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService<C>,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
pub fn new(a: A, f: F) -> Self {
|
||||
Self {
|
||||
a,
|
||||
f,
|
||||
@@ -119,10 +123,10 @@ impl<A, F, E, C> MapErrNewService<A, F, E, C> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, C> Clone for MapErrNewService<A, F, E, C>
|
||||
impl<A, F, E> Clone for MapErrNewService<A, F, E>
|
||||
where
|
||||
A: Clone,
|
||||
F: Clone,
|
||||
A: NewService + Clone,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
@@ -133,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 {
|
||||
@@ -170,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,6 +1,4 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{try_ready, Async, Future, Poll};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::{IntoNewService, NewService, Service};
|
||||
use crate::cell::Cell;
|
||||
@@ -48,8 +46,12 @@ where
|
||||
type Future = ThenFuture<A, B>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
try_ready!(self.a.poll_ready());
|
||||
self.b.get_mut().poll_ready()
|
||||
let not_ready = self.a.poll_ready()?.is_not_ready();
|
||||
if self.b.get_mut().poll_ready()?.is_not_ready() || not_ready {
|
||||
Ok(Async::NotReady)
|
||||
} else {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||
@@ -111,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,
|
||||
@@ -151,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,
|
||||
@@ -170,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,
|
||||
@@ -191,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,
|
||||
@@ -211,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,
|
||||
|
@@ -1,56 +1,17 @@
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures::{Future, Poll};
|
||||
use futures::{Async, Future, IntoFuture, Poll};
|
||||
|
||||
use crate::transform_map_err::{TransformMapErr, TransformMapErrNewTransform};
|
||||
use crate::transform_map_init_err::TransformMapInitErr;
|
||||
use crate::Service;
|
||||
use crate::transform_err::{TransformFromErr, TransformMapInitErr};
|
||||
use crate::{IntoNewService, NewService, Service};
|
||||
|
||||
/// An asynchronous function for transforming service call result.
|
||||
pub trait Transform<Service> {
|
||||
/// Requests handled by the service.
|
||||
type Request;
|
||||
|
||||
/// Responses given by the service.
|
||||
type Response;
|
||||
|
||||
/// Errors produced by the service.
|
||||
type Error;
|
||||
|
||||
/// The future response value.
|
||||
type Future: Future<Item = Self::Response, Error = Self::Error>;
|
||||
|
||||
/// Returns `Ready` when the service is able to process requests.
|
||||
///
|
||||
/// This method is similar to `Service::poll_ready` method.
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error>;
|
||||
|
||||
/// Process the request and apply it to provided service,
|
||||
/// return the response asynchronously.
|
||||
fn call(&mut self, request: Self::Request, service: &mut Service) -> Self::Future;
|
||||
|
||||
/// Map this transform's error to a different error, returning a new transform.
|
||||
///
|
||||
/// This function is similar to the `Result::map_err` where it will change
|
||||
/// the error type of the underlying transform. This is useful for example to
|
||||
/// ensure that services and transforms have the same error type.
|
||||
///
|
||||
/// Note that this function consumes the receiving transform and returns a
|
||||
/// wrapped version of it.
|
||||
fn map_err<F, E>(self, f: F) -> TransformMapErr<Self, Service, F, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::Error) -> E,
|
||||
{
|
||||
TransformMapErr::new(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
/// `Transform` service factory
|
||||
///
|
||||
/// `Config` is a service factory configuration type.
|
||||
pub trait NewTransform<Service, Config = ()> {
|
||||
/// 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;
|
||||
|
||||
@@ -61,8 +22,7 @@ pub trait NewTransform<Service, Config = ()> {
|
||||
type Error;
|
||||
|
||||
/// The `TransformService` value created by this factory
|
||||
type Transform: Transform<
|
||||
Service,
|
||||
type Transform: Service<
|
||||
Request = Self::Request,
|
||||
Response = Self::Response,
|
||||
Error = Self::Error,
|
||||
@@ -74,101 +34,79 @@ pub trait NewTransform<Service, Config = ()> {
|
||||
/// The future response value.
|
||||
type Future: Future<Item = Self::Transform, Error = Self::InitError>;
|
||||
|
||||
/// Create and return a new service value asynchronously.
|
||||
fn new_transform(&self, cfg: &Config) -> Self::Future;
|
||||
/// Creates and returns a new Service component, asynchronously
|
||||
fn new_transform(&self, service: S) -> Self::Future;
|
||||
|
||||
/// Map this transforms's output to a different type, returning a new transform
|
||||
/// of the resulting type.
|
||||
fn map_err<F, E>(self, f: F) -> TransformMapErrNewTransform<Self, Service, Config, F, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::Error) -> E,
|
||||
{
|
||||
TransformMapErrNewTransform::new(self, f)
|
||||
}
|
||||
|
||||
/// Map this service's factory init error to a different error,
|
||||
/// Map this service's factory error to a different error,
|
||||
/// returning a new transform service factory.
|
||||
fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, Service, Config, F, E>
|
||||
fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, S, F, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::InitError) -> E,
|
||||
{
|
||||
TransformMapInitErr::new(self, f)
|
||||
}
|
||||
|
||||
/// Map this service's init error to any error implementing `From` for
|
||||
/// this service`s `Error`.
|
||||
///
|
||||
/// Note that this function consumes the receiving transform and returns a
|
||||
/// wrapped version of it.
|
||||
fn from_err<E>(self) -> TransformFromErr<Self, S, E>
|
||||
where
|
||||
Self: Sized,
|
||||
E: From<Self::InitError>,
|
||||
{
|
||||
TransformFromErr::new(self)
|
||||
}
|
||||
|
||||
// /// Map this service's init error to service's init error
|
||||
// /// if it is implementing `Into` to this service`s `InitError`.
|
||||
// ///
|
||||
// /// Note that this function consumes the receiving transform and returns a
|
||||
// /// wrapped version of it.
|
||||
// fn into_err<E>(self) -> TransformIntoErr<Self, S>
|
||||
// where
|
||||
// Self: Sized,
|
||||
// Self::InitError: From<Self::InitError>,
|
||||
// {
|
||||
// TransformFromErr::new(self)
|
||||
// }
|
||||
}
|
||||
|
||||
impl<'a, T, S> Transform<S> for &'a mut T
|
||||
impl<T, S> Transform<S> for Rc<T>
|
||||
where
|
||||
T: Transform<S> + 'a,
|
||||
S: Service<Error = T::Error>,
|
||||
T: Transform<S>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = T::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), T::Error> {
|
||||
(**self).poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Self::Request, service: &mut S) -> T::Future {
|
||||
(**self).call(request, service)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> Transform<S> for Box<T>
|
||||
where
|
||||
T: Transform<S> + ?Sized,
|
||||
S: Service<Error = T::Error>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = T::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), S::Error> {
|
||||
(**self).poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Self::Request, service: &mut S) -> T::Future {
|
||||
(**self).call(request, service)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, C, T> NewTransform<S, C> for Rc<T>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Transform = T::Transform;
|
||||
type InitError = T::InitError;
|
||||
type Transform = T::Transform;
|
||||
type Future = T::Future;
|
||||
|
||||
fn new_transform(&self, cfg: &C) -> T::Future {
|
||||
self.as_ref().new_transform(cfg)
|
||||
fn new_transform(&self, service: S) -> T::Future {
|
||||
self.as_ref().new_transform(service)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, C, T> NewTransform<S, C> for Arc<T>
|
||||
impl<T, S> Transform<S> for Arc<T>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
T: Transform<S>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Transform = T::Transform;
|
||||
type InitError = T::InitError;
|
||||
type Transform = T::Transform;
|
||||
type Future = T::Future;
|
||||
|
||||
fn new_transform(&self, cfg: &C) -> T::Future {
|
||||
self.as_ref().new_transform(cfg)
|
||||
fn new_transform(&self, service: S) -> T::Future {
|
||||
self.as_ref().new_transform(service)
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a `TransformService`
|
||||
/// Trait for types that can be converted to a *transform service*
|
||||
pub trait IntoTransform<T, S>
|
||||
where
|
||||
T: Transform<S>,
|
||||
@@ -177,15 +115,6 @@ where
|
||||
fn into_transform(self) -> T;
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a TransfromNewService
|
||||
pub trait IntoNewTransform<T, S, C = ()>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
{
|
||||
/// Convert to an `TranformNewService`
|
||||
fn into_new_transform(self) -> T;
|
||||
}
|
||||
|
||||
impl<T, S> IntoTransform<T, S> for T
|
||||
where
|
||||
T: Transform<S>,
|
||||
@@ -195,11 +124,109 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C> IntoNewTransform<T, S, C> for T
|
||||
/// 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, F, U>(
|
||||
t: F,
|
||||
service: U,
|
||||
) -> impl NewService<
|
||||
Config = S::Config,
|
||||
Request = T::Request,
|
||||
Response = T::Response,
|
||||
Error = T::Error,
|
||||
Service = T::Transform,
|
||||
InitError = S::InitError,
|
||||
> + Clone
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
F: IntoTransform<T, S::Service>,
|
||||
U: IntoNewService<S>,
|
||||
{
|
||||
fn into_new_transform(self) -> T {
|
||||
self
|
||||
ApplyTransform::new(t.into_transform(), service.into_new_service())
|
||||
}
|
||||
|
||||
/// `Apply` transform to new service
|
||||
pub struct ApplyTransform<T, S> {
|
||||
s: Rc<S>,
|
||||
t: Rc<T>,
|
||||
}
|
||||
|
||||
impl<T, S> ApplyTransform<T, S>
|
||||
where
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
{
|
||||
/// Create new `ApplyTransform` new service instance
|
||||
pub fn new<F: IntoTransform<T, S::Service>>(t: F, service: S) -> Self {
|
||||
Self {
|
||||
s: Rc::new(service),
|
||||
t: Rc::new(t.into_transform()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> Clone for ApplyTransform<T, S> {
|
||||
fn clone(&self) -> Self {
|
||||
ApplyTransform {
|
||||
s: self.s.clone(),
|
||||
t: self.t.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> NewService for ApplyTransform<T, S>
|
||||
where
|
||||
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>;
|
||||
|
||||
fn new_service(&self, cfg: &S::Config) -> Self::Future {
|
||||
ApplyTransformFuture {
|
||||
t_cell: self.t.clone(),
|
||||
fut_a: self.s.new_service(cfg).into_future(),
|
||||
fut_t: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ApplyTransformFuture<T, S>
|
||||
where
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
{
|
||||
fut_a: S::Future,
|
||||
fut_t: Option<<T::Future as IntoFuture>::Future>,
|
||||
t_cell: Rc<T>,
|
||||
}
|
||||
|
||||
impl<T, S> Future for ApplyTransformFuture<T, S>
|
||||
where
|
||||
S: NewService,
|
||||
T: Transform<S::Service, InitError = S::InitError>,
|
||||
{
|
||||
type Item = T::Transform;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if self.fut_t.is_none() {
|
||||
if let Async::Ready(service) = self.fut_a.poll()? {
|
||||
self.fut_t = Some(self.t_cell.new_transform(service).into_future());
|
||||
}
|
||||
}
|
||||
if let Some(ref mut fut) = self.fut_t {
|
||||
fut.poll()
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
162
actix-service/src/transform_err.rs
Normal file
162
actix-service/src/transform_err.rs
Normal file
@@ -0,0 +1,162 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{Future, Poll};
|
||||
|
||||
use super::Transform;
|
||||
|
||||
/// Transform for the `map_err` combinator, changing the type of a new
|
||||
/// transform's init error.
|
||||
///
|
||||
/// This is created by the `Transform::map_err` method.
|
||||
pub struct TransformMapInitErr<T, S, F, E> {
|
||||
t: T,
|
||||
f: F,
|
||||
e: PhantomData<(S, E)>,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapInitErr<T, S, F, E> {
|
||||
/// Create new `TransformMapErr` new transform instance
|
||||
pub fn new(t: T, f: F) -> Self
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::InitError) -> E,
|
||||
{
|
||||
Self {
|
||||
t,
|
||||
f,
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Clone for TransformMapInitErr<T, S, F, E>
|
||||
where
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
t: self.t.clone(),
|
||||
f: self.f.clone(),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Transform<S> for TransformMapInitErr<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::InitError) -> E + Clone,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Transform = T::Transform;
|
||||
|
||||
type InitError = E;
|
||||
type Future = TransformMapInitErrFuture<T, S, F, E>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
TransformMapInitErrFuture {
|
||||
fut: self.t.new_transform(service),
|
||||
f: self.f.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformMapInitErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::InitError) -> E,
|
||||
{
|
||||
fut: T::Future,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Future for TransformMapInitErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::InitError) -> E + Clone,
|
||||
{
|
||||
type Item = T::Transform;
|
||||
type Error = E;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
self.fut.poll().map_err(&self.f)
|
||||
}
|
||||
}
|
||||
|
||||
/// Transform for the `from_err` combinator, changing the type of a new
|
||||
/// transform's init error.
|
||||
///
|
||||
/// This is created by the `Transform::from_err` method.
|
||||
pub struct TransformFromErr<T, S, E> {
|
||||
t: T,
|
||||
e: PhantomData<(S, E)>,
|
||||
}
|
||||
|
||||
impl<T, S, E> TransformFromErr<T, S, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
E: From<T::InitError>,
|
||||
{
|
||||
/// Create new `TransformFromErr` new transform instance
|
||||
pub fn new(t: T) -> Self {
|
||||
Self { t, e: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, E> Clone for TransformFromErr<T, S, E>
|
||||
where
|
||||
T: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
t: self.t.clone(),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, E> Transform<S> for TransformFromErr<T, S, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
E: From<T::InitError>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Transform = T::Transform;
|
||||
|
||||
type InitError = E;
|
||||
type Future = TransformFromErrFuture<T, S, E>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
TransformFromErrFuture {
|
||||
fut: self.t.new_transform(service),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformFromErrFuture<T, S, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
E: From<T::InitError>,
|
||||
{
|
||||
fut: T::Future,
|
||||
_t: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<T, S, E> Future for TransformFromErrFuture<T, S, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
E: From<T::InitError>,
|
||||
{
|
||||
type Item = T::Transform;
|
||||
type Error = E;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
self.fut.poll().map_err(E::from)
|
||||
}
|
||||
}
|
@@ -1,188 +0,0 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::{NewTransform, Transform};
|
||||
|
||||
/// Service for the `map_err` combinator, changing the type of a transform's
|
||||
/// error.
|
||||
///
|
||||
/// This is created by the `Transform::map_err` method.
|
||||
pub struct TransformMapErr<T, S, F, E> {
|
||||
transform: T,
|
||||
f: F,
|
||||
_t: PhantomData<(S, E)>,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErr<T, S, F, E> {
|
||||
/// Create new `MapErr` combinator
|
||||
pub fn new(transform: T, f: F) -> Self
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
Self {
|
||||
transform,
|
||||
f,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Clone for TransformMapErr<T, S, F, E>
|
||||
where
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
TransformMapErr {
|
||||
transform: self.transform.clone(),
|
||||
f: self.f.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Transform<S> for TransformMapErr<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = E;
|
||||
type Future = TransformMapErrFuture<T, S, F, E>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.transform.poll_ready().map_err(&self.f)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T::Request, service: &mut S) -> Self::Future {
|
||||
TransformMapErrFuture::new(self.transform.call(req, service), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
f: F,
|
||||
fut: T::Future,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
TransformMapErrFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Future for TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
type Item = T::Response;
|
||||
type Error = E;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
self.fut.poll().map_err(&self.f)
|
||||
}
|
||||
}
|
||||
|
||||
/// NewTransform for the `map_err` combinator, changing the type of a new
|
||||
/// transform's error.
|
||||
///
|
||||
/// This is created by the `NewTransform::map_err` method.
|
||||
pub struct TransformMapErrNewTransform<T, S, C, F, E> {
|
||||
t: T,
|
||||
f: F,
|
||||
e: PhantomData<(S, C, E)>,
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> TransformMapErrNewTransform<T, S, C, F, E> {
|
||||
/// Create new `MapErr` new service instance
|
||||
pub fn new(t: T, f: F) -> Self
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
Self {
|
||||
t,
|
||||
f,
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> Clone for TransformMapErrNewTransform<T, S, C, F, E>
|
||||
where
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
t: self.t.clone(),
|
||||
f: self.f.clone(),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> NewTransform<S, C> for TransformMapErrNewTransform<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = E;
|
||||
type Transform = TransformMapErr<T::Transform, S, F, E>;
|
||||
|
||||
type InitError = T::InitError;
|
||||
type Future = TransformMapErrNewTransformFuture<T, S, C, F, E>;
|
||||
|
||||
fn new_transform(&self, cfg: &C) -> Self::Future {
|
||||
TransformMapErrNewTransformFuture::new(self.t.new_transform(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformMapErrNewTransformFuture<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fut: T::Future,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> TransformMapErrNewTransformFuture<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
TransformMapErrNewTransformFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> Future for TransformMapErrNewTransformFuture<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Item = TransformMapErr<T::Transform, S, F, E>;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Async::Ready(tr) = self.fut.poll()? {
|
||||
Ok(Async::Ready(TransformMapErr::new(tr, self.f.clone())))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user