goose 0.19.1

A load testing framework inspired by Locust.
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
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
//! Run folders: where the output flags given without a path, and the dashboard's
//! Save report, write a run's files.
//!
//! A run's folder is `--output-dir`, or `goose-runs/<YYYYMMDD-HHMMSS>` from the
//! local time the run started. Goose never writes a run into a folder that
//! already holds files when the run starts: it takes `-2`, `-3` and so on,
//! always counted on the original name. The folder is created as the run
//! starts and holds a `.goose-run` file while the run lasts, so no other run
//! takes the folder. It is removed at the end of the run if the run wrote
//! nothing.

use crate::config::{GooseConfiguration, RUN_FOLDER};
use crate::graph::GraphData;
use crate::logger::{move_goose_log, GooseLogFormat};
#[cfg(feature = "dashboard")]
use crate::metrics::dashboard_snapshot::SnapshotReport;
#[cfg(feature = "dashboard")]
use crate::metrics::MetricsCommand;
use crate::metrics::{load_baseline_file, write_folder_report, GooseMetrics, LoadedReport};
#[cfg(feature = "dashboard")]
use crate::{ControlOutcome, GooseAttackRunState};
use crate::{GooseAttack, GooseError};
use chrono::{DateTime, Local, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
#[cfg(feature = "dashboard")]
use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

/// The folder run folders go in when `--output-dir` is not given.
pub(crate) const DEFAULT_PARENT: &str = "goose-runs";

/// The HTML report in a run's folder.
pub(crate) const REPORT_HTML: &str = "report.html";
/// The JSON report in a run's folder, also read by `--baseline-file <folder>`.
pub(crate) const REPORT_JSON: &str = "report.json";
/// The Markdown report, which the dashboard renders from the JSON report.
#[cfg(feature = "dashboard")]
pub(crate) const REPORT_MD: &str = "report.md";

/// The file that reserves a run's folder for its run, so no other process
/// takes the folder.
pub(crate) const RESERVED: &str = ".goose-run";

/// The Goose log in a run's folder.
pub(crate) const GOOSE_LOG: &str = "goose.log";
/// The names of the other logs in a run's folder, before their format's
/// extension.
pub(crate) const LOG_NAMES: [&str; 5] =
    ["requests", "transactions", "scenarios", "errors", "debug"];

/// How a run ended, as its JSON report records it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum EndedBy {
    /// The test plan (or `--run-time`) ran to its end.
    Completed,
    /// A Stop from the dashboard or a Controller, or a Controller `shutdown`.
    Stopped,
    /// The killswitch: Ctrl-C, or code calling `trigger_killswitch`.
    Canceled,
    /// Every user exited on its own, for example after `--iterations`.
    UsersExited,
}

/// The record of a run that its JSON report holds beside its metrics. Every
/// field has a default, so a JSON report written before them still loads.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub(crate) struct RunRecord {
    /// The run's `--notes`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
    #[serde(default)]
    pub goose_version: String,
    /// The load test's executable name.
    #[serde(default)]
    pub test: String,
    /// When the run started, RFC 3339, UTC.
    #[serde(default)]
    pub started: Option<String>,
    /// When the run ended, RFC 3339, UTC; `None` while it is in progress.
    #[serde(default)]
    pub ended: Option<String>,
    /// How the run ended; `None` while it is in progress.
    #[serde(default)]
    pub ended_by: Option<EndedBy>,
    /// Why the run was canceled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canceled_reason: Option<String>,
    /// Written by Save report now while the run continued; the report at the
    /// end of the run replaces it.
    #[serde(default)]
    pub in_progress: bool,
    /// When the graphs do not cover the whole run: where they start, and why.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub graphs_start: Option<GraphsStart>,
}

/// Where a report's graphs start when they do not cover the whole run.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct GraphsStart {
    /// RFC 3339, UTC.
    pub time: String,
    pub reason: String,
}

impl GraphsStart {
    /// The sentence a report shows.
    pub(crate) fn describe(&self) -> String {
        let time = DateTime::parse_from_rfc3339(&self.time)
            .map(|time| {
                time.with_timezone(&Local)
                    .format("%Y-%m-%d %H:%M:%S")
                    .to_string()
            })
            .unwrap_or_else(|_| self.time.clone());
        format!(
            "The graphs start at {time}, not at the start of the run: {}",
            self.reason
        )
    }
}

impl RunRecord {
    /// The paragraphs the HTML and Markdown reports open with: the notes, and
    /// whether the report was written while the run continued.
    pub(crate) fn intro(&self) -> Vec<String> {
        let mut intro = Vec::new();
        if let Some(notes) = self.notes.as_deref().filter(|notes| !notes.is_empty()) {
            intro.push(notes.to_string());
        }
        if self.in_progress {
            intro.push(IN_PROGRESS.to_string());
        }
        intro
    }
}

/// What a report written by Save report now says.
pub(crate) const IN_PROGRESS: &str =
    "This report was saved while the run was in progress. The report written when the run ends replaces it.";

/// `name` without a trailing `.gz`, and whether it had one: a report or log
/// named `.gz` is written gzipped, in the format the rest of the name gives.
pub(crate) fn without_gz(name: &str) -> (&str, bool) {
    match name.strip_suffix(".gz") {
        Some(inner) => (inner, true),
        None => (name, false),
    }
}

/// The file name of a log in a run's folder: `name` with its format's
/// extension.
pub(crate) fn log_file_name(name: &str, format: Option<&GooseLogFormat>) -> String {
    let extension = match format {
        Some(GooseLogFormat::Csv) => "csv",
        Some(GooseLogFormat::Raw | GooseLogFormat::Pretty) => "log",
        Some(GooseLogFormat::Json) | None => "json",
    };
    format!("{name}.{extension}")
}

/// The folder run folders go in: the one `--output-dir` sits in, or
/// `goose-runs`.
#[cfg(any(test, feature = "dashboard"))]
pub(crate) fn parent_folder(configuration: &GooseConfiguration) -> PathBuf {
    match configuration.output_dir() {
        Some(dir) => match Path::new(dir).parent() {
            Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
            _ => PathBuf::from("."),
        },
        None => PathBuf::from(DEFAULT_PARENT),
    }
}

/// A run's folder, chosen when the run starts.
#[derive(Clone, Debug)]
pub(crate) struct RunFolder {
    /// The folder, as given or as Goose named it, never made absolute.
    pub path: PathBuf,
}

impl RunFolder {
    /// The folder of a run started at `started`: `--output-dir`, or
    /// `goose-runs/<YYYYMMDD-HHMMSS>`, or the first of `-2`, `-3` and so on
    /// that Goose can take. The folder is created and holds [`RESERVED`]
    /// when this returns.
    pub(crate) fn choose(
        configuration: &GooseConfiguration,
        started: DateTime<Local>,
    ) -> io::Result<RunFolder> {
        Ok(RunFolder {
            path: reserve(&Self::base(configuration, started))?,
        })
    }

