use std::{io, path::Path};
use hyper::server::{Builder, Server};
use conn::SocketIncoming;
pub(crate) mod conn {
use hyper::server::accept::Accept;
use pin_project_lite::pin_project;
use std::{
io,
path::Path,
pin::Pin,
task::{Context, Poll},
thread,
};
use tokio::sync::mpsc;
use uds_windows::UnixListener;
use crate::windows::convert_unix_stream_to_nb_tcp_stream;
pin_project! {
#[derive(Debug)]
pub struct SocketIncoming {
rx: mpsc::Receiver<std::net::TcpStream>,
}
}
impl SocketIncoming {
pub fn bind(path: impl AsRef<Path>) -> Result<Self, std::io::Error> {
let listener = UnixListener::bind(path)?;
Ok(Self::from_listener(listener))
}
#[allow(clippy::must_use_candidate)]
pub fn from_listener(listener: UnixListener) -> Self {
let (tx, rx) = mpsc::channel(32);
thread::spawn(move || {
while let Ok((socket, _addr)) = listener.accept() {
let tcp_stream = convert_unix_stream_to_nb_tcp_stream(socket);
if tx.blocking_send(tcp_stream).is_err() {
break;
}
}
});
Self { rx }
}
}
impl Accept for SocketIncoming {
type Conn = tokio::net::TcpStream;
type Error = io::Error;
fn poll_accept(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
self.project()
.rx
.poll_recv(cx)
.map(|t| t.map(tokio::net::TcpStream::from_std))
}
}
impl From<UnixListener> for SocketIncoming {
fn from(listener: UnixListener) -> Self {
Self::from_listener(listener)
}
}
}
pub trait UnixServerExt {
#[allow(clippy::missing_errors_doc)]
fn bind_unix(path: impl AsRef<Path>) -> Result<Builder<SocketIncoming>, io::Error>;
}
impl UnixServerExt for Server<SocketIncoming, ()> {
fn bind_unix(path: impl AsRef<Path>) -> Result<Builder<SocketIncoming>, io::Error> {
let incoming = SocketIncoming::bind(path)?;
Ok(Server::builder(incoming))
}
}