Skip to main content

pitchfork_cli/
program_status.rs

1//! Program Status Protocol (OSC 7501) reports from daemon output.
2//!
3//! A daemon can tell its supervisor what it is doing by writing
4//! `ESC ] 7501 ; state=working:progress=40:msg=<base64> ESC \` (or ending in
5//! BEL). Only the root record is tracked: a report that names an `id` belongs
6//! to a child record and is ignored.
7//!
8//! Spec: <https://www.superlogical.com/rex/docs/build/program-status>
9
10use base64::Engine as _;
11use base64::engine::general_purpose::STANDARD;
12use serde::{Deserialize, Serialize};
13use std::fmt;
14
15const PREFIX: &str = "\x1b]7501;";
16const MAX_SEQUENCE: usize = 4096;
17const MAX_KEY: usize = 16;
18const MAX_MSG_ENCODED: usize = 2732;
19const MAX_MSG_DECODED: usize = 2048;
20const MAX_TITLE_ENCODED: usize = 256;
21const MAX_TITLE_DECODED: usize = 192;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "lowercase")]
25pub enum ProgramState {
26    Idle,
27    Working,
28    Done,
29    Blocked,
30    Error,
31}
32
33impl ProgramState {
34    fn parse(s: &str) -> Option<Self> {
35        Some(match s {
36            "idle" => Self::Idle,
37            "working" => Self::Working,
38            "done" => Self::Done,
39            "blocked" => Self::Blocked,
40            "error" => Self::Error,
41            _ => return None,
42        })
43    }
44
45    pub fn as_str(self) -> &'static str {
46        match self {
47            Self::Idle => "idle",
48            Self::Working => "working",
49            Self::Done => "done",
50            Self::Blocked => "blocked",
51            Self::Error => "error",
52        }
53    }
54
55    /// `idle`, `working` and `blocked` describe a live process; `done` and
56    /// `error` outlive it.
57    pub fn ends_with_process(self) -> bool {
58        matches!(self, Self::Idle | Self::Working | Self::Blocked)
59    }
60}
61
62impl fmt::Display for ProgramState {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.write_str(self.as_str())
65    }
66}
67
68/// The last root-record status a daemon reported.
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70pub struct ProgramStatus {
71    pub state: ProgramState,
72    /// 0 to 100; only kept for `working` and `blocked`.
73    #[serde(skip_serializing_if = "Option::is_none", default)]
74    pub progress: Option<u8>,
75    /// One human-readable line, with control and invisible formatting
76    /// characters removed.
77    #[serde(skip_serializing_if = "Option::is_none", default)]
78    pub msg: Option<String>,
79}
80
81impl ProgramStatus {
82    /// `working 40% Syncing issues`
83    pub fn summary(&self) -> String {
84        let mut out = self.state.to_string();
85        if let Some(p) = self.progress {
86            out.push_str(&format!(" {p}%"));
87        }
88        if let Some(msg) = &self.msg {
89            out.push(' ');
90            out.push_str(msg);
91        }
92        out
93    }
94}
95
96/// What a report does to the root record.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub enum StatusUpdate {
99    Set(ProgramStatus),
100    Clear,
101}
102
103/// Every valid root-record report in `line`, in order.
104#[cfg(test)]
105fn parse_line(line: &str) -> Vec<StatusUpdate> {
106    OscScanner::default().feed(line.as_bytes())
107}
108
109enum ScanState {
110    /// Matching the opening `ESC ] 7501 ;`; holds how many bytes matched.
111    Search(usize),
112    Body,
113    /// Saw `ESC` in the body, which ends it only if `\` follows.
114    BodyEsc,
115}
116
117/// Finds reports in a byte stream, however it is split into reads.
118///
119/// A report ends with ST (`ESC \` or BEL), not a newline, so a daemon that
120/// prints one on its own still has it seen right away. State carries across
121/// calls to `feed`; a report that never terminates is dropped.
122pub struct OscScanner {
123    state: ScanState,
124    body: Vec<u8>,
125}
126
127impl Default for OscScanner {
128    fn default() -> Self {
129        Self {
130            state: ScanState::Search(0),
131            body: Vec::new(),
132        }
133    }
134}
135
136impl OscScanner {
137    pub fn feed(&mut self, bytes: &[u8]) -> Vec<StatusUpdate> {
138        let prefix = PREFIX.as_bytes();
139        let mut updates = Vec::new();
140        for &b in bytes {
141            match self.state {
142                ScanState::Search(n) => {
143                    self.state = if b == prefix[n] {
144                        if n + 1 == prefix.len() {
145                            self.body.clear();
146                            ScanState::Body
147                        } else {
148                            ScanState::Search(n + 1)
149                        }
150                    } else if b == prefix[0] {
151                        ScanState::Search(1)
152                    } else {
153                        ScanState::Search(0)
154                    };
155                }
156                ScanState::Body => match b {
157                    0x07 => self.finish(1, &mut updates),
158                    0x1b => self.state = ScanState::BodyEsc,
159                    // The body has no newline, so this is not a report.
160                    b'\n' => self.state = ScanState::Search(0),
161                    _ if self.body.len() >= MAX_SEQUENCE => self.state = ScanState::Search(0),
162                    _ => self.body.push(b),
163                },
164                ScanState::BodyEsc => {
165                    if b == b'\\' {
166                        self.finish(2, &mut updates);
167                    } else {
168                        // An escape that does not end the report starts afresh.
169                        self.state = if b == prefix[0] {
170                            ScanState::Search(1)
171                        } else {
172                            ScanState::Search(0)
173                        };
174                    }
175                }
176            }
177        }
178        updates
179    }
180
181    fn finish(&mut self, term_len: usize, updates: &mut Vec<StatusUpdate>) {
182        self.state = ScanState::Search(0);
183        if PREFIX.len() + self.body.len() + term_len > MAX_SEQUENCE {
184            return;
185        }
186        if let Ok(body) = std::str::from_utf8(&self.body)
187            && let Some(update) = parse_body(body)
188        {
189            updates.push(update);
190        }
191    }
192}
193
194fn parse_body(body: &str) -> Option<StatusUpdate> {
195    // Feature detection query; nothing to record.
196    if body.trim() == "?" {
197        return None;
198    }
199    let mut state = None;
200    let mut id_present = false;
201    let mut progress = None;
202    let mut msg = None;
203    for pair in body.split(':') {
204        let Some((key, value)) = pair.split_once('=') else {
205            continue;
206        };
207        let (key, value) = (key.trim(), value.trim());
208        if key.is_empty()
209            || key.len() > MAX_KEY
210            || !key.bytes().all(|b| b.is_ascii_lowercase())
211            || !value
212                .bytes()
213                .all(|b| b.is_ascii_alphanumeric() || b"_.,+/=-".contains(&b))
214        {
215            continue;
216        }
217        match key {
218            "state" => state = Some(value),
219            "id" => id_present = true,
220            "progress" => {
221                progress = value.parse::<u8>().ok().filter(|p| *p <= 100);
222            }
223            "msg" => msg = Some(value),
224            "title" => {
225                // Not shown, but a title that breaks a limit voids the report.
226                decode_text(value, MAX_TITLE_ENCODED, MAX_TITLE_DECODED)?;
227            }
228            _ => {}
229        }
230    }
231    let state_str = state?;
232    if state_str == "clear" {
233        // `clear` with an id removes a child record, which is not tracked.
234        return (!id_present).then_some(StatusUpdate::Clear);
235    }
236    let state = ProgramState::parse(state_str)?;
237    let msg = match msg {
238        Some(m) => {
239            Some(decode_text(m, MAX_MSG_ENCODED, MAX_MSG_DECODED)?).filter(|m| !m.is_empty())
240        }
241        None => None,
242    };
243    if id_present {
244        return None;
245    }
246    let progress =
247        progress.filter(|_| matches!(state, ProgramState::Working | ProgramState::Blocked));
248    Some(StatusUpdate::Set(ProgramStatus {
249        state,
250        progress,
251        msg,
252    }))
253}
254
255/// Decode a base64 free-text value. `None` voids the report: a limit broken, bad
256/// base64 or UTF-8, or a control character in the text. Invisible formatting
257/// characters, such as text direction overrides, are dropped.
258fn decode_text(encoded: &str, max_encoded: usize, max_decoded: usize) -> Option<String> {
259    if encoded.len() > max_encoded {
260        return None;
261    }
262    let bytes = STANDARD.decode(encoded).ok()?;
263    if bytes.len() > max_decoded {
264        return None;
265    }
266    let text = String::from_utf8(bytes).ok()?;
267    if text.chars().any(char::is_control) {
268        return None;
269    }
270    Some(text.chars().filter(|c| !is_invisible_format(*c)).collect())
271}
272
273fn is_invisible_format(c: char) -> bool {
274    matches!(
275        c,
276        '\u{00AD}'
277            | '\u{061C}'
278            | '\u{180E}'
279            | '\u{200B}'..='\u{200F}'
280            | '\u{202A}'..='\u{202E}'
281            | '\u{2060}'..='\u{2064}'
282            | '\u{2066}'..='\u{206F}'
283            | '\u{FEFF}'
284    )
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    fn enc(s: &str) -> String {
292        STANDARD.encode(s)
293    }
294
295    fn set(state: ProgramState, progress: Option<u8>, msg: Option<&str>) -> StatusUpdate {
296        StatusUpdate::Set(ProgramStatus {
297            state,
298            progress,
299            msg: msg.map(str::to_string),
300        })
301    }
302
303    #[test]
304    fn parses_state_progress_and_message() {
305        let line = format!(
306            "\x1b]7501;state=working:progress=40:msg={}\x1b\\",
307            enc("Syncing issues")
308        );
309        assert_eq!(
310            parse_line(&line),
311            vec![set(ProgramState::Working, Some(40), Some("Syncing issues"))]
312        );
313    }
314
315    #[test]
316    fn accepts_bel_terminator_and_surrounding_output() {
317        let line = "before \x1b]7501;state=done\x07 after";
318        assert_eq!(parse_line(line), vec![set(ProgramState::Done, None, None)]);
319    }
320
321    #[test]
322    fn returns_reports_in_order() {
323        let line = "\x1b]7501;state=working\x07\x1b]7501;state=error\x07";
324        assert_eq!(
325            parse_line(line),
326            vec![
327                set(ProgramState::Working, None, None),
328                set(ProgramState::Error, None, None)
329            ]
330        );
331    }
332
333    #[test]
334    fn progress_only_with_working_or_blocked() {
335        assert_eq!(
336            parse_line("\x1b]7501;state=done:progress=50\x07"),
337            vec![set(ProgramState::Done, None, None)]
338        );
339        assert_eq!(
340            parse_line("\x1b]7501;state=blocked:kind=auth:progress=7\x07"),
341            vec![set(ProgramState::Blocked, Some(7), None)]
342        );
343        assert_eq!(
344            parse_line("\x1b]7501;state=working:progress=101\x07"),
345            vec![set(ProgramState::Working, None, None)]
346        );
347    }
348
349    #[test]
350    fn ignores_unknown_state_and_missing_state() {
351        assert!(parse_line("\x1b]7501;state=sleeping\x07").is_empty());
352        assert!(parse_line("\x1b]7501;progress=3\x07").is_empty());
353    }
354
355    #[test]
356    fn ignores_child_records_and_feature_queries() {
357        assert!(parse_line("\x1b]7501;state=working:id=build/test\x07").is_empty());
358        assert!(parse_line("\x1b]7501;?\x07").is_empty());
359        assert!(parse_line("\x1b]7501;state=clear:id=build\x07").is_empty());
360    }
361
362    #[test]
363    fn clear_without_id_clears() {
364        assert_eq!(
365            parse_line("\x1b]7501;state=clear\x07"),
366            vec![StatusUpdate::Clear]
367        );
368    }
369
370    #[test]
371    fn malformed_pairs_are_skipped_and_last_value_wins() {
372        let line = "\x1b]7501;junk:state=idle:Bad=1:state=working\x07";
373        assert_eq!(
374            parse_line(line),
375            vec![set(ProgramState::Working, None, None)]
376        );
377    }
378
379    #[test]
380    fn unknown_keys_are_ignored() {
381        let line = "\x1b]7501;state=idle:app=cargo:future=1\x07";
382        assert_eq!(parse_line(line), vec![set(ProgramState::Idle, None, None)]);
383    }
384
385    #[test]
386    fn message_with_control_character_voids_the_report() {
387        let line = format!("\x1b]7501;state=working:msg={}\x07", enc("a\x1b[31mb"));
388        assert!(parse_line(&line).is_empty());
389    }
390
391    #[test]
392    fn invisible_formatting_is_stripped() {
393        let line = format!("\x1b]7501;state=done:msg={}\x07", enc("ok\u{202E}gnp"));
394        assert_eq!(
395            parse_line(&line),
396            vec![set(ProgramState::Done, None, Some("okgnp"))]
397        );
398    }
399
400    #[test]
401    fn oversized_message_voids_the_report() {
402        let line = format!(
403            "\x1b]7501;state=working:msg={}\x07",
404            enc(&"x".repeat(MAX_MSG_DECODED + 1))
405        );
406        assert!(parse_line(&line).is_empty());
407    }
408
409    #[test]
410    fn invalid_base64_voids_the_report() {
411        // A byte outside the value set skips only that pair.
412        assert_eq!(
413            parse_line("\x1b]7501;state=working:msg=@@@\x07"),
414            vec![set(ProgramState::Working, None, None)]
415        );
416        assert!(parse_line("\x1b]7501;state=working:msg=abc\x07").is_empty());
417    }
418
419    #[test]
420    fn unterminated_sequence_is_not_a_report() {
421        assert!(parse_line("\x1b]7501;state=working").is_empty());
422    }
423
424    #[test]
425    fn a_report_split_across_reads_and_without_newline_is_seen() {
426        let mut scanner = OscScanner::default();
427        assert!(scanner.feed(b"x\x1b]75").is_empty());
428        assert!(scanner.feed(b"01;state=work").is_empty());
429        assert_eq!(
430            scanner.feed(b"ing\x1b"),
431            vec![],
432            "ESC alone does not end a report"
433        );
434        assert_eq!(
435            scanner.feed(b"\\"),
436            vec![set(ProgramState::Working, None, None)]
437        );
438    }
439
440    #[test]
441    fn a_newline_inside_a_report_abandons_it() {
442        let mut scanner = OscScanner::default();
443        assert!(scanner.feed(b"\x1b]7501;state=working\n\x07").is_empty());
444        assert_eq!(
445            scanner.feed(b"\x1b]7501;state=done\x07"),
446            vec![set(ProgramState::Done, None, None)]
447        );
448    }
449
450    #[test]
451    fn summary_joins_parts() {
452        let status = ProgramStatus {
453            state: ProgramState::Working,
454            progress: Some(40),
455            msg: Some("Syncing".into()),
456        };
457        assert_eq!(status.summary(), "working 40% Syncing");
458    }
459}