Skip to main content

modem_device/conformance/
layer.rs

1//! The conformance kit for a [`Layer`] (#157): synchronous, no runtime.
2//!
3//! A layer is a function of its state, so everything here drives it
4//! directly, with a clock the kit advances by hand. The checks are what "a
5//! layer never lies" comes to once the trait is written down: a round trip is
6//! the identity, the overhead a layer declares is the overhead it has, a
7//! layer that claims integrity refuses a changed frame and one that claims
8//! anti-replay refuses a repeated one, a refusal moves a counter, a deadline
9//! announced is a deadline kept and nothing is owed that was not announced,
10//! a counter is scoped by the layer that keeps it, and an SDU sent on a lane
11//! arrives on the matching lane.
12//!
13//! Two shapes. [`layer`] drives one instance both ways, for a layer whose two
14//! ends are interchangeable. [`pair`] drives two instances, A encoding toward
15//! B and B toward A, for a layer whose ends differ: directional keys (#158),
16//! addresses (#160). `layer` is `pair` with the same instance at both ends.
17//!
18//! Three reference layers live here too, public because the driver's own
19//! tests and its test-only `layer-overhead` feature build them: [`Identity`],
20//! [`Overhead`] and [`Split`].
21
22use std::collections::BTreeMap;
23use std::time::{Duration, Instant};
24
25use super::Failure;
26use crate::layer::{Decoded, Frames, Layer, LayerError};
27use crate::{Capabilities, Counter, ESTABLISHMENT_FLOOR, Guarantee, LaneKey, Sdu};
28
29/// Hold `l` to every check, driving one instance in both directions: what
30/// it encodes on `lanes[i]` it decodes on the lane below that it asked for.
31pub fn layer(l: &mut dyn Layer, below: &Capabilities, lanes: &[LaneKey]) -> Vec<Failure> {
32    let mut out = Vec::new();
33    if lanes.is_empty() {
34        out.push(Failure::new("kit", "no lanes to drive the layer on"));
35        return out;
36    }
37    let Some(above) = capabilities_of(l, below, &mut out) else {
38        return out;
39    };
40    let Some(lanes_below) = lanes_of(l, lanes, &mut out) else {
41        return out;
42    };
43    let mut kit = Kit::new(below, &above);
44    let ends = Ends {
45        lanes_a: lanes,
46        below_a: &lanes_below,
47        lanes_b: lanes,
48        below_b: &lanes_below,
49    };
50    let mut p = Pair(l, None);
51    kit.round_trips(&mut p, &ends, &mut out);
52    kit.overhead(p.a(), &lanes[0], &mut out);
53    kit.integrity(&mut p, &ends, &mut out);
54    kit.ticks(p.a(), &lanes[0], &mut out);
55    kit.counters(p.a(), &mut out);
56    out
57}
58
59/// Hold a pair to every check: `a` encodes on `lanes_a[i]` what `b` decodes
60/// and must deliver on `lanes_b[i]`, and the other way round. The lanes each
61/// end asks of the layer below are matched by position, so the two lists are
62/// the same length.
63pub fn pair(
64    a: &mut dyn Layer,
65    b: &mut dyn Layer,
66    below: &Capabilities,
67    lanes_a: &[LaneKey],
68    lanes_b: &[LaneKey],
69) -> Vec<Failure> {
70    let mut out = Vec::new();
71    if lanes_a.is_empty() || lanes_a.len() != lanes_b.len() {
72        out.push(Failure::new(
73            "kit",
74            format!(
75                "the pair's lane lists must be non-empty and equally long: {} toward b, {} \
76                 toward a",
77                lanes_a.len(),
78                lanes_b.len()
79            ),
80        ));
81        return out;
82    }
83    let (Some(above_a), Some(above_b)) = (
84        capabilities_of(a, below, &mut out),
85        capabilities_of(b, below, &mut out),
86    ) else {
87        return out;
88    };
89    let (Some(below_a), Some(below_b)) = (
90        lanes_of(a, lanes_a, &mut out),
91        lanes_of(b, lanes_b, &mut out),
92    ) else {
93        return out;
94    };
95    if below_a.len() != below_b.len() {
96        out.push(Failure::new(
97            "lanes-map-back",
98            format!(
99                "the two ends asked the layer below for {} and {} lanes; a pair maps them by \
100                 position",
101                below_a.len(),
102                below_b.len()
103            ),
104        ));
105        return out;
106    }
107    let toward_b = Ends {
108        lanes_a,
109        below_a: &below_a,
110        lanes_b,
111        below_b: &below_b,
112    };
113    let toward_a = Ends {
114        lanes_a: lanes_b,
115        below_a: &below_b,
116        lanes_b: lanes_a,
117        below_b: &below_a,
118    };
119    let mut kit = Kit::new(below, &above_a);
120    let mut p = Pair(a, Some(b));
121    kit.round_trips(&mut p, &toward_b, &mut out);
122    kit.overhead(p.a(), &lanes_a[0], &mut out);
123    kit.integrity(&mut p, &toward_b, &mut out);
124    kit.ticks(p.a(), &lanes_a[0], &mut out);
125    kit.counters(p.a(), &mut out);
126    let Pair(a, Some(b)) = p else { unreachable!() };
127    let mut kit = Kit::new(below, &above_b);
128    let mut p = Pair(b, Some(a));
129    kit.round_trips(&mut p, &toward_a, &mut out);
130    kit.overhead(p.a(), &lanes_b[0], &mut out);
131    kit.integrity(&mut p, &toward_a, &mut out);
132    kit.ticks(p.a(), &lanes_b[0], &mut out);
133    kit.counters(p.a(), &mut out);
134    out
135}
136
137fn capabilities_of(
138    l: &dyn Layer,
139    below: &Capabilities,
140    out: &mut Vec<Failure>,
141) -> Option<Capabilities> {
142    match l.capabilities(below) {
143        Ok(c) => Some(c),
144        Err(e) => {
145            out.push(Failure::new(
146                "capabilities-accepted",
147                format!(
148                    "{} refused to sit over {}/{} bytes: {e}",
149                    l.kind(),
150                    below.tx_max_sdu,
151                    below.rx_max_sdu
152                ),
153            ));
154            None
155        }
156    }
157}
158
159fn lanes_of(l: &mut dyn Layer, lanes: &[LaneKey], out: &mut Vec<Failure>) -> Option<Vec<LaneKey>> {
160    match l.lanes(lanes) {
161        Ok(v) if v.is_empty() => {
162            out.push(Failure::new(
163                "lanes-map-back",
164                format!("{} asked the layer below for no lanes at all", l.kind()),
165            ));
166            None
167        }
168        Ok(v) => Some(v),
169        Err(e) => {
170            out.push(Failure::new(
171                "lanes-accepted",
172                format!("{} refused the lanes {lanes:?}: {e}", l.kind()),
173            ));
174            None
175        }
176    }
177}
178
179/// The two ends of a direction: one instance playing both, or two.
180struct Pair<'a>(&'a mut dyn Layer, Option<&'a mut dyn Layer>);
181
182impl Pair<'_> {
183    /// The encoding end.
184    fn a(&mut self) -> &mut dyn Layer {
185        &mut *self.0
186    }
187
188    /// The decoding end: the other instance, or the same one.
189    fn b(&mut self) -> &mut dyn Layer {
190        match &mut self.1 {
191            Some(b) => &mut **b,
192            None => &mut *self.0,
193        }
194    }
195}
196
197/// The lanes of one direction: `a` encodes on `lanes_a[i]`, its frames
198/// leave on `below_a[j]`, arrive at `b` on `below_b[j]`, and the SDU must
199/// come out on `lanes_b[i]`.
200struct Ends<'a> {
201    lanes_a: &'a [LaneKey],
202    below_a: &'a [LaneKey],
203    lanes_b: &'a [LaneKey],
204    below_b: &'a [LaneKey],
205}
206
207struct Kit {
208    below: Capabilities,
209    above: Capabilities,
210    now: Instant,
211}
212
213impl Kit {
214    fn new(below: &Capabilities, above: &Capabilities) -> Self {
215        Self {
216            below: *below,
217            above: *above,
218            now: Instant::now(),
219        }
220    }
221
222    /// The sizes every check runs at: nothing, one byte, a few, just under
223    /// the floor, half, one short of the largest, the largest.
224    fn sizes(&self) -> Vec<usize> {
225        let max = usize::from(self.above.tx_max_sdu);
226        let mut v = vec![
227            0,
228            1,
229            7,
230            usize::from(ESTABLISHMENT_FLOOR) - 1,
231            max / 2,
232            max.saturating_sub(1),
233            max,
234        ];
235        v.retain(|s| *s <= max);
236        v.sort_unstable();
237        v.dedup();
238        v
239    }
240
241    fn sdu(len: usize, seed: u8) -> Sdu {
242        (0..len)
243            .map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed))
244            .collect()
245    }
246
247    fn tick(l: &mut dyn Layer, now: Instant) -> (Frames, Frames, Option<Instant>) {
248        let mut down = Frames::new();
249        let mut up = Frames::new();
250        let next = l.tick(now, &mut down, &mut up);
251        (down, up, next)
252    }
253
254    /// Carry `sdu` from `a` on `lane_a` to `b` the way the stack would: the
255    /// frames `encode` produces and the ones a tick owes, each decoded on the
256    /// matching lane below `b`, plus whatever `b`'s tick owes upward.
257    fn carry(
258        &self,
259        p: &mut Pair<'_>,
260        lane_a: &LaneKey,
261        sdu: &Sdu,
262        ends: &Ends<'_>,
263        out: &mut Vec<Failure>,
264    ) -> Frames {
265        let mut frames = Frames::new();
266        if let Err(e) = p.a().encode(lane_a, sdu.clone(), self.now, &mut frames) {
267            out.push(Failure::new(
268                "round-trip-is-identity",
269                format!(
270                    "{} refused to encode {} bytes: {e}",
271                    p.a().kind(),
272                    sdu.len()
273                ),
274            ));
275            return Frames::new();
276        }
277        let (down, _, _) = Self::tick(p.a(), self.now);
278        frames.extend(down);
279        let mut delivered = Frames::new();
280        for (lane_lo, frame) in frames {
281            let Some(j) = ends.below_a.iter().position(|l| *l == lane_lo) else {
282                out.push(Failure::new(
283                    "lanes-map-back",
284                    format!(
285                        "{} encoded onto lane {lane_lo}, which it did not ask of the layer below",
286                        p.a().kind()
287                    ),
288                ));
289                continue;
290            };
291            let mut got = Frames::new();
292            if let Decoded::Refused { reason, detail } =
293                p.b().decode(&ends.below_b[j], frame, self.now, &mut got)
294            {
295                out.push(Failure::new(
296                    "round-trip-is-identity",
297                    format!(
298                        "{} refused a frame its own kind encoded ({reason}: {detail})",
299                        p.b().kind()
300                    ),
301                ));
302            }
303            delivered.extend(got);
304            let (_, up, _) = Self::tick(p.b(), self.now);
305            delivered.extend(up);
306        }
307        delivered
308    }
309
310    fn round_trips(&mut self, p: &mut Pair<'_>, ends: &Ends<'_>, out: &mut Vec<Failure>) {
311        for (i, lane) in ends.lanes_a.iter().enumerate() {
312            for (n, size) in self.sizes().into_iter().enumerate() {
313                let sdu = Self::sdu(size, n as u8);
314                let got = self.carry(p, lane, &sdu, ends, out);
315                let payloads: Vec<&Sdu> = got.iter().map(|(_, s)| s).collect();
316                if payloads != [&sdu] {
317                    out.push(Failure::new(
318                        "round-trip-is-identity",
319                        format!(
320                            "{} bytes on {lane} came back as {:?} (lengths)",
321                            sdu.len(),
322                            payloads.iter().map(|p| p.len()).collect::<Vec<_>>()
323                        ),
324                    ));
325                    continue;
326                }
327                let expect = &ends.lanes_b[i];
328                if got[0].0 != *expect {
329                    out.push(Failure::new(
330                        "lanes-map-back",
331                        format!(
332                            "an SDU sent on {lane} arrived on {}, not on the matching lane {expect}",
333                            got[0].0
334                        ),
335                    ));
336                }
337            }
338        }
339    }
340
341    /// The overhead a layer declares is the overhead it has: every frame
342    /// fits the layer below, and a one-to-one layer's frames are exactly the
343    /// declared number of bytes longer than the SDU, at every size.
344    fn overhead(&mut self, a: &mut dyn Layer, lane: &LaneKey, out: &mut Vec<Failure>) {
345        // A layer that offers more than the layer below carries (a fragment
346        // layer) is one-to-many by nature; only the fit is checked for it.
347        let declared =
348            usize::from(self.below.tx_max_sdu).checked_sub(usize::from(self.above.tx_max_sdu));
349        let mut one_to_one = true;
350        let mut observed = BTreeMap::new();
351        for size in self.sizes() {
352            let mut frames = Frames::new();
353            if a.encode(lane, Self::sdu(size, 9), self.now, &mut frames)
354                .is_err()
355            {
356                continue;
357            }
358            let (down, _, _) = Self::tick(a, self.now);
359            frames.extend(down);
360            for (_, f) in &frames {
361                if f.len() > usize::from(self.below.tx_max_sdu) {
362                    out.push(Failure::new(
363                        "overhead-is-declared",
364                        format!(
365                            "{} made a {}-byte frame from a {size}-byte SDU; the layer below \
366                             carries {}",
367                            a.kind(),
368                            f.len(),
369                            self.below.tx_max_sdu
370                        ),
371                    ));
372                }
373            }
374            if frames.len() == 1 {
375                observed.insert(size, frames[0].1.len().saturating_sub(size));
376            } else {
377                one_to_one = false;
378            }
379        }
380        if let (true, Some(declared)) = (one_to_one, declared) {
381            for (size, got) in observed {
382                if got != declared {
383                    out.push(Failure::new(
384                        "overhead-is-declared",
385                        format!(
386                            "{} declares {declared} bytes of overhead and added {got} to a \
387                             {size}-byte SDU",
388                            a.kind()
389                        ),
390                    ));
391                }
392            }
393        }
394    }
395
396    /// Where a layer claims integrity, a changed frame is refused; where it
397    /// claims anti-replay, a repeated one is; and every refusal moves a
398    /// counter, so an operator can see it.
399    fn integrity(&mut self, p: &mut Pair<'_>, ends: &Ends<'_>, out: &mut Vec<Failure>) {
400        let claims = p
401            .b()
402            .security(None)
403            .map(|s| s.guarantees)
404            .unwrap_or_default();
405        let integrity = claims.contains(&Guarantee::Integrity);
406        let anti_replay = claims.contains(&Guarantee::AntiReplay);
407        if !integrity && !anti_replay {
408            return;
409        }
410        let lane = &ends.lanes_a[0];
411        let sdu = Self::sdu(usize::from(self.above.tx_max_sdu).min(40), 3);
412        let mut frames = Frames::new();
413        if p.a().encode(lane, sdu, self.now, &mut frames).is_err() || frames.is_empty() {
414            out.push(Failure::new(
415                "integrity-is-enforced",
416                format!("{} could not encode the probe", p.a().kind()),
417            ));
418            return;
419        }
420        let (lane_lo, frame) = frames[0].clone();
421        let j = ends.below_a.iter().position(|l| *l == lane_lo).unwrap_or(0);
422        let lane_lo_b = ends.below_b.get(j).cloned().unwrap_or(lane_lo);
423        let total = |l: &dyn Layer| l.counters().iter().map(|c| c.value).sum::<u64>();
424        let b = p.b();
425
426        let mut attempts: Vec<(&str, Sdu)> = Vec::new();
427        if integrity {
428            let mut flipped = frame.clone();
429            let at = flipped.len() / 2;
430            flipped[at] ^= 0x01;
431            attempts.push(("a flipped bit", flipped));
432            attempts.push(("a one-byte truncation", frame[..frame.len() - 1].to_vec()));
433        }
434        for (what, bad) in attempts {
435            let before = total(b);
436            let mut got = Frames::new();
437            match b.decode(&lane_lo_b, bad, self.now, &mut got) {
438                Decoded::Refused { .. } if got.is_empty() => {}
439                other => out.push(Failure::new(
440                    "integrity-is-enforced",
441                    format!(
442                        "{} claims integrity and accepted {what}: {other:?}, delivered {}",
443                        b.kind(),
444                        got.len()
445                    ),
446                )),
447            }
448            if total(b) <= before {
449                out.push(Failure::new(
450                    "refusal-is-counted",
451                    format!("{} refused {what} and no counter moved", b.kind()),
452                ));
453            }
454        }
455        // The genuine frame, then the same frame again.
456        let mut got = Frames::new();
457        if let Decoded::Refused { reason, detail } =
458            b.decode(&lane_lo_b, frame.clone(), self.now, &mut got)
459        {
460            out.push(Failure::new(
461                "integrity-is-enforced",
462                format!(
463                    "{} refused the genuine frame ({reason}: {detail})",
464                    b.kind()
465                ),
466            ));
467        }
468        if anti_replay {
469            let before = total(b);
470            let mut got = Frames::new();
471            match b.decode(&lane_lo_b, frame, self.now, &mut got) {
472                Decoded::Refused { .. } if got.is_empty() => {}
473                other => out.push(Failure::new(
474                    "integrity-is-enforced",
475                    format!(
476                        "{} claims anti-replay and accepted a repeated frame: {other:?}",
477                        b.kind()
478                    ),
479                )),
480            }
481            if total(b) <= before {
482                out.push(Failure::new(
483                    "refusal-is-counted",
484                    format!("{} refused a replay and no counter moved", b.kind()),
485                ));
486            }
487        }
488    }
489
490    /// A deadline announced is a deadline kept: ticks advance to `None` in
491    /// bounded steps, never name a time already past, and a layer with
492    /// nothing pending owes nothing, however long the clock is left alone.
493    fn ticks(&mut self, a: &mut dyn Layer, lane: &LaneKey, out: &mut Vec<Failure>) {
494        let mut frames = Frames::new();
495        let _ = a.encode(
496            lane,
497            Self::sdu(usize::from(self.above.tx_max_sdu), 5),
498            self.now,
499            &mut frames,
500        );
501        let mut now = self.now;
502        let mut steps = 0;
503        loop {
504            let (_, _, next) = Self::tick(a, now);
505            match next {
506                None => break,
507                Some(deadline) if deadline < now => {
508                    out.push(Failure::new(
509                        "tick-terminates",
510                        format!("{} announced a deadline already past", a.kind()),
511                    ));
512                    break;
513                }
514                Some(deadline) => now = deadline.max(now + Duration::from_millis(1)),
515            }
516            steps += 1;
517            if steps > 1_000 {
518                out.push(Failure::new(
519                    "tick-terminates",
520                    format!(
521                        "{} still announced a deadline after 1000 ticks with nothing arriving",
522                        a.kind()
523                    ),
524                ));
525                break;
526            }
527        }
528        let (down, up, next) = Self::tick(a, now + Duration::from_secs(3_600));
529        if !down.is_empty() || !up.is_empty() {
530            out.push(Failure::new(
531                "tick-owes-nothing-unannounced",
532                format!(
533                    "{} owed {} frames down and {} up on a tick after it said nothing was pending",
534                    a.kind(),
535                    down.len(),
536                    up.len()
537                ),
538            ));
539        }
540        if next.is_some() {
541            out.push(Failure::new(
542                "tick-owes-nothing-unannounced",
543                format!("{} announced a deadline out of nothing", a.kind()),
544            ));
545        }
546        self.now = now;
547    }
548
549    fn counters(&self, a: &dyn Layer, out: &mut Vec<Failure>) {
550        for c in a.counters() {
551            if c.scope != a.kind() {
552                out.push(Failure::new(
553                    "counters-are-scoped-by-kind",
554                    format!(
555                        "{} keeps a counter scoped {:?}: a layer's counters are its own, under \
556                         its kind",
557                        a.kind(),
558                        c.scope
559                    ),
560                ));
561            }
562        }
563    }
564}
565
566// --- reference layers ------------------------------------------------------
567
568/// A layer that changes nothing: the kit's positive control, and what the
569/// driver's `Stack` is held to in the medium kit's decorator check.
570#[derive(Debug, Default)]
571pub struct Identity;
572
573impl Layer for Identity {
574    fn kind(&self) -> &'static str {
575        "identity"
576    }
577    fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
578        Ok(*below)
579    }
580    fn encode(
581        &mut self,
582        lane: &LaneKey,
583        sdu: Sdu,
584        _now: Instant,
585        out: &mut Frames,
586    ) -> Result<(), LayerError> {
587        out.push((lane.clone(), sdu));
588        Ok(())
589    }
590    fn decode(&mut self, lane: &LaneKey, frame: Sdu, _now: Instant, out: &mut Frames) -> Decoded {
591        out.push((lane.clone(), frame));
592        Decoded::Accepted
593    }
594}
595
596/// A layer with `bytes` of header per SDU and nothing to say in it: what the
597/// driver's test-only `layer-overhead` feature configures, so the capability
598/// arithmetic, the floor and the counters pipe are tested without a real
599/// layer. Counts the SDUs it carried as `sdus_total`.
600#[derive(Debug)]
601pub struct Overhead {
602    bytes: u16,
603    sdus: u64,
604}
605
606impl Overhead {
607    /// The header byte, so a frame that is not this layer's is refused.
608    pub const MARK: u8 = 0xA5;
609
610    /// `bytes` of header per SDU.
611    #[must_use]
612    pub fn new(bytes: u16) -> Self {
613        Self { bytes, sdus: 0 }
614    }
615}
616
617impl Layer for Overhead {
618    fn kind(&self) -> &'static str {
619        "overhead"
620    }
621    fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
622        if below.tx_max_sdu <= self.bytes || below.rx_max_sdu <= self.bytes {
623            return Err(LayerError::TooSmallBelow {
624                layer: "overhead",
625                needs: self.bytes.saturating_add(1),
626                below: below.tx_max_sdu.min(below.rx_max_sdu),
627            });
628        }
629        let mut c = *below;
630        c.tx_max_sdu -= self.bytes;
631        c.rx_max_sdu -= self.bytes;
632        Ok(c)
633    }
634    fn encode(
635        &mut self,
636        lane: &LaneKey,
637        sdu: Sdu,
638        _now: Instant,
639        out: &mut Frames,
640    ) -> Result<(), LayerError> {
641        let mut frame = vec![Self::MARK; usize::from(self.bytes)];
642        frame.extend_from_slice(&sdu);
643        self.sdus += 1;
644        out.push((lane.clone(), frame));
645        Ok(())
646    }
647    fn decode(&mut self, lane: &LaneKey, frame: Sdu, _now: Instant, out: &mut Frames) -> Decoded {
648        let n = usize::from(self.bytes);
649        if frame.len() < n || frame[..n].iter().any(|b| *b != Self::MARK) {
650            return Decoded::refused("malformed", "overhead: not this layer's header");
651        }
652        out.push((lane.clone(), frame[n..].to_vec()));
653        Decoded::Accepted
654    }
655    fn counters(&self) -> Vec<Counter> {
656        vec![Counter::new("overhead", "sdus_total", self.sdus)]
657    }
658}
659
660/// A layer that turns every SDU into `n` frames and reassembles them: the
661/// kit's and the driver's test of a one-to-many transform, of backpressure
662/// through a send that becomes several, and of a deadline (an incomplete
663/// reassembly is dropped after [`Split::TIMEOUT`], counted as
664/// `incomplete_total`).
665///
666/// Frame: `| seq | index | n | chunk |`. The SDU it offers upward is three
667/// bytes smaller than the frame below, so every chunk fits.
668/// When a packet's first fragment arrived, and the fragments so far.
669type Reassembly = (Instant, Vec<Option<Sdu>>);
670
671#[derive(Debug)]
672pub struct Split {
673    n: u8,
674    seq: u8,
675    pending: BTreeMap<(LaneKey, u8), Reassembly>,
676    incomplete: u64,
677}
678
679impl Split {
680    /// How long an incomplete reassembly is kept.
681    pub const TIMEOUT: Duration = Duration::from_secs(1);
682
683    /// `n` frames per SDU, 1 to 255.
684    #[must_use]
685    pub fn new(n: u8) -> Self {
686        Self {
687            n: n.max(1),
688            seq: 0,
689            pending: BTreeMap::new(),
690            incomplete: 0,
691        }
692    }
693}
694
695impl Layer for Split {
696    fn kind(&self) -> &'static str {
697        "split"
698    }
699    fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
700        if below.tx_max_sdu <= 3 || below.rx_max_sdu <= 3 {
701            return Err(LayerError::TooSmallBelow {
702                layer: "split",
703                needs: 4,
704                below: below.tx_max_sdu.min(below.rx_max_sdu),
705            });
706        }
707        let mut c = *below;
708        c.tx_max_sdu -= 3;
709        c.rx_max_sdu -= 3;
710        Ok(c)
711    }
712    fn encode(
713        &mut self,
714        lane: &LaneKey,
715        sdu: Sdu,
716        _now: Instant,
717        out: &mut Frames,
718    ) -> Result<(), LayerError> {
719        let seq = self.seq;
720        self.seq = self.seq.wrapping_add(1);
721        let n = usize::from(self.n);
722        let chunk = sdu.len().div_ceil(n).max(1);
723        for i in 0..n {
724            let start = (i * chunk).min(sdu.len());
725            let end = ((i + 1) * chunk).min(sdu.len());
726            let mut frame = vec![seq, i as u8, self.n];
727            frame.extend_from_slice(&sdu[start..end]);
728            out.push((lane.clone(), frame));
729        }
730        Ok(())
731    }
732    fn decode(&mut self, lane: &LaneKey, frame: Sdu, now: Instant, out: &mut Frames) -> Decoded {
733        if frame.len() < 3 || frame[2] == 0 || frame[1] >= frame[2] {
734            return Decoded::refused("malformed", "split: not this layer's header");
735        }
736        let (seq, index, n) = (frame[0], usize::from(frame[1]), usize::from(frame[2]));
737        let key = (lane.clone(), seq);
738        let entry = self
739            .pending
740            .entry(key.clone())
741            .or_insert_with(|| (now, vec![None; n]));
742        if entry.1.len() != n {
743            return Decoded::refused("malformed", "split: a frame count that changed mid-packet");
744        }
745        entry.0 = now;
746        entry.1[index] = Some(frame[3..].to_vec());
747        if entry.1.iter().all(Option::is_some) {
748            let (_, parts) = self.pending.remove(&key).expect("present");
749            let sdu: Sdu = parts.into_iter().flatten().flatten().collect();
750            out.push((lane.clone(), sdu));
751        }
752        Decoded::Accepted
753    }
754    fn tick(&mut self, now: Instant, _down: &mut Frames, _up: &mut Frames) -> Option<Instant> {
755        let before = self.pending.len();
756        self.pending
757            .retain(|_, (at, _)| now.duration_since(*at) < Self::TIMEOUT);
758        self.incomplete += (before - self.pending.len()) as u64;
759        self.pending
760            .values()
761            .map(|(at, _)| *at + Self::TIMEOUT)
762            .min()
763    }
764    fn counters(&self) -> Vec<Counter> {
765        vec![Counter::new("split", "incomplete_total", self.incomplete)]
766    }
767}
768
769#[cfg(test)]
770mod tests {
771    use super::*;
772    use crate::{Duplex, Scope, SecurityProperties};
773
774    fn below() -> Capabilities {
775        Capabilities::new(220, 220, Duplex::Half, false)
776    }
777
778    fn lane(endpoint: &str) -> LaneKey {
779        LaneKey {
780            endpoint: crate::EndpointId::new(endpoint),
781            reliable: false,
782            rank: 0,
783        }
784    }
785
786    fn names(failures: &[Failure]) -> Vec<&str> {
787        let mut v: Vec<&str> = failures.iter().map(|f| f.check).collect();
788        v.sort_unstable();
789        v.dedup();
790        v
791    }
792
793    #[test]
794    fn the_reference_layers_pass() {
795        for (name, mut l) in [
796            ("identity", Box::new(Identity) as Box<dyn Layer>),
797            ("overhead", Box::new(Overhead::new(6))),
798            ("split", Box::new(Split::new(3))),
799        ] {
800            let failures = layer(l.as_mut(), &below(), &[lane("b")]);
801            assert!(failures.is_empty(), "{name}: {failures:?}");
802        }
803        let mut a = Overhead::new(4);
804        let mut b = Overhead::new(4);
805        let failures = pair(&mut a, &mut b, &below(), &[lane("b")], &[lane("a")]);
806        assert!(failures.is_empty(), "{failures:?}");
807    }
808
809    #[test]
810    fn split_reassembles_in_any_order_and_drops_an_incomplete_packet_on_time() {
811        let mut s = Split::new(3);
812        let t0 = Instant::now();
813        let mut frames = Frames::new();
814        s.encode(&lane("b"), (0..10u8).collect(), t0, &mut frames)
815            .unwrap();
816        assert_eq!(frames.len(), 3);
817        frames.swap(0, 2);
818        let mut got = Frames::new();
819        for (l, f) in frames {
820            assert_eq!(s.decode(&l, f, t0, &mut got), Decoded::Accepted);
821        }
822        assert_eq!(got, vec![(lane("b"), (0..10u8).collect::<Vec<_>>())]);
823        // One fragment of the next packet, then nothing: the deadline is
824        // announced, and kept.
825        let mut frames = Frames::new();
826        s.encode(&lane("b"), vec![1; 9], t0, &mut frames).unwrap();
827        let mut got = Frames::new();
828        s.decode(&lane("b"), frames[0].1.clone(), t0, &mut got);
829        assert!(got.is_empty());
830        let (_, _, next) = Kit::tick(&mut s, t0);
831        assert_eq!(next, Some(t0 + Split::TIMEOUT));
832        let (_, _, next) = Kit::tick(&mut s, t0 + Split::TIMEOUT);
833        assert_eq!(next, None);
834        assert_eq!(s.counters()[0].value, 1);
835    }
836
837    /// A pass-through body shared by the layers written to fail one check.
838    macro_rules! passes_through {
839        () => {
840            fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
841                Ok(*below)
842            }
843            fn encode(
844                &mut self,
845                lane: &LaneKey,
846                sdu: Sdu,
847                _: Instant,
848                out: &mut Frames,
849            ) -> Result<(), LayerError> {
850                out.push((lane.clone(), sdu));
851                Ok(())
852            }
853            fn decode(
854                &mut self,
855                lane: &LaneKey,
856                frame: Sdu,
857                _: Instant,
858                out: &mut Frames,
859            ) -> Decoded {
860                out.push((lane.clone(), frame));
861                Decoded::Accepted
862            }
863        };
864    }
865
866    /// Declares four bytes, adds six.
867    struct LiesAboutOverhead;
868    impl Layer for LiesAboutOverhead {
869        fn kind(&self) -> &'static str {
870            "liar"
871        }
872        fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
873            let mut c = *below;
874            c.tx_max_sdu -= 4;
875            c.rx_max_sdu -= 4;
876            Ok(c)
877        }
878        fn encode(
879            &mut self,
880            lane: &LaneKey,
881            sdu: Sdu,
882            _: Instant,
883            out: &mut Frames,
884        ) -> Result<(), LayerError> {
885            let mut f = vec![0; 6];
886            f.extend(sdu);
887            out.push((lane.clone(), f));
888            Ok(())
889        }
890        fn decode(&mut self, lane: &LaneKey, frame: Sdu, _: Instant, out: &mut Frames) -> Decoded {
891            out.push((lane.clone(), frame[6.min(frame.len())..].to_vec()));
892            Decoded::Accepted
893        }
894    }
895
896    /// Claims integrity and anti-replay, checks nothing, counts nothing.
897    struct Credulous;
898    impl Layer for Credulous {
899        fn kind(&self) -> &'static str {
900            "credulous"
901        }
902        passes_through!();
903        fn security(&self, _: Option<&SecurityProperties>) -> Option<SecurityProperties> {
904            Some(
905                SecurityProperties::new("credulous", Scope::Hop)
906                    .guarantee(Guarantee::Integrity)
907                    .guarantee(Guarantee::AntiReplay),
908            )
909        }
910    }
911
912    /// A one-byte XOR "integrity" check: refuses what it should, and no
913    /// counter moves.
914    struct SilentRefuser;
915    impl SilentRefuser {
916        fn xor(body: &[u8]) -> u8 {
917            body.iter().fold(0x5A, |a, b| a ^ b)
918        }
919    }
920    impl Layer for SilentRefuser {
921        fn kind(&self) -> &'static str {
922            "silent"
923        }
924        fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
925            let mut c = *below;
926            c.tx_max_sdu -= 1;
927            c.rx_max_sdu -= 1;
928            Ok(c)
929        }
930        fn encode(
931            &mut self,
932            lane: &LaneKey,
933            sdu: Sdu,
934            _: Instant,
935            out: &mut Frames,
936        ) -> Result<(), LayerError> {
937            let mut f = vec![Self::xor(&sdu)];
938            f.extend(sdu);
939            out.push((lane.clone(), f));
940            Ok(())
941        }
942        fn decode(&mut self, lane: &LaneKey, frame: Sdu, _: Instant, out: &mut Frames) -> Decoded {
943            if frame.is_empty() || Self::xor(&frame[1..]) != frame[0] {
944                return Decoded::refused("auth-failed", "silent: refused");
945            }
946            out.push((lane.clone(), frame[1..].to_vec()));
947            Decoded::Accepted
948        }
949        fn security(&self, _: Option<&SecurityProperties>) -> Option<SecurityProperties> {
950            Some(SecurityProperties::new("silent", Scope::Hop).guarantee(Guarantee::Integrity))
951        }
952    }
953
954    /// Always wants another tick, one millisecond on.
955    struct Restless;
956    impl Layer for Restless {
957        fn kind(&self) -> &'static str {
958            "restless"
959        }
960        passes_through!();
961        fn tick(&mut self, now: Instant, _: &mut Frames, _: &mut Frames) -> Option<Instant> {
962            Some(now + Duration::from_millis(1))
963        }
964    }
965
966    /// Owes a frame on every tick, having announced none.
967    struct Chatty;
968    impl Layer for Chatty {
969        fn kind(&self) -> &'static str {
970            "chatty"
971        }
972        passes_through!();
973        fn tick(&mut self, _: Instant, down: &mut Frames, _: &mut Frames) -> Option<Instant> {
974            down.push((lane("b"), vec![0]));
975            None
976        }
977    }
978
979    /// Keeps a counter under somebody else's name.
980    struct Misfiled;
981    impl Layer for Misfiled {
982        fn kind(&self) -> &'static str {
983            "misfiled"
984        }
985        passes_through!();
986        fn counters(&self) -> Vec<Counter> {
987            vec![Counter::new("sdu", "sdus_total", 1)]
988        }
989    }
990
991    /// Encodes onto a lane it never asked the layer below for.
992    struct Misroutes;
993    impl Layer for Misroutes {
994        fn kind(&self) -> &'static str {
995            "misroutes"
996        }
997        fn capabilities(&self, below: &Capabilities) -> Result<Capabilities, LayerError> {
998            Ok(*below)
999        }
1000        fn encode(
1001            &mut self,
1002            _: &LaneKey,
1003            sdu: Sdu,
1004            _: Instant,
1005            out: &mut Frames,
1006        ) -> Result<(), LayerError> {
1007            out.push((lane("nowhere"), sdu));
1008            Ok(())
1009        }
1010        fn decode(&mut self, lane: &LaneKey, frame: Sdu, _: Instant, out: &mut Frames) -> Decoded {
1011            out.push((lane.clone(), frame));
1012            Decoded::Accepted
1013        }
1014    }
1015
1016    #[test]
1017    fn each_check_catches_the_layer_written_to_fail_it() {
1018        let cases: Vec<(Box<dyn Layer>, &[&str])> = vec![
1019            (Box::new(LiesAboutOverhead), &["overhead-is-declared"]),
1020            (
1021                Box::new(Credulous),
1022                &["integrity-is-enforced", "refusal-is-counted"],
1023            ),
1024            (Box::new(SilentRefuser), &["refusal-is-counted"]),
1025            (
1026                Box::new(Restless),
1027                &["tick-owes-nothing-unannounced", "tick-terminates"],
1028            ),
1029            (
1030                Box::new(Chatty),
1031                &["round-trip-is-identity", "tick-owes-nothing-unannounced"],
1032            ),
1033            (Box::new(Misfiled), &["counters-are-scoped-by-kind"]),
1034            (
1035                Box::new(Misroutes),
1036                &["lanes-map-back", "round-trip-is-identity"],
1037            ),
1038        ];
1039        for (mut l, expect) in cases {
1040            let kind = l.kind();
1041            let failures = layer(l.as_mut(), &below(), &[lane("b")]);
1042            assert_eq!(names(&failures), *expect, "{kind}: {failures:?}");
1043        }
1044    }
1045}