zond-engine 0.15.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
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
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # The exported document
//!
//! The data transfer objects that define what a zond report looks like on the
//! wire. Everything a consumer parses is described here, and nothing else in the
//! engine is serializable at all.
//!
//! ## Why this layer exists
//!
//! [`Host`] and its neighbours are the engine's working types. Their fields are
//! private, their layout follows what the scanners need, and they are refactored
//! whenever that changes. Deriving `Serialize` on them would publish that layout
//! as a format, and the first refactor after the first customer would be a
//! breaking change to their parser rather than a private matter.
//!
//! So the mapping is written out by hand, once, here. It costs a file and buys
//! the freedom to move a field, rename a variant or split a struct without
//! anyone outside noticing. In the other direction, changing the wire format
//! becomes a deliberate edit to a file whose purpose is to be stable rather than
//! a side effect of a refactor. Every enum is mapped by an exhaustive `match`, so
//! adding a variant to a core type fails to compile until somebody decides what
//! it is called in JSON.
//!
//! ## Conventions the whole document obeys
//!
//! These hold everywhere, so a consumer learns them once:
//!
//! - **Timestamps are RFC 3339 strings in UTC**, to microsecond precision. Never
//!   epoch floats; see [`time`](crate::format::time) for why.
//! - **Durations are integers of microseconds**, in a field whose name ends in
//!   `_us`. The unit is in the name because a bare `timeout` field is a support
//!   ticket waiting to happen.
//! - **Counts that can exceed 2^53 are decimal strings**, not numbers. An IPv6
//!   sweep's address count does not fit a JSON number as JavaScript implements
//!   one, and a count that rounds silently is worse than one that needs parsing.
//!   Everything narrow enough to be exact stays a number.
//! - **Objects have a fixed shape, and absence never means anything.** A field
//!   with no value is present and `null`, and a list with nothing in it is
//!   present and empty. The exception is a field describing something the scan
//!   did not do at all, such as an evasion profile on a scan that altered no
//!   packets or a switch on a network with no managed equipment, which is left
//!   out rather than nulled. A consumer reading an absent field as the empty one,
//!   `null` or `[]` or `false`, reads every document correctly.
//!   `assets/schema/zond-report-v1.schema.json` is the list: every field it does
//!   not mark `required` is one of these.
//! - **Order is deterministic.** Hosts sort by primary IP, ports by number, sets
//!   by their natural order. Two scans that found the same things produce
//!   documents that diff cleanly.
//! - **Unknown fields may appear.** Additive changes do not bump
//!   [`SCHEMA_VERSION`], so a consumer must ignore what it does not recognise.
//!
//! ## Every type here is `#[non_exhaustive]`
//!
//! Adding a field to the document is additive for a consumer parsing JSON and
//! would break one writing Rust, since a struct with public fields can be built
//! by name from outside this crate and the next field breaks every such
//! expression.
//!
//! Every field stays public and readable, which is what a consumer rendering a
//! report in their own format does. What stops is constructing one by name, and
//! each of these has a constructor taking the engine value it describes.
//!
//! ## Streaming
//!
//! [`ReportDto`] borrows the report rather than copying it, and serializes hosts
//! from an iterator. One [`HostDto`] exists at a time, whatever the size of the
//! scan, so exporting a /16 costs a host's worth of memory rather than a
//! network's.
//!
//! [`Host`]: crate::model::host::Host

use std::borrow::Cow;
use std::net::IpAddr;
use std::time::{Duration, SystemTime};

use serde::Serialize;
use serde::ser::{SerializeSeq, Serializer};

use crate::config::{RetryConfig, ScanEffort};
use crate::export::ExportOptions;
use crate::format::time::rfc3339;
use crate::model::capture::CaptureCounts;
use crate::model::finding::{Finding, Reference};
use crate::model::host::{
    HardwareInfo, Hop, Host, HostStatus, HostTelemetry, OsFingerprint, StatusReason,
    ip_protocol_name,
};
use crate::model::ip::range::IpRange;
use crate::model::port::{CertificateInfo, Discovery, Port, PortSet, PortState, Security, Service};
use crate::model::tls::{CipherSuite, VersionSupport};
use crate::report::{
    ATTEMPTS_COUNTED, BUCKET_BOUNDS_MS, EvasionRecord, PortScope, ProbeStats, Refusal, ScanPhase,
    ScanReport, ScanSettings, ScanSummary, ScannerFailure, TargetScope,
};
use crate::system::privilege::Privilege;
use crate::transport::probe::SendMode;

// The two values a reader of this document has to agree with live in
// `crate::format` rather than here, so a reader does not depend on the writer.
// Re-exported so this module still reads as the whole description of the
// document.
pub use crate::format::{ENGINE_NAME, SCHEMA_VERSION};
pub use crate::report::ENGINE_VERSION;

// ---------------------------------------------------------------------------
// Enum names
//
// The wire spelling of every enumerated value in the document. Public so a
// third-party exporter rendering the same data in its own format spells them the
// way the JSON does.
// ---------------------------------------------------------------------------

/// The wire name of a host's reachability status.
// The names below are defined in `record::wire`, beside the parsers that read
// them back, so a name and its inverse cannot drift apart. Re-exported rather
// than called through, since a caller should not have to know where they live.
pub use crate::record::wire::{
    attachment_source_name, confidence_name, detection_ceiling_name, detection_class_name,
    filtering_name, host_status_name, ip_protocol_state_name, network_role_name, port_scope_name,
    port_state_name, protocol_name, reference_kind_name, scan_kind_name, scan_response_name,
    scanner_kind_name, severity_name, status_protocol_name, stop_reason_name, tcp_flags_name,
};

/// The wire name of a send mode.
pub fn send_mode_name(mode: SendMode) -> &'static str {
    match mode {
        SendMode::Auto => "auto",
        SendMode::RawSocket => "raw_socket",
        SendMode::Ethernet => "ethernet",
    }
}

/// The wire name of a retransmission effort level.
pub fn scan_effort_name(effort: ScanEffort) -> &'static str {
    match effort {
        ScanEffort::Single => "single",
        ScanEffort::Fast => "fast",
        ScanEffort::Balanced => "balanced",
        ScanEffort::Thorough => "thorough",
    }
}

/// Renders a duration as whole microseconds.
///
/// Saturates rather than wrapping. The bound is roughly 585,000 years, so nothing
/// the engine measures approaches it, and a measurement that cannot be
/// represented should not come out small.
fn micros(duration: Duration) -> u64 {
    u64::try_from(duration.as_micros()).unwrap_or(u64::MAX)
}

/// Renders an optional duration as whole microseconds.
fn micros_opt(duration: Option<Duration>) -> Option<u64> {
    duration.map(micros)
}

// ---------------------------------------------------------------------------
// The document
// ---------------------------------------------------------------------------

/// A whole scan report, ready to serialize.
///
/// Borrows the report it describes: constructing one is free, and serializing
/// it walks the hosts rather than materialising them. See the
/// [module documentation](self) for the conventions the output obeys.
///
/// ```no_run
/// use zond_engine::report::ScanReport;
/// use zond_engine::export::{ExportOptions, schema::ReportDto};
///
/// # fn example(report: &ScanReport) -> Result<(), Box<dyn std::error::Error>> {
/// let options = ExportOptions::new();
/// let document = ReportDto::new(report, &options);
/// # let _ = document;
/// # Ok(())
/// # }
/// ```
#[non_exhaustive]
#[derive(Debug)]
pub struct ReportDto<'a> {
    report: &'a ScanReport,
    options: &'a ExportOptions,
    generated_at: SystemTime,
}

impl<'a> ReportDto<'a> {
    /// Describes a report, stamped with the current time as its generation
    /// time.
    pub fn new(report: &'a ScanReport, options: &'a ExportOptions) -> Self {
        Self::generated_at(report, options, SystemTime::now())
    }

    /// Describes a report with an explicit generation time.
    ///
    /// For a test producing a document that is byte-identical across runs.
    /// Everything else in a report is determined by the scan, and the generation
    /// stamp is the only field that moves on its own.
    pub fn generated_at(
        report: &'a ScanReport,
        options: &'a ExportOptions,
        generated_at: SystemTime,
    ) -> Self {
        Self {
            report,
            options,
            generated_at,
        }
    }

    /// The report being described.
    pub fn report(&self) -> &'a ScanReport {
        self.report
    }

    /// The options in force.
    pub fn options(&self) -> &'a ExportOptions {
        self.options
    }
}

impl Serialize for ReportDto<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;

        let mut doc = serializer.serialize_struct("Report", HEADER_FIELDS + 1)?;
        write_header(&mut doc, self.report, self.generated_at, self.options)?;
        doc.serialize_field(
            "hosts",
            &HostsDto {
                report: self.report,
                options: self.options,
            },
        )?;
        doc.end()
    }
}

/// Everything a report says about itself, without the hosts.
///
/// The same fields [`ReportDto`] emits before its `hosts` array, and in the same
/// order. A record-per-line format writes this once and then the hosts one at a
/// time; splitting the document that way must not change what the header says,
/// so both are rendered by the same code.
#[non_exhaustive]
#[derive(Debug)]
pub struct ReportHeaderDto<'a> {
    report: &'a ScanReport,
    options: &'a ExportOptions,
    generated_at: SystemTime,
}

impl<'a> ReportHeaderDto<'a> {
    /// Describes a report's header, stamped with the current time.
    ///
    /// Takes the same options the hosts are written under. A phase carries the
    /// switch this machine was plugged into, which names a device and a hardware
    /// address, so a header rendered without the policy would leak from a
    /// document whose every host record honoured it.
    pub fn new(report: &'a ScanReport, options: &'a ExportOptions) -> Self {
        Self::generated_at(report, options, SystemTime::now())
    }

    /// Describes a report's header with an explicit generation time.
    pub fn generated_at(
        report: &'a ScanReport,
        options: &'a ExportOptions,
        generated_at: SystemTime,
    ) -> Self {
        Self {
            report,
            options,
            generated_at,
        }
    }
}

impl Serialize for ReportHeaderDto<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;

        let mut doc = serializer.serialize_struct("ReportHeader", HEADER_FIELDS)?;
        write_header(&mut doc, self.report, self.generated_at, self.options)?;
        doc.end()
    }
}

