tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
use std::{
    future::Future,
    io,
    net::{SocketAddr, TcpStream as StdTcpStream},
    pin::Pin,
    task::{Context, Poll},
};

use futures_io::{AsyncRead, AsyncWrite};
use hyper::rt::{Read as HyperRead, ReadBufCursor, Write as HyperWrite};
use socket2::{Domain, Protocol, SockAddr, Socket, TcpKeepalive, Type};
use tokio::{
    io::{AsyncRead as TokioRead, AsyncWrite as TokioWrite, ReadBuf},
    net::{TcpSocket, TcpStream},
    runtime::Handle,
};

use super::{Connect, Connected, Connector, Executor, Io, Runtime, SocketOptions, Timer};
use crate::dns::{Resolve, Resolver};

/// Builds runtime capabilities backed by a Tokio runtime handle.
#[derive(Clone, Debug)]
pub struct Tokio {
    handle: Handle,
}

impl Tokio {
    /// Uses an explicit Tokio runtime handle.
    #[must_use]
    pub fn new(handle: Handle) -> Self {
        Self { handle }
    }

    /// Captures the currently entered Tokio runtime.
    ///
    /// # Errors
    ///
    /// Returns an error when called outside a Tokio runtime context.
    pub fn current() -> crate::Result<Self> {
        Handle::try_current()
            .map(Self::new)
            .map_err(|_| crate::Error::request("a Tokio runtime is not currently entered"))
    }

    /// Creates a complete Tokio runtime integration for a Tez client.
    ///
    /// The referenced Tokio runtime must remain alive while clients using the
    /// returned capabilities can perform work.
    #[must_use]
    pub fn runtime(&self) -> Runtime {
        let executor = self.handle.clone();
        let timer = self.handle.clone();
        let resolver = self.handle.clone();
        Runtime::builder()
            .executor(Executor::new(move |future| {
                executor.spawn(future);
            }))
            .timer(Timer::new(move |deadline| {
                OnRuntime::new(timer.clone(), async move {
                    tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await;
                })
            }))
            .resolver(TokioResolver { handle: resolver })
            .connector(TokioConnector {
                handle: self.handle.clone(),
            })
            .build()
    }
}

#[derive(Clone, Debug)]
struct TokioResolver {
    handle: Handle,
}

impl Resolver for TokioResolver {
    fn resolve<'a>(&'a self, host: &'a str, port: u16) -> Resolve<'a> {
        Box::pin(OnRuntime::new(self.handle.clone(), async move {
            tokio::net::lookup_host((host, port))
                .await
                .map(Iterator::collect)
        }))
    }
}

#[derive(Clone, Debug)]
struct TokioConnector {
    handle: Handle,
}

impl Connector for TokioConnector {
    fn connect(&self, address: SocketAddr, options: SocketOptions) -> Connect<'_> {
        let handle = self.handle.clone();
        Box::pin(OnRuntime::new(handle, 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)?;
            let socket = TcpSocket::from_std_stream(StdTcpStream::from(socket));
            let stream = socket.connect(address).await?;
            stream.set_nodelay(options.nodelay())?;
            Ok(Connected::new(
                Io::from_stream(TokioIo::new(stream)),
                address,
            ))
        }))
    }
}

struct OnRuntime<F> {
    handle: Handle,
    future: Pin<Box<F>>,
}

impl<F> OnRuntime<F> {
    fn new(handle: Handle, future: F) -> Self {
        Self {
            handle,
            future: Box::pin(future),
        }
    }
}

impl<F> Future for OnRuntime<F>
where
    F: Future,
{
    type Output = F::Output;

    fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
        let _guard = self.handle.enter();
        self.future.as_mut().poll(context)
    }
}

struct TokioIo {
    inner: hyper_util::rt::TokioIo<TcpStream>,
}

impl TokioIo {
    fn new(stream: TcpStream) -> Self {
        Self {
            inner: hyper_util::rt::TokioIo::new(stream),
        }
    }
}

impl super::io::Stream for TokioIo {
    fn poll_read_buf(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        buffer: &mut bytes::BytesMut,
    ) -> Poll<io::Result<usize>> {
        tokio_util::io::poll_read_buf(Pin::new(self.inner.inner_mut()), context, buffer)
    }
}

impl AsyncRead for TokioIo {
    fn poll_read(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        buffer: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let mut read = ReadBuf::new(buffer);
        match Pin::new(self.inner.inner_mut()).poll_read(context, &mut read) {
            Poll::Ready(Ok(())) => Poll::Ready(Ok(read.filled().len())),
            Poll::Ready(Err(error)) => Poll::Ready(Err(error)),
            Poll::Pending => Poll::Pending,
        }
    }
}

impl AsyncWrite for TokioIo {
    fn poll_write(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        bytes: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(self.inner.inner_mut()).poll_write(context, bytes)
    }

    fn poll_write_vectored(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        buffers: &[io::IoSlice<'_>],
    ) -> Poll<io::Result<usize>> {
        Pin::new(self.inner.inner_mut()).poll_write_vectored(context, buffers)
    }

    fn poll_flush(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(self.inner.inner_mut()).poll_flush(context)
    }

    fn poll_close(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(self.inner.inner_mut()).poll_shutdown(context)
    }
}

impl HyperRead for TokioIo {
    fn poll_read(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        buffer: ReadBufCursor<'_>,
    ) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_read(context, buffer)
    }
}

impl HyperWrite for TokioIo {
    fn poll_write(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        bytes: &[u8],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.inner).poll_write(context, bytes)
    }

    fn poll_flush(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_flush(context)
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
        Pin::new(&mut self.inner).poll_shutdown(context)
    }

    fn is_write_vectored(&self) -> bool {
        self.inner.is_write_vectored()
    }

    fn poll_write_vectored(
        mut self: Pin<&mut Self>,
        context: &mut Context<'_>,
        buffers: &[io::IoSlice<'_>],
    ) -> Poll<io::Result<usize>> {
        Pin::new(&mut self.inner).poll_write_vectored(context, buffers)
    }
}