Skip to main content

laravel_rust_debugbar/
commands.rs

1use std::collections::BTreeMap;
2
3use laravel::console::{Console, clap};
4use laravel::container::Inject;
5use serde::Serialize;
6
7use crate::history::{Filter, History, Query, RecordKind, RequestRecord, now_ms};
8
9/// List the requests, commands, and jobs that the debugbar stored, newest first.
10#[derive(clap::Parser)]
11#[command(name = "debugbar:find")]
12pub struct Find {
13    /// Only this HTTP method, such as GET.
14    #[arg(long)]
15    method: Option<String>,
16    /// Only URIs that match this pattern, such as /users/*.
17    #[arg(long)]
18    uri: Option<String>,
19    /// Only this client IP.
20    #[arg(long)]
21    ip: Option<String>,
22    /// Only requests, commands, or jobs.
23    #[arg(long, value_parser = ["request", "command", "job"])]
24    kind: Option<String>,
25    /// Only records with an exception, a failed status, or duplicate queries.
26    #[arg(long)]
27    issues: bool,
28    /// How many records to list.
29    #[arg(long, default_value_t = 20)]
30    limit: usize,
31    /// Print JSON instead of a table.
32    #[arg(long)]
33    json: bool,
34}
35
36#[laravel::console::command]
37impl Find {
38    async fn handle(self, console: &mut Console, history: Inject<History>) -> laravel::Result<()> {
39        let filter = Filter {
40            method: self.method,
41            uri: self.uri,
42            ip: self.ip,
43            kind: self.kind.as_deref().map(parse_kind),
44            ..Filter::default()
45        };
46        let summaries: Vec<_> = history
47            .summaries(&filter)?
48            .into_iter()
49            .filter(|summary| !self.issues || summary.exceptions > 0 || failed(summary.kind, summary.status))
50            .take(self.limit)
51            .collect();
52
53        if self.json {
54            console.line(serde_json::to_string_pretty(&summaries)?);
55            return Ok(());
56        }
57        if summaries.is_empty() {
58            console.info("The debugbar has no stored records.");
59            return Ok(());
60        }
61
62        let now = now_ms();
63        console.table(
64            [
65                "ID",
66                "When",
67                "Kind",
68                "Method",
69                "URI",
70                "Status",
71                "Duration",
72                "Queries",
73                "Exceptions",
74            ],
75            summaries.iter().map(|summary| {
76                [
77                    summary.id.to_string(),
78                    ago(now.saturating_sub(summary.time_ms)),
79                    kind_name(summary.kind).to_owned(),
80                    summary.method.clone(),
81                    summary.uri.clone(),
82                    summary.status.to_string(),
83                    format!("{:.1} ms", summary.duration_ms),
84                    summary.queries.to_string(),
85                    summary.exceptions.to_string(),
86                ]
87            }),
88        );
89
90        Ok(())
91    }
92}
93
94/// Show one stored record: a request, a command, or a job.
95#[derive(clap::Parser)]
96#[command(name = "debugbar:get")]
97pub struct Get {
98    /// The record's ID, or `latest`.
99    id: String,
100    /// Print the whole record as JSON.
101    #[arg(long)]
102    json: bool,
103}
104
105#[laravel::console::command]
106impl Get {
107    async fn handle(self, console: &mut Console, history: Inject<History>) -> laravel::Result<u8> {
108        let Some(record) = find(&history, &self.id)? else {
109            console.error(format!("The debugbar has no record `{}`.", self.id));
110            return Ok(1);
111        };
112
113        if self.json {
114            console.line(serde_json::to_string_pretty(&record)?);
115            return Ok(0);
116        }
117
118        let mut activity: BTreeMap<String, usize> = BTreeMap::new();
119        for entry in &record.activity {
120            *activity
121                .entry(
122                    serde_json::to_value(entry.kind)?
123                        .as_str()
124                        .unwrap_or_default()
125                        .to_owned(),
126                )
127                .or_default() += 1;
128        }
129
130        let mut rows = vec![
131            ["ID".to_owned(), record.id.to_string()],
132            ["Kind".to_owned(), kind_name(record.kind).to_owned()],
133            ["Method".to_owned(), record.method.clone()],
134            ["URI".to_owned(), record.uri.clone()],
135            ["Status".to_owned(), record.status.to_string()],
136            ["Duration".to_owned(), format!("{:.1} ms", record.duration_ms)],
137            [
138                "Route".to_owned(),
139                record.route.clone().unwrap_or_else(|| "-".to_owned()),
140            ],
141            [
142                "Inertia".to_owned(),
143                record.inertia_component.clone().unwrap_or_else(|| "-".to_owned()),
144            ],
145            ["Queries".to_owned(), record.queries.len().to_string()],
146            ["Messages".to_owned(), record.messages.len().to_string()],
147            ["Measures".to_owned(), record.measures.len().to_string()],
148        ];
149        rows.extend(
150            activity
151                .into_iter()
152                .map(|(kind, count)| [capitalize(&kind), count.to_string()]),
153        );
154        rows.extend(
155            record
156                .details
157                .iter()
158                .map(|(name, value)| [capitalize(name), value.clone()]),
159        );
160        console.table(["Field", "Value"], rows);
161
162        Ok(0)
163    }
164}
165
166/// Show the queries of one stored record, with its duplicates and repeated query shapes.
167#[derive(clap::Parser)]
168#[command(name = "debugbar:queries")]
169pub struct Queries {
170    /// The record's ID, or `latest`.
171    id: String,
172    /// Run EXPLAIN on each SELECT and show its plan.
173    #[arg(long)]
174    explain: bool,
175    /// Print JSON instead of tables.
176    #[arg(long)]
177    json: bool,
178}
179
180#[derive(Serialize)]
181struct QueryReport<'a> {
182    queries: &'a [Query],
183    excluded: usize,
184    duplicates: usize,
185    repeated: Vec<Repeated>,
186    plans: BTreeMap<usize, Vec<String>>,
187}
188
189#[derive(Serialize)]
190pub struct Repeated {
191    pub sql: String,
192    pub count: usize,
193    pub total_ms: f64,
194}
195
196#[laravel::console::command]
197impl Queries {
198    async fn handle(self, console: &mut Console, history: Inject<History>) -> laravel::Result<u8> {
199        let Some(record) = find(&history, &self.id)? else {
200            console.error(format!("The debugbar has no record `{}`.", self.id));
201            return Ok(1);
202        };
203
204        let mut plans = BTreeMap::new();
205        if self.explain {
206            for (index, query) in record.queries.iter().enumerate().filter(|(_, query)| query.explainable) {
207                let connection = laravel::db::connection(&query.connection)?;
208                let plan = crate::query_plan::plan(&connection, query)
209                    .await
210                    .unwrap_or_else(|error| vec![format!("EXPLAIN failed: {error}")]);
211                plans.insert(index, plan);
212            }
213        }
214
215        let report = QueryReport {
216            queries: &record.queries,
217            excluded: record.queries_excluded,
218            duplicates: record.queries.iter().filter(|query| query.duplicate).count(),
219            repeated: repeated(&record.queries),
220            plans,
221        };
222
223        if self.json {
224            console.line(serde_json::to_string_pretty(&report)?);
225            return Ok(0);
226        }
227
228        let total = record
229            .queries
230            .iter()
231            .fold(0.0, |total, query| total + query.duration_ms);
232        console.info(format!(
233            "{} queries in {total:.2} ms, {} excluded, {} duplicates, {} repeated shapes.",
234            record.queries.len(),
235            report.excluded,
236            report.duplicates,
237            report.repeated.len()
238        ));
239        if record.queries.is_empty() {
240            return Ok(0);
241        }
242
243        console.table(
244            ["#", "Time", "SQL", "Where", "Flags"],
245            record.queries.iter().enumerate().map(|(index, query)| {
246                let flags: Vec<&str> = [(query.duplicate, "duplicate"), (query.slow, "slow")]
247                    .into_iter()
248                    .filter_map(|(on, flag)| on.then_some(flag))
249                    .collect();
250                [
251                    index.to_string(),
252                    format!("{:.2} ms", query.duration_ms),
253                    query.sql.clone(),
254                    query.origin.clone().unwrap_or_else(|| query.location.clone()),
255                    flags.join(", "),
256                ]
257            }),
258        );
259
260        for (index, plan) in &report.plans {
261            console.line(format!("Plan for query #{index}:"));
262            for line in plan {
263                console.line(format!("  {line}"));
264            }
265        }
266
267        if !report.repeated.is_empty() {
268            console.warn("Repeated query shapes, which may be N+1 queries:");
269            console.table(
270                ["Count", "Total", "SQL"],
271                report.repeated.iter().map(|shape| {
272                    [
273                        shape.count.to_string(),
274                        format!("{:.2} ms", shape.total_ms),
275                        shape.sql.clone(),
276                    ]
277                }),
278            );
279        }
280
281        Ok(0)
282    }
283}
284
285/// Delete every record that the debugbar stored.
286#[derive(clap::Parser)]
287#[command(name = "debugbar:clear")]
288pub struct Clear;
289
290#[laravel::console::command]
291impl Clear {
292    async fn handle(self, console: &mut Console, history: Inject<History>) -> laravel::Result<()> {
293        history.clear()?;
294        console.info("The debugbar's stored records are deleted.");
295
296        Ok(())
297    }
298}
299
300pub fn repeated(queries: &[Query]) -> Vec<Repeated> {
301    let mut shapes: Vec<Repeated> = Vec::new();
302
303    for query in queries {
304        match shapes.iter_mut().find(|shape| shape.sql == query.sql) {
305            Some(shape) => {
306                shape.count += 1;
307                shape.total_ms += query.duration_ms;
308            }
309            None => shapes.push(Repeated {
310                sql: query.sql.clone(),
311                count: 1,
312                total_ms: query.duration_ms,
313            }),
314        }
315    }
316
317    shapes.retain(|shape| shape.count > 1);
318    shapes.sort_by_key(|shape| std::cmp::Reverse(shape.count));
319    shapes
320}
321
322fn find(history: &History, id: &str) -> laravel::Result<Option<RequestRecord>> {
323    if id == "latest" {
324        return history.latest();
325    }
326
327    match id.parse() {
328        Ok(id) => history.find(id),
329        Err(_) => Ok(None),
330    }
331}
332
333fn failed(kind: RecordKind, status: u16) -> bool {
334    match kind {
335        RecordKind::Request => status >= 500,
336        RecordKind::Command | RecordKind::Job => status != 0,
337    }
338}
339
340fn parse_kind(kind: &str) -> RecordKind {
341    match kind {
342        "command" => RecordKind::Command,
343        "job" => RecordKind::Job,
344        _ => RecordKind::Request,
345    }
346}
347
348fn kind_name(kind: RecordKind) -> &'static str {
349    match kind {
350        RecordKind::Request => "request",
351        RecordKind::Command => "command",
352        RecordKind::Job => "job",
353    }
354}
355
356fn ago(milliseconds: u64) -> String {
357    match milliseconds / 1000 {
358        seconds @ 0..60 => format!("{seconds}s ago"),
359        seconds @ 60..3600 => format!("{}m ago", seconds / 60),
360        seconds @ 3600..86_400 => format!("{}h ago", seconds / 3600),
361        seconds => format!("{}d ago", seconds / 86_400),
362    }
363}
364
365fn capitalize(text: &str) -> String {
366    let mut characters = text.chars();
367    characters
368        .next()
369        .map(|first| first.to_uppercase().chain(characters).collect())
370        .unwrap_or_default()
371}