laravel-rust-debugbar 0.1.0

A debug bar for Laravel for Rust applications: requests, queries, logs, timeline, and Inertia visits.
Documentation
use std::backtrace::Backtrace;
use std::path::{Path, PathBuf};
use std::time::Instant;

use laravel::db::{Driver, QueryInfo};

use crate::config::DebugbarConfig;
use crate::history::{Message, Query};
use crate::recorder::{milliseconds, record as collect};

struct Settings {
    root: PathBuf,
    backtrace: bool,
    frames: usize,
    backtrace_exclude: Vec<String>,
    explain: bool,
    runnable: bool,
    soft_limit: usize,
    hard_limit: usize,
    exclude_paths: Vec<String>,
}

pub fn listener(settings: &DebugbarConfig, root: PathBuf) -> impl Fn(&QueryInfo) + Send + Sync + 'static {
    let settings = Settings {
        root,
        backtrace: settings.backtrace,
        frames: settings.backtrace_frames.max(1),
        backtrace_exclude: trimmed(&settings.backtrace_exclude),
        explain: settings.explain,
        runnable: settings.show_query_result,
        soft_limit: settings.query_soft_limit,
        hard_limit: settings.query_hard_limit,
        exclude_paths: trimmed(&settings.query_exclude_paths),
    };

    move |query| record(query, &settings)
}

fn record(query: &QueryInfo, settings: &Settings) {
    let finished = Instant::now();
    let duration = *query.elapsed;
    let location = format!("{}:{}", short_path(query.location.file()), query.location.line());

    collect(|recorder, collected| {
        let recorded = collected.queries.len();
        if recorded >= settings.hard_limit {
            collected.queries_excluded += 1;
            if !collected.hard_limited {
                collected.hard_limited = true;
                collected.messages.push(limit_message(
                    recorder.since_start(finished),
                    format!(
                        "The query hard limit of {} was reached. Later queries are not recorded.",
                        settings.hard_limit
                    ),
                ));
            }
            return;
        }

        let detailed = recorded < settings.soft_limit;
        if recorded == settings.soft_limit {
            collected.messages.push(limit_message(
                recorder.since_start(finished),
                format!(
                    "The query soft limit of {} was reached. Later queries have no bindings or backtrace.",
                    settings.soft_limit
                ),
            ));
        }

        let backtrace = if settings.backtrace && detailed {
            app_frames(
                &Backtrace::force_capture().to_string(),
                &settings.root,
                &settings.backtrace_exclude,
                settings.frames,
            )
        } else {
            Vec::new()
        };
        if [Some(&location), backtrace.first()].into_iter().flatten().any(|place| {
            settings
                .exclude_paths
                .iter()
                .any(|path| place.starts_with(path.as_str()))
        }) {
            collected.queries_excluded += 1;
            return;
        }

        let bindings: Vec<String> = if detailed {
            query
                .bindings
                .iter()
                .map(|binding| {
                    binding
                        .value
                        .clone()
                        .unwrap_or_else(|| format!("<{}>", short_type_name(binding.type_name)))
                })
                .collect()
        } else {
            Vec::new()
        };
        let is_select = is_explainable(query.driver, &query.sql);

        collected.queries.push(Query {
            sql: query.sql.clone(),
            bindings_hidden: !detailed || query.bindings.iter().any(|binding| binding.value.is_none()),
            runnable: settings.runnable && is_select && query.bindings.is_empty(),
            bindings,
            origin: backtrace.first().cloned(),
            backtrace,
            explainable: settings.explain && is_select,
            connection: query.connection.clone(),
            location,
            start_ms: recorder.since_start(finished.checked_sub(duration).unwrap_or(finished)),
            duration_ms: milliseconds(duration),
            duplicate: false,
            slow: false,
        });
    });
}

fn limit_message(at_ms: f64, message: String) -> Message {
    Message {
        level: "INFO".to_owned(),
        target: "debugbar".to_owned(),
        message,
        fields: Vec::new(),
        at_ms,
        location: None,
        value: None,
    }
}

fn trimmed(values: &[String]) -> Vec<String> {
    values
        .iter()
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
        .collect()
}

