tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
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;

/// One established TCP stream and its peer address.
#[derive(Debug)]
pub struct Connected {
    io: Io,
    remote_addr: SocketAddr,
}

impl Connected {
    /// Records a runtime-created stream and its connected peer.
    #[must_use]
    pub fn new(io: Io, remote_addr: SocketAddr) -> Self {
        Self { io, remote_addr }
    }

    /// Returns the established stream and its peer address.
    pub fn into_parts(self) -> (Io, SocketAddr) {
        (self.io, self.remote_addr)
    }
}

/// Socket options passed to a runtime's TCP connector.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SocketOptions {
    local_address: Option<SocketAddr>,
    nodelay: bool,
    keepalive: Option<Duration>,
}

impl SocketOptions {
    /// Creates the socket policy supplied to a runtime connector.
    pub const fn new(
        local_address: Option<SocketAddr>,
        nodelay: bool,
        keepalive: Option<Duration>,
    ) -> Self {
        Self {
            local_address,
            nodelay,
            keepalive,
        }
    }

    /// Returns the requested local bind address.
    #[must_use]
    pub const fn local_address(self) -> Option<SocketAddr> {
        self.local_address
    }

    /// Returns whether Nagle's algorithm should be disabled.
    #[must_use]
    pub const fn nodelay(self) -> bool {
        self.nodelay
    }

    /// Returns the requested TCP keepalive idle duration.
    #[must_use]
    pub const fn keepalive(self) -> Option<Duration> {
        self.keepalive
    }
}

/// A future that establishes one TCP stream.
pub type Connect<'a> = Pin<Box<dyn Future<Output = std::io::Result<Connected>> + Send + 'a>>;

/// Establishes TCP streams using an application's asynchronous reactor.
pub trait Connector: Send + Sync {
    /// Connects to one resolved address with the supplied socket options.
    fn connect(&self, address: SocketAddr, options: SocketOptions) -> Connect<'_>;
}

/// The portable `async-io` TCP connector used by default.
#[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)
}