use crate::record;
use std::collections::VecDeque;
use std::fs::{File, OpenOptions};
use std::io::{self, BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard, PoisonError};
const MEMORY_CAPACITY_DEFAULT: usize = 100_000;
const MEMORY_BYTES_DEFAULT: usize = 64 * 1024 * 1024;
const MARKER_BYTES_MAX: u64 = 80;
const HEADER_LINE_BYTES_MAX: u64 = 64 * 1024;
const MAX_BYTES_DEFAULT: u64 = 256 * 1024 * 1024;
const FLUSH_EVERY_DEFAULT: u32 = 64;
const PATH_NAME_BYTES_MAX: usize = 64;
pub trait TraceSink: Send + Sync {
fn write(&self, line: &str);
fn flush(&self) {}
}
fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct JsonlOptions {
append: bool,
max_bytes: u64,
flush_every: u32,
}
impl Default for JsonlOptions {
fn default() -> JsonlOptions {
JsonlOptions {
append: false,
max_bytes: MAX_BYTES_DEFAULT,
flush_every: FLUSH_EVERY_DEFAULT,
}
}
}
impl JsonlOptions {
pub fn with_append(mut self, append: bool) -> JsonlOptions {
self.append = append;
self
}
pub fn with_max_bytes(mut self, max_bytes: u64) -> JsonlOptions {
self.max_bytes = max_bytes;
self
}
pub fn with_flush_every(mut self, flush_every: u32) -> JsonlOptions {
self.flush_every = flush_every.max(1);
self
}
}
struct JsonlState {
out: BufWriter<File>,
written: u64,
pending: u32,
stopped: bool,
}
pub struct JsonlSink {
state: Mutex<JsonlState>,
options: JsonlOptions,
errors: AtomicU64,
path: PathBuf,
}
impl JsonlSink {
pub fn create(path: impl AsRef<Path>) -> io::Result<JsonlSink> {
JsonlSink::with_options(path, JsonlOptions::default())
}
pub fn with_options(path: impl AsRef<Path>, options: JsonlOptions) -> io::Result<JsonlSink> {
let path = path.as_ref().to_path_buf();
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
create_private_dirs(parent)?;
}
let mut file = open_private(&path, options.append)?;
let written = prepare_existing(&mut file)?;
let state = JsonlState {
out: BufWriter::new(file),
written,
pending: 0,
stopped: written >= options.max_bytes,
};
Ok(JsonlSink {
state: Mutex::new(state),
options,
errors: AtomicU64::new(0),
path,
})
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn errors(&self) -> u64 {
self.errors.load(Ordering::Relaxed)
}
pub fn bytes_written(&self) -> u64 {
locked(&self.state).written
}
fn count(&self, result: io::Result<()>) {
if result.is_err() {
self.errors.fetch_add(1, Ordering::Relaxed);
}
}
}
impl TraceSink for JsonlSink {
fn write(&self, line: &str) {
let mut state = locked(&self.state);
if state.stopped {
return;
}
let size = line.len() as u64 + 1;
let reserved = state.written.saturating_add(MARKER_BYTES_MAX + 1);
if reserved.saturating_add(size) > self.options.max_bytes {
state.stopped = true;
let marker = record::truncated_from(line);
let marker_size = marker.len() as u64 + 1;
assert!(marker_size <= MARKER_BYTES_MAX + 1);
if state.written + marker_size <= self.options.max_bytes {
let result = writeln!(state.out, "{marker}").and_then(|()| state.out.flush());
if result.is_ok() {
state.written += marker_size;
}
self.count(result);
}
assert!(state.written <= self.options.max_bytes);
return;
}
let result = writeln!(state.out, "{line}");
if result.is_err() {
state.stopped = true;
self.count(result);
return;
}
state.written += size;
state.pending += 1;
if state.pending >= self.options.flush_every {
state.pending = 0;
let result = state.out.flush();
self.count(result);
}
assert!(state.written <= self.options.max_bytes);
}
fn flush(&self) {
let mut state = locked(&self.state);
state.pending = 0;
let result = state.out.flush();
self.count(result);
}
}
impl Drop for JsonlSink {
fn drop(&mut self) {
TraceSink::flush(self);
}
}
#[cfg(unix)]
fn create_private_dirs(dir: &Path) -> io::Result<()> {
use std::os::unix::fs::DirBuilderExt;
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)
}
#[cfg(not(unix))]
fn create_private_dirs(dir: &Path) -> io::Result<()> {
std::fs::create_dir_all(dir)
}
fn open_private(path: &Path, append: bool) -> io::Result<File> {
let mut options = OpenOptions::new();
if append {
let is_link = std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink());
if is_link {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"trace file is a symlink",
));
}
options.read(true).append(true).create(true);
} else {
options.write(true).create_new(true);
}
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
options.open(path)
}
fn prepare_existing(file: &mut File) -> io::Result<u64> {
let len = file.metadata()?.len();
if len == 0 {
return Ok(0);
}
let mut first = String::new();
BufReader::new(Read::by_ref(file).take(HEADER_LINE_BYTES_MAX)).read_line(&mut first)?;
if !(first.starts_with("{\"v\":") && first.contains(",\"t\":\"header\",")) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"existing file is not a trace",
));
}
make_private(file)?;
file.seek(SeekFrom::Start(len - 1))?;
let mut last = [0u8; 1];
file.read_exact(&mut last)?;
if last[0] == b'\n' {
return Ok(len);
}
file.write_all(b"\n")?;
Ok(len + 1)
}
#[cfg(unix)]
fn make_private(file: &File) -> io::Result<()> {
use std::os::unix::fs::PermissionsExt;
let mode = file.metadata()?.permissions().mode();
if mode & 0o077 == 0 {
return Ok(());
}
file.set_permissions(std::fs::Permissions::from_mode(mode & 0o700))
}
#[cfg(not(unix))]
fn make_private(_file: &File) -> io::Result<()> {
Ok(())
}
pub struct MemorySink {
lines: Mutex<MemoryLines>,
capacity: usize,
max_bytes: usize,
dropped: AtomicU64,
}
struct MemoryLines {
lines: VecDeque<String>,
bytes: usize,
}
impl Default for MemorySink {
fn default() -> MemorySink {
MemorySink::new(MEMORY_CAPACITY_DEFAULT)
}
}
impl MemorySink {
pub fn new(capacity: usize) -> MemorySink {
let capacity = capacity.max(1);
MemorySink {
lines: Mutex::new(MemoryLines {
lines: VecDeque::new(),
bytes: 0,
}),
capacity,
max_bytes: MEMORY_BYTES_DEFAULT,
dropped: AtomicU64::new(0),
}
}
pub fn with_max_bytes(mut self, max_bytes: usize) -> MemorySink {
self.max_bytes = max_bytes.max(1);
self
}
pub fn lines(&self) -> Vec<String> {
locked(&self.lines).lines.iter().cloned().collect()
}
pub fn dropped(&self) -> u64 {
self.dropped.load(Ordering::Relaxed)
}
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn max_bytes(&self) -> usize {
self.max_bytes
}
}
impl TraceSink for MemorySink {
fn write(&self, line: &str) {
if line.len() > self.max_bytes {
self.dropped.fetch_add(1, Ordering::Relaxed);
return;
}
let mut kept = locked(&self.lines);
while kept.lines.len() == self.capacity || kept.bytes + line.len() > self.max_bytes {
let old = kept.lines.pop_front().expect("a line over the limit was refused");
kept.bytes -= old.len();
self.dropped.fetch_add(1, Ordering::Relaxed);
}
kept.bytes += line.len();
kept.lines.push_back(line.to_owned());
assert!(kept.lines.len() <= self.capacity);
assert!(kept.bytes <= self.max_bytes);
}
}
type Callback = Box<dyn Fn(&str) + Send + Sync>;
pub struct CallbackSink {
callback: Callback,
disabled: AtomicBool,
panics: AtomicU64,
}
impl CallbackSink {
pub fn new(callback: impl Fn(&str) + Send + Sync + 'static) -> CallbackSink {
CallbackSink {
callback: Box::new(callback),
disabled: AtomicBool::new(false),
panics: AtomicU64::new(0),
}
}
pub fn panics(&self) -> u64 {
self.panics.load(Ordering::Relaxed)
}
pub fn is_disabled(&self) -> bool {
self.disabled.load(Ordering::Relaxed)
}
}
impl TraceSink for CallbackSink {
fn write(&self, line: &str) {
if self.is_disabled() {
return;
}
if catch_unwind(AssertUnwindSafe(|| (self.callback)(line))).is_err() {
self.disabled.store(true, Ordering::Relaxed);
self.panics.fetch_add(1, Ordering::Relaxed);
}
}
}
pub fn default_trace_path(name: &str, trace_id: u64) -> PathBuf {
let dir = std::env::var_os("TROUPEKIT_TRACE_DIR")
.map_or_else(|| PathBuf::from("traces"), PathBuf::from);
dir.join(format!("{}-{trace_id:016x}.jsonl", file_stem(name)))
}
fn file_stem(name: &str) -> String {
if name.is_empty() {
return "trace".to_owned();
}
let stem: String = name
.bytes()
.take(PATH_NAME_BYTES_MAX)
.map(|b| match b {
b'a'..=b'z' | b'0'..=b'9' | b'_' | b'-' => char::from(b),
_ => '_',
})
.collect();
assert!(stem.len() <= PATH_NAME_BYTES_MAX);
assert!(!stem.contains(['/', '\\', '.']));
stem
}