laravel-rust-devtools 0.4.0

Developer tools for Laravel for Rust applications: an app inspector and request debugger in a floating toolbar.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
//! What one unit of work recorded: a request, a console command, a queued job, a scheduled task, a
//! workflow step or a tick, with the spans and log lines that ran inside it.

use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

/// The fields a span or log line carried, by name: strings, numbers and booleans as `tracing`
/// recorded them.
pub(crate) type Fields = BTreeMap<String, serde_json::Value>;

/// The ID of a [`Trace`]: unique across the application's processes, and ordered by when the trace
/// started, so sorting IDs sorts traces by time.
///
/// The order holds to the millisecond. Within one millisecond, the traces of one process are in
/// order; those of different processes are in an order of their own, by bits each process picks at
/// random when it starts.
///
/// It reads and writes as 32 lowercase hexadecimal digits.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct TraceId(u128);

impl TraceId {
    /// A new ID: the current time in milliseconds, then 48 bits this process picked at random,
    /// then a counter. Two processes that write to the same history don't collide, even with the
    /// same process ID, as the services of a Docker setup each have in their container.
    #[must_use]
    pub(crate) fn generate() -> Self {
        static SEQUENCE: AtomicU64 = AtomicU64::new(0);
        static PROCESS: OnceLock<u64> = OnceLock::new();

        let millis = now_millis();
        let process = *PROCESS.get_or_init(process_bits);
        let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) & 0xFFFF_FFFF;

        Self(((millis & 0xFFFF_FFFF_FFFF) << 80) | (u128::from(process) << 32) | u128::from(sequence))
    }

    /// When the trace started, in milliseconds since the Unix epoch.
    pub(crate) fn millis(self) -> u64 {
        u64::try_from(self.0 >> 80).unwrap_or(u64::MAX)
    }
}

fn now_millis() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |elapsed| elapsed.as_millis())
}

/// 48 random bits for this process, from the system's randomness: two processes with the same ID,
/// started in the same millisecond, still get different bits. They are the last bits of a random
/// UUID, which holds no version or variant there.
fn process_bits() -> u64 {
    laravel::str::uuid().as_u64_pair().1 & 0xFFFF_FFFF_FFFF
}

impl fmt::Debug for TraceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "TraceId({self})")
    }
}

impl fmt::Display for TraceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:032x}", self.0)
    }
}

/// Why a string isn't a [`TraceId`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ParseTraceIdError;

impl fmt::Display for ParseTraceIdError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a trace ID is 32 hexadecimal digits")
    }
}

impl std::error::Error for ParseTraceIdError {}

impl FromStr for TraceId {
    type Err = ParseTraceIdError;

    /// Reads the 32 hexadecimal digits that [`TraceId`]'s `Display` writes.
    ///
    /// # Errors
    ///
    /// Returns [`ParseTraceIdError`] when the string isn't exactly 32 hexadecimal digits.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.len() != 32 || !s.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            return Err(ParseTraceIdError);
        }

        u128::from_str_radix(s, 16)
            .map(Self)
            .map_err(|_unreachable| ParseTraceIdError)
    }
}

impl Serialize for TraceId {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for TraceId {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
        text.parse().map_err(serde::de::Error::custom)
    }
}

/// What kind of work a [`Trace`] recorded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, laravel::Enum)]
#[serde(rename_all = "snake_case")]
pub(crate) enum TraceKind {
    /// An HTTP request.
    Request,
    /// A console command, except the long-running ones such as `serve` or `queue:work`.
    Command,
    /// One attempt of a queued job.
    Job,
    /// A scheduled task.
    ScheduledTask,
    /// A workflow advancing, or one of its steps.
    Workflow,
    /// A tick: work the application repeats on an interval.
    Tick,
}

impl TraceKind {
    /// Whether the process usually ends with the work, as it does after a console command or a
    /// task run by `schedule:run`. Its trace is written before the work returns; any other work
    /// runs inside a server or a queue worker, whose threads must not wait for a file.
    pub(crate) fn ends_its_process(self) -> bool {
        match self {
            Self::Command | Self::ScheduledTask => true,
            Self::Request | Self::Job | Self::Workflow | Self::Tick => false,
        }
    }
}

