mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-12 12:17:08 +02:00
Compare commits
104 Commits
service-v0
...
codec-0.1.
Author | SHA1 | Date | |
---|---|---|---|
|
b407c65f4c | ||
|
51bd7d2721 | ||
|
c03d869694 | ||
|
25f1eae51f | ||
|
1153715149 | ||
|
aa2967c653 | ||
|
dfbb77f98d | ||
|
e8a49801eb | ||
|
03f2046a42 | ||
|
2e18ca805c | ||
|
15dafeff3d | ||
|
ed14e6b8ea | ||
|
700abc997e | ||
|
8c48bf4de7 | ||
|
9bc492cf6c | ||
|
d2a223e69e | ||
|
e9657a399a | ||
|
9f25fdf929 | ||
|
82930de8e7 | ||
|
04a3e59bd5 | ||
|
0ff0daa795 | ||
|
fb43940824 | ||
|
0410f59cf5 | ||
|
400023a07b | ||
|
2e4c84dbb6 | ||
|
672c3936a6 | ||
|
fbf4444b04 | ||
|
b5b3168b34 | ||
|
668e4f9ac4 | ||
|
d0b8b6940c | ||
|
f1bc9d0deb | ||
|
6ed020565c | ||
|
7ee33efdfd | ||
|
83f51b28d7 | ||
|
83a19e9cb3 | ||
|
6b4010892d | ||
|
d2bd9134aa | ||
|
a0e2d926e6 | ||
|
43d2dd473f | ||
|
862be49e30 | ||
|
6ea128fac5 | ||
|
a97d7f0ccf | ||
|
3d7daabdd7 | ||
|
32f4718880 | ||
|
b8f9bf4bc8 | ||
|
e354c6df92 | ||
|
a53f06a1a4 | ||
|
9979bfb3ef | ||
|
17d0f84f63 | ||
|
08bc328826 | ||
|
7dca264546 | ||
|
3bddba5da5 | ||
|
4be025926c | ||
|
0063a26aab | ||
|
bcc466f6ab | ||
|
663ae53954 | ||
|
406088524e | ||
|
5b8446105f | ||
|
429ad453d3 | ||
|
bd977373bc | ||
|
d45fb9521f | ||
|
94a0da3659 | ||
|
8d62ac4b2f | ||
|
442163690e | ||
|
d83bf95304 | ||
|
8cdbf49187 | ||
|
132be0baa1 | ||
|
cedba24a36 | ||
|
aa20b304ec | ||
|
9f0a288e4b | ||
|
cabebb6b3f | ||
|
84bd257b86 | ||
|
ff6ac0a67f | ||
|
c1c989034d | ||
|
515bfad830 | ||
|
0340d82314 | ||
|
88548199d7 | ||
|
278176fca5 | ||
|
2c8e7c4ae4 | ||
|
b6414d6197 | ||
|
f94ef5248e | ||
|
cbc378b67f | ||
|
db2367b26e | ||
|
0bee4db270 | ||
|
615a0d52ed | ||
|
cfb62ccc40 | ||
|
605a947c3e | ||
|
31f0a96c20 | ||
|
66a7c59aaf | ||
|
316974616a | ||
|
b5d84bd980 | ||
|
e969429e2c | ||
|
6fe741025f | ||
|
f8e170fdaf | ||
|
474fed4dfe | ||
|
2b8f41e9e4 | ||
|
3484007e4e | ||
|
58ba1d8269 | ||
|
7017bad4bb | ||
|
112a7b6b1b | ||
|
48a1c7320c | ||
|
37d28304c9 | ||
|
640c39fdc8 | ||
|
cd5435e5ee |
@@ -39,6 +39,7 @@ script:
|
||||
cd actix-rt && cargo test && cd ..
|
||||
cd actix-connector && cargo test && cd ..
|
||||
cd actix-utils && cargo test && cd ..
|
||||
cd router && cargo test && cd ..
|
||||
fi
|
||||
- |
|
||||
if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then
|
||||
@@ -52,4 +53,5 @@ script:
|
||||
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 ..
|
||||
fi
|
||||
|
29
Cargo.toml
29
Cargo.toml
@@ -1,34 +1,11 @@
|
||||
[package]
|
||||
name = "actix-net"
|
||||
version = "0.3.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix net - framework for the compisible network services for Rust (experimental)"
|
||||
readme = "README.md"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-net/"
|
||||
categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
|
||||
[workspace]
|
||||
members = [
|
||||
"actix-codec",
|
||||
"actix-connector",
|
||||
"actix-rt",
|
||||
"actix-service",
|
||||
"actix-server",
|
||||
"actix-rt",
|
||||
"actix-test-server",
|
||||
"actix-utils",
|
||||
"router",
|
||||
]
|
||||
|
||||
[dev-dependencies]
|
||||
actix-service = "0.1.1"
|
||||
actix-codec = "0.1.0"
|
||||
actix-rt = { path="actix-rt" }
|
||||
actix-server = { path="actix-server", features=["ssl"] }
|
||||
env_logger = "0.5"
|
||||
futures = "0.1.24"
|
||||
openssl = { version="0.10" }
|
||||
tokio-openssl = { version="0.3" }
|
||||
|
@@ -1,5 +1,10 @@
|
||||
# Changes
|
||||
|
||||
## [0.1.0] - 2019-03-06
|
||||
|
||||
* Added `FramedParts::with_read_buffer()` method.
|
||||
|
||||
|
||||
## [0.1.0] - 2018-12-09
|
||||
|
||||
* Move codec to separate crate
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-codec"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Utilities for encoding and decoding frames"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
|
@@ -349,4 +349,17 @@ impl<T, U> FramedParts<T, U> {
|
||||
_priv: (),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new `FramedParts` with read buffer
|
||||
pub fn with_read_buf(io: T, codec: U, read_buf: BytesMut) -> FramedParts<T, U> {
|
||||
FramedParts {
|
||||
io,
|
||||
codec,
|
||||
read_buf,
|
||||
write_buf: BytesMut::new(),
|
||||
write_buf_lw: LW,
|
||||
write_buf_hw: HW,
|
||||
_priv: (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,5 +1,28 @@
|
||||
# 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
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-connector"
|
||||
version = "0.1.0"
|
||||
version = "0.3.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix Connector - tcp connector service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -11,7 +11,7 @@ categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
workspace = ".."
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl"]
|
||||
@@ -27,13 +27,13 @@ default = []
|
||||
ssl = ["openssl", "tokio-openssl"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.1.1"
|
||||
#actix-service = "0.3.0"
|
||||
actix-service = { path="../actix-service" }
|
||||
actix-codec = "0.1.0"
|
||||
actix-rt = "0.1.0"
|
||||
futures = "0.1"
|
||||
tokio-tcp = "0.1"
|
||||
trust-dns-proto = "^0.5.0"
|
||||
trust-dns-resolver = "^0.10.0"
|
||||
tokio-current-thread = "0.1"
|
||||
trust-dns-resolver = { version="0.11.0-alpha.2", default-features = false }
|
||||
|
||||
# openssl
|
||||
openssl = { version="0.10", optional = true }
|
||||
|
@@ -4,8 +4,8 @@ use std::net::{IpAddr, SocketAddr};
|
||||
use std::time::Duration;
|
||||
use std::{fmt, io};
|
||||
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::future::{ok, Either, FutureResult};
|
||||
use 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};
|
||||
@@ -178,11 +178,12 @@ impl Connector {
|
||||
opts: ResolverOpts,
|
||||
) -> impl NewService<
|
||||
Connect,
|
||||
(),
|
||||
Response = (Connect, TcpStream),
|
||||
Error = ConnectorError,
|
||||
InitError = E,
|
||||
> + Clone {
|
||||
move || -> FutureResult<Connector, E> { ok(Connector::new(cfg.clone(), opts)) }
|
||||
fn_factory(move || ok(Connector::new(cfg.clone(), opts)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -317,7 +318,7 @@ impl<T: RequestPort> Future for TcpConnectorResponse<T> {
|
||||
if let Some(new) = self.stream.as_mut() {
|
||||
match new.poll() {
|
||||
Ok(Async::Ready(sock)) => {
|
||||
return Ok(Async::Ready((self.req.take().unwrap(), sock)))
|
||||
return Ok(Async::Ready((self.req.take().unwrap(), sock)));
|
||||
}
|
||||
Ok(Async::NotReady) => return Ok(Async::NotReady),
|
||||
Err(err) => {
|
||||
|
@@ -42,7 +42,7 @@ 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);
|
||||
actix_rt::Arbiter::spawn(bg);
|
||||
tokio_current_thread::spawn(bg);
|
||||
Resolver {
|
||||
resolver,
|
||||
req: PhantomData,
|
||||
|
@@ -43,7 +43,7 @@ impl<R, T, E> Clone for OpensslConnector<R, T, E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService<(R, T)>
|
||||
impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService<(R, T), ()>
|
||||
for OpensslConnector<R, T, E>
|
||||
{
|
||||
type Response = (R, SslStream<T>);
|
||||
@@ -52,7 +52,7 @@ impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService<(R, T)>
|
||||
type InitError = E;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(OpensslConnectorService {
|
||||
connector: self.connector.clone(),
|
||||
_t: PhantomData,
|
||||
|
@@ -1,5 +1,11 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.0] - 2019-03-06
|
||||
|
||||
* `run` method returns `io::Result<()>`
|
||||
|
||||
* Removed `Handle`
|
||||
|
||||
## [0.1.0] - 2018-12-09
|
||||
|
||||
* Initial release
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-rt"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix runtime"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -20,7 +20,7 @@ path = "src/lib.rs"
|
||||
[dependencies]
|
||||
log = "0.4"
|
||||
bytes = "0.4"
|
||||
futures = "0.1.24"
|
||||
futures = "0.1.25"
|
||||
tokio-current-thread = "0.1"
|
||||
tokio-executor = "0.1.5"
|
||||
tokio-reactor = "0.1.7"
|
||||
|
@@ -72,7 +72,7 @@ impl Builder {
|
||||
/// This function will start tokio runtime and will finish once the
|
||||
/// `System::stop()` message get called.
|
||||
/// Function `f` get called within tokio runtime context.
|
||||
pub fn run<F>(self, f: F) -> i32
|
||||
pub fn run<F>(self, f: F) -> io::Result<()>
|
||||
where
|
||||
F: FnOnce() + 'static,
|
||||
{
|
||||
@@ -140,7 +140,7 @@ pub struct SystemRunner {
|
||||
impl SystemRunner {
|
||||
/// This function will start event loop and will finish once the
|
||||
/// `System::stop()` function is called.
|
||||
pub fn run(self) -> i32 {
|
||||
pub fn run(self) -> io::Result<()> {
|
||||
let SystemRunner { mut rt, stop, .. } = self;
|
||||
|
||||
// run loop
|
||||
@@ -148,12 +148,21 @@ impl SystemRunner {
|
||||
Arbiter::run_system();
|
||||
Ok::<_, ()>(())
|
||||
}));
|
||||
let code = match rt.block_on(stop) {
|
||||
Ok(code) => code,
|
||||
Err(_) => 1,
|
||||
let result = match rt.block_on(stop) {
|
||||
Ok(code) => {
|
||||
if code != 0 {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("Non-zero exit code: {}", code),
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)),
|
||||
};
|
||||
Arbiter::stop_system();
|
||||
code
|
||||
result
|
||||
}
|
||||
|
||||
/// Execute a future and wait for result.
|
||||
|
@@ -7,7 +7,7 @@ mod system;
|
||||
|
||||
pub use self::arbiter::Arbiter;
|
||||
pub use self::builder::{Builder, SystemRunner};
|
||||
pub use self::runtime::{Handle, Runtime};
|
||||
pub use self::runtime::Runtime;
|
||||
pub use self::system::System;
|
||||
|
||||
/// Spawns a future on the current arbiter.
|
||||
|
@@ -1,9 +1,7 @@
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::{fmt, io};
|
||||
|
||||
use futures::{future, Future};
|
||||
use tokio_current_thread::Handle as ExecutorHandle;
|
||||
use futures::Future;
|
||||
use tokio_current_thread::{self as current_thread, CurrentThread};
|
||||
use tokio_executor;
|
||||
use tokio_reactor::{self, Reactor};
|
||||
@@ -26,58 +24,6 @@ pub struct Runtime {
|
||||
executor: CurrentThread<Timer<Reactor>>,
|
||||
}
|
||||
|
||||
/// Handle to spawn a future on the corresponding `CurrentThread` runtime instance
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Handle(ExecutorHandle);
|
||||
|
||||
impl Handle {
|
||||
/// Spawn a future onto the `CurrentThread` runtime instance corresponding to this handle
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function panics if the spawn fails. Failure occurs if the `CurrentThread`
|
||||
/// instance of the `Handle` does not exist anymore.
|
||||
pub fn spawn<F>(&self, future: F) -> Result<(), tokio_executor::SpawnError>
|
||||
where
|
||||
F: Future<Item = (), Error = ()> + Send + 'static,
|
||||
{
|
||||
self.0.spawn(future)
|
||||
}
|
||||
|
||||
/// Provides a best effort **hint** to whether or not `spawn` will succeed.
|
||||
///
|
||||
/// This function may return both false positives **and** false negatives.
|
||||
/// If `status` returns `Ok`, then a call to `spawn` will *probably*
|
||||
/// succeed, but may fail. If `status` returns `Err`, a call to `spawn` will
|
||||
/// *probably* fail, but may succeed.
|
||||
///
|
||||
/// This allows a caller to avoid creating the task if the call to `spawn`
|
||||
/// has a high likelihood of failing.
|
||||
pub fn status(&self) -> Result<(), tokio_executor::SpawnError> {
|
||||
self.0.status()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> future::Executor<T> for Handle
|
||||
where
|
||||
T: Future<Item = (), Error = ()> + Send + 'static,
|
||||
{
|
||||
fn execute(&self, future: T) -> Result<(), future::ExecuteError<T>> {
|
||||
if let Err(e) = self.status() {
|
||||
let kind = if e.is_at_capacity() {
|
||||
future::ExecuteErrorKind::NoCapacity
|
||||
} else {
|
||||
future::ExecuteErrorKind::Shutdown
|
||||
};
|
||||
|
||||
return Err(future::ExecuteError::new(kind, future));
|
||||
}
|
||||
|
||||
let _ = self.spawn(future);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Error returned by the `run` function.
|
||||
#[derive(Debug)]
|
||||
pub struct RunError {
|
||||
@@ -120,14 +66,6 @@ impl Runtime {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a new handle to spawn futures on the single-threaded Tokio runtime
|
||||
///
|
||||
/// Different to the runtime itself, the handle can be sent to different
|
||||
/// threads.
|
||||
pub fn handle(&self) -> Handle {
|
||||
Handle(self.executor.handle().clone())
|
||||
}
|
||||
|
||||
/// Spawn a future onto the single-threaded Tokio runtime.
|
||||
///
|
||||
/// See [module level][mod] documentation for more details.
|
||||
|
@@ -1,4 +1,5 @@
|
||||
use std::cell::RefCell;
|
||||
use std::io;
|
||||
|
||||
use futures::sync::mpsc::UnboundedSender;
|
||||
|
||||
@@ -109,7 +110,7 @@ impl System {
|
||||
/// This function will start tokio runtime and will finish once the
|
||||
/// `System::stop()` message get called.
|
||||
/// Function `f` get called within tokio runtime context.
|
||||
pub fn run<F>(f: F) -> i32
|
||||
pub fn run<F>(f: F) -> io::Result<()>
|
||||
where
|
||||
F: FnOnce() + 'static,
|
||||
{
|
||||
|
@@ -1,8 +1,59 @@
|
||||
# Changes
|
||||
|
||||
## [0.4.0] - 2019-03-xx
|
||||
|
||||
* Upgrade actix-service
|
||||
|
||||
|
||||
## [0.3.1] - 2019-03-04
|
||||
|
||||
### Added
|
||||
|
||||
* Add `ServerBuilder::maxconnrate` sets the maximum per-worker number of concurrent connections
|
||||
|
||||
* Add helper ssl error `SslError`
|
||||
|
||||
|
||||
### Changed
|
||||
|
||||
* Rename `StreamServiceFactory` to `ServiceFactory`
|
||||
|
||||
* Deprecate `StreamServiceFactory`
|
||||
|
||||
|
||||
## [0.3.0] - 2019-03-02
|
||||
|
||||
### Changed
|
||||
|
||||
* Use new `NewService` trait
|
||||
|
||||
|
||||
## [0.2.1] - 2019-02-09
|
||||
|
||||
### Changed
|
||||
|
||||
* Drop service response
|
||||
|
||||
|
||||
## [0.2.0] - 2019-02-01
|
||||
|
||||
### Changed
|
||||
|
||||
* Migrate to actix-service 0.2
|
||||
|
||||
* Updated rustls dependency
|
||||
|
||||
|
||||
## [0.1.3] - 2018-12-21
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fix max concurrent connections handling
|
||||
|
||||
|
||||
## [0.1.2] - 2018-12-12
|
||||
|
||||
## Changed
|
||||
### Changed
|
||||
|
||||
* rename ServiceConfig::rt() to ServiceConfig::apply()
|
||||
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-server"
|
||||
version = "0.1.2"
|
||||
version = "0.3.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix server - General purpose tcp server"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -11,7 +11,7 @@ categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
workspace = ".."
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["ssl", "tls", "rust-tls"]
|
||||
@@ -33,21 +33,20 @@ ssl = ["openssl", "tokio-openssl"]
|
||||
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.1.1"
|
||||
actix-rt = "0.1.0"
|
||||
#actix-service = "0.3.2"
|
||||
actix-service = { path="../actix-service" }
|
||||
actix-rt = "0.2.0"
|
||||
|
||||
log = "0.4"
|
||||
num_cpus = "1.0"
|
||||
|
||||
# io
|
||||
mio = "^0.6.13"
|
||||
net2 = "0.2"
|
||||
bytes = "0.4"
|
||||
futures = "0.1"
|
||||
slab = "0.4"
|
||||
tokio-io = "0.1"
|
||||
tokio-tcp = "0.1"
|
||||
tokio-timer = "0.2"
|
||||
tokio-timer = "0.2.8"
|
||||
tokio-reactor = "0.1"
|
||||
tokio-signal = "0.2"
|
||||
|
||||
@@ -59,13 +58,11 @@ openssl = { version="0.10", optional = true }
|
||||
tokio-openssl = { version="0.3", optional = true }
|
||||
|
||||
#rustls
|
||||
rustls = { version = "^0.14", optional = true }
|
||||
tokio-rustls = { version = "^0.8", optional = true }
|
||||
webpki = { version = "0.18", optional = true }
|
||||
webpki-roots = { version = "0.15", optional = true }
|
||||
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]
|
||||
env_logger = "0.5"
|
||||
actix-service = "0.1.1"
|
||||
env_logger = "0.6"
|
||||
actix-codec = "0.1.0"
|
||||
actix-rt = "0.1.0"
|
||||
|
@@ -14,11 +14,10 @@ use tokio_timer::sleep;
|
||||
use crate::accept::{AcceptLoop, AcceptNotify, Command};
|
||||
use crate::config::{ConfiguredService, ServiceConfig};
|
||||
use crate::server::{Server, ServerCommand};
|
||||
use crate::services::{InternalServiceFactory, StreamNewService, StreamServiceFactory};
|
||||
use crate::services::{ServiceFactory, ServiceNewService};
|
||||
use crate::services::{InternalServiceFactory, ServiceFactory, StreamNewService};
|
||||
use crate::signals::{Signal, Signals};
|
||||
use crate::worker::{self, Worker, WorkerAvailability, WorkerClient};
|
||||
use crate::Token;
|
||||
use crate::{ssl, Token};
|
||||
|
||||
/// Server builder
|
||||
pub struct ServerBuilder {
|
||||
@@ -82,9 +81,18 @@ impl ServerBuilder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Stop actix system.
|
||||
/// Sets the maximum per-worker concurrent connection establish process.
|
||||
///
|
||||
/// `SystemExit` message stops currently running system.
|
||||
/// All listeners will stop accepting connections when this limit is reached. It
|
||||
/// can be used to limit the global SSL CPU usage.
|
||||
///
|
||||
/// By default max connections is set to a 256.
|
||||
pub fn maxconnrate(self, num: usize) -> Self {
|
||||
ssl::max_concurrent_ssl_connect(num);
|
||||
self
|
||||
}
|
||||
|
||||
/// Stop actix system.
|
||||
pub fn system_exit(mut self) -> Self {
|
||||
self.exit = true;
|
||||
self
|
||||
@@ -138,7 +146,7 @@ impl ServerBuilder {
|
||||
/// Add new service to the server.
|
||||
pub fn bind<F, U, N: AsRef<str>>(mut self, name: N, addr: U, factory: F) -> io::Result<Self>
|
||||
where
|
||||
F: StreamServiceFactory,
|
||||
F: ServiceFactory,
|
||||
U: net::ToSocketAddrs,
|
||||
{
|
||||
let sockets = bind_addr(addr)?;
|
||||
@@ -163,31 +171,11 @@ impl ServerBuilder {
|
||||
lst: net::TcpListener,
|
||||
factory: F,
|
||||
) -> Self
|
||||
where
|
||||
F: StreamServiceFactory,
|
||||
{
|
||||
let token = self.token.next();
|
||||
self.services.push(StreamNewService::create(
|
||||
name.as_ref().to_string(),
|
||||
token,
|
||||
factory,
|
||||
));
|
||||
self.sockets.push((token, lst));
|
||||
self
|
||||
}
|
||||
|
||||
/// Add new service to the server.
|
||||
pub fn listen2<F, N: AsRef<str>>(
|
||||
mut self,
|
||||
name: N,
|
||||
lst: net::TcpListener,
|
||||
factory: F,
|
||||
) -> Self
|
||||
where
|
||||
F: ServiceFactory,
|
||||
{
|
||||
let token = self.token.next();
|
||||
self.services.push(ServiceNewService::create(
|
||||
self.services.push(StreamNewService::create(
|
||||
name.as_ref().to_string(),
|
||||
token,
|
||||
factory,
|
||||
@@ -204,9 +192,6 @@ impl ServerBuilder {
|
||||
/// This methods panics if no socket addresses get bound.
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// # extern crate futures;
|
||||
/// # extern crate actix_web;
|
||||
/// # use futures::Future;
|
||||
/// use actix_web::*;
|
||||
///
|
||||
/// fn main() {
|
||||
|
@@ -114,7 +114,7 @@ impl InternalServiceFactory for ConfiguredService {
|
||||
// construct services
|
||||
let mut fut = Vec::new();
|
||||
for (token, ns) in rt.services {
|
||||
fut.push(ns.new_service().map(move |service| (token, service)));
|
||||
fut.push(ns.new_service(&()).map(move |service| (token, service)));
|
||||
}
|
||||
|
||||
Box::new(join_all(fut).map_err(|e| {
|
||||
@@ -218,8 +218,8 @@ where
|
||||
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, _: &()) -> Self::Future {
|
||||
Box::new(self.inner.new_service(&()).map_err(|_| ()).map(|s| {
|
||||
let service: BoxedServerService = Box::new(StreamService::new(s));
|
||||
service
|
||||
}))
|
||||
|
@@ -13,7 +13,10 @@ mod worker;
|
||||
pub use self::builder::ServerBuilder;
|
||||
pub use self::config::{ServiceConfig, ServiceRuntime};
|
||||
pub use self::server::Server;
|
||||
pub use self::services::{ServerMessage, ServiceFactory, StreamServiceFactory};
|
||||
pub use self::services::ServiceFactory;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub use self::services::ServiceFactory as StreamServiceFactory;
|
||||
|
||||
/// Socket id token
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
@@ -28,6 +31,6 @@ impl Token {
|
||||
}
|
||||
|
||||
/// Start server building process
|
||||
pub fn build() -> ServerBuilder {
|
||||
pub fn new() -> ServerBuilder {
|
||||
ServerBuilder::default()
|
||||
}
|
||||
|
@@ -13,7 +13,7 @@ use super::Token;
|
||||
use crate::counter::CounterGuard;
|
||||
|
||||
/// Server message
|
||||
pub enum ServerMessage {
|
||||
pub(crate) enum ServerMessage {
|
||||
/// New stream
|
||||
Connect(net::TcpStream),
|
||||
/// Gracefull shutdown
|
||||
@@ -22,14 +22,8 @@ pub enum ServerMessage {
|
||||
ForceShutdown,
|
||||
}
|
||||
|
||||
pub trait StreamServiceFactory: Send + Clone + 'static {
|
||||
type NewService: NewService<TcpStream, Response = ()>;
|
||||
|
||||
fn create(&self) -> Self::NewService;
|
||||
}
|
||||
|
||||
pub trait ServiceFactory: Send + Clone + 'static {
|
||||
type NewService: NewService<ServerMessage, Response = ()>;
|
||||
type NewService: NewService<TcpStream>;
|
||||
|
||||
fn create(&self) -> Self::NewService;
|
||||
}
|
||||
@@ -63,7 +57,7 @@ impl<T> StreamService<T> {
|
||||
|
||||
impl<T> Service<(Option<CounterGuard>, ServerMessage)> for StreamService<T>
|
||||
where
|
||||
T: Service<TcpStream, Response = ()>,
|
||||
T: Service<TcpStream>,
|
||||
T::Future: 'static,
|
||||
T::Error: 'static,
|
||||
{
|
||||
@@ -83,9 +77,9 @@ where
|
||||
});
|
||||
|
||||
if let Ok(stream) = stream {
|
||||
spawn(self.service.call(stream).map_err(|_| ()).map(move |val| {
|
||||
spawn(self.service.call(stream).then(move |res| {
|
||||
drop(guard);
|
||||
val
|
||||
res.map_err(|_| ()).map(|_| ())
|
||||
}));
|
||||
ok(())
|
||||
} else {
|
||||
@@ -97,86 +91,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ServerService<T> {
|
||||
service: T,
|
||||
}
|
||||
|
||||
impl<T> ServerService<T> {
|
||||
fn new(service: T) -> Self {
|
||||
ServerService { service }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service<(Option<CounterGuard>, ServerMessage)> for ServerService<T>
|
||||
where
|
||||
T: Service<ServerMessage, Response = ()>,
|
||||
T::Future: 'static,
|
||||
T::Error: 'static,
|
||||
{
|
||||
type Response = ();
|
||||
type Error = ();
|
||||
type Future = FutureResult<(), ()>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready().map_err(|_| ())
|
||||
}
|
||||
|
||||
fn call(&mut self, (guard, req): (Option<CounterGuard>, ServerMessage)) -> Self::Future {
|
||||
spawn(self.service.call(req).map_err(|_| ()).map(move |val| {
|
||||
drop(guard);
|
||||
val
|
||||
}));
|
||||
ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ServiceNewService<F: ServiceFactory> {
|
||||
name: String,
|
||||
inner: F,
|
||||
token: Token,
|
||||
}
|
||||
|
||||
impl<F> ServiceNewService<F>
|
||||
where
|
||||
F: ServiceFactory,
|
||||
{
|
||||
pub(crate) fn create(name: String, token: Token, inner: F) -> Box<InternalServiceFactory> {
|
||||
Box::new(Self { name, inner, token })
|
||||
}
|
||||
}
|
||||
|
||||
impl<F> InternalServiceFactory for ServiceNewService<F>
|
||||
where
|
||||
F: ServiceFactory,
|
||||
{
|
||||
fn name(&self, _: Token) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn clone_factory(&self) -> Box<InternalServiceFactory> {
|
||||
Box::new(Self {
|
||||
name: self.name.clone(),
|
||||
inner: self.inner.clone(),
|
||||
token: self.token,
|
||||
})
|
||||
}
|
||||
|
||||
fn create(&self) -> Box<Future<Item = Vec<(Token, BoxedServerService)>, Error = ()>> {
|
||||
let token = self.token;
|
||||
Box::new(
|
||||
self.inner
|
||||
.create()
|
||||
.new_service()
|
||||
.map_err(|_| ())
|
||||
.map(move |inner| {
|
||||
let service: BoxedServerService = Box::new(ServerService::new(inner));
|
||||
vec![(token, service)]
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct StreamNewService<F: StreamServiceFactory> {
|
||||
pub(crate) struct StreamNewService<F: ServiceFactory> {
|
||||
name: String,
|
||||
inner: F,
|
||||
token: Token,
|
||||
@@ -184,7 +99,7 @@ pub(crate) struct StreamNewService<F: StreamServiceFactory> {
|
||||
|
||||
impl<F> StreamNewService<F>
|
||||
where
|
||||
F: StreamServiceFactory,
|
||||
F: ServiceFactory,
|
||||
{
|
||||
pub(crate) fn create(name: String, token: Token, inner: F) -> Box<InternalServiceFactory> {
|
||||
Box::new(Self { name, token, inner })
|
||||
@@ -193,7 +108,7 @@ where
|
||||
|
||||
impl<F> InternalServiceFactory for StreamNewService<F>
|
||||
where
|
||||
F: StreamServiceFactory,
|
||||
F: ServiceFactory,
|
||||
{
|
||||
fn name(&self, _: Token) -> &str {
|
||||
&self.name
|
||||
@@ -212,7 +127,7 @@ where
|
||||
Box::new(
|
||||
self.inner
|
||||
.create()
|
||||
.new_service()
|
||||
.new_service(&())
|
||||
.map_err(|_| ())
|
||||
.map(move |inner| {
|
||||
let service: BoxedServerService = Box::new(StreamService::new(inner));
|
||||
@@ -239,19 +154,7 @@ impl InternalServiceFactory for Box<InternalServiceFactory> {
|
||||
impl<F, T> ServiceFactory for F
|
||||
where
|
||||
F: Fn() -> T + Send + Clone + 'static,
|
||||
T: NewService<ServerMessage, Response = ()>,
|
||||
{
|
||||
type NewService = T;
|
||||
|
||||
fn create(&self) -> T {
|
||||
(self)()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, T> StreamServiceFactory for F
|
||||
where
|
||||
F: Fn() -> T + Send + Clone + 'static,
|
||||
T: NewService<TcpStream, Response = ()>,
|
||||
T: NewService<TcpStream>,
|
||||
{
|
||||
type NewService = T;
|
||||
|
||||
|
@@ -33,3 +33,9 @@ pub(crate) static MAX_CONN: AtomicUsize = AtomicUsize::new(256);
|
||||
thread_local! {
|
||||
static MAX_CONN_COUNTER: Counter = Counter::new(MAX_CONN.load(Ordering::Relaxed));
|
||||
}
|
||||
|
||||
/// Ssl error combinded with service error.
|
||||
pub enum SslError<E1, E2> {
|
||||
Ssl(E1),
|
||||
Service(E2),
|
||||
}
|
||||
|
@@ -43,7 +43,7 @@ impl<T: AsyncRead + AsyncWrite> NewService<T> for NativeTlsAcceptor<T> {
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
MAX_CONN_COUNTER.with(|conns| {
|
||||
ok(NativeTlsAcceptorService {
|
||||
acceptor: self.acceptor.clone(),
|
||||
|
@@ -43,7 +43,7 @@ impl<T: AsyncRead + AsyncWrite> NewService<T> for OpensslAcceptor<T> {
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
MAX_CONN_COUNTER.with(|conns| {
|
||||
ok(OpensslAcceptorService {
|
||||
acceptor: self.acceptor.clone(),
|
||||
|
@@ -45,7 +45,7 @@ impl<T: AsyncRead + AsyncWrite> NewService<T> for RustlsAcceptor<T> {
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
MAX_CONN_COUNTER.with(|conns| {
|
||||
ok(RustlsAcceptorService {
|
||||
acceptor: self.config.clone().into(),
|
||||
|
@@ -1,8 +1,112 @@
|
||||
# Changes
|
||||
|
||||
## [0.3.2] - 2019-03-xx
|
||||
|
||||
### Added
|
||||
|
||||
* Add `ApplyTransform` new service for transform and new service.
|
||||
|
||||
### Changed
|
||||
|
||||
* Revert IntoFuture change
|
||||
|
||||
|
||||
## [0.3.2] - 2019-03-04
|
||||
|
||||
### Changed
|
||||
|
||||
* Change `NewService::Future` and `Transform::Future` to the `IntoFuture` trait.
|
||||
|
||||
* Export `AndThenTransform` type
|
||||
|
||||
|
||||
## [0.3.1] - 2019-03-04
|
||||
|
||||
### Changed
|
||||
|
||||
* Simplify Transform trait
|
||||
|
||||
|
||||
## [0.3.0] - 2019-03-02
|
||||
|
||||
## Added
|
||||
|
||||
* Added boxed NewService and Service.
|
||||
|
||||
## Changed
|
||||
|
||||
* Added `Config` parameter to `NewService` trait.
|
||||
|
||||
* Added `Config` parameter to `NewTransform` trait.
|
||||
|
||||
|
||||
## [0.2.2] - 2019-02-19
|
||||
|
||||
### Added
|
||||
|
||||
* Added `NewService` impl for `Rc<S> where S: NewService`
|
||||
|
||||
* Added `NewService` impl for `Arc<S> where S: NewService`
|
||||
|
||||
|
||||
## [0.2.1] - 2019-02-03
|
||||
|
||||
### Changed
|
||||
|
||||
* Generalize `.apply` combinator with Transform trait
|
||||
|
||||
|
||||
## [0.2.0] - 2019-02-01
|
||||
|
||||
### Changed
|
||||
|
||||
* Use associated type instead of generic for Service definition.
|
||||
|
||||
* Before:
|
||||
|
||||
```rust
|
||||
impl Service<Request> for Client {
|
||||
type Response = Response;
|
||||
// ...
|
||||
}
|
||||
```
|
||||
* After:
|
||||
|
||||
```rust
|
||||
impl Service for Client {
|
||||
type Request = Request;
|
||||
type Response = Response;
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## [0.1.6] - 2019-01-24
|
||||
|
||||
### Changed
|
||||
|
||||
* Use `FnMut` instead of `Fn` for .apply() and .map() combinators and `FnService` type
|
||||
|
||||
* Change `.apply()` error semantic, new service's error is `From<Self::Error>`
|
||||
|
||||
|
||||
## [0.1.5] - 2019-01-13
|
||||
|
||||
### Changed
|
||||
|
||||
* Make `Out::Error` convertable from `T::Error` for apply combinator
|
||||
|
||||
|
||||
## [0.1.4] - 2019-01-11
|
||||
|
||||
### Changed
|
||||
|
||||
* Use `FnMut` instead of `Fn` for `FnService`
|
||||
|
||||
|
||||
## [0.1.3] - 2018-12-12
|
||||
|
||||
## Changed
|
||||
### Changed
|
||||
|
||||
* Split service combinators to separate trait
|
||||
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-service"
|
||||
version = "0.1.3"
|
||||
version = "0.3.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix Service"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -11,11 +11,11 @@ categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
workspace = ".."
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "actix/actix-service", branch = "master" }
|
||||
# appveyor = { repository = "fafhrd91/actix-web-hdy9d" }
|
||||
appveyor = { repository = "actix/actix-net" }
|
||||
codecov = { repository = "actix/actix-service", branch = "master", service = "github" }
|
||||
|
||||
[lib]
|
||||
@@ -24,3 +24,7 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
futures = "0.1.24"
|
||||
void = "1.0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.1"
|
@@ -14,9 +14,9 @@ pub struct AndThen<A, B> {
|
||||
|
||||
impl<A, B> AndThen<A, B> {
|
||||
/// Create new `AndThen` combinator
|
||||
pub fn new<Request>(a: A, b: B) -> Self
|
||||
pub fn new<R>(a: A, b: B) -> Self
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
B: Service<A::Response, Error = A::Error>,
|
||||
{
|
||||
Self { a, b: Cell::new(b) }
|
||||
@@ -35,28 +35,28 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, Request> Service<Request> for AndThen<A, B>
|
||||
impl<A, B, R> Service<R> for AndThen<A, B>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
B: Service<A::Response, Error = A::Error>,
|
||||
{
|
||||
type Response = B::Response;
|
||||
type Error = A::Error;
|
||||
type Future = AndThenFuture<A, B, Request>;
|
||||
type Future = AndThenFuture<A, B, R>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
try_ready!(self.a.poll_ready());
|
||||
self.b.get_mut().poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request) -> Self::Future {
|
||||
fn call(&mut self, req: R) -> Self::Future {
|
||||
AndThenFuture::new(self.a.call(req), self.b.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenFuture<A, B, Request>
|
||||
pub struct AndThenFuture<A, B, R>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
B: Service<A::Response, Error = A::Error>,
|
||||
{
|
||||
b: Cell<B>,
|
||||
@@ -64,9 +64,9 @@ where
|
||||
fut_a: Option<A::Future>,
|
||||
}
|
||||
|
||||
impl<A, B, Request> AndThenFuture<A, B, Request>
|
||||
impl<A, B, R> AndThenFuture<A, B, R>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
B: Service<A::Response, Error = A::Error>,
|
||||
{
|
||||
fn new(a: A::Future, b: Cell<B>) -> Self {
|
||||
@@ -78,9 +78,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, Request> Future for AndThenFuture<A, B, Request>
|
||||
impl<A, B, R> Future for AndThenFuture<A, B, R>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
B: Service<A::Response, Error = A::Error>,
|
||||
{
|
||||
type Item = B::Response;
|
||||
@@ -111,10 +111,10 @@ pub struct AndThenNewService<A, B> {
|
||||
|
||||
impl<A, B> AndThenNewService<A, B> {
|
||||
/// Create new `AndThen` combinator
|
||||
pub fn new<Request, F: IntoNewService<B, A::Response>>(a: A, f: F) -> Self
|
||||
pub fn new<R, C, F: IntoNewService<B, A::Response, C>>(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService<Request>,
|
||||
B: NewService<A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<A::Response, C, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
Self {
|
||||
a,
|
||||
@@ -123,20 +123,20 @@ impl<A, B> AndThenNewService<A, B> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, Request> NewService<Request> for AndThenNewService<A, B>
|
||||
impl<A, B, R, C> NewService<R, C> for AndThenNewService<A, B>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
B: NewService<A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<A::Response, C, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
type Response = B::Response;
|
||||
type Error = A::Error;
|
||||
type Service = AndThen<A::Service, B::Service>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = AndThenNewServiceFuture<A, B, Request>;
|
||||
type Future = AndThenNewServiceFuture<A, B, R, C>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
AndThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
AndThenNewServiceFuture::new(self.a.new_service(cfg), self.b.new_service(cfg))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,10 +153,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenNewServiceFuture<A, B, Request>
|
||||
pub struct AndThenNewServiceFuture<A, B, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
B: NewService<A::Response>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<A::Response, C>,
|
||||
{
|
||||
fut_b: B::Future,
|
||||
fut_a: A::Future,
|
||||
@@ -164,10 +164,10 @@ where
|
||||
b: Option<B::Service>,
|
||||
}
|
||||
|
||||
impl<A, B, Request> AndThenNewServiceFuture<A, B, Request>
|
||||
impl<A, B, R, C> AndThenNewServiceFuture<A, B, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
B: NewService<A::Response>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<A::Response, C, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
|
||||
AndThenNewServiceFuture {
|
||||
@@ -179,10 +179,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, Request> Future for AndThenNewServiceFuture<A, B, Request>
|
||||
impl<A, B, R, C> Future for AndThenNewServiceFuture<A, B, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
B: NewService<A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<A::Response, C, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
type Item = AndThen<A::Service, B::Service>;
|
||||
type Error = A::InitError;
|
||||
@@ -219,7 +219,7 @@ mod tests {
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::*;
|
||||
use crate::{NewService, Service};
|
||||
use crate::{NewService, Service, ServiceExt};
|
||||
|
||||
struct Srv1(Rc<Cell<usize>>);
|
||||
impl Service<&'static str> for Srv1 {
|
||||
@@ -282,7 +282,7 @@ mod tests {
|
||||
let new_srv = blank
|
||||
.into_new_service()
|
||||
.and_then(move || Ok(Srv2(cnt.clone())));
|
||||
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
|
||||
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
|
||||
let res = srv.call("srv1").poll();
|
||||
assert!(res.is_ok());
|
||||
assert_eq!(res.unwrap(), Async::Ready(("srv1", "srv2")));
|
||||
|
187
actix-service/src/and_then_apply.rs
Normal file
187
actix-service/src/and_then_apply.rs
Normal file
@@ -0,0 +1,187 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::and_then::AndThen;
|
||||
use crate::from_err::FromErr;
|
||||
use crate::{NewService, Transform};
|
||||
|
||||
/// `Apply` new service combinator
|
||||
pub struct AndThenTransform<T, A, B, BR> {
|
||||
a: A,
|
||||
b: B,
|
||||
t: Rc<T>,
|
||||
_t: PhantomData<BR>,
|
||||
}
|
||||
|
||||
impl<T, A, B, BR> AndThenTransform<T, A, B, BR> {
|
||||
/// Create new `ApplyNewService` new service instance
|
||||
pub fn new<AR, C>(t: T, a: A, b: B) -> Self
|
||||
where
|
||||
A: NewService<AR, C>,
|
||||
B: NewService<BR, C, InitError = A::InitError>,
|
||||
T: Transform<B::Service, A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
Self {
|
||||
a,
|
||||
b,
|
||||
t: Rc::new(t),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A, B, BR> Clone for AndThenTransform<T, A, B, BR>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
t: self.t.clone(),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, A, B, AR, BR, C> NewService<AR, C> for AndThenTransform<T, A, B, BR>
|
||||
where
|
||||
A: NewService<AR, C>,
|
||||
B: NewService<BR, C, InitError = A::InitError>,
|
||||
T: Transform<B::Service, A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
|
||||
type InitError = T::InitError;
|
||||
type Service = AndThen<FromErr<A::Service, T::Error>, T::Transform>;
|
||||
type Future = AndThenTransformFuture<T, A, B, AR, BR, C>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
AndThenTransformFuture {
|
||||
a: None,
|
||||
t: None,
|
||||
t_cell: self.t.clone(),
|
||||
fut_a: self.a.new_service(cfg),
|
||||
fut_b: self.b.new_service(cfg),
|
||||
fut_t: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenTransformFuture<T, A, B, AR, BR, C>
|
||||
where
|
||||
A: NewService<AR, C>,
|
||||
B: NewService<BR, C, InitError = A::InitError>,
|
||||
T: Transform<B::Service, A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
fut_a: A::Future,
|
||||
fut_b: B::Future,
|
||||
fut_t: Option<T::Future>,
|
||||
a: Option<A::Service>,
|
||||
t: Option<T::Transform>,
|
||||
t_cell: Rc<T>,
|
||||
}
|
||||
|
||||
impl<T, A, B, AR, BR, C> Future for AndThenTransformFuture<T, A, B, AR, BR, C>
|
||||
where
|
||||
A: NewService<AR, C>,
|
||||
B: NewService<BR, C, InitError = A::InitError>,
|
||||
T: Transform<B::Service, A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
type Item = AndThen<FromErr<A::Service, T::Error>, T::Transform>;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if self.fut_t.is_none() {
|
||||
if let Async::Ready(service) = self.fut_b.poll()? {
|
||||
self.fut_t = Some(self.t_cell.new_transform(service));
|
||||
}
|
||||
}
|
||||
|
||||
if self.a.is_none() {
|
||||
if let Async::Ready(service) = self.fut_a.poll()? {
|
||||
self.a = Some(service);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref mut fut) = self.fut_t {
|
||||
if let Async::Ready(transform) = fut.poll()? {
|
||||
self.t = Some(transform);
|
||||
}
|
||||
}
|
||||
|
||||
if self.a.is_some() && self.t.is_some() {
|
||||
Ok(Async::Ready(AndThen::new(
|
||||
FromErr::new(self.a.take().unwrap()),
|
||||
self.t.take().unwrap(),
|
||||
)))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::{IntoNewService, IntoService, NewService, Service, ServiceExt};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Srv;
|
||||
impl Service<()> for Srv {
|
||||
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_apply() {
|
||||
let blank = |req| Ok(req);
|
||||
|
||||
let mut srv = blank
|
||||
.into_service()
|
||||
.apply_fn(Srv, |req: &'static str, srv: &mut Srv| {
|
||||
srv.call(()).map(move |res| (req, res))
|
||||
});
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
let res = srv.call("srv").poll();
|
||||
assert!(res.is_ok());
|
||||
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_service() {
|
||||
let blank = || Ok::<_, ()>((|req| Ok(req)).into_service());
|
||||
|
||||
let new_srv = blank.into_new_service().apply(
|
||||
|req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)),
|
||||
|| Ok(Srv),
|
||||
);
|
||||
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
let res = srv.call("srv").poll();
|
||||
assert!(res.is_ok());
|
||||
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
}
|
||||
}
|
298
actix-service/src/and_then_apply_fn.rs
Normal file
298
actix-service/src/and_then_apply_fn.rs
Normal file
@@ -0,0 +1,298 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||
|
||||
use super::{IntoNewService, IntoService, NewService, Service};
|
||||
use crate::cell::Cell;
|
||||
|
||||
/// `Apply` service combinator
|
||||
pub struct AndThenApply<A, B, F, Out, AReq, BReq> {
|
||||
a: A,
|
||||
b: Cell<B>,
|
||||
f: Cell<F>,
|
||||
r: PhantomData<(Out, AReq, BReq)>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, AReq, BReq> AndThenApply<A, B, F, Out, AReq, BReq>
|
||||
where
|
||||
A: Service<AReq>,
|
||||
B: Service<BReq, Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
/// Create new `Apply` combinator
|
||||
pub fn new<A1: IntoService<A, AReq>, B1: IntoService<B, BReq>>(a: A1, b: B1, f: F) -> Self {
|
||||
Self {
|
||||
f: Cell::new(f),
|
||||
a: a.into_service(),
|
||||
b: Cell::new(b.into_service()),
|
||||
r: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, AReq, BReq> Clone for AndThenApply<A, B, F, Out, AReq, BReq>
|
||||
where
|
||||
A: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
AndThenApply {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
f: self.f.clone(),
|
||||
r: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, AReq, BReq> Service<AReq> for AndThenApply<A, B, F, Out, AReq, BReq>
|
||||
where
|
||||
A: Service<AReq>,
|
||||
B: Service<BReq, Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
type Response = Out::Item;
|
||||
type Error = A::Error;
|
||||
type Future = AndThenApplyFuture<A, B, F, Out, AReq, BReq>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
try_ready!(self.a.poll_ready());
|
||||
self.b.get_mut().poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: AReq) -> Self::Future {
|
||||
AndThenApplyFuture {
|
||||
b: self.b.clone(),
|
||||
f: self.f.clone(),
|
||||
fut_b: None,
|
||||
fut_a: Some(self.a.call(req)),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenApplyFuture<A, B, F, Out, AReq, BReq>
|
||||
where
|
||||
A: Service<AReq>,
|
||||
B: Service<BReq, Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
b: Cell<B>,
|
||||
f: Cell<F>,
|
||||
fut_a: Option<A::Future>,
|
||||
fut_b: Option<Out::Future>,
|
||||
_t: PhantomData<(AReq, BReq)>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, AReq, BReq> Future for AndThenApplyFuture<A, B, F, Out, AReq, BReq>
|
||||
where
|
||||
A: Service<AReq>,
|
||||
B: Service<BReq, Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
type Item = Out::Item;
|
||||
type Error = A::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.fut_b {
|
||||
return fut.poll().map_err(|e| e.into());
|
||||
}
|
||||
|
||||
match self.fut_a.as_mut().expect("Bug in actix-service").poll() {
|
||||
Ok(Async::Ready(resp)) => {
|
||||
let _ = self.fut_a.take();
|
||||
self.fut_b =
|
||||
Some((&mut *self.f.get_mut())(resp, self.b.get_mut()).into_future());
|
||||
self.poll()
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ApplyNewService` new service combinator
|
||||
pub struct AndThenApplyNewService<A, B, F, Out, AReq, BReq, Cfg> {
|
||||
a: A,
|
||||
b: B,
|
||||
f: Cell<F>,
|
||||
r: PhantomData<(Out, AReq, BReq, Cfg)>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, AReq, BReq, Cfg> AndThenApplyNewService<A, B, F, Out, AReq, BReq, Cfg>
|
||||
where
|
||||
A: NewService<AReq, Cfg>,
|
||||
B: NewService<BReq, Cfg, 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, AReq, Cfg>, B1: IntoNewService<B, BReq, Cfg>>(
|
||||
a: A1,
|
||||
b: B1,
|
||||
f: F,
|
||||
) -> Self {
|
||||
Self {
|
||||
f: Cell::new(f),
|
||||
a: a.into_new_service(),
|
||||
b: b.into_new_service(),
|
||||
r: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, AReq, BReq, Cfg> Clone
|
||||
for AndThenApplyNewService<A, B, F, Out, AReq, BReq, Cfg>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
f: self.f.clone(),
|
||||
r: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, AReq, BReq, Cfg> NewService<AReq, Cfg>
|
||||
for AndThenApplyNewService<A, B, F, Out, AReq, BReq, Cfg>
|
||||
where
|
||||
A: NewService<AReq, Cfg>,
|
||||
B: NewService<BReq, Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
type Response = Out::Item;
|
||||
type Error = A::Error;
|
||||
type Service = AndThenApply<A::Service, B::Service, F, Out, AReq, BReq>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = AndThenApplyNewServiceFuture<A, B, F, Out, AReq, BReq, Cfg>;
|
||||
|
||||
fn new_service(&self, cfg: &Cfg) -> Self::Future {
|
||||
AndThenApplyNewServiceFuture {
|
||||
a: None,
|
||||
b: None,
|
||||
f: self.f.clone(),
|
||||
fut_a: self.a.new_service(cfg).into_future(),
|
||||
fut_b: self.b.new_service(cfg).into_future(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenApplyNewServiceFuture<A, B, F, Out, AReq, BReq, Cfg>
|
||||
where
|
||||
A: NewService<AReq, Cfg>,
|
||||
B: NewService<BReq, Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
fut_b: B::Future,
|
||||
fut_a: A::Future,
|
||||
f: Cell<F>,
|
||||
a: Option<A::Service>,
|
||||
b: Option<B::Service>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, AReq, BReq, Cfg> Future
|
||||
for AndThenApplyNewServiceFuture<A, B, F, Out, AReq, BReq, Cfg>
|
||||
where
|
||||
A: NewService<AReq, Cfg>,
|
||||
B: NewService<BReq, Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
type Item = AndThenApply<A::Service, B::Service, F, Out, AReq, BReq>;
|
||||
type Error = A::InitError;
|
||||
|
||||
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(AndThenApply {
|
||||
f: self.f.clone(),
|
||||
a: self.a.take().unwrap(),
|
||||
b: Cell::new(self.b.take().unwrap()),
|
||||
r: PhantomData,
|
||||
}))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::blank::{Blank, BlankNewService};
|
||||
use crate::{NewService, Service, ServiceExt};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Srv;
|
||||
impl Service<()> for Srv {
|
||||
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_call() {
|
||||
let mut srv = Blank::new().apply_fn(Srv, |req: &'static str, srv| {
|
||||
srv.call(()).map(move |res| (req, res))
|
||||
});
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
let res = srv.call("srv").poll();
|
||||
assert!(res.is_ok());
|
||||
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_service() {
|
||||
let new_srv = BlankNewService::new_unit().apply_fn(
|
||||
|| Ok(Srv),
|
||||
|req: &'static str, srv| srv.call(()).map(move |res| (req, res)),
|
||||
);
|
||||
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
let res = srv.call("srv").poll();
|
||||
assert!(res.is_ok());
|
||||
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
}
|
||||
}
|
@@ -5,23 +5,23 @@ use futures::{Async, Future, IntoFuture, Poll};
|
||||
use super::{IntoNewService, IntoService, NewService, Service};
|
||||
|
||||
/// `Apply` service combinator
|
||||
pub struct Apply<T, F, In, Out, Request>
|
||||
where
|
||||
T: Service<Request>,
|
||||
{
|
||||
pub struct Apply<T, R, F, In, Out> {
|
||||
service: T,
|
||||
f: F,
|
||||
r: PhantomData<(In, Out, Request)>,
|
||||
r: PhantomData<(R, In, Out)>,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Request> Apply<T, F, In, Out, Request>
|
||||
impl<T, R, F, In, Out> Apply<T, R, F, In, Out>
|
||||
where
|
||||
T: Service<Request>,
|
||||
F: Fn(In, &mut T) -> Out,
|
||||
Out: IntoFuture,
|
||||
F: FnMut(In, &mut T) -> Out,
|
||||
{
|
||||
/// Create new `Apply` combinator
|
||||
pub fn new<I: IntoService<T, Request>>(service: I, f: F) -> Self {
|
||||
pub fn new<I: IntoService<T, R>>(service: I, f: F) -> Self
|
||||
where
|
||||
T: Service<R>,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
Self {
|
||||
service: service.into_service(),
|
||||
f,
|
||||
@@ -30,9 +30,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Request> Clone for Apply<T, F, In, Out, Request>
|
||||
impl<T, R, F, In, Out> Clone for Apply<T, R, F, In, Out>
|
||||
where
|
||||
T: Service<Request> + Clone,
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
@@ -44,18 +44,19 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Request> Service<In> for Apply<T, F, In, Out, Request>
|
||||
impl<T, R, F, In, Out> Service<In> for Apply<T, R, F, In, Out>
|
||||
where
|
||||
T: Service<Request, Error = Out::Error>,
|
||||
F: Fn(In, &mut T) -> Out,
|
||||
T: Service<R>,
|
||||
F: FnMut(In, &mut T) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
type Future = Out::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready()
|
||||
self.service.poll_ready().map_err(|e| e.into())
|
||||
}
|
||||
|
||||
fn call(&mut self, req: In) -> Self::Future {
|
||||
@@ -64,23 +65,21 @@ where
|
||||
}
|
||||
|
||||
/// `ApplyNewService` new service combinator
|
||||
pub struct ApplyNewService<T, F, In, Out, Request>
|
||||
where
|
||||
T: NewService<Request>,
|
||||
{
|
||||
pub struct ApplyNewService<T, F, In, Out, Req> {
|
||||
service: T,
|
||||
f: F,
|
||||
r: PhantomData<(In, Out, Request)>,
|
||||
r: PhantomData<(In, Out, Req)>,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Request> ApplyNewService<T, F, In, Out, Request>
|
||||
where
|
||||
T: NewService<Request>,
|
||||
F: Fn(In, &mut T::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
impl<T, F, In, Out, Req> ApplyNewService<T, F, In, Out, Req> {
|
||||
/// Create new `ApplyNewService` new service instance
|
||||
pub fn new<F1: IntoNewService<T, Request>>(service: F1, f: F) -> Self {
|
||||
pub fn new<Cfg, F1: IntoNewService<T, Req, Cfg>>(service: F1, f: F) -> Self
|
||||
where
|
||||
T: NewService<Req, Cfg>,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
Self {
|
||||
f,
|
||||
service: service.into_new_service(),
|
||||
@@ -89,11 +88,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Request> Clone for ApplyNewService<T, F, In, Out, Request>
|
||||
impl<T, F, In, Out, Req> Clone for ApplyNewService<T, F, In, Out, Req>
|
||||
where
|
||||
T: NewService<Request> + Clone,
|
||||
F: Fn(Out, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
@@ -104,28 +102,29 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Request> NewService<In> for ApplyNewService<T, F, In, Out, Request>
|
||||
impl<T, F, In, Out, Req, Cfg> NewService<In, Cfg> for ApplyNewService<T, F, In, Out, Req>
|
||||
where
|
||||
T: NewService<Request, Error = Out::Error>,
|
||||
F: Fn(In, &mut T::Service) -> Out + Clone,
|
||||
T: NewService<Req, Cfg>,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
type Service = Apply<T::Service, F, In, Out, Request>;
|
||||
type Service = Apply<T::Service, Req, F, In, Out>;
|
||||
|
||||
type InitError = T::InitError;
|
||||
type Future = ApplyNewServiceFuture<T, F, In, Out, Request>;
|
||||
type Future = ApplyNewServiceFuture<T, F, In, Out, Req, Cfg>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
ApplyNewServiceFuture::new(self.service.new_service(), self.f.clone())
|
||||
fn new_service(&self, cfg: &Cfg) -> Self::Future {
|
||||
ApplyNewServiceFuture::new(self.service.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ApplyNewServiceFuture<T, F, In, Out, Request>
|
||||
pub struct ApplyNewServiceFuture<T, F, In, Out, Req, Cfg>
|
||||
where
|
||||
T: NewService<Request>,
|
||||
F: Fn(In, &mut T::Service) -> Out,
|
||||
T: NewService<Req, Cfg>,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fut: T::Future,
|
||||
@@ -133,10 +132,10 @@ where
|
||||
r: PhantomData<(In, Out)>,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Request> ApplyNewServiceFuture<T, F, In, Out, Request>
|
||||
impl<T, F, In, Out, Req, Cfg> ApplyNewServiceFuture<T, F, In, Out, Req, Cfg>
|
||||
where
|
||||
T: NewService<Request>,
|
||||
F: Fn(In, &mut T::Service) -> Out,
|
||||
T: NewService<Req, Cfg>,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
@@ -148,13 +147,14 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out, Request> Future for ApplyNewServiceFuture<T, F, In, Out, Request>
|
||||
impl<T, F, In, Out, Req, Cfg> Future for ApplyNewServiceFuture<T, F, In, Out, Req, Cfg>
|
||||
where
|
||||
T: NewService<Request>,
|
||||
F: Fn(In, &mut T::Service) -> Out,
|
||||
T: NewService<Req, Cfg>,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
{
|
||||
type Item = Apply<T::Service, F, In, Out, Request>;
|
||||
type Item = Apply<T::Service, Req, F, In, Out>;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
@@ -171,7 +171,8 @@ mod tests {
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::{IntoNewService, IntoService, NewService, Service};
|
||||
use super::*;
|
||||
use crate::{IntoService, NewService, Service, ServiceExt};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Srv;
|
||||
@@ -193,9 +194,11 @@ mod tests {
|
||||
fn test_call() {
|
||||
let blank = |req| Ok(req);
|
||||
|
||||
let mut srv = blank.into_service().apply(Srv, |req: &'static str, srv| {
|
||||
srv.call(()).map(move |res| (req, res))
|
||||
});
|
||||
let mut srv = blank
|
||||
.into_service()
|
||||
.apply_fn(Srv, |req: &'static str, srv| {
|
||||
srv.call(()).map(move |res| (req, res))
|
||||
});
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
let res = srv.call("srv").poll();
|
||||
assert!(res.is_ok());
|
||||
@@ -204,13 +207,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_new_service() {
|
||||
let blank = || Ok::<_, ()>((|req| Ok(req)).into_service());
|
||||
|
||||
let new_srv = blank.into_new_service().apply(
|
||||
|| Ok(Srv),
|
||||
let new_srv = ApplyNewService::new(
|
||||
|| Ok::<_, ()>(Srv),
|
||||
|req: &'static str, srv| srv.call(()).map(move |res| (req, res)),
|
||||
);
|
||||
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
|
||||
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
let res = srv.call("srv").poll();
|
||||
assert!(res.is_ok());
|
||||
|
81
actix-service/src/blank.rs
Normal file
81
actix-service/src/blank.rs
Normal file
@@ -0,0 +1,81 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Poll};
|
||||
|
||||
use super::{NewService, Service};
|
||||
|
||||
/// Empty service
|
||||
#[derive(Clone)]
|
||||
pub struct Blank<R, E> {
|
||||
_t: PhantomData<(R, E)>,
|
||||
}
|
||||
|
||||
impl<R, E> Blank<R, E> {
|
||||
pub fn err<E1>(self) -> Blank<R, E1> {
|
||||
Blank { _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<R> Blank<R, ()> {
|
||||
#[allow(clippy::new_ret_no_self)]
|
||||
pub fn new<E>() -> Blank<R, E> {
|
||||
Blank { _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, E> Default for Blank<R, E> {
|
||||
fn default() -> Blank<R, E> {
|
||||
Blank { _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, E> Service<R> for Blank<R, E> {
|
||||
type Response = R;
|
||||
type Error = E;
|
||||
type Future = FutureResult<R, E>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: R) -> Self::Future {
|
||||
ok(req)
|
||||
}
|
||||
}
|
||||
|
||||
/// Empty service factory
|
||||
pub struct BlankNewService<R, E1, E2 = ()> {
|
||||
_t: PhantomData<(R, E1, E2)>,
|
||||
}
|
||||
|
||||
impl<R, E1, E2> BlankNewService<R, E1, E2> {
|
||||
pub fn new() -> BlankNewService<R, E1, E2> {
|
||||
BlankNewService { _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, E1> BlankNewService<R, E1, ()> {
|
||||
pub fn new_unit() -> BlankNewService<R, E1, ()> {
|
||||
BlankNewService { _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, E1, E2> Default for BlankNewService<R, E1, E2> {
|
||||
fn default() -> BlankNewService<R, E1, E2> {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, E1, E2> NewService<R, ()> for BlankNewService<R, E1, E2> {
|
||||
type Response = R;
|
||||
type Error = E1;
|
||||
type Service = Blank<R, E1>;
|
||||
|
||||
type InitError = E2;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(Blank::default())
|
||||
}
|
||||
}
|
144
actix-service/src/boxed.rs
Normal file
144
actix-service/src/boxed.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use crate::{NewService, Service};
|
||||
use futures::{Future, IntoFuture, Poll};
|
||||
|
||||
pub type BoxedService<Req, Res, Err> = Box<
|
||||
Service<Req, Response = Res, Error = Err, Future = Box<Future<Item = Res, Error = Err>>>,
|
||||
>;
|
||||
|
||||
/// Create boxed new service
|
||||
pub fn new_service<T, R, C>(
|
||||
service: T,
|
||||
) -> BoxedNewService<C, R, T::Response, T::Error, T::InitError>
|
||||
where
|
||||
C: 'static,
|
||||
T: NewService<R, C> + 'static,
|
||||
T::Response: 'static,
|
||||
T::Service: 'static,
|
||||
T::Future: 'static,
|
||||
T::Error: 'static,
|
||||
T::InitError: 'static,
|
||||
R: 'static,
|
||||
{
|
||||
BoxedNewService(Box::new(NewServiceWrapper {
|
||||
service,
|
||||
_t: PhantomData,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Create boxed service
|
||||
pub fn service<T, R>(service: T) -> BoxedService<R, T::Response, T::Error>
|
||||
where
|
||||
T: Service<R> + 'static,
|
||||
T::Future: 'static,
|
||||
R: 'static,
|
||||
{
|
||||
Box::new(ServiceWrapper {
|
||||
service,
|
||||
_t: PhantomData,
|
||||
})
|
||||
}
|
||||
|
||||
type Inner<C, Req, Res, Err, InitErr> = Box<
|
||||
NewService<
|
||||
Req,
|
||||
C,
|
||||
Response = Res,
|
||||
Error = Err,
|
||||
InitError = InitErr,
|
||||
Service = BoxedService<Req, Res, Err>,
|
||||
Future = Box<Future<Item = BoxedService<Req, Res, Err>, Error = InitErr>>,
|
||||
>,
|
||||
>;
|
||||
|
||||
pub struct BoxedNewService<C, Req, Res, Err, InitErr>(Inner<C, Req, Res, Err, InitErr>);
|
||||
|
||||
impl<C, Req, Res, Err, InitErr> NewService<Req, C>
|
||||
for BoxedNewService<C, Req, Res, Err, InitErr>
|
||||
where
|
||||
Req: 'static,
|
||||
Res: 'static,
|
||||
Err: 'static,
|
||||
InitErr: 'static,
|
||||
{
|
||||
type Response = Res;
|
||||
type Error = Err;
|
||||
type InitError = InitErr;
|
||||
type Service = BoxedService<Req, Res, Err>;
|
||||
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
self.0.new_service(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
struct NewServiceWrapper<T: NewService<R, C>, R, C> {
|
||||
service: T,
|
||||
_t: std::marker::PhantomData<(R, C)>,
|
||||
}
|
||||
|
||||
impl<C, T, Req, Res, Err, InitErr> NewService<Req, C> for NewServiceWrapper<T, Req, C>
|
||||
where
|
||||
Req: 'static,
|
||||
Res: 'static,
|
||||
Err: 'static,
|
||||
InitErr: 'static,
|
||||
T: NewService<Req, C, Response = Res, Error = Err, InitError = InitErr>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service<Req>>::Future: 'static,
|
||||
{
|
||||
type Response = Res;
|
||||
type Error = Err;
|
||||
type InitError = InitErr;
|
||||
type Service = BoxedService<Req, Res, Err>;
|
||||
type Future = Box<Future<Item = Self::Service, Error = Self::InitError>>;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
Box::new(
|
||||
self.service
|
||||
.new_service(cfg)
|
||||
.into_future()
|
||||
.map(ServiceWrapper::boxed),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct ServiceWrapper<T: Service<R>, R> {
|
||||
service: T,
|
||||
_t: PhantomData<R>,
|
||||
}
|
||||
|
||||
impl<T, R> ServiceWrapper<T, R>
|
||||
where
|
||||
T: Service<R> + 'static,
|
||||
T::Future: 'static,
|
||||
R: 'static,
|
||||
{
|
||||
fn boxed(service: T) -> BoxedService<R, T::Response, T::Error> {
|
||||
Box::new(ServiceWrapper {
|
||||
service,
|
||||
_t: PhantomData,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Req, Res, Err> Service<Req> for ServiceWrapper<T, Req>
|
||||
where
|
||||
T: Service<Req, Response = Res, Error = Err>,
|
||||
T::Future: 'static,
|
||||
Req: 'static,
|
||||
{
|
||||
type Response = Res;
|
||||
type Error = Err;
|
||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Req) -> Self::Future {
|
||||
Box::new(self.service.call(req))
|
||||
}
|
||||
}
|
@@ -1,55 +1,79 @@
|
||||
use std::marker;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{
|
||||
future::{ok, FutureResult},
|
||||
Async, IntoFuture, Poll,
|
||||
};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, IntoFuture, Poll};
|
||||
|
||||
use super::{IntoNewService, IntoService, NewService, Service};
|
||||
use crate::{IntoConfigurableNewService, IntoNewService, IntoService, NewService, Service};
|
||||
|
||||
pub struct FnService<F, Req, Resp, E, Fut>
|
||||
/// Create `NewService` for function that can act as Service
|
||||
pub fn fn_service<F, Req, Out, Cfg>(f: F) -> FnNewService<F, Req, Out, Cfg>
|
||||
where
|
||||
F: Fn(Req) -> Fut,
|
||||
Fut: IntoFuture<Item = Resp, Error = E>,
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
f: F,
|
||||
_t: marker::PhantomData<(Req, Resp, E)>,
|
||||
FnNewService::new(f)
|
||||
}
|
||||
|
||||
impl<F, Req, Resp, E, Fut> FnService<F, Req, Resp, E, Fut>
|
||||
/// Create `NewService` for function that can produce services
|
||||
pub fn fn_factory<F, R, S, E, Req>(f: F) -> FnNewServiceNoConfig<F, R, S, E, Req>
|
||||
where
|
||||
F: Fn(Req) -> Fut,
|
||||
Fut: IntoFuture<Item = Resp, Error = E>,
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
FnNewServiceNoConfig::new(f)
|
||||
}
|
||||
|
||||
/// Create `NewService` for function that can produce services with configuration
|
||||
pub fn fn_cfg_factory<F, C, R, S, E, Req>(f: F) -> FnNewServiceConfig<F, C, R, S, E, Req>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
FnNewServiceConfig::new(f)
|
||||
}
|
||||
|
||||
pub struct FnService<F, Req, Out>
|
||||
where
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(Req,)>,
|
||||
}
|
||||
|
||||
impl<F, Req, Out> FnService<F, Req, Out>
|
||||
where
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnService {
|
||||
f,
|
||||
_t: marker::PhantomData,
|
||||
}
|
||||
FnService { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Resp, E, Fut> Clone for FnService<F, Req, Resp, E, Fut>
|
||||
impl<F, Req, Out> Clone for FnService<F, Req, Out>
|
||||
where
|
||||
F: Fn(Req) -> Fut + Clone,
|
||||
Fut: IntoFuture<Item = Resp, Error = E>,
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
FnService {
|
||||
f: self.f.clone(),
|
||||
_t: marker::PhantomData,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Resp, E, Fut> Service<Req> for FnService<F, Req, Resp, E, Fut>
|
||||
impl<F, Req, Out> Service<Req> for FnService<F, Req, Out>
|
||||
where
|
||||
F: Fn(Req) -> Fut,
|
||||
Fut: IntoFuture<Item = Resp, Error = E>,
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
type Response = Resp;
|
||||
type Error = E;
|
||||
type Future = Fut::Future;
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
type Future = Out::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
@@ -60,70 +84,210 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Resp, Err, Fut> IntoService<FnService<F, Req, Resp, Err, Fut>, Req> for F
|
||||
impl<F, Req, Out> IntoService<FnService<F, Req, Out>, Req> for F
|
||||
where
|
||||
F: Fn(Req) -> Fut + 'static,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
F: FnMut(Req) -> Out + 'static,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn into_service(self) -> FnService<F, Req, Resp, Err, Fut> {
|
||||
fn into_service(self) -> FnService<F, Req, Out> {
|
||||
FnService::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FnNewService<F, Req, Resp, Err, Fut>
|
||||
pub struct FnNewService<F, Req, Out, Cfg>
|
||||
where
|
||||
F: Fn(Req) -> Fut,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
f: F,
|
||||
_t: marker::PhantomData<(Req, Resp, Err)>,
|
||||
_t: PhantomData<(Req, Cfg)>,
|
||||
}
|
||||
|
||||
impl<F, Req, Resp, Err, Fut> FnNewService<F, Req, Resp, Err, Fut>
|
||||
impl<F, Req, Out, Cfg> FnNewService<F, Req, Out, Cfg>
|
||||
where
|
||||
F: Fn(Req) -> Fut + Clone,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewService {
|
||||
f,
|
||||
_t: marker::PhantomData,
|
||||
}
|
||||
FnNewService { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Resp, Err, Fut> NewService<Req> for FnNewService<F, Req, Resp, Err, Fut>
|
||||
impl<F, Req, Out, Cfg> NewService<Req, Cfg> for FnNewService<F, Req, Out, Cfg>
|
||||
where
|
||||
F: Fn(Req) -> Fut + Clone,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
type Response = Resp;
|
||||
type Error = Err;
|
||||
type Service = FnService<F, Req, Resp, Err, Fut>;
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
type Service = FnService<F, Req, Out>;
|
||||
|
||||
type InitError = ();
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
fn new_service(&self, _: &Cfg) -> Self::Future {
|
||||
ok(FnService::new(self.f.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Resp, Err, Fut> IntoNewService<FnNewService<F, Req, Resp, Err, Fut>, Req> for F
|
||||
impl<F, Req, Out, Cfg> Clone for FnNewService<F, Req, Out, Cfg>
|
||||
where
|
||||
F: Fn(Req) -> Fut + Clone + 'static,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewService<F, Req, Resp, Err, Fut> {
|
||||
FnNewService::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Resp, Err, Fut> Clone for FnNewService<F, Req, Resp, Err, Fut>
|
||||
where
|
||||
F: Fn(Req) -> Fut + Clone,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Out, Cfg> IntoNewService<FnNewService<F, Req, Out, Cfg>, Req, 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, Req>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<Req>,
|
||||
}
|
||||
|
||||
impl<F, R, S, E, Req> FnNewServiceNoConfig<F, R, S, E, Req>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewServiceNoConfig { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, S, E, Req> NewService<Req, ()> for FnNewServiceNoConfig<F, R, S, E, Req>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
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, Req> Clone for FnNewServiceNoConfig<F, R, S, E, Req>
|
||||
where
|
||||
F: Fn() -> R + Clone,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, S, E, Req> IntoNewService<FnNewServiceNoConfig<F, R, S, E, Req>, Req, ()> for F
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewServiceNoConfig<F, R, S, E, Req> {
|
||||
FnNewServiceNoConfig::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
|
||||
pub struct FnNewServiceConfig<F, C, R, S, E, Req>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(C, R, S, E, Req)>,
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E, Req> FnNewServiceConfig<F, C, R, S, E, Req>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewServiceConfig { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E, Req> NewService<Req, C> for FnNewServiceConfig<F, C, R, S, E, Req>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S;
|
||||
|
||||
type InitError = E;
|
||||
type Future = R::Future;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
(self.f)(cfg).into_future()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E, Req> Clone for FnNewServiceConfig<F, C, R, S, E, Req>
|
||||
where
|
||||
F: Fn(&C) -> R + Clone,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E, Req>
|
||||
IntoConfigurableNewService<FnNewServiceConfig<F, C, R, S, E, Req>, Req, C> for F
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Req>,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewServiceConfig<F, C, R, S, E, Req> {
|
||||
FnNewServiceConfig::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::{IntoService, Service, ServiceExt};
|
||||
|
||||
#[test]
|
||||
fn test_fn_service() {
|
||||
let mut rt = actix_rt::Runtime::new().unwrap();
|
||||
|
||||
let srv = (|_t: &str| -> Result<usize, ()> { Ok(1) }).into_service();
|
||||
let mut srv = srv.and_then(|test: usize| Ok(test));
|
||||
|
||||
let s = "HELLO".to_owned();
|
||||
let res = rt.block_on(srv.call(&s)).unwrap();
|
||||
assert_eq!(res, 1);
|
||||
}
|
||||
}
|
||||
|
65
actix-service/src/fn_transform.rs
Normal file
65
actix-service/src/fn_transform.rs
Normal file
@@ -0,0 +1,65 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::IntoFuture;
|
||||
|
||||
use crate::{Apply, IntoTransform, Service, Transform};
|
||||
|
||||
pub struct FnTransform<F, S, R, In, Out, Err>
|
||||
where
|
||||
F: FnMut(In, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(S, R, In, Out, Err)>,
|
||||
}
|
||||
|
||||
impl<F, S, R, In, Out, Err> FnTransform<F, S, R, In, Out, Err>
|
||||
where
|
||||
F: FnMut(In, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnTransform { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, R, In, Out, Err> Transform<S, In> for FnTransform<F, S, R, In, Out, Err>
|
||||
where
|
||||
S: Service<R>,
|
||||
F: FnMut(In, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<S::Error>,
|
||||
{
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
type Transform = Apply<S, R, F, In, Out>;
|
||||
type InitError = Err;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ok(Apply::new(service, self.f.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, R, In, Out, Err> IntoTransform<FnTransform<F, S, R, In, Out, Err>, S, In> for F
|
||||
where
|
||||
S: Service<R>,
|
||||
F: FnMut(In, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<S::Error>,
|
||||
{
|
||||
fn into_transform(self) -> FnTransform<F, S, R, In, Out, Err> {
|
||||
FnTransform::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, R, In, Out, Err> Clone for FnTransform<F, S, R, In, Out, Err>
|
||||
where
|
||||
F: FnMut(In, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
}
|
||||
}
|
@@ -13,9 +13,9 @@ pub struct FromErr<A, E> {
|
||||
}
|
||||
|
||||
impl<A, E> FromErr<A, E> {
|
||||
pub(crate) fn new<Request>(service: A) -> Self
|
||||
pub(crate) fn new<R>(service: A) -> Self
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
FromErr {
|
||||
@@ -37,20 +37,20 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, E, Request> Service<Request> for FromErr<A, E>
|
||||
impl<A, E, R> Service<R> for FromErr<A, E>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
type Response = A::Response;
|
||||
type Error = E;
|
||||
type Future = FromErrFuture<A, E, Request>;
|
||||
type Future = FromErrFuture<A, R, E>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), E> {
|
||||
Ok(self.service.poll_ready().map_err(E::from)?)
|
||||
self.service.poll_ready().map_err(E::from)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request) -> Self::Future {
|
||||
fn call(&mut self, req: R) -> Self::Future {
|
||||
FromErrFuture {
|
||||
fut: self.service.call(req),
|
||||
f: PhantomData,
|
||||
@@ -58,14 +58,14 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FromErrFuture<A: Service<Request>, E, Request> {
|
||||
pub struct FromErrFuture<A: Service<R>, R, E> {
|
||||
fut: A::Future,
|
||||
f: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<A, E, Request> Future for FromErrFuture<A, E, Request>
|
||||
impl<A, R, E> Future for FromErrFuture<A, R, E>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
type Item = A::Response;
|
||||
@@ -80,23 +80,23 @@ where
|
||||
/// service's error.
|
||||
///
|
||||
/// This is created by the `NewServiceExt::from_err` method.
|
||||
pub struct FromErrNewService<A, E> {
|
||||
pub struct FromErrNewService<A, E, C> {
|
||||
a: A,
|
||||
e: PhantomData<E>,
|
||||
e: PhantomData<(E, C)>,
|
||||
}
|
||||
|
||||
impl<A, E> FromErrNewService<A, E> {
|
||||
impl<A, E, C> FromErrNewService<A, E, C> {
|
||||
/// Create new `FromErr` new service instance
|
||||
pub fn new<Request>(a: A) -> Self
|
||||
pub fn new<R>(a: A) -> Self
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
Self { a, e: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, E> Clone for FromErrNewService<A, E>
|
||||
impl<A, E, C> Clone for FromErrNewService<A, E, C>
|
||||
where
|
||||
A: Clone,
|
||||
{
|
||||
@@ -108,9 +108,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, E, Request> NewService<Request> for FromErrNewService<A, E>
|
||||
impl<A, E, C, R> NewService<R, C> for FromErrNewService<A, E, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
type Response = A::Response;
|
||||
@@ -118,28 +118,28 @@ where
|
||||
type Service = FromErr<A::Service, E>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = FromErrNewServiceFuture<A, E, Request>;
|
||||
type Future = FromErrNewServiceFuture<A, E, C, R>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
FromErrNewServiceFuture {
|
||||
fut: self.a.new_service(),
|
||||
fut: self.a.new_service(cfg),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FromErrNewServiceFuture<A, E, Request>
|
||||
pub struct FromErrNewServiceFuture<A, E, C, R>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
fut: A::Future,
|
||||
e: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<A, E, Request> Future for FromErrNewServiceFuture<A, E, Request>
|
||||
impl<A, E, C, R> Future for FromErrNewServiceFuture<A, E, C, R>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
type Item = FromErr<A::Service, E>;
|
||||
@@ -159,7 +159,7 @@ mod tests {
|
||||
use futures::future::{err, FutureResult};
|
||||
|
||||
use super::*;
|
||||
use crate::{IntoNewService, NewService, Service};
|
||||
use crate::{IntoNewService, NewService, Service, ServiceExt};
|
||||
|
||||
struct Srv;
|
||||
impl Service<()> for Srv {
|
||||
@@ -205,7 +205,7 @@ mod tests {
|
||||
fn test_new_service() {
|
||||
let blank = || Ok::<_, ()>(Srv);
|
||||
let new_srv = blank.into_new_service().from_err::<Error>();
|
||||
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
|
||||
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
|
||||
let res = srv.call(()).poll();
|
||||
assert!(res.is_err());
|
||||
assert_eq!(res.err().unwrap(), Error);
|
||||
|
@@ -1,24 +1,43 @@
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures::{Future, IntoFuture, Poll};
|
||||
|
||||
pub use void::Void;
|
||||
|
||||
mod and_then;
|
||||
mod and_then_apply;
|
||||
mod and_then_apply_fn;
|
||||
mod apply;
|
||||
pub mod blank;
|
||||
pub mod boxed;
|
||||
mod cell;
|
||||
mod fn_service;
|
||||
mod fn_transform;
|
||||
mod from_err;
|
||||
mod map;
|
||||
mod map_err;
|
||||
mod map_init_err;
|
||||
mod then;
|
||||
mod transform;
|
||||
mod transform_map_init_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::fn_service::{FnNewService, FnService};
|
||||
pub use self::fn_service::{fn_cfg_factory, fn_factory, fn_service, FnService};
|
||||
pub use self::fn_transform::FnTransform;
|
||||
pub use self::from_err::{FromErr, FromErrNewService};
|
||||
pub use self::map::{Map, MapNewService};
|
||||
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};
|
||||
|
||||
/// An asynchronous function from `Request` to a `Response`.
|
||||
///
|
||||
/// `Request` - requests handled by the service.
|
||||
pub trait Service<Request> {
|
||||
/// Responses given by the service.
|
||||
type Response;
|
||||
@@ -57,19 +76,20 @@ pub trait Service<Request> {
|
||||
pub trait ServiceExt<Request>: Service<Request> {
|
||||
/// Apply function to specified service and use it as a next service in
|
||||
/// chain.
|
||||
fn apply<T, I, F, Out, Req>(
|
||||
fn apply_fn<F, B, B1, Out, Req>(
|
||||
self,
|
||||
service: I,
|
||||
service: B1,
|
||||
f: F,
|
||||
) -> AndThen<Self, Apply<T, F, Self::Response, Out, Req>>
|
||||
) -> AndThenApply<Self, B, F, Out, Request, Req>
|
||||
where
|
||||
Self: Sized,
|
||||
T: Service<Req, Error = Self::Error>,
|
||||
I: IntoService<T, Req>,
|
||||
F: Fn(Self::Response, &mut T) -> Out,
|
||||
Out: IntoFuture<Error = Self::Error>,
|
||||
F: FnMut(Self::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<Self::Error>,
|
||||
B: Service<Req, Error = Self::Error>,
|
||||
B1: IntoService<B, Req>,
|
||||
{
|
||||
self.and_then(Apply::new(service.into_service(), f))
|
||||
AndThenApply::new(self, service, f)
|
||||
}
|
||||
|
||||
/// Call another service after call to this one has resolved successfully.
|
||||
@@ -128,7 +148,7 @@ pub trait ServiceExt<Request>: Service<Request> {
|
||||
fn map<F, R>(self, f: F) -> Map<Self, F, R>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::Response) -> R,
|
||||
F: FnMut(Self::Response) -> R,
|
||||
{
|
||||
Map::new(self, f)
|
||||
}
|
||||
@@ -150,7 +170,7 @@ pub trait ServiceExt<Request>: Service<Request> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ?Sized, Request> ServiceExt<Request> for T where T: Service<Request> {}
|
||||
impl<T: ?Sized, R> ServiceExt<R> for T where T: Service<R> {}
|
||||
|
||||
/// Creates new `Service` values.
|
||||
///
|
||||
@@ -160,8 +180,9 @@ impl<T: ?Sized, Request> ServiceExt<Request> for T where T: Service<Request> {}
|
||||
/// `NewService` trait, and uses that new `Service` value to process inbound
|
||||
/// requests on that new TCP stream.
|
||||
///
|
||||
/// Request - request handled by the service
|
||||
pub trait NewService<Request> {
|
||||
/// * `Request` - requests handled by the service.
|
||||
/// * `Config` - is a service factory configuration type.
|
||||
pub trait NewService<Request, Config = ()> {
|
||||
/// Responses given by the service
|
||||
type Response;
|
||||
|
||||
@@ -178,31 +199,50 @@ pub trait NewService<Request> {
|
||||
type Future: Future<Item = Self::Service, Error = Self::InitError>;
|
||||
|
||||
/// Create and return a new service value asynchronously.
|
||||
fn new_service(&self) -> Self::Future;
|
||||
fn new_service(&self, cfg: &Config) -> Self::Future;
|
||||
|
||||
/// Apply function to specified service and use it as a next service in
|
||||
/// chain.
|
||||
fn apply<T, I, F, Out, Req>(
|
||||
fn apply<T, T1, B, B1, Req>(
|
||||
self,
|
||||
transform: T1,
|
||||
service: B1,
|
||||
) -> AndThenTransform<T, Self, B, Req>
|
||||
where
|
||||
Self: Sized,
|
||||
T: Transform<B::Service, Self::Response, InitError = Self::InitError>,
|
||||
T::Error: From<Self::Error>,
|
||||
T1: IntoTransform<T, B::Service, Self::Response>,
|
||||
B: NewService<Req, Config, InitError = Self::InitError>,
|
||||
B1: IntoNewService<B, Req, Config>,
|
||||
{
|
||||
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, Req>(
|
||||
self,
|
||||
service: I,
|
||||
f: F,
|
||||
) -> AndThenNewService<Self, ApplyNewService<T, F, Self::Response, Out, Req>>
|
||||
) -> AndThenApplyNewService<Self, B, F, Out, Request, Req, Config>
|
||||
where
|
||||
Self: Sized,
|
||||
T: NewService<Req, InitError = Self::InitError, Error = Self::Error>,
|
||||
I: IntoNewService<T, Req>,
|
||||
F: Fn(Self::Response, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture<Error = Self::Error>,
|
||||
B: NewService<Req, Config, Error = Self::Error, InitError = Self::InitError>,
|
||||
I: IntoNewService<B, Req, Config>,
|
||||
F: FnMut(Self::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<Self::Error>,
|
||||
{
|
||||
self.and_then(ApplyNewService::new(service, f))
|
||||
AndThenApplyNewService::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>
|
||||
where
|
||||
Self: Sized,
|
||||
F: IntoNewService<B, Self::Response>,
|
||||
B: NewService<Self::Response, Error = Self::Error, InitError = Self::InitError>,
|
||||
F: IntoNewService<B, Self::Response, Config>,
|
||||
B: NewService<Self::Response, Config, Error = Self::Error, InitError = Self::InitError>,
|
||||
{
|
||||
AndThenNewService::new(self, new_service)
|
||||
}
|
||||
@@ -213,7 +253,7 @@ pub trait NewService<Request> {
|
||||
///
|
||||
/// Note that this function consumes the receiving new service and returns a
|
||||
/// wrapped version of it.
|
||||
fn from_err<E>(self) -> FromErrNewService<Self, E>
|
||||
fn from_err<E>(self) -> FromErrNewService<Self, E, Config>
|
||||
where
|
||||
Self: Sized,
|
||||
E: From<Self::Error>,
|
||||
@@ -227,31 +267,32 @@ pub trait NewService<Request> {
|
||||
///
|
||||
/// 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>
|
||||
fn then<F, B>(self, new_service: F) -> ThenNewService<Self, B, Config>
|
||||
where
|
||||
Self: Sized,
|
||||
F: IntoNewService<B, Result<Self::Response, Self::Error>>,
|
||||
F: IntoNewService<B, Result<Self::Response, Self::Error>, Config>,
|
||||
B: NewService<
|
||||
Result<Self::Response, Self::Error>,
|
||||
Config,
|
||||
Error = Self::Error,
|
||||
InitError = Self::InitError,
|
||||
>,
|
||||
{
|
||||
ThenNewService::new(self, new_service)
|
||||
ThenNewService::new(self, new_service.into_new_service())
|
||||
}
|
||||
|
||||
/// Map this service's output to a different type, returning a new service
|
||||
/// of the resulting type.
|
||||
fn map<F, R>(self, f: F) -> MapNewService<Self, F, R>
|
||||
fn map<F, R>(self, f: F) -> MapNewService<Self, F, R, Config>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::Response) -> R,
|
||||
F: FnMut(Self::Response) -> R,
|
||||
{
|
||||
MapNewService::new(self, f)
|
||||
}
|
||||
|
||||
/// Map this service's error to a different error, returning a new service.
|
||||
fn map_err<F, E>(self, f: F) -> MapErrNewService<Self, F, E>
|
||||
fn map_err<F, E>(self, f: F) -> MapErrNewService<Self, F, E, Config>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::Error) -> E,
|
||||
@@ -260,7 +301,7 @@ pub trait NewService<Request> {
|
||||
}
|
||||
|
||||
/// Map this service's init error to a different error, returning a new service.
|
||||
fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, E>
|
||||
fn map_init_err<F, E>(self, f: F) -> MapInitErr<Self, F, E, Config>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::InitError) -> E,
|
||||
@@ -269,9 +310,9 @@ pub trait NewService<Request> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, S, Request> Service<Request> for &'a mut S
|
||||
impl<'a, S, R> Service<R> for &'a mut S
|
||||
where
|
||||
S: Service<Request> + 'a,
|
||||
S: Service<R> + 'a,
|
||||
{
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
@@ -281,14 +322,14 @@ where
|
||||
(**self).poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Request) -> S::Future {
|
||||
fn call(&mut self, request: R) -> S::Future {
|
||||
(**self).call(request)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, Request> Service<Request> for Box<S>
|
||||
impl<S, R> Service<R> for Box<S>
|
||||
where
|
||||
S: Service<Request> + ?Sized,
|
||||
S: Service<R> + ?Sized,
|
||||
{
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
@@ -298,58 +339,89 @@ where
|
||||
(**self).poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Request) -> S::Future {
|
||||
fn call(&mut self, request: R) -> S::Future {
|
||||
(**self).call(request)
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, E, S, Request> NewService<Request> for F
|
||||
impl<S, R, C> NewService<R, C> for Rc<S>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service<Request>,
|
||||
S: NewService<R, C>,
|
||||
{
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S;
|
||||
type InitError = E;
|
||||
type Future = R::Future;
|
||||
type Service = S::Service;
|
||||
type InitError = S::InitError;
|
||||
type Future = S::Future;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
(*self)().into_future()
|
||||
fn new_service(&self, cfg: &C) -> S::Future {
|
||||
self.as_ref().new_service(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, R, C> NewService<R, C> for Arc<S>
|
||||
where
|
||||
S: NewService<R, C>,
|
||||
{
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S::Service;
|
||||
type InitError = S::InitError;
|
||||
type Future = S::Future;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> S::Future {
|
||||
self.as_ref().new_service(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a `Service`
|
||||
pub trait IntoService<T, Request>
|
||||
pub trait IntoService<T, R>
|
||||
where
|
||||
T: Service<Request>,
|
||||
T: Service<R>,
|
||||
{
|
||||
/// Convert to a `Service`
|
||||
fn into_service(self) -> T;
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a Service
|
||||
pub trait IntoNewService<T, Request>
|
||||
/// Trait for types that can be converted to a `NewService`
|
||||
pub trait IntoNewService<T, R, C = ()>
|
||||
where
|
||||
T: NewService<Request>,
|
||||
T: NewService<R, C>,
|
||||
{
|
||||
/// Convert to an `NewService`
|
||||
fn into_new_service(self) -> T;
|
||||
}
|
||||
|
||||
impl<T, Request> IntoService<T, Request> for T
|
||||
impl<T, R> IntoService<T, R> for T
|
||||
where
|
||||
T: Service<Request>,
|
||||
T: Service<R>,
|
||||
{
|
||||
fn into_service(self) -> T {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Request> IntoNewService<T, Request> for T
|
||||
impl<T, R, C> IntoNewService<T, R, C> for T
|
||||
where
|
||||
T: NewService<Request>,
|
||||
T: NewService<R, C>,
|
||||
{
|
||||
fn into_new_service(self) -> T {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a configurable `NewService`
|
||||
pub trait IntoConfigurableNewService<T, R, C>
|
||||
where
|
||||
T: NewService<R, C>,
|
||||
{
|
||||
/// Convert to an `NewService`
|
||||
fn into_new_service(self) -> T;
|
||||
}
|
||||
|
||||
impl<T, R, C> IntoConfigurableNewService<T, R, C> for T
|
||||
where
|
||||
T: NewService<R, C>,
|
||||
{
|
||||
fn into_new_service(self) -> T {
|
||||
self
|
||||
|
@@ -15,10 +15,10 @@ pub struct Map<A, F, Response> {
|
||||
|
||||
impl<A, F, Response> Map<A, F, Response> {
|
||||
/// Create new `Map` combinator
|
||||
pub fn new<Request>(service: A, f: F) -> Self
|
||||
pub fn new<R>(service: A, f: F) -> Self
|
||||
where
|
||||
A: Service<Request>,
|
||||
F: Fn(A::Response) -> Response,
|
||||
A: Service<R>,
|
||||
F: FnMut(A::Response) -> Response,
|
||||
{
|
||||
Self {
|
||||
service,
|
||||
@@ -42,47 +42,47 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Request, Response> Service<Request> for Map<A, F, Response>
|
||||
impl<A, F, R, Response> Service<R> for Map<A, F, Response>
|
||||
where
|
||||
A: Service<Request>,
|
||||
F: Fn(A::Response) -> Response + Clone,
|
||||
A: Service<R>,
|
||||
F: FnMut(A::Response) -> Response + Clone,
|
||||
{
|
||||
type Response = Response;
|
||||
type Error = A::Error;
|
||||
type Future = MapFuture<A, F, Request, Response>;
|
||||
type Future = MapFuture<A, F, R, Response>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request) -> Self::Future {
|
||||
fn call(&mut self, req: R) -> Self::Future {
|
||||
MapFuture::new(self.service.call(req), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapFuture<A, F, Request, Response>
|
||||
pub struct MapFuture<A, F, R, Response>
|
||||
where
|
||||
A: Service<Request>,
|
||||
F: Fn(A::Response) -> Response,
|
||||
A: Service<R>,
|
||||
F: FnMut(A::Response) -> Response,
|
||||
{
|
||||
f: F,
|
||||
fut: A::Future,
|
||||
}
|
||||
|
||||
impl<A, F, Request, Response> MapFuture<A, F, Request, Response>
|
||||
impl<A, F, R, Response> MapFuture<A, F, R, Response>
|
||||
where
|
||||
A: Service<Request>,
|
||||
F: Fn(A::Response) -> Response,
|
||||
A: Service<R>,
|
||||
F: FnMut(A::Response) -> Response,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
MapFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Request, Response> Future for MapFuture<A, F, Request, Response>
|
||||
impl<A, F, R, Response> Future for MapFuture<A, F, R, Response>
|
||||
where
|
||||
A: Service<Request>,
|
||||
F: Fn(A::Response) -> Response,
|
||||
A: Service<R>,
|
||||
F: FnMut(A::Response) -> Response,
|
||||
{
|
||||
type Item = Response;
|
||||
type Error = A::Error;
|
||||
@@ -96,18 +96,18 @@ where
|
||||
}
|
||||
|
||||
/// `MapNewService` new service combinator
|
||||
pub struct MapNewService<A, F, Response> {
|
||||
pub struct MapNewService<A, F, Res, Cfg> {
|
||||
a: A,
|
||||
f: F,
|
||||
r: PhantomData<Response>,
|
||||
r: PhantomData<(Res, Cfg)>,
|
||||
}
|
||||
|
||||
impl<A, F, Response> MapNewService<A, F, Response> {
|
||||
impl<A, F, Res, Cfg> MapNewService<A, F, Res, Cfg> {
|
||||
/// Create new `Map` new service instance
|
||||
pub fn new<Request>(a: A, f: F) -> Self
|
||||
pub fn new<Req>(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService<Request>,
|
||||
F: Fn(A::Response) -> Response,
|
||||
A: NewService<Req, Cfg>,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
Self {
|
||||
a,
|
||||
@@ -117,7 +117,7 @@ impl<A, F, Response> MapNewService<A, F, Response> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Response> Clone for MapNewService<A, F, Response>
|
||||
impl<A, F, Res, Cfg> Clone for MapNewService<A, F, Res, Cfg>
|
||||
where
|
||||
A: Clone,
|
||||
F: Clone,
|
||||
@@ -131,48 +131,48 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Request, Response> NewService<Request> for MapNewService<A, F, Response>
|
||||
impl<A, F, Req, Res, Cfg> NewService<Req, Cfg> for MapNewService<A, F, Res, Cfg>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
F: Fn(A::Response) -> Response + Clone,
|
||||
A: NewService<Req, Cfg>,
|
||||
F: FnMut(A::Response) -> Res + Clone,
|
||||
{
|
||||
type Response = Response;
|
||||
type Response = Res;
|
||||
type Error = A::Error;
|
||||
type Service = Map<A::Service, F, Response>;
|
||||
type Service = Map<A::Service, F, Res>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = MapNewServiceFuture<A, F, Request, Response>;
|
||||
type Future = MapNewServiceFuture<A, F, Req, Res, Cfg>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
MapNewServiceFuture::new(self.a.new_service(), self.f.clone())
|
||||
fn new_service(&self, cfg: &Cfg) -> Self::Future {
|
||||
MapNewServiceFuture::new(self.a.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapNewServiceFuture<A, F, Request, Response>
|
||||
pub struct MapNewServiceFuture<A, F, Req, Res, Cfg>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
F: Fn(A::Response) -> Response,
|
||||
A: NewService<Req, Cfg>,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
fut: A::Future,
|
||||
f: Option<F>,
|
||||
}
|
||||
|
||||
impl<A, F, Request, Response> MapNewServiceFuture<A, F, Request, Response>
|
||||
impl<A, F, Req, Res, Cfg> MapNewServiceFuture<A, F, Req, Res, Cfg>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
F: Fn(A::Response) -> Response,
|
||||
A: NewService<Req, Cfg>,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
MapNewServiceFuture { f: Some(f), fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Request, Response> Future for MapNewServiceFuture<A, F, Request, Response>
|
||||
impl<A, F, Req, Res, Cfg> Future for MapNewServiceFuture<A, F, Req, Res, Cfg>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
F: Fn(A::Response) -> Response,
|
||||
A: NewService<Req, Cfg>,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
type Item = Map<A::Service, F, Response>;
|
||||
type Item = Map<A::Service, F, Res>;
|
||||
type Error = A::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
@@ -189,7 +189,7 @@ mod tests {
|
||||
use futures::future::{ok, FutureResult};
|
||||
|
||||
use super::*;
|
||||
use crate::{IntoNewService, Service};
|
||||
use crate::{IntoNewService, Service, ServiceExt};
|
||||
|
||||
struct Srv;
|
||||
impl Service<()> for Srv {
|
||||
@@ -226,7 +226,7 @@ mod tests {
|
||||
fn test_new_service() {
|
||||
let blank = || Ok::<_, ()>(Srv);
|
||||
let new_srv = blank.into_new_service().map(|_| "ok");
|
||||
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
|
||||
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
|
||||
let res = srv.call(()).poll();
|
||||
assert!(res.is_ok());
|
||||
assert_eq!(res.unwrap(), Async::Ready("ok"));
|
||||
|
@@ -16,9 +16,9 @@ pub struct MapErr<A, F, E> {
|
||||
|
||||
impl<A, F, E> MapErr<A, F, E> {
|
||||
/// Create new `MapErr` combinator
|
||||
pub fn new<Request>(service: A, f: F) -> Self
|
||||
pub fn new<R>(service: A, f: F) -> Self
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
Self {
|
||||
@@ -43,46 +43,39 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, Request> Service<Request> for MapErr<A, F, E>
|
||||
impl<A, F, E, R> Service<R> for MapErr<A, F, E>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
type Response = A::Response;
|
||||
type Error = E;
|
||||
type Future = MapErrFuture<A, F, E, Request>;
|
||||
type Future = MapErrFuture<A, F, E, R>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready().map_err(&self.f)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request) -> Self::Future {
|
||||
MapErrFuture::new(self.service.call(req), self.f.clone())
|
||||
fn call(&mut self, req: R) -> Self::Future {
|
||||
MapErrFuture {
|
||||
fut: self.service.call(req),
|
||||
f: self.f.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapErrFuture<A, F, E, Request>
|
||||
pub struct MapErrFuture<A, F, E, R>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
f: F,
|
||||
fut: A::Future,
|
||||
}
|
||||
|
||||
impl<A, F, E, Request> MapErrFuture<A, F, E, Request>
|
||||
impl<A, F, E, R> Future for MapErrFuture<A, F, E, R>
|
||||
where
|
||||
A: Service<Request>,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
MapErrFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, Request> Future for MapErrFuture<A, F, E, Request>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
type Item = A::Response;
|
||||
@@ -97,17 +90,17 @@ where
|
||||
/// service's error.
|
||||
///
|
||||
/// This is created by the `NewServiceExt::map_err` method.
|
||||
pub struct MapErrNewService<A, F, E> {
|
||||
pub struct MapErrNewService<A, F, E, C> {
|
||||
a: A,
|
||||
f: F,
|
||||
e: PhantomData<E>,
|
||||
e: PhantomData<(E, C)>,
|
||||
}
|
||||
|
||||
impl<A, F, E> MapErrNewService<A, F, E> {
|
||||
impl<A, F, E, C> MapErrNewService<A, F, E, C> {
|
||||
/// Create new `MapErr` new service instance
|
||||
pub fn new<Request>(a: A, f: F) -> Self
|
||||
pub fn new<R>(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
Self {
|
||||
@@ -118,7 +111,7 @@ impl<A, F, E> MapErrNewService<A, F, E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E> Clone for MapErrNewService<A, F, E>
|
||||
impl<A, F, E, C> Clone for MapErrNewService<A, F, E, C>
|
||||
where
|
||||
A: Clone,
|
||||
F: Clone,
|
||||
@@ -132,9 +125,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, Request> NewService<Request> for MapErrNewService<A, F, E>
|
||||
impl<A, F, E, R, C> NewService<R, C> for MapErrNewService<A, F, E, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
type Response = A::Response;
|
||||
@@ -142,25 +135,25 @@ where
|
||||
type Service = MapErr<A::Service, F, E>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = MapErrNewServiceFuture<A, F, E, Request>;
|
||||
type Future = MapErrNewServiceFuture<A, F, E, R, C>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
MapErrNewServiceFuture::new(self.a.new_service(), self.f.clone())
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
MapErrNewServiceFuture::new(self.a.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapErrNewServiceFuture<A, F, E, Request>
|
||||
pub struct MapErrNewServiceFuture<A, F, E, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
fut: A::Future,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<A, F, E, Request> MapErrNewServiceFuture<A, F, E, Request>
|
||||
impl<A, F, E, R, C> MapErrNewServiceFuture<A, F, E, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
@@ -168,9 +161,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, Request> Future for MapErrNewServiceFuture<A, F, E, Request>
|
||||
impl<A, F, E, R, C> Future for MapErrNewServiceFuture<A, F, E, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
type Item = MapErr<A::Service, F, E>;
|
||||
@@ -190,7 +183,7 @@ mod tests {
|
||||
use futures::future::{err, FutureResult};
|
||||
|
||||
use super::*;
|
||||
use crate::{IntoNewService, NewService, Service};
|
||||
use crate::{IntoNewService, NewService, Service, ServiceExt};
|
||||
|
||||
struct Srv;
|
||||
|
||||
@@ -228,7 +221,7 @@ mod tests {
|
||||
fn test_new_service() {
|
||||
let blank = || Ok::<_, ()>(Srv);
|
||||
let new_srv = blank.into_new_service().map_err(|_| "error");
|
||||
if let Async::Ready(mut srv) = new_srv.new_service().poll().unwrap() {
|
||||
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
|
||||
let res = srv.call(()).poll();
|
||||
assert!(res.is_err());
|
||||
assert_eq!(res.err().unwrap(), "error");
|
||||
|
@@ -5,17 +5,17 @@ use futures::{Future, Poll};
|
||||
use super::NewService;
|
||||
|
||||
/// `MapInitErr` service combinator
|
||||
pub struct MapInitErr<A, F, E> {
|
||||
pub struct MapInitErr<A, F, E, C> {
|
||||
a: A,
|
||||
f: F,
|
||||
e: PhantomData<E>,
|
||||
e: PhantomData<(E, C)>,
|
||||
}
|
||||
|
||||
impl<A, F, E> MapInitErr<A, F, E> {
|
||||
impl<A, F, E, C> MapInitErr<A, F, E, C> {
|
||||
/// Create new `MapInitErr` combinator
|
||||
pub fn new<Request>(a: A, f: F) -> Self
|
||||
pub fn new<R>(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
Self {
|
||||
@@ -26,7 +26,7 @@ impl<A, F, E> MapInitErr<A, F, E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E> Clone for MapInitErr<A, F, E>
|
||||
impl<A, F, E, C> Clone for MapInitErr<A, F, E, C>
|
||||
where
|
||||
A: Clone,
|
||||
F: Clone,
|
||||
@@ -40,9 +40,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, Request> NewService<Request> for MapInitErr<A, F, E>
|
||||
impl<A, F, E, R, C> NewService<R, C> for MapInitErr<A, F, E, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
F: Fn(A::InitError) -> E + Clone,
|
||||
{
|
||||
type Response = A::Response;
|
||||
@@ -50,35 +50,28 @@ where
|
||||
type Service = A::Service;
|
||||
|
||||
type InitError = E;
|
||||
type Future = MapInitErrFuture<A, F, E, Request>;
|
||||
type Future = MapInitErrFuture<A, F, E, R, C>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
MapInitErrFuture::new(self.a.new_service(), self.f.clone())
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
MapInitErrFuture {
|
||||
fut: self.a.new_service(cfg),
|
||||
f: self.f.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapInitErrFuture<A, F, E, Request>
|
||||
pub struct MapInitErrFuture<A, F, E, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
f: F,
|
||||
fut: A::Future,
|
||||
}
|
||||
|
||||
impl<A, F, E, Request> MapInitErrFuture<A, F, E, Request>
|
||||
impl<A, F, E, R, C> Future for MapInitErrFuture<A, F, E, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
MapInitErrFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E, Request> Future for MapInitErrFuture<A, F, E, Request>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
type Item = A::Service;
|
||||
|
@@ -1,6 +1,8 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{try_ready, Async, Future, Poll};
|
||||
|
||||
use super::{IntoNewService, NewService, Service};
|
||||
use super::{NewService, Service};
|
||||
use crate::cell::Cell;
|
||||
|
||||
/// Service for the `then` combinator, chaining a computation onto the end of
|
||||
@@ -14,9 +16,9 @@ pub struct Then<A, B> {
|
||||
|
||||
impl<A, B> Then<A, B> {
|
||||
/// Create new `Then` combinator
|
||||
pub fn new<Request>(a: A, b: B) -> Then<A, B>
|
||||
pub fn new<R>(a: A, b: B) -> Then<A, B>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
B: Service<Result<A::Response, A::Error>, Error = A::Error>,
|
||||
{
|
||||
Then { a, b: Cell::new(b) }
|
||||
@@ -35,28 +37,28 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, Request> Service<Request> for Then<A, B>
|
||||
impl<A, B, R> Service<R> for Then<A, B>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
B: Service<Result<A::Response, A::Error>, Error = A::Error>,
|
||||
{
|
||||
type Response = B::Response;
|
||||
type Error = B::Error;
|
||||
type Future = ThenFuture<A, B, Request>;
|
||||
type Future = ThenFuture<A, B, R>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
try_ready!(self.a.poll_ready());
|
||||
self.b.get_mut().poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request) -> Self::Future {
|
||||
fn call(&mut self, req: R) -> Self::Future {
|
||||
ThenFuture::new(self.a.call(req), self.b.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ThenFuture<A, B, Request>
|
||||
pub struct ThenFuture<A, B, R>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
B: Service<Result<A::Response, A::Error>>,
|
||||
{
|
||||
b: Cell<B>,
|
||||
@@ -64,9 +66,9 @@ where
|
||||
fut_a: Option<A::Future>,
|
||||
}
|
||||
|
||||
impl<A, B, Request> ThenFuture<A, B, Request>
|
||||
impl<A, B, R> ThenFuture<A, B, R>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
B: Service<Result<A::Response, A::Error>>,
|
||||
{
|
||||
fn new(a: A::Future, b: Cell<B>) -> Self {
|
||||
@@ -78,9 +80,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, Request> Future for ThenFuture<A, B, Request>
|
||||
impl<A, B, R> Future for ThenFuture<A, B, R>
|
||||
where
|
||||
A: Service<Request>,
|
||||
A: Service<R>,
|
||||
B: Service<Result<A::Response, A::Error>>,
|
||||
{
|
||||
type Item = B::Response;
|
||||
@@ -108,48 +110,50 @@ where
|
||||
}
|
||||
|
||||
/// `ThenNewService` new service combinator
|
||||
pub struct ThenNewService<A, B> {
|
||||
pub struct ThenNewService<A, B, C> {
|
||||
a: A,
|
||||
b: B,
|
||||
_t: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<A, B> ThenNewService<A, B> {
|
||||
impl<A, B, C> ThenNewService<A, B, C> {
|
||||
/// Create new `AndThen` combinator
|
||||
pub fn new<F, Request>(a: A, f: F) -> Self
|
||||
pub fn new<R>(a: A, f: B) -> Self
|
||||
where
|
||||
A: NewService<Request>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<
|
||||
Result<A::Response, A::Error>,
|
||||
C,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
F: IntoNewService<B, Result<A::Response, A::Error>>,
|
||||
{
|
||||
Self {
|
||||
a,
|
||||
b: f.into_new_service(),
|
||||
b: f,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, Request> NewService<Request> for ThenNewService<A, B>
|
||||
impl<A, B, R, C> NewService<R, C> for ThenNewService<A, B, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<Result<A::Response, A::Error>, C, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
type Response = B::Response;
|
||||
type Error = A::Error;
|
||||
type Service = Then<A::Service, B::Service>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = ThenNewServiceFuture<A, B, Request>;
|
||||
type Future = ThenNewServiceFuture<A, B, R, C>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
ThenNewServiceFuture::new(self.a.new_service(), self.b.new_service())
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
ThenNewServiceFuture::new(self.a.new_service(cfg), self.b.new_service(cfg))
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> Clone for ThenNewService<A, B>
|
||||
impl<A, B, C> Clone for ThenNewService<A, B, C>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
@@ -158,14 +162,15 @@ where
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ThenNewServiceFuture<A, B, Request>
|
||||
pub struct ThenNewServiceFuture<A, B, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<Result<A::Response, A::Error>, C, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
fut_b: B::Future,
|
||||
fut_a: A::Future,
|
||||
@@ -173,10 +178,10 @@ where
|
||||
b: Option<B::Service>,
|
||||
}
|
||||
|
||||
impl<A, B, Request> ThenNewServiceFuture<A, B, Request>
|
||||
impl<A, B, R, C> ThenNewServiceFuture<A, B, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<Result<A::Response, A::Error>, C, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
|
||||
ThenNewServiceFuture {
|
||||
@@ -188,10 +193,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, Request> Future for ThenNewServiceFuture<A, B, Request>
|
||||
impl<A, B, R, C> Future for ThenNewServiceFuture<A, B, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
B: NewService<Result<A::Response, A::Error>, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<Result<A::Response, A::Error>, C, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
type Item = Then<A::Service, B::Service>;
|
||||
type Error = A::InitError;
|
||||
@@ -223,11 +228,11 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use futures::future::{err, ok, FutureResult};
|
||||
use futures::{Async, Poll};
|
||||
use futures::{Async, Future, Poll};
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::*;
|
||||
use crate::{IntoNewService, NewService, Service, ServiceExt};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Srv1(Rc<Cell<usize>>);
|
||||
@@ -299,7 +304,7 @@ mod tests {
|
||||
let cnt2 = cnt.clone();
|
||||
let blank = move || Ok::<_, ()>(Srv1(cnt2.clone()));
|
||||
let new_srv = blank.into_new_service().then(move || Ok(Srv2(cnt.clone())));
|
||||
if let Async::Ready(mut srv) = new_srv.clone().new_service().poll().unwrap() {
|
||||
if let Async::Ready(mut srv) = new_srv.clone().new_service(&()).poll().unwrap() {
|
||||
let res = srv.call(Ok("srv1")).poll();
|
||||
assert!(res.is_ok());
|
||||
assert_eq!(res.unwrap(), Async::Ready(("srv1", "ok")));
|
||||
|
167
actix-service/src/transform.rs
Normal file
167
actix-service/src/transform.rs
Normal file
@@ -0,0 +1,167 @@
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures::{Async, Future, IntoFuture, Poll};
|
||||
|
||||
use crate::transform_map_init_err::TransformMapInitErr;
|
||||
use crate::{NewService, Service};
|
||||
|
||||
/// `Transform` service factory.
|
||||
///
|
||||
/// Transform factory creates service that wraps other services.
|
||||
///
|
||||
/// * `S` is a wrapped service.
|
||||
/// * `R` requests handled by this transform service.
|
||||
pub trait Transform<S, R> {
|
||||
/// Responses given by the service.
|
||||
type Response;
|
||||
|
||||
/// Errors produced by the service.
|
||||
type Error;
|
||||
|
||||
/// The `TransformService` value created by this factory
|
||||
type Transform: Service<R, Response = Self::Response, Error = Self::Error>;
|
||||
|
||||
/// Errors produced while building a service.
|
||||
type InitError;
|
||||
|
||||
/// The future response value.
|
||||
type Future: Future<Item = Self::Transform, Error = Self::InitError>;
|
||||
|
||||
/// Create and return a new service value asynchronously.
|
||||
fn new_transform(&self, service: S) -> Self::Future;
|
||||
|
||||
/// Map this service's factory init 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
|
||||
Self: Sized,
|
||||
F: Fn(Self::InitError) -> E,
|
||||
{
|
||||
TransformMapInitErr::new(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, R> Transform<S, R> for Rc<T>
|
||||
where
|
||||
T: Transform<S, R>,
|
||||
{
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type InitError = T::InitError;
|
||||
type Transform = T::Transform;
|
||||
type Future = T::Future;
|
||||
|
||||
fn new_transform(&self, service: S) -> T::Future {
|
||||
self.as_ref().new_transform(service)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, R> Transform<S, R> for Arc<T>
|
||||
where
|
||||
T: Transform<S, R>,
|
||||
{
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type InitError = T::InitError;
|
||||
type Transform = T::Transform;
|
||||
type Future = T::Future;
|
||||
|
||||
fn new_transform(&self, service: S) -> T::Future {
|
||||
self.as_ref().new_transform(service)
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a *transform service*
|
||||
pub trait IntoTransform<T, S, R>
|
||||
where
|
||||
T: Transform<S, R>,
|
||||
{
|
||||
/// Convert to a `TransformService`
|
||||
fn into_transform(self) -> T;
|
||||
}
|
||||
|
||||
impl<T, S, R> IntoTransform<T, S, R> for T
|
||||
where
|
||||
T: Transform<S, R>,
|
||||
{
|
||||
fn into_transform(self) -> T {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// `Apply` transform new service
|
||||
#[derive(Clone)]
|
||||
pub struct ApplyTransform<T, S, R, Req, Cfg> {
|
||||
a: S,
|
||||
t: Rc<T>,
|
||||
_t: std::marker::PhantomData<(R, Req, Cfg)>,
|
||||
}
|
||||
|
||||
impl<T, S, R, Req, Cfg> ApplyTransform<T, S, R, Req, Cfg>
|
||||
where
|
||||
S: NewService<Req, Cfg>,
|
||||
T: Transform<S::Service, R, Error = S::Error, InitError = S::InitError>,
|
||||
{
|
||||
/// Create new `ApplyNewService` new service instance
|
||||
pub fn new<F: IntoTransform<T, S::Service, R>>(t: F, a: S) -> Self {
|
||||
Self {
|
||||
a,
|
||||
t: Rc::new(t.into_transform()),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, R, Req, Cfg> NewService<R, Cfg> for ApplyTransform<T, S, R, Req, Cfg>
|
||||
where
|
||||
S: NewService<Req, Cfg>,
|
||||
T: Transform<S::Service, R, Error = S::Error, InitError = S::InitError>,
|
||||
{
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
|
||||
type Service = T::Transform;
|
||||
type InitError = T::InitError;
|
||||
type Future = ApplyTransformFuture<T, S, R, Req, Cfg>;
|
||||
|
||||
fn new_service(&self, cfg: &Cfg) -> Self::Future {
|
||||
ApplyTransformFuture {
|
||||
t_cell: self.t.clone(),
|
||||
fut_a: self.a.new_service(cfg).into_future(),
|
||||
fut_t: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ApplyTransformFuture<T, S, R, Req, Cfg>
|
||||
where
|
||||
S: NewService<Req, Cfg>,
|
||||
T: Transform<S::Service, R, Error = S::Error, InitError = S::InitError>,
|
||||
{
|
||||
fut_a: S::Future,
|
||||
fut_t: Option<T::Future>,
|
||||
t_cell: Rc<T>,
|
||||
}
|
||||
|
||||
impl<T, S, R, Req, Cfg> Future for ApplyTransformFuture<T, S, R, Req, Cfg>
|
||||
where
|
||||
S: NewService<Req, Cfg>,
|
||||
T: Transform<S::Service, R, Error = S::Error, InitError = S::InitError>,
|
||||
{
|
||||
type Item = T::Transform;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if self.fut_t.is_none() {
|
||||
if let Async::Ready(service) = self.fut_a.poll()? {
|
||||
self.fut_t = Some(self.t_cell.new_transform(service).into_future());
|
||||
}
|
||||
}
|
||||
if let Some(ref mut fut) = self.fut_t {
|
||||
fut.poll()
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
93
actix-service/src/transform_map_init_err.rs
Normal file
93
actix-service/src/transform_map_init_err.rs
Normal file
@@ -0,0 +1,93 @@
|
||||
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<R>(t: T, f: F) -> Self
|
||||
where
|
||||
T: Transform<S, R>,
|
||||
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, R, S, F, E> Transform<S, R> for TransformMapInitErr<T, S, F, E>
|
||||
where
|
||||
T: Transform<S, R>,
|
||||
F: Fn(T::InitError) -> E + Clone,
|
||||
{
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Transform = T::Transform;
|
||||
|
||||
type InitError = E;
|
||||
type Future = TransformMapInitErrFuture<T, R, 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, R, S, F, E>
|
||||
where
|
||||
T: Transform<S, R>,
|
||||
F: Fn(T::InitError) -> E,
|
||||
{
|
||||
fut: T::Future,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<T, R, S, F, E> TransformMapInitErrFuture<T, R, S, F, E>
|
||||
where
|
||||
T: Transform<S, R>,
|
||||
F: Fn(T::InitError) -> E,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
TransformMapInitErrFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, R, S, F, E> Future for TransformMapInitErrFuture<T, R, S, F, E>
|
||||
where
|
||||
T: Transform<S, R>,
|
||||
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)
|
||||
}
|
||||
}
|
56
actix-test-server/Cargo.toml
Normal file
56
actix-test-server/Cargo.toml
Normal file
@@ -0,0 +1,56 @@
|
||||
[package]
|
||||
name = "actix-test-server"
|
||||
version = "0.1.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix test server"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-net.git"
|
||||
documentation = "https://docs.rs/actix-test-server/"
|
||||
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", "tls", "rust-tls"]
|
||||
|
||||
[lib]
|
||||
name = "actix_test_server"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
|
||||
# tls
|
||||
tls = ["native-tls", "actix-server/tls"]
|
||||
|
||||
# openssl
|
||||
ssl = ["openssl", "actix-server/ssl"]
|
||||
|
||||
# rustls
|
||||
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
|
||||
|
||||
[dependencies]
|
||||
actix-rt = "0.1.0"
|
||||
#actix-server = "0.3.0"
|
||||
actix-server = { path="../actix-server" }
|
||||
|
||||
log = "0.4"
|
||||
net2 = "0.2"
|
||||
futures = "0.1"
|
||||
tokio-tcp = "0.1"
|
||||
tokio-reactor = "0.1"
|
||||
|
||||
# native-tls
|
||||
native-tls = { version="0.2", optional = true }
|
||||
|
||||
# openssl
|
||||
openssl = { version="0.10", optional = true }
|
||||
|
||||
#rustls
|
||||
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 }
|
142
actix-test-server/src/lib.rs
Normal file
142
actix-test-server/src/lib.rs
Normal file
@@ -0,0 +1,142 @@
|
||||
//! Various helpers for Actix applications to use during testing.
|
||||
use std::sync::mpsc;
|
||||
use std::{net, thread};
|
||||
|
||||
use actix_rt::{Runtime, System};
|
||||
use actix_server::{Server, StreamServiceFactory};
|
||||
|
||||
use futures::Future;
|
||||
use net2::TcpBuilder;
|
||||
use tokio_reactor::Handle;
|
||||
use tokio_tcp::TcpStream;
|
||||
|
||||
/// The `TestServer` type.
|
||||
///
|
||||
/// `TestServer` is very simple test server that simplify process of writing
|
||||
/// integration tests cases for actix applications.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// # extern crate actix_test_server;
|
||||
/// # use actix_web::*;
|
||||
/// #
|
||||
/// # fn my_handler(req: &HttpRequest) -> HttpResponse {
|
||||
/// # HttpResponse::Ok().into()
|
||||
/// # }
|
||||
/// #
|
||||
/// # fn main() {
|
||||
/// use actix_test_server::TestServer;
|
||||
///
|
||||
/// let mut srv = TestServer::new(|app| app.handler(my_handler));
|
||||
///
|
||||
/// let req = srv.get().finish().unwrap();
|
||||
/// let response = srv.execute(req.send()).unwrap();
|
||||
/// assert!(response.status().is_success());
|
||||
/// # }
|
||||
/// ```
|
||||
pub struct TestServer;
|
||||
|
||||
/// Test server runstime
|
||||
pub struct TestServerRuntime {
|
||||
addr: net::SocketAddr,
|
||||
host: String,
|
||||
port: u16,
|
||||
rt: Runtime,
|
||||
}
|
||||
|
||||
impl TestServer {
|
||||
/// Start new test server with application factory
|
||||
pub fn with<F: StreamServiceFactory>(factory: F) -> TestServerRuntime {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
|
||||
// run server in separate thread
|
||||
thread::spawn(move || {
|
||||
let sys = System::new("actix-test-server");
|
||||
let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let local_addr = tcp.local_addr().unwrap();
|
||||
|
||||
Server::build()
|
||||
.listen("test", tcp, factory)
|
||||
.workers(1)
|
||||
.disable_signals()
|
||||
.start();
|
||||
|
||||
tx.send((System::current(), local_addr)).unwrap();
|
||||
sys.run();
|
||||
});
|
||||
|
||||
let (system, addr) = rx.recv().unwrap();
|
||||
System::set_current(system);
|
||||
|
||||
let rt = Runtime::new().unwrap();
|
||||
let host = format!("{}", addr.ip());
|
||||
let port = addr.port();
|
||||
|
||||
TestServerRuntime {
|
||||
addr,
|
||||
rt,
|
||||
host,
|
||||
port,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get firat available unused local address
|
||||
pub fn unused_addr() -> net::SocketAddr {
|
||||
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
|
||||
let socket = TcpBuilder::new_v4().unwrap();
|
||||
socket.bind(&addr).unwrap();
|
||||
socket.reuse_address(true).unwrap();
|
||||
let tcp = socket.to_tcp_listener().unwrap();
|
||||
tcp.local_addr().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
impl TestServerRuntime {
|
||||
/// Execute future on current runtime
|
||||
pub fn block_on<F, I, E>(&mut self, fut: F) -> Result<I, E>
|
||||
where
|
||||
F: Future<Item = I, Error = E>,
|
||||
{
|
||||
self.rt.block_on(fut)
|
||||
}
|
||||
|
||||
/// Spawn future to the current runtime
|
||||
pub fn spawn<F>(&mut self, fut: F)
|
||||
where
|
||||
F: Future<Item = (), Error = ()> + 'static,
|
||||
{
|
||||
self.rt.spawn(fut);
|
||||
}
|
||||
|
||||
/// Test server host
|
||||
pub fn host(&self) -> &str {
|
||||
&self.host
|
||||
}
|
||||
|
||||
/// Test server port
|
||||
pub fn port(&self) -> u16 {
|
||||
self.port
|
||||
}
|
||||
|
||||
/// Get test server address
|
||||
pub fn addr(&self) -> net::SocketAddr {
|
||||
self.addr
|
||||
}
|
||||
|
||||
/// Stop http server
|
||||
fn stop(&mut self) {
|
||||
System::current().stop();
|
||||
}
|
||||
|
||||
/// Connect to server, return tokio TcpStream
|
||||
pub fn connect(&self) -> std::io::Result<TcpStream> {
|
||||
TcpStream::from_std(net::TcpStream::connect(self.addr)?, &Handle::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestServerRuntime {
|
||||
fn drop(&mut self) {
|
||||
self.stop()
|
||||
}
|
||||
}
|
@@ -1,5 +1,81 @@
|
||||
# Changes
|
||||
|
||||
## [0.4.0] - 2019-03-xx
|
||||
|
||||
* Upgrade actix-service
|
||||
|
||||
|
||||
## [0.3.2] - 2019-03-04
|
||||
|
||||
### Changed
|
||||
|
||||
* Use IntoFuture for new services
|
||||
|
||||
|
||||
## [0.3.1] - 2019-03-04
|
||||
|
||||
### Changed
|
||||
|
||||
* Use new type of transform trait
|
||||
|
||||
|
||||
## [0.3.0] - 2019-03-02
|
||||
|
||||
### Changed
|
||||
|
||||
* Use new `NewService` trait
|
||||
|
||||
* BoxedNewService` and `BoxedService` types moved to actix-service crate.
|
||||
|
||||
|
||||
## [0.2.4] - 2019-02-21
|
||||
|
||||
### Changed
|
||||
|
||||
* Custom `BoxedNewService` implementation.
|
||||
|
||||
|
||||
## [0.2.3] - 2019-02-21
|
||||
|
||||
### Added
|
||||
|
||||
* Add `BoxedNewService` and `BoxedService`
|
||||
|
||||
|
||||
## [0.2.2] - 2019-02-11
|
||||
|
||||
### Added
|
||||
|
||||
* Add `Display` impl for `TimeoutError`
|
||||
|
||||
* Add `Display` impl for `InOrderError`
|
||||
|
||||
|
||||
## [0.2.1] - 2019-02-06
|
||||
|
||||
### Added
|
||||
|
||||
* Add `InOrder` service. the service yields responses as they become available,
|
||||
in the order that their originating requests were submitted to the service.
|
||||
|
||||
### Changed
|
||||
|
||||
* Convert `Timeout` and `InFlight` services to a transforms
|
||||
|
||||
|
||||
## [0.2.0] - 2019-02-01
|
||||
|
||||
* Fix framed transport error handling
|
||||
|
||||
* Added Clone impl for Either service
|
||||
|
||||
* Added Clone impl for Timeout service factory
|
||||
|
||||
* Added Service and NewService for Stream dispatcher
|
||||
|
||||
* Switch to actix-service 0.2
|
||||
|
||||
|
||||
## [0.1.0] - 2018-12-09
|
||||
|
||||
* Move utils services to separate crate
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-utils"
|
||||
version = "0.1.0"
|
||||
version = "0.3.2"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix utils - various actix net related services"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -11,18 +11,21 @@ categories = ["network-programming", "asynchronous"]
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
workspace = ".."
|
||||
|
||||
[lib]
|
||||
name = "actix_utils"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.1.1"
|
||||
#actix-service = "0.3.2"
|
||||
actix-service = { path="../actix-service" }
|
||||
actix-codec = "0.1.0"
|
||||
actix-rt = "0.1.0"
|
||||
|
||||
# io
|
||||
bytes = "0.4"
|
||||
futures = "0.1"
|
||||
futures = "0.1.24"
|
||||
tokio-timer = "0.2.8"
|
||||
tokio-current-thread = "0.1.4"
|
||||
log = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.1"
|
||||
|
@@ -1,17 +1,11 @@
|
||||
//! Custom cell impl
|
||||
|
||||
#[cfg(feature = "cell")]
|
||||
use std::cell::UnsafeCell;
|
||||
#[cfg(not(feature = "cell"))]
|
||||
use std::cell::{Ref, RefCell, RefMut};
|
||||
use std::fmt;
|
||||
use std::rc::Rc;
|
||||
|
||||
pub(crate) struct Cell<T> {
|
||||
#[cfg(feature = "cell")]
|
||||
inner: Rc<UnsafeCell<T>>,
|
||||
#[cfg(not(feature = "cell"))]
|
||||
inner: Rc<RefCell<T>>,
|
||||
}
|
||||
|
||||
impl<T> Clone for Cell<T> {
|
||||
@@ -28,7 +22,6 @@ impl<T: fmt::Debug> fmt::Debug for Cell<T> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "cell")]
|
||||
impl<T> Cell<T> {
|
||||
pub fn new(inner: T) -> Self {
|
||||
Self {
|
||||
@@ -36,28 +29,11 @@ impl<T> Cell<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn borrow(&self) -> &T {
|
||||
pub fn get_ref(&self) -> &T {
|
||||
unsafe { &*self.inner.as_ref().get() }
|
||||
}
|
||||
|
||||
pub fn borrow_mut(&self) -> &mut T {
|
||||
pub fn get_mut(&mut self) -> &mut T {
|
||||
unsafe { &mut *self.inner.as_ref().get() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "cell"))]
|
||||
impl<T> Cell<T> {
|
||||
pub fn new(inner: T) -> Self {
|
||||
Self {
|
||||
inner: Rc::new(RefCell::new(inner)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn borrow(&self) -> Ref<T> {
|
||||
self.inner.borrow()
|
||||
}
|
||||
|
||||
pub fn borrow_mut(&self) -> RefMut<T> {
|
||||
self.inner.borrow_mut()
|
||||
}
|
||||
}
|
||||
|
@@ -13,9 +13,9 @@ pub struct CloneableService<T: 'static> {
|
||||
}
|
||||
|
||||
impl<T: 'static> CloneableService<T> {
|
||||
pub fn new<Request>(service: T) -> Self
|
||||
pub fn new<R>(service: T) -> Self
|
||||
where
|
||||
T: Service<Request>,
|
||||
T: Service<R>,
|
||||
{
|
||||
Self {
|
||||
service: Cell::new(service),
|
||||
@@ -33,19 +33,19 @@ impl<T: 'static> Clone for CloneableService<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: 'static, Request> Service<Request> for CloneableService<T>
|
||||
impl<T, R> Service<R> for CloneableService<T>
|
||||
where
|
||||
T: Service<Request>,
|
||||
T: Service<R> + 'static,
|
||||
{
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = T::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.borrow_mut().poll_ready()
|
||||
self.service.get_mut().poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request) -> Self::Future {
|
||||
self.service.borrow_mut().call(req)
|
||||
fn call(&mut self, req: R) -> Self::Future {
|
||||
self.service.get_mut().call(req)
|
||||
}
|
||||
}
|
||||
|
@@ -1,6 +1,6 @@
|
||||
//! Contains `Either` service and related types and functions.
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::{future, try_ready, Async, Future, Poll};
|
||||
use futures::{future, try_ready, Async, Future, IntoFuture, Poll};
|
||||
|
||||
/// Combine two different service types into a single type.
|
||||
///
|
||||
@@ -12,10 +12,19 @@ pub enum EitherService<A, B> {
|
||||
B(B),
|
||||
}
|
||||
|
||||
impl<A, B, Request> Service<Request> for EitherService<A, 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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, R> Service<R> for EitherService<A, B>
|
||||
where
|
||||
A: Service<Request>,
|
||||
B: Service<Request, Response = A::Response, Error = A::Error>,
|
||||
A: Service<R>,
|
||||
B: Service<R, Response = A::Response, Error = A::Error>,
|
||||
{
|
||||
type Response = A::Response;
|
||||
type Error = A::Error;
|
||||
@@ -28,7 +37,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request) -> Self::Future {
|
||||
fn call(&mut self, req: R) -> Self::Future {
|
||||
match self {
|
||||
EitherService::A(ref mut inner) => future::Either::A(inner.call(req)),
|
||||
EitherService::B(ref mut inner) => future::Either::B(inner.call(req)),
|
||||
@@ -42,35 +51,62 @@ pub enum Either<A, B> {
|
||||
B(B),
|
||||
}
|
||||
|
||||
impl<A, B, Request> NewService<Request> for Either<A, B>
|
||||
impl<A, B> Either<A, B> {
|
||||
pub fn new_a<R, C>(srv: A) -> Self
|
||||
where
|
||||
A: NewService<R, C>,
|
||||
B: NewService<R, C, Response = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
Either::A(srv)
|
||||
}
|
||||
|
||||
pub fn new_b<R, C>(srv: B) -> Self
|
||||
where
|
||||
A: NewService<R, C>,
|
||||
B: NewService<R, C, Response = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
Either::B(srv)
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, R, C> NewService<R, C> for Either<A, B>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
B: NewService<Request, Response = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<R, C, Response = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
type Response = A::Response;
|
||||
type Error = A::Error;
|
||||
type InitError = A::InitError;
|
||||
type Service = EitherService<A::Service, B::Service>;
|
||||
type Future = EitherNewService<A, B, Request>;
|
||||
type Future = EitherNewService<A, B, R, C>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
match self {
|
||||
Either::A(ref inner) => EitherNewService::A(inner.new_service()),
|
||||
Either::B(ref inner) => EitherNewService::B(inner.new_service()),
|
||||
Either::A(ref inner) => EitherNewService::A(inner.new_service(cfg)),
|
||||
Either::B(ref inner) => EitherNewService::B(inner.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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub enum EitherNewService<A: NewService<R>, B: NewService<R>, R> {
|
||||
A(A::Future),
|
||||
B(B::Future),
|
||||
pub enum EitherNewService<A: NewService<R, C>, B: NewService<R, C>, R, C> {
|
||||
A(<A::Future as IntoFuture>::Future),
|
||||
B(<B::Future as IntoFuture>::Future),
|
||||
}
|
||||
|
||||
impl<A, B, Request> Future for EitherNewService<A, B, Request>
|
||||
impl<A, B, R, C> Future for EitherNewService<A, B, R, C>
|
||||
where
|
||||
A: NewService<Request>,
|
||||
B: NewService<Request, Response = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<R, C>,
|
||||
B: NewService<R, C, Response = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
type Item = EitherService<A::Service, B::Service>;
|
||||
type Error = A::InitError;
|
||||
|
@@ -1,33 +1,37 @@
|
||||
//! Framed dispatcher service and related utilities
|
||||
use std::collections::VecDeque;
|
||||
use std::marker::PhantomData;
|
||||
use std::mem;
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Decoder, Encoder, Framed};
|
||||
use actix_rt::Arbiter;
|
||||
use actix_service::{IntoNewService, IntoService, NewService, Service};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::unsync::mpsc;
|
||||
use futures::{Async, AsyncSink, Future, Poll, Sink, Stream};
|
||||
use futures::task::AtomicTask;
|
||||
use futures::{Async, Future, IntoFuture, Poll, Sink, Stream};
|
||||
use log::debug;
|
||||
|
||||
use crate::cell::Cell;
|
||||
|
||||
type Request<U> = <U as Decoder>::Item;
|
||||
type Response<U> = <U as Encoder>::Item;
|
||||
|
||||
pub struct FramedNewService<S, T, U> {
|
||||
pub struct FramedNewService<S, T, U, C> {
|
||||
factory: S,
|
||||
_t: PhantomData<(T, U)>,
|
||||
_t: PhantomData<(T, U, C)>,
|
||||
}
|
||||
|
||||
impl<S, T, U> FramedNewService<S, T, U>
|
||||
impl<S, T, U, C> FramedNewService<S, T, U, C>
|
||||
where
|
||||
C: Clone,
|
||||
S: NewService<Request<U>, C, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service<Request<U>>>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
S: NewService<Request<U>, Response = Response<U>>,
|
||||
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
|
||||
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
pub fn new<F1: IntoNewService<S, Request<U>>>(factory: F1) -> Self {
|
||||
pub fn new<F1: IntoNewService<S, Request<U>, C>>(factory: F1) -> Self {
|
||||
Self {
|
||||
factory: factory.into_new_service(),
|
||||
_t: PhantomData,
|
||||
@@ -35,7 +39,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, U> Clone for FramedNewService<S, T, U>
|
||||
impl<S, T, U, C> Clone for FramedNewService<S, T, U, C>
|
||||
where
|
||||
S: Clone,
|
||||
{
|
||||
@@ -47,60 +51,66 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, U> NewService<Framed<T, U>> for FramedNewService<S, T, U>
|
||||
impl<S, T, U, C> NewService<Framed<T, U>, C> for FramedNewService<S, T, U, C>
|
||||
where
|
||||
C: Clone,
|
||||
S: NewService<Request<U>, C, Response = Response<U>> + Clone,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service<Request<U>>>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
S: NewService<Request<U>, Response = Response<U>> + Clone,
|
||||
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
|
||||
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
type Response = FramedTransport<S::Service, T, U>;
|
||||
type Error = S::InitError;
|
||||
type InitError = S::InitError;
|
||||
type Service = FramedService<S, T, U>;
|
||||
type Service = FramedService<S, T, U, C>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
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> {
|
||||
pub struct FramedService<S, T, U, C> {
|
||||
factory: S,
|
||||
config: C,
|
||||
_t: PhantomData<(T, U)>,
|
||||
}
|
||||
|
||||
impl<S, T, U> Clone for FramedService<S, 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> Service<Framed<T, U>> for FramedService<S, T, U>
|
||||
impl<S, T, U, C> Service<Framed<T, U>> for FramedService<S, T, U, C>
|
||||
where
|
||||
S: NewService<Request<U>, C, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service<Request<U>>>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
S: NewService<Request<U>, Response = Response<U>>,
|
||||
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
|
||||
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
C: Clone,
|
||||
{
|
||||
type Response = FramedTransport<S::Service, T, U>;
|
||||
type Error = S::InitError;
|
||||
type Future = FramedServiceResponseFuture<S, T, U>;
|
||||
type Future = FramedServiceResponseFuture<S, T, U, C>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
@@ -108,37 +118,36 @@ where
|
||||
|
||||
fn call(&mut self, req: Framed<T, U>) -> Self::Future {
|
||||
FramedServiceResponseFuture {
|
||||
fut: self.factory.new_service(),
|
||||
|
||||
fut: self.factory.new_service(&self.config),
|
||||
framed: Some(req),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct FramedServiceResponseFuture<S, T, U>
|
||||
pub struct FramedServiceResponseFuture<S, T, U, C>
|
||||
where
|
||||
S: NewService<Request<U>, C, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service<Request<U>>>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
S: NewService<Request<U>, Response = Response<U>>,
|
||||
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
|
||||
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
fut: S::Future,
|
||||
fut: <S::Future as IntoFuture>::Future,
|
||||
framed: Option<Framed<T, U>>,
|
||||
}
|
||||
|
||||
impl<S, T, U> Future for FramedServiceResponseFuture<S, T, U>
|
||||
impl<S, T, U, C> Future for FramedServiceResponseFuture<S, T, U, C>
|
||||
where
|
||||
S: NewService<Request<U>, C, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service<Request<U>>>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
S: NewService<Request<U>, Response = Response<U>>,
|
||||
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Future: 'static,
|
||||
<<S as NewService<Request<U>>>::Service as Service<Request<U>>>::Error: 'static,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
type Item = FramedTransport<S::Service, T, U>;
|
||||
type Error = S::InitError;
|
||||
@@ -172,46 +181,142 @@ impl<E, U: Encoder + Decoder> From<E> for FramedTransportError<E, U> {
|
||||
pub struct FramedTransport<S, T, U>
|
||||
where
|
||||
S: Service<Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
S::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Encoder + Decoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
service: S,
|
||||
state: TransportState<S, U>,
|
||||
framed: Framed<T, U>,
|
||||
request: Option<Request<U>>,
|
||||
response: Option<Response<U>>,
|
||||
write_rx: mpsc::Receiver<Result<Response<U>, S::Error>>,
|
||||
write_tx: mpsc::Sender<Result<Response<U>, S::Error>>,
|
||||
flushed: bool,
|
||||
inner: Cell<FramedTransportInner<<U as Encoder>::Item, S::Error>>,
|
||||
}
|
||||
|
||||
enum TransportState<S: Service<Request<U>>, U: Encoder + Decoder> {
|
||||
Processing,
|
||||
Error(FramedTransportError<S::Error, U>),
|
||||
EncoderError(FramedTransportError<S::Error, U>),
|
||||
FramedError(FramedTransportError<S::Error, U>),
|
||||
Stopping,
|
||||
}
|
||||
|
||||
struct FramedTransportInner<I, E> {
|
||||
buf: VecDeque<Result<I, E>>,
|
||||
task: AtomicTask,
|
||||
}
|
||||
|
||||
impl<S, T, U> FramedTransport<S, T, U>
|
||||
where
|
||||
S: Service<Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
S::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
fn poll_read(&mut self) -> bool {
|
||||
loop {
|
||||
match self.service.poll_ready() {
|
||||
Ok(Async::Ready(_)) => loop {
|
||||
let item = match self.framed.poll() {
|
||||
Ok(Async::Ready(Some(el))) => el,
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::FramedError(FramedTransportError::Decoder(err));
|
||||
return true;
|
||||
}
|
||||
Ok(Async::NotReady) => return false,
|
||||
Ok(Async::Ready(None)) => {
|
||||
self.state = TransportState::Stopping;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
let mut cell = self.inner.clone();
|
||||
cell.get_mut().task.register();
|
||||
tokio_current_thread::spawn(self.service.call(item).then(move |item| {
|
||||
let inner = cell.get_mut();
|
||||
inner.buf.push_back(item);
|
||||
inner.task.notify();
|
||||
Ok(())
|
||||
}));
|
||||
},
|
||||
Ok(Async::NotReady) => return false,
|
||||
Err(err) => {
|
||||
self.state = TransportState::Error(FramedTransportError::Service(err));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// write to framed object
|
||||
fn poll_write(&mut self) -> bool {
|
||||
let inner = self.inner.get_mut();
|
||||
loop {
|
||||
while !self.framed.is_write_buf_full() {
|
||||
if let Some(msg) = inner.buf.pop_front() {
|
||||
match msg {
|
||||
Ok(msg) => {
|
||||
if let Err(err) = self.framed.force_send(msg) {
|
||||
self.state = TransportState::FramedError(
|
||||
FramedTransportError::Encoder(err),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::Error(FramedTransportError::Service(err));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !self.framed.is_write_buf_empty() {
|
||||
match self.framed.poll_complete() {
|
||||
Ok(Async::NotReady) => break,
|
||||
Err(err) => {
|
||||
debug!("Error sending data: {:?}", err);
|
||||
self.state =
|
||||
TransportState::FramedError(FramedTransportError::Encoder(err));
|
||||
return true;
|
||||
}
|
||||
Ok(Async::Ready(_)) => (),
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, U> FramedTransport<S, T, U>
|
||||
where
|
||||
S: Service<Request<U>, Response = Response<U>>,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
<U as Encoder>::Error: 'static,
|
||||
S::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
pub fn new<F: IntoService<S, Request<U>>>(framed: Framed<T, U>, service: F) -> Self {
|
||||
let (write_tx, write_rx) = mpsc::channel(16);
|
||||
FramedTransport {
|
||||
framed,
|
||||
write_rx,
|
||||
write_tx,
|
||||
service: service.into_service(),
|
||||
state: TransportState::Processing,
|
||||
request: None,
|
||||
response: None,
|
||||
flushed: true,
|
||||
inner: Cell::new(FramedTransportInner {
|
||||
buf: VecDeque::new(),
|
||||
task: AtomicTask::new(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,144 +344,15 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, U> FramedTransport<S, T, U>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
S: Service<Request<U>, Response = Response<U>>,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: 'static,
|
||||
{
|
||||
fn poll_service(&mut self) -> bool {
|
||||
match self.service.poll_ready() {
|
||||
Ok(Async::Ready(_)) => {
|
||||
if let Some(item) = self.request.take() {
|
||||
let sender = self.write_tx.clone();
|
||||
Arbiter::spawn(
|
||||
self.service
|
||||
.call(item)
|
||||
.then(|item| sender.send(item).map(|_| ()).map_err(|_| ())),
|
||||
);
|
||||
}
|
||||
|
||||
loop {
|
||||
let item = match self.framed.poll() {
|
||||
Ok(Async::Ready(Some(el))) => el,
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::Error(FramedTransportError::Decoder(err));
|
||||
return true;
|
||||
}
|
||||
Ok(Async::NotReady) => return false,
|
||||
Ok(Async::Ready(None)) => {
|
||||
self.state = TransportState::Stopping;
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
match self.service.poll_ready() {
|
||||
Ok(Async::Ready(_)) => {
|
||||
let sender = self.write_tx.clone();
|
||||
Arbiter::spawn(
|
||||
self.service
|
||||
.call(item)
|
||||
.then(|item| sender.send(item).map(|_| ()).map_err(|_| ())),
|
||||
);
|
||||
}
|
||||
Ok(Async::NotReady) => {
|
||||
self.request = Some(item);
|
||||
return false;
|
||||
}
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::Error(FramedTransportError::Service(err));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Async::NotReady) => false,
|
||||
Err(err) => {
|
||||
self.state = TransportState::Error(FramedTransportError::Service(err));
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// write to sink
|
||||
fn poll_response(&mut self) -> bool {
|
||||
let mut item = self.response.take();
|
||||
loop {
|
||||
item = if let Some(msg) = item {
|
||||
self.flushed = false;
|
||||
match self.framed.start_send(msg) {
|
||||
Ok(AsyncSink::Ready) => None,
|
||||
Ok(AsyncSink::NotReady(item)) => Some(item),
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::EncoderError(FramedTransportError::Encoder(err));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// flush sink
|
||||
if !self.flushed {
|
||||
match self.framed.poll_complete() {
|
||||
Ok(Async::Ready(_)) => {
|
||||
self.flushed = true;
|
||||
}
|
||||
Ok(Async::NotReady) => break,
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::EncoderError(FramedTransportError::Encoder(err));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// check channel
|
||||
if self.flushed {
|
||||
if item.is_none() {
|
||||
match self.write_rx.poll() {
|
||||
Ok(Async::Ready(Some(msg))) => match msg {
|
||||
Ok(msg) => item = Some(msg),
|
||||
Err(err) => {
|
||||
self.state =
|
||||
TransportState::Error(FramedTransportError::Service(err));
|
||||
return true;
|
||||
}
|
||||
},
|
||||
Ok(Async::NotReady) => break,
|
||||
Err(_) => panic!("Bug in gw code"),
|
||||
Ok(Async::Ready(None)) => panic!("Bug in gw code"),
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
self.response = item;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, U> Future for FramedTransport<S, T, U>
|
||||
where
|
||||
S: Service<Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
S::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
S: Service<Request<U>, Response = Response<U>>,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
type Item = ();
|
||||
type Error = FramedTransportError<S::Error, U>;
|
||||
@@ -384,21 +360,23 @@ where
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match mem::replace(&mut self.state, TransportState::Processing) {
|
||||
TransportState::Processing => {
|
||||
if self.poll_service() || self.poll_response() {
|
||||
if self.poll_read() || self.poll_write() {
|
||||
self.poll()
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
TransportState::Error(err) => {
|
||||
if self.poll_response() || self.flushed {
|
||||
if self.framed.is_write_buf_empty()
|
||||
|| (self.poll_write() || self.framed.is_write_buf_empty())
|
||||
{
|
||||
Err(err)
|
||||
} else {
|
||||
self.state = TransportState::Error(err);
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
TransportState::EncoderError(err) => Err(err),
|
||||
TransportState::FramedError(err) => Err(err),
|
||||
TransportState::Stopping => Ok(Async::Ready(())),
|
||||
}
|
||||
}
|
||||
@@ -428,7 +406,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U, F> NewService<T> for IntoFramed<T, U, F>
|
||||
impl<T, U, F> NewService<T, ()> for IntoFramed<T, U, F>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
F: Fn() -> U + Send + Clone + 'static,
|
||||
@@ -440,7 +418,7 @@ where
|
||||
type Service = IntoFramedService<T, U, F>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(IntoFramedService {
|
||||
factory: self.factory.clone(),
|
||||
_t: PhantomData,
|
||||
|
@@ -1,5 +1,6 @@
|
||||
use actix_service::{IntoNewService, IntoService, NewService, Service};
|
||||
use futures::{try_ready, Async, Future, Poll};
|
||||
use actix_service::{Service, Transform, Void};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::counter::{Counter, CounterGuard};
|
||||
|
||||
@@ -7,113 +8,68 @@ use super::counter::{Counter, CounterGuard};
|
||||
/// async requests.
|
||||
///
|
||||
/// Default number of in-flight requests is 15
|
||||
pub struct InFlight<T> {
|
||||
factory: T,
|
||||
pub struct InFlight {
|
||||
max_inflight: usize,
|
||||
}
|
||||
|
||||
impl<T> InFlight<T> {
|
||||
pub fn new<F, Request>(factory: F) -> Self
|
||||
where
|
||||
T: NewService<Request>,
|
||||
F: IntoNewService<T, Request>,
|
||||
{
|
||||
Self {
|
||||
factory: factory.into_new_service(),
|
||||
max_inflight: 15,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set max number of in-flight requests.
|
||||
///
|
||||
/// By default max in-flight requests is 15.
|
||||
pub fn max_inflight(mut self, max: usize) -> Self {
|
||||
self.max_inflight = max;
|
||||
self
|
||||
impl InFlight {
|
||||
pub fn new(max: usize) -> Self {
|
||||
Self { max_inflight: max }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Request> NewService<Request> for InFlight<T>
|
||||
where
|
||||
T: NewService<Request>,
|
||||
{
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type InitError = T::InitError;
|
||||
type Service = InFlightService<T::Service>;
|
||||
type Future = InFlightResponseFuture<T, Request>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
InFlightResponseFuture {
|
||||
fut: self.factory.new_service(),
|
||||
max_inflight: self.max_inflight,
|
||||
}
|
||||
impl Default for InFlight {
|
||||
fn default() -> Self {
|
||||
Self::new(15)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InFlightResponseFuture<T: NewService<Request>, Request> {
|
||||
fut: T::Future,
|
||||
max_inflight: usize,
|
||||
}
|
||||
impl<S: Service<R>, R> Transform<S, R> for InFlight {
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type InitError = Void;
|
||||
type Transform = InFlightService<S>;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
impl<T: NewService<Request>, Request> Future for InFlightResponseFuture<T, Request> {
|
||||
type Item = InFlightService<T::Service>;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
Ok(Async::Ready(InFlightService::with_max_inflight(
|
||||
self.max_inflight,
|
||||
try_ready!(self.fut.poll()),
|
||||
)))
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ok(InFlightService::new(self.max_inflight, service))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InFlightService<T> {
|
||||
service: T,
|
||||
pub struct InFlightService<S> {
|
||||
count: Counter,
|
||||
service: S,
|
||||
}
|
||||
|
||||
impl<T> InFlightService<T> {
|
||||
pub fn new<F, Request>(service: F) -> Self
|
||||
where
|
||||
T: Service<Request>,
|
||||
F: IntoService<T, Request>,
|
||||
{
|
||||
impl<S> InFlightService<S> {
|
||||
pub fn new(max: usize, service: S) -> Self {
|
||||
Self {
|
||||
service: service.into_service(),
|
||||
count: Counter::new(15),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_max_inflight<F, Request>(max: usize, service: F) -> Self
|
||||
where
|
||||
T: Service<Request>,
|
||||
F: IntoService<T, Request>,
|
||||
{
|
||||
Self {
|
||||
service: service.into_service(),
|
||||
service,
|
||||
count: Counter::new(max),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Request> Service<Request> for InFlightService<T>
|
||||
impl<T, R> Service<R> for InFlightService<T>
|
||||
where
|
||||
T: Service<Request>,
|
||||
T: Service<R>,
|
||||
{
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = InFlightServiceResponse<T, Request>;
|
||||
type Future = InFlightServiceResponse<T, R>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
let res = self.service.poll_ready();
|
||||
if res.is_ok() && !self.count.available() {
|
||||
return Ok(Async::NotReady);
|
||||
self.service.poll_ready()?;
|
||||
|
||||
if !self.count.available() {
|
||||
log::trace!("InFlight limit exceeded");
|
||||
Ok(Async::NotReady)
|
||||
} else {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
res
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Request) -> Self::Future {
|
||||
fn call(&mut self, req: R) -> Self::Future {
|
||||
InFlightServiceResponse {
|
||||
fut: self.service.call(req),
|
||||
_guard: self.count.get(),
|
||||
@@ -122,12 +78,12 @@ where
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct InFlightServiceResponse<T: Service<Request>, Request> {
|
||||
pub struct InFlightServiceResponse<T: Service<R>, R> {
|
||||
fut: T::Future,
|
||||
_guard: CounterGuard,
|
||||
}
|
||||
|
||||
impl<T: Service<Request>, Request> Future for InFlightServiceResponse<T, Request> {
|
||||
impl<T: Service<R>, R> Future for InFlightServiceResponse<T, R> {
|
||||
type Item = T::Response;
|
||||
type Error = T::Error;
|
||||
|
||||
@@ -135,3 +91,74 @@ impl<T: Service<Request>, Request> Future for InFlightServiceResponse<T, Request
|
||||
self.fut.poll()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use futures::future::lazy;
|
||||
use futures::{Async, Poll};
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
use actix_service::blank::{Blank, BlankNewService};
|
||||
use actix_service::{NewService, Service, ServiceExt};
|
||||
|
||||
struct SleepService(Duration);
|
||||
|
||||
impl Service<()> for SleepService {
|
||||
type Response = ();
|
||||
type Error = ();
|
||||
type Future = Box<Future<Item = (), Error = ()>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, _: ()) -> Self::Future {
|
||||
Box::new(tokio_timer::sleep(self.0).map_err(|_| ()))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_transform() {
|
||||
let wait_time = Duration::from_millis(50);
|
||||
let _ = actix_rt::System::new("test").block_on(lazy(|| {
|
||||
let mut srv =
|
||||
Blank::new().and_then(InFlightService::new(1, SleepService(wait_time)));
|
||||
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
|
||||
|
||||
let mut res = srv.call(());
|
||||
let _ = res.poll();
|
||||
assert_eq!(srv.poll_ready(), Ok(Async::NotReady));
|
||||
|
||||
drop(res);
|
||||
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
|
||||
|
||||
Ok::<_, ()>(())
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_newtransform() {
|
||||
let wait_time = Duration::from_millis(50);
|
||||
let _ = actix_rt::System::new("test").block_on(lazy(|| {
|
||||
let srv =
|
||||
BlankNewService::new().apply(InFlight::new(1), || Ok(SleepService(wait_time)));
|
||||
|
||||
if let Async::Ready(mut srv) = srv.new_service(&()).poll().unwrap() {
|
||||
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
|
||||
|
||||
let mut res = srv.call(());
|
||||
let _ = res.poll();
|
||||
assert_eq!(srv.poll_ready(), Ok(Async::NotReady));
|
||||
|
||||
drop(res);
|
||||
assert_eq!(srv.poll_ready(), Ok(Async::Ready(())));
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
|
||||
Ok::<_, ()>(())
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
@@ -1,13 +1,12 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use actix_service::{NewService, Service};
|
||||
use actix_service::{NewService, Service, Void};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
use tokio_timer::Delay;
|
||||
|
||||
use super::time::{LowResTime, LowResTimeService};
|
||||
use super::Never;
|
||||
|
||||
pub struct KeepAlive<R, E, F> {
|
||||
f: F,
|
||||
@@ -44,17 +43,17 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, E, F> NewService<R> for KeepAlive<R, E, F>
|
||||
impl<R, E, F> NewService<R, ()> for KeepAlive<R, E, F>
|
||||
where
|
||||
F: Fn() -> E + Clone,
|
||||
{
|
||||
type Response = R;
|
||||
type Error = E;
|
||||
type InitError = Never;
|
||||
type InitError = Void;
|
||||
type Service = KeepAliveService<R, E, F>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(KeepAliveService::new(
|
||||
self.ka,
|
||||
self.time.timer(),
|
||||
@@ -110,7 +109,7 @@ where
|
||||
}
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::Ready(())),
|
||||
Err(_) => panic!(),
|
||||
Err(_e) => panic!(),
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -6,9 +6,7 @@ pub mod either;
|
||||
pub mod framed;
|
||||
pub mod inflight;
|
||||
pub mod keepalive;
|
||||
pub mod order;
|
||||
pub mod stream;
|
||||
pub mod time;
|
||||
pub mod timeout;
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum Never {}
|
||||
|
264
actix-utils/src/order.rs
Normal file
264
actix-utils/src/order.rs
Normal file
@@ -0,0 +1,264 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_service::{Service, Transform, Void};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::task::AtomicTask;
|
||||
use futures::unsync::oneshot;
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
struct Record<I, E> {
|
||||
rx: oneshot::Receiver<Result<I, E>>,
|
||||
tx: oneshot::Sender<Result<I, E>>,
|
||||
}
|
||||
|
||||
/// Timeout error
|
||||
pub enum InOrderError<E> {
|
||||
/// Service error
|
||||
Service(E),
|
||||
/// Service call dropped
|
||||
Disconnected,
|
||||
}
|
||||
|
||||
impl<E> From<E> for InOrderError<E> {
|
||||
fn from(err: E) -> Self {
|
||||
InOrderError::Service(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: fmt::Debug> fmt::Debug for InOrderError<E> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
InOrderError::Service(e) => write!(f, "InOrderError::Service({:?})", e),
|
||||
InOrderError::Disconnected => write!(f, "InOrderError::Disconnected"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: fmt::Display> fmt::Display for InOrderError<E> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
InOrderError::Service(e) => e.fmt(f),
|
||||
InOrderError::Disconnected => write!(f, "InOrder service disconnected"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// InOrder - The service will yield responses as they become available,
|
||||
/// in the order that their originating requests were submitted to the service.
|
||||
pub struct InOrder<S> {
|
||||
_t: PhantomData<S>,
|
||||
}
|
||||
|
||||
impl<S> InOrder<S> {
|
||||
pub fn new<R>() -> Self
|
||||
where
|
||||
S: Service<R>,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
Self { _t: PhantomData }
|
||||
}
|
||||
|
||||
pub fn service<R>(service: S) -> InOrderService<S, R>
|
||||
where
|
||||
S: Service<R>,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
InOrderService::new(service)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, R> Transform<S, R> for InOrder<S>
|
||||
where
|
||||
S: Service<R>,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
type Response = S::Response;
|
||||
type Error = InOrderError<S::Error>;
|
||||
type InitError = Void;
|
||||
type Transform = InOrderService<S, R>;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ok(InOrderService::new(service))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InOrderService<S: Service<R>, R> {
|
||||
service: S,
|
||||
task: Rc<AtomicTask>,
|
||||
acks: VecDeque<Record<S::Response, S::Error>>,
|
||||
}
|
||||
|
||||
impl<S, R> InOrderService<S, R>
|
||||
where
|
||||
S: Service<R>,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
pub fn new(service: S) -> Self {
|
||||
Self {
|
||||
service,
|
||||
acks: VecDeque::new(),
|
||||
task: Rc::new(AtomicTask::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, R> Service<R> for InOrderService<S, R>
|
||||
where
|
||||
S: Service<R>,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
type Response = S::Response;
|
||||
type Error = InOrderError<S::Error>;
|
||||
type Future = InOrderServiceResponse<S, R>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
// 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();
|
||||
match rec.rx.poll() {
|
||||
Ok(Async::Ready(res)) => {
|
||||
let rec = self.acks.pop_front().unwrap();
|
||||
let _ = rec.tx.send(res);
|
||||
}
|
||||
Ok(Async::NotReady) => break,
|
||||
Err(oneshot::Canceled) => return Err(InOrderError::Disconnected),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, request: R) -> Self::Future {
|
||||
let (tx1, rx1) = oneshot::channel();
|
||||
let (tx2, rx2) = oneshot::channel();
|
||||
self.acks.push_back(Record { rx: rx1, tx: tx2 });
|
||||
|
||||
let task = self.task.clone();
|
||||
tokio_current_thread::spawn(self.service.call(request).then(move |res| {
|
||||
task.notify();
|
||||
let _ = tx1.send(res);
|
||||
Ok(())
|
||||
}));
|
||||
|
||||
InOrderServiceResponse { rx: rx2 }
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct InOrderServiceResponse<S: Service<R>, R> {
|
||||
rx: oneshot::Receiver<Result<S::Response, S::Error>>,
|
||||
}
|
||||
|
||||
impl<S: Service<R>, R> Future for InOrderServiceResponse<S, R> {
|
||||
type Item = S::Response;
|
||||
type Error = InOrderError<S::Error>;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
match self.rx.poll() {
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Ok(Async::Ready(Ok(res))) => Ok(Async::Ready(res)),
|
||||
Ok(Async::Ready(Err(e))) => Err(e.into()),
|
||||
Err(oneshot::Canceled) => Err(InOrderError::Disconnected),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use futures::future::{lazy, Future};
|
||||
use futures::{stream::futures_unordered, sync::oneshot, Async, Poll, Stream};
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
use actix_service::blank::Blank;
|
||||
use actix_service::{Service, ServiceExt};
|
||||
|
||||
struct Srv;
|
||||
|
||||
impl Service<oneshot::Receiver<usize>> for Srv {
|
||||
type Response = usize;
|
||||
type Error = ();
|
||||
type Future = Box<Future<Item = usize, Error = ()>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: oneshot::Receiver<usize>) -> Self::Future {
|
||||
Box::new(req.map_err(|_| ()))
|
||||
}
|
||||
}
|
||||
|
||||
struct SrvPoll<S: Service<oneshot::Receiver<usize>>> {
|
||||
s: S,
|
||||
}
|
||||
|
||||
impl<S: Service<oneshot::Receiver<usize>>> Future for SrvPoll<S> {
|
||||
type Item = ();
|
||||
type Error = ();
|
||||
|
||||
fn poll(&mut self) -> Poll<(), ()> {
|
||||
let _ = self.s.poll_ready();
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inorder() {
|
||||
let (tx1, rx1) = oneshot::channel();
|
||||
let (tx2, rx2) = oneshot::channel();
|
||||
let (tx3, rx3) = oneshot::channel();
|
||||
let (tx_stop, rx_stop) = oneshot::channel();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
let rx1 = rx1;
|
||||
let rx2 = rx2;
|
||||
let rx3 = rx3;
|
||||
let tx_stop = tx_stop;
|
||||
let _ = actix_rt::System::new("test").block_on(lazy(move || {
|
||||
let mut srv = Blank::new().and_then(InOrderService::new(Srv));
|
||||
|
||||
let res1 = srv.call(rx1);
|
||||
let res2 = srv.call(rx2);
|
||||
let res3 = srv.call(rx3);
|
||||
tokio_current_thread::spawn(SrvPoll { s: srv });
|
||||
|
||||
futures_unordered(vec![res1, res2, res3])
|
||||
.collect()
|
||||
.and_then(move |res: Vec<_>| {
|
||||
assert_eq!(res, vec![1, 2, 3]);
|
||||
let _ = tx_stop.send(());
|
||||
Ok(())
|
||||
})
|
||||
}));
|
||||
});
|
||||
|
||||
let _ = tx3.send(3);
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let _ = tx2.send(2);
|
||||
let _ = tx1.send(1);
|
||||
|
||||
let _ = rx_stop.wait();
|
||||
}
|
||||
}
|
@@ -1,35 +1,150 @@
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_rt::spawn;
|
||||
use actix_service::{IntoService, NewService, Service};
|
||||
use actix_service::{IntoNewService, IntoService, NewService, Service};
|
||||
use futures::future::{ok, Future, FutureResult};
|
||||
use futures::unsync::mpsc;
|
||||
use futures::{future, Async, Future, Poll, Stream};
|
||||
use futures::{Async, Poll, Stream};
|
||||
|
||||
pub struct StreamDispatcher<S: Stream, T> {
|
||||
type Request<T> = Result<<T as IntoStream>::Item, <T as IntoStream>::Error>;
|
||||
|
||||
pub trait IntoStream {
|
||||
type Item;
|
||||
type Error;
|
||||
type Stream: Stream<Item = Self::Item, Error = Self::Error>;
|
||||
|
||||
fn into_stream(self) -> Self::Stream;
|
||||
}
|
||||
|
||||
impl<T> IntoStream for T
|
||||
where
|
||||
T: Stream,
|
||||
{
|
||||
type Item = T::Item;
|
||||
type Error = T::Error;
|
||||
type Stream = T;
|
||||
|
||||
fn into_stream(self) -> Self::Stream {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub struct StreamNewService<S, T, E, C> {
|
||||
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<Request<S>, C, Response = (), Error = E, InitError = E>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service<Request<S>>>::Future: 'static,
|
||||
{
|
||||
pub fn new<F: IntoNewService<T, Request<S>, 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<S, C> for StreamNewService<S, T, E, C>
|
||||
where
|
||||
C: Clone,
|
||||
S: IntoStream + 'static,
|
||||
T: NewService<Request<S>, C, Response = (), Error = E, InitError = E>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service<Request<S>>>::Future: 'static,
|
||||
{
|
||||
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,
|
||||
_t: PhantomData<(S, E)>,
|
||||
}
|
||||
|
||||
impl<S, T, E, C> Service<S> for StreamService<S, T, E, C>
|
||||
where
|
||||
S: IntoStream + 'static,
|
||||
T: NewService<Request<S>, C, Response = (), Error = E, InitError = E>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service<Request<S>>>::Future: 'static,
|
||||
C: Clone,
|
||||
{
|
||||
type Response = ();
|
||||
type Error = E;
|
||||
type Future = Box<Future<Item = (), Error = E>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, req: S) -> Self::Future {
|
||||
Box::new(
|
||||
self.factory
|
||||
.new_service(&self.config)
|
||||
.and_then(move |srv| StreamDispatcher::new(req, srv)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct StreamDispatcher<S, T>
|
||||
where
|
||||
S: IntoStream + 'static,
|
||||
T: Service<Request<S>, Response = ()> + 'static,
|
||||
T::Future: 'static,
|
||||
{
|
||||
stream: S,
|
||||
service: T,
|
||||
item: Option<Result<S::Item, S::Error>>,
|
||||
stop_rx: mpsc::UnboundedReceiver<()>,
|
||||
stop_tx: mpsc::UnboundedSender<()>,
|
||||
err_rx: mpsc::UnboundedReceiver<T::Error>,
|
||||
err_tx: mpsc::UnboundedSender<T::Error>,
|
||||
}
|
||||
|
||||
impl<S, T> StreamDispatcher<S, T>
|
||||
where
|
||||
S: Stream,
|
||||
T: Service<Result<S::Item, S::Error>, Response = (), Error = ()>,
|
||||
T: Service<Request<S>, Response = ()>,
|
||||
T::Future: 'static,
|
||||
{
|
||||
pub fn new<F>(stream: S, service: F) -> Self
|
||||
pub fn new<F1, F2>(stream: F1, service: F2) -> Self
|
||||
where
|
||||
F: IntoService<T, Result<S::Item, S::Error>>,
|
||||
F1: IntoStream<Stream = S, Item = S::Item, Error = S::Error>,
|
||||
F2: IntoService<T, Request<S>>,
|
||||
{
|
||||
let (stop_tx, stop_rx) = mpsc::unbounded();
|
||||
let (err_tx, err_rx) = mpsc::unbounded();
|
||||
StreamDispatcher {
|
||||
stream,
|
||||
item: None,
|
||||
err_rx,
|
||||
err_tx,
|
||||
stream: stream.into_stream(),
|
||||
service: service.into_service(),
|
||||
stop_rx,
|
||||
stop_tx,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,36 +152,34 @@ where
|
||||
impl<S, T> Future for StreamDispatcher<S, T>
|
||||
where
|
||||
S: Stream,
|
||||
T: Service<Result<S::Item, S::Error>, Response = (), Error = ()>,
|
||||
T: Service<Request<S>, Response = ()>,
|
||||
T::Future: 'static,
|
||||
{
|
||||
type Item = ();
|
||||
type Error = ();
|
||||
type Error = T::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Ok(Async::Ready(Some(_))) = self.stop_rx.poll() {
|
||||
return Ok(Async::Ready(()));
|
||||
if let Ok(Async::Ready(Some(e))) = self.err_rx.poll() {
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let mut item = self.item.take();
|
||||
loop {
|
||||
if item.is_some() {
|
||||
match self.service.poll_ready()? {
|
||||
Async::Ready(_) => spawn(StreamDispatcherService {
|
||||
fut: self.service.call(item.take().unwrap()),
|
||||
stop: self.stop_tx.clone(),
|
||||
}),
|
||||
Async::NotReady => {
|
||||
self.item = item;
|
||||
return Ok(Async::NotReady);
|
||||
match self.service.poll_ready()? {
|
||||
Async::Ready(_) => match self.stream.poll() {
|
||||
Ok(Async::Ready(Some(item))) => {
|
||||
tokio_current_thread::spawn(StreamDispatcherService {
|
||||
fut: self.service.call(Ok(item)),
|
||||
stop: self.err_tx.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
match self.stream.poll() {
|
||||
Ok(Async::Ready(Some(el))) => item = Some(Ok(el)),
|
||||
Err(err) => item = Some(Err(err)),
|
||||
Ok(Async::NotReady) => return Ok(Async::NotReady),
|
||||
Ok(Async::Ready(None)) => return Ok(Async::Ready(())),
|
||||
Err(err) => tokio_current_thread::spawn(StreamDispatcherService {
|
||||
fut: self.service.call(Err(err)),
|
||||
stop: self.err_tx.clone(),
|
||||
}),
|
||||
Ok(Async::NotReady) => return Ok(Async::NotReady),
|
||||
Ok(Async::Ready(None)) => return Ok(Async::Ready(())),
|
||||
},
|
||||
Async::NotReady => return Ok(Async::NotReady),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,7 +187,7 @@ where
|
||||
|
||||
struct StreamDispatcherService<F: Future> {
|
||||
fut: F,
|
||||
stop: mpsc::UnboundedSender<()>,
|
||||
stop: mpsc::UnboundedSender<F::Error>,
|
||||
}
|
||||
|
||||
impl<F: Future> Future for StreamDispatcherService<F> {
|
||||
@@ -85,8 +198,8 @@ impl<F: Future> Future for StreamDispatcherService<F> {
|
||||
match self.fut.poll() {
|
||||
Ok(Async::Ready(_)) => Ok(Async::Ready(())),
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
Err(_) => {
|
||||
let _ = self.stop.unbounded_send(());
|
||||
Err(e) => {
|
||||
let _ = self.stop.unbounded_send(e);
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
}
|
||||
@@ -117,15 +230,15 @@ impl<T> Clone for TakeItem<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Stream> NewService<T> for TakeItem<T> {
|
||||
impl<T: Stream> NewService<T, ()> for TakeItem<T> {
|
||||
type Response = (Option<T::Item>, T);
|
||||
type Error = T::Error;
|
||||
type InitError = ();
|
||||
type Service = TakeItemService<T>;
|
||||
type Future = future::FutureResult<Self::Service, Self::InitError>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
future::ok(TakeItemService { _t: PhantomData })
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(TakeItemService { _t: PhantomData })
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -1,13 +1,11 @@
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::{self, Duration, Instant};
|
||||
|
||||
use actix_rt::spawn;
|
||||
use actix_service::{NewService, Service};
|
||||
use actix_service::{NewService, Service, Void};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
use tokio_timer::sleep;
|
||||
|
||||
use super::cell::Cell;
|
||||
use super::Never;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LowResTime(Cell<Inner>);
|
||||
@@ -45,12 +43,12 @@ impl Default for LowResTime {
|
||||
|
||||
impl NewService<()> for LowResTime {
|
||||
type Response = Instant;
|
||||
type Error = Never;
|
||||
type InitError = Never;
|
||||
type Error = Void;
|
||||
type InitError = Void;
|
||||
type Service = LowResTimeService;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(self.timer())
|
||||
}
|
||||
}
|
||||
@@ -66,22 +64,24 @@ impl LowResTimeService {
|
||||
/// Get current time. This function has to be called from
|
||||
/// future's poll method, otherwise it panics.
|
||||
pub fn now(&self) -> Instant {
|
||||
let cur = self.0.borrow().current;
|
||||
let cur = self.0.get_ref().current;
|
||||
if let Some(cur) = cur {
|
||||
cur
|
||||
} else {
|
||||
let now = Instant::now();
|
||||
let inner = self.0.clone();
|
||||
let mut inner = self.0.clone();
|
||||
let interval = {
|
||||
let mut b = inner.borrow_mut();
|
||||
let mut b = inner.get_mut();
|
||||
b.current = Some(now);
|
||||
b.resolution
|
||||
};
|
||||
|
||||
spawn(sleep(interval).map_err(|_| panic!()).and_then(move |_| {
|
||||
inner.borrow_mut().current.take();
|
||||
Ok(())
|
||||
}));
|
||||
tokio_current_thread::spawn(sleep(interval).map_err(|_| panic!()).and_then(
|
||||
move |_| {
|
||||
inner.get_mut().current.take();
|
||||
Ok(())
|
||||
},
|
||||
));
|
||||
now
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,7 @@ impl LowResTimeService {
|
||||
|
||||
impl Service<()> for LowResTimeService {
|
||||
type Response = Instant;
|
||||
type Error = Never;
|
||||
type Error = Void;
|
||||
type Future = FutureResult<Self::Response, Self::Error>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
@@ -100,3 +100,148 @@ impl Service<()> for LowResTimeService {
|
||||
ok(self.now())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SystemTime(Cell<SystemTimeInner>);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SystemTimeInner {
|
||||
resolution: Duration,
|
||||
current: Option<time::SystemTime>,
|
||||
}
|
||||
|
||||
impl SystemTimeInner {
|
||||
fn new(resolution: Duration) -> Self {
|
||||
SystemTimeInner {
|
||||
resolution,
|
||||
current: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SystemTimeService(Cell<SystemTimeInner>);
|
||||
|
||||
impl SystemTimeService {
|
||||
pub fn with(resolution: Duration) -> SystemTimeService {
|
||||
SystemTimeService(Cell::new(SystemTimeInner::new(resolution)))
|
||||
}
|
||||
|
||||
/// Get current time. This function has to be called from
|
||||
/// future's poll method, otherwise it panics.
|
||||
pub fn now(&self) -> time::SystemTime {
|
||||
let cur = self.0.get_ref().current;
|
||||
if let Some(cur) = cur {
|
||||
cur
|
||||
} else {
|
||||
let now = time::SystemTime::now();
|
||||
let mut inner = self.0.clone();
|
||||
let interval = {
|
||||
let mut b = inner.get_mut();
|
||||
b.current = Some(now);
|
||||
b.resolution
|
||||
};
|
||||
|
||||
tokio_current_thread::spawn(sleep(interval).map_err(|_| panic!()).and_then(
|
||||
move |_| {
|
||||
inner.get_mut().current.take();
|
||||
Ok(())
|
||||
},
|
||||
));
|
||||
now
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use futures::future;
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
/// State Under Test: Two calls of `SystemTimeService::now()` return the same value if they are done within resolution interval of `SystemTimeService`.
|
||||
///
|
||||
/// Expected Behavior: Two back-to-back calls of `SystemTimeService::now()` return the same value.
|
||||
#[test]
|
||||
fn system_time_service_time_does_not_immediately_change() {
|
||||
let resolution = Duration::from_millis(50);
|
||||
|
||||
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
|
||||
let time_service = SystemTimeService::with(resolution);
|
||||
|
||||
assert_eq!(time_service.now(), time_service.now());
|
||||
|
||||
Ok::<(), ()>(())
|
||||
}));
|
||||
}
|
||||
|
||||
/// State Under Test: Two calls of `LowResTimeService::now()` return the same value if they are done within resolution interval of `SystemTimeService`.
|
||||
///
|
||||
/// Expected Behavior: Two back-to-back calls of `LowResTimeService::now()` return the same value.
|
||||
#[test]
|
||||
fn lowres_time_service_time_does_not_immediately_change() {
|
||||
let resolution = Duration::from_millis(50);
|
||||
|
||||
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
|
||||
let time_service = LowResTimeService::with(resolution);
|
||||
|
||||
assert_eq!(time_service.now(), time_service.now());
|
||||
|
||||
Ok::<(), ()>(())
|
||||
}));
|
||||
}
|
||||
|
||||
/// State Under Test: `SystemTimeService::now()` updates returned value every resolution period.
|
||||
///
|
||||
/// Expected Behavior: Two calls of `LowResTimeService::now()` made in subsequent resolution interval return different values
|
||||
/// and second value is greater than the first one at least by a resolution interval.
|
||||
#[test]
|
||||
fn system_time_service_time_updates_after_resolution_interval() {
|
||||
let resolution = Duration::from_millis(100);
|
||||
let wait_time = Duration::from_millis(150);
|
||||
|
||||
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
|
||||
let time_service = SystemTimeService::with(resolution);
|
||||
|
||||
let first_time = time_service
|
||||
.now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.unwrap();
|
||||
|
||||
sleep(wait_time).then(move |_| {
|
||||
let second_time = time_service
|
||||
.now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.unwrap();
|
||||
|
||||
assert!(second_time - first_time >= wait_time);
|
||||
|
||||
Ok::<(), ()>(())
|
||||
})
|
||||
}));
|
||||
}
|
||||
|
||||
/// State Under Test: `LowResTimeService::now()` updates returned value every resolution period.
|
||||
///
|
||||
/// Expected Behavior: Two calls of `LowResTimeService::now()` made in subsequent resolution interval return different values
|
||||
/// and second value is greater than the first one at least by a resolution interval.
|
||||
#[test]
|
||||
fn lowres_time_service_time_updates_after_resolution_interval() {
|
||||
let resolution = Duration::from_millis(100);
|
||||
let wait_time = Duration::from_millis(150);
|
||||
|
||||
let _ = actix_rt::System::new("test").block_on(future::lazy(|| {
|
||||
let time_service = LowResTimeService::with(resolution);
|
||||
|
||||
let first_time = time_service.now();
|
||||
|
||||
sleep(wait_time).then(move |_| {
|
||||
let second_time = time_service.now();
|
||||
|
||||
assert!(second_time - first_time >= wait_time);
|
||||
|
||||
Ok::<(), ()>(())
|
||||
})
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
@@ -3,18 +3,19 @@
|
||||
//! If the response does not complete within the specified timeout, the response
|
||||
//! will be aborted.
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::time::Duration;
|
||||
|
||||
use actix_service::{NewService, Service};
|
||||
use futures::try_ready;
|
||||
use actix_service::{Service, Transform};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
use tokio_timer::{clock, Delay};
|
||||
|
||||
/// Applies a timeout to requests.
|
||||
#[derive(Debug)]
|
||||
pub struct Timeout<T> {
|
||||
inner: T,
|
||||
pub struct Timeout<E = ()> {
|
||||
timeout: Duration,
|
||||
_t: PhantomData<E>,
|
||||
}
|
||||
|
||||
/// Timeout error
|
||||
@@ -25,6 +26,12 @@ pub enum TimeoutError<E> {
|
||||
Timeout,
|
||||
}
|
||||
|
||||
impl<E> From<E> for TimeoutError<E> {
|
||||
fn from(err: E) -> Self {
|
||||
TimeoutError::Service(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
@@ -34,93 +41,91 @@ impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Timeout<T> {
|
||||
pub fn new<Request>(timeout: Duration, inner: T) -> Self
|
||||
where
|
||||
T: NewService<Request> + Clone,
|
||||
{
|
||||
Timeout { inner, timeout }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Request> NewService<Request> for Timeout<T>
|
||||
where
|
||||
T: NewService<Request> + Clone,
|
||||
{
|
||||
type Response = T::Response;
|
||||
type Error = TimeoutError<T::Error>;
|
||||
type InitError = T::InitError;
|
||||
type Service = TimeoutService<T::Service>;
|
||||
type Future = TimeoutFut<T, Request>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
TimeoutFut {
|
||||
fut: self.inner.new_service(),
|
||||
timeout: self.timeout,
|
||||
impl<E: fmt::Display> fmt::Display for TimeoutError<E> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
TimeoutError::Service(e) => e.fmt(f),
|
||||
TimeoutError::Timeout => write!(f, "Service call timeout"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `Timeout` response future
|
||||
#[derive(Debug)]
|
||||
pub struct TimeoutFut<T: NewService<Request>, Request> {
|
||||
fut: T::Future,
|
||||
timeout: Duration,
|
||||
impl<E: PartialEq> PartialEq for TimeoutError<E> {
|
||||
fn eq(&self, other: &TimeoutError<E>) -> bool {
|
||||
match self {
|
||||
TimeoutError::Service(e1) => match other {
|
||||
TimeoutError::Service(e2) => e1 == e2,
|
||||
TimeoutError::Timeout => false,
|
||||
},
|
||||
TimeoutError::Timeout => match other {
|
||||
TimeoutError::Service(_) => false,
|
||||
TimeoutError::Timeout => true,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Request> Future for TimeoutFut<T, Request>
|
||||
where
|
||||
T: NewService<Request>,
|
||||
{
|
||||
type Item = TimeoutService<T::Service>;
|
||||
type Error = T::InitError;
|
||||
impl<E> Timeout<E> {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
Timeout {
|
||||
timeout,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
let service = try_ready!(self.fut.poll());
|
||||
Ok(Async::Ready(TimeoutService::new(self.timeout, service)))
|
||||
impl<E> Clone for Timeout<E> {
|
||||
fn clone(&self) -> Self {
|
||||
Timeout::new(self.timeout)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, R, E> Transform<S, R> for Timeout<E>
|
||||
where
|
||||
S: Service<R>,
|
||||
{
|
||||
type Response = S::Response;
|
||||
type Error = TimeoutError<S::Error>;
|
||||
type InitError = E;
|
||||
type Transform = TimeoutService<S>;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn new_transform(&self, service: S) -> Self::Future {
|
||||
ok(TimeoutService {
|
||||
service,
|
||||
timeout: self.timeout,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a timeout to requests.
|
||||
#[derive(Debug)]
|
||||
pub struct TimeoutService<T> {
|
||||
inner: T,
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TimeoutService<S> {
|
||||
service: S,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl<T> TimeoutService<T> {
|
||||
pub fn new<Request>(timeout: Duration, inner: T) -> Self
|
||||
where
|
||||
T: Service<Request>,
|
||||
{
|
||||
TimeoutService { inner, timeout }
|
||||
impl<S> TimeoutService<S> {
|
||||
pub fn new(timeout: Duration, service: S) -> Self {
|
||||
TimeoutService { service, timeout }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> Clone for TimeoutService<T> {
|
||||
fn clone(&self) -> Self {
|
||||
TimeoutService {
|
||||
inner: self.inner.clone(),
|
||||
timeout: self.timeout,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Request> Service<Request> for TimeoutService<T>
|
||||
impl<S, R> Service<R> for TimeoutService<S>
|
||||
where
|
||||
T: Service<Request>,
|
||||
S: Service<R>,
|
||||
{
|
||||
type Response = T::Response;
|
||||
type Error = TimeoutError<T::Error>;
|
||||
type Future = TimeoutServiceResponse<T, Request>;
|
||||
type Response = S::Response;
|
||||
type Error = TimeoutError<S::Error>;
|
||||
type Future = TimeoutServiceResponse<S, R>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.inner.poll_ready().map_err(TimeoutError::Service)
|
||||
self.service.poll_ready().map_err(TimeoutError::Service)
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Request) -> Self::Future {
|
||||
fn call(&mut self, request: R) -> Self::Future {
|
||||
TimeoutServiceResponse {
|
||||
fut: self.inner.call(request),
|
||||
fut: self.service.call(request),
|
||||
sleep: Delay::new(clock::now() + self.timeout),
|
||||
}
|
||||
}
|
||||
@@ -128,14 +133,14 @@ where
|
||||
|
||||
/// `TimeoutService` response future
|
||||
#[derive(Debug)]
|
||||
pub struct TimeoutServiceResponse<T: Service<Request>, Request> {
|
||||
pub struct TimeoutServiceResponse<T: Service<R>, R> {
|
||||
fut: T::Future,
|
||||
sleep: Delay,
|
||||
}
|
||||
|
||||
impl<T, Request> Future for TimeoutServiceResponse<T, Request>
|
||||
impl<T, R> Future for TimeoutServiceResponse<T, R>
|
||||
where
|
||||
T: Service<Request>,
|
||||
T: Service<R>,
|
||||
{
|
||||
type Item = T::Response;
|
||||
type Error = TimeoutError<T::Error>;
|
||||
@@ -156,3 +161,74 @@ where
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use futures::future::lazy;
|
||||
use futures::{Async, Poll};
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
use actix_service::blank::{Blank, BlankNewService};
|
||||
use actix_service::{NewService, Service, ServiceExt};
|
||||
|
||||
struct SleepService(Duration);
|
||||
|
||||
impl Service<()> for SleepService {
|
||||
type Response = ();
|
||||
type Error = ();
|
||||
type Future = Box<Future<Item = (), Error = ()>>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, _: ()) -> Self::Future {
|
||||
Box::new(tokio_timer::sleep(self.0).map_err(|_| ()))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_success() {
|
||||
let resolution = Duration::from_millis(100);
|
||||
let wait_time = Duration::from_millis(50);
|
||||
|
||||
let res = actix_rt::System::new("test").block_on(lazy(|| {
|
||||
let mut timeout = Blank::default()
|
||||
.and_then(TimeoutService::new(resolution, SleepService(wait_time)));
|
||||
timeout.call(())
|
||||
}));
|
||||
assert_eq!(res, Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_timeout() {
|
||||
let resolution = Duration::from_millis(100);
|
||||
let wait_time = Duration::from_millis(150);
|
||||
|
||||
let res = actix_rt::System::new("test").block_on(lazy(|| {
|
||||
let mut timeout = Blank::default()
|
||||
.and_then(TimeoutService::new(resolution, SleepService(wait_time)));
|
||||
timeout.call(())
|
||||
}));
|
||||
assert_eq!(res, Err(TimeoutError::Timeout));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_timeout_newservice() {
|
||||
let resolution = Duration::from_millis(100);
|
||||
let wait_time = Duration::from_millis(150);
|
||||
|
||||
let res = actix_rt::System::new("test").block_on(lazy(|| {
|
||||
let timeout = BlankNewService::<(), (), ()>::default()
|
||||
.apply(Timeout::new(resolution), || Ok(SleepService(wait_time)));
|
||||
if let Async::Ready(mut to) = timeout.new_service(&()).poll().unwrap() {
|
||||
to.call(())
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
}));
|
||||
assert_eq!(res, Err(TimeoutError::Timeout));
|
||||
}
|
||||
}
|
||||
|
31
router/Cargo.toml
Normal file
31
router/Cargo.toml
Normal file
@@ -0,0 +1,31 @@
|
||||
[package]
|
||||
name = "actix-router"
|
||||
version = "0.1.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Path 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/"
|
||||
license = "MIT/Apache-2.0"
|
||||
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
|
||||
edition = "2018"
|
||||
workspace = "../"
|
||||
|
||||
[lib]
|
||||
name = "actix_router"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[features]
|
||||
default = ["http"]
|
||||
|
||||
[dependencies]
|
||||
bytes = "0.4"
|
||||
regex = "1.0"
|
||||
serde = "1.0.80"
|
||||
string = "0.1.3"
|
||||
http = { version="0.1.14", optional=true }
|
||||
|
||||
[dev-dependencies]
|
||||
http = "0.1.14"
|
||||
serde_derive = "1.0"
|
709
router/src/de.rs
Normal file
709
router/src/de.rs
Normal file
@@ -0,0 +1,709 @@
|
||||
use serde::de::{self, Deserializer, Error as DeError, Visitor};
|
||||
use serde::forward_to_deserialize_any;
|
||||
|
||||
use crate::path::{Path, PathIter};
|
||||
use crate::ResourcePath;
|
||||
|
||||
macro_rules! unsupported_type {
|
||||
($trait_fn:ident, $name:expr) => {
|
||||
fn $trait_fn<V>(self, _: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor<'de>
|
||||
{
|
||||
Err(de::value::Error::custom(concat!("unsupported type: ", $name)))
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! parse_single_value {
|
||||
($trait_fn:ident, $visit_fn:ident, $tp:tt) => {
|
||||
fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor<'de>
|
||||
{
|
||||
if self.path.len() != 1 {
|
||||
Err(de::value::Error::custom(
|
||||
format!("wrong number of parameters: {} expected 1",
|
||||
self.path.len()).as_str()))
|
||||
} else {
|
||||
let v = self.path[0].parse().map_err(
|
||||
|_| de::value::Error::custom(
|
||||
format!("can not parse {:?} to a {}", &self.path[0], $tp)))?;
|
||||
visitor.$visit_fn(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PathDeserializer<'de, T: ResourcePath + 'de> {
|
||||
path: &'de Path<T>,
|
||||
}
|
||||
|
||||
impl<'de, T: ResourcePath + 'de> PathDeserializer<'de, T> {
|
||||
pub fn new(path: &'de Path<T>) -> Self {
|
||||
PathDeserializer { path }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, T: ResourcePath + 'de> Deserializer<'de> for PathDeserializer<'de, T> {
|
||||
type Error = de::value::Error;
|
||||
|
||||
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_map(ParamsDeserializer {
|
||||
params: self.path.iter(),
|
||||
current: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn deserialize_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.deserialize_map(visitor)
|
||||
}
|
||||
|
||||
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_unit_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
self.deserialize_unit(visitor)
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
if self.path.len() < len {
|
||||
Err(de::value::Error::custom(
|
||||
format!(
|
||||
"wrong number of parameters: {} expected {}",
|
||||
self.path.len(),
|
||||
len
|
||||
)
|
||||
.as_str(),
|
||||
))
|
||||
} else {
|
||||
visitor.visit_seq(ParamsSeq {
|
||||
params: self.path.iter(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_tuple_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
len: usize,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
if self.path.len() < len {
|
||||
Err(de::value::Error::custom(
|
||||
format!(
|
||||
"wrong number of parameters: {} expected {}",
|
||||
self.path.len(),
|
||||
len
|
||||
)
|
||||
.as_str(),
|
||||
))
|
||||
} else {
|
||||
visitor.visit_seq(ParamsSeq {
|
||||
params: self.path.iter(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
if self.path.len() < 1 {
|
||||
Err(de::value::Error::custom(
|
||||
"expeceted at least one parameters",
|
||||
))
|
||||
} else {
|
||||
visitor.visit_enum(ValueEnum {
|
||||
value: &self.path[0],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
if self.path.len() != 1 {
|
||||
Err(de::value::Error::custom(
|
||||
format!("wrong number of parameters: {} expected 1", self.path.len()).as_str(),
|
||||
))
|
||||
} else {
|
||||
visitor.visit_str(&self.path[0])
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_seq(ParamsSeq {
|
||||
params: self.path.iter(),
|
||||
})
|
||||
}
|
||||
|
||||
unsupported_type!(deserialize_any, "'any'");
|
||||
unsupported_type!(deserialize_bytes, "bytes");
|
||||
unsupported_type!(deserialize_option, "Option<T>");
|
||||
unsupported_type!(deserialize_identifier, "identifier");
|
||||
unsupported_type!(deserialize_ignored_any, "ignored_any");
|
||||
|
||||
parse_single_value!(deserialize_bool, visit_bool, "bool");
|
||||
parse_single_value!(deserialize_i8, visit_i8, "i8");
|
||||
parse_single_value!(deserialize_i16, visit_i16, "i16");
|
||||
parse_single_value!(deserialize_i32, visit_i32, "i32");
|
||||
parse_single_value!(deserialize_i64, visit_i64, "i64");
|
||||
parse_single_value!(deserialize_u8, visit_u8, "u8");
|
||||
parse_single_value!(deserialize_u16, visit_u16, "u16");
|
||||
parse_single_value!(deserialize_u32, visit_u32, "u32");
|
||||
parse_single_value!(deserialize_u64, visit_u64, "u64");
|
||||
parse_single_value!(deserialize_f32, visit_f32, "f32");
|
||||
parse_single_value!(deserialize_f64, visit_f64, "f64");
|
||||
parse_single_value!(deserialize_string, visit_string, "String");
|
||||
parse_single_value!(deserialize_byte_buf, visit_string, "String");
|
||||
parse_single_value!(deserialize_char, visit_char, "char");
|
||||
}
|
||||
|
||||
struct ParamsDeserializer<'de, T: ResourcePath> {
|
||||
params: PathIter<'de, T>,
|
||||
current: Option<(&'de str, &'de str)>,
|
||||
}
|
||||
|
||||
impl<'de, T: ResourcePath> de::MapAccess<'de> for ParamsDeserializer<'de, T> {
|
||||
type Error = de::value::Error;
|
||||
|
||||
fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error>
|
||||
where
|
||||
K: de::DeserializeSeed<'de>,
|
||||
{
|
||||
self.current = self.params.next().map(|ref item| (item.0, item.1));
|
||||
match self.current {
|
||||
Some((key, _)) => Ok(Some(seed.deserialize(Key { key })?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: de::DeserializeSeed<'de>,
|
||||
{
|
||||
if let Some((_, value)) = self.current.take() {
|
||||
seed.deserialize(Value { value })
|
||||
} else {
|
||||
Err(de::value::Error::custom("unexpected item"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Key<'de> {
|
||||
key: &'de str,
|
||||
}
|
||||
|
||||
impl<'de> Deserializer<'de> for Key<'de> {
|
||||
type Error = de::value::Error;
|
||||
|
||||
fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_str(self.key)
|
||||
}
|
||||
|
||||
fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("Unexpected"))
|
||||
}
|
||||
|
||||
forward_to_deserialize_any! {
|
||||
bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes
|
||||
byte_buf option unit unit_struct newtype_struct seq tuple
|
||||
tuple_struct map struct enum ignored_any
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! parse_value {
|
||||
($trait_fn:ident, $visit_fn:ident, $tp:tt) => {
|
||||
fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where V: Visitor<'de>
|
||||
{
|
||||
let v = self.value.parse().map_err(
|
||||
|_| de::value::Error::custom(
|
||||
format!("can not parse {:?} to a {}", self.value, $tp)))?;
|
||||
visitor.$visit_fn(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Value<'de> {
|
||||
value: &'de str,
|
||||
}
|
||||
|
||||
impl<'de> Deserializer<'de> for Value<'de> {
|
||||
type Error = de::value::Error;
|
||||
|
||||
parse_value!(deserialize_bool, visit_bool, "bool");
|
||||
parse_value!(deserialize_i8, visit_i8, "i8");
|
||||
parse_value!(deserialize_i16, visit_i16, "i16");
|
||||
parse_value!(deserialize_i32, visit_i32, "i16");
|
||||
parse_value!(deserialize_i64, visit_i64, "i64");
|
||||
parse_value!(deserialize_u8, visit_u8, "u8");
|
||||
parse_value!(deserialize_u16, visit_u16, "u16");
|
||||
parse_value!(deserialize_u32, visit_u32, "u32");
|
||||
parse_value!(deserialize_u64, visit_u64, "u64");
|
||||
parse_value!(deserialize_f32, visit_f32, "f32");
|
||||
parse_value!(deserialize_f64, visit_f64, "f64");
|
||||
parse_value!(deserialize_string, visit_string, "String");
|
||||
parse_value!(deserialize_byte_buf, visit_string, "String");
|
||||
parse_value!(deserialize_char, visit_char, "char");
|
||||
|
||||
fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_unit_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_unit()
|
||||
}
|
||||
|
||||
fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_borrowed_bytes(self.value.as_bytes())
|
||||
}
|
||||
|
||||
fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_borrowed_str(self.value)
|
||||
}
|
||||
|
||||
fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_some(self)
|
||||
}
|
||||
|
||||
fn deserialize_enum<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: &'static [&'static str],
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_enum(ValueEnum { value: self.value })
|
||||
}
|
||||
|
||||
fn deserialize_newtype_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
visitor: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
visitor.visit_newtype_struct(self)
|
||||
}
|
||||
|
||||
fn deserialize_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("unsupported type: tuple"))
|
||||
}
|
||||
|
||||
fn deserialize_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: &'static [&'static str],
|
||||
_: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("unsupported type: struct"))
|
||||
}
|
||||
|
||||
fn deserialize_tuple_struct<V>(
|
||||
self,
|
||||
_: &'static str,
|
||||
_: usize,
|
||||
_: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("unsupported type: tuple struct"))
|
||||
}
|
||||
|
||||
unsupported_type!(deserialize_any, "any");
|
||||
unsupported_type!(deserialize_seq, "seq");
|
||||
unsupported_type!(deserialize_map, "map");
|
||||
unsupported_type!(deserialize_identifier, "identifier");
|
||||
}
|
||||
|
||||
struct ParamsSeq<'de, T: ResourcePath> {
|
||||
params: PathIter<'de, T>,
|
||||
}
|
||||
|
||||
impl<'de, T: ResourcePath> de::SeqAccess<'de> for ParamsSeq<'de, T> {
|
||||
type Error = de::value::Error;
|
||||
|
||||
fn next_element_seed<U>(&mut self, seed: U) -> Result<Option<U::Value>, Self::Error>
|
||||
where
|
||||
U: de::DeserializeSeed<'de>,
|
||||
{
|
||||
match self.params.next() {
|
||||
Some(item) => Ok(Some(seed.deserialize(Value { value: item.1 })?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ValueEnum<'de> {
|
||||
value: &'de str,
|
||||
}
|
||||
|
||||
impl<'de> de::EnumAccess<'de> for ValueEnum<'de> {
|
||||
type Error = de::value::Error;
|
||||
type Variant = UnitVariant;
|
||||
|
||||
fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error>
|
||||
where
|
||||
V: de::DeserializeSeed<'de>,
|
||||
{
|
||||
Ok((seed.deserialize(Key { key: self.value })?, UnitVariant))
|
||||
}
|
||||
}
|
||||
|
||||
struct UnitVariant;
|
||||
|
||||
impl<'de> de::VariantAccess<'de> for UnitVariant {
|
||||
type Error = de::value::Error;
|
||||
|
||||
fn unit_variant(self) -> Result<(), Self::Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
|
||||
where
|
||||
T: de::DeserializeSeed<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("not supported"))
|
||||
}
|
||||
|
||||
fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("not supported"))
|
||||
}
|
||||
|
||||
fn struct_variant<V>(
|
||||
self,
|
||||
_: &'static [&'static str],
|
||||
_: V,
|
||||
) -> Result<V::Value, Self::Error>
|
||||
where
|
||||
V: Visitor<'de>,
|
||||
{
|
||||
Err(de::value::Error::custom("not supported"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde::de;
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
use super::*;
|
||||
use crate::path::Path;
|
||||
use crate::router::Router;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MyStruct {
|
||||
key: String,
|
||||
value: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Id {
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Test1(String, u32);
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Test2 {
|
||||
key: String,
|
||||
value: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum TestEnum {
|
||||
Val1,
|
||||
Val2,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Test3 {
|
||||
val: TestEnum,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_request_extract() {
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{key}/{value}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/name/user1/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
|
||||
let s: MyStruct = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(s.key, "name");
|
||||
assert_eq!(s.value, "user1");
|
||||
|
||||
let s: (String, String) =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(s.0, "name");
|
||||
assert_eq!(s.1, "user1");
|
||||
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{key}/{value}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/name/32/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
|
||||
let s: Test1 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(s.0, "name");
|
||||
assert_eq!(s.1, 32);
|
||||
|
||||
let s: Test2 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(s.key, "name");
|
||||
assert_eq!(s.value, 32);
|
||||
|
||||
let s: (String, u8) =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(s.0, "name");
|
||||
assert_eq!(s.1, 32);
|
||||
|
||||
let res: Vec<String> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(res[0], "name".to_owned());
|
||||
assert_eq!(res[1], "32".to_owned());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_path_single() {
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{value}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/32/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
let i: i8 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(i, 32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_enum() {
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{val}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/val1/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
let i: TestEnum = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(i, TestEnum::Val1);
|
||||
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{val1}/{val2}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/val1/val2/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
let i: (TestEnum, TestEnum) =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(i, (TestEnum::Val1, TestEnum::Val2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_enum_value() {
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{val}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/val1/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
let i: Test3 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap();
|
||||
assert_eq!(i.val, TestEnum::Val1);
|
||||
|
||||
let mut path = Path::new("/val3/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
let i: Result<Test3, de::value::Error> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path));
|
||||
assert!(i.is_err());
|
||||
assert!(format!("{:?}", i).contains("unknown variant"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_errors() {
|
||||
let mut router = Router::<()>::build();
|
||||
router.path("/{value}/", ());
|
||||
let router = router.finish();
|
||||
|
||||
let mut path = Path::new("/name/");
|
||||
assert!(router.recognize(&mut path).is_some());
|
||||
|
||||
let s: Result<Test1, de::value::Error> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path));
|
||||
assert!(s.is_err());
|
||||
assert!(format!("{:?}", s).contains("wrong number of parameters"));
|
||||
|
||||
let s: Result<Test2, de::value::Error> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path));
|
||||
assert!(s.is_err());
|
||||
assert!(format!("{:?}", s).contains("can not parse"));
|
||||
|
||||
let s: Result<(String, String), de::value::Error> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path));
|
||||
assert!(s.is_err());
|
||||
assert!(format!("{:?}", s).contains("wrong number of parameters"));
|
||||
|
||||
let s: Result<u32, de::value::Error> =
|
||||
de::Deserialize::deserialize(PathDeserializer::new(&path));
|
||||
assert!(s.is_err());
|
||||
assert!(format!("{:?}", s).contains("can not parse"));
|
||||
}
|
||||
|
||||
// #[test]
|
||||
// fn test_extract_path_decode() {
|
||||
// let mut router = Router::<()>::default();
|
||||
// router.register_resource(Resource::new(ResourceDef::new("/{value}/")));
|
||||
|
||||
// macro_rules! test_single_value {
|
||||
// ($value:expr, $expected:expr) => {{
|
||||
// let req = TestRequest::with_uri($value).finish();
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// let req = req.with_route_info(info);
|
||||
// assert_eq!(
|
||||
// *Path::<String>::from_request(&req, &PathConfig::default()).unwrap(),
|
||||
// $expected
|
||||
// );
|
||||
// }};
|
||||
// }
|
||||
|
||||
// test_single_value!("/%25/", "%");
|
||||
// test_single_value!("/%40%C2%A3%24%25%5E%26%2B%3D/", "@£$%^&+=");
|
||||
// test_single_value!("/%2B/", "+");
|
||||
// test_single_value!("/%252B/", "%2B");
|
||||
// test_single_value!("/%2F/", "/");
|
||||
// test_single_value!("/%252F/", "%2F");
|
||||
// test_single_value!(
|
||||
// "/http%3A%2F%2Flocalhost%3A80%2Ffoo/",
|
||||
// "http://localhost:80/foo"
|
||||
// );
|
||||
// test_single_value!("/%2Fvar%2Flog%2Fsyslog/", "/var/log/syslog");
|
||||
// test_single_value!(
|
||||
// "/http%3A%2F%2Flocalhost%3A80%2Ffile%2F%252Fvar%252Flog%252Fsyslog/",
|
||||
// "http://localhost:80/file/%2Fvar%2Flog%2Fsyslog"
|
||||
// );
|
||||
|
||||
// let req = TestRequest::with_uri("/%25/7/?id=test").finish();
|
||||
|
||||
// let mut router = Router::<()>::default();
|
||||
// router.register_resource(Resource::new(ResourceDef::new("/{key}/{value}/")));
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// let req = req.with_route_info(info);
|
||||
|
||||
// let s = Path::<Test2>::from_request(&req, &PathConfig::default()).unwrap();
|
||||
// assert_eq!(s.key, "%");
|
||||
// assert_eq!(s.value, 7);
|
||||
|
||||
// let s = Path::<(String, String)>::from_request(&req, &PathConfig::default()).unwrap();
|
||||
// assert_eq!(s.0, "%");
|
||||
// assert_eq!(s.1, "7");
|
||||
// }
|
||||
|
||||
// #[test]
|
||||
// fn test_extract_path_no_decode() {
|
||||
// let mut router = Router::<()>::default();
|
||||
// router.register_resource(Resource::new(ResourceDef::new("/{value}/")));
|
||||
|
||||
// let req = TestRequest::with_uri("/%25/").finish();
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// let req = req.with_route_info(info);
|
||||
// assert_eq!(
|
||||
// *Path::<String>::from_request(&req, &&PathConfig::default().disable_decoding())
|
||||
// .unwrap(),
|
||||
// "%25"
|
||||
// );
|
||||
// }
|
||||
}
|
54
router/src/lib.rs
Normal file
54
router/src/lib.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
//! Resource path matching library.
|
||||
mod de;
|
||||
mod path;
|
||||
mod resource;
|
||||
mod router;
|
||||
|
||||
pub use self::de::PathDeserializer;
|
||||
pub use self::path::Path;
|
||||
pub use self::resource::ResourceDef;
|
||||
pub use self::router::{ResourceInfo, Router, RouterBuilder};
|
||||
|
||||
pub trait Resource<T: ResourcePath> {
|
||||
fn resource_path(&mut self) -> &mut Path<T>;
|
||||
}
|
||||
|
||||
pub trait ResourcePath {
|
||||
fn path(&self) -> &str;
|
||||
}
|
||||
|
||||
impl ResourcePath for String {
|
||||
fn path(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ResourcePath for &'a str {
|
||||
fn path(&self) -> &str {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<[u8]>> ResourcePath for string::String<T> {
|
||||
fn path(&self) -> &str {
|
||||
&*self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "http")]
|
||||
mod url;
|
||||
|
||||
#[cfg(feature = "http")]
|
||||
pub use self::url::Url;
|
||||
|
||||
#[cfg(feature = "http")]
|
||||
mod http_support {
|
||||
use super::ResourcePath;
|
||||
use http::Uri;
|
||||
|
||||
impl ResourcePath for Uri {
|
||||
fn path(&self) -> &str {
|
||||
self.path()
|
||||
}
|
||||
}
|
||||
}
|
210
router/src/path.rs
Normal file
210
router/src/path.rs
Normal file
@@ -0,0 +1,210 @@
|
||||
use std::ops::Index;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde::de;
|
||||
|
||||
use crate::de::PathDeserializer;
|
||||
use crate::{Resource, ResourcePath};
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum PathItem {
|
||||
Static(&'static str),
|
||||
Segment(u16, u16),
|
||||
}
|
||||
|
||||
/// Resource path match information
|
||||
///
|
||||
/// If resource path contains variable patterns, `Path` stores them.
|
||||
#[derive(Debug)]
|
||||
pub struct Path<T> {
|
||||
path: T,
|
||||
pub(crate) skip: u16,
|
||||
pub(crate) segments: Vec<(Rc<String>, PathItem)>,
|
||||
}
|
||||
|
||||
impl<T: Default> Default for Path<T> {
|
||||
fn default() -> Self {
|
||||
Path {
|
||||
path: T::default(),
|
||||
skip: 0,
|
||||
segments: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> Clone for Path<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Path {
|
||||
path: self.path.clone(),
|
||||
skip: self.skip,
|
||||
segments: self.segments.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ResourcePath> Path<T> {
|
||||
pub fn new(path: T) -> Path<T> {
|
||||
Path {
|
||||
path,
|
||||
skip: 0,
|
||||
segments: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get reference to inner path instance
|
||||
pub fn get_ref(&self) -> &T {
|
||||
&self.path
|
||||
}
|
||||
|
||||
/// Get mutable reference to inner path instance
|
||||
pub fn get_mut(&mut self) -> &mut T {
|
||||
&mut self.path
|
||||
}
|
||||
|
||||
/// Path
|
||||
pub fn path(&self) -> &str {
|
||||
let skip = self.skip as usize;
|
||||
let path = self.path.path();
|
||||
if skip <= path.len() {
|
||||
&path[skip..]
|
||||
} else {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset inner path
|
||||
pub fn set(&mut self, path: T) {
|
||||
self.skip = 0;
|
||||
self.path = path;
|
||||
self.segments.clear();
|
||||
}
|
||||
|
||||
/// Skip first `n` chars in path
|
||||
pub fn skip(&mut self, n: u16) {
|
||||
self.skip = self.skip + n;
|
||||
}
|
||||
|
||||
pub(crate) fn add(&mut self, name: Rc<String>, value: PathItem) {
|
||||
match value {
|
||||
PathItem::Static(s) => self.segments.push((name, PathItem::Static(s))),
|
||||
PathItem::Segment(begin, end) => self
|
||||
.segments
|
||||
.push((name, PathItem::Segment(self.skip + begin, self.skip + end))),
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn add_static(&mut self, name: &str, value: &'static str) {
|
||||
self.segments
|
||||
.push((Rc::new(name.to_string()), PathItem::Static(value)));
|
||||
}
|
||||
|
||||
/// Check if there are any matched patterns
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.segments.is_empty()
|
||||
}
|
||||
|
||||
/// Check number of extracted parameters
|
||||
pub fn len(&self) -> usize {
|
||||
self.segments.len()
|
||||
}
|
||||
|
||||
/// Get matched parameter by name without type conversion
|
||||
pub fn get(&self, key: &str) -> Option<&str> {
|
||||
for item in self.segments.iter() {
|
||||
if key == item.0.as_str() {
|
||||
return match item.1 {
|
||||
PathItem::Static(ref s) => Some(&s),
|
||||
PathItem::Segment(s, e) => {
|
||||
Some(&self.path.path()[(s as usize)..(e as usize)])
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
if key == "tail" {
|
||||
Some(&self.path.path()[(self.skip as usize)..])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Get unprocessed part of the path
|
||||
pub fn unprocessed(&self) -> &str {
|
||||
&self.path.path()[(self.skip as usize)..]
|
||||
}
|
||||
|
||||
/// Get matched parameter by name.
|
||||
///
|
||||
/// If keyed parameter is not available empty string is used as default
|
||||
/// value.
|
||||
pub fn query(&self, key: &str) -> &str {
|
||||
if let Some(s) = self.get(key) {
|
||||
s
|
||||
} else {
|
||||
""
|
||||
}
|
||||
}
|
||||
|
||||
/// Return iterator to items in parameter container
|
||||
pub fn iter(&self) -> PathIter<T> {
|
||||
PathIter {
|
||||
idx: 0,
|
||||
params: self,
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to deserialize matching parameters to a specified type `U`
|
||||
pub fn load<'de, U: serde::Deserialize<'de>>(&'de self) -> Result<U, de::value::Error> {
|
||||
de::Deserialize::deserialize(PathDeserializer::new(self))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PathIter<'a, T> {
|
||||
idx: usize,
|
||||
params: &'a Path<T>,
|
||||
}
|
||||
|
||||
impl<'a, T: ResourcePath> Iterator for PathIter<'a, T> {
|
||||
type Item = (&'a str, &'a str);
|
||||
|
||||
#[inline]
|
||||
fn next(&mut self) -> Option<(&'a str, &'a str)> {
|
||||
if self.idx < self.params.len() {
|
||||
let idx = self.idx;
|
||||
let res = match self.params.segments[idx].1 {
|
||||
PathItem::Static(ref s) => &s,
|
||||
PathItem::Segment(s, e) => &self.params.path.path()[(s as usize)..(e as usize)],
|
||||
};
|
||||
self.idx += 1;
|
||||
return Some((&self.params.segments[idx].0, res));
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: ResourcePath> Index<&'a str> for Path<T> {
|
||||
type Output = str;
|
||||
|
||||
fn index(&self, name: &'a str) -> &str {
|
||||
self.get(name)
|
||||
.expect("Value for parameter is not available")
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ResourcePath> Index<usize> for Path<T> {
|
||||
type Output = str;
|
||||
|
||||
fn index(&self, idx: usize) -> &str {
|
||||
match self.segments[idx].1 {
|
||||
PathItem::Static(ref s) => &s,
|
||||
PathItem::Segment(s, e) => &self.path.path()[(s as usize)..(e as usize)],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ResourcePath> Resource<T> for Path<T> {
|
||||
fn resource_path(&mut self) -> &mut Self {
|
||||
self
|
||||
}
|
||||
}
|
454
router/src/resource.rs
Normal file
454
router/src/resource.rs
Normal file
@@ -0,0 +1,454 @@
|
||||
use std::cmp::min;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::rc::Rc;
|
||||
|
||||
use regex::{escape, Regex};
|
||||
|
||||
use crate::path::{Path, PathItem};
|
||||
use crate::ResourcePath;
|
||||
|
||||
const MAX_DYNAMIC_SEGMENTS: usize = 16;
|
||||
|
||||
/// ResourceDef describes an entry in resources table
|
||||
///
|
||||
/// Resource definition can contain only 16 dynamic segments
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ResourceDef {
|
||||
tp: PatternType,
|
||||
rtp: ResourceType,
|
||||
name: String,
|
||||
pattern: String,
|
||||
elements: Vec<PatternElement>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
/// Resource type
|
||||
pub enum ResourceType {
|
||||
/// Normal resource
|
||||
Normal,
|
||||
/// Resource for application default handler
|
||||
Default,
|
||||
/// External resource
|
||||
External,
|
||||
/// Unknown resource type
|
||||
Unset,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum PatternElement {
|
||||
Str(String),
|
||||
Var(String),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum PatternType {
|
||||
Static(String),
|
||||
Prefix(String),
|
||||
Dynamic(Regex, Vec<Rc<String>>, usize),
|
||||
}
|
||||
|
||||
impl ResourceDef {
|
||||
/// Parse path pattern and create new `Pattern` instance.
|
||||
///
|
||||
/// Panics if path pattern is wrong.
|
||||
pub fn new(path: &str) -> Self {
|
||||
ResourceDef::with_prefix(path, false)
|
||||
}
|
||||
|
||||
/// Parse path pattern and create new `Pattern` instance.
|
||||
///
|
||||
/// Use `prefix` type instead of `static`.
|
||||
///
|
||||
/// Panics if path regex pattern is wrong.
|
||||
pub fn prefix(path: &str) -> Self {
|
||||
ResourceDef::with_prefix(path, true)
|
||||
}
|
||||
|
||||
/// Parse path pattern and create new `Pattern` instance.
|
||||
/// Inserts `/` to begging of the pattern.
|
||||
///
|
||||
///
|
||||
/// Use `prefix` type instead of `static`.
|
||||
///
|
||||
/// Panics if path regex pattern is wrong.
|
||||
pub fn root_prefix(path: &str) -> Self {
|
||||
ResourceDef::with_prefix(&insert_slash(path), true)
|
||||
}
|
||||
|
||||
/// Construct external resource def
|
||||
///
|
||||
/// Panics if path pattern is malformed.
|
||||
pub fn external(path: &str) -> Self {
|
||||
let mut resource = ResourceDef::with_prefix(path, false);
|
||||
resource.rtp = ResourceType::External;
|
||||
resource
|
||||
}
|
||||
|
||||
/// Parse path pattern and create new `Pattern` instance with custom prefix
|
||||
fn with_prefix(path: &str, for_prefix: bool) -> Self {
|
||||
let path = path.to_owned();
|
||||
let (pattern, elements, is_dynamic, len) = ResourceDef::parse(&path, for_prefix);
|
||||
|
||||
let tp = if is_dynamic {
|
||||
let re = match Regex::new(&pattern) {
|
||||
Ok(re) => re,
|
||||
Err(err) => panic!("Wrong path pattern: \"{}\" {}", path, err),
|
||||
};
|
||||
// actix creates one router per thread
|
||||
let names = re
|
||||
.capture_names()
|
||||
.filter_map(|name| name.map(|name| Rc::new(name.to_owned())))
|
||||
.collect();
|
||||
PatternType::Dynamic(re, names, len)
|
||||
} else if for_prefix {
|
||||
PatternType::Prefix(pattern.clone())
|
||||
} else {
|
||||
PatternType::Static(pattern.clone())
|
||||
};
|
||||
|
||||
ResourceDef {
|
||||
tp,
|
||||
elements,
|
||||
name: String::new(),
|
||||
rtp: ResourceType::Normal,
|
||||
pattern: path.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Path pattern of the resource
|
||||
pub fn pattern(&self) -> &str {
|
||||
&self.pattern
|
||||
}
|
||||
|
||||
/// Check if path matchs this pattern?
|
||||
pub fn is_match(&self, path: &str) -> bool {
|
||||
match self.tp {
|
||||
PatternType::Static(ref s) => s == path,
|
||||
PatternType::Dynamic(ref re, _, _) => re.is_match(path),
|
||||
PatternType::Prefix(ref s) => path.starts_with(s),
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the given path and parameters a match against this pattern?
|
||||
pub fn match_path<T: ResourcePath>(&self, path: &mut Path<T>) -> bool {
|
||||
match self.tp {
|
||||
PatternType::Static(ref s) => {
|
||||
if s == path.path() {
|
||||
path.skip(path.len() as u16);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
PatternType::Dynamic(ref re, ref names, len) => {
|
||||
let mut idx = 0;
|
||||
let mut pos = 0;
|
||||
let mut segments: [PathItem; MAX_DYNAMIC_SEGMENTS] =
|
||||
[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);
|
||||
idx += 1;
|
||||
pos = m.end();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
for idx in 0..idx {
|
||||
path.add(names[idx].clone(), segments[idx]);
|
||||
}
|
||||
path.skip((pos + len) as u16);
|
||||
true
|
||||
}
|
||||
PatternType::Prefix(ref s) => {
|
||||
let rpath = path.path();
|
||||
let len = if s == rpath {
|
||||
s.len()
|
||||
} else if rpath.starts_with(s)
|
||||
&& (s.ends_with('/') || rpath.split_at(s.len()).1.starts_with('/'))
|
||||
{
|
||||
if s.ends_with('/') {
|
||||
s.len() - 1
|
||||
} else {
|
||||
s.len()
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
};
|
||||
path.skip(min(rpath.len(), len) as u16);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// /// Build resource path.
|
||||
// pub fn resource_path<U, I>(
|
||||
// &self, path: &mut String, elements: &mut U,
|
||||
// ) -> Result<(), UrlGenerationError>
|
||||
// where
|
||||
// U: Iterator<Item = I>,
|
||||
// I: AsRef<str>,
|
||||
// {
|
||||
// match self.tp {
|
||||
// PatternType::Prefix(ref p) => path.push_str(p),
|
||||
// PatternType::Static(ref p) => path.push_str(p),
|
||||
// PatternType::Dynamic(..) => {
|
||||
// for el in &self.elements {
|
||||
// match *el {
|
||||
// PatternElement::Str(ref s) => path.push_str(s),
|
||||
// PatternElement::Var(_) => {
|
||||
// if let Some(val) = elements.next() {
|
||||
// path.push_str(val.as_ref())
|
||||
// } else {
|
||||
// return Err(UrlGenerationError::NotEnoughElements);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// };
|
||||
// Ok(())
|
||||
// }
|
||||
|
||||
fn parse_param(pattern: &str) -> (PatternElement, String, &str) {
|
||||
const DEFAULT_PATTERN: &str = "[^/]+";
|
||||
let mut params_nesting = 0usize;
|
||||
let close_idx = pattern
|
||||
.find(|c| match c {
|
||||
'{' => {
|
||||
params_nesting += 1;
|
||||
false
|
||||
}
|
||||
'}' => {
|
||||
params_nesting -= 1;
|
||||
params_nesting == 0
|
||||
}
|
||||
_ => false,
|
||||
})
|
||||
.expect("malformed dynamic segment");
|
||||
let (mut param, rem) = pattern.split_at(close_idx + 1);
|
||||
param = ¶m[1..param.len() - 1]; // Remove outer brackets
|
||||
let (name, pattern) = match param.find(':') {
|
||||
Some(idx) => {
|
||||
let (name, pattern) = param.split_at(idx);
|
||||
(name, &pattern[1..])
|
||||
}
|
||||
None => (param, DEFAULT_PATTERN),
|
||||
};
|
||||
(
|
||||
PatternElement::Var(name.to_string()),
|
||||
format!(r"(?P<{}>{})", &name, &pattern),
|
||||
rem,
|
||||
)
|
||||
}
|
||||
|
||||
fn parse(
|
||||
mut pattern: &str,
|
||||
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(),
|
||||
);
|
||||
};
|
||||
|
||||
let mut elems = Vec::new();
|
||||
let mut re = String::from("^");
|
||||
let mut dyn_elems = 0;
|
||||
|
||||
while let Some(idx) = pattern.find('{') {
|
||||
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);
|
||||
elems.push(param_pattern);
|
||||
re.push_str(&re_part);
|
||||
pattern = rem;
|
||||
dyn_elems += 1;
|
||||
}
|
||||
|
||||
elems.push(PatternElement::Str(String::from(pattern)));
|
||||
re.push_str(&escape(pattern));
|
||||
|
||||
if dyn_elems > MAX_DYNAMIC_SEGMENTS {
|
||||
panic!(
|
||||
"Only {} dynanic segments are allowed, provided: {}",
|
||||
MAX_DYNAMIC_SEGMENTS, dyn_elems
|
||||
);
|
||||
}
|
||||
|
||||
if !for_prefix {
|
||||
re.push_str("$");
|
||||
}
|
||||
|
||||
(re, elems, true, pattern.chars().count())
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for ResourceDef {}
|
||||
|
||||
impl PartialEq for ResourceDef {
|
||||
fn eq(&self, other: &ResourceDef) -> bool {
|
||||
self.pattern == other.pattern
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for ResourceDef {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.pattern.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a str> for ResourceDef {
|
||||
fn from(path: &'a str) -> ResourceDef {
|
||||
ResourceDef::new(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for ResourceDef {
|
||||
fn from(path: String) -> ResourceDef {
|
||||
ResourceDef::new(&path)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn insert_slash(path: &str) -> String {
|
||||
let mut path = path.to_owned();
|
||||
if !path.is_empty() && !path.starts_with('/') {
|
||||
path.insert(0, '/');
|
||||
};
|
||||
path
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use http::{HttpTryFrom, Uri};
|
||||
|
||||
#[test]
|
||||
fn test_parse_static() {
|
||||
let re = ResourceDef::new("/");
|
||||
assert!(re.is_match("/"));
|
||||
assert!(!re.is_match("/a"));
|
||||
|
||||
let re = ResourceDef::new("/name");
|
||||
assert!(re.is_match("/name"));
|
||||
assert!(!re.is_match("/name1"));
|
||||
assert!(!re.is_match("/name/"));
|
||||
assert!(!re.is_match("/name~"));
|
||||
|
||||
let re = ResourceDef::new("/name/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(!re.is_match("/name"));
|
||||
assert!(!re.is_match("/name/gs"));
|
||||
|
||||
let re = ResourceDef::new("/user/profile");
|
||||
assert!(re.is_match("/user/profile"));
|
||||
assert!(!re.is_match("/user/profile/profile"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_param() {
|
||||
let re = ResourceDef::new("/user/{id}");
|
||||
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 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/1245125");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "1245125");
|
||||
|
||||
let re = ResourceDef::new("/v{version}/resource/{id}");
|
||||
assert!(re.is_match("/v1/resource/320120"));
|
||||
assert!(!re.is_match("/v/resource/1"));
|
||||
assert!(!re.is_match("/resource"));
|
||||
|
||||
let mut path = Path::new("/v151/resource/adahg32");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("version").unwrap(), "151");
|
||||
assert_eq!(path.get("id").unwrap(), "adahg32");
|
||||
|
||||
let re = ResourceDef::new("/{id:[[:digit:]]{6}}");
|
||||
assert!(re.is_match("/012345"));
|
||||
assert!(!re.is_match("/012"));
|
||||
assert!(!re.is_match("/01234567"));
|
||||
assert!(!re.is_match("/XXXXXX"));
|
||||
|
||||
let mut path = Path::new("/012345");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "012345");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_urlencoded_param() {
|
||||
let re = ResourceDef::new("/user/{id}/test");
|
||||
|
||||
let mut path = Path::new("/user/2345/test");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "2345");
|
||||
|
||||
let mut path = Path::new("/user/qwe%25/test");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "qwe%25");
|
||||
|
||||
let uri = Uri::try_from("/user/qwe%25/test").unwrap();
|
||||
let mut path = Path::new(uri);
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "qwe%25");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_resource_prefix() {
|
||||
let re = ResourceDef::prefix("/name");
|
||||
assert!(re.is_match("/name"));
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(re.is_match("/name/test/test"));
|
||||
assert!(re.is_match("/name1"));
|
||||
assert!(re.is_match("/name~"));
|
||||
|
||||
let re = ResourceDef::prefix("/name/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(re.is_match("/name/gs"));
|
||||
assert!(!re.is_match("/name"));
|
||||
|
||||
let re = ResourceDef::root_prefix("name/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(re.is_match("/name/gs"));
|
||||
assert!(!re.is_match("/name"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_reousrce_prefix_dynamic() {
|
||||
let re = ResourceDef::prefix("/{name}/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(re.is_match("/name/gs"));
|
||||
assert!(!re.is_match("/name"));
|
||||
|
||||
let mut path = Path::new("/test2/");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(&path["name"], "test2");
|
||||
assert_eq!(&path[0], "test2");
|
||||
|
||||
let mut path = Path::new("/test2/subpath1/subpath2/index.html");
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(&path["name"], "test2");
|
||||
assert_eq!(&path[0], "test2");
|
||||
}
|
||||
}
|
439
router/src/router.rs
Normal file
439
router/src/router.rs
Normal file
@@ -0,0 +1,439 @@
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::resource::ResourceDef;
|
||||
use crate::{Resource, ResourcePath};
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
pub(crate) enum ResourceId {
|
||||
Default,
|
||||
Normal(u16),
|
||||
}
|
||||
|
||||
/// Information about current resource
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ResourceInfo {
|
||||
rmap: Rc<ResourceMap>,
|
||||
resource: ResourceId,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub(crate) struct ResourceMap {
|
||||
root: Option<ResourceDef>,
|
||||
named: HashMap<String, ResourceDef>,
|
||||
patterns: Vec<ResourceDef>,
|
||||
}
|
||||
|
||||
/// Resource router.
|
||||
pub struct Router<T, U = ()> {
|
||||
rmap: Rc<ResourceMap>,
|
||||
named: HashMap<String, ResourceDef>,
|
||||
resources: Vec<(T, Option<U>)>,
|
||||
}
|
||||
|
||||
impl<T, U> Router<T, U> {
|
||||
pub fn build() -> RouterBuilder<T, U> {
|
||||
RouterBuilder {
|
||||
rmap: ResourceMap::default(),
|
||||
named: HashMap::new(),
|
||||
resources: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn recognize<R: Resource<P>, P: ResourcePath>(
|
||||
&self,
|
||||
res: &mut R,
|
||||
) -> Option<(&T, ResourceInfo)> {
|
||||
for (idx, resource) in self.rmap.patterns.iter().enumerate() {
|
||||
if resource.match_path(res.resource_path()) {
|
||||
let info = ResourceInfo {
|
||||
rmap: self.rmap.clone(),
|
||||
resource: ResourceId::Normal(idx as u16),
|
||||
};
|
||||
return Some((&self.resources[idx].0, info));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn recognize_mut<R: Resource<P>, P: ResourcePath>(
|
||||
&mut self,
|
||||
res: &mut R,
|
||||
) -> Option<(&mut T, ResourceInfo)> {
|
||||
for (idx, resource) in self.rmap.patterns.iter().enumerate() {
|
||||
if resource.match_path(res.resource_path()) {
|
||||
let info = ResourceInfo {
|
||||
rmap: self.rmap.clone(),
|
||||
resource: ResourceId::Normal(idx as u16),
|
||||
};
|
||||
return Some((&mut self.resources[idx].0, info));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn recognize_mut_checked<R: Resource<P>, P: ResourcePath, F>(
|
||||
&mut self,
|
||||
res: &mut R,
|
||||
check: F,
|
||||
) -> Option<(&mut T, ResourceInfo)>
|
||||
where
|
||||
F: Fn(&R, &Option<U>) -> bool,
|
||||
{
|
||||
for (idx, resource) in self.rmap.patterns.iter().enumerate() {
|
||||
if resource.match_path(res.resource_path()) && check(res, &self.resources[idx].1) {
|
||||
let info = ResourceInfo {
|
||||
rmap: self.rmap.clone(),
|
||||
resource: ResourceId::Normal(idx as u16),
|
||||
};
|
||||
return Some((&mut self.resources[idx].0, info));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, U> IntoIterator for &'a Router<T, U> {
|
||||
type Item = &'a (T, Option<U>);
|
||||
type IntoIter = std::slice::Iter<'a, (T, Option<U>)>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.resources.iter()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, U> IntoIterator for &'a mut Router<T, U> {
|
||||
type Item = &'a mut (T, Option<U>);
|
||||
type IntoIter = std::slice::IterMut<'a, (T, Option<U>)>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.resources.iter_mut()
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourceMap {
|
||||
fn register(&mut self, pattern: ResourceDef) {
|
||||
self.patterns.push(pattern);
|
||||
}
|
||||
|
||||
fn register_named(&mut self, name: String, pattern: ResourceDef) {
|
||||
self.patterns.push(pattern.clone());
|
||||
self.named.insert(name, pattern);
|
||||
}
|
||||
|
||||
fn has_resource(&self, path: &str) -> bool {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RouterBuilder<T, U = ()> {
|
||||
rmap: ResourceMap,
|
||||
named: HashMap<String, ResourceDef>,
|
||||
resources: Vec<(T, Option<U>)>,
|
||||
}
|
||||
|
||||
impl<T, U> RouterBuilder<T, U> {
|
||||
/// Register resource for specified path.
|
||||
pub fn path(&mut self, path: &str, resource: T) {
|
||||
self.rmap.register(ResourceDef::new(path));
|
||||
self.resources.push((resource, None));
|
||||
}
|
||||
|
||||
/// Register resource for specified path prefix.
|
||||
pub fn prefix(&mut self, prefix: &str, resource: T) {
|
||||
self.rmap.register(ResourceDef::prefix(prefix));
|
||||
self.resources.push((resource, None));
|
||||
}
|
||||
|
||||
/// Register resource for ResourceDef
|
||||
pub fn rdef(&mut self, rdef: ResourceDef, resource: T) {
|
||||
self.rmap.register(rdef);
|
||||
self.resources.push((resource, None));
|
||||
}
|
||||
|
||||
/// Method attachs user data to lastly added resource.
|
||||
///
|
||||
/// This panics if no resources were added.
|
||||
pub fn set_user_data(&mut self, userdata: Option<U>) {
|
||||
self.resources.last_mut().unwrap().1 = userdata;
|
||||
}
|
||||
|
||||
/// Finish configuration and create router instance.
|
||||
pub fn finish(self) -> Router<T, U> {
|
||||
Router {
|
||||
rmap: Rc::new(self.rmap),
|
||||
named: self.named,
|
||||
resources: self.resources,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::path::Path;
|
||||
use crate::router::{ResourceId, Router};
|
||||
|
||||
#[test]
|
||||
fn test_recognizer_1() {
|
||||
let mut router = Router::<usize>::build();
|
||||
router.path("/name", 10);
|
||||
router.path("/name/{val}", 11);
|
||||
router.path("/name/{val}/index.html", 12);
|
||||
router.path("/file/{file}.{ext}", 13);
|
||||
router.path("/v{val}/{val2}/index.html", 14);
|
||||
router.path("/v/{tail:.*}", 15);
|
||||
router.path("/test2/{test}.html", 16);
|
||||
router.path("/{test}/index.html", 17);
|
||||
let mut router = router.finish();
|
||||
|
||||
let mut path = Path::new("/unknown");
|
||||
assert!(router.recognize_mut(&mut path).is_none());
|
||||
|
||||
let mut path = Path::new("/name");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 10);
|
||||
assert_eq!(info.resource, ResourceId::Normal(0));
|
||||
assert!(path.is_empty());
|
||||
|
||||
let mut path = Path::new("/name/value");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 11);
|
||||
assert_eq!(info.resource, ResourceId::Normal(1));
|
||||
assert_eq!(path.get("val").unwrap(), "value");
|
||||
assert_eq!(&path["val"], "value");
|
||||
|
||||
let mut path = Path::new("/name/value2/index.html");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 12);
|
||||
assert_eq!(info.resource, ResourceId::Normal(2));
|
||||
assert_eq!(path.get("val").unwrap(), "value2");
|
||||
|
||||
let mut path = Path::new("/file/file.gz");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 13);
|
||||
assert_eq!(info.resource, ResourceId::Normal(3));
|
||||
assert_eq!(path.get("file").unwrap(), "file");
|
||||
assert_eq!(path.get("ext").unwrap(), "gz");
|
||||
|
||||
let mut path = Path::new("/vtest/ttt/index.html");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 14);
|
||||
assert_eq!(info.resource, ResourceId::Normal(4));
|
||||
assert_eq!(path.get("val").unwrap(), "test");
|
||||
assert_eq!(path.get("val2").unwrap(), "ttt");
|
||||
|
||||
let mut path = Path::new("/v/blah-blah/index.html");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 15);
|
||||
assert_eq!(info.resource, ResourceId::Normal(5));
|
||||
assert_eq!(path.get("tail").unwrap(), "blah-blah/index.html");
|
||||
|
||||
let mut path = Path::new("/test2/index.html");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 16);
|
||||
assert_eq!(info.resource, ResourceId::Normal(6));
|
||||
assert_eq!(path.get("test").unwrap(), "index");
|
||||
|
||||
let mut path = Path::new("/bbb/index.html");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 17);
|
||||
assert_eq!(info.resource, ResourceId::Normal(7));
|
||||
assert_eq!(path.get("test").unwrap(), "bbb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_recognizer_2() {
|
||||
let mut router = Router::<usize>::build();
|
||||
router.path("/index.json", 10);
|
||||
router.path("/{source}.json", 11);
|
||||
let mut router = router.finish();
|
||||
|
||||
let mut path = Path::new("/index.json");
|
||||
let (h, _) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 10);
|
||||
|
||||
let mut path = Path::new("/test.json");
|
||||
let (h, _) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_recognizer_with_prefix() {
|
||||
let mut router = Router::<usize>::build();
|
||||
router.path("/name", 10);
|
||||
router.path("/name/{val}", 11);
|
||||
let mut router = router.finish();
|
||||
|
||||
let mut path = Path::new("/name");
|
||||
path.skip(5);
|
||||
assert!(router.recognize_mut(&mut path).is_none());
|
||||
|
||||
let mut path = Path::new("/test/name");
|
||||
path.skip(5);
|
||||
let (h, _) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 10);
|
||||
|
||||
let mut path = Path::new("/test/name/value");
|
||||
path.skip(5);
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 11);
|
||||
assert_eq!(info.resource, ResourceId::Normal(1));
|
||||
assert_eq!(path.get("val").unwrap(), "value");
|
||||
assert_eq!(&path["val"], "value");
|
||||
|
||||
// same patterns
|
||||
let mut router = Router::<usize>::build();
|
||||
router.path("/name", 10);
|
||||
router.path("/name/{val}", 11);
|
||||
let mut router = router.finish();
|
||||
|
||||
let mut path = Path::new("/name");
|
||||
path.skip(6);
|
||||
assert!(router.recognize_mut(&mut path).is_none());
|
||||
|
||||
let mut path = Path::new("/test2/name");
|
||||
path.skip(6);
|
||||
let (h, _) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 10);
|
||||
|
||||
let mut path = Path::new("/test2/name-test");
|
||||
path.skip(6);
|
||||
assert!(router.recognize_mut(&mut path).is_none());
|
||||
|
||||
let mut path = Path::new("/test2/name/ttt");
|
||||
path.skip(6);
|
||||
let (h, _) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 11);
|
||||
assert_eq!(&path["val"], "ttt");
|
||||
}
|
||||
|
||||
// #[test]
|
||||
// fn test_request_resource() {
|
||||
// let mut router = Router::<()>::default();
|
||||
// let mut resource = Resource::new(ResourcePattern::new("/index.json"));
|
||||
// resource.name("r1");
|
||||
// router.register_resource(resource);
|
||||
// let mut resource = Resource::new(ResourcePattern::new("/test.json"));
|
||||
// resource.name("r2");
|
||||
// router.register_resource(resource);
|
||||
|
||||
// let req = TestRequest::with_uri("/index.json").finish();
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// assert_eq!(info.resource, ResourceId::Normal(0));
|
||||
|
||||
// assert_eq!(info.name(), "r1");
|
||||
|
||||
// let req = TestRequest::with_uri("/test.json").finish();
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// assert_eq!(info.resource, ResourceId::Normal(1));
|
||||
// assert_eq!(info.name(), "r2");
|
||||
// }
|
||||
|
||||
// #[test]
|
||||
// fn test_has_resource() {
|
||||
// let mut router = Router::<()>::default();
|
||||
// let scope = Scope::new("/test").resource("/name", |_| "done");
|
||||
// router.register_scope(scope);
|
||||
|
||||
// {
|
||||
// let info = router.default_route_info();
|
||||
// assert!(!info.has_resource("/test"));
|
||||
// assert!(info.has_resource("/test/name"));
|
||||
// }
|
||||
|
||||
// let scope = Scope::new("/test2").nested("/test10", |s| s.resource("/name", |_| "done"));
|
||||
// router.register_scope(scope);
|
||||
|
||||
// let info = router.default_route_info();
|
||||
// assert!(info.has_resource("/test2/test10/name"));
|
||||
// }
|
||||
|
||||
// #[test]
|
||||
// fn test_url_for() {
|
||||
// let mut router = Router::<()>::new(ResourcePattern::prefix(""));
|
||||
|
||||
// let mut resource = Resource::new(ResourcePattern::new("/tttt"));
|
||||
// resource.name("r0");
|
||||
// router.register_resource(resource);
|
||||
|
||||
// let scope = Scope::new("/test").resource("/name", |r| {
|
||||
// r.name("r1");
|
||||
// });
|
||||
// router.register_scope(scope);
|
||||
|
||||
// let scope =
|
||||
// Scope::new("/test2").nested("/test10", |s| s.resource("/name", |r| r.name("r2")));
|
||||
// router.register_scope(scope);
|
||||
// router.finish();
|
||||
|
||||
// let req = TestRequest::with_uri("/test").request();
|
||||
// {
|
||||
// let info = router.default_route_info();
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r0", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/tttt");
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r1", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/test/name");
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r2", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/test2/test10/name");
|
||||
// }
|
||||
|
||||
// let req = TestRequest::with_uri("/test/name").request();
|
||||
// let info = router.recognize(&req, &(), 0);
|
||||
// assert_eq!(info.resource, ResourceId::Normal(1));
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r0", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/tttt");
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r1", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/test/name");
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r2", Vec::<&'static str>::new())
|
||||
// .unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/test2/test10/name");
|
||||
// }
|
||||
|
||||
// #[test]
|
||||
// fn test_url_for_dynamic() {
|
||||
// let mut router = Router::<()>::new(ResourcePattern::prefix(""));
|
||||
|
||||
// let mut resource = Resource::new(ResourcePattern::new("/{name}/test/index.{ext}"));
|
||||
// resource.name("r0");
|
||||
// router.register_resource(resource);
|
||||
|
||||
// let scope = Scope::new("/{name1}").nested("/{name2}", |s| {
|
||||
// s.resource("/{name3}/test/index.{ext}", |r| r.name("r2"))
|
||||
// });
|
||||
// router.register_scope(scope);
|
||||
// router.finish();
|
||||
|
||||
// let req = TestRequest::with_uri("/test").request();
|
||||
// {
|
||||
// let info = router.default_route_info();
|
||||
|
||||
// let res = info.url_for(&req, "r0", vec!["sec1", "html"]).unwrap();
|
||||
// assert_eq!(res.as_str(), "http://localhost:8080/sec1/test/index.html");
|
||||
|
||||
// let res = info
|
||||
// .url_for(&req, "r2", vec!["sec1", "sec2", "sec3", "html"])
|
||||
// .unwrap();
|
||||
// assert_eq!(
|
||||
// res.as_str(),
|
||||
// "http://localhost:8080/sec1/sec2/sec3/test/index.html"
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
}
|
214
router/src/url.rs
Normal file
214
router/src/url.rs
Normal file
@@ -0,0 +1,214 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::ResourcePath;
|
||||
|
||||
#[allow(dead_code)]
|
||||
const GEN_DELIMS: &[u8] = b":/?#[]@";
|
||||
#[allow(dead_code)]
|
||||
const SUB_DELIMS_WITHOUT_QS: &[u8] = b"!$'()*,";
|
||||
#[allow(dead_code)]
|
||||
const SUB_DELIMS: &[u8] = b"!$'()*,+?=;";
|
||||
#[allow(dead_code)]
|
||||
const RESERVED: &[u8] = b":/?#[]@!$'()*,+?=;";
|
||||
#[allow(dead_code)]
|
||||
const UNRESERVED: &[u8] = b"abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
||||
1234567890
|
||||
-._~";
|
||||
const ALLOWED: &[u8] = b"abcdefghijklmnopqrstuvwxyz
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
||||
1234567890
|
||||
-._~
|
||||
!$'()*,";
|
||||
const QS: &[u8] = b"+&=;b";
|
||||
|
||||
#[inline]
|
||||
fn bit_at(array: &[u8], ch: u8) -> bool {
|
||||
array[(ch >> 3) as usize] & (1 << (ch & 7)) != 0
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn set_bit(array: &mut [u8], ch: u8) {
|
||||
array[(ch >> 3) as usize] |= 1 << (ch & 7)
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static DEFAULT_QUOTER: Quoter = { Quoter::new(b"@:", b"/+") };
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Debug)]
|
||||
pub struct Url {
|
||||
uri: http::Uri,
|
||||
path: Option<Rc<String>>,
|
||||
}
|
||||
|
||||
impl Url {
|
||||
pub fn new(uri: http::Uri) -> Url {
|
||||
let path = DEFAULT_QUOTER.with(|q| q.requote(uri.path().as_bytes()));
|
||||
|
||||
Url { uri, path }
|
||||
}
|
||||
|
||||
pub fn uri(&self) -> &http::Uri {
|
||||
&self.uri
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &str {
|
||||
if let Some(ref s) = self.path {
|
||||
s
|
||||
} else {
|
||||
self.uri.path()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&mut self, uri: &http::Uri) {
|
||||
self.uri = uri.clone();
|
||||
self.path = DEFAULT_QUOTER.with(|q| q.requote(uri.path().as_bytes()));
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourcePath for Url {
|
||||
fn path(&self) -> &str {
|
||||
self.path()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Quoter {
|
||||
safe_table: [u8; 16],
|
||||
protected_table: [u8; 16],
|
||||
}
|
||||
|
||||
impl Quoter {
|
||||
pub fn new(safe: &[u8], protected: &[u8]) -> Quoter {
|
||||
let mut q = Quoter {
|
||||
safe_table: [0; 16],
|
||||
protected_table: [0; 16],
|
||||
};
|
||||
|
||||
// prepare safe table
|
||||
for i in 0..128 {
|
||||
if ALLOWED.contains(&i) {
|
||||
set_bit(&mut q.safe_table, i);
|
||||
}
|
||||
if QS.contains(&i) {
|
||||
set_bit(&mut q.safe_table, i);
|
||||
}
|
||||
}
|
||||
|
||||
for ch in safe {
|
||||
set_bit(&mut q.safe_table, *ch)
|
||||
}
|
||||
|
||||
// prepare protected table
|
||||
for ch in protected {
|
||||
set_bit(&mut q.safe_table, *ch);
|
||||
set_bit(&mut q.protected_table, *ch);
|
||||
}
|
||||
|
||||
q
|
||||
}
|
||||
|
||||
pub fn requote(&self, val: &[u8]) -> Option<Rc<String>> {
|
||||
let mut has_pct = 0;
|
||||
let mut pct = [b'%', 0, 0];
|
||||
let mut idx = 0;
|
||||
let mut cloned: Option<Vec<u8>> = None;
|
||||
|
||||
let len = val.len();
|
||||
while idx < len {
|
||||
let ch = val[idx];
|
||||
|
||||
if has_pct != 0 {
|
||||
pct[has_pct] = val[idx];
|
||||
has_pct += 1;
|
||||
if has_pct == 3 {
|
||||
has_pct = 0;
|
||||
let buf = cloned.as_mut().unwrap();
|
||||
|
||||
if let Some(ch) = restore_ch(pct[1], pct[2]) {
|
||||
if ch < 128 {
|
||||
if bit_at(&self.protected_table, ch) {
|
||||
buf.extend_from_slice(&pct);
|
||||
idx += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if bit_at(&self.safe_table, ch) {
|
||||
buf.push(ch);
|
||||
idx += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
buf.push(ch);
|
||||
} else {
|
||||
buf.extend_from_slice(&pct[..]);
|
||||
}
|
||||
}
|
||||
} else if ch == b'%' {
|
||||
has_pct = 1;
|
||||
if cloned.is_none() {
|
||||
let mut c = Vec::with_capacity(len);
|
||||
c.extend_from_slice(&val[..idx]);
|
||||
cloned = Some(c);
|
||||
}
|
||||
} else if let Some(ref mut cloned) = cloned {
|
||||
cloned.push(ch)
|
||||
}
|
||||
idx += 1;
|
||||
}
|
||||
|
||||
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) }))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn from_hex(v: u8) -> Option<u8> {
|
||||
if v >= b'0' && v <= b'9' {
|
||||
Some(v - 0x30) // ord('0') == 0x30
|
||||
} else if v >= b'A' && v <= b'F' {
|
||||
Some(v - 0x41 + 10) // ord('A') == 0x41
|
||||
} else if v > b'a' && v <= b'f' {
|
||||
Some(v - 0x61 + 10) // ord('a') == 0x61
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn restore_ch(d1: u8, d2: u8) -> Option<u8> {
|
||||
from_hex(d1).and_then(|d1| from_hex(d2).and_then(move |d2| Some(d1 << 4 | d2)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use http::{HttpTryFrom, Uri};
|
||||
|
||||
use super::*;
|
||||
use crate::{Path, ResourceDef};
|
||||
|
||||
#[test]
|
||||
fn test_parse_url() {
|
||||
let re = ResourceDef::new("/user/{id}/test");
|
||||
|
||||
let url = Uri::try_from("/user/2345/test").unwrap();
|
||||
let mut path = Path::new(Url::new(url));
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "2345");
|
||||
|
||||
let url = Uri::try_from("/user/qwe%25/test").unwrap();
|
||||
let mut path = Path::new(Url::new(url));
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "qwe%");
|
||||
|
||||
let url = Uri::try_from("/user/qwe%25rty/test").unwrap();
|
||||
let mut path = Path::new(Url::new(url));
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "qwe%rty");
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user