use std::{io, time::Duration};
use rho_protocol::CloseOnShutdown;
use tokio::net::windows::named_pipe::{NamedPipeClient, NamedPipeServer};
use super::{
files::DaemonPathError,
pipe::{self, Opened, PipeServer},
};
use crate::daemon::paths::{DaemonPaths, SocketFound};
const RESTART_POLL_INTERVAL: Duration = Duration::from_millis(10);
pub(crate) type Stream = CloseOnShutdown<NamedPipeClient>;
pub(in crate::daemon) struct Listener {
pipe: Option<PipeServer>,
}
impl Listener {
pub(in crate::daemon) fn bind(paths: &DaemonPaths) -> io::Result<Self> {
Ok(Self {
pipe: Some(PipeServer::create(paths.socket.as_os_str())?),
})
}
pub(in crate::daemon) async fn accept(&mut self) -> io::Result<NamedPipeServer> {
match &mut self.pipe {
Some(pipe) => pipe.accept().await,
None => std::future::pending().await,
}
}
pub(in crate::daemon) fn hold_for_restart(&mut self) {
self.pipe = None;
}
}
pub(in crate::daemon) fn remove_endpoint(_paths: &DaemonPaths) -> io::Result<()> {
Ok(())
}
pub(in crate::daemon) async fn connect(paths: &DaemonPaths) -> io::Result<Option<Stream>> {
Ok(pipe::open(paths.socket.as_os_str())
.await?
.map(CloseOnShutdown::new))
}
pub(in crate::daemon) async fn connect_restarting(
paths: &DaemonPaths,
) -> io::Result<Option<Stream>> {
let pipe = paths.socket.as_os_str();
loop {
match pipe::try_open(pipe)? {
Opened::Client(stream) => return Ok(Some(CloseOnShutdown::new(stream))),
Opened::Foreign => return Err(pipe::foreign(pipe)),
Opened::Missing | Opened::Busy => {}
}
tokio::time::sleep(RESTART_POLL_INTERVAL).await;
}
}
pub(in crate::daemon) fn inspect_endpoint(
paths: &DaemonPaths,
) -> Result<SocketFound, DaemonPathError> {
let unreadable = |message: String| DaemonPathError::Unreadable {
path: paths.socket.clone(),
message,
};
match pipe::probe(paths.socket.as_os_str()) {
Ok(Opened::Client(_)) => Ok(SocketFound::Private),
Ok(Opened::Missing) => Ok(SocketFound::Missing),
Ok(Opened::Busy) => Err(unreadable(
"every instance of the pipe is taken; retry".to_owned(),
)),
Ok(Opened::Foreign) => Err(DaemonPathError::ForeignPipe {
path: paths.socket.clone(),
}),
Err(error) => Err(unreadable(error.to_string())),
}
}