/// How long a scan took, as the document reports it.
///
/// The sum of the phases as rendered, not the truncation of the underlying sum.
/// Each phase's figure is truncated to whole microseconds independently, so a
/// total taken from the durations behind them can exceed the sum of the numbers
/// printed beside it, and the document would contradict itself by a microsecond.
///
/// Public because every rendering of a report has to agree about this number,
/// including one written outside this crate.
pub fn total_elapsed_us(phases: &[PhaseDto<'_>]) -> u64 {
    phases
        .iter()
        .fold(0u64, |total, phase| total.saturating_add(phase.elapsed_us))
}

/// How many fields [`write_header`] emits.
const HEADER_FIELDS: usize = 9;

/// Emits the fields every rendering of a report starts with.
fn write_header<S: serde::ser::SerializeStruct>(
    doc: &mut S,
    report: &ScanReport,
    generated_at: SystemTime,
    options: &ExportOptions,
) -> Result<(), S::Error> {
    let phases: Vec<PhaseDto<'_>> = report
        .phases()
        .iter()
        .map(|phase| PhaseDto::new(phase, options))
        .collect();
    let elapsed_us = total_elapsed_us(&phases);

    doc.serialize_field("schema_version", &SCHEMA_VERSION)?;
    doc.serialize_field(
        "engine",
        &EngineDto {
            name: ENGINE_NAME,
            version: ENGINE_VERSION,
        },
    )?;
    doc.serialize_field("produced_by", report.engine_version())?;
    doc.serialize_field("generated_at", &rfc3339(generated_at))?;
    doc.serialize_field("started_at", &rfc3339(report.started_at()))?;
    doc.serialize_field("elapsed_us", &elapsed_us)?;
    doc.serialize_field("partial", &report.is_partial())?;
    doc.serialize_field("summary", &SummaryDto::new(&report.summary()))?;
    doc.serialize_field("phases", &phases)?;

    Ok(())
}

/// The report's hosts, serialized one at a time.
struct HostsDto<'a> {
    report: &'a ScanReport,
    options: &'a ExportOptions,
}

impl Serialize for HostsDto<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut seq = serializer.serialize_seq(Some(self.report.host_count()))?;
        for host in self.report.hosts() {
            seq.serialize_element(&HostDto::new(host, self.options))?;
        }
        seq.end()
    }
}

/// Which build wrote a document.
///
/// This build, both halves. A `version` beside a name is that name's version, and
/// the name here is fixed, so writing somebody else's version next to it produced
/// `zond-engine` paired with `nmap 7.94`, a build that never existed. What
/// produced the findings is `produced_by`.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct EngineDto {
    /// Always [`ENGINE_NAME`]. Present so a document carrying a report can be
    /// told apart from one carrying something else, and checked on the way back
    /// in.
    pub name: &'static str,
    /// Always [`ENGINE_VERSION`]: the crate version of the build that wrote the
    /// document.
    pub version: &'static str,
}

// ---------------------------------------------------------------------------
// Summary
// ---------------------------------------------------------------------------

/// Headline counts, with the full distribution behind each one.
///
/// The per-status and per-state breakdowns are structs rather than maps, so every
/// category is present in severity order whether or not anything landed in it. A
/// consumer reading `filtered: 0` learns something; one deciding what a missing
/// key means does not.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct SummaryDto {
    /// Hosts recorded, whatever their status.
    pub hosts_total: usize,
    /// Hosts confirmed present on the network: `up` or `filtered`.
    pub hosts_alive: usize,
    /// The full status distribution.
    pub hosts_by_status: HostStatusCounts,
    /// Port records across all hosts.
    pub ports_total: usize,
    /// Ports found accepting connections.
    pub ports_open: usize,
    /// The full port-state distribution.
    pub ports_by_state: PortStateCounts,
    /// Ports whose service was identified by fingerprinting.
    pub services_identified: usize,
    /// Hosts counted by the address families they answered at.
    pub hosts_by_family: FamilyCounts,
}

/// Hosts counted by the address families they answered at.
///
/// A dual-stack host is counted in all three, so these do not partition
/// `hosts_total`. They answer how much of a network was seen over each family,
/// which a partition would not.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Serialize)]
pub struct FamilyCounts {
    /// Hosts with at least one IPv4 address.
    pub ipv4: usize,
    /// Hosts with at least one IPv6 address.
    pub ipv6: usize,
    /// Hosts with both.
    pub dual_stack: usize,
}

impl SummaryDto {
    /// Renders a computed summary.
    pub fn new(summary: &ScanSummary) -> Self {
        let status = |status: HostStatus| {
            summary
                .hosts_by_status
                .get(&status)
                .copied()
                .unwrap_or_default()
        };
        let state = |state: PortState| {
            summary
                .ports_by_state
                .get(&state)
                .copied()
                .unwrap_or_default()
        };

        Self {
            hosts_total: summary.hosts_total,
            hosts_alive: summary.hosts_alive,
            hosts_by_status: HostStatusCounts {
                up: status(HostStatus::Up),
                filtered: status(HostStatus::Filtered),
                down: status(HostStatus::Down),
                unknown: status(HostStatus::Unknown),
            },
            ports_total: summary.ports_total,
            ports_open: summary.ports_open,
            ports_by_state: PortStateCounts {
                open: state(PortState::Open),
                open_filtered: state(PortState::OpenFiltered),
                closed: state(PortState::Closed),
                unfiltered: state(PortState::Unfiltered),
                filtered: state(PortState::Filtered),
                closed_filtered: state(PortState::ClosedFiltered),
                unasked: state(PortState::Unasked),
            },
            services_identified: summary.services_identified,
            hosts_by_family: FamilyCounts {
                ipv4: summary.hosts_by_family.ipv4,
                ipv6: summary.hosts_by_family.ipv6,
                dual_stack: summary.hosts_by_family.dual_stack,
            },
        }
    }
}

/// How many hosts fell into each reachability status.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct HostStatusCounts {
    /// Online and responding.
    pub up: usize,
    /// Present, but probes are being dropped.
    pub filtered: usize,
    /// Explicitly confirmed unreachable.
    pub down: usize,
    /// Never determined.
    pub unknown: usize,
}

/// How many ports fell into each state.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct PortStateCounts {
    /// Accepting connections.
    pub open: usize,
    /// Either open or silently dropped; the usual UDP outcome.
    pub open_filtered: usize,
    /// Actively refusing connections.
    pub closed: usize,
    /// Reachable, but open or closed could not be told apart.
    pub unfiltered: usize,
    /// Probes dropped with no answer.
    pub filtered: usize,
    /// Either closed or dropped.
    pub closed_filtered: usize,
    /// Named by the scan and never probed, so nothing was established. A
    /// non-zero count here is the visible half of a run that fell short; the
    /// phase's `timed_out` and `stop_reason` say why.
    pub unasked: usize,
}

// ---------------------------------------------------------------------------
// Phases
// ---------------------------------------------------------------------------

/// One call into the engine: what it was asked to do, how it was configured,
/// how long it took, and what it observed about itself.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct PhaseDto<'a> {
    /// `discovery` or `port_scan`.
    pub kind: &'static str,
    /// When the phase began.
    pub started_at: String,
    /// How long it ran, measured monotonically.
    pub elapsed_us: u64,
    /// Whether the engine held the privileges its raw strategies need. An
    /// unprivileged phase reached its targets over plain TCP connect attempts,
    /// which see less.
    ///
    /// `null` on a phase this engine did not measure, where the question is
    /// about strategies that never ran.
    pub privileged: Option<bool>,
    /// What the phase was asked to cover.
    pub targets: ScopeDto,
    /// The settings that shaped the packets it sent.
    pub settings: SettingsDto,
    /// Strategies that did not run to completion. A non-empty list means the
    /// findings are narrower than the caller asked for.
    pub failures: Vec<FailureDto<'a>>,
    /// Ground the phase declined to cover before sending anything, and why.
    ///
    /// Not failures and not listed among them, on the same reasoning
    /// `unroutable` is kept out: nothing broke. The engine worked out that part
    /// of what it was asked for had no strategy behind it and said so, which is
    /// a claim about the scan as written rather than about the machine or the
    /// network. A reader acts on the two differently, a failure might not
    /// recur, and a refusal will recur every time the same scan is run.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub refusals: Vec<RefusalDto<'a>>,
    /// Addresses this host had no route to, so nothing was sent to them,
    /// ascending.
    ///
    /// Not failures and not listed among them: no strategy broke and the result
    /// is not partial because of these. They are here because the caller named
    /// the addresses and got no answer about them, which a host count cannot
    /// say.
    ///
    /// An address here was never probed at all, which is a different finding
    /// from one that was probed and stayed silent.
    pub unroutable: Vec<String>,
    /// Addresses the phase stopped working on because their own budget ran out,
    /// ascending.
    ///
    /// Left out when empty, which is every phase that set no per-host budget.
    /// An address here carries whatever the phase managed to ask about and
    /// nothing after that: the ports it never reached are present with the
    /// scan's silence verdict, so without this list a page of `filtered` reads
    /// as a quiet machine rather than as a scan that ran out of time.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub timed_out: Vec<String>,
    /// What each instrumented scanner observed about its own run. Empty where
    /// no strategy in this phase carries instrumentation, which is not the same
    /// as a scanner that measured zero.
    pub probe_stats: Vec<ProbeStatsDto>,
    /// Which document this phase was folded in from, for a report merged out of
    /// several.
    ///
    /// `null` on a phase the engine that wrote this document measured itself,
    /// where the report's own `engine` is the attribution.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub origin: Option<PhaseOriginDto<'a>>,
    /// Which switch ports the machine running this phase was plugged into, as
    /// the equipment on the far end announced itself.
    ///
    /// Empty where nothing announced itself, which is every unmanaged network.
    /// Never a claim that the machine is attached to nothing.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub attachments: Vec<AttachmentDto<'a>>,
}

