2018-03-16 20:04:01 +01:00
|
|
|
use std::{fmt, io, time};
|
|
|
|
use std::cell::RefCell;
|
|
|
|
use std::rc::Rc;
|
2018-02-27 00:26:27 +01:00
|
|
|
use std::net::Shutdown;
|
2018-03-16 20:04:01 +01:00
|
|
|
use std::time::{Duration, Instant};
|
|
|
|
use std::collections::{HashMap, VecDeque};
|
2018-01-30 08:01:20 +01:00
|
|
|
|
2018-03-16 20:04:01 +01:00
|
|
|
use actix::{fut, Actor, ActorFuture, Context, AsyncContext,
|
2018-02-12 21:17:30 +01:00
|
|
|
Handler, Message, ActorResponse, Supervised};
|
2018-02-09 02:13:56 +01:00
|
|
|
use actix::registry::ArbiterService;
|
2018-01-30 20:17:17 +01:00
|
|
|
use actix::fut::WrapFuture;
|
2018-01-30 08:01:20 +01:00
|
|
|
use actix::actors::{Connector, ConnectorError, Connect as ResolveConnect};
|
|
|
|
|
2018-01-30 20:17:17 +01:00
|
|
|
use http::{Uri, HttpTryFrom, Error as HttpError};
|
2018-03-16 20:04:01 +01:00
|
|
|
use futures::{Async, Poll};
|
2018-01-30 08:01:20 +01:00
|
|
|
use tokio_io::{AsyncRead, AsyncWrite};
|
|
|
|
|
2018-01-30 20:17:17 +01:00
|
|
|
#[cfg(feature="alpn")]
|
2018-02-27 01:11:00 +01:00
|
|
|
use openssl::ssl::{SslMethod, SslConnector, Error as OpensslError};
|
2018-01-30 20:17:17 +01:00
|
|
|
#[cfg(feature="alpn")]
|
|
|
|
use tokio_openssl::SslConnectorExt;
|
2018-02-27 01:11:00 +01:00
|
|
|
#[cfg(feature="alpn")]
|
|
|
|
use futures::Future;
|
2018-01-30 20:17:17 +01:00
|
|
|
|
2018-03-07 02:34:46 +01:00
|
|
|
#[cfg(all(feature="tls", not(feature="alpn")))]
|
|
|
|
use native_tls::{TlsConnector, Error as TlsError};
|
|
|
|
#[cfg(all(feature="tls", not(feature="alpn")))]
|
|
|
|
use tokio_tls::TlsConnectorExt;
|
|
|
|
#[cfg(all(feature="tls", not(feature="alpn")))]
|
|
|
|
use futures::Future;
|
|
|
|
|
|
|
|
use {HAS_OPENSSL, HAS_TLS};
|
2018-01-30 08:01:20 +01:00
|
|
|
use server::IoStream;
|
|
|
|
|
2018-01-30 20:17:17 +01:00
|
|
|
|
2018-01-30 08:01:20 +01:00
|
|
|
#[derive(Debug)]
|
2018-01-30 21:44:14 +01:00
|
|
|
/// `Connect` type represents message that can be send to `ClientConnector`
|
|
|
|
/// with connection request.
|
2018-03-06 23:26:09 +01:00
|
|
|
pub struct Connect {
|
|
|
|
pub uri: Uri,
|
2018-03-07 02:04:48 +01:00
|
|
|
pub conn_timeout: Duration,
|
2018-03-06 23:26:09 +01:00
|
|
|
}
|
2018-01-30 08:01:20 +01:00
|
|
|
|
2018-01-30 20:17:17 +01:00
|
|
|
impl Connect {
|
2018-01-30 21:44:14 +01:00
|
|
|
/// Create `Connect` message for specified `Uri`
|
2018-01-30 20:17:17 +01:00
|
|
|
pub fn new<U>(uri: U) -> Result<Connect, HttpError> where Uri: HttpTryFrom<U> {
|
2018-03-06 23:26:09 +01:00
|
|
|
Ok(Connect {
|
|
|
|
uri: Uri::try_from(uri).map_err(|e| e.into())?,
|
2018-03-07 02:04:48 +01:00
|
|
|
conn_timeout: Duration::from_secs(1)
|
2018-03-06 23:26:09 +01:00
|
|
|
})
|
2018-01-30 20:17:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-12 21:17:30 +01:00
|
|
|
impl Message for Connect {
|
|
|
|
type Result = Result<Connection, ClientConnectorError>;
|
2018-01-30 08:01:20 +01:00
|
|
|
}
|
|
|
|
|
2018-01-30 21:44:14 +01:00
|
|
|
/// A set of errors that can occur during connecting to a http host
|
2018-01-30 08:01:20 +01:00
|
|
|
#[derive(Fail, Debug)]
|
|
|
|
pub enum ClientConnectorError {
|
|
|
|
/// Invalid url
|
|
|
|
#[fail(display="Invalid url")]
|
|
|
|
InvalidUrl,
|
|
|
|
|
|
|
|
/// SSL feature is not enabled
|
|
|
|
#[fail(display="SSL is not supported")]
|
|
|
|
SslIsNotSupported,
|
|
|
|
|
2018-01-30 20:17:17 +01:00
|
|
|
/// SSL error
|
|
|
|
#[cfg(feature="alpn")]
|
|
|
|
#[fail(display="{}", _0)]
|
2018-02-22 07:53:23 +01:00
|
|
|
SslError(#[cause] OpensslError),
|
2018-01-30 20:17:17 +01:00
|
|
|
|
2018-03-07 02:34:46 +01:00
|
|
|
/// SSL error
|
|
|
|
#[cfg(all(feature="tls", not(feature="alpn")))]
|
|
|
|
#[fail(display="{}", _0)]
|
|
|
|
SslError(#[cause] TlsError),
|
|
|
|
|
2018-01-30 08:01:20 +01:00
|
|
|
/// Connection error
|
|
|
|
#[fail(display = "{}", _0)]
|
2018-02-22 07:53:23 +01:00
|
|
|
Connector(#[cause] ConnectorError),
|
2018-01-30 08:01:20 +01:00
|
|
|
|
2018-03-09 22:03:15 +01:00
|
|
|
/// Connection took too long
|
2018-01-30 08:01:20 +01:00
|
|
|
#[fail(display = "Timeout out while establishing connection")]
|
|
|
|
Timeout,
|
|
|
|
|
|
|
|
/// Connector has been disconnected
|
|
|
|
#[fail(display = "Internal error: connector has been disconnected")]
|
|
|
|
Disconnected,
|
|
|
|
|
|
|
|
/// Connection io error
|
|
|
|
#[fail(display = "{}", _0)]
|
2018-02-22 07:53:23 +01:00
|
|
|
IoError(#[cause] io::Error),
|
2018-01-30 08:01:20 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl From<ConnectorError> for ClientConnectorError {
|
|
|
|
fn from(err: ConnectorError) -> ClientConnectorError {
|
2018-03-07 21:09:53 +01:00
|
|
|
match err {
|
|
|
|
ConnectorError::Timeout => ClientConnectorError::Timeout,
|
|
|
|
_ => ClientConnectorError::Connector(err)
|
|
|
|
}
|
2018-01-30 08:01:20 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct ClientConnector {
|
2018-03-07 02:34:46 +01:00
|
|
|
#[cfg(all(feature="alpn"))]
|
2018-01-30 20:17:17 +01:00
|
|
|
connector: SslConnector,
|
2018-03-07 02:34:46 +01:00
|
|
|
#[cfg(all(feature="tls", not(feature="alpn")))]
|
|
|
|
connector: TlsConnector,
|
2018-03-16 20:04:01 +01:00
|
|
|
pool: Rc<Pool>,
|
2018-01-30 08:01:20 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Actor for ClientConnector {
|
|
|
|
type Context = Context<ClientConnector>;
|
2018-03-16 20:04:01 +01:00
|
|
|
|
|
|
|
fn started(&mut self, ctx: &mut Self::Context) {
|
|
|
|
self.collect(ctx);
|
|
|
|
}
|
2018-01-30 08:01:20 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Supervised for ClientConnector {}
|
|
|
|
|
|
|
|
impl ArbiterService for ClientConnector {}
|
|
|
|
|
2018-01-30 20:17:17 +01:00
|
|
|
impl Default for ClientConnector {
|
|
|
|
fn default() -> ClientConnector {
|
2018-03-07 02:34:46 +01:00
|
|
|
#[cfg(all(feature="alpn"))]
|
2018-01-30 20:17:17 +01:00
|
|
|
{
|
2018-02-27 01:11:00 +01:00
|
|
|
let builder = SslConnector::builder(SslMethod::tls()).unwrap();
|
2018-01-30 20:17:17 +01:00
|
|
|
ClientConnector {
|
2018-03-16 20:04:01 +01:00
|
|
|
connector: builder.build(),
|
|
|
|
pool: Rc::new(Pool::new()),
|
2018-01-30 20:17:17 +01:00
|
|
|
}
|
|
|
|
}
|
2018-03-07 02:34:46 +01:00
|
|
|
#[cfg(all(feature="tls", not(feature="alpn")))]
|
|
|
|
{
|
|
|
|
let builder = TlsConnector::builder().unwrap();
|
|
|
|
ClientConnector {
|
2018-03-16 20:04:01 +01:00
|
|
|
connector: builder.build().unwrap(),
|
|
|
|
pool: Rc::new(Pool::new()),
|
2018-03-07 02:34:46 +01:00
|
|
|
}
|
|
|
|
}
|
2018-01-30 20:17:17 +01:00
|
|
|
|
2018-03-07 02:34:46 +01:00
|
|
|
#[cfg(not(any(feature="alpn", feature="tls")))]
|
2018-03-16 20:04:01 +01:00
|
|
|
ClientConnector {pool: Rc::new(Pool::new())}
|
2018-01-30 20:17:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ClientConnector {
|
|
|
|
|
|
|
|
#[cfg(feature="alpn")]
|
|
|
|
/// Create `ClientConnector` actor with custom `SslConnector` instance.
|
|
|
|
///
|
|
|
|
/// By default `ClientConnector` uses very simple ssl configuration.
|
|
|
|
/// With `with_connector` method it is possible to use custom `SslConnector`
|
|
|
|
/// object.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # #![cfg(feature="alpn")]
|
|
|
|
/// # extern crate actix;
|
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// # extern crate futures;
|
|
|
|
/// # use futures::Future;
|
|
|
|
/// # use std::io::Write;
|
|
|
|
/// extern crate openssl;
|
|
|
|
/// use actix::prelude::*;
|
|
|
|
/// use actix_web::client::{Connect, ClientConnector};
|
|
|
|
///
|
|
|
|
/// use openssl::ssl::{SslMethod, SslConnector};
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let sys = System::new("test");
|
|
|
|
///
|
|
|
|
/// // Start `ClientConnector` with custom `SslConnector`
|
|
|
|
/// let ssl_conn = SslConnector::builder(SslMethod::tls()).unwrap().build();
|
|
|
|
/// let conn: Address<_> = ClientConnector::with_connector(ssl_conn).start();
|
|
|
|
///
|
|
|
|
/// Arbiter::handle().spawn({
|
2018-02-13 16:50:49 +01:00
|
|
|
/// conn.send(
|
2018-01-31 18:28:53 +01:00
|
|
|
/// Connect::new("https://www.rust-lang.org").unwrap()) // <- connect to host
|
2018-01-30 20:17:17 +01:00
|
|
|
/// .map_err(|_| ())
|
|
|
|
/// .and_then(|res| {
|
|
|
|
/// if let Ok(mut stream) = res {
|
|
|
|
/// stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap();
|
|
|
|
/// }
|
2018-02-13 07:56:47 +01:00
|
|
|
/// # Arbiter::system().do_send(actix::msgs::SystemExit(0));
|
2018-01-30 20:17:17 +01:00
|
|
|
/// Ok(())
|
|
|
|
/// })
|
|
|
|
/// });
|
|
|
|
///
|
|
|
|
/// sys.run();
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub fn with_connector(connector: SslConnector) -> ClientConnector {
|
2018-02-27 01:11:00 +01:00
|
|
|
ClientConnector { connector }
|
2018-01-30 20:17:17 +01:00
|
|
|
}
|
2018-03-16 20:04:01 +01:00
|
|
|
|
|
|
|
fn collect(&mut self, ctx: &mut Context<Self>) {
|
|
|
|
self.pool.collect();
|
|
|
|
ctx.run_later(Duration::from_secs(1), |act, ctx| act.collect(ctx));
|
|
|
|
}
|
2018-01-30 20:17:17 +01:00
|
|
|
}
|
|
|
|
|
2018-01-30 08:01:20 +01:00
|
|
|
impl Handler<Connect> for ClientConnector {
|
2018-02-12 21:17:30 +01:00
|
|
|
type Result = ActorResponse<ClientConnector, Connection, ClientConnectorError>;
|
2018-01-30 08:01:20 +01:00
|
|
|
|
|
|
|
fn handle(&mut self, msg: Connect, _: &mut Self::Context) -> Self::Result {
|
2018-03-06 23:26:09 +01:00
|
|
|
let uri = &msg.uri;
|
2018-03-07 02:04:48 +01:00
|
|
|
let conn_timeout = msg.conn_timeout;
|
2018-01-30 08:01:20 +01:00
|
|
|
|
2018-01-30 20:17:17 +01:00
|
|
|
// host name is required
|
2018-01-30 08:01:20 +01:00
|
|
|
if uri.host().is_none() {
|
2018-02-12 21:17:30 +01:00
|
|
|
return ActorResponse::reply(Err(ClientConnectorError::InvalidUrl))
|
2018-01-30 08:01:20 +01:00
|
|
|
}
|
|
|
|
|
2018-01-30 20:17:17 +01:00
|
|
|
// supported protocols
|
2018-01-30 08:01:20 +01:00
|
|
|
let proto = match uri.scheme_part() {
|
|
|
|
Some(scheme) => match Protocol::from(scheme.as_str()) {
|
|
|
|
Some(proto) => proto,
|
2018-02-12 21:17:30 +01:00
|
|
|
None => return ActorResponse::reply(Err(ClientConnectorError::InvalidUrl)),
|
2018-01-30 08:01:20 +01:00
|
|
|
},
|
2018-02-12 21:17:30 +01:00
|
|
|
None => return ActorResponse::reply(Err(ClientConnectorError::InvalidUrl)),
|
2018-01-30 08:01:20 +01:00
|
|
|
};
|
|
|
|
|
2018-01-30 20:17:17 +01:00
|
|
|
// check ssl availability
|
2018-03-07 02:34:46 +01:00
|
|
|
if proto.is_secure() && !HAS_OPENSSL && !HAS_TLS {
|
2018-02-12 21:17:30 +01:00
|
|
|
return ActorResponse::reply(Err(ClientConnectorError::SslIsNotSupported))
|
2018-01-30 20:17:17 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
let host = uri.host().unwrap().to_owned();
|
2018-01-30 08:01:20 +01:00
|
|
|
let port = uri.port().unwrap_or_else(|| proto.port());
|
2018-03-16 20:04:01 +01:00
|
|
|
let key = Key {host, port, ssl: proto.is_secure()};
|
|
|
|
|
|
|
|
let pool = if proto.is_http() {
|
|
|
|
if let Some(conn) = self.pool.query(&key) {
|
|
|
|
return ActorResponse::async(fut::ok(conn))
|
|
|
|
} else {
|
|
|
|
Some(Rc::clone(&self.pool))
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
2018-01-30 08:01:20 +01:00
|
|
|
|
2018-02-12 21:17:30 +01:00
|
|
|
ActorResponse::async(
|
2018-01-30 08:01:20 +01:00
|
|
|
Connector::from_registry()
|
2018-03-16 20:04:01 +01:00
|
|
|
.send(ResolveConnect::host_and_port(&key.host, port)
|
2018-03-07 02:04:48 +01:00
|
|
|
.timeout(conn_timeout))
|
2018-02-13 01:08:04 +01:00
|
|
|
.into_actor(self)
|
2018-01-30 08:01:20 +01:00
|
|
|
.map_err(|_, _, _| ClientConnectorError::Disconnected)
|
2018-01-30 20:17:17 +01:00
|
|
|
.and_then(move |res, _act, _| {
|
|
|
|
#[cfg(feature="alpn")]
|
|
|
|
match res {
|
|
|
|
Err(err) => fut::Either::B(fut::err(err.into())),
|
|
|
|
Ok(stream) => {
|
|
|
|
if proto.is_secure() {
|
|
|
|
fut::Either::A(
|
|
|
|
_act.connector.connect_async(&host, stream)
|
2018-02-27 01:11:00 +01:00
|
|
|
.map_err(ClientConnectorError::SslError)
|
2018-03-16 20:04:01 +01:00
|
|
|
.map(|stream| Connection::new(
|
|
|
|
key, pool, Box::new(stream)))
|
2018-01-30 20:17:17 +01:00
|
|
|
.into_actor(_act))
|
|
|
|
} else {
|
2018-03-16 20:04:01 +01:00
|
|
|
fut::Either::B(fut::ok(
|
|
|
|
Connection::new(key, pool, Box::new(stream))))
|
2018-01-30 20:17:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-07 02:34:46 +01:00
|
|
|
#[cfg(all(feature="tls", not(feature="alpn")))]
|
|
|
|
match res {
|
|
|
|
Err(err) => fut::Either::B(fut::err(err.into())),
|
|
|
|
Ok(stream) => {
|
|
|
|
if proto.is_secure() {
|
|
|
|
fut::Either::A(
|
|
|
|
_act.connector.connect_async(&host, stream)
|
|
|
|
.map_err(ClientConnectorError::SslError)
|
2018-03-16 20:04:01 +01:00
|
|
|
.map(|stream| Connection::new(
|
|
|
|
key, pool, Box::new(stream)))
|
2018-03-07 02:34:46 +01:00
|
|
|
.into_actor(_act))
|
|
|
|
} else {
|
2018-03-16 20:04:01 +01:00
|
|
|
fut::Either::B(fut::ok(
|
|
|
|
Connection::new(key, pool, Box::new(stream))))
|
2018-03-07 02:34:46 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(not(any(feature="alpn", feature="tls")))]
|
2018-01-30 20:17:17 +01:00
|
|
|
match res {
|
|
|
|
Err(err) => fut::err(err.into()),
|
|
|
|
Ok(stream) => {
|
|
|
|
if proto.is_secure() {
|
|
|
|
fut::err(ClientConnectorError::SslIsNotSupported)
|
|
|
|
} else {
|
2018-03-16 20:04:01 +01:00
|
|
|
fut::ok(Connection::new(key, pool, Box::new(stream)))
|
2018-01-30 20:17:17 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-01-30 08:01:20 +01:00
|
|
|
}))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-30 20:17:17 +01:00
|
|
|
#[derive(PartialEq, Hash, Debug, Clone, Copy)]
|
2018-01-30 08:01:20 +01:00
|
|
|
enum Protocol {
|
|
|
|
Http,
|
|
|
|
Https,
|
|
|
|
Ws,
|
|
|
|
Wss,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Protocol {
|
|
|
|
fn from(s: &str) -> Option<Protocol> {
|
|
|
|
match s {
|
|
|
|
"http" => Some(Protocol::Http),
|
|
|
|
"https" => Some(Protocol::Https),
|
|
|
|
"ws" => Some(Protocol::Ws),
|
|
|
|
"wss" => Some(Protocol::Wss),
|
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-16 20:04:01 +01:00
|
|
|
fn is_http(&self) -> bool {
|
|
|
|
match *self {
|
|
|
|
Protocol::Https | Protocol::Http => true,
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-30 20:17:17 +01:00
|
|
|
fn is_secure(&self) -> bool {
|
|
|
|
match *self {
|
|
|
|
Protocol::Https | Protocol::Wss => true,
|
|
|
|
_ => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-30 08:01:20 +01:00
|
|
|
fn port(&self) -> u16 {
|
|
|
|
match *self {
|
|
|
|
Protocol::Http | Protocol::Ws => 80,
|
|
|
|
Protocol::Https | Protocol::Wss => 443
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-16 20:04:01 +01:00
|
|
|
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
|
|
|
|
struct Key {
|
|
|
|
host: String,
|
|
|
|
port: u16,
|
|
|
|
ssl: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Key {
|
|
|
|
fn empty() -> Key {
|
|
|
|
Key{host: String::new(), port: 0, ssl: false}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct Conn(Instant, Connection);
|
|
|
|
|
|
|
|
pub struct Pool {
|
|
|
|
max_size: usize,
|
|
|
|
keep_alive: Duration,
|
|
|
|
max_lifetime: Duration,
|
|
|
|
pool: RefCell<HashMap<Key, VecDeque<Conn>>>,
|
|
|
|
to_close: RefCell<Vec<Connection>>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Pool {
|
|
|
|
fn new() -> Pool {
|
|
|
|
Pool {
|
|
|
|
max_size: 128,
|
|
|
|
keep_alive: Duration::from_secs(15),
|
|
|
|
max_lifetime: Duration::from_secs(75),
|
|
|
|
pool: RefCell::new(HashMap::new()),
|
|
|
|
to_close: RefCell::new(Vec::new()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn collect(&self) {
|
|
|
|
let mut pool = self.pool.borrow_mut();
|
|
|
|
let mut to_close = self.to_close.borrow_mut();
|
|
|
|
|
|
|
|
// check keep-alive
|
|
|
|
let now = Instant::now();
|
|
|
|
for conns in pool.values_mut() {
|
|
|
|
while !conns.is_empty() {
|
|
|
|
if (now - conns[0].0) > self.keep_alive
|
|
|
|
|| (now - conns[0].1.ts) > self.max_lifetime
|
|
|
|
{
|
|
|
|
let conn = conns.pop_front().unwrap().1;
|
|
|
|
to_close.push(conn);
|
|
|
|
} else {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// check connections for shutdown
|
|
|
|
let mut idx = 0;
|
|
|
|
while idx < to_close.len() {
|
|
|
|
match AsyncWrite::shutdown(&mut to_close[idx]) {
|
|
|
|
Ok(Async::NotReady) => idx += 1,
|
|
|
|
_ => {
|
|
|
|
to_close.swap_remove(idx);
|
|
|
|
},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn query(&self, key: &Key) -> Option<Connection> {
|
|
|
|
let mut pool = self.pool.borrow_mut();
|
|
|
|
let mut to_close = self.to_close.borrow_mut();
|
|
|
|
|
|
|
|
if let Some(ref mut connections) = pool.get_mut(key) {
|
|
|
|
let now = Instant::now();
|
|
|
|
while let Some(conn) = connections.pop_back() {
|
|
|
|
// check if it still usable
|
|
|
|
if (now - conn.0) > self.keep_alive
|
|
|
|
|| (now - conn.1.ts) > self.max_lifetime
|
|
|
|
{
|
|
|
|
to_close.push(conn.1);
|
|
|
|
} else {
|
|
|
|
let mut conn = conn.1;
|
|
|
|
let mut buf = [0; 2];
|
|
|
|
match conn.stream().read(&mut buf) {
|
|
|
|
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => (),
|
|
|
|
Ok(n) if n > 0 => {
|
|
|
|
to_close.push(conn);
|
|
|
|
continue
|
|
|
|
},
|
|
|
|
Ok(_) | Err(_) => continue,
|
|
|
|
}
|
|
|
|
return Some(conn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
fn release(&self, conn: Connection) {
|
|
|
|
if (Instant::now() - conn.ts) < self.max_lifetime {
|
|
|
|
let mut pool = self.pool.borrow_mut();
|
|
|
|
if !pool.contains_key(&conn.key) {
|
|
|
|
let key = conn.key.clone();
|
|
|
|
let mut vec = VecDeque::new();
|
|
|
|
vec.push_back(Conn(Instant::now(), conn));
|
|
|
|
pool.insert(key, vec);
|
|
|
|
} else {
|
|
|
|
let vec = pool.get_mut(&conn.key).unwrap();
|
|
|
|
vec.push_back(Conn(Instant::now(), conn));
|
|
|
|
if vec.len() > self.max_size {
|
|
|
|
let conn = vec.pop_front().unwrap();
|
|
|
|
self.to_close.borrow_mut().push(conn.1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-30 08:01:20 +01:00
|
|
|
|
|
|
|
pub struct Connection {
|
2018-03-16 20:04:01 +01:00
|
|
|
key: Key,
|
2018-01-30 08:01:20 +01:00
|
|
|
stream: Box<IoStream>,
|
2018-03-16 20:04:01 +01:00
|
|
|
pool: Option<Rc<Pool>>,
|
|
|
|
ts: Instant,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl fmt::Debug for Connection {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
write!(f, "Connection {}:{}", self.key.host, self.key.port)
|
|
|
|
}
|
2018-01-30 08:01:20 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Connection {
|
2018-03-16 20:04:01 +01:00
|
|
|
fn new(key: Key, pool: Option<Rc<Pool>>, stream: Box<IoStream>) -> Self {
|
|
|
|
Connection {
|
|
|
|
key, pool, stream,
|
|
|
|
ts: Instant::now(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-30 08:01:20 +01:00
|
|
|
pub fn stream(&mut self) -> &mut IoStream {
|
|
|
|
&mut *self.stream
|
|
|
|
}
|
2018-02-22 07:53:23 +01:00
|
|
|
|
|
|
|
pub fn from_stream<T: IoStream>(io: T) -> Connection {
|
2018-03-16 20:04:01 +01:00
|
|
|
Connection::new(Key::empty(), None, Box::new(io))
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn release(mut self) {
|
|
|
|
if let Some(pool) = self.pool.take() {
|
|
|
|
pool.release(self)
|
|
|
|
}
|
2018-02-22 07:53:23 +01:00
|
|
|
}
|
2018-01-30 08:01:20 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl IoStream for Connection {
|
|
|
|
fn shutdown(&mut self, how: Shutdown) -> io::Result<()> {
|
|
|
|
IoStream::shutdown(&mut *self.stream, how)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn set_nodelay(&mut self, nodelay: bool) -> io::Result<()> {
|
|
|
|
IoStream::set_nodelay(&mut *self.stream, nodelay)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn set_linger(&mut self, dur: Option<time::Duration>) -> io::Result<()> {
|
|
|
|
IoStream::set_linger(&mut *self.stream, dur)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl io::Read for Connection {
|
|
|
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
|
|
|
self.stream.read(buf)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsyncRead for Connection {}
|
|
|
|
|
|
|
|
impl io::Write for Connection {
|
|
|
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
|
|
|
self.stream.write(buf)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn flush(&mut self) -> io::Result<()> {
|
|
|
|
self.stream.flush()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AsyncWrite for Connection {
|
|
|
|
fn shutdown(&mut self) -> Poll<(), io::Error> {
|
|
|
|
self.stream.shutdown()
|
|
|
|
}
|
|
|
|
}
|