modem-device 0.3.0

The seam between the zenoh-modem driver and a physical or simulated medium
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
//! The seam between the driver and a medium.
//!
//! This crate deliberately does not depend on `zenoh`, and CI holds that with a
//! dependency-graph guard. The driver moves opaque batches and the medium moves
//! opaque SDUs; the moment either could parse a key expression, the second
//! policy plane the architecture forbids would exist
//! (`docs/architecture.md` I1, ยง4.8).
//!
//! Everything here describes a medium in terms a modem vendor would recognise โ€”
//! how big an SDU may be, whether it can transmit and receive at once, whether
//! delivery is ordered and loss-free. Nothing here describes Zenoh.
//!
//! Two traits since #117, split along the planes of
//! `docs/design/device-planes.md`: [`Device`] is what the management plane
//! serves โ€” a report, events, a lifecycle, and later a configuration plane โ€”
//! and [`Medium`]`: Device` is the SDU data plane on top of it. A device whose
//! data plane is the kernel's is a [`Netdev`]`: Device` โ€” named, served on the
//! management plane, and never seen by the lanes.

use std::fmt;

pub mod action;
pub mod config;
pub mod conformance;
pub mod layer;
pub use action::Actions;
pub use config::Configure;

/// Zenoh's own framing on the data path: a two-byte little-endian length
/// before every batch, which the driver strips before the medium and re-adds
/// after (`docs/architecture.md` ยง4.1). Stated here because a batch of N
/// bytes puts N - 2 on the medium, and every document that names a
/// `max_batch_size` has to add it back โ€” the contract's `Capabilities` does.
pub const LENGTH_PREFIX: usize = 2;

/// The smallest `batch_size` that carries a Zenoh session: 80 bytes.
///
/// Zenoh's establishment messages are never fragmented, and the largest is
/// 78 bytes (`docs/measurements/small-mtu-and-latency.md`, M1), so a medium
/// whose SDU is below `80 - LENGTH_PREFIX` cannot establish a transport at
/// any setting. The driver refuses such a configuration where it becomes a
/// device (#157); a `fragment` layer above the medium is what lifts a
/// smaller frame over the floor (#162).
pub const ESTABLISHMENT_FLOOR: u16 = 80;

/// One service data unit: exactly what the medium carries in one transmission.
///
/// The driver has already stripped Zenoh's two-byte length prefix by the time an
/// SDU reaches a backend, and re-adds it on the way back
/// (`docs/architecture.md` ยง4.1). Contents are never inspected.
pub type Sdu = Vec<u8>;

/// A remote endpoint reachable over the medium.
///
/// Opaque to the driver and to Zenoh alike. It is a name from configuration โ€”
/// `"peer-b"`, `"auv-03"`, an IMEI โ€” and per invariant I5 it is an *addressing*
/// identifier, never a proof of identity.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EndpointId(String);

impl EndpointId {
    /// Wrap a configured endpoint name.
    pub fn new(name: impl Into<String>) -> Self {
        Self(name.into())
    }

    /// The configured name, for logging and for keying medium-side tables.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for EndpointId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// The driver's view of one QoS lane.
///
/// Under decision D1 a lane is a socket, and its properties come from the
/// locator metadata Zenoh was configured with (`?rel=1;prio=0-2`) โ€” resolved
/// once, at startup, into this. A backend schedules lanes; it is never told what
/// a Zenoh priority is, which is what keeps [`Sdu`] traffic and Zenoh semantics
/// on opposite sides of this crate boundary.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LaneKey {
    /// Which remote this lane reaches.
    pub endpoint: EndpointId,
    /// Whether this lane promises ordered, loss-free delivery.
    ///
    /// Per invariant I2 this is a claim about the *medium*, not a request. A
    /// backend that cannot honour it must not be configured behind a lane that
    /// asserts it: Zenoh will not notice the lie, because `verify_sn` accepts a
    /// forward sequence gap silently โ€” the failure mode is lost data, not a
    /// fault.
    pub reliable: bool,
    /// Scheduling rank; lower is more urgent.
    ///
    /// Derived at configuration time from the lane's declared priority range.
    /// Rank 0 sorts first. The numbering happens to mirror Zenoh's, where
    /// `Control` is 0, but nothing here depends on that.
    pub rank: u8,
}

impl fmt::Display for LaneKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}/{}#{}",
            self.endpoint,
            if self.reliable { "rel" } else { "be" },
            self.rank
        )
    }
}

/// Whether the medium can transmit and receive simultaneously.
///
/// Only the two variants that change behaviour exist. The withdrawn ICD series
/// carried five, three of which had no consequence anywhere in the
/// specification; new variants are added here when something acts on them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
// Deliberately *not* `#[non_exhaustive]` (#97): a new duplex mode changes what
// every scheduler and simulator must do, so it should break their builds, and
// the contract's own `Duplex` maps this one variant for variant.
pub enum Duplex {
    /// Transmit and receive are independent.
    #[default]
    Full,
    /// Transmitting blocks receiving and vice versa, as on a shared RF channel.
    Half,
}

/// Whether a medium retransmits an SDU it failed to deliver.
///
/// This models the modem's *own* link-layer ARQ, which many packet radios and
/// every store-and-forward satellite service provide. Invariant I2 and
/// architecture ยง9 draw the line here: using the modem's ARQ is exactly right,
/// and inventing one above the modem is what the architecture forbids. A
/// backend declares what is in front of it (ยง4.13), and the simulator models
/// the same three cases, which is why the type is the seam's and not the
/// simulator's: [`Capabilities::arq`] and a simulated profile's `arq` are one
/// fact.
///
/// It is not free. Every attempt occupies the channel for another airtime, so a
/// link with ARQ and 5% loss carries measurably more than one without โ€” which
/// is the whole reason to model it rather than assume it.
///
/// Deliberately *not* `#[non_exhaustive]`, for [`Duplex`]'s reason: a fourth
/// kind of ARQ changes what every reliability claim means, and should break
/// every match that reasons about it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[cfg_attr(
    feature = "serde",
    serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)
)]
pub enum Arq {
    /// No retransmission. What a bare packet radio does.
    #[default]
    None,
    /// Retry a fixed number of times, then give up.
    ///
    /// Residual loss is `loss^(attempts+1)` โ€” small, but not zero, which is why
    /// this may not claim reliable delivery.
    Bounded { attempts: u32 },
    /// Retry until delivered.
    ///
    /// Delivery is guaranteed and latency is not. This is the only ARQ setting
    /// that may back a lane declaring `rel=1`.
    Unbounded,
}

impl Arq {
    /// The probability an SDU is still lost after this ARQ has finished trying.
    ///
    /// Stated rather than implied, so a profile's honesty is checkable and a
    /// write-up can quote a number.
    #[must_use]
    pub fn residual_loss(self, loss: f64) -> f64 {
        match self {
            Arq::None => loss,
            Arq::Bounded { attempts } => loss.powi(attempts as i32 + 1),
            Arq::Unbounded => 0.0,
        }
    }

    /// Whether a medium using this ARQ can honestly claim reliable delivery.
    #[must_use]
    pub fn guarantees_delivery(self) -> bool {
        matches!(self, Arq::Unbounded)
    }
}

impl fmt::Display for Arq {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Arq::None => f.write_str("none"),
            Arq::Bounded { attempts } => write!(f, "bounded({attempts})"),
            Arq::Unbounded => f.write_str("unbounded"),
        }
    }
}

/// How a medium's firmware splits an SDU into air frames (#159).
///
/// Many radio modules accept a payload larger than their air frame and
/// fragment it themselves. To the driver that is a medium with a larger SDU;
/// what the seam needs is the honesty: an SDU of *s* bytes over frames of
/// *f* is โŒˆs/fโŒ‰ frames, each paying its own preamble, and the SDU survives
/// only if every frame does. A module that fragments without per-frame ARQ
/// cannot be reliable over a lossy air (I2), and the plane shows the
/// frames-per-SDU an operator can watch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Framing {
    /// Bytes per air frame.
    pub frame: u16,
    /// What retransmits a lost *frame*, as the module states it.
    pub arq: Arq,
}

