laravel-rust-devtools 0.2.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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
//! The `tracing` layer that turns the framework's spans into [`Trace`]s.

use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant, SystemTime};

use tracing::field::{Field, Visit};
use tracing::span::{Attributes, Id, Record};
use tracing::{Event, Metadata, Subscriber};
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::layer::{Context, Layer};
use tracing_subscriber::registry::{LookupSpan, SpanRef};

use crate::store::Store;
use crate::trace::{Dropped, Fields, Level, LogRecord, SpanKind, SpanRecord, Trace, TraceId, TraceKind};

/// How much one [`Trace`] may hold, so a runaway loop can't fill the memory. What doesn't fit is
/// counted in [`Trace::dropped`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Limits {
    spans: usize,
    logs: usize,
    value_len: usize,
}

impl Default for Limits {
    /// 1 000 spans, 500 log lines, and 4 KiB per field value.
    fn default() -> Self {
        Self {
            spans: 1_000,
            logs: 500,
            value_len: 4 * 1024,
        }
    }
}

impl Limits {
    /// Keep at most `spans` spans per trace.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn with_spans(mut self, spans: usize) -> Self {
        self.spans = spans;
        self
    }

    /// Keep at most `logs` log lines per trace.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn with_logs(mut self, logs: usize) -> Self {
        self.logs = logs;
        self
    }

    /// Cut a field's text after `bytes` bytes, at a character boundary.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn with_value_len(mut self, bytes: usize) -> Self {
        self.value_len = bytes;
        self
    }
}

/// A `tracing` layer that records each request, console command, queued job, scheduled task,
/// workflow step and tick as a [`Trace`] and puts it in a [`Store`] when the work ends.
///
/// It records the spans and log lines inside each unit of work, at `DEBUG` and above, that come
/// from the framework (targets under `laravel::`) or from the application's own code: its crates
/// and the packages it builds from a path. Lines that come through the `log` crate are judged by
/// the target and file they were written with, and a line that names no file is left out. Spans
/// outside any unit of work, such as a queue worker polling for jobs, aren't recorded.
///
/// The libraries under the framework stay out, in two ways:
///
/// - Libraries whose lines carry values are never recorded, wherever their sources are and even
///   when named with [`with_crates`](Self::with_crates): `sqlx` and every crate named `sqlx_*`,
///   whose lines carry a query's SQL with its literals; `lettre`, whose lines carry the SMTP
///   conversation; and `aws_smithy_runtime`, whose lines carry an S3 object's key. The list covers
///   the libraries under the framework: an application that adds a library of its own that logs
///   values, and builds from vendored or remapped sources, has to filter that library itself.
/// - The rest are told apart by where Cargo keeps their sources: a crate from a registry or Git.
///   A build that keeps them elsewhere, such as `cargo vendor`, Nix or `--remap-path-prefix`, records
///   their lines too. To record a downloaded package, name it with
///   [`with_crates`](Self::with_crates).
///
/// What a mail, SMS or broadcast says stays out: the framework's `log` mailer writes each mail's
/// recipients, subject and text, and the trace keeps only its ID. What the framework's errors say
/// is recorded as `[masked]` too, unless turned on with [`with_error_text`](Self::with_error_text):
/// a trace keeps an error's kind, where it was raised and when. In the application's own lines,
/// only a field named `error` is masked: an error's text in a message, or in a field named
/// otherwise, is recorded as written.
///
/// Fields whose name suggests a secret, such as `password`, `x-api-key` or `session_id`, are
/// recorded as `[masked]`. Masking goes by name: a secret in a log line's message, or in the value
/// of a field with an ordinary name, is recorded as it was written.
#[derive(Debug)]
pub(crate) struct Collector {
    /// Tells this collector's places in a span's extensions from another's: an application may
    /// add more than one, or a clone of the same.
    id: u64,
    store: Arc<dyn Store>,
    limits: Limits,
    crates: Vec<String>,
    error_text: bool,
}