    /// The name a run started at `started` asks for, before any suffix.
    fn base(configuration: &GooseConfiguration, started: DateTime<Local>) -> PathBuf {
        match configuration.output_dir() {
            Some(dir) => PathBuf::from(dir),
            None => Path::new(DEFAULT_PARENT).join(started.format("%Y%m%d-%H%M%S").to_string()),
        }
    }

    /// `name` in this folder.
    pub(crate) fn file(&self, name: &str) -> PathBuf {
        self.path.join(name)
    }

    /// The folder's name as the dashboard shows it.
    #[cfg(test)]
    pub(crate) fn name(&self) -> String {
        self.path
            .file_name()
            .map(|name| name.to_string_lossy().into_owned())
            .unwrap_or_default()
    }

    /// The error for a folder Goose can't write to.
    pub(crate) fn error(&self, e: io::Error) -> GooseError {
        folder_error(&self.path, e)
    }

    /// Fail before any load when the folder can't be written to: the nearest
    /// folder that exists must be a folder Goose can create a file in. The
    /// file is removed at once.
    pub(crate) fn check_writable(&self) -> Result<(), GooseError> {
        let mut dir = self.path.as_path();
        loop {
            match std::fs::metadata(dir) {
                Ok(metadata) if metadata.is_dir() => break,
                Ok(_) => {
                    return Err(self.error(io::Error::other(format!(
                        "{} is not a folder",
                        dir.display()
                    ))))
                }
                Err(e) if e.kind() == io::ErrorKind::NotFound => {
                    dir = match dir.parent() {
                        Some(parent) if !parent.as_os_str().is_empty() => parent,
                        _ => Path::new("."),
                    };
                }
                Err(e) => return Err(self.error(e)),
            }
        }
        let probe = dir.join(format!(".goose-write-check-{}", std::process::id()));
        // A probe left by an earlier process with the same id goes first.
        let _ = std::fs::remove_file(&probe);
        std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&probe)
            .and_then(|_| std::fs::remove_file(&probe))
            .map_err(|e| self.error(e))
    }
}

/// The error for `path` in a run's folder, or the folder, that Goose can't
/// write to.
pub(crate) fn folder_error(path: &Path, e: io::Error) -> GooseError {
    GooseError::InvalidOption {
        option: "--output-dir".to_string(),
        value: path.to_string_lossy().into_owned(),
        detail: format!("Can't write to {}: {e}", path.display()),
    }
}

/// Take `base`, or the first of `base-2`, `base-3` and so on, that is
/// missing or an empty folder: create it, then create [`RESERVED`] in it only
/// if no other process has, so two processes never take the same folder.
fn reserve(base: &Path) -> io::Result<PathBuf> {
    if let Some(parent) = base
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        std::fs::create_dir_all(parent)?;
    }
    let name = base
        .file_name()
        .map(|name| name.to_string_lossy().into_owned());
    let mut n = 1u32;
    // Another process can remove an empty folder between the steps below;
    // the same name is then tried again, a few times at most.
    let mut retries = 3;
    loop {
        let candidate = match (n, &name) {
            (1, _) | (_, None) => base.to_path_buf(),
            (n, Some(name)) => base.with_file_name(format!("{name}-{n}")),
        };
        let (created, free) = match std::fs::create_dir(&candidate) {
            Ok(()) => (true, Ok(true)),
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
                (false, is_empty_folder(&candidate))
            }
            Err(e) => return Err(e),
        };
        let taken = match free {
            Ok(true) => std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(candidate.join(RESERVED))
                .map(|_| true),
            other => other,
        };
        match taken {
            Ok(true) => return Ok(candidate),
            Ok(false) => {}
            // Another process took it first.
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
            Err(e) if e.kind() == io::ErrorKind::NotFound && retries > 0 => {
                retries -= 1;
                continue;
            }
            Err(e) => {
                if created {
                    let _ = std::fs::remove_dir(&candidate);
                }
                return Err(e);
            }
        }
        if name.is_none() {
            break;
        }
        n += 1;
    }
    Err(io::Error::new(
        io::ErrorKind::AlreadyExists,
        format!("{} already holds files", base.display()),
    ))
}

/// True when `path` is a folder with nothing in it, never following a
/// symlink.
fn is_empty_folder(path: &Path) -> io::Result<bool> {
    match std::fs::symlink_metadata(path) {
        Ok(metadata) if metadata.is_dir() => Ok(std::fs::read_dir(path)?.next().is_none()),
        Ok(_) => Ok(false),
        Err(e) => Err(e),
    }
}

/// What Goose writes for each run, kept on [`GooseAttack`].
#[derive(Debug, Default)]
pub(crate) struct Output {
    /// The run's folder, chosen when the run starts, when it may need one.
    pub folder: Option<RunFolder>,
    /// The folder this process reserves with [`RESERVED`]. It stays reserved
    /// until its run ends. While a bare `--goose-log` is open there, it stays
    /// reserved until the next run starts.
    reserved: Option<PathBuf>,
    /// Save report: write `report.json` and `report.html` into the folder.
    pub save_report: bool,
    /// Goose turned Save report off for this run, as the folder only the
    /// dashboard asked for can't be written to; it is on again when the run
    /// ends.
    save_report_held: bool,
    /// Include graph data in the JSON report.
    pub graph_data: bool,
    /// When the run started.
    pub started: Option<DateTime<Utc>>,
    /// The folder of the last report written into a run's folder at the end
    /// of a run.
    pub last_report: Option<String>,
    /// Why the last report Goose tried to write into the folder failed,
    /// shared with the task Save report now writes in.
    error: Arc<Mutex<Option<String>>>,
    /// The reports Goose has written into a run's folder in this process,
    /// shared with the task Save report now writes in.
    writes: Arc<AtomicU64>,
    /// Save report now wrote a report during this run, which the report at
    /// its end replaces.
    pub saved_now: bool,
    /// The report Save report now is writing.
    pub saving_now: Option<tokio::task::JoinHandle<()>>,
}

impl Output {
    /// Why the last report Goose tried to write into the folder failed.
    #[cfg(any(test, feature = "dashboard"))]
    pub(crate) fn error(&self) -> Option<String> {
        lock(&self.error).clone()
    }

    pub(crate) fn set_error(&self, error: Option<String>) {
        *lock(&self.error) = error;
    }

    /// Why the run in progress has no folder.
    #[cfg(feature = "dashboard")]
    fn no_folder_reason(&self) -> String {
        self.error()
            .unwrap_or_else(|| "this run has no folder".to_string())
    }

    /// As a run ends: turn Save report on again if Goose turned it off for
    /// the run, as its folder could not be written to.
    pub(crate) fn end_save_report_hold(&mut self) {
        if std::mem::take(&mut self.save_report_held) {
            self.save_report = true;
        }
    }

    /// Give up the run's folder: remove [`RESERVED`], then the folder if that
    /// leaves it empty. Only the first call does anything.
    pub(crate) fn release_folder(&mut self) {
        release(self.reserved.take());
    }
}

