Skip to main content

sonos_cli/
liveness.rs

1//! Did this command actually reach a speaker?
2//!
3//! `SonosSystem::new()` can hand back a full speaker list without a single
4//! packet leaving the machine: discovery is cached on disk for 24h, and on a
5//! cache hit no SSDP sweep is attempted at all. Commands that only *read*
6//! state — `speakers`, `groups`, `status` — then discard every failed fetch
7//! with `.ok()` and print whatever they still have, which on a machine with
8//! broken SSDP is a list of names from a weeks-old cache. stdout looked
9//! exactly like success and the exit code was 0.
10//!
11//! The fix does not need new data. Those commands already make the calls that
12//! answer the question; they just threw the answers away. This module is the
13//! bookkeeping ([`Probes`]) plus the two pure decisions — did anything come
14//! back ([`verdict`]), and what should `main` do about it ([`disposition`]) —
15//! kept free of I/O so both are unit-testable with no network.
16
17/// Whether a command established contact with at least one speaker.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum Liveness {
20    /// At least one probe reached a speaker and came back.
21    Live,
22    /// Every probe this command attempted failed. Anything printed came out of
23    /// the discovery cache and was never confirmed against a speaker.
24    NothingContacted,
25}
26
27/// Decide liveness from the probes a command attempted and the ones that
28/// came back.
29///
30/// Pure: no network, no clock, no globals.
31///
32/// **One success is enough.** A partly reachable household is a real
33/// household, and a speaker that is merely powered off must not turn a
34/// correct listing into a failure. The condition being guarded is *total*
35/// silence rendered as success.
36///
37/// **`attempted == 0` is [`Liveness::Live`].** A command that probed nothing
38/// made no claim about any speaker's state, so there is nothing unvalidated to
39/// flag — `sonos speakers` on an empty system prints "No speakers found" and
40/// emits its own discovery hint. Returning `NothingContacted` there would
41/// staple a "this data may be wrong" banner onto output that contains no data.
42pub fn verdict(attempted: usize, succeeded: usize) -> Liveness {
43    if attempted == 0 || succeeded > 0 {
44        Liveness::Live
45    } else {
46        Liveness::NothingContacted
47    }
48}
49
50/// Running tally of probes attempted versus probes that returned.
51///
52/// [`Probes::record`] is a drop-in for the `.ok()` that used to discard each
53/// outcome: it still yields `Option<T>`, so the formatting code below it is
54/// unchanged, but the outcome is counted on the way past.
55#[derive(Debug, Default, Clone, Copy)]
56pub struct Probes {
57    attempted: usize,
58    succeeded: usize,
59}
60
61impl Probes {
62    /// Count one probe and convert it to the `Option` the callers already use.
63    pub fn record<T, E>(&mut self, outcome: Result<T, E>) -> Option<T> {
64        self.attempted += 1;
65        match outcome {
66            Ok(value) => {
67                self.succeeded += 1;
68                Some(value)
69            }
70            Err(_) => None,
71        }
72    }
73
74    /// The verdict for everything recorded so far.
75    pub fn verdict(&self) -> Liveness {
76        verdict(self.attempted, self.succeeded)
77    }
78}
79
80/// A command's stdout together with whether it was validated against a live
81/// speaker.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct CommandOutput {
84    /// Exactly what the command would have printed before this change. The
85    /// plain-text format is the de-facto machine contract (there is no `--json`
86    /// mode), so nothing is annotated here — the verdict travels beside the
87    /// text, not inside it.
88    pub stdout: String,
89    /// Whether any speaker was actually reached while producing `stdout`.
90    pub liveness: Liveness,
91}
92
93impl CommandOutput {
94    /// Output from a command that cannot silently degrade.
95    ///
96    /// Every write command (`play`, `volume`, `join`, …) propagates its SOAP
97    /// error with `?`, so reaching the `Ok` arm at all proves a speaker
98    /// answered. Only the read commands that swallow failures per-field need
99    /// to count.
100    pub fn live(stdout: impl Into<String>) -> Self {
101        Self {
102            stdout: stdout.into(),
103            liveness: Liveness::Live,
104        }
105    }
106
107    /// Output whose liveness was measured by the handler.
108    pub fn new(stdout: impl Into<String>, liveness: Liveness) -> Self {
109        Self {
110            stdout: stdout.into(),
111            liveness,
112        }
113    }
114}
115
116/// What `main` should do with a finished command.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum Disposition {
119    /// Print stdout, say nothing on stderr, exit 0.
120    Success,
121    /// Print stdout, print a one-line note on stderr, exit 0. (`--offline`)
122    AcceptedUnvalidated,
123    /// Print stdout, print the banner on stderr, exit 3. (default)
124    WarnUnvalidated,
125    /// Suppress stdout, print the banner on stderr, exit 1. (`--require-live`)
126    RejectUnvalidated,
127}
128
129impl Disposition {
130    /// Whether the command's stdout should be printed at all.
131    ///
132    /// Only `--require-live` withholds it: the user asked for verified data, so
133    /// handing them unverified data would be the same bug in a quieter form.
134    pub fn prints_stdout(self) -> bool {
135        !matches!(self, Self::RejectUnvalidated)
136    }
137
138    /// Whether the framed stderr banner should be emitted.
139    pub fn prints_banner(self) -> bool {
140        matches!(self, Self::WarnUnvalidated | Self::RejectUnvalidated)
141    }
142
143    /// Whether the short `--offline` acknowledgement should be emitted.
144    pub fn prints_note(self) -> bool {
145        matches!(self, Self::AcceptedUnvalidated)
146    }
147
148    /// Process exit status.
149    ///
150    /// 3 is a new code, deliberately outside the documented 0/1/2 range rather
151    /// than folded into it: the command *did* run and its stdout *is* printed,
152    /// so it is not the runtime failure 1 means, and it is certainly not a
153    /// usage error. A script that only tests `-ne 0` treats it as failure
154    /// (which is the point); one that wants the old behaviour opts in with
155    /// `--offline`.
156    pub fn exit_code(self) -> u8 {
157        match self {
158            Self::Success | Self::AcceptedUnvalidated => 0,
159            Self::RejectUnvalidated => 1,
160            Self::WarnUnvalidated => 3,
161        }
162    }
163}
164
165/// Map a verdict plus the two opt-in flags onto what `main` does.
166///
167/// Pure, so the whole exit-code matrix is testable without spawning the binary.
168///
169/// `--offline` and `--require-live` are declared as conflicting in the clap
170/// definition, so the both-set row is unreachable through the CLI. It is still
171/// defined here rather than left to panic: `require_live` wins, because it is
172/// the stricter request and the safer thing to do with an ambiguous demand is
173/// to withhold unverified data.
174pub fn disposition(liveness: Liveness, offline: bool, require_live: bool) -> Disposition {
175    match liveness {
176        Liveness::Live => Disposition::Success,
177        Liveness::NothingContacted => {
178            if require_live {
179                Disposition::RejectUnvalidated
180            } else if offline {
181                Disposition::AcceptedUnvalidated
182            } else {
183                Disposition::WarnUnvalidated
184            }
185        }
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    #[test]
194    fn total_failure_is_not_live() {
195        assert_eq!(verdict(4, 0), Liveness::NothingContacted);
196    }
197
198    #[test]
199    fn one_success_out_of_four_is_live() {
200        assert_eq!(verdict(4, 1), Liveness::Live);
201    }
202
203    #[test]
204    fn all_successes_are_live() {
205        assert_eq!(verdict(4, 4), Liveness::Live);
206    }
207
208    /// Probing nothing is not evidence of a dead network — see `verdict`.
209    #[test]
210    fn nothing_attempted_is_live() {
211        assert_eq!(verdict(0, 0), Liveness::Live);
212    }
213
214    #[test]
215    fn probes_counts_both_arms() {
216        let mut probes = Probes::default();
217        assert_eq!(probes.record::<u8, ()>(Ok(7)), Some(7));
218        assert_eq!(probes.record::<u8, ()>(Err(())), None);
219        // `record` must stay a drop-in for `.ok()`: same Option, counted.
220        assert_eq!(probes.verdict(), Liveness::Live);
221    }
222
223    #[test]
224    fn probes_all_failing_is_nothing_contacted() {
225        let mut probes = Probes::default();
226        for _ in 0..3 {
227            assert_eq!(probes.record::<u8, ()>(Err(())), None);
228        }
229        assert_eq!(probes.verdict(), Liveness::NothingContacted);
230    }
231
232    #[test]
233    fn empty_probes_is_live() {
234        assert_eq!(Probes::default().verdict(), Liveness::Live);
235    }
236
237    #[test]
238    fn command_output_live_helper() {
239        let out = CommandOutput::live("Playing (Kitchen)");
240        assert_eq!(out.stdout, "Playing (Kitchen)");
241        assert_eq!(out.liveness, Liveness::Live);
242    }
243
244    // -- the full exit matrix ------------------------------------------------
245
246    #[test]
247    fn live_prints_and_exits_zero() {
248        let d = disposition(Liveness::Live, false, false);
249        assert_eq!(d, Disposition::Success);
250        assert!(d.prints_stdout());
251        assert!(!d.prints_banner());
252        assert!(!d.prints_note());
253        assert_eq!(d.exit_code(), 0);
254    }
255
256    #[test]
257    fn live_ignores_both_flags() {
258        for (offline, require_live) in [(true, false), (false, true)] {
259            let d = disposition(Liveness::Live, offline, require_live);
260            assert_eq!(
261                d,
262                Disposition::Success,
263                "offline={offline} require_live={require_live}"
264            );
265            assert_eq!(d.exit_code(), 0);
266        }
267    }
268
269    #[test]
270    fn nothing_contacted_with_offline_prints_and_exits_zero() {
271        let d = disposition(Liveness::NothingContacted, true, false);
272        assert_eq!(d, Disposition::AcceptedUnvalidated);
273        assert!(d.prints_stdout());
274        assert!(!d.prints_banner());
275        assert!(d.prints_note());
276        assert_eq!(d.exit_code(), 0);
277    }
278
279    #[test]
280    fn nothing_contacted_by_default_prints_and_exits_three() {
281        let d = disposition(Liveness::NothingContacted, false, false);
282        assert_eq!(d, Disposition::WarnUnvalidated);
283        assert!(d.prints_stdout());
284        assert!(d.prints_banner());
285        assert!(!d.prints_note());
286        assert_eq!(d.exit_code(), 3);
287    }
288
289    #[test]
290    fn nothing_contacted_with_require_live_suppresses_stdout_and_exits_one() {
291        let d = disposition(Liveness::NothingContacted, false, true);
292        assert_eq!(d, Disposition::RejectUnvalidated);
293        assert!(!d.prints_stdout());
294        assert!(d.prints_banner());
295        assert_eq!(d.exit_code(), 1);
296    }
297
298    /// clap rejects this combination, but the function must still be total.
299    #[test]
300    fn require_live_wins_over_offline() {
301        assert_eq!(
302            disposition(Liveness::NothingContacted, true, true),
303            Disposition::RejectUnvalidated
304        );
305    }
306
307    /// The whole point of the change: total failure must never exit 0 unless
308    /// the user opted in.
309    #[test]
310    fn total_failure_never_exits_zero_without_opt_in() {
311        assert_ne!(
312            disposition(verdict(10, 0), false, false).exit_code(),
313            0,
314            "ten failed probes reported as success"
315        );
316    }
317}