Skip to main content

mur_common/
ledger.rs

1use anyhow::{Context, Result};
2use chrono::{Local, NaiveDate};
3use serde::{Serialize, de::DeserializeOwned};
4use std::{
5    fs::{self, OpenOptions},
6    io::{BufRead, BufReader, Write},
7    path::{Path, PathBuf},
8    time::{Duration, Instant},
9};
10
11/// Append-only JSONL ledger with per-day file rotation.
12///
13/// Generic over the event type `E`. For multi-writer scenarios,
14/// wrap in `Arc<Mutex<Ledger<E>>>` — the file-level `flock` is
15/// handled by the OS when opening for append.
16pub struct Ledger<E> {
17    base_dir: PathBuf,
18    last_fsync: Instant,
19    _marker: std::marker::PhantomData<E>,
20}
21
22impl<E: Serialize + DeserializeOwned> Ledger<E> {
23    /// Open (or create) a ledger directory.
24    pub fn open(base_dir: &Path) -> Result<Self> {
25        fs::create_dir_all(base_dir).context("create ledger dir")?;
26        Ok(Self {
27            base_dir: base_dir.to_path_buf(),
28            last_fsync: Instant::now(),
29            _marker: std::marker::PhantomData,
30        })
31    }
32
33    /// Append one event to today's JSONL file. Debounced fsync (≤1s).
34    pub fn append(&mut self, event: &E) -> Result<()> {
35        let today = Local::now().date_naive().format("%Y-%m-%d").to_string();
36        let path = self.base_dir.join(format!("{today}.jsonl"));
37        let mut f = OpenOptions::new()
38            .create(true)
39            .append(true)
40            .open(&path)
41            .with_context(|| format!("open ledger {}", path.display()))?;
42        let line = serde_json::to_string(event).context("serialize event")?;
43        writeln!(f, "{line}").context("write event")?;
44
45        if self.last_fsync.elapsed() > Duration::from_secs(1) {
46            f.sync_data().context("fsync ledger")?;
47            self.last_fsync = Instant::now();
48        }
49        Ok(())
50    }
51
52    pub fn base_dir(&self) -> &Path {
53        &self.base_dir
54    }
55
56    pub fn flush(&mut self) -> Result<()> {
57        let today = Local::now().date_naive().format("%Y-%m-%d").to_string();
58        let path = self.base_dir.join(format!("{today}.jsonl"));
59        if path.exists() {
60            let f = OpenOptions::new()
61                .write(true)
62                .open(&path)
63                .with_context(|| format!("open for fsync {}", path.display()))?;
64            f.sync_data().context("fsync ledger")?;
65        }
66        self.last_fsync = Instant::now();
67        Ok(())
68    }
69
70    /// Scan the most recent `days` daily files in chronological order.
71    /// Skips malformed lines and missing files.
72    pub fn scan_days(base_dir: &Path, days: u32) -> Vec<Result<E>> {
73        let mut out = Vec::new();
74        if !base_dir.exists() {
75            return out;
76        }
77        let today = Local::now().date_naive();
78        let mut dates: Vec<_> = (0..days as i64)
79            .map(|i| today - chrono::Duration::days(i))
80            .collect();
81        dates.sort();
82        for date in dates {
83            let p = day_path(base_dir, date);
84            if p.exists() {
85                let _ = read_day(&p, |e| out.push(Ok(e)));
86            }
87        }
88        out
89    }
90
91    /// Scan every daily file dated `since` or later (all of them when `None`),
92    /// oldest first, tagging each event with its file's day.
93    ///
94    /// Unlike [`Self::scan_days`] the window is not tied to today, so a reader
95    /// that must not lose old records (trash expiry, #2174) can resume from a
96    /// day it chose. Files not named `YYYY-MM-DD.jsonl` and malformed lines are
97    /// skipped. Read failures are NOT silent: the result says which days could
98    /// not be read in full and whether the directory listing itself failed, so
99    /// a caller that checkpoints progress can tell a complete replay from one
100    /// that missed records (review #2176 P2).
101    pub fn scan_since(base_dir: &Path, since: Option<NaiveDate>) -> DayScan<E> {
102        let mut scan = DayScan {
103            events: Vec::new(),
104            unreadable_days: Vec::new(),
105            malformed_days: Vec::new(),
106            listing_failed: false,
107        };
108        let dir = match fs::read_dir(base_dir) {
109            Ok(dir) => dir,
110            // No ledger yet: an empty but complete replay.
111            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return scan,
112            Err(e) => {
113                tracing::warn!("ledger {} not listable: {e}", base_dir.display());
114                scan.listing_failed = true;
115                return scan;
116            }
117        };
118        let mut days = Vec::new();
119        for item in dir {
120            let Ok(item) = item else {
121                scan.listing_failed = true;
122                continue;
123            };
124            let Ok(name) = item.file_name().into_string() else {
125                continue;
126            };
127            let Some(day) = name
128                .strip_suffix(".jsonl")
129                .and_then(|stem| NaiveDate::parse_from_str(stem, DAY_FORMAT).ok())
130            else {
131                continue;
132            };
133            if since.is_none_or(|s| day >= s) {
134                days.push(day);
135            }
136        }
137        days.sort();
138        for day in days {
139            let read = read_day(&day_path(base_dir, day), |e| scan.events.push((day, e)));
140            if !read.complete {
141                scan.unreadable_days.push(day);
142            }
143            if read.malformed {
144                scan.malformed_days.push(day);
145            }
146        }
147        scan
148    }
149}
150
151/// Result of [`Ledger::scan_since`].
152#[derive(Debug)]
153pub struct DayScan<E> {
154    /// Every well-formed event read, oldest day first, with its file's day.
155    pub events: Vec<(NaiveDate, E)>,
156    /// Days whose file could not be opened or read to the end; their records
157    /// may be missing from `events`.
158    pub unreadable_days: Vec<NaiveDate>,
159    /// Days with at least one line that did not parse; that record is lost,
160    /// so a reader that must account for every record cannot trust the sum.
161    pub malformed_days: Vec<NaiveDate>,
162    /// The directory listing failed, so whole days may be missing.
163    pub listing_failed: bool,
164}
165
166impl<E> DayScan<E> {
167    /// True when every matching day file was read to the end.
168    pub fn is_complete(&self) -> bool {
169        !self.listing_failed && self.unreadable_days.is_empty()
170    }
171
172    /// [`Self::is_complete`] and no malformed line either: every record that
173    /// was written is in `events`.
174    pub fn is_exact(&self) -> bool {
175        self.is_complete() && self.malformed_days.is_empty()
176    }
177}
178
179/// What reading one day file found.
180struct DayRead {
181    /// The file opened and every line was read (I/O-wise).
182    complete: bool,
183    /// At least one line did not parse.
184    malformed: bool,
185}
186
187const DAY_FORMAT: &str = "%Y-%m-%d";
188
189fn day_path(base_dir: &Path, day: NaiveDate) -> PathBuf {
190    base_dir.join(format!("{}.jsonl", day.format(DAY_FORMAT)))
191}
192
193/// Feed every well-formed event in one day file to `push`, reporting whether
194/// the file was read in full and whether any line failed to parse.
195fn read_day<E: DeserializeOwned>(p: &Path, mut push: impl FnMut(E)) -> DayRead {
196    let f = match fs::File::open(p) {
197        Ok(f) => f,
198        Err(err) => {
199            tracing::warn!("ledger {} not readable: {err}", p.display());
200            return DayRead {
201                complete: false,
202                malformed: false,
203            };
204        }
205    };
206    let mut complete = true;
207    let mut malformed = false;
208    for (i, line) in BufReader::new(f).lines().enumerate() {
209        let line = match line {
210            Ok(line) => line,
211            Err(err) => {
212                tracing::warn!("ledger {}:{} read failed: {err}", p.display(), i + 1);
213                complete = false;
214                continue;
215            }
216        };
217        if line.trim().is_empty() {
218            continue;
219        }
220        match serde_json::from_str::<E>(&line) {
221            Ok(e) => push(e),
222            Err(err) => {
223                malformed = true;
224                tracing::warn!(
225                    "ledger {}:{} skip malformed line: {err}",
226                    p.display(),
227                    i + 1
228                );
229            }
230        }
231    }
232    DayRead {
233        complete,
234        malformed,
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241    use serde::Deserialize;
242    use tempfile::TempDir;
243
244    #[derive(Debug, Serialize, Deserialize, PartialEq)]
245    struct TestEvent {
246        msg: String,
247        n: u32,
248    }
249
250    #[test]
251    fn append_and_scan_roundtrip() {
252        let tmp = TempDir::new().unwrap();
253        let mut ledger = Ledger::<TestEvent>::open(tmp.path()).unwrap();
254        ledger
255            .append(&TestEvent {
256                msg: "hello".into(),
257                n: 1,
258            })
259            .unwrap();
260        ledger
261            .append(&TestEvent {
262                msg: "world".into(),
263                n: 2,
264            })
265            .unwrap();
266        // Must flush so the file is on disk before scanning
267        ledger.flush().unwrap();
268        drop(ledger);
269
270        let results = Ledger::<TestEvent>::scan_days(tmp.path(), 1);
271        let events: Vec<_> = results.into_iter().filter_map(|r| r.ok()).collect();
272        assert_eq!(events.len(), 2);
273        assert_eq!(events[0].msg, "hello");
274        assert_eq!(events[1].msg, "world");
275    }
276
277    #[test]
278    fn open_creates_missing_dir() {
279        let tmp = TempDir::new().unwrap();
280        let sub = tmp.path().join("sub");
281        let _ledger = Ledger::<TestEvent>::open(&sub).unwrap();
282        assert!(sub.exists());
283    }
284
285    #[test]
286    fn scan_empty_dir_returns_empty() {
287        let tmp = TempDir::new().unwrap();
288        let results = Ledger::<TestEvent>::scan_days(tmp.path(), 7);
289        assert!(results.is_empty());
290    }
291
292    #[test]
293    fn scan_skips_malformed_lines() {
294        let tmp = TempDir::new().unwrap();
295        let today = Local::now().date_naive().format("%Y-%m-%d").to_string();
296        let path = tmp.path().join(format!("{today}.jsonl"));
297        std::fs::write(
298            &path,
299            r#"{"msg":"ok","n":1}"#.to_string()
300                + "\n"
301                + "garbage\n"
302                + r#"{"msg":"also ok","n":3}"#
303                + "\n",
304        )
305        .unwrap();
306
307        let results = Ledger::<TestEvent>::scan_days(tmp.path(), 1);
308        let events: Vec<_> = results.into_iter().filter_map(|r| r.ok()).collect();
309        assert_eq!(events.len(), 2);
310        assert_eq!(events[0].msg, "ok");
311        assert_eq!(events[1].msg, "also ok");
312    }
313
314    #[test]
315    fn scan_since_reads_old_files_and_respects_the_start_day() {
316        let tmp = TempDir::new().unwrap();
317        let today = Local::now().date_naive();
318        for (age, n) in [(400i64, 1u32), (40, 2), (0, 3)] {
319            let day = today - chrono::Duration::days(age);
320            std::fs::write(
321                day_path(tmp.path(), day),
322                format!("{{\"msg\":\"m\",\"n\":{n}}}\n"),
323            )
324            .unwrap();
325        }
326        std::fs::write(tmp.path().join("notes.jsonl"), "garbage\n").unwrap();
327
328        let all = Ledger::<TestEvent>::scan_since(tmp.path(), None);
329        assert!(all.is_complete());
330        let all = all.events;
331        let ns: Vec<u32> = all.iter().map(|(_, e)| e.n).collect();
332        assert_eq!(ns, vec![1, 2, 3], "every day file, oldest first");
333        assert_eq!(all[0].0, today - chrono::Duration::days(400));
334
335        let since = today - chrono::Duration::days(40);
336        let recent = Ledger::<TestEvent>::scan_since(tmp.path(), Some(since)).events;
337        let ns: Vec<u32> = recent.iter().map(|(_, e)| e.n).collect();
338        assert_eq!(ns, vec![2, 3], "start day inclusive");
339    }
340
341    #[test]
342    fn scan_since_missing_dir_is_empty() {
343        let tmp = TempDir::new().unwrap();
344        let scan = Ledger::<TestEvent>::scan_since(&tmp.path().join("nope"), None);
345        assert!(scan.events.is_empty());
346        assert!(scan.is_complete(), "no ledger yet is complete, not failed");
347    }
348
349    #[cfg(unix)]
350    #[test]
351    fn scan_since_reports_an_unreadable_day() {
352        use std::os::unix::fs::PermissionsExt;
353        let tmp = TempDir::new().unwrap();
354        let day = Local::now().date_naive() - chrono::Duration::days(100);
355        let p = day_path(tmp.path(), day);
356        std::fs::write(&p, "{\"msg\":\"m\",\"n\":1}\n").unwrap();
357        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o000)).unwrap();
358        let scan = Ledger::<TestEvent>::scan_since(tmp.path(), None);
359        std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o644)).unwrap();
360        if scan.events.len() == 1 {
361            return; // running as root: permissions do not block reads
362        }
363        assert!(!scan.is_complete());
364        assert_eq!(scan.unreadable_days, vec![day]);
365    }
366
367    #[test]
368    fn scan_since_reports_a_malformed_line_without_calling_the_day_unreadable() {
369        let tmp = TempDir::new().unwrap();
370        let day = Local::now().date_naive();
371        std::fs::write(
372            day_path(tmp.path(), day),
373            "{\"msg\":\"m\",\"n\":1}\ngarbage\n",
374        )
375        .unwrap();
376        let scan = Ledger::<TestEvent>::scan_since(tmp.path(), None);
377        assert_eq!(scan.events.len(), 1);
378        assert!(scan.is_complete(), "a parse error is not an I/O failure");
379        assert!(!scan.is_exact());
380        assert_eq!(scan.malformed_days, vec![day]);
381    }
382}