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    Ok(read_text(path)?
158        .lines()
159        .filter_map(|line| serde_json::from_str(line).ok())
160        .collect())
161}
162
163/// `path`'s existing lines, raw and unparsed, or an empty ring if the
164/// file does not exist yet.
165///
166/// Does not parse: eviction operates on whole lines exactly as they sit
167/// on disk, so a line a future shep wrote, or a fragment a dead writer
168/// left, still counts toward the byte cap and survives an eviction it
169/// does not trigger. [`read`] is where an unparseable line is dropped.
170fn read_lines(path: &Path) -> Result<Vec<String>, BarkError> {
171    Ok(read_text(path)?.lines().map(str::to_owned).collect())
172}
173
174/// `path`'s bytes, or an empty string if the file is not there yet.
175///
176/// A ring nobody has written to is an empty ring, not a fault, and both
177/// readers above want exactly that reading before they go their separate
178/// ways on what to do with the lines.
179fn read_text(path: &Path) -> Result<String, BarkError> {
180    match std::fs::read_to_string(path) {
181        Ok(text) => Ok(text),
182        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
183        Err(err) => Err(BarkError::Io(err)),
184    }
185}
186
187/// Total on-disk size, in bytes, if `lines` were written one per line
188/// (each line plus its trailing `\n`).
189fn ring_bytes(lines: &[String]) -> u64 {
190    lines.iter().map(|line| line.len() as u64 + 1).sum()
191}
192
193/// Rewrites `path` to hold exactly `lines`: the content lands in a
194/// uniquely-named sibling temp file, is `fsync`ed, then `rename`d over
195/// `path`, so an interrupted write leaves the original untouched.
196///
197/// The name is unique per call, not a fixed `<path>.tmp`: two writers
198/// racing on a shared name can have one `rename` consume the other's
199/// staging file. [`FileLock`] already keeps two appenders apart; this is
200/// the second lock for a caller that reaches `write_ring` another way.
201fn write_ring(path: &Path, lines: &[String]) -> Result<(), BarkError> {
202    let parent = crate::atomic_file::parent_of(path);
203    let mut tmp = crate::atomic_file::create_staging_file(parent, "barks", ".tmp")?;
204
205    for line in lines {
206        tmp.write_all(line.as_bytes())?;
207        tmp.write_all(b"\n")?;
208    }
209    crate::atomic_file::publish(tmp, path).map_err(BarkError::Io)
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    /// A representative fired alert. `at_ms` is a caller-chosen tag, not a
217    /// real timestamp: tests use it to tell records apart.
218    fn bark_for(subject: &str, at_ms: u64) -> Bark {
219        Bark {
220            at_ms,
221            rule: "watchdog".to_string(),
222            subject: subject.to_string(),
223            message: "restart budget exhausted".to_string(),
224            sinks: vec![SinkOutcome {
225                sink: "discord".to_string(),
226                error: None,
227            }],
228        }
229    }
230
231    /// The serialized length, plus its trailing newline, of one
232    /// `bark_for`-shaped line, computed here so it cannot happen to equal
233    /// the implementation's own byte count.
234    fn one_bark_len() -> u64 {
235        let line = serde_json::to_string(&bark_for("second", 1)).unwrap();
236        line.len() as u64 + 1
237    }
238
239    /// Cap set to force eviction on the third write.
240    #[test]
241    fn the_ring_drops_the_oldest_bark_to_stay_under_its_cap() {
242        let dir = tempfile::tempdir().unwrap();
243        let path = dir.path().join("barks.jsonl");
244        let cap = 2 * one_bark_len();
245
246        for (i, subject) in ["first", "second", "third"].iter().enumerate() {
247            append(&path, &bark_for(subject, i as u64), cap).unwrap();
248        }
249
250        let barks = read(&path).unwrap();
251        let subjects: Vec<&str> = barks.iter().map(|b| b.subject.as_str()).collect();
252        assert_eq!(subjects, ["second", "third"], "oldest out, newest kept");
253        assert!(
254            std::fs::metadata(&path).unwrap().len() <= cap,
255            "the cap is a cap"
256        );
257    }
258
259    #[test]
260    fn a_bark_bigger_than_the_cap_is_written_anyway() {
261        let dir = tempfile::tempdir().unwrap();
262        let path = dir.path().join("barks.jsonl");
263        let huge = Bark {
264            message: "x".repeat(4096),
265            ..bark_for("web", 0)
266        };
267        append(&path, &huge, 64).unwrap();
268        assert_eq!(read(&path).unwrap().len(), 1);
269    }
270
271    #[test]
272    fn a_line_that_will_not_parse_costs_one_record_and_not_the_file() {
273        let dir = tempfile::tempdir().unwrap();
274        let path = dir.path().join("barks.jsonl");
275        append(&path, &bark_for("web", 1), DEFAULT_MAX_BYTES).unwrap();
276        std::fs::OpenOptions::new()
277            .append(true)
278            .open(&path)
279            .unwrap()
280            .write_all(b"{\"at_ms\": 2, \"rul\n")
281            .unwrap();
282        append(&path, &bark_for("api", 3), DEFAULT_MAX_BYTES).unwrap();
283
284        let barks = read(&path).unwrap();
285        assert_eq!(
286            barks.iter().map(|b| b.subject.as_str()).collect::<Vec<_>>(),
287            ["web", "api"]
288        );
289    }
290
291    #[test]
292    fn no_file_yet_is_no_barks_rather_than_a_failure() {
293        let dir = tempfile::tempdir().unwrap();
294        assert_eq!(read(&dir.path().join("nothing.jsonl")).unwrap(), vec![]);
295    }
296
297    /// Env var naming the ring file the re-executed child should append
298    /// to. Its presence is also what tells the child it is a child.
299    #[cfg(any(unix, windows))]
300    const CHILD_PATH_VAR: &str = "SHEP_BARK_RACE_PATH";
301    /// Env var carrying the child's tag, which it stamps into every
302    /// record's `subject` so the parent can tell the two writers apart.
303    #[cfg(any(unix, windows))]
304    const CHILD_TAG_VAR: &str = "SHEP_BARK_RACE_TAG";
305    /// How many records each of the two writers appends. Large enough
306    /// that the two read-modify-rename sequences overlap many times over.
307    #[cfg(any(unix, windows))]
308    const RECORDS_PER_WRITER: u64 = 200;
309
310    /// Not a test: the child half of
311    /// [`two_writer_processes_do_not_lose_each_other_s_barks`], re-executed
312    /// as a separate OS process via `--ignored --exact`. Asserts nothing;
313    /// its job is to hammer [`append`] while the parent judges the result.
314    #[cfg(any(unix, windows))]
315    #[test]
316    #[ignore = "child process of two_writer_processes_do_not_lose_each_other_s_barks"]
317    fn bark_race_child() {
318        let Ok(path) = std::env::var(CHILD_PATH_VAR) else {
319            panic!("{CHILD_PATH_VAR} unset — this test is only run as a child process");
320        };
321        let tag = std::env::var(CHILD_TAG_VAR).expect("child needs a tag");
322        let path = std::path::PathBuf::from(path);
323
324        for i in 0..RECORDS_PER_WRITER {
325            append(&path, &bark_for(&tag, i), DEFAULT_MAX_BYTES).expect("child append");
326        }
327    }
328
329    /// Two OS processes, not threads: an in-process mutex would prove
330    /// nothing about a race that crosses address spaces via `rename`.
331    /// Covers Windows too: reverting `acquire`'s Windows arm to
332    /// `Ok(Self {})` reddens this rather than passing quietly. Without
333    /// the lock this can still pass on a lucky serial schedule.
334    #[cfg(any(unix, windows))]
335    #[test]
336    fn two_writer_processes_do_not_lose_each_other_s_barks() {
337        let dir = tempfile::tempdir().unwrap();
338        let path = dir.path().join("barks.jsonl");
339        let exe = std::env::current_exe().expect("test binary path");
340
341        let children: Vec<_> = ["alpha", "beta"]
342            .iter()
343            .map(|tag| {
344                std::process::Command::new(&exe)
345                    .args(["--exact", "--ignored", "barks::tests::bark_race_child"])
346                    .env(CHILD_PATH_VAR, &path)
347                    .env(CHILD_TAG_VAR, tag)
348                    // Piped, not inherited: a passing run should not
349                    // interleave two child harnesses' output into this
350                    // one's, and a failing child's harness output is
351                    // exactly what the assertion below needs to show.
352                    .stdout(std::process::Stdio::piped())
353                    .spawn()
354                    .expect("spawn writer")
355            })
356            .collect();
357
358        for child in children {
359            let out = child.wait_with_output().expect("wait for writer");
360            assert!(
361                out.status.success(),
362                "a writer process failed: {}\n{}",
363                out.status,
364                String::from_utf8_lossy(&out.stdout)
365            );
366        }
367
368        let barks = read(&path).unwrap();
369        for tag in ["alpha", "beta"] {
370            let mut seen: Vec<u64> = barks
371                .iter()
372                .filter(|b| b.subject == tag)
373                .map(|b| b.at_ms)
374                .collect();
375            seen.sort_unstable();
376            let expected: Vec<u64> = (0..RECORDS_PER_WRITER).collect();
377            assert_eq!(
378                seen, expected,
379                "{tag}'s records did not all survive the other writer"
380            );
381        }
382        assert_eq!(
383            barks.len() as u64,
384            2 * RECORDS_PER_WRITER,
385            "the ring holds records nobody wrote"
386        );
387    }
388
389    /// No field here is a credential today; the mode stays narrow so a
390    /// future one that is arrives already protected.
391    #[cfg(unix)]
392    #[test]
393    fn append_creates_the_ring_owner_only_on_unix() {
394        use std::os::unix::fs::PermissionsExt;
395        let dir = tempfile::tempdir().unwrap();
396        let path = dir.path().join("barks.jsonl");
397
398        append(&path, &bark_for("web", 0), DEFAULT_MAX_BYTES).unwrap();
399
400        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
401        assert_eq!(
402            mode, 0o600,
403            "barks.jsonl is not the credential file, but stays narrow anyway"
404        );
405    }
406}