/// Remove [`RESERVED`] from `folder`, then the folder if that leaves it empty.
fn release(folder: Option<PathBuf>) {
    if let Some(folder) = folder {
        let _ = std::fs::remove_file(folder.join(RESERVED));
        let _ = std::fs::remove_dir(&folder);
    }
}

/// `mutex` locked, even after a panic while it was held.
pub(crate) fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

impl Drop for Output {
    /// A run that ends with an error still gives up its folder.
    fn drop(&mut self) {
        self.release_folder();
    }
}

/// The seconds of graph data Goose keeps for the dashboard while no report
/// at the end of the run needs more: twice its chart window.
pub(crate) const DASHBOARD_GRAPH_SECS: usize =
    crate::metrics::dashboard_snapshot::SERIES_WINDOW_SECS as usize * 2;

impl GooseAttack {
    /// Record how the run ended. The first cause recorded wins.
    pub(crate) fn set_ended_by(&mut self, ended_by: EndedBy, reason: Option<String>) {
        if self.run_in_progress && self.ended_by.is_none() {
            self.ended_by = Some((ended_by, reason));
        }
    }

    /// Whether the graph data is kept for the whole run: a report will be
    /// written at its end, to a `--report-file` path or by Save report.
    pub(crate) fn keeps_full_graph(&self) -> bool {
        self.configuration.keeps_full_graph(self.output.save_report)
    }

    /// Whether the per second histograms also fold into whole run columns,
    /// for the report's response time heatmap.
    pub(crate) fn records_latency_columns(&self) -> bool {
        self.keeps_full_graph() && self.configuration.records_latency_series()
    }

    /// When a run starts: choose its folder when it may need one, failing
    /// before any load when it can't be written to. A folder only the
    /// dashboard asks for that can't be written to is skipped with a warning
    /// instead, and Save report is off for the run.
    pub(crate) fn start_run_folder(&mut self) -> Result<(), GooseError> {
        // The last run's folder is given up only once a bare --goose-log has
        // moved out of it, so no other process deletes the open log.
        let previous = self.output.reserved.take();
        let started = self.choose_run_folder();
        release(previous);
        started
    }

    /// Whether a bare `--goose-log` is open in the run's folder, and stays
    /// open there after the run ends until the next run starts.
    pub(crate) fn goose_log_in_folder(&self) -> bool {
        self.configuration.goose_log() == Some(RUN_FOLDER) && crate::logger::goose_log_installed()
    }

    /// [`Self::start_run_folder`], before the last run's folder is given up.
    fn choose_run_folder(&mut self) -> Result<(), GooseError> {
        self.output.folder = None;
        self.output.last_report = None;
        self.output.set_error(None);
        self.output.saved_now = false;
        self.output.started = None;
        self.output.end_save_report_hold();
        if !self.configuration.uses_run_folder() {
            return Ok(());
        }
        let started = Local::now();
        let folder = RunFolder::choose(&self.configuration, started)
            .map_err(|e| folder_error(&RunFolder::base(&self.configuration, started), e))
            .and_then(|folder| {
                self.output.reserved = Some(folder.path.clone());
                folder.check_writable().map(|()| folder)
            });
        let folder = match folder {
            Ok(folder) => folder,
            Err(e) if self.configuration.folder_only_for_dashboard() => {
                let reason = reason(&e);
                warn!("{reason}. This run's report is not saved.");
                self.output.release_folder();
                self.output.set_error(Some(reason));
                if self.output.save_report {
                    self.output.save_report = false;
                    self.output.save_report_held = true;
                }
                return Ok(());
            }
            Err(e) => return Err(e),
        };
        // A bare --goose-log moves to each run's folder as the run starts.
        if self.configuration.goose_log() == Some(RUN_FOLDER) {
            let name = match self.configuration.compress {
                Some(_) => format!("{GOOSE_LOG}.gz"),
                None => GOOSE_LOG.to_string(),
            };
            // Move the log first, so the line naming this run's folder lands
            // in that folder's log. A failure here ends the session, so the
            // last run's folder, given up next, holds no open log after it.
            move_goose_log(&folder.file(&name)).map_err(|e| folder.error(e))?;
        }
        info!("writing this run's files to {}", folder.path.display());
        self.output.folder = Some(folder);
        Ok(())
    }

    /// The record of a report drawn from `graph_data`, whose first second is
    /// where its graphs start.
    pub(crate) fn report_record_for(&self, in_progress: bool, graph_data: &GraphData) -> RunRecord {
        self.report_record(in_progress, graph_data.first_second())
    }

    /// The record of the run in its reports: written while it continues when
    /// `in_progress`, otherwise at its end. `graphs_from` is the first second
    /// of the run the graph data holds.
    pub(crate) fn report_record(&self, in_progress: bool, graphs_from: usize) -> RunRecord {
        let (ended_by, canceled_reason) = match (in_progress, &self.ended_by) {
            (true, _) => (None, None),
            (false, Some((ended_by, reason))) => (Some(*ended_by), reason.clone()),
            (false, None) => (Some(EndedBy::Completed), None),
        };
        RunRecord {
            notes: self.configuration.notes().map(str::to_string),
            goose_version: env!("CARGO_PKG_VERSION").to_string(),
            test: test_name(),
            started: self.output.started.map(rfc3339),
            ended: (!in_progress).then(|| rfc3339(Utc::now())),
            ended_by,
            canceled_reason,
            in_progress,
            graphs_start: self.graphs_start(graphs_from),
        }
    }

    /// Where the graphs start when they do not cover the whole run, as the
    /// dashboard keeps only its window while no report needs more.
    fn graphs_start(&self, graphs_from: usize) -> Option<GraphsStart> {
        let started = self.output.started.filter(|_| graphs_from > 0)?;
        let reason = if self.keeps_full_graph() {
            format!(
                "Save report was off for part of the run, and Goose then keeps only the dashboard's last {} minutes of graphs.",
                DASHBOARD_GRAPH_SECS / 60
            )
        } else {
            format!(
                "Save report is off, so Goose keeps only the dashboard's last {} minutes of graphs.",
                DASHBOARD_GRAPH_SECS / 60
            )
        };
        Some(GraphsStart {
            time: rfc3339(started + chrono::Duration::seconds(graphs_from as i64)),
            reason,
        })
    }

