about summary refs log tree commit diff
path: root/tvix/store/src/listener/mod.rs
blob: ed1220803562ac5e818b04ea0290504b688923fd (plain) (blame)
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use std::{
    io,
    ops::{Deref, DerefMut},
    pin::Pin,
    task::{Context, Poll},
};

use futures::Stream;
use pin_project_lite::pin_project;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_listener::{Listener, ListenerAddress};
use tonic::transport::server::{Connected, TcpConnectInfo, UdsConnectInfo};

/// A wrapper around a [Listener] which implements the [Stream] trait.
/// Mainly used to bridge [tokio_listener] with [tonic].
pub struct ListenerStream {
    inner: Listener,
}

impl ListenerStream {
    /// Convert a [Listener] into a [Stream].
    pub fn new(inner: Listener) -> Self {
        Self { inner }
    }

    /// Binds to the specified address and returns a [Stream] of connections.
    pub async fn bind(addr: &ListenerAddress) -> io::Result<Self> {
        let listener = Listener::bind(addr, &Default::default(), &Default::default()).await?;

        Ok(Self::new(listener))
    }
}

impl Stream for ListenerStream {
    type Item = io::Result<Connection>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        match self.inner.poll_accept(cx) {
            Poll::Ready(Ok((connection, _))) => Poll::Ready(Some(Ok(Connection::new(connection)))),
            Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),
            Poll::Pending => Poll::Pending,
        }
    }
}

pin_project! {
    /// A wrapper around a [tokio_listener::Connection] that implements the [Connected] trait
    /// so it is compatible with [tonic].
    pub struct Connection {
        #[pin]
        inner: tokio_listener::Connection,
    }
}

impl Connection {
    fn new(inner: tokio_listener::Connection) -> Self {
        Self { inner }
    }
}

impl Deref for Connection {
    type Target = tokio_listener::Connection;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for Connection {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

#[derive(Clone)]
pub enum ListenerConnectInfo {
    TCP(TcpConnectInfo),
    Unix(UdsConnectInfo),
    Stdio,
    Other,
}

impl Connected for Connection {
    type ConnectInfo = ListenerConnectInfo;

    fn connect_info(&self) -> Self::ConnectInfo {
        if let Some(tcp_stream) = self.try_borrow_tcp() {
            ListenerConnectInfo::TCP(tcp_stream.connect_info())
        } else if let Some(unix_stream) = self.try_borrow_unix() {
            ListenerConnectInfo::Unix(unix_stream.connect_info())
        } else if let Some(_) = self.try_borrow_stdio() {
            ListenerConnectInfo::Stdio
        } else {
            ListenerConnectInfo::Other
        }
    }
}

impl AsyncRead for Connection {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        self.project().inner.poll_read(cx, buf)
    }
}

impl AsyncWrite for Connection {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &[u8],
    ) -> Poll<std::result::Result<usize, io::Error>> {
        self.project().inner.poll_write(cx, buf)
    }

    fn poll_flush(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<std::result::Result<(), io::Error>> {
        self.project().inner.poll_flush(cx)
    }

    fn poll_shutdown(
        self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<std::result::Result<(), io::Error>> {
        self.project().inner.poll_shutdown(cx)
    }
}