use std::{io, net::SocketAddr, time::Duration};
use tokio::{
net::{TcpListener, TcpStream},
time::{Instant, sleep_until},
};
pub(super) type Accepted = (TcpStream, SocketAddr);
pub(super) struct Acceptor {
listener: TcpListener,
retry_at: Instant,
pressure_delay: Duration,
#[cfg(test)]
pub faults: std::collections::VecDeque<io::Error>,
#[cfg(test)]
pub attempts: usize,
}
impl Acceptor {
pub(super) fn new(listener: TcpListener) -> Self {
Self {
listener,
retry_at: Instant::now(),
pressure_delay: Duration::from_millis(10),
#[cfg(test)]
faults: std::collections::VecDeque::new(),
#[cfg(test)]
attempts: 0,
}
}
pub(super) fn local_addr(&self) -> io::Result<std::net::SocketAddr> {
self.listener.local_addr()
}
pub(super) async fn accept(&mut self) -> io::Result<Accepted> {
loop {
sleep_until(self.retry_at).await;
let accepted = self.next().await;
match accepted {
Ok(stream) => {
self.pressure_delay = Duration::from_millis(10);
return Ok(stream);
}
Err(error) => {
let delay = match classify(&error) {
Retry::Connection => Duration::from_millis(1),
Retry::Pressure => {
let delay = self.pressure_delay;
self.pressure_delay = (delay * 2).min(Duration::from_millis(250));
delay
}
Retry::Fatal => return Err(error),
};
tracing::info!(kind = ?error.kind(), retry_ms = delay.as_millis() as u64, "accept retry");
self.retry_at = Instant::now() + delay;
}
}
}
}
async fn next(&mut self) -> io::Result<Accepted> {
#[cfg(test)]
{
self.attempts += 1;
if let Some(error) = self.faults.pop_front() {
return Err(error);
}
}
self.listener.accept().await
}
}
enum Retry {
Connection,
Pressure,
Fatal,
}
fn classify(error: &io::Error) -> Retry {
use io::ErrorKind;
#[cfg(unix)]
if error.raw_os_error().is_some_and(|code| {
[libc::EMFILE, libc::ENFILE, libc::ENOBUFS, libc::ENOMEM].contains(&code)
}) {
return Retry::Pressure;
}
#[cfg(target_os = "linux")]
if error.raw_os_error().is_some_and(|code| {
[
libc::ENETDOWN,
libc::EPROTO,
libc::ENOPROTOOPT,
libc::EHOSTDOWN,
libc::ENONET,
libc::EHOSTUNREACH,
libc::EOPNOTSUPP,
libc::ENETUNREACH,
]
.contains(&code)
}) {
return Retry::Connection;
}
match error.kind() {
ErrorKind::ConnectionAborted
| ErrorKind::ConnectionReset
| ErrorKind::Interrupted
| ErrorKind::TimedOut
| ErrorKind::NetworkDown
| ErrorKind::NetworkUnreachable
| ErrorKind::HostUnreachable => Retry::Connection,
ErrorKind::WouldBlock | ErrorKind::OutOfMemory => Retry::Pressure,
_ => Retry::Fatal,
}
}
#[cfg(test)]
#[path = "acceptor_test.rs"]
mod acceptor_test;