laravel-rust-devtools 0.3.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
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
//! A [`Store`] in a directory, which every process of the application shares.

use std::collections::BTreeSet;
use std::fs;
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError};
use std::sync::{Arc, Mutex, OnceLock, PoisonError};
use std::thread::JoinHandle;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crate::store::{Store, StoreError};
use crate::trace::{Trace, TraceId, TraceKind, TraceSummary};

/// How many traces may wait for the writer before new ones are discarded.
const BACKLOG: usize = 256;

/// How long work other than a request waits for its trace to be written.
const WAIT: Duration = Duration::from_secs(2);

/// How old a file left half-written, by a process that ended while writing it, may get.
const HALF_WRITTEN: Duration = Duration::from_secs(60);

const TRACE: &str = ".json";
const SUMMARY: &str = ".summary.json";
const TEMPORARY: &str = ".tmp";

/// A [`Store`] that keeps the most recent traces as files in a directory, so a queue worker's jobs
/// and console commands show next to the requests, and the history outlives a restart.
///
/// Each trace is a file of its own, next to a small file with its summary, named by its
/// [`TraceId`]. Every process of the application writes to the same directory without locks: a
/// file is written under a temporary name and then renamed, so a reader sees it whole or not at
/// all. The directory belongs to the store, which removes what it no longer keeps. It is created
/// readable only by its owner, and so is each file: a trace holds the application's paths and the
/// shape of its queries. A directory that already exists keeps its permissions; its files are
/// still readable only by their owner, but anyone who can list the directory sees the traces' IDs.
///
/// The files are written on a thread of their own. A request hands its trace over and never waits.
/// Other work, such as a console command, waits up to two seconds for its trace to be written once
/// it is handed over. That happens when the work's span closes, which a database library can delay
/// until after the work has returned: sqlx's SQLite worker thread lets go of a query's span only
/// after the query's caller has moved on. A process that ends right after its work may then, rarely,
/// lose that work's trace. When more traces wait than the writer can keep up with, new ones are
/// discarded, and the log says so once for each reason.
///
/// [`list`](Store::list), [`get`](Store::get) and [`clear`](Store::clear) first wait, up to two
/// seconds, for what this store was handed to be written, and then read the directory: they block,
/// so an async handler calls them through `laravel::task::spawn_blocking`.
///
/// A process that ends without dropping the store, such as a server stopped with Ctrl+C, loses the
/// requests' traces still waiting to be written. Dropping the store writes them, waiting up to two
/// seconds.
///
/// The store keeps the most recent traces of all processes together, 100 by default, none older
/// than 24 hours. A trace whose file would be larger than 2 MiB keeps the beginning of the work:
/// its later spans and log lines are left out and counted in [`Trace::dropped`], while the summary
/// in the list still counts all its queries and lines. The work's own fields are kept whole, so a limit smaller than
/// them is exceeded by that much.
#[derive(Debug)]
pub(crate) struct FileStore {
    settings: Settings,
    writer: OnceLock<Option<SyncSender<Message>>>,
    /// The writer thread, and what tells it ended.
    thread: Mutex<Option<(JoinHandle<()>, Receiver<()>)>>,
    discarded: AtomicUsize,
    /// Whether the log has said a trace was discarded, for each [`Discard`].
    warned: [AtomicBool; 2],
    /// Traces handed to the writer and not yet written.
    waiting: Arc<AtomicUsize>,
}

#[derive(Debug, Clone)]
struct Settings {
    directory: PathBuf,
    capacity: usize,
    max_age: Duration,
    max_trace_bytes: usize,
}

/// Why a trace was discarded. The log says each once a store, so that no trace is lost unnoticed and
/// a writer that can't keep up doesn't flood the log.
#[derive(Debug, Clone, Copy)]
enum Discard {
    /// `BACKLOG` traces already wait for the writer.
    Backlog,
    /// The writer thread has ended.
    Stopped,
}

#[derive(Debug)]
enum Message {
    Write(Box<Trace>),
    /// Answered once everything sent before it is written.
    Flush(SyncSender<()>),
}

impl FileStore {
    /// A store in `directory`, which it creates when it writes the first trace. It keeps 100
    /// traces, none older than 24 hours, and trace files up to 2 MiB.
    #[must_use]
    pub(crate) fn new(directory: impl Into<PathBuf>) -> Self {
        Self {
            settings: Settings {
                directory: directory.into(),
                capacity: 100,
                max_age: Duration::from_hours(24),
                max_trace_bytes: 2 * 1024 * 1024,
            },
            writer: OnceLock::new(),
            thread: Mutex::new(None),
            discarded: AtomicUsize::new(0),
            warned: [AtomicBool::new(false), AtomicBool::new(false)],
            waiting: Arc::default(),
        }
    }

