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 offers a coding agent: the application's state in one call, the problems found
//! in it, and a call that waits for something to happen instead of sleeping.
//!
//! [`crate::markdown`] renders these compactly, [`crate::mcp`] serves them as tools, and
//! [`crate::docs`] tells an agent they exist.

use std::fmt::Write as _;
use std::time::Duration;

use tokio::sync::broadcast::error::RecvError;

use crate::queues;
use crate::store::{StudioStore, TraceFilter, now_ms};
use crate::types::{
    AgentMetrics, AgentSummary, DiagnosticIssue, DiagnosticsReport, QueuesOverviewResponse, StudioEvent, TraceRecord,
    WorkflowsListResponse,
};
use crate::workflows::{self, WorkflowFilter};

/// Everything Studio knows that isn't in its buffers, loaded once for a request, with the problems
/// found in all of it.
#[derive(Debug)]
pub struct Snapshot {
    pub workflows: WorkflowsListResponse,
    pub queues: QueuesOverviewResponse,
    pub diagnostics: DiagnosticsReport,
}

/// Load the workflow runs and the queues, and diagnose them together with the captured telemetry.
pub async fn snapshot(store: &StudioStore) -> Snapshot {
    snapshot_since(store, i64::MIN).await
}

/// The problems alone. With `within`, only those seen that recently, which is how to ask what has
/// gone wrong since a change that didn't restart the application.
pub async fn diagnose(store: &StudioStore, within: Option<Duration>) -> DiagnosticsReport {
    let since_ms = within.map_or(i64::MIN, |within| {
        now_ms().saturating_sub(i64::try_from(within.as_millis()).unwrap_or(i64::MAX))
    });

    snapshot_since(store, since_ms).await.diagnostics
}

async fn snapshot_since(store: &StudioStore, since_ms: i64) -> Snapshot {
    let mount = store.config().mount_path();
    let workflows = workflows::list_workflows(
        store,
        WorkflowFilter {
            limit: 50,
            ..WorkflowFilter::default()
        },
    )
    .await;
    let queues = queues::queue_overview(store).await;

    // A problem found in what was captured is as old as the last capture of it, and the code may
    // have changed since. A failed job, a failed run, and a paused queue stay as they are until
    // something is done about them...
    let mut observed = store.diagnose_telemetry_since(since_ms);
    let mut standing = workflows::diagnose_workflows(&workflows.runs, &mount);
    standing.extend(queues::diagnose_queues(&queues, &mount));
    standing.retain(|issue| issue.last_seen_ms.is_none_or(|seen| seen >= since_ms));
    merge_reported_failures(store, &mut standing, &mut observed);

    Snapshot {
        workflows,
        queues,
        diagnostics: store.report(observed, standing),
    }
}

/// A job or a workflow run that fails also reports its error, which would make two issues of one
/// failure. The job's or the run's issue stays, since it says what to retry, and takes the error's
/// source line.
fn merge_reported_failures(store: &StudioStore, standing: &mut [DiagnosticIssue], observed: &mut Vec<DiagnosticIssue>) {
    let exceptions = store.list_exceptions(None, 100);
    let mut merged = Vec::new();

    for issue in standing.iter_mut() {
        if !matches!(issue.category.as_str(), "job_failed" | "workflow_failed") {
            continue;
        }
        let Some(exception) = exceptions.iter().find(|exception| exception.message == issue.detail) else {
            continue;
        };
        merged.push(exception.id.to_string());
        issue.trace_id.clone_from(&exception.trace_id);
        // A workflow wraps its step's error, so that error's line is the framework's, not the step's...
        issue.location = exception
            .location
            .clone()
            .filter(|location| !crate::store::is_dependency_location(location));
        if !exception.causes.is_empty() {
            let _ = write!(issue.detail, " Caused by: {}.", exception.causes.join(" → "));
        }
    }

    observed.retain(|issue| {
        issue.category != "exception" || !issue.resource_id.as_ref().is_some_and(|id| merged.contains(id))
    });
}

/// The report an agent starts from: the application's health, what's wrong, and what happened last.
pub async fn build_agent_summary(store: &StudioStore) -> AgentSummary {
    let Snapshot {
        mut workflows,
        queues,
        diagnostics,
    } = snapshot(store).await;
    let app = &laravel::config().app;
    let metrics = store.compute_metrics();
    let count = |status: &str| workflows.counts.get(status).copied().unwrap_or(0);
    let (waiting_workflows, failed_workflows) = (count("waiting"), count("failed"));
    workflows.runs.truncate(15);

    AgentSummary {
        app_name: app.name.clone(),
        app_env: app.env.to_string(),
        uptime_seconds: store.uptime_seconds(),
        health: diagnostics.status.clone(),
        metrics: AgentMetrics {
            total_requests: metrics.total_requests,
            total_errors: metrics.total_errors,
            avg_request_ms: metrics.avg_request_ms,
            total_queries: metrics.total_queries,
            slow_queries: metrics.slow_queries,
            exceptions_in_buffer: store.buffer_counts().exceptions,
            failed_jobs: queues.failed_jobs.len(),
            waiting_workflows,
            failed_workflows,
        },
        diagnostics,
        latest_requests: store.list_traces(
            &TraceFilter {
                kind: Some("request"),
                ..TraceFilter::default()
            },
            10,
        ),
        latest_exceptions: store.list_exceptions(None, 5),
        workflows,
        failed_jobs: queues.failed_jobs.into_iter().take(15).collect(),
        latest_mails: store.list_mails(None, None, 5),
    }
}