impl Collector {
    /// A collector that puts finished traces in `store`, within the default [`Limits`].
    ///
    /// To read the traces while the collector records them, pass an `Arc` of the store and keep a
    /// clone.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn new(store: impl Store + 'static) -> Self {
        Self::shared(Arc::new(store))
    }

    /// A collector that records into `store`, which others hold too, without wrapping it again.
    pub(crate) fn shared(store: Arc<dyn Store>) -> Self {
        Self {
            id: next_id(),
            store,
            limits: Limits::default(),
            crates: Vec::new(),
            error_text: false,
        }
    }

    /// What tells this collector's traces from another's, for [`running`].
    pub(crate) const fn key(&self) -> u64 {
        self.id
    }

    /// Record within `limits` instead of the default ones.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn with_limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// Also record the spans and lines of these downloaded crates, such as packages the
    /// application installed from crates.io. Names may be written with `-` or `_`.
    ///
    /// A line belongs to a crate by its target's first part, which is the crate's name unless the
    /// crate sets targets of its own: name those instead. Libraries whose lines carry values, such
    /// as `sqlx`, stay out even when named.
    #[must_use]
    pub(crate) fn with_crates<I>(mut self, crates: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<String>,
    {
        self.crates
            .extend(crates.into_iter().map(|name| name.into().replace('-', "_")));
        self
    }

    /// Record what errors say, instead of `[masked]`, while looking for a bug. Off by default.
    ///
    /// An error's text can quote what the application handled: a response body from an API, the
    /// recipient a mail provider refused, a Redis command's arguments. So by default a trace keeps
    /// what kind of error it was, where it was raised and when, and records its text as
    /// `[masked]`: a reported error's message and causes, the text of a job that will be retried,
    /// why a JSON-LD schema was left out of a page's head, and every field named `error`. Where an
    /// error was raised is where it was built, which for an error the framework builds is in the
    /// framework: the trace's spans lead back to the application's code. Turned on, everyone who
    /// can read the traces sees those texts.
    #[must_use]
    pub(crate) fn with_error_text(mut self, error_text: bool) -> Self {
        self.error_text = error_text;
        self
    }

    /// The fields of what `target` writes that are recorded as `[masked]`.
    fn masked(&self, target: &str) -> &'static [&'static str] {
        match (target, self.error_text) {
            // The `Set-Cookie` header of a cookie that couldn't be parsed, unencrypted.
            (COOKIE, false) => &["error", "header"],
            (COOKIE, true) => &["header"],
            (ERRORS, false) => &["error", "causes"],
            // A JSON-LD schema that couldn't serialize quotes the serializer's error.
            (HEAD, false) => &["error", "problem"],
            (_, false) => &["error"],
            (_, true) => &[],
        }
    }

    /// The message of a line `target` wrote, with the error text it quotes masked unless errors'
    /// texts are recorded.
    fn message(&self, target: &str, message: String) -> String {
        if self.error_text {
            return message;
        }
        if target == ERRORS {
            // A reported error's line is its text.
            return MASKED.to_owned();
        }
        match message.strip_prefix(RETRIED) {
            Some(_) if target == QUEUE => format!("{RETRIED}{MASKED}"),
            _ => message,
        }
    }

    /// Whether what `target` wrote, in `file`, belongs in a trace.
    fn admits(&self, target: &str, file: Option<&str>) -> bool {
        if target == "laravel" || target.starts_with("laravel::") {
            return true;
        }
        let crate_name = target.split_once("::").map_or(target, |(crate_name, _)| crate_name);
        if carries_values(crate_name) {
            return false;
        }
        if self.crates.iter().any(|name| name == crate_name) {
            return true;
        }

        file.is_some_and(|file| !downloaded(file))
    }
}

/// What a trace that is still being built shows so far: what a response carries in its headers
/// before its work ends.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Running {
    pub(crate) id: TraceId,
    pub(crate) queries: usize,
    pub(crate) query_time: Duration,
    pub(crate) elapsed: Duration,
}

/// The trace the collector with `key` builds around the current span, if it builds one.
///
/// The span's subscriber must be built on `tracing_subscriber`'s registry, as an application's is.
pub(crate) fn running(key: u64) -> Option<Running> {
    tracing::Span::current()
        .with_subscriber(|(id, dispatch)| {
            let registry = dispatch.downcast_ref::<tracing_subscriber::Registry>()?;
            let span = registry.span(id)?;
            let Located::In { trace, .. } = place_of(&span, key)? else {
                return None;
            };
            let building = lock(&trace);
            let queries = building.spans.iter().filter(|open| open.record.kind == SpanKind::Query);
            Some(Running {
                id: building.id,
                queries: queries.clone().count(),
                query_time: queries.filter_map(|open| open.record.duration).sum(),
                elapsed: building.started.elapsed(),
            })
        })
        .flatten()
}