pub fn is_explainable(driver: Driver, sql: &str) -> bool {
    matches!(
        driver,
        Driver::Postgres | Driver::Sqlite | Driver::MySql | Driver::MariaDb
    ) && sql
        .trim_start()
        .get(..6)
        .is_some_and(|start| start.eq_ignore_ascii_case("select"))
}

fn app_frames(backtrace: &str, root: &Path, exclude: &[String], limit: usize) -> Vec<String> {
    let root = format!("{}/", root.display());

    backtrace
        .lines()
        .filter_map(|line| line.trim().strip_prefix("at "))
        .filter_map(|frame| {
            let file = frame.strip_prefix(&root).or_else(|| frame.strip_prefix("./"))?;
            let (path, _column) = file.rsplit_once(':')?;

            (!path.starts_with('/')
                && !path.contains("laravel-rust-debugbar")
                && !exclude.iter().any(|excluded| path.starts_with(excluded.as_str())))
            .then(|| path.to_owned())
        })
        .take(limit)
        .collect()
}

fn short_type_name(name: &str) -> String {
    let mut short = String::new();
    let mut path = String::new();

    for character in name.chars() {
        if character.is_alphanumeric() || character == '_' || character == ':' {
            path.push(character);
        } else {
            short.push_str(path.rsplit("::").next().unwrap_or_default());
            path.clear();
            short.push(character);
        }
    }
    short.push_str(path.rsplit("::").next().unwrap_or_default());

    short
}

pub fn short_path(file: &str) -> String {
    let Some((_, crate_path)) = file
        .split_once("/registry/src/")
        .and_then(|(_, rest)| rest.split_once('/'))
    else {
        return file.to_owned();
    };
    let Some((crate_dir, path)) = crate_path.split_once('/') else {
        return file.to_owned();
    };
    let name = crate_dir.rsplit_once('-').map_or(crate_dir, |(name, _version)| name);

    format!("{name}/{path}")
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::{app_frames, short_path, short_type_name};

    #[test]
    fn the_backtrace_keeps_the_application_frames_up_to_the_limit_without_excluded_paths() {
        let backtrace = "   0: std::backtrace::Backtrace::force_capture
             at /rustc/abc/library/std/src/backtrace.rs:312:13
   1: laravel_rust_debugbar::queries::record
             at /Users/me/laravel-rust-debugbar/src/queries.rs:38:21
   2: laravel_database::db::cache
             at /Users/me/.cargo/registry/src/index.crates.io-1/laravel-rust-cache-0.1.2/src/cache/database.rs:324:9
   3: app::http::handlers::debugbar_demo::show
             at /Users/me/app/src/http/handlers/debugbar_demo.rs:22:5
   4: app::main
             at ./src/main.rs:5:1";

        let root = Path::new("/Users/me/app");

        assert_eq!(
            app_frames(backtrace, root, &[], 5),
            ["src/http/handlers/debugbar_demo.rs:22", "src/main.rs:5"]
        );
        assert_eq!(
            app_frames(backtrace, root, &[], 1),
            ["src/http/handlers/debugbar_demo.rs:22"]
        );
        assert_eq!(
            app_frames(backtrace, root, &["src/http".to_owned()], 5),
            ["src/main.rs:5"]
        );
        assert!(app_frames("at /rustc/x.rs:1:1", root, &[], 5).is_empty());
    }

    #[test]
    fn a_path_in_the_cargo_registry_keeps_the_crate_name_and_its_own_path() {
        assert_eq!(
            short_path(
                "/Users/me/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/laravel-rust-cache-0.1.2/src/cache/database.rs"
            ),
            "laravel-rust-cache/src/cache/database.rs"
        );
        assert_eq!(short_path("src/http/handlers/pings.rs"), "src/http/handlers/pings.rs");
    }

    #[test]
    fn a_type_name_keeps_only_the_last_segment_of_each_path() {
        assert_eq!(short_type_name("core::option::Option<i32>"), "Option<i32>");
        assert_eq!(
            short_type_name("std::collections::HashMap<alloc::string::String, i64>"),
            "HashMap<String, i64>"
        );
        assert_eq!(short_type_name("i64"), "i64");
    }
}