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
//! The conformance kit for a [`Layer`] (#157): synchronous, no runtime.
//!
//! A layer is a function of its state, so everything here drives it
//! directly, with a clock the kit advances by hand. The checks are what "a
//! layer never lies" comes to once the trait is written down: a round trip is
//! the identity, the overhead a layer declares is the overhead it has, a
//! layer that claims integrity refuses a changed frame and one that claims
//! anti-replay refuses a repeated one, a refusal moves a counter, a deadline
//! announced is a deadline kept and nothing is owed that was not announced,
//! a counter is scoped by the layer that keeps it, and an SDU sent on a lane
//! arrives on the matching lane.
//!
//! Two shapes. [`layer`] drives one instance both ways, for a layer whose two
//! ends are interchangeable. [`pair`] drives two instances, A encoding toward
//! B and B toward A, for a layer whose ends differ: directional keys (#158),
//! addresses (#160). `layer` is `pair` with the same instance at both ends.
//!
//! Three reference layers live here too, public because the driver's own
//! tests and its test-only `layer-overhead` feature build them: [`Identity`],
//! [`Overhead`] and [`Split`].

use std::collections::BTreeMap;
use std::time::{Duration, Instant};

use super::Failure;
use crate::layer::{Decoded, Frames, Layer, LayerError};
use crate::{Capabilities, Counter, ESTABLISHMENT_FLOOR, Guarantee, LaneKey, Sdu};

/// Hold `l` to every check, driving one instance in both directions: what
/// it encodes on `lanes[i]` it decodes on the lane below that it asked for.
pub fn layer(l: &mut dyn Layer, below: &Capabilities, lanes: &[LaneKey]) -> Vec<Failure> {
    let mut out = Vec::new();
    if lanes.is_empty() {
        out.push(Failure::new("kit", "no lanes to drive the layer on"));
        return out;
    }
    let Some(above) = capabilities_of(l, below, &mut out) else {
        return out;
    };
    let Some(lanes_below) = lanes_of(l, lanes, &mut out) else {
        return out;
    };
    let mut kit = Kit::new(below, &above);
    let ends = Ends {
        lanes_a: lanes,
        below_a: &lanes_below,
        lanes_b: lanes,
        below_b: &lanes_below,
    };
    let mut p = Pair(l, None);
    kit.round_trips(&mut p, &ends, &mut out);
    kit.overhead(p.a(), &lanes[0], &mut out);
    kit.integrity(&mut p, &ends, &mut out);
    kit.ticks(p.a(), &lanes[0], &mut out);
    kit.counters(p.a(), &mut out);
    out
}

/// Hold a pair to every check: `a` encodes on `lanes_a[i]` what `b` decodes
/// and must deliver on `lanes_b[i]`, and the other way round. The lanes each
/// end asks of the layer below are matched by position, so the two lists are
/// the same length.
pub fn pair(
    a: &mut dyn Layer,
    b: &mut dyn Layer,
    below: &Capabilities,
    lanes_a: &[LaneKey],
    lanes_b: &[LaneKey],
) -> Vec<Failure> {
    let mut out = Vec::new();
    if lanes_a.is_empty() || lanes_a.len() != lanes_b.len() {
        out.push(Failure::new(
            "kit",
            format!(
                "the pair's lane lists must be non-empty and equally long: {} toward b, {} \
                 toward a",
                lanes_a.len(),
                lanes_b.len()
            ),
        ));
        return out;
    }
    let (Some(above_a), Some(above_b)) = (
        capabilities_of(a, below, &mut out),
        capabilities_of(b, below, &mut out),
    ) else {
        return out;
    };
    let (Some(below_a), Some(below_b)) = (
        lanes_of(a, lanes_a, &mut out),
        lanes_of(b, lanes_b, &mut out),
    ) else {
        return out;
    };
    if below_a.len() != below_b.len() {
        out.push(Failure::new(
            "lanes-map-back",
            format!(
                "the two ends asked the layer below for {} and {} lanes; a pair maps them by \
                 position",
                below_a.len(),
                below_b.len()
            ),
        ));
        return out;
    }
    let toward_b = Ends {
        lanes_a,
        below_a: &below_a,
        lanes_b,
        below_b: &below_b,
    };
    let toward_a = Ends {
        lanes_a: lanes_b,
        below_a: &below_b,
        lanes_b: lanes_a,
        below_b: &below_a,
    };
    let mut kit = Kit::new(below, &above_a);
    let mut p = Pair(a, Some(b));
    kit.round_trips(&mut p, &toward_b, &mut out);
    kit.overhead(p.a(), &lanes_a[0], &mut out);
    kit.integrity(&mut p, &toward_b, &mut out);
    kit.ticks(p.a(), &lanes_a[0], &mut out);
    kit.counters(p.a(), &mut out);
    let Pair(a, Some(b)) = p else { unreachable!() };
    let mut kit = Kit::new(below, &above_b);
    let mut p = Pair(b, Some(a));
    kit.round_trips(&mut p, &toward_a, &mut out);
    kit.overhead(p.a(), &lanes_b[0], &mut out);
    kit.integrity(&mut p, &toward_a, &mut out);
    kit.ticks(p.a(), &lanes_b[0], &mut out);
    kit.counters(p.a(), &mut out);
    out
}

