mockforge-chaos 0.3.21

Chaos engineering features for MockForge - fault injection and resilience testing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Distributed chaos coordination
//!
//! Coordinate chaos orchestrations across distributed systems with leader election,
//! state synchronization, and distributed consensus.

use crate::scenario_orchestrator::OrchestratedScenario;
use chrono::{DateTime, Utc};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::mpsc;
use tracing::{debug, info, warn};

/// Node in the distributed system
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Node {
    pub id: String,
    pub address: String,
    pub region: Option<String>,
    pub zone: Option<String>,
    pub capabilities: Vec<String>,
    pub last_heartbeat: DateTime<Utc>,
    pub status: NodeStatus,
}

/// Node status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum NodeStatus {
    Active,
    Inactive,
    Degraded,
    Failed,
}

/// Leader election state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LeaderState {
    pub leader_id: Option<String>,
    pub term: u64,
    pub elected_at: Option<DateTime<Utc>>,
}

/// Distributed orchestration task
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DistributedTask {
    pub id: String,
    pub orchestration: OrchestratedScenario,
    pub target_nodes: Vec<String>,
    pub coordination_mode: CoordinationMode,
    pub created_at: DateTime<Utc>,
    pub started_at: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
    pub status: TaskStatus,
}

/// Coordination mode for distributed execution
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CoordinationMode {
    /// All nodes execute in parallel
    Parallel,
    /// One node at a time
    Sequential,
    /// Leader assigns tasks
    LeaderAssigned,
    /// Nodes coordinate amongst themselves
    PeerToPeer,
}

/// Task status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum TaskStatus {
    Pending,
    Running,
    Completed,
    Failed,
    Cancelled,
}

/// Node execution state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeExecutionState {
    pub node_id: String,
    pub task_id: String,
    pub status: TaskStatus,
    pub progress: f64,
    pub started_at: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
    pub error: Option<String>,
    pub metrics: ExecutionMetrics,
}

/// Execution metrics for a node
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ExecutionMetrics {
    pub steps_completed: usize,
    pub steps_total: usize,
    pub events_generated: usize,
    pub errors: usize,
    pub avg_latency_ms: f64,
}

/// Distributed coordinator
pub struct DistributedCoordinator {
    /// Current node ID
    node_id: String,
    /// Registered nodes
    nodes: Arc<RwLock<HashMap<String, Node>>>,
    /// Leader state
    leader_state: Arc<RwLock<LeaderState>>,
    /// Active tasks
    tasks: Arc<RwLock<HashMap<String, DistributedTask>>>,
    /// Node execution states
    execution_states: Arc<RwLock<HashMap<String, NodeExecutionState>>>,
    /// Control channel
    control_tx: Option<mpsc::Sender<CoordinatorControl>>,
}

/// Coordinator control commands
enum CoordinatorControl {
    RegisterNode(Node),
    UnregisterNode(String),
    SubmitTask(DistributedTask),
    Heartbeat(String),
    TriggerElection,
}

impl DistributedCoordinator {
    /// Create a new distributed coordinator
    pub fn new(node_id: impl Into<String>) -> Self {
        Self {
            node_id: node_id.into(),
            nodes: Arc::new(RwLock::new(HashMap::new())),
            leader_state: Arc::new(RwLock::new(LeaderState {
                leader_id: None,
                term: 0,
                elected_at: None,
            })),
            tasks: Arc::new(RwLock::new(HashMap::new())),
            execution_states: Arc::new(RwLock::new(HashMap::new())),
            control_tx: None,
        }
    }

    /// Start the coordinator
    pub async fn start(&mut self) -> Result<(), String> {
        info!("Starting distributed coordinator for node {}", self.node_id);

        // Create control channel
        let (control_tx, mut control_rx) = mpsc::channel::<CoordinatorControl>(100);
        self.control_tx = Some(control_tx);

        // Clone Arc references for background task
        let node_id = self.node_id.clone();
        let nodes = Arc::clone(&self.nodes);
        let leader_state = Arc::clone(&self.leader_state);
        let tasks = Arc::clone(&self.tasks);
        let execution_states = Arc::clone(&self.execution_states);

        // Spawn coordinator task
        tokio::spawn(async move {
            Self::coordinator_task(
                node_id,
                nodes,
                leader_state,
                tasks,
                execution_states,
                &mut control_rx,
            )
            .await;
        });

        Ok(())
    }