/// Where the machine running a phase was plugged in.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct AttachmentDto<'a> {
    /// Which of the scanning machine's interfaces the announcement arrived on.
    pub link: &'a str,
    /// Which protocol it was read from.
    pub source: &'a str,
    /// The hardware address the device identified its chassis with, masked
    /// under redaction. `null` where it named itself some other way.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device_mac: Option<String>,
    /// What the device calls itself, which on managed equipment is its
    /// hostname. Masked under redaction, on the same terms a host's is.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device_name: Option<Cow<'a, str>>,
    /// What the device calls the port this machine is plugged into.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub port: Option<&'a str>,
    /// The VLAN untagged traffic on this port lands in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub native_vlan: Option<u16>,
    /// An address the device is managed at.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub management_address: Option<String>,
    /// When the announcement arrived.
    pub observed_at: String,
}

/// Which document a phase came from, for a merged report.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct PhaseOriginDto<'a> {
    /// What the caller called the document it was read from. `null` where it
    /// gave no name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<&'a str>,
    /// What produced the phase, as that scanner attributed itself. `nmap 7.94`
    /// for a phase read out of nmap's XML, and no evidence this engine ran it.
    pub engine_version: &'a str,
}

impl<'a> PhaseDto<'a> {
    /// Renders a recorded phase, applying the redaction policy in `options`.
    ///
    /// A phase carried nothing to redact until it began carrying an
    /// [`attachment`](crate::report::Attachment), which names a device and its
    /// hardware address. Neither is less identifying for describing a switch
    /// rather than a workstation.
    pub fn new(phase: &'a ScanPhase, options: &ExportOptions) -> Self {
        Self {
            kind: scan_kind_name(phase.kind()),
            started_at: rfc3339(phase.started_at()),
            elapsed_us: micros(phase.elapsed()),
            privileged: phase.privilege().map(Privilege::is_raw),
            targets: ScopeDto::new(phase.targets()),
            settings: SettingsDto::new(phase.settings()),
            failures: phase.failures().iter().map(FailureDto::new).collect(),
            refusals: phase.refusals().iter().map(RefusalDto::new).collect(),
            unroutable: phase
                .unroutable()
                .iter()
                .map(std::string::ToString::to_string)
                .collect(),
            timed_out: phase
                .timed_out()
                .iter()
                .map(std::string::ToString::to_string)
                .collect(),
            probe_stats: phase.probe_stats().iter().map(ProbeStatsDto::new).collect(),
            origin: phase.origin().map(|origin| PhaseOriginDto {
                label: origin.label(),
                engine_version: origin.engine_version(),
            }),
            attachments: phase
                .attachments()
                .iter()
                .map(|attachment| AttachmentDto {
                    link: attachment.link().name(),
                    source: attachment_source_name(attachment.source()),
                    device_mac: attachment
                        .device_mac()
                        .map(|mac| options.redaction.mac(&mac)),
                    device_name: attachment
                        .device_name()
                        .map(|name| options.redaction.hostname(name)),
                    port: attachment.port(),
                    native_vlan: attachment.native_vlan(),
                    management_address: attachment
                        .management_address()
                        .map(|address| address.to_string()),
                    observed_at: rfc3339(attachment.observed_at()),
                })
                .collect(),
        }
    }
}

/// What a phase was asked to cover.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct ScopeDto {
    /// The merged ranges the sweep actually iterated, ascending. Overlapping
    /// arguments have already been coalesced, so these do not restate what a
    /// user typed.
    pub ranges: Vec<RangeDto>,
    /// How many distinct addresses were in scope, as a decimal string.
    pub addresses: String,
    /// How many address/port/protocol combinations were in scope, as a decimal
    /// string.
    ///
    /// `null` on a discovery phase, which has no port dimension, and on a target
    /// set too large to count, which is a failure to measure rather than a
    /// plausible-looking number. The phase `kind` tells the two apart.
    pub probes: Option<String>,
    /// The links this phase swept whole, by interface name, ascending.
    ///
    /// `ranges` is what a target set named; a sweep of a local segment also
    /// reaches every host on the link, which is ground no range expresses. A
    /// consumer checking whether a host was in scope has to read both.
    ///
    /// Empty for a phase that swept no segment. Only the interface name travels:
    /// its index is a runtime detail of the machine that scanned, and means
    /// nothing on the machine reading this.
    pub links: Vec<String>,
    /// The links this phase read traffic from without probing them.
    ///
    /// Never coverage, which is why it is not `links`. A sweep puts a probe on
    /// the segment that every host there is obliged to answer, so a host missing
    /// from the report was not on it. Listening establishes nothing of the kind,
    /// since a machine quiet during the window is indistinguishable from one that
    /// is absent.
    ///
    /// Read it to know where a phase was standing, never to conclude that
    /// anything was or was not there.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub listened: Vec<String>,
    /// Which ports the phase walked, and whether it walked the same ones for
    /// every address.
    ///
    /// `null` where the record does not say, which is what a report rebuilt from
    /// another tool's output or from a build older than this field carries.
    /// `probes` counts these combinations; this names the ports they were.
    pub ports: Option<PortScopeDto>,
    /// The transport protocols in scope, ascending. Empty on a discovery phase,
    /// whose probes are chosen by the strategy rather than by the caller.
    pub protocols: Vec<&'static str>,
    /// The merged ranges the phase was forbidden to probe, ascending.
    ///
    /// Empty when no exclusion policy was in force. A policy that was in force
    /// and overlapped nothing appears here in full with `withheld` at zero, since
    /// a consumer acting on scope compliance needs both facts.
    ///
    /// This is the part of the document a reader can check the engine against:
    /// no host in this report may fall inside any of these ranges.
    pub excluded: Vec<RangeDto>,
    /// How many addresses the exclusion policy took out of this phase, as a
    /// decimal string.
    ///
    /// The overlap between the policy and what this phase was handed, measured
    /// when its scope was recorded. That gives `"0"` for a policy naming ground
    /// the phase would never have walked, and `"0"` again for a phase whose input
    /// an earlier one had already narrowed.
    pub withheld: String,
}

/// Which ports a phase walked.
///
/// Two fields rather than one, because a set of ports on its own does not say
/// what may be concluded from it. `kind` is what does.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct PortScopeDto {
    /// `none` for a phase that walked no ports, `every` where each address was
    /// walked for the same set, and `mixed` where they differed and `spec` is
    /// their union.
    ///
    /// Only `every` supports concluding that a particular endpoint of a covered
    /// address was probed. Under `mixed`, a port in the set was walked for at
    /// least one address and not necessarily for any given one, though a port
    /// absent from the set was walked for none.
    pub kind: &'static str,
    /// The ports, written as the specification a scanner takes: comma
    /// separated, `start-end` for a run, `u:` prefixing the UDP half. Empty
    /// under `none`.
    pub spec: String,
}

impl PortScopeDto {
    /// Renders a port scope, or `None` where the record does not state one.
    pub fn new(scope: &PortScope) -> Option<Self> {
        match scope {
            PortScope::Unstated => None,
            other => Some(Self {
                kind: port_scope_name(other),
                spec: other.ports().map(PortSet::to_string).unwrap_or_default(),
            }),
        }
    }
}

impl ScopeDto {
    /// Renders a recorded scope.
    pub fn new(scope: &TargetScope) -> Self {
        Self {
            ranges: scope.ranges().iter().map(RangeDto::new).collect(),
            links: {
                let mut links: Vec<String> = scope
                    .links()
                    .iter()
                    .map(|zone| zone.name().to_owned())
                    .collect();
                links.sort();
                links
            },
            listened: {
                let mut listened: Vec<String> = scope
                    .listened()
                    .iter()
                    .map(|zone| zone.name().to_owned())
                    .collect();
                listened.sort();
                listened
            },
            addresses: scope.addresses().to_string(),
            probes: scope.probes().map(|count| count.to_string()),
            ports: PortScopeDto::new(scope.ports()),
            protocols: scope
                .protocols()
                .iter()
                .copied()
                .map(protocol_name)
                .collect(),
            excluded: scope.excluded().iter().map(RangeDto::new).collect(),
            withheld: scope.withheld().to_string(),
        }
    }
}

/// One inclusive address range.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct RangeDto {
    /// `ipv4` or `ipv6`.
    pub family: &'static str,
    /// The first address in the range.
    pub start: String,
    /// The last address in the range, inclusive.
    pub end: String,
}

impl RangeDto {
    /// Renders an address range.
    pub fn new(range: &IpRange) -> Self {
        Self {
            family: match range {
                IpRange::V4(_) => "ipv4",
                IpRange::V6(_) => "ipv6",
            },
            start: range.start_addr().to_string(),
            end: range.end_addr().to_string(),
        }
    }
}

