use std::collections::HashMap;
use std::time::Duration;
use http::{Method, StatusCode};
use laravel::axum::Json as Body;
use laravel::axum::extract::Query;
use laravel::container::Inject;
use laravel::http::middleware::PreventRequestForgery;
use laravel::http::sse::{Event, EventStream};
use laravel::http::{IntoResponse, Json, Middleware, MiddlewareGroup, Next, Request, Response};
use laravel::routing::{Params, Router};
use laravel::view::Html;
use serde::Deserialize;
use serde_json::{Value, json};
use tokio::sync::broadcast::error::RecvError;
use crate::agent::{self, WaitFor};
use crate::config::StudioGate;
use crate::store::{QueryFilter, StudioStore, TraceFilter};
use crate::types::{
ActionResult, OverviewResponse, QueuesOverviewResponse, SystemInfoResponse, WorkflowRunDetail,
WorkflowsListResponse,
};
use crate::workflows::{self, WorkflowFilter};
use crate::{docs, markdown, mcp, queues};
type QueryString = Query<HashMap<String, String>>;
#[derive(Clone, Debug)]
pub struct StudioAccess {
gate: StudioGate,
store: StudioStore,
}
impl Middleware for StudioAccess {
async fn handle(&self, request: Request, next: Next) -> laravel::Result<Response> {
if !self.gate.enabled {
return Err(laravel::abort(404));
}
if !self.gate.is_authorized(&request) {
return Err(laravel::abort_with(
403,
"Studio answers only in the local environment. To open it here, give `StudioServiceProvider` an \
`authorize` callback, or set `STUDIO_ALLOW_IN_PRODUCTION=true`.",
));
}
if !matches!(*request.method(), Method::GET | Method::HEAD | Method::OPTIONS) {
let cross_origin = request
.header("origin")
.is_some_and(|origin| !origin.eq_ignore_ascii_case(&request.origin()));
let cross_site = request
.header("sec-fetch-site")
.is_some_and(|site| !matches!(site, "same-origin" | "none"));
if cross_origin || cross_site {
return Err(laravel::abort_with(
403,
"Studio doesn't take requests from other sites.",
));
}
}
agent::sync(&self.store).await;
Ok(next.run(request).await)
}
}
pub(crate) fn register_routes(
route: &mut Router,
mount: &str,
gate: StudioGate,
middleware: MiddlewareGroup,
store: StudioStore,
mcp_enabled: bool,
) {
route
.prefix(mount)
.middleware((StudioAccess { gate, store }, middleware))
.group(|route| {
route.get("/", index);
route.get("/llms.txt", llms_txt);
route.get("/skill.md", skill_md);
if mcp_enabled {
route.post("/mcp", mcp).without_middleware::<PreventRequestForgery>();
}
route
.prefix("/api")
.without_middleware::<PreventRequestForgery>()
.group(api_routes);
route.get("/{*path}", index);
});
}
fn api_routes(route: &mut Router) {
route.get("/overview", overview);
route.get("/system", system);
route.get("/stream", stream);
route.post("/clear", clear);
route.get("/traces", traces);
route.get("/traces/{id}", trace);
route.get("/queries", queries);
route.get("/logs", logs);
route.get("/exceptions", exceptions);
route.get("/exceptions/{id}", exception);
route.get("/mail", mails);
route.get("/mail/{id}", mail);
route.get("/http-client", http_client);
route.get("/cache", cache);
route.get("/workflows", workflow_runs);
route.post("/workflows/resume", resume_workflow);
route.post("/workflows/recover", recover_workflows);
route.post("/workflows/prune", prune_workflows);
route.get("/workflows/{id}", workflow_run);
route.post("/workflows/{id}/cancel", cancel_workflow);
route.post("/workflows/{id}/retry", retry_workflow);
route.get("/queues", queue_overview);
route.get("/queues/failed", failed_jobs);
route.post("/queues/failed/retry-all", retry_all_failed_jobs);
route.post("/queues/failed/flush", flush_failed_jobs);
route.post("/queues/failed/{id}/retry", retry_failed_job);
route.delete("/queues/failed/{id}", forget_failed_job);
route.post("/queues/batches/{id}/cancel", cancel_batch);
route.post("/queues/pause", pause_queue);
route.post("/queues/continue", continue_queue);
route.post("/queues/restart", restart_workers);
route.get("/agent/summary", agent_summary);
route.get("/agent/diagnose", agent_diagnose);
route.get("/agent/last-request", agent_last_request);
route.get("/agent/last-error", agent_last_error);
route.get("/agent/last-mail", agent_last_mail);
route.get("/agent/wait", agent_wait);
}
pub async fn index(store: Inject<StudioStore>) -> Html {
let config = store.config();
let app = &laravel::config().app;
let boot = json!({
"basePath": config.mount_path(),
"appName": app.name,
"appEnv": app.env.to_string(),
"hasDatabase": cfg!(feature = "database"),
"mcpEnabled": config.mcp_enabled,
"slowQueryMs": config.slow_query_ms,
"slowRequestMs": config.slow_request_ms,
"version": env!("CARGO_PKG_VERSION"),
});
let boot = boot.to_string().replace("</", "<\\/");
Html::raw(format!(
r#"<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Studio — {title}</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='8' fill='%23f53003'/%3E%3Cpath d='M13 2 4 14h7l-1 8 9-12h-7z' transform='translate(7.4 7) scale(.75)' fill='%23fff' stroke='%23fff' stroke-width='1.6' stroke-linejoin='round'/%3E%3C/svg%3E">
<link rel="stylesheet" href="{style}">
</head>
<body>
<div id="root"></div>
<script>window.__STUDIO__ = {boot};</script>
<script type="module" src="{script}"></script>
</body>
</html>
"#,
title = escape_html(&app.name),
style = laravel::url::vendor_asset("studio", "style.css"),
script = laravel::url::vendor_asset("studio", "app.js"),
))
}
fn studio_url(store: &StudioStore, request: &Request) -> String {
format!("{}{}", request.origin(), store.config().mount_path())
}
pub async fn llms_txt(store: Inject<StudioStore>, request: Request) -> Response {
let body = docs::render_llms_txt(
&studio_url(&store, &request),
&laravel::config().app.name,
store.config().mcp_enabled,
);
body.with_header("content-type", "text/plain; charset=utf-8")
}
pub async fn skill_md(store: Inject<StudioStore>, request: Request) -> Response {
docs::render_skill(&studio_url(&store, &request)).with_header("content-type", "text/markdown; charset=utf-8")
}
pub async fn mcp(store: Inject<StudioStore>, Body(message): Body<Value>) -> Response {
match mcp::handle(&store, message).await {
Some(answer) => Json(answer).into_response(),
None => StatusCode::ACCEPTED.into_response(),
}
}
pub async fn overview(store: Inject<StudioStore>) -> Json<OverviewResponse> {
let snapshot = agent::snapshot(&store).await;
let metrics = store.compute_metrics();
let counts = store.buffer_counts();
Json(OverviewResponse {
uptime_seconds: store.uptime_seconds(),
total_requests: metrics.total_requests,
total_errors: metrics.total_errors,
error_rate_pct: metrics.error_rate_pct,
avg_request_ms: metrics.avg_request_ms,
p95_request_ms: metrics.p95_request_ms,
total_queries: metrics.total_queries,
slow_queries: metrics.slow_queries,
duplicate_query_traces: metrics.duplicate_query_traces,
total_exceptions: counts.exceptions,
total_mails: counts.mails,
total_http_client: counts.http_client,
cache_hit_rate_pct: metrics.cache_hit_rate_pct,
workflow_counts: snapshot.workflows.counts,
failed_jobs_count: snapshot.queues.failed_jobs.len(),
pending_jobs_count: snapshot
.queues
.queues
.iter()
.map(|queue| queue.pending + queue.delayed + queue.reserved)
.sum(),
recent_traces: store.list_traces(&TraceFilter::default(), 12),
recent_exceptions: store.list_exceptions(None, 5),
diagnostics: snapshot.diagnostics,
latency_series: metrics.latency_series,
})
}
pub async fn system(store: Inject<StudioStore>) -> Json<SystemInfoResponse> {
let config = laravel::config();
let studio = store.config();
Json(SystemInfoResponse {
app_name: config.app.name.clone(),
app_env: config.app.env.to_string(),
app_debug: config.app.debug,
studio_version: env!("CARGO_PKG_VERSION").to_owned(),
studio_path: studio.mount_path(),
mcp_enabled: studio.mcp_enabled,
database_feature: cfg!(feature = "database"),
#[cfg(feature = "database")]
default_db_connection: config.database.default.clone(),
#[cfg(not(feature = "database"))]
default_db_connection: String::new(),
default_queue_connection: config.queue.default.clone(),
default_cache_store: config.cache.default.clone(),
default_workflow_store: config.workflow.default.clone(),
uptime_seconds: store.uptime_seconds(),
slow_query_ms: studio.slow_query_ms,
slow_request_ms: studio.slow_request_ms,
buffer_counts: store.buffer_counts(),
process: store.process().role.clone(),
pid: store.process().pid,
journal_dir: store.journal_dir().map(|dir| dir.display().to_string()),
})
}
pub async fn stream(store: Inject<StudioStore>) -> EventStream {
let store = (*store).clone();
let mut events = store.subscribe();
EventStream::channel(async move |sse| {
sse.send(Event::new("ready", "{}")).await?;
let mut sync = tokio::time::interval(Duration::from_secs(1));
let mut ping = tokio::time::interval(Duration::from_secs(10));
loop {
tokio::select! {
_ = sync.tick() => agent::sync(&store).await,
_ = ping.tick() => sse.send(Event::new("ping", "{}")).await?,
event = events.recv() => match event {
Ok(event) => sse.send(Event::new("studio", serde_json::to_string(&event)?)).await?,
Err(RecvError::Lagged(missed)) => {
sse.send(Event::new("lagged", json!({ "missed": missed }).to_string())).await?;
}
Err(RecvError::Closed) => return Ok(()),
},
}
}
})
.without_end_event()
}
pub async fn clear(store: Inject<StudioStore>) -> Json<ActionResult> {
store.clear();
Json(ActionResult {
ok: true,
message: "The captured telemetry was cleared.".to_owned(),
detail: None,
})
}
pub async fn traces(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
let filter = TraceFilter {
kind: text(&query, "kind"),
status: text(&query, "status"),
search: text(&query, "search"),
slow: flag(&query, "slow"),
errors: flag(&query, "errors"),
};
let traces = store.list_traces(&filter, limit(&query, 100, 500));
Json(json!({ "traces": traces }))
}
pub async fn trace(store: Inject<StudioStore>, Params(id): Params<String>) -> laravel::Result<Json<Value>> {
let Some(trace) = store.get_trace(&id) else {
return Err(laravel::abort_with(404, format!("No trace has the ID `{id}`.")));
};
Ok(Json(trace_details(&store, &trace)))
}
fn trace_details(store: &StudioStore, trace: &crate::types::TraceRecord) -> Value {
let id = trace.id.as_str();
let during = |trace_id: &Option<String>| trace_id.as_deref() == Some(id);
json!({
"trace": trace,
"queries": store.list_queries(&QueryFilter { trace_id: Some(id), ..QueryFilter::default() }, 1000),
"logs": store.list_logs(Some(id), None, None, 500),
"exceptions": store.list_exceptions(None, usize::MAX).into_iter().filter(|e| during(&e.trace_id)).collect::<Vec<_>>(),
"mails": store.list_mails(None, None, usize::MAX).into_iter().filter(|m| during(&m.trace_id)).collect::<Vec<_>>(),
"http_client": store.list_http_client(Some(id), 200),
"cache": store.list_cache(Some(id), 500),
})
}
pub async fn queries(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
let filter = QueryFilter {
trace_id: text(&query, "trace_id"),
slow: flag(&query, "slow"),
writes: flag(&query, "writes"),
duplicates: flag(&query, "duplicates"),
app_only: flag(&query, "app"),
search: text(&query, "search"),
};
let queries = store.list_queries(&filter, limit(&query, 150, 1000));
Json(json!({ "queries": queries, "slow_threshold_ms": store.config().slow_query_ms }))
}
pub async fn logs(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
let logs = store.list_logs(
text(&query, "trace_id"),
text(&query, "level"),
text(&query, "search"),
limit(&query, 200, 1000),
);
Json(json!({ "logs": logs }))
}
pub async fn exceptions(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
let exceptions = store.list_exceptions(text(&query, "search"), limit(&query, 100, 500));
Json(json!({ "exceptions": exceptions }))
}
pub async fn exception(store: Inject<StudioStore>, Params(id): Params<u64>) -> laravel::Result<Json<Value>> {
let Some(exception) = store.get_exception(id) else {
return Err(laravel::abort_with(404, format!("No error has the ID `{id}`.")));
};
Ok(Json(json!({ "exception": exception })))
}
pub async fn mails(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
let mails = store.list_mails(text(&query, "kind"), text(&query, "search"), limit(&query, 100, 200));
Json(json!({ "mails": mails }))
}
pub async fn mail(store: Inject<StudioStore>, Params(id): Params<u64>) -> laravel::Result<Json<Value>> {
let Some(mail) = store.get_mail(id) else {
return Err(laravel::abort_with(404, format!("No message has the ID `{id}`.")));
};
Ok(Json(json!({ "mail": mail })))
}
pub async fn http_client(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
let requests = store.list_http_client(text(&query, "trace_id"), limit(&query, 100, 500));
Json(json!({ "requests": requests }))
}
pub async fn cache(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
let operations = store.list_cache(text(&query, "trace_id"), limit(&query, 150, 1000));
Json(json!({ "operations": operations }))
}
pub async fn workflow_runs(store: Inject<StudioStore>, Query(query): QueryString) -> Json<WorkflowsListResponse> {
let filter = WorkflowFilter {
status: text(&query, "status").map(str::to_owned),
workflow: text(&query, "workflow").map(str::to_owned),
attribute: text(&query, "attribute")
.and_then(|attribute| attribute.split_once('='))
.map(|(name, value)| (name.to_owned(), value.to_owned())),
search: text(&query, "search").map(str::to_owned),
limit: limit(&query, 50, 200),
};
Json(workflows::list_workflows(&store, filter).await)
}
pub async fn workflow_run(
Params(id): Params<String>,
Query(query): QueryString,
request: Request,
) -> laravel::Result<Response> {
let Some(run) = workflows::get_workflow(&id).await? else {
return Err(laravel::abort_with(404, format!("No workflow run has the ID `{id}`.")));
};
if wants_markdown(&query, &request) {
return Ok(markdown(markdown::render_workflow_markdown(&run)));
}
Ok(Json::<WorkflowRunDetail>(run).into_response())
}
#[derive(Deserialize)]
pub struct Resume {
pub token: String,
#[serde(default)]
pub value: Value,
}
pub async fn resume_workflow(Body(resume): Body<Resume>) -> laravel::Result<Json<ActionResult>> {
Ok(Json(workflows::resume_workflow(resume.token, resume.value).await?))
}
#[derive(Deserialize, Default)]
pub struct Cancel {
pub reason: Option<String>,
}
pub async fn cancel_workflow(
Params(id): Params<String>,
cancel: Option<Body<Cancel>>,
) -> laravel::Result<Json<ActionResult>> {
let reason = cancel.and_then(|Body(cancel)| cancel.reason);
Ok(Json(workflows::cancel_workflow(&id, reason).await?))
}
pub async fn retry_workflow(Params(id): Params<String>) -> laravel::Result<Json<ActionResult>> {
Ok(Json(workflows::retry_workflow(&id).await?))
}
pub async fn recover_workflows() -> laravel::Result<Json<ActionResult>> {
Ok(Json(workflows::recover_workflows().await?))
}
#[derive(Deserialize)]
pub struct Prune {
pub hours: Option<u32>,
}
pub async fn prune_workflows(prune: Option<Body<Prune>>) -> laravel::Result<Json<ActionResult>> {
let hours = prune.and_then(|Body(prune)| prune.hours).unwrap_or(24);
Ok(Json(workflows::prune_workflows(hours).await?))
}
pub async fn queue_overview(store: Inject<StudioStore>) -> Json<QueuesOverviewResponse> {
Json(queues::queue_overview(&store).await)
}
pub async fn failed_jobs(Query(query): QueryString) -> Json<Value> {
let jobs = queues::list_failed_jobs(limit(&query, 100, 500), text(&query, "search")).await;
Json(json!({ "failed_jobs": jobs }))
}
pub async fn retry_failed_job(Params(id): Params<String>) -> laravel::Result<Json<ActionResult>> {
Ok(Json(queues::retry_failed_job(&id).await?))
}
pub async fn retry_all_failed_jobs() -> laravel::Result<Json<ActionResult>> {
Ok(Json(queues::retry_all_failed_jobs().await?))
}
pub async fn forget_failed_job(Params(id): Params<String>) -> laravel::Result<Json<ActionResult>> {
Ok(Json(queues::forget_failed_job(&id).await?))
}
#[derive(Deserialize, Default)]
pub struct Flush {
pub hours: Option<u32>,
}
pub async fn flush_failed_jobs(flush: Option<Body<Flush>>) -> laravel::Result<Json<ActionResult>> {
let hours = flush.and_then(|Body(flush)| flush.hours);
Ok(Json(queues::flush_failed_jobs(hours).await?))
}
pub async fn cancel_batch(Params(id): Params<String>) -> laravel::Result<Json<ActionResult>> {
Ok(Json(queues::cancel_batch(&id).await?))
}
#[derive(Deserialize, Default)]
pub struct QueueName {
pub connection: Option<String>,
pub queue: Option<String>,
#[serde(default)]
pub all: bool,
}
pub async fn pause_queue(queue: Option<Body<QueueName>>) -> laravel::Result<Json<ActionResult>> {
let Body(queue) = queue.unwrap_or_default();
Ok(Json(
queues::pause_queue(queue.connection, queue.queue, queue.all).await?,
))
}
pub async fn continue_queue(queue: Option<Body<QueueName>>) -> laravel::Result<Json<ActionResult>> {
let Body(queue) = queue.unwrap_or_default();
Ok(Json(
queues::continue_queue(queue.connection, queue.queue, queue.all).await?,
))
}
pub async fn restart_workers() -> laravel::Result<Json<ActionResult>> {
Ok(Json(queues::restart_workers().await?))
}
pub async fn agent_summary(store: Inject<StudioStore>, Query(query): QueryString, request: Request) -> Response {
let summary = agent::build_agent_summary(&store).await;
if wants_markdown(&query, &request) {
return markdown(markdown::render_summary_markdown(
&summary,
&store.config().mount_path(),
));
}
Json(summary).into_response()
}
pub async fn agent_diagnose(store: Inject<StudioStore>, Query(query): QueryString, request: Request) -> Response {
let within = seconds(&query, "since").and_then(|seconds| Duration::try_from_secs_f64(seconds).ok());
let diagnostics = agent::diagnose(&store, within).await;
if wants_markdown(&query, &request) {
return markdown(markdown::render_diagnostics_markdown(&diagnostics));
}
Json(diagnostics).into_response()
}
pub async fn agent_last_request(
store: Inject<StudioStore>,
Query(query): QueryString,
request: Request,
) -> laravel::Result<Response> {
let Some(trace) = agent::latest_request(&store, text(&query, "path"), text(&query, "method")) else {
return Err(laravel::abort_with(404, "No such request has been captured yet."));
};
if wants_markdown(&query, &request) {
let mut out = markdown::render_trace_markdown(&trace);
markdown::append_trace_details(&store, &trace, &mut out);
return Ok(markdown(out));
}
Ok(Json(trace_details(&store, &trace)).into_response())
}
pub async fn agent_last_error(
store: Inject<StudioStore>,
Query(query): QueryString,
request: Request,
) -> laravel::Result<Response> {
let Some(exception) = store.latest_exception() else {
return Err(laravel::abort_with(404, "No error has been captured yet."));
};
if wants_markdown(&query, &request) {
return Ok(markdown(markdown::render_exception_markdown(
&exception,
&store.config().mount_path(),
)));
}
Ok(Json(exception).into_response())
}
pub async fn agent_last_mail(
store: Inject<StudioStore>,
Query(query): QueryString,
request: Request,
) -> laravel::Result<Response> {
let recipient = text(&query, "to").map(str::to_lowercase);
let mail = store
.list_mails(text(&query, "kind"), None, usize::MAX)
.into_iter()
.find(|mail| {
recipient.as_ref().is_none_or(|to| {
mail.to
.as_ref()
.is_some_and(|sent_to| sent_to.to_lowercase().contains(to))
})
});
let Some(mail) = mail else {
return Err(laravel::abort_with(404, "No such message has been captured yet."));
};
if wants_markdown(&query, &request) {
return Ok(markdown(markdown::render_mail_markdown(&mail)));
}
Ok(Json(mail).into_response())
}
pub async fn agent_wait(store: Inject<StudioStore>, Query(query): QueryString) -> Json<Value> {
let lasting = |name: &str, default: f64, max: f64| {
Duration::from_secs_f64(seconds(&query, name).unwrap_or(default).clamp(0.0, max))
};
let wait = WaitFor {
kind: text(&query, "for").unwrap_or_default().to_owned(),
contains: text(&query, "contains").map(str::to_owned),
timeout: lasting("timeout", 15.0, 120.0),
lookback: lasting("lookback", 10.0, 3600.0),
};
match agent::wait_for_event(&store, wait).await {
Some(event) => Json(json!({ "matched": true, "event": event })),
None => Json(json!({ "matched": false })),
}
}
fn markdown(body: String) -> Response {
body.with_header("content-type", "text/markdown; charset=utf-8")
}
fn wants_markdown(query: &HashMap<String, String>, request: &Request) -> bool {
match text(query, "format") {
Some(format) => matches!(format, "md" | "markdown" | "text"),
None => request
.header("accept")
.is_some_and(|accept| accept.contains("text/markdown")),
}
}
fn text<'a>(query: &'a HashMap<String, String>, name: &str) -> Option<&'a str> {
query.get(name).map(String::as_str).filter(|value| !value.is_empty())
}
fn seconds(query: &HashMap<String, String>, name: &str) -> Option<f64> {
text(query, name)?
.parse::<f64>()
.ok()
.filter(|seconds| !seconds.is_nan())
}
fn flag(query: &HashMap<String, String>, name: &str) -> bool {
matches!(text(query, name), Some("1" | "true" | "yes"))
}
fn limit(query: &HashMap<String, String>, default: usize, max: usize) -> usize {
text(query, "limit")
.and_then(|limit| limit.parse::<usize>().ok())
.map_or(default, |limit| limit.clamp(1, max))
}
fn escape_html(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}