mirror of
https://github.com/fafhrd91/actix-net
synced 2025-08-13 01:37:05 +02:00
Compare commits
37 Commits
server-0.2
...
utils-0.3.
Author | SHA1 | Date | |
---|---|---|---|
|
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 |
25
Cargo.toml
25
Cargo.toml
@@ -1,18 +1,3 @@
|
||||
[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",
|
||||
@@ -24,13 +9,3 @@ members = [
|
||||
"actix-utils",
|
||||
"router",
|
||||
]
|
||||
|
||||
[dev-dependencies]
|
||||
actix-service = "0.2.0"
|
||||
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,6 +1,6 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.0] - 2019-01-xx
|
||||
## [0.2.0] - 2019-02-01
|
||||
|
||||
### Changes
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
* Upgrade trust-dns-resolver
|
||||
|
||||
* Use tokio-current-thread instead of diract actix-rt dipendency
|
||||
* Use tokio-current-thread instead of direct actix-rt dipendency
|
||||
|
||||
|
||||
## [0.1.1] - 2019-01-13
|
||||
|
@@ -27,7 +27,7 @@ default = []
|
||||
ssl = ["openssl", "tokio-openssl"]
|
||||
|
||||
[dependencies]
|
||||
#actix-service = "0.1.6"
|
||||
#actix-service = "0.2.0"
|
||||
actix-service = { path="../actix-service" }
|
||||
actix-codec = "0.1.0"
|
||||
futures = "0.1"
|
||||
|
@@ -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};
|
||||
@@ -177,12 +177,13 @@ impl Connector {
|
||||
cfg: ResolverConfig,
|
||||
opts: ResolverOpts,
|
||||
) -> impl NewService<
|
||||
(),
|
||||
Request = 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)))
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -44,7 +44,9 @@ impl<R, T, E> Clone for OpensslConnector<R, T, E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService for OpensslConnector<R, T, E> {
|
||||
impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService<()>
|
||||
for OpensslConnector<R, T, E>
|
||||
{
|
||||
type Request = (R, T);
|
||||
type Response = (R, SslStream<T>);
|
||||
type Error = HandshakeError<T>;
|
||||
@@ -52,7 +54,7 @@ impl<R: RequestHost, T: AsyncRead + AsyncWrite, E> NewService for OpensslConnect
|
||||
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,8 +1,15 @@
|
||||
# Changes
|
||||
|
||||
## [0.2.1] - 2019-02-09
|
||||
|
||||
### Changes
|
||||
|
||||
* Drop service response
|
||||
|
||||
|
||||
## [0.2.0] - 2019-02-01
|
||||
|
||||
## Changes
|
||||
### Changes
|
||||
|
||||
* Migrate to actix-service 0.2
|
||||
|
||||
@@ -11,14 +18,14 @@
|
||||
|
||||
## [0.1.3] - 2018-12-21
|
||||
|
||||
## Fixed
|
||||
### 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.2.0"
|
||||
version = "0.2.1"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix server - General purpose tcp server"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -33,7 +33,8 @@ ssl = ["openssl", "tokio-openssl"]
|
||||
rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
|
||||
|
||||
[dependencies]
|
||||
actix-service = "0.2.0"
|
||||
#actix-service = "0.2.1"
|
||||
actix-service = { path="../actix-service" }
|
||||
actix-rt = "0.1.0"
|
||||
|
||||
log = "0.4"
|
||||
|
@@ -15,7 +15,6 @@ 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::signals::{Signal, Signals};
|
||||
use crate::worker::{self, Worker, WorkerAvailability, WorkerClient};
|
||||
use crate::Token;
|
||||
@@ -176,26 +175,6 @@ impl ServerBuilder {
|
||||
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(
|
||||
name.as_ref().to_string(),
|
||||
token,
|
||||
factory,
|
||||
));
|
||||
self.sockets.push((token, lst));
|
||||
self
|
||||
}
|
||||
|
||||
/// Spawn new thread and start listening for incoming connections.
|
||||
///
|
||||
/// This method spawns new thread and starts new actix system. Other than
|
||||
|
@@ -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| {
|
||||
@@ -219,8 +219,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,7 @@ 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::StreamServiceFactory;
|
||||
|
||||
/// Socket id token
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
|
@@ -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
|
||||
@@ -23,13 +23,7 @@ pub enum ServerMessage {
|
||||
}
|
||||
|
||||
pub trait StreamServiceFactory: Send + Clone + 'static {
|
||||
type NewService: NewService<Request = TcpStream, Response = ()>;
|
||||
|
||||
fn create(&self) -> Self::NewService;
|
||||
}
|
||||
|
||||
pub trait ServiceFactory: Send + Clone + 'static {
|
||||
type NewService: NewService<Request = ServerMessage, Response = ()>;
|
||||
type NewService: NewService<Request = TcpStream>;
|
||||
|
||||
fn create(&self) -> Self::NewService;
|
||||
}
|
||||
@@ -63,7 +57,7 @@ impl<T> StreamService<T> {
|
||||
|
||||
impl<T> Service for StreamService<T>
|
||||
where
|
||||
T: Service<Request = TcpStream, Response = ()>,
|
||||
T: Service<Request = TcpStream>,
|
||||
T::Future: 'static,
|
||||
T::Error: 'static,
|
||||
{
|
||||
@@ -86,7 +80,7 @@ where
|
||||
if let Ok(stream) = stream {
|
||||
spawn(self.service.call(stream).then(move |res| {
|
||||
drop(guard);
|
||||
res.map_err(|_| ())
|
||||
res.map_err(|_| ()).map(|_| ())
|
||||
}));
|
||||
ok(())
|
||||
} else {
|
||||
@@ -98,86 +92,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ServerService<T> {
|
||||
service: T,
|
||||
}
|
||||
|
||||
impl<T> ServerService<T> {
|
||||
fn new(service: T) -> Self {
|
||||
ServerService { service }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service for ServerService<T>
|
||||
where
|
||||
T: Service<Request = ServerMessage, Response = ()>,
|
||||
T::Future: 'static,
|
||||
T::Error: 'static,
|
||||
{
|
||||
type Request = (Option<CounterGuard>, ServerMessage);
|
||||
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).then(move |res| {
|
||||
drop(guard);
|
||||
res.map_err(|_| ())
|
||||
}));
|
||||
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> {
|
||||
name: String,
|
||||
inner: F,
|
||||
@@ -214,7 +128,7 @@ where
|
||||
Box::new(
|
||||
self.inner
|
||||
.create()
|
||||
.new_service()
|
||||
.new_service(&())
|
||||
.map_err(|_| ())
|
||||
.map(move |inner| {
|
||||
let service: BoxedServerService = Box::new(StreamService::new(inner));
|
||||
@@ -238,22 +152,10 @@ impl InternalServiceFactory for Box<InternalServiceFactory> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, T> ServiceFactory for F
|
||||
where
|
||||
F: Fn() -> T + Send + Clone + 'static,
|
||||
T: NewService<Request = 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<Request = TcpStream, Response = ()>,
|
||||
T: NewService<Request = TcpStream>,
|
||||
{
|
||||
type NewService = T;
|
||||
|
||||
|
@@ -44,7 +44,7 @@ impl<T: AsyncRead + AsyncWrite> NewService 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(),
|
||||
|
@@ -44,7 +44,7 @@ impl<T: AsyncRead + AsyncWrite> NewService 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(),
|
||||
|
@@ -46,7 +46,7 @@ impl<T: AsyncRead + AsyncWrite> NewService 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,5 +1,34 @@
|
||||
# Changes
|
||||
|
||||
## [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
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-service"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix 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 = ".."
|
||||
|
||||
[badges]
|
||||
travis-ci = { repository = "actix/actix-service", branch = "master" }
|
||||
@@ -24,3 +24,4 @@ path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
futures = "0.1.24"
|
||||
void = "1.0.2"
|
||||
|
@@ -1,3 +1,5 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{try_ready, Async, Future, Poll};
|
||||
|
||||
use super::{IntoNewService, NewService, Service};
|
||||
@@ -105,29 +107,31 @@ where
|
||||
}
|
||||
|
||||
/// `AndThenNewService` new service combinator
|
||||
pub struct AndThenNewService<A, B> {
|
||||
pub struct AndThenNewService<A, B, C> {
|
||||
a: A,
|
||||
b: B,
|
||||
_t: PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<A, B> AndThenNewService<A, B> {
|
||||
impl<A, B, C> AndThenNewService<A, B, C> {
|
||||
/// Create new `AndThen` combinator
|
||||
pub fn new<F: IntoNewService<B>>(a: A, f: F) -> Self
|
||||
pub fn new<F: IntoNewService<B, C>>(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService,
|
||||
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
Self {
|
||||
a,
|
||||
b: f.into_new_service(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> NewService for AndThenNewService<A, B>
|
||||
impl<A, B, C> NewService<C> for AndThenNewService<A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = B::Response;
|
||||
@@ -135,14 +139,14 @@ where
|
||||
type Service = AndThen<A::Service, B::Service>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = AndThenNewServiceFuture<A, B>;
|
||||
type Future = AndThenNewServiceFuture<A, B, 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))
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> Clone for AndThenNewService<A, B>
|
||||
impl<A, B, C> Clone for AndThenNewService<A, B, C>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
@@ -151,14 +155,15 @@ where
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenNewServiceFuture<A, B>
|
||||
pub struct AndThenNewServiceFuture<A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
B: NewService<Request = A::Response>,
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response>,
|
||||
{
|
||||
fut_b: B::Future,
|
||||
fut_a: A::Future,
|
||||
@@ -166,10 +171,10 @@ where
|
||||
b: Option<B::Service>,
|
||||
}
|
||||
|
||||
impl<A, B> AndThenNewServiceFuture<A, B>
|
||||
impl<A, B, C> AndThenNewServiceFuture<A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
B: NewService<Request = A::Response>,
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response>,
|
||||
{
|
||||
fn new(fut_a: A::Future, fut_b: B::Future) -> Self {
|
||||
AndThenNewServiceFuture {
|
||||
@@ -181,10 +186,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> Future for AndThenNewServiceFuture<A, B>
|
||||
impl<A, B, C> Future for AndThenNewServiceFuture<A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
B: NewService<Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Request = A::Response, Error = A::Error, InitError = A::InitError>,
|
||||
{
|
||||
type Item = AndThen<A::Service, B::Service>;
|
||||
type Error = A::InitError;
|
||||
@@ -286,7 +291,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")));
|
||||
|
@@ -1,125 +1,120 @@
|
||||
use std::marker::PhantomData;
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||
|
||||
use super::{IntoNewService, IntoService, NewService, Service};
|
||||
use super::{NewService, NewTransform, Service, Transform};
|
||||
use crate::cell::Cell;
|
||||
|
||||
/// `Apply` service combinator
|
||||
pub struct AndThenApply<A, B, F, Out>
|
||||
pub struct AndThenTransform<T, A, B>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
a: A,
|
||||
b: Cell<B>,
|
||||
f: Cell<F>,
|
||||
r: PhantomData<(Out,)>,
|
||||
t: Cell<T>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out> AndThenApply<A, B, F, Out>
|
||||
impl<T, A, B> AndThenTransform<T, A, B>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
/// Create new `Apply` combinator
|
||||
pub fn new<A1: IntoService<A>, B1: IntoService<B>>(a: A1, b: B1, f: F) -> Self {
|
||||
pub fn new(t: T, a: A, b: B) -> Self {
|
||||
Self {
|
||||
f: Cell::new(f),
|
||||
a: a.into_service(),
|
||||
b: Cell::new(b.into_service()),
|
||||
r: PhantomData,
|
||||
a,
|
||||
b: Cell::new(b),
|
||||
t: Cell::new(t),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out> Clone for AndThenApply<A, B, F, Out>
|
||||
impl<T, A, B> Clone for AndThenTransform<T, A, B>
|
||||
where
|
||||
A: Service + Clone,
|
||||
B: Service<Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
AndThenApply {
|
||||
AndThenTransform {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
f: self.f.clone(),
|
||||
r: PhantomData,
|
||||
t: self.t.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out> Service for AndThenApply<A, B, F, Out>
|
||||
impl<T, A, B> Service for AndThenTransform<T, A, B>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = Out::Item;
|
||||
type Error = A::Error;
|
||||
type Future = AndThenApplyFuture<A, B, F, Out>;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = AndThenTransformFuture<T, A, B>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
try_ready!(self.a.poll_ready());
|
||||
self.b.get_mut().poll_ready().map_err(|e| e.into())
|
||||
let notready = Async::NotReady == self.a.poll_ready()?;
|
||||
let notready = Async::NotReady == self.b.get_mut().poll_ready()? || notready;
|
||||
let notready = Async::NotReady == self.t.get_mut().poll_ready()? || notready;
|
||||
|
||||
if notready {
|
||||
Ok(Async::NotReady)
|
||||
} else {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||
AndThenApplyFuture {
|
||||
AndThenTransformFuture {
|
||||
b: self.b.clone(),
|
||||
f: self.f.clone(),
|
||||
fut_b: None,
|
||||
t: self.t.clone(),
|
||||
fut_t: None,
|
||||
fut_a: Some(self.a.call(req)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenApplyFuture<A, B, F, Out>
|
||||
pub struct AndThenTransformFuture<T, A, B>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
b: Cell<B>,
|
||||
f: Cell<F>,
|
||||
t: Cell<T>,
|
||||
fut_a: Option<A::Future>,
|
||||
fut_b: Option<Out::Future>,
|
||||
fut_t: Option<T::Future>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out> Future for AndThenApplyFuture<A, B, F, Out>
|
||||
impl<T, A, B> Future for AndThenTransformFuture<T, A, B>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
T: Transform<B, Request = A::Response>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
type Item = Out::Item;
|
||||
type Error = A::Error;
|
||||
type Item = T::Response;
|
||||
type Error = T::Error;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Some(ref mut fut) = self.fut_b {
|
||||
return fut.poll().map_err(|e| e.into());
|
||||
if let Some(ref mut fut) = self.fut_t {
|
||||
return fut.poll();
|
||||
}
|
||||
|
||||
match self.fut_a.as_mut().expect("Bug in actix-service").poll() {
|
||||
Ok(Async::Ready(resp)) => {
|
||||
let _ = self.fut_a.take();
|
||||
self.fut_b =
|
||||
Some((&mut *self.f.get_mut())(resp, self.b.get_mut()).into_future());
|
||||
self.fut_t = Some(self.t.get_mut().call(resp, self.b.get_mut()));
|
||||
self.poll()
|
||||
}
|
||||
Ok(Async::NotReady) => Ok(Async::NotReady),
|
||||
@@ -128,102 +123,107 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// `ApplyNewService` new service combinator
|
||||
pub struct AndThenApplyNewService<A, B, F, Out> {
|
||||
/// `Apply` new service combinator
|
||||
pub struct AndThenTransformNewService<T, A, B, C> {
|
||||
a: A,
|
||||
b: B,
|
||||
f: Cell<F>,
|
||||
r: PhantomData<(Out)>,
|
||||
t: T,
|
||||
_t: std::marker::PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out> AndThenApplyNewService<A, B, F, Out>
|
||||
impl<T, A, B, C> AndThenTransformNewService<T, A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
B: NewService<Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Error = A::Error, InitError = A::InitError>,
|
||||
T: NewTransform<B::Service, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
/// Create new `ApplyNewService` new service instance
|
||||
pub fn new<A1: IntoNewService<A>, B1: IntoNewService<B>>(a: A1, b: B1, f: F) -> Self {
|
||||
pub fn new(t: T, a: A, b: B) -> Self {
|
||||
Self {
|
||||
f: Cell::new(f),
|
||||
a: a.into_new_service(),
|
||||
b: b.into_new_service(),
|
||||
r: PhantomData,
|
||||
a,
|
||||
b,
|
||||
t,
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out> Clone for AndThenApplyNewService<A, B, F, Out>
|
||||
impl<T, A, B, C> Clone for AndThenTransformNewService<T, A, B, C>
|
||||
where
|
||||
A: Clone,
|
||||
B: Clone,
|
||||
T: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
f: self.f.clone(),
|
||||
r: PhantomData,
|
||||
t: self.t.clone(),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out> NewService for AndThenApplyNewService<A, B, F, Out>
|
||||
impl<T, A, B, C> NewService<C> for AndThenTransformNewService<T, A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
B: NewService<Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Error = A::Error, InitError = A::InitError>,
|
||||
T: NewTransform<B::Service, C, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = Out::Item;
|
||||
type Error = A::Error;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Service = AndThenApply<A::Service, B::Service, F, Out>;
|
||||
type Future = AndThenApplyNewServiceFuture<A, B, F, Out>;
|
||||
type InitError = T::InitError;
|
||||
type Service = AndThenTransform<T::Transform, A::Service, B::Service>;
|
||||
type Future = AndThenTransformNewServiceFuture<T, A, B, C>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
AndThenApplyNewServiceFuture {
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
AndThenTransformNewServiceFuture {
|
||||
a: None,
|
||||
b: None,
|
||||
f: self.f.clone(),
|
||||
fut_a: self.a.new_service(),
|
||||
fut_b: self.b.new_service(),
|
||||
t: None,
|
||||
fut_a: self.a.new_service(cfg),
|
||||
fut_b: self.b.new_service(cfg),
|
||||
fut_t: self.t.new_transform(cfg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenApplyNewServiceFuture<A, B, F, Out>
|
||||
pub struct AndThenTransformNewServiceFuture<T, A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
B: NewService<Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Error = A::Error, InitError = A::InitError>,
|
||||
T: NewTransform<B::Service, C, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
fut_b: B::Future,
|
||||
fut_a: A::Future,
|
||||
f: Cell<F>,
|
||||
fut_t: T::Future,
|
||||
a: Option<A::Service>,
|
||||
b: Option<B::Service>,
|
||||
t: Option<T::Transform>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out> Future for AndThenApplyNewServiceFuture<A, B, F, Out>
|
||||
impl<T, A, B, C> Future for AndThenTransformNewServiceFuture<T, A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
B: NewService<Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
A: NewService<C>,
|
||||
B: NewService<C, Error = A::Error, InitError = A::InitError>,
|
||||
T: NewTransform<B::Service, C, Request = A::Response, InitError = A::InitError>,
|
||||
T::Error: From<A::Error>,
|
||||
{
|
||||
type Item = AndThenApply<A::Service, B::Service, F, Out>;
|
||||
type Error = A::InitError;
|
||||
type Item = AndThenTransform<T::Transform, A::Service, B::Service>;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if self.t.is_none() {
|
||||
if let Async::Ready(transform) = self.fut_t.poll()? {
|
||||
self.t = Some(transform);
|
||||
}
|
||||
}
|
||||
|
||||
if self.a.is_none() {
|
||||
if let Async::Ready(service) = self.fut_a.poll()? {
|
||||
self.a = Some(service);
|
||||
@@ -236,12 +236,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
if self.a.is_some() && self.b.is_some() {
|
||||
Ok(Async::Ready(AndThenApply {
|
||||
f: self.f.clone(),
|
||||
if self.a.is_some() && self.b.is_some() && self.t.is_some() {
|
||||
Ok(Async::Ready(AndThenTransform {
|
||||
a: self.a.take().unwrap(),
|
||||
t: Cell::new(self.t.take().unwrap()),
|
||||
b: Cell::new(self.b.take().unwrap()),
|
||||
r: PhantomData,
|
||||
}))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
@@ -274,12 +273,13 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_call() {
|
||||
fn test_apply() {
|
||||
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(
|
||||
|req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)),
|
||||
Srv,
|
||||
);
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
let res = srv.call("srv").poll();
|
||||
assert!(res.is_ok());
|
||||
@@ -291,10 +291,10 @@ mod tests {
|
||||
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),
|
||||
|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());
|
||||
|
307
actix-service/src/and_then_apply_fn.rs
Normal file
307
actix-service/src/and_then_apply_fn.rs
Normal file
@@ -0,0 +1,307 @@
|
||||
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>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
a: A,
|
||||
b: Cell<B>,
|
||||
f: Cell<F>,
|
||||
r: PhantomData<(Out,)>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out> AndThenApply<A, B, F, Out>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<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>, B1: IntoService<B>>(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> Clone for AndThenApply<A, B, F, Out>
|
||||
where
|
||||
A: Service + Clone,
|
||||
B: Service<Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
AndThenApply {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
f: self.f.clone(),
|
||||
r: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B, F, Out> Service for AndThenApply<A, B, F, Out>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<Error = A::Error>,
|
||||
F: FnMut(A::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = Out::Item;
|
||||
type Error = A::Error;
|
||||
type Future = AndThenApplyFuture<A, B, F, Out>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
try_ready!(self.a.poll_ready());
|
||||
self.b.get_mut().poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: A::Request) -> Self::Future {
|
||||
AndThenApplyFuture {
|
||||
b: self.b.clone(),
|
||||
f: self.f.clone(),
|
||||
fut_b: None,
|
||||
fut_a: Some(self.a.call(req)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenApplyFuture<A, B, F, Out>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<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>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out> Future for AndThenApplyFuture<A, B, F, Out>
|
||||
where
|
||||
A: Service,
|
||||
B: Service<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, Cfg> {
|
||||
a: A,
|
||||
b: B,
|
||||
f: Cell<F>,
|
||||
r: PhantomData<(Out, Cfg)>,
|
||||
}
|
||||
|
||||
impl<A, B, F, Out, Cfg> AndThenApplyNewService<A, B, F, Out, Cfg>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<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, Cfg>, B1: IntoNewService<B, 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, Cfg> Clone for AndThenApplyNewService<A, B, F, Out, 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, Cfg> NewService<Cfg> for AndThenApplyNewService<A, B, F, Out, Cfg>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<Cfg, Error = A::Error, InitError = A::InitError>,
|
||||
F: FnMut(A::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<A::Error>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
type Response = Out::Item;
|
||||
type Error = A::Error;
|
||||
type Service = AndThenApply<A::Service, B::Service, F, Out>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = AndThenApplyNewServiceFuture<A, B, F, Out, 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),
|
||||
fut_b: self.b.new_service(cfg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<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, Cfg> Future for AndThenApplyNewServiceFuture<A, B, F, Out, Cfg>
|
||||
where
|
||||
A: NewService<Cfg>,
|
||||
B: NewService<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>;
|
||||
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 Request = ();
|
||||
type Response = ();
|
||||
type Error = ();
|
||||
type Future = FutureResult<(), ()>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, _: ()) -> Self::Future {
|
||||
ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_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!()
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,172 +1,218 @@
|
||||
use std::marker::PhantomData;
|
||||
use futures::{try_ready, Async, Future, IntoFuture, Poll};
|
||||
|
||||
use futures::{Async, Future, IntoFuture, Poll};
|
||||
|
||||
use super::{IntoNewService, IntoService, NewService, Service};
|
||||
use super::{FnNewTransform, FnTransform};
|
||||
use super::{
|
||||
IntoNewService, IntoNewTransform, IntoService, IntoTransform, NewService, NewTransform,
|
||||
Service, Transform,
|
||||
};
|
||||
|
||||
/// `Apply` service combinator
|
||||
pub struct Apply<T, F, In, Out>
|
||||
pub struct Apply<T, S>
|
||||
where
|
||||
T: Service,
|
||||
T: Transform<S>,
|
||||
T::Error: From<S::Error>,
|
||||
S: Service,
|
||||
{
|
||||
service: T,
|
||||
f: F,
|
||||
r: PhantomData<(In, Out)>,
|
||||
transform: T,
|
||||
service: S,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out> Apply<T, F, In, Out>
|
||||
impl<T, S> Apply<T, S>
|
||||
where
|
||||
T: Service,
|
||||
F: FnMut(In, &mut T) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
T: Transform<S>,
|
||||
T::Error: From<S::Error>,
|
||||
S: Service,
|
||||
{
|
||||
/// Create new `Apply` combinator
|
||||
pub fn new<I: IntoService<T>>(service: I, f: F) -> Self {
|
||||
pub fn new<T1: IntoTransform<T, S>, S1: IntoService<S>>(
|
||||
transform: T1,
|
||||
service: S1,
|
||||
) -> Self {
|
||||
Self {
|
||||
transform: transform.into_transform(),
|
||||
service: service.into_service(),
|
||||
f,
|
||||
r: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out> Clone for Apply<T, F, In, Out>
|
||||
impl<F, S, Req, Out> Apply<FnTransform<F, S, Req, Out>, S>
|
||||
where
|
||||
T: Service + Clone,
|
||||
F: Clone,
|
||||
F: FnMut(Req, &mut S) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<S::Error>,
|
||||
S: Service,
|
||||
{
|
||||
/// Create new `Apply` combinator
|
||||
pub fn new_fn<S1: IntoService<S>>(service: S1, transform: F) -> Self {
|
||||
Self {
|
||||
service: service.into_service(),
|
||||
transform: transform.into_transform(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> Clone for Apply<T, S>
|
||||
where
|
||||
S: Service + Clone,
|
||||
T::Error: From<S::Error>,
|
||||
T: Transform<S> + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Apply {
|
||||
service: self.service.clone(),
|
||||
f: self.f.clone(),
|
||||
r: PhantomData,
|
||||
transform: self.transform.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out> Service for Apply<T, F, In, Out>
|
||||
impl<T, S> Service for Apply<T, S>
|
||||
where
|
||||
T: Service,
|
||||
F: FnMut(In, &mut T) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
T: Transform<S>,
|
||||
T::Error: From<S::Error>,
|
||||
S: Service,
|
||||
{
|
||||
type Request = In;
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
type Future = Out::Future;
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = T::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.service.poll_ready().map_err(|e| e.into())
|
||||
try_ready!(self.service.poll_ready());
|
||||
self.transform.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: In) -> Self::Future {
|
||||
(self.f)(req, &mut self.service).into_future()
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
self.transform.call(req, &mut self.service).into_future()
|
||||
}
|
||||
}
|
||||
|
||||
/// `ApplyNewService` new service combinator
|
||||
pub struct ApplyNewService<T, F, In, Out>
|
||||
pub struct ApplyNewService<T, S, C>
|
||||
where
|
||||
T: NewService,
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError>,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C>,
|
||||
{
|
||||
service: T,
|
||||
f: F,
|
||||
r: PhantomData<(In, Out)>,
|
||||
transform: T,
|
||||
service: S,
|
||||
_t: std::marker::PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out> ApplyNewService<T, F, In, Out>
|
||||
impl<T, S, C> ApplyNewService<T, S, C>
|
||||
where
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError>,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C>,
|
||||
{
|
||||
/// Create new `ApplyNewService` new service instance
|
||||
pub fn new<F1: IntoNewService<T>>(service: F1, f: F) -> Self {
|
||||
pub fn new<T1: IntoNewTransform<T, S::Service, C>, S1: IntoNewService<S, C>>(
|
||||
transform: T1,
|
||||
service: S1,
|
||||
) -> Self {
|
||||
Self {
|
||||
f,
|
||||
transform: transform.into_new_transform(),
|
||||
service: service.into_new_service(),
|
||||
r: PhantomData,
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out> Clone for ApplyNewService<T, F, In, Out>
|
||||
impl<F, S, In, Out, Cfg>
|
||||
ApplyNewService<FnNewTransform<F, S::Service, In, Out, S::InitError, Cfg>, S, Cfg>
|
||||
where
|
||||
T: NewService + Clone,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
F: FnMut(In, &mut S::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<S::Error>,
|
||||
S: NewService<Cfg>,
|
||||
{
|
||||
/// Create new `Apply` combinator factory
|
||||
pub fn new_fn<S1: IntoNewService<S, Cfg>>(service: S1, transform: F) -> Self {
|
||||
Self {
|
||||
service: service.into_new_service(),
|
||||
transform: FnNewTransform::new(transform),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C> Clone for ApplyNewService<T, S, C>
|
||||
where
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError> + Clone,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C> + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
service: self.service.clone(),
|
||||
f: self.f.clone(),
|
||||
r: PhantomData,
|
||||
transform: self.transform.clone(),
|
||||
_t: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out> NewService for ApplyNewService<T, F, In, Out>
|
||||
impl<T, S, C> NewService<C> for ApplyNewService<T, S, C>
|
||||
where
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError>,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C>,
|
||||
{
|
||||
type Request = In;
|
||||
type Response = Out::Item;
|
||||
type Error = Out::Error;
|
||||
type Service = Apply<T::Service, F, In, Out>;
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Service = Apply<T::Transform, S::Service>;
|
||||
|
||||
type InitError = T::InitError;
|
||||
type Future = ApplyNewServiceFuture<T, F, In, Out>;
|
||||
type Future = ApplyNewServiceFuture<T, S, C>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
ApplyNewServiceFuture::new(self.service.new_service(), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ApplyNewServiceFuture<T, F, In, Out>
|
||||
where
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fut: T::Future,
|
||||
f: Option<F>,
|
||||
r: PhantomData<(In, Out)>,
|
||||
}
|
||||
|
||||
impl<T, F, In, Out> ApplyNewServiceFuture<T, F, In, Out>
|
||||
where
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
ApplyNewServiceFuture {
|
||||
f: Some(f),
|
||||
fut,
|
||||
r: PhantomData,
|
||||
fut_t: self.transform.new_transform(cfg),
|
||||
fut_s: self.service.new_service(cfg),
|
||||
service: None,
|
||||
transform: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, F, In, Out> Future for ApplyNewServiceFuture<T, F, In, Out>
|
||||
pub struct ApplyNewServiceFuture<T, S, C>
|
||||
where
|
||||
T: NewService,
|
||||
F: FnMut(In, &mut T::Service) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
Out::Error: From<T::Error>,
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError>,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C>,
|
||||
{
|
||||
type Item = Apply<T::Service, F, In, Out>;
|
||||
fut_s: S::Future,
|
||||
fut_t: T::Future,
|
||||
service: Option<S::Service>,
|
||||
transform: Option<T::Transform>,
|
||||
}
|
||||
|
||||
impl<T, S, C> Future for ApplyNewServiceFuture<T, S, C>
|
||||
where
|
||||
T: NewTransform<S::Service, C, InitError = S::InitError>,
|
||||
T::Error: From<S::Error>,
|
||||
S: NewService<C>,
|
||||
{
|
||||
type Item = Apply<T::Transform, S::Service>;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Async::Ready(service) = self.fut.poll()? {
|
||||
Ok(Async::Ready(Apply::new(service, self.f.take().unwrap())))
|
||||
if self.transform.is_none() {
|
||||
if let Async::Ready(transform) = self.fut_t.poll()? {
|
||||
self.transform = Some(transform);
|
||||
}
|
||||
}
|
||||
|
||||
if self.service.is_none() {
|
||||
if let Async::Ready(service) = self.fut_s.poll()? {
|
||||
self.service = Some(service);
|
||||
}
|
||||
}
|
||||
|
||||
if self.transform.is_some() && self.service.is_some() {
|
||||
Ok(Async::Ready(Apply {
|
||||
service: self.service.take().unwrap(),
|
||||
transform: self.transform.take().unwrap(),
|
||||
}))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
@@ -178,7 +224,8 @@ mod tests {
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use crate::{IntoNewService, IntoService, NewService, Service, ServiceExt};
|
||||
use super::*;
|
||||
use crate::{NewService, Service};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Srv;
|
||||
@@ -198,10 +245,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_call() {
|
||||
let blank = |req| Ok(req);
|
||||
|
||||
let mut srv = blank.into_service().apply(Srv, |req: &'static str, srv| {
|
||||
fn test_apply() {
|
||||
let mut srv = Apply::new_fn(Srv, |req: &'static str, srv| {
|
||||
srv.call(()).map(move |res| (req, res))
|
||||
});
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
@@ -212,13 +257,27 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_new_service() {
|
||||
let blank = || Ok::<_, ()>((|req| Ok(req)).into_service());
|
||||
let new_srv = ApplyNewService::new(
|
||||
|req: &'static str, srv: &mut Srv| srv.call(()).map(move |res| (req, res)),
|
||||
|| Ok::<_, ()>(Srv),
|
||||
);
|
||||
if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() {
|
||||
assert!(srv.poll_ready().is_ok());
|
||||
let res = srv.call("srv").poll();
|
||||
assert!(res.is_ok());
|
||||
assert_eq!(res.unwrap(), Async::Ready(("srv", ())));
|
||||
} else {
|
||||
panic!()
|
||||
}
|
||||
}
|
||||
|
||||
let new_srv = blank.into_new_service().apply(
|
||||
|| Ok(Srv),
|
||||
#[test]
|
||||
fn test_new_service_fn() {
|
||||
let new_srv = ApplyNewService::new_fn(
|
||||
|| Ok::<_, ()>(Srv),
|
||||
|req: &'static str, srv| srv.call(()).map(move |res| (req, res)),
|
||||
);
|
||||
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());
|
||||
|
83
actix-service/src/blank.rs
Normal file
83
actix-service/src/blank.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
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 for Blank<R, E> {
|
||||
type Request = R;
|
||||
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<()> for BlankNewService<R, E1, E2> {
|
||||
type Request = R;
|
||||
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())
|
||||
}
|
||||
}
|
136
actix-service/src/boxed.rs
Normal file
136
actix-service/src/boxed.rs
Normal file
@@ -0,0 +1,136 @@
|
||||
use crate::{NewService, Service};
|
||||
use futures::{Future, Poll};
|
||||
|
||||
pub type BoxedService<Req, Res, Err> = Box<
|
||||
Service<
|
||||
Request = Req,
|
||||
Response = Res,
|
||||
Error = Err,
|
||||
Future = Box<Future<Item = Res, Error = Err>>,
|
||||
>,
|
||||
>;
|
||||
|
||||
/// Create boxed new service
|
||||
pub fn new_service<T, C>(
|
||||
service: T,
|
||||
) -> BoxedNewService<C, T::Request, T::Response, T::Error, T::InitError>
|
||||
where
|
||||
C: 'static,
|
||||
T: NewService<C> + 'static,
|
||||
T::Request: 'static,
|
||||
T::Response: 'static,
|
||||
T::Service: 'static,
|
||||
T::Future: 'static,
|
||||
T::Error: 'static,
|
||||
T::InitError: 'static,
|
||||
{
|
||||
BoxedNewService(Box::new(NewServiceWrapper {
|
||||
service,
|
||||
_t: std::marker::PhantomData,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Create boxed service
|
||||
pub fn service<T>(service: T) -> BoxedService<T::Request, T::Response, T::Error>
|
||||
where
|
||||
T: Service + 'static,
|
||||
T::Future: 'static,
|
||||
{
|
||||
Box::new(ServiceWrapper(service))
|
||||
}
|
||||
|
||||
type Inner<C, Req, Res, Err, InitErr> = Box<
|
||||
NewService<
|
||||
C,
|
||||
Request = Req,
|
||||
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<C> for BoxedNewService<C, Req, Res, Err, InitErr>
|
||||
where
|
||||
Req: 'static,
|
||||
Res: 'static,
|
||||
Err: 'static,
|
||||
InitErr: 'static,
|
||||
{
|
||||
type Request = Req;
|
||||
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<C, T: NewService<C>> {
|
||||
service: T,
|
||||
_t: std::marker::PhantomData<C>,
|
||||
}
|
||||
|
||||
impl<C, T, Req, Res, Err, InitErr> NewService<C> for NewServiceWrapper<C, T>
|
||||
where
|
||||
Req: 'static,
|
||||
Res: 'static,
|
||||
Err: 'static,
|
||||
InitErr: 'static,
|
||||
T: NewService<C, Request = Req, Response = Res, Error = Err, InitError = InitErr>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
type Request = Req;
|
||||
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)
|
||||
.map(|service| ServiceWrapper::boxed(service)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct ServiceWrapper<T: Service>(T);
|
||||
|
||||
impl<T> ServiceWrapper<T>
|
||||
where
|
||||
T: Service + 'static,
|
||||
T::Future: 'static,
|
||||
{
|
||||
fn boxed(service: T) -> BoxedService<T::Request, T::Response, T::Error> {
|
||||
Box::new(ServiceWrapper(service))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Req, Res, Err> Service for ServiceWrapper<T>
|
||||
where
|
||||
T: Service<Request = Req, Response = Res, Error = Err>,
|
||||
T::Future: 'static,
|
||||
{
|
||||
type Request = Req;
|
||||
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.0.poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, req: Self::Request) -> Self::Future {
|
||||
Box::new(self.0.call(req))
|
||||
}
|
||||
}
|
@@ -1,56 +1,80 @@
|
||||
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: FnMut(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>(f: F) -> FnNewServiceNoConfig<F, R, S, E>
|
||||
where
|
||||
F: FnMut(Req) -> Fut,
|
||||
Fut: IntoFuture<Item = Resp, Error = E>,
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
FnNewServiceNoConfig::new(f)
|
||||
}
|
||||
|
||||
/// Create `NewService` for function that can produce services with configuration
|
||||
pub fn fn_cfg_factory<F, C, R, S, E>(f: F) -> FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
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: FnMut(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 for FnService<F, Req, Resp, E, Fut>
|
||||
impl<F, Req, Out> Service for FnService<F, Req, Out>
|
||||
where
|
||||
F: FnMut(Req) -> Fut,
|
||||
Fut: IntoFuture<Item = Resp, Error = E>,
|
||||
F: FnMut(Req) -> Out,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
type Request = Req;
|
||||
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(()))
|
||||
@@ -61,71 +85,194 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, Req, Resp, Err, Fut> IntoService<FnService<F, Req, Resp, Err, Fut>> for F
|
||||
impl<F, Req, Out> IntoService<FnService<F, Req, Out>> for F
|
||||
where
|
||||
F: FnMut(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: FnMut(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: FnMut(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 for FnNewService<F, Req, Resp, Err, Fut>
|
||||
impl<F, Req, Out, Cfg> NewService<Cfg> for FnNewService<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(Req) -> Fut + Clone,
|
||||
Fut: IntoFuture<Item = Resp, Error = Err>,
|
||||
F: FnMut(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
type Request = Req;
|
||||
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>> for F
|
||||
impl<F, Req, Out, Cfg> Clone for FnNewService<F, Req, Out, Cfg>
|
||||
where
|
||||
F: FnMut(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: FnMut(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>, Cfg> for F
|
||||
where
|
||||
F: Fn(Req) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewService<F, Req, Out, Cfg> {
|
||||
FnNewService::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converter for `Fn() -> Future<Service>` fn
|
||||
pub struct FnNewServiceNoConfig<F, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<F, R, S, E> FnNewServiceNoConfig<F, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewServiceNoConfig { f }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, S, E> NewService<()> for FnNewServiceNoConfig<F, R, S, E>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S;
|
||||
|
||||
type InitError = E;
|
||||
type Future = R::Future;
|
||||
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
(self.f)().into_future()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, S, E> Clone for FnNewServiceNoConfig<F, R, S, E>
|
||||
where
|
||||
F: Fn() -> R + Clone,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, S, E> IntoNewService<FnNewServiceNoConfig<F, R, S, E>, ()> for F
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewServiceNoConfig<F, R, S, E> {
|
||||
FnNewServiceNoConfig::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `Fn(&Config) -> Future<Service>` fn to NewService
|
||||
pub struct FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(C, R, S, E)>,
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewServiceConfig { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> NewService<C> for FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = S::Error;
|
||||
type Service = S;
|
||||
|
||||
type InitError = E;
|
||||
type Future = R::Future;
|
||||
|
||||
fn new_service(&self, cfg: &C) -> Self::Future {
|
||||
(self.f)(cfg).into_future()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> Clone for FnNewServiceConfig<F, C, R, S, E>
|
||||
where
|
||||
F: Fn(&C) -> R + Clone,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, C, R, S, E> IntoConfigurableNewService<FnNewServiceConfig<F, C, R, S, E>, C> for F
|
||||
where
|
||||
F: Fn(&C) -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
{
|
||||
fn into_new_service(self) -> FnNewServiceConfig<F, C, R, S, E> {
|
||||
FnNewServiceConfig::new(self)
|
||||
}
|
||||
}
|
||||
|
124
actix-service/src/fn_transform.rs
Normal file
124
actix-service/src/fn_transform.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, IntoFuture, Poll};
|
||||
|
||||
use crate::{IntoNewTransform, IntoTransform, NewTransform, Transform};
|
||||
|
||||
pub struct FnTransform<F, S, Req, Res>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(S, Req, Res)>,
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res> FnTransform<F, S, Req, Res>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnTransform { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res> Clone for FnTransform<F, S, Req, Res>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res + Clone,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
FnTransform {
|
||||
f: self.f.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res> Transform<S> for FnTransform<F, S, Req, Res>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
type Request = Req;
|
||||
type Response = Res::Item;
|
||||
type Error = Res::Error;
|
||||
type Future = Res::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Req, service: &mut S) -> Self::Future {
|
||||
(self.f)(request, service).into_future()
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res> IntoTransform<FnTransform<F, S, Req, Res>, S> for F
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
fn into_transform(self) -> FnTransform<F, S, Req, Res> {
|
||||
FnTransform::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FnNewTransform<F, S, Req, Out, Err, Cfg>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Out + Clone,
|
||||
Out: IntoFuture,
|
||||
{
|
||||
f: F,
|
||||
_t: PhantomData<(S, Req, Out, Err, Cfg)>,
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res, Err, Cfg> FnNewTransform<F, S, Req, Res, Err, Cfg>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res + Clone,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
pub fn new(f: F) -> Self {
|
||||
FnNewTransform { f, _t: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res, Err, Cfg> NewTransform<S, Cfg> for FnNewTransform<F, S, Req, Res, Err, Cfg>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res + Clone,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
type Request = Req;
|
||||
type Response = Res::Item;
|
||||
type Error = Res::Error;
|
||||
type Transform = FnTransform<F, S, Req, Res>;
|
||||
type InitError = Err;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn new_transform(&self, _: &Cfg) -> Self::Future {
|
||||
ok(FnTransform::new(self.f.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res, Err, Cfg>
|
||||
IntoNewTransform<FnNewTransform<F, S, Req, Res, Err, Cfg>, S, Cfg> for F
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res + Clone,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
fn into_new_transform(self) -> FnNewTransform<F, S, Req, Res, Err, Cfg> {
|
||||
FnNewTransform::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, S, Req, Res, Err, Cfg> Clone for FnNewTransform<F, S, Req, Res, Err, Cfg>
|
||||
where
|
||||
F: FnMut(Req, &mut S) -> Res + Clone,
|
||||
Res: IntoFuture,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self::new(self.f.clone())
|
||||
}
|
||||
}
|
@@ -81,23 +81,23 @@ where
|
||||
/// service's error.
|
||||
///
|
||||
/// This is created by the `NewServiceExt::from_err` method.
|
||||
pub struct FromErrNewService<A, E> {
|
||||
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(a: A) -> Self
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<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,
|
||||
{
|
||||
@@ -109,9 +109,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, E> NewService for FromErrNewService<A, E>
|
||||
impl<A, E, C> NewService<C> for FromErrNewService<A, E, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
type Request = A::Request;
|
||||
@@ -120,28 +120,28 @@ where
|
||||
type Service = FromErr<A::Service, E>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = FromErrNewServiceFuture<A, E>;
|
||||
type Future = FromErrNewServiceFuture<A, E, C>;
|
||||
|
||||
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>
|
||||
pub struct FromErrNewServiceFuture<A, E, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
fut: A::Future,
|
||||
e: PhantomData<E>,
|
||||
}
|
||||
|
||||
impl<A, E> Future for FromErrNewServiceFuture<A, E>
|
||||
impl<A, E, C> Future for FromErrNewServiceFuture<A, E, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
E: From<A::Error>,
|
||||
{
|
||||
type Item = FromErr<A::Service, E>;
|
||||
@@ -208,7 +208,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,25 +1,40 @@
|
||||
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_err;
|
||||
mod transform_map_init_err;
|
||||
|
||||
pub use self::and_then::{AndThen, AndThenNewService};
|
||||
pub use self::and_then_apply::{AndThenApply, AndThenApplyNewService};
|
||||
use self::and_then_apply::{AndThenTransform, AndThenTransformNewService};
|
||||
use self::and_then_apply_fn::{AndThenApply, AndThenApplyNewService};
|
||||
pub use self::apply::{Apply, ApplyNewService};
|
||||
pub use self::fn_service::{FnNewService, FnService};
|
||||
pub use self::fn_service::{fn_cfg_factory, fn_factory, fn_service, FnService};
|
||||
pub use self::fn_transform::{FnNewTransform, 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::{IntoNewTransform, IntoTransform, NewTransform, Transform};
|
||||
|
||||
/// An asynchronous function from `Request` to a `Response`.
|
||||
pub trait Service {
|
||||
@@ -61,16 +76,30 @@ pub trait Service {
|
||||
/// An extension trait for `Service`s that provides a variety of convenient
|
||||
/// adapters
|
||||
pub trait ServiceExt: Service {
|
||||
/// Apply function to specified service and use it as a next service in
|
||||
/// Apply tranformation to specified service and use it as a next service in
|
||||
/// chain.
|
||||
fn apply<B, I, F, Out, Req>(self, service: I, f: F) -> AndThenApply<Self, B, F, Out>
|
||||
fn apply<T, T1, B, B1>(self, transform: T1, service: B1) -> AndThenTransform<T, Self, B>
|
||||
where
|
||||
Self: Sized,
|
||||
T: Transform<B, Request = Self::Response>,
|
||||
T::Error: From<Self::Error>,
|
||||
T1: IntoTransform<T, B>,
|
||||
B: Service<Error = Self::Error>,
|
||||
B1: IntoService<B>,
|
||||
{
|
||||
AndThenTransform::new(transform.into_transform(), self, service.into_service())
|
||||
}
|
||||
|
||||
/// Apply function to specified service and use it as a next service in
|
||||
/// chain.
|
||||
fn apply_fn<F, B, B1, Out>(self, service: B1, f: F) -> AndThenApply<Self, B, F, Out>
|
||||
where
|
||||
Self: Sized,
|
||||
B: Service<Request = Req, Error = Self::Error>,
|
||||
I: IntoService<B>,
|
||||
F: FnMut(Self::Response, &mut B) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<Self::Error>,
|
||||
B: Service<Error = Self::Error>,
|
||||
B1: IntoService<B>,
|
||||
{
|
||||
AndThenApply::new(self, service, f)
|
||||
}
|
||||
@@ -162,7 +191,9 @@ impl<T: ?Sized> ServiceExt for T where T: Service {}
|
||||
/// accepts new TCP streams, obtains a new `Service` value using the
|
||||
/// `NewService` trait, and uses that new `Service` value to process inbound
|
||||
/// requests on that new TCP stream.
|
||||
pub trait NewService {
|
||||
///
|
||||
/// `Config` is a service factory configuration type.
|
||||
pub trait NewService<Config = ()> {
|
||||
/// Requests handled by the service.
|
||||
type Request;
|
||||
|
||||
@@ -186,19 +217,41 @@ pub trait NewService {
|
||||
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<B, I, F, Out, Req>(
|
||||
fn apply<T, T1, B, B1>(
|
||||
self,
|
||||
transform: T1,
|
||||
service: B1,
|
||||
) -> AndThenTransformNewService<T, Self, B, Config>
|
||||
where
|
||||
Self: Sized,
|
||||
T: NewTransform<B::Service, Request = Self::Response, InitError = Self::InitError>,
|
||||
T::Error: From<Self::Error>,
|
||||
T1: IntoNewTransform<T, B::Service>,
|
||||
B: NewService<Config, Error = Self::Error, InitError = Self::InitError>,
|
||||
B1: IntoNewService<B, Config>,
|
||||
{
|
||||
AndThenTransformNewService::new(
|
||||
transform.into_new_transform(),
|
||||
self,
|
||||
service.into_new_service(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Apply function to specified service and use it as a next service in
|
||||
/// chain.
|
||||
fn apply_fn<B, I, F, Out>(
|
||||
self,
|
||||
service: I,
|
||||
f: F,
|
||||
) -> AndThenApplyNewService<Self, B, F, Out>
|
||||
) -> AndThenApplyNewService<Self, B, F, Out, Config>
|
||||
where
|
||||
Self: Sized,
|
||||
B: NewService<Request = Req, Error = Self::Error, InitError = Self::InitError>,
|
||||
I: IntoNewService<B>,
|
||||
B: NewService<Config, Error = Self::Error, InitError = Self::InitError>,
|
||||
I: IntoNewService<B, Config>,
|
||||
F: FnMut(Self::Response, &mut B::Service) -> Out,
|
||||
Out: IntoFuture,
|
||||
Out::Error: Into<Self::Error>,
|
||||
@@ -207,11 +260,12 @@ pub trait NewService {
|
||||
}
|
||||
|
||||
/// Call another service after call to this one has resolved successfully.
|
||||
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B>
|
||||
fn and_then<F, B>(self, new_service: F) -> AndThenNewService<Self, B, Config>
|
||||
where
|
||||
Self: Sized,
|
||||
F: IntoNewService<B>,
|
||||
F: IntoNewService<B, Config>,
|
||||
B: NewService<
|
||||
Config,
|
||||
Request = Self::Response,
|
||||
Error = Self::Error,
|
||||
InitError = Self::InitError,
|
||||
@@ -226,7 +280,7 @@ pub trait NewService {
|
||||
///
|
||||
/// 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>,
|
||||
@@ -240,11 +294,12 @@ pub trait NewService {
|
||||
///
|
||||
/// 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>,
|
||||
F: IntoNewService<B, Config>,
|
||||
B: NewService<
|
||||
Config,
|
||||
Request = Result<Self::Response, Self::Error>,
|
||||
Error = Self::Error,
|
||||
InitError = Self::InitError,
|
||||
@@ -255,7 +310,7 @@ pub trait NewService {
|
||||
|
||||
/// 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: FnMut(Self::Response) -> R,
|
||||
@@ -264,7 +319,7 @@ pub trait NewService {
|
||||
}
|
||||
|
||||
/// 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,
|
||||
@@ -273,7 +328,7 @@ pub trait NewService {
|
||||
}
|
||||
|
||||
/// 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,
|
||||
@@ -318,21 +373,35 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, R, E, S> NewService for F
|
||||
impl<S, C> NewService<C> for Rc<S>
|
||||
where
|
||||
F: Fn() -> R,
|
||||
R: IntoFuture<Item = S, Error = E>,
|
||||
S: Service,
|
||||
S: NewService<C>,
|
||||
{
|
||||
type Request = S::Request;
|
||||
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, C> NewService<C> for Arc<S>
|
||||
where
|
||||
S: NewService<C>,
|
||||
{
|
||||
type Request = S::Request;
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,10 +414,10 @@ where
|
||||
fn into_service(self) -> T;
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a Service
|
||||
pub trait IntoNewService<T>
|
||||
/// Trait for types that can be converted to a `NewService`
|
||||
pub trait IntoNewService<T, C = ()>
|
||||
where
|
||||
T: NewService,
|
||||
T: NewService<C>,
|
||||
{
|
||||
/// Convert to an `NewService`
|
||||
fn into_new_service(self) -> T;
|
||||
@@ -363,9 +432,27 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IntoNewService<T> for T
|
||||
impl<T, C> IntoNewService<T, C> for T
|
||||
where
|
||||
T: NewService,
|
||||
T: NewService<C>,
|
||||
{
|
||||
fn into_new_service(self) -> T {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a configurable `NewService`
|
||||
pub trait IntoConfigurableNewService<T, C>
|
||||
where
|
||||
T: NewService<C>,
|
||||
{
|
||||
/// Convert to an `NewService`
|
||||
fn into_new_service(self) -> T;
|
||||
}
|
||||
|
||||
impl<T, C> IntoConfigurableNewService<T, C> for T
|
||||
where
|
||||
T: NewService<C>,
|
||||
{
|
||||
fn into_new_service(self) -> T {
|
||||
self
|
||||
|
@@ -97,18 +97,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(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Response,
|
||||
A: NewService<Cfg>,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
Self {
|
||||
a,
|
||||
@@ -118,7 +118,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,
|
||||
@@ -132,49 +132,49 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Response> NewService for MapNewService<A, F, Response>
|
||||
impl<A, F, Res, Cfg> NewService<Cfg> for MapNewService<A, F, Res, Cfg>
|
||||
where
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Response + Clone,
|
||||
A: NewService<Cfg>,
|
||||
F: FnMut(A::Response) -> Res + Clone,
|
||||
{
|
||||
type Request = A::Request;
|
||||
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, Response>;
|
||||
type Future = MapNewServiceFuture<A, F, 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, Response>
|
||||
pub struct MapNewServiceFuture<A, F, Res, Cfg>
|
||||
where
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Response,
|
||||
A: NewService<Cfg>,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
fut: A::Future,
|
||||
f: Option<F>,
|
||||
}
|
||||
|
||||
impl<A, F, Response> MapNewServiceFuture<A, F, Response>
|
||||
impl<A, F, Res, Cfg> MapNewServiceFuture<A, F, Res, Cfg>
|
||||
where
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Response,
|
||||
A: NewService<Cfg>,
|
||||
F: FnMut(A::Response) -> Res,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
MapNewServiceFuture { f: Some(f), fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, Response> Future for MapNewServiceFuture<A, F, Response>
|
||||
impl<A, F, Res, Cfg> Future for MapNewServiceFuture<A, F, Res, Cfg>
|
||||
where
|
||||
A: NewService,
|
||||
F: FnMut(A::Response) -> Response,
|
||||
A: NewService<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> {
|
||||
@@ -229,7 +229,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"));
|
||||
|
@@ -98,17 +98,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(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
Self {
|
||||
@@ -119,7 +119,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,
|
||||
@@ -133,9 +133,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E> NewService for MapErrNewService<A, F, E>
|
||||
impl<A, F, E, C> NewService<C> for MapErrNewService<A, F, E, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
type Request = A::Request;
|
||||
@@ -144,25 +144,25 @@ where
|
||||
type Service = MapErr<A::Service, F, E>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = MapErrNewServiceFuture<A, F, E>;
|
||||
type Future = MapErrNewServiceFuture<A, F, E, 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>
|
||||
pub struct MapErrNewServiceFuture<A, F, E, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
fut: A::Future,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<A, F, E> MapErrNewServiceFuture<A, F, E>
|
||||
impl<A, F, E, C> MapErrNewServiceFuture<A, F, E, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
F: Fn(A::Error) -> E,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
@@ -170,9 +170,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E> Future for MapErrNewServiceFuture<A, F, E>
|
||||
impl<A, F, E, C> Future for MapErrNewServiceFuture<A, F, E, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
F: Fn(A::Error) -> E + Clone,
|
||||
{
|
||||
type Item = MapErr<A::Service, F, E>;
|
||||
@@ -231,7 +231,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(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<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> NewService for MapInitErr<A, F, E>
|
||||
impl<A, F, E, C> NewService<C> for MapInitErr<A, F, E, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
F: Fn(A::InitError) -> E + Clone,
|
||||
{
|
||||
type Request = A::Request;
|
||||
@@ -51,25 +51,25 @@ where
|
||||
type Service = A::Service;
|
||||
|
||||
type InitError = E;
|
||||
type Future = MapInitErrFuture<A, F, E>;
|
||||
type Future = MapInitErrFuture<A, F, E, 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::new(self.a.new_service(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MapInitErrFuture<A, F, E>
|
||||
pub struct MapInitErrFuture<A, F, E, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
f: F,
|
||||
fut: A::Future,
|
||||
}
|
||||
|
||||
impl<A, F, E> MapInitErrFuture<A, F, E>
|
||||
impl<A, F, E, C> MapInitErrFuture<A, F, E, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
fn new(fut: A::Future, f: F) -> Self {
|
||||
@@ -77,9 +77,9 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, F, E> Future for MapInitErrFuture<A, F, E>
|
||||
impl<A, F, E, C> Future for MapInitErrFuture<A, F, E, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
F: Fn(A::InitError) -> E,
|
||||
{
|
||||
type Item = A::Service;
|
||||
|
@@ -1,3 +1,5 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{try_ready, Async, Future, Poll};
|
||||
|
||||
use super::{IntoNewService, NewService, Service};
|
||||
@@ -109,34 +111,38 @@ 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>(a: A, f: F) -> Self
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
>,
|
||||
F: IntoNewService<B>,
|
||||
F: IntoNewService<B, C>,
|
||||
{
|
||||
Self {
|
||||
a,
|
||||
b: f.into_new_service(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> NewService for ThenNewService<A, B>
|
||||
impl<A, B, C> NewService<C> for ThenNewService<A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
@@ -148,14 +154,14 @@ where
|
||||
type Service = Then<A::Service, B::Service>;
|
||||
|
||||
type InitError = A::InitError;
|
||||
type Future = ThenNewServiceFuture<A, B>;
|
||||
type Future = ThenNewServiceFuture<A, B, 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,
|
||||
@@ -164,14 +170,16 @@ where
|
||||
Self {
|
||||
a: self.a.clone(),
|
||||
b: self.b.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ThenNewServiceFuture<A, B>
|
||||
pub struct ThenNewServiceFuture<A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
@@ -183,10 +191,11 @@ where
|
||||
b: Option<B::Service>,
|
||||
}
|
||||
|
||||
impl<A, B> ThenNewServiceFuture<A, B>
|
||||
impl<A, B, C> ThenNewServiceFuture<A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
@@ -202,10 +211,11 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> Future for ThenNewServiceFuture<A, B>
|
||||
impl<A, B, C> Future for ThenNewServiceFuture<A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = Result<A::Response, A::Error>,
|
||||
Error = A::Error,
|
||||
InitError = A::InitError,
|
||||
@@ -319,7 +329,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")));
|
||||
|
205
actix-service/src/transform.rs
Normal file
205
actix-service/src/transform.rs
Normal file
@@ -0,0 +1,205 @@
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use futures::{Future, Poll};
|
||||
|
||||
use crate::transform_map_err::{TransformMapErr, TransformMapErrNewTransform};
|
||||
use crate::transform_map_init_err::TransformMapInitErr;
|
||||
use crate::Service;
|
||||
|
||||
/// An asynchronous function for transforming service call result.
|
||||
pub trait Transform<Service> {
|
||||
/// Requests handled by the service.
|
||||
type Request;
|
||||
|
||||
/// Responses given by the service.
|
||||
type Response;
|
||||
|
||||
/// Errors produced by the service.
|
||||
type Error;
|
||||
|
||||
/// The future response value.
|
||||
type Future: Future<Item = Self::Response, Error = Self::Error>;
|
||||
|
||||
/// Returns `Ready` when the service is able to process requests.
|
||||
///
|
||||
/// This method is similar to `Service::poll_ready` method.
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error>;
|
||||
|
||||
/// Process the request and apply it to provided service,
|
||||
/// return the response asynchronously.
|
||||
fn call(&mut self, request: Self::Request, service: &mut Service) -> Self::Future;
|
||||
|
||||
/// Map this transform's error to a different error, returning a new transform.
|
||||
///
|
||||
/// This function is similar to the `Result::map_err` where it will change
|
||||
/// the error type of the underlying transform. This is useful for example to
|
||||
/// ensure that services and transforms have the same error type.
|
||||
///
|
||||
/// Note that this function consumes the receiving transform and returns a
|
||||
/// wrapped version of it.
|
||||
fn map_err<F, E>(self, f: F) -> TransformMapErr<Self, Service, F, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::Error) -> E,
|
||||
{
|
||||
TransformMapErr::new(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
/// `Transform` service factory
|
||||
///
|
||||
/// `Config` is a service factory configuration type.
|
||||
pub trait NewTransform<Service, Config = ()> {
|
||||
/// Requests handled by the service.
|
||||
type Request;
|
||||
|
||||
/// Responses given by the service.
|
||||
type Response;
|
||||
|
||||
/// Errors produced by the service.
|
||||
type Error;
|
||||
|
||||
/// The `TransformService` value created by this factory
|
||||
type Transform: Transform<
|
||||
Service,
|
||||
Request = Self::Request,
|
||||
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, cfg: &Config) -> Self::Future;
|
||||
|
||||
/// Map this transforms's output to a different type, returning a new transform
|
||||
/// of the resulting type.
|
||||
fn map_err<F, E>(self, f: F) -> TransformMapErrNewTransform<Self, Service, Config, F, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::Error) -> E,
|
||||
{
|
||||
TransformMapErrNewTransform::new(self, f)
|
||||
}
|
||||
|
||||
/// Map this service's factory init error to a different error,
|
||||
/// returning a new transform service factory.
|
||||
fn map_init_err<F, E>(self, f: F) -> TransformMapInitErr<Self, Service, Config, F, E>
|
||||
where
|
||||
Self: Sized,
|
||||
F: Fn(Self::InitError) -> E,
|
||||
{
|
||||
TransformMapInitErr::new(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T, S> Transform<S> for &'a mut T
|
||||
where
|
||||
T: Transform<S> + 'a,
|
||||
S: Service<Error = T::Error>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = T::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), T::Error> {
|
||||
(**self).poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Self::Request, service: &mut S) -> T::Future {
|
||||
(**self).call(request, service)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S> Transform<S> for Box<T>
|
||||
where
|
||||
T: Transform<S> + ?Sized,
|
||||
S: Service<Error = T::Error>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Future = T::Future;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), S::Error> {
|
||||
(**self).poll_ready()
|
||||
}
|
||||
|
||||
fn call(&mut self, request: Self::Request, service: &mut S) -> T::Future {
|
||||
(**self).call(request, service)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, C, T> NewTransform<S, C> for Rc<T>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Transform = T::Transform;
|
||||
type InitError = T::InitError;
|
||||
type Future = T::Future;
|
||||
|
||||
fn new_transform(&self, cfg: &C) -> T::Future {
|
||||
self.as_ref().new_transform(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, C, T> NewTransform<S, C> for Arc<T>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Transform = T::Transform;
|
||||
type InitError = T::InitError;
|
||||
type Future = T::Future;
|
||||
|
||||
fn new_transform(&self, cfg: &C) -> T::Future {
|
||||
self.as_ref().new_transform(cfg)
|
||||
}
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a `TransformService`
|
||||
pub trait IntoTransform<T, S>
|
||||
where
|
||||
T: Transform<S>,
|
||||
{
|
||||
/// Convert to a `TransformService`
|
||||
fn into_transform(self) -> T;
|
||||
}
|
||||
|
||||
/// Trait for types that can be converted to a TransfromNewService
|
||||
pub trait IntoNewTransform<T, S, C = ()>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
{
|
||||
/// Convert to an `TranformNewService`
|
||||
fn into_new_transform(self) -> T;
|
||||
}
|
||||
|
||||
impl<T, S> IntoTransform<T, S> for T
|
||||
where
|
||||
T: Transform<S>,
|
||||
{
|
||||
fn into_transform(self) -> T {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C> IntoNewTransform<T, S, C> for T
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
{
|
||||
fn into_new_transform(self) -> T {
|
||||
self
|
||||
}
|
||||
}
|
188
actix-service/src/transform_map_err.rs
Normal file
188
actix-service/src/transform_map_err.rs
Normal file
@@ -0,0 +1,188 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::{NewTransform, Transform};
|
||||
|
||||
/// Service for the `map_err` combinator, changing the type of a transform's
|
||||
/// error.
|
||||
///
|
||||
/// This is created by the `Transform::map_err` method.
|
||||
pub struct TransformMapErr<T, S, F, E> {
|
||||
transform: T,
|
||||
f: F,
|
||||
_t: PhantomData<(S, E)>,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErr<T, S, F, E> {
|
||||
/// Create new `MapErr` combinator
|
||||
pub fn new(transform: T, f: F) -> Self
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
Self {
|
||||
transform,
|
||||
f,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Clone for TransformMapErr<T, S, F, E>
|
||||
where
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
TransformMapErr {
|
||||
transform: self.transform.clone(),
|
||||
f: self.f.clone(),
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Transform<S> for TransformMapErr<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = E;
|
||||
type Future = TransformMapErrFuture<T, S, F, E>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.transform.poll_ready().map_err(&self.f)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T::Request, service: &mut S) -> Self::Future {
|
||||
TransformMapErrFuture::new(self.transform.call(req, service), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
f: F,
|
||||
fut: T::Future,
|
||||
}
|
||||
|
||||
impl<T, S, F, E> TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
TransformMapErrFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, F, E> Future for TransformMapErrFuture<T, S, F, E>
|
||||
where
|
||||
T: Transform<S>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
type Item = T::Response;
|
||||
type Error = E;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
self.fut.poll().map_err(&self.f)
|
||||
}
|
||||
}
|
||||
|
||||
/// NewTransform for the `map_err` combinator, changing the type of a new
|
||||
/// transform's error.
|
||||
///
|
||||
/// This is created by the `NewTransform::map_err` method.
|
||||
pub struct TransformMapErrNewTransform<T, S, C, F, E> {
|
||||
t: T,
|
||||
f: F,
|
||||
e: PhantomData<(S, C, E)>,
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> TransformMapErrNewTransform<T, S, C, F, E> {
|
||||
/// Create new `MapErr` new service instance
|
||||
pub fn new(t: T, f: F) -> Self
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
Self {
|
||||
t,
|
||||
f,
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> Clone for TransformMapErrNewTransform<T, S, C, F, E>
|
||||
where
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
t: self.t.clone(),
|
||||
f: self.f.clone(),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> NewTransform<S, C> for TransformMapErrNewTransform<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = E;
|
||||
type Transform = TransformMapErr<T::Transform, S, F, E>;
|
||||
|
||||
type InitError = T::InitError;
|
||||
type Future = TransformMapErrNewTransformFuture<T, S, C, F, E>;
|
||||
|
||||
fn new_transform(&self, cfg: &C) -> Self::Future {
|
||||
TransformMapErrNewTransformFuture::new(self.t.new_transform(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformMapErrNewTransformFuture<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fut: T::Future,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> TransformMapErrNewTransformFuture<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::Error) -> E,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
TransformMapErrNewTransformFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> Future for TransformMapErrNewTransformFuture<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::Error) -> E + Clone,
|
||||
{
|
||||
type Item = TransformMapErr<T::Transform, S, F, E>;
|
||||
type Error = T::InitError;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
if let Async::Ready(tr) = self.fut.poll()? {
|
||||
Ok(Async::Ready(TransformMapErr::new(tr, self.f.clone())))
|
||||
} else {
|
||||
Ok(Async::NotReady)
|
||||
}
|
||||
}
|
||||
}
|
94
actix-service/src/transform_map_init_err.rs
Normal file
94
actix-service/src/transform_map_init_err.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use futures::{Future, Poll};
|
||||
|
||||
use super::NewTransform;
|
||||
|
||||
/// 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, C, F, E> {
|
||||
t: T,
|
||||
f: F,
|
||||
e: PhantomData<(S, C, E)>,
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> TransformMapInitErr<T, S, C, F, E> {
|
||||
/// Create new `MapInitErr` new transform instance
|
||||
pub fn new(t: T, f: F) -> Self
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::InitError) -> E,
|
||||
{
|
||||
Self {
|
||||
t,
|
||||
f,
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> Clone for TransformMapInitErr<T, S, C, F, E>
|
||||
where
|
||||
T: Clone,
|
||||
F: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
t: self.t.clone(),
|
||||
f: self.f.clone(),
|
||||
e: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> NewTransform<S, C> for TransformMapInitErr<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::InitError) -> E + Clone,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type Transform = T::Transform;
|
||||
|
||||
type InitError = E;
|
||||
type Future = TransformMapInitErrFuture<T, S, C, F, E>;
|
||||
|
||||
fn new_transform(&self, cfg: &C) -> Self::Future {
|
||||
TransformMapInitErrFuture::new(self.t.new_transform(cfg), self.f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TransformMapInitErrFuture<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::InitError) -> E,
|
||||
{
|
||||
fut: T::Future,
|
||||
f: F,
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> TransformMapInitErrFuture<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
F: Fn(T::InitError) -> E,
|
||||
{
|
||||
fn new(fut: T::Future, f: F) -> Self {
|
||||
TransformMapInitErrFuture { f, fut }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, C, F, E> Future for TransformMapInitErrFuture<T, S, C, F, E>
|
||||
where
|
||||
T: NewTransform<S, C>,
|
||||
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(|e| (self.f)(e))
|
||||
}
|
||||
}
|
@@ -34,7 +34,7 @@ rust-tls = ["rustls", "tokio-rustls", "webpki", "webpki-roots"]
|
||||
|
||||
[dependencies]
|
||||
actix-rt = "0.1.0"
|
||||
#actix-server = "0.1.0"
|
||||
#actix-server = "0.2.0"
|
||||
actix-server = { path="../actix-server" }
|
||||
|
||||
log = "0.4"
|
||||
|
@@ -1,5 +1,49 @@
|
||||
# Changes
|
||||
|
||||
## [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
|
||||
|
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-utils"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix utils - various actix net related services"
|
||||
keywords = ["network", "framework", "async", "futures"]
|
||||
@@ -11,20 +11,20 @@ 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.2.0"
|
||||
actix-service = "0.3.0"
|
||||
actix-codec = "0.1.0"
|
||||
bytes = "0.4"
|
||||
futures = "0.1"
|
||||
futures = "0.1.24"
|
||||
tokio-timer = "0.2.8"
|
||||
tokio-current-thread = "0.1"
|
||||
tokio-current-thread = "0.1.4"
|
||||
log = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
actix-rt = "0.1"
|
||||
actix-rt = "0.1"
|
||||
|
@@ -53,10 +53,11 @@ pub enum Either<A, B> {
|
||||
}
|
||||
|
||||
impl<A, B> Either<A, B> {
|
||||
pub fn new_a(srv: A) -> Self
|
||||
pub fn new_a<C>(srv: A) -> Self
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = A::Request,
|
||||
Response = A::Response,
|
||||
Error = A::Error,
|
||||
@@ -66,10 +67,11 @@ impl<A, B> Either<A, B> {
|
||||
Either::A(srv)
|
||||
}
|
||||
|
||||
pub fn new_b(srv: B) -> Self
|
||||
pub fn new_b<C>(srv: B) -> Self
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = A::Request,
|
||||
Response = A::Response,
|
||||
Error = A::Error,
|
||||
@@ -80,10 +82,11 @@ impl<A, B> Either<A, B> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<A, B> NewService for Either<A, B>
|
||||
impl<A, B, C> NewService<C> for Either<A, B>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = A::Request,
|
||||
Response = A::Response,
|
||||
Error = A::Error,
|
||||
@@ -95,12 +98,12 @@ where
|
||||
type Error = A::Error;
|
||||
type InitError = A::InitError;
|
||||
type Service = EitherService<A::Service, B::Service>;
|
||||
type Future = EitherNewService<A, B>;
|
||||
type Future = EitherNewService<A, B, 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)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,15 +118,16 @@ impl<A: Clone, B: Clone> Clone for Either<A, B> {
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub enum EitherNewService<A: NewService, B: NewService> {
|
||||
pub enum EitherNewService<A: NewService<C>, B: NewService<C>, C> {
|
||||
A(A::Future),
|
||||
B(B::Future),
|
||||
}
|
||||
|
||||
impl<A, B> Future for EitherNewService<A, B>
|
||||
impl<A, B, C> Future for EitherNewService<A, B, C>
|
||||
where
|
||||
A: NewService,
|
||||
A: NewService<C>,
|
||||
B: NewService<
|
||||
C,
|
||||
Request = A::Request,
|
||||
Response = A::Response,
|
||||
Error = A::Error,
|
||||
|
@@ -15,14 +15,15 @@ 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
|
||||
S: NewService<Request = Request<U>, Response = Response<U>>,
|
||||
C: Clone,
|
||||
S: NewService<C, Request = Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
@@ -30,7 +31,7 @@ where
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
{
|
||||
pub fn new<F1: IntoNewService<S>>(factory: F1) -> Self {
|
||||
pub fn new<F1: IntoNewService<S, C>>(factory: F1) -> Self {
|
||||
Self {
|
||||
factory: factory.into_new_service(),
|
||||
_t: PhantomData,
|
||||
@@ -38,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,
|
||||
{
|
||||
@@ -50,9 +51,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, U> NewService for FramedNewService<S, T, U>
|
||||
impl<S, T, U, C> NewService<C> for FramedNewService<S, T, U, C>
|
||||
where
|
||||
S: NewService<Request = Request<U>, Response = Response<U>> + Clone,
|
||||
C: Clone,
|
||||
S: NewService<C, Request = Request<U>, Response = Response<U>> + Clone,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
@@ -64,48 +66,53 @@ where
|
||||
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 for FramedService<S, T, U>
|
||||
impl<S, T, U, C> Service for FramedService<S, T, U, C>
|
||||
where
|
||||
S: NewService<Request = Request<U>, Response = Response<U>>,
|
||||
S: NewService<C, Request = Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
U: Decoder + Encoder,
|
||||
<U as Encoder>::Item: 'static,
|
||||
<U as Encoder>::Error: std::fmt::Debug,
|
||||
C: Clone,
|
||||
{
|
||||
type Request = Framed<T, U>;
|
||||
type Response = FramedTransport<S::Service, T, U>;
|
||||
type Error = S::InitError;
|
||||
type Future = FramedServiceResponseFuture<S, T, U>;
|
||||
type Future = FramedServiceResponseFuture<S, T, U, C>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
Ok(Async::Ready(()))
|
||||
@@ -113,17 +120,16 @@ 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 = Request<U>, Response = Response<U>>,
|
||||
S: NewService<C, Request = Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
@@ -135,9 +141,9 @@ where
|
||||
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 = Request<U>, Response = Response<U>>,
|
||||
S: NewService<C, Request = Request<U>, Response = Response<U>>,
|
||||
S::Error: 'static,
|
||||
<S::Service as Service>::Future: 'static,
|
||||
T: AsyncRead + AsyncWrite,
|
||||
@@ -402,7 +408,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U, F> NewService for IntoFramed<T, U, F>
|
||||
impl<T, U, F> NewService<()> for IntoFramed<T, U, F>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite,
|
||||
F: Fn() -> U + Send + Clone + 'static,
|
||||
@@ -415,7 +421,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::{NewTransform, Service, Transform, Void};
|
||||
use futures::future::{ok, FutureResult};
|
||||
use futures::{Async, Future, Poll};
|
||||
|
||||
use super::counter::{Counter, CounterGuard};
|
||||
|
||||
@@ -7,98 +8,48 @@ 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>(factory: F) -> Self
|
||||
where
|
||||
T: NewService,
|
||||
F: IntoNewService<T>,
|
||||
{
|
||||
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> NewService for InFlight<T>
|
||||
where
|
||||
T: NewService,
|
||||
{
|
||||
impl Default for InFlight {
|
||||
fn default() -> Self {
|
||||
Self::new(15)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Service, C> NewTransform<T, C> for InFlight {
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = T::Error;
|
||||
type InitError = T::InitError;
|
||||
type Service = InFlightService<T::Service>;
|
||||
type Future = InFlightResponseFuture<T>;
|
||||
type InitError = Void;
|
||||
type Transform = InFlightService;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
InFlightResponseFuture {
|
||||
fut: self.factory.new_service(),
|
||||
max_inflight: self.max_inflight,
|
||||
}
|
||||
fn new_transform(&self, _: &C) -> Self::Future {
|
||||
ok(InFlightService::new(self.max_inflight))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InFlightResponseFuture<T: NewService> {
|
||||
fut: T::Future,
|
||||
max_inflight: usize,
|
||||
}
|
||||
|
||||
impl<T: NewService> Future for InFlightResponseFuture<T> {
|
||||
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()),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InFlightService<T> {
|
||||
service: T,
|
||||
pub struct InFlightService {
|
||||
count: Counter,
|
||||
}
|
||||
|
||||
impl<T> InFlightService<T> {
|
||||
pub fn new<F>(service: F) -> Self
|
||||
where
|
||||
T: Service,
|
||||
F: IntoService<T>,
|
||||
{
|
||||
impl InFlightService {
|
||||
pub fn new(max: usize) -> Self {
|
||||
Self {
|
||||
service: service.into_service(),
|
||||
count: Counter::new(15),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_max_inflight<F>(max: usize, service: F) -> Self
|
||||
where
|
||||
T: Service,
|
||||
F: IntoService<T>,
|
||||
{
|
||||
Self {
|
||||
service: service.into_service(),
|
||||
count: Counter::new(max),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service for InFlightService<T>
|
||||
impl<T> Transform<T> for InFlightService
|
||||
where
|
||||
T: Service,
|
||||
{
|
||||
@@ -108,17 +59,17 @@ where
|
||||
type Future = InFlightServiceResponse<T>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
let res = self.service.poll_ready()?;
|
||||
if res.is_ready() && !self.count.available() {
|
||||
if !self.count.available() {
|
||||
log::trace!("InFlight limit exceeded");
|
||||
return Ok(Async::NotReady);
|
||||
Ok(Async::NotReady)
|
||||
} else {
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn call(&mut self, req: T::Request) -> Self::Future {
|
||||
fn call(&mut self, req: T::Request, service: &mut T) -> Self::Future {
|
||||
InFlightServiceResponse {
|
||||
fut: self.service.call(req),
|
||||
fut: service.call(req),
|
||||
_guard: self.count.get(),
|
||||
}
|
||||
}
|
||||
@@ -138,3 +89,74 @@ impl<T: Service> Future for InFlightServiceResponse<T> {
|
||||
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 Request = ();
|
||||
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().apply(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,18 +43,18 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<R, E, F> NewService for KeepAlive<R, E, F>
|
||||
impl<R, E, F> NewService<()> for KeepAlive<R, E, F>
|
||||
where
|
||||
F: Fn() -> E + Clone,
|
||||
{
|
||||
type Request = R;
|
||||
type Response = R;
|
||||
type Error = E;
|
||||
type InitError = 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(),
|
||||
@@ -112,7 +111,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 {}
|
||||
|
284
actix-utils/src/order.rs
Normal file
284
actix-utils/src/order.rs
Normal file
@@ -0,0 +1,284 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
use std::rc::Rc;
|
||||
|
||||
use actix_service::{NewTransform, 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>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self { _t: PhantomData }
|
||||
}
|
||||
|
||||
pub fn service() -> impl Transform<
|
||||
S,
|
||||
Request = S::Request,
|
||||
Response = S::Response,
|
||||
Error = InOrderError<S::Error>,
|
||||
> {
|
||||
InOrderService::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Default for InOrder<S>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, C> NewTransform<S, C> for InOrder<S>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = InOrderError<S::Error>;
|
||||
type InitError = Void;
|
||||
type Transform = InOrderService<S>;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn new_transform(&self, _: &C) -> Self::Future {
|
||||
ok(InOrderService::new())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InOrderService<S: Service> {
|
||||
task: Rc<AtomicTask>,
|
||||
acks: VecDeque<Record<S::Response, S::Error>>,
|
||||
}
|
||||
|
||||
impl<S> InOrderService<S>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
acks: VecDeque::new(),
|
||||
task: Rc::new(AtomicTask::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Default for InOrderService<S>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Transform<S> for InOrderService<S>
|
||||
where
|
||||
S: Service,
|
||||
S::Response: 'static,
|
||||
S::Future: 'static,
|
||||
S::Error: 'static,
|
||||
{
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = InOrderError<S::Error>;
|
||||
type Future = InOrderServiceResponse<S>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.task.register();
|
||||
|
||||
// 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: S::Request, service: &mut S) -> 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(service.call(request).then(move |res| {
|
||||
task.notify();
|
||||
let _ = tx1.send(res);
|
||||
Ok(())
|
||||
}));
|
||||
|
||||
InOrderServiceResponse { rx: rx2 }
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct InOrderServiceResponse<S: Service> {
|
||||
rx: oneshot::Receiver<Result<S::Response, S::Error>>,
|
||||
}
|
||||
|
||||
impl<S: Service> Future for InOrderServiceResponse<S> {
|
||||
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 for Srv {
|
||||
type Request = oneshot::Receiver<usize>;
|
||||
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> {
|
||||
s: S,
|
||||
}
|
||||
|
||||
impl<S: Service> 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().apply(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();
|
||||
}
|
||||
}
|
@@ -29,20 +29,21 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct StreamNewService<S, T, E> {
|
||||
pub struct StreamNewService<S, T, E, C> {
|
||||
factory: Rc<T>,
|
||||
_t: PhantomData<(S, E)>,
|
||||
_t: PhantomData<(S, E, C)>,
|
||||
}
|
||||
|
||||
impl<S, T, E> StreamNewService<S, T, E>
|
||||
impl<S, T, E, C> StreamNewService<S, T, E, C>
|
||||
where
|
||||
C: Clone,
|
||||
S: IntoStream,
|
||||
T: NewService<Request = Request<S>, Response = (), Error = E, InitError = E>,
|
||||
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
{
|
||||
pub fn new<F: IntoNewService<T>>(factory: F) -> Self {
|
||||
pub fn new<F: IntoNewService<T, C>>(factory: F) -> Self {
|
||||
Self {
|
||||
factory: Rc::new(factory.into_new_service()),
|
||||
_t: PhantomData,
|
||||
@@ -50,7 +51,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, E> Clone for StreamNewService<S, T, E> {
|
||||
impl<S, T, E, C> Clone for StreamNewService<S, T, E, C> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
factory: self.factory.clone(),
|
||||
@@ -59,10 +60,11 @@ impl<S, T, E> Clone for StreamNewService<S, T, E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, T, E> NewService for StreamNewService<S, T, E>
|
||||
impl<S, T, E, C> NewService<C> for StreamNewService<S, T, E, C>
|
||||
where
|
||||
C: Clone,
|
||||
S: IntoStream + 'static,
|
||||
T: NewService<Request = Request<S>, Response = (), Error = E, InitError = E>,
|
||||
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
@@ -71,29 +73,32 @@ where
|
||||
type Response = ();
|
||||
type Error = E;
|
||||
type InitError = E;
|
||||
type Service = StreamService<S, T, E>;
|
||||
type Service = StreamService<S, T, E, C>;
|
||||
type Future = FutureResult<Self::Service, E>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
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> {
|
||||
pub struct StreamService<S, T, E, C = ()> {
|
||||
factory: Rc<T>,
|
||||
config: C,
|
||||
_t: PhantomData<(S, E)>,
|
||||
}
|
||||
|
||||
impl<S, T, E> Service for StreamService<S, T, E>
|
||||
impl<S, T, E, C> Service for StreamService<S, T, E, C>
|
||||
where
|
||||
S: IntoStream + 'static,
|
||||
T: NewService<Request = Request<S>, Response = (), Error = E, InitError = E>,
|
||||
T: NewService<C, Request = Request<S>, Response = (), Error = E, InitError = E>,
|
||||
T::Future: 'static,
|
||||
T::Service: 'static,
|
||||
<T::Service as Service>::Future: 'static,
|
||||
C: Clone,
|
||||
{
|
||||
type Request = S;
|
||||
type Response = ();
|
||||
@@ -107,7 +112,7 @@ where
|
||||
fn call(&mut self, req: S) -> Self::Future {
|
||||
Box::new(
|
||||
self.factory
|
||||
.new_service()
|
||||
.new_service(&self.config)
|
||||
.and_then(move |srv| StreamDispatcher::new(req, srv)),
|
||||
)
|
||||
}
|
||||
@@ -227,7 +232,7 @@ impl<T> Clone for TakeItem<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Stream> NewService for TakeItem<T> {
|
||||
impl<T: Stream> NewService<()> for TakeItem<T> {
|
||||
type Request = T;
|
||||
type Response = (Option<T::Item>, T);
|
||||
type Error = T::Error;
|
||||
@@ -235,7 +240,7 @@ impl<T: Stream> NewService for TakeItem<T> {
|
||||
type Service = TakeItemService<T>;
|
||||
type Future = FutureResult<Self::Service, Self::InitError>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
fn new_service(&self, _: &()) -> Self::Future {
|
||||
ok(TakeItemService { _t: PhantomData })
|
||||
}
|
||||
}
|
||||
|
@@ -1,12 +1,11 @@
|
||||
use std::time::{self, 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::sleep;
|
||||
|
||||
use super::cell::Cell;
|
||||
use super::Never;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LowResTime(Cell<Inner>);
|
||||
@@ -42,15 +41,15 @@ impl Default for LowResTime {
|
||||
}
|
||||
}
|
||||
|
||||
impl NewService for LowResTime {
|
||||
impl NewService<()> for LowResTime {
|
||||
type Request = ();
|
||||
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())
|
||||
}
|
||||
}
|
||||
@@ -92,7 +91,7 @@ impl LowResTimeService {
|
||||
impl Service for LowResTimeService {
|
||||
type Request = ();
|
||||
type Response = Instant;
|
||||
type Error = Never;
|
||||
type Error = Void;
|
||||
type Future = FutureResult<Self::Response, Self::Error>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
@@ -133,7 +132,7 @@ impl SystemTimeService {
|
||||
/// 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.clone();
|
||||
let cur = self.0.get_ref().current;
|
||||
if let Some(cur) = cur {
|
||||
cur
|
||||
} else {
|
||||
|
@@ -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::{NewTransform, 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,107 +41,91 @@ impl<E: fmt::Debug> fmt::Debug for TimeoutError<E> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Timeout<T> {
|
||||
pub fn new(timeout: Duration, inner: T) -> Self
|
||||
where
|
||||
T: NewService + Clone,
|
||||
{
|
||||
Timeout { inner, 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"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Clone for Timeout<T>
|
||||
where
|
||||
T: Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
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<E> Timeout<E> {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
Timeout {
|
||||
inner: self.inner.clone(),
|
||||
timeout: self.timeout,
|
||||
timeout,
|
||||
_t: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> NewService for Timeout<T>
|
||||
where
|
||||
T: NewService + Clone,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = TimeoutError<T::Error>;
|
||||
type InitError = T::InitError;
|
||||
type Service = TimeoutService<T::Service>;
|
||||
type Future = TimeoutFut<T>;
|
||||
|
||||
fn new_service(&self) -> Self::Future {
|
||||
TimeoutFut {
|
||||
fut: self.inner.new_service(),
|
||||
timeout: self.timeout,
|
||||
}
|
||||
impl<E> Clone for Timeout<E> {
|
||||
fn clone(&self) -> Self {
|
||||
Timeout::new(self.timeout)
|
||||
}
|
||||
}
|
||||
|
||||
/// `Timeout` response future
|
||||
#[derive(Debug)]
|
||||
pub struct TimeoutFut<T: NewService> {
|
||||
fut: T::Future,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl<T> Future for TimeoutFut<T>
|
||||
impl<S, C, E> NewTransform<S, C> for Timeout<E>
|
||||
where
|
||||
T: NewService,
|
||||
S: Service,
|
||||
{
|
||||
type Item = TimeoutService<T::Service>;
|
||||
type Error = T::InitError;
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = TimeoutError<S::Error>;
|
||||
type InitError = E;
|
||||
type Transform = TimeoutService;
|
||||
type Future = FutureResult<Self::Transform, Self::InitError>;
|
||||
|
||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||
let service = try_ready!(self.fut.poll());
|
||||
Ok(Async::Ready(TimeoutService::new(self.timeout, service)))
|
||||
fn new_transform(&self, _: &C) -> Self::Future {
|
||||
ok(TimeoutService {
|
||||
timeout: self.timeout,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a timeout to requests.
|
||||
#[derive(Debug)]
|
||||
pub struct TimeoutService<T> {
|
||||
inner: T,
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TimeoutService {
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl<T> TimeoutService<T> {
|
||||
pub fn new(timeout: Duration, inner: T) -> Self
|
||||
where
|
||||
T: Service,
|
||||
{
|
||||
TimeoutService { inner, timeout }
|
||||
impl TimeoutService {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
TimeoutService { timeout }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> Clone for TimeoutService<T> {
|
||||
fn clone(&self) -> Self {
|
||||
TimeoutService {
|
||||
inner: self.inner.clone(),
|
||||
timeout: self.timeout,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Service for TimeoutService<T>
|
||||
impl<S> Transform<S> for TimeoutService
|
||||
where
|
||||
T: Service,
|
||||
S: Service,
|
||||
{
|
||||
type Request = T::Request;
|
||||
type Response = T::Response;
|
||||
type Error = TimeoutError<T::Error>;
|
||||
type Future = TimeoutServiceResponse<T>;
|
||||
type Request = S::Request;
|
||||
type Response = S::Response;
|
||||
type Error = TimeoutError<S::Error>;
|
||||
type Future = TimeoutServiceResponse<S>;
|
||||
|
||||
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
|
||||
self.inner.poll_ready().map_err(TimeoutError::Service)
|
||||
Ok(Async::Ready(()))
|
||||
}
|
||||
|
||||
fn call(&mut self, request: T::Request) -> Self::Future {
|
||||
fn call(&mut self, request: S::Request, service: &mut S) -> Self::Future {
|
||||
TimeoutServiceResponse {
|
||||
fut: self.inner.call(request),
|
||||
fut: service.call(request),
|
||||
sleep: Delay::new(clock::now() + self.timeout),
|
||||
}
|
||||
}
|
||||
@@ -170,3 +161,75 @@ 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 Request = ();
|
||||
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()
|
||||
.apply(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()
|
||||
.apply(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));
|
||||
}
|
||||
}
|
||||
|
@@ -2,7 +2,7 @@ use serde::de::{self, Deserializer, Error as DeError, Visitor};
|
||||
use serde::forward_to_deserialize_any;
|
||||
|
||||
use crate::path::{Path, PathIter};
|
||||
use crate::RequestPath;
|
||||
use crate::ResourcePath;
|
||||
|
||||
macro_rules! unsupported_type {
|
||||
($trait_fn:ident, $name:expr) => {
|
||||
@@ -33,17 +33,17 @@ macro_rules! parse_single_value {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PathDeserializer<'de, T: RequestPath + 'de> {
|
||||
pub struct PathDeserializer<'de, T: ResourcePath + 'de> {
|
||||
path: &'de Path<T>,
|
||||
}
|
||||
|
||||
impl<'de, T: RequestPath + 'de> PathDeserializer<'de, T> {
|
||||
impl<'de, T: ResourcePath + 'de> PathDeserializer<'de, T> {
|
||||
pub fn new(path: &'de Path<T>) -> Self {
|
||||
PathDeserializer { path }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de, T: RequestPath + 'de> Deserializer<'de> for PathDeserializer<'de, T> {
|
||||
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>
|
||||
@@ -206,12 +206,12 @@ impl<'de, T: RequestPath + 'de> Deserializer<'de> for PathDeserializer<'de, T> {
|
||||
parse_single_value!(deserialize_char, visit_char, "char");
|
||||
}
|
||||
|
||||
struct ParamsDeserializer<'de, T: RequestPath> {
|
||||
struct ParamsDeserializer<'de, T: ResourcePath> {
|
||||
params: PathIter<'de, T>,
|
||||
current: Option<(&'de str, &'de str)>,
|
||||
}
|
||||
|
||||
impl<'de, T: RequestPath> de::MapAccess<'de> for ParamsDeserializer<'de, T> {
|
||||
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>
|
||||
@@ -406,11 +406,11 @@ impl<'de> Deserializer<'de> for Value<'de> {
|
||||
unsupported_type!(deserialize_identifier, "identifier");
|
||||
}
|
||||
|
||||
struct ParamsSeq<'de, T: RequestPath> {
|
||||
struct ParamsSeq<'de, T: ResourcePath> {
|
||||
params: PathIter<'de, T>,
|
||||
}
|
||||
|
||||
impl<'de, T: RequestPath> de::SeqAccess<'de> for ParamsSeq<'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>
|
||||
|
@@ -1,31 +1,31 @@
|
||||
//! Resource path matching library.
|
||||
mod de;
|
||||
mod path;
|
||||
mod pattern;
|
||||
mod resource;
|
||||
mod router;
|
||||
|
||||
pub use self::de::PathDeserializer;
|
||||
pub use self::path::Path;
|
||||
pub use self::pattern::Pattern;
|
||||
pub use self::resource::ResourceDef;
|
||||
pub use self::router::{ResourceInfo, Router, RouterBuilder};
|
||||
|
||||
pub trait RequestPath {
|
||||
pub trait ResourcePath {
|
||||
fn path(&self) -> &str;
|
||||
}
|
||||
|
||||
impl RequestPath for String {
|
||||
impl ResourcePath for String {
|
||||
fn path(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> RequestPath for &'a str {
|
||||
impl<'a> ResourcePath for &'a str {
|
||||
fn path(&self) -> &str {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<[u8]>> RequestPath for string::String<T> {
|
||||
impl<T: AsRef<[u8]>> ResourcePath for string::String<T> {
|
||||
fn path(&self) -> &str {
|
||||
&*self
|
||||
}
|
||||
@@ -39,10 +39,10 @@ pub use self::url::Url;
|
||||
|
||||
#[cfg(feature = "http")]
|
||||
mod http_support {
|
||||
use super::RequestPath;
|
||||
use super::ResourcePath;
|
||||
use http::Uri;
|
||||
|
||||
impl RequestPath for Uri {
|
||||
impl ResourcePath for Uri {
|
||||
fn path(&self) -> &str {
|
||||
self.path()
|
||||
}
|
||||
|
@@ -4,7 +4,7 @@ use std::rc::Rc;
|
||||
use serde::de;
|
||||
|
||||
use crate::de::PathDeserializer;
|
||||
use crate::RequestPath;
|
||||
use crate::ResourcePath;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum PathItem {
|
||||
@@ -42,7 +42,7 @@ impl<T: Clone> Clone for Path<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RequestPath> Path<T> {
|
||||
impl<T: ResourcePath> Path<T> {
|
||||
pub fn new(path: T) -> Path<T> {
|
||||
Path {
|
||||
path,
|
||||
@@ -165,7 +165,7 @@ pub struct PathIter<'a, T> {
|
||||
params: &'a Path<T>,
|
||||
}
|
||||
|
||||
impl<'a, T: RequestPath> Iterator for PathIter<'a, T> {
|
||||
impl<'a, T: ResourcePath> Iterator for PathIter<'a, T> {
|
||||
type Item = (&'a str, &'a str);
|
||||
|
||||
#[inline]
|
||||
@@ -183,7 +183,7 @@ impl<'a, T: RequestPath> Iterator for PathIter<'a, T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: RequestPath> Index<&'a str> for Path<T> {
|
||||
impl<'a, T: ResourcePath> Index<&'a str> for Path<T> {
|
||||
type Output = str;
|
||||
|
||||
fn index(&self, name: &'a str) -> &str {
|
||||
@@ -192,7 +192,7 @@ impl<'a, T: RequestPath> Index<&'a str> for Path<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: RequestPath> Index<usize> for Path<T> {
|
||||
impl<T: ResourcePath> Index<usize> for Path<T> {
|
||||
type Output = str;
|
||||
|
||||
fn index(&self, idx: usize) -> &str {
|
||||
|
@@ -5,20 +5,35 @@ use std::rc::Rc;
|
||||
use regex::{escape, Regex};
|
||||
|
||||
use crate::path::{Path, PathItem};
|
||||
use crate::RequestPath;
|
||||
use crate::ResourcePath;
|
||||
|
||||
const MAX_DYNAMIC_SEGMENTS: usize = 16;
|
||||
|
||||
/// Resource type describes an entry in resources table
|
||||
/// ResourceDef describes an entry in resources table
|
||||
///
|
||||
/// Resource pattern can contain only 16 dynamic segments
|
||||
/// Resource definition can contain only 16 dynamic segments
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Pattern {
|
||||
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),
|
||||
@@ -32,12 +47,12 @@ enum PatternType {
|
||||
Dynamic(Regex, Vec<Rc<String>>, usize),
|
||||
}
|
||||
|
||||
impl Pattern {
|
||||
impl ResourceDef {
|
||||
/// Parse path pattern and create new `Pattern` instance.
|
||||
///
|
||||
/// Panics if path pattern is wrong.
|
||||
pub fn new(path: &str) -> Self {
|
||||
Pattern::with_prefix(path, false)
|
||||
ResourceDef::with_prefix(path, false)
|
||||
}
|
||||
|
||||
/// Parse path pattern and create new `Pattern` instance.
|
||||
@@ -46,13 +61,22 @@ impl Pattern {
|
||||
///
|
||||
/// Panics if path regex pattern is wrong.
|
||||
pub fn prefix(path: &str) -> Self {
|
||||
Pattern::with_prefix(path, true)
|
||||
ResourceDef::with_prefix(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) = Pattern::parse(&path, for_prefix);
|
||||
let (pattern, elements, is_dynamic, len) = ResourceDef::parse(&path, for_prefix);
|
||||
|
||||
let tp = if is_dynamic {
|
||||
let re = match Regex::new(&pattern) {
|
||||
@@ -71,9 +95,11 @@ impl Pattern {
|
||||
PatternType::Static(pattern.clone())
|
||||
};
|
||||
|
||||
Pattern {
|
||||
ResourceDef {
|
||||
tp,
|
||||
elements,
|
||||
name: String::new(),
|
||||
rtp: ResourceType::Normal,
|
||||
pattern: path.to_owned(),
|
||||
}
|
||||
}
|
||||
@@ -93,7 +119,7 @@ impl Pattern {
|
||||
}
|
||||
|
||||
/// Is the given path and parameters a match against this pattern?
|
||||
pub fn match_path<T: RequestPath>(&self, path: &mut Path<T>) -> bool {
|
||||
pub fn match_path<T: ResourcePath>(&self, path: &mut Path<T>) -> bool {
|
||||
match self.tp {
|
||||
PatternType::Static(ref s) => {
|
||||
if s == path.path() {
|
||||
@@ -261,20 +287,32 @@ impl Pattern {
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Pattern {
|
||||
fn eq(&self, other: &Pattern) -> bool {
|
||||
impl Eq for ResourceDef {}
|
||||
|
||||
impl PartialEq for ResourceDef {
|
||||
fn eq(&self, other: &ResourceDef) -> bool {
|
||||
self.pattern == other.pattern
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Pattern {}
|
||||
|
||||
impl Hash for 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)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -282,29 +320,29 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_parse_static() {
|
||||
let re = Pattern::new("/");
|
||||
let re = ResourceDef::new("/");
|
||||
assert!(re.is_match("/"));
|
||||
assert!(!re.is_match("/a"));
|
||||
|
||||
let re = Pattern::new("/name");
|
||||
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 = Pattern::new("/name/");
|
||||
let re = ResourceDef::new("/name/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(!re.is_match("/name"));
|
||||
assert!(!re.is_match("/name/gs"));
|
||||
|
||||
let re = Pattern::new("/user/profile");
|
||||
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 = Pattern::new("/user/{id}");
|
||||
let re = ResourceDef::new("/user/{id}");
|
||||
assert!(re.is_match("/user/profile"));
|
||||
assert!(re.is_match("/user/2345"));
|
||||
assert!(!re.is_match("/user/2345/"));
|
||||
@@ -318,7 +356,7 @@ mod tests {
|
||||
assert!(re.match_path(&mut path));
|
||||
assert_eq!(path.get("id").unwrap(), "1245125");
|
||||
|
||||
let re = Pattern::new("/v{version}/resource/{id}");
|
||||
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"));
|
||||
@@ -328,7 +366,7 @@ mod tests {
|
||||
assert_eq!(path.get("version").unwrap(), "151");
|
||||
assert_eq!(path.get("id").unwrap(), "adahg32");
|
||||
|
||||
let re = Pattern::new("/{id:[[:digit:]]{6}}");
|
||||
let re = ResourceDef::new("/{id:[[:digit:]]{6}}");
|
||||
assert!(re.is_match("/012345"));
|
||||
assert!(!re.is_match("/012"));
|
||||
assert!(!re.is_match("/01234567"));
|
||||
@@ -341,7 +379,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_parse_urlencoded_param() {
|
||||
let re = Pattern::new("/user/{id}/test");
|
||||
let re = ResourceDef::new("/user/{id}/test");
|
||||
|
||||
let mut path = Path::new("/user/2345/test");
|
||||
assert!(re.match_path(&mut path));
|
||||
@@ -359,14 +397,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_resource_prefix() {
|
||||
let re = Pattern::prefix("/name");
|
||||
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 = Pattern::prefix("/name/");
|
||||
let re = ResourceDef::prefix("/name/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(re.is_match("/name/gs"));
|
||||
assert!(!re.is_match("/name"));
|
||||
@@ -374,7 +412,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_reousrce_prefix_dynamic() {
|
||||
let re = Pattern::prefix("/{name}/");
|
||||
let re = ResourceDef::prefix("/{name}/");
|
||||
assert!(re.is_match("/name/"));
|
||||
assert!(re.is_match("/name/gs"));
|
||||
assert!(!re.is_match("/name"));
|
@@ -2,8 +2,8 @@ use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::path::Path;
|
||||
use crate::pattern::Pattern;
|
||||
use crate::RequestPath;
|
||||
use crate::resource::ResourceDef;
|
||||
use crate::ResourcePath;
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq)]
|
||||
pub(crate) enum ResourceId {
|
||||
@@ -20,15 +20,15 @@ pub struct ResourceInfo {
|
||||
|
||||
#[derive(Default, Debug)]
|
||||
pub(crate) struct ResourceMap {
|
||||
root: Option<Pattern>,
|
||||
named: HashMap<String, Pattern>,
|
||||
patterns: Vec<Pattern>,
|
||||
root: Option<ResourceDef>,
|
||||
named: HashMap<String, ResourceDef>,
|
||||
patterns: Vec<ResourceDef>,
|
||||
}
|
||||
|
||||
/// Resource router.
|
||||
pub struct Router<T> {
|
||||
rmap: Rc<ResourceMap>,
|
||||
named: HashMap<String, Pattern>,
|
||||
named: HashMap<String, ResourceDef>,
|
||||
resources: Vec<T>,
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ impl<T> Router<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn recognize<U: RequestPath>(&self, path: &mut Path<U>) -> Option<(&T, ResourceInfo)> {
|
||||
pub fn recognize<U: ResourcePath>(&self, path: &mut Path<U>) -> Option<(&T, ResourceInfo)> {
|
||||
if !path.path().is_empty() {
|
||||
for (idx, resource) in self.rmap.patterns.iter().enumerate() {
|
||||
if resource.match_path(path) {
|
||||
@@ -56,7 +56,7 @@ impl<T> Router<T> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn recognize_mut<U: RequestPath>(
|
||||
pub fn recognize_mut<U: ResourcePath>(
|
||||
&mut self,
|
||||
path: &mut Path<U>,
|
||||
) -> Option<(&mut T, ResourceInfo)> {
|
||||
@@ -94,11 +94,11 @@ impl<'a, T> IntoIterator for &'a mut Router<T> {
|
||||
}
|
||||
|
||||
impl ResourceMap {
|
||||
fn register(&mut self, pattern: Pattern) {
|
||||
fn register(&mut self, pattern: ResourceDef) {
|
||||
self.patterns.push(pattern);
|
||||
}
|
||||
|
||||
fn register_named(&mut self, name: String, pattern: Pattern) {
|
||||
fn register_named(&mut self, name: String, pattern: ResourceDef) {
|
||||
self.patterns.push(pattern.clone());
|
||||
self.named.insert(name, pattern);
|
||||
}
|
||||
@@ -110,21 +110,30 @@ impl ResourceMap {
|
||||
|
||||
pub struct RouterBuilder<T> {
|
||||
rmap: ResourceMap,
|
||||
named: HashMap<String, Pattern>,
|
||||
named: HashMap<String, ResourceDef>,
|
||||
resources: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T> RouterBuilder<T> {
|
||||
/// Register resource for specified path.
|
||||
pub fn path(&mut self, path: &str, resource: T) {
|
||||
self.rmap.register(Pattern::new(path));
|
||||
self.rmap.register(ResourceDef::new(path));
|
||||
self.resources.push(resource);
|
||||
}
|
||||
|
||||
/// Register resource for specified path prefix.
|
||||
pub fn prefix(&mut self, prefix: &str, resource: T) {
|
||||
self.rmap.register(Pattern::prefix(prefix));
|
||||
self.rmap.register(ResourceDef::prefix(prefix));
|
||||
self.resources.push(resource);
|
||||
}
|
||||
|
||||
/// Register resource for ResourceDef
|
||||
pub fn rdef(&mut self, rdef: ResourceDef, resource: T) {
|
||||
self.rmap.register(rdef);
|
||||
self.resources.push(resource);
|
||||
}
|
||||
|
||||
/// Finish configuration and create router instance.
|
||||
pub fn finish(self) -> Router<T> {
|
||||
Router {
|
||||
rmap: Rc::new(self.rmap),
|
||||
|
@@ -1,6 +1,6 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::RequestPath;
|
||||
use crate::ResourcePath;
|
||||
|
||||
#[allow(dead_code)]
|
||||
const GEN_DELIMS: &[u8] = b":/?#[]@";
|
||||
@@ -67,7 +67,7 @@ impl Url {
|
||||
}
|
||||
}
|
||||
|
||||
impl RequestPath for Url {
|
||||
impl ResourcePath for Url {
|
||||
fn path(&self) -> &str {
|
||||
self.path()
|
||||
}
|
||||
@@ -190,11 +190,11 @@ mod tests {
|
||||
use http::{HttpTryFrom, Uri};
|
||||
|
||||
use super::*;
|
||||
use crate::{Path, Pattern};
|
||||
use crate::{Path, ResourceDef};
|
||||
|
||||
#[test]
|
||||
fn test_parse_url() {
|
||||
let re = Pattern::new("/user/{id}/test");
|
||||
let re = ResourceDef::new("/user/{id}/test");
|
||||
|
||||
let url = Uri::try_from("/user/2345/test").unwrap();
|
||||
let mut path = Path::new(Url::new(url));
|
||||
|
Reference in New Issue
Block a user