Skip to main content

troupekit_trace/
sink.rs

1use crate::record;
2use std::collections::VecDeque;
3use std::fs::{File, OpenOptions};
4use std::io::{self, BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
5use std::panic::{catch_unwind, AssertUnwindSafe};
6use std::path::{Path, PathBuf};
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8use std::sync::{Mutex, MutexGuard, PoisonError};
9
10const MEMORY_CAPACITY_DEFAULT: usize = 100_000;
11const MEMORY_BYTES_DEFAULT: usize = 64 * 1024 * 1024;
12const MARKER_BYTES_MAX: u64 = 80;
13const HEADER_LINE_BYTES_MAX: u64 = 64 * 1024;
14const MAX_BYTES_DEFAULT: u64 = 256 * 1024 * 1024;
15const FLUSH_EVERY_DEFAULT: u32 = 64;
16const PATH_NAME_BYTES_MAX: usize = 64;
17
18/// A destination for finished trace record lines.
19/// Input: one JSON line per call, without a trailing newline.
20/// A sink never returns an error and never panics through the caller.
21pub trait TraceSink: Send + Sync {
22    /// Takes one record line. Errors are counted by the sink, not returned.
23    fn write(&self, line: &str);
24
25    /// Pushes buffered lines to their destination. The default does nothing.
26    /// Trace points made during a flush are suppressed, as during a write.
27    fn flush(&self) {}
28}
29
30fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
31    mutex.lock().unwrap_or_else(PoisonError::into_inner)
32}
33
34/// Settings for `JsonlSink`. Defaults: refuse an existing file, stop at
35/// 256 MiB with one `truncated` record inside the limit, flush every 64
36/// records.
37/// Input: `with_*` setters. Output: passed to `JsonlSink::with_options`.
38#[derive(Clone, Debug, PartialEq, Eq)]
39#[non_exhaustive]
40pub struct JsonlOptions {
41    append: bool,
42    max_bytes: u64,
43    flush_every: u32,
44}
45
46impl Default for JsonlOptions {
47    fn default() -> JsonlOptions {
48        JsonlOptions {
49            append: false,
50            max_bytes: MAX_BYTES_DEFAULT,
51            flush_every: FLUSH_EVERY_DEFAULT,
52        }
53    }
54}
55
56impl JsonlOptions {
57    /// Appends to an existing file instead of refusing it. The file must be
58    /// empty or start with a trace header line, and must not be a symlink;
59    /// it is made private (mode 0600 on Unix) before the first write.
60    /// A file already at or over the byte limit opens stopped: nothing more
61    /// is written to it.
62    /// Input: the flag. Output: the options.
63    pub fn with_append(mut self, append: bool) -> JsonlOptions {
64        self.append = append;
65        self
66    }
67
68    /// Sets the byte limit of the file, the `truncated` record included.
69    /// A limit too small for that record ends the file without it.
70    /// Input: bytes. Output: the options.
71    pub fn with_max_bytes(mut self, max_bytes: u64) -> JsonlOptions {
72        self.max_bytes = max_bytes;
73        self
74    }
75
76    /// Flushes after this many records, at least 1. Input: the count.
77    /// Output: the options.
78    pub fn with_flush_every(mut self, flush_every: u32) -> JsonlOptions {
79        self.flush_every = flush_every.max(1);
80        self
81    }
82}
83
84struct JsonlState {
85    out: BufWriter<File>,
86    written: u64,
87    pending: u32,
88    stopped: bool,
89}
90
91/// Writes record lines to a private JSON lines file.
92/// The file is created with mode 0600 and missing folders with 0700 on
93/// Unix. I/O errors are counted, never returned to the traced run; a
94/// failed record write stops the sink, since its bytes on disk are unknown.
95pub struct JsonlSink {
96    state: Mutex<JsonlState>,
97    options: JsonlOptions,
98    errors: AtomicU64,
99    path: PathBuf,
100}
101
102impl JsonlSink {
103    /// Creates `path` with the default options; an existing file is refused.
104    /// Input: the file path. Output: the sink or the I/O error.
105    pub fn create(path: impl AsRef<Path>) -> io::Result<JsonlSink> {
106        JsonlSink::with_options(path, JsonlOptions::default())
107    }
108
109    /// Creates or, with `with_append(true)`, opens `path` for appending.
110    /// Input: the file path and options. Output: the sink or the I/O error.
111    pub fn with_options(path: impl AsRef<Path>, options: JsonlOptions) -> io::Result<JsonlSink> {
112        let path = path.as_ref().to_path_buf();
113        if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
114            create_private_dirs(parent)?;
115        }
116        let mut file = open_private(&path, options.append)?;
117        let written = prepare_existing(&mut file)?;
118        let state = JsonlState {
119            out: BufWriter::new(file),
120            written,
121            pending: 0,
122            stopped: written >= options.max_bytes,
123        };
124        Ok(JsonlSink {
125            state: Mutex::new(state),
126            options,
127            errors: AtomicU64::new(0),
128            path,
129        })
130    }
131
132    /// Returns the file path. Input: none. Output: the path.
133    pub fn path(&self) -> &Path {
134        &self.path
135    }
136
137    /// Returns the number of I/O errors so far. Input: none. Output: the count.
138    pub fn errors(&self) -> u64 {
139        self.errors.load(Ordering::Relaxed)
140    }
141
142    /// Returns the bytes in the file, buffered lines included.
143    /// Input: none. Output: the count.
144    pub fn bytes_written(&self) -> u64 {
145        locked(&self.state).written
146    }
147
148    fn count(&self, result: io::Result<()>) {
149        if result.is_err() {
150            self.errors.fetch_add(1, Ordering::Relaxed);
151        }
152    }
153}
154
155impl TraceSink for JsonlSink {
156    fn write(&self, line: &str) {
157        let mut state = locked(&self.state);
158        if state.stopped {
159            return;
160        }
161        let size = line.len() as u64 + 1;
162        let reserved = state.written.saturating_add(MARKER_BYTES_MAX + 1);
163        if reserved.saturating_add(size) > self.options.max_bytes {
164            state.stopped = true;
165            let marker = record::truncated_from(line);
166            let marker_size = marker.len() as u64 + 1;
167            assert!(marker_size <= MARKER_BYTES_MAX + 1);
168            if state.written + marker_size <= self.options.max_bytes {
169                let result = writeln!(state.out, "{marker}").and_then(|()| state.out.flush());
170                if result.is_ok() {
171                    state.written += marker_size;
172                }
173                self.count(result);
174            }
175            assert!(state.written <= self.options.max_bytes);
176            return;
177        }
178        let result = writeln!(state.out, "{line}");
179        if result.is_err() {
180            state.stopped = true;
181            self.count(result);
182            return;
183        }
184        state.written += size;
185        state.pending += 1;
186        if state.pending >= self.options.flush_every {
187            state.pending = 0;
188            let result = state.out.flush();
189            self.count(result);
190        }
191        assert!(state.written <= self.options.max_bytes);
192    }
193
194    fn flush(&self) {
195        let mut state = locked(&self.state);
196        state.pending = 0;
197        let result = state.out.flush();
198        self.count(result);
199    }
200}
201
202impl Drop for JsonlSink {
203    fn drop(&mut self) {
204        TraceSink::flush(self);
205    }
206}
207
208#[cfg(unix)]
209fn create_private_dirs(dir: &Path) -> io::Result<()> {
210    use std::os::unix::fs::DirBuilderExt;
211    std::fs::DirBuilder::new()
212        .recursive(true)
213        .mode(0o700)
214        .create(dir)
215}
216
217#[cfg(not(unix))]
218fn create_private_dirs(dir: &Path) -> io::Result<()> {
219    std::fs::create_dir_all(dir)
220}
221
222fn open_private(path: &Path, append: bool) -> io::Result<File> {
223    let mut options = OpenOptions::new();
224    if append {
225        let is_link = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink());
226        if is_link {
227            return Err(io::Error::new(
228                io::ErrorKind::InvalidInput,
229                "trace file is a symlink",
230            ));
231        }
232        options.read(true).append(true).create(true);
233    } else {
234        options.write(true).create_new(true);
235    }
236    #[cfg(unix)]
237    {
238        use std::os::unix::fs::OpenOptionsExt;
239        options.mode(0o600);
240    }
241    options.open(path)
242}
243
244/// Checks a file opened for appending before the first write: an existing
245/// file must start with a trace header line and is made private, and a
246/// last line without its newline gets one, so no new record joins it.
247/// Input: the open file. Output: its length after the fix, or the reason.
248fn prepare_existing(file: &mut File) -> io::Result<u64> {
249    let len = file.metadata()?.len();
250    if len == 0 {
251        return Ok(0);
252    }
253    let mut first = String::new();
254    BufReader::new(Read::by_ref(file).take(HEADER_LINE_BYTES_MAX)).read_line(&mut first)?;
255    if !(first.starts_with("{\"v\":") && first.contains(",\"t\":\"header\",")) {
256        return Err(io::Error::new(
257            io::ErrorKind::InvalidData,
258            "existing file is not a trace",
259        ));
260    }
261    make_private(file)?;
262    file.seek(SeekFrom::Start(len - 1))?;
263    let mut last = [0u8; 1];
264    file.read_exact(&mut last)?;
265    if last[0] == b'\n' {
266        return Ok(len);
267    }
268    file.write_all(b"\n")?;
269    Ok(len + 1)
270}
271
272#[cfg(unix)]
273fn make_private(file: &File) -> io::Result<()> {
274    use std::os::unix::fs::PermissionsExt;
275    let mode = file.metadata()?.permissions().mode();
276    if mode & 0o077 == 0 {
277        return Ok(());
278    }
279    file.set_permissions(std::fs::Permissions::from_mode(mode & 0o700))
280}
281
282#[cfg(not(unix))]
283fn make_private(_file: &File) -> io::Result<()> {
284    Ok(())
285}
286
287/// Keeps the newest record lines in memory, dropping the oldest past its
288/// capacity (default 100 000 lines) or its byte limit (default 64 MiB),
289/// and counting what it dropped. Input: lines. Output: `lines()` copies
290/// and `dropped()`.
291pub struct MemorySink {
292    lines: Mutex<MemoryLines>,
293    capacity: usize,
294    max_bytes: usize,
295    dropped: AtomicU64,
296}
297
298struct MemoryLines {
299    lines: VecDeque<String>,
300    bytes: usize,
301}
302
303impl Default for MemorySink {
304    fn default() -> MemorySink {
305        MemorySink::new(MEMORY_CAPACITY_DEFAULT)
306    }
307}
308
309impl MemorySink {
310    /// Returns an empty sink holding at most `capacity` lines, at least 1.
311    /// Input: the capacity. Output: the sink.
312    pub fn new(capacity: usize) -> MemorySink {
313        let capacity = capacity.max(1);
314        MemorySink {
315            lines: Mutex::new(MemoryLines {
316                lines: VecDeque::new(),
317                bytes: 0,
318            }),
319            capacity,
320            max_bytes: MEMORY_BYTES_DEFAULT,
321            dropped: AtomicU64::new(0),
322        }
323    }
324
325    /// Sets the byte limit of the kept lines, at least 1. A line longer
326    /// than the limit is dropped and counted. Input: bytes. Output: the sink.
327    pub fn with_max_bytes(mut self, max_bytes: usize) -> MemorySink {
328        self.max_bytes = max_bytes.max(1);
329        self
330    }
331
332    /// Returns a copy of the kept lines, oldest first. Input: none.
333    pub fn lines(&self) -> Vec<String> {
334        locked(&self.lines).lines.iter().cloned().collect()
335    }
336
337    /// Returns how many lines were dropped. Input: none. Output: the count.
338    pub fn dropped(&self) -> u64 {
339        self.dropped.load(Ordering::Relaxed)
340    }
341
342    /// Returns the line capacity. Input: none. Output: the capacity.
343    pub fn capacity(&self) -> usize {
344        self.capacity
345    }
346
347    /// Returns the byte limit. Input: none. Output: the limit.
348    pub fn max_bytes(&self) -> usize {
349        self.max_bytes
350    }
351}
352
353impl TraceSink for MemorySink {
354    fn write(&self, line: &str) {
355        if line.len() > self.max_bytes {
356            self.dropped.fetch_add(1, Ordering::Relaxed);
357            return;
358        }
359        let mut kept = locked(&self.lines);
360        while kept.lines.len() == self.capacity || kept.bytes + line.len() > self.max_bytes {
361            let old = kept.lines.pop_front().expect("a line over the limit was refused");
362            kept.bytes -= old.len();
363            self.dropped.fetch_add(1, Ordering::Relaxed);
364        }
365        kept.bytes += line.len();
366        kept.lines.push_back(line.to_owned());
367        assert!(kept.lines.len() <= self.capacity);
368        assert!(kept.bytes <= self.max_bytes);
369    }
370}
371
372type Callback = Box<dyn Fn(&str) + Send + Sync>;
373
374/// Hands every record line to a callback. A panic in the callback is
375/// caught, counted and disables the sink, so it never fails the run.
376/// Input: lines. Output: calls to the callback.
377pub struct CallbackSink {
378    callback: Callback,
379    disabled: AtomicBool,
380    panics: AtomicU64,
381}
382
383impl CallbackSink {
384    /// Returns a sink that calls `callback` with each line.
385    /// Input: the callback. Output: the sink.
386    pub fn new(callback: impl Fn(&str) + Send + Sync + 'static) -> CallbackSink {
387        CallbackSink {
388            callback: Box::new(callback),
389            disabled: AtomicBool::new(false),
390            panics: AtomicU64::new(0),
391        }
392    }
393
394    /// Returns how many times the callback panicked. Input: none.
395    pub fn panics(&self) -> u64 {
396        self.panics.load(Ordering::Relaxed)
397    }
398
399    /// Returns whether a panic disabled the sink. Input: none.
400    pub fn is_disabled(&self) -> bool {
401        self.disabled.load(Ordering::Relaxed)
402    }
403}
404
405impl TraceSink for CallbackSink {
406    fn write(&self, line: &str) {
407        if self.is_disabled() {
408            return;
409        }
410        if catch_unwind(AssertUnwindSafe(|| (self.callback)(line))).is_err() {
411            self.disabled.store(true, Ordering::Relaxed);
412            self.panics.fetch_add(1, Ordering::Relaxed);
413        }
414    }
415}
416
417/// Returns the default trace file path: `$TROUPEKIT_TRACE_DIR` or
418/// `./traces`, file `<name>-<trace id>.jsonl`. Bytes of `name` outside
419/// `[a-z0-9_-]` become `_`; the name is cut to 64 bytes, empty is `trace`.
420pub fn default_trace_path(name: &str, trace_id: u64) -> PathBuf {
421    let dir = std::env::var_os("TROUPEKIT_TRACE_DIR")
422        .map_or_else(|| PathBuf::from("traces"), PathBuf::from);
423    dir.join(format!("{}-{trace_id:016x}.jsonl", file_stem(name)))
424}
425
426fn file_stem(name: &str) -> String {
427    if name.is_empty() {
428        return "trace".to_owned();
429    }
430    let stem: String = name
431        .bytes()
432        .take(PATH_NAME_BYTES_MAX)
433        .map(|b| match b {
434            b'a'..=b'z' | b'0'..=b'9' | b'_' | b'-' => char::from(b),
435            _ => '_',
436        })
437        .collect();
438    assert!(stem.len() <= PATH_NAME_BYTES_MAX);
439    assert!(!stem.contains(['/', '\\', '.']));
440    stem
441}