impl Framing {
    /// Frames of `frame` bytes, with `arq` per frame.
    #[must_use]
    pub fn new(frame: u16, arq: Arq) -> Self {
        Self { frame, arq }
    }

    /// How many frames an SDU of `sdu_len` bytes takes: โŒˆs/fโŒ‰, at least one.
    #[must_use]
    pub fn frames_for(&self, sdu_len: u16) -> u16 {
        if self.frame == 0 {
            return 1;
        }
        sdu_len.div_ceil(self.frame).max(1)
    }

    /// The probability an SDU of `sdu_len` bytes arrives whole over an air
    /// losing `loss` of its frames: `(1 โˆ’ residual)^frames`.
    #[must_use]
    pub fn survival(&self, loss: f64, sdu_len: u16) -> f64 {
        (1.0 - self.arq.residual_loss(loss)).powi(i32::from(self.frames_for(sdu_len)))
    }
}

/// What a medium can do, as the medium itself would describe it.
///
/// Transmit and receive limits are separate because real media are asymmetric:
/// Iridium SBD carries 340 bytes up and 270 down. Collapsing them to their
/// minimum โ€” as the withdrawn design did โ€” silently wasted 21% of every paid
/// uplink message (`docs/architecture.md` ยง4.9).
///
/// `#[non_exhaustive]` since 0.3: a capability a layer or a module adds (the
/// ARQ, the firmware framing) must not break every implementor's literal.
/// Build one with [`Capabilities::new`] and the setters.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Capabilities {
    /// Largest SDU the medium will transmit, in bytes.
    ///
    /// `u16` because Zenoh's own `BatchSize` is `u16`, so a larger value could
    /// never be filled.
    pub tx_max_sdu: u16,
    /// Largest SDU the medium will deliver, in bytes.
    ///
    /// **A promise this backend makes, and the driver checks it** (#75). An
    /// arrival larger than this counts `rx_oversize_total` and is logged as a
    /// contract violation; it is still delivered, because the batch is Zenoh's
    /// to judge and discarding it here would be the driver deciding a question
    /// I1 gives to Zenoh.
    ///
    /// It is **not** what stops a peer sending too much, and the distinction
    /// matters on an asymmetric bearer. `batch_size` is node-global and Zenoh
    /// negotiates the minimum of the two ends, so a pair configured
    /// inconsistently produces a *small* effective batch โ€” 21% of a paid
    /// uplink slot wasted on SBD โ€” never an oversized arrival. What an
    /// operator does with this number is size the *far* node's `batch_size`,
    /// which is why `Driver::start` logs it as `peer_max_batch_size` (#82).
    pub rx_max_sdu: u16,
    /// Whether transmit and receive contend.
    pub duplex: Duplex,
    /// Whether the medium delivers in order and without loss.
    ///
    /// Per invariant I2 this must be the truth about the hardware, not an
    /// aspiration. A lane may only assert [`LaneKey::reliable`] over a medium
    /// that reports `true` here.
    pub reliable: bool,
    /// What retransmits a lost SDU, as the module states it (ยง4.13). The
    /// claim `reliable` rests on, made explicit: only [`Arq::Unbounded`]
    /// guarantees delivery.
    pub arq: Arq,
    /// How the firmware splits an SDU into air frames, where it does (#159).
    /// `None` is one SDU, one frame.
    pub framing: Option<Framing>,
}

impl Capabilities {
    /// The four facts every medium states; `arq` defaults to none and
    /// `framing` to one frame per SDU, which the setters change.
    #[must_use]
    pub fn new(tx_max_sdu: u16, rx_max_sdu: u16, duplex: Duplex, reliable: bool) -> Self {
        Self {
            tx_max_sdu,
            rx_max_sdu,
            duplex,
            reliable,
            arq: Arq::None,
            framing: None,
        }
    }

    /// With the module's declared ARQ.
    #[must_use]
    pub fn arq(mut self, arq: Arq) -> Self {
        self.arq = arq;
        self
    }

    /// With the module's declared firmware framing.
    #[must_use]
    pub fn framing(mut self, framing: Framing) -> Self {
        self.framing = Some(framing);
        self
    }
}

/// Counters a medium exposes for telemetry.
///
/// Deliberately minimal: these are the quantities the driver can assert on in a
/// test. Radio-specific figures such as RSSI belong on the management plane
/// (`docs/architecture.md` ยง4.6), not in the data-path interface.
///
/// `#[non_exhaustive]` since 0.3; built with [`Metrics::new`] and the
/// setters, or `Default`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Metrics {
    /// SDUs handed to the medium and accepted.
    pub tx_sdus: u64,
    /// Bytes across those SDUs.
    pub tx_bytes: u64,
    /// SDUs delivered by the medium.
    pub rx_sdus: u64,
    /// Bytes across those SDUs.
    pub rx_bytes: u64,
    /// SDUs the medium accepted and then lost, where it can tell.
    ///
    /// A medium that cannot distinguish loss from delivery leaves this at zero;
    /// per the architecture's telemetry rule, absence means unknown and must not
    /// be read as none.
    pub dropped: u64,
}

impl Metrics {
    /// Every counter at zero.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// SDUs handed to the medium and accepted.
    #[must_use]
    pub fn tx_sdus(mut self, n: u64) -> Self {
        self.tx_sdus = n;
        self
    }

    /// Bytes across the transmitted SDUs.
    #[must_use]
    pub fn tx_bytes(mut self, n: u64) -> Self {
        self.tx_bytes = n;
        self
    }

    /// SDUs delivered by the medium.
    #[must_use]
    pub fn rx_sdus(mut self, n: u64) -> Self {
        self.rx_sdus = n;
        self
    }

    /// Bytes across the delivered SDUs.
    #[must_use]
    pub fn rx_bytes(mut self, n: u64) -> Self {
        self.rx_bytes = n;
        self
    }

    /// SDUs accepted and then lost, where the medium can tell.
    #[must_use]
    pub fn dropped(mut self, n: u64) -> Self {
        self.dropped = n;
        self
    }
}

/// What a device, or a layer above it, guarantees about the bytes it carries
/// (invariant I6): properties, never a boolean.
///
/// "AES enabled" states nothing about mode, key management, peer
/// authentication, anti-replay or scope, which is why this type has no
/// `encrypted` field and cannot have one. A device that provides nothing says
/// `None` from [`Device::security`], and the management plane publishes
/// exactly that. A layer that seals SDUs (#158) reports what it provides and
/// only that; a radio that encrypts below the driver reports its own. Every
/// property here is hop-by-hop: it ends at the neighbour's Zenoh, and a
/// router that applies key-expression ACLs sees plaintext.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SecurityProperties {
    /// Who provides it: `"zenoh-modem aead"`, a radio's own name.
    pub provider: String,
    /// How far the guarantee reaches.
    pub scope: Scope,
    /// What is guaranteed, each one named.
    pub guarantees: Vec<Guarantee>,
    /// The principal the far side was authenticated as, where one was. A key
    /// shared by more than two nodes proves only "holds the key", and even a
    /// pairwise key binds a key, not an identity (I5): `None` for both.
    pub principal: Option<String>,
}

impl SecurityProperties {
    /// A provider guaranteeing nothing yet; add guarantees with
    /// [`guarantee`](Self::guarantee).
    #[must_use]
    pub fn new(provider: impl Into<String>, scope: Scope) -> Self {
        Self {
            provider: provider.into(),
            scope,
            guarantees: Vec::new(),
            principal: None,
        }
    }

    /// One more guarantee, kept unique.
    #[must_use]
    pub fn guarantee(mut self, g: Guarantee) -> Self {
        if !self.guarantees.contains(&g) {
            self.guarantees.push(g);
        }
        self
    }

    /// The authenticated principal, where there is one.
    #[must_use]
    pub fn principal(mut self, p: impl Into<String>) -> Self {
        self.principal = Some(p.into());
        self
    }
}