fn capabilities_of(
    l: &dyn Layer,
    below: &Capabilities,
    out: &mut Vec<Failure>,
) -> Option<Capabilities> {
    match l.capabilities(below) {
        Ok(c) => Some(c),
        Err(e) => {
            out.push(Failure::new(
                "capabilities-accepted",
                format!(
                    "{} refused to sit over {}/{} bytes: {e}",
                    l.kind(),
                    below.tx_max_sdu,
                    below.rx_max_sdu
                ),
            ));
            None
        }
    }
}

fn lanes_of(l: &mut dyn Layer, lanes: &[LaneKey], out: &mut Vec<Failure>) -> Option<Vec<LaneKey>> {
    match l.lanes(lanes) {
        Ok(v) if v.is_empty() => {
            out.push(Failure::new(
                "lanes-map-back",
                format!("{} asked the layer below for no lanes at all", l.kind()),
            ));
            None
        }
        Ok(v) => Some(v),
        Err(e) => {
            out.push(Failure::new(
                "lanes-accepted",
                format!("{} refused the lanes {lanes:?}: {e}", l.kind()),
            ));
            None
        }
    }
}

/// The two ends of a direction: one instance playing both, or two.
struct Pair<'a>(&'a mut dyn Layer, Option<&'a mut dyn Layer>);

impl Pair<'_> {
    /// The encoding end.
    fn a(&mut self) -> &mut dyn Layer {
        &mut *self.0
    }

    /// The decoding end: the other instance, or the same one.
    fn b(&mut self) -> &mut dyn Layer {
        match &mut self.1 {
            Some(b) => &mut **b,
            None => &mut *self.0,
        }
    }
}

/// The lanes of one direction: `a` encodes on `lanes_a[i]`, its frames
/// leave on `below_a[j]`, arrive at `b` on `below_b[j]`, and the SDU must
/// come out on `lanes_b[i]`.
struct Ends<'a> {
    lanes_a: &'a [LaneKey],
    below_a: &'a [LaneKey],
    lanes_b: &'a [LaneKey],
    below_b: &'a [LaneKey],
}

struct Kit {
    below: Capabilities,
    above: Capabilities,
    now: Instant,
}

impl Kit {
    fn new(below: &Capabilities, above: &Capabilities) -> Self {
        Self {
            below: *below,
            above: *above,
            now: Instant::now(),
        }
    }

    /// The sizes every check runs at: nothing, one byte, a few, just under
    /// the floor, half, one short of the largest, the largest.
    fn sizes(&self) -> Vec<usize> {
        let max = usize::from(self.above.tx_max_sdu);
        let mut v = vec![
            0,
            1,
            7,
            usize::from(ESTABLISHMENT_FLOOR) - 1,
            max / 2,
            max.saturating_sub(1),
            max,
        ];
        v.retain(|s| *s <= max);
        v.sort_unstable();
        v.dedup();
        v
    }

