monoio_transports/connectors/
l4_connector.rs

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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
use std::{
    io,
    net::{SocketAddr, ToSocketAddrs},
    path::{Path, PathBuf},
};

use http::Uri;
use monoio::{
    io::{AsyncReadRent, AsyncWriteRent, Split},
    net::{TcpStream, UnixStream},
};

use super::{Connector, TransportConnMeta, TransportConnMetadata};

/// A connector for establishing TCP connections.
#[derive(Clone, Copy, Debug)]
pub struct TcpConnector {
    /// Whether to set TCP_NODELAY on the created connection.
    pub no_delay: bool,
}

impl Default for TcpConnector {
    #[inline]
    fn default() -> Self {
        Self { no_delay: true }
    }
}

impl<T: ToSocketAddrs> Connector<T> for TcpConnector {
    type Connection = TcpStream;
    type Error = io::Error;

    #[inline]
    async fn connect(&self, key: T) -> Result<Self::Connection, Self::Error> {
        TcpStream::connect(key).await.map(|io| {
            if self.no_delay {
                // we will ignore the set nodelay error
                let _ = io.set_nodelay(true);
            }
            io
        })
    }
}

impl TransportConnMetadata for TcpStream {
    type Metadata = TransportConnMeta;

    fn get_conn_metadata(&self) -> Self::Metadata {
        TransportConnMeta::default()
    }
}

// A connector for establishing Unix domain socket connections.
#[derive(Default, Clone, Copy, Debug)]
pub struct UnixConnector;

impl<P: AsRef<Path>> Connector<P> for UnixConnector {
    type Connection = UnixStream;
    type Error = io::Error;

    #[inline]
    async fn connect(&self, key: P) -> Result<Self::Connection, Self::Error> {
        UnixStream::connect(key).await
    }
}

impl TransportConnMetadata for UnixStream {
    type Metadata = TransportConnMeta;

    fn get_conn_metadata(&self) -> Self::Metadata {
        TransportConnMeta::default()
    }
}

/// A connector that can establish either TCP or Unix domain socket connections.
#[derive(Default, Clone, Copy, Debug)]
pub struct UnifiedL4Connector {
    tcp: TcpConnector,
    unix: UnixConnector,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum UnifiedL4Addr {
    Tcp(SocketAddr),
    Unix(PathBuf),
}

impl AsRef<UnifiedL4Addr> for UnifiedL4Addr {
    #[inline]
    fn as_ref(&self) -> &UnifiedL4Addr {
        self
    }
}

impl TryFrom<&Uri> for UnifiedL4Addr {
    type Error = crate::FromUriError;

    #[inline]
    fn try_from(uri: &Uri) -> Result<Self, Self::Error> {
        let host = match uri.host() {
            Some(a) => a,
            None => return Err(crate::FromUriError::NoAuthority),
        };

        let default_port = match uri.scheme() {
            Some(scheme) if scheme == &http::uri::Scheme::HTTP => 80,
            Some(scheme) if scheme == &http::uri::Scheme::HTTPS => 443,
            _ => 0,
        };
        let port = uri.port_u16().unwrap_or(default_port);
        let addr = (host, port)
            .to_socket_addrs()?
            .next()
            .ok_or(crate::FromUriError::NoResolve)?;

        Ok(Self::Tcp(addr))
    }
}

impl TryFrom<Uri> for UnifiedL4Addr {
    type Error = crate::FromUriError;

    fn try_from(value: Uri) -> Result<Self, Self::Error> {
        Self::try_from(&value)
    }
}

/// A unified L4 stream that can be either a TCP or Unix stream.
#[derive(Debug)]
pub enum UnifiedL4Stream {
    Tcp(TcpStream),
    Unix(UnixStream),
}

impl<T: AsRef<UnifiedL4Addr>> Connector<T> for UnifiedL4Connector {
    type Connection = UnifiedL4Stream;
    type Error = io::Error;

    #[inline]
    async fn connect(&self, key: T) -> Result<Self::Connection, Self::Error> {
        match key.as_ref() {
            UnifiedL4Addr::Tcp(addr) => self.tcp.connect(addr).await.map(UnifiedL4Stream::Tcp),
            UnifiedL4Addr::Unix(path) => self.unix.connect(path).await.map(UnifiedL4Stream::Unix),
        }
    }
}

impl AsyncReadRent for UnifiedL4Stream {
    #[inline]
    async fn read<T: monoio::buf::IoBufMut>(&mut self, buf: T) -> monoio::BufResult<usize, T> {
        match self {
            UnifiedL4Stream::Tcp(inner) => inner.read(buf).await,
            UnifiedL4Stream::Unix(inner) => inner.read(buf).await,
        }
    }

    #[inline]
    async fn readv<T: monoio::buf::IoVecBufMut>(&mut self, buf: T) -> monoio::BufResult<usize, T> {
        match self {
            UnifiedL4Stream::Tcp(inner) => inner.readv(buf).await,
            UnifiedL4Stream::Unix(inner) => inner.readv(buf).await,
        }
    }
}

impl AsyncWriteRent for UnifiedL4Stream {
    #[inline]
    async fn write<T: monoio::buf::IoBuf>(&mut self, buf: T) -> monoio::BufResult<usize, T> {
        match self {
            UnifiedL4Stream::Tcp(inner) => inner.write(buf).await,
            UnifiedL4Stream::Unix(inner) => inner.write(buf).await,
        }
    }

    #[inline]
    async fn writev<T: monoio::buf::IoVecBuf>(
        &mut self,
        buf_vec: T,
    ) -> monoio::BufResult<usize, T> {
        match self {
            UnifiedL4Stream::Tcp(inner) => inner.writev(buf_vec).await,
            UnifiedL4Stream::Unix(inner) => inner.writev(buf_vec).await,
        }
    }

    #[inline]
    async fn flush(&mut self) -> std::io::Result<()> {
        match self {
            UnifiedL4Stream::Tcp(inner) => inner.flush().await,
            UnifiedL4Stream::Unix(inner) => inner.flush().await,
        }
    }

    #[inline]
    async fn shutdown(&mut self) -> std::io::Result<()> {
        match self {
            UnifiedL4Stream::Tcp(inner) => inner.shutdown().await,
            UnifiedL4Stream::Unix(inner) => inner.shutdown().await,
        }
    }
}

unsafe impl Split for UnifiedL4Stream {}