Skip to main content

agentmux_srv_core/backend/audit_query/
jekt_file.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The jekt audit file (`reactive::audit_store`), read from its end: the file is never rotated, so a page
5//! of the newest entries reads the tail of it, and a cursor says where the next page's lines end.
6
7use std::fs::File;
8use std::io::{Read, Seek, SeekFrom};
9use std::path::Path;
10
11/// How much of the file is read at a time.
12const CHUNK: u64 = 64 * 1024;
13
14/// One line of the file: where it starts and ends (past its newline), and the raw bytes without the newline.
15pub(super) struct RawLine {
16    pub start: u64,
17    pub bytes: Vec<u8>,
18}
19
20/// The lines of a file that end at or before `end`, last first.
21pub(super) struct ReverseLines {
22    file: File,
23    /// The bytes `[pos, edge)` read so far and not yet given out.
24    buf: Vec<u8>,
25    pos: u64,
26    chunk: u64,
27}
28
29impl ReverseLines {
30    /// `end`: where the lines may end (a line boundary); None is the end of the file.
31    pub fn open(path: &Path, end: Option<u64>) -> std::io::Result<Self> {
32        Self::open_with(path, end, CHUNK)
33    }
34
35    fn open_with(path: &Path, end: Option<u64>, chunk: u64) -> std::io::Result<Self> {
36        let file = File::open(path)?;
37        let len = file.metadata()?.len();
38        let edge = end.map_or(len, |e| e.min(len));
39        Ok(Self { file, buf: Vec::new(), pos: edge, chunk: chunk.max(1) })
40    }
41
42    fn read_before(&mut self) -> std::io::Result<()> {
43        let from = self.pos.saturating_sub(self.chunk);
44        let mut more = vec![0u8; (self.pos - from) as usize];
45        self.file.seek(SeekFrom::Start(from))?;
46        self.file.read_exact(&mut more)?;
47        more.extend_from_slice(&self.buf);
48        self.buf = more;
49        self.pos = from;
50        Ok(())
51    }
52}
53
54impl Iterator for ReverseLines {
55    type Item = std::io::Result<RawLine>;
56
57    fn next(&mut self) -> Option<Self::Item> {
58        loop {
59            // Past a trailing newline there is nothing: the line before it ends there.
60            let body_end = if self.buf.last() == Some(&b'\n') { self.buf.len() - 1 } else { self.buf.len() };
61            if let Some(i) = self.buf[..body_end].iter().rposition(|b| *b == b'\n') {
62                let line = RawLine { start: self.pos + i as u64 + 1, bytes: self.buf[i + 1..body_end].to_vec() };
63                self.buf.truncate(i + 1);
64                return Some(Ok(line));
65            }
66            if self.pos == 0 {
67                if self.buf.is_empty() {
68                    return None;
69                }
70                let line = RawLine { start: 0, bytes: self.buf[..body_end].to_vec() };
71                self.buf.clear();
72                return Some(Ok(line));
73            }
74            if let Err(e) = self.read_before() {
75                // Nothing more is read after an error: asking again would fail the same way.
76                self.pos = 0;
77                self.buf.clear();
78                return Some(Err(e));
79            }
80        }
81    }
82}
83
84/// An entry of the file (an `AuditLogEntry` of the jekt file, an `ActivityRow` of a day's), with where its line starts and where it ends (the next line's start).
85pub(super) fn entries<T: serde::de::DeserializeOwned>(path: &Path, end: Option<u64>) -> impl Iterator<Item = (u64, u64, T)> {
86    ReverseLines::open(path, end).into_iter().flatten().map_while(Result::ok).filter_map(|line| {
87        let to = line.start + line.bytes.len() as u64 + 1;
88        serde_json::from_slice::<T>(&line.bytes).ok().map(|e| (line.start, to, e))
89    })
90}
91
92/// Calls `each` with every entry from byte `from` on, oldest first, and returns where the last complete line
93/// ends: a line the writer hasn't finished isn't read, and is the next scan's first.
94pub(super) fn scan<T: serde::de::DeserializeOwned>(path: &Path, from: u64, mut each: impl FnMut(T)) -> std::io::Result<u64> {
95    use std::io::BufRead;
96    let mut file = File::open(path)?;
97    file.seek(SeekFrom::Start(from))?;
98    let mut reader = std::io::BufReader::new(file);
99    let (mut at, mut line) = (from, Vec::new());
100    loop {
101        line.clear();
102        let n = reader.read_until(b'\n', &mut line)?;
103        if n == 0 || line.last() != Some(&b'\n') {
104            return Ok(at);
105        }
106        at += n as u64;
107        if let Ok(entry) = serde_json::from_slice::<T>(&line) {
108            each(entry);
109        }
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use crate::backend::reactive::types::AuditLogEntry;
117
118    fn file_of(lines: &[&str], trailing_newline: bool) -> (tempfile::TempDir, std::path::PathBuf) {
119        let dir = tempfile::tempdir().unwrap();
120        let path = dir.path().join("jekt-audit.jsonl");
121        let mut text = lines.join("\n");
122        if trailing_newline {
123            text.push('\n');
124        }
125        std::fs::write(&path, text).unwrap();
126        (dir, path)
127    }
128
129    fn all(path: &Path, end: Option<u64>, chunk: u64) -> Vec<(u64, String)> {
130        ReverseLines::open_with(path, end, chunk)
131            .unwrap()
132            .map(|l| l.unwrap())
133            .map(|l| (l.start, String::from_utf8(l.bytes).unwrap()))
134            .collect()
135    }
136
137    #[test]
138    fn lines_come_last_first_whatever_the_chunk_size() {
139        let lines = ["alpha", "bb", "", "gamma-gamma-gamma", "d"];
140        for trailing in [true, false] {
141            let (_dir, path) = file_of(&lines, trailing);
142            for chunk in [1, 2, 3, 7, 64] {
143                let got = all(&path, None, chunk);
144                let want: Vec<&str> = lines.iter().rev().copied().collect();
145                assert_eq!(got.iter().map(|(_, l)| l.as_str()).collect::<Vec<_>>(), want, "chunk {chunk}, trailing {trailing}");
146            }
147        }
148    }
149
150    #[test]
151    fn a_line_start_is_where_a_later_read_can_end() {
152        let (_dir, path) = file_of(&["one", "two", "three"], true);
153        let got = all(&path, None, 4);
154        assert_eq!(got[0], (8, "three".to_string()));
155        // Reading from the start of "three" gives what came before it.
156        let before = all(&path, Some(8), 4);
157        assert_eq!(before.iter().map(|(_, l)| l.as_str()).collect::<Vec<_>>(), ["two", "one"]);
158        assert!(all(&path, Some(0), 4).is_empty());
159    }
160
161    #[test]
162    fn a_read_error_ends_the_lines_instead_of_repeating() {
163        let (_dir, path) = file_of(&["alpha", "bravo", "charlie", "delta"], true);
164        let mut lines = ReverseLines::open_with(&path, None, 4).unwrap();
165        // The file shrinks after it was measured: reading back past the new end fails.
166        std::fs::write(&path, "al").unwrap();
167        let got: Vec<_> = lines.by_ref().take(10).collect();
168        assert!(got.iter().any(|l| l.is_err()), "the error is reported once");
169        assert!(got.len() < 10 && lines.next().is_none(), "and then there is nothing more");
170    }
171
172    #[test]
173    fn a_scan_stops_before_a_line_the_writer_has_not_finished() {
174        let dir = tempfile::tempdir().unwrap();
175        let path = dir.path().join("a.jsonl");
176        let line = |ts: u64| format!("{}\n", serde_json::json!({"timestamp": ts, "target_agent": "x", "block_id": "", "message_hash": "", "message_length": 0, "success": true, "request_id": ""}));
177        std::fs::write(&path, format!("{}{}{{\"timestamp\":3", line(1), line(2))).unwrap();
178        let mut seen = Vec::new();
179        let end = scan(&path, 0, |e: AuditLogEntry| seen.push(e.timestamp)).unwrap();
180        assert_eq!((seen.clone(), end), (vec![1, 2], (line(1).len() + line(2).len()) as u64));
181        // Finished, it is read from where the scan stopped.
182        std::fs::write(&path, format!("{}{}{}", line(1), line(2), line(3))).unwrap();
183        seen.clear();
184        scan(&path, end, |e: AuditLogEntry| seen.push(e.timestamp)).unwrap();
185        assert_eq!(seen, [3]);
186    }
187
188    #[test]
189    fn an_empty_or_missing_file_has_no_lines() {
190        let (_dir, path) = file_of(&[], false);
191        assert!(all(&path, None, 4).is_empty());
192        assert_eq!(entries::<AuditLogEntry>(&path.with_file_name("nope"), None).count(), 0);
193    }
194
195    #[test]
196    fn a_line_that_is_not_an_entry_is_skipped() {
197        let (_dir, path) = file_of(&["{not json", "{\"x\":1}"], true);
198        assert_eq!(entries::<AuditLogEntry>(&path, None).count(), 0);
199    }
200}