/// What a [`SpanRecord`] measured, from the framework's span targets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum SpanKind {
    /// A database statement, including a transaction's `BEGIN` and `COMMIT`.
    Query,
    /// A cache operation.
    Cache,
    /// A Redis command.
    Redis,
    /// An outgoing HTTP request.
    Http,
    /// Rendering or sending a mail.
    Mail,
    /// Sending an SMS.
    Sms,
    /// A unit of work nested in another, such as a job the request ran synchronously.
    Work,
    /// Any other span: the application's own, or a package's.
    Other,
}

/// The level of a [`LogRecord`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Level {
    /// `tracing::Level::DEBUG`.
    Debug,
    /// `tracing::Level::INFO`.
    Info,
    /// `tracing::Level::WARN`.
    Warn,
    /// `tracing::Level::ERROR`.
    Error,
}

/// One span inside a [`Trace`], such as a query.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct SpanRecord {
    /// The index of the span that contains this one in [`Trace::spans`]; `None` when the trace's own
    /// work contains it directly. A span the trace left out, for its limits or its `TRACE` level,
    /// passes its place to what it contains: they point to the nearest recorded span around it.
    pub(crate) parent: Option<usize>,
    /// What the span measured.
    pub(crate) kind: SpanKind,
    /// The span's name: the framework's short description, such as `SELECT users` for a query, or
    /// the name the code gave the span.
    pub(crate) name: String,
    /// The `tracing` target, such as `laravel::db`.
    pub(crate) target: String,
    /// When the span started, after the trace started.
    #[serde(rename = "start_us", with = "micros")]
    pub(crate) start: Duration,
    /// Where the span stood when the trace ended.
    #[serde(flatten)]
    pub(crate) state: SpanState,
    /// For a query, whether it begins or ends a transaction or savepoint. A trace written before
    /// 0.3.4 has none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) boundary: Option<Boundary>,
    /// Whether the span ended in an error.
    pub(crate) failed: bool,
    /// The span's fields, such as `db.query.text`.
    pub(crate) fields: Fields,
}

/// Where a [`SpanRecord`] stood when its trace ended, and how long it had run.
///
/// It reads and writes as `duration_us`, until the span was last left, and `open`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "SpanEnd", into = "SpanEnd")]
pub(crate) enum SpanState {
    /// Still open and never left: still running, such as background work waiting for something.
    Running,
    /// Still open, but left after this long: held by a library after its work was done, as sqlx's
    /// SQLite worker holds a query's span for a moment, or still running after a pause, of which
    /// this is only the part before it.
    Left(Duration),
    /// Closed, after this long: until it was last left, or until it closed if it was never left.
    Closed(Duration),
}

impl SpanState {
    /// How long the span ran until it was last left or closed; `None` while it runs.
    pub(crate) fn duration(self) -> Option<Duration> {
        match self {
            Self::Running => None,
            Self::Left(duration) | Self::Closed(duration) => Some(duration),
        }
    }

    /// The span, left `elapsed` after it started. A closed span stays as it closed.
    #[must_use]
    pub(crate) fn left(self, elapsed: Duration) -> Self {
        match self {
            Self::Running | Self::Left(_) => Self::Left(elapsed),
            Self::Closed(_) => self,
        }
    }

    /// The span, closed `elapsed` after it started. It lasts until it was last left, or until it
    /// closes if it never was.
    #[must_use]
    pub(crate) fn closed(self, elapsed: Duration) -> Self {
        match self {
            Self::Running => Self::Closed(elapsed),
            Self::Left(duration) | Self::Closed(duration) => Self::Closed(duration),
        }
    }
}

/// How a [`SpanState`] reads and writes.
#[derive(Serialize, Deserialize)]
struct SpanEnd {
    #[serde(rename = "duration_us", with = "option_micros")]
    duration: Option<Duration>,
    open: bool,
}

impl From<SpanEnd> for SpanState {
    fn from(end: SpanEnd) -> Self {
        match (end.duration, end.open) {
            (None, _) => Self::Running,
            (Some(duration), true) => Self::Left(duration),
            (Some(duration), false) => Self::Closed(duration),
        }
    }
}

