laravel-rust-devtools 0.3.0

Developer tools for Laravel for Rust applications: an app inspector and request debugger in a floating toolbar.
Documentation
//! Where finished traces are kept, so the toolbar can list and show them.

#[cfg(test)]
use std::collections::VecDeque;
use std::fmt;
#[cfg(test)]
use std::sync::{Mutex, PoisonError};

use crate::trace::{Trace, TraceId, TraceSummary};

/// Where the [`Collector`](crate::collector::Collector) keeps the traces it finishes.
///
/// A store keeps only the most recent traces. Its methods take `&self` and are called from any
/// thread, so a store guards its own state.
pub(crate) trait Store: fmt::Debug + Send + Sync {
    /// Keep a finished trace, dropping the oldest when the store is full.
    ///
    /// The [`Collector`](crate::collector::Collector) calls it; an application rarely does.
    ///
    /// The work that produced the trace has already ended, but the caller may still be on its
    /// thread, or on a thread of a library that held the work's span: a store that writes somewhere
    /// slow hands the trace on rather than waiting. A store may wait briefly for work whose process
    /// is likely to end right after it, as [`FileStore`](crate::file_store::FileStore) does for work other than
    /// a request.
    fn put(&self, trace: Trace);

    /// Summaries of the kept traces, the most recent first.
    ///
    /// # Errors
    ///
    /// Returns an error when the store can't be read.
    fn list(&self) -> Result<Vec<TraceSummary>, StoreError>;

    /// The trace with this ID, if the store still keeps it.
    ///
    /// # Errors
    ///
    /// Returns an error when the store can't be read.
    fn get(&self, id: TraceId) -> Result<Option<Trace>, StoreError>;

    /// The summary of the trace with this ID, as [`list`](Self::list) gives it: of the whole work,
    /// also when the kept trace left part of it out.
    ///
    /// # Errors
    ///
    /// Returns an error when the store can't be read.
    fn summary(&self, id: TraceId) -> Result<Option<TraceSummary>, StoreError>;

    /// Forget every trace.
    ///
    /// # Errors
    ///
    /// Returns an error when the store can't be written.
    fn clear(&self) -> Result<(), StoreError>;
}

/// A shared store, so a [`Collector`](crate::collector::Collector) can record into a store that the
/// application reads.
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()
    }
}

/// Why a [`Store`] couldn't read or write its traces.
#[derive(Debug)]
pub(crate) enum StoreError {
    /// Reading or writing the store's files failed.
    Io(std::io::Error),
    /// A trace couldn't be written as JSON, or a kept trace couldn't be read back from it.
    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)
    }
}

/// A [`Store`] that keeps the most recent traces in memory, and loses them when the process ends.
///
/// The tests' store: each process has its own, so it can't show a queue worker's jobs next to the
/// requests that queued them.
#[cfg(test)]
#[derive(Debug)]
pub(crate) struct MemoryStore {
    capacity: usize,
    traces: Mutex<VecDeque<Trace>>,
}

#[cfg(test)]
impl MemoryStore {
    /// A store that keeps the `capacity` most recent traces, and at least one.
    #[must_use]
    pub(crate) fn new(capacity: usize) -> Self {
        let capacity = capacity.max(1);

        Self {
            capacity,
            traces: Mutex::new(VecDeque::with_capacity(capacity)),
        }
    }

    /// How many traces the store keeps.
    #[must_use]
    pub(crate) fn capacity(&self) -> usize {
        self.capacity
    }

    // A thread that panicked while holding the lock left at worst a trace too many or too few,
    // which is no reason to stop recording.
    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);
    }
}