/// The settings that shaped what a phase put on the wire.
///
/// A deliberate subset of the engine's configuration: what changed the packets
/// and how long the engine waited for answers. Presentation settings are not
/// here, so a quieter terminal never reads as a different scan.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct SettingsDto {
    /// How raw probes were placed on the wire.
    pub send_mode: &'static str,
    /// Which segment each TCP port probe carried: `syn`, `fin`, `null`, `xmas`,
    /// `maimon` or `ack`.
    ///
    /// Without it a port state cannot be read. `closed` from a SYN scan is a
    /// refused connection attempt; `closed` from a FIN scan is a reset drawn by
    /// a segment that was not one, and against a stack that resets everything it
    /// may be nothing at all.
    pub tcp_technique: &'static str,
    /// Which chunk each SCTP port probe carried: `init` or `cookie-echo`.
    ///
    /// An SCTP port reported `open_filtered` came from a `cookie-echo` scan,
    /// which draws an answer only from a closed port and so cannot report one
    /// open at all. Under `init` the same port would have been settled either
    /// way.
    pub sctp_technique: &'static str,
    /// The retransmission budget and patience in force.
    pub retry: RetryDto,
    /// The probe-rate ceiling in probes per second, or `null` if the scanner's
    /// own default applied.
    pub max_probe_rate: Option<u32>,
    /// The probe-rate floor in probes per second, or `null` if the scan was free
    /// to settle wherever it liked.
    ///
    /// It bounds a reading of the traffic as much as the ceiling does: a scan
    /// that emitted more packets than its targets were answering did so because
    /// it was told to finish in time.
    pub min_probe_rate: Option<u32>,
    /// The shortest gap kept between two probes at one host, or `null` if none
    /// was asked for.
    ///
    /// It bounds how long the phase's own numbers took to reach: a sweep of a
    /// thousand addresses spaced a tenth of a second apart cannot have finished
    /// in under a hundred seconds.
    pub host_probe_interval_us: Option<u64>,
    /// The wall-clock budget each host was given, or `null` if none was set.
    ///
    /// It bounds what a host's entry can claim. Three open ports out of a
    /// thousand is a different finding depending on whether the other nine
    /// hundred and ninety-seven were asked, and `timed_out` on the phase says
    /// which hosts ran out.
    pub host_timeout_us: Option<u64>,
    /// The wall-clock budget the whole phase was given, or `null` if none was
    /// set.
    ///
    /// A phase that spent it stopped where it stood, and its scanners record
    /// `timed_out` as their stop reason.
    pub scan_timeout_us: Option<u64>,
    /// Whether name resolution was permitted to generate traffic.
    pub dns_enabled: bool,
    /// Whether the caller asked the *scan* to mask identifying detail. Distinct
    /// from export redaction, which is chosen when the report is written and is
    /// visible in what this document actually contains.
    pub redact: bool,
    /// How far the phase went to identify operating systems: `off`, `passive`,
    /// `active` or `aggressive`.
    ///
    /// A host with no operating system reported reads differently at each: `off`
    /// means nothing looked. It also says how much of this phase's traffic the
    /// engine originated for the purpose, which under `off` and `passive` is
    /// none.
    pub os_detection: &'static str,

    /// How far the phase went to identify services: `off`, `banner` or `probe`.
    ///
    /// A port with no service reported reads differently at each: `off` means
    /// nothing connected to it. It also says whether the phase completed a
    /// connection to every open port, which is what the target would have
    /// logged.
    pub service_detection: &'static str,

    /// The intrusiveness ceiling detections ran under: `passive`,
    /// `active_benign`, `active_mutating`, `exploit` or `dos`. A finding of a
    /// given class could appear only where the scan permitted that class, so this
    /// bounds what the report could ever have said was wrong.
    pub detection: &'static str,

    /// Whether the phase measured the route to each host that answered.
    pub traceroute: bool,
    /// Whether the phase characterised the filter in front of each host that
    /// answered.
    pub characterise: bool,

    /// Which IP protocols the phase asked each host that answered about,
    /// ascending. Empty for a phase that ran no such pass.
    pub ip_protocols: Vec<u8>,

    /// Whether the phase established what each TLS port accepts, rather than
    /// only what one handshake negotiated.
    ///
    /// A port whose `security` block lists no accepted versions is two things: a
    /// scan that never enumerated, and one that did and found an endpoint
    /// refusing every offer. Only this tells them apart.
    pub tls_enumeration: bool,
    /// What the scan changed about the packets it sent, omitted when it changed
    /// nothing. See [`EvasionDto`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub evasion: Option<EvasionDto>,
    /// The zombie a TCP port scan read its verdicts through, omitted for an
    /// ordinary scan. See [`IdleScanDto`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idle_scan: Option<IdleScanDto>,
    /// Whether the capture kept ICMP errors the technique did not need for its
    /// verdict.
    ///
    /// What decides how a filtered port's `no_response` reads. With this set the
    /// scan listened for a refusal and none came; without it, a refusal would
    /// not have been heard.
    pub icmp_evidence: bool,
}

/// What a scan changed about the packets it sent, as it appears in the report.
/// Each field is present only for a technique the scan used. The serialized form
/// of [`EvasionRecord`].
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct EvasionDto {
    /// The source port every probe left from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_port: Option<u16>,
    /// The hop limit every ordinary probe carried.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl: Option<u8>,
    /// The number of random bytes appended to each probe's payload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub padding: Option<u16>,
    /// Whether TCP probes carried a deliberately wrong checksum.
    #[serde(skip_serializing_if = "is_false")]
    pub bad_tcp_checksum: bool,
    /// The hardware address every frame claimed to come from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub spoof_mac: Option<String>,
    /// The largest each IP fragment a probe was split into, in bytes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fragment: Option<u16>,
    /// The addresses probes were also sent from as decoys.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub decoys: Vec<String>,
    /// The TCP flags every port probe carried in place of the technique's own,
    /// named (e.g. `fin|psh|urg`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flags: Option<String>,
}

/// The zombie a TCP port scan read its verdicts through, as it appears in the
/// report. Present only for an idle scan; its presence is what says the port
/// states were inferred through a third party rather than seen directly. The
/// serialized form of [`IdleScan`](crate::config::IdleScan).
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct IdleScanDto {
    /// The zombie's address.
    pub zombie: String,
    /// The port on the zombie its counter was read from, omitted for the
    /// scanner's default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub zombie_port: Option<u16>,
}

/// Omits a `false` boolean from the document, so a field appears only for a
/// technique the scan used. The counterpart of `skip_serializing_if` on the
/// optional fields beside it.
fn is_false(value: &bool) -> bool {
    !*value
}

impl EvasionDto {
    /// Renders a recorded evasion profile.
    pub fn new(record: &EvasionRecord) -> Self {
        Self {
            source_port: record.source_port,
            ttl: record.ttl,
            padding: record.padding,
            bad_tcp_checksum: record.bad_tcp_checksum,
            spoof_mac: record.spoof_mac.map(|mac| mac.to_string()),
            fragment: record.fragment,
            decoys: record.decoys.iter().map(|ip| ip.to_string()).collect(),
            flags: record.flags.map(tcp_flags_name),
        }
    }
}

impl SettingsDto {
    /// Renders recorded settings.
    pub fn new(settings: &ScanSettings) -> Self {
        Self {
            send_mode: send_mode_name(settings.send_mode),
            tcp_technique: settings.tcp_technique.name(),
            sctp_technique: settings.sctp_technique.name(),
            retry: RetryDto::new(&settings.retry),
            max_probe_rate: settings.max_probe_rate.map(std::num::NonZeroU32::get),
            min_probe_rate: settings.min_probe_rate.map(std::num::NonZeroU32::get),
            host_probe_interval_us: micros_opt(settings.host_probe_interval),
            host_timeout_us: micros_opt(settings.host_timeout),
            scan_timeout_us: micros_opt(settings.scan_timeout),
            dns_enabled: settings.dns_enabled,
            redact: settings.redact,
            os_detection: settings.os_detection.name(),
            service_detection: settings.service_detection.name(),
            detection: detection_ceiling_name(settings.detection.ceiling()),
            traceroute: settings.traceroute,
            characterise: settings.characterise,
            ip_protocols: settings.ip_protocols.clone(),
            tls_enumeration: settings.tls_enumeration,
            evasion: settings.evasion.as_ref().map(EvasionDto::new),
            idle_scan: settings.idle_scan.map(|idle| IdleScanDto {
                zombie: idle.zombie.to_string(),
                zombie_port: idle.zombie_port,
            }),
            icmp_evidence: settings.icmp_evidence,
        }
    }
}

/// The retransmission budget a phase ran under.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct RetryDto {
    /// The effort level: `single`, `fast`, `balanced` or `thorough`.
    pub effort: &'static str,
    /// An attempt budget set by the caller, overriding what `effort` implies.
    /// One or more, never zero.
    pub max_attempts: Option<u8>,
    /// A multiplier on how long the scan was willing to wait.
    ///
    /// `null` when the caller set none. Always a positive, finite number when
    /// present: [`TimeoutScale`](crate::config::TimeoutScale) refuses anything
    /// else, so this no longer has to filter for what a scan could not have
    /// honoured.
    pub timeout_scale: Option<f64>,
    /// Whether a host that answered nothing could have its budget cut short.
    pub dampen_silent_hosts: bool,
}

impl RetryDto {
    /// Renders a retry configuration.
    pub fn new(retry: &RetryConfig) -> Self {
        Self {
            effort: scan_effort_name(retry.effort),
            max_attempts: retry.max_attempts.map(std::num::NonZeroU8::get),
            timeout_scale: retry.timeout_scale.map(crate::config::TimeoutScale::get),
            dampen_silent_hosts: retry.dampen_silent_hosts,
        }
    }
}

/// A strategy that did not run to completion.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct FailureDto<'a> {
    /// The strategy that failed.
    pub scanner: &'static str,
    /// A human-readable description of the failure.
    pub reason: &'a str,
    /// When it was observed.
    pub at: String,
}

impl<'a> FailureDto<'a> {
    /// Renders a recorded failure.
    pub fn new(failure: &'a ScannerFailure) -> Self {
        Self {
            scanner: scanner_kind_name(failure.scanner()),
            reason: failure.reason(),
            at: rfc3339(failure.at()),
        }
    }
}

/// Ground a phase declined to cover.
///
/// No timestamp, unlike [`FailureDto`]: a refusal is decided before the phase
/// begins rather than observed while it runs, so there is no moment to report.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct RefusalDto<'a> {
    /// The strategy that would have taken this work.
    pub scanner: &'static str,
    /// What was not done, and what could be asked for instead.
    pub reason: &'a str,
}

impl<'a> RefusalDto<'a> {
    /// Renders a recorded refusal.
    pub fn new(refusal: &'a Refusal) -> Self {
        Self {
            scanner: scanner_kind_name(refusal.scanner()),
            reason: refusal.reason(),
        }
    }
}

// ---------------------------------------------------------------------------
// Probe instrumentation
// ---------------------------------------------------------------------------