/// A clone records into the same store, and is told from the original in a span's extensions:
/// added as two layers, both record each trace whole.
impl Clone for Collector {
    fn clone(&self) -> Self {
        Self {
            id: next_id(),
            store: Arc::clone(&self.store),
            limits: self.limits,
            crates: self.crates.clone(),
            error_text: self.error_text,
        }
    }
}

fn next_id() -> u64 {
    static NEXT: AtomicU64 = AtomicU64::new(0);

    NEXT.fetch_add(1, Ordering::Relaxed)
}

/// Whether a library's lines carry values: SQL with its literals, a mail's SMTP conversation, or
/// an S3 object's key (`aws_smithy_runtime` logs the endpoint parameters, which hold it).
///
/// This list keeps values out of a trace, whatever the build. Where a library's sources are keeps
/// out only noise: a build that moves them, such as `cargo vendor`, defeats it. Every crate named
/// `sqlx_*` is left out, an application's own too, so that no driver of `sqlx` slips through.
fn carries_values(crate_name: &str) -> bool {
    matches!(crate_name, "sqlx" | "lettre" | "aws_smithy_runtime") || crate_name.starts_with("sqlx_")
}

/// Whether `file` belongs to a crate Cargo downloaded: from a registry, such as crates.io, or from
/// Git. The application's own crates and its path dependencies are anywhere else.
fn downloaded(file: &str) -> bool {
    [
        "/registry/src/",
        "\\registry\\src\\",
        "/git/checkouts/",
        "\\git\\checkouts\\",
    ]
    .iter()
    .any(|directory| file.contains(directory))
}

// The framework's span targets and names. Laravel for Rust doesn't export them, so tests with the
// real framework spans guard them.
const REQUEST: &str = "laravel::request";
const COMMAND: &str = "laravel::console";
const QUEUE: &str = "laravel::queue";
const SCHEDULE: &str = "laravel::schedule";
const WORKFLOW: &str = "laravel::workflow";
const TICK: &str = "laravel::tick";
const UNTRACED: &str = "laravel::untraced";

// The targets and the one message whose error text a trace masks: the framework writes every other
// error's text in a field named `error`. Read from laravel-rust 0.1.4's and 0.1.5's sources: a later
// version may write an error's text elsewhere, and its tests in `error_text.rs` are the check.
const ERRORS: &str = "laravel::errors";
const COOKIE: &str = "laravel::cookie";
const HEAD: &str = "laravel::head";
const RETRIED: &str = "The job failed and will be retried: ";

/// Mail and SMS lines keep which message it was, never what it says or to whom. A failed mailer's
/// `error` is masked like any other.
const MESSAGE: &[&str] = &[
    "id",
    "mailer",
    "sender",
    "failover",
    "provider_id",
    "attachments",
    "error",
];

/// The `log` broadcaster's lines keep which event went where, not its payload or socket.
const BROADCAST: &[&str] = &["event", "channels"];

/// The only fields a line of `target` keeps, if not all: for the targets that write what a
/// message says, and to whom.
fn kept(target: &str) -> Option<&'static [&'static str]> {
    match target {
        "laravel::mail" | "laravel::sms" => Some(MESSAGE),
        "laravel::broadcast" => Some(BROADCAST),
        _ => None,
    }
}

fn work(metadata: &Metadata<'_>) -> Option<TraceKind> {
    match (metadata.target(), metadata.name()) {
        (REQUEST, "request") => Some(TraceKind::Request),
        (COMMAND, "command") => Some(TraceKind::Command),
        (QUEUE, "job") => Some(TraceKind::Job),
        (SCHEDULE, "scheduled_task") => Some(TraceKind::ScheduledTask),
        (WORKFLOW, "workflow" | "step") => Some(TraceKind::Workflow),
        (TICK, "tick") => Some(TraceKind::Tick),
        _ => None,
    }
}

fn span_kind(metadata: &Metadata<'_>) -> SpanKind {
    match metadata.target() {
        "laravel::db" => SpanKind::Query,
        "laravel::cache" => SpanKind::Cache,
        "laravel::redis" => SpanKind::Redis,
        "laravel::http::client" => SpanKind::Http,
        "laravel::mail" => SpanKind::Mail,
        "laravel::sms" => SpanKind::Sms,
        _ if work(metadata).is_some() => SpanKind::Work,
        _ => SpanKind::Other,
    }
}

