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

Compare commits

..

102 Commits

Author SHA1 Message Date
Nikolay Kim
a76fcaf4d8 prepare actix-utils release 2019-05-12 08:00:23 -07:00
Nikolay Kim
a2134035d6 prepare actix-service release 2019-05-12 07:53:26 -07:00
Nikolay Kim
5f8599faf1 merge master 2019-05-12 06:06:45 -07:00
Nikolay Kim
f0776fca94 Use associated type for NewService config 2019-05-12 06:03:50 -07:00
Nikolay Kim
49ade171f6 Update CHANGES.md 2019-05-01 23:20:00 -07:00
Nikolay Kim
0a2a520c35 Merge pull request #16 from boustrophedon/derive_debug
Derive debug for Server and ServerCommand
2019-05-01 23:19:16 -07:00
Harry Stern
b0c37dfc87 Derive debug for Server and ServerCommand 2019-05-02 01:31:04 -04:00
Nikolay Kim
91e28a4312 Merge pull request #15 from neoeinstein/tower-interop
Add compatibility layer for tower-service
2019-04-29 10:21:32 -07:00
Marcus Griep
508dce8bf1 Add compatibility crate for tower-service
Introduces a new crate `actix-tower`, which makes it easier to use
services built on the `tower-service` abstraction to be used with
`actix-service`.
2019-04-29 12:39:16 -04:00
Nikolay Kim
8ed1099a2e Merge pull request #14 from Bobo1239/master
Increase compiler recursion limit
2019-04-23 13:04:32 -07:00
Boris-Chengbiao Zhou
83544bd971 Increase compiler recursion limit
Fixes `cargo doc` on Windows. (actix/actix#189)
2019-04-23 22:02:37 +02:00
Nikolay Kim
76c317e0b2 Added support for remainder match 2019-04-22 21:19:22 -07:00
Nikolay Kim
3b314e4c8c Connect::set_addr() 2019-04-19 17:43:52 -07:00
Nikolay Kim
ae27b87641 IoStream trait and impls for TcpStream, SslStream and TlsStream 2019-04-16 08:32:12 -07:00
Nikolay Kim
fc2dcadc7a use stable version of trust-dns-resolver 2019-04-14 20:46:36 -07:00
Nikolay Kim
54f62b5035 prep release 2019-04-12 12:30:55 -07:00
Nikolay Kim
d3208bf7a8 Do not start default resolver immediately for default connector. 2019-04-12 12:28:18 -07:00
Nikolay Kim
21507d3da1 add TestServerRuntime::run_on() method 2019-04-12 12:26:47 -07:00
Nikolay Kim
b9d8a215b4 Start trust-dns default resolver on first use 2019-04-11 09:57:21 -07:00
Nikolay Kim
51c4dfe5cb Allow to reset Path instance; export Quoter type 2019-04-07 22:48:18 -07:00
Nikolay Kim
a60112c71e Poll boxed service call result immediately 2019-04-07 20:48:40 -07:00
Nikolay Kim
bd814d6f80 re-export trust-dns types 2019-04-05 10:36:57 -07:00
Nikolay Kim
a4e0c71baa Merge branch 'master' of github.com:actix/actix-net 2019-04-04 15:41:50 -07:00
Nikolay Kim
b9ea445e70 Log error if dns system config could not be loaded 2019-04-04 15:41:05 -07:00
Nikolay Kim
ba2901269d Merge pull request #11 from Dowwie/master
added docs for trait Service, trait Transform
2019-04-04 11:06:02 -07:00
dowwie
5cbc29306a updated as per comments 2019-04-04 14:02:53 -04:00
Nikolay Kim
810fa869ae remove unneeded static 2019-04-04 10:04:19 -07:00
dowwie
33cd51aabf added docs for trait Service, trait Transform 2019-04-04 11:40:28 -04:00
Nikolay Kim
629ed05f82 Get dynamic segment by name instead of iterator 2019-04-03 21:40:21 -07:00
Nikolay Kim
5e8ae210f7 Rename connect Connector to TcpConnector #10 2019-03-31 19:14:13 -07:00
Nikolay Kim
3add90628f Fix SIGINT force shutdown 2019-03-30 12:09:02 -07:00
Nikolay Kim
02ab804e0b prepare actix-service release 2019-03-29 11:16:40 -07:00
Nikolay Kim
feac0b43d9 add impl Service for Rc<RefCell<S>> 2019-03-29 10:21:17 -07:00
Nikolay Kim
1441355d4f use release 2019-03-28 04:02:39 -07:00
Nikolay Kim
7c5afc09a6 move threadpool to separate crate 2019-03-28 03:56:52 -07:00
Nikolay Kim
16856c7d3f Merge branch 'master' of github.com:actix/actix-net 2019-03-27 17:30:54 -07:00
Nikolay Kim
95d02659d5 Added Framed::map_io() method 2019-03-27 17:30:37 -07:00
Juan Aguilar Santillana
bcbd7e6ddf Fix unnecessary arbiter clone at builder rt 2019-03-23 09:46:08 +03:00
Nikolay Kim
e0d3581239 allow to send messages to framed transport via mpsc channel 2019-03-20 09:44:23 -07:00
Nikolay Kim
ef1bdb2eb2 update travis config 2019-03-17 10:25:24 -07:00
Nikolay Kim
10301ff49d temp tarpaulin fix 2019-03-17 08:53:50 -07:00
Nikolay Kim
27c28d6597 Fix error handling for single address 2019-03-15 11:37:51 -07:00
Nikolay Kim
b290273e81 prepare actix-connect release 2019-03-14 22:39:49 -07:00
Nikolay Kim
720230b852 Merge pull request #8 from Firstyear/2019-03-15-arbiter-docs
Improve Arbiter documentation
2019-03-14 20:58:33 -07:00
Nikolay Kim
44c2639fd6 prepare actix-server release 2019-03-14 20:55:55 -07:00
Nikolay Kim
9a5705d1b6 merge travis branch 2019-03-14 20:53:56 -07:00
Nikolay Kim
7ff923a58f stop tests threads 2019-03-14 20:52:17 -07:00
Nikolay Kim
6659b192d3 travis config 2019-03-14 20:52:13 -07:00
Nikolay Kim
1146d9cf30 fix init order 2019-03-14 20:48:58 -07:00
Nikolay Kim
b7b76c47e5 rename method 2019-03-14 20:23:49 -07:00
Nikolay Kim
d23dc6f6af Allow to run future before server service initialization 2019-03-14 20:09:34 -07:00
William Brown
9b6a955da4 Improve Arbiter documentation 2019-03-15 10:24:27 +10:00
Nikolay Kim
f3aa48309f travis config 2019-03-14 11:55:39 -07:00
Nikolay Kim
c9b86712e5 reinstall tarpaulin 2019-03-14 11:31:32 -07:00
Nikolay Kim
0f74f280f9 impl Address for http::Uri 2019-03-14 11:15:32 -07:00
Nikolay Kim
eb37e15554 use specific version of nightly 2019-03-14 10:43:36 -07:00
Nikolay Kim
ad007b8b42 Merge branch 'master' of github.com:actix/actix-net 2019-03-14 10:28:47 -07:00
Nikolay Kim
7c0d1f2273 update travis config 2019-03-14 10:25:34 -07:00
Nikolay Kim
d82bc7c52b Merge pull request #7 from najamelan/fix/compiler_warnings
Fix compiler warnings.
2019-03-14 07:24:37 -07:00
Nikolay Kim
265229b44b allow to override port 2019-03-13 22:55:01 -07:00
Nikolay Kim
38545dedc7 refactor Connect type and add tests 2019-03-13 22:51:31 -07:00
Nikolay Kim
6ebff22601 simplify name 2019-03-13 16:38:08 -07:00
Nikolay Kim
2c9b91b366 add specific constructors 2019-03-13 15:55:20 -07:00
Nikolay Kim
b483200037 remove generic 2019-03-13 15:52:51 -07:00
Nikolay Kim
a73600fbcd remove generic E 2019-03-13 15:51:21 -07:00
Nikolay Kim
084a28ca07 add Connect::with_request 2019-03-13 15:49:31 -07:00
Nikolay Kim
a7c74c53ea store request in Connect request 2019-03-13 15:37:12 -07:00
Nikolay Kim
3e7d737e73 update travis 2019-03-13 14:39:02 -07:00
Nikolay Kim
87db4bf741 changes 2019-03-13 14:38:33 -07:00
Nikolay Kim
8b0fe6f796 rename crate 2019-03-13 12:41:41 -07:00
Nikolay Kim
52a45fda53 redesign actix-connector 2019-03-13 12:40:11 -07:00
Naja Melan
2c7de7e0fb Fix compiler warnings.
Compiles in stable and nightly
2019-03-13 08:41:26 +01:00
Nikolay Kim
1fcc0734b5 prep release 2019-03-12 17:01:02 -07:00
Nikolay Kim
b6f952b036 remove constraint 2019-03-12 16:49:57 -07:00
Nikolay Kim
0fdac38307 add constraint 2019-03-12 16:48:29 -07:00
Nikolay Kim
a3c4637372 prepare actix-server release 2019-03-12 16:40:22 -07:00
Nikolay Kim
ae9bc5ae78 refactor ApplyConfig combinator 2019-03-12 16:32:10 -07:00
Nikolay Kim
21c289d7e4 fix InOrderService::poll_ready() nested service rediness check 2019-03-12 16:03:05 -07:00
Nikolay Kim
5e6eed905c fix InFlightService::poll_ready() nested service rediness check 2019-03-12 15:48:02 -07:00
Nikolay Kim
6801a38de5 check readiness for all services 2019-03-12 15:15:14 -07:00
Nikolay Kim
39356690b0 use ServerConfig for system configuration 2019-03-12 14:14:21 -07:00
Nikolay Kim
f6f292a678 enforce constraint on OpensslAcceptor 2019-03-12 13:57:28 -07:00
Nikolay Kim
b3366bc1af service response is not important 2019-03-12 13:55:31 -07:00
Nikolay Kim
2c1f8f0b96 enforce constraints on AndThenNewService type 2019-03-12 13:50:14 -07:00
Nikolay Kim
e7465bfa2e fix map_err constraints 2019-03-12 13:45:05 -07:00
Nikolay Kim
755d4958c5 use IntoService types for transform services 2019-03-12 13:39:04 -07:00
Nikolay Kim
825117fd4c add Deref/DerefMut impls for Io 2019-03-12 13:12:22 -07:00
Nikolay Kim
7033b50fed add Io::set method for overriding param 2019-03-12 12:53:43 -07:00
Nikolay Kim
ef9bfb8981 add helpers 2019-03-12 12:53:08 -07:00
Nikolay Kim
bef199f831 add blocking mod support 2019-03-11 22:54:27 -07:00
Nikolay Kim
f1d4bcef4b add Arbiter::exec_fn and exec functions 2019-03-11 22:51:17 -07:00
Nikolay Kim
8e13ba7bce update readme 2019-03-11 18:24:31 -07:00
Nikolay Kim
9a9b3e9ca9 update server tests 2019-03-11 15:19:28 -07:00
Nikolay Kim
5567fb41d2 add default type parameter 2019-03-11 13:48:55 -07:00
Nikolay Kim
ad50595ece add PartialEq impl for Io 2019-03-11 13:37:30 -07:00
Nikolay Kim
2430c7247b update timing for travis 2019-03-11 12:53:16 -07:00
Nikolay Kim
1bf0f1e1a5 add Debug impl for Io; update examples 2019-03-11 12:46:12 -07:00
Nikolay Kim
9887aef6e8 add delay to test 2019-03-11 12:35:57 -07:00
Nikolay Kim
787255d030 add io parameters 2019-03-11 12:01:55 -07:00
Nikolay Kim
f696914038 prepare router release 2019-03-09 14:38:08 -08:00
Nikolay Kim
3618f542fb prepare release actix-utils 2019-03-09 14:30:37 -08:00
Nikolay Kim
1f54ae9051 update deps 2019-03-09 14:23:08 -08:00
93 changed files with 3585 additions and 2164 deletions

View File

@@ -10,9 +10,9 @@ matrix:
include:
- rust: stable
- rust: beta
- rust: nightly
- rust: nightly-2019-03-02
allow_failures:
- rust: nightly
- rust: nightly-2019-03-02
env:
global:
@@ -24,34 +24,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-03-02" ]]; then
RUSTFLAGS="--cfg procmacro2_semver_exempt" cargo install 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-03-02" ]]; 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-03-02" ]]; 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

View File

@@ -16,18 +16,20 @@ 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-utils",
"router",
]
[dev-dependencies]
actix-service = { path="actix-service" }
actix-service = "0.3.3"
actix-codec = "0.1.1"
actix-rt = "0.2.0"
actix-server = { path="actix-server", features=["ssl"] }

View File

