Skip to main content

schedr_agent/
output.rs

1//! The captured stdout and stderr of a process: the last part up to the output size limit.
2//!
3//! When a stream exceeds the limit, the output keeps **the last part** and is marked
4//! truncated; the full stream is always in the task's log file (see archive/PROJECT.md, Task
5//! assignment: `Finished`).
6
7use std::collections::VecDeque;
8
9use serde_json::{Value, json};
10
11#[cfg(test)]
12mod tests;
13
14/// The last `limit` bytes of a stream.
15#[derive(Debug, Clone)]
16pub struct TailBuffer {
17    limit: usize,
18    data: VecDeque<u8>,
19    truncated: bool,
20}
21
22impl TailBuffer {
23    /// An empty buffer keeping at most `limit` bytes.
24    #[must_use]
25    pub fn new(limit: usize) -> Self {
26        Self {
27            limit,
28            data: VecDeque::new(),
29            truncated: false,
30        }
31    }
32
33    /// Appends bytes, dropping the oldest ones beyond the limit.
34    pub fn push(&mut self, bytes: &[u8]) {
35        self.data.extend(bytes);
36        if self.data.len() > self.limit {
37            let excess = self.data.len() - self.limit;
38            self.data.drain(..excess);
39            self.truncated = true;
40        }
41    }
42
43    /// Whether bytes were dropped.
44    #[must_use]
45    pub const fn truncated(&self) -> bool {
46        self.truncated
47    }
48
49    /// The kept text. Invalid UTF-8 and NUL (which Postgres can't store, B104) are replaced
50    /// with U+FFFD; when truncated, a character cut in two at the start is dropped.
51    #[must_use]
52    pub fn text(&self) -> String {
53        let bytes: Vec<u8> = self.data.iter().copied().collect();
54        let start = if self.truncated {
55            bytes
56                .iter()
57                .take(3)
58                .take_while(|b| (**b & 0b1100_0000) == 0b1000_0000)
59                .count()
60        } else {
61            0
62        };
63        String::from_utf8_lossy(&bytes[start..]).replace('\0', "\u{fffd}")
64    }
65}
66
67/// The exit code reported for a process killed by a signal: `128 + signal`, as shells do.
68#[must_use]
69pub const fn signal_exit_code(signal: i32) -> i32 {
70    128 + signal
71}
72
73/// A `ProcessResult` as stored (the output of `command` and `script` tasks).
74#[must_use]
75pub fn process_result(stdout: &TailBuffer, stderr: &TailBuffer, exit_code: i32) -> Value {
76    json!({
77        "stdout": stdout.text(),
78        "stderr": stderr.text(),
79        "exit_code": exit_code,
80        "stdout_truncated": stdout.truncated(),
81        "stderr_truncated": stderr.truncated(),
82    })
83}