laravel-rust-devtools 0.2.1

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
//! 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::hash::{BuildHasher, Hasher, RandomState};
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.
///
/// Values are JSON values: strings, numbers and booleans as `tracing` recorded them. They are
/// [`serde_json::Value`]s, so `serde_json` 1.x is part of this crate's public API.
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(std::process::id(), millis));
        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 bits for the process with `pid`, started at `millis`. The hasher's keys come from the
/// system's randomness anew in each process, so two processes with the same ID, started in the same
/// millisecond, still get different bits.
fn process_bits(pid: u32, millis: u128) -> u64 {
    let mut hasher = RandomState::new().build_hasher();
    hasher.write_u32(pid);
    hasher.write_u128(millis);

    hasher.finish() & 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,
}

/// 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,
    /// How long the span ran, until it was last left; `None` when it had been neither left nor
    /// closed when the trace ended.
    #[serde(rename = "duration_us", with = "option_micros")]
    pub(crate) duration: Option<Duration>,
    /// Whether the span was still open when the trace ended: still running, such as background
    /// work waiting for something, or held by a library after its work was done, as sqlx's SQLite
    /// worker holds a query's span for a moment. Its [`duration`](Self::duration) then runs until
    /// it was last left, which for work still running is only part of it.
    pub(crate) open: bool,
    /// Whether the span ended in an error.
    pub(crate) failed: bool,
    /// The span's fields, such as `db.query.text`.
    pub(crate) fields: Fields,
}

/// 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| !ends_or_begins_a_transaction(&query.name))
            .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(),
        }
    }
}

/// Whether a query's span, which the framework names by its statement's first word, begins or ends
/// a transaction or savepoint: a statement every transaction runs, not one the application repeats.
fn ends_or_begins_a_transaction(name: &str) -> bool {
    let word = name.split_whitespace().next().unwrap_or_default();
    ["BEGIN", "COMMIT", "ROLLBACK", "SAVEPOINT", "RELEASE"]
        .iter()
        .any(|boundary| boundary.eq_ignore_ascii_case(word))
}

/// 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, with a fixed process ID and time.
    #[test]
    fn processes_with_the_same_id_get_different_bits() {
        let name = crate::tests::test_name!(processes_with_the_same_id_get_different_bits);
        if crate::tests::is_alone(name) {
            let bits = format!("<{:012x}>", process_bits(30, 1_796_287_027_151));
            std::io::Write::write_all(&mut std::io::stdout(), bits.as_bytes()).unwrap();
            return;
        }
        // Two processes, as the services of a Docker setup are: same process ID, same millisecond.
        let bits = || {
            let output = crate::tests::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 an_id_reads_back_what_it_writes() {
        let id = TraceId::generate();

        assert_eq!(id.to_string().parse::<TraceId>(), Ok(id));
    }

    #[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),
                duration: None,
                open: false,
                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,
            duration: Some(Duration::from_micros(100)),
            open: false,
            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);
    }

    /// 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
        };
        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);
    }

    /// 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));
    }

    #[test]
    fn a_later_id_sorts_after_an_earlier_one() {
        assert!(TraceId::generate() < TraceId::generate());
    }

    #[test]
    fn text_that_isn_t_an_id_is_refused() {
        assert_eq!("not an id".parse::<TraceId>(), Err(ParseTraceIdError));
    }
}