Skip to main content

sail_api/
client.rs

1//! The thin daemon client used by `sail-z3` (ADR 0011).
2//!
3//! Every call has timeouts. Any failure is reported as an error, which the
4//! shim treats as a miss and falls back to the pinned solver.
5
6use socket2::{Domain, SockAddr, Socket, Type};
7use std::io::Write as _;
8use std::os::unix::net::UnixStream;
9use std::path::Path;
10use std::time::Duration;
11
12use crate::protocol::{
13    Identity, Info, PutMeta, Request, StatsSnapshot, read_response, split_status_payload,
14};
15
16/// Timeout for each request/response exchange.
17pub const TIMEOUT: Duration = Duration::from_secs(10);
18
19/// Connect deadline for service-presence probes and best-effort wakeups.
20pub const PROBE_TIMEOUT: Duration = Duration::from_millis(25);
21
22/// Most `PUT`s [`Client::put_all`] sends before reading their
23/// acknowledgements. The unread acknowledgements stay far below any socket
24/// buffer, so the daemon never blocks writing them while the client writes.
25const PUT_WINDOW: usize = 64;
26
27/// Connect to a Unix endpoint with a bounded connect and per-operation I/O timeouts.
28///
29/// # Errors
30/// Returns connection/configuration errors, including an unavailable or full
31/// listener, expiration of `timeout`, or a zero `timeout`.
32pub fn connect_stream(path: &Path, timeout: Duration) -> std::io::Result<UnixStream> {
33    if timeout.is_zero() {
34        return Err(std::io::Error::new(
35            std::io::ErrorKind::InvalidInput,
36            "Unix connection timeout must be nonzero",
37        ));
38    }
39    // Setting read/write timeouts after a blocking connect leaves a saturated
40    // listener backlog unbounded. The runtime client already uses this safe,
41    // nonblocking-connect implementation on both supported platforms.
42    let socket = Socket::new(Domain::UNIX, Type::STREAM, None)?;
43    socket.connect_timeout(&SockAddr::unix(path)?, timeout)?;
44    let fd: std::os::fd::OwnedFd = socket.into();
45    let stream = UnixStream::from(fd);
46    stream.set_read_timeout(Some(timeout))?;
47    stream.set_write_timeout(Some(timeout))?;
48    Ok(stream)
49}
50
51/// Check whether an endpoint accepts a connection without waiting indefinitely.
52///
53/// `false` means only that the path is absent or the connection was refused.
54/// A successful probe establishes listener presence, not protocol readiness.
55/// Some platforms also refuse connections when a live listener's queue is full;
56/// this probe does not distinguish that refusal from a stale socket.
57///
58/// # Errors
59/// Returns every other connection error, including a full listener backlog,
60/// timeout or denied access. These errors never establish that a socket is stale.
61pub fn probe_listener(path: &Path) -> std::io::Result<bool> {
62    match connect_stream(path, PROBE_TIMEOUT) {
63        Ok(_) => Ok(true),
64        Err(error)
65            if matches!(
66                error.kind(),
67                std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused
68            ) =>
69        {
70            Ok(false)
71        }
72        Err(error) => Err(error),
73    }
74}
75
76/// A connection to the daemon.
77#[derive(Debug)]
78pub struct Client {
79    stream: UnixStream,
80}
81
82impl Client {
83    /// Connects to the daemon socket at `path`.
84    ///
85    /// # Errors
86    ///
87    /// Connection errors.
88    pub fn connect(path: &Path) -> std::io::Result<Self> {
89        Self::connect_with_timeout(path, TIMEOUT)
90    }
91
92    /// Connects to the daemon socket at `path`, with `timeout` for the connect and each
93    /// read and write instead of [`TIMEOUT`].
94    ///
95    /// # Errors
96    ///
97    /// Connection errors, or a zero `timeout`.
98    pub fn connect_with_timeout(path: &Path, timeout: Duration) -> std::io::Result<Self> {
99        Ok(Self {
100            stream: connect_stream(path, timeout)?,
101        })
102    }
103
104    fn call(&mut self, req: &Request) -> std::io::Result<Vec<u8>> {
105        req.write(&mut self.stream)?;
106        read_response(&mut self.stream)
107    }
108
109    /// The identity of the solver at `solver_path`.
110    ///
111    /// # Errors
112    ///
113    /// I/O errors, or the daemon's error message.
114    pub fn hello(&mut self, solver_path: &str) -> std::io::Result<Identity> {
115        self.hello_in_mode(solver_path, crate::protocol::VerificationMode::Default)
116    }
117
118    /// Identifies a solver and negotiates the connection's cache namespace.
119    ///
120    /// Call once before any cache lookup or store. A failed or repeated
121    /// handshake retires the connection; connect again to retry.
122    ///
123    /// # Errors
124    ///
125    /// I/O errors, a rejected handshake, or a stale daemon protocol.
126    pub fn hello_in_mode(
127        &mut self,
128        solver_path: &str,
129        mode: crate::protocol::VerificationMode,
130    ) -> std::io::Result<Identity> {
131        let body = self.call(&Request::Hello(crate::protocol::Hello {
132            solver_path: solver_path.to_owned(),
133            mode,
134        }))?;
135        let (status, payload) = split_status_payload(&body)?;
136        if status == 0 {
137            let id: Identity = serde_json::from_slice(payload).map_err(std::io::Error::other)?;
138            if id.protocol_version == crate::protocol::PROTOCOL_VERSION {
139                Ok(id)
140            } else {
141                Err(std::io::Error::other(format!(
142                    "daemon speaks protocol {}, client {}",
143                    id.protocol_version,
144                    crate::protocol::PROTOCOL_VERSION
145                )))
146            }
147        } else {
148            Err(std::io::Error::other(
149                String::from_utf8_lossy(payload).into_owned(),
150            ))
151        }
152    }
153
154    /// The cached reply for `key`, or `None` on a miss.
155    /// Requires a successful [`Self::hello`] or [`Self::hello_in_mode`].
156    ///
157    /// # Errors
158    ///
159    /// I/O errors.
160    pub fn get(&mut self, key: &[u8; 32]) -> std::io::Result<Option<Vec<u8>>> {
161        Ok(self.get_with_effort(key)?.map(|(reply, _)| reply))
162    }
163
164    /// The cached reply for `key` with its recorded effort, if the daemon
165    /// sent one, or `None` on a miss.
166    ///
167    /// # Errors
168    ///
169    /// I/O errors.
170    pub fn get_with_effort(
171        &mut self,
172        key: &[u8; 32],
173    ) -> std::io::Result<Option<(Vec<u8>, Option<crate::protocol::Effort>)>> {
174        let body = self.call(&Request::Get(*key))?;
175        let (status, payload) = split_status_payload(&body)?;
176        if status != 1 {
177            return Ok(None);
178        }
179        Ok(Some((
180            payload.to_vec(),
181            crate::protocol::get_effort_trailer(&body),
182        )))
183    }
184
185    /// Stores `reply` for `key`.
186    /// Requires a successful [`Self::hello`] or [`Self::hello_in_mode`].
187    ///
188    /// # Errors
189    ///
190    /// I/O errors.
191    pub fn put(&mut self, key: &[u8; 32], meta: PutMeta, reply: Vec<u8>) -> std::io::Result<()> {
192        self.call(&Request::Put {
193            key: *key,
194            meta,
195            reply,
196        })
197        .map(|_| ())
198    }
199
200    /// Stores every `(key, meta, reply)` in order, sending up to a window of
201    /// requests before reading their acknowledgements, so a session's stores
202    /// cost a few round trips instead of one each. The daemon answers each
203    /// request in order, exactly as for [`Client::put`].
204    ///
205    /// # Errors
206    ///
207    /// I/O errors. Stores before the failing window may have been made.
208    pub fn put_all(
209        &mut self,
210        puts: impl IntoIterator<Item = ([u8; 32], PutMeta, Vec<u8>)>,
211    ) -> std::io::Result<()> {
212        let mut puts = puts.into_iter().peekable();
213        let mut frames = Vec::new();
214        while puts.peek().is_some() {
215            frames.clear();
216            let mut sent = 0usize;
217            for (key, meta, reply) in puts.by_ref().take(PUT_WINDOW) {
218                Request::Put { key, meta, reply }.write(&mut frames)?;
219                sent += 1;
220            }
221            (&self.stream).write_all(&frames)?;
222            // Only acknowledgements of these requests can arrive, so the
223            // buffer never holds bytes past the last one.
224            let mut acks = std::io::BufReader::new(&self.stream);
225            for _ in 0..sent {
226                read_response(&mut acks)?;
227            }
228        }
229        Ok(())
230    }
231
232    /// The daemon's counters since it started.
233    ///
234    /// # Errors
235    ///
236    /// I/O errors and malformed replies.
237    pub fn stats(&mut self) -> std::io::Result<StatsSnapshot> {
238        let body = self.call(&Request::Stats)?;
239        let (_, payload) = split_status_payload(&body)?;
240        serde_json::from_slice(payload).map_err(std::io::Error::other)
241    }
242
243    /// The daemon's configuration and state.
244    ///
245    /// # Errors
246    ///
247    /// I/O errors and malformed replies. A daemon that predates `INFO`
248    /// closes the connection, which is an I/O error.
249    pub fn info(&mut self) -> std::io::Result<Info> {
250        let body = self.call(&Request::Info)?;
251        let (_, payload) = split_status_payload(&body)?;
252        serde_json::from_slice(payload).map_err(std::io::Error::other)
253    }
254}