    /// When a run has fully stopped: write the `--report-file` reports and, with
    /// Save report on or after a Save report now, the folder's, attempting
    /// both even if one fails. Returns the first error. When the session
    /// `returns_to_idle`, a folder's report that fails is only logged and
    /// shown on the dashboard, and the session goes on. When the session shuts
    /// down after the run instead, as after an autostarted run that ends on its
    /// own, a Controller `shutdown` or Ctrl-C, it returns that error.
    pub(crate) async fn write_end_of_run(
        &mut self,
        returns_to_idle: bool,
    ) -> Result<(), GooseError> {
        // A report Save report now is still writing finishes first, so this
        // one replaces it.
        if let Some(saving) = self.output.saving_now.take() {
            let _ = saving.await;
        }
        // Load the baseline once for all report writers. A baseline that no
        // longer loads fails the --report-file reports, as it does at
        // startup, and the folder's report is written without it.
        let (baseline, baseline_error) = match &self.configuration.baseline_file {
            Some(file) => match load_baseline_file(file) {
                Ok(baseline) => (Some(baseline), None),
                Err(e) => (None, Some(e)),
            },
            None => (None, None),
        };
        let record = self.report_record_for(false, &self.graph_data);
        let save = self.output.save_report || self.output.saved_now;
        let folder = match (save, self.output.folder.as_ref()) {
            (true, Some(folder)) => Some(folder.path.clone()),
            _ => None,
        };
        // The HTML report is generated once for --report-file and the folder.
        let mut html = None;
        let source = self.report_source(&record);
        let report_files = match baseline_error {
            Some(e) => Err(e),
            None => {
                self.write_report_files(&source, baseline.as_ref(), &mut html)
                    .await
            }
        };
        let written = match folder {
            None => return report_files,
            Some(folder) => write_folder_report(
                &folder,
                &source,
                baseline.as_ref(),
                &mut html,
                self.configuration.compress,
            )
            .map(|files| (folder, files)),
        };
        match written {
            Ok((folder, files)) => {
                for file in files {
                    info!("report file written to: {}", file.display());
                }
                self.output.last_report = Some(folder.to_string_lossy().into_owned());
                self.output.set_error(None);
                self.output.writes.fetch_add(1, Ordering::Relaxed);
                report_files
            }
            Err(e) => {
                let reason = reason(&e);
                error!("couldn't save the report: {reason}");
                self.output.set_error(Some(reason));
                if returns_to_idle {
                    report_files
                } else {
                    report_files.and(Err(e))
                }
            }
        }
    }
}

impl GooseAttack {
    /// `--render-report`: write the reports `--report-file` paths name from the
    /// JSON report at `path`, without running a load test.
    pub(crate) async fn render_report(&self, path: &str) -> Result<GooseMetrics, GooseError> {
        let loaded =
            LoadedReport::read(Path::new(path)).map_err(|detail| GooseError::InvalidOption {
                option: "--render-report".to_string(),
                value: path.to_string(),
                detail,
            })?;
        let baseline = match &self.configuration.baseline_file {
            Some(file) => Some(load_baseline_file(file)?),
            None => None,
        };
        let empty = GraphData::new();
        let source = loaded.source(&self.configuration, &empty);
        self.create_reports().await?;
        self.write_report_files(&source, baseline.as_ref(), &mut None)
            .await?;
        Ok(loaded.data.raw_metrics.into_owned())
    }

    /// The report this run writes, as the dashboard shows it.
    #[cfg(feature = "dashboard")]
    pub(crate) fn report_snapshot(&self) -> SnapshotReport {
        SnapshotReport {
            save: self.output.save_report,
            graph_data: self.output.graph_data,
            folder: self
                .output
                .folder
                .as_ref()
                .map(|folder| folder.path.to_string_lossy().into_owned()),
            paths: self.configuration.report_paths(),
            notes: self.configuration.notes().map(str::to_string),
            last_report: self.output.last_report.clone(),
            last_report_name: self
                .output
                .last_report
                .as_deref()
                .and_then(|folder| Path::new(folder).file_name())
                .map(|name| name.to_string_lossy().into_owned())
                .filter(|name| is_report_name(name)),
            error: self.output.error(),
            writes: self.output.writes.load(Ordering::Relaxed),
        }
    }
}

/// One report the runs panel lists: a folder's name and what its
/// `report.json` says about its run.
#[cfg(feature = "dashboard")]
#[derive(Clone, Debug, Serialize)]
pub(crate) struct ListedReport {
    /// The folder's name, which the report routes take.
    pub name: String,
    #[serde(flatten)]
    pub record: RunRecord,
    /// Still marked in progress, and the folder of the run in progress now.
    pub running: bool,
    pub duration_secs: u64,
    pub max_users: u64,
    pub requests: u64,
    pub failed_requests: u64,
    /// When the run started, else when the report was written: what the list
    /// is sorted by. Seconds since the epoch.
    #[serde(skip)]
    sort_key: i64,
}

/// What a listing remembers of each `report.json`, by path, so a file is
/// parsed again only when its size or modification time changes.
#[cfg(feature = "dashboard")]
pub(crate) type ListingCache = HashMap<PathBuf, (u64, std::time::SystemTime, ListedReport)>;

/// True for a folder name the report routes take: a letter or digit, then
/// letters, digits, `.`, `_` and `-`. Never `..`, never a path.
#[cfg(feature = "dashboard")]
pub(crate) fn is_report_name(name: &str) -> bool {
    let mut chars = name.chars();
    chars.next().is_some_and(|c| c.is_ascii_alphanumeric())
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}

/// The real folder `name` in `parent` and the regular `report.json`, else
/// `report.json.gz`, in it, never following a symlink.
#[cfg(feature = "dashboard")]
pub(crate) fn report_folder(parent: &Path, name: &str) -> Option<(PathBuf, PathBuf)> {
    if !is_report_name(name) {
        return None;
    }
    let folder = parent.join(name);
    if !std::fs::symlink_metadata(&folder).is_ok_and(|m| m.file_type().is_dir()) {
        return None;
    }
    let json = regular_file(&folder, REPORT_JSON)?;
    Some((folder, json))
}

/// The regular file `name`, else `name.gz`, in `folder`, never following a
/// symlink.
#[cfg(feature = "dashboard")]
pub(crate) fn regular_file(folder: &Path, name: &str) -> Option<PathBuf> {
    [name.to_string(), format!("{name}.gz")]
        .iter()
        .map(|name| folder.join(name))
        .find(|path| std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file()))
}

/// The reports in the folders of `parent`, one level down, newest first.
/// `running` is the folder of the run in progress, if any. A folder that
/// does not exist lists nothing; a report that can't be read is left out.
#[cfg(feature = "dashboard")]
pub(crate) fn list_reports(
    parent: &Path,
    running: Option<&Path>,
    cache: &mut ListingCache,
) -> io::Result<Vec<ListedReport>> {
    let entries = match std::fs::read_dir(parent) {
        Ok(entries) => entries,
        Err(e) if e.kind() == io::ErrorKind::NotFound => {
            cache.clear();
            return Ok(Vec::new());
        }
        Err(e) => return Err(e),
    };
    let mut listed = Vec::new();
    let mut seen = std::collections::HashSet::new();
    for entry in entries.filter_map(Result::ok) {
        let Some(name) = entry.file_name().to_str().map(str::to_string) else {
            continue;
        };
        let Some((folder, json)) = report_folder(parent, &name) else {
            continue;
        };
        let Ok(metadata) = std::fs::metadata(&json) else {
            continue;
        };
        let modified = metadata.modified().unwrap_or(std::time::UNIX_EPOCH);
        seen.insert(json.clone());
        let cached = cache
            .get(&json)
            .filter(|(len, time, _)| *len == metadata.len() && *time == modified)
            .map(|(_, _, report)| report.clone());
        let mut report = match cached {
            Some(report) => report,
            None => match read_listed(&json, &name, modified) {
                Some(report) => {
                    cache.insert(json.clone(), (metadata.len(), modified, report.clone()));
                    report
                }
                None => continue,
            },
        };
        report.running = report.record.in_progress && running == Some(folder.as_path());
        listed.push(report);
    }
    cache.retain(|path, _| seen.contains(path));
    listed.sort_by(|a, b| {
        b.sort_key
            .cmp(&a.sort_key)
            .then_with(|| b.name.cmp(&a.name))
    });
    Ok(listed)
}