    fn sdu(len: usize, seed: u8) -> Sdu {
        (0..len)
            .map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed))
            .collect()
    }

    fn tick(l: &mut dyn Layer, now: Instant) -> (Frames, Frames, Option<Instant>) {
        let mut down = Frames::new();
        let mut up = Frames::new();
        let next = l.tick(now, &mut down, &mut up);
        (down, up, next)
    }

    /// Carry `sdu` from `a` on `lane_a` to `b` the way the stack would: the
    /// frames `encode` produces and the ones a tick owes, each decoded on the
    /// matching lane below `b`, plus whatever `b`'s tick owes upward.
    fn carry(
        &self,
        p: &mut Pair<'_>,
        lane_a: &LaneKey,
        sdu: &Sdu,
        ends: &Ends<'_>,
        out: &mut Vec<Failure>,
    ) -> Frames {
        let mut frames = Frames::new();
        if let Err(e) = p.a().encode(lane_a, sdu.clone(), self.now, &mut frames) {
            out.push(Failure::new(
                "round-trip-is-identity",
                format!(
                    "{} refused to encode {} bytes: {e}",
                    p.a().kind(),
                    sdu.len()
                ),
            ));
            return Frames::new();
        }
        let (down, _, _) = Self::tick(p.a(), self.now);
        frames.extend(down);
        let mut delivered = Frames::new();
        for (lane_lo, frame) in frames {
            let Some(j) = ends.below_a.iter().position(|l| *l == lane_lo) else {
                out.push(Failure::new(
                    "lanes-map-back",
                    format!(
                        "{} encoded onto lane {lane_lo}, which it did not ask of the layer below",
                        p.a().kind()
                    ),
                ));
                continue;
            };
            let mut got = Frames::new();
            if let Decoded::Refused { reason, detail } =
                p.b().decode(&ends.below_b[j], frame, self.now, &mut got)
            {
                out.push(Failure::new(
                    "round-trip-is-identity",
                    format!(
                        "{} refused a frame its own kind encoded ({reason}: {detail})",
                        p.b().kind()
                    ),
                ));
            }
            delivered.extend(got);
            let (_, up, _) = Self::tick(p.b(), self.now);
            delivered.extend(up);
        }
        delivered
    }

    fn round_trips(&mut self, p: &mut Pair<'_>, ends: &Ends<'_>, out: &mut Vec<Failure>) {
        for (i, lane) in ends.lanes_a.iter().enumerate() {
            for (n, size) in self.sizes().into_iter().enumerate() {
                let sdu = Self::sdu(size, n as u8);
                let got = self.carry(p, lane, &sdu, ends, out);
                let payloads: Vec<&Sdu> = got.iter().map(|(_, s)| s).collect();
                if payloads != [&sdu] {
                    out.push(Failure::new(
                        "round-trip-is-identity",
                        format!(
                            "{} bytes on {lane} came back as {:?} (lengths)",
                            sdu.len(),
                            payloads.iter().map(|p| p.len()).collect::<Vec<_>>()
                        ),
                    ));
                    continue;
                }
                let expect = &ends.lanes_b[i];
                if got[0].0 != *expect {
                    out.push(Failure::new(
                        "lanes-map-back",
                        format!(
                            "an SDU sent on {lane} arrived on {}, not on the matching lane {expect}",
                            got[0].0
                        ),
                    ));
                }
            }
        }
    }

    /// The overhead a layer declares is the overhead it has: every frame
    /// fits the layer below, and a one-to-one layer's frames are exactly the
    /// declared number of bytes longer than the SDU, at every size.
    fn overhead(&mut self, a: &mut dyn Layer, lane: &LaneKey, out: &mut Vec<Failure>) {
        // A layer that offers more than the layer below carries (a fragment
        // layer) is one-to-many by nature; only the fit is checked for it.
        let declared =
            usize::from(self.below.tx_max_sdu).checked_sub(usize::from(self.above.tx_max_sdu));
        let mut one_to_one = true;
        let mut observed = BTreeMap::new();
        for size in self.sizes() {
            let mut frames = Frames::new();
            if a.encode(lane, Self::sdu(size, 9), self.now, &mut frames)
                .is_err()
            {
                continue;
            }
            let (down, _, _) = Self::tick(a, self.now);
            frames.extend(down);
            for (_, f) in &frames {
                if f.len() > usize::from(self.below.tx_max_sdu) {
                    out.push(Failure::new(
                        "overhead-is-declared",
                        format!(
                            "{} made a {}-byte frame from a {size}-byte SDU; the layer below \
                             carries {}",
                            a.kind(),
                            f.len(),
                            self.below.tx_max_sdu
                        ),
                    ));
                }
            }
            if frames.len() == 1 {
                observed.insert(size, frames[0].1.len().saturating_sub(size));
            } else {
                one_to_one = false;
            }
        }
        if let (true, Some(declared)) = (one_to_one, declared) {
            for (size, got) in observed {
                if got != declared {
                    out.push(Failure::new(
                        "overhead-is-declared",
                        format!(
                            "{} declares {declared} bytes of overhead and added {got} to a \
                             {size}-byte SDU",
                            a.kind()
                        ),
                    ));
                }
            }
        }
    }

    /// Where a layer claims integrity, a changed frame is refused; where it
    /// claims anti-replay, a repeated one is; and every refusal moves a
    /// counter, so an operator can see it.
    fn integrity(&mut self, p: &mut Pair<'_>, ends: &Ends<'_>, out: &mut Vec<Failure>) {
        let claims = p
            .b()
            .security(None)
            .map(|s| s.guarantees)
            .unwrap_or_default();
        let integrity = claims.contains(&Guarantee::Integrity);
        let anti_replay = claims.contains(&Guarantee::AntiReplay);
        if !integrity && !anti_replay {
            return;
        }
        let lane = &ends.lanes_a[0];
        let sdu = Self::sdu(usize::from(self.above.tx_max_sdu).min(40), 3);
        let mut frames = Frames::new();
        if p.a().encode(lane, sdu, self.now, &mut frames).is_err() || frames.is_empty() {
            out.push(Failure::new(
                "integrity-is-enforced",
                format!("{} could not encode the probe", p.a().kind()),
            ));
            return;
        }
        let (lane_lo, frame) = frames[0].clone();
        let j = ends.below_a.iter().position(|l| *l == lane_lo).unwrap_or(0);
        let lane_lo_b = ends.below_b.get(j).cloned().unwrap_or(lane_lo);
        let total = |l: &dyn Layer| l.counters().iter().map(|c| c.value).sum::<u64>();
        let b = p.b();

        let mut attempts: Vec<(&str, Sdu)> = Vec::new();
        if integrity {
            let mut flipped = frame.clone();
            let at = flipped.len() / 2;
            flipped[at] ^= 0x01;
            attempts.push(("a flipped bit", flipped));
            attempts.push(("a one-byte truncation", frame[..frame.len() - 1].to_vec()));
        }
        for (what, bad) in attempts {
            let before = total(b);
            let mut got = Frames::new();
            match b.decode(&lane_lo_b, bad, self.now, &mut got) {
                Decoded::Refused { .. } if got.is_empty() => {}
                other => out.push(Failure::new(
                    "integrity-is-enforced",
                    format!(
                        "{} claims integrity and accepted {what}: {other:?}, delivered {}",
                        b.kind(),
                        got.len()
                    ),
                )),
            }
            if total(b) <= before {
                out.push(Failure::new(
                    "refusal-is-counted",
                    format!("{} refused {what} and no counter moved", b.kind()),
                ));
            }
        }
        // The genuine frame, then the same frame again.
        let mut got = Frames::new();
        if let Decoded::Refused { reason, detail } =
            b.decode(&lane_lo_b, frame.clone(), self.now, &mut got)
        {
            out.push(Failure::new(
                "integrity-is-enforced",
                format!(
                    "{} refused the genuine frame ({reason}: {detail})",
                    b.kind()
                ),
            ));
        }
        if anti_replay {
            let before = total(b);
            let mut got = Frames::new();
            match b.decode(&lane_lo_b, frame, self.now, &mut got) {
                Decoded::Refused { .. } if got.is_empty() => {}
                other => out.push(Failure::new(
                    "integrity-is-enforced",
                    format!(
                        "{} claims anti-replay and accepted a repeated frame: {other:?}",
                        b.kind()
                    ),
                )),
            }
            if total(b) <= before {
                out.push(Failure::new(
                    "refusal-is-counted",
                    format!("{} refused a replay and no counter moved", b.kind()),
                ));
            }
        }
    }

    /// A deadline announced is a deadline kept: ticks advance to `None` in
    /// bounded steps, never name a time already past, and a layer with
    /// nothing pending owes nothing, however long the clock is left alone.
    fn ticks(&mut self, a: &mut dyn Layer, lane: &LaneKey, out: &mut Vec<Failure>) {
        let mut frames = Frames::new();
        let _ = a.encode(
            lane,
            Self::sdu(usize::from(self.above.tx_max_sdu), 5),
            self.now,
            &mut frames,
        );
        let mut now = self.now;
        let mut steps = 0;
        loop {
            let (_, _, next) = Self::tick(a, now);
            match next {
                None => break,
                Some(deadline) if deadline < now => {
                    out.push(Failure::new(
                        "tick-terminates",
                        format!("{} announced a deadline already past", a.kind()),
                    ));
                    break;
                }
                Some(deadline) => now = deadline.max(now + Duration::from_millis(1)),
            }
            steps += 1;
            if steps > 1_000 {
                out.push(Failure::new(
                    "tick-terminates",
                    format!(
                        "{} still announced a deadline after 1000 ticks with nothing arriving",
                        a.kind()
                    ),
                ));
                break;
            }
        }
        let (down, up, next) = Self::tick(a, now + Duration::from_secs(3_600));
        if !down.is_empty() || !up.is_empty() {
            out.push(Failure::new(
                "tick-owes-nothing-unannounced",
                format!(
                    "{} owed {} frames down and {} up on a tick after it said nothing was pending",
                    a.kind(),
                    down.len(),
                    up.len()
                ),
            ));
        }
        if next.is_some() {
            out.push(Failure::new(
                "tick-owes-nothing-unannounced",
                format!("{} announced a deadline out of nothing", a.kind()),
            ));
        }
        self.now = now;
    }

    fn counters(&self, a: &dyn Layer, out: &mut Vec<Failure>) {
        for c in a.counters() {
            if c.scope != a.kind() {
                out.push(Failure::new(
                    "counters-are-scoped-by-kind",
                    format!(
                        "{} keeps a counter scoped {:?}: a layer's counters are its own, under \
                         its kind",
                        a.kind(),
                        c.scope
                    ),
                ));
            }
        }
    }
}

