1
0
mirror of https://github.com/fafhrd91/actix-net synced 2025-01-18 20:01:48 +01:00

refactor Connector service

This commit is contained in:
Nikolay Kim 2018-08-29 15:15:24 -07:00
parent 7ec92f7b1c
commit 361ffd8d2f
3 changed files with 121 additions and 76 deletions

View File

@ -1,5 +1,6 @@
use std::collections::VecDeque;
use std::io;
use std::marker::PhantomData;
use std::net::SocketAddr;
use futures::{
@ -15,6 +16,16 @@ use trust_dns_resolver::{AsyncResolver, Background};
use super::{NewService, Service};
pub trait HostAware {
fn host(&self) -> &str;
}
impl HostAware for String {
fn host(&self) -> &str {
self.as_ref()
}
}
#[derive(Fail, Debug)]
pub enum ConnectorError {
/// Failed to resolve the hostname
@ -35,11 +46,12 @@ pub struct ConnectionInfo {
pub addr: SocketAddr,
}
pub struct Connector {
pub struct Connector<T> {
resolver: AsyncResolver,
req: PhantomData<T>,
}
impl Default for Connector {
impl<T: HostAware> Default for Connector<T> {
fn default() -> Self {
let (cfg, opts) = if let Ok((cfg, opts)) = read_system_conf() {
(cfg, opts)
@ -51,66 +63,72 @@ impl Default for Connector {
}
}
impl Connector {
impl<T: HostAware> Connector<T> {
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
let (resolver, bg) = AsyncResolver::new(cfg, opts);
tokio::spawn(bg);
Connector { resolver }
Connector {
resolver,
req: PhantomData,
}
}
pub fn new_service<E>() -> impl NewService<
Request = String,
Response = (ConnectionInfo, TcpStream),
Request = T,
Response = (T, ConnectionInfo, TcpStream),
Error = ConnectorError,
InitError = E,
> + Clone {
|| -> FutureResult<Connector, E> { ok(Connector::default()) }
|| -> FutureResult<Connector<T>, E> { ok(Connector::default()) }
}
pub fn new_service_with_config<E>(
cfg: ResolverConfig, opts: ResolverOpts,
) -> impl NewService<
Request = String,
Response = (ConnectionInfo, TcpStream),
Request = T,
Response = (T, ConnectionInfo, TcpStream),
Error = ConnectorError,
InitError = E,
> + Clone {
move || -> FutureResult<Connector, E> { ok(Connector::new(cfg.clone(), opts.clone())) }
}
}
impl Clone for Connector {
fn clone(&self) -> Self {
Connector {
resolver: self.resolver.clone(),
move || -> FutureResult<Connector<T>, E> {
ok(Connector::new(cfg.clone(), opts.clone()))
}
}
}
impl Service for Connector {
type Request = String;
type Response = (ConnectionInfo, TcpStream);
impl<T> Clone for Connector<T> {
fn clone(&self) -> Self {
Connector {
resolver: self.resolver.clone(),
req: PhantomData,
}
}
}
impl<T: HostAware> Service for Connector<T> {
type Request = T;
type Response = (T, ConnectionInfo, TcpStream);
type Error = ConnectorError;
type Future = ConnectorFuture;
type Future = ConnectorFuture<T>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, addr: String) -> Self::Future {
let fut = ResolveFut::new(addr, 0, &self.resolver);
fn call(&mut self, req: Self::Request) -> Self::Future {
let fut = ResolveFut::new(req, 0, &self.resolver);
ConnectorFuture { fut, fut2: None }
}
}
pub struct ConnectorFuture {
fut: ResolveFut,
fut2: Option<TcpConnector>,
pub struct ConnectorFuture<T: HostAware> {
fut: ResolveFut<T>,
fut2: Option<TcpConnector<T>>,
}
impl Future for ConnectorFuture {
type Item = (ConnectionInfo, TcpStream);
impl<T: HostAware> Future for ConnectorFuture<T> {
type Item = (T, ConnectionInfo, TcpStream);
type Error = ConnectorError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@ -118,8 +136,8 @@ impl Future for ConnectorFuture {
return fut.poll();
}
match self.fut.poll()? {
Async::Ready((host, addrs)) => {
self.fut2 = Some(TcpConnector::new(host, addrs));
Async::Ready((req, host, addrs)) => {
self.fut2 = Some(TcpConnector::new(req, host, addrs));
self.poll()
}
Async::NotReady => Ok(Async::NotReady),
@ -128,7 +146,8 @@ impl Future for ConnectorFuture {
}
/// Resolver future
struct ResolveFut {
struct ResolveFut<T> {
req: Option<T>,
host: Option<String>,
port: u16,
lookup: Option<Background<LookupIpFuture>>,
@ -137,20 +156,25 @@ struct ResolveFut {
error2: Option<String>,
}
impl ResolveFut {
pub fn new(addr: String, port: u16, resolver: &AsyncResolver) -> Self {
impl<T: HostAware> ResolveFut<T> {
pub fn new(addr: T, port: u16, resolver: &AsyncResolver) -> Self {
// we need to do dns resolution
match ResolveFut::parse(addr.as_ref(), port) {
Ok((host, port)) => ResolveFut {
port,
host: Some(host.to_owned()),
lookup: Some(resolver.lookup_ip(host)),
addrs: None,
error: None,
error2: None,
},
match ResolveFut::<T>::parse(addr.host(), port) {
Ok((host, port)) => {
let lookup = Some(resolver.lookup_ip(host.as_str()));
ResolveFut {
port,
lookup,
req: Some(addr),
host: Some(host),
addrs: None,
error: None,
error2: None,
}
}
Err(err) => ResolveFut {
port,
req: None,
host: None,
lookup: None,
addrs: None,
@ -160,7 +184,7 @@ impl ResolveFut {
}
}
fn parse(addr: &str, port: u16) -> Result<(&str, u16), ConnectorError> {
fn parse(addr: &str, port: u16) -> Result<(String, u16), ConnectorError> {
macro_rules! try_opt {
($e:expr, $msg:expr) => {
match $e {
@ -176,12 +200,12 @@ impl ResolveFut {
let port_str = parts_iter.next().unwrap_or("");
let port: u16 = port_str.parse().unwrap_or(port);
Ok((host, port))
Ok((host.to_owned(), port))
}
}
impl Future for ResolveFut {
type Item = (String, VecDeque<SocketAddr>);
impl<T> Future for ResolveFut<T> {
type Item = (T, String, VecDeque<SocketAddr>);
type Error = ConnectorError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@ -190,7 +214,11 @@ impl Future for ResolveFut {
} else if let Some(err) = self.error2.take() {
Err(ConnectorError::Resolver(err))
} else if let Some(addrs) = self.addrs.take() {
Ok(Async::Ready((self.host.take().unwrap(), addrs)))
Ok(Async::Ready((
self.req.take().unwrap(),
self.host.take().unwrap(),
addrs,
)))
} else {
match self.lookup.as_mut().unwrap().poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
@ -204,7 +232,11 @@ impl Future for ResolveFut {
"Expect at least one A dns record".to_owned(),
))
} else {
Ok(Async::Ready((self.host.take().unwrap(), addrs)))
Ok(Async::Ready((
self.req.take().unwrap(),
self.host.take().unwrap(),
addrs,
)))
}
}
Err(err) => Err(ConnectorError::Resolver(format!("{}", err))),
@ -214,17 +246,19 @@ impl Future for ResolveFut {
}
/// Tcp stream connector
pub struct TcpConnector {
pub struct TcpConnector<T> {
req: Option<T>,
host: Option<String>,
addr: Option<SocketAddr>,
addrs: VecDeque<SocketAddr>,
stream: Option<ConnectFuture>,
}
impl TcpConnector {
pub fn new(host: String, addrs: VecDeque<SocketAddr>) -> TcpConnector {
impl<T> TcpConnector<T> {
pub fn new(req: T, host: String, addrs: VecDeque<SocketAddr>) -> TcpConnector<T> {
TcpConnector {
addrs,
req: Some(req),
host: Some(host),
addr: None,
stream: None,
@ -232,8 +266,8 @@ impl TcpConnector {
}
}
impl Future for TcpConnector {
type Item = (ConnectionInfo, TcpStream);
impl<T> Future for TcpConnector<T> {
type Item = (T, ConnectionInfo, TcpStream);
type Error = ConnectorError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
@ -243,6 +277,7 @@ impl Future for TcpConnector {
match new.poll() {
Ok(Async::Ready(sock)) => {
return Ok(Async::Ready((
self.req.take().unwrap(),
ConnectionInfo {
host: self.host.take().unwrap(),
addr: self.addr.take().unwrap(),

View File

@ -53,7 +53,7 @@ pub use tower_service::{NewService, Service};
pub(crate) mod accept;
pub mod configurable;
mod connector;
pub mod connector;
mod server;
mod server_service;
pub mod service;
@ -61,7 +61,6 @@ pub mod ssl;
mod worker;
pub use configurable::{IntoNewConfigurableService, NewConfigurableService};
pub use connector::{ConnectionInfo, Connector, ConnectorError};
pub use server::Server;
pub use service::{IntoNewService, IntoService, NewServiceExt, ServiceExt};

View File

@ -92,83 +92,94 @@ impl<T: AsyncRead + AsyncWrite> Service for OpensslAcceptorService<T> {
}
/// Openssl connector factory
pub struct OpensslConnector<T> {
pub struct OpensslConnector<T, Io> {
connector: SslConnector,
io: PhantomData<T>,
t: PhantomData<T>,
io: PhantomData<Io>,
}
impl<T> OpensslConnector<T> {
impl<T, Io> OpensslConnector<T, Io> {
pub fn new(connector: SslConnector) -> Self {
OpensslConnector {
connector,
t: PhantomData,
io: PhantomData,
}
}
}
impl<T> Clone for OpensslConnector<T> {
impl<T, Io> Clone for OpensslConnector<T, Io> {
fn clone(&self) -> Self {
Self {
connector: self.connector.clone(),
t: PhantomData,
io: PhantomData,
}
}
}
impl<T: AsyncRead + AsyncWrite> NewService for OpensslConnector<T> {
type Request = (ConnectionInfo, T);
type Response = (ConnectionInfo, SslStream<T>);
impl<T, Io: AsyncRead + AsyncWrite> NewService for OpensslConnector<T, Io> {
type Request = (T, ConnectionInfo, Io);
type Response = (T, ConnectionInfo, SslStream<Io>);
type Error = Error;
type Service = OpensslConnectorService<T>;
type Service = OpensslConnectorService<T, Io>;
type InitError = io::Error;
type Future = FutureResult<Self::Service, Self::InitError>;
fn new_service(&self) -> Self::Future {
future::ok(OpensslConnectorService {
connector: self.connector.clone(),
t: PhantomData,
io: PhantomData,
})
}
}
pub struct OpensslConnectorService<T> {
pub struct OpensslConnectorService<T, Io> {
connector: SslConnector,
io: PhantomData<T>,
t: PhantomData<T>,
io: PhantomData<Io>,
}
impl<T: AsyncRead + AsyncWrite> Service for OpensslConnectorService<T> {
type Request = (ConnectionInfo, T);
type Response = (ConnectionInfo, SslStream<T>);
impl<T, Io: AsyncRead + AsyncWrite> Service for OpensslConnectorService<T, Io> {
type Request = (T, ConnectionInfo, Io);
type Response = (T, ConnectionInfo, SslStream<Io>);
type Error = Error;
type Future = ConnectAsyncExt<T>;
type Future = ConnectAsyncExt<T, Io>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, (info, stream): Self::Request) -> Self::Future {
fn call(&mut self, (req, info, stream): Self::Request) -> Self::Future {
ConnectAsyncExt {
fut: SslConnectorExt::connect_async(&self.connector, &info.host, stream),
req: Some(req),
host: Some(info),
}
}
}
pub struct ConnectAsyncExt<T> {
fut: ConnectAsync<T>,
pub struct ConnectAsyncExt<T, Io> {
fut: ConnectAsync<Io>,
req: Option<T>,
host: Option<ConnectionInfo>,
}
impl<T> Future for ConnectAsyncExt<T>
impl<T, Io> Future for ConnectAsyncExt<T, Io>
where
T: AsyncRead + AsyncWrite,
Io: AsyncRead + AsyncWrite,
{
type Item = (ConnectionInfo, SslStream<T>);
type Item = (T, ConnectionInfo, SslStream<Io>);
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.fut.poll()? {
Async::Ready(stream) => Ok(Async::Ready((self.host.take().unwrap(), stream))),
Async::Ready(stream) => Ok(Async::Ready((
self.req.take().unwrap(),
self.host.take().unwrap(),
stream,
))),
Async::NotReady => Ok(Async::NotReady),
}
}