sqlx_core/net/socket/
mod.rs

1use std::future::Future;
2use std::io;
3use std::path::Path;
4use std::pin::Pin;
5use std::task::{ready, Context, Poll};
6
7use bytes::BufMut;
8
9pub use buffered::{BufferedSocket, WriteBuffer};
10
11use crate::io::ReadBuf;
12
13mod buffered;
14
15pub trait Socket: Send + Sync + Unpin + 'static {
16    fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result<usize>;
17
18    fn try_write(&mut self, buf: &[u8]) -> io::Result<usize>;
19
20    fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
21
22    fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
23
24    fn poll_flush(&mut self, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
25        // `flush()` is a no-op for TCP/UDS
26        Poll::Ready(Ok(()))
27    }
28
29    fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>>;
30
31    fn read<'a, B: ReadBuf>(&'a mut self, buf: &'a mut B) -> Read<'a, Self, B>
32    where
33        Self: Sized,
34    {
35        Read { socket: self, buf }
36    }
37
38    fn write<'a>(&'a mut self, buf: &'a [u8]) -> Write<'a, Self>
39    where
40        Self: Sized,
41    {
42        Write { socket: self, buf }
43    }
44
45    fn flush(&mut self) -> Flush<'_, Self>
46    where
47        Self: Sized,
48    {
49        Flush { socket: self }
50    }
51
52    fn shutdown(&mut self) -> Shutdown<'_, Self>
53    where
54        Self: Sized,
55    {
56        Shutdown { socket: self }
57    }
58}
59
60pub struct Read<'a, S: ?Sized, B> {
61    socket: &'a mut S,
62    buf: &'a mut B,
63}
64
65impl<'a, S: ?Sized, B> Future for Read<'a, S, B>
66where
67    S: Socket,
68    B: ReadBuf,
69{
70    type Output = io::Result<usize>;
71
72    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
73        let this = &mut *self;
74
75        while this.buf.has_remaining_mut() {
76            match this.socket.try_read(&mut *this.buf) {
77                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
78                    ready!(this.socket.poll_read_ready(cx))?;
79                }
80                ready => return Poll::Ready(ready),
81            }
82        }
83
84        Poll::Ready(Ok(0))
85    }
86}
87
88pub struct Write<'a, S: ?Sized> {
89    socket: &'a mut S,
90    buf: &'a [u8],
91}
92
93impl<'a, S: ?Sized> Future for Write<'a, S>
94where
95    S: Socket,
96{
97    type Output = io::Result<usize>;
98
99    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
100        let this = &mut *self;
101
102        while !this.buf.is_empty() {
103            match this.socket.try_write(this.buf) {
104                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
105                    ready!(this.socket.poll_write_ready(cx))?;
106                }
107                ready => return Poll::Ready(ready),
108            }
109        }
110
111        Poll::Ready(Ok(0))
112    }
113}
114
115pub struct Flush<'a, S: ?Sized> {
116    socket: &'a mut S,
117}
118
119impl<'a, S: Socket + ?Sized> Future for Flush<'a, S> {
120    type Output = io::Result<()>;
121
122    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
123        self.socket.poll_flush(cx)
124    }
125}
126
127pub struct Shutdown<'a, S: ?Sized> {
128    socket: &'a mut S,
129}
130
131impl<'a, S: ?Sized> Future for Shutdown<'a, S>
132where
133    S: Socket,
134{
135    type Output = io::Result<()>;
136
137    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
138        self.socket.poll_shutdown(cx)
139    }
140}
141
142pub trait WithSocket {
143    type Output;
144
145    fn with_socket<S: Socket>(
146        self,
147        socket: S,
148    ) -> impl std::future::Future<Output = Self::Output> + Send;
149}
150
151pub struct SocketIntoBox;
152
153impl WithSocket for SocketIntoBox {
154    type Output = Box<dyn Socket>;
155
156    async fn with_socket<S: Socket>(self, socket: S) -> Self::Output {
157        Box::new(socket)
158    }
159}
160
161impl<S: Socket + ?Sized> Socket for Box<S> {
162    fn try_read(&mut self, buf: &mut dyn ReadBuf) -> io::Result<usize> {
163        (**self).try_read(buf)
164    }
165
166    fn try_write(&mut self, buf: &[u8]) -> io::Result<usize> {
167        (**self).try_write(buf)
168    }
169
170    fn poll_read_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
171        (**self).poll_read_ready(cx)
172    }
173
174    fn poll_write_ready(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
175        (**self).poll_write_ready(cx)
176    }
177
178    fn poll_flush(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
179        (**self).poll_flush(cx)
180    }
181
182    fn poll_shutdown(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
183        (**self).poll_shutdown(cx)
184    }
185}
186
187pub async fn connect_tcp<Ws: WithSocket>(
188    host: &str,
189    port: u16,
190    with_socket: Ws,
191) -> crate::Result<Ws::Output> {
192    // IPv6 addresses in URLs will be wrapped in brackets and the `url` crate doesn't trim those.
193    let host = host.trim_matches(&['[', ']'][..]);
194
195    #[cfg(feature = "_rt-tokio")]
196    if crate::rt::rt_tokio::available() {
197        use tokio::net::TcpStream;
198
199        let stream = TcpStream::connect((host, port)).await?;
200        stream.set_nodelay(true)?;
201
202        return Ok(with_socket.with_socket(stream).await);
203    }
204
205    #[cfg(feature = "_rt-async-std")]
206    {
207        use async_io::Async;
208        use async_std::net::ToSocketAddrs;
209        use std::net::TcpStream;
210
211        let mut last_err = None;
212
213        // Loop through all the Socket Addresses that the hostname resolves to
214        for socket_addr in (host, port).to_socket_addrs().await? {
215            let stream = Async::<TcpStream>::connect(socket_addr)
216                .await
217                .and_then(|s| {
218                    s.get_ref().set_nodelay(true)?;
219                    Ok(s)
220                });
221            match stream {
222                Ok(stream) => return Ok(with_socket.with_socket(stream).await),
223                Err(e) => last_err = Some(e),
224            }
225        }
226
227        // If we reach this point, it means we failed to connect to any of the addresses.
228        // Return the last error we encountered, or a custom error if the hostname didn't resolve to any address.
229        match last_err {
230            Some(err) => Err(err.into()),
231            None => Err(io::Error::new(
232                io::ErrorKind::AddrNotAvailable,
233                "Hostname did not resolve to any addresses",
234            )
235            .into()),
236        }
237    }
238
239    #[cfg(not(feature = "_rt-async-std"))]
240    {
241        crate::rt::missing_rt((host, port, with_socket))
242    }
243}
244
245/// Connect a Unix Domain Socket at the given path.
246///
247/// Returns an error if Unix Domain Sockets are not supported on this platform.
248pub async fn connect_uds<P: AsRef<Path>, Ws: WithSocket>(
249    path: P,
250    with_socket: Ws,
251) -> crate::Result<Ws::Output> {
252    #[cfg(unix)]
253    {
254        #[cfg(feature = "_rt-tokio")]
255        if crate::rt::rt_tokio::available() {
256            use tokio::net::UnixStream;
257
258            let stream = UnixStream::connect(path).await?;
259
260            return Ok(with_socket.with_socket(stream).await);
261        }
262
263        #[cfg(feature = "_rt-async-std")]
264        {
265            use async_io::Async;
266            use std::os::unix::net::UnixStream;
267
268            let stream = Async::<UnixStream>::connect(path).await?;
269
270            Ok(with_socket.with_socket(stream).await)
271        }
272
273        #[cfg(not(feature = "_rt-async-std"))]
274        {
275            crate::rt::missing_rt((path, with_socket))
276        }
277    }
278
279    #[cfg(not(unix))]
280    {
281        drop((path, with_socket));
282
283        Err(io::Error::new(
284            io::ErrorKind::Unsupported,
285            "Unix domain sockets are not supported on this platform",
286        )
287        .into())
288    }
289}