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
18pub trait TraceSink: Send + Sync {
22 fn write(&self, line: &str);
24
25 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#[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 pub fn with_append(mut self, append: bool) -> JsonlOptions {
64 self.append = append;
65 self
66 }
67
68 pub fn with_max_bytes(mut self, max_bytes: u64) -> JsonlOptions {
72 self.max_bytes = max_bytes;
73 self
74 }
75
76 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
91pub struct JsonlSink {
96 state: Mutex<JsonlState>,
97 options: JsonlOptions,
98 errors: AtomicU64,
99 path: PathBuf,
100}
101
102impl JsonlSink {
103 pub fn create(path: impl AsRef<Path>) -> io::Result<JsonlSink> {
106 JsonlSink::with_options(path, JsonlOptions::default())
107 }
108
109 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 pub fn path(&self) -> &Path {
134 &self.path
135 }
136
137 pub fn errors(&self) -> u64 {
139 self.errors.load(Ordering::Relaxed)
140 }
141
142 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
244fn 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
287pub 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 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 pub fn with_max_bytes(mut self, max_bytes: usize) -> MemorySink {
328 self.max_bytes = max_bytes.max(1);
329 self
330 }
331
332 pub fn lines(&self) -> Vec<String> {
334 locked(&self.lines).lines.iter().cloned().collect()
335 }
336
337 pub fn dropped(&self) -> u64 {
339 self.dropped.load(Ordering::Relaxed)
340 }
341
342 pub fn capacity(&self) -> usize {
344 self.capacity
345 }
346
347 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
374pub struct CallbackSink {
378 callback: Callback,
379 disabled: AtomicBool,
380 panics: AtomicU64,
381}
382
383impl CallbackSink {
384 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 pub fn panics(&self) -> u64 {
396 self.panics.load(Ordering::Relaxed)
397 }
398
399 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
417pub 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}