/// The record of the run in the JSON report at `json`, plain or gzipped.
#[cfg(feature = "dashboard")]
pub(crate) fn read_record(json: &Path) -> Option<RunRecord> {
    let text = crate::metrics::read_report_text(json).ok()?;
    serde_json::from_str(&text).ok()
}

/// Whether the runs panel would list the report at `json`: Delete touches
/// nothing in a folder the panel does not show.
#[cfg(feature = "dashboard")]
pub(crate) fn is_listed(json: &Path) -> bool {
    read_listed(json, "", std::time::UNIX_EPOCH).is_some()
}

/// What the runs panel shows of the report at `json`, in the folder `name`.
#[cfg(feature = "dashboard")]
fn read_listed(json: &Path, name: &str, modified: std::time::SystemTime) -> Option<ListedReport> {
    #[derive(Deserialize)]
    struct Listed {
        raw_metrics: Metrics,
    }
    #[derive(Deserialize)]
    struct Metrics {
        #[serde(default)]
        duration: u64,
        #[serde(default)]
        maximum_users: u64,
        #[serde(default)]
        requests: HashMap<String, Requests>,
    }
    #[derive(Deserialize)]
    struct Requests {
        #[serde(default)]
        success_count: u64,
        #[serde(default)]
        fail_count: u64,
    }
    let text = crate::metrics::read_report_text(json).ok()?;
    let record: RunRecord = serde_json::from_str(&text).ok()?;
    let metrics = serde_json::from_str::<Listed>(&text).ok()?.raw_metrics;
    let written = DateTime::<Utc>::from(modified).timestamp();
    let sort_key = record
        .started
        .as_deref()
        .and_then(|started| DateTime::parse_from_rfc3339(started).ok())
        .map_or(written, |started| started.timestamp());
    Some(ListedReport {
        name: name.to_string(),
        record,
        running: false,
        duration_secs: metrics.duration,
        max_users: metrics.maximum_users,
        requests: metrics
            .requests
            .values()
            .map(|r| r.success_count + r.fail_count)
            .sum(),
        failed_requests: metrics.requests.values().map(|r| r.fail_count).sum(),
        sort_key,
    })
}

/// The files `DELETE /api/v1/reports/{name}` removes from a run's folder:
/// its reports and the logs Goose names there, plain and gzipped.
#[cfg(feature = "dashboard")]
pub(crate) fn deletable_files() -> Vec<String> {
    let mut names = vec![
        REPORT_JSON.to_string(),
        REPORT_HTML.to_string(),
        REPORT_MD.to_string(),
        GOOSE_LOG.to_string(),
    ];
    for name in LOG_NAMES {
        for extension in ["json", "csv", "log"] {
            names.push(format!("{name}.{extension}"));
        }
    }
    let gzipped: Vec<String> = names.iter().map(|name| format!("{name}.gz")).collect();
    names.extend(gzipped);
    // The reports' temporary files, left by a process that ended while
    // writing one.
    let temporary: Vec<String> = [REPORT_JSON, REPORT_HTML]
        .iter()
        .flat_map(|name| [format!(".{name}.tmp"), format!(".{name}.gz.tmp")])
        .collect();
    names.extend(temporary);
    names
}

/// Whether a Goose process reserves `folder` for its run, so Delete leaves it
/// alone.
/// A process that ended without giving the folder up leaves [`RESERVED`]
/// behind; removing that file by hand frees the folder.
#[cfg(feature = "dashboard")]
pub(crate) fn is_reserved(folder: &Path) -> bool {
    std::fs::symlink_metadata(folder.join(RESERVED)).is_ok()
}

#[cfg(feature = "dashboard")]
impl GooseAttack {
    /// The dashboard's Save report and Include graph data switches, which can
    /// change at any time. Turning Save report on during a run keeps the
    /// graphs from then on, and the dashboard's window before it.
    pub(crate) fn control_report(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
        save: Option<bool>,
        graph_data: Option<bool>,
    ) -> ControlOutcome {
        if save == Some(true) && self.configuration.no_metrics {
            return self.control_outcome(
                goose_attack_run_state,
                false,
                Some("invalid_report"),
                "--no-metrics keeps no report to save",
                None,
            );
        }
        if save == Some(true) && self.run_in_progress && self.output.folder.is_none() {
            let message = self.output.no_folder_reason();
            return self.control_outcome(
                goose_attack_run_state,
                false,
                Some("invalid_report"),
                message,
                None,
            );
        }
        if let Some(graph_data) = graph_data {
            self.output.graph_data = graph_data;
        }
        if save.is_some() {
            self.output.save_report_held = false;
        }
        if let Some(save) = save.filter(|save| *save != self.output.save_report) {
            let keeps_before = self.keeps_full_graph();
            self.output.save_report = save;
            let keep = self.keeps_full_graph();
            if self.run_in_progress && keep != keeps_before {
                let now = self.series_elapsed_secs();
                let _ = goose_attack_run_state
                    .metrics_cmd_tx
                    .send(MetricsCommand::KeepGraph { keep, now });
            }
        }
        let message = format!(
            "save report {}, include graph data {}",
            if self.output.save_report { "on" } else { "off" },
            if self.output.graph_data { "on" } else { "off" }
        );
        self.control_outcome(goose_attack_run_state, true, None, message, None)
    }

