laravel-rust-debugbar 0.1.0

A debug bar for Laravel for Rust applications: requests, queries, logs, timeline, and Inertia visits.
Documentation
use std::panic::Location;
use std::path::Path;
use std::sync::{Arc, OnceLock, RwLock};
use std::time::Instant;

use serde::Serialize;
use serde_json::Value;

use crate::history::{Activity, ActivityKind, CodeSnippet, CustomTab, Measure, Message, RequestRecord};
use crate::queries::short_path;
use crate::recorder::{PendingMeasure, current, milliseconds, record};

const SNIPPET_RADIUS: usize = 5;

pub trait Collector: Send + Sync + 'static {
    fn name(&self) -> &str;

    fn collect(&self, record: &RequestRecord) -> Option<Value>;
}

fn registry() -> &'static RwLock<Vec<Arc<dyn Collector>>> {
    static COLLECTORS: OnceLock<RwLock<Vec<Arc<dyn Collector>>>> = OnceLock::new();
    COLLECTORS.get_or_init(RwLock::default)
}

pub fn add_collector(collector: impl Collector) {
    registry()
        .write()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .push(Arc::new(collector));
}

pub fn collectors() -> Vec<Arc<dyn Collector>> {
    registry()
        .read()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .clone()
}

pub fn push_custom(tabs: &mut Vec<CustomTab>, name: &str, entry: Value) {
    match tabs.iter_mut().find(|tab| tab.name == name) {
        Some(tab) => tab.entries.push(entry),
        None => tabs.push(CustomTab {
            name: name.to_owned(),
            entries: vec![entry],
        }),
    }
}

#[track_caller]
pub fn dump(value: &impl Serialize) {
    let location = Location::caller();
    let value = serde_json::to_value(value).unwrap_or_else(|error| Value::String(error.to_string()));

    push_message("DEBUG", "dump", String::new(), Some(value), location);
}

#[track_caller]
pub fn message(label: impl Into<String>, text: impl Into<String>) {
    push_message("INFO", &label.into(), text.into(), None, Location::caller());
}

fn push_message(level: &str, target: &str, text: String, value: Option<Value>, location: &Location<'_>) {
    let at = Instant::now();

    record(|recorder, collected| {
        collected.messages.push(Message {
            level: level.to_owned(),
            target: target.to_owned(),
            message: text,
            fields: Vec::new(),
            at_ms: recorder.since_start(at),
            location: Some(caller(location)),
            value,
        });
    });
}

pub fn start_measure(label: impl Into<String>) {
    let label = label.into();

    record(|_, collected| {
        collected.pending_measures.push(PendingMeasure {
            label,
            started: Instant::now(),
        });
    });
}

pub fn stop_measure(label: &str) {
    let stopped = Instant::now();

    record(|recorder, collected| {
        let Some(position) = collected
            .pending_measures
            .iter()
            .rposition(|pending| pending.label == label)
        else {
            return;
        };
        let PendingMeasure { label, started } = collected.pending_measures.remove(position);

        collected.measures.push(Measure {
            label,
            start_ms: recorder.since_start(started),
            duration_ms: milliseconds(stopped.saturating_duration_since(started)),
            params: Vec::new(),
        });
    });
}

#[track_caller]
pub fn add_error<E: std::error::Error + ?Sized>(error: &E) {
    let location = caller(Location::caller());
    let at = Instant::now();
    let type_name = std::any::type_name::<E>().to_owned();
    let text = error.to_string();

    record(|recorder, collected| {
        collected.activity.push(Activity {
            kind: ActivityKind::Exceptions,
            message: text,
            fields: vec![
                ("type".to_owned(), type_name),
                ("location".to_owned(), location.clone()),
            ],
            at_ms: recorder.since_start(at),
            duration_ms: None,
            code: snippet(&location),
        });
    });
}

pub fn collect(tab: &str, value: &impl Serialize) {
    let value = serde_json::to_value(value).unwrap_or_else(|error| Value::String(error.to_string()));

    record(|_, collected| push_custom(&mut collected.custom, tab, value));
}

pub fn enable() {
    if let Some(recorder) = current() {
        recorder.set_active(true);
    }
}

pub fn disable() {
    if let Some(recorder) = current() {
        recorder.set_active(false);
    }
}

pub fn snippet(location: &str) -> Option<CodeSnippet> {
    let (file, line) = location.rsplit_once(':')?;
    let (file, line) = match line.parse::<usize>() {
        Ok(line) => (file, line),
        Err(_) => {
            let (file, line) = file.rsplit_once(':')?;
            (file, line.parse().ok()?)
        }
    };
    let root = std::env::current_dir().ok()?;
    let path = if Path::new(file).is_absolute() {
        Path::new(file).to_path_buf()
    } else {
        root.join(file)
    };
    if !path.starts_with(&root) || line == 0 {
        return None;
    }

    let source = std::fs::read_to_string(&path).ok()?;
    let start_line = line.saturating_sub(SNIPPET_RADIUS).max(1);
    let lines = source
        .lines()
        .skip(start_line - 1)
        .take(SNIPPET_RADIUS * 2 + 1)
        .map(str::to_owned)
        .collect();

    Some(CodeSnippet {
        file: path
            .strip_prefix(&root)
            .map_or_else(|_| file.to_owned(), |relative| relative.display().to_string()),
        line,
        start_line,
        lines,
    })
}

fn caller(location: &Location<'_>) -> String {
    let file = std::env::current_dir()
        .ok()
        .and_then(|root| {
            location
                .file()
                .strip_prefix(&format!("{}/", root.display()))
                .map(str::to_owned)
        })
        .unwrap_or_else(|| location.file().to_owned());

    format!("{}:{}", short_path(&file), location.line())
}