Skip to main content

shep_core/
barks.rs

1//! `barks.jsonl`: the size-capped ring of fired alerts.
2//!
3//! One [`Bark`] per line, appended by the bark dog on a rule fire and by
4//! the shepherd on a dog's exhausted restart budget, and read by `shep
5//! barks`. [`append`] evicts oldest-first under a byte cap by rewriting
6//! survivors to a temp file and `rename`ing it over the original, so a
7//! writer that dies mid-rewrite never leaves a fragment. [`read`] skips
8//! any unparseable line, since this file is read during an incident.
9//!
10//! The two writers are separate OS processes, so a [`crate::file_lock`] on
11//! a sibling `<path>.lock` serializes them.
12
13// The lock type lives in shep-core rather than shep-daemon so both writers
14// can name it.
15use core::fmt;
16use std::io::Write as _;
17use std::path::Path;
18
19use serde::{Deserialize, Serialize};
20
21use crate::file_lock::FileLock;
22
23/// Cap the ring keeps itself under when nobody configured one.
24pub const DEFAULT_MAX_BYTES: u64 = 1024 * 1024;
25
26/// One fired alert, as it lands in `$SHEP_HOME/barks.jsonl`.
27///
28/// One JSON object per line: an interrupted write then costs the reader
29/// one record, not the whole file.
30///
31/// `Debug` is derived, not redacted. Every field here is shep's own prose
32/// or a config key, never a sink's target; a field that ever carried a
33/// webhook URL or token would need its own redacted `Debug`.
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35pub struct Bark {
36    /// Unix millis when the alert fired.
37    pub at_ms: u64,
38    /// The rule that fired, or `daemon` when the shepherd wrote this
39    /// itself.
40    pub rule: String,
41    /// What it is about: a sheep's name, or a dog's.
42    pub subject: String,
43    /// The human-readable line. Plain English, no theme: this is read
44    /// during an incident.
45    pub message: String,
46    /// Which sinks the alert was delivered to, and whether each took it.
47    /// Empty when the shepherd wrote the record itself: it has no sinks
48    /// and no webhook code, and says so by carrying none.
49    pub sinks: Vec<SinkOutcome>,
50}
51
52/// What one sink made of one alert.
53///
54/// Names the sink by its `[dog.bark.sinks]` config key, never by its
55/// webhook URL or bearer token, so [`Bark`] stays safe to print with a
56/// derived `Debug`.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58pub struct SinkOutcome {
59    /// The sink's name from `[dog.bark.sinks]`.
60    pub sink: String,
61    /// `None` when it was delivered; the failure otherwise.
62    pub error: Option<String>,
63}
64
65/// Error type returned by [`append`] and [`read`].
66///
67/// Wraps `io::Error`/`serde_json::Error` directly so callers keep the
68/// underlying diagnostic via [`core::error::Error::source`]; this enum
69/// cannot derive `Clone`/`PartialEq`/`Eq` as a result.
70///
71/// `#[non_exhaustive]`: shep-core is a published library, so a future
72/// failure variant must not break an out-of-tree consumer's `match`.
73#[non_exhaustive]
74#[derive(Debug)]
75pub enum BarkError {
76    /// The ring file could not be read, written, or replaced.
77    Io(std::io::Error),
78    /// A [`Bark`] could not be serialized to JSON.
79    Encode(serde_json::Error),
80}
81
82impl fmt::Display for BarkError {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        match self {
85            Self::Io(err) => write!(f, "bark ring I/O failed: {err}"),
86            Self::Encode(err) => write!(f, "bark record failed to serialize: {err}"),
87        }
88    }
89}
90
91impl core::error::Error for BarkError {
92    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
93        match self {
94            Self::Io(err) => Some(err),
95            Self::Encode(err) => Some(err),
96        }
97    }
98}
99
100impl From<std::io::Error> for BarkError {
101    fn from(source: std::io::Error) -> Self {
102        Self::Io(source)
103    }
104}
105
106impl From<serde_json::Error> for BarkError {
107    fn from(source: serde_json::Error) -> Self {
108        Self::Encode(source)
109    }
110}
111
112/// Appends `bark` to `path`, evicting oldest-first to keep the file under
113/// `max_bytes`.
114///
115/// Eviction drops a prefix of whole lines, atomically; an oversized
116/// record is written anyway, since dropping it would silently lose the
117/// one alert too big to fit. Serialized against other appenders by an
118/// advisory lock on a sibling `<path>.lock`. Concurrent [`read`]s are not
119/// blocked: the ring is only ever replaced whole.
120///
121/// # Errors
122/// - [`BarkError::Io`]: the file or its lock could not be read, written, or replaced.
123/// - [`BarkError::Encode`]: the record could not be serialized.
124pub fn append(path: &Path, bark: &Bark, max_bytes: u64) -> Result<(), BarkError> {
125    // Held until this returns, so the read and the final rename are one
126    // transaction as far as any other writer is concerned.
127    let _lock = FileLock::acquire(path)?;
128
129    let mut lines = read_lines(path)?;
130    let new_line = serde_json::to_string(bark)?;
131    lines.push(new_line);
132
133    // Oldest-out: drop the front line until the ring fits under the cap,
134    // or only the record just appended is left.
135    loop {
136        if lines.len() <= 1 || ring_bytes(&lines) <= max_bytes {
137            break;
138        }
139        lines.remove(0);
140    }
141
142    write_ring(path, &lines)
143}
144
145/// Reads every bark in `path`, oldest first, skipping any line that will
146/// not parse.
147///
148/// A line that will not parse is a partially-written record from a writer
149/// that died mid-append, or a record from a future shep. Neither refuses
150/// the whole history during an incident, which is the one time this file
151/// is read.
152///
153/// # Errors
154/// - [`BarkError::Io`]: the file exists and could not be read. A missing
155///   file is `Ok(Vec::new())`: no barks yet is not a fault.
156pub fn read(path: &Path) -> Result<Vec<Bark>, BarkError> {
157    match std::fs::read_to_string(path) {
158        Ok(text) => Ok(text
159            .lines()
160            .filter_map(|line| serde_json::from_str(line).ok())
161            .collect()),
162        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
163        Err(err) => Err(BarkError::Io(err)),
164    }
165}
166
167/// `path`'s existing lines, raw and unparsed, or an empty ring if the
168/// file does not exist yet.
169///
170/// Does not parse: eviction operates on whole lines exactly as they sit
171/// on disk, so a line a future shep wrote, or a fragment a dead writer
172/// left, still counts toward the byte cap and survives an eviction it
173/// does not trigger. [`read`] is where an unparseable line is dropped.
174fn read_lines(path: &Path) -> Result<Vec<String>, BarkError> {
175    match std::fs::read_to_string(path) {
176        Ok(text) => Ok(text.lines().map(str::to_owned).collect()),
177        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
178        Err(err) => Err(BarkError::Io(err)),
179    }
180}
181
182/// Total on-disk size, in bytes, if `lines` were written one per line
183/// (each line plus its trailing `\n`).
184fn ring_bytes(lines: &[String]) -> u64 {
185    lines.iter().map(|line| line.len() as u64 + 1).sum()
186}
187
188/// Rewrites `path` to hold exactly `lines`: the content lands in a
189/// uniquely-named sibling temp file, is `fsync`ed, then `rename`d over
190/// `path`, so an interrupted write leaves the original untouched.
191///
192/// The name is unique per call, not a fixed `<path>.tmp`: two writers
193/// racing on a shared name can have one `rename` consume the other's
194/// staging file. [`FileLock`] already keeps two appenders apart; this is
195/// the second lock for a caller that reaches `write_ring` another way.
196fn write_ring(path: &Path, lines: &[String]) -> Result<(), BarkError> {
197    let parent = path.parent().unwrap_or_else(|| Path::new("."));
198    let mut tmp = crate::atomic_file::create_staging_file(parent, "barks", ".tmp")?;
199
200    for line in lines {
201        tmp.write_all(line.as_bytes())?;
202        tmp.write_all(b"\n")?;
203    }
204    crate::atomic_file::publish(tmp, path).map_err(BarkError::Io)
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    /// A representative fired alert. `at_ms` is a caller-chosen tag, not a
212    /// real timestamp: tests use it to tell records apart.
213    fn bark_for(subject: &str, at_ms: u64) -> Bark {
214        Bark {
215            at_ms,
216            rule: "watchdog".to_string(),
217            subject: subject.to_string(),
218            message: "restart budget exhausted".to_string(),
219            sinks: vec![SinkOutcome {
220                sink: "discord".to_string(),
221                error: None,
222            }],
223        }
224    }
225
226    /// The serialized length, plus its trailing newline, of one
227    /// `bark_for`-shaped line, computed here so it cannot happen to equal
228    /// the implementation's own byte count.
229    fn one_bark_len() -> u64 {
230        let line = serde_json::to_string(&bark_for("second", 1)).unwrap();
231        line.len() as u64 + 1
232    }
233
234    /// Cap set to force eviction on the third write.
235    #[test]
236    fn the_ring_drops_the_oldest_bark_to_stay_under_its_cap() {
237        let dir = tempfile::tempdir().unwrap();
238        let path = dir.path().join("barks.jsonl");
239        let cap = 2 * one_bark_len();
240
241        for (i, subject) in ["first", "second", "third"].iter().enumerate() {
242            append(&path, &bark_for(subject, i as u64), cap).unwrap();
243        }
244
245        let barks = read(&path).unwrap();
246        let subjects: Vec<&str> = barks.iter().map(|b| b.subject.as_str()).collect();
247        assert_eq!(subjects, ["second", "third"], "oldest out, newest kept");
248        assert!(
249            std::fs::metadata(&path).unwrap().len() <= cap,
250            "the cap is a cap"
251        );
252    }
253
254    #[test]
255    fn a_bark_bigger_than_the_cap_is_written_anyway() {
256        let dir = tempfile::tempdir().unwrap();
257        let path = dir.path().join("barks.jsonl");
258        let huge = Bark {
259            message: "x".repeat(4096),
260            ..bark_for("web", 0)
261        };
262        append(&path, &huge, 64).unwrap();
263        assert_eq!(read(&path).unwrap().len(), 1);
264    }
265
266    #[test]
267    fn a_line_that_will_not_parse_costs_one_record_and_not_the_file() {
268        let dir = tempfile::tempdir().unwrap();
269        let path = dir.path().join("barks.jsonl");
270        append(&path, &bark_for("web", 1), DEFAULT_MAX_BYTES).unwrap();
271        std::fs::OpenOptions::new()
272            .append(true)
273            .open(&path)
274            .unwrap()
275            .write_all(b"{\"at_ms\": 2, \"rul\n")
276            .unwrap();
277        append(&path, &bark_for("api", 3), DEFAULT_MAX_BYTES).unwrap();
278
279        let barks = read(&path).unwrap();
280        assert_eq!(
281            barks.iter().map(|b| b.subject.as_str()).collect::<Vec<_>>(),
282            ["web", "api"]
283        );
284    }
285
286    #[test]
287    fn no_file_yet_is_no_barks_rather_than_a_failure() {
288        let dir = tempfile::tempdir().unwrap();
289        assert_eq!(read(&dir.path().join("nothing.jsonl")).unwrap(), vec![]);
290    }
291
292    /// Env var naming the ring file the re-executed child should append
293    /// to. Its presence is also what tells the child it is a child.
294    #[cfg(any(unix, windows))]
295    const CHILD_PATH_VAR: &str = "SHEP_BARK_RACE_PATH";
296    /// Env var carrying the child's tag, which it stamps into every
297    /// record's `subject` so the parent can tell the two writers apart.
298    #[cfg(any(unix, windows))]
299    const CHILD_TAG_VAR: &str = "SHEP_BARK_RACE_TAG";
300    /// How many records each of the two writers appends. Large enough
301    /// that the two read-modify-rename sequences overlap many times over.
302    #[cfg(any(unix, windows))]
303    const RECORDS_PER_WRITER: u64 = 200;
304
305    /// Not a test: the child half of
306    /// [`two_writer_processes_do_not_lose_each_other_s_barks`], re-executed
307    /// as a separate OS process via `--ignored --exact`. Asserts nothing;
308    /// its job is to hammer [`append`] while the parent judges the result.
309    #[cfg(any(unix, windows))]
310    #[test]
311    #[ignore = "child process of two_writer_processes_do_not_lose_each_other_s_barks"]
312    fn bark_race_child() {
313        let Ok(path) = std::env::var(CHILD_PATH_VAR) else {
314            panic!("{CHILD_PATH_VAR} unset — this test is only run as a child process");
315        };
316        let tag = std::env::var(CHILD_TAG_VAR).expect("child needs a tag");
317        let path = std::path::PathBuf::from(path);
318
319        for i in 0..RECORDS_PER_WRITER {
320            append(&path, &bark_for(&tag, i), DEFAULT_MAX_BYTES).expect("child append");
321        }
322    }
323
324    /// Two OS processes, not threads: an in-process mutex would prove
325    /// nothing about a race that crosses address spaces via `rename`.
326    /// Covers Windows too: reverting `acquire`'s Windows arm to
327    /// `Ok(Self {})` reddens this rather than passing quietly. Without
328    /// the lock this can still pass on a lucky serial schedule.
329    #[cfg(any(unix, windows))]
330    #[test]
331    fn two_writer_processes_do_not_lose_each_other_s_barks() {
332        let dir = tempfile::tempdir().unwrap();
333        let path = dir.path().join("barks.jsonl");
334        let exe = std::env::current_exe().expect("test binary path");
335
336        let children: Vec<_> = ["alpha", "beta"]
337            .iter()
338            .map(|tag| {
339                std::process::Command::new(&exe)
340                    .args(["--exact", "--ignored", "barks::tests::bark_race_child"])
341                    .env(CHILD_PATH_VAR, &path)
342                    .env(CHILD_TAG_VAR, tag)
343                    // Piped, not inherited: a passing run should not
344                    // interleave two child harnesses' output into this
345                    // one's, and a failing child's harness output is
346                    // exactly what the assertion below needs to show.
347                    .stdout(std::process::Stdio::piped())
348                    .spawn()
349                    .expect("spawn writer")
350            })
351            .collect();
352
353        for child in children {
354            let out = child.wait_with_output().expect("wait for writer");
355            assert!(
356                out.status.success(),
357                "a writer process failed: {}\n{}",
358                out.status,
359                String::from_utf8_lossy(&out.stdout)
360            );
361        }
362
363        let barks = read(&path).unwrap();
364        for tag in ["alpha", "beta"] {
365            let mut seen: Vec<u64> = barks
366                .iter()
367                .filter(|b| b.subject == tag)
368                .map(|b| b.at_ms)
369                .collect();
370            seen.sort_unstable();
371            let expected: Vec<u64> = (0..RECORDS_PER_WRITER).collect();
372            assert_eq!(
373                seen, expected,
374                "{tag}'s records did not all survive the other writer"
375            );
376        }
377        assert_eq!(
378            barks.len() as u64,
379            2 * RECORDS_PER_WRITER,
380            "the ring holds records nobody wrote"
381        );
382    }
383
384    /// No field here is a credential today; the mode stays narrow so a
385    /// future one that is arrives already protected.
386    #[cfg(unix)]
387    #[test]
388    fn append_creates_the_ring_owner_only_on_unix() {
389        use std::os::unix::fs::PermissionsExt;
390        let dir = tempfile::tempdir().unwrap();
391        let path = dir.path().join("barks.jsonl");
392
393        append(&path, &bark_for("web", 0), DEFAULT_MAX_BYTES).unwrap();
394
395        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
396        assert_eq!(
397            mode, 0o600,
398            "barks.jsonl is not the credential file, but stays narrow anyway"
399        );
400    }
401}