/// What one raw scanner observed about its own run.
///
/// Instrumentation about the scan, not a finding about the network. It exists
/// to bound how much the findings can be trusted: a sweep that stopped on
/// `deadline_expired` with `last_reply_us` close to `elapsed_us` was still
/// finding hosts when it ran out of time, and nothing in the host list says so.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct ProbeStatsDto {
    /// The strategy these counters belong to.
    pub scanner: &'static str,
    /// How many targets this scanner owned, as a decimal string.
    pub targets: String,
    /// Why the receive loop stopped.
    pub stop_reason: &'static str,
    /// Whether the loop stopped because it had nothing left to do, rather than
    /// because something cut it short. Derived from `stop_reason`, and carried
    /// so a consumer does not have to encode which reasons mean "finished".
    pub complete: bool,
    /// How long the scanner ran.
    pub elapsed_us: u64,
    /// Probes the scanner tried to put on the wire.
    pub sends_attempted: u64,
    /// Of those, ones the sender refused. Non-zero means the shortfall starts
    /// at home, before the network is implicated at all.
    pub sends_failed: u64,
    /// Of those, ones seen leaving on the wire. The gap below `sends_attempted`
    /// is probes the OS took and dropped; zero means no egress capture.
    pub sends_witnessed: u64,
    /// Segments the capture handed up, before any of the scanner's own checks.
    pub segments_seen: u64,
    /// Segments from an address outside this scan's target set. A large count
    /// means the capture filter is admitting other traffic.
    pub segments_off_target: u64,
    /// In-set replies that answered no outstanding probe. They proved a host
    /// alive but yielded no round-trip sample.
    pub replies_without_rtt: u64,
    /// Targets credited as alive for the first time.
    pub hosts_found: u64,
    /// Found hosts by the attempt whose reply revealed them. This is what says
    /// whether retransmission is earning its traffic.
    pub answered_on: Vec<AttemptCountDto>,
    /// Found hosts whose reply named no attempt: it arrived after the probe had
    /// been written off, or carried nothing to match against.
    pub answered_unattributed: u64,
    /// How far into the run the first host was credited.
    pub first_reply_us: Option<u64>,
    /// How far into the run the last host was credited.
    pub last_reply_us: Option<u64>,
    /// Hosts by how far into the run they were credited.
    ///
    /// This measures discovery time, not round trip. A host found at 700 ms
    /// because its third attempt went out at 690 ms has a 10 ms round trip;
    /// reading these as latency turns a retry schedule into an imaginary slow
    /// path. Round trips are per host, under `telemetry`.
    pub found_at: Vec<BucketDto>,
    /// What the kernel capture reported, where there was one to ask. `null` for
    /// a scanner driven by a synthetic receive stream, which has no kernel
    /// buffer, rather than a clean-looking zero.
    pub capture: Option<CaptureDto>,
    /// What this run's congestion window did, for a scanner paced by one.
    ///
    /// The field that says whether the silence in this phase is a finding. A run
    /// whose window was cut back to its floor and still left most of its probes
    /// unanswered established that it could not ask, not that anything was
    /// filtered. `null` for a scanner paced some other way.
    pub window: Option<WindowDto>,
}

/// What a scan's congestion window did over one run.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct WindowDto {
    /// Probes it was willing to have outstanding when the run ended.
    pub capacity: u64,
    /// The most it was ever willing to have outstanding.
    pub peak: u64,
    /// How many times it was cut back.
    pub reductions: u32,
    /// Whether the window was allowed to move at all.
    ///
    /// A fixed window and an adaptive one that never had to move record the same
    /// `capacity`, `peak` and `reductions`, and mean quite different things: the
    /// first was told not to adapt, the second was never pushed.
    pub adaptive: bool,
    /// Whether it ended cut back as far as it is permitted to go, which says the
    /// scan was still being outrun when it stopped.
    pub at_floor: bool,
}

impl ProbeStatsDto {
    /// Renders a scanner's counters.
    pub fn new(stats: &ProbeStats) -> Self {
        let answered_on = stats
            .answered_on()
            .iter()
            .enumerate()
            .map(|(index, &count)| AttemptCountDto {
                attempt: index as u32 + 1,
                or_later: index + 1 == ATTEMPTS_COUNTED,
                count,
            })
            .collect();

        let found_at = stats
            .found_at()
            .iter()
            .enumerate()
            .map(|(index, &count)| BucketDto {
                le_ms: BUCKET_BOUNDS_MS.get(index).copied(),
                count,
            })
            .collect();

        Self {
            scanner: scanner_kind_name(stats.scanner()),
            targets: stats.targets().to_string(),
            stop_reason: stop_reason_name(stats.stop_reason()),
            complete: stats.stop_reason().is_complete(),
            elapsed_us: micros(stats.elapsed()),
            sends_attempted: stats.sends_attempted(),
            sends_failed: stats.sends_failed(),
            sends_witnessed: stats.sends_witnessed(),
            segments_seen: stats.segments_seen(),
            segments_off_target: stats.segments_off_target(),
            replies_without_rtt: stats.replies_without_rtt(),
            hosts_found: stats.hosts_found(),
            answered_on,
            answered_unattributed: stats.answered_unattributed(),
            first_reply_us: micros_opt(stats.first_reply()),
            last_reply_us: micros_opt(stats.last_reply()),
            found_at,
            capture: stats.capture().map(CaptureDto::new),
            window: stats.window().map(|window| WindowDto {
                capacity: window.capacity as u64,
                peak: window.peak as u64,
                reductions: window.reductions,
                adaptive: window.adaptive,
                at_floor: window.at_floor,
            }),
        }
    }
}

/// How many hosts a given attempt revealed.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct AttemptCountDto {
    /// The attempt number, counting from one.
    pub attempt: u32,
    /// Whether this entry also absorbs every later attempt. True on the last
    /// entry only, so a hand-raised retry budget still has somewhere to land.
    pub or_later: bool,
    /// Hosts first credited by this attempt's reply.
    pub count: u64,
}

/// One bucket of a discovery-time histogram.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct BucketDto {
    /// The bucket's inclusive upper bound in milliseconds, or `null` for the
    /// final open-ended bucket.
    pub le_ms: Option<u64>,
    /// Hosts credited within this bucket.
    pub count: u64,
}

/// What the kernel capture reported.
///
/// The only place where loss on the receive path is distinguishable from loss
/// on the network. A reply the kernel discards because the buffer was full
/// reaches no other counter in this document.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct CaptureDto {
    /// Frames the capture accepted and handed to the process.
    pub received: u64,
    /// Frames discarded because the buffer was full when they arrived.
    pub dropped: u64,
    /// Frames discarded by the interface or driver before the capture saw them.
    /// Not every platform reports this, so a zero is weaker evidence here than
    /// in `dropped`.
    pub if_dropped: u64,
    /// How many captures ended before they were told to.
    ///
    /// Counted in captures rather than frames, unlike the three above. Non-zero
    /// means an interface stopped hearing part-way through, so the counts beside
    /// it describe less of the network than they appear to.
    pub stopped_early: u64,
}

impl CaptureDto {
    /// Renders capture counters.
    pub fn new(counts: CaptureCounts) -> Self {
        Self {
            received: counts.received,
            dropped: counts.dropped,
            if_dropped: counts.if_dropped,
            stopped_early: counts.stopped_early,
        }
    }
}

// ---------------------------------------------------------------------------
// Hosts
// ---------------------------------------------------------------------------

/// Everything the scan established about one host.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct HostDto<'a> {
    /// The address the host is keyed by. Stable across a merge, so two phases
    /// that both saw this host produce one record.
    pub primary_ip: String,
    /// Every address known for this host, ascending. Multi-homed and dual-stack
    /// hosts have more than one.
    pub ips: Vec<String>,
    /// The interface `primary_ip` is valid on, when the host was found at the
    /// link layer.
    ///
    /// Carried separately rather than folded into the addresses, so a consumer
    /// parsing `ips` still gets addresses. An IPv6 link-local names a different
    /// machine on every segment and no socket can be opened to one without the
    /// zone, so `fe80::…` on its own describes a host nothing can reach.
    pub zone: Option<&'a str>,
    /// The address families this host answered at: `ipv4`, `ipv6`, or both.
    ///
    /// Derivable from `ips` and stated anyway, since consumers ask which half of
    /// a network was seen over IPv6 constantly and should not have to re-derive
    /// it by parsing addresses.
    pub families: Vec<&'static str>,
    /// The resolved hostname, masked under redaction.
    pub hostname: Option<Cow<'a, str>>,
    /// The reachability status: `up`, `filtered`, `down` or `unknown`.
    pub status: &'static str,
    /// Whether the host is confirmed present on the network. True for `up` and
    /// `filtered`; carried so a consumer does not have to know that a filtered
    /// host is still a host.
    pub alive: bool,
    /// The evidence behind the status, sorted.
    pub reasons: Vec<ReasonDto<'a>>,
    /// Inferred roles, sorted.
    pub roles: Vec<&'static str>,
    /// What the filter in front of the host was shown to be doing, sorted.
    pub filtering: Vec<&'static str>,
    /// What the scan concluded about each IP protocol it asked this host about,
    /// ascending by number. Empty for a scan that did not ask.
    pub ip_protocols: Vec<IpProtocolDto>,
    /// The identified operating system.
    pub os: Option<OsDto<'a>>,
    /// Physical hardware identity, masked under redaction.
    pub hardware: Option<HardwareDto<'a>>,
    /// Network path measurements.
    pub telemetry: TelemetryDto,
    /// The routers between the scanning host and this one, ascending by
    /// distance. Empty when no trace ran, which the phase's `traceroute`
    /// setting distinguishes from a trace that found nothing.
    pub path: Vec<HopDto>,
    /// Discovered ports, ascending by number.
    pub ports: Vec<PortDto<'a>>,
    /// What a detection concluded is wrong with the host as a whole, worst-first.
    /// A port's own findings are on the port.
    pub findings: Vec<FindingDto<'a>>,
    /// When this host was first seen.
    pub first_seen: String,
    /// When it was last updated.
    pub last_seen: String,
}