/// How far a security property reaches.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Scope {
    /// One hop: from this node's driver to its neighbour's.
    Hop,
}

impl Scope {
    /// The wire spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Hop => "hop",
        }
    }
}

impl fmt::Display for Scope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One thing a provider guarantees, in the words `docs/design/link-security.md`
/// uses.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Guarantee {
    /// Nobody on the channel reads the payload.
    Confidentiality,
    /// A changed or forged SDU is refused.
    Integrity,
    /// A repeated SDU is refused.
    AntiReplay,
    /// The peer was authenticated when the transport was established, and
    /// nothing after that.
    PeerAuthenticationAtEstablishment,
}

impl Guarantee {
    /// The wire spelling, kebab-case.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Confidentiality => "confidentiality",
            Self::Integrity => "integrity",
            Self::AntiReplay => "anti-replay",
            Self::PeerAuthenticationAtEstablishment => "peer-authentication-at-establishment",
        }
    }
}

impl fmt::Display for Guarantee {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One named counter a device or a layer keeps beyond the fixed vocabulary
/// of [`Metrics`] and [`Report`] (#157): a layer's refusals, a module's
/// frames.
///
/// The management plane publishes a counter only under a subject the
/// registry declares for its `scope` and `name`, gated per scope, so a
/// counter nobody declared is visible in a log and nowhere else, and the
/// registry never lies about what is served.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Counter {
    /// Who keeps it: a layer's kind (`"aead"`), or `"air"` for a medium's
    /// frames.
    pub scope: String,
    /// What it counts: `auth_failures_total`.
    pub name: String,
    /// Its value now.
    pub value: u64,
}

impl Counter {
    /// A counter by scope and name.
    #[must_use]
    pub fn new(scope: impl Into<String>, name: impl Into<String>, value: u64) -> Self {
        Self {
            scope: scope.into(),
            name: name.into(),
            value,
        }
    }
}

/// What a device says about itself, as far as it knows.
///
/// `Capabilities` is what the medium *can* carry and is read once; `Metrics` is
/// what the driver counted and is what a test asserts on. This is the third
/// thing, and the one that fell off the edge: what the hardware knows about its
/// own condition. `modem-device` named the gap years before it had a shape โ€”
/// "radio-specific figures such as RSSI belong on the management plane" โ€” and
/// then never built the other side of it (#49).
///
/// **Every field is `Option`, and that is load-bearing twice over.** A device
/// that cannot answer says `None` rather than zero, because a zeroed counter is
/// a claim and absence is not. And several implementors in this workspace are
/// decorators wrapping another `Medium`; a decorator that forgets to forward
/// this method inherits the default, whose every field is `None` โ€” the same
/// answer as "I do not know", rather than a confident wrong number belonging to
/// the medium underneath.
///
/// `#[non_exhaustive]` because #49 lists eleven quantities and hardware will
/// suggest twenty more. As fields on one struct behind one defaulted method,
/// adding `signal.rssi_dbm` later touches the backend that fills it and the
/// publisher that reads it โ€” as methods, each would be an eight-implementor
/// event for ever.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Report {
    /// How long ago this snapshot was taken.
    ///
    /// [`Device::report`] is sync, so a backend cannot do I/O in it and
    /// must answer from a cache. A cache with no age is a lie the moment the
    /// modem stops answering, which is exactly when an operator is reading it โ€”
    /// so the age rides along, and a report older than a consumer's tolerance is
    /// published as absent rather than as current.
    pub age_ms: Option<u64>,

    /// Cumulative channel occupancy, in milliseconds.
    ///
    /// What the medium has actually spent on the air. On a service billed in
    /// airtime this is the bill; `lease-tuning-in-a-cell.md` is the measurement
    /// that made the distinction between this and a message count matter.
    pub time_on_air_ms: Option<u64>,

    /// Transmissions made only because an earlier attempt was lost.
    ///
    /// The medium's own ARQ, which `rf-arq-requirement.md` makes a hardware
    /// selection requirement. Counted by every simulator in the tree today and
    /// reachable through none of them.
    pub retransmits: Option<u64>,

    /// Slot bytes paid for and not used.
    ///
    /// A per-message service charges for the whole slot; M2 measured 9.4%
    /// utilisation at the defaults. This is the same figure from the medium's
    /// side, for a deployment rather than for a measurement.
    pub bytes_wasted: Option<u64>,

    /// Frames the medium received and could not accept: FIFO overrun,
    /// collision, CRC or header failure.
    ///
    /// **Distinct from [`Metrics::dropped`]**, which is accepted-then-lost on
    /// *transmit*. #49 describes these as conflated; they are not โ€” no shipped
    /// medium puts receive-side errors into `dropped` โ€” but they are counted
    /// (`sim.rs`'s `lost_attempts`, `cell.rs`'s `collisions` and `overruns`) and
    /// have had no way out of the crate at all.
    pub rx_errors: Option<u64>,

    /// Whether the medium may transmit now, and how long until it may.
    pub duty_cycle: Option<DutyCycle>,

    /// Received signal strength, on the device's own 0โ€“5 scale.
    ///
    /// **Bars, not dBm, and the distinction is the point.** An Iridium ISU
    /// answers `AT+CSQF` with an integer 0โ€“5 and has no dBm to give; an
    /// SX1262 reads a dBm out of a packet-status register and has no bars.
    /// A field spelled `rssi_dbm` would force one of them to invent a number,
    /// which is the failure `Report`'s all-`Option` shape exists to
    /// avoid โ€” a device says what it knows and stays quiet about the rest. A
    /// dBm field arrives with the backend that measures one (#49, #76).
    pub signal_bars: Option<u8>,

    // --- The IP-bearer vocabulary (#123). Names carry no unit suffix: the
    // registry's `unit` is where a unit lives, and a name-and-field pair is
    // two places to drift. Fixed-point, because this type is `Copy + Eq`:
    // milli-units cover RSRQ's and SNR's half-dB steps exactly.
    /// Received signal strength, milli-dBm (ModemManager `Modem.Signal`,
    /// an SX1262's packet status).
    pub rssi: Option<i32>,
    /// Reference signal received power, milli-dBm (LTE, NR).
    pub rsrp: Option<i32>,
    /// Reference signal received quality, milli-dB.
    pub rsrq: Option<i32>,
    /// Signal-to-noise ratio, milli-dB.
    pub snr: Option<i32>,
    /// Error rate, milli-percent.
    pub error_rate: Option<i32>,
    /// Current receive data rate, bit/s (DLEP, RFC 8175 ยง13 โ€” session level;
    /// per-destination metrics are not device-level and are not here).
    pub rx_rate: Option<u64>,
    /// Current transmit data rate, bit/s.
    pub tx_rate: Option<u64>,
    /// Maximum receive data rate, bit/s.
    pub rx_max_rate: Option<u64>,
    /// Maximum transmit data rate, bit/s.
    pub tx_max_rate: Option<u64>,
    /// Latency, microseconds.
    pub latency: Option<u64>,
    /// Resources available on the link, milli-percent.
    pub resources: Option<i32>,
    /// Relative receive link quality, milli-percent.
    pub rx_quality: Option<i32>,
    /// Relative transmit link quality, milli-percent.
    pub tx_quality: Option<i32>,
    /// Network registration, for a bearer that registers with one.
    pub registration: Option<Registration>,
    /// The access technology the bearer is on.
    pub access_technology: Option<AccessTechnology>,
}

impl Report {
    /// An empty report โ€” the same thing [`Device::report`]'s default
    /// returns, and the starting point for a backend that fills some of it.
    ///
    /// The setters below take and return `self` so a backend names only what it
    /// knows: `Report::new().retransmits(n).rx_errors(m)`. That shape is
    /// what makes `#[non_exhaustive]` free rather than annoying โ€” this type is
    /// implemented from *outside* this crate, so a struct literal would make
    /// every new field a breaking change, which is exactly the churn #49's
    /// eleven-and-counting quantities would cause.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// How old this snapshot is. See [`Report::age_ms`].
    #[must_use]
    pub fn age_ms(mut self, ms: u64) -> Self {
        self.age_ms = Some(ms);
        self
    }