/// Where a span stands for each collector, kept in its extensions.
#[derive(Default)]
struct Places(Vec<(u64, Place)>);

impl Places {
    fn get(&self, collector: u64) -> Option<&Place> {
        self.0.iter().find(|(id, _)| *id == collector).map(|(_, place)| place)
    }

    fn remove(&mut self, collector: u64) -> Option<Place> {
        let index = self.0.iter().position(|(id, _)| *id == collector)?;
        Some(self.0.swap_remove(index).1)
    }
}

/// Where a span stands.
enum Place {
    /// The span is a unit of work, and its trace is being built.
    Root(Arc<Mutex<Building>>),
    /// The span is recorded at `index` in a trace.
    Span { trace: Arc<Mutex<Building>>, index: usize },
    /// The span is in a trace but not recorded: the trace had no room for it, or its level is
    /// `TRACE`. Its log lines and spans go to the nearest recorded span around it.
    Hidden {
        trace: Arc<Mutex<Building>>,
        parent: Option<usize>,
    },
    /// The framework's own housekeeping, which isn't the application's work.
    Untraced,
}

/// A trace while its work runs.
struct Building {
    id: TraceId,
    kind: TraceKind,
    /// The name of the work's span, for work that doesn't name itself.
    span_name: &'static str,
    /// Whether the trace went to the store. Work started in the background, such as with
    /// `laravel::task::background`, keeps the request's span open after the response; what it does
    /// later isn't part of the request.
    finished: bool,
    started: Instant,
    started_at: SystemTime,
    fields: Fields,
    spans: Vec<OpenSpan>,
    logs: Vec<LogRecord>,
    dropped: Dropped,
}

struct OpenSpan {
    record: SpanRecord,
    started: Instant,
}

fn lock(trace: &Mutex<Building>) -> MutexGuard<'_, Building> {
    trace.lock().unwrap_or_else(PoisonError::into_inner)
}

