use std::fmt::Write as _;
use serde_json::Value;
use crate::store::{StudioStore, counted, now_ms, short_type, truncate};
use crate::types::{
AgentSummary, DiagnosticIssue, DiagnosticsReport, ExceptionRecord, MailRecord, TraceRecord, TraceSummary,
WorkflowRunDetail,
};
fn code(text: &str) -> String {
if text.contains('`') {
format!("`` {text} ``")
} else {
format!("`{text}`")
}
}
fn ago(timestamp_ms: i64) -> String {
let seconds = (now_ms() - timestamp_ms).max(0) / 1000;
match seconds {
0..=1 => "just now".to_owned(),
2..=119 => format!("{seconds}s ago"),
120..=7199 => format!("{}m ago", seconds / 60),
_ => format!("{}h ago", seconds / 3600),
}
}
fn took(duration_ms: f64, responded_ms: Option<f64>) -> String {
match responded_ms {
Some(responded_ms) => format!(
"{responded_ms:.1}ms, then streamed for {:.1}s",
(duration_ms - responded_ms) / 1000.0
),
None => format!("{duration_ms:.1}ms"),
}
}
#[must_use]
pub fn trace_line(trace: &TraceSummary) -> String {
let status = trace.status_code.map(|code| format!(" → {code}")).unwrap_or_default();
let mut notes = vec![took(trace.duration_ms, trace.responded_ms)];
if trace.query_count > 0 {
notes.push(format!(
"{} {:.1}ms",
counted(trace.query_count, "query", "queries"),
trace.total_query_ms
));
}
if trace.duplicate_query_count > 0 {
notes.push(format!("{} repeated (N+1)", trace.duplicate_query_count));
}
if trace.slow_query_count > 0 {
notes.push(format!("{} slow", trace.slow_query_count));
}
if trace.exception_count > 0 || trace.is_error {
notes.push("FAILED".to_owned());
}
if trace.mail_count > 0 {
notes.push(format!("{} mail", trace.mail_count));
}
format!(
"- {}{status} ({}) — {} — trace `{}`",
trace.name,
notes.join(", "),
ago(trace.started_at_ms),
trace.id
)
}
#[must_use]
pub fn render_summary_markdown(summary: &AgentSummary, mount: &str) -> String {
let mut out = String::new();
let metrics = &summary.metrics;
let _ = writeln!(
out,
"# {} ({}) — {}",
summary.app_name,
summary.app_env,
summary.health.to_uppercase()
);
let _ = writeln!(
out,
"{} captured ({} failed, {:.1}ms average), {} ({} slow), {}, {}, workflows: {} waiting, {} failed.",
counted(metrics.total_requests, "request", "requests"),
metrics.total_errors,
metrics.avg_request_ms,
counted(metrics.total_queries, "query", "queries"),
metrics.slow_queries,
counted(metrics.exceptions_in_buffer, "error", "errors"),
counted(metrics.failed_jobs, "failed job", "failed jobs"),
metrics.waiting_workflows,
metrics.failed_workflows,
);
let _ = writeln!(out, "\n## Problems ({})", summary.diagnostics.issue_count);
write_issues(&mut out, &summary.diagnostics, "###");
if !summary.latest_requests.is_empty() {
let _ = writeln!(out, "\n## Latest requests");
for trace in summary.latest_requests.iter().take(8) {
let _ = writeln!(out, "{}", trace_line(trace));
}
}
if !summary.workflows.runs.is_empty() {
let _ = writeln!(out, "\n## Workflow runs");
for run in summary.workflows.runs.iter().take(8) {
let mut line = format!(
"- {} [{}] `{}`, {}",
run.workflow,
run.status,
run.id,
counted(run.step_count, "step", "steps")
);
if !run.waiting_tokens.is_empty() {
let _ = write!(line, ", waits for `{}`", run.waiting_tokens.join("`, `"));
} else if let Some(wake_at) = run.wake_at.as_ref().filter(|_| run.status == "waiting") {
let _ = write!(line, ", wakes at {wake_at}");
}
if let Some(error) = &run.error {
let _ = write!(line, " — {}", truncate(error, 160));
}
let _ = writeln!(out, "{line}");
}
}
if !summary.failed_jobs.is_empty() {
let _ = writeln!(out, "\n## Failed jobs");
for job in summary.failed_jobs.iter().take(8) {
let _ = writeln!(
out,
"- {} `{}` on {}:{} — {}",
job.display_name.as_deref().unwrap_or(&job.job_name),
job.job_id,
job.connection,
job.queue,
truncate(&job.error, 160)
);
}
}
if !summary.latest_mails.is_empty() {
let _ = writeln!(out, "\n## Latest mail");
for mail in &summary.latest_mails {
let _ = writeln!(out, "{}", mail_line(mail));
}
}
let _ = writeln!(
out,
"\nMore: `{mount}/api/agent/last-request`, `{mount}/api/traces/<id>`, `{mount}/api/workflows/<id>`, `{mount}/llms.txt`."
);
out
}
fn mail_line(mail: &MailRecord) -> String {
let mut line = format!(
"- [{}] to {}: {} — {}",
mail.kind,
mail.to.as_deref().unwrap_or("?"),
mail.subject
.as_deref()
.or(mail.text.as_deref())
.map_or_else(|| "(no subject)".to_owned(), |text| truncate(text, 90)),
ago(mail.timestamp_ms)
);
if !mail.extracted_codes.is_empty() {
let _ = write!(line, " — codes: {}", mail.extracted_codes.join(", "));
}
for url in mail.extracted_urls.iter().take(3) {
let _ = write!(line, "\n - {url}");
}
line
}
fn write_issues(out: &mut String, report: &DiagnosticsReport, heading: &str) {
let restarted = !report.before_restart.is_empty();
if report.issues.is_empty() {
let _ = match (restarted, report.traces_since_start) {
(false, _) => writeln!(out, "None found."),
(true, 0) => writeln!(out, "No request or job has been captured since the server restarted."),
(true, traces) => writeln!(
out,
"None found in the {} captured since the server restarted.",
counted(traces, "request or job", "requests and jobs")
),
};
}
for (number, issue) in report.issues.iter().enumerate() {
write_issue(out, number + 1, issue);
}
if restarted {
let _ = writeln!(
out,
"\n{heading} Before the server restarted {}, and not seen since",
ago(report.started_at_ms)
);
for (number, issue) in report.before_restart.iter().enumerate() {
write_issue(out, report.issues.len() + number + 1, issue);
}
}
}
fn write_issue(out: &mut String, number: usize, issue: &DiagnosticIssue) {
let location = issue
.location
.as_deref()
.map(|location| format!(" at `{location}`"))
.unwrap_or_default();
let seen = issue
.last_seen_ms
.map(|seen| format!(" — {}", ago(seen)))
.unwrap_or_default();
let _ = writeln!(
out,
"{number}. **{}** [{}]{location}: {}{seen}",
issue.severity.to_uppercase(),
issue.category,
issue.title
);
if issue.detail != issue.title && !issue.title.ends_with(&issue.detail) {
let _ = writeln!(out, " {}", truncate(&issue.detail, 400));
}
let _ = writeln!(out, " → {}", issue.hint);
if let Some(next) = &issue.next {
let _ = writeln!(out, " → {next}");
}
}
#[must_use]
pub fn render_diagnostics_markdown(report: &DiagnosticsReport) -> String {
let mut out = format!(
"# Diagnostics — {} ({} critical, {})\n\n",
report.status.to_uppercase(),
report.critical_count,
counted(report.warning_count, "warning", "warnings")
);
write_issues(&mut out, report, "##");
out
}
#[must_use]
pub fn render_trace_markdown(trace: &TraceRecord) -> String {
let mut out = String::new();
let status = trace.status_code.map(|code| format!(" → {code}")).unwrap_or_default();
let _ = writeln!(
out,
"# {}{status} — {}",
trace.name,
took(trace.duration_ms, trace.responded_ms)
);
let mut facts = Vec::new();
if trace.query_count > 0 {
let mut queries = format!(
"{} in {:.1}ms",
counted(trace.query_count, "query", "queries"),
trace.total_query_ms
);
if trace.duplicate_query_count > 0 {
let _ = write!(queries, ", {} of them repeats (N+1)", trace.duplicate_query_count);
}
if trace.slow_query_count > 0 {
let _ = write!(queries, ", {} slow", trace.slow_query_count);
}
facts.push(queries);
}
if trace.cache_hits + trace.cache_misses > 0 {
facts.push(format!(
"cache {} hits / {} misses",
trace.cache_hits, trace.cache_misses
));
}
for (count, what) in [
(trace.http_client_count, "outgoing requests"),
(trace.mail_count, "messages sent"),
(trace.exception_count, "errors"),
] {
if count > 0 {
facts.push(format!("{count} {what}"));
}
}
let _ = writeln!(
out,
"{} trace `{}`, captured by `{}` {}. {}",
trace.kind.as_str(),
trace.id,
trace.process,
ago(trace.started_at_ms),
if facts.is_empty() {
String::new()
} else {
format!("{}.", facts.join("; "))
},
);
if let Some(route) = trace.route.as_ref().filter(|route| Some(*route) != trace.path.as_ref()) {
let _ = writeln!(out, "Route: `{route}`");
}
if let Some(run) = &trace.workflow_run_id {
let _ = writeln!(out, "Workflow run: `{run}`");
}
if let Some(error) = &trace.error {
let _ = writeln!(out, "Error: {error}");
}
let _ = writeln!(out, "\n## Spans");
let depth_of = |mut parent: Option<u64>| {
let mut depth = 0;
while let Some(id) = parent {
depth += 1;
parent = trace
.spans
.iter()
.find(|span| span.id == id)
.and_then(|span| span.parent_id);
if depth > 32 {
break;
}
}
depth
};
let statement_of = |span: &crate::types::SpanRecord| {
let sql = span.fields.get("db.query.text").and_then(Value::as_str)?;
Some((span.parent_id, crate::store::normalize_sql(sql), span.location.clone()))
};
let mut repeats: std::collections::HashMap<_, (usize, f64)> = std::collections::HashMap::new();
for span in &trace.spans {
if let Some(key) = statement_of(span) {
let repeat = repeats.entry(key).or_insert((0, 0.0));
repeat.0 += 1;
repeat.1 += span.duration_ms;
}
}
let mut shown = std::collections::HashSet::new();
for span in &trace.spans {
let key = statement_of(span);
let (times, total_ms) = key
.as_ref()
.and_then(|key| repeats.get(key).copied())
.unwrap_or((1, 0.0));
if times > 2
&& let Some(key) = key
&& !shown.insert(key)
{
continue;
}
let indent = " ".repeat(depth_of(span.parent_id));
let mut line = format!("{indent}- +{:.1}ms {}", span.start_offset_ms, span.name);
if times > 2 {
let _ = write!(line, " ×{times} ({total_ms:.1}ms in all)");
} else {
let _ = write!(line, " ({:.1}ms)", span.duration_ms);
}
if span.is_error {
line.push_str(" FAILED");
}
if let Some(error) = &span.error {
let _ = write!(line, ": {error}");
}
if let Some(hit) = span.fields.get("cache.hit").and_then(Value::as_bool) {
line.push_str(if hit { " hit" } else { " miss" });
}
match (&span.vendor, span.fields.get("db.query.text").and_then(Value::as_str)) {
(Some(vendor), Some(_)) => {
let _ = write!(line, " [{vendor}]");
}
(None, Some(sql)) => {
let _ = write!(line, " {}", code(&truncate(sql, 200)));
if let Some(location) = &span.location {
let _ = write!(line, " at `{location}`");
}
let reads = span.fields.get("db.operation.name").and_then(Value::as_str) == Some("SELECT");
if times > 2 && reads && !span.read_back {
line.push_str(" ← N+1");
}
}
_ => {}
}
let _ = writeln!(out, "{line}");
}
out
}
#[must_use]
pub fn render_exception_markdown(exception: &ExceptionRecord, mount: &str) -> String {
let mut out = format!("# {}\n\n{}\n", short_type(&exception.error_type), exception.message);
let _ = writeln!(out, "\n- Type: `{}`", exception.error_type);
if let Some(location) = &exception.location {
let _ = writeln!(out, "- Raised at: `{location}`");
}
if let (Some(method), Some(path)) = (&exception.method, &exception.path) {
let _ = writeln!(out, "- Request: {method} {path}");
}
if let Some(trace) = &exception.trace_id {
let _ = writeln!(out, "- Trace: `{trace}` (GET {mount}/api/traces/{trace})");
}
let _ = writeln!(out, "- When: {}", ago(exception.timestamp_ms));
if !exception.causes.is_empty() {
let _ = writeln!(out, "\n## Caused by");
for cause in &exception.causes {
let _ = writeln!(out, "- {cause}");
}
}
if !exception.context.is_empty() {
let _ = writeln!(out, "\n## Context");
for (name, value) in &exception.context {
let _ = writeln!(out, "- {name}: {value}");
}
}
out
}
#[must_use]
pub fn render_mail_markdown(mail: &MailRecord) -> String {
let mut out = format!(
"# {}\n\n- Kind: {}\n- To: {}\n",
mail.subject.as_deref().unwrap_or("(no subject)"),
mail.kind,
mail.to.as_deref().unwrap_or("?")
);
if let Some(from) = &mail.from {
let _ = writeln!(out, "- From: {from}");
}
let _ = writeln!(out, "- When: {}", ago(mail.timestamp_ms));
if let Some(error) = &mail.error {
let _ = writeln!(out, "- FAILED: {error}");
}
if !mail.extracted_codes.is_empty() {
let _ = writeln!(out, "\n## Codes\n");
for code in &mail.extracted_codes {
let _ = writeln!(out, "- `{code}`");
}
}
if !mail.extracted_urls.is_empty() {
let _ = writeln!(out, "\n## Links\n");
for url in &mail.extracted_urls {
let _ = writeln!(out, "- {url}");
}
}
if let Some(text) = &mail.text {
let _ = writeln!(out, "\n## Text\n\n{}", text.trim_end());
}
out
}
#[must_use]
pub fn render_workflow_markdown(run: &WorkflowRunDetail) -> String {
let mut out = format!("# {} [{}]\n\nRun `{}`", run.workflow, run.status, run.id);
if let Some(created_at) = &run.created_at {
let _ = write!(out, ", started {created_at}");
}
if let Some(finished_at) = &run.finished_at {
let _ = write!(out, ", finished {finished_at}");
}
out.push('\n');
if let Some(input) = &run.input {
let _ = writeln!(out, "- Input: `{input}`");
}
if let Some(output) = &run.output {
let _ = writeln!(out, "- Output: `{output}`");
}
if let Some(error) = &run.error {
let _ = writeln!(out, "- Error: {error}");
}
if let Some(wake_at) = &run.wake_at {
let _ = writeln!(out, "- Wakes at: {wake_at}");
}
for (name, value) in &run.attributes {
let _ = writeln!(out, "- Attribute {name}: {value}");
}
let _ = writeln!(out, "\n## Steps");
for step in &run.steps {
let mut line = format!("- {} `{}` [{}]", step.kind, step.name, step.status);
if step.kind == "step" && step.tries != 1 {
let _ = write!(line, ", {} tries", step.tries);
}
if let Some(duration) = step.duration_ms {
let _ = write!(line, ", {duration:.1}ms");
}
if step.timed_out {
line.push_str(", timed out");
}
if let Some(wake_at) = step.wake_at.as_ref().filter(|_| step.status == "pending") {
let _ = write!(line, ", until {wake_at}");
}
if let Some(output) = step.output.as_ref().filter(|output| !output.is_null()) {
let _ = write!(line, " → `{}`", truncate(&output.to_string(), 200));
}
if let Some(error) = &step.error {
let _ = write!(line, " — {error}");
}
let _ = writeln!(out, "{line}");
}
let waiting: Vec<&str> = run
.waits
.iter()
.filter(|wait| wait.is_waiting)
.map(|wait| wait.token.as_str())
.collect();
if !waiting.is_empty() {
let _ = writeln!(out, "\nWaiting for a value on: `{}`.", waiting.join("`, `"));
}
if run.can_retry {
let _ = writeln!(out, "\nThe run can be retried from its failed step.");
}
out
}
pub fn append_trace_details(store: &StudioStore, trace: &TraceRecord, out: &mut String) {
let mount = store.config().mount_path();
let exceptions: Vec<ExceptionRecord> = store
.list_exceptions(Some(&trace.id), 20)
.into_iter()
.filter(|exception| exception.trace_id.as_deref() == Some(trace.id.as_str()))
.collect();
for exception in &exceptions {
let _ = write!(
out,
"\n## Error\n\n{}",
render_exception_markdown(exception, &mount).replacen("# ", "### ", 1)
);
}
let mut logs = store.list_logs(Some(&trace.id), None, None, 50);
logs.retain(|log| log.target != "laravel::errors");
if !logs.is_empty() {
let _ = writeln!(out, "\n## Logs");
for log in logs.iter().rev() {
let fields = if log.fields.is_empty() {
String::new()
} else {
format!(" {}", Value::Object(log.fields.clone().into_iter().collect()))
};
let _ = writeln!(
out,
"- {} {}: {}{fields}",
log.level.to_uppercase(),
log.target,
log.message
);
}
}
for mail in store.list_mails(None, None, 200) {
if mail.trace_id.as_deref() == Some(trace.id.as_str()) {
let _ = writeln!(out, "\n## Mail sent\n\n{}", mail_line(&mail));
}
}
}