use std::os::unix::net::UnixStream; use camino::{Utf8Path, Utf8PathBuf}; use gatherer_api::{ request::{self, Request}, response::{self, Response}, }; pub use gatherer_api::response::{GeneratedGraphs, GraphBounds}; pub struct Client { socket_path: Utf8PathBuf, } impl Client { pub fn new(socket_path: Utf8PathBuf) -> Self { Self { socket_path } } pub fn connect(&self) -> Result { Ok(Connection::new(&self.socket_path)?) } } pub struct Connection { stream: UnixStream, } impl Connection { pub(crate) fn new(path: &Utf8Path) -> Result { let stream = UnixStream::connect(path).map_err(|_| Error::ConnectionFailed)?; Ok(Self { stream }) } pub fn graph_bounds(&mut self) -> Result { let request = Request::new(request::Message::GetGraphBounds); request .send(&mut self.stream) .map_err(|_| Error::SendError)?; let response = self.get_response()?; response.get_body().map_err(|_| Error::ReceiveError) } pub fn generate_graphs( &mut self, root: Utf8PathBuf, ) -> Result { let request = Request::new(request::Message::GenerateGraphs) .with_body(request::GenerateGraphsBody { directory: root }) .map_err(|_| Error::SendError)?; request .send(&mut self.stream) .map_err(|_| Error::SendError)?; let response = self.get_response()?; response.get_body().map_err(|_| Error::ReceiveError) } pub fn regular_graphs(&mut self) -> Result { let request = Request::new(request::Message::GetRegularGraphs); request .send(&mut self.stream) .map_err(|_| Error::SendError)?; let response = self.get_response()?; response.get_body().map_err(|_| Error::ReceiveError) } fn get_response(&mut self) -> Result { let mut buffer = vec![0; 8096]; let count = gatherer_api::read_packet(&mut self.stream, &mut buffer) .map_err(|_| Error::ReceiveError)?; tracing::trace!("read {count} bytes"); Response::from_buffer(&buffer[..count]).map_err(|_| Error::SendError) } } #[derive(Debug, PartialEq)] pub enum Error { ConnectionFailed, SendError, ReceiveError, }