@@ -1,20 +1,18 @@
# Actix net [![Build Status](https://travis-ci.org/actix/actix-net.svg?branch=master)](https://travis-ci.org/actix/actix-net) [![codecov](https://codecov.io/gh/actix/actix-net/branch/master/graph/badge.svg)](https://codecov.io/gh/actix/actix-net) [![crates.io](https://meritbadge.herokuapp.com/actix-net)](https://crates.io/crates/actix-net) [![Join the chat at https://gitter.im/actix/actix](https://badges.gitter.im/actix/actix.svg)](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.32 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()
}
```

View File

@@ -1,6 +1,11 @@
# Changes
## [0.1.0] - 2019-03-06
## [0.1.2] - 2019-03-27
* Added `Framed::map_io()` method.
## [0.1.1] - 2019-03-06
* Added `FramedParts::with_read_buffer()` method.

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-codec"
version = "0.1.1"
version = "0.1.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Utilities for encoding and decoding frames"
keywords = ["network", "framework", "async", "futures"]
@@ -11,15 +11,15 @@ categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = "../"
workspace = ".."
[lib]
name = "actix_codec"
path = "src/lib.rs"
[dependencies]
bytes = "0.4"
bytes = "0.4.12"
futures = "0.1.24"
tokio-io = "0.1"
tokio-codec = "0.1"
tokio-io = "0.1.12"
tokio-codec = "0.1.1"
log = "0.4"

View File

@@ -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

56
actix-connect/CHANGES.md Normal file
View File

@@ -0,0 +1,56 @@
# Changes
## [0.2.0] - 2019-05-11
### 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

54
actix-connect/Cargo.toml Normal file
View File

@@ -0,0 +1,54 @@
[package]
name = "actix-connect"
version = "0.1.5"
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"]
# support http::Uri as connect address
uri = ["http"]
[dependencies]
actix-service = "0.3.6"
actix-codec = "0.1.2"
actix-utils = "0.3.5"
derive_more = "0.14.0"
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 }
[dev-dependencies]
bytes = "0.4"
actix-test-server = { version="0.2.1", features=["ssl"] }
actix-server-config = "0.1.0"
actix-utils = "0.3.4"
tokio-tcp = "0.1"

View File

@@ -0,0 +1,180 @@
use std::collections::VecDeque;
use std::fmt;
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
}
/// 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)
}
}
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())
}
}
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)
}
}

View File

@@ -0,0 +1,157 @@
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)
}
}
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(TcpConnector(PhantomData))
}
}
/// Tcp connector service
#[derive(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(),
));
}
}
}

View 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),
}

109
actix-connect/src/lib.rs Normal file
View File

@@ -0,0 +1,109 @@
//! 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;
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};
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())
}

View File

@@ -0,0 +1,187 @@
use std::collections::VecDeque;
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,
}
}
}
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(Resolver {
resolver: self.resolver.clone(),
_t: PhantomData,
})
}
}
/// 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 mut req = self.req.take().unwrap();
let mut addrs: VecDeque<_> = ips
.iter()
.map(|ip| SocketAddr::new(ip, req.port()))
.collect();
trace!(
"DNS resolver: host {:?} resolved to {:?}",
req.host(),
addrs
);
if addrs.is_empty() {
Err(ConnectError::NoRecords)
} else if addrs.len() == 1 {
req.addr = Some(either::Either::Left(addrs.pop_front().unwrap()));
Ok(Async::Ready(req))
} else {
req.addr = Some(either::Either::Right(addrs));
Ok(Async::Ready(req))
}
}
}
}
}

View File

@@ -0,0 +1,128 @@
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 openssl::ssl::{HandshakeError, SslConnector};
use tokio_openssl::{ConnectAsync, SslConnectorExt, SslStream};
use crate::{Address, 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: 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),
}
}
}

37
actix-connect/src/uri.rs Normal file
View 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
}
}

View File

@@ -0,0 +1,109 @@
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());
}
#[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());
}

View File

@@ -1,28 +0,0 @@
# Changes
## [0.3.0] - 2019-03-02
### Changed
* Migrate to actix-service 0.3
## [0.2.0] - 2019-02-01
### Changed
* 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

View File

@@ -1,40 +0,0 @@
[package]
name = "actix-connector"
version = "0.3.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.3.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 }

View File

@@ -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))
}
}

View File

@@ -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};

View File

@@ -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),
}
}
}
}

View File

@@ -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),
}
}
}

View File

@@ -1,5 +1,21 @@
# Changes
## [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<()>`

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-rt"
version = "0.2.0"
version = "0.2.2"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix runtime"
keywords = ["network", "framework", "async", "futures"]
@@ -11,15 +11,14 @@ 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"
actix-threadpool = "0.1.0"
futures = "0.1.25"
tokio-current-thread = "0.1"
tokio-executor = "0.1.5"

View File

@@ -4,7 +4,7 @@ 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;
@@ -22,6 +22,7 @@ pub(crate) static COUNT: AtomicUsize = AtomicUsize::new(0);
pub(crate) enum ArbiterCommand {
Stop,
Execute(Box<Future<Item = (), Error = ()> + Send>),
ExecuteFn(Box<FnExec>),
}
impl fmt::Debug for ArbiterCommand {
@@ -29,11 +30,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 {
@@ -54,7 +59,8 @@ impl Arbiter {
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 +68,7 @@ impl Arbiter {
})
}
/// Stop arbiter
/// Stop arbiter from continuing it's event loop.
pub fn stop(&self) {
let _ = self.0.unbounded_send(ArbiterCommand::Stop);
}
@@ -126,7 +132,9 @@ 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,
@@ -140,7 +148,9 @@ impl Arbiter {
});
}
/// 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 +159,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 +168,38 @@ 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 || {
let _ = 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
}
}
struct ArbiterController {
@@ -194,6 +236,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 +302,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,
{
#[cfg_attr(feature = "cargo-clippy", allow(boxed_local))]
fn call_box(self: Box<Self>) {
(*self)()
}
}

View File

@@ -86,8 +86,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);

View File

@@ -10,6 +10,9 @@ pub use self::builder::{Builder, SystemRunner};
pub use self::runtime::Runtime;
pub use self::system::System;
#[doc(hidden)]
pub use actix_threadpool as blocking;
/// Spawns a future on the current arbiter.
///
/// # Panics

View File

@@ -41,7 +41,7 @@ impl Error for RunError {
self.inner.description()
}
fn cause(&self) -> Option<&Error> {
self.inner.cause()
self.inner.source()
}
}

View File

@@ -1,14 +1,18 @@
use std::cell::RefCell;
use std::io;
use std::sync::atomic::{AtomicUsize, Ordering};
use futures::sync::mpsc::UnboundedSender;
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,
@@ -29,6 +33,7 @@ impl System {
sys,
arbiter,
stop_on_panic,
id: SYSTEM_COUNT.fetch_add(1, Ordering::SeqCst),
};
System::set_current(sys.clone());
sys
@@ -82,6 +87,11 @@ impl System {
})
}
/// System id
pub fn id(&self) -> usize {
self.id
}
/// Stop the system
pub fn stop(&self) {
self.stop_with_code(0)

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-server-config"
version = "0.1.0"
version = "0.1.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix server config utils"
homepage = "https://actix.rs"
@@ -13,6 +13,22 @@ workspace = ".."
name = "actix_server_config"
path = "src/lib.rs"
[package.metadata.docs.rs]
features = ["ssl", "rust-tls"]
[features]
default = []
# openssl
ssl = ["tokio-openssl"]
# rustls
rust-tls = ["rustls", "tokio-rustls"]
[dependencies]
actix-service = { path="../actix-service" }
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 }

View File

@@ -0,0 +1,7 @@
# Changes
## [0.1.1] - 2019-04-16
### Added
* `IoStream` trait and impls for TcpStream, SslStream and TlsStream

View File

@@ -1,6 +1,10 @@
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 {
@@ -31,3 +35,184 @@ impl ServerConfig {
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 {
io: self.io,
proto: self.proto,
params: params,
}
}
/// 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)
}
}

View File

@@ -1,6 +1,49 @@
# Changes
## [0.4.0] - 2019-03-xx
## [0.5.0] - 2019-05-11
### 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

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-server"
version = "0.3.1"
version = "0.4.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix server - General purpose tcp server"
keywords = ["network", "framework", "async", "futures"]
@@ -27,21 +27,20 @@ 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"]
[dependencies]
actix-rt = "0.2.0"
#actix-service = "0.3.2"
actix-service = { path="../actix-service" }
actix-server-config = { path="../actix-server-config" }
actix-rt = "0.2.1"
actix-service = "0.3.4"
actix-server-config = "0.1.1"
log = "0.4"
num_cpus = "1.0"
mio = "^0.6.13"
mio = "0.6.13"
net2 = "0.2"
futures = "0.1"
slab = "0.4"
@@ -59,11 +58,12 @@ 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 = { 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"

View File

@@ -12,8 +12,8 @@ use num_cpus;
use tokio_timer::sleep;
use crate::accept::{AcceptLoop, AcceptNotify, Command};
use crate::config::{ConfiguredService, ServiceConfig};
use crate::server::{Server, ServerCommand};
use crate::service_config::{ConfiguredService, ServiceConfig};
use crate::services::{InternalServiceFactory, ServiceFactory, StreamNewService};
use crate::signals::{Signal, Signals};
use crate::worker::{self, Worker, WorkerAvailability, WorkerClient};
@@ -23,6 +23,7 @@ use crate::{ssl, Token};
pub struct ServerBuilder {
threads: usize,
token: Token,
backlog: i32,
workers: Vec<(usize, WorkerClient)>,
services: Vec<Box<InternalServiceFactory>>,
sockets: Vec<(Token, net::TcpListener)>,
@@ -53,6 +54,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 +72,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
@@ -125,7 +142,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)?;
@@ -133,7 +150,7 @@ impl ServerBuilder {
let mut srv = ConfiguredService::new(apply);
for (name, lst) in cfg.services {
let token = self.token.next();
srv.stream(token, name);
srv.stream(token, name, lst.local_addr()?);
self.sockets.push((token, lst));
}
self.services.push(Box::new(srv));
@@ -149,7 +166,7 @@ impl ServerBuilder {
F: ServiceFactory,
U: net::ToSocketAddrs,
{
let sockets = bind_addr(addr)?;
let sockets = bind_addr(addr, self.backlog)?;
for lst in sockets {
let token = self.token.next();
@@ -311,7 +328,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
@@ -393,12 +410,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);
@@ -421,12 +441,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)?)
}

View File

@@ -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;
@@ -18,12 +19,14 @@ pub struct ServiceConfig {
pub(crate) services: Vec<(String, net::TcpListener)>,
pub(crate) apply: Option<Box<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);
@@ -73,7 +76,7 @@ impl ServiceConfig {
pub(super) struct ConfiguredService {
rt: Box<ServiceRuntimeConfiguration>,
names: HashMap<Token, String>,
names: HashMap<Token, (String, net::SocketAddr)>,
services: HashMap<String, Token>,
}
@@ -86,15 +89,15 @@ 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> {
@@ -111,15 +114,44 @@ impl InternalServiceFactory for ConfiguredService {
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);
})
}),
)
}
}
}
@@ -149,6 +181,7 @@ fn not_configured(_: &mut ServiceRuntime) {
pub struct ServiceRuntime {
names: HashMap<String, Token>,
services: HashMap<Token, BoxedNewService>,
onstart: Vec<Box<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,6 +225,14 @@ 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<
@@ -195,6 +241,7 @@ type BoxedNewService = Box<
Response = (),
Error = (),
InitError = (),
Config = ServerConfig,
Service = BoxedServerService,
Future = Box<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 = ()>>;
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
}))

View File

@@ -2,19 +2,19 @@
mod accept;
mod builder;
mod config;
mod counter;
mod server;
mod service_config;
mod services;
mod signals;
pub mod ssl;
mod worker;
pub use actix_server_config::ServerConfig;
pub use actix_server_config::{Io, IoStream, Protocol, ServerConfig};
pub use self::builder::ServerBuilder;
pub use self::config::{ServiceConfig, ServiceRuntime};
pub use self::server::Server;
pub use self::service_config::{ServiceConfig, ServiceRuntime};
pub use self::services::ServiceFactory;
#[doc(hidden)]

View File

@@ -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 {

View File

@@ -1,14 +1,14 @@
use std::net::{SocketAddr, TcpStream};
use std::net::{self, SocketAddr};
use std::time::Duration;
use actix_rt::spawn;
use actix_server_config::ServerConfig;
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 as TokioTcpStream;
use tokio_tcp::TcpStream;
use super::Token;
use crate::counter::CounterGuard;
@@ -16,7 +16,7 @@ use crate::counter::CounterGuard;
/// Server message
pub(crate) enum ServerMessage {
/// New stream
Connect(TcpStream),
Connect(net::TcpStream),
/// Gracefull shutdown
Shutdown(Duration),
/// Force shutdown
@@ -24,7 +24,7 @@ pub(crate) enum ServerMessage {
}
pub trait ServiceFactory: Send + Clone + 'static {
type NewService: NewService<ServerConfig, Request = TokioTcpStream>;
type NewService: NewService<Config = ServerConfig, Request = Io<TcpStream>>;
fn create(&self) -> Self::NewService;
}
@@ -58,7 +58,7 @@ impl<T> StreamService<T> {
impl<T> Service for StreamService<T>
where
T: Service<Request = TokioTcpStream>,
T: Service<Request = Io<TcpStream>>,
T::Future: 'static,
T::Error: 'static,
{
@@ -74,13 +74,12 @@ where
fn call(&mut self, (guard, req): (Option<CounterGuard>, ServerMessage)) -> Self::Future {
match req {
ServerMessage::Connect(stream) => {
let stream =
TokioTcpStream::from_std(stream, &Handle::default()).map_err(|e| {
error!("Can not convert to an async tcp stream: {}", e);
});
let stream = TcpStream::from_std(stream, &Handle::default()).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(|_| ())
}));
@@ -170,7 +169,7 @@ impl InternalServiceFactory for Box<InternalServiceFactory> {
impl<F, T> ServiceFactory for F
where
F: Fn() -> T + Send + Clone + 'static,
T: NewService<ServerConfig, Request = TokioTcpStream>,
T: NewService<Config = ServerConfig, Request = Io<TcpStream>>,
{
type NewService = T;

View File

@@ -35,6 +35,7 @@ thread_local! {
}
/// Ssl error combinded with service error.
#[derive(Debug)]
pub enum SslError<E1, E2> {
Ssl(E1),
Service(E2),

View File

@@ -1,7 +1,6 @@
use std::io;
use std::marker::PhantomData;
use actix_server_config::ServerConfig;
use actix_service::{NewService, Service};
use futures::{future::ok, future::FutureResult, Async, Future, Poll};
use native_tls::{self, Error, HandshakeError, TlsAcceptor};
@@ -9,16 +8,17 @@ use tokio_io::{AsyncRead, AsyncWrite};
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 {
@@ -28,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(),
@@ -37,11 +37,13 @@ impl<T: AsyncRead + AsyncWrite> Clone for NativeTlsAcceptor<T> {
}
}
impl<T: AsyncRead + AsyncWrite> NewService<ServerConfig> 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>;
@@ -58,17 +60,17 @@ impl<T: AsyncRead + AsyncWrite> NewService<ServerConfig> 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() {
@@ -78,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),
}
}
}
@@ -100,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)));

View File

@@ -8,17 +8,17 @@ use tokio_openssl::{AcceptAsync, SslAcceptorExt, SslStream};
use crate::counter::{Counter, CounterGuard};
use crate::ssl::MAX_CONN_COUNTER;
use crate::ServerConfig;
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 {
@@ -28,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(),
@@ -37,11 +37,12 @@ impl<T: AsyncRead + AsyncWrite> Clone for OpensslAcceptor<T> {
}
}
impl<T: AsyncRead + AsyncWrite> NewService<ServerConfig> 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>;
@@ -58,17 +59,17 @@ impl<T: AsyncRead + AsyncWrite> NewService<ServerConfig> 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() {
@@ -78,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,
)))
}
}

View File

@@ -10,17 +10,17 @@ use tokio_rustls::{Accept, TlsAcceptor, TlsStream};
use crate::counter::{Counter, CounterGuard};
use crate::ssl::MAX_CONN_COUNTER;
use crate::ServerConfig as SrvConfig;
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 {
@@ -30,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(),
@@ -39,11 +39,13 @@ impl<T> Clone for RustlsAcceptor<T> {
}
}
impl<T: AsyncRead + AsyncWrite> NewService<SrvConfig> 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>;
@@ -60,17 +62,17 @@ impl<T: AsyncRead + AsyncWrite> NewService<SrvConfig> 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() {
@@ -80,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,
)))
}
}

