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};
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
}
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
}
}
}
struct Pair<'a>(&'a mut dyn Layer, Option<&'a mut dyn Layer>);
impl Pair<'_> {
fn a(&mut self) -> &mut dyn Layer {
&mut *self.0
}
fn b(&mut self) -> &mut dyn Layer {
match &mut self.1 {
Some(b) => &mut **b,
None => &mut *self.0,
}
}
}
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(),
}
}
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)
}
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
),
));
}
}
}
}
fn overhead(&mut self, a: &mut dyn Layer, lane: &LaneKey, out: &mut Vec<Failure>) {
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()
),
));
}
}
}
}
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()),
));
}
}
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()),
));
}
}
}
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
),
));
}
}
}
}
#[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
}
}
#[derive(Debug)]
pub struct Overhead {
bytes: u16,
sdus: u64,
}
impl Overhead {
pub const MARK: u8 = 0xA5;
#[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)]
}
}
type Reassembly = (Instant, Vec<Option<Sdu>>);
#[derive(Debug)]
pub struct Split {
n: u8,
seq: u8,
pending: BTreeMap<(LaneKey, u8), Reassembly>,
incomplete: u64,
}
impl Split {
pub const TIMEOUT: Duration = Duration::from_secs(1);
#[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<_>>())]);
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);
}
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
}
};
}
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
}
}
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),
)
}
}
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))
}
}
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))
}
}
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
}
}
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)]
}
}
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:?}");
}
}
}