-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathtcp.rs
More file actions
93 lines (78 loc) · 2.53 KB
/
tcp.rs
File metadata and controls
93 lines (78 loc) · 2.53 KB
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
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use async_std::net::TcpStream;
use async_trait::async_trait;
use deadpool::managed::{Manager, Object, RecycleResult};
use futures::io::{AsyncRead, AsyncWrite};
use futures::task::{Context, Poll};
use crate::Config;
#[derive(Clone)]
#[cfg_attr(not(feature = "rustls"), derive(std::fmt::Debug))]
pub(crate) struct TcpConnection {
addr: SocketAddr,
config: Arc<Config>,
}
impl TcpConnection {
pub(crate) fn new(addr: SocketAddr, config: Arc<Config>) -> Self {
Self { addr, config }
}
}
pub(crate) struct TcpConnWrapper {
conn: Object<TcpConnection>,
}
impl TcpConnWrapper {
pub(crate) fn new(conn: Object<TcpConnection>) -> Self {
Self { conn }
}
}
impl AsyncRead for TcpConnWrapper {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize, std::io::Error>> {
Pin::new(&mut *self.conn).poll_read(cx, buf)
}
}
impl AsyncWrite for TcpConnWrapper {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut *self.conn).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut *self.conn).poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut *self.conn).poll_close(cx)
}
}
#[async_trait]
impl Manager for TcpConnection {
type Type = TcpStream;
type Error = std::io::Error;
async fn create(&self) -> Result<TcpStream, std::io::Error> {
let tcp_stream = TcpStream::connect(self.addr).await?;
#[cfg(feature = "unstable-config")]
tcp_stream.set_nodelay(self.config.tcp_no_delay)?;
Ok(tcp_stream)
}
async fn recycle(&self, conn: &mut TcpStream) -> RecycleResult<std::io::Error> {
let mut buf = [0; 4];
let mut cx = Context::from_waker(futures::task::noop_waker_ref());
#[cfg(feature = "unstable-config")]
conn.set_nodelay(self.config.tcp_no_delay)?;
match Pin::new(conn).poll_read(&mut cx, &mut buf) {
Poll::Ready(Err(error)) => Err(error),
Poll::Ready(Ok(bytes)) if bytes == 0 => Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"connection appeared to be closed (EoF)",
)),
_ => Ok(()),
}?;
Ok(())
}
}