1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2025-01-17 20:56:08 +00:00
actix-web/src/connector.rs

302 lines
8.5 KiB
Rust
Raw Normal View History

2018-08-24 03:47:41 +00:00
use std::collections::VecDeque;
use std::io;
2018-08-29 22:15:24 +00:00
use std::marker::PhantomData;
2018-08-24 03:47:41 +00:00
use std::net::SocketAddr;
2018-08-28 23:24:36 +00:00
use futures::{
future::{ok, FutureResult},
Async, Future, Poll,
};
2018-08-24 03:47:41 +00:00
use tokio;
use tokio_tcp::{ConnectFuture, TcpStream};
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
use trust_dns_resolver::lookup_ip::LookupIpFuture;
2018-08-28 23:24:36 +00:00
use trust_dns_resolver::system_conf::read_system_conf;
2018-08-24 03:47:41 +00:00
use trust_dns_resolver::{AsyncResolver, Background};
2018-08-28 23:24:36 +00:00
use super::{NewService, Service};
2018-08-29 22:15:24 +00:00
pub trait HostAware {
fn host(&self) -> &str;
}
impl HostAware for String {
fn host(&self) -> &str {
self.as_ref()
}
}
2018-08-24 03:47:41 +00:00
#[derive(Fail, Debug)]
pub enum ConnectorError {
/// Failed to resolve the hostname
#[fail(display = "Failed resolving hostname: {}", _0)]
Resolver(String),
/// Address is invalid
#[fail(display = "Invalid input: {}", _0)]
InvalidInput(&'static str),
/// Connection io error
#[fail(display = "{}", _0)]
IoError(io::Error),
}
2018-08-28 23:24:36 +00:00
pub struct ConnectionInfo {
pub host: String,
pub addr: SocketAddr,
}
2018-08-30 03:06:33 +00:00
pub struct Connector<T = String> {
2018-08-24 03:47:41 +00:00
resolver: AsyncResolver,
2018-08-29 22:15:24 +00:00
req: PhantomData<T>,
2018-08-24 03:47:41 +00:00
}
2018-08-29 22:15:24 +00:00
impl<T: HostAware> Default for Connector<T> {
2018-08-28 23:24:36 +00:00
fn default() -> Self {
let (cfg, opts) = if let Ok((cfg, opts)) = read_system_conf() {
(cfg, opts)
} else {
(ResolverConfig::default(), ResolverOpts::default())
2018-08-24 03:47:41 +00:00
};
2018-08-28 23:24:36 +00:00
Connector::new(cfg, opts)
}
}
2018-08-29 22:15:24 +00:00
impl<T: HostAware> Connector<T> {
2018-08-28 23:24:36 +00:00
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
let (resolver, bg) = AsyncResolver::new(cfg, opts);
tokio::spawn(bg);
2018-08-29 22:15:24 +00:00
Connector {
resolver,
req: PhantomData,
}
2018-08-24 03:47:41 +00:00
}
2018-08-28 03:32:49 +00:00
2018-08-28 23:24:36 +00:00
pub fn new_service<E>() -> impl NewService<
2018-08-29 22:15:24 +00:00
Request = T,
Response = (T, ConnectionInfo, TcpStream),
2018-08-28 23:24:36 +00:00
Error = ConnectorError,
InitError = E,
> + Clone {
2018-08-29 22:15:24 +00:00
|| -> FutureResult<Connector<T>, E> { ok(Connector::default()) }
2018-08-28 23:24:36 +00:00
}
pub fn new_service_with_config<E>(
cfg: ResolverConfig, opts: ResolverOpts,
) -> impl NewService<
2018-08-29 22:15:24 +00:00
Request = T,
Response = (T, ConnectionInfo, TcpStream),
2018-08-28 23:24:36 +00:00
Error = ConnectorError,
InitError = E,
> + Clone {
2018-08-30 16:26:27 +00:00
move || -> FutureResult<Connector<T>, E> { ok(Connector::new(cfg.clone(), opts)) }
2018-08-28 03:32:49 +00:00
}
}
2018-08-29 22:15:24 +00:00
impl<T> Clone for Connector<T> {
2018-08-28 03:32:49 +00:00
fn clone(&self) -> Self {
Connector {
resolver: self.resolver.clone(),
2018-08-29 22:15:24 +00:00
req: PhantomData,
2018-08-28 03:32:49 +00:00
}
}
2018-08-24 03:47:41 +00:00
}
2018-08-29 22:15:24 +00:00
impl<T: HostAware> Service for Connector<T> {
type Request = T;
type Response = (T, ConnectionInfo, TcpStream);
2018-08-24 03:47:41 +00:00
type Error = ConnectorError;
2018-08-29 22:15:24 +00:00
type Future = ConnectorFuture<T>;
2018-08-24 03:47:41 +00:00
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
2018-08-29 22:15:24 +00:00
fn call(&mut self, req: Self::Request) -> Self::Future {
let fut = ResolveFut::new(req, 0, &self.resolver);
2018-08-28 23:24:36 +00:00
ConnectorFuture { fut, fut2: None }
2018-08-24 03:47:41 +00:00
}
}
2018-08-29 22:15:24 +00:00
pub struct ConnectorFuture<T: HostAware> {
fut: ResolveFut<T>,
fut2: Option<TcpConnector<T>>,
2018-08-24 03:47:41 +00:00
}
2018-08-29 22:15:24 +00:00
impl<T: HostAware> Future for ConnectorFuture<T> {
type Item = (T, ConnectionInfo, TcpStream);
2018-08-24 03:47:41 +00:00
type Error = ConnectorError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Some(ref mut fut) = self.fut2 {
2018-08-28 23:24:36 +00:00
return fut.poll();
2018-08-24 03:47:41 +00:00
}
match self.fut.poll()? {
2018-08-29 22:15:24 +00:00
Async::Ready((req, host, addrs)) => {
self.fut2 = Some(TcpConnector::new(req, host, addrs));
2018-08-24 03:47:41 +00:00
self.poll()
2018-08-24 05:12:10 +00:00
}
Async::NotReady => Ok(Async::NotReady),
2018-08-24 03:47:41 +00:00
}
}
}
/// Resolver future
2018-08-29 22:15:24 +00:00
struct ResolveFut<T> {
req: Option<T>,
2018-08-28 23:24:36 +00:00
host: Option<String>,
2018-08-24 03:47:41 +00:00
port: u16,
2018-08-28 23:24:36 +00:00
lookup: Option<Background<LookupIpFuture>>,
2018-08-24 03:47:41 +00:00
addrs: Option<VecDeque<SocketAddr>>,
error: Option<ConnectorError>,
error2: Option<String>,
}
2018-08-29 22:15:24 +00:00
impl<T: HostAware> ResolveFut<T> {
pub fn new(addr: T, port: u16, resolver: &AsyncResolver) -> Self {
2018-08-24 03:47:41 +00:00
// we need to do dns resolution
2018-08-29 22:15:24 +00:00
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,
}
}
2018-08-24 03:47:41 +00:00
Err(err) => ResolveFut {
port,
2018-08-29 22:15:24 +00:00
req: None,
2018-08-28 23:24:36 +00:00
host: None,
2018-08-24 03:47:41 +00:00
lookup: None,
addrs: None,
error: Some(err),
error2: None,
},
}
}
2018-08-29 22:15:24 +00:00
fn parse(addr: &str, port: u16) -> Result<(String, u16), ConnectorError> {
2018-08-24 03:47:41 +00:00
macro_rules! try_opt {
($e:expr, $msg:expr) => {
match $e {
Some(r) => r,
None => return Err(ConnectorError::InvalidInput($msg)),
}
};
}
// split the string by ':' and convert the second part to u16
let mut parts_iter = addr.splitn(2, ':');
let host = try_opt!(parts_iter.next(), "invalid socket address");
let port_str = parts_iter.next().unwrap_or("");
let port: u16 = port_str.parse().unwrap_or(port);
2018-08-29 22:15:24 +00:00
Ok((host.to_owned(), port))
2018-08-24 03:47:41 +00:00
}
}
2018-08-29 22:15:24 +00:00
impl<T> Future for ResolveFut<T> {
type Item = (T, String, VecDeque<SocketAddr>);
2018-08-24 03:47:41 +00:00
type Error = ConnectorError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Some(err) = self.error.take() {
Err(err)
} else if let Some(err) = self.error2.take() {
Err(ConnectorError::Resolver(err))
} else if let Some(addrs) = self.addrs.take() {
2018-08-29 22:15:24 +00:00
Ok(Async::Ready((
self.req.take().unwrap(),
self.host.take().unwrap(),
addrs,
)))
2018-08-24 03:47:41 +00:00
} else {
match self.lookup.as_mut().unwrap().poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(ips)) => {
let addrs: VecDeque<_> = ips
.iter()
.map(|ip| SocketAddr::new(ip, self.port))
.collect();
if addrs.is_empty() {
Err(ConnectorError::Resolver(
"Expect at least one A dns record".to_owned(),
))
} else {
2018-08-29 22:15:24 +00:00
Ok(Async::Ready((
self.req.take().unwrap(),
self.host.take().unwrap(),
addrs,
)))
2018-08-24 03:47:41 +00:00
}
}
Err(err) => Err(ConnectorError::Resolver(format!("{}", err))),
}
}
}
}
/// Tcp stream connector
2018-08-29 22:15:24 +00:00
pub struct TcpConnector<T> {
req: Option<T>,
2018-08-28 23:24:36 +00:00
host: Option<String>,
addr: Option<SocketAddr>,
2018-08-24 03:47:41 +00:00
addrs: VecDeque<SocketAddr>,
stream: Option<ConnectFuture>,
}
2018-08-29 22:15:24 +00:00
impl<T> TcpConnector<T> {
pub fn new(req: T, host: String, addrs: VecDeque<SocketAddr>) -> TcpConnector<T> {
2018-08-24 03:47:41 +00:00
TcpConnector {
addrs,
2018-08-29 22:15:24 +00:00
req: Some(req),
2018-08-28 23:24:36 +00:00
host: Some(host),
addr: None,
2018-08-24 03:47:41 +00:00
stream: None,
}
}
}
2018-08-29 22:15:24 +00:00
impl<T> Future for TcpConnector<T> {
type Item = (T, ConnectionInfo, TcpStream);
2018-08-24 03:47:41 +00:00
type Error = ConnectorError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
// connect
loop {
if let Some(new) = self.stream.as_mut() {
match new.poll() {
2018-08-28 23:24:36 +00:00
Ok(Async::Ready(sock)) => {
return Ok(Async::Ready((
2018-08-29 22:15:24 +00:00
self.req.take().unwrap(),
2018-08-28 23:24:36 +00:00
ConnectionInfo {
host: self.host.take().unwrap(),
addr: self.addr.take().unwrap(),
},
sock,
)))
}
2018-08-24 03:47:41 +00:00
Ok(Async::NotReady) => return Ok(Async::NotReady),
Err(err) => {
if self.addrs.is_empty() {
return Err(ConnectorError::IoError(err));
}
}
}
}
// try to connect
let addr = self.addrs.pop_front().unwrap();
self.stream = Some(TcpStream::connect(&addr));
2018-08-28 23:24:36 +00:00
self.addr = Some(addr)
2018-08-24 03:47:41 +00:00
}
}
}