laravel-rust-studio 0.1.1

See what a running Laravel for Rust application did: requests with their queries, errors with their source lines, mail, queued jobs, and durable workflows. For you in the browser, and for coding agents over MCP.
Documentation
//! What Studio hears from the framework besides its spans and log lines: the errors it reports, the
//! events its workflows and queue workers dispatch, and the queries its connections run.

use std::collections::BTreeMap;

use laravel::container::Registrar;
use laravel::event::Event;
use laravel::queue::events::{JobFailed, JobProcessed};
use laravel::workflow::events::{RunCancelled, RunCompleted, RunFailed};

use crate::store::{StudioStore, clean_location, now_ms, round_ms};
use crate::types::{ExceptionRecord, JobActivityRecord, WorkflowActivityRecord};

/// Register Studio's error reporter and its workflow and queue listeners.
pub(crate) fn register_hooks(app: &mut Registrar, store: &StudioStore) {
    report_errors(app, store.clone());
    listen_to_workflows(app, store);
    listen_to_jobs(app, store);
}

/// The error handler passes every failure it reports to this reporter, with the error itself, so
/// Studio reads the error's type, its causes, and where it was raised.
fn report_errors(app: &mut Registrar, store: StudioStore) {
    app.errors().report_all(move |error: &laravel::Error| {
        let link = store.current_span_link();
        if link.as_ref().is_some_and(|link| link.ignored) {
            return;
        }

        let context: BTreeMap<String, serde_json::Value> = laravel::context::Context::current()
            .map(|_| laravel::context::all().into_iter().collect())
            .unwrap_or_default();

        store.record_exception(ExceptionRecord {
            id: store.next_id(),
            trace_id: link.and_then(|link| link.trace_id),
            error_type: error.type_name().to_owned(),
            message: error.to_string(),
            location: error.location().map(|location| {
                clean_location(&format!(
                    "{}:{}:{}",
                    location.file(),
                    location.line(),
                    location.column()
                ))
                .0
            }),
            causes: error.chain().skip(1).map(ToString::to_string).collect(),
            context,
            method: None,
            path: None,
            route: None,
            timestamp_ms: now_ms(),
        });
    });
}

fn listen_to_workflows(app: &mut Registrar, store: &StudioStore) {
    let record = |store: &StudioStore, run_id: String, workflow: &str, status: &str, error: Option<String>| {
        store.record_workflow_activity(WorkflowActivityRecord {
            run_id,
            workflow: workflow.to_owned(),
            status: status.to_owned(),
            error,
            updated_at_ms: now_ms(),
        });
    };

    let completed = store.clone();
    app.events().listen(move |event: Event<RunCompleted>| {
        record(&completed, event.run_id.to_string(), &event.workflow, "completed", None);
        std::future::ready(())
    });

    let failed = store.clone();
    app.events().listen(move |event: Event<RunFailed>| {
        let error = Some(event.error.to_string());
        record(&failed, event.run_id.to_string(), &event.workflow, "failed", error);
        std::future::ready(())
    });

    let cancelled = store.clone();
    app.events().listen(move |event: Event<RunCancelled>| {
        let reason = event.reason.clone();
        record(
            &cancelled,
            event.run_id.to_string(),
            &event.workflow,
            "cancelled",
            reason,
        );
        std::future::ready(())
    });
}

fn listen_to_jobs(app: &mut Registrar, store: &StudioStore) {
    let processed = store.clone();
    app.events().listen(move |event: Event<JobProcessed>| {
        processed.record_job_activity(JobActivityRecord {
            id: processed.next_id(),
            job_id: event.job.id.to_string(),
            name: event.job.name.clone(),
            connection: event.job.connection.clone(),
            queue: event.job.queue.clone(),
            attempt: event.job.attempt,
            outcome: event.outcome.to_string(),
            duration_ms: round_ms(event.duration.as_secs_f64() * 1000.0),
            error: None,
            timestamp_ms: now_ms(),
        });
        std::future::ready(())
    });

    // `JobProcessed` says that a job's last attempt failed, and this says why...
    let failed = store.clone();
    app.events().listen(move |event: Event<JobFailed>| {
        failed.record_job_activity(JobActivityRecord {
            id: failed.next_id(),
            job_id: event.job.id.to_string(),
            name: event.job.name.clone(),
            connection: event.job.connection.clone(),
            queue: event.job.queue.clone(),
            attempt: event.job.attempt,
            outcome: "failed".to_owned(),
            duration_ms: 0.0,
            error: Some(event.error.to_string()),
            timestamp_ms: now_ms(),
        });
        std::future::ready(())
    });
}

/// Listen to every query the application's connections run. A listener learns what a query's span
/// can't say: the SQL as it was sent, the types of its bindings, and the line of the application's
/// code that built it.
#[cfg(feature = "database")]
pub(crate) fn install_db_listener(store: StudioStore) {
    use crate::store::{DbSpanEnrichment, normalize_sql, parse_sql_op_table, short_type};
    use crate::types::{QueryBinding, QueryRecord};

    store.set_db_listener_active(true);

    laravel::db::listen(move |query| {
        let link = store.current_span_link();
        if link.as_ref().is_some_and(|link| link.ignored) {
            return;
        }

        let driver = format!("{:?}", query.driver).to_ascii_lowercase();
        let (location, vendor) = clean_location(&format!(
            "{}:{}:{}",
            query.location.file(),
            query.location.line(),
            query.location.column()
        ));
        let bindings: Vec<QueryBinding> = query
            .bindings
            .iter()
            .map(|binding| QueryBinding {
                type_name: short_generic(binding.type_name),
                value: binding.value.clone(),
            })
            .collect();
        let (operation, table) = parse_sql_op_table(&query.sql);
        let duration_ms = round_ms(query.elapsed.as_secs_f64() * 1000.0);

        // The query's span is still open, and shows the same details in its trace's waterfall...
        if let Some(span) = link.as_ref().and_then(|link| link.db_span) {
            store.attach_db_enrichment(
                span,
                DbSpanEnrichment {
                    sql: query.sql.clone(),
                    connection: query.connection.clone(),
                    location: location.clone(),
                    vendor: vendor.clone(),
                    bindings: bindings.clone(),
                    duration_ms,
                },
            );
        }

        store.record_query(QueryRecord {
            id: store.next_id(),
            trace_id: link.and_then(|link| link.trace_id),
            normalized_sql: normalize_sql(&query.sql),
            sql: query.sql.clone(),
            operation,
            table,
            connection: query.connection.clone(),
            driver,
            duration_ms,
            is_slow: false,
            is_write: !query.read,
            joined_transaction: query.joined_transaction,
            bindings,
            location: Some(location),
            vendor,
            read_back: false,
            started_at_ms: now_ms() - query.elapsed.as_millis() as i64,
            is_error: false,
            error: None,
        });
    });

    /// A type's name without its module paths, as `Option<i64>` for `core::option::Option<i64>`.
    fn short_generic(name: &str) -> String {
        let mut short = String::with_capacity(name.len());
        for part in name.split_inclusive(['<', '>', ',', ' ', '(', ')', '[', ']', '&']) {
            let (path, delimiter) = match part.char_indices().next_back() {
                Some((index, last)) if "<>, ()[]&".contains(last) => (&part[..index], &part[index..]),
                _ => (part, ""),
            };
            short.push_str(short_type(path));
            short.push_str(delimiter);
        }

        short
    }
}