impl<S> Layer<S> for Collector
where
    S: Subscriber + for<'lookup> LookupSpan<'lookup>,
{
    fn max_level_hint(&self) -> Option<LevelFilter> {
        Some(LevelFilter::DEBUG)
    }

    fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
        let Some(span) = ctx.span(id) else { return };
        let metadata = span.metadata();

        let place = if metadata.target() == UNTRACED {
            Some(Place::Untraced)
        } else {
            match span.parent().as_ref().and_then(|parent| place_of(parent, self.id)) {
                Some(Located::Untraced) => Some(Place::Untraced),
                Some(Located::In { trace, parent })
                    if *metadata.level() > tracing::Level::DEBUG
                        || !self.admits(metadata.target(), metadata.file()) =>
                {
                    Some(Place::Hidden { trace, parent })
                }
                Some(Located::In { trace, parent }) => Some(self.open(attrs, metadata, trace, parent)),
                // The developer tools' own requests aren't the application's work: the panel asks
                // every few seconds, and its requests would push the application's out of the history.
                None if work(metadata) == Some(TraceKind::Request) && devtools_path(attrs) => Some(Place::Untraced),
                None => work(metadata).map(|kind| Place::Root(Arc::new(Mutex::new(self.start(kind, attrs))))),
            }
        };

        if let Some(place) = place {
            let mut extensions = span.extensions_mut();
            if let Some(places) = extensions.get_mut::<Places>() {
                places.0.push((self.id, place));
            } else {
                extensions.insert(Places(vec![(self.id, place)]));
            }
        }
    }

    fn on_record(&self, id: &Id, values: &Record<'_>, ctx: Context<'_, S>) {
        let Some(span) = ctx.span(id) else { return };
        let extensions = span.extensions();
        match extensions.get::<Places>().and_then(|places| places.get(self.id)) {
            Some(Place::Root(trace)) => values.record(&mut Recorder::new(
                &mut lock(trace).fields,
                self.limits,
                self.masked(""),
            )),
            Some(Place::Span { trace, index }) => {
                if let Some(open) = lock(trace).spans.get_mut(*index) {
                    values.record(&mut Recorder::new(
                        &mut open.record.fields,
                        self.limits,
                        self.masked(""),
                    ));
                }
            }
            Some(Place::Hidden { .. } | Place::Untraced) | None => {}
        }
    }

    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
        let metadata = event.metadata();
        if *metadata.level() > tracing::Level::DEBUG {
            return;
        }
        // A line from the `log` crate arrives with the target `log`; the target and file it was
        // written with are among its fields.
        let bridged = (metadata.target() == "log").then(|| {
            let mut origin = LogOrigin::default();
            event.record(&mut origin);
            origin
        });
        let (target, file) = match &bridged {
            Some(origin) => (origin.target.as_deref().unwrap_or("log"), origin.file.as_deref()),
            None => (metadata.target(), metadata.file()),
        };
        if !self.admits(target, file) {
            return;
        }
        let Some(span) = ctx.event_span(event) else { return };
        let Some(Located::In { trace, parent }) = place_of(&span, self.id) else {
            return;
        };

        // The framework writes a request's line once the response has been sent, and ends the
        // request there, as it does for its OpenTelemetry span: work the request started in the
        // background holds the request's span until that work is done.
        let ends_request =
            parent.is_none() && metadata.target() == REQUEST && metadata.fields().field("duration_ms").is_some();

        let mut building = lock(&trace);
        if building.finished {
            return;
        }
        let ends_request = ends_request && building.kind == TraceKind::Request;
        let has_room = building.logs.len() < self.limits.logs;
        if !has_room {
            building.dropped.logs += 1;
            if !ends_request {
                return;
            }
        }
        drop(building);

        let mut fields = Fields::new();
        let mut message = None;
        event.record(&mut Recorder {
            fields: &mut fields,
            message: Some(&mut message),
            limits: self.limits,
            only: kept(target),
            masked: self.masked(target),
            skip_log: bridged.is_some(),
        });
        let message = message.map(|message| self.message(target, message));

        let mut building = lock(&trace);
        if building.finished {
            return;
        }
        if ends_request && let Some(status) = fields.get("status").cloned() {
            // A client that left before the response leaves the span without a status.
            building
                .fields
                .entry("http.response.status_code".to_owned())
                .or_insert(status);
        }
        // Other threads of the same work may have filled the trace while the fields were recorded.
        if building.logs.len() < self.limits.logs {
            let at = building.started.elapsed();
            building.logs.push(LogRecord {
                at,
                level: level(metadata),
                target: target.to_owned(),
                message: message.unwrap_or_default(),
                span: parent,
                fields,
            });
        } else if has_room {
            building.dropped.logs += 1;
        }

        if ends_request {
            let trace = finish(&mut building);
            drop(building);
            self.store.put(trace);
        }
    }

    /// A span lasts until it was last left, not until it closes: a library may keep a handle to a
    /// span after the work in it is done, such as sqlx's SQLite worker thread, which lets go of a
    /// query's span only after the query's caller has moved on.
    fn on_exit(&self, id: &Id, ctx: Context<'_, S>) {
        let Some(span) = ctx.span(id) else { return };
        let extensions = span.extensions();
        let Some(Place::Span { trace, index }) = extensions.get::<Places>().and_then(|places| places.get(self.id))
        else {
            return;
        };
        if let Some(open) = lock(trace).spans.get_mut(*index) {
            open.record.duration = Some(open.started.elapsed());
        }
    }

    fn on_close(&self, id: Id, ctx: Context<'_, S>) {
        let Some(span) = ctx.span(&id) else { return };
        let Some(place) = span
            .extensions_mut()
            .get_mut::<Places>()
            .and_then(|places| places.remove(self.id))
        else {
            return;
        };

        match place {
            Place::Root(trace) => {
                let mut building = lock(&trace);
                if !building.finished {
                    let trace = finish(&mut building);
                    drop(building);
                    self.store.put(trace);
                }
            }
            // A span that was never entered lasts until it closes.
            Place::Span { trace, index } => {
                if let Some(open) = lock(&trace).spans.get_mut(index) {
                    open.record.open = false;
                    if open.record.duration.is_none() {
                        open.record.duration = Some(open.started.elapsed());
                    }
                }
            }
            Place::Hidden { .. } | Place::Untraced => {}
        }
    }
}

/// Where the log lines and child spans of a span go.
enum Located {
    In {
        trace: Arc<Mutex<Building>>,
        parent: Option<usize>,
    },
    Untraced,
}