View File

@@ -1,8 +1,14 @@
use std::io::Read;
use std::sync::mpsc;
use std::{net, thread, time};
use actix_server::{Server, ServerConfig};
use actix_service::{fn_cfg_factory, fn_service, IntoService};
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();
@@ -16,55 +22,141 @@ fn unused_addr() -> net::SocketAddr {
#[test]
fn test_bind() {
let addr = unused_addr();
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
Server::build()
let h = thread::spawn(move || {
let sys = actix_rt::System::new("test");
let srv = Server::build()
.bind("test", addr, move || {
fn_cfg_factory(move |cfg: &ServerConfig| {
new_service_cfg(move |cfg: &ServerConfig| {
assert_eq!(cfg.local_addr(), addr);
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
})
})
.unwrap()
.run()
.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();
thread::spawn(move || {
Server::build()
.bind("test", addr, move || fn_service(|_| Ok::<_, ()>(())))
let h = thread::spawn(move || {
let sys = actix_rt::System::new("test");
let srv = Server::build()
.bind("test", addr, move || service_fn(|_| Ok::<_, ()>(())))
.unwrap()
.run()
.start();
let _ = tx.send((srv, actix_rt::System::current()));
let _ = sys.run();
});
thread::sleep(time::Duration::from_millis(500));
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();
thread::spawn(move || {
let h = thread::spawn(move || {
let sys = actix_rt::System::new("test");
let lst = net::TcpListener::bind(addr).unwrap();
Server::build()
let srv = Server::build()
.listen("test", lst, move || {
fn_cfg_factory(move |cfg: &ServerConfig| {
new_service_cfg(move |cfg: &ServerConfig| {
assert_eq!(cfg.local_addr(), addr);
Ok::<_, ()>((|_| Ok::<_, ()>(())).into_service())
})
})
.unwrap()
.run()
.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();
}

View File

@@ -1,5 +1,49 @@
# Changes
## [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

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-service"
version = "0.3.3"
version = "0.4.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix Service"
keywords = ["network", "framework", "async", "futures"]
@@ -23,8 +23,7 @@ name = "actix_service"
path = "src/lib.rs"
[dependencies]
futures = "0.1.24"
void = "1.0.2"
futures = "0.1.25"
[dev-dependencies]
actix-rt = "0.1"
actix-rt = "0.2"

View File

@@ -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;

View File

@@ -7,17 +7,16 @@ use crate::from_err::FromErr;
use crate::{NewService, Transform};
/// `Apply` new service combinator
pub struct AndThenTransform<T, A, B, C> {
pub struct AndThenTransform<T, A, B> {
a: A,
b: B,
t: Rc<T>,
_t: std::marker::PhantomData<C>,
}
impl<T, A, B, C> AndThenTransform<T, A, B, C>
impl<T, A, B> AndThenTransform<T, A, B>
where
A: NewService<C>,
B: NewService<C, InitError = A::InitError>,
A: NewService,
B: NewService<Config = A::Config, InitError = A::InitError>,
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>,
{
@@ -27,12 +26,11 @@ where
a,
b,
t: Rc::new(t),
_t: std::marker::PhantomData,
}
}
}
impl<T, A, B, C> Clone for AndThenTransform<T, A, B, C>
impl<T, A, B> Clone for AndThenTransform<T, A, B>
where
A: Clone,
B: Clone,
@@ -42,15 +40,14 @@ where
a: self.a.clone(),
b: self.b.clone(),
t: self.t.clone(),
_t: std::marker::PhantomData,
}
}
}
impl<T, A, B, C> NewService<C> for AndThenTransform<T, A, B, C>
impl<T, A, B> NewService for AndThenTransform<T, A, B>
where
A: NewService<C>,
B: NewService<C, InitError = A::InitError>,
A: NewService,
B: NewService<Config = A::Config, InitError = A::InitError>,
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>,
{
@@ -58,11 +55,12 @@ where
type Response = T::Response;
type Error = T::Error;
type Config = A::Config;
type InitError = T::InitError;
type Service = AndThen<FromErr<A::Service, T::Error>, T::Transform>;
type Future = AndThenTransformFuture<T, A, B, C>;
type Future = AndThenTransformFuture<T, A, B>;
fn new_service(&self, cfg: &C) -> Self::Future {
fn new_service(&self, cfg: &A::Config) -> Self::Future {
AndThenTransformFuture {
a: None,
t: None,
@@ -74,10 +72,10 @@ where
}
}
pub struct AndThenTransformFuture<T, A, B, C>
pub struct AndThenTransformFuture<T, A, B>
where
A: NewService<C>,
B: NewService<C, InitError = A::InitError>,
A: NewService,
B: NewService<InitError = A::InitError>,
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>,
{
@@ -89,10 +87,10 @@ where
t_cell: Rc<T>,
}
impl<T, A, B, C> Future for AndThenTransformFuture<T, A, B, C>
impl<T, A, B> Future for AndThenTransformFuture<T, A, B>
where
A: NewService<C>,
B: NewService<C, InitError = A::InitError>,
A: NewService,
B: NewService<InitError = A::InitError>,
T: Transform<B::Service, Request = A::Response, InitError = A::InitError>,
T::Error: From<A::Error>,
{

View File

@@ -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,11 +186,11 @@ where
type Response = Out::Item;
type Error = A::Error;
type Service = AndThenApply<A::Service, B::Service, F, Out>;
type Config = A::Config;
type InitError = A::InitError;
type Future = AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>;
type Future = AndThenApplyNewServiceFuture<A, B, F, Out>;
fn new_service(&self, cfg: &Cfg) -> Self::Future {
fn new_service(&self, cfg: &A::Config) -> Self::Future {
AndThenApplyNewServiceFuture {
a: None,
b: None,
@@ -201,10 +201,10 @@ where
}
}
pub struct AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>
pub struct AndThenApplyNewServiceFuture<A, B, F, Out>
where
A: NewService<Cfg>,
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
A: NewService,
B: NewService<Error = A::Error, InitError = A::InitError>,
F: FnMut(A::Response, &mut B::Service) -> Out,
Out: IntoFuture,
Out::Error: Into<A::Error>,
@@ -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>,

View File

@@ -4,6 +4,31 @@ use futures::{Async, Future, IntoFuture, Poll};
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: Service,
F: FnMut(In, &mut T) -> Out,
Out: IntoFuture,
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
@@ -22,7 +47,7 @@ where
Out::Error: From<T::Error>,
{
/// Create new `Apply` combinator
pub fn new<I: IntoService<T>>(service: I, f: F) -> Self {
pub(crate) fn new<I: IntoService<T>>(service: I, f: F) -> Self {
Self {
service: service.into_service(),
f,
@@ -67,24 +92,24 @@ where
}
/// `ApplyNewService` new service combinator
pub struct ApplyNewService<T, F, In, Out, Cfg>
pub struct ApplyNewService<T, F, In, Out>
where
T: NewService<Cfg>,
T: NewService,
{
service: T,
f: F,
r: PhantomData<(In, Out, Cfg)>,
r: PhantomData<(In, Out)>,
}
impl<T, F, In, Out, Cfg> ApplyNewService<T, F, In, Out, Cfg>
impl<T, F, In, Out> ApplyNewService<T, F, In, Out>
where
T: NewService<Cfg>,
T: NewService,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<T::Error>,
{
/// Create new `ApplyNewService` new service instance
pub fn new<F1: IntoNewService<T, Cfg>>(service: F1, f: F) -> Self {
pub(crate) fn new<F1: IntoNewService<T>>(service: F1, f: F) -> Self {
Self {
f,
service: service.into_new_service(),
@@ -93,9 +118,9 @@ where
}
}
impl<T, F, In, Out, Cfg> Clone for ApplyNewService<T, F, In, Out, Cfg>
impl<T, F, In, Out> Clone for ApplyNewService<T, F, In, Out>
where
T: NewService<Cfg> + Clone,
T: NewService + Clone,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
{
@@ -108,9 +133,9 @@ where
}
}
impl<T, F, In, Out, Cfg> NewService<Cfg> for ApplyNewService<T, F, In, Out, Cfg>
impl<T, F, In, Out> NewService for ApplyNewService<T, F, In, Out>
where
T: NewService<Cfg>,
T: NewService,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<T::Error>,
@@ -118,19 +143,20 @@ where
type Request = In;
type Response = Out::Item;
type Error = Out::Error;
type Config = T::Config;
type Service = Apply<T::Service, F, In, Out>;
type InitError = T::InitError;
type Future = ApplyNewServiceFuture<T, F, In, Out, Cfg>;
type Future = ApplyNewServiceFuture<T, F, In, Out>;
fn new_service(&self, cfg: &Cfg) -> Self::Future {
fn new_service(&self, cfg: &T::Config) -> Self::Future {
ApplyNewServiceFuture::new(self.service.new_service(cfg), self.f.clone())
}
}
pub struct ApplyNewServiceFuture<T, F, In, Out, Cfg>
pub struct ApplyNewServiceFuture<T, F, In, Out>
where
T: NewService<Cfg>,
T: NewService,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
{
@@ -139,9 +165,9 @@ where
r: PhantomData<(In, Out)>,
}
impl<T, F, In, Out, Cfg> ApplyNewServiceFuture<T, F, In, Out, Cfg>
impl<T, F, In, Out> ApplyNewServiceFuture<T, F, In, Out>
where
T: NewService<Cfg>,
T: NewService,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
{
@@ -154,9 +180,9 @@ where
}
}
impl<T, F, In, Out, Cfg> Future for ApplyNewServiceFuture<T, F, In, Out, Cfg>
impl<T, F, In, Out> Future for ApplyNewServiceFuture<T, F, In, Out>
where
T: NewService<Cfg>,
T: NewService,
F: FnMut(In, &mut T::Service) -> Out + Clone,
Out: IntoFuture,
Out::Error: From<T::Error>,

View File

@@ -1,163 +1,104 @@
use std::marker::PhantomData;
use futures::{Async, Future, Poll};
use futures::future::Future;
use futures::{try_ready, Async, IntoFuture, Poll};
use crate::and_then::AndThen;
use crate::{IntoNewService, NewService};
use crate::cell::Cell;
use crate::{IntoService, NewService, Service};
/// `ApplyNewService` new service combinator
pub struct ApplyConfig<F, A, B, C1, C2> {
a: A,
b: B,
f: F,
r: PhantomData<(C1, C2)>,
}
impl<F, A, B, C1, C2> ApplyConfig<F, A, B, C1, C2>
/// Convert `Fn(&Config, &mut Service) -> Future<Service>` fn to a NewService
pub fn apply_cfg<F, C, T, R, S>(srv: T, f: F) -> ApplyConfigService<F, C, T, R, S>
where
A: NewService<C1>,
B: NewService<C2, Request = A::Response, Error = A::Error, InitError = A::InitError>,
F: Fn(&C1) -> C2,
F: FnMut(&C, &mut T) -> R,
T: Service,
R: IntoFuture,
R::Item: IntoService<S>,
S: Service,
{
/// Create new `ApplyNewService` new service instance
pub fn new<A1: IntoNewService<A, C1>, B1: IntoNewService<B, C2>>(
a: A1,
b: B1,
f: F,
) -> Self {
Self {
f,
a: a.into_new_service(),
b: b.into_new_service(),
r: PhantomData,
}
ApplyConfigService {
f: Cell::new(f),
srv: Cell::new(srv.into_service()),
_t: PhantomData,
}
}
impl<F, A, B, C1, C2> Clone for ApplyConfig<F, A, B, C1, C2>
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
pub struct ApplyConfigService<F, C, T, R, S>
where
A: Clone,
B: Clone,
F: Clone,
F: FnMut(&C, &mut T) -> R,
T: Service,
R: IntoFuture,
R::Item: IntoService<S>,
S: Service,
{
f: Cell<F>,
srv: Cell<T>,
_t: PhantomData<(C, R, S)>,
}
impl<F, C, T, R, S> Clone for ApplyConfigService<F, C, T, R, S>
where
F: FnMut(&C, &mut T) -> R,
T: Service,
R: IntoFuture,
R::Item: IntoService<S>,
S: Service,
{
fn clone(&self) -> Self {
Self {
a: self.a.clone(),
b: self.b.clone(),
ApplyConfigService {
f: self.f.clone(),
r: PhantomData,
srv: self.srv.clone(),
_t: PhantomData,
}
}
}
impl<F, A, B, C1, C2> NewService<C1> for ApplyConfig<F, A, B, C1, C2>
impl<F, C, T, R, S> NewService for ApplyConfigService<F, C, T, R, S>
where
A: NewService<C1>,
B: NewService<C2, Request = A::Response, Error = A::Error, InitError = A::InitError>,
F: Fn(&C1) -> C2,
F: FnMut(&C, &mut T) -> R,
T: Service,
R: IntoFuture,
R::Item: IntoService<S>,
S: Service,
{
type Request = A::Request;
type Response = B::Response;
type Error = A::Error;
type Service = AndThen<A::Service, B::Service>;
type Config = C;
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S;
type InitError = A::InitError;
type Future = ApplyConfigResponse<A, B, C1, C2>;
type InitError = R::Error;
type Future = FnNewServiceConfigFut<R, S>;
fn new_service(&self, cfg: &C1) -> Self::Future {
let cfg2 = (self.f)(cfg);
ApplyConfigResponse {
a: None,
b: None,
fut_a: self.a.new_service(cfg),
fut_b: self.b.new_service(&cfg2),
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,
}
}
}
pub struct ApplyConfigResponse<A, B, C1, C2>
pub struct FnNewServiceConfigFut<R, S>
where
A: NewService<C1>,
B: NewService<C2>,
R: IntoFuture,
R::Item: IntoService<S>,
S: Service,
{
fut_b: B::Future,
fut_a: A::Future,
a: Option<A::Service>,
b: Option<B::Service>,
fut: R::Future,
_t: PhantomData<(S,)>,
}
impl<A, B, C1, C2> Future for ApplyConfigResponse<A, B, C1, C2>
impl<R, S> Future for FnNewServiceConfigFut<R, S>
where
A: NewService<C1>,
B: NewService<C2, Request = A::Response, Error = A::Error, InitError = A::InitError>,
R: IntoFuture,
R::Item: IntoService<S>,
S: Service,
{
type Item = AndThen<A::Service, B::Service>;
type Error = A::InitError;
type Item = S;
type Error = R::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if self.a.is_none() {
if let Async::Ready(service) = self.fut_a.poll()? {
self.a = Some(service);
}
}
if self.b.is_none() {
if let Async::Ready(service) = self.fut_b.poll()? {
self.b = Some(service);
}
}
if self.a.is_some() && self.b.is_some() {
Ok(Async::Ready(AndThen::new(
self.a.take().unwrap(),
self.b.take().unwrap(),
)))
} else {
Ok(Async::NotReady)
}
}
}
#[cfg(test)]
mod tests {
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use crate::{fn_cfg_factory, NewService, Service};
#[derive(Clone)]
struct Srv;
impl Service for Srv {
type Request = ();
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
ok(())
}
}
#[test]
fn test_new_service() {
let new_srv = fn_cfg_factory(|_: &usize| Ok::<_, ()>(Srv)).apply_cfg(
fn_cfg_factory(|s: &String| {
assert_eq!(s, "test");
Ok::<_, ()>(Srv)
}),
|cfg: &usize| {
assert_eq!(*cfg, 1);
"test".to_string()
},
);
if let Async::Ready(mut srv) = new_srv.new_service(&1).poll().unwrap() {
assert!(srv.poll_ready().is_ok());
}
Ok(Async::Ready(try_ready!(self.fut.poll()).into_service()))
}
}

View File

@@ -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>;

View File

@@ -1,22 +1,28 @@
use futures::future::{err, ok, Either, FutureResult};
use futures::{Async, Future, IntoFuture, Poll};
use crate::{NewService, Service};
use futures::{Future, IntoFuture, Poll};
pub type BoxedService<Req, Res, Err> = Box<
Service<
Request = Req,
Response = Res,
Error = Err,
Future = Box<Future<Item = Res, Error = Err>>,
Future = BoxedServiceResponse<Res, Err>,
>,
>;
pub type BoxedServiceResponse<Res, Err> =
Either<FutureResult<Res, Err>, Box<Future<Item = Res, Error = Err>>>;
pub struct BoxedNewService<C, Req, Res, Err, InitErr>(Inner<C, Req, Res, Err, InitErr>);
/// Create boxed new service
pub fn new_service<T, C>(
pub fn new_service<T>(
service: T,
) -> BoxedNewService<C, T::Request, T::Response, T::Error, T::InitError>
) -> BoxedNewService<T::Config, T::Request, T::Response, T::Error, T::InitError>
where
C: 'static,
T: NewService<C> + 'static,
T: NewService + 'static,
T::Request: 'static,
T::Response: 'static,
T::Service: 'static,
@@ -41,7 +47,7 @@ where
type Inner<C, Req, Res, Err, InitErr> = Box<
NewService<
C,
Config = C,
Request = Req,
Response = Res,
Error = Err,
@@ -51,9 +57,7 @@ type Inner<C, Req, Res, Err, InitErr> = Box<
>,
>;
pub struct BoxedNewService<C, Req, Res, Err, InitErr>(Inner<C, Req, Res, Err, InitErr>);
impl<C, Req, Res, Err, InitErr> NewService<C> for BoxedNewService<C, Req, Res, Err, InitErr>
impl<C, Req, Res, Err, InitErr> NewService for BoxedNewService<C, Req, Res, Err, InitErr>
where
Req: 'static,
Res: 'static,
@@ -64,6 +68,7 @@ where
type Response = Res;
type Error = Err;
type InitError = InitErr;
type Config = C;
type Service = BoxedService<Req, Res, Err>;
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
@@ -72,18 +77,18 @@ where
}
}
struct NewServiceWrapper<C, T: NewService<C>> {
struct NewServiceWrapper<C, T: NewService> {
service: T,
_t: std::marker::PhantomData<C>,
}
impl<C, T, Req, Res, Err, InitErr> NewService<C> for NewServiceWrapper<C, T>
impl<C, T, Req, Res, Err, InitErr> NewService for NewServiceWrapper<C, T>
where
Req: 'static,
Res: 'static,
Err: 'static,
InitErr: 'static,
T: NewService<C, Request = Req, Response = Res, Error = Err, InitError = InitErr>,
T: NewService<Config = C, Request = Req, Response = Res, Error = Err, InitError = InitErr>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service>::Future: 'static,
@@ -92,6 +97,7 @@ where
type Response = Res;
type Error = Err;
type InitError = InitErr;
type Config = C;
type Service = BoxedService<Req, Res, Err>;
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
@@ -125,13 +131,21 @@ where
type Request = Req;
type Response = Res;
type Error = Err;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
type Future = Either<
FutureResult<Self::Response, Self::Error>,
Box<Future<Item = Self::Response, Error = Self::Error>>,
>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.0.poll_ready()
}
fn call(&mut self, req: Self::Request) -> Self::Future {
Box::new(self.0.call(req))
let mut fut = self.0.call(req);
match fut.poll() {
Ok(Async::Ready(res)) => Either::A(ok(res)),
Err(e) => Either::A(err(e)),
Ok(Async::NotReady) => Either::B(Box::new(fut)),
}
}
}

View File

@@ -29,4 +29,8 @@ impl<T> Cell<T> {
pub(crate) fn get_mut(&mut self) -> &mut T {
unsafe { &mut *self.inner.as_ref().get() }
}
pub(crate) unsafe fn get_mut_unsafe(&self) -> &mut T {
&mut *self.inner.as_ref().get()
}
}

View File

@@ -3,29 +3,30 @@ use std::marker::PhantomData;
use futures::future::{ok, Future, FutureResult};
use futures::{try_ready, Async, IntoFuture, Poll};
use crate::{IntoConfigurableNewService, IntoNewService, IntoService, NewService, Service};
use crate::{IntoNewService, IntoService, NewService, Service};
/// Create `NewService` for function that can act as Service
pub fn fn_service<F, Req, Out, Cfg>(f: F) -> FnNewService<F, Req, Out, Cfg>
/// Create `NewService` for function that can act as a Service
pub fn service_fn<F, Req, Out, Cfg>(f: F) -> NewServiceFn<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
{
FnNewService::new(f)
NewServiceFn::new(f)
}
/// Create `NewService` for function that can produce services
pub fn fn_factory<F, R, S, E>(f: F) -> FnNewServiceNoConfig<F, R, S, E>
pub fn new_service_fn<F, C, R, S, E>(f: F) -> FnNewServiceNoConfig<F, C, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
R::Item: IntoService<S>,
S: Service,
{
FnNewServiceNoConfig::new(f)
}
/// Create `NewService` for function that can produce services with configuration
pub fn fn_cfg_factory<F, C, R, S, E>(f: F) -> FnNewServiceConfig<F, C, R, S, E>
pub fn new_service_cfg<F, C, R, S, E>(f: F) -> FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
@@ -35,39 +36,36 @@ where
FnNewServiceConfig::new(f)
}
pub struct FnService<F, Req, Out>
pub struct ServiceFn<F, Req, Out>
where
F: FnMut(Req) -> Out,
Out: IntoFuture,
{
f: F,
_t: PhantomData<(Req,)>,
_t: PhantomData<Req>,
}
impl<F, Req, Out> FnService<F, Req, Out>
impl<F, Req, Out> ServiceFn<F, Req, Out>
where
F: FnMut(Req) -> Out,
Out: IntoFuture,
{
pub fn new(f: F) -> Self {
FnService { f, _t: PhantomData }
pub(crate) fn new(f: F) -> Self {
ServiceFn { f, _t: PhantomData }
}
}
impl<F, Req, Out> Clone for FnService<F, Req, Out>
impl<F, Req, Out> Clone for ServiceFn<F, Req, Out>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
{
fn clone(&self) -> Self {
FnService {
f: self.f.clone(),
_t: PhantomData,
}
ServiceFn::new(self.f.clone())
}
}
impl<F, Req, Out> Service for FnService<F, Req, Out>
impl<F, Req, Out> Service for ServiceFn<F, Req, Out>
where
F: FnMut(Req) -> Out,
Out: IntoFuture,
@@ -86,17 +84,17 @@ where
}
}
impl<F, Req, Out> IntoService<FnService<F, Req, Out>> for F
impl<F, Req, Out> IntoService<ServiceFn<F, Req, Out>> for F
where
F: FnMut(Req) -> Out + 'static,
F: FnMut(Req) -> Out,
Out: IntoFuture,
{
fn into_service(self) -> FnService<F, Req, Out> {
FnService::new(self)
fn into_service(self) -> ServiceFn<F, Req, Out> {
ServiceFn::new(self)
}
}
pub struct FnNewService<F, Req, Out, Cfg>
pub struct NewServiceFn<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out,
Out: IntoFuture,
@@ -105,17 +103,27 @@ where
_t: PhantomData<(Req, Cfg)>,
}
impl<F, Req, Out, Cfg> FnNewService<F, Req, Out, Cfg>
impl<F, Req, Out, Cfg> NewServiceFn<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
{
pub fn new(f: F) -> Self {
FnNewService { f, _t: PhantomData }
pub(crate) fn new(f: F) -> Self {
NewServiceFn { f, _t: PhantomData }
}
}
impl<F, Req, Out, Cfg> NewService<Cfg> for FnNewService<F, Req, Out, Cfg>
impl<F, Req, Out, Cfg> Clone for NewServiceFn<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
{
fn clone(&self) -> Self {
NewServiceFn::new(self.f.clone())
}
}
impl<F, Req, Out, Cfg> NewService for NewServiceFn<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
@@ -123,95 +131,34 @@ where
type Request = Req;
type Response = Out::Item;
type Error = Out::Error;
type Service = FnService<F, Req, Out>;
type Config = Cfg;
type Service = ServiceFn<F, Req, Out>;
type InitError = ();
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &Cfg) -> Self::Future {
ok(FnService::new(self.f.clone()))
ok(ServiceFn::new(self.f.clone()))
}
}
impl<F, Req, Out, Cfg> Clone for FnNewService<F, Req, Out, Cfg>
impl<F, Req, Out, Cfg> IntoService<ServiceFn<F, Req, Out>> for NewServiceFn<F, Req, Out, Cfg>
where
F: FnMut(Req) -> Out + Clone,
Out: IntoFuture,
{
fn clone(&self) -> Self {
Self::new(self.f.clone())
fn into_service(self) -> ServiceFn<F, Req, Out> {
ServiceFn::new(self.f.clone())
}
}
impl<F, Req, Out, Cfg> IntoNewService<FnNewService<F, Req, Out, Cfg>, Cfg> for F
impl<F, Req, Out, Cfg> IntoNewService<NewServiceFn<F, Req, Out, Cfg>> for F
where
F: Fn(Req) -> Out + Clone,
Out: IntoFuture,
{
fn into_new_service(self) -> FnNewService<F, Req, Out, Cfg> {
FnNewService::new(self)
}
}
/// Converter for `Fn() -> Future<Service>` fn
pub struct FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
f: F,
}
impl<F, R, S, E> FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
pub fn new(f: F) -> Self {
FnNewServiceNoConfig { f }
}
}
impl<F, R, S, E> NewService<()> for FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S;
type InitError = E;
type Future = R::Future;
fn new_service(&self, _: &()) -> Self::Future {
(self.f)().into_future()
}
}
impl<F, R, S, E> Clone for FnNewServiceNoConfig<F, R, S, E>
where
F: Fn() -> R + Clone,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
fn clone(&self) -> Self {
Self::new(self.f.clone())
}
}
impl<F, R, S, E> IntoNewService<FnNewServiceNoConfig<F, R, S, E>, ()> for F
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
fn into_new_service(self) -> FnNewServiceNoConfig<F, R, S, E> {
FnNewServiceNoConfig::new(self)
fn into_new_service(self) -> NewServiceFn<F, Req, Out, Cfg> {
NewServiceFn::new(self)
}
}
@@ -239,7 +186,7 @@ where
}
}
impl<F, C, R, S, E> NewService<C> for FnNewServiceConfig<F, C, R, S, E>
impl<F, C, R, S, E> NewService for FnNewServiceConfig<F, C, R, S, E>
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
@@ -249,8 +196,9 @@ where
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S;
type Config = C;
type Service = S;
type InitError = E;
type Future = FnNewServiceConfigFut<R, S, E>;
@@ -298,14 +246,65 @@ where
}
}
impl<F, C, R, S, E> IntoConfigurableNewService<FnNewServiceConfig<F, C, R, S, E>, C> for F
/// Converter for `Fn() -> Future<Service>` fn
pub struct FnNewServiceNoConfig<F, C, R, S, E>
where
F: Fn(&C) -> R,
R: IntoFuture<Error = E>,
R::Item: IntoService<S>,
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
fn into_new_service(self) -> FnNewServiceConfig<F, C, R, S, E> {
FnNewServiceConfig::new(self)
f: F,
_t: PhantomData<C>,
}
impl<F, C, R, S, E> FnNewServiceNoConfig<F, C, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
pub fn new(f: F) -> Self {
FnNewServiceNoConfig { f, _t: PhantomData }
}
}
impl<F, C, R, S, E> NewService for FnNewServiceNoConfig<F, C, R, S, E>
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S;
type Config = C;
type InitError = E;
type Future = R::Future;
fn new_service(&self, _: &C) -> Self::Future {
(self.f)().into_future()
}
}
impl<F, C, R, S, E> Clone for FnNewServiceNoConfig<F, C, R, S, E>
where
F: Fn() -> R + Clone,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
fn clone(&self) -> Self {
Self::new(self.f.clone())
}
}
impl<F, C, R, S, E> IntoNewService<FnNewServiceNoConfig<F, C, R, S, E>> for F
where
F: Fn() -> R,
R: IntoFuture<Item = S, Error = E>,
S: Service,
{
fn into_new_service(self) -> FnNewServiceNoConfig<F, C, R, S, E> {
FnNewServiceNoConfig::new(self)
}
}