    /// Cumulative channel occupancy.
    #[must_use]
    pub fn time_on_air_ms(mut self, ms: u64) -> Self {
        self.time_on_air_ms = Some(ms);
        self
    }

    /// Transmissions made only because an earlier attempt was lost.
    #[must_use]
    pub fn retransmits(mut self, n: u64) -> Self {
        self.retransmits = Some(n);
        self
    }

    /// Slot bytes paid for and not used.
    #[must_use]
    pub fn bytes_wasted(mut self, n: u64) -> Self {
        self.bytes_wasted = Some(n);
        self
    }

    /// Frames received and not accepted.
    #[must_use]
    pub fn rx_errors(mut self, n: u64) -> Self {
        self.rx_errors = Some(n);
        self
    }

    /// Whether the medium may transmit now.
    #[must_use]
    pub fn duty_cycle(mut self, duty: DutyCycle) -> Self {
        self.duty_cycle = Some(duty);
        self
    }

    /// Signal strength on the device's own 0โ€“5 scale.
    #[must_use]
    pub fn signal_bars(mut self, bars: u8) -> Self {
        self.signal_bars = Some(bars);
        self
    }

    /// Received signal strength, milli-dBm.
    #[must_use]
    pub fn rssi(mut self, milli_dbm: i32) -> Self {
        self.rssi = Some(milli_dbm);
        self
    }

    /// Reference signal received power, milli-dBm.
    #[must_use]
    pub fn rsrp(mut self, milli_dbm: i32) -> Self {
        self.rsrp = Some(milli_dbm);
        self
    }

    /// Reference signal received quality, milli-dB.
    #[must_use]
    pub fn rsrq(mut self, milli_db: i32) -> Self {
        self.rsrq = Some(milli_db);
        self
    }

    /// Signal-to-noise ratio, milli-dB.
    #[must_use]
    pub fn snr(mut self, milli_db: i32) -> Self {
        self.snr = Some(milli_db);
        self
    }

    /// Error rate, milli-percent.
    #[must_use]
    pub fn error_rate(mut self, milli_percent: i32) -> Self {
        self.error_rate = Some(milli_percent);
        self
    }

    /// Current receive data rate, bit/s.
    #[must_use]
    pub fn rx_rate(mut self, bps: u64) -> Self {
        self.rx_rate = Some(bps);
        self
    }

    /// Current transmit data rate, bit/s.
    #[must_use]
    pub fn tx_rate(mut self, bps: u64) -> Self {
        self.tx_rate = Some(bps);
        self
    }

    /// Maximum receive data rate, bit/s.
    #[must_use]
    pub fn rx_max_rate(mut self, bps: u64) -> Self {
        self.rx_max_rate = Some(bps);
        self
    }

    /// Maximum transmit data rate, bit/s.
    #[must_use]
    pub fn tx_max_rate(mut self, bps: u64) -> Self {
        self.tx_max_rate = Some(bps);
        self
    }

    /// Latency, microseconds.
    #[must_use]
    pub fn latency(mut self, us: u64) -> Self {
        self.latency = Some(us);
        self
    }

    /// Resources available on the link, milli-percent.
    #[must_use]
    pub fn resources(mut self, milli_percent: i32) -> Self {
        self.resources = Some(milli_percent);
        self
    }

    /// Relative receive link quality, milli-percent.
    #[must_use]
    pub fn rx_quality(mut self, milli_percent: i32) -> Self {
        self.rx_quality = Some(milli_percent);
        self
    }

    /// Relative transmit link quality, milli-percent.
    #[must_use]
    pub fn tx_quality(mut self, milli_percent: i32) -> Self {
        self.tx_quality = Some(milli_percent);
        self
    }

    /// Network registration.
    #[must_use]
    pub fn registration(mut self, r: Registration) -> Self {
        self.registration = Some(r);
        self
    }

    /// The access technology the bearer is on.
    #[must_use]
    pub fn access_technology(mut self, t: AccessTechnology) -> Self {
        self.access_technology = Some(t);
        self
    }
}

/// Where a bearer stands with its network (ModemManager's 3GPP registration
/// states; #123). A device that registers with nothing โ€” a point-to-point
/// radio โ€” reports none.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Registration {
    /// Not registered, not searching.
    Idle,
    /// Registered on the home network.
    Home,
    /// Searching for a network.
    Searching,
    /// Registration denied.
    Denied,
    /// Registered, roaming.
    Roaming,
    /// The device cannot say.
    Unknown,
}

impl Registration {
    /// The wire spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Home => "home",
            Self::Searching => "searching",
            Self::Denied => "denied",
            Self::Roaming => "roaming",
            Self::Unknown => "unknown",
        }
    }
}

impl fmt::Display for Registration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The access technology a bearer is on (#123). Closed and
/// `#[non_exhaustive]`: a value is added when a device produces it, and a
/// reader that sees one it does not know treats it as text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AccessTechnology {
    Gsm,
    Gprs,
    Edge,
    Umts,
    Hspa,
    Lte,
    /// LTE-M (Cat-M1), ModemManager's `lte-cat-m`.
    LteM,
    /// NB-IoT, ModemManager's `lte-nb-iot`.
    NbIot,
    Nr5g,
    /// Iridium's own air interface โ€” an SBD terminal.
    Iridium,
}

impl AccessTechnology {
    /// The wire spelling: ModemManager's, lowercase.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Gsm => "gsm",
            Self::Gprs => "gprs",
            Self::Edge => "edge",
            Self::Umts => "umts",
            Self::Hspa => "hspa",
            Self::Lte => "lte",
            Self::LteM => "lte-cat-m",
            Self::NbIot => "lte-nb-iot",
            Self::Nr5g => "5gnr",
            Self::Iridium => "iridium",
        }
    }
}

impl fmt::Display for AccessTechnology {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Why a medium is not transmitting, when the answer is "not yet".
///
/// The case #49 calls sharpest, and the reason it is in v1 rather than deferred
/// with the rest: a compliant EU868 backend must **block** in `send` for up to
/// ~99 s, and an operator watching `queue_depth` climb cannot tell
/// "duty-cycle limited" from "radio dead". `SimMedium::slide_to_contact` already
/// blocks for exactly this reason and `ContactWindow::wait_at` already computes
/// the number, so this is a producer that exists rather than a keyspace row
/// waiting for hardware.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct DutyCycle {
    /// Whether the medium would take an SDU right now.
    pub available: bool,
    /// Milliseconds until it would, when it would not.
    ///
    /// Zero while [`available`](Self::available) is false means the medium is
    /// blocked and does not know for how long, which is a different answer from
    /// "blocked for 0 ms" and a real state for a device that can say it is busy
    /// without saying when it will not be.
    pub next_available_in_ms: u64,
}

impl DutyCycle {
    /// The medium would take an SDU now.
    #[must_use]
    pub fn ready() -> Self {
        Self {
            available: true,
            next_available_in_ms: 0,
        }
    }

    /// The medium would not, and this is how long until it would.
    ///
    /// Two named constructors rather than one taking `(bool, u64)`, because the
    /// two states are what a caller is choosing between and a boolean argument
    /// at a call site says nothing about which way round it goes.
    #[must_use]
    pub fn wait_ms(ms: u64) -> Self {
        Self {
            available: false,
            next_available_in_ms: ms,
        }
    }
}

