Skip to main content

oxirs_cluster/simulation/
mod.rs

1//! In-memory cluster simulation for scalability testing.
2//!
3//! `SimCluster` runs N virtual nodes in a single tokio runtime with bounded
4//! mailbox channels.  No real network sockets are created; all inter-node
5//! communication is through `tokio::sync::mpsc` queues.
6//!
7//! This module is available under `#[cfg(any(test, feature = "simulation"))]`
8//! to avoid adding compile-time weight to production builds.
9//!
10//! # Example
11//!
12//! ```rust
13//! # #[cfg(feature = "simulation")]
14//! # {
15//! use oxirs_cluster::simulation::SimCluster;
16//!
17//! let cluster = SimCluster::new(10);
18//! assert_eq!(cluster.size(), 10);
19//! # }
20//! ```
21
22pub mod scaling_bench;
23
24use std::collections::HashMap;
25use tokio::sync::mpsc;
26
27/// Messages exchanged between simulated nodes.
28#[derive(Debug, Clone)]
29pub enum SimMessage {
30    /// A gossip payload from one node to another.
31    Gossip {
32        /// Sender node ID.
33        from: u64,
34        /// Arbitrary payload bytes.
35        data: Vec<u8>,
36    },
37    /// Heartbeat ping from `from` to its recipient.
38    Ping(u64),
39    /// Heartbeat pong reply.
40    Pong(u64),
41}
42
43/// A single simulated cluster node with inbox and named outboxes.
44pub struct SimNode {
45    /// Unique identifier for this node.
46    pub id: u64,
47    /// Receiving end of this node's mailbox.
48    pub inbox: mpsc::Receiver<SimMessage>,
49    /// Sending ends to all *other* nodes (including self, for simplicity).
50    pub outboxes: HashMap<u64, mpsc::Sender<SimMessage>>,
51}
52
53/// An in-memory cluster of N simulated nodes with bounded mailboxes.
54///
55/// Construction is O(N) time and O(N²) channel handles (each node holds a
56/// sender to every other node, which is acceptable for simulation use up to
57/// a few thousand nodes).
58pub struct SimCluster {
59    /// All simulated nodes.
60    nodes: Vec<SimNode>,
61    /// Shared sending handles keyed by node ID (for `gossip` helper).
62    senders: HashMap<u64, mpsc::Sender<SimMessage>>,
63}
64
65impl SimCluster {
66    /// Mailbox capacity per node.
67    const MAILBOX_CAPACITY: usize = 256;
68
69    /// Create a cluster of `n` simulated nodes with bounded mailboxes.
70    ///
71    /// Each node receives its own `mpsc::Receiver` and a clone of every
72    /// sender, so any node can message any other without coordination.
73    pub fn new(n: usize) -> Self {
74        // Build sender+receiver pairs for every node.
75        let mut senders: HashMap<u64, mpsc::Sender<SimMessage>> = HashMap::with_capacity(n);
76        let mut receivers: HashMap<u64, mpsc::Receiver<SimMessage>> = HashMap::with_capacity(n);
77
78        for i in 0..n as u64 {
79            let (tx, rx) = mpsc::channel::<SimMessage>(Self::MAILBOX_CAPACITY);
80            senders.insert(i, tx);
81            receivers.insert(i, rx);
82        }
83
84        // Build SimNode instances; each node clones the full sender map.
85        // `receivers.remove` is infallible here because we just inserted each key.
86        let nodes: Vec<SimNode> = (0..n as u64)
87            .map(|i| {
88                let outboxes = senders.clone();
89                let inbox = receivers
90                    .remove(&i)
91                    .unwrap_or_else(|| unreachable!("receiver for node {i} was just inserted"));
92                SimNode {
93                    id: i,
94                    inbox,
95                    outboxes,
96                }
97            })
98            .collect();
99
100        SimCluster { nodes, senders }
101    }
102
103    /// Number of nodes in the cluster.
104    pub fn size(&self) -> usize {
105        self.nodes.len()
106    }
107
108    /// Send a gossip message from `from` to `to`.
109    ///
110    /// Returns `Err` if `to` is unknown or the mailbox is full.
111    pub async fn gossip(&self, from: u64, to: u64, data: Vec<u8>) -> Result<(), String> {
112        let sender = self
113            .senders
114            .get(&to)
115            .ok_or_else(|| format!("no node with id {to}"))?;
116        sender
117            .send(SimMessage::Gossip { from, data })
118            .await
119            .map_err(|e| e.to_string())
120    }
121
122    /// Send a ping from `from` to `to`.
123    ///
124    /// Returns `Err` if `to` is unknown or the mailbox is full.
125    pub async fn ping(&self, from: u64, to: u64) -> Result<(), String> {
126        let sender = self
127            .senders
128            .get(&to)
129            .ok_or_else(|| format!("no node with id {to}"))?;
130        sender
131            .send(SimMessage::Ping(from))
132            .await
133            .map_err(|e| e.to_string())
134    }
135
136    /// Immutable borrow of the node list.
137    pub fn nodes(&self) -> &[SimNode] {
138        &self.nodes
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    #[test]
147    fn test_sim_cluster_empty() {
148        let c = SimCluster::new(0);
149        assert_eq!(c.size(), 0);
150    }
151
152    #[test]
153    fn test_sim_cluster_single_node() {
154        let c = SimCluster::new(1);
155        assert_eq!(c.size(), 1);
156    }
157
158    #[test]
159    fn test_sim_cluster_10_nodes() {
160        let c = SimCluster::new(10);
161        assert_eq!(c.size(), 10);
162    }
163
164    #[test]
165    fn test_sim_cluster_1000_nodes() {
166        let c = SimCluster::new(1000);
167        assert_eq!(c.size(), 1000);
168    }
169
170    #[tokio::test]
171    async fn test_gossip_delivery() {
172        let cluster = SimCluster::new(3);
173        let result = cluster.gossip(0, 1, b"hello".to_vec()).await;
174        assert!(result.is_ok(), "gossip delivery should succeed");
175    }
176
177    #[tokio::test]
178    async fn test_gossip_unknown_target() {
179        let cluster = SimCluster::new(3);
180        let result = cluster.gossip(0, 999, b"hello".to_vec()).await;
181        assert!(result.is_err(), "gossip to unknown node should fail");
182    }
183
184    #[tokio::test]
185    async fn test_ping_delivery() {
186        let cluster = SimCluster::new(2);
187        let result = cluster.ping(0, 1).await;
188        assert!(result.is_ok());
189    }
190}