View File

@@ -3,7 +3,21 @@ use std::marker::PhantomData;
use futures::future::{ok, FutureResult};
use futures::IntoFuture;
use crate::{Apply, IntoTransform, Service, Transform};
use crate::apply::Apply;
use crate::{IntoTransform, Service, Transform};
/// Use function as transform service
pub fn transform_fn<F, S, In, Out, Err>(
f: F,
) -> 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)
}
pub struct FnTransform<F, S, In, Out, Err>
where

View File

@@ -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>;

View File

@@ -1,10 +1,9 @@
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use futures::{Future, IntoFuture, Poll};
pub use void::Void;
mod and_then;
mod and_then_apply;
mod and_then_apply_fn;
@@ -17,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_init_err;
mod transform_err;
pub use self::and_then::{AndThen, AndThenNewService};
use self::and_then_apply::AndThenTransform;
use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService};
pub use self::apply::{Apply, ApplyNewService};
pub use self::apply_cfg::ApplyConfig;
pub use self::fn_service::{fn_cfg_factory, fn_factory, fn_service, FnService};
pub use self::fn_transform::FnTransform;
pub use self::apply::{apply_fn, new_apply_fn, Apply, ApplyNewService};
pub use self::apply_cfg::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::{ApplyTransform, IntoTransform, 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 {
@@ -180,7 +182,7 @@ impl<T: ?Sized> ServiceExt for T where T: Service {}
/// 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;
@@ -190,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,
@@ -204,37 +209,29 @@ pub trait NewService<Config = ()> {
type Future: Future<Item = Self::Service, Error = Self::InitError>;
/// Create and return a new service value asynchronously.
fn new_service(&self, cfg: &Config) -> Self::Future;
fn new_service(&self, cfg: &Self::Config) -> Self::Future;
/// Apply transform service to specified service and use it as a next service in
/// chain.
fn apply<T, T1, B, B1>(
self,
transform: T1,
service: B1,
) -> AndThenTransform<T, Self, B, Config>
fn apply<T, T1, B, B1>(self, transform: T1, service: B1) -> AndThenTransform<T, Self, B>
where
Self: Sized,
T: Transform<B::Service, Request = Self::Response, InitError = Self::InitError>,
T::Error: From<Self::Error>,
T1: IntoTransform<T, B::Service>,
B: NewService<Config, InitError = Self::InitError>,
B1: IntoNewService<B, Config>,
B: NewService<Config = Self::Config, InitError = Self::InitError>,
B1: IntoNewService<B>,
{
AndThenTransform::new(transform.into_transform(), self, service.into_new_service())
}
/// Apply function to specified service and use it as a next service in
/// chain.
fn apply_fn<B, I, F, Out>(
self,
service: I,
f: F,
) -> AndThenApplyNewService<Self, B, F, Out, Config>
fn apply_fn<B, I, F, Out>(self, service: I, f: F) -> AndThenApplyNewService<Self, B, F, Out>
where
Self: Sized,
B: NewService<Config, Error = Self::Error, InitError = Self::InitError>,
I: IntoNewService<B, Config>,
B: NewService<Config = Self::Config, Error = Self::Error, InitError = Self::InitError>,
I: IntoNewService<B>,
F: FnMut(Self::Response, &mut B::Service) -> Out,
Out: IntoFuture,
Out::Error: Into<Self::Error>,
@@ -242,30 +239,13 @@ pub trait NewService<Config = ()> {
AndThenApplyNewService::new(self, service, f)
}
/// Map this service's config type to a different config,
/// and use for nested service
fn apply_cfg<F, C, B, B1>(self, service: B1, f: F) -> ApplyConfig<F, Self, B, Config, C>
where
Self: Sized,
F: Fn(&Config) -> C,
B1: IntoNewService<B, C>,
B: NewService<
C,
Request = Self::Response,
Error = Self::Error,
InitError = Self::InitError,
>,
{
ApplyConfig::new(self, service, f)
}
/// Call another service after call to this one has resolved successfully.
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B, Config>
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B>
where
Self: Sized,
F: IntoNewService<B, Config>,
F: IntoNewService<B>,
B: NewService<
Config,
Config = Self::Config,
Request = Self::Response,
Error = Self::Error,
InitError = Self::InitError,
@@ -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

View File

@@ -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>;

View 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(&())
}
}

View File

@@ -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>;

View File

@@ -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;

View File

@@ -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,

View File

@@ -3,12 +3,19 @@ use std::sync::Arc;
use futures::{Async, Future, IntoFuture, Poll};
use crate::transform_map_init_err::TransformMapInitErr;
use crate::{NewService, Service};
use crate::transform_err::{TransformFromErr, TransformMapInitErr};
use crate::{IntoNewService, NewService, Service};
/// `Transform` service factory.
/// The `Transform` trait defines the interface of a Service factory. `Transform`
/// is often implemented for middleware, defining how to manufacture a
/// middleware Service. A Service that is manufactured by the factory takes
/// the Service that follows it during execution as a parameter, assuming
/// ownership of the next Service. A Service can be a variety of types, such
/// as (but not limited to) another middleware Service, an extractor Service,
/// other helper Services, or the request handler endpoint Service.
///
/// A Service is created by the factory during server initialization.
///
/// Transform factory creates service that wraps other services.
/// `Config` is a service factory configuration type.
pub trait Transform<S> {
/// Requests handled by the service.
@@ -33,10 +40,10 @@ pub trait Transform<S> {
/// The future response value.
type Future: Future<Item = Self::Transform, Error = Self::InitError>;
/// Create and return a new service value asynchronously.
/// Creates and returns a new Service component, asynchronously
fn new_transform(&self, service: S) -> Self::Future;
/// Map this service's factory 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, S, F, E>
where
@@ -45,6 +52,32 @@ pub trait Transform<S> {
{
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<T, S> Transform<S> for Rc<T>
@@ -97,65 +130,95 @@ where
}
}
/// `Apply` transform new service
#[derive(Clone)]
pub struct ApplyTransform<T, A, C> {
a: A,
t: Rc<T>,
_t: std::marker::PhantomData<C>,
/// 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
S: NewService,
T: Transform<S::Service, InitError = S::InitError>,
F: IntoTransform<T, S::Service>,
U: IntoNewService<S>,
{
ApplyTransform::new(t.into_transform(), service.into_new_service())
}
impl<T, A, C> ApplyTransform<T, A, C>
/// `Apply` transform to new service
pub struct ApplyTransform<T, S> {
s: Rc<S>,
t: Rc<T>,
}
impl<T, S> ApplyTransform<T, S>
where
A: NewService<C>,
T: Transform<A::Service, Error = A::Error, InitError = A::InitError>,
S: NewService,
T: Transform<S::Service, InitError = S::InitError>,
{
/// Create new `ApplyNewService` new service instance
pub fn new<F: IntoTransform<T, A::Service>>(t: F, a: A) -> Self {
/// Create new `ApplyTransform` new service instance
pub fn new<F: IntoTransform<T, S::Service>>(t: F, service: S) -> Self {
Self {
a,
s: Rc::new(service),
t: Rc::new(t.into_transform()),
_t: std::marker::PhantomData,
}
}
}
impl<T, A, C> NewService<C> for ApplyTransform<T, A, C>
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
A: NewService<C>,
T: Transform<A::Service, Error = A::Error, InitError = A::InitError>,
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, A, C>;
type Future = ApplyTransformFuture<T, S>;
fn new_service(&self, cfg: &C) -> Self::Future {
fn new_service(&self, cfg: &S::Config) -> Self::Future {
ApplyTransformFuture {
t_cell: self.t.clone(),
fut_a: self.a.new_service(cfg).into_future(),
fut_a: self.s.new_service(cfg).into_future(),
fut_t: None,
}
}
}
pub struct ApplyTransformFuture<T, A, C>
pub struct ApplyTransformFuture<T, S>
where
A: NewService<C>,
T: Transform<A::Service, Error = A::Error, InitError = A::InitError>,
S: NewService,
T: Transform<S::Service, InitError = S::InitError>,
{
fut_a: A::Future,
fut_a: S::Future,
fut_t: Option<<T::Future as IntoFuture>::Future>,
t_cell: Rc<T>,
}
impl<T, A, C> Future for ApplyTransformFuture<T, A, C>
impl<T, S> Future for ApplyTransformFuture<T, S>
where
A: NewService<C>,
T: Transform<A::Service, Error = A::Error, InitError = A::InitError>,
S: NewService,
T: Transform<S::Service, InitError = S::InitError>,
{
type Item = T::Transform;
type Error = T::InitError;

View 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)
}
}

View File

@@ -1,94 +0,0 @@
use std::marker::PhantomData;
use futures::{Future, Poll};
use super::Transform;
/// NewTransform for the `map_init_err` combinator, changing the type of a new
/// transform's error.
///
/// This is created by the `NewTransform::map_init_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 `MapInitErr` 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::new(self.t.new_transform(service), 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> TransformMapInitErrFuture<T, S, F, E>
where
T: Transform<S>,
F: Fn(T::InitError) -> E,
{
fn new(fut: T::Future, f: F) -> Self {
TransformMapInitErrFuture { f, fut }
}
}
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)
}
}

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-test-server"
version = "0.1.0"
version = "0.2.1"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix test server"
keywords = ["network", "framework", "async", "futures"]
@@ -33,9 +33,9 @@ ssl = ["openssl", "actix-server/ssl"]
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
[dependencies]
actix-rt = "0.1.0"
#actix-server = "0.3.0"
actix-server = { path="../actix-server" }
actix-rt = "0.2.1"
actix-server = "0.4.0"
actix-server-config = "0.1.0"
log = "0.4"
net2 = "0.2"
@@ -54,3 +54,6 @@ rustls = { version = "^0.15", optional = true }
tokio-rustls = { version = "^0.9", optional = true }
webpki = { version = "0.19", optional = true }
webpki-roots = { version = "0.16", optional = true }
[dev-dependencies]
actix-service = "0.3.4"

