Skip to main content

sail_api/
protocol.rs

1//! The daemon wire protocol: length-prefixed binary frames (ADR 0011).
2//!
3//! A request is `u32` (big-endian) body length, then the body: one operation
4//! byte, then its payload.
5//!
6//! | Op | Payload | Response |
7//! |---|---|---|
8//! | 1 `HELLO` | [`Hello`] JSON (path and mode) | `0`, `u32` len, identity JSON; or `1`, `u32` len, error text |
9//! | 2 `GET` | 32-byte key | `0` (miss); or `1`, `u32` len, reply bytes, then optionally `u32` len, effort JSON |
10//! | 3 `PUT` | 32-byte key, `u32` meta len, meta JSON, reply bytes | `0` |
11//! | 4 `STATS` | empty | `0`, `u32` len, [`StatsSnapshot`] JSON |
12//! | 5 `INFO` | empty | `0`, `u32` len, [`Info`] JSON |
13//!
14//! Operations 4 and 5 are read-only and additive: they kept
15//! the original version (ADR 0012, ADR 0015). Version 4 requires silent-session
16//! publication (ADR 0022) and negotiates the mode in HELLO (ADR 0020). A daemon that predates
17//! one rejects it by closing that connection; nothing else changes.
18//!
19//! Version 5 requires exactly one successful `HELLO` before `GET` or `PUT`.
20//! Missing, failed or repeated handshakes close the connection without reading
21//! further requests. `STATS` and `INFO` remain available without a handshake.
22//!
23//! Frames larger than [`MAX_FRAME`] are rejected.
24
25use std::io::{self, Read, Write};
26
27use serde::{Deserialize, Serialize};
28
29/// The protocol version. Bump on any incompatible change; the daemon reports
30/// it in `HELLO`, clients refuse a mismatch, and the default socket name
31/// includes it, so an upgraded client never talks to a stale daemon.
32pub const PROTOCOL_VERSION: u32 = 5;
33
34/// A cache namespace negotiated for one solver connection.
35#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "kebab-case")]
37pub enum VerificationMode {
38    /// Exact default-mode replies.
39    #[default]
40    Default,
41    /// Complete verification attempts in the seed portfolio.
42    AcceptFirstProof,
43}
44
45impl VerificationMode {
46    /// The stable namespace name.
47    #[must_use]
48    pub fn name(self) -> &'static str {
49        match self {
50            Self::Default => "default",
51            Self::AcceptFirstProof => "accept-first-proof",
52        }
53    }
54}
55
56/// A solver handshake, including the cache namespace.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58pub struct Hello {
59    /// The exact solver executable to identify.
60    pub solver_path: String,
61    /// The namespace used for every subsequent lookup and store.
62    pub mode: VerificationMode,
63}
64
65/// Largest accepted frame body, in bytes.
66pub const MAX_FRAME: u32 = 256 * 1024 * 1024;
67
68const OP_HELLO: u8 = 1;
69const OP_GET: u8 = 2;
70const OP_PUT: u8 = 3;
71const OP_STATS: u8 = 4;
72const OP_INFO: u8 = 5;
73
74/// Solver identity as the daemon reports it (see `sail_key::SolverIdentity`).
75#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
76pub struct Identity {
77    /// Solver family.
78    pub name: String,
79    /// Version the solver reports.
80    pub version: String,
81    /// SHA-256 of the binary, as hex.
82    pub binary_sha256: String,
83    /// Platform class.
84    pub platform: String,
85    /// The daemon's protocol version ([`PROTOCOL_VERSION`]).
86    #[serde(default)]
87    pub protocol_version: u32,
88}
89
90/// Solver effort recorded with a `check-sat` reply (ADR 0009).
91#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
92pub struct Effort {
93    /// The `:rlimit` in force for the check (0 means unlimited).
94    pub limit: Option<u64>,
95    /// Resource units the check used (`rlimit-count` after minus before).
96    pub used: Option<u64>,
97    /// The `get-info :reason-unknown` reply, for `unknown` answers.
98    pub reason: Option<String>,
99}
100
101/// Metadata sent with a `PUT`.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103pub struct PutMeta {
104    /// The command the reply answers.
105    pub command: String,
106    /// Provenance (charter rule 7), for example `pinned-solver`.
107    pub provenance: String,
108    /// Effort, for `check-sat` replies.
109    #[serde(default)]
110    pub effort: Option<Effort>,
111}
112
113/// The daemon's counters since it started (the `STATS` operation). Benchmarks
114/// read them before and after a run and report the difference.
115#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
116pub struct StatsSnapshot {
117    /// `HELLO` requests: one per cached shim session.
118    pub hellos: u64,
119    /// `GET` requests. A session stops asking at its first miss.
120    pub gets: u64,
121    /// `GET` requests answered from the cache.
122    pub hits: u64,
123    /// `PUT` requests: replies recorded from the solver.
124    pub puts: u64,
125    /// `GET` hits served from the in-memory tier (included in `hits`).
126    #[serde(default)]
127    pub memory_hits: u64,
128    /// `PUT`s dropped because the write-behind queue stayed full. Each
129    /// costs a future miss, never correctness.
130    #[serde(default)]
131    pub dropped_puts: u64,
132    /// Local misses looked up in the shared store (ADR 0017).
133    #[serde(default)]
134    pub shared_lookups: u64,
135    /// Shared entries that passed every check and were served (included
136    /// in `hits`).
137    #[serde(default)]
138    pub shared_hits: u64,
139    /// Shared entries that failed a check, including the two counts below.
140    /// Each is a miss.
141    #[serde(default)]
142    pub shared_rejected: u64,
143    /// Shared entries signed for another solver: refused.
144    #[serde(default)]
145    pub shared_other_solver: u64,
146    /// Shared entries signed for this solver on another platform class:
147    /// refused (ADR 0010).
148    #[serde(default)]
149    pub shared_other_platform: u64,
150    /// Shared lookups that timed out.
151    #[serde(default)]
152    pub shared_timeouts: u64,
153    /// Local misses not looked up in the shared store: backing off after a
154    /// timeout, a recent miss for the key, or too many reads in flight.
155    #[serde(default)]
156    pub shared_skipped: u64,
157    /// Local misses looked up in the release's bundled replies (ADR 0062).
158    #[serde(default)]
159    pub bundled_lookups: u64,
160    /// Bundled entries that passed every check and were served (included
161    /// in `hits`).
162    #[serde(default)]
163    pub bundled_hits: u64,
164    /// Bundled entries that failed a check. Each is a miss.
165    #[serde(default)]
166    pub bundled_rejected: u64,
167}
168
169impl StatsSnapshot {
170    /// The counters accumulated between `earlier` and `self`.
171    #[must_use]
172    pub fn since(&self, earlier: &Self) -> Self {
173        Self {
174            hellos: self.hellos.saturating_sub(earlier.hellos),
175            gets: self.gets.saturating_sub(earlier.gets),
176            hits: self.hits.saturating_sub(earlier.hits),
177            puts: self.puts.saturating_sub(earlier.puts),
178            memory_hits: self.memory_hits.saturating_sub(earlier.memory_hits),
179            dropped_puts: self.dropped_puts.saturating_sub(earlier.dropped_puts),
180            shared_lookups: self.shared_lookups.saturating_sub(earlier.shared_lookups),
181            shared_hits: self.shared_hits.saturating_sub(earlier.shared_hits),
182            shared_rejected: self.shared_rejected.saturating_sub(earlier.shared_rejected),
183            shared_other_solver: self
184                .shared_other_solver
185                .saturating_sub(earlier.shared_other_solver),
186            shared_other_platform: self
187                .shared_other_platform
188                .saturating_sub(earlier.shared_other_platform),
189            shared_timeouts: self.shared_timeouts.saturating_sub(earlier.shared_timeouts),
190            shared_skipped: self.shared_skipped.saturating_sub(earlier.shared_skipped),
191            bundled_lookups: self.bundled_lookups.saturating_sub(earlier.bundled_lookups),
192            bundled_hits: self.bundled_hits.saturating_sub(earlier.bundled_hits),
193            bundled_rejected: self
194                .bundled_rejected
195                .saturating_sub(earlier.bundled_rejected),
196        }
197    }
198}
199
200/// The in-memory tier's state, as `INFO` reports it.
201#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
202pub struct MemoryInfo {
203    /// Budget in bytes (0: the tier is off).
204    pub capacity_bytes: u64,
205    /// Replies held.
206    pub entries: u64,
207    /// Bytes charged for them.
208    pub bytes: u64,
209    /// Replies held whose disk write is still queued.
210    pub pending: u64,
211}
212
213/// The write-behind queue's state, as `INFO` reports it.
214#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
215pub struct QueueInfo {
216    /// Budget in bytes.
217    pub capacity_bytes: u64,
218    /// Writes queued or in progress.
219    pub entries: u64,
220    /// Their reply bytes.
221    pub bytes: u64,
222}
223
224/// The daemon's configuration and state (the `INFO` operation).
225#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
226pub struct Info {
227    /// The daemon's protocol version ([`PROTOCOL_VERSION`]).
228    pub protocol_version: u32,
229    /// The daemon's sail version.
230    pub sail_version: String,
231    /// The daemon's process id.
232    pub pid: u32,
233    /// Seconds since the daemon started.
234    pub uptime_secs: u64,
235    /// The socket it serves.
236    pub socket: String,
237    /// The cache root it serves.
238    pub cache_root: String,
239    /// Its log file, if it has one.
240    #[serde(default)]
241    pub log: Option<String>,
242    /// Seconds without connections after which it stops (0: never).
243    pub idle_timeout_secs: u64,
244    /// The in-memory tier.
245    pub memory: MemoryInfo,
246    /// The write-behind queue.
247    pub queue: QueueInfo,
248    /// The shared tier, if one is configured (ADR 0017).
249    #[serde(default)]
250    pub shared: Option<SharedInfo>,
251    /// The release's bundled replies, if this installation ships them
252    /// (ADR 0062): the pack, and whether it is loading, used or refused.
253    #[serde(default, skip_serializing_if = "Option::is_none")]
254    pub bundled: Option<String>,
255}
256
257/// The shared tier's configuration, as `INFO` reports it.
258#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
259pub struct SharedInfo {
260    /// The shared store's directory.
261    pub store: String,
262    /// The directory of trusted public keys.
263    pub trust_dir: String,
264    /// Ids of the keys trusted now.
265    pub trusted_keys: Vec<String>,
266    /// How long one lookup may take, in milliseconds.
267    pub timeout_ms: u64,
268    /// Optional HTTP transport state; absent for directory stores and older daemons.
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub remote: Option<RemoteInfo>,
271}
272
273/// Sanitized optional HTTP transport state, with no credentials or response bodies.
274#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
275pub struct RemoteInfo {
276    /// Sanitized endpoint, without URL credentials or query strings.
277    pub endpoint: String,
278    /// Most recent result category (for example `ok`, `http-401`, `timeout`).
279    pub last_status: Option<String>,
280    /// HTTP requests attempted since this endpoint was configured.
281    pub requests: u64,
282    /// Requests refused for authentication or authorization.
283    pub auth_refused: u64,
284    /// Requests that could not deliver usable bytes.
285    pub unavailable: u64,
286    /// Concurrent same-key readers joined to an existing lookup.
287    pub coalesced: u64,
288}
289
290/// A decoded request.
291#[derive(Debug, Clone, PartialEq, Eq)]
292pub enum Request {
293    /// Identify the solver at this path.
294    Hello(Hello),
295    /// Look up a key.
296    Get([u8; 32]),
297    /// Store a reply.
298    Put {
299        /// The key.
300        key: [u8; 32],
301        /// Metadata.
302        meta: PutMeta,
303        /// The exact reply bytes.
304        reply: Vec<u8>,
305    },
306    /// Report the daemon's counters.
307    Stats,
308    /// Report the daemon's configuration and state.
309    Info,
310}
311
312fn invalid(msg: &str) -> io::Error {
313    io::Error::new(io::ErrorKind::InvalidData, msg.to_owned())
314}
315
316fn write_frame(w: &mut impl Write, body: &[u8]) -> io::Result<()> {
317    let len = u32::try_from(body.len()).map_err(|_| invalid("frame too large"))?;
318    w.write_all(&len.to_be_bytes())?;
319    w.write_all(body)?;
320    w.flush()
321}
322
323fn read_u32(r: &mut impl Read) -> io::Result<u32> {
324    let mut b = [0u8; 4];
325    r.read_exact(&mut b)?;
326    Ok(u32::from_be_bytes(b))
327}
328
329fn read_bytes(r: &mut impl Read, len: u32) -> io::Result<Vec<u8>> {
330    if len > MAX_FRAME {
331        return Err(invalid("frame too large"));
332    }
333    let mut buf = vec![0u8; usize::try_from(len).map_err(|_| invalid("frame too large"))?];
334    r.read_exact(&mut buf)?;
335    Ok(buf)
336}
337
338impl Request {
339    /// Writes this request as one frame.
340    ///
341    /// # Errors
342    ///
343    /// I/O errors, or a body larger than `u32::MAX`.
344    pub fn write(&self, w: &mut impl Write) -> io::Result<()> {
345        let mut body = Vec::new();
346        match self {
347            Self::Hello(hello) => {
348                body.push(OP_HELLO);
349                body.extend_from_slice(&serde_json::to_vec(hello).map_err(io::Error::other)?);
350            }
351            Self::Get(key) => {
352                body.push(OP_GET);
353                body.extend_from_slice(key);
354            }
355            Self::Put { key, meta, reply } => {
356                body.push(OP_PUT);
357                body.extend_from_slice(key);
358                let m = serde_json::to_vec(meta).map_err(io::Error::other)?;
359                let len = u32::try_from(m.len()).map_err(|_| invalid("meta too large"))?;
360                body.extend_from_slice(&len.to_be_bytes());
361                body.extend_from_slice(&m);
362                body.extend_from_slice(reply);
363            }
364            Self::Stats => body.push(OP_STATS),
365            Self::Info => body.push(OP_INFO),
366        }
367        write_frame(w, &body)
368    }
369
370    /// Reads one request frame. `Ok(None)` at a clean end of stream.
371    ///
372    /// # Errors
373    ///
374    /// I/O errors and malformed frames.
375    pub fn read(r: &mut impl Read) -> io::Result<Option<Self>> {
376        let len = match read_u32(r) {
377            Ok(n) => n,
378            Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
379            Err(e) => return Err(e),
380        };
381        let body = read_bytes(r, len)?;
382        let (&op, rest) = body.split_first().ok_or_else(|| invalid("empty frame"))?;
383        let key = |b: &[u8]| -> io::Result<[u8; 32]> {
384            b.get(..32)
385                .and_then(|k| <[u8; 32]>::try_from(k).ok())
386                .ok_or_else(|| invalid("short key"))
387        };
388        match op {
389            OP_HELLO => Ok(Some(Self::Hello(
390                serde_json::from_slice(rest).map_err(|_| invalid("bad solver handshake"))?,
391            ))),
392            OP_GET => Ok(Some(Self::Get(key(rest)?))),
393            OP_PUT => {
394                let k = key(rest)?;
395                let after = rest.get(32..).ok_or_else(|| invalid("short put"))?;
396                let mlen = after
397                    .get(..4)
398                    .and_then(|b| <[u8; 4]>::try_from(b).ok())
399                    .map(u32::from_be_bytes)
400                    .ok_or_else(|| invalid("short put"))?;
401                let mlen = usize::try_from(mlen).map_err(|_| invalid("bad meta length"))?;
402                let meta_bytes = after
403                    .get(4..4 + mlen)
404                    .ok_or_else(|| invalid("short meta"))?;
405                let meta: PutMeta =
406                    serde_json::from_slice(meta_bytes).map_err(|_| invalid("bad meta"))?;
407                let reply = after.get(4 + mlen..).unwrap_or_default().to_vec();
408                Ok(Some(Self::Put {
409                    key: k,
410                    meta,
411                    reply,
412                }))
413            }
414            OP_STATS => Ok(Some(Self::Stats)),
415            OP_INFO => Ok(Some(Self::Info)),
416            _ => Err(invalid("unknown operation")),
417        }
418    }
419}
420
421/// Writes a `HELLO` response.
422///
423/// # Errors
424///
425/// I/O errors.
426pub fn write_hello_response(w: &mut impl Write, result: Result<&Identity, &str>) -> io::Result<()> {
427    let (status, payload) = match result {
428        Ok(id) => (0u8, serde_json::to_vec(id).map_err(io::Error::other)?),
429        Err(msg) => (1u8, msg.as_bytes().to_vec()),
430    };
431    let mut body = vec![status];
432    let len = u32::try_from(payload.len()).map_err(|_| invalid("too large"))?;
433    body.extend_from_slice(&len.to_be_bytes());
434    body.extend_from_slice(&payload);
435    write_frame(w, &body)
436}
437
438/// Writes a `GET` response.
439///
440/// # Errors
441///
442/// I/O errors.
443pub fn write_get_response(
444    w: &mut impl Write,
445    reply: Option<(&[u8], Option<&Effort>)>,
446) -> io::Result<()> {
447    let mut body = Vec::new();
448    match reply {
449        None => body.push(0),
450        Some((r, effort)) => {
451            body.push(1);
452            let len = u32::try_from(r.len()).map_err(|_| invalid("too large"))?;
453            body.extend_from_slice(&len.to_be_bytes());
454            body.extend_from_slice(r);
455            // Optional trailer: the entry's effort as JSON. Clients that do
456            // not know it ignore bytes after the reply.
457            if let Some(e) = effort {
458                let json = serde_json::to_vec(e).map_err(io::Error::other)?;
459                let len = u32::try_from(json.len()).map_err(|_| invalid("too large"))?;
460                body.extend_from_slice(&len.to_be_bytes());
461                body.extend_from_slice(&json);
462            }
463        }
464    }
465    write_frame(w, &body)
466}
467
468/// The effort trailer of a `GET` hit body, if present.
469#[must_use]
470pub fn get_effort_trailer(body: &[u8]) -> Option<Effort> {
471    let reply_len = usize::try_from(u32::from_be_bytes(
472        <[u8; 4]>::try_from(body.get(1..5)?).ok()?,
473    ))
474    .ok()?;
475    let rest = body.get(5 + reply_len..)?;
476    let len = usize::try_from(u32::from_be_bytes(
477        <[u8; 4]>::try_from(rest.get(..4)?).ok()?,
478    ))
479    .ok()?;
480    serde_json::from_slice(rest.get(4..4 + len)?).ok()
481}
482
483/// Writes a `STATS` response.
484///
485/// # Errors
486///
487/// I/O errors.
488pub fn write_stats_response(w: &mut impl Write, stats: &StatsSnapshot) -> io::Result<()> {
489    let payload = serde_json::to_vec(stats).map_err(io::Error::other)?;
490    let mut body = vec![0u8];
491    let len = u32::try_from(payload.len()).map_err(|_| invalid("too large"))?;
492    body.extend_from_slice(&len.to_be_bytes());
493    body.extend_from_slice(&payload);
494    write_frame(w, &body)
495}
496
497/// Writes an `INFO` response.
498///
499/// # Errors
500///
501/// I/O errors.
502pub fn write_info_response(w: &mut impl Write, info: &Info) -> io::Result<()> {
503    let payload = serde_json::to_vec(info).map_err(io::Error::other)?;
504    let mut body = vec![0u8];
505    let len = u32::try_from(payload.len()).map_err(|_| invalid("too large"))?;
506    body.extend_from_slice(&len.to_be_bytes());
507    body.extend_from_slice(&payload);
508    write_frame(w, &body)
509}
510
511/// Writes a `PUT` acknowledgement.
512///
513/// # Errors
514///
515/// I/O errors.
516pub fn write_put_response(w: &mut impl Write) -> io::Result<()> {
517    write_frame(w, &[0])
518}
519
520/// Reads one response frame body.
521///
522/// # Errors
523///
524/// I/O errors and oversize frames.
525pub fn read_response(r: &mut impl Read) -> io::Result<Vec<u8>> {
526    let len = read_u32(r)?;
527    read_bytes(r, len)
528}
529
530/// Splits a `status, u32 len, payload` response body.
531///
532/// # Errors
533///
534/// Malformed bodies.
535pub fn split_status_payload(body: &[u8]) -> io::Result<(u8, &[u8])> {
536    let (&status, rest) = body
537        .split_first()
538        .ok_or_else(|| invalid("empty response"))?;
539    if rest.is_empty() {
540        return Ok((status, rest));
541    }
542    let len = rest
543        .get(..4)
544        .and_then(|b| <[u8; 4]>::try_from(b).ok())
545        .map(u32::from_be_bytes)
546        .ok_or_else(|| invalid("short response"))?;
547    let len = usize::try_from(len).map_err(|_| invalid("bad length"))?;
548    let payload = rest
549        .get(4..4 + len)
550        .ok_or_else(|| invalid("short response"))?;
551    Ok((status, payload))
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557
558    #[test]
559    fn requests_round_trip() {
560        let reqs = [
561            Request::Hello(Hello {
562                solver_path: "/opt/z3".to_owned(),
563                mode: VerificationMode::Default,
564            }),
565            Request::Hello(Hello {
566                solver_path: "/opt/z3".to_owned(),
567                mode: VerificationMode::AcceptFirstProof,
568            }),
569            Request::Get([9; 32]),
570            Request::Put {
571                key: [7; 32],
572                meta: PutMeta {
573                    command: "check-sat".to_owned(),
574                    provenance: "pinned-solver".to_owned(),
575                    effort: Some(Effort {
576                        limit: Some(30_000_000),
577                        used: Some(1234),
578                        reason: None,
579                    }),
580                },
581                reply: b"unsat\n".to_vec(),
582            },
583            Request::Stats,
584            Request::Info,
585        ];
586        let mut buf = Vec::new();
587        for r in &reqs {
588            assert!(r.write(&mut buf).is_ok());
589        }
590        let mut cur = std::io::Cursor::new(buf);
591        for r in &reqs {
592            assert_eq!(Request::read(&mut cur).ok().flatten().as_ref(), Some(r));
593        }
594        assert!(matches!(Request::read(&mut cur), Ok(None)));
595    }
596
597    #[test]
598    fn stats_response_round_trips() {
599        let stats = StatsSnapshot {
600            hellos: 1,
601            gets: 5,
602            hits: 4,
603            puts: 3,
604            memory_hits: 2,
605            dropped_puts: 0,
606            ..StatsSnapshot::default()
607        };
608        let mut buf = Vec::new();
609        assert!(write_stats_response(&mut buf, &stats).is_ok());
610        let body = read_response(&mut std::io::Cursor::new(buf)).unwrap_or_default();
611        let parsed = split_status_payload(&body)
612            .ok()
613            .and_then(|(_, p)| serde_json::from_slice::<StatsSnapshot>(p).ok());
614        assert_eq!(parsed, Some(stats));
615        assert_eq!(stats.since(&StatsSnapshot { gets: 2, ..stats }).gets, 3);
616        assert_eq!(
617            StatsSnapshot::default().since(&stats),
618            StatsSnapshot::default()
619        );
620    }
621
622    #[test]
623    fn info_round_trips_and_old_stats_json_reads() {
624        let info = Info {
625            protocol_version: PROTOCOL_VERSION,
626            sail_version: "0.0.0".to_owned(),
627            pid: 7,
628            uptime_secs: 3,
629            socket: "/tmp/d.sock".to_owned(),
630            cache_root: "/tmp/c".to_owned(),
631            log: None,
632            idle_timeout_secs: 1800,
633            memory: MemoryInfo::default(),
634            queue: QueueInfo::default(),
635            shared: Some(SharedInfo {
636                store: "/srv/sail".to_owned(),
637                trust_dir: "/tmp/c/trust".to_owned(),
638                trusted_keys: vec!["0123456789abcdef".to_owned()],
639                timeout_ms: 250,
640                remote: None,
641            }),
642            bundled: Some(
643                "/opt/sail/replies/vstd.pack (3 entries, key 0123456789abcdef)".to_owned(),
644            ),
645        };
646        let mut buf = Vec::new();
647        assert!(write_info_response(&mut buf, &info).is_ok());
648        let body = read_response(&mut std::io::Cursor::new(buf)).unwrap_or_default();
649        let parsed = split_status_payload(&body)
650            .ok()
651            .and_then(|(_, p)| serde_json::from_slice::<Info>(p).ok());
652        assert_eq!(parsed, Some(info));
653        // A daemon from before the per-tier counters.
654        let old: Option<StatsSnapshot> =
655            serde_json::from_str(r#"{"hellos":1,"gets":2,"hits":1,"puts":1}"#).ok();
656        assert_eq!(old.map(|s| s.memory_hits), Some(0));
657    }
658
659    #[test]
660    fn malformed_frames_are_errors_not_panics() {
661        for bytes in [
662            &[0, 0, 0, 1, 9][..],
663            &[0, 0, 0, 2, 2, 1][..],
664            &[0, 0, 0, 3, 3, 1, 2][..],
665            &[0xff, 0xff, 0xff, 0xff][..],
666            &[0, 0, 0][..],
667        ] {
668            let _ = Request::read(&mut std::io::Cursor::new(bytes));
669        }
670        assert!(Request::read(&mut std::io::Cursor::new(&[0, 0, 0, 1, 9][..])).is_err());
671    }
672}