fn place_of<S>(span: &SpanRef<'_, S>, collector: u64) -> Option<Located>
where
    S: for<'lookup> LookupSpan<'lookup>,
{
    let extensions = span.extensions();
    match extensions.get::<Places>()?.get(collector)? {
        Place::Root(trace) => Some(Located::In {
            trace: Arc::clone(trace),
            parent: None,
        }),
        Place::Span { trace, index } => Some(Located::In {
            trace: Arc::clone(trace),
            parent: Some(*index),
        }),
        Place::Hidden { trace, parent } => Some(Located::In {
            trace: Arc::clone(trace),
            parent: *parent,
        }),
        Place::Untraced => Some(Located::Untraced),
    }
}

impl Collector {
    fn start(&self, kind: TraceKind, attributes: &Attributes<'_>) -> Building {
        let mut fields = Fields::new();
        attributes.record(&mut Recorder::new(&mut fields, self.limits, self.masked("")));

        Building {
            id: TraceId::generate(),
            kind,
            span_name: attributes.metadata().name(),
            finished: false,
            started: Instant::now(),
            started_at: SystemTime::now(),
            fields,
            spans: Vec::new(),
            logs: Vec::new(),
            dropped: Dropped::default(),
        }
    }

    fn open(
        &self,
        attributes: &Attributes<'_>,
        metadata: &'static Metadata<'static>,
        trace: Arc<Mutex<Building>>,
        parent: Option<usize>,
    ) -> Place {
        let mut building = lock(&trace);
        if building.finished {
            drop(building);
            return Place::Hidden { trace, parent };
        }
        if building.spans.len() >= self.limits.spans {
            building.dropped.spans += 1;
            drop(building);
            return Place::Hidden { trace, parent };
        }

        let mut fields = Fields::new();
        attributes.record(&mut Recorder::new(&mut fields, self.limits, self.masked("")));
        let now = Instant::now();
        let start = now.duration_since(building.started);
        building.spans.push(OpenSpan {
            record: SpanRecord {
                parent,
                kind: span_kind(metadata),
                name: metadata.name().to_owned(),
                target: metadata.target().to_owned(),
                start,
                duration: None,
                open: true,
                failed: false,
                fields,
            },
            started: now,
        });
        let index = building.spans.len() - 1;
        drop(building);

        Place::Span { trace, index }
    }
}

/// The finished trace of a unit of work that just ended.
fn finish(building: &mut Building) -> Trace {
    building.finished = true;
    let duration = building.started.elapsed();
    let mut fields = std::mem::take(&mut building.fields);
    let (otel_name, failed) = take_otel(&mut fields);

    let name = match building.kind {
        TraceKind::Request => {
            let text = |key: &str| fields.get(key).and_then(serde_json::Value::as_str).unwrap_or_default();
            format!("{} {}", text("method"), text("path"))
        }
        _ => otel_name.unwrap_or_else(|| building.span_name.to_owned()),
    };
    let status = fields
        .get("http.response.status_code")
        .and_then(serde_json::Value::as_u64)
        .and_then(|status| u16::try_from(status).ok());

    let spans = std::mem::take(&mut building.spans)
        .into_iter()
        .map(|open| {
            let mut record = open.record;
            let (name, failed) = take_otel(&mut record.fields);
            if let Some(name) = name {
                record.name = name;
            }
            record.failed = failed;
            record
        })
        .collect();

    Trace {
        id: building.id,
        kind: building.kind,
        name,
        started_at: building.started_at,
        duration,
        status,
        failed,
        fields,
        spans,
        logs: std::mem::take(&mut building.logs),
        dropped: building.dropped,
    }
}

/// Take the OpenTelemetry bookkeeping out of `fields`: the span's name, if it set one, and whether
/// it failed.
fn take_otel(fields: &mut Fields) -> (Option<String>, bool) {
    let name = match fields.remove("otel.name") {
        Some(serde_json::Value::String(name)) => Some(name),
        _ => None,
    };
    let failed = fields
        .remove("otel.status_code")
        .is_some_and(|status| status.as_str() == Some("error"));
    fields.retain(|key, _| !key.starts_with("otel."));

    (name, failed)
}

fn level(metadata: &Metadata<'_>) -> Level {
    match *metadata.level() {
        tracing::Level::ERROR => Level::Error,
        tracing::Level::WARN => Level::Warn,
        tracing::Level::INFO => Level::Info,
        _ => Level::Debug,
    }
}

/// Words in a field's name that mark its value as a secret, compared without case, and with `-`
/// and `.` counting as `_`, so `X-Api-Key` and `api.key` match `api_key`.
const SECRETS: &[&str] = &[
    "password",
    "passwd",
    "secret",
    "token",
    "authorization",
    "cookie",
    "session",
    "signature",
    "api_key",
    "apikey",
    "private_key",
    "credential",
];

const MASKED: &str = "[masked]";

fn is_secret(name: &str) -> bool {
    let name = name.as_bytes();
    SECRETS.iter().any(|secret| {
        name.windows(secret.len()).any(|window| {
            window
                .iter()
                .zip(secret.bytes())
                .all(|(&byte, wanted)| normalized(byte) == wanted)
        })
    })
}

fn normalized(byte: u8) -> u8 {
    match byte {
        b'-' | b'.' => b'_',
        _ => byte.to_ascii_lowercase(),
    }
}

/// Whether a request's span is for a path under the developer tools' own.
fn devtools_path(attrs: &Attributes<'_>) -> bool {
    struct Path(bool);

    // laravel-rust records the path as a `&str` since 0.1.5 and with `%` before; `Debug` of a
    // `&str` would quote it.
    impl Visit for Path {
        fn record_str(&mut self, field: &Field, value: &str) {
            if field.name() == "path" {
                self.0 = crate::http::is_own(value);
            }
        }

        fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
            if field.name() == "path" {
                self.0 = crate::http::is_own(&format!("{value:?}"));
            }
        }
    }

    let mut path = Path(false);
    attrs.record(&mut path);
    path.0
}