impl From<SpanState> for SpanEnd {
    fn from(state: SpanState) -> Self {
        Self {
            duration: state.duration(),
            open: !matches!(state, SpanState::Closed(_)),
        }
    }
}

/// One log line written inside a [`Trace`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct LogRecord {
    /// When the line was written, after the trace started.
    #[serde(rename = "at_us", with = "micros")]
    pub(crate) at: Duration,
    /// The line's level.
    pub(crate) level: Level,
    /// The `tracing` target, such as the module that wrote the line.
    pub(crate) target: String,
    /// The line's message.
    pub(crate) message: String,
    /// The index of the span the line was written in, in [`Trace::spans`]; `None` for the trace's
    /// own work. A line written in a span the trace left out points to the nearest recorded span
    /// around it.
    pub(crate) span: Option<usize>,
    /// The line's other fields.
    pub(crate) fields: Fields,
}

/// How much a [`Trace`] left out to stay within its [`Limits`](crate::collector::Limits).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct Dropped {
    /// Spans that weren't recorded.
    pub(crate) spans: usize,
    /// Log lines that weren't recorded.
    pub(crate) logs: usize,
}

/// One unit of work and everything recorded inside it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub(crate) struct Trace {
    /// The trace's ID.
    pub(crate) id: TraceId,
    /// What kind of work it was.
    pub(crate) kind: TraceKind,
    /// What ran: `GET /orders` for a request, the command's, job's, task's or workflow's name.
    pub(crate) name: String,
    /// When the work started.
    #[serde(rename = "started_at_ms", with = "unix_millis")]
    pub(crate) started_at: SystemTime,
    /// How long the work ran.
    #[serde(rename = "duration_us", with = "micros")]
    pub(crate) duration: Duration,
    /// A request's response status.
    pub(crate) status: Option<u16>,
    /// Whether the work ended in an error, such as a request answered with a server error.
    pub(crate) failed: bool,
    /// The fields of the work's own span, such as a request's `route`.
    pub(crate) fields: Fields,
    /// The spans that ran inside the work, in the order they started.
    pub(crate) spans: Vec<SpanRecord>,
    /// The log lines written inside the work, in the order they were written.
    pub(crate) logs: Vec<LogRecord>,
    /// What the trace left out to stay within its limits.
    pub(crate) dropped: Dropped,
}

impl Trace {
    /// The trace's summary, for lists.
    #[must_use]
    pub(crate) fn summary(&self) -> TraceSummary {
        let queries: Vec<&SpanRecord> = self.spans.iter().filter(|span| span.kind == SpanKind::Query).collect();
        let mut statements: BTreeMap<&str, usize> = BTreeMap::new();
        for statement in queries
            .iter()
            .filter(|query| query.boundary.is_none())
            .filter_map(|query| query.fields.get(QUERY_TEXT)?.as_str())
        {
            *statements.entry(statement).or_default() += 1;
        }

        TraceSummary {
            id: self.id,
            kind: self.kind,
            name: self.name.clone(),
            started_at: self.started_at,
            duration: self.duration,
            status: self.status,
            failed: self.failed,
            queries: queries.len(),
            repeated: statements.values().filter(|&&count| count > 1).count(),
            logs: self.logs.len(),
            warnings: self.logs.iter().filter(|log| log.level >= Level::Warn).count(),
        }
    }
}

/// Where a transaction or savepoint begins or ends: a statement every transaction runs, not one the
/// application repeats.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Boundary {
    /// `BEGIN`.
    Begin,
    /// `COMMIT`.
    Commit,
    /// `ROLLBACK`, also to a savepoint.
    Rollback,
    /// `SAVEPOINT`.
    Savepoint,
    /// `RELEASE`, of a savepoint.
    Release,
}