    /// Save report now: write the run's report into its folder as it stands,
    /// marked in progress, while the run continues. The report at the end of
    /// the run replaces it.
    pub(crate) async fn control_save_report_now(
        &mut self,
        goose_attack_run_state: &mut GooseAttackRunState,
    ) -> Result<ControlOutcome, GooseError> {
        let refuse = |attack: &Self, state: &GooseAttackRunState, error, message: &str| {
            Ok(attack.control_outcome(state, false, Some(error), message.to_string(), None))
        };
        if self.configuration.no_metrics {
            return refuse(
                self,
                goose_attack_run_state,
                "invalid_report",
                "--no-metrics keeps no report to save",
            );
        }
        if !self.run_in_progress {
            return refuse(
                self,
                goose_attack_run_state,
                "invalid_phase",
                "Save report now needs a run in progress",
            );
        }
        let Some(folder) = self.output.folder.clone() else {
            let message = self.output.no_folder_reason();
            return refuse(self, goose_attack_run_state, "report_failed", &message);
        };
        if self
            .output
            .saving_now
            .as_ref()
            .is_some_and(|saving| !saving.is_finished())
        {
            return refuse(
                self,
                goose_attack_run_state,
                "report_busy",
                "a report is being saved; try again when it is written",
            );
        }
        if let Err(e) = folder.check_writable() {
            let reason = reason(&e);
            self.output.set_error(Some(reason.clone()));
            return refuse(self, goose_attack_run_state, "report_failed", &reason);
        }
        self.update_duration();
        let (respond, report_data) = tokio::sync::oneshot::channel();
        let sent = goose_attack_run_state
            .metrics_cmd_tx
            .send(MetricsCommand::GetReportData {
                duration: self.metrics.duration,
                total_users: self.metrics.total_users,
                maximum_users: self.metrics.maximum_users,
                history: self.metrics.history.clone(),
                respond,
            });
        let (Ok(()), Ok((metrics, graph_data))) = (sent, report_data.await) else {
            return refuse(
                self,
                goose_attack_run_state,
                "report_failed",
                "the metrics are not available",
            );
        };
        let folder_path = folder.path.clone();
        let record = self.report_record_for(true, &graph_data);
        let configuration = self.configuration.clone();
        let graph_data_in_json = self.output.graph_data;
        let compress = self.configuration.compress;
        let error = Arc::clone(&self.output.error);
        let writes = Arc::clone(&self.output.writes);
        self.output.saved_now = true;
        self.output.saving_now = Some(tokio::task::spawn_blocking(move || {
            let baseline = match configuration
                .baseline_file
                .as_ref()
                .map(|file| load_baseline_file(file).map_err(|e| (file.clone(), reason(&e))))
            {
                Some(Ok(baseline)) => Some(baseline),
                Some(Err((file, reason))) => {
                    warn!("the report saved now has no baseline, as {file} doesn't load: {reason}");
                    None
                }
                None => None,
            };
            let source = crate::metrics::ReportSource {
                configuration: &configuration,
                metrics: &metrics,
                graph_data: &graph_data,
                graphs: true,
                heatmap: None,
                loaded: None,
                record: &record,
                graph_data_in_json,
            };
            match write_folder_report(
                &folder_path,
                &source,
                baseline.as_ref(),
                &mut None,
                compress,
            ) {
                Ok(files) => {
                    for file in files {
                        info!("in progress report written to: {}", file.display());
                    }
                    *lock(&error) = None;
                    writes.fetch_add(1, Ordering::Relaxed);
                }
                Err(e) => {
                    let reason = reason(&e);
                    error!("couldn't save the report now: {reason}");
                    *lock(&error) = Some(reason);
                }
            }
        }));
        let message = format!("saving the report to {}", folder.path.display());
        Ok(self.control_outcome(goose_attack_run_state, true, None, message, None))
    }
}

/// Why `e` happened, as the dashboard shows it: an invalid option's detail,
/// which its `Display` leaves out.
pub(crate) fn reason(e: &GooseError) -> String {
    match e {
        GooseError::InvalidOption { detail, .. } => detail.clone(),
        other => other.to_string(),
    }
}

/// RFC 3339 in UTC, to the second, as the JSON report records times.
pub(crate) fn rfc3339(time: DateTime<Utc>) -> String {
    time.to_rfc3339_opts(SecondsFormat::Secs, true)
}