/// The target and file a line from the `log` crate was written with.
#[derive(Default)]
struct LogOrigin {
    target: Option<String>,
    file: Option<String>,
}

impl Visit for LogOrigin {
    fn record_str(&mut self, field: &Field, value: &str) {
        match field.name() {
            "log.target" => self.target = Some(value.to_owned()),
            "log.file" => self.file = Some(value.to_owned()),
            _ => {}
        }
    }

    fn record_debug(&mut self, _: &Field, _: &dyn fmt::Debug) {}
}

/// Records `tracing` fields as JSON values, within the limits, masking secrets.
struct Recorder<'a> {
    fields: &'a mut Fields,
    /// Where an event's `message` goes; a span's is a field like any other.
    message: Option<&'a mut Option<String>>,
    limits: Limits,
    /// The only fields to keep, if not all.
    only: Option<&'static [&'static str]>,
    /// The fields kept as `[masked]`: that there was one, not what it said.
    masked: &'static [&'static str],
    /// Leave out the `log.*` fields that carry a `log` line's origin.
    skip_log: bool,
}

impl<'a> Recorder<'a> {
    fn new(fields: &'a mut Fields, limits: Limits, masked: &'static [&'static str]) -> Self {
        Self {
            fields,
            message: None,
            limits,
            only: None,
            masked,
            skip_log: false,
        }
    }

    fn keeps(&self, field: &Field) -> bool {
        let name = field.name();
        if self.skip_log && name.starts_with("log.") {
            return false;
        }
        self.only.is_none_or(|only| name == "message" || only.contains(&name))
    }

    fn insert(&mut self, field: &Field, value: serde_json::Value) {
        if !self.keeps(field) {
            return;
        }
        let masked = self.masked.contains(&field.name());
        let value = if masked || is_secret(field.name()) {
            MASKED.into()
        } else {
            value
        };
        self.fields.insert(field.name().to_owned(), value);
    }

    fn text(&mut self, field: &Field, mut text: String) {
        if !self.keeps(field) {
            return;
        }
        truncate(&mut text, self.limits.value_len);
        if field.name() == "message"
            && let Some(message) = self.message.as_deref_mut()
        {
            *message = Some(text);
            return;
        }
        self.insert(field, text.into());
    }
}

impl Visit for Recorder<'_> {
    fn record_f64(&mut self, field: &Field, value: f64) {
        self.insert(field, value.into());
    }

    fn record_i64(&mut self, field: &Field, value: i64) {
        self.insert(field, value.into());
    }

    fn record_u64(&mut self, field: &Field, value: u64) {
        self.insert(field, value.into());
    }

    fn record_bool(&mut self, field: &Field, value: bool) {
        self.insert(field, value.into());
    }

