Skip to main content

viam_rust_utils/proxy/
uds.rs

1use hyper::server::accept::Accept;
2use rand::distributions::{Alphanumeric, DistString};
3use std::io::Error;
4use std::pin::Pin;
5use std::task::{Context, Poll};
6use tokio::net::{UnixListener, UnixStream};
7
8pub struct Connector {
9    inner: UnixListener,
10    path: String,
11}
12
13impl Connector {
14    pub fn new_with_path(path: String) -> Result<Self, Error> {
15        let uds = UnixListener::bind(&path)?;
16        Ok(Connector { inner: uds, path })
17    }
18    pub fn new() -> Result<Self, Error> {
19        let mut rname = Alphanumeric.sample_string(&mut rand::thread_rng(), 8);
20        rname = format!("/tmp/proxy-{}.sock", rname);
21        Self::new_with_path(rname)
22    }
23    pub fn get_path(&self) -> &str {
24        &self.path
25    }
26}
27
28impl Accept for Connector {
29    type Conn = UnixStream;
30    type Error = Error;
31
32    fn poll_accept(
33        self: Pin<&mut Self>,
34        cx: &mut Context<'_>,
35    ) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
36        match self.inner.poll_accept(cx) {
37            Poll::Pending => Poll::Pending,
38            Poll::Ready(Ok((socket, _addr))) => Poll::Ready(Some(Ok(socket))),
39            Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),
40        }
41    }
42}
43
44impl Drop for Connector {
45    fn drop(&mut self) {
46        std::fs::remove_file(&self.path).unwrap();
47    }
48}