1use std::io;
19use std::path::{Path, PathBuf};
20use std::time::Duration;
21
22use thiserror::Error;
23use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
24use tokio::net::UnixStream;
25use tokio::time::timeout;
26
27use crate::protocol::{Request, Response};
28
29pub const DIAL_TIMEOUT: Duration = Duration::from_secs(2);
34
35#[derive(Debug, Error)]
36pub enum ClientError {
37 #[error("could not reach daemon at {path}: {source}")]
38 Connect {
39 path: PathBuf,
40 #[source]
41 source: io::Error,
42 },
43 #[error("daemon timed out after {timeout:?} at {path}")]
44 Timeout { path: PathBuf, timeout: Duration },
45 #[error("i/o while talking to daemon at {path}: {source}")]
46 Io {
47 path: PathBuf,
48 #[source]
49 source: io::Error,
50 },
51 #[error("daemon sent unparseable reply at {path}: {source}")]
52 Parse {
53 path: PathBuf,
54 #[source]
55 source: serde_json::Error,
56 },
57 #[error("daemon closed connection before replying at {path}")]
58 Closed { path: PathBuf },
59}
60
61#[derive(Debug, Clone)]
64pub struct Client {
65 socket_path: PathBuf,
66 timeout: Duration,
67}
68
69impl Client {
70 #[must_use]
71 pub fn new(socket_path: impl Into<PathBuf>) -> Self {
72 Self {
73 socket_path: socket_path.into(),
74 timeout: DIAL_TIMEOUT,
75 }
76 }
77
78 #[must_use]
81 pub fn with_timeout(mut self, t: Duration) -> Self {
82 self.timeout = t;
83 self
84 }
85
86 #[must_use]
87 pub fn socket_path(&self) -> &Path {
88 &self.socket_path
89 }
90
91 #[must_use]
96 pub fn socket_exists(&self) -> bool {
97 self.socket_path.exists()
98 }
99
100 pub async fn send(&self, req: &Request) -> Result<Response, ClientError> {
103 let fut = async {
104 let stream = UnixStream::connect(&self.socket_path)
105 .await
106 .map_err(|source| ClientError::Connect {
107 path: self.socket_path.clone(),
108 source,
109 })?;
110
111 let (read_half, mut write_half) = stream.into_split();
112 let mut line = serde_json::to_string(req).map_err(|source| ClientError::Parse {
113 path: self.socket_path.clone(),
114 source,
115 })?;
116 line.push('\n');
117
118 write_half
119 .write_all(line.as_bytes())
120 .await
121 .map_err(|source| ClientError::Io {
122 path: self.socket_path.clone(),
123 source,
124 })?;
125 write_half.flush().await.map_err(|source| ClientError::Io {
126 path: self.socket_path.clone(),
127 source,
128 })?;
129
130 let mut reader = BufReader::new(read_half);
131 let mut response_line = String::new();
132 let n = reader
133 .read_line(&mut response_line)
134 .await
135 .map_err(|source| ClientError::Io {
136 path: self.socket_path.clone(),
137 source,
138 })?;
139 if n == 0 {
140 return Err(ClientError::Closed {
141 path: self.socket_path.clone(),
142 });
143 }
144 let trimmed = response_line.trim_end_matches(['\r', '\n']);
145 serde_json::from_str::<Response>(trimmed).map_err(|source| ClientError::Parse {
146 path: self.socket_path.clone(),
147 source,
148 })
149 };
150
151 match timeout(self.timeout, fut).await {
152 Ok(r) => r,
153 Err(_) => Err(ClientError::Timeout {
154 path: self.socket_path.clone(),
155 timeout: self.timeout,
156 }),
157 }
158 }
159}