#[cfg(test)]
use std::collections::VecDeque;
use std::fmt;
#[cfg(test)]
use std::sync::{Mutex, PoisonError};
use crate::trace::{Trace, TraceId, TraceSummary};
pub(crate) trait Store: fmt::Debug + Send + Sync {
fn put(&self, trace: Trace);
fn list(&self) -> Result<Vec<TraceSummary>, StoreError>;
fn get(&self, id: TraceId) -> Result<Option<Trace>, StoreError>;
fn summary(&self, id: TraceId) -> Result<Option<TraceSummary>, StoreError>;
fn clear(&self) -> Result<(), StoreError>;
}
impl<S: Store + ?Sized> Store for std::sync::Arc<S> {
fn put(&self, trace: Trace) {
(**self).put(trace);
}
fn list(&self) -> Result<Vec<TraceSummary>, StoreError> {
(**self).list()
}
fn get(&self, id: TraceId) -> Result<Option<Trace>, StoreError> {
(**self).get(id)
}
fn summary(&self, id: TraceId) -> Result<Option<TraceSummary>, StoreError> {
(**self).summary(id)
}
fn clear(&self) -> Result<(), StoreError> {
(**self).clear()
}
}
#[derive(Debug)]
pub(crate) enum StoreError {
Io(std::io::Error),
Json(serde_json::Error),
}
impl fmt::Display for StoreError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(_) => f.write_str("the devtools history couldn't be read or written"),
Self::Json(_) => f.write_str("a trace in the devtools history isn't valid JSON"),
}
}
}
impl std::error::Error for StoreError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(error) => Some(error),
Self::Json(error) => Some(error),
}
}
}
impl From<std::io::Error> for StoreError {
fn from(error: std::io::Error) -> Self {
Self::Io(error)
}
}
impl From<serde_json::Error> for StoreError {
fn from(error: serde_json::Error) -> Self {
Self::Json(error)
}
}
#[cfg(test)]
#[derive(Debug)]
pub(crate) struct MemoryStore {
capacity: usize,
traces: Mutex<VecDeque<Trace>>,
}
#[cfg(test)]
impl MemoryStore {
#[must_use]
pub(crate) fn new(capacity: usize) -> Self {
let capacity = capacity.max(1);
Self {
capacity,
traces: Mutex::new(VecDeque::with_capacity(capacity)),
}
}
#[must_use]
pub(crate) fn capacity(&self) -> usize {
self.capacity
}
fn traces(&self) -> std::sync::MutexGuard<'_, VecDeque<Trace>> {
self.traces.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[cfg(test)]
impl Store for MemoryStore {
fn put(&self, trace: Trace) {
let mut traces = self.traces();
if traces.len() == self.capacity {
traces.pop_front();
}
traces.push_back(trace);
}
fn list(&self) -> Result<Vec<TraceSummary>, StoreError> {
Ok(self.traces().iter().rev().map(Trace::summary).collect())
}
fn get(&self, id: TraceId) -> Result<Option<Trace>, StoreError> {
Ok(self.traces().iter().find(|trace| trace.id == id).cloned())
}
fn summary(&self, id: TraceId) -> Result<Option<TraceSummary>, StoreError> {
Ok(self.traces().iter().find(|trace| trace.id == id).map(Trace::summary))
}
fn clear(&self) -> Result<(), StoreError> {
self.traces().clear();
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::time::{Duration, SystemTime};
use super::*;
use crate::trace::{Dropped, Fields, TraceKind};
fn trace(name: &str) -> Trace {
Trace {
id: TraceId::generate(),
kind: TraceKind::Request,
name: name.to_owned(),
started_at: SystemTime::now(),
duration: Duration::from_millis(1),
status: Some(200),
failed: false,
fields: Fields::new(),
spans: Vec::new(),
logs: Vec::new(),
dropped: Dropped::default(),
}
}
fn names(store: &MemoryStore) -> Vec<String> {
store.list().unwrap().into_iter().map(|summary| summary.name).collect()
}
#[test]
fn it_lists_the_most_recent_first() {
let store = MemoryStore::new(10);
store.put(trace("GET /a"));
store.put(trace("GET /b"));
assert_eq!(names(&store), ["GET /b", "GET /a"]);
}
#[test]
fn a_full_store_drops_the_oldest() {
let store = MemoryStore::new(2);
let oldest = trace("GET /a");
let oldest_id = oldest.id;
store.put(oldest);
store.put(trace("GET /b"));
store.put(trace("GET /c"));
assert_eq!(names(&store), ["GET /c", "GET /b"]);
assert_eq!(store.get(oldest_id).unwrap(), None);
}
#[test]
fn it_finds_a_trace_by_id() {
let store = MemoryStore::new(10);
let wanted = trace("GET /a");
let id = wanted.id;
store.put(wanted.clone());
store.put(trace("GET /b"));
assert_eq!(store.get(id).unwrap(), Some(wanted));
assert_eq!(store.get(TraceId::generate()).unwrap(), None);
}
#[test]
fn clearing_forgets_everything() {
let store = MemoryStore::new(10);
store.put(trace("GET /a"));
store.clear().unwrap();
assert_eq!(names(&store), Vec::<String>::new());
}
#[test]
fn it_keeps_at_least_one_trace() {
let store = MemoryStore::new(0);
store.put(trace("GET /a"));
assert_eq!(store.capacity(), 1);
assert_eq!(names(&store), ["GET /a"]);
}
#[test]
fn a_new_memory_store_lists_nothing() {
assert_eq!(MemoryStore::new(100).list().unwrap(), Vec::new());
}
#[test]
fn an_unknown_id_has_no_trace() {
let id: TraceId = "0000019ad5c3e1f20000000000000001".parse().unwrap();
assert_eq!(MemoryStore::new(100).get(id).unwrap(), None);
}
#[test]
fn a_memory_store_keeps_at_least_one_trace() {
assert_eq!(MemoryStore::new(0).capacity(), 1);
}
}