about summary refs log tree commit diff
path: root/gatherer-client/src/lib.rs
blob: 4a75d12ccdf1ccc822bccc5d30b506122c5de6a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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<Connection, Error> {
		Ok(Connection::new(&self.socket_path)?)
	}
}

pub struct Connection {
	stream: UnixStream,
}

impl Connection {
	pub(crate) fn new(path: &Utf8Path) -> Result<Connection, Error> {
		let stream = UnixStream::connect(path).map_err(|_| Error::ConnectionFailed)?;
		Ok(Self { stream })
	}

	pub fn graph_bounds(&mut self) -> Result<response::GraphBounds, Error> {
		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<response::GeneratedGraphs, Error> {
		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<response::GeneratedGraphs, Error> {
		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<Response, Error> {
		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,
}