impl Boundary {
    /// The boundary a query's span is, by the first word the framework names it with; `None` for any
    /// other statement.
    pub(crate) fn of(name: &str) -> Option<Self> {
        let word = name.split_whitespace().next().unwrap_or_default();
        [
            ("BEGIN", Self::Begin),
            ("COMMIT", Self::Commit),
            ("ROLLBACK", Self::Rollback),
            ("SAVEPOINT", Self::Savepoint),
            ("RELEASE", Self::Release),
        ]
        .into_iter()
        .find_map(|(first, boundary)| first.eq_ignore_ascii_case(word).then_some(boundary))
    }
}

/// What a list of traces shows about each, without its spans and log lines.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct TraceSummary {
    /// The trace's ID.
    pub(crate) id: TraceId,
    /// What kind of work it was.
    pub(crate) kind: TraceKind,
    /// What ran.
    pub(crate) name: String,
    /// When the work started.
    #[serde(rename = "started_at_ms", with = "unix_millis")]
    pub(crate) started_at: SystemTime,
    /// How long the work ran.
    #[serde(rename = "duration_us", with = "micros")]
    pub(crate) duration: Duration,
    /// A request's response status.
    pub(crate) status: Option<u16>,
    /// Whether the work ended in an error.
    pub(crate) failed: bool,
    /// How many queries it ran.
    pub(crate) queries: usize,
    /// How many different statements it ran more than once, by their text with values left out.
    #[serde(default)]
    pub(crate) repeated: usize,
    /// How many log lines it wrote.
    pub(crate) logs: usize,
    /// How many of them are warnings or errors.
    #[serde(default)]
    pub(crate) warnings: usize,
}

/// The field of a query's span that holds its statement, with values left out.
const QUERY_TEXT: &str = "db.query.text";

// JSON carries times as whole numbers, which every client reads without a date library.

mod micros {
    use std::time::Duration;

    use serde::{Deserialize, Deserializer, Serializer};

    pub(super) fn serialize<S: Serializer>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_u64(u64::try_from(duration.as_micros()).unwrap_or(u64::MAX))
    }

    pub(super) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Duration, D::Error> {
        u64::deserialize(deserializer).map(Duration::from_micros)
    }
}

mod option_micros {
    use std::time::Duration;

    use serde::{Deserialize, Deserializer, Serializer};

    #[expect(clippy::ref_option, reason = "serde's `with` passes the field by reference")]
    pub(super) fn serialize<S: Serializer>(duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error> {
        match duration {
            Some(duration) => super::micros::serialize(duration, serializer),
            None => serializer.serialize_none(),
        }
    }

    pub(super) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Duration>, D::Error> {
        Ok(Option::<u64>::deserialize(deserializer)?.map(Duration::from_micros))
    }
}

mod unix_millis {
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    use serde::{Deserialize, Deserializer, Serializer};

    pub(super) fn serialize<S: Serializer>(time: &SystemTime, serializer: S) -> Result<S::Ok, S::Error> {
        let millis = time.duration_since(UNIX_EPOCH).map_or(0, |since| since.as_millis());
        serializer.serialize_u64(u64::try_from(millis).unwrap_or(u64::MAX))
    }