impl<'a> HostDto<'a> {
    /// Renders a host, applying the redaction policy in `options`.
    pub fn new(host: &'a Host, options: &ExportOptions) -> Self {
        let redaction = options.redaction;

        let mut families: Vec<&'static str> = Vec::with_capacity(2);
        if host.ips().iter().any(std::net::IpAddr::is_ipv4) {
            families.push("ipv4");
        }
        if host.ips().iter().any(std::net::IpAddr::is_ipv6) {
            families.push("ipv6");
        }

        let mut reasons: Vec<ReasonDto<'a>> = host.reasons().iter().map(ReasonDto::new).collect();
        reasons.sort_by(|a, b| {
            a.protocol
                .cmp(&b.protocol)
                .then(a.source_ip.cmp(&b.source_ip))
                .then(a.details.cmp(&b.details))
        });

        let mut roles: Vec<&'static str> = host
            .network_roles()
            .iter()
            .copied()
            .map(network_role_name)
            .collect();
        roles.sort_unstable();

        let mut filtering: Vec<&'static str> = host
            .filtering()
            .iter()
            .copied()
            .map(filtering_name)
            .collect();
        filtering.sort_unstable();

        Self {
            primary_ip: host.primary_ip().to_string(),
            ips: host.ips().iter().map(IpAddr::to_string).collect(),
            zone: host.zone().map(|zone| zone.name()),
            families,
            hostname: host.hostname().map(|name| redaction.hostname(name)),
            status: host_status_name(host.status()),
            alive: host.is_alive(),
            reasons,
            roles,
            filtering,
            ip_protocols: host
                .ip_protocols()
                .iter()
                .map(|(number, state)| IpProtocolDto {
                    protocol: *number,
                    name: ip_protocol_name(*number),
                    state: ip_protocol_state_name(*state),
                })
                .collect(),
            os: host.os().map(OsDto::new),
            hardware: host
                .hardware()
                .map(|hardware| HardwareDto::new(hardware, options)),
            telemetry: TelemetryDto::new(host.telemetry()),
            path: host.path().hops().iter().map(HopDto::new).collect(),
            ports: host
                .ports()
                .map(|port| PortDto::new(port, options))
                .collect(),
            findings: findings_dto(host.findings()),
            first_seen: rfc3339(host.first_seen()),
            last_seen: rfc3339(host.last_seen()),
        }
    }
}

/// One router on the way to a host.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct HopDto {
    /// How many routers from the scanning host this one sits.
    ///
    /// The key, not the position: a router that declines to answer leaves a gap,
    /// and the entries either side keep the distances they were measured at. A
    /// consumer counting array indices to get a distance will be wrong on every
    /// path with a silent router in it, which is most of them.
    pub distance: u8,
    /// The address the router answered from, or `null` where nothing answered
    /// at this distance.
    ///
    /// Null is a finding rather than a hole in the data. A router is there, since
    /// the hops beyond it were reached, and it did not identify itself. Many will
    /// not, and many rate-limit the answer to nothing.
    pub address: Option<String>,
    /// The round trip to this router in microseconds, or `null`.
    ///
    /// Measured from the scanning host, so it includes every hop in front of this
    /// one, and it times a router's error generation, which is the
    /// lowest-priority work most routers do. A hop slower than the one past it is
    /// ordinary and says nothing about the path.
    pub rtt_us: Option<u64>,
    /// Whether this hop was measured on the way to this host, or taken from
    /// another host's trace that passed through the same router.
    ///
    /// A scan of many hosts behind one gateway measures the shared part of the
    /// path once. That assumes two paths meeting at one router at one distance
    /// agreed before it, so the inference is marked and a consumer acting on a
    /// single hop can tell which kind it has.
    pub inferred: bool,
}

impl HopDto {
    /// Renders one hop.
    pub fn new(hop: &Hop) -> Self {
        Self {
            distance: hop.distance(),
            address: hop.address().map(|address| address.to_string()),
            rtt_us: hop
                .rtt()
                .and_then(|rtt| u64::try_from(rtt.as_micros()).ok()),
            inferred: hop.inferred(),
        }
    }
}

/// One piece of evidence for a host's status.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct ReasonDto<'a> {
    /// The protocol event that produced the evidence.
    pub protocol: Cow<'a, str>,
    /// The address that sent the evidence, when it was not the host itself.
    ///
    /// Present only for second-hand evidence, such as an ICMP error from a router
    /// or firewall about the probed address. `null` means the host answered for
    /// itself, the stronger claim, so a consumer weighing how much to trust a
    /// status can do it from this field alone.
    pub source_ip: Option<String>,
    /// What was observed, where the strategy recorded it.
    pub details: Option<&'a str>,
}

impl<'a> ReasonDto<'a> {
    /// Renders a status reason.
    pub fn new(reason: &'a StatusReason) -> Self {
        Self {
            protocol: status_protocol_name(&reason.protocol),
            source_ip: reason.source.map(|ip| ip.to_string()),
            details: reason.details.as_deref(),
        }
    }
}

/// An identified operating system.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct OsDto<'a> {
    /// The primary OS name.
    pub name: &'a str,
    /// The broad family.
    pub family: Option<&'a str>,
    /// The version or generation.
    pub generation: Option<&'a str>,
    /// The vendor.
    pub vendor: Option<&'a str>,
    /// Confidence in this identification, 0 to 100.
    pub accuracy: u8,
    /// CPE identifiers, sorted.
    pub cpes: Vec<&'a str>,
    /// What this identification was read off, in one line, or `null` where the
    /// technique that produced it recorded nothing.
    ///
    /// For a person rather than a parser. Different techniques render different
    /// things here, and the fields a consumer should act on are the named ones
    /// above. It lets a disputed finding be diagnosed, and turned into a corpus
    /// entry, without re-running the scan.
    pub evidence: Option<&'a str>,
    /// The kernel release, or `null` where nothing read one.
    ///
    /// Beside `generation` rather than a finer form of it: a distribution
    /// release and the kernel it ships are two facts about one machine. It is
    /// also what a known-vulnerability lookup keys on for a Unix host.
    pub kernel: Option<&'a str>,
    /// The instruction set, such as `"x86_64"` or `"mips"`, or `null` where
    /// nothing read one.
    ///
    /// A third axis beside what the machine runs and what it is: two hosts of
    /// one family on different silicon are not interchangeable to an exploit
    /// that needs a payload built for the target.
    pub arch: Option<&'a str>,
    /// How well supported everything *past* the family is, or `null` where the
    /// finding stops at a family.
    ///
    /// `accuracy` beside it describes the family, which is what every source can
    /// speak to. A release is usually named by exactly one of them, so a single
    /// figure for both would report the weaker claim at the stronger claim's
    /// strength.
    pub detail_accuracy: Option<u8>,
    /// What kind of box this is, such as `"Printer"` or `"Switch"`, or `null`
    /// where nothing named a class.
    ///
    /// A separate axis from `family`, not a coarser one: what a machine is and
    /// what it runs are independent, and a host may have either answered without
    /// the other. Both may be `null` on a finding that named only a product.
    pub device: Option<&'a str>,
}

impl<'a> OsDto<'a> {
    /// Renders an OS fingerprint.
    pub fn new(os: &'a OsFingerprint) -> Self {
        Self {
            name: os.name(),
            family: os.family(),
            generation: os.generation(),
            vendor: os.vendor(),
            accuracy: os.accuracy(),
            cpes: os.cpes().iter().map(|cpe| &**cpe).collect(),
            evidence: os.evidence(),
            kernel: os.kernel(),
            arch: os.arch(),
            detail_accuracy: os.detail_accuracy(),
            device: os.device(),
        }
    }
}

/// One IP protocol the scan asked a host about, and what it concluded.
///
/// The number is the finding and the name is a courtesy: a reader recognises
/// `gre` faster than `47`, and a number the IANA registry has no keyword for is
/// reported as the number alone rather than invented for.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct IpProtocolDto {
    /// The IP protocol number.
    pub protocol: u8,
    /// Its registry keyword, where it has one worth printing.
    pub name: Option<&'static str>,
    /// `open`, `closed`, `filtered`, `open_filtered` or `unasked`. What each
    /// means here is
    /// [`IpProtocolState`](crate::model::host::IpProtocolState)'s own
    /// documentation, and the words are not a port's: `open` is the host taking
    /// delivery of the protocol rather than something listening behind it.
    pub state: &'static str,
}

/// Physical hardware identity.
///
/// The last-seen timestamps the engine keeps per address are not exported: they
/// are monotonic readings, which have no meaning outside the process that took
/// them.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct HardwareDto<'a> {
    /// The most recently observed address, which is the one currently on the
    /// network.
    pub mac: Option<String>,
    /// Every address observed for this host, sorted. More than one means a
    /// multi-NIC host or a device rotating a randomized address.
    pub macs: Vec<String>,
    /// The vendor resolved from the address's OUI.
    ///
    /// Survives redaction: masking preserves the OUI, so naming the vendor
    /// reveals nothing the masked address does not already.
    pub vendor: Option<&'a str>,
    /// The model, where a service named it: `PDR M800`, `Firewall-1`.
    ///
    /// Not derivable from an address at any prefix length, so it arrives only
    /// from something that stated it, and it survives redaction for the same
    /// reason the vendor does: it describes the product rather than the host.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product: Option<&'a str>,
    /// The line that model belongs to, where a rule distinguishes the two.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub family: Option<&'a str>,
    /// The hardware's platform identifier, separate from the operating
    /// system's: a report naming both names two things about one machine.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cpe23: Option<&'a str>,
    /// The model number on its own, where the product string carried more than
    /// one thing: `4200` beside a product of `Xerox WorkCentre 4200`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<&'a str>,
    /// The hardware revision, which is the board rather than the firmware: a
    /// unit that ships in two silicon revisions under one model number is two
    /// different machines to an exploit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<&'a str>,
    /// The serial number, where a service handed one over.
    ///
    /// Dropped under redaction, unlike everything else in this record. The rest
    /// describes a product line and stays true of every unit built; this names
    /// one machine, and a masked prefix of it would still do so within a fleet
    /// that bought them in a batch.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub serial_number: Option<&'a str>,
}

impl<'a> HardwareDto<'a> {
    /// Renders hardware information, applying the redaction policy.
    pub fn new(hardware: &'a HardwareInfo, options: &ExportOptions) -> Self {
        let redaction = options.redaction;

        let mut macs: Vec<String> = hardware
            .macs()
            .keys()
            .map(|mac| redaction.mac(mac))
            .collect();
        // Masking collapses addresses that share an OUI, which would otherwise
        // list the same string twice. Consecutive deduplication suffices: the
        // source is sorted by address, and masking preserves the leading
        // octets, so collapsed entries are always neighbours.
        macs.dedup();

        Self {
            mac: hardware.most_recent_mac().map(|mac| redaction.mac(&mac)),
            macs,
            vendor: hardware.vendor(),
            product: hardware.product(),
            family: hardware.family(),
            cpe23: hardware.cpe23(),
            model: hardware.model(),
            version: hardware.hardware_version(),
            serial_number: match redaction.is_active() {
                true => None,
                false => hardware.serial_number(),
            },
        }
    }
}