    /// Coordinator background task
    async fn coordinator_task(
        node_id: String,
        nodes: Arc<RwLock<HashMap<String, Node>>>,
        leader_state: Arc<RwLock<LeaderState>>,
        tasks: Arc<RwLock<HashMap<String, DistributedTask>>>,
        _execution_states: Arc<RwLock<HashMap<String, NodeExecutionState>>>,
        control_rx: &mut mpsc::Receiver<CoordinatorControl>,
    ) {
        loop {
            tokio::select! {
                Some(cmd) = control_rx.recv() => {
                    match cmd {
                        CoordinatorControl::RegisterNode(node) => {
                            info!("Registering node: {}", node.id);
                            let mut nodes_guard = nodes.write();
                            nodes_guard.insert(node.id.clone(), node);
                        }
                        CoordinatorControl::UnregisterNode(id) => {
                            info!("Unregistering node: {}", id);
                            let mut nodes_guard = nodes.write();
                            nodes_guard.remove(&id);
                        }
                        CoordinatorControl::SubmitTask(task) => {
                            info!("Submitting task: {}", task.id);
                            let mut tasks_guard = tasks.write();
                            tasks_guard.insert(task.id.clone(), task);
                        }
                        CoordinatorControl::Heartbeat(node_id) => {
                            debug!("Heartbeat from node: {}", node_id);
                            let mut nodes_guard = nodes.write();
                            if let Some(node) = nodes_guard.get_mut(&node_id) {
                                node.last_heartbeat = Utc::now();
                            }
                        }
                        CoordinatorControl::TriggerElection => {
                            info!("Triggering leader election");
                            Self::elect_leader(&node_id, &nodes, &leader_state);
                        }
                    }
                }
                _ = tokio::time::sleep(tokio::time::Duration::from_secs(5)) => {
                    // Periodic health checks
                    Self::check_node_health(&nodes);

                    // Check if leader election needed
                    let needs_election = {
                        let state = leader_state.read();
                        state.leader_id.is_none()
                    };

                    if needs_election {
                        Self::elect_leader(&node_id, &nodes, &leader_state);
                    }
                }
            }
        }
    }

    /// Register a node
    pub async fn register_node(&self, node: Node) -> Result<(), String> {
        if let Some(ref tx) = self.control_tx {
            tx.send(CoordinatorControl::RegisterNode(node))
                .await
                .map_err(|e| format!("Failed to register node: {}", e))?;
            Ok(())
        } else {
            Err("Coordinator not started".to_string())
        }
    }

    /// Unregister a node
    pub async fn unregister_node(&self, node_id: &str) -> Result<(), String> {
        if let Some(ref tx) = self.control_tx {
            tx.send(CoordinatorControl::UnregisterNode(node_id.to_string()))
                .await
                .map_err(|e| format!("Failed to unregister node: {}", e))?;
            Ok(())
        } else {
            Err("Coordinator not started".to_string())
        }
    }

    /// Submit a distributed task
    pub async fn submit_task(&self, task: DistributedTask) -> Result<(), String> {
        if let Some(ref tx) = self.control_tx {
            tx.send(CoordinatorControl::SubmitTask(task))
                .await
                .map_err(|e| format!("Failed to submit task: {}", e))?;
            Ok(())
        } else {
            Err("Coordinator not started".to_string())
        }
    }

    /// Send heartbeat
    pub async fn heartbeat(&self) -> Result<(), String> {
        if let Some(ref tx) = self.control_tx {
            tx.send(CoordinatorControl::Heartbeat(self.node_id.clone()))
                .await
                .map_err(|e| format!("Failed to send heartbeat: {}", e))?;
            Ok(())
        } else {
            Err("Coordinator not started".to_string())
        }
    }

    /// Trigger leader election
    pub async fn trigger_election(&self) -> Result<(), String> {
        if let Some(ref tx) = self.control_tx {
            tx.send(CoordinatorControl::TriggerElection)
                .await
                .map_err(|e| format!("Failed to trigger election: {}", e))?;
            Ok(())
        } else {
            Err("Coordinator not started".to_string())
        }
    }