// --- reference layers ------------------------------------------------------

/// A layer that changes nothing: the kit's positive control, and what the
/// driver's `Stack` is held to in the medium kit's decorator check.
#[derive(Debug, Default)]
pub struct Identity;

impl Layer for Identity {
    fn kind(&self) -> &'static str {
        "identity"
    }
    fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
        Ok(*below)
    }
    fn encode(
        &mut self,
        lane: &LaneKey,
        sdu: Sdu,
        _now: Instant,
        out: &mut Frames,
    ) -> Result<(), LayerError> {
        out.push((lane.clone(), sdu));
        Ok(())
    }
    fn decode(&mut self, lane: &LaneKey, frame: Sdu, _now: Instant, out: &mut Frames) -> Decoded {
        out.push((lane.clone(), frame));
        Decoded::Accepted
    }
}

/// A layer with `bytes` of header per SDU and nothing to say in it: what the
/// driver's test-only `layer-overhead` feature configures, so the capability
/// arithmetic, the floor and the counters pipe are tested without a real
/// layer. Counts the SDUs it carried as `sdus_total`.
#[derive(Debug)]
pub struct Overhead {
    bytes: u16,
    sdus: u64,
}

impl Overhead {
    /// The header byte, so a frame that is not this layer's is refused.
    pub const MARK: u8 = 0xA5;