/// The load test's executable name, without extension.
pub(crate) fn test_name() -> String {
    std::env::current_exe()
        .ok()
        .and_then(|exe| exe.file_stem().map(|s| s.to_string_lossy().into_owned()))
        .unwrap_or_default()
}

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

    fn temp_dir(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "goose-folder-test-{name}-{}-{}",
            std::process::id(),
            Utc::now().timestamp_nanos_opt().unwrap_or_default()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    fn configuration(output_dir: Option<&Path>) -> GooseConfiguration {
        GooseConfiguration {
            output_dir: output_dir.map(|dir| dir.to_string_lossy().into_owned()),
            ..Default::default()
        }
    }

    #[test]
    fn default_folder_is_named_for_the_start_time() {
        let started = Local.with_ymd_and_hms(2026, 10, 9, 14, 12, 3).unwrap();
        let base = RunFolder::base(&configuration(None), started);
        assert_eq!(base, Path::new("goose-runs/20261009-141203"));
    }

    /// The first of DIR, DIR-2, DIR-3 that is missing or empty, always
    /// counted on DIR.
    #[test]
    fn folder_holding_files_is_never_reused() {
        let parent = temp_dir("suffix");
        let dir = parent.join("nightly");
        let started = Local::now();
        let choose = || RunFolder::choose(&configuration(Some(&dir)), started).unwrap();
        let mut chosen = Vec::new();
        for _ in 0..4 {
            let folder = choose();
            std::fs::write(folder.file("goose.log"), "x").unwrap();
            std::fs::remove_file(folder.file(RESERVED)).unwrap();
            chosen.push(folder.name());
        }
        assert_eq!(chosen, ["nightly", "nightly-2", "nightly-3", "nightly-4"]);

        // An empty folder is used; a file in the way is skipped.
        std::fs::remove_file(parent.join("nightly-3").join("goose.log")).unwrap();
        assert_eq!(choose().name(), "nightly-3");
        std::fs::write(parent.join("nightly-5"), "a file").unwrap();
        std::fs::write(parent.join("nightly-3").join("goose.log"), "x").unwrap();
        assert_eq!(choose().name(), "nightly-6");
        std::fs::remove_dir_all(&parent).ok();
    }

    /// Two runs that choose before either writes never share a folder, and
    /// an empty folder that is already there goes to the first of them.
    #[test]
    fn a_chosen_folder_is_reserved_at_once() {
        let parent = temp_dir("reserve");
        let dir = parent.join("nightly");
        let started = Local::now();
        let first = RunFolder::choose(&configuration(Some(&dir)), started).unwrap();
        let second = RunFolder::choose(&configuration(Some(&dir)), started).unwrap();
        assert_eq!(
            (first.name(), second.name()),
            ("nightly".into(), "nightly-2".into())
        );
        assert!(first.path.is_dir() && second.path.is_dir());

        let empty = parent.join("empty");
        std::fs::create_dir(&empty).unwrap();
        let first = RunFolder::choose(&configuration(Some(&empty)), started).unwrap();
        let second = RunFolder::choose(&configuration(Some(&empty)), started).unwrap();
        assert_eq!(
            (first.name(), second.name()),
            ("empty".into(), "empty-2".into())
        );
        std::fs::remove_dir_all(&parent).ok();
    }

    #[test]
    fn writable_check_finds_the_nearest_folder() {
        let parent = temp_dir("writable");
        let folder = RunFolder {
            path: parent.join("a").join("b"),
        };
        folder.check_writable().unwrap();
        // Nothing is left behind, and nothing is created.
        assert_eq!(std::fs::read_dir(&parent).unwrap().count(), 0);

        std::fs::write(parent.join("a"), "a file").unwrap();
        let error = folder.check_writable().unwrap_err();
        match error {
            GooseError::InvalidOption { option, value, .. } => {
                assert_eq!(option, "--output-dir");
                assert_eq!(value, folder.path.to_string_lossy());
            }
            other => panic!("{:?}", other),
        }
        std::fs::remove_dir_all(&parent).ok();
    }

    /// Rule 5: when the graphs start after the run did, the record says when
    /// and why; when they cover the run, it says nothing.
    #[test]
    fn graphs_start_when_the_graphs_do_not_cover_the_run() {
        let mut attack = GooseAttack::initialize_with_config(configuration(None)).unwrap();
        attack.output.started = Some(Utc.with_ymd_and_hms(2026, 10, 22, 10, 0, 0).unwrap());
        assert_eq!(attack.report_record(false, 0).graphs_start, None);
        attack.output.save_report = true;
        let start = attack.report_record(false, 300).graphs_start.unwrap();
        assert_eq!(start.time, "2026-10-22T10:05:00Z");
        assert!(start
            .reason
            .contains("Save report was off for part of the run"));
        attack.output.save_report = false;
        let start = attack.report_record(false, 300).graphs_start.unwrap();
        assert!(start.reason.starts_with("Save report is off"));
    }

    /// Rule 5: the report written at the end of a run whose graph data no
    /// longer reaches back to its start records where its graphs start.
    #[tokio::test]
    async fn the_end_of_run_report_says_where_its_graphs_start() {
        use crate::test_plan::{TestPlanHistory, TestPlanStepAction};
        let parent = temp_dir("graphs-start");
        let mut attack =
            GooseAttack::initialize_with_config(configuration(Some(&parent.join("run")))).unwrap();
        let started = Utc.with_ymd_and_hms(2026, 10, 22, 10, 0, 0).unwrap();
        attack.run_in_progress = true;
        attack.output.started = Some(started);
        attack.output.save_report = true;
        attack.output.folder =
            Some(RunFolder::choose(&attack.configuration, Local::now()).unwrap());
        for step in [TestPlanStepAction::Increasing, TestPlanStepAction::Finished] {
            attack.metrics.history.push(TestPlanHistory::step(step, 0));
        }
        for second in 0..=900 {
            attack.graph_data.record_users_per_second(1, second);
        }
        attack.graph_data.prune_to_window(600);
        let origin = attack.graph_data.first_second();
        assert!(origin > 0);
        attack.write_end_of_run(false).await.unwrap();
        let report: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(parent.join("run").join(REPORT_JSON)).unwrap(),
        )
        .unwrap();
        assert_eq!(
            report["graphs_start"]["time"],
            rfc3339(started + chrono::Duration::seconds(origin as i64))
        );
        std::fs::remove_dir_all(&parent).ok();
    }

    /// Rule 11: a report written while the run continues is marked in
    /// progress, has no end, and says so at its top.
    #[test]
    fn a_report_saved_now_is_marked_in_progress() {
        let mut attack = GooseAttack::initialize_with_config(configuration(None)).unwrap();
        attack.run_in_progress = true;
        attack.output.started = Some(Utc::now());
        let record = attack.report_record(true, 0);
        assert!(record.in_progress);
        assert_eq!((record.ended.as_deref(), record.ended_by), (None, None));
        assert_eq!(record.intro(), vec![IN_PROGRESS.to_string()]);
        let record = attack.report_record(false, 0);
        assert!(!record.in_progress);
        assert_eq!(record.ended_by, Some(EndedBy::Completed));
        assert!(record.intro().is_empty());
    }

    /// The graph data is kept whole when a `--report-file` path or Save report
    /// needs it, when the run starts and after Save report is turned on or off.
    #[test]
    fn keeps_full_graph_table() {
        for path in [false, true] {
            for bare in [false, true] {
                for dashboard in [false, true] {
                    let mut report_file = Vec::new();
                    if path {
                        report_file.push("report.html".to_string());
                    }
                    if bare {
                        report_file.push(RUN_FOLDER.to_string());
                    }
                    let mut attack = GooseAttack::initialize_with_config(GooseConfiguration {
                        report_file,
                        dashboard,
                        ..Default::default()
                    })
                    .unwrap();
                    let save = attack.configuration.save_report_at_start();
                    assert_eq!(save, bare || dashboard);
                    for save in [save, !save] {
                        attack.output.save_report = save;
                        assert_eq!(
                            attack.keeps_full_graph(),
                            path || save,
                            "path={path} bare={bare} dashboard={dashboard} save={save}"
                        );
                    }
                }
            }
        }
    }

    /// Turning Save report off tells the metrics processor to stop keeping
    /// the whole run's graphs only when no `--report-file` path needs them.
    #[cfg(feature = "dashboard")]
    #[tokio::test]
    async fn save_report_off_keeps_the_graphs_a_path_needs() {
        for (path, sent) in [(true, None), (false, Some(false))] {
            let report_file = if path {
                vec!["report.html".to_string()]
            } else {
                Vec::new()
            };
            let mut attack = GooseAttack::initialize_with_config(GooseConfiguration {
                report_file,
                no_telnet: true,
                no_websocket: true,
                ..Default::default()
            })
            .unwrap();
            let mut run_state = attack.initialize_attack().await.unwrap();
            let (metrics_cmd_tx, metrics_cmd_rx) = flume::unbounded();
            run_state.metrics_cmd_tx = metrics_cmd_tx;
            attack.run_in_progress = true;
            attack.output.save_report = true;
            assert!(attack.control_report(&mut run_state, Some(false), None).ok);
            let keep = metrics_cmd_rx.try_iter().find_map(|command| match command {
                MetricsCommand::KeepGraph { keep, .. } => Some(keep),
                _ => None,
            });
            assert_eq!(keep, sent, "path={path}");
        }
    }

    /// The run's folder goes at its end when the run wrote nothing into it;
    /// otherwise only [`RESERVED`] goes.
    #[test]
    fn a_released_folder_goes_only_when_empty() {
        let parent = temp_dir("release");
        let started = Local::now();
        let empty =
            RunFolder::choose(&configuration(Some(&parent.join("empty"))), started).unwrap();
        let mut output = Output::default();
        output.reserved = Some(empty.path.clone());
        output.release_folder();
        assert!(!empty.path.exists());
        let used = RunFolder::choose(&configuration(Some(&parent.join("used"))), started).unwrap();
        std::fs::write(used.file("goose.log"), "x").unwrap();
        output.reserved = Some(used.path.clone());
        output.release_folder();
        assert!(used.file("goose.log").exists());
        assert!(!used.file(RESERVED).exists());
        std::fs::remove_dir_all(&parent).ok();
    }

    /// A folder report that fails ends the run with an error, unless the
    /// session returns to Idle, which shows the reason instead; a
    /// `--report-file` path that fails is an error either way.
    #[tokio::test]
    async fn a_failed_folder_report_is_an_error_unless_the_session_goes_on() {
        let parent = temp_dir("end-of-run-error");
        let run = |report_file: Vec<String>| {
            let mut attack = GooseAttack::initialize_with_config(GooseConfiguration {
                report_file,
                ..configuration(Some(&parent.join("run")))
            })
            .unwrap();
            let folder = RunFolder::choose(&attack.configuration, Local::now()).unwrap();
            // A folder where report.html goes, so the write fails.
            std::fs::create_dir(folder.file(REPORT_HTML)).unwrap();
            attack.run_in_progress = true;
            attack.output.started = Some(Utc::now());
            attack.output.save_report = true;
            attack.output.folder = Some(folder);
            attack
        };
        let mut attack = run(Vec::new());
        assert!(attack.write_end_of_run(false).await.is_err());
        let mut attack = run(Vec::new());
        attack.write_end_of_run(true).await.unwrap();
        let error = attack.output.error().unwrap_or_default();
        assert!(error.contains(&*parent.to_string_lossy()), "{}", error);
        let missing = parent.join("missing").join("report.html");
        let mut attack = run(vec![missing.to_string_lossy().into_owned()]);
        assert!(attack.write_end_of_run(true).await.is_err());
        std::fs::remove_dir_all(&parent).ok();
    }

    /// The banner's downloads name only a folder the report routes take.
    #[cfg(feature = "dashboard")]
    #[test]
    fn last_report_name_is_only_a_name_the_routes_take() {
        let mut attack =
            GooseAttack::initialize_with_config(GooseConfiguration::default()).unwrap();
        for (folder, name) in [
            ("goose-runs/nightly", Some("nightly")),
            ("goose-runs/nightly run", None),
        ] {
            attack.output.last_report = Some(folder.to_string());
            assert_eq!(
                attack.report_snapshot().last_report_name.as_deref(),
                name,
                "{}",
                folder
            );
        }
    }

    /// New fields default, so a JSON report from before them loads.
    #[test]
    fn a_record_without_its_fields_loads() {
        let record: RunRecord = serde_json::from_str("{}").unwrap();
        assert_eq!(record, RunRecord::default());
    }

    #[test]
    fn parent_folder_holds_the_run_folder() {
        assert_eq!(parent_folder(&configuration(None)), Path::new("goose-runs"));
        let nested = configuration(Some(Path::new("goose-runs/nightly")));
        assert_eq!(parent_folder(&nested), Path::new("goose-runs"));
        let bare = configuration(Some(Path::new("nightly")));
        assert_eq!(parent_folder(&bare), Path::new("."));
    }

    #[test]
    fn a_gz_name_is_its_inner_format() {
        assert_eq!(without_gz("report.json.gz"), ("report.json", true));
        assert_eq!(without_gz("report.pdf.gz"), ("report.pdf", true));
        assert_eq!(without_gz("report.json"), ("report.json", false));
        // Only one .gz is taken off.
        assert_eq!(without_gz("x.gz.gz"), ("x.gz", true));
    }

    /// A folder's JSON report is its report.json, else its report.json.gz,
    /// and a gzipped report that is cut short is an error, never a panic.
    #[test]
    fn gzipped_reports_are_read_whole_or_not_at_all() {
        use std::io::Write;
        let dir = temp_dir("gz-read");
        let json = dir.join("report.json.gz");
        let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        gzip.write_all(br#"{"notes": "zipped"}"#).unwrap();
        let bytes = gzip.finish().unwrap();
        std::fs::write(&json, &bytes).unwrap();
        assert_eq!(crate::metrics::json_report_path(&dir), json);
        let text = crate::metrics::read_report_text(&json).unwrap();
        assert_eq!(text, r#"{"notes": "zipped"}"#);
        std::fs::write(dir.join("report.json"), "{}").unwrap();
        assert_eq!(
            crate::metrics::json_report_path(&dir),
            dir.join("report.json")
        );

        std::fs::write(&json, &bytes[..bytes.len() - 6]).unwrap();
        assert!(crate::metrics::read_report_text(&json).is_err());
        std::fs::write(&json, b"plain text").unwrap();
        assert!(crate::metrics::read_report_text(&json).is_err());
        std::fs::remove_dir_all(&dir).ok();
    }

    #[cfg(feature = "dashboard")]
    #[test]
    fn delete_takes_plain_and_gzipped_names() {
        let names = deletable_files();
        for name in [
            "report.json",
            "report.json.gz",
            "goose.log.gz",
            "requests.csv.gz",
        ] {
            assert!(names.iter().any(|n| n == name), "{}", name);
        }
        assert!(!names.iter().any(|n| n.contains('/')));
    }

    /// Rule 12: a listing parses a report again when it changes, so the
    /// report that replaces one saved now lists as ended, never as running
    /// or incomplete; a report marked in progress is running only for the
    /// run in progress.
    #[cfg(feature = "dashboard")]
    #[test]
    fn a_changed_report_is_listed_again() {
        let parent = temp_dir("listing");
        let folder = parent.join("run");
        std::fs::create_dir(&folder).unwrap();
        let json = folder.join(REPORT_JSON);
        let report = |in_progress: bool, requests: u64| {
            serde_json::json!({
                "in_progress": in_progress,
                "started": "2026-10-22T10:00:00Z",
                "raw_metrics": {"requests": {"GET /": {"success_count": requests, "fail_count": 0}}},
            })
            .to_string()
        };
        let mut cache = ListingCache::new();
        std::fs::write(&json, report(true, 5)).unwrap();
        let listed = list_reports(&parent, Some(&folder), &mut cache).unwrap();
        assert!(listed[0].record.in_progress && listed[0].running);
        assert_eq!(listed[0].requests, 5);
        let listed = list_reports(&parent, None, &mut cache).unwrap();
        assert!(listed[0].record.in_progress && !listed[0].running);

        std::fs::write(&json, report(false, 12345)).unwrap();
        let listed = list_reports(&parent, Some(&folder), &mut cache).unwrap();
        assert!(!listed[0].record.in_progress && !listed[0].running);
        assert_eq!(listed[0].requests, 12345);
        std::fs::remove_dir_all(&parent).ok();
    }

    #[test]
    fn log_names_follow_the_format() {
        assert_eq!(log_file_name("requests", None), "requests.json");
        assert_eq!(
            log_file_name("errors", Some(&GooseLogFormat::Csv)),
            "errors.csv"
        );
        assert_eq!(
            log_file_name("debug", Some(&GooseLogFormat::Pretty)),
            "debug.log"
        );
        assert_eq!(
            log_file_name("scenarios", Some(&GooseLogFormat::Raw)),
            "scenarios.log"
        );
    }
}