    /// Keep the `capacity` most recent traces, and at least one.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn with_capacity(mut self, capacity: usize) -> Self {
        self.settings.capacity = capacity.max(1);
        self
    }

    /// Keep no trace that started longer than `max_age` ago.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn with_max_age(mut self, max_age: Duration) -> Self {
        self.settings.max_age = max_age;
        self
    }

    /// Keep trace files to `bytes`: a larger trace loses its later spans and log lines. The work's
    /// own fields are kept whole, so a file is larger when they alone are.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn with_max_trace_bytes(mut self, bytes: usize) -> Self {
        self.settings.max_trace_bytes = bytes;
        self
    }

    /// How many traces this store discarded because the writer couldn't keep up, or couldn't be
    /// started.
    #[must_use]
    #[cfg(test)]
    pub(crate) fn discarded(&self) -> usize {
        self.discarded.load(Ordering::Relaxed)
    }

    /// The writer, started on first use; `None` when the thread couldn't be started.
    fn writer(&self) -> Option<&SyncSender<Message>> {
        self.writer
            .get_or_init(|| {
                let (sender, receiver) = mpsc::sync_channel(BACKLOG);
                let (ending, ended) = mpsc::channel::<()>();
                let settings = self.settings.clone();
                let waiting = Arc::clone(&self.waiting);
                let thread = std::thread::Builder::new()
                    .name("devtools-store".to_owned())
                    .spawn(move || {
                        let _ending = ending;
                        write_all(&settings, &receiver, &waiting);
                    });
                match thread {
                    Ok(thread) => {
                        *self.thread.lock().unwrap_or_else(PoisonError::into_inner) = Some((thread, ended));
                        Some(sender)
                    }
                    Err(error) => {
                        tracing::warn!(
                            error = &error as &dyn std::error::Error,
                            "the devtools history's writer couldn't be started"
                        );
                        None
                    }
                }
            })
            .as_ref()
    }

    /// Count a trace that won't be written, and say why the first time it happens for `reason`.
    fn discard(&self, reason: Discard) {
        self.discarded.fetch_add(1, Ordering::Relaxed);
        if self.warned[reason as usize].swap(true, Ordering::Relaxed) {
            return;
        }
        let directory = self.settings.directory.display();
        match reason {
            Discard::Backlog => tracing::warn!(
                waiting = BACKLOG,
                %directory,
                "traces are being discarded: the devtools history's writer can't keep up"
            ),
            Discard::Stopped => tracing::warn!(
                %directory,
                "traces are being discarded: the devtools history's writer has stopped"
            ),
        }
    }

    /// Wait until what this store was handed so far is written, so it reads its own writes.
    fn flush(&self) {
        let Some(Some(writer)) = self.writer.get() else {
            return;
        };
        let (done, written) = mpsc::sync_channel(1);
        if writer.try_send(Message::Flush(done)).is_ok() {
            let _ = written.recv_timeout(WAIT);
        }
    }

    fn ids(&self) -> Result<Vec<TraceId>, StoreError> {
        let oldest = oldest_kept(self.settings.max_age);
        let mut ids: Vec<TraceId> = files(&self.settings.directory)?
            .into_iter()
            .filter_map(|file| match file {
                File::Summary(id) if id.millis() >= oldest => Some(id),
                _ => None,
            })
            .collect();
        ids.sort_unstable_by(|a, b| b.cmp(a));
        ids.truncate(self.settings.capacity);

        Ok(ids)
    }
}

impl Store for FileStore {
    fn put(&self, trace: Trace) {
        let wait = trace.kind != TraceKind::Request;
        let Some(writer) = self.writer() else {
            self.discarded.fetch_add(1, Ordering::Relaxed);
            return;
        };
        // Counted before it is sent, so the writer never counts it down first.
        self.waiting.fetch_add(1, Ordering::Relaxed);
        match writer.try_send(Message::Write(Box::new(trace))) {
            Ok(()) if wait => self.flush(),
            Ok(()) => {}
            Err(error) => {
                self.waiting.fetch_sub(1, Ordering::Relaxed);
                self.discard(match error {
                    TrySendError::Full(_) => Discard::Backlog,
                    TrySendError::Disconnected(_) => Discard::Stopped,
                });
            }
        }
    }

    fn list(&self) -> Result<Vec<TraceSummary>, StoreError> {
        self.flush();
        let directory = &self.settings.directory;

        // A summary removed by another process since the directory was read, or not readable, is
        // left out of the list rather than failing it.
        Ok(self
            .ids()?
            .into_iter()
            .filter_map(|id| fs::read(directory.join(format!("{id}{SUMMARY}"))).ok())
            .filter_map(|json| serde_json::from_slice(&json).ok())
            .collect())
    }

    fn get(&self, id: TraceId) -> Result<Option<Trace>, StoreError> {
        self.flush();
        if !self.ids()?.contains(&id) {
            return Ok(None);
        }
        match fs::read(self.settings.directory.join(format!("{id}{TRACE}"))) {
            Ok(json) => Ok(Some(serde_json::from_slice(&json)?)),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(error) => Err(error.into()),
        }
    }

    fn summary(&self, id: TraceId) -> Result<Option<TraceSummary>, StoreError> {
        self.flush();
        if !self.ids()?.contains(&id) {
            return Ok(None);
        }
        match fs::read(self.settings.directory.join(format!("{id}{SUMMARY}"))) {
            Ok(json) => Ok(Some(serde_json::from_slice(&json)?)),
            Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
            Err(error) => Err(error.into()),
        }
    }

    fn clear(&self) -> Result<(), StoreError> {
        self.flush();
        let directory = &self.settings.directory;
        let files = files(directory)?;
        let summaries: BTreeSet<TraceId> = files
            .iter()
            .filter_map(|file| match file {
                File::Summary(id) => Some(*id),
                _ => None,
            })
            .collect();
        // Another process may be writing a trace right now, its trace and then its summary; what it
        // wrote so far stays, or its summary would list a trace that is gone.
        let mut gone: Vec<&File> = files
            .iter()
            .filter(|file| match file {
                File::Summary(_) => true,
                File::Trace(id) => summaries.contains(id) || half_written(&directory.join(file.name())),
                File::Temporary(name) => half_written(&directory.join(name)),
            })
            .collect();
        remove_all(directory, &mut gone)
    }
}