View File

@@ -4,8 +4,9 @@ use std::{net, thread};
use actix_rt::{Runtime, System};
use actix_server::{Server, StreamServiceFactory};
pub use actix_server_config::{Io, ServerConfig};
use futures::Future;
use futures::future::{lazy, Future, IntoFuture};
use net2::TcpBuilder;
use tokio_reactor::Handle;
use tokio_tcp::TcpStream;
@@ -13,27 +14,24 @@ use tokio_tcp::TcpStream;
/// The `TestServer` type.
///
/// `TestServer` is very simple test server that simplify process of writing
/// integration tests cases for actix applications.
/// integration tests for actix-net applications.
///
/// # Examples
///
/// ```rust
/// # extern crate actix_test_server;
/// # use actix_web::*;
/// #
/// # fn my_handler(req: &HttpRequest) -> HttpResponse {
/// # HttpResponse::Ok().into()
/// # }
/// #
/// # fn main() {
/// use actix_service::{service_fn, IntoNewService};
/// use actix_test_server::TestServer;
///
/// let mut srv = TestServer::new(|app| app.handler(my_handler));
/// fn main() {
/// let srv = TestServer::with(|| service_fn(
/// |sock| {
/// println!("New connection: {:?}", sock);
/// Ok::<_, ()>(())
/// }
/// ));
///
/// let req = srv.get().finish().unwrap();
/// let response = srv.execute(req.send()).unwrap();
/// assert!(response.status().is_success());
/// # }
/// println!("SOCKET: {:?}", srv.connect());
/// }
/// ```
pub struct TestServer;
@@ -57,13 +55,13 @@ impl TestServer {
let local_addr = tcp.local_addr().unwrap();
Server::build()
.listen("test", tcp, factory)
.listen("test", tcp, factory)?
.workers(1)
.disable_signals()
.start();
tx.send((System::current(), local_addr)).unwrap();
sys.run();
sys.run()
});
let (system, addr) = rx.recv().unwrap();
@@ -101,6 +99,15 @@ impl TestServerRuntime {
self.rt.block_on(fut)
}
/// Runs the provided function, with runtime enabled.
pub fn run_on<F, R>(&mut self, f: F) -> Result<R::Item, R::Error>
where
F: FnOnce() -> R,
R: IntoFuture,
{
self.rt.block_on(lazy(|| f().into_future()))
}
/// Spawn future to the current runtime
pub fn spawn<F>(&mut self, fut: F)
where

View File

@@ -0,0 +1,5 @@
# Changes
## [0.1.0] - 2019-03-28
* Move threadpool to separate crate

View File

@@ -0,0 +1,27 @@
[package]
name = "actix-threadpool"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix thread pool for sync code"
keywords = ["actix", "network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-threadpool/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[lib]
name = "actix_threadpool"
path = "src/lib.rs"
[dependencies]
derive_more = "0.14"
futures = "0.1.25"
parking_lot = "0.7"
lazy_static = "1.2"
log = "0.4"
num_cpus = "1.10"
threadpool = "1.7"

View File

@@ -0,0 +1,88 @@
//! Thread pool for blocking operations
use std::fmt;
use derive_more::Display;
use futures::sync::oneshot;
use futures::{Async, Future, Poll};
use parking_lot::Mutex;
use threadpool::ThreadPool;
/// Env variable for default cpu pool size
const ENV_CPU_POOL_VAR: &str = "ACTIX_THREADPOOL";
lazy_static::lazy_static! {
pub(crate) static ref DEFAULT_POOL: Mutex<ThreadPool> = {
let default = match std::env::var(ENV_CPU_POOL_VAR) {
Ok(val) => {
if let Ok(val) = val.parse() {
val
} else {
log::error!("Can not parse ACTIX_THREADPOOL value");
num_cpus::get() * 5
}
}
Err(_) => num_cpus::get() * 5,
};
Mutex::new(
threadpool::Builder::new()
.thread_name("actix-web".to_owned())
.num_threads(default)
.build(),
)
};
}
thread_local! {
static POOL: ThreadPool = {
DEFAULT_POOL.lock().clone()
};
}
/// Blocking operation execution error
#[derive(Debug, Display)]
pub enum BlockingError<E: fmt::Debug> {
#[display(fmt = "{:?}", _0)]
Error(E),
#[display(fmt = "Thread pool is gone")]
Canceled,
}
/// Execute blocking function on a thread pool, returns future that resolves
/// to result of the function execution.
pub fn run<F, I, E>(f: F) -> CpuFuture<I, E>
where
F: FnOnce() -> Result<I, E> + Send + 'static,
I: Send + 'static,
E: Send + fmt::Debug + 'static,
{
let (tx, rx) = oneshot::channel();
POOL.with(|pool| {
pool.execute(move || {
if !tx.is_canceled() {
let _ = tx.send(f());
}
})
});
CpuFuture { rx }
}
/// Blocking operation completion future. It resolves with results
/// of blocking function execution.
pub struct CpuFuture<I, E> {
rx: oneshot::Receiver<Result<I, E>>,
}
impl<I, E: fmt::Debug> Future for CpuFuture<I, E> {
type Item = I;
type Error = BlockingError<E>;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let res = futures::try_ready!(self.rx.poll().map_err(|_| BlockingError::Canceled));
match res {
Ok(val) => Ok(Async::Ready(val)),
Err(err) => Err(BlockingError::Error(err)),
}
}
}

2
actix-tower/CHANGES.md Normal file
View File

@@ -0,0 +1,2 @@
# Changes

29
actix-tower/Cargo.toml Normal file
View File