    pub(super) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<SystemTime, D::Error> {
        let millis = u64::deserialize(deserializer)?;
        Ok(UNIX_EPOCH + Duration::from_millis(millis))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn ids_are_ordered_by_time_and_unique() {
        let first = TraceId::generate();
        let second = TraceId::generate();

        assert!(first < second);
        assert_ne!(first, second);
    }

    /// What `process_bits` gave the process the test started.
    #[test]
    fn processes_with_the_same_id_get_different_bits() {
        let name = crate::harness::test_name!(processes_with_the_same_id_get_different_bits);
        if crate::harness::is_alone(name) {
            let bits = format!("<{:012x}>", process_bits());
            std::io::Write::write_all(&mut std::io::stdout(), bits.as_bytes()).unwrap();
            return;
        }
        // Two processes of the same program, as the services of a Docker setup are.
        let bits = || {
            let output = crate::harness::child(name, &[]);
            let text = String::from_utf8_lossy(&output.stdout).into_owned();
            let start = text.find('<').unwrap() + 1;
            text[start..start + 12].to_owned()
        };
        let (first, second) = (bits(), bits());

        assert_eq!(first.len(), 12, "{first:?}");
        assert_ne!(first, second);
    }

    #[test]
    fn only_32_hexadecimal_digits_are_an_id() {
        for text in [
            "",
            "abc",
            &"g".repeat(32),
            &"0".repeat(33),
            "+0000000000000000000000000000000",
        ] {
            assert_eq!(text.parse::<TraceId>(), Err(ParseTraceIdError), "{text:?}");
        }
    }

    #[test]
    fn a_trace_survives_json() {
        let trace = Trace {
            id: TraceId::generate(),
            kind: TraceKind::Request,
            name: "GET /orders".to_owned(),
            started_at: UNIX_EPOCH + Duration::from_millis(1_764_700_000_123),
            duration: Duration::from_micros(4_321),
            status: Some(200),
            failed: false,
            fields: Fields::from([("route".to_owned(), "/orders".into())]),
            spans: vec![SpanRecord {
                parent: None,
                kind: SpanKind::Query,
                name: "SELECT orders".to_owned(),
                target: "laravel::db".to_owned(),
                start: Duration::from_micros(12),
                state: SpanState::Running,
                boundary: None,
                failed: false,
                fields: Fields::new(),
            }],
            logs: vec![LogRecord {
                at: Duration::from_micros(40),
                level: Level::Info,
                target: "app".to_owned(),
                message: "listed".to_owned(),
                span: Some(0),
                fields: Fields::new(),
            }],
            dropped: Dropped { spans: 1, logs: 2 },
        };

        let json = serde_json::to_value(&trace).unwrap();

        assert_eq!(json["started_at_ms"], 1_764_700_000_123_u64);
        assert_eq!(json["duration_us"], 4_321);
        assert_eq!(json["spans"][0]["duration_us"], serde_json::Value::Null);
        assert_eq!(json["kind"], "request");
        assert_eq!(serde_json::from_value::<Trace>(json).unwrap(), trace);
    }

    fn query(text: &str) -> SpanRecord {
        SpanRecord {
            parent: None,
            kind: SpanKind::Query,
            name: "SELECT users".to_owned(),
            target: "laravel::db".to_owned(),
            start: Duration::ZERO,
            state: SpanState::Closed(Duration::from_micros(100)),
            boundary: None,
            failed: false,
            fields: Fields::from([(QUERY_TEXT.to_owned(), text.into())]),
        }
    }

    fn line(level: Level) -> LogRecord {
        LogRecord {
            at: Duration::ZERO,
            level,
            target: "app".to_owned(),
            message: "m".to_owned(),
            span: None,
            fields: Fields::new(),
        }
    }

    /// A summary counts the statements that ran more than once, each once however often it ran,
    /// and the lines at `warn` or above.
    #[test]
    fn a_summary_points_at_what_deserves_a_look() {
        let mut cache = query("ignored");
        cache.kind = SpanKind::Cache;
        let mut untexted = query("");
        untexted.fields.clear();
        let trace = Trace {
            id: TraceId::generate(),
            kind: TraceKind::Request,
            name: "GET /orders".to_owned(),
            started_at: UNIX_EPOCH,
            duration: Duration::ZERO,
            status: Some(200),
            failed: false,
            fields: Fields::new(),
            spans: vec![
                query("select * from users where id = ?"),
                query("select * from users where id = ?"),
                query("select * from users where id = ?"),
                query("select * from orders"),
                query("select * from teams"),
                query("select * from teams"),
                cache.clone(),
                cache,
                untexted.clone(),
                untexted,
            ],
            logs: [Level::Debug, Level::Info, Level::Warn, Level::Error, Level::Error]
                .into_iter()
                .map(line)
                .collect(),
            dropped: Dropped::default(),
        };

        let summary = trace.summary();

        assert_eq!(summary.queries, 8);
        assert_eq!(summary.repeated, 2);
        assert_eq!(summary.logs, 5);
        assert_eq!(summary.warnings, 3);
    }

    #[test]
    fn a_query_s_first_word_says_whether_it_begins_or_ends_a_transaction() {
        for (name, boundary) in [
            ("BEGIN", Some(Boundary::Begin)),
            ("commit", Some(Boundary::Commit)),
            ("ROLLBACK TO SAVEPOINT laravel_cursor", Some(Boundary::Rollback)),
            ("SAVEPOINT laravel_cursor", Some(Boundary::Savepoint)),
            ("RELEASE SAVEPOINT laravel_cursor", Some(Boundary::Release)),
            ("SELECT users", None),
            ("BEGINNING", None),
            ("", None),
        ] {
            assert_eq!(Boundary::of(name), boundary, "{name:?}");
        }
    }

    /// A transaction's statements are queries, but beginning and ending one twice is no statement
    /// run more than once: the panel's SQL view counts them the same way.
    #[test]
    fn transactions_begun_and_ended_more_than_once_are_no_repeated_statement() {
        let boundary = |name: &str, text: &str| {
            let mut span = query(text);
            name.clone_into(&mut span.name);
            span.boundary = Boundary::of(name);
            span
        };
        let mut spans = Vec::new();
        for _ in 0..2 {
            spans.extend([
                boundary("BEGIN", "BEGIN"),
                boundary("SAVEPOINT", "SAVEPOINT laravel_cursor"),
                boundary("ROLLBACK", "ROLLBACK TO SAVEPOINT laravel_cursor"),
                boundary("RELEASE", "RELEASE SAVEPOINT laravel_cursor"),
                boundary("COMMIT", "COMMIT"),
                boundary("rollback", "rollback"),
            ]);
        }
        spans.push(query("select * from users where id = ?"));
        let trace = Trace {
            id: TraceId::generate(),
            kind: TraceKind::Request,
            name: "POST /orders".to_owned(),
            started_at: UNIX_EPOCH,
            duration: Duration::ZERO,
            status: Some(200),
            failed: false,
            fields: Fields::new(),
            spans,
            logs: Vec::new(),
            dropped: Dropped::default(),
        };

        let summary = trace.summary();

        assert_eq!(summary.queries, 13);
        assert_eq!(summary.repeated, 0);
    }

    /// The panel reads a span's state as before: how long it ran until it was last left, and
    /// whether it was still open.
    #[test]
    fn a_span_s_state_reads_and_writes_as_its_duration_and_whether_it_is_open() {
        for (state, json) in [
            (
                SpanState::Running,
                serde_json::json!({ "duration_us": null, "open": true }),
            ),
            (
                SpanState::Left(Duration::from_micros(5)),
                serde_json::json!({ "duration_us": 5, "open": true }),
            ),
            (
                SpanState::Closed(Duration::from_micros(7)),
                serde_json::json!({ "duration_us": 7, "open": false }),
            ),
        ] {
            assert_eq!(serde_json::to_value(state).unwrap(), json);
            assert_eq!(serde_json::from_value::<SpanState>(json).unwrap(), state);
        }
    }

    #[test]
    fn a_span_lasts_until_it_was_last_left() {
        let (one, two, three) = (
            Duration::from_micros(1),
            Duration::from_micros(2),
            Duration::from_micros(3),
        );

        assert_eq!(SpanState::Running.closed(three), SpanState::Closed(three));
        assert_eq!(
            SpanState::Running.left(one).left(two).closed(three),
            SpanState::Closed(two)
        );
        assert_eq!(SpanState::Closed(one).left(two), SpanState::Closed(one));
    }

    /// A summary written before it counted repeated statements and warnings still reads, with none.
    #[test]
    fn an_older_summary_reads_without_the_newer_counts() {
        let json = serde_json::json!({
            "id": TraceId::generate(), "kind": "job", "name": "SendInvoice", "started_at_ms": 0,
            "duration_us": 0, "status": null, "failed": false, "queries": 2, "logs": 1,
        });

        let summary = serde_json::from_value::<TraceSummary>(json).unwrap();

        assert_eq!(
            (summary.queries, summary.repeated, summary.logs, summary.warnings),
            (2, 0, 1, 0)
        );
    }

    #[test]
    fn an_id_is_32_characters_and_reads_back() {
        let id = TraceId::generate();
        let text = id.to_string();

        assert_eq!(text.len(), 32);
        assert_eq!(text.parse::<TraceId>(), Ok(id));
    }
}