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};
#[derive(Debug)]
pub struct Snapshot {
pub workflows: WorkflowsListResponse,
pub queues: QueuesOverviewResponse,
pub diagnostics: DiagnosticsReport,
}
pub async fn snapshot(store: &StudioStore) -> Snapshot {
snapshot_since(store, i64::MIN).await
}
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;
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),
}
}
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);
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))
});
}
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),
}
}
#[derive(Debug, Clone, Default)]
pub struct WaitFor {
pub kind: String,
pub contains: Option<String>,
pub timeout: Duration,
pub lookback: Duration,
}
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,
_ = 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,
},
}
}
}
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))
})
})
}
#[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))
}