impl Drop for FileStore {
    /// Writes what is still waiting before the store goes, for up to two seconds; the writer
    /// finishes the rest on its own while the process runs, and says how many it had left.
    fn drop(&mut self) {
        drop(self.writer.take());
        let Some((thread, ended)) = self.thread.get_mut().unwrap_or_else(PoisonError::into_inner).take() else {
            return;
        };
        if ended.recv_timeout(WAIT) == Err(RecvTimeoutError::Disconnected) {
            let _ = thread.join();
        } else {
            let waiting = self.waiting.load(Ordering::Relaxed);
            tracing::warn!(
                waiting,
                "the devtools history is still being written; traces still waiting are lost if the process ends now"
            );
        }
    }
}

/// The writer thread: writes each trace and then removes what the store no longer keeps.
fn write_all(settings: &Settings, receiver: &Receiver<Message>, waiting: &AtomicUsize) {
    let directory = settings.directory.display();
    loop {
        match receiver.recv_timeout(Duration::from_hours(1)) {
            Ok(Message::Write(trace)) => {
                let written = write(settings, *trace);
                waiting.fetch_sub(1, Ordering::Relaxed);
                match written {
                    Ok(()) => prune_or_warn(settings),
                    Err(error) => {
                        tracing::warn!(
                            error = &error as &dyn std::error::Error,
                            %directory,
                            "a trace couldn't be written to the devtools history"
                        );
                    }
                }
            }
            Ok(Message::Flush(done)) => {
                let _ = done.try_send(());
            }
            // A quiet hour: traces still age out of the history.
            Err(RecvTimeoutError::Timeout) => prune_or_warn(settings),
            Err(RecvTimeoutError::Disconnected) => return,
        }
    }
}

fn prune_or_warn(settings: &Settings) {
    if let Err(error) = prune(settings) {
        let directory = settings.directory.display();
        tracing::warn!(
            error = &error as &dyn std::error::Error,
            %directory,
            "old traces couldn't be removed from the devtools history"
        );
    }
}

fn write(settings: &Settings, mut trace: Trace) -> Result<(), StoreError> {
    // The summary counts the queries and lines of the whole work, also those the file leaves out.
    let summary = serde_json::to_vec(&trace.summary())?;
    let json = fit(&mut trace, settings.max_trace_bytes)?;
    create_directory(&settings.directory)?;

    // The summary is what lists the trace, so it appears last and its trace is there to read.
    let id = trace.id;
    write_whole(&settings.directory, &format!("{id}{TRACE}"), &json)?;
    write_whole(&settings.directory, &format!("{id}{SUMMARY}"), &summary)
}

/// The trace as JSON of at most `max` bytes: when it's larger, it keeps the beginning of the work,
/// its spans and log lines in the order they happened until they no longer fit, and counts the
/// rest in [`Trace::dropped`]. The work's own fields are kept whole.
fn fit(trace: &mut Trace, max: usize) -> Result<Vec<u8>, StoreError> {
    if size(trace, max)?.is_some() {
        return Ok(serde_json::to_vec(trace)?);
    }
    let parents: Vec<Option<usize>> = trace.spans.iter().map(|span| span.parent).collect();
    let dropped = trace.dropped;
    let (spans, logs) = (std::mem::take(&mut trace.spans), std::mem::take(&mut trace.logs));
    let (all_spans, all_logs) = (spans.len(), logs.len());

    // Each span and line is measured once, and every measure is at least what it ends up taking:
    // the trace without them counts the most it could drop, each one counts its comma, and a line
    // has room for its span to become `null`. So what is kept fits without measuring again.
    trace.dropped.spans = dropped.spans.saturating_add(all_spans);
    trace.dropped.logs = dropped.logs.saturating_add(all_logs);
    let mut room = size(trace, max)?.map_or(0, |bare| max - bare);
    let (mut kept_spans, mut kept_logs) = (0, 0);
    loop {
        let span_next = match (spans.get(kept_spans), logs.get(kept_logs)) {
            (Some(span), Some(log)) => span.start <= log.at,
            (Some(_), None) => true,
            (None, Some(_)) => false,
            (None, None) => break,
        };
        let next = match (span_next, spans.get(kept_spans), logs.get(kept_logs)) {
            (true, Some(span), _) => size(span, room)?.map(|size| size + 1),
            (false, _, Some(log)) => size(log, room)?.map(|size| size + ",null".len()),
            _ => None,
        };
        let Some(left) = next.and_then(|next| room.checked_sub(next)) else {
            break;
        };
        room = left;
        if span_next {
            kept_spans += 1;
        } else {
            kept_logs += 1;
        }
    }
    trace.spans = spans;
    trace.logs = logs;

    trace.spans.truncate(kept_spans);
    trace.logs.truncate(kept_logs);
    trace.dropped.spans = dropped.spans.saturating_add(all_spans - kept_spans);
    trace.dropped.logs = dropped.logs.saturating_add(all_logs - kept_logs);
    move_lines_to_kept_spans(trace, &parents);

    Ok(serde_json::to_vec(trace)?)
}

/// Move each line in a span that was left out to the nearest kept span around it. A span starts
/// after the span around it; a parent that doesn't is not followed, so no input loops.
fn move_lines_to_kept_spans(trace: &mut Trace, parents: &[Option<usize>]) {
    let spans = trace.spans.len();
    for log in &mut trace.logs {
        while let Some(span) = log.span.filter(|&span| span >= spans) {
            log.span = parents.get(span).copied().flatten().filter(|&parent| parent < span);
        }
    }
}

