vls_proxy/grpc/
incoming.rs

1use futures::Stream;
2use std::{
3    io,
4    net::SocketAddr,
5    pin::Pin,
6    task::{Context, Poll},
7};
8use tokio::net::{TcpListener, TcpStream};
9
10/// TcpIncoming encapsulates a TcpListener and holds the TCP configuration
11/// for nodelay so that every accepted connection is configured.
12pub struct TcpIncoming {
13    listener: TcpListener,
14    nodelay: bool,
15}
16
17impl TcpIncoming {
18    /// Binds a TcpListener to the given address and constructs a TcpIncoming
19    /// with the provided socket options.
20    pub async fn new(addr: SocketAddr, nodelay: bool) -> io::Result<Self> {
21        let listener = TcpListener::bind(addr).await?;
22        Ok(TcpIncoming { listener, nodelay })
23    }
24}
25
26impl Stream for TcpIncoming {
27    type Item = io::Result<TcpStream>;
28
29    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
30        match Pin::new(&self.listener).poll_accept(cx) {
31            Poll::Ready(Ok((stream, _peer_addr))) => {
32                stream.set_nodelay(self.nodelay)?;
33                return Poll::Ready(Some(Ok(stream)));
34            }
35            Poll::Ready(Err(e)) => Poll::Ready(Some(Err(e))),
36            Poll::Pending => Poll::Pending,
37        }
38    }
39}