Skip to main content

zero_headless/
client.rs

1//! Client-side dialer for the daemon.
2//!
3//! Used by the `zero-commands` real `SupervisorSource` adapter
4//! and by the integration tests. A thin wrapper over a
5//! `UnixStream`: one request per dial, line-delimited JSON,
6//! hard-timed.
7//!
8//! # Why one-shot
9//!
10//! The CLI is the supervisor's client, not a long-lived
11//! session. Every dial is a discrete intent ("arm", "disarm",
12//! "kill", "how are you"). Reusing a connection would save a
13//! handful of microseconds at the cost of having to reason
14//! about a half-closed socket during a kill-switch round-trip.
15//! We trade throughput for clarity here — the supervisor fields
16//! human-scale request rates.
17
18use 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
29/// Total round-trip budget for a single dial. Generous: the
30/// daemon's hottest path is a local socket write + in-memory
31/// state flip + JSON serialize. If we don't have an answer in
32/// 2 s the daemon is wedged and the operator should know.
33pub 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/// Dialer pinned at a socket path. Cheap to construct; the
62/// actual `UnixStream` is opened per-request.
63#[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    /// Override the per-request timeout. Tests rely on this to
79    /// distinguish "daemon down" from "daemon slow".
80    #[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    /// Returns `true` if the socket file exists. Not a
92    /// liveness check — a stale socket (daemon crashed
93    /// without cleanup) will still return `true` and the next
94    /// [`Self::send`] will surface the real failure mode.
95    #[must_use]
96    pub fn socket_exists(&self) -> bool {
97        self.socket_path.exists()
98    }
99
100    /// Send a single request and wait for a single reply. All
101    /// I/O is bounded by [`Self::with_timeout`].
102    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}