/// Network path measurements for a host.
///
/// The individual samples are not exported. They are timestamped with monotonic
/// readings that mean nothing outside the scanning process, and the aggregates
/// below are what the samples were being kept for.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct TelemetryDto {
    /// The fastest round trip observed.
    pub rtt_min_us: Option<u64>,
    /// The median round trip: the single best summary of typical latency,
    /// because one retransmit or scheduling hiccup barely moves it.
    pub rtt_median_us: Option<u64>,
    /// The arithmetic mean round trip.
    pub rtt_avg_us: Option<u64>,
    /// The slowest round trip observed.
    pub rtt_max_us: Option<u64>,
    /// Mean absolute difference between consecutive samples. High jitter
    /// relative to the average often means congestion or bufferbloat.
    pub jitter_us: Option<u64>,
    /// How many samples the figures above are drawn from.
    pub samples: usize,
}

impl TelemetryDto {
    /// Renders host telemetry.
    pub fn new(telemetry: &HostTelemetry) -> Self {
        Self {
            rtt_min_us: micros_opt(telemetry.min_rtt()),
            rtt_median_us: micros_opt(telemetry.median_rtt()),
            rtt_avg_us: micros_opt(telemetry.average_rtt()),
            rtt_max_us: micros_opt(telemetry.max_rtt()),
            jitter_us: micros_opt(telemetry.jitter()),
            samples: telemetry.history().len(),
        }
    }
}

// ---------------------------------------------------------------------------
// Ports
// ---------------------------------------------------------------------------

/// One discovered port.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct PortDto<'a> {
    /// The port number.
    pub port: u16,
    /// The transport protocol.
    pub protocol: &'static str,
    /// The discovered state.
    pub state: &'static str,
    /// What is running there, where fingerprinting identified it.
    pub service: Option<ServiceDto<'a>>,
    /// Negotiated transport security, where a TLS handshake succeeded.
    pub security: Option<SecurityDto<'a>>,
    /// How the state was established.
    pub discovery: Option<DiscoveryDto<'a>>,
    /// What a detection concluded is wrong with what is listening here,
    /// worst-first.
    pub findings: Vec<FindingDto<'a>>,
}

impl<'a> PortDto<'a> {
    /// Renders a port, applying the redaction policy.
    pub fn new(port: &'a Port, options: &ExportOptions) -> Self {
        Self {
            port: port.number(),
            protocol: protocol_name(port.protocol()),
            state: port_state_name(port.state()),
            service: port.service().map(ServiceDto::new),
            security: port
                .security()
                .map(|security| SecurityDto::new(security, options)),
            discovery: port.discovery().map(DiscoveryDto::new),
            findings: findings_dto(port.findings()),
        }
    }
}

/// The findings of a subject, worst-first for a person reading the report:
/// severity descending, then producer id. The model sorts by identity for a
/// stable file, and a report sorts by severity for a legible page.
fn findings_dto<'a>(findings: impl Iterator<Item = &'a Finding>) -> Vec<FindingDto<'a>> {
    let mut findings: Vec<&'a Finding> = findings.collect();
    findings.sort_by(|a, b| {
        b.severity()
            .cmp(&a.severity())
            .then_with(|| a.detection().id().cmp(b.detection().id()))
    });
    findings.into_iter().map(FindingDto::new).collect()
}

/// One finding, for a report a consumer parses.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct FindingDto<'a> {
    /// The detection that produced it. Author-chosen and untrusted; an exporter
    /// writing to markup escapes it.
    pub id: &'a str,
    /// The detection's version, `major.minor.patch`.
    pub version: String,
    /// The content hash of the detection body, for reproducibility.
    pub content_hash: &'a str,
    /// The one-line title. Untrusted.
    pub title: &'a str,
    /// How bad it is if true: `info`, `low`, `medium`, `high` or `critical`.
    pub severity: &'static str,
    /// How sure it is true: `heuristic`, `weak`, `probable`, `strong` or
    /// `certain`. Independent of severity, so a finding can be `critical` and
    /// only `probable`.
    pub confidence: &'static str,
    /// The intrusiveness the detection ran under.
    pub class: &'static str,
    /// The bytes that justify it, for a person rather than a parser. Untrusted;
    /// absent where the detection carried none.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub excerpt: Option<&'a str>,
    /// External references: CVE, CWE and advisory links.
    pub references: Vec<ReferenceDto<'a>>,
    /// Remediation advice, if the detection carried any. Untrusted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remediation: Option<&'a str>,
}

impl<'a> FindingDto<'a> {
    /// Renders a finding.
    pub fn new(finding: &'a Finding) -> Self {
        Self {
            id: finding.detection().id(),
            version: finding.detection().version().to_string(),
            content_hash: finding.detection().content_hash(),
            title: finding.title(),
            severity: severity_name(finding.severity()),
            confidence: confidence_name(finding.confidence()),
            class: detection_class_name(finding.class()),
            excerpt: (!finding.excerpt().is_empty()).then(|| finding.excerpt().as_str()),
            references: finding.references().map(ReferenceDto::new).collect(),
            remediation: finding.remediation(),
        }
    }
}

/// One external reference: a typed kind and the value it carries.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct ReferenceDto<'a> {
    /// `cve`, `cwe`, or `url`.
    pub kind: &'static str,
    /// The identifier or link. A `url` value is untrusted.
    pub value: Cow<'a, str>,
}

impl<'a> ReferenceDto<'a> {
    /// Renders a reference.
    pub fn new(reference: &'a Reference) -> Self {
        Self {
            kind: reference_kind_name(reference),
            value: match reference {
                Reference::Cve(id) | Reference::Url(id) => Cow::Borrowed(id.as_str()),
                Reference::Cwe(number) => Cow::Owned(number.to_string()),
            },
        }
    }
}

/// A reference as one line of human-readable text: the CVE or CWE identifier, or
/// the URL. [`ReferenceDto`] keeps the kind and value apart for a parser, while
/// this is the flattened form the nmap-XML `<script output>` and the CSV findings
/// column put in front of a reader.
///
/// Compiled only for the exporters that use it.
#[cfg(any(feature = "export-nmap", feature = "export-csv"))]
pub(crate) fn reference_text(reference: &Reference) -> String {
    match reference {
        Reference::Cve(id) => id.clone(),
        Reference::Cwe(number) => format!("CWE-{number}"),
        Reference::Url(url) => url.clone(),
    }
}

/// What is running on a port.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct ServiceDto<'a> {
    /// The high-level protocol name, such as `ssh` or `http`.
    pub name: &'a str,
    /// Certainty of this identification, 0 to 100. A table lookup by port
    /// number scores near zero; a completed protocol handshake scores near 100.
    pub confidence: u8,
    /// The specific product or daemon.
    pub product: Option<&'a str>,
    /// The organization behind the product, where one could be attributed.
    pub vendor: Option<&'a str>,
    /// The version string reported or detected.
    pub version: Option<&'a str>,
    /// Additional metadata or environment hints.
    pub extrainfo: Option<&'a str>,
    /// CPE identifiers, in the order they were established.
    pub cpes: Vec<&'a str>,
}

impl<'a> ServiceDto<'a> {
    /// Renders a service identification.
    pub fn new(service: &'a Service) -> Self {
        Self {
            name: service.name(),
            confidence: service.confidence(),
            product: service.product(),
            vendor: service.vendor(),
            version: service.version(),
            extrainfo: service.extrainfo(),
            cpes: service.cpes().iter().map(AsRef::as_ref).collect(),
        }
    }
}

/// Transport security negotiated on a port.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct SecurityDto<'a> {
    /// The negotiated TLS version.
    pub tls_version: Option<&'a str>,
    /// The cipher suite the server selected.
    pub cipher_suite: Option<&'a str>,
    /// ALPN protocols offered, in order.
    pub alpn: Vec<&'a str>,
    /// The presented X.509 certificate.
    pub certificate: Option<CertificateDto<'a>>,
    /// What the endpoint turned out to accept, one entry per version, oldest
    /// first. Left out where the scan did not enumerate.
    ///
    /// A different fact from `tls_version` and `cipher_suite` above, which are
    /// what one handshake settled on. A port naming `TLSv1.3` there and listing
    /// `TLSv1.0` here is a server that prefers the modern version and still
    /// accepts the withdrawn one, which is the configuration an audit looks for.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub accepts: Vec<AcceptedVersionDto>,
}

impl<'a> SecurityDto<'a> {
    /// Renders security telemetry, applying the redaction policy.
    pub fn new(security: &'a Security, options: &ExportOptions) -> Self {
        Self {
            tls_version: security.tls_version(),
            cipher_suite: security.cipher_suite(),
            alpn: security.alpn().iter().map(AsRef::as_ref).collect(),
            certificate: security
                .certificate()
                .map(|cert| CertificateDto::new(cert, options)),
            accepts: security
                .support()
                .versions()
                .iter()
                .map(AcceptedVersionDto::new)
                .collect(),
        }
    }
}

/// One protocol version an endpoint accepted, and the suites it chose under it.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct AcceptedVersionDto {
    /// The version, spelled the way every tool prints it: `SSLv3`, `TLSv1.0`
    /// through `TLSv1.3`.
    pub version: &'static str,
    /// Whether a standards body has withdrawn it, and so whether its presence is
    /// itself the finding.
    pub deprecated: bool,
    /// The suites accepted, in the order the server chose them. The first is
    /// that server's own preference among everything offered, where the server
    /// has one.
    pub suites: Vec<AcceptedSuiteDto>,
    /// Suites the server chose that this build does not carry, by number,
    /// rendered as `0x` hex. Absent where there were none.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub unrecognised: Vec<String>,
}

impl AcceptedVersionDto {
    /// Renders one version's worth of what an endpoint accepts.
    pub fn new(support: &VersionSupport) -> Self {
        Self {
            version: support.version().name(),
            deprecated: support.version().is_deprecated(),
            suites: support.suites().iter().map(AcceptedSuiteDto::new).collect(),
            unrecognised: support
                .unrecognised()
                .iter()
                .map(|code| format!("0x{code:04X}"))
                .collect(),
        }
    }
}

/// One cipher suite an endpoint accepted, and what is wrong with it.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct AcceptedSuiteDto {
    /// The IANA name, which is what every other tool prints.
    pub name: &'static str,
    /// The wire number, as `0x` hex, for a reader matching against a registry.
    pub code: String,
    /// `strong`, `weak` or `insecure`, derived from the faults below rather than
    /// stored beside them.
    pub strength: &'static str,
    /// Everything wrong with the suite, least costly first. Empty for a suite
    /// with nothing against it.
    pub faults: Vec<&'static str>,
}