    /// `bytes` of header per SDU.
    #[must_use]
    pub fn new(bytes: u16) -> Self {
        Self { bytes, sdus: 0 }
    }
}

impl Layer for Overhead {
    fn kind(&self) -> &'static str {
        "overhead"
    }
    fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
        if below.tx_max_sdu <= self.bytes || below.rx_max_sdu <= self.bytes {
            return Err(LayerError::TooSmallBelow {
                layer: "overhead",
                needs: self.bytes.saturating_add(1),
                below: below.tx_max_sdu.min(below.rx_max_sdu),
            });
        }
        let mut c = *below;
        c.tx_max_sdu -= self.bytes;
        c.rx_max_sdu -= self.bytes;
        Ok(c)
    }
    fn encode(
        &mut self,
        lane: &LaneKey,
        sdu: Sdu,
        _now: Instant,
        out: &mut Frames,
    ) -> Result<(), LayerError> {
        let mut frame = vec![Self::MARK; usize::from(self.bytes)];
        frame.extend_from_slice(&sdu);
        self.sdus += 1;
        out.push((lane.clone(), frame));
        Ok(())
    }
    fn decode(&mut self, lane: &LaneKey, frame: Sdu, _now: Instant, out: &mut Frames) -> Decoded {
        let n = usize::from(self.bytes);
        if frame.len() < n || frame[..n].iter().any(|b| *b != Self::MARK) {
            return Decoded::refused("malformed", "overhead: not this layer's header");
        }
        out.push((lane.clone(), frame[n..].to_vec()));
        Decoded::Accepted
    }
    fn counters(&self) -> Vec<Counter> {
        vec![Counter::new("overhead", "sdus_total", self.sdus)]
    }
}