/// How many bytes `value` takes as JSON, if no more than `max`, without writing it anywhere. It
/// stops counting past `max`, so a large value costs about `max` bytes of work, plus its longest
/// string: `serde_json` reads a string whole before it writes any of it.
fn size(value: &impl serde::Serialize, max: usize) -> Result<Option<usize>, serde_json::Error> {
    struct Counted {
        bytes: usize,
        max: usize,
    }

    impl io::Write for Counted {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.bytes += buf.len();
            if self.bytes > self.max {
                return Err(io::ErrorKind::FileTooLarge.into());
            }
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    let mut counted = Counted { bytes: 0, max };
    match serde_json::to_writer(&mut counted, value) {
        Ok(()) => Ok(Some(counted.bytes)),
        Err(_) if counted.bytes > max => Ok(None),
        Err(error) => Err(error),
    }
}

/// Write `bytes` to `name` in `directory` under a temporary name first, then rename it, so that no
/// reader sees it half-written.
fn write_whole(directory: &Path, name: &str, bytes: &[u8]) -> Result<(), StoreError> {
    let temporary = directory.join(format!(".{name}.{}{TEMPORARY}", std::process::id()));
    let result = owner_only_file(&temporary)
        .and_then(|mut file| file.write_all(bytes))
        .and_then(|()| fs::rename(&temporary, directory.join(name)));
    if result.is_err() {
        let _ = fs::remove_file(&temporary);
    }

    Ok(result?)
}

/// Remove the traces beyond the capacity, those too old, and files left half-written.
fn prune(settings: &Settings) -> Result<(), StoreError> {
    let oldest = oldest_kept(settings.max_age);
    let files = files(&settings.directory)?;

    let mut ids: Vec<TraceId> = files
        .iter()
        .filter_map(|file| match file {
            File::Trace(id) | File::Summary(id) => Some(*id),
            File::Temporary(_) => None,
        })
        .collect();
    ids.sort_unstable_by(|a, b| b.cmp(a));
    ids.dedup();
    let kept: Vec<TraceId> = ids
        .into_iter()
        .filter(|id| id.millis() >= oldest)
        .take(settings.capacity)
        .collect();

    let mut gone: Vec<&File> = files
        .iter()
        .filter(|file| match file {
            File::Trace(id) | File::Summary(id) => kept.binary_search_by(|kept| id.cmp(kept)).is_err(),
            File::Temporary(name) => half_written(&settings.directory.join(name)),
        })
        .collect();
    remove_all(&settings.directory, &mut gone)
}

/// Remove `files`, each summary before its trace, so a reader never lists a trace that's gone.
/// One that can't be removed doesn't keep the others: the first error is returned at the end.
fn remove_all(directory: &Path, files: &mut [&File]) -> Result<(), StoreError> {
    files.sort_by_key(|file| (!matches!(file, File::Summary(_)), file.name()));
    let mut first_error = None;
    for file in files {
        if let Err(error) = remove(&directory.join(file.name())) {
            first_error.get_or_insert(error);
        }
    }

    first_error.map_or(Ok(()), Err)
}

/// Whether the temporary file at `path` was left half-written by a process that ended while
/// writing it. A file is judged by when it was last written to: work that ran long writes its
/// trace under a name as old as the work.
fn half_written(path: &Path) -> bool {
    fs::symlink_metadata(path)
        .and_then(|metadata| metadata.modified())
        .is_ok_and(|modified| modified.elapsed().is_ok_and(|age| age > HALF_WRITTEN))
}

/// A file of the store's, by its name.
#[derive(Debug)]
enum File {
    Trace(TraceId),
    Summary(TraceId),
    /// A file being written, or left half-written, by its name.
    Temporary(String),
}

impl File {
    fn parse(name: &str) -> Option<Self> {
        if let Some(rest) = name.strip_prefix('.')
            && let Some(rest) = rest.strip_suffix(TEMPORARY)
        {
            rest.get(..32)?.parse::<TraceId>().ok()?;
            return Some(Self::Temporary(name.to_owned()));
        }
        if let Some(id) = name.strip_suffix(SUMMARY) {
            return id.parse().ok().map(Self::Summary);
        }
        name.strip_suffix(TRACE)?.parse().ok().map(Self::Trace)
    }

    fn name(&self) -> String {
        match self {
            Self::Trace(id) => format!("{id}{TRACE}"),
            Self::Summary(id) => format!("{id}{SUMMARY}"),
            Self::Temporary(name) => name.clone(),
        }
    }
}

/// The store's files in `directory`; none when it doesn't exist yet. Other files are left alone.
fn files(directory: &Path) -> Result<Vec<File>, StoreError> {
    let entries = match fs::read_dir(directory) {
        Ok(entries) => entries,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => return Err(error.into()),
    };
    let mut files = Vec::new();
    for entry in entries {
        if let Some(file) = entry?.file_name().to_str().and_then(File::parse) {
            files.push(file);
        }
    }

    Ok(files)
}

/// Remove `path`, which another process may have removed already.
fn remove(path: &Path) -> Result<(), StoreError> {
    match fs::remove_file(path) {
        Err(error) if error.kind() != io::ErrorKind::NotFound => Err(error.into()),
        _ => Ok(()),
    }
}

/// The milliseconds since the Unix epoch at which a trace that started `max_age` ago started.
fn oldest_kept(max_age: Duration) -> u64 {
    let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
    u64::try_from(now.saturating_sub(max_age).as_millis()).unwrap_or(u64::MAX)
}

#[cfg(unix)]
fn create_directory(directory: &Path) -> io::Result<()> {
    use std::os::unix::fs::DirBuilderExt as _;

    if let Some(parent) = directory.parent().filter(|parent| !parent.as_os_str().is_empty()) {
        fs::create_dir_all(parent)?;
    }
    match fs::DirBuilder::new().mode(0o700).create(directory) {
        Err(error) if error.kind() != io::ErrorKind::AlreadyExists => Err(error),
        _ => Ok(()),
    }
}

#[cfg(not(unix))]
fn create_directory(directory: &Path) -> io::Result<()> {
    fs::create_dir_all(directory)
}

#[cfg(unix)]
fn owner_only_file(path: &Path) -> io::Result<fs::File> {
    use std::os::unix::fs::OpenOptionsExt as _;

    fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(path)
}

#[cfg(not(unix))]
fn owner_only_file(path: &Path) -> io::Result<fs::File> {
    fs::OpenOptions::new().write(true).create_new(true).open(path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::trace::{Dropped, Fields, Level, LogRecord, SpanKind, SpanRecord};

    #[derive(Clone, Default)]
    struct Captured(Arc<Mutex<Vec<u8>>>);

    impl io::Write for Captured {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn a_discarded_trace_is_told_once_for_each_reason() {
        let captured = Captured::default();
        let writer = captured.clone();
        let subscriber = tracing_subscriber::fmt()
            .with_ansi(false)
            .with_writer(move || writer.clone())
            .finish();
        let store = FileStore::new("storage/devtools");

        tracing::subscriber::with_default(subscriber, || {
            for reason in [Discard::Backlog, Discard::Stopped, Discard::Backlog, Discard::Stopped] {
                store.discard(reason);
            }
        });

        let output = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
        assert_eq!(output.matches("can't keep up").count(), 1, "{output}");
        assert_eq!(output.matches("has stopped").count(), 1, "{output}");
        assert_eq!(store.discarded(), 4);
    }

    /// An empty directory of the test's own, removed when the test ends, also when it fails.
    struct Directory(PathBuf);

    impl Drop for Directory {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    impl std::ops::Deref for Directory {
        type Target = Path;

        fn deref(&self) -> &Path {
            &self.0
        }
    }

    fn directory(name: &str) -> Directory {
        let directory = std::env::temp_dir().join(format!("laravel-rust-devtools-{}-{name}", std::process::id()));
        let _ = fs::remove_dir_all(&directory);
        Directory(directory)
    }

    /// The ID of a trace that started `ago`, the `n`th of its millisecond.
    fn id(ago: Duration, n: u32) -> TraceId {
        let started = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .checked_sub(ago)
            .unwrap();
        format!("{:012x}{:020x}", started.as_millis(), n).parse().unwrap()
    }

    fn trace(id: TraceId, name: &str) -> Trace {
        Trace {
            id,
            kind: TraceKind::Job,
            name: name.to_owned(),
            // Whole milliseconds, as the JSON keeps them.
            started_at: UNIX_EPOCH + Duration::from_millis(id.millis()),
            duration: Duration::from_millis(1),
            status: None,
            failed: false,
            fields: Fields::new(),
            spans: Vec::new(),
            logs: Vec::new(),
            dropped: Dropped::default(),
        }
    }

    fn names(store: &FileStore) -> Vec<String> {
        store.list().unwrap().into_iter().map(|summary| summary.name).collect()
    }

    fn file_names(directory: &Path) -> Vec<String> {
        let mut names: Vec<String> = fs::read_dir(directory)
            .unwrap()
            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
            .collect();
        names.sort();
        names
    }

    #[test]
    fn the_history_outlives_the_store() {
        let directory = directory("restart");
        let wanted = trace(id(Duration::ZERO, 1), "first");
        let store = FileStore::new(&*directory);
        store.put(wanted.clone());
        // A request doesn't wait for its trace to be written: dropping the store writes it.
        let mut second = trace(id(Duration::ZERO, 2), "second");
        second.kind = TraceKind::Request;
        store.put(second);
        drop(store);

        let store = FileStore::new(&*directory);
        assert_eq!(names(&store), ["second", "first"]);
        assert_eq!(store.get(wanted.id).unwrap(), Some(wanted));
        assert_eq!(store.get(id(Duration::ZERO, 3)).unwrap(), None);
    }

    #[test]
    fn work_other_than_a_request_waits_until_its_trace_is_written() {
        let directory = directory("wait");
        let store = FileStore::new(&*directory);
        let job = id(Duration::ZERO, 1);
        store.put(trace(job, "job"));

        // Read from the disk without the store, which would wait for its writer first.
        assert_eq!(
            file_names(&directory),
            [format!("{job}.json"), format!("{job}.summary.json")]
        );
        drop(store);
    }

    #[test]
    fn a_store_reads_what_it_was_just_handed() {
        let directory = directory("own-writes");
        let store = FileStore::new(&*directory);
        let mut request = trace(id(Duration::ZERO, 1), "GET /");
        request.kind = TraceKind::Request;
        store.put(request);

        assert_eq!(names(&store), ["GET /"]);
        drop(store);
    }

    #[test]
    fn a_full_store_removes_the_oldest() {
        let directory = directory("capacity");
        let store = FileStore::new(&*directory).with_capacity(2);
        let ids: Vec<TraceId> = (1..=3).map(|n| id(Duration::ZERO, n)).collect();
        for (n, id) in ids.iter().enumerate() {
            store.put(trace(*id, &format!("job {}", n + 1)));
        }

        assert_eq!(names(&store), ["job 3", "job 2"]);
        assert_eq!(store.get(ids[0]).unwrap(), None);
        assert!(store.get(ids[1]).unwrap().is_some());
        assert_eq!(store.summary(ids[0]).unwrap(), None);
        assert_eq!(
            store.summary(ids[1]).unwrap().map(|summary| summary.name),
            Some("job 2".to_owned())
        );
        assert_eq!(file_names(&directory).len(), 4, "{:?}", file_names(&directory));
        drop(store);
    }

    #[test]
    fn traces_older_than_the_max_age_are_removed() {
        let directory = directory("age");
        let old = id(Duration::from_hours(2), 1);
        let kept_longer = FileStore::new(&*directory);
        kept_longer.put(trace(old, "old"));
        drop(kept_longer);

        // A trace that started before the max age isn't listed, and is gone once the store writes.
        let store = FileStore::new(&*directory).with_max_age(Duration::from_hours(1));
        assert_eq!(names(&store), Vec::<String>::new());
        assert_eq!(store.get(old).unwrap(), None);
        assert_eq!(store.summary(old).unwrap(), None);
        assert_eq!(file_names(&directory).len(), 2, "{:?}", file_names(&directory));
        store.put(trace(id(Duration::ZERO, 2), "new"));

        assert_eq!(names(&store), ["new"]);
        assert_eq!(file_names(&directory).len(), 2, "{:?}", file_names(&directory));
        drop(store);
    }

    #[test]
    fn a_trace_too_large_loses_its_last_spans_and_lines() {
        let directory = directory("large");
        let store = FileStore::new(&*directory).with_max_trace_bytes(64 * 1024);
        let mut large = trace(id(Duration::ZERO, 1), "large");
        for n in 0..1_000_usize {
            let at = Duration::from_millis(n.try_into().unwrap());
            large.spans.push(SpanRecord {
                parent: n.checked_sub(1),
                kind: if n % 2 == 0 { SpanKind::Query } else { SpanKind::Other },
                name: format!("span {n}"),
                target: "app".to_owned(),
                start: at,
                duration: None,
                open: false,
                failed: false,
                fields: Fields::from([("text".to_owned(), "x".repeat(100).into())]),
            });
            large.logs.push(LogRecord {
                at: at + Duration::from_micros(1),
                level: Level::Info,
                target: "app".to_owned(),
                message: "y".repeat(100),
                span: Some(n),
                fields: Fields::new(),
            });
        }
        let id = large.id;
        store.put(large);

        let kept = store.get(id).unwrap().unwrap();
        let size = fs::metadata(directory.join(format!("{}.json", kept.id))).unwrap().len();
        assert!((60 * 1024..=64 * 1024).contains(&size), "{size}");
        // The beginning of the work: each span with the line written in it.
        assert!(
            kept.logs.len().abs_diff(kept.spans.len()) <= 1,
            "{} {}",
            kept.logs.len(),
            kept.spans.len()
        );
        assert!(
            !kept.spans.is_empty() && kept.spans.len() < 1_000,
            "{}",
            kept.spans.len()
        );
        assert_eq!(kept.dropped.spans, 1_000 - kept.spans.len());
        assert_eq!(kept.dropped.logs, 1_000 - kept.logs.len());
        assert!(
            kept.logs
                .iter()
                .all(|log| log.span.is_some_and(|span| span < kept.spans.len()))
        );
        // The list counts what the work did, also what its file left out.
        let summary = store.list().unwrap().remove(0);
        assert_eq!((summary.queries, summary.logs), (500, 1_000));
        drop(store);
    }

    #[test]
    fn spans_that_point_at_themselves_or_ahead_are_not_followed() {
        let directory = directory("cycle");
        let mut cyclic = trace(id(Duration::ZERO, 1), "cyclic");
        let span = |parent| SpanRecord {
            parent,
            kind: SpanKind::Other,
            name: "span".to_owned(),
            target: "app".to_owned(),
            start: Duration::from_millis(1),
            duration: None,
            open: false,
            failed: false,
            fields: Fields::from([("text".to_owned(), "x".repeat(1024).into())]),
        };
        cyclic.spans = vec![span(None), span(Some(1)), span(Some(3)), span(Some(2))];
        // The lines come first, so they are kept and their spans are not.
        let line = |span| LogRecord {
            at: Duration::ZERO,
            level: Level::Info,
            target: "app".to_owned(),
            message: "line".to_owned(),
            span: Some(span),
            fields: Fields::new(),
        };
        cyclic.logs = vec![line(1), line(2), line(3), line(9)];
        let id = cyclic.id;

        let (written, done) = mpsc::channel();
        let path = directory.to_path_buf();
        std::thread::spawn(move || {
            let store = FileStore::new(path).with_max_trace_bytes(2 * 1024);
            store.put(cyclic);
            let _ = written.send(store.get(id));
        });
        let kept = done.recv_timeout(Duration::from_secs(10)).unwrap().unwrap().unwrap();

        assert_eq!((kept.spans.len(), kept.logs.len()), (1, 4));
        assert!(
            kept.logs
                .iter()
                .all(|log| log.span.is_none_or(|span| span < kept.spans.len())),
            "{:?}",
            kept.logs
        );
    }

    #[test]
    fn a_file_being_written_is_left_alone_however_long_its_work_ran() {
        let directory = directory("temporary");
        fs::create_dir_all(&*directory).unwrap();
        // Another process writes the trace of a job that ran two minutes; another was left
        // half-written two minutes ago.
        let writing = directory.join(format!(".{}.json.1.tmp", id(Duration::from_secs(120), 1)));
        let left = directory.join(format!(".{}.json.2.tmp", id(Duration::from_secs(120), 2)));
        fs::write(&writing, "being written").unwrap();
        fs::write(&left, "left half-written").unwrap();
        let two_minutes_ago = SystemTime::now().checked_sub(Duration::from_secs(120)).unwrap();
        fs::File::options()
            .write(true)
            .open(&left)
            .unwrap()
            .set_modified(two_minutes_ago)
            .unwrap();

        let store = FileStore::new(&*directory);
        store.put(trace(id(Duration::ZERO, 3), "job"));
        assert!(writing.exists());
        assert!(!left.exists());
        store.clear().unwrap();
        assert_eq!(file_names(&directory), [writing.file_name().unwrap().to_str().unwrap()]);
        drop(store);
    }

    /// Another process writes a trace, then its summary: clearing in between must take neither,
    /// or the summary would list a trace that is gone.
    #[test]
    fn a_trace_still_waiting_for_its_summary_outlives_clearing() {
        let directory = directory("clear-between");
        fs::create_dir_all(&*directory).unwrap();
        let writing = trace(id(Duration::ZERO, 1), "being written");
        let json = serde_json::to_vec(&writing).unwrap();
        fs::write(directory.join(format!("{}{TRACE}", writing.id)), &json).unwrap();
        // One that a process ending between the two files left two minutes ago.
        let left = id(Duration::from_secs(120), 2);
        let left_path = directory.join(format!("{left}{TRACE}"));
        fs::write(&left_path, &json).unwrap();
        let two_minutes_ago = SystemTime::now().checked_sub(Duration::from_secs(120)).unwrap();
        fs::File::options()
            .write(true)
            .open(&left_path)
            .unwrap()
            .set_modified(two_minutes_ago)
            .unwrap();

        let store = FileStore::new(&*directory);
        store.clear().unwrap();
        assert_eq!(file_names(&directory), [format!("{}{TRACE}", writing.id)]);

        let summary = serde_json::to_vec(&writing.summary()).unwrap();
        fs::write(directory.join(format!("{}{SUMMARY}", writing.id)), summary).unwrap();
        assert_eq!(names(&store), ["being written"]);
        assert_eq!(store.get(writing.id).unwrap(), Some(writing));
        drop(store);
    }

    #[test]
    fn broken_and_foreign_files_are_left_out_and_left_alone() {
        let directory = directory("broken");
        let store = FileStore::new(&*directory);
        let broken = id(Duration::ZERO, 1);
        store.put(trace(broken, "broken"));
        store.put(trace(id(Duration::ZERO, 2), "fine"));
        fs::write(directory.join(format!("{broken}.json")), "{").unwrap();
        fs::write(directory.join(format!("{}.summary.json", id(Duration::ZERO, 3))), "{").unwrap();
        fs::write(directory.join("README.md"), "mine").unwrap();

        assert_eq!(names(&store), ["fine", "broken"]);
        assert!(matches!(store.get(broken), Err(StoreError::Json(_))));
        store.clear().unwrap();

        assert_eq!(names(&store), Vec::<String>::new());
        assert_eq!(file_names(&directory), ["README.md"]);
        drop(store);
    }

    #[test]
    fn what_can_t_be_removed_doesn_t_keep_the_rest() {
        let directory = directory("stuck");
        fs::create_dir_all(&*directory).unwrap();
        // Directories under the names of the oldest traces, which no file removal takes away. One
        // has a summary's name: summaries go first, whatever order the directory lists them in.
        let stuck: Vec<String> = (1..=3)
            .map(|n| {
                let suffix = if n == 2 { SUMMARY } else { TRACE };
                format!("{}{suffix}", id(Duration::from_secs(60), n))
            })
            .collect();
        for name in &stuck {
            fs::create_dir(directory.join(name)).unwrap();
        }

        let store = FileStore::new(&*directory).with_capacity(1);
        let ids: Vec<TraceId> = (4..=6).map(|n| id(Duration::ZERO, n)).collect();
        for id in &ids {
            store.put(trace(*id, "job"));
        }
        let mut kept = stuck.clone();
        kept.extend([format!("{}.json", ids[2]), format!("{}.summary.json", ids[2])]);
        assert_eq!(file_names(&directory), kept);

        assert!(store.clear().is_err());
        assert_eq!(file_names(&directory), stuck);
        drop(store);
    }

    /// A small xorshift generator: the same seed gives the same traces on every run.
    struct Random(u64);

    impl Random {
        fn below(&mut self, n: usize) -> usize {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            usize::try_from(self.0 % u64::try_from(n.max(1)).unwrap()).unwrap()
        }

        fn chance(&mut self, one_in: usize) -> bool {
            self.below(one_in) == 0
        }

        fn time(&mut self, usual: u64) -> Duration {
            if self.chance(6) {
                Duration::from_micros(u64::try_from(self.below(usize::MAX)).unwrap())
            } else {
                Duration::from_micros(usual)
            }
        }

        /// Fields with characters JSON escapes, so a byte takes up to six.
        fn fields(&mut self) -> Fields {
            (0..self.below(4))
                .map(|n| {
                    let len = if self.chance(10) {
                        self.below(20_000)
                    } else {
                        self.below(200)
                    };
                    let text: String = (0..len).map(|k| ['"', '\u{1}', 'ü', 'a', 'a'][(k + n) % 5]).collect();
                    (format!("f{n}"), text.into())
                })
                .collect()
        }

        /// A span index as a broken trace may hold one: none, itself, ahead, past the end.
        fn index(&mut self, spans: usize) -> Option<usize> {
            match self.below(8) {
                0 => None,
                1 => Some(usize::MAX),
                2 => Some(self.below(spans + 5)),
                _ => (spans > 0).then(|| self.below(spans)),
            }
        }

        fn trace(&mut self, id: TraceId) -> Trace {
            let mut random = trace(id, "random");
            if self.chance(4) {
                random.fields = self.fields();
            }
            let spans = self.below(300);
            for n in 0..spans {
                let parent = if self.chance(5) {
                    self.index(spans)
                } else {
                    n.checked_sub(1 + self.below(3))
                };
                let start = self.time(u64::try_from(n).unwrap() * 10);
                random.spans.push(SpanRecord {
                    parent,
                    kind: if self.chance(2) {
                        SpanKind::Query
                    } else {
                        SpanKind::Other
                    },
                    name: "span".to_owned(),
                    target: "app".to_owned(),
                    start,
                    duration: self.chance(9).then_some(Duration::MAX),
                    open: false,
                    failed: false,
                    fields: self.fields(),
                });
            }
            for n in 0..self.below(300) {
                let at = self.time(u64::try_from(n).unwrap() * 10 + 5);
                random.logs.push(LogRecord {
                    at,
                    level: Level::Info,
                    target: "app".to_owned(),
                    message: "line".to_owned(),
                    span: self.index(spans),
                    fields: self.fields(),
                });
            }
            if self.chance(5) {
                random.dropped = Dropped {
                    spans: usize::MAX - self.below(3),
                    logs: usize::MAX - self.below(3),
                };
            }
            random
        }
    }

    /// Random traces, broken ones too, against random limits: cutting ends, keeps the beginning
    /// of the work within the limit, and counts what it left out.
    #[test]
    fn any_trace_is_cut_to_its_limit() {
        let (finished, done) = mpsc::channel();
        std::thread::spawn(move || {
            let mut random = Random(0x9e37_79b9_7f4a_7c15);
            for round in 0..100 {
                let whole = random.trace(id(Duration::ZERO, round));
                let max = match random.below(4) {
                    0 => random.below(2_000),
                    1 => random.below(64 * 1024),
                    2 => random.below(2 * 1024 * 1024),
                    _ => 0,
                };
                let mut cut = whole.clone();
                let json = fit(&mut cut, max).unwrap();

                assert_eq!(json, serde_json::to_vec(&cut).unwrap(), "round {round}");
                if size(&whole, max).unwrap().is_some() {
                    assert_eq!(cut, whole, "round {round}");
                    continue;
                }
                assert!(
                    json.len() <= max || (cut.spans.is_empty() && cut.logs.is_empty()),
                    "round {round}: {} bytes of {max}",
                    json.len()
                );
                assert_eq!(cut.spans, whole.spans[..cut.spans.len()], "round {round}");
                assert!(
                    cut.logs
                        .iter()
                        .zip(&whole.logs)
                        .all(|(cut, whole)| (cut.at, &cut.fields) == (whole.at, &whole.fields)),
                    "round {round}"
                );
                assert!(
                    cut.logs
                        .iter()
                        .all(|log| log.span.is_none_or(|span| span < cut.spans.len())),
                    "round {round}"
                );
                let left_out = |before: usize, all: usize, kept: usize| before.saturating_add(all - kept);
                assert_eq!(
                    cut.dropped,
                    Dropped {
                        spans: left_out(whole.dropped.spans, whole.spans.len(), cut.spans.len()),
                        logs: left_out(whole.dropped.logs, whole.logs.len(), cut.logs.len()),
                    },
                    "round {round}"
                );
            }
            let _ = finished.send(());
        });
        done.recv_timeout(Duration::from_secs(60)).unwrap();
    }

    /// Every limit, byte by byte: for spans alone, whose count of what was left out grows to three
    /// digits, and for lines whose span is left out, turning `5` into `null`.
    #[test]
    fn the_limit_holds_to_the_byte() {
        let span = |n: u64| SpanRecord {
            parent: None,
            kind: SpanKind::Query,
            name: "span".to_owned(),
            target: "app".to_owned(),
            start: Duration::from_millis(1 + n),
            duration: None,
            open: false,
            failed: false,
            fields: Fields::new(),
        };
        let line = |n: u64| LogRecord {
            at: Duration::from_micros(n),
            level: Level::Info,
            target: "app".to_owned(),
            message: "line".to_owned(),
            span: Some(5),
            fields: Fields::new(),
        };
        let mut spans = trace(id(Duration::ZERO, 1), "spans");
        spans.spans = (0..300).map(span).collect();
        let mut lines = trace(id(Duration::ZERO, 2), "lines");
        lines.spans = (0..30).map(span).collect();
        lines.logs = (0..30).map(line).collect();

        for small in [spans, lines] {
            for max in 0..=4_000 {
                let mut cut = small.clone();
                let json = fit(&mut cut, max).unwrap();
                assert!(
                    json.len() <= max || (cut.spans.is_empty() && cut.logs.is_empty()),
                    "{}: {} bytes of {max}",
                    small.name,
                    json.len()
                );
            }
        }
    }

    #[test]
    fn a_missing_directory_is_an_empty_history() {
        let directory = directory("missing");
        let store = FileStore::new(&*directory);

        assert_eq!(names(&store), Vec::<String>::new());
        store.clear().unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn only_the_owner_can_read_the_history() {
        use std::os::unix::fs::PermissionsExt as _;

        let directory = directory("permissions");
        let store = FileStore::new(directory.join("devtools"));
        store.put(trace(id(Duration::ZERO, 1), "job"));
        drop(store);

        let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode(&directory.join("devtools")), 0o700);
        for name in file_names(&directory.join("devtools")) {
            assert_eq!(mode(&directory.join("devtools").join(&name)), 0o600, "{name}");
        }
    }

    #[test]
    fn a_store_keeps_100_traces_for_24_hours_up_to_2_mib_by_default() {
        let store = FileStore::new("storage/devtools");
        assert_eq!(store.settings.capacity, 100);
        assert_eq!(store.settings.max_age, Duration::from_hours(24));
        assert_eq!(store.settings.max_trace_bytes, 2 * 1024 * 1024);
    }

    #[test]
    fn a_store_keeps_at_least_one_trace() {
        assert_eq!(FileStore::new("storage/devtools").with_capacity(0).settings.capacity, 1);
    }

    #[test]
    fn a_new_store_has_discarded_nothing() {
        assert_eq!(FileStore::new("storage/devtools").discarded(), 0);
    }
}