/// Something the medium wants to say when nobody is calling [`Medium::send`].
///
/// The gap #51 names: every `DeviceError` is the return value of a data-path
/// call, so a radio that loses registration, overheats, or drops off the bus is
/// silent until the next transmission โ€” which on a store-and-forward link may
/// be an hour away, and on a dead one is never.
///
/// A plain struct rather than a channel, and that is the whole reason this
/// works. `modem-device` has three dependencies โ€” `async-trait`, `thiserror`,
/// optional `serde` โ€” and **no tokio**. Putting a `watch::Receiver` or a
/// `broadcast::Receiver` on the trait would drag a runtime into a crate whose
/// entire job is to be the seam, to obtain a channel type. An `async fn`
/// mirroring [`Medium::recv`] needs nothing, is dyn-compatible through the
/// `async-trait` already here, and has a default whose meaning is exactly
/// "this medium never says anything".
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DeviceEvent {
    /// The lane it concerns, if it concerns one.
    ///
    /// `None` for a device-wide condition โ€” registration lost, over
    /// temperature, duty-cycle budget exhausted โ€” which is most of them.
    pub lane: Option<LaneKey>,
    /// Whether this is the medium becoming unhappy or becoming happy again.
    ///
    /// Edge-triggered by contract. A backend that repeated `Raised` while a
    /// condition persisted would produce a stream no `rate` declaration could
    /// honestly cover, and the consumer's job is to publish these, not to
    /// deduplicate somebody else's.
    pub edge: Edge,
    /// The device's own words.
    ///
    /// Carried verbatim to the management plane, which is the point: until #51
    /// a `DeviceError::Device(String)` reached a `warn!` and was discarded, so
    /// `+CME ERROR 3` โ€” the one thing that says what is actually wrong โ€” never
    /// left the process.
    pub detail: String,
}

impl DeviceEvent {
    /// A condition beginning.
    #[must_use]
    pub fn raised(detail: impl Into<String>) -> Self {
        Self {
            lane: None,
            edge: Edge::Raised,
            detail: detail.into(),
        }
    }

    /// A condition ending.
    #[must_use]
    pub fn cleared(detail: impl Into<String>) -> Self {
        Self {
            lane: None,
            edge: Edge::Cleared,
            detail: detail.into(),
        }
    }

    /// Attribute this event to one lane.
    #[must_use]
    pub fn on_lane(mut self, lane: LaneKey) -> Self {
        self.lane = Some(lane);
        self
    }
}

/// Which way a condition just went.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Edge {
    /// It started.
    Raised,
    /// It stopped.
    Cleared,
}

/// Why a medium refused or failed an SDU.
///
/// `#[non_exhaustive]`: both consumers on the data path already match with a
/// catch-all (`sched.rs`'s retry arm, `lanes.rs`'s receive loop), so this costs
/// nothing today and leaves room for the variants a real device will need. The
/// alternative is discovering later that adding one is a breaking change to a
/// crate whose whole job is to be implemented from outside.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DeviceError {
    /// The SDU is larger than the medium can carry.
    ///
    /// Invariant I4: the driver never splits a batch to make it fit. An SDU that
    /// does not fit is a configuration error โ€” Zenoh's `batch_size` was set
    /// above what this medium can carry โ€” and it is reported, loudly, as one.
    #[error(
        "sdu of {got} bytes exceeds the medium's tx_max_sdu of {max}: \
         lower zenoh's batch_size to at most {} (architecture I4, ยง4.5)", *max as usize + 2
    )]
    SduTooLarge { got: usize, max: u16 },

    /// No such lane is configured on this medium.
    #[error("unknown lane {0} (architecture ยง4.1)")]
    UnknownLane(LaneKey),

    /// The medium is up but cannot transmit right now, and says so rather than
    /// waiting.
    ///
    /// For hardware whose API refuses instead of blocking โ€” a half-duplex
    /// medium mid-reception, on a device that reports rather than queues.
    ///
    /// **A contact window is still not an instance of this.** A satellite
    /// terminal out of coverage *blocks*, because that is what a
    /// store-and-forward service does. See
    /// `docs/measurements/contact-windows.md`.
    ///
    /// What returning it costs, exactly: on a **reliable** lane the scheduler
    /// holds the batch and offers it again with a backoff, for as long as the
    /// medium keeps refusing (#40) โ€” so this trades a stall for a delay, never
    /// for lost data, and the stall reaches Zenoh as ordinary backpressure. On
    /// a **best-effort** lane the batch is dropped and counted, which is what
    /// best-effort means. Either way the refusal appears on
    /// `DriverMetrics::tx_failed`.
    ///
    /// Earlier versions of this note warned that the scheduler dropped the
    /// batch on both lane classes. It did, silently, and that was #40.
    #[error("medium cannot transmit at present")]
    TxUnavailable,

    /// The medium is gone: closed, unplugged, or failed.
    #[error("medium is closed")]
    Closed,

    /// Anything hardware-specific, in the backend's own words.
    ///
    /// Handled exactly as [`DeviceError::TxUnavailable`]: held and retried on
    /// a reliable lane, dropped and counted on a best-effort one. Return it
    /// for a failure the medium expects to survive โ€” `+CME ERROR`, an SPI
    /// timeout, an MO status of "no network". A device that is *gone* should
    /// say [`DeviceError::Closed`] instead, which stops the driver rather
    /// than retrying into it.
    ///
    /// The string reaches the management plane verbatim. `sched::transmit`
    /// raises a [`DeviceEvent`] carrying it, the driver's event stream carries
    /// that, and it is published as `events/modem/device_fault/<ulid>` with the
    /// text in `detail` (#51). Write it for an operator, not for a log grep:
    /// it is the only place a device speaks in its own words.
    #[error("medium error: {0}")]
    Device(String),
}

/// RFC 2863's operational status โ€” the states something here produces.
///
/// `dormant`, `testing` and `lowerLayerDown` are not declared, deliberately: a
/// state is added when a device produces it. Linux's operstate documentation
/// defines dormant as "L1 up, but waiting for an external event", and a
/// coverage gap is L1 down โ€” so a terminal out of coverage is [`Down`] with
/// [`OperStatus::recoverable`] set, never dormant (#121).
///
/// [`Down`]: OperState::Down
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum OperState {
    /// Passing traffic.
    Up,
    /// Not passing traffic; [`OperStatus::recoverable`] says whether it
    /// expects to again without help.
    Down,
    /// The device node is gone: a serial port unplugged, an interface
    /// removed. Distinct from `Down` because no amount of waiting fixes it.
    NotPresent,
    /// The device has not said, and nothing else can tell. The default.
    Unknown,
}

impl OperState {
    /// The wire spelling: RFC 2863's own, so `notPresent` keeps its case.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
            Self::NotPresent => "notPresent",
            Self::Unknown => "unknown",
        }
    }
}

impl fmt::Display for OperState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// RFC 2863's administrative status: what was asked of the device.
///
/// Exists so that radio silence is expressible and distinguishable from a
/// failure โ€” an operator who ordered EMCON reads `admin: down, status: down`
/// and knows nothing broke. Ordering it is a hot configuration group (#126).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AdminState {
    /// Asked to carry traffic.
    #[default]
    Up,
    /// Asked to be silent.
    Down,
}

impl AdminState {
    /// The wire spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Up => "up",
            Self::Down => "down",
        }
    }
}

impl fmt::Display for AdminState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// What a device says about whether it is working (#121).
///
/// Sync and cached, like [`Report`]: the management plane polls it, and a
/// device that needs I/O to answer keeps a snapshot. Every field is a fact
/// the device has; a device that has none returns [`OperStatus::unknown`],
/// which is the default and is honest. It cannot be derived from
/// [`DeviceEvent`], whose detail is free text.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct OperStatus {
    /// The operational status.
    pub status: OperState,
    /// The administrative status.
    pub admin: AdminState,
    /// Why, in the device's words, when it is not up.
    pub reason: Option<String>,
    /// Whether the device expects to come back on its own. `false` is the
    /// one value that means something โ€” a dead medium โ€” and is what a
    /// supervisor reads before deciding to restart (#96). A coverage gap is
    /// `true`; so are `up` and `unknown`, because neither is a reason to
    /// restart.
    pub recoverable: bool,
    /// When the status last changed, on the device's clock.
    pub since: Option<std::time::SystemTime>,
}

