use std::{
fmt,
future::Future,
net::{SocketAddr, TcpStream},
pin::Pin,
sync::Arc,
time::Duration,
};
use socket2::{Domain, Protocol, SockAddr, Socket, TcpKeepalive, Type};
use super::Io;
#[derive(Debug)]
pub struct Connected {
io: Io,
remote_addr: SocketAddr,
}
impl Connected {
#[must_use]
pub fn new(io: Io, remote_addr: SocketAddr) -> Self {
Self { io, remote_addr }
}
pub fn into_parts(self) -> (Io, SocketAddr) {
(self.io, self.remote_addr)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SocketOptions {
local_address: Option<SocketAddr>,
nodelay: bool,
keepalive: Option<Duration>,
}
impl SocketOptions {
pub const fn new(
local_address: Option<SocketAddr>,
nodelay: bool,
keepalive: Option<Duration>,
) -> Self {
Self {
local_address,
nodelay,
keepalive,
}
}
#[must_use]
pub const fn local_address(self) -> Option<SocketAddr> {
self.local_address
}
#[must_use]
pub const fn nodelay(self) -> bool {
self.nodelay
}
#[must_use]
pub const fn keepalive(self) -> Option<Duration> {
self.keepalive
}
}
pub type Connect<'a> = Pin<Box<dyn Future<Output = std::io::Result<Connected>> + Send + 'a>>;
pub trait Connector: Send + Sync {
fn connect(&self, address: SocketAddr, options: SocketOptions) -> Connect<'_>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct AsyncIoConnector;
impl Connector for AsyncIoConnector {
fn connect(&self, address: SocketAddr, options: SocketOptions) -> Connect<'_> {
Box::pin(async move {
let socket = Socket::new(
Domain::for_address(address),
Type::STREAM,
Some(Protocol::TCP),
)?;
if let Some(local) = options.local_address() {
socket.bind(&SockAddr::from(local))?;
}
if let Some(idle) = options.keepalive() {
socket.set_tcp_keepalive(&TcpKeepalive::new().with_time(idle))?;
}
socket.set_nonblocking(true)?;
match socket.connect(&SockAddr::from(address)) {
Ok(()) => {}
Err(error) if connect_in_progress(&error) => {}
Err(error) => return Err(error),
}
let stream = async_io::Async::new_nonblocking(TcpStream::from(socket))?;
stream.writable().await?;
if let Some(error) = stream.get_ref().take_error()? {
return Err(error);
}
stream.get_ref().set_nodelay(options.nodelay())?;
Ok(Connected::new(Io::from_futures(stream), address))
})
}
}
#[derive(Clone)]
pub(crate) struct SharedConnector(Arc<dyn Connector>);
impl SharedConnector {
pub(crate) fn new(connector: impl Connector + 'static) -> Self {
Self(Arc::new(connector))
}
}
impl Connector for SharedConnector {
fn connect(&self, address: SocketAddr, options: SocketOptions) -> Connect<'_> {
self.0.connect(address, options)
}
}
impl fmt::Debug for SharedConnector {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.debug_struct("Connector").finish_non_exhaustive()
}
}
#[cfg(unix)]
fn connect_in_progress(error: &std::io::Error) -> bool {
error.kind() == std::io::ErrorKind::WouldBlock
|| error.raw_os_error() == Some(libc::EINPROGRESS)
}
#[cfg(windows)]
fn connect_in_progress(error: &std::io::Error) -> bool {
error.kind() == std::io::ErrorKind::WouldBlock || error.raw_os_error() == Some(10035)
}