laravel-rust-devtools 0.1.0

Developer tools for Laravel for Rust applications: an app inspector and request debugger in a floating toolbar.
Documentation
//! `/_devtools/api`: the recorded traces, as JSON.

use std::sync::Arc;

use laravel::container::Inject;
use laravel::http::{Json, NoContent, Query};
use laravel::routing::Params;

use crate::store::Store;
use crate::trace::{Trace, TraceId, TraceKind, TraceSummary};

/// The store the collector records into, as the API reads it.
pub(crate) struct History(pub(crate) Arc<dyn Store>);

/// What `GET /_devtools/api/traces` lists. A value that doesn't fit is dropped, not refused.
#[laravel::query]
pub(crate) struct TraceFilter {
    kind: Option<TraceKind>,
    #[default = 100]
    #[validate(min_value(1), max_value(1000))]
    limit: usize,
}

/// `GET /_devtools/api/traces`: the most recent traces' summaries, the newest first.
pub(crate) async fn index(
    history: Inject<History>,
    Query(filter): Query<TraceFilter>,
) -> laravel::Result<Json<Vec<TraceSummary>>> {
    let store = Arc::clone(&history.0);
    let summaries = laravel::task::spawn_blocking(move || store.list()).await??;
    let kind = filter.kind;

    Ok(Json(
        summaries
            .into_iter()
            .filter(|summary| kind.is_none_or(|kind| summary.kind == kind))
            .take(filter.limit)
            .collect(),
    ))
}

/// `GET /_devtools/api/traces/{id}`: one trace, whole.
pub(crate) async fn show(history: Inject<History>, Params(id): Params<TraceId>) -> laravel::Result<Json<Trace>> {
    let store = Arc::clone(&history.0);
    match laravel::task::spawn_blocking(move || store.get(id)).await?? {
        Some(trace) => Ok(Json(trace)),
        None => laravel::abort!(404),
    }
}

/// `GET /_devtools/api/traces/{id}/summary`: what a list shows of one trace, for the pill.
pub(crate) async fn summary(
    history: Inject<History>,
    Params(id): Params<TraceId>,
) -> laravel::Result<Json<TraceSummary>> {
    let store = Arc::clone(&history.0);
    match laravel::task::spawn_blocking(move || store.summary(id)).await?? {
        Some(summary) => Ok(Json(summary)),
        None => laravel::abort!(404),
    }
}

/// `DELETE /_devtools/api/traces`: forget every trace.
pub(crate) async fn destroy(history: Inject<History>) -> laravel::Result<NoContent> {
    let store = Arc::clone(&history.0);
    laravel::task::spawn_blocking(move || store.clear()).await??;

    Ok(NoContent)
}