impl Default for OperStatus {
    fn default() -> Self {
        Self::unknown()
    }
}

impl OperStatus {
    fn with(status: OperState, reason: Option<String>, recoverable: bool) -> Self {
        Self {
            status,
            admin: AdminState::Up,
            reason,
            recoverable,
            since: None,
        }
    }

    /// The device has not said. The default.
    #[must_use]
    pub fn unknown() -> Self {
        Self::with(OperState::Unknown, None, true)
    }

    /// Passing traffic.
    #[must_use]
    pub fn up() -> Self {
        Self::with(OperState::Up, None, true)
    }

    /// Not passing traffic, with the reason and whether it expects to again.
    #[must_use]
    pub fn down(reason: impl Into<String>, recoverable: bool) -> Self {
        Self::with(OperState::Down, Some(reason.into()), recoverable)
    }

    /// The device node is gone.
    #[must_use]
    pub fn not_present(reason: impl Into<String>) -> Self {
        Self::with(OperState::NotPresent, Some(reason.into()), false)
    }

    /// When this status began, on the device's clock.
    #[must_use]
    pub fn since(mut self, at: std::time::SystemTime) -> Self {
        self.since = Some(at);
        self
    }

    /// With the administrative status.
    #[must_use]
    pub fn admin(mut self, admin: AdminState) -> Self {
        self.admin = admin;
        self
    }

    /// Whether the device is passing traffic.
    #[must_use]
    pub fn is_up(&self) -> bool {
        self.status == OperState::Up
    }
}

/// What a device is, with RFC 8348's field names (#122).
///
/// Every field optional and the type `#[non_exhaustive]`: a device says what
/// it knows, and a field arrives when a device produces it. **Subscriber
/// identifiers never appear here** โ€” an IMSI, an ICCID, an MSISDN identifies
/// a person's subscription, not equipment (invariant I5). The equipment
/// identifier does, because the gateway keys its endpoints by it; it is an
/// addressing identifier, never a proof of identity.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Identity {
    /// Who made it.
    pub mfg_name: Option<String>,
    /// What it is, in the maker's words.
    pub model_name: Option<String>,
    /// The maker's serial number.
    pub serial_num: Option<String>,
    /// Hardware revision.
    pub hardware_rev: Option<String>,
    /// Firmware revision.
    pub firmware_rev: Option<String>,
    /// Software revision, where it is distinct from the firmware's.
    pub software_rev: Option<String>,
    /// The bearer's equipment identifier โ€” an IMEI.
    pub imei: Option<String>,
}

impl Identity {
    /// A device that knows nothing about itself.
    #[must_use]
    pub fn unknown() -> Self {
        Self::default()
    }

    /// Whether the device said anything at all.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        *self == Self::default()
    }

    fn set(mut self, field: fn(&mut Self) -> &mut Option<String>, v: impl Into<String>) -> Self {
        *field(&mut self) = Some(v.into());
        self
    }

    /// With the maker's name.
    #[must_use]
    pub fn mfg_name(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.mfg_name, v)
    }

    /// With the model name.
    #[must_use]
    pub fn model_name(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.model_name, v)
    }

    /// With the serial number.
    #[must_use]
    pub fn serial_num(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.serial_num, v)
    }

    /// With the hardware revision.
    #[must_use]
    pub fn hardware_rev(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.hardware_rev, v)
    }

    /// With the firmware revision.
    #[must_use]
    pub fn firmware_rev(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.firmware_rev, v)
    }

    /// With the software revision.
    #[must_use]
    pub fn software_rev(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.software_rev, v)
    }

    /// With the equipment identifier.
    #[must_use]
    pub fn imei(self, v: impl Into<String>) -> Self {
        self.set(|i| &mut i.imei, v)
    }
}

/// A device: anything the driver serves on the management plane.
///
/// The core and introspection planes of `docs/design/device-planes.md`, and
/// nothing about how bytes move โ€” that is [`Medium`] for an SDU device, and
/// a netdev's is the kernel's. Every method is defaulted, because a device
/// that says nothing about itself is a legitimate device and every simulator
/// was one until #49; the split from the old `Backend` (#117) changed no
/// behaviour, only which trait a method belongs to.
#[async_trait::async_trait]
pub trait Device: Send + Sync {
    /// What this device says about itself.
    ///
    /// Defaulted to "nothing", because a medium that knows nothing about its
    /// own condition is a legitimate medium and every simulator was one until
    /// #49. Sync rather than `async` **on purpose**: the driver calls this from
    /// `mgmt/telemetry.rs`'s five-second publish loop, and an `async` signature
    /// would invite a backend to put an AT-command round trip there. A device
    /// that needs I/O to answer keeps atomics and a cached snapshot, and says
    /// how old the snapshot is through [`Report::age_ms`].
    ///
    /// **Decorators must forward this.** Several implementors in this workspace
    /// wrap another `Medium`, and one that inherits the default answers `None` to
    /// everything โ€” which reads as "unknown" rather than as a wrong number, but
    /// is still a lie about the medium underneath. The conformance kit's
    /// [`conformance::medium_decorator_forwards`] is what catches it, and it
    /// covers the whole trait rather than this method alone โ€” which is new: the
    /// check this comment named for three issues asserted `report` and
    /// nothing else, and `close`, `configure_lanes` and `next_event` had gone
    /// unforwarded behind the claim (#50, #51, #52).
    fn report(&self) -> Report {
        Report::default()
    }

    /// Whether this device is working, as RFC 2863 has it (#121).
    ///
    /// Sync and cached, for [`report`](Device::report)'s reason. Defaulted to
    /// [`OperStatus::unknown`]: a device that cannot tell says so, and the
    /// plane publishes that rather than a guess. A medium that has *failed*
    /// need not report it here โ€” the driver knows, and overlays `down` with
    /// `recoverable: false` on whatever the device says. What a device does
    /// know that the driver cannot is the recoverable kind of down: a
    /// coverage gap, a closed contact window, a carrier that dropped.
    ///
    /// **Decorators must forward this**, like everything else here.
    fn oper(&self) -> OperStatus {
        OperStatus::default()
    }

    /// What this device is (#122): RFC 8348's fields and the bearer's
    /// equipment identifier, as much of it as the device knows.
    ///
    /// Sync and cached, for [`report`](Device::report)'s reason: a modem
    /// reads its model, firmware and IMEI once, at open, and answers from
    /// that. Defaulted to [`Identity::unknown`], which is a legitimate
    /// answer โ€” the management plane publishes it as a document with only
    /// the device's name, and a reader knows the device was asked. The plane
    /// polls it and raises `identity_change` when it differs: a terminal
    /// swapped, or its firmware updated, under a running driver.
    ///
    /// **Never a subscriber identifier** (I5). **Decorators must forward
    /// this**, like everything else here.
    fn identity(&self) -> Identity {
        Identity::default()
    }

    /// Wait for the next thing the medium wants to say.
    ///
    /// Mirrors [`recv`](Medium::recv) deliberately: a driver drains this in
    /// its own task, so a backend may block here for as long as it likes and a
    /// medium with nothing to report simply never resolves. The default is
    /// exactly that, which is why every medium in this workspace needs no
    /// implementation.
    ///
    /// **Edge-triggered.** One event when a condition starts and one when it
    /// stops, not a repeat while it persists โ€” see [`Edge`]. A backend that
    /// repeated itself would produce a rate the `events` keyspace cannot
    /// honestly declare, and the driver deduplicating on its behalf would be
    /// guessing at which repeats meant something.
    async fn next_event(&self) -> Result<DeviceEvent, DeviceError> {
        std::future::pending().await
    }