@@ -0,0 +1,29 @@
[package]
name = "actix-tower"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>", "Marcus Griep <marcus@griep.us>"]
description = "Actix Tower"
keywords = ["network", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://docs.rs/actix-tower/"
categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[badges]
travis-ci = { repository = "actix/actix-tower", branch = "master" }
appveyor = { repository = "actix/actix-net" }
codecov = { repository = "actix/actix-tower", branch = "master", service = "github" }
[lib]
name = "actix_tower"
path = "src/lib.rs"
[dependencies]
actix-service = "0.3.6"
futures = "0.1.24"
tower-service = "0.2.0"

191
actix-tower/src/lib.rs Normal file
View File

@@ -0,0 +1,191 @@
//! Utilities to ease interoperability with services based on the `tower-service` crate.
use actix_service::Service as ActixService;
use std::marker::PhantomData;
use tower_service::Service as TowerService;
/// Compatibility wrapper associating a `tower_service::Service` with a particular
/// `Request` type, so that it can be used as an `actix_service::Service`.
pub struct TowerCompat<S, R> {
inner: S,
_phantom: PhantomData<R>,
}
impl<S, R> TowerCompat<S, R> {
/// Wraps a `tower_service::Service` in a compatibility wrapper.
pub fn new(inner: S) -> Self {
TowerCompat {
inner,
_phantom: PhantomData,
}
}
}
/// Extension trait for wrapping `tower_service::Service` instances for use as
/// an `actix_service::Service`.
pub trait TowerServiceExt {
/// Wraps a `tower_service::Service` in a compatibility wrapper.
fn compat<R>(self) -> TowerCompat<Self, R>
where
Self: TowerService<R> + Sized;
}
impl<S> TowerServiceExt for S {
fn compat<R>(self) -> TowerCompat<Self, R>
where
Self: TowerService<R> + Sized
{
TowerCompat::new(self)
}
}
impl<S, R> ActixService for TowerCompat<S, R>
where
S: TowerService<R>,
{
type Request = R;
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
fn poll_ready(&mut self) -> futures::Poll<(), Self::Error> {
TowerService::poll_ready(&mut self.inner)
}
fn call(&mut self, req: Self::Request) -> Self::Future {
TowerService::call(&mut self.inner, req)
}
}
#[cfg(test)]
mod tests {
use super::TowerServiceExt;
use actix_service::{Service as ActixService, ServiceExt, Transform};
use futures::{future::FutureResult, Async, Poll, Future};
use tower_service::Service as TowerService;
struct RandomService;
impl<R> TowerService<R> for RandomService {
type Response = u32;
type Error = ();
type Future = FutureResult<Self::Response, Self::Error>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _req: R) -> Self::Future {
futures::finished(4)
}
}
#[test]
fn tower_service_as_actix_service_returns_4() {
let mut s = RandomService.compat();
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
assert_eq!(Ok(Async::Ready(4)), s.call(()).poll());
}
#[test]
fn tower_service_as_actix_service_can_combine() {
let mut s = RandomService.compat().map(|x| x + 1);
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
assert_eq!(Ok(Async::Ready(5)), s.call(()).poll());
}
struct AddOneService;
impl TowerService<u32> for AddOneService {
type Response = u32;
type Error = ();
type Future = FutureResult<Self::Response, Self::Error>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: u32) -> Self::Future {
futures::finished(req + 1)
}
}
#[test]
fn tower_services_as_actix_services_chained() {
let s1 = RandomService.compat();
let s2 = AddOneService.compat();
let s3 = AddOneService.compat();
let mut s = s1.and_then(s2).and_then(s3);
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
assert_eq!(Ok(Async::Ready(6)), s.call(()).poll());
}
#[test]
fn tower_services_as_actix_services_chained_2() {
let s1 = RandomService.compat();
let s2 = AddOneService.compat();
let s3 = AddOneService.compat();
let s4 = RandomService.compat();
let mut s = s1.and_then(s2).and_then(s3).and_then(s4);
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
assert_eq!(Ok(Async::Ready(4)), s.call(()).poll());
}
struct DoMathTransform<S>(S);
impl<S> ActixService for DoMathTransform<S>
where
S: ActixService<Response = u32>,
S::Future: 'static,
{
type Request = S::Request;
type Response = u32;
type Error = S::Error;
type Future = 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 {
let fut = self.0.call(req).map(|x| x * 17);
Box::new(fut)
}
}
struct DoMath;
impl<S> Transform<S> for DoMath
where
S: ActixService<Response = u32>,
S::Future: 'static,
{
type Request = S::Request;
type Response = u32;
type Error = S::Error;
type Transform = DoMathTransform<S>;
type InitError = ();
type Future = FutureResult<Self::Transform, Self::InitError>;
fn new_transform(&self, service: S) -> Self::Future {
futures::finished(DoMathTransform(service))
}
}
#[test]
fn tower_service_as_actix_service_can_be_transformed() {
let transform = DoMath;
let mut s = transform.new_transform(RandomService.compat()).wait().unwrap();
assert_eq!(Ok(Async::Ready(())), s.poll_ready());
assert_eq!(Ok(Async::Ready(68)), s.call(()).poll());
}
}

View File

@@ -1,8 +1,50 @@
# Changes
## [0.4.0] - 2019-03-xx
## [0.4.0] - 2019-05-11
* Upgrade actix-service
### Changed
* Change `Either` to handle two nexted services
* Upgrade actix-service 0.4
### Deleted
* Framed related services
* Stream related services
## [0.3.5] - 2019-04-04
### Added
* Allow to send messages to `FramedTransport` via mpsc channel.
### Changed
* Remove 'static constraint from Clonable service
## [0.3.4] - 2019-03-12
### Changed
* `TimeoutService`, `InOrderService`, `InFlightService` accepts generic IntoService services.
### Fixed
* Fix `InFlightService::poll_ready()` nested service readiness check
* Fix `InOrderService::poll_ready()` nested service readiness check
## [0.3.3] - 2019-03-09
### Changed
* Revert IntoFuture change
* Add generic config param for IntoFramed and TakeOne new services
## [0.3.2] - 2019-03-04

View File

@@ -1,6 +1,6 @@
[package]
name = "actix-utils"
version = "0.3.2"
version = "0.4.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix utils - various actix net related services"
keywords = ["network", "framework", "async", "futures"]
@@ -18,14 +18,14 @@ name = "actix_utils"
path = "src/lib.rs"
[dependencies]
#actix-service = "0.3.2"
actix-service = { path="../actix-service" }
actix-codec = "0.1.0"
actix-service = "0.4.0"
actix-codec = "0.1.1"
bytes = "0.4"
futures = "0.1.24"
either = "1.5.2"
futures = "0.1.25"
tokio-timer = "0.2.8"
tokio-current-thread = "0.1.4"
log = "0.4"
[dev-dependencies]
actix-rt = "0.1"
actix-rt = "0.2.2"

View File

@@ -7,12 +7,12 @@ use futures::Poll;
use super::cell::Cell;
/// Service that allows to turn non-clone service to a service with `Clone` impl
pub struct CloneableService<T: 'static> {
pub struct CloneableService<T> {
service: Cell<T>,
_t: PhantomData<Rc<()>>,
}
impl<T: 'static> CloneableService<T> {
impl<T> CloneableService<T> {
pub fn new(service: T) -> Self
where
T: Service,
@@ -24,7 +24,7 @@ impl<T: 'static> CloneableService<T> {
}
}
impl<T: 'static> Clone for CloneableService<T> {
impl<T> Clone for CloneableService<T> {
fn clone(&self) -> Self {
Self {
service: self.service.clone(),
@@ -35,7 +35,7 @@ impl<T: 'static> Clone for CloneableService<T> {
impl<T> Service for CloneableService<T>
where
T: Service + 'static,
T: Service,
{
type Request = T::Request;
type Response = T::Response;

View File

@@ -1,5 +1,5 @@
//! Contains `Either` service and related types and functions.
use actix_service::{NewService, Service};
use actix_service::{IntoNewService, NewService, Service};
use futures::{future, try_ready, Async, Future, IntoFuture, Poll};
/// Combine two different service types into a single type.
@@ -7,16 +7,16 @@ use futures::{future, try_ready, Async, Future, IntoFuture, Poll};
/// Both services must be of the same request, response, and error types.
/// `EitherService` is useful for handling conditional branching in service
/// middleware to different inner service types.
pub enum EitherService<A, B> {
A(A),
B(B),
pub struct EitherService<A, B> {
left: A,
right: B,
}
impl<A: Clone, B: Clone> Clone for EitherService<A, B> {
fn clone(&self) -> Self {
match self {
EitherService::A(srv) => EitherService::A(srv.clone()),
EitherService::B(srv) => EitherService::B(srv.clone()),
EitherService {
left: self.left.clone(),
right: self.right.clone(),
}
}
}
@@ -24,129 +24,130 @@ impl<A: Clone, B: Clone> Clone for EitherService<A, B> {
impl<A, B> Service for EitherService<A, B>
where
A: Service,
B: Service<Request = A::Request, Response = A::Response, Error = A::Error>,
B: Service<Response = A::Response, Error = A::Error>,
{
type Request = A::Request;
type Request = either::Either<A::Request, B::Request>;
type Response = A::Response;
type Error = A::Error;
type Future = future::Either<A::Future, B::Future>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
match self {
EitherService::A(ref mut inner) => inner.poll_ready(),
EitherService::B(ref mut inner) => inner.poll_ready(),
let left = self.left.poll_ready()?;
let right = self.right.poll_ready()?;
if left.is_ready() && right.is_ready() {
Ok(Async::Ready(()))
} else {
Ok(Async::NotReady)
}
}
fn call(&mut self, req: A::Request) -> Self::Future {
match self {
EitherService::A(ref mut inner) => future::Either::A(inner.call(req)),
EitherService::B(ref mut inner) => future::Either::B(inner.call(req)),
fn call(&mut self, req: either::Either<A::Request, B::Request>) -> Self::Future {
match req {
either::Either::Left(req) => future::Either::A(self.left.call(req)),
either::Either::Right(req) => future::Either::B(self.right.call(req)),
}
}
}
/// Combine two different new service types into a single type.
pub enum Either<A, B> {
A(A),
B(B),
/// Combine two different new service types into a single service.
pub struct Either<A, B> {
left: A,
right: B,
}
impl<A, B> Either<A, B> {
pub fn new_a<C>(srv: A) -> Self
pub fn new_a<F>(srv: F) -> Either<A, ()>
where
A: NewService<C>,
B: NewService<
C,
Request = A::Request,
Response = A::Response,
Error = A::Error,
InitError = A::InitError,
>,
A: NewService,
F: IntoNewService<A>,
{
Either::A(srv)
Either {
left: srv.into_new_service(),
right: (),
}
}
pub fn new_b<C>(srv: B) -> Self
pub fn new_b<F>(srv: F) -> Either<(), B>
where
A: NewService<C>,
B: NewService<
C,
Request = A::Request,
Response = A::Response,
Error = A::Error,
InitError = A::InitError,
>,
B: NewService,
F: IntoNewService<B>,
{
Either::B(srv)
Either {
left: (),
right: srv.into_new_service(),
}
}
}
impl<A, B, C> NewService<C> for Either<A, B>
impl<A, B> NewService for Either<A, B>
where
A: NewService<C>,
A: NewService,
B: NewService<
C,
Request = A::Request,
Config = A::Config,
Response = A::Response,
Error = A::Error,
InitError = A::InitError,
>,
{
type Request = A::Request;
type Request = either::Either<A::Request, B::Request>;
type Response = A::Response;
type Error = A::Error;
type InitError = A::InitError;
type Config = A::Config;
type Service = EitherService<A::Service, B::Service>;
type Future = EitherNewService<A, B, C>;
type Future = EitherNewService<A, B>;
fn new_service(&self, cfg: &C) -> Self::Future {
match self {
Either::A(ref inner) => EitherNewService::A(inner.new_service(cfg)),
Either::B(ref inner) => EitherNewService::B(inner.new_service(cfg)),
fn new_service(&self, cfg: &A::Config) -> Self::Future {
EitherNewService {
left: None,
right: None,
left_fut: self.left.new_service(cfg),
right_fut: self.right.new_service(cfg),
}
}
}
impl<A: Clone, B: Clone> Clone for Either<A, B> {
fn clone(&self) -> Self {
match self {
Either::A(srv) => Either::A(srv.clone()),
Either::B(srv) => Either::B(srv.clone()),
Self {
left: self.left.clone(),
right: self.right.clone(),
}
}
}
#[doc(hidden)]
pub enum EitherNewService<A: NewService<C>, B: NewService<C>, C> {
A(<A::Future as IntoFuture>::Future),
B(<B::Future as IntoFuture>::Future),
pub struct EitherNewService<A: NewService, B: NewService> {
left: Option<A::Service>,
right: Option<B::Service>,
left_fut: <A::Future as IntoFuture>::Future,
right_fut: <B::Future as IntoFuture>::Future,
}
impl<A, B, C> Future for EitherNewService<A, B, C>
impl<A, B> Future for EitherNewService<A, B>
where
A: NewService<C>,
B: NewService<
C,
Request = A::Request,
Response = A::Response,
Error = A::Error,
InitError = A::InitError,
>,
A: NewService,
B: NewService<Response = A::Response, Error = A::Error, InitError = A::InitError>,
{
type Item = EitherService<A::Service, B::Service>;
type Error = A::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self {
EitherNewService::A(ref mut fut) => {
let service = try_ready!(fut.poll());
Ok(Async::Ready(EitherService::A(service)))
}
EitherNewService::B(ref mut fut) => {
let service = try_ready!(fut.poll());
Ok(Async::Ready(EitherService::B(service)))
}
if self.left.is_none() {
self.left = Some(try_ready!(self.left_fut.poll()));
}
if self.right.is_none() {
self.right = Some(try_ready!(self.right_fut.poll()));
}
if self.left.is_some() && self.right.is_some() {
Ok(Async::Ready(EitherService {
left: self.left.take().unwrap(),
right: self.right.take().unwrap(),
}))
} else {
Ok(Async::NotReady)
}
}
}

View File

@@ -1,13 +1,12 @@
//! Framed dispatcher service and related utilities
use std::collections::VecDeque;
use std::marker::PhantomData;
use std::mem;
use std::{fmt, mem};
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
use actix_service::{IntoNewService, IntoService, NewService, Service};
use futures::future::{ok, FutureResult};
use actix_service::{IntoService, Service};
use futures::task::AtomicTask;
use futures::{Async, Future, IntoFuture, Poll, Sink, Stream};
use futures::unsync::mpsc;
use futures::{Async, Future, Poll, Sink, Stream};
use log::debug;
use crate::cell::Cell;
@@ -15,156 +14,6 @@ use crate::cell::Cell;
type Request<U> = <U as Decoder>::Item;
type Response<U> = <U as Encoder>::Item;
pub struct FramedNewService<S, T, U, C> {
factory: S,
_t: PhantomData<(T, U, C)>,
}
impl<S, T, U, C> FramedNewService<S, T, U, C>
where
C: Clone,
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
pub fn new<F1: IntoNewService<S, C>>(factory: F1) -> Self {
Self {
factory: factory.into_new_service(),
_t: PhantomData,
}
}
}
impl<S, T, U, C> Clone for FramedNewService<S, T, U, C>
where
S: Clone,
{
fn clone(&self) -> Self {
Self {
factory: self.factory.clone(),
_t: PhantomData,
}
}
}
impl<S, T, U, C> NewService<C> for FramedNewService<S, T, U, C>
where
C: Clone,
S: NewService<C, Request = Request<U>, Response = Response<U>> + Clone,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
type Request = Framed<T, U>;
type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError;
type InitError = S::InitError;
type Service = FramedService<S, T, U, C>;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, cfg: &C) -> Self::Future {
ok(FramedService {
factory: self.factory.clone(),
config: cfg.clone(),
_t: PhantomData,
})
}
}
pub struct FramedService<S, T, U, C> {
factory: S,
config: C,
_t: PhantomData<(T, U)>,
}
impl<S, T, U, C> Clone for FramedService<S, T, U, C>
where
S: Clone,
C: Clone,
{
fn clone(&self) -> Self {
Self {
factory: self.factory.clone(),
config: self.config.clone(),
_t: PhantomData,
}
}
}
impl<S, T, U, C> Service for FramedService<S, T, U, C>
where
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
C: Clone,
{
type Request = Framed<T, U>;
type Response = FramedTransport<S::Service, T, U>;
type Error = S::InitError;
type Future = FramedServiceResponseFuture<S, T, U, C>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: Framed<T, U>) -> Self::Future {
FramedServiceResponseFuture {
fut: self.factory.new_service(&self.config),
framed: Some(req),
}
}
}
#[doc(hidden)]
pub struct FramedServiceResponseFuture<S, T, U, C>
where
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
fut: <S::Future as IntoFuture>::Future,
framed: Option<Framed<T, U>>,
}
impl<S, T, U, C> Future for FramedServiceResponseFuture<S, T, U, C>
where
S: NewService<C, Request = Request<U>, Response = Response<U>>,
S::Error: 'static,
<S::Service as Service>::Future: 'static,
T: AsyncRead + AsyncWrite,
U: Decoder + Encoder,
<U as Encoder>::Item: 'static,
<U as Encoder>::Error: std::fmt::Debug,
{
type Item = FramedTransport<S::Service, T, U>;
type Error = S::InitError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.fut.poll()? {
Async::NotReady => Ok(Async::NotReady),
Async::Ready(service) => Ok(Async::Ready(FramedTransport::new(
self.framed.take().unwrap(),
service,
))),
}
}
}
/// Framed transport errors
pub enum FramedTransportError<E, U: Encoder + Decoder> {
Service(E),
@@ -178,6 +27,47 @@ impl<E, U: Encoder + Decoder> From<E> for FramedTransportError<E, U> {
}
}
impl<E, U: Encoder + Decoder> fmt::Debug for FramedTransportError<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 {
FramedTransportError::Service(ref e) => {
write!(fmt, "FramedTransportError::Service({:?})", e)
}
FramedTransportError::Encoder(ref e) => {
write!(fmt, "FramedTransportError::Encoder({:?})", e)
}
FramedTransportError::Decoder(ref e) => {
write!(fmt, "FramedTransportError::Encoder({:?})", e)
}
}
}
}
impl<E, U: Encoder + Decoder> fmt::Display for FramedTransportError<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 {
FramedTransportError::Service(ref e) => write!(fmt, "{}", e),
FramedTransportError::Encoder(ref e) => write!(fmt, "{:?}", e),
FramedTransportError::Decoder(ref e) => write!(fmt, "{:?}", e),
}
}
}
pub enum FramedMessage<T> {
Message(T),
Close,
}
/// FramedTransport - is a future that reads frames from Framed object
/// and pass then to the service.
pub struct FramedTransport<S, T, U>
@@ -193,6 +83,7 @@ where
service: S,
state: TransportState<S, U>,
framed: Framed<T, U>,
rx: Option<mpsc::UnboundedReceiver<FramedMessage<<U as Encoder>::Item>>>,
inner: Cell<FramedTransportInner<<U as Encoder>::Item, S::Error>>,
}
@@ -200,6 +91,7 @@ enum TransportState<S: Service, U: Encoder + Decoder> {
Processing,
Error(FramedTransportError<S::Error, U>),
FramedError(FramedTransportError<S::Error, U>),
FlushAndStop,
Stopping,
}
@@ -221,7 +113,7 @@ where
fn poll_read(&mut self) -> bool {
loop {
match self.service.poll_ready() {
Ok(Async::Ready(_)) => loop {
Ok(Async::Ready(_)) => {
let item = match self.framed.poll() {
Ok(Async::Ready(Some(el))) => el,
Err(err) => {
@@ -244,7 +136,7 @@ where
inner.task.notify();
Ok(())
}));
},
}
Ok(Async::NotReady) => return false,
Err(err) => {
self.state = TransportState::Error(FramedTransportError::Service(err));
@@ -257,10 +149,12 @@ where
/// write to framed object
fn poll_write(&mut self) -> bool {
let inner = 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 let Some(msg) = inner.buf.pop_front() {
match msg {
if !buf_empty {
match inner.buf.pop_front().unwrap() {
Ok(msg) => {
if let Err(err) = self.framed.force_send(msg) {
self.state = TransportState::FramedError(
@@ -268,6 +162,7 @@ where
);
return true;
}
buf_empty = inner.buf.is_empty();
}
Err(err) => {
self.state =
@@ -275,7 +170,33 @@ where
return true;
}
}
} else {
}
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.state = TransportState::FramedError(
FramedTransportError::Encoder(err),
);
return true;
}
}
Ok(Async::Ready(Some(FramedMessage::Close))) => {
self.state = TransportState::FlushAndStop;
return true;
}
Ok(Async::Ready(None)) => {
let _ = self.rx.take();
}
Ok(Async::NotReady) => rx_done = true,
Err(_e) => {
let _ = self.rx.take();
}
}
}
if rx_done && buf_empty {
break;
}
}
@@ -313,6 +234,7 @@ where
pub fn new<F: IntoService<S>>(framed: Framed<T, U>, service: F) -> Self {
FramedTransport {
framed,
rx: None,
service: service.into_service(),
state: TransportState::Processing,
inner: Cell::new(FramedTransportInner {
@@ -322,6 +244,15 @@ where
}
}
/// Get Sender
pub fn set_receiver(
mut self,
rx: mpsc::UnboundedReceiver<FramedMessage<<U as Encoder>::Item>>,
) -> Self {
self.rx = Some(rx);
self
}
/// Get reference to a service wrapped by `FramedTransport` instance.
pub fn get_ref(&self) -> &S {
&self.service
@@ -378,83 +309,22 @@ where
Ok(Async::NotReady)
}
}
TransportState::FlushAndStop => {
if !self.framed.is_write_buf_empty() {
match self.framed.poll_complete() {
Err(err) => {
debug!("Error sending data: {:?}", err);
Ok(Async::Ready(()))
}
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(_)) => Ok(Async::Ready(())),
}
} else {
Ok(Async::Ready(()))
}
}
TransportState::FramedError(err) => Err(err),
TransportState::Stopping => Ok(Async::Ready(())),
}
}
}
pub struct IntoFramed<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
factory: F,
_t: PhantomData<(T,)>,
}
impl<T, U, F> IntoFramed<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
pub fn new(factory: F) -> Self {
IntoFramed {
factory,
_t: PhantomData,
}
}
}
impl<T, C, U, F> NewService<C> for IntoFramed<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
type Request = T;
type Response = Framed<T, U>;
type Error = ();
type InitError = ();
type Service = IntoFramedService<T, U, F>;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &C) -> Self::Future {
ok(IntoFramedService {
factory: self.factory.clone(),
_t: PhantomData,
})
}
}
pub struct IntoFramedService<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
factory: F,
_t: PhantomData<(T,)>,
}
impl<T, U, F> Service for IntoFramedService<T, U, F>
where
T: AsyncRead + AsyncWrite,
F: Fn() -> U + Send + Clone + 'static,
U: Encoder + Decoder,
{
type Request = T;
type Response = Framed<T, U>;
type Error = ();
type Future = FutureResult<Self::Response, Self::Error>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: T) -> Self::Future {
ok(Framed::new(req, (self.factory)()))
}
}

