//! An in-memory, simulated-time network for client-against-host tests: two one-way links with optional loss, //! duplication and reordering (all from a seeded [`SeqRng`], so every run is the same), and a driver that shuttles //! datagrams between two sans-I/O endpoints, advancing the clock to the next delivery or deadline. use domistream::Instant; use super::SeqRng; /// One side of a session, as the wire drives it. pub trait Endpoint { /// The next datagram this side wants to send. fn transmit(&mut self, now: Instant) -> Option>; /// A datagram arrived. fn receive(&mut self, now: Instant, datagram: &[u8]); /// When this side wants [`Endpoint::tick`]. fn deadline(&self) -> Option; /// Timers. fn tick(&mut self, now: Instant); } /// What a one-way link does to datagrams. Rates are per mille. #[derive(Clone, Copy, Debug, Default)] pub struct Impair { pub loss: u32, pub duplicate: u32, /// Chance that a datagram is held back by up to `reorder_ms` extra. pub reorder: u32, pub reorder_ms: u64, /// Fixed one-way latency, ms. pub latency_ms: u64, } impl Impair { pub fn clean(latency_ms: u64) -> Self { Self { latency_ms, ..Self::default() } } pub fn lossy(loss: u32, latency_ms: u64) -> Self { Self { loss, duplicate: 20, reorder: 100, reorder_ms: 30, latency_ms } } } /// A one-way link. #[derive(Debug)] pub struct Link { pub impair: Impair, rng: SeqRng, queue: Vec<(u64, u64, Vec)>, order: u64, /// Datagrams handed to the link, and the ones it dropped. pub sent: usize, pub lost: usize, /// When set, every datagram is dropped (a peer that vanished). pub cut: bool, } impl Link { pub fn new(impair: Impair, seed: u64) -> Self { Self { impair, rng: SeqRng::new(seed), queue: Vec::new(), order: 0, sent: 0, lost: 0, cut: false } } fn chance(&mut self, per_mille: u32) -> bool { per_mille > 0 && (self.rng.below(1000) as u32) < per_mille } pub fn send(&mut self, now_ms: u64, datagram: Vec) { self.sent += 1; if self.cut || self.chance(self.impair.loss) { self.lost += 1; return; } let copies = if self.chance(self.impair.duplicate) { 2 } else { 1 }; for _ in 0..copies { let mut due = now_ms + self.impair.latency_ms; if self.impair.reorder_ms > 0 && self.chance(self.impair.reorder) { due += 1 + self.rng.below(self.impair.reorder_ms as usize) as u64; } self.order += 1; self.queue.push((due, self.order, datagram.clone())); } } pub fn next_due(&self) -> Option { self.queue.iter().map(|(d, _, _)| *d).min() } /// Datagrams due by `now_ms`, in delivery order. pub fn due(&mut self, now_ms: u64) -> Vec> { let mut ready: Vec<(u64, u64, Vec)> = Vec::new(); let mut rest = Vec::new(); for item in self.queue.drain(..) { if item.0 <= now_ms { ready.push(item) } else { rest.push(item) } } self.queue = rest; ready.sort_by_key(|(d, o, _)| (*d, *o)); ready.into_iter().map(|(_, _, d)| d).collect() } } pub fn ms(t: Instant) -> u64 { t.as_micros().div_ceil(1000) } pub fn at(ms: u64) -> Instant { Instant::from_micros(ms * 1000) } /// A client, a host and the two links between them. pub struct Wire { pub client: C, pub host: H, pub to_host: Link, pub to_client: Link, pub now_ms: u64, } impl Wire { pub fn new(client: C, host: H, to_host: Impair, to_client: Impair, seed: u64) -> Self { Self { client, host, to_host: Link::new(to_host, seed ^ 0xC2C2), to_client: Link::new(to_client, seed ^ 0x4848), now_ms: 0, } } /// Moves everything that can move at the current time (transmit, deliver, timers), until quiet. pub fn settle(&mut self) { for _ in 0..10_000 { let now = at(self.now_ms); let mut moved = false; if self.client.deadline().is_some_and(|t| t <= now) { self.client.tick(now); } if self.host.deadline().is_some_and(|t| t <= now) { self.host.tick(now); } while let Some(d) = self.client.transmit(now) { self.to_host.send(self.now_ms, d); moved = true; } while let Some(d) = self.host.transmit(now) { self.to_client.send(self.now_ms, d); moved = true; } for d in self.to_host.due(self.now_ms) { self.host.receive(now, &d); moved = true; } for d in self.to_client.due(self.now_ms) { self.client.receive(now, &d); moved = true; } if !moved { return; } } panic!("the wire never settles at {} ms", self.now_ms); } /// The next moment anything happens, if anything ever does. pub fn next_event(&self) -> Option { [ self.to_host.next_due(), self.to_client.next_due(), self.client.deadline().map(ms), self.host.deadline().map(ms), ] .into_iter() .flatten() .min() } /// Runs until `done` holds or `limit_ms` passes; returns whether `done` held. pub fn run_until(&mut self, limit_ms: u64, mut done: impl FnMut(&mut Self) -> bool) -> bool { loop { self.settle(); if done(self) { return true; } let next = self.next_event().unwrap_or(u64::MAX).max(self.now_ms + 1); if next > limit_ms { self.now_ms = limit_ms.max(self.now_ms); self.settle(); return done(self); } self.now_ms = next; } } /// Runs for `duration_ms` of simulated time. pub fn run_for(&mut self, duration_ms: u64) { let end = self.now_ms + duration_ms; self.run_until(end, |w| w.now_ms >= end); } }