    /// Stop, cleanly.
    ///
    /// Called once, on the way down, after every lane task has been aborted and
    /// before the process exits. The default does nothing, because an
    /// in-process medium has nothing to release.
    ///
    /// **A real device does (#50).** Teardown used to be: `Driver::shutdown`
    /// aborts its tasks, the `Arc<dyn Medium>` is dropped, and anything a
    /// radio needed to be told happened in `Drop` with no `async` available. A
    /// radio left keyed, or a modem left in binary-write mode, is the
    /// observable consequence โ€” and neither is visible while a simulator is the
    /// only implementor, because a simulator never needs telling.
    ///
    /// Errors are reported and not propagated: the process is going away, and
    /// there is nothing a caller could do differently. Say what failed.
    async fn close(&self) -> Result<(), DeviceError> {
        Ok(())
    }

    /// This device's configuration plane, if it has one (#125).
    ///
    /// `None` is the honest default: a device with nothing to configure
    /// declares no resource, and the management plane serves none for it.
    fn configuration(&self) -> Option<&dyn Configure> {
        None
    }

    /// The operator actions this device offers (#129): explicit, costed,
    /// never scheduled โ€” an operator deciding, once, now. `None` for a
    /// device with none. There is no `reset` and there will not be one
    /// (architecture ยง4.11): recovery is a restart, of the device (the
    /// driver's own `reopen` action) or of the daemon (#96).
    fn actions(&self) -> Option<&dyn Actions> {
        None
    }

    /// What this device guarantees about the bytes it carries (I6), as
    /// properties. `None`, the default, is a device that provides nothing,
    /// which every medium in this workspace is: the management plane
    /// publishes that as `provider: none` with an empty guarantee set, never
    /// as `encrypted: false`. A layer that seals SDUs, or a radio that
    /// encrypts below the driver, answers with what it provides and only
    /// that. **Decorators must forward this**, like everything else here.
    fn security(&self) -> Option<SecurityProperties> {
        None
    }

    /// Counters beyond the fixed vocabulary (#157): a layer's refusals, a
    /// module's frames. Empty by default. Sync and cached, like
    /// [`report`](Device::report); the management plane publishes those the
    /// registry declares, gated by scope. **Decorators must forward this.**
    fn counters(&self) -> Vec<Counter> {
        Vec::new()
    }
}

/// A physical or simulated medium: the SDU data plane of a [`Device`].
///
/// Implementations own everything below the driver: framing on the air, vendor
/// APIs, contact scheduling, radio state. They own nothing above it โ€” no
/// routing, no retransmission the hardware does not already provide, and no
/// knowledge of what the bytes mean. `Medium: Device`, so an `Arc<dyn Medium>`
/// upcasts to `Arc<dyn Device>` and the management plane serves it like any
/// other device.
#[async_trait::async_trait]
pub trait Medium: Device {
    /// What this medium can carry. Read once at startup to size lanes.
    fn capabilities(&self) -> Capabilities;

    /// Transmit one SDU on one lane.
    ///
    /// Returns once the medium has taken ownership โ€” which is *not* a delivery
    /// receipt. Implementations must apply backpressure by not returning, rather
    /// than by accepting into an unbounded queue: invariant I3 exists because a
    /// hidden backlog between Zenoh's congestion control and the radio defeats
    /// the whole design.
    async fn send(&self, lane: &LaneKey, sdu: &[u8]) -> Result<(), DeviceError>;

    /// Wait for the next SDU the medium delivers.
    ///
    /// Returns the lane it arrived on, so the driver can route it back to the
    /// matching socket without inspecting the payload.
    async fn recv(&self) -> Result<(LaneKey, Sdu), DeviceError>;

    /// A snapshot of this medium's counters.
    fn metrics(&self) -> Metrics;

    /// Tell the medium which lanes this driver will serve.
    ///
    /// Called once, from `Driver::start`, before anything moves. The default
    /// does nothing, because a medium that was given its topology at
    /// construction has nothing to learn โ€” which is every medium in this
    /// workspace, and was every medium there was when the trait was written.
    ///
    /// **A real backend needs this and had no way to get it (#52).** `recv`
    /// returns a `LaneKey`, and hardware receives bytes with no lane in them:
    /// the endpoint can be recovered from on-air framing, but `reliable` and
    /// `rank` have to be *synthesised*, and nothing told the backend what
    /// combinations exist. Guess wrong and the driver drops the batch on a lane
    /// it does not have โ€” silently until #52's first commit, and counted as
    /// `rx_unroutable_total` since.
    ///
    /// The driver is the authority here: these are the lanes it resolved from
    /// its own config and will actually serve, not the lanes a config file
    /// mentioned. Returning an error refuses startup, which is the right
    /// response to a medium that cannot serve what it is being asked for.
    async fn configure_lanes(&self, lanes: &[LaneKey]) -> Result<(), DeviceError> {
        let _ = lanes;
        Ok(())
    }
}

/// A device whose data plane is the kernel's: a network interface that Zenoh
/// reaches over an ordinary TCP link bound to it (#118, #130).
///
/// Nothing here moves a byte โ€” that is the point. The driver serves such a
/// device on the management plane exactly as it serves a [`Medium`], and the
/// lanes, the scheduler and the framing never see it: `Netdev: Device`, not
/// `Netdev: Medium`. The kernel's view (statistics, the presence epoch) is
/// this trait's; what the vendor's control API knows (signal, registration,
/// data rates) arrives through [`Device::report`], and an adapter that wraps
/// the kernel view with a vendor's must forward both.
pub trait Netdev: Device {
    /// The interface name, as the kernel spells it: `wwan0`, `ppp0`.
    fn interface(&self) -> &str;

    /// The interface's counters, as the kernel keeps them (#130): sync and
    /// cached, like [`Device::report`]. A counter the kernel does not keep
    /// is absent, never zero.
    fn statistics(&self) -> NetdevStats {
        NetdevStats::default()
    }

    /// The presence epoch (zenkey RFC 04 ยง5, v1.39): moves when the
    /// interface is re-enumerated (its `ifindex` changed) or a counter is
    /// observed to decrease โ€” what a USB modem re-enumerating looks like โ€”
    /// and the management plane cycles `device/{device}/alive` when it does,
    /// which is the one reset the registry sanctions for the counters under
    /// this device. `0` until it moves.
    fn epoch(&self) -> u64 {
        0
    }

    /// The neighbours the device's radio reports it can reach (#137): a
    /// DLEP radio's destinations. `None`, the default, is a device that has
    /// no such notion, which is every netdev that is not a radio with a
    /// neighbour table; `Some` of an empty list is one that has the notion
    /// and no neighbour now. Sync and cached, like
    /// [`statistics`](Netdev::statistics).
    ///
    /// **Not endpoints** (architecture ยง4.6): an endpoint is a remote the
    /// operator configured lanes toward; a destination is what a radio
    /// discovered, and comes and goes on its own.
    fn destinations(&self) -> Option<Vec<Destination>> {
        None
    }
}

/// One neighbour a netdev's radio can reach (#137), as the radio reports
/// it. The metrics are the radio's for the link toward this neighbour, in
/// the units [`Report`] uses for the same quantities, and absent where the
/// radio gives only session-wide ones.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Destination {
    /// How the radio names it, spelled as a key chunk: for DLEP its MAC
    /// address, lowercase hex separated by hyphens.
    pub id: String,
    /// The addresses the radio says it has.
    pub addresses: Vec<std::net::IpAddr>,
    /// Current receive data rate toward it, bit/s.
    pub rx_rate: Option<u64>,
    /// Current transmit data rate, bit/s.
    pub tx_rate: Option<u64>,
    /// Maximum receive data rate, bit/s.
    pub rx_max_rate: Option<u64>,
    /// Maximum transmit data rate, bit/s.
    pub tx_max_rate: Option<u64>,
    /// Latency, microseconds.
    pub latency: Option<u64>,
    /// Resources available toward it, milli-percent.
    pub resources: Option<i32>,
    /// Relative receive link quality, milli-percent.
    pub rx_quality: Option<i32>,
    /// Relative transmit link quality, milli-percent.
    pub tx_quality: Option<i32>,
}