View File

@@ -1,4 +1,6 @@
use actix_service::{Service, Transform, Void};
use std::convert::Infallible;
use actix_service::{IntoService, Service, Transform};
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
@@ -28,7 +30,7 @@ impl<S: Service> Transform<S> for InFlight {
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type InitError = Void;
type InitError = Infallible;
type Transform = InFlightService<S>;
type Future = FutureResult<Self::Transform, Self::InitError>;
@@ -42,11 +44,17 @@ pub struct InFlightService<S> {
service: S,
}
impl<S> InFlightService<S> {
pub fn new(max: usize, service: S) -> Self {
impl<S> InFlightService<S>
where
S: Service,
{
pub fn new<U>(max: usize, service: U) -> Self
where
U: IntoService<S>,
{
Self {
service,
count: Counter::new(max),
service: service.into_service(),
}
}
}
@@ -61,9 +69,9 @@ where
type Future = InFlightServiceResponse<T>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
self.service.poll_ready()?;
if !self.count.available() {
if let Async::NotReady = self.service.poll_ready()? {
Ok(Async::NotReady)
} else if !self.count.available() {
log::trace!("InFlight limit exceeded");
Ok(Async::NotReady)
} else {

View File

@@ -1,7 +1,8 @@
use std::convert::Infallible;
use std::marker::PhantomData;
use std::time::{Duration, Instant};
use actix_service::{NewService, Service, Void};
use actix_service::{NewService, Service};
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use tokio_timer::Delay;
@@ -43,14 +44,15 @@ where
}
}
impl<R, E, F> NewService<()> for KeepAlive<R, E, F>
impl<R, E, F> NewService for KeepAlive<R, E, F>
where
F: Fn() -> E + Clone,
{
type Request = R;
type Response = R;
type Error = E;
type InitError = Void;
type InitError = Infallible;
type Config = ();
type Service = KeepAliveService<R, E, F>;
type Future = FutureResult<Self::Service, Self::InitError>;

View File

@@ -1,9 +1,10 @@
use std::collections::VecDeque;
use std::convert::Infallible;
use std::fmt;
use std::marker::PhantomData;
use std::rc::Rc;
use actix_service::{Service, Transform, Void};
use actix_service::{IntoService, Service, Transform};
use futures::future::{ok, FutureResult};
use futures::task::AtomicTask;
use futures::unsync::oneshot;
@@ -90,7 +91,7 @@ where
type Request = S::Request;
type Response = S::Response;
type Error = InOrderError<S::Error>;
type InitError = Void;
type InitError = Infallible;
type Transform = InOrderService<S>;
type Future = FutureResult<Self::Transform, Self::InitError>;
@@ -112,9 +113,12 @@ where
S::Future: 'static,
S::Error: 'static,
{
pub fn new(service: S) -> Self {
pub fn new<U>(service: U) -> Self
where
U: IntoService<S>,
{
Self {
service,
service: service.into_service(),
acks: VecDeque::new(),
task: Rc::new(AtomicTask::new()),
}
@@ -137,9 +141,6 @@ where
// poll_ready could be called from different task
self.task.register();
// check nested service
self.service.poll_ready().map_err(InOrderError::Service)?;
// check acks
while !self.acks.is_empty() {
let rec = self.acks.front_mut().unwrap();
@@ -153,7 +154,12 @@ where
}
}
Ok(Async::Ready(()))
// check nested service
if let Async::NotReady = self.service.poll_ready().map_err(InOrderError::Service)? {
Ok(Async::NotReady)
} else {
Ok(Async::Ready(()))
}
}
fn call(&mut self, request: S::Request) -> Self::Future {
@@ -240,7 +246,7 @@ mod tests {
let (tx3, rx3) = oneshot::channel();
let (tx_stop, rx_stop) = oneshot::channel();
std::thread::spawn(move || {
let h = std::thread::spawn(move || {
let rx1 = rx1;
let rx2 = rx2;
let rx3 = rx3;
@@ -258,6 +264,7 @@ mod tests {
.and_then(move |res: Vec<_>| {
assert_eq!(res, vec![1, 2, 3]);
let _ = tx_stop.send(());
actix_rt::System::current().stop();
Ok(())
})
}));
@@ -269,5 +276,6 @@ mod tests {
let _ = tx1.send(1);
let _ = rx_stop.wait();
let _ = h.join();
}
}

View File

@@ -1,10 +1,9 @@
use std::marker::PhantomData;
use std::rc::Rc;
use actix_service::{IntoNewService, IntoService, NewService, Service};
use futures::future::{ok, Future, FutureResult};
use actix_service::{IntoService, NewService, Service};
use futures::unsync::mpsc;
use futures::{Async, Poll, Stream};
use futures::{Async, Future, Poll, Stream};
type Request<T> = Result<<T as IntoStream>::Item, <T as IntoStream>::Error>;
@@ -29,76 +28,19 @@ where
}
}
pub struct StreamNewService<S, T, E, C> {
pub struct StreamService<S, T: NewService, E> {
factory: Rc<T>,
_t: PhantomData<(S, E, C)>,
}
impl<S, T, E, C> StreamNewService<S, T, E, C>
where
C: Clone,
S: IntoStream,
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service>::Future: 'static,
{
pub fn new<F: IntoNewService<T, C>>(factory: F) -> Self {
Self {
factory: Rc::new(factory.into_new_service()),
_t: PhantomData,
}
}
}
impl<S, T, E, C> Clone for StreamNewService<S, T, E, C> {
fn clone(&self) -> Self {
Self {
factory: self.factory.clone(),
_t: PhantomData,
}
}
}
impl<S, T, E, C> NewService<C> for StreamNewService<S, T, E, C>
where
C: Clone,
S: IntoStream + 'static,
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service>::Future: 'static,
{
type Request = S;
type Response = ();
type Error = E;
type InitError = E;
type Service = StreamService<S, T, E, C>;
type Future = FutureResult<Self::Service, E>;
fn new_service(&self, cfg: &C) -> Self::Future {
ok(StreamService {
factory: self.factory.clone(),
config: cfg.clone(),
_t: PhantomData,
})
}
}
pub struct StreamService<S, T, E, C = ()> {
factory: Rc<T>,
config: C,
config: T::Config,
_t: PhantomData<(S, E)>,
}
impl<S, T, E, C> Service for StreamService<S, T, E, C>
impl<S, T, E> Service for StreamService<S, T, E>
where
S: IntoStream + 'static,
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
T: NewService<Request = Request<S>, Response = (), Error = E, InitError = E>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service>::Future: 'static,
C: Clone,
{
type Request = S;
type Response = ();
@@ -207,83 +149,3 @@ impl<F: Future> Future for StreamDispatcherService<F> {
}
}
}
/// `NewService` that implements, read one item from the stream.
pub struct TakeItem<T> {
_t: PhantomData<T>,
}
impl<T> TakeItem<T> {
/// Create new `TakeRequest` instance.
pub fn new() -> Self {
TakeItem { _t: PhantomData }
}
}
impl<T> Default for TakeItem<T> {
fn default() -> Self {
TakeItem { _t: PhantomData }
}
}
impl<T> Clone for TakeItem<T> {
fn clone(&self) -> TakeItem<T> {
TakeItem { _t: PhantomData }
}
}
impl<T: Stream, C> NewService<C> for TakeItem<T> {
type Request = T;
type Response = (Option<T::Item>, T);
type Error = T::Error;
type InitError = ();
type Service = TakeItemService<T>;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self, _: &C) -> Self::Future {
ok(TakeItemService { _t: PhantomData })
}
}
/// `NewService` that implements, read one request from framed object feature.
pub struct TakeItemService<T> {
_t: PhantomData<T>,
}
impl<T> Clone for TakeItemService<T> {
fn clone(&self) -> TakeItemService<T> {
TakeItemService { _t: PhantomData }
}
}
impl<T: Stream> Service for TakeItemService<T> {
type Request = T;
type Response = (Option<T::Item>, T);
type Error = T::Error;
type Future = TakeItemServiceResponse<T>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, req: T) -> Self::Future {
TakeItemServiceResponse { stream: Some(req) }
}
}
#[doc(hidden)]
pub struct TakeItemServiceResponse<T: Stream> {
stream: Option<T>,
}
impl<T: Stream> Future for TakeItemServiceResponse<T> {
type Item = (Option<T::Item>, T);
type Error = T::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.stream.as_mut().expect("Use after finish").poll()? {
Async::Ready(item) => Ok(Async::Ready((item, self.stream.take().unwrap()))),
Async::NotReady => Ok(Async::NotReady),
}
}
}

View File

@@ -1,6 +1,7 @@
use std::convert::Infallible;
use std::time::{self, Duration, Instant};
use actix_service::{NewService, Service, Void};
use actix_service::{NewService, Service};
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use tokio_timer::sleep;
@@ -41,11 +42,12 @@ impl Default for LowResTime {
}
}
impl NewService<()> for LowResTime {
impl NewService for LowResTime {
type Request = ();
type Response = Instant;
type Error = Void;
type InitError = Void;
type Error = Infallible;
type InitError = Infallible;
type Config = ();
type Service = LowResTimeService;
type Future = FutureResult<Self::Service, Self::InitError>;
@@ -91,7 +93,7 @@ impl LowResTimeService {
impl Service for LowResTimeService {
type Request = ();
type Response = Instant;
type Error = Void;
type Error = Infallible;
type Future = FutureResult<Self::Response, Self::Error>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {

View File

@@ -6,7 +6,7 @@ use std::fmt;
use std::marker::PhantomData;
use std::time::Duration;
use actix_service::{Service, Transform};
use actix_service::{IntoService, Service, Transform};
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use tokio_timer::{clock, Delay};
@@ -106,9 +106,18 @@ pub struct TimeoutService<S> {
timeout: Duration,
}
impl<S> TimeoutService<S> {
pub fn new(timeout: Duration, service: S) -> Self {
TimeoutService { service, timeout }
impl<S> TimeoutService<S>
where
S: Service,
{
pub fn new<U>(timeout: Duration, service: U) -> Self
where
U: IntoService<S>,
{
TimeoutService {
timeout,
service: service.into_service(),
}
}
}

View File

@@ -9,8 +9,8 @@ use std::{env, fmt, io};
use actix_codec::{AsyncRead, AsyncWrite};
use actix_rt::System;
use actix_server::Server;
use actix_service::{fn_service, NewService};
use actix_server::{Io, Server};
use actix_service::{service_fn, NewService};
use futures::{future, Future};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
use tokio_openssl::SslAcceptorExt;
@@ -54,14 +54,14 @@ fn main() -> io::Result<()> {
let acceptor = acceptor.clone();
// service for converting incoming TcpStream to a SslStream<TcpStream>
fn_service(move |stream: tokio_tcp::TcpStream| {
SslAcceptorExt::accept_async(&acceptor, stream)
service_fn(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))
.and_then(logger)
// Next service counts number of connections
.and_then(move |_| {
let num = num.fetch_add(1, Ordering::Relaxed);

19
router/CHANGES.txt Normal file
View File

@@ -0,0 +1,19 @@
# Changes
## [0.1.3] - 2019-04-22
* Added support for `remainder match` (i.e "/path/{tail}*")
## [0.1.2] - 2019-04-07
* Export `Quoter` type
* Allow to reset `Path` instance
## [0.1.1] - 2019-04-03
* Get dynamic segment by name instead of iterator.
## [0.1.0] - 2019-03-09
* Initial release

View File

@@ -1,16 +1,16 @@
[package]
name = "actix-router"
version = "0.1.0"
version = "0.1.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Path router"
description = "Path table router"
keywords = ["actix"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-net.git"
documentation = "https://actix.rs/api/actix-net/stable/actix_router/"
documentation = "https://docs.rs/actix-router/"
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = "../"
workspace = ".."
[lib]
name = "actix_router"
@@ -23,7 +23,8 @@ default = ["http"]
bytes = "0.4"
regex = "1.0"
serde = "1.0.80"
string = "0.1.3"
string = "0.2.0"
log = "0.4"
http = { version="0.1.14", optional=true }
[dev-dependencies]

View File

@@ -39,7 +39,7 @@ impl<T: AsRef<[u8]>> ResourcePath for string::String<T> {
mod url;
#[cfg(feature = "http")]
pub use self::url::Url;
pub use self::url::{Quoter, Url};
#[cfg(feature = "http")]
mod http_support {

View File

@@ -51,16 +51,19 @@ impl<T: ResourcePath> Path<T> {
}
}
#[inline]
/// Get reference to inner path instance
pub fn get_ref(&self) -> &T {
&self.path
}
#[inline]
/// Get mutable reference to inner path instance
pub fn get_mut(&mut self) -> &mut T {
&mut self.path
}
#[inline]
/// Path
pub fn path(&self) -> &str {
let skip = self.skip as usize;
@@ -72,13 +75,22 @@ impl<T: ResourcePath> Path<T> {
}
}
/// Reset inner path
#[inline]
/// Set new path
pub fn set(&mut self, path: T) {
self.skip = 0;
self.path = path;
self.segments.clear();
}
#[inline]
/// Reset state
pub fn reset(&mut self) {
self.skip = 0;
self.segments.clear();
}
#[inline]
/// Skip first `n` chars in path
pub fn skip(&mut self, n: u16) {
self.skip = self.skip + n;
@@ -99,11 +111,13 @@ impl<T: ResourcePath> Path<T> {
.push((Rc::new(name.to_string()), PathItem::Static(value)));
}
#[inline]
/// Check if there are any matched patterns
pub fn is_empty(&self) -> bool {
self.segments.is_empty()
}
#[inline]
/// Check number of extracted parameters
pub fn len(&self) -> usize {
self.segments.len()
@@ -208,32 +222,3 @@ impl<T: ResourcePath> Resource<T> for Path<T> {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "http")]
#[test]
fn test_get_param_by_name() {
use crate::Url;
use http::{HttpTryFrom, Uri};
let mut params = Path::new(Url::new(Uri::try_from("/").unwrap()));
params.add_static("item1", "path");
params.add_static("item2", "http%3A%2F%2Flocalhost%3A80%2Ffoo");
assert_eq!(params.get("item0"), None);
assert_eq!(params.get_decoded("item0"), None);
assert_eq!(params.get("item1"), Some("path"));
assert_eq!(params.get_decoded("item1").unwrap().to_owned(), "path");
assert_eq!(
params.get("item2"),
Some("http%3A%2F%2Flocalhost%3A80%2Ffoo")
);
assert_eq!(
params.get_decoded("item2").unwrap().to_owned(),
"http://localhost:80/foo"
);
}
}

View File

@@ -118,6 +118,7 @@ impl ResourceDef {
&self.pattern
}
#[inline]
/// Check if path matchs this pattern?
pub fn is_match(&self, path: &str) -> bool {
match self.tp {
@@ -196,18 +197,17 @@ impl ResourceDef {
[PathItem::Static(""); MAX_DYNAMIC_SEGMENTS];
if let Some(captures) = re.captures(path.path()) {
let mut passed = false;
for capture in captures.iter() {
if let Some(ref m) = capture {
if !passed {
passed = true;
continue;
}
segments[idx] = PathItem::Segment(m.start() as u16, m.end() as u16);
for (no, name) in names.iter().enumerate() {
if let Some(m) = captures.name(&name) {
idx += 1;
pos = m.end();
segments[no] = PathItem::Segment(m.start() as u16, m.end() as u16);
} else {
log::error!(
"Dynamic path match but not all segments found: {}",
name
);
false;
}
}
} else {
@@ -267,8 +267,9 @@ impl ResourceDef {
true
}
fn parse_param(pattern: &str) -> (PatternElement, String, &str) {
fn parse_param(pattern: &str) -> (PatternElement, String, &str, bool) {
const DEFAULT_PATTERN: &str = "[^/]+";
const DEFAULT_PATTERN_TAIL: &str = ".*";
let mut params_nesting = 0usize;
let close_idx = pattern
.find(|c| match c {
@@ -283,34 +284,54 @@ impl ResourceDef {
_ => false,
})
.expect("malformed dynamic segment");
let (mut param, rem) = pattern.split_at(close_idx + 1);
let (mut param, mut rem) = pattern.split_at(close_idx + 1);
param = &param[1..param.len() - 1]; // Remove outer brackets
let tail = rem == "*";
let (name, pattern) = match param.find(':') {
Some(idx) => {
if tail {
panic!("Custom regex is not supported for remainder match");
}
let (name, pattern) = param.split_at(idx);
(name, &pattern[1..])
}
None => (param, DEFAULT_PATTERN),
None => (
param,
if tail {
rem = &rem[1..];
DEFAULT_PATTERN_TAIL
} else {
DEFAULT_PATTERN
},
),
};
(
PatternElement::Var(name.to_string()),
format!(r"(?P<{}>{})", &name, &pattern),
rem,
tail,
)
}
fn parse(
mut pattern: &str,
for_prefix: bool,
mut for_prefix: bool,
) -> (String, Vec<PatternElement>, bool, usize) {
if pattern.find('{').is_none() {
return (
String::from(pattern),
vec![PatternElement::Str(String::from(pattern))],
false,
pattern.chars().count(),
);
};
return if pattern.ends_with('*') {
let path = &pattern[..pattern.len() - 1];
let re = String::from("^") + path + "(.*)";
(re, vec![PatternElement::Str(String::from(path))], true, 0)
} else {
(
String::from(pattern),
vec![PatternElement::Str(String::from(pattern))],
false,
pattern.chars().count(),
)
};
}
let mut elems = Vec::new();
let mut re = String::from("^");
@@ -320,7 +341,11 @@ impl ResourceDef {
let (prefix, rem) = pattern.split_at(idx);
elems.push(PatternElement::Str(String::from(prefix)));
re.push_str(&escape(prefix));
let (param_pattern, re_part, rem) = Self::parse_param(rem);
let (param_pattern, re_part, rem, tail) = Self::parse_param(rem);
if tail {
for_prefix = true;
}
elems.push(param_pattern);
re.push_str(&re_part);
pattern = rem;
@@ -340,7 +365,6 @@ impl ResourceDef {
if !for_prefix {
re.push_str("$");
}
(re, elems, true, pattern.chars().count())
}
}
@@ -448,6 +472,42 @@ mod tests {
assert_eq!(path.get("id").unwrap(), "012345");
}
#[test]
fn test_parse_tail() {
let re = ResourceDef::new("/user/-{id}*");
let mut path = Path::new("/user/-profile");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "profile");
let mut path = Path::new("/user/-2345");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "2345");
let mut path = Path::new("/user/-2345/");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "2345/");
let mut path = Path::new("/user/-2345/sdg");
assert!(re.match_path(&mut path));
assert_eq!(path.get("id").unwrap(), "2345/sdg");
}
#[test]
fn test_static_tail() {
let re = ResourceDef::new("/user*");
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(re.is_match("/user/2345/"));
assert!(re.is_match("/user/2345/sdg"));
let re = ResourceDef::new("/user/*");
assert!(re.is_match("/user/profile"));
assert!(re.is_match("/user/2345"));
assert!(re.is_match("/user/2345/"));
assert!(re.is_match("/user/2345/sdg"));
}
#[test]
fn test_parse_urlencoded_param() {
let re = ResourceDef::new("/user/{id}/test");

View File

@@ -1,5 +1,3 @@
use std::rc::Rc;
use crate::ResourcePath;
#[allow(dead_code)]
@@ -39,7 +37,7 @@ thread_local! {
#[derive(Default, Clone, Debug)]
pub struct Url {
uri: http::Uri,
path: Option<Rc<String>>,
path: Option<String>,
}
impl Url {
@@ -49,6 +47,13 @@ impl Url {
Url { uri, path }
}
pub fn with_quoter(uri: http::Uri, quoter: &Quoter) -> Url {
Url {
path: quoter.requote(uri.path().as_bytes()),
uri,
}
}
pub fn uri(&self) -> &http::Uri {
&self.uri
}
@@ -61,19 +66,27 @@ impl Url {
}
}
#[inline]
pub fn update(&mut self, uri: &http::Uri) {
self.uri = uri.clone();
self.path = DEFAULT_QUOTER.with(|q| q.requote(uri.path().as_bytes()));
}
#[inline]
pub fn update_with_quoter(&mut self, uri: &http::Uri, quoter: &Quoter) {
self.uri = uri.clone();
self.path = quoter.requote(uri.path().as_bytes());
}
}
impl ResourcePath for Url {
#[inline]
fn path(&self) -> &str {
self.path()
}
}
pub(crate) struct Quoter {
pub struct Quoter {
safe_table: [u8; 16],
protected_table: [u8; 16],
}
@@ -108,7 +121,7 @@ impl Quoter {
q
}
pub fn requote(&self, val: &[u8]) -> Option<Rc<String>> {
pub fn requote(&self, val: &[u8]) -> Option<String> {
let mut has_pct = 0;
let mut pct = [b'%', 0, 0];
let mut idx = 0;
@@ -160,7 +173,7 @@ impl Quoter {
if let Some(data) = cloned {
// Unsafe: we get data from http::Uri, which does utf-8 checks already
// this code only decodes valid pct encoded values
Some(Rc::new(unsafe { String::from_utf8_unchecked(data) }))
Some(unsafe { String::from_utf8_unchecked(data) })
} else {
None
}