impl AcceptedSuiteDto {
    /// Renders one accepted suite.
    pub fn new(suite: &CipherSuite) -> Self {
        Self {
            name: suite.name(),
            code: format!("0x{:04X}", suite.code()),
            strength: suite.strength().name(),
            faults: suite
                .faults()
                .into_iter()
                .map(|fault| fault.name())
                .collect(),
        }
    }
}

/// A presented X.509 certificate.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct CertificateDto<'a> {
    /// The subject Common Name, masked under redaction: an internal CA issues
    /// certificates naming people and machines.
    pub common_name: Cow<'a, str>,
    /// Subject Alternative Names, masked under redaction for the same reason.
    pub sans: Vec<Cow<'a, str>>,
    /// The issuing authority.
    pub issuer: &'a str,
    /// When the certificate becomes valid.
    pub validity_start: String,
    /// When it expires.
    pub validity_end: String,
    /// The public key algorithm.
    pub pubkey_type: &'a str,
    /// The public key size in bits.
    pub pubkey_bits: u32,
    /// The SHA-256 fingerprint of the DER-encoded certificate.
    pub fingerprint_sha256: &'a str,
}

impl<'a> CertificateDto<'a> {
    /// Renders certificate information, applying the redaction policy.
    pub fn new(cert: &'a CertificateInfo, options: &ExportOptions) -> Self {
        let redaction = options.redaction;

        Self {
            common_name: redaction.hostname(cert.common_name()),
            sans: cert
                .sans()
                .iter()
                .map(|san| redaction.hostname(san))
                .collect(),
            issuer: cert.issuer(),
            validity_start: rfc3339(cert.validity_start()),
            validity_end: rfc3339(cert.validity_end()),
            pubkey_type: cert.pubkey_type(),
            pubkey_bits: cert.pubkey_bits(),
            fingerprint_sha256: cert.fingerprint_sha256(),
        }
    }
}

/// How a port's state was established.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize)]
pub struct DiscoveryDto<'a> {
    /// The packet response that decided the state.
    pub reason: Cow<'a, str>,
    /// When the state was first confirmed.
    pub timestamp: String,
    /// The probe's round trip.
    pub rtt_us: Option<u64>,
    /// The TTL of the response packet.
    pub ttl: Option<u8>,
    /// The local interface address the probe was answered on. Relevant on
    /// multi-homed hosts, where port states differ by path.
    pub source_ip: Option<String>,
}

impl<'a> DiscoveryDto<'a> {
    /// Renders discovery telemetry.
    pub fn new(discovery: &'a Discovery) -> Self {
        Self {
            reason: scan_response_name(discovery.reason()),
            timestamp: rfc3339(discovery.timestamp()),
            rtt_us: micros_opt(discovery.rtt()),
            ttl: discovery.ttl(),
            source_ip: discovery.source_ip().map(|ip| ip.to_string()),
        }
    }
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::exclusion::Exclusions;
    use crate::model::host::{NetworkRole, StatusProtocol};
    use crate::model::ip::set::IpSet;
    use crate::model::port::PortSet;
    use crate::model::port::{Protocol, ScanResponse};
    use crate::model::target::{TargetMap, TargetSet};
    use crate::report::ScannerKind;
    use crate::report::{ScanKind, StopReason};

    /// Every enumerated value the document can carry is spelled the same way
    /// twice, once here and once in the schema file. Pinning the strings turns a
    /// rename into a failing test rather than a silent break in somebody's
    /// parser.
    #[test]
    fn wire_names_are_pinned() {
        assert_eq!(scan_kind_name(ScanKind::PortScan), "port_scan");
        assert_eq!(scanner_kind_name(ScannerKind::SynPort), "syn_port");
        assert_eq!(host_status_name(HostStatus::Filtered), "filtered");
        assert_eq!(port_state_name(PortState::OpenFiltered), "open_filtered");
        assert_eq!(protocol_name(Protocol::Udp), "udp");
        // Spelled out in full, unlike the enums above: this is the whole role
        // vocabulary a consumer switches on, and it is the one that grows.
        for (role, name) in [
            (NetworkRole::Router, "router"),
            (NetworkRole::DnsServer, "dns"),
            (NetworkRole::DhcpServer, "dhcp"),
            (NetworkRole::NtpServer, "ntp"),
            (NetworkRole::SnmpAgent, "snmp"),
            (NetworkRole::Origin, "origin"),
            (NetworkRole::Tarpit, "tarpit"),
            (NetworkRole::Truncated, "truncated"),
        ] {
            assert_eq!(network_role_name(role), name);
        }
        assert_eq!(
            stop_reason_name(StopReason::AttemptsSpent),
            "attempts_spent"
        );
        assert_eq!(send_mode_name(SendMode::RawSocket), "raw_socket");
        assert_eq!(scan_effort_name(ScanEffort::Thorough), "thorough");
    }

    /// A strategy naming itself after a built-in must not produce a reason
    /// indistinguishable from the real thing.
    #[test]
    fn a_custom_name_can_never_collide_with_a_builtin() {
        let impostor = StatusProtocol::Custom("arp".into());

        assert_eq!(status_protocol_name(&StatusProtocol::Arp), "arp");
        assert_eq!(status_protocol_name(&impostor), "custom:arp");

        let response = ScanResponse::Custom("tcp_rst".into());
        assert_eq!(scan_response_name(&ScanResponse::TcpRst), "tcp_rst");
        assert_eq!(scan_response_name(&response), "custom:tcp_rst");
    }

    /// Every status and state is a key in the summary, whether or not anything
    /// landed in it, so a consumer never has to guess what a missing key means.
    #[test]
    fn the_summary_reports_categories_that_saw_nothing() {
        let summary = SummaryDto::new(&ScanSummary::default());

        assert_eq!(summary.hosts_by_status.up, 0);
        assert_eq!(summary.hosts_by_status.unknown, 0);
        assert_eq!(summary.ports_by_state.open, 0);
        assert_eq!(summary.ports_by_state.closed_filtered, 0);
    }

    /// The counts that can exceed what a JSON number holds exactly are the ones
    /// an IPv6 sweep produces. They have to survive the round trip as text.
    #[test]
    fn oversized_counts_are_rendered_as_exact_strings() {
        let mut ips = IpSet::new();
        ips.insert_range("2001:db8::/32".parse().expect("a valid range"));

        let scope = ScopeDto::new(&TargetScope::from_ip_set(&mut ips, &Exclusions::none()));

        // 2^96, which a JSON number as JavaScript implements one would round to
        // something else entirely.
        assert_eq!(scope.addresses, "79228162514264337593543950336");
        assert!(scope.addresses.parse::<u128>().expect("exact") > (1u128 << 53));
    }

    /// A discovery phase has no port dimension, so its probe count is absent
    /// rather than zero, which would claim the sweep sent nothing.
    #[test]
    fn a_discovery_scope_has_no_probe_count() {
        let mut ips = IpSet::new();
        ips.insert_range("192.168.0.0/24".parse().expect("a valid range"));

        let scope = ScopeDto::new(&TargetScope::from_ip_set(&mut ips, &Exclusions::none()));

        assert_eq!(scope.addresses, "256");
        assert_eq!(scope.probes, None);
        assert!(scope.protocols.is_empty());
        assert_eq!(scope.ranges.len(), 1);
        assert_eq!(scope.ranges[0].family, "ipv4");
        assert_eq!(scope.ranges[0].start, "192.168.0.0");
        assert_eq!(scope.ranges[0].end, "192.168.0.255");
    }

    #[test]
    fn a_port_scan_scope_carries_the_probe_count() {
        let mut ips = IpSet::new();
        ips.insert_range("10.0.0.1-10.0.0.4".parse().expect("a valid range"));

        let mut targets = TargetMap::new();
        targets.add_unit(TargetSet::new(
            ips,
            PortSet::from_iter([(80, Protocol::Tcp), (53, Protocol::Udp)]),
        ));

        let scope = ScopeDto::new(&TargetScope::from_target_map(
            &mut targets,
            &Exclusions::none(),
        ));

        assert_eq!(scope.addresses, "4");
        assert_eq!(scope.probes.as_deref(), Some("8"));
        assert_eq!(scope.protocols, vec!["tcp", "udp"]);
    }

    /// A consumer that adds up the phases and compares the result to the total
    /// must get the same number, whatever the sub-microsecond remainders were.
    #[cfg(feature = "export-json")]
    #[test]
    fn the_total_duration_is_exactly_the_sum_of_the_phases() {
        let mut report = crate::export::fixture::report();
        report.merge(crate::export::fixture::report());

        let document = serde_json::to_value(ReportDto::new(&report, &ExportOptions::new()))
            .expect("the report serializes");

        let summed: u64 = document["phases"]
            .as_array()
            .expect("a phase array")
            .iter()
            .map(|phase| phase["elapsed_us"].as_u64().expect("a phase duration"))
            .sum();

        assert_eq!(document["elapsed_us"].as_u64(), Some(summed));
    }

    /// A scale nobody can write down is not a scale two runs should be claimed
    /// to share, and it is not a JSON number either.
    ///
    /// This document used to be where that was caught, by filtering a value the
    /// engine had already discarded and recorded anyway. The refusal is at
    /// [`TimeoutScale`](crate::config::TimeoutScale) now, so what reaches here
    /// is always a number JSON can hold, and this holds that rather than the
    /// filter.
    #[test]
    fn a_recorded_timeout_scale_is_always_a_number_json_can_hold() {
        for scale in [0.0, -1.0, f64::NAN, f64::INFINITY] {
            assert_eq!(
                crate::config::TimeoutScale::new(scale),
                None,
                "a scale of {scale} would have reached a report"
            );
        }

        let retry = RetryConfig {
            timeout_scale: crate::config::TimeoutScale::new(2.5),
            ..Default::default()
        };
        let rendered = RetryDto::new(&retry).timeout_scale;
        assert_eq!(rendered, Some(2.5));
        assert!(rendered.is_some_and(f64::is_finite));
    }
}