// ---- Waiting for something to happen ----

/// What [`wait_for_event`] waits for.
#[derive(Debug, Clone, Default)]
pub struct WaitFor {
    /// `request`, `job`, `workflow`, `command`, `trace` for any of those, `exception`, `mail`,
    /// `log`, or `activity` for a job's or a workflow run's change of state. Empty waits for any.
    pub kind: String,
    /// Words the record's JSON must contain, all of them, such as a path, an email address, or a
    /// run's ID and `completed`.
    pub contains: Option<String>,
    /// How long to wait.
    pub timeout: Duration,
    /// Also accept a record captured this long before the call, since what an agent waits for has
    /// often happened by the time it asks.
    pub lookback: Duration,
}

/// Return the first captured record that matches, or `None` when the time runs out. An agent calls
/// this after it sets something off, such as a request that queues a job, instead of sleeping and
/// polling.
pub async fn wait_for_event(store: &StudioStore, wait: WaitFor) -> Option<StudioEvent> {
    let mut events = store.subscribe();
    let since = now_ms() - wait.lookback.as_millis() as i64;
    sync(store).await;
    if let Some(found) = recent_events(store, since)
        .into_iter()
        .find(|event| matches(event, &wait))
    {
        return Some(found);
    }

    let deadline = tokio::time::Instant::now() + wait.timeout;
    let mut tick = tokio::time::interval(Duration::from_millis(250));
    loop {
        tokio::select! {
            () = tokio::time::sleep_until(deadline) => return None,
            // Another process's records arrive through the journal, which is read on each tick...
            _ = tick.tick() => {
                sync(store).await;
            }
            event = events.recv() => match event {
                Ok(event) if matches(&event, &wait) => return Some(event),
                Ok(_) | Err(RecvError::Lagged(_)) => {}
                Err(RecvError::Closed) => return None,
            },
        }
    }
}

/// Read the journal off the async runtime's threads, since it reads files.
pub(crate) async fn sync(store: &StudioStore) {
    if store.journal_dir().is_none() {
        return;
    }
    let store = store.clone();
    let _ = tokio::task::spawn_blocking(move || store.sync()).await;
}

fn recent_events(store: &StudioStore, since_ms: i64) -> Vec<StudioEvent> {
    let mut events: Vec<(i64, StudioEvent)> = Vec::new();
    for trace in store.list_traces(&TraceFilter::default(), 50) {
        events.push((trace.started_at_ms, StudioEvent::Trace(trace)));
    }
    for exception in store.list_exceptions(None, 20) {
        events.push((exception.timestamp_ms, StudioEvent::Exception(exception)));
    }
    for mail in store.list_mails(None, None, 20) {
        events.push((mail.timestamp_ms, StudioEvent::Mail(mail)));
    }
    for log in store.list_logs(None, None, None, 50) {
        events.push((log.timestamp_ms, StudioEvent::Log(log)));
    }
    for activity in store.list_workflow_activity(50) {
        events.push((activity.updated_at_ms, StudioEvent::Workflow(activity)));
    }
    for activity in store.list_job_activity(50) {
        events.push((activity.timestamp_ms, StudioEvent::Job(activity)));
    }

    events.retain(|(at, _)| *at >= since_ms);
    events.sort_by_key(|(at, _)| std::cmp::Reverse(*at));
    events.into_iter().map(|(_, event)| event).collect()
}

fn matches(event: &StudioEvent, wait: &WaitFor) -> bool {
    let kind = match (wait.kind.as_str(), event) {
        ("" | "any", StudioEvent::Cleared | StudioEvent::Query(_)) => false,
        ("" | "any", _) => true,
        ("trace", StudioEvent::Trace(_)) => true,
        ("request" | "job" | "workflow" | "command" | "schedule", StudioEvent::Trace(trace)) => {
            trace.kind.as_str() == wait.kind
        }
        ("exception" | "error", StudioEvent::Exception(_)) => true,
        ("mail" | "sms", StudioEvent::Mail(mail)) => mail.kind == wait.kind,
        ("log", StudioEvent::Log(_)) => true,
        ("activity", StudioEvent::Workflow(_) | StudioEvent::Job(_)) => true,
        _ => false,
    };

    kind && wait.contains.as_ref().is_none_or(|words| {
        serde_json::to_string(event).is_ok_and(|json| {
            let json = json.to_lowercase();
            words.to_lowercase().split_whitespace().all(|word| json.contains(word))
        })
    })
}

/// The latest request, or the latest to a path or with a method.
#[must_use]
pub fn latest_request(store: &StudioStore, path: Option<&str>, method: Option<&str>) -> Option<TraceRecord> {
    if path.is_none() && method.is_none() {
        return store.latest_request_trace();
    }

    store
        .list_traces(
            &TraceFilter {
                kind: Some("request"),
                ..TraceFilter::default()
            },
            usize::MAX,
        )
        .into_iter()
        .find(|trace| {
            path.is_none_or(|path| trace.path.as_deref() == Some(path) || trace.route.as_deref() == Some(path))
                && method.is_none_or(|method| trace.method.as_deref().is_some_and(|m| m.eq_ignore_ascii_case(method)))
        })
        .and_then(|trace| store.get_trace(&trace.id))
}