use std::collections::BTreeSet;
use std::fs;
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use std::thread::JoinHandle;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::store::{Store, StoreError};
use crate::trace::{Trace, TraceId, TraceKind, TraceSummary};
const BACKLOG: usize = 256;
const WAIT: Duration = Duration::from_secs(2);
const HALF_WRITTEN: Duration = Duration::from_secs(60);
const TRACE: &str = ".json";
const SUMMARY: &str = ".summary.json";
const TEMPORARY: &str = ".tmp";
#[derive(Debug)]
pub(crate) struct FileStore {
settings: Settings,
writer: OnceLock<Option<SyncSender<Message>>>,
thread: Mutex<Option<(JoinHandle<()>, Receiver<()>)>>,
discarded: AtomicUsize,
warned: [AtomicBool; 2],
waiting: Arc<AtomicUsize>,
}
#[derive(Debug, Clone)]
struct Settings {
directory: PathBuf,
capacity: usize,
max_age: Duration,
max_trace_bytes: usize,
}
#[derive(Debug, Clone, Copy)]
enum Discard {
Backlog,
Stopped,
}
#[derive(Debug)]
enum Message {
Write(Box<Trace>),
Flush(SyncSender<()>),
}
impl FileStore {
#[must_use]
pub(crate) fn new(directory: impl Into<PathBuf>) -> Self {
Self {
settings: Settings {
directory: directory.into(),
capacity: 100,
max_age: Duration::from_hours(24),
max_trace_bytes: 2 * 1024 * 1024,
},
writer: OnceLock::new(),
thread: Mutex::new(None),
discarded: AtomicUsize::new(0),
warned: [AtomicBool::new(false), AtomicBool::new(false)],
waiting: Arc::default(),
}
}
#[must_use]
#[cfg(test)]
pub(crate) fn with_capacity(mut self, capacity: usize) -> Self {
self.settings.capacity = capacity.max(1);
self
}
#[must_use]
#[cfg(test)]
pub(crate) fn with_max_age(mut self, max_age: Duration) -> Self {
self.settings.max_age = max_age;
self
}
#[must_use]
#[cfg(test)]
pub(crate) fn with_max_trace_bytes(mut self, bytes: usize) -> Self {
self.settings.max_trace_bytes = bytes;
self
}
#[must_use]
#[cfg(test)]
pub(crate) fn discarded(&self) -> usize {
self.discarded.load(Ordering::Relaxed)
}
fn writer(&self) -> Option<&SyncSender<Message>> {
self.writer
.get_or_init(|| {
let (sender, receiver) = mpsc::sync_channel(BACKLOG);
let (ending, ended) = mpsc::channel::<()>();
let settings = self.settings.clone();
let waiting = Arc::clone(&self.waiting);
let thread = std::thread::Builder::new()
.name("devtools-store".to_owned())
.spawn(move || {
let _ending = ending;
write_all(&settings, &receiver, &waiting);
});
match thread {
Ok(thread) => {
*self.thread.lock().unwrap_or_else(PoisonError::into_inner) = Some((thread, ended));
Some(sender)
}
Err(error) => {
tracing::warn!(
error = &error as &dyn std::error::Error,
"the devtools history's writer couldn't be started"
);
None
}
}
})
.as_ref()
}
fn discard(&self, reason: Discard) {
self.discarded.fetch_add(1, Ordering::Relaxed);
if self.warned[reason as usize].swap(true, Ordering::Relaxed) {
return;
}
let directory = self.settings.directory.display();
match reason {
Discard::Backlog => tracing::warn!(
waiting = BACKLOG,
%directory,
"traces are being discarded: the devtools history's writer can't keep up"
),
Discard::Stopped => tracing::warn!(
%directory,
"traces are being discarded: the devtools history's writer has stopped"
),
}
}
fn flush(&self) {
let Some(Some(writer)) = self.writer.get() else {
return;
};
let (done, written) = mpsc::sync_channel(1);
if writer.try_send(Message::Flush(done)).is_ok() {
let _ = written.recv_timeout(WAIT);
}
}
fn ids(&self) -> Result<Vec<TraceId>, StoreError> {
let oldest = oldest_kept(self.settings.max_age);
let mut ids: Vec<TraceId> = files(&self.settings.directory)?
.into_iter()
.filter_map(|file| match file {
File::Summary(id) if id.millis() >= oldest => Some(id),
_ => None,
})
.collect();
ids.sort_unstable_by(|a, b| b.cmp(a));
ids.truncate(self.settings.capacity);
Ok(ids)
}
}
impl Store for FileStore {
fn put(&self, trace: Trace) {
let wait = trace.kind != TraceKind::Request;
let Some(writer) = self.writer() else {
self.discarded.fetch_add(1, Ordering::Relaxed);
return;
};
self.waiting.fetch_add(1, Ordering::Relaxed);
match writer.try_send(Message::Write(Box::new(trace))) {
Ok(()) if wait => self.flush(),
Ok(()) => {}
Err(error) => {
self.waiting.fetch_sub(1, Ordering::Relaxed);
self.discard(match error {
TrySendError::Full(_) => Discard::Backlog,
TrySendError::Disconnected(_) => Discard::Stopped,
});
}
}
}
fn list(&self) -> Result<Vec<TraceSummary>, StoreError> {
self.flush();
let directory = &self.settings.directory;
Ok(self
.ids()?
.into_iter()
.filter_map(|id| fs::read(directory.join(format!("{id}{SUMMARY}"))).ok())
.filter_map(|json| serde_json::from_slice(&json).ok())
.collect())
}
fn get(&self, id: TraceId) -> Result<Option<Trace>, StoreError> {
self.flush();
if !self.ids()?.contains(&id) {
return Ok(None);
}
match fs::read(self.settings.directory.join(format!("{id}{TRACE}"))) {
Ok(json) => Ok(Some(serde_json::from_slice(&json)?)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error.into()),
}
}
fn summary(&self, id: TraceId) -> Result<Option<TraceSummary>, StoreError> {
self.flush();
if !self.ids()?.contains(&id) {
return Ok(None);
}
match fs::read(self.settings.directory.join(format!("{id}{SUMMARY}"))) {
Ok(json) => Ok(Some(serde_json::from_slice(&json)?)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error.into()),
}
}
fn clear(&self) -> Result<(), StoreError> {
self.flush();
let directory = &self.settings.directory;
let files = files(directory)?;
let summaries: BTreeSet<TraceId> = files
.iter()
.filter_map(|file| match file {
File::Summary(id) => Some(*id),
_ => None,
})
.collect();
let mut gone: Vec<&File> = files
.iter()
.filter(|file| match file {
File::Summary(_) => true,
File::Trace(id) => summaries.contains(id) || half_written(&directory.join(file.name())),
File::Temporary(name) => half_written(&directory.join(name)),
})
.collect();
remove_all(directory, &mut gone)
}
}
impl Drop for FileStore {
fn drop(&mut self) {
drop(self.writer.take());
let Some((thread, ended)) = self.thread.get_mut().unwrap_or_else(PoisonError::into_inner).take() else {
return;
};
if ended.recv_timeout(WAIT) == Err(RecvTimeoutError::Disconnected) {
let _ = thread.join();
} else {
let waiting = self.waiting.load(Ordering::Relaxed);
tracing::warn!(
waiting,
"the devtools history is still being written; traces still waiting are lost if the process ends now"
);
}
}
}
fn write_all(settings: &Settings, receiver: &Receiver<Message>, waiting: &AtomicUsize) {
let directory = settings.directory.display();
loop {
match receiver.recv_timeout(Duration::from_hours(1)) {
Ok(Message::Write(trace)) => {
let written = write(settings, *trace);
waiting.fetch_sub(1, Ordering::Relaxed);
match written {
Ok(()) => prune_or_warn(settings),
Err(error) => {
tracing::warn!(
error = &error as &dyn std::error::Error,
%directory,
"a trace couldn't be written to the devtools history"
);
}
}
}
Ok(Message::Flush(done)) => {
let _ = done.try_send(());
}
Err(RecvTimeoutError::Timeout) => prune_or_warn(settings),
Err(RecvTimeoutError::Disconnected) => return,
}
}
}
fn prune_or_warn(settings: &Settings) {
if let Err(error) = prune(settings) {
let directory = settings.directory.display();
tracing::warn!(
error = &error as &dyn std::error::Error,
%directory,
"old traces couldn't be removed from the devtools history"
);
}
}
fn write(settings: &Settings, mut trace: Trace) -> Result<(), StoreError> {
let summary = serde_json::to_vec(&trace.summary())?;
let json = fit(&mut trace, settings.max_trace_bytes)?;
create_directory(&settings.directory)?;
let id = trace.id;
write_whole(&settings.directory, &format!("{id}{TRACE}"), &json)?;
write_whole(&settings.directory, &format!("{id}{SUMMARY}"), &summary)
}
fn fit(trace: &mut Trace, max: usize) -> Result<Vec<u8>, StoreError> {
if size(trace, max)?.is_some() {
return Ok(serde_json::to_vec(trace)?);
}
let parents: Vec<Option<usize>> = trace.spans.iter().map(|span| span.parent).collect();
let dropped = trace.dropped;
let (spans, logs) = (std::mem::take(&mut trace.spans), std::mem::take(&mut trace.logs));
let (all_spans, all_logs) = (spans.len(), logs.len());
trace.dropped.spans = dropped.spans.saturating_add(all_spans);
trace.dropped.logs = dropped.logs.saturating_add(all_logs);
let mut room = size(trace, max)?.map_or(0, |bare| max - bare);
let (mut kept_spans, mut kept_logs) = (0, 0);
loop {
let span_next = match (spans.get(kept_spans), logs.get(kept_logs)) {
(Some(span), Some(log)) => span.start <= log.at,
(Some(_), None) => true,
(None, Some(_)) => false,
(None, None) => break,
};
let next = match (span_next, spans.get(kept_spans), logs.get(kept_logs)) {
(true, Some(span), _) => size(span, room)?.map(|size| size + 1),
(false, _, Some(log)) => size(log, room)?.map(|size| size + ",null".len()),
_ => None,
};
let Some(left) = next.and_then(|next| room.checked_sub(next)) else {
break;
};
room = left;
if span_next {
kept_spans += 1;
} else {
kept_logs += 1;
}
}
trace.spans = spans;
trace.logs = logs;
trace.spans.truncate(kept_spans);
trace.logs.truncate(kept_logs);
trace.dropped.spans = dropped.spans.saturating_add(all_spans - kept_spans);
trace.dropped.logs = dropped.logs.saturating_add(all_logs - kept_logs);
move_lines_to_kept_spans(trace, &parents);
Ok(serde_json::to_vec(trace)?)
}
fn move_lines_to_kept_spans(trace: &mut Trace, parents: &[Option<usize>]) {
let spans = trace.spans.len();
for log in &mut trace.logs {
while let Some(span) = log.span.filter(|&span| span >= spans) {
log.span = parents.get(span).copied().flatten().filter(|&parent| parent < span);
}
}
}
fn size(value: &impl serde::Serialize, max: usize) -> Result<Option<usize>, serde_json::Error> {
struct Counted {
bytes: usize,
max: usize,
}
impl io::Write for Counted {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.bytes += buf.len();
if self.bytes > self.max {
return Err(io::ErrorKind::FileTooLarge.into());
}
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
let mut counted = Counted { bytes: 0, max };
match serde_json::to_writer(&mut counted, value) {
Ok(()) => Ok(Some(counted.bytes)),
Err(_) if counted.bytes > max => Ok(None),
Err(error) => Err(error),
}
}
fn write_whole(directory: &Path, name: &str, bytes: &[u8]) -> Result<(), StoreError> {
let temporary = directory.join(format!(".{name}.{}{TEMPORARY}", std::process::id()));
let result = owner_only_file(&temporary)
.and_then(|mut file| file.write_all(bytes))
.and_then(|()| fs::rename(&temporary, directory.join(name)));
if result.is_err() {
let _ = fs::remove_file(&temporary);
}
Ok(result?)
}
fn prune(settings: &Settings) -> Result<(), StoreError> {
let oldest = oldest_kept(settings.max_age);
let files = files(&settings.directory)?;
let mut ids: Vec<TraceId> = files
.iter()
.filter_map(|file| match file {
File::Trace(id) | File::Summary(id) => Some(*id),
File::Temporary(_) => None,
})
.collect();
ids.sort_unstable_by(|a, b| b.cmp(a));
ids.dedup();
let kept: Vec<TraceId> = ids
.into_iter()
.filter(|id| id.millis() >= oldest)
.take(settings.capacity)
.collect();
let mut gone: Vec<&File> = files
.iter()
.filter(|file| match file {
File::Trace(id) | File::Summary(id) => kept.binary_search_by(|kept| id.cmp(kept)).is_err(),
File::Temporary(name) => half_written(&settings.directory.join(name)),
})
.collect();
remove_all(&settings.directory, &mut gone)
}
fn remove_all(directory: &Path, files: &mut [&File]) -> Result<(), StoreError> {
files.sort_by_key(|file| (!matches!(file, File::Summary(_)), file.name()));
let mut first_error = None;
for file in files {
if let Err(error) = remove(&directory.join(file.name())) {
first_error.get_or_insert(error);
}
}
first_error.map_or(Ok(()), Err)
}
fn half_written(path: &Path) -> bool {
fs::symlink_metadata(path)
.and_then(|metadata| metadata.modified())
.is_ok_and(|modified| modified.elapsed().is_ok_and(|age| age > HALF_WRITTEN))
}
#[derive(Debug)]
enum File {
Trace(TraceId),
Summary(TraceId),
Temporary(String),
}
impl File {
fn parse(name: &str) -> Option<Self> {
if let Some(rest) = name.strip_prefix('.')
&& let Some(rest) = rest.strip_suffix(TEMPORARY)
{
rest.get(..32)?.parse::<TraceId>().ok()?;
return Some(Self::Temporary(name.to_owned()));
}
if let Some(id) = name.strip_suffix(SUMMARY) {
return id.parse().ok().map(Self::Summary);
}
name.strip_suffix(TRACE)?.parse().ok().map(Self::Trace)
}
fn name(&self) -> String {
match self {
Self::Trace(id) => format!("{id}{TRACE}"),
Self::Summary(id) => format!("{id}{SUMMARY}"),
Self::Temporary(name) => name.clone(),
}
}
}
fn files(directory: &Path) -> Result<Vec<File>, StoreError> {
let entries = match fs::read_dir(directory) {
Ok(entries) => entries,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(error.into()),
};
let mut files = Vec::new();
for entry in entries {
if let Some(file) = entry?.file_name().to_str().and_then(File::parse) {
files.push(file);
}
}
Ok(files)
}
fn remove(path: &Path) -> Result<(), StoreError> {
match fs::remove_file(path) {
Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error.into()),
_ => Ok(()),
}
}
fn oldest_kept(max_age: Duration) -> u64 {
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
u64::try_from(now.saturating_sub(max_age).as_millis()).unwrap_or(u64::MAX)
}
#[cfg(unix)]
fn create_directory(directory: &Path) -> io::Result<()> {
use std::os::unix::fs::DirBuilderExt as _;
if let Some(parent) = directory.parent().filter(|parent| !parent.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
}
match fs::DirBuilder::new().mode(0o700).create(directory) {
Err(error) if error.kind() != io::ErrorKind::AlreadyExists => Err(error),
_ => Ok(()),
}
}
#[cfg(not(unix))]
fn create_directory(directory: &Path) -> io::Result<()> {
fs::create_dir_all(directory)
}
#[cfg(unix)]
fn owner_only_file(path: &Path) -> io::Result<fs::File> {
use std::os::unix::fs::OpenOptionsExt as _;
fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
}
#[cfg(not(unix))]
fn owner_only_file(path: &Path) -> io::Result<fs::File> {
fs::OpenOptions::new().write(true).create_new(true).open(path)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::trace::{Dropped, Fields, Level, LogRecord, SpanKind, SpanRecord};
#[derive(Clone, Default)]
struct Captured(Arc<Mutex<Vec<u8>>>);
impl io::Write for Captured {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn a_discarded_trace_is_told_once_for_each_reason() {
let captured = Captured::default();
let writer = captured.clone();
let subscriber = tracing_subscriber::fmt()
.with_ansi(false)
.with_writer(move || writer.clone())
.finish();
let store = FileStore::new("storage/devtools");
tracing::subscriber::with_default(subscriber, || {
for reason in [Discard::Backlog, Discard::Stopped, Discard::Backlog, Discard::Stopped] {
store.discard(reason);
}
});
let output = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
assert_eq!(output.matches("can't keep up").count(), 1, "{output}");
assert_eq!(output.matches("has stopped").count(), 1, "{output}");
assert_eq!(store.discarded(), 4);
}
struct Directory(PathBuf);
impl Drop for Directory {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
impl std::ops::Deref for Directory {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}
fn directory(name: &str) -> Directory {
let directory = std::env::temp_dir().join(format!("laravel-rust-devtools-{}-{name}", std::process::id()));
let _ = fs::remove_dir_all(&directory);
Directory(directory)
}
fn id(ago: Duration, n: u32) -> TraceId {
let started = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.checked_sub(ago)
.unwrap();
format!("{:012x}{:020x}", started.as_millis(), n).parse().unwrap()
}
fn trace(id: TraceId, name: &str) -> Trace {
Trace {
id,
kind: TraceKind::Job,
name: name.to_owned(),
started_at: UNIX_EPOCH + Duration::from_millis(id.millis()),
duration: Duration::from_millis(1),
status: None,
failed: false,
fields: Fields::new(),
spans: Vec::new(),
logs: Vec::new(),
dropped: Dropped::default(),
}
}
fn names(store: &FileStore) -> Vec<String> {
store.list().unwrap().into_iter().map(|summary| summary.name).collect()
}
fn file_names(directory: &Path) -> Vec<String> {
let mut names: Vec<String> = fs::read_dir(directory)
.unwrap()
.map(|entry| entry.unwrap().file_name().into_string().unwrap())
.collect();
names.sort();
names
}
#[test]
fn the_history_outlives_the_store() {
let directory = directory("restart");
let wanted = trace(id(Duration::ZERO, 1), "first");
let store = FileStore::new(&*directory);
store.put(wanted.clone());
let mut second = trace(id(Duration::ZERO, 2), "second");
second.kind = TraceKind::Request;
store.put(second);
drop(store);
let store = FileStore::new(&*directory);
assert_eq!(names(&store), ["second", "first"]);
assert_eq!(store.get(wanted.id).unwrap(), Some(wanted));
assert_eq!(store.get(id(Duration::ZERO, 3)).unwrap(), None);
}
#[test]
fn work_other_than_a_request_waits_until_its_trace_is_written() {
let directory = directory("wait");
let store = FileStore::new(&*directory);
let job = id(Duration::ZERO, 1);
store.put(trace(job, "job"));
assert_eq!(
file_names(&directory),
[format!("{job}.json"), format!("{job}.summary.json")]
);
drop(store);
}
#[test]
fn a_store_reads_what_it_was_just_handed() {
let directory = directory("own-writes");
let store = FileStore::new(&*directory);
let mut request = trace(id(Duration::ZERO, 1), "GET /");
request.kind = TraceKind::Request;
store.put(request);
assert_eq!(names(&store), ["GET /"]);
drop(store);
}
#[test]
fn a_full_store_removes_the_oldest() {
let directory = directory("capacity");
let store = FileStore::new(&*directory).with_capacity(2);
let ids: Vec<TraceId> = (1..=3).map(|n| id(Duration::ZERO, n)).collect();
for (n, id) in ids.iter().enumerate() {
store.put(trace(*id, &format!("job {}", n + 1)));
}
assert_eq!(names(&store), ["job 3", "job 2"]);
assert_eq!(store.get(ids[0]).unwrap(), None);
assert!(store.get(ids[1]).unwrap().is_some());
assert_eq!(store.summary(ids[0]).unwrap(), None);
assert_eq!(
store.summary(ids[1]).unwrap().map(|summary| summary.name),
Some("job 2".to_owned())
);
assert_eq!(file_names(&directory).len(), 4, "{:?}", file_names(&directory));
drop(store);
}
#[test]
fn traces_older_than_the_max_age_are_removed() {
let directory = directory("age");
let old = id(Duration::from_hours(2), 1);
let kept_longer = FileStore::new(&*directory);
kept_longer.put(trace(old, "old"));
drop(kept_longer);
let store = FileStore::new(&*directory).with_max_age(Duration::from_hours(1));
assert_eq!(names(&store), Vec::<String>::new());
assert_eq!(store.get(old).unwrap(), None);
assert_eq!(store.summary(old).unwrap(), None);
assert_eq!(file_names(&directory).len(), 2, "{:?}", file_names(&directory));
store.put(trace(id(Duration::ZERO, 2), "new"));
assert_eq!(names(&store), ["new"]);
assert_eq!(file_names(&directory).len(), 2, "{:?}", file_names(&directory));
drop(store);
}
#[test]
fn a_trace_too_large_loses_its_last_spans_and_lines() {
let directory = directory("large");
let store = FileStore::new(&*directory).with_max_trace_bytes(64 * 1024);
let mut large = trace(id(Duration::ZERO, 1), "large");
for n in 0..1_000_usize {
let at = Duration::from_millis(n.try_into().unwrap());
large.spans.push(SpanRecord {
parent: n.checked_sub(1),
kind: if n % 2 == 0 { SpanKind::Query } else { SpanKind::Other },
name: format!("span {n}"),
target: "app".to_owned(),
start: at,
duration: None,
open: false,
failed: false,
fields: Fields::from([("text".to_owned(), "x".repeat(100).into())]),
});
large.logs.push(LogRecord {
at: at + Duration::from_micros(1),
level: Level::Info,
target: "app".to_owned(),
message: "y".repeat(100),
span: Some(n),
fields: Fields::new(),
});
}
let id = large.id;
store.put(large);
let kept = store.get(id).unwrap().unwrap();
let size = fs::metadata(directory.join(format!("{}.json", kept.id))).unwrap().len();
assert!((60 * 1024..=64 * 1024).contains(&size), "{size}");
assert!(
kept.logs.len().abs_diff(kept.spans.len()) <= 1,
"{} {}",
kept.logs.len(),
kept.spans.len()
);
assert!(
!kept.spans.is_empty() && kept.spans.len() < 1_000,
"{}",
kept.spans.len()
);
assert_eq!(kept.dropped.spans, 1_000 - kept.spans.len());
assert_eq!(kept.dropped.logs, 1_000 - kept.logs.len());
assert!(
kept.logs
.iter()
.all(|log| log.span.is_some_and(|span| span < kept.spans.len()))
);
let summary = store.list().unwrap().remove(0);
assert_eq!((summary.queries, summary.logs), (500, 1_000));
drop(store);
}
#[test]
fn spans_that_point_at_themselves_or_ahead_are_not_followed() {
let directory = directory("cycle");
let mut cyclic = trace(id(Duration::ZERO, 1), "cyclic");
let span = |parent| SpanRecord {
parent,
kind: SpanKind::Other,
name: "span".to_owned(),
target: "app".to_owned(),
start: Duration::from_millis(1),
duration: None,
open: false,
failed: false,
fields: Fields::from([("text".to_owned(), "x".repeat(1024).into())]),
};
cyclic.spans = vec![span(None), span(Some(1)), span(Some(3)), span(Some(2))];
let line = |span| LogRecord {
at: Duration::ZERO,
level: Level::Info,
target: "app".to_owned(),
message: "line".to_owned(),
span: Some(span),
fields: Fields::new(),
};
cyclic.logs = vec![line(1), line(2), line(3), line(9)];
let id = cyclic.id;
let (written, done) = mpsc::channel();
let path = directory.to_path_buf();
std::thread::spawn(move || {
let store = FileStore::new(path).with_max_trace_bytes(2 * 1024);
store.put(cyclic);
let _ = written.send(store.get(id));
});
let kept = done.recv_timeout(Duration::from_secs(10)).unwrap().unwrap().unwrap();
assert_eq!((kept.spans.len(), kept.logs.len()), (1, 4));
assert!(
kept.logs
.iter()
.all(|log| log.span.is_none_or(|span| span < kept.spans.len())),
"{:?}",
kept.logs
);
}
#[test]
fn a_file_being_written_is_left_alone_however_long_its_work_ran() {
let directory = directory("temporary");
fs::create_dir_all(&*directory).unwrap();
let writing = directory.join(format!(".{}.json.1.tmp", id(Duration::from_secs(120), 1)));
let left = directory.join(format!(".{}.json.2.tmp", id(Duration::from_secs(120), 2)));
fs::write(&writing, "being written").unwrap();
fs::write(&left, "left half-written").unwrap();
let two_minutes_ago = SystemTime::now().checked_sub(Duration::from_secs(120)).unwrap();
fs::File::options()
.write(true)
.open(&left)
.unwrap()
.set_modified(two_minutes_ago)
.unwrap();
let store = FileStore::new(&*directory);
store.put(trace(id(Duration::ZERO, 3), "job"));
assert!(writing.exists());
assert!(!left.exists());
store.clear().unwrap();
assert_eq!(file_names(&directory), [writing.file_name().unwrap().to_str().unwrap()]);
drop(store);
}
#[test]
fn a_trace_still_waiting_for_its_summary_outlives_clearing() {
let directory = directory("clear-between");
fs::create_dir_all(&*directory).unwrap();
let writing = trace(id(Duration::ZERO, 1), "being written");
let json = serde_json::to_vec(&writing).unwrap();
fs::write(directory.join(format!("{}{TRACE}", writing.id)), &json).unwrap();
let left = id(Duration::from_secs(120), 2);
let left_path = directory.join(format!("{left}{TRACE}"));
fs::write(&left_path, &json).unwrap();
let two_minutes_ago = SystemTime::now().checked_sub(Duration::from_secs(120)).unwrap();
fs::File::options()
.write(true)
.open(&left_path)
.unwrap()
.set_modified(two_minutes_ago)
.unwrap();
let store = FileStore::new(&*directory);
store.clear().unwrap();
assert_eq!(file_names(&directory), [format!("{}{TRACE}", writing.id)]);
let summary = serde_json::to_vec(&writing.summary()).unwrap();
fs::write(directory.join(format!("{}{SUMMARY}", writing.id)), summary).unwrap();
assert_eq!(names(&store), ["being written"]);
assert_eq!(store.get(writing.id).unwrap(), Some(writing));
drop(store);
}
#[test]
fn broken_and_foreign_files_are_left_out_and_left_alone() {
let directory = directory("broken");
let store = FileStore::new(&*directory);
let broken = id(Duration::ZERO, 1);
store.put(trace(broken, "broken"));
store.put(trace(id(Duration::ZERO, 2), "fine"));
fs::write(directory.join(format!("{broken}.json")), "{").unwrap();
fs::write(directory.join(format!("{}.summary.json", id(Duration::ZERO, 3))), "{").unwrap();
fs::write(directory.join("README.md"), "mine").unwrap();
assert_eq!(names(&store), ["fine", "broken"]);
assert!(matches!(store.get(broken), Err(StoreError::Json(_))));
store.clear().unwrap();
assert_eq!(names(&store), Vec::<String>::new());
assert_eq!(file_names(&directory), ["README.md"]);
drop(store);
}
#[test]
fn what_can_t_be_removed_doesn_t_keep_the_rest() {
let directory = directory("stuck");
fs::create_dir_all(&*directory).unwrap();
let stuck: Vec<String> = (1..=3)
.map(|n| {
let suffix = if n == 2 { SUMMARY } else { TRACE };
format!("{}{suffix}", id(Duration::from_secs(60), n))
})
.collect();
for name in &stuck {
fs::create_dir(directory.join(name)).unwrap();
}
let store = FileStore::new(&*directory).with_capacity(1);
let ids: Vec<TraceId> = (4..=6).map(|n| id(Duration::ZERO, n)).collect();
for id in &ids {
store.put(trace(*id, "job"));
}
let mut kept = stuck.clone();
kept.extend([format!("{}.json", ids[2]), format!("{}.summary.json", ids[2])]);
assert_eq!(file_names(&directory), kept);
assert!(store.clear().is_err());
assert_eq!(file_names(&directory), stuck);
drop(store);
}
struct Random(u64);
impl Random {
fn below(&mut self, n: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
usize::try_from(self.0 % u64::try_from(n.max(1)).unwrap()).unwrap()
}
fn chance(&mut self, one_in: usize) -> bool {
self.below(one_in) == 0
}
fn time(&mut self, usual: u64) -> Duration {
if self.chance(6) {
Duration::from_micros(u64::try_from(self.below(usize::MAX)).unwrap())
} else {
Duration::from_micros(usual)
}
}
fn fields(&mut self) -> Fields {
(0..self.below(4))
.map(|n| {
let len = if self.chance(10) {
self.below(20_000)
} else {
self.below(200)
};
let text: String = (0..len).map(|k| ['"', '\u{1}', 'ü', 'a', 'a'][(k + n) % 5]).collect();
(format!("f{n}"), text.into())
})
.collect()
}
fn index(&mut self, spans: usize) -> Option<usize> {
match self.below(8) {
0 => None,
1 => Some(usize::MAX),
2 => Some(self.below(spans + 5)),
_ => (spans > 0).then(|| self.below(spans)),
}
}
fn trace(&mut self, id: TraceId) -> Trace {
let mut random = trace(id, "random");
if self.chance(4) {
random.fields = self.fields();
}
let spans = self.below(300);
for n in 0..spans {
let parent = if self.chance(5) {
self.index(spans)
} else {
n.checked_sub(1 + self.below(3))
};
let start = self.time(u64::try_from(n).unwrap() * 10);
random.spans.push(SpanRecord {
parent,
kind: if self.chance(2) {
SpanKind::Query
} else {
SpanKind::Other
},
name: "span".to_owned(),
target: "app".to_owned(),
start,
duration: self.chance(9).then_some(Duration::MAX),
open: false,
failed: false,
fields: self.fields(),
});
}
for n in 0..self.below(300) {
let at = self.time(u64::try_from(n).unwrap() * 10 + 5);
random.logs.push(LogRecord {
at,
level: Level::Info,
target: "app".to_owned(),
message: "line".to_owned(),
span: self.index(spans),
fields: self.fields(),
});
}
if self.chance(5) {
random.dropped = Dropped {
spans: usize::MAX - self.below(3),
logs: usize::MAX - self.below(3),
};
}
random
}
}
#[test]
fn any_trace_is_cut_to_its_limit() {
let (finished, done) = mpsc::channel();
std::thread::spawn(move || {
let mut random = Random(0x9e37_79b9_7f4a_7c15);
for round in 0..100 {
let whole = random.trace(id(Duration::ZERO, round));
let max = match random.below(4) {
0 => random.below(2_000),
1 => random.below(64 * 1024),
2 => random.below(2 * 1024 * 1024),
_ => 0,
};
let mut cut = whole.clone();
let json = fit(&mut cut, max).unwrap();
assert_eq!(json, serde_json::to_vec(&cut).unwrap(), "round {round}");
if size(&whole, max).unwrap().is_some() {
assert_eq!(cut, whole, "round {round}");
continue;
}
assert!(
json.len() <= max || (cut.spans.is_empty() && cut.logs.is_empty()),
"round {round}: {} bytes of {max}",
json.len()
);
assert_eq!(cut.spans, whole.spans[..cut.spans.len()], "round {round}");
assert!(
cut.logs
.iter()
.zip(&whole.logs)
.all(|(cut, whole)| (cut.at, &cut.fields) == (whole.at, &whole.fields)),
"round {round}"
);
assert!(
cut.logs
.iter()
.all(|log| log.span.is_none_or(|span| span < cut.spans.len())),
"round {round}"
);
let left_out = |before: usize, all: usize, kept: usize| before.saturating_add(all - kept);
assert_eq!(
cut.dropped,
Dropped {
spans: left_out(whole.dropped.spans, whole.spans.len(), cut.spans.len()),
logs: left_out(whole.dropped.logs, whole.logs.len(), cut.logs.len()),
},
"round {round}"
);
}
let _ = finished.send(());
});
done.recv_timeout(Duration::from_secs(60)).unwrap();
}
#[test]
fn the_limit_holds_to_the_byte() {
let span = |n: u64| SpanRecord {
parent: None,
kind: SpanKind::Query,
name: "span".to_owned(),
target: "app".to_owned(),
start: Duration::from_millis(1 + n),
duration: None,
open: false,
failed: false,
fields: Fields::new(),
};
let line = |n: u64| LogRecord {
at: Duration::from_micros(n),
level: Level::Info,
target: "app".to_owned(),
message: "line".to_owned(),
span: Some(5),
fields: Fields::new(),
};
let mut spans = trace(id(Duration::ZERO, 1), "spans");
spans.spans = (0..300).map(span).collect();
let mut lines = trace(id(Duration::ZERO, 2), "lines");
lines.spans = (0..30).map(span).collect();
lines.logs = (0..30).map(line).collect();
for small in [spans, lines] {
for max in 0..=4_000 {
let mut cut = small.clone();
let json = fit(&mut cut, max).unwrap();
assert!(
json.len() <= max || (cut.spans.is_empty() && cut.logs.is_empty()),
"{}: {} bytes of {max}",
small.name,
json.len()
);
}
}
}
#[test]
fn a_missing_directory_is_an_empty_history() {
let directory = directory("missing");
let store = FileStore::new(&*directory);
assert_eq!(names(&store), Vec::<String>::new());
store.clear().unwrap();
}
#[cfg(unix)]
#[test]
fn only_the_owner_can_read_the_history() {
use std::os::unix::fs::PermissionsExt as _;
let directory = directory("permissions");
let store = FileStore::new(directory.join("devtools"));
store.put(trace(id(Duration::ZERO, 1), "job"));
drop(store);
let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&directory.join("devtools")), 0o700);
for name in file_names(&directory.join("devtools")) {
assert_eq!(mode(&directory.join("devtools").join(&name)), 0o600, "{name}");
}
}
#[test]
fn a_store_keeps_100_traces_for_24_hours_up_to_2_mib_by_default() {
let store = FileStore::new("storage/devtools");
assert_eq!(store.settings.capacity, 100);
assert_eq!(store.settings.max_age, Duration::from_hours(24));
assert_eq!(store.settings.max_trace_bytes, 2 * 1024 * 1024);
}
#[test]
fn a_store_keeps_at_least_one_trace() {
assert_eq!(FileStore::new("storage/devtools").with_capacity(0).settings.capacity, 1);
}
#[test]
fn a_new_store_has_discarded_nothing() {
assert_eq!(FileStore::new("storage/devtools").discarded(), 0);
}
}