1use std::{
2 fmt,
3 future::Future,
4 pin::Pin,
5 sync::Arc,
6 task::{Context, Poll},
7};
8
9use pin_project_lite::pin_project;
10use tokio::{
11 io::{self, AsyncRead, AsyncWrite},
12 sync::{OwnedSemaphorePermit, Semaphore},
13};
14
15pub trait Listener: Send + 'static {
17 type Io: AsyncRead + AsyncWrite + Unpin + Send + 'static;
19
20 type Addr: Send;
22
23 fn accept(&mut self) -> impl Future<Output = (Self::Io, Self::Addr)> + Send;
28
29 fn local_addr(&self) -> io::Result<Self::Addr>;
31}
32
33#[cfg(not(target_arch = "wasm32"))]
34impl Listener for tokio::net::TcpListener {
35 type Io = tokio::net::TcpStream;
36 type Addr = std::net::SocketAddr;
37
38 async fn accept(&mut self) -> (Self::Io, Self::Addr) {
39 loop {
40 match Self::accept(self).await {
41 Ok(tup) => {
42 let _ = tup.0.set_nodelay(true);
43 return tup;
44 }
45 Err(e) => handle_accept_error(e).await,
46 }
47 }
48 }
49
50 #[inline]
51 fn local_addr(&self) -> io::Result<Self::Addr> {
52 Self::local_addr(self)
53 }
54}
55
56#[cfg(unix)]
57impl Listener for tokio::net::UnixListener {
58 type Io = tokio::net::UnixStream;
59 type Addr = tokio::net::unix::SocketAddr;
60
61 async fn accept(&mut self) -> (Self::Io, Self::Addr) {
62 loop {
63 match Self::accept(self).await {
64 Ok(tup) => return tup,
65 Err(e) => handle_accept_error(e).await,
66 }
67 }
68 }
69
70 #[inline]
71 fn local_addr(&self) -> io::Result<Self::Addr> {
72 Self::local_addr(self)
73 }
74}
75
76pub trait ListenerExt: Listener + Sized {
78 fn limit_connections(self, limit: usize) -> ConnLimiter<Self> {
90 ConnLimiter {
91 listener: self,
92 sem: Arc::new(Semaphore::new(limit)),
93 }
94 }
95
96 fn tap_io<F>(self, tap_fn: F) -> TapIo<Self, F>
119 where
120 F: FnMut(&mut Self::Io) + Send + 'static,
121 {
122 TapIo {
123 listener: self,
124 tap_fn,
125 }
126 }
127}
128
129impl<L: Listener> ListenerExt for L {}
130
131#[derive(Debug)]
135pub struct ConnLimiter<T> {
136 listener: T,
137 sem: Arc<Semaphore>,
138}
139
140impl<T: Listener> Listener for ConnLimiter<T> {
141 type Io = ConnLimiterIo<T::Io>;
142 type Addr = T::Addr;
143
144 async fn accept(&mut self) -> (Self::Io, Self::Addr) {
145 let permit = self.sem.clone().acquire_owned().await.unwrap();
146 let (io, addr) = self.listener.accept().await;
147 (ConnLimiterIo { io, permit }, addr)
148 }
149
150 fn local_addr(&self) -> tokio::io::Result<Self::Addr> {
151 self.listener.local_addr()
152 }
153}
154
155pin_project! {
156 #[derive(Debug)]
160 pub struct ConnLimiterIo<T> {
161 #[pin]
162 io: T,
163 permit: OwnedSemaphorePermit,
164 }
165}
166
167impl<T: AsyncRead> AsyncRead for ConnLimiterIo<T> {
169 fn poll_read(
170 self: Pin<&mut Self>,
171 cx: &mut Context<'_>,
172 buf: &mut io::ReadBuf<'_>,
173 ) -> Poll<io::Result<()>> {
174 self.project().io.poll_read(cx, buf)
175 }
176}
177
178impl<T: AsyncWrite> AsyncWrite for ConnLimiterIo<T> {
180 fn is_write_vectored(&self) -> bool {
181 self.io.is_write_vectored()
182 }
183
184 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
185 self.project().io.poll_flush(cx)
186 }
187
188 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
189 self.project().io.poll_shutdown(cx)
190 }
191
192 fn poll_write(
193 self: Pin<&mut Self>,
194 cx: &mut Context<'_>,
195 buf: &[u8],
196 ) -> Poll<io::Result<usize>> {
197 self.project().io.poll_write(cx, buf)
198 }
199
200 fn poll_write_vectored(
201 self: Pin<&mut Self>,
202 cx: &mut Context<'_>,
203 bufs: &[std::io::IoSlice<'_>],
204 ) -> Poll<io::Result<usize>> {
205 self.project().io.poll_write_vectored(cx, bufs)
206 }
207}
208
209pub struct TapIo<L, F> {
213 listener: L,
214 tap_fn: F,
215}
216
217impl<L, F> fmt::Debug for TapIo<L, F>
218where
219 L: Listener + fmt::Debug,
220{
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 f.debug_struct("TapIo")
223 .field("listener", &self.listener)
224 .finish_non_exhaustive()
225 }
226}
227
228impl<L, F> Listener for TapIo<L, F>
229where
230 L: Listener,
231 F: FnMut(&mut L::Io) + Send + 'static,
232{
233 type Io = L::Io;
234 type Addr = L::Addr;
235
236 async fn accept(&mut self) -> (Self::Io, Self::Addr) {
237 let (mut io, addr) = self.listener.accept().await;
238 (self.tap_fn)(&mut io);
239 (io, addr)
240 }
241
242 fn local_addr(&self) -> io::Result<Self::Addr> {
243 self.listener.local_addr()
244 }
245}
246
247#[cfg(not(target_arch = "wasm32"))]
248async fn handle_accept_error(e: io::Error) {
249 if is_connection_error(&e) {
250 return;
251 }
252
253 error!("accept error: {e}");
265 tokio::time::sleep(std::time::Duration::from_secs(1)).await;
266}
267
268#[cfg(not(target_arch = "wasm32"))]
269fn is_connection_error(e: &io::Error) -> bool {
270 matches!(
271 e.kind(),
272 io::ErrorKind::ConnectionRefused
273 | io::ErrorKind::ConnectionAborted
274 | io::ErrorKind::ConnectionReset
275 )
276}
277
278#[cfg(test)]
279mod tests {
280 use std::sync::atomic::{AtomicUsize, Ordering};
281
282 use tokio::{io, time};
283
284 use super::{Listener, ListenerExt};
285
286 #[tokio::test]
287 async fn tcp_listener_sets_nodelay() {
288 let mut listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
289 let addr = Listener::local_addr(&listener).unwrap();
290 let _client = tokio::net::TcpStream::connect(addr).await.unwrap();
291
292 let (stream, _) = Listener::accept(&mut listener).await;
293
294 assert!(stream.nodelay().unwrap());
295 }
296
297 #[tokio::test]
298 async fn tap_io_can_unset_nodelay() {
299 let mut listener = tokio::net::TcpListener::bind("127.0.0.1:0")
300 .await
301 .unwrap()
302 .tap_io(|stream| stream.set_nodelay(false).unwrap());
303 let addr = listener.local_addr().unwrap();
304 let _client = tokio::net::TcpStream::connect(addr).await.unwrap();
305
306 let (stream, _) = listener.accept().await;
307
308 assert!(!stream.nodelay().unwrap());
309 }
310
311 #[tokio::test(start_paused = true)]
312 async fn limit_connections() {
313 static COUNT: AtomicUsize = AtomicUsize::new(0);
314
315 struct MyListener;
316
317 impl Listener for MyListener {
318 type Io = io::DuplexStream;
319 type Addr = ();
320
321 async fn accept(&mut self) -> (Self::Io, Self::Addr) {
322 COUNT.fetch_add(1, Ordering::SeqCst);
323 (io::duplex(0).0, ()) }
325
326 fn local_addr(&self) -> io::Result<Self::Addr> {
327 Ok(())
328 }
329 }
330
331 let mut listener = MyListener.limit_connections(1);
332
333 assert_eq!(COUNT.load(Ordering::SeqCst), 0);
334
335 let conn1 = listener.accept().await;
337 assert_eq!(COUNT.load(Ordering::SeqCst), 1);
338
339 time::timeout(time::Duration::from_secs(1), listener.accept())
340 .await
341 .expect_err("Second 'accept' should time out.");
342 assert_eq!(COUNT.load(Ordering::SeqCst), 1);
344
345 drop(conn1);
347
348 let _conn2 = listener.accept().await;
350 assert_eq!(COUNT.load(Ordering::SeqCst), 2);
351 }
352}