Skip to main content

spacedb_sim/
network.rs

1//! The network model — the "noise".
2//!
3//! Every message a replica sends is subject to latency (a base plus random jitter),
4//! a drop probability, and — when active — a partition that severs the two sides.
5//! All randomness flows through the simulation's single seeded [`Rng`], so the noise
6//! is reproducible.
7
8use crate::rng::Rng;
9
10/// Per-message network behaviour.
11#[derive(Clone, Copy, Debug)]
12pub struct NetworkModel {
13    /// Minimum delivery delay, in ticks.
14    pub latency_base: u64,
15    /// Extra uniform jitter in `[0, latency_jitter]` ticks.
16    pub latency_jitter: u64,
17    /// Probability a message is dropped in flight.
18    pub drop_prob: f64,
19}
20
21impl NetworkModel {
22    /// A fast, lossless network.
23    pub fn perfect() -> Self {
24        Self {
25            latency_base: 1,
26            latency_jitter: 0,
27            drop_prob: 0.0,
28        }
29    }
30
31    /// A network with the given mean latency window and loss.
32    pub fn new(latency_base: u64, latency_jitter: u64, drop_prob: f64) -> Self {
33        Self {
34            latency_base,
35            latency_jitter,
36            drop_prob,
37        }
38    }
39
40    /// Draw a delivery delay.
41    pub fn delay(&self, rng: &mut Rng) -> u64 {
42        self.latency_base + rng.below(self.latency_jitter + 1)
43    }
44
45    /// Whether this message is dropped.
46    pub fn drops(&self, rng: &mut Rng) -> bool {
47        rng.chance(self.drop_prob)
48    }
49}
50
51/// A two-sided network partition: replicas on different sides cannot reach each
52/// other until it heals.
53#[derive(Clone, Debug)]
54pub struct Partition {
55    /// Side (0 or 1) per replica index.
56    side: Vec<u8>,
57}
58
59impl Partition {
60    /// Put the replicas listed in `group_a` on one side and everyone else on the
61    /// other.
62    pub fn split(replicas: usize, group_a: &[usize]) -> Self {
63        let mut side = vec![0u8; replicas];
64        for &r in group_a {
65            if r < replicas {
66                side[r] = 1;
67            }
68        }
69        Self { side }
70    }
71
72    /// Whether `a` and `b` can currently reach each other.
73    pub fn connected(&self, a: usize, b: usize) -> bool {
74        self.side.get(a) == self.side.get(b)
75    }
76}