use std::{io, path::PathBuf, time::Duration};
use super::{
paths::DaemonPaths,
platform::{self, Stream},
};
use rho_protocol::{Client, ClientError, ClientHello, ClientInfo, HelloResponse, Notifications};
pub(crate) const DAEMON_RESTART_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Debug, thiserror::Error)]
pub(crate) enum ConnectError {
#[error("rho daemon is not running")]
NotRunning,
#[error("could not connect to the rho daemon at {socket}: {source}")]
Io { socket: PathBuf, source: io::Error },
#[error(transparent)]
Handshake(#[from] ClientError),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ConnectAs {
Frontend,
Command,
Agent,
}
impl ConnectAs {
pub(crate) fn hello(self) -> ClientHello {
let client = ClientInfo {
name: "rho-cli".to_owned(),
version: env!("CARGO_PKG_VERSION").to_owned(),
};
match self {
Self::Frontend => ClientHello::frontend(client),
Self::Command => ClientHello::command(client),
Self::Agent => ClientHello::agent(client),
}
}
}
pub(crate) struct Connection {
pub(crate) client: Client,
pub(crate) notifications: Notifications,
pub(crate) hello: HelloResponse,
}
pub(crate) async fn connect(
paths: &DaemonPaths,
hello: ClientHello,
) -> Result<Connection, ConnectError> {
handshake(paths, platform::connect(paths).await, hello).await
}
pub(crate) async fn connect_restarting(
paths: &DaemonPaths,
hello: ClientHello,
) -> Result<Connection, ConnectError> {
handshake(paths, platform::connect_restarting(paths).await, hello).await
}
async fn handshake(
paths: &DaemonPaths,
connected: io::Result<Option<Stream>>,
hello: ClientHello,
) -> Result<Connection, ConnectError> {
let stream = match connected {
Ok(Some(stream)) => stream,
Ok(None) => return Err(ConnectError::NotRunning),
Err(source) => {
return Err(ConnectError::Io {
socket: paths.socket.clone(),
source,
})
}
};
let (client, notifications, hello) = Client::handshake(stream, hello).await?;
Ok(Connection {
client,
notifications,
hello,
})
}