1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use hyper::Uri;
use hyper_util::rt::TokioIo;
use pin_project_lite::pin_project;
use std::pin::Pin;
use std::task::Context;
use std::task::{self, Poll};
use std::{fmt, marker::PhantomData};
use std::{future::Future, path::Path};
use tokio::net::UnixStream;
use tower_service::Service;

use super::UnixSocketConnection;

type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// A Connector for a Socket.
#[derive(Clone)]
pub struct UnixSocketConnector<P> {
    socket_path: P,
}

impl<P: AsRef<Path>> UnixSocketConnector<P> {
    /// Construct a new `UnixStreamConnector`.
    #[must_use]
    pub fn new(socket_path: P) -> Self {
        Self { socket_path }
    }
}

impl<T: AsRef<Path>> From<T> for UnixSocketConnector<T> {
    fn from(args: T) -> UnixSocketConnector<T> {
        UnixSocketConnector { socket_path: args }
    }
}

impl<T> fmt::Debug for UnixSocketConnector<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("HttpsConnector").finish_non_exhaustive()
    }
}

impl<T> Service<Uri> for UnixSocketConnector<T>
where
    T: AsRef<Path> + Clone + Send,
{
    type Response = UnixSocketConnection;
    type Error = BoxError;
    type Future = UnixStreamConnecting;

    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, _: Uri) -> Self::Future {
        let socket_path = self.socket_path.as_ref().to_owned();

        let fut = async move {
            UnixStream::connect(socket_path)
                .await
                .map(TokioIo::new)
                .map(Into::into)
                .map_err(Into::into)
        };

        UnixStreamConnecting {
            fut: Box::pin(fut),
            _marker: PhantomData,
        }
    }
}

type ConnectResult = Result<UnixSocketConnection, BoxError>;
type BoxConnecting = Pin<Box<dyn Future<Output = ConnectResult> + Send>>;

pin_project! {
    #[must_use = "futures do nothing unless polled"]
    #[allow(missing_debug_implementations)]
    pub struct UnixStreamConnecting<R = ()> {
        #[pin]
        fut: BoxConnecting,
        _marker: PhantomData<R>,
    }
}

impl<R> Future for UnixStreamConnecting<R> {
    type Output = ConnectResult;

    fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
        self.project().fut.poll(cx)
    }
}

impl<R> fmt::Debug for UnixStreamConnecting<R> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("UnixStreamConnecting")
    }
}