impl Destination {
    /// A destination known by `id` and nothing else yet. The fields are
    /// public and set directly; this type is `#[non_exhaustive]` so that a
    /// new metric is not a breaking change.
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            ..Self::default()
        }
    }

    /// With these addresses.
    #[must_use]
    pub fn addresses(mut self, addresses: Vec<std::net::IpAddr>) -> Self {
        self.addresses = addresses;
        self
    }
}

/// A network interface's counters (#130), with RFC 8343's names where Linux
/// keeps exactly that counter and nothing else.
///
/// `in_pkts` and `out_pkts` are **not** RFC 8343's: the RFC splits packets by
/// unicast, multicast and broadcast, Linux's `rx_packets` includes multicast,
/// and Linux keeps no broadcast counter. They are here because an operator
/// asks for them; the registry says what they are.
///
/// `#[non_exhaustive]` since 0.3; built with [`NetdevStats::new`] and the
/// setters, or `Default`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct NetdevStats {
    /// `rx_bytes` โ€” RFC 8343 `in-octets`.
    pub in_octets: Option<u64>,
    /// `tx_bytes` โ€” RFC 8343 `out-octets`.
    pub out_octets: Option<u64>,
    /// `rx_errors` โ€” RFC 8343 `in-errors`.
    pub in_errors: Option<u64>,
    /// `tx_errors` โ€” RFC 8343 `out-errors`.
    pub out_errors: Option<u64>,
    /// `rx_dropped` โ€” RFC 8343 `in-discards`.
    pub in_discards: Option<u64>,
    /// `tx_dropped` โ€” RFC 8343 `out-discards`.
    pub out_discards: Option<u64>,
    /// `multicast` โ€” RFC 8343 `in-multicast-pkts`.
    pub in_multicast_pkts: Option<u64>,
    /// `rx_packets` โ€” not RFC 8343: unicast and multicast together.
    pub in_pkts: Option<u64>,
    /// `tx_packets` โ€” not RFC 8343.
    pub out_pkts: Option<u64>,
    /// Bytes queued in the interface's queue discipline now, not yet sent
    /// (#136). Not a sysfs counter: read over netlink, and only from the
    /// kernel's own interface. The queue an operator watches form when a
    /// bearer is slower than what is offered to it.
    pub qdisc_backlog_bytes: Option<u64>,
    /// Packets queued in the queue discipline now (#136).
    pub qdisc_backlog_pkts: Option<u64>,
}

macro_rules! netdev_stat_setters {
    ($($name:ident),* $(,)?) => {
        impl NetdevStats {
            /// Every counter absent.
            #[must_use]
            pub fn new() -> Self {
                Self::default()
            }
            $(
                #[doc = concat!("With `", stringify!($name), "`.")]
                #[must_use]
                pub fn $name(mut self, n: u64) -> Self {
                    self.$name = Some(n);
                    self
                }
            )*
        }
    };
}

netdev_stat_setters!(
    in_octets,
    out_octets,
    in_errors,
    out_errors,
    in_discards,
    out_discards,
    in_multicast_pkts,
    in_pkts,
    out_pkts,
    qdisc_backlog_bytes,
    qdisc_backlog_pkts,
);

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

    fn lane(rank: u8, reliable: bool) -> LaneKey {
        LaneKey {
            endpoint: EndpointId::new("peer-b"),
            reliable,
            rank,
        }
    }

    #[test]
    fn the_operational_states_spell_themselves_as_rfc_2863_does() {
        assert_eq!(OperState::Up.as_str(), "up");
        assert_eq!(OperState::Down.as_str(), "down");
        assert_eq!(OperState::NotPresent.as_str(), "notPresent");
        assert_eq!(OperState::Unknown.as_str(), "unknown");
        assert_eq!(AdminState::Down.to_string(), "down");
    }

    #[test]
    fn a_device_that_says_nothing_is_unknown_and_not_a_reason_to_restart() {
        let s = OperStatus::default();
        assert_eq!(s.status, OperState::Unknown);
        assert_eq!(s.admin, AdminState::Up);
        assert!(s.recoverable, "unknown is not a reason to restart");
        assert!(s.reason.is_none());
        assert!(!s.is_up());
        assert!(!OperStatus::down("dead", false).recoverable);
        assert!(OperStatus::down("no coverage", true).recoverable);
        assert!(!OperStatus::not_present("port unplugged").recoverable);
        assert!(OperStatus::up().is_up());
    }

    #[test]
    fn an_identity_says_only_what_the_device_knows() {
        assert!(Identity::unknown().is_empty());
        let id = Identity::unknown()
            .model_name("IRIDIUM 9603")
            .imei("300234060000000");
        assert!(!id.is_empty());
        assert_eq!(id.model_name.as_deref(), Some("IRIDIUM 9603"));
        assert_eq!(id.mfg_name, None, "unasked is absent, not empty");
    }

    #[test]
    fn the_vocabulary_keeps_the_report_copy_and_eq_at_fixed_point() {
        // RSRQ and SNR move in half-dB steps; milli-units hold them exactly,
        // which is what lets `Report` stay `Copy + Eq` without an `f64`.
        let r = Report::new()
            .rssi(-97_500)
            .rsrq(-10_500)
            .snr(12_000)
            .rx_rate(1_000_000)
            .latency(45_000)
            .registration(Registration::Home)
            .access_technology(AccessTechnology::Lte);
        assert_eq!(r, r, "Eq");
        let copy = r;
        assert_eq!(copy.rssi, Some(-97_500));
        assert_eq!(r.rsrp, None, "unmeasured is absent");
        assert_eq!(Registration::Home.as_str(), "home");
        assert_eq!(AccessTechnology::Nr5g.as_str(), "5gnr");
    }

    #[test]
    fn a_lane_renders_as_endpoint_reliability_and_rank() {
        assert_eq!(lane(0, true).to_string(), "peer-b/rel#0");
        assert_eq!(lane(5, false).to_string(), "peer-b/be#5");
    }

    #[test]
    fn lanes_differing_only_in_reliability_are_distinct() {
        assert_ne!(lane(0, true), lane(0, false));
    }

    #[test]
    fn capabilities_may_be_asymmetric() {
        // The SBD profile: 340 up, 270 down. Nothing here collapses them.
        let caps = Capabilities::new(340, 270, Duplex::Full, true).arq(Arq::Unbounded);
        assert_ne!(caps.tx_max_sdu, caps.rx_max_sdu);
        assert_eq!(caps.framing, None);
    }

    #[test]
    fn framing_counts_frames_and_their_survival() {
        let f = Framing::new(64, Arq::None);
        assert_eq!(f.frames_for(220), 4);
        assert_eq!(f.frames_for(64), 1);
        assert_eq!(f.frames_for(0), 1);
        let p = f.survival(0.05, 220);
        assert!((p - 0.95f64.powi(4)).abs() < 1e-12, "{p}");
        assert_eq!(Framing::new(64, Arq::Unbounded).survival(0.05, 220), 1.0);
        assert_eq!(Arq::Bounded { attempts: 3 }.to_string(), "bounded(3)");
    }

    #[test]
    fn security_properties_name_what_they_guarantee_and_nothing_else() {
        let p = SecurityProperties::new("test", Scope::Hop)
            .guarantee(Guarantee::Integrity)
            .guarantee(Guarantee::Integrity);
        assert_eq!(p.guarantees, vec![Guarantee::Integrity]);
        assert_eq!(p.principal, None);
        assert_eq!(Guarantee::AntiReplay.as_str(), "anti-replay");
        assert_eq!(Scope::Hop.as_str(), "hop");
    }

    #[test]
    fn an_oversized_sdu_names_the_batch_size_that_would_fit() {
        // The +2 is Zenoh's length prefix, which lives inside the batch buffer:
        // a batch_size of N puts N-2 bytes on the medium.
        let e = DeviceError::SduTooLarge { got: 300, max: 218 };
        assert_eq!(
            e.to_string(),
            "sdu of 300 bytes exceeds the medium's tx_max_sdu of 218: \
             lower zenoh's batch_size to at most 220 (architecture I4, ยง4.5)"
        );
    }
}