/// A layer that turns every SDU into `n` frames and reassembles them: the
/// kit's and the driver's test of a one-to-many transform, of backpressure
/// through a send that becomes several, and of a deadline (an incomplete
/// reassembly is dropped after [`Split::TIMEOUT`], counted as
/// `incomplete_total`).
///
/// Frame: `| seq | index | n | chunk |`. The SDU it offers upward is three
/// bytes smaller than the frame below, so every chunk fits.
/// When a packet's first fragment arrived, and the fragments so far.
type Reassembly = (Instant, Vec<Option<Sdu>>);

#[derive(Debug)]
pub struct Split {
    n: u8,
    seq: u8,
    pending: BTreeMap<(LaneKey, u8), Reassembly>,
    incomplete: u64,
}

impl Split {
    /// How long an incomplete reassembly is kept.
    pub const TIMEOUT: Duration = Duration::from_secs(1);

    /// `n` frames per SDU, 1 to 255.
    #[must_use]
    pub fn new(n: u8) -> Self {
        Self {
            n: n.max(1),
            seq: 0,
            pending: BTreeMap::new(),
            incomplete: 0,
        }
    }
}

impl Layer for Split {
    fn kind(&self) -> &'static str {
        "split"
    }
    fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
        if below.tx_max_sdu <= 3 || below.rx_max_sdu <= 3 {
            return Err(LayerError::TooSmallBelow {
                layer: "split",
                needs: 4,
                below: below.tx_max_sdu.min(below.rx_max_sdu),
            });
        }
        let mut c = *below;
        c.tx_max_sdu -= 3;
        c.rx_max_sdu -= 3;
        Ok(c)
    }
    fn encode(
        &mut self,
        lane: &LaneKey,
        sdu: Sdu,
        _now: Instant,
        out: &mut Frames,
    ) -> Result<(), LayerError> {
        let seq = self.seq;
        self.seq = self.seq.wrapping_add(1);
        let n = usize::from(self.n);
        let chunk = sdu.len().div_ceil(n).max(1);
        for i in 0..n {
            let start = (i * chunk).min(sdu.len());
            let end = ((i + 1) * chunk).min(sdu.len());
            let mut frame = vec![seq, i as u8, self.n];
            frame.extend_from_slice(&sdu[start..end]);
            out.push((lane.clone(), frame));
        }
        Ok(())
    }
    fn decode(&mut self, lane: &LaneKey, frame: Sdu, now: Instant, out: &mut Frames) -> Decoded {
        if frame.len() < 3 || frame[2] == 0 || frame[1] >= frame[2] {
            return Decoded::refused("malformed", "split: not this layer's header");
        }
        let (seq, index, n) = (frame[0], usize::from(frame[1]), usize::from(frame[2]));
        let key = (lane.clone(), seq);
        let entry = self
            .pending
            .entry(key.clone())
            .or_insert_with(|| (now, vec![None; n]));
        if entry.1.len() != n {
            return Decoded::refused("malformed", "split: a frame count that changed mid-packet");
        }
        entry.0 = now;
        entry.1[index] = Some(frame[3..].to_vec());
        if entry.1.iter().all(Option::is_some) {
            let (_, parts) = self.pending.remove(&key).expect("present");
            let sdu: Sdu = parts.into_iter().flatten().flatten().collect();
            out.push((lane.clone(), sdu));
        }
        Decoded::Accepted
    }
    fn tick(&mut self, now: Instant, _down: &mut Frames, _up: &mut Frames) -> Option<Instant> {
        let before = self.pending.len();
        self.pending
            .retain(|_, (at, _)| now.duration_since(*at) < Self::TIMEOUT);
        self.incomplete += (before - self.pending.len()) as u64;
        self.pending
            .values()
            .map(|(at, _)| *at + Self::TIMEOUT)
            .min()
    }
    fn counters(&self) -> Vec<Counter> {
        vec![Counter::new("split", "incomplete_total", self.incomplete)]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Duplex, Scope, SecurityProperties};

    fn below() -> Capabilities {
        Capabilities::new(220, 220, Duplex::Half, false)
    }

    fn lane(endpoint: &str) -> LaneKey {
        LaneKey {
            endpoint: crate::EndpointId::new(endpoint),
            reliable: false,
            rank: 0,
        }
    }

    fn names(failures: &[Failure]) -> Vec<&str> {
        let mut v: Vec<&str> = failures.iter().map(|f| f.check).collect();
        v.sort_unstable();
        v.dedup();
        v
    }

    #[test]
    fn the_reference_layers_pass() {
        for (name, mut l) in [
            ("identity", Box::new(Identity) as Box<dyn Layer>),
            ("overhead", Box::new(Overhead::new(6))),
            ("split", Box::new(Split::new(3))),
        ] {
            let failures = layer(l.as_mut(), &below(), &[lane("b")]);
            assert!(failures.is_empty(), "{name}: {failures:?}");
        }
        let mut a = Overhead::new(4);
        let mut b = Overhead::new(4);
        let failures = pair(&mut a, &mut b, &below(), &[lane("b")], &[lane("a")]);
        assert!(failures.is_empty(), "{failures:?}");
    }

    #[test]
    fn split_reassembles_in_any_order_and_drops_an_incomplete_packet_on_time() {
        let mut s = Split::new(3);
        let t0 = Instant::now();
        let mut frames = Frames::new();
        s.encode(&lane("b"), (0..10u8).collect(), t0, &mut frames)
            .unwrap();
        assert_eq!(frames.len(), 3);
        frames.swap(0, 2);
        let mut got = Frames::new();
        for (l, f) in frames {
            assert_eq!(s.decode(&l, f, t0, &mut got), Decoded::Accepted);
        }
        assert_eq!(got, vec![(lane("b"), (0..10u8).collect::<Vec<_>>())]);
        // One fragment of the next packet, then nothing: the deadline is
        // announced, and kept.
        let mut frames = Frames::new();
        s.encode(&lane("b"), vec![1; 9], t0, &mut frames).unwrap();
        let mut got = Frames::new();
        s.decode(&lane("b"), frames[0].1.clone(), t0, &mut got);
        assert!(got.is_empty());
        let (_, _, next) = Kit::tick(&mut s, t0);
        assert_eq!(next, Some(t0 + Split::TIMEOUT));
        let (_, _, next) = Kit::tick(&mut s, t0 + Split::TIMEOUT);
        assert_eq!(next, None);
        assert_eq!(s.counters()[0].value, 1);
    }

    /// A pass-through body shared by the layers written to fail one check.
    macro_rules! passes_through {
        () => {
            fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
                Ok(*below)
            }
            fn encode(
                &mut self,
                lane: &LaneKey,
                sdu: Sdu,
                _: Instant,
                out: &mut Frames,
            ) -> Result<(), LayerError> {
                out.push((lane.clone(), sdu));
                Ok(())
            }
            fn decode(
                &mut self,
                lane: &LaneKey,
                frame: Sdu,
                _: Instant,
                out: &mut Frames,
            ) -> Decoded {
                out.push((lane.clone(), frame));
                Decoded::Accepted
            }
        };
    }

    /// Declares four bytes, adds six.
    struct LiesAboutOverhead;
    impl Layer for LiesAboutOverhead {
        fn kind(&self) -> &'static str {
            "liar"
        }
        fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
            let mut c = *below;
            c.tx_max_sdu -= 4;
            c.rx_max_sdu -= 4;
            Ok(c)
        }
        fn encode(
            &mut self,
            lane: &LaneKey,
            sdu: Sdu,
            _: Instant,
            out: &mut Frames,
        ) -> Result<(), LayerError> {
            let mut f = vec![0; 6];
            f.extend(sdu);
            out.push((lane.clone(), f));
            Ok(())
        }
        fn decode(&mut self, lane: &LaneKey, frame: Sdu, _: Instant, out: &mut Frames) -> Decoded {
            out.push((lane.clone(), frame[6.min(frame.len())..].to_vec()));
            Decoded::Accepted
        }
    }

    /// Claims integrity and anti-replay, checks nothing, counts nothing.
    struct Credulous;
    impl Layer for Credulous {
        fn kind(&self) -> &'static str {
            "credulous"
        }
        passes_through!();
        fn security(&self, _: Option<&SecurityProperties>) -> Option<SecurityProperties> {
            Some(
                SecurityProperties::new("credulous", Scope::Hop)
                    .guarantee(Guarantee::Integrity)
                    .guarantee(Guarantee::AntiReplay),
            )
        }
    }

    /// A one-byte XOR "integrity" check: refuses what it should, and no
    /// counter moves.
    struct SilentRefuser;
    impl SilentRefuser {
        fn xor(body: &[u8]) -> u8 {
            body.iter().fold(0x5A, |a, b| a ^ b)
        }
    }
    impl Layer for SilentRefuser {
        fn kind(&self) -> &'static str {
            "silent"
        }
        fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
            let mut c = *below;
            c.tx_max_sdu -= 1;
            c.rx_max_sdu -= 1;
            Ok(c)
        }
        fn encode(
            &mut self,
            lane: &LaneKey,
            sdu: Sdu,
            _: Instant,
            out: &mut Frames,
        ) -> Result<(), LayerError> {
            let mut f = vec![Self::xor(&sdu)];
            f.extend(sdu);
            out.push((lane.clone(), f));
            Ok(())
        }
        fn decode(&mut self, lane: &LaneKey, frame: Sdu, _: Instant, out: &mut Frames) -> Decoded {
            if frame.is_empty() || Self::xor(&frame[1..]) != frame[0] {
                return Decoded::refused("auth-failed", "silent: refused");
            }
            out.push((lane.clone(), frame[1..].to_vec()));
            Decoded::Accepted
        }
        fn security(&self, _: Option<&SecurityProperties>) -> Option<SecurityProperties> {
            Some(SecurityProperties::new("silent", Scope::Hop).guarantee(Guarantee::Integrity))
        }
    }

    /// Always wants another tick, one millisecond on.
    struct Restless;
    impl Layer for Restless {
        fn kind(&self) -> &'static str {
            "restless"
        }
        passes_through!();
        fn tick(&mut self, now: Instant, _: &mut Frames, _: &mut Frames) -> Option<Instant> {
            Some(now + Duration::from_millis(1))
        }
    }

    /// Owes a frame on every tick, having announced none.
    struct Chatty;
    impl Layer for Chatty {
        fn kind(&self) -> &'static str {
            "chatty"
        }
        passes_through!();
        fn tick(&mut self, _: Instant, down: &mut Frames, _: &mut Frames) -> Option<Instant> {
            down.push((lane("b"), vec![0]));
            None
        }
    }

    /// Keeps a counter under somebody else's name.
    struct Misfiled;
    impl Layer for Misfiled {
        fn kind(&self) -> &'static str {
            "misfiled"
        }
        passes_through!();
        fn counters(&self) -> Vec<Counter> {
            vec![Counter::new("sdu", "sdus_total", 1)]
        }
    }

    /// Encodes onto a lane it never asked the layer below for.
    struct Misroutes;
    impl Layer for Misroutes {
        fn kind(&self) -> &'static str {
            "misroutes"
        }
        fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
            Ok(*below)
        }
        fn encode(
            &mut self,
            _: &LaneKey,
            sdu: Sdu,
            _: Instant,
            out: &mut Frames,
        ) -> Result<(), LayerError> {
            out.push((lane("nowhere"), sdu));
            Ok(())
        }
        fn decode(&mut self, lane: &LaneKey, frame: Sdu, _: Instant, out: &mut Frames) -> Decoded {
            out.push((lane.clone(), frame));
            Decoded::Accepted
        }
    }

    #[test]
    fn each_check_catches_the_layer_written_to_fail_it() {
        let cases: Vec<(Box<dyn Layer>, &[&str])> = vec![
            (Box::new(LiesAboutOverhead), &["overhead-is-declared"]),
            (
                Box::new(Credulous),
                &["integrity-is-enforced", "refusal-is-counted"],
            ),
            (Box::new(SilentRefuser), &["refusal-is-counted"]),
            (
                Box::new(Restless),
                &["tick-owes-nothing-unannounced", "tick-terminates"],
            ),
            (
                Box::new(Chatty),
                &["round-trip-is-identity", "tick-owes-nothing-unannounced"],
            ),
            (Box::new(Misfiled), &["counters-are-scoped-by-kind"]),
            (
                Box::new(Misroutes),
                &["lanes-map-back", "round-trip-is-identity"],
            ),
        ];
        for (mut l, expect) in cases {
            let kind = l.kind();
            let failures = layer(l.as_mut(), &below(), &[lane("b")]);
            assert_eq!(names(&failures), *expect, "{kind}: {failures:?}");
        }
    }
}