    fn record_str(&mut self, field: &Field, value: &str) {
        self.text(field, value.to_owned());
    }

    fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
        self.text(field, value.to_string());
    }

    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
        self.text(field, format!("{value:?}"));
    }
}

/// Cut `text` after at most `len` bytes, at a character boundary, and mark the cut.
fn truncate(text: &mut String, len: usize) {
    if text.len() <= len {
        return;
    }
    let mut end = len;
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    text.truncate(end);
    text.push('…');
}

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

    #[test]
    fn secrets_are_recognised_by_their_name() {
        for name in [
            "password",
            "user.password_hash",
            "API_KEY",
            "x-csrf-token",
            "Authorization",
            "cookie",
            "x-api-key",
            "api-key",
            "api.key",
            "private-key",
            "session_id",
            "signature",
        ] {
            assert!(is_secret(name), "{name}");
        }
        for name in ["user", "db.query.text", "cache.key", "route"] {
            assert!(!is_secret(name), "{name}");
        }
    }

    const REGISTRY: &str =
        "/home/dev/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/sqlx-core-0.8.6/src/logger.rs";

    #[test]
    fn crates_from_a_registry_or_git_are_downloaded() {
        for file in [
            REGISTRY,
            "/usr/local/cargo/registry/src/index.crates.io-0/hyper-1.0.0/src/proto.rs",
            "/home/dev/.cargo/git/checkouts/fork-0a1b/2c3d/src/lib.rs",
            r"C:\Users\dev\.cargo\registry\src\index.crates.io-0\h2-0.4.0\src\lib.rs",
        ] {
            assert!(downloaded(file), "{file}");
        }
        for file in [
            "src/http/handlers/orders.rs",
            "/home/dev/work/packages/permissions/src/lib.rs",
        ] {
            assert!(!downloaded(file), "{file}");
        }
    }

    #[test]
    fn the_framework_and_the_application_s_own_code_are_recorded() {
        let collector = Collector::new(MemoryStore::new(1));

        assert!(collector.admits("laravel::db", Some(REGISTRY)));
        assert!(collector.admits("app::orders", Some("src/orders.rs")));
        assert!(!collector.admits("sqlx::query", Some(REGISTRY)));
        assert!(!collector.admits("lettre::transport", Some(REGISTRY)));
        assert!(!collector.admits("app::orders", None));
    }

    #[test]
    fn a_named_crate_is_recorded_though_downloaded() {
        let collector = Collector::new(MemoryStore::new(1)).with_crates(["laravel-rust-permissions"]);

        assert!(collector.admits("laravel_rust_permissions::check", Some(REGISTRY)));
        assert!(!collector.admits("laravel_rust_other", Some(REGISTRY)));
    }

    #[test]
    fn libraries_that_carry_values_stay_out_wherever_their_sources_are() {
        let collector = Collector::new(MemoryStore::new(1)).with_crates(["sqlx", "sqlx-postgres", "lettre"]);

        for (target, file) in [
            ("sqlx::query", "/app/vendor/sqlx-core-0.8.6/src/logger.rs"),
            (
                "sqlx_postgres::connection",
                "/deps/sqlx-postgres-0.8.6/src/connection.rs",
            ),
            ("sqlx", "external/crates__sqlx-core-0.8.6/src/lib.rs"),
            ("lettre::transport::smtp", "src/main.rs"),
            (
                "aws_smithy_runtime::client::orchestrator::endpoints",
                "/deps/aws-smithy-runtime-1.16.4/src/lib.rs",
            ),
        ] {
            assert!(!collector.admits(target, Some(file)), "{target}");
        }
        assert!(!collector.admits("sqlx_app::orders", Some("src/orders.rs")));
        assert!(collector.admits("sqlxtra::orders", Some("src/orders.rs")));
    }

    #[test]
    fn long_text_is_cut_at_a_character_boundary() {
        let mut text = "aé".repeat(4);
        truncate(&mut text, 4);

        assert_eq!(text, "aéa…");
    }

    #[test]
    fn short_text_is_left_alone() {
        let mut text = "short".to_owned();
        truncate(&mut text, 5);

        assert_eq!(text, "short");
    }

    #[test]
    fn the_default_limits_are_those_the_docs_name() {
        assert_eq!(
            Limits::default(),
            Limits {
                spans: 1_000,
                logs: 500,
                value_len: 4 * 1024,
            }
        );
    }
}