    /// Elect leader (simple implementation)
    fn elect_leader(
        _current_node_id: &str,
        nodes: &Arc<RwLock<HashMap<String, Node>>>,
        leader_state: &Arc<RwLock<LeaderState>>,
    ) {
        let nodes_guard = nodes.read();

        // Find active nodes
        let active_nodes: Vec<_> =
            nodes_guard.values().filter(|n| n.status == NodeStatus::Active).collect();

        if active_nodes.is_empty() {
            warn!("No active nodes for leader election");
            return;
        }

        // Simple election: node with lowest ID becomes leader
        let leader = active_nodes.iter().min_by(|a, b| a.id.cmp(&b.id)).unwrap();

        let mut state = leader_state.write();
        state.leader_id = Some(leader.id.clone());
        state.term += 1;
        state.elected_at = Some(Utc::now());

        info!("Leader elected: {} (term {})", leader.id, state.term);
    }

    /// Check node health
    fn check_node_health(nodes: &Arc<RwLock<HashMap<String, Node>>>) {
        let mut nodes_guard = nodes.write();
        let now = Utc::now();
        let timeout = chrono::Duration::seconds(30);

        for node in nodes_guard.values_mut() {
            if node.status == NodeStatus::Active {
                let since_heartbeat = now - node.last_heartbeat;
                if since_heartbeat > timeout {
                    warn!("Node {} missed heartbeat", node.id);
                    node.status = NodeStatus::Degraded;
                }
                if since_heartbeat > timeout * 2 {
                    warn!("Node {} failed (no heartbeat)", node.id);
                    node.status = NodeStatus::Failed;
                }
            }
        }
    }

    /// Get current leader
    pub fn get_leader(&self) -> Option<String> {
        let state = self.leader_state.read();
        state.leader_id.clone()
    }

    /// Check if this node is the leader
    pub fn is_leader(&self) -> bool {
        let state = self.leader_state.read();
        state.leader_id.as_ref() == Some(&self.node_id)
    }

    /// Get all registered nodes
    pub fn get_nodes(&self) -> Vec<Node> {
        let nodes = self.nodes.read();
        nodes.values().cloned().collect()
    }

    /// Get active nodes
    pub fn get_active_nodes(&self) -> Vec<Node> {
        let nodes = self.nodes.read();
        nodes.values().filter(|n| n.status == NodeStatus::Active).cloned().collect()
    }

    /// Get task status
    pub fn get_task(&self, task_id: &str) -> Option<DistributedTask> {
        let tasks = self.tasks.read();
        tasks.get(task_id).cloned()
    }

    /// Get all tasks
    pub fn get_tasks(&self) -> Vec<DistributedTask> {
        let tasks = self.tasks.read();
        tasks.values().cloned().collect()
    }

    /// Get node execution states for a task
    pub fn get_task_execution_states(&self, task_id: &str) -> Vec<NodeExecutionState> {
        let states = self.execution_states.read();
        states
            .iter()
            .filter(|(k, _)| k.starts_with(&format!("{}:", task_id)))
            .map(|(_, v)| v.clone())
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_coordinator_creation() {
        let coordinator = DistributedCoordinator::new("node-1");
        assert_eq!(coordinator.node_id, "node-1");
        assert!(!coordinator.is_leader());
    }

    #[test]
    fn test_node_status() {
        let node = Node {
            id: "node-1".to_string(),
            address: "127.0.0.1:8080".to_string(),
            region: Some("us-east-1".to_string()),
            zone: Some("us-east-1a".to_string()),
            capabilities: vec!["chaos".to_string()],
            last_heartbeat: Utc::now(),
            status: NodeStatus::Active,
        };

        assert_eq!(node.status, NodeStatus::Active);
    }

    #[tokio::test]
    async fn test_coordinator_start() {
        let mut coordinator = DistributedCoordinator::new("node-1");
        assert!(coordinator.start().await.is_ok());
    }

    #[tokio::test]
    async fn test_register_node() {
        let mut coordinator = DistributedCoordinator::new("node-1");
        coordinator.start().await.unwrap();

        let node = Node {
            id: "node-2".to_string(),
            address: "127.0.0.1:8081".to_string(),
            region: None,
            zone: None,
            capabilities: vec![],
            last_heartbeat: Utc::now(),
            status: NodeStatus::Active,
        };

        // Give the coordinator task time to start
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        assert!(coordinator.register_node(node).await.is_ok());

        // Wait for registration to process
        tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;

        let nodes = coordinator.get_nodes();
        assert!(nodes.iter().any(|n| n.id == "node-2"));
    }
}