1use serde::{Deserialize, Serialize};
7use std::collections::{HashMap, VecDeque};
8use std::sync::{Arc, RwLock};
9use std::time::{Duration, SystemTime};
10use tokio::sync::mpsc;
11use tokio::time::{interval, MissedTickBehavior};
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct ClusterMetrics {
16 pub node_metrics: HashMap<u64, NodeMetrics>,
18 pub cluster_metrics: ClusterWideMetrics,
20 pub historical_data: HistoricalMetrics,
22 pub alerts: Vec<PerformanceAlert>,
24}
25
26#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct NodeMetrics {
29 pub node_id: u64,
30 pub is_leader: bool,
31 pub uptime: Duration,
32
33 pub consensus_latency: Duration,
35 pub leader_elections: u64,
36 pub raft_log_size: u64,
37 pub commit_index: u64,
38
39 pub storage_size: u64,
41 pub triple_count: u64,
42 pub shard_count: u32,
43
44 pub network_latency: Duration,
46 pub bytes_sent: u64,
47 pub bytes_received: u64,
48 pub connection_count: u32,
49
50 pub operations_per_second: f64,
52 pub memory_usage: u64,
53 pub cpu_usage: f64,
54 pub disk_io: DiskIOMetrics,
55
56 pub error_rate: f64,
58 pub availability: f64,
59 pub last_heartbeat: SystemTime,
60}
61
62#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct ClusterWideMetrics {
65 pub total_nodes: u32,
66 pub active_nodes: u32,
67 pub cluster_health: f64, pub total_ops_per_second: f64,
71 pub average_latency: Duration,
72 pub peak_latency: Duration,
73 pub total_storage: u64,
74 pub total_triples: u64,
75
76 pub cluster_uptime: Duration,
78 pub consensus_stability: f64,
79 pub data_consistency: f64,
80 pub fault_tolerance_level: f64,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
85pub struct HistoricalMetrics {
86 pub hourly_stats: VecDeque<TimeSliceMetrics>,
87 pub daily_stats: VecDeque<TimeSliceMetrics>,
88 pub weekly_stats: VecDeque<TimeSliceMetrics>,
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct TimeSliceMetrics {
94 pub timestamp: SystemTime,
95 pub avg_ops_per_second: f64,
96 pub avg_latency: Duration,
97 pub peak_latency: Duration,
98 pub error_rate: f64,
99 pub active_nodes: u32,
100 pub total_operations: u64,
101}
102
103#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct DiskIOMetrics {
106 pub reads_per_second: f64,
107 pub writes_per_second: f64,
108 pub read_bandwidth: f64, pub write_bandwidth: f64, pub average_read_latency: Duration,
111 pub average_write_latency: Duration,
112}
113
114#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct PerformanceAlert {
117 pub alert_type: AlertType,
118 pub severity: AlertSeverity,
119 pub node_id: Option<u64>,
120 pub message: String,
121 pub timestamp: SystemTime,
122 pub threshold_value: f64,
123 pub actual_value: f64,
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub enum AlertType {
128 HighLatency,
129 LowThroughput,
130 ConsensusFailure,
131 NodeFailure,
132 StorageCapacity,
133 NetworkPartition,
134 MemoryPressure,
135 DiskIOSaturation,
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
139pub enum AlertSeverity {
140 Info,
141 Warning,
142 Critical,
143 Emergency,
144}
145
146#[derive(Debug, Clone)]
148pub struct PerformanceThresholds {
149 pub max_consensus_latency: Duration,
150 pub min_ops_per_second: f64,
151 pub max_error_rate: f64,
152 pub min_availability: f64,
153 pub max_memory_usage: f64,
154 pub max_cpu_usage: f64,
155 pub max_disk_usage: f64,
156 pub min_cluster_health: f64,
157}
158
159impl Default for PerformanceThresholds {
160 fn default() -> Self {
161 Self {
162 max_consensus_latency: Duration::from_millis(100),
163 min_ops_per_second: 100.0,
164 max_error_rate: 0.01, min_availability: 0.99, max_memory_usage: 0.8, max_cpu_usage: 0.8, max_disk_usage: 0.9, min_cluster_health: 0.95, }
171 }
172}
173
174pub struct PerformanceMonitor {
176 metrics: Arc<RwLock<ClusterMetrics>>,
177 thresholds: PerformanceThresholds,
178 alert_sender: mpsc::UnboundedSender<PerformanceAlert>,
179 collection_interval: Duration,
180 start_time: SystemTime,
181}
182
183impl PerformanceMonitor {
184 pub fn new(
186 thresholds: PerformanceThresholds,
187 ) -> (Self, mpsc::UnboundedReceiver<PerformanceAlert>) {
188 let (alert_sender, alert_receiver) = mpsc::unbounded_channel();
189
190 let monitor = Self {
191 metrics: Arc::new(RwLock::new(ClusterMetrics {
192 node_metrics: HashMap::new(),
193 cluster_metrics: ClusterWideMetrics::default(),
194 historical_data: HistoricalMetrics::default(),
195 alerts: Vec::new(),
196 })),
197 thresholds,
198 alert_sender,
199 collection_interval: Duration::from_secs(5),
200 start_time: SystemTime::now(),
201 };
202
203 (monitor, alert_receiver)
204 }
205
206 pub async fn start_monitoring(&self) {
208 let mut interval = interval(self.collection_interval);
209 interval.set_missed_tick_behavior(MissedTickBehavior::Skip);
210
211 loop {
212 interval.tick().await;
213
214 if let Err(e) = self.collect_metrics().await {
215 eprintln!("Error collecting metrics: {e}");
216 }
217
218 self.analyze_and_alert().await;
219 self.update_historical_data().await;
220 }
221 }
222
223 async fn collect_metrics(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
225 let mut node_metrics_map = std::collections::HashMap::new();
230 for node_id in 1..=5 {
231 let node_metrics = self.collect_node_metrics(node_id).await?;
232 node_metrics_map.insert(node_id, node_metrics);
233 }
234
235 {
237 let mut metrics = self.metrics.write().unwrap_or_else(|e| e.into_inner());
238 metrics.node_metrics = node_metrics_map;
239 metrics.cluster_metrics = self.calculate_cluster_metrics(&metrics.node_metrics);
241 }
242
243 Ok(())
244 }
245
246 async fn collect_node_metrics(
248 &self,
249 node_id: u64,
250 ) -> Result<NodeMetrics, Box<dyn std::error::Error + Send + Sync>> {
251 let base_latency = Duration::from_millis(10 + (node_id * 2));
255 let operations_per_second = 1000.0 + (node_id as f64 * 50.0);
256
257 Ok(NodeMetrics {
258 node_id,
259 is_leader: node_id == 1, uptime: self.start_time.elapsed().unwrap_or_default(),
261
262 consensus_latency: base_latency,
263 leader_elections: if node_id == 1 { 3 } else { 0 },
264 raft_log_size: 10000 + (node_id * 1000),
265 commit_index: 5000 + (node_id * 500),
266
267 storage_size: 1024 * 1024 * 100 * node_id, triple_count: 10000 * node_id,
269 shard_count: 10,
270
271 network_latency: Duration::from_millis(5),
272 bytes_sent: 1024 * 1024 * node_id,
273 bytes_received: 1024 * 1024 * node_id,
274 connection_count: 4, operations_per_second,
277 memory_usage: 1024 * 1024 * 200, cpu_usage: 0.3 + (node_id as f64 * 0.05),
279 disk_io: DiskIOMetrics {
280 reads_per_second: 100.0,
281 writes_per_second: 50.0,
282 read_bandwidth: 10.0,
283 write_bandwidth: 5.0,
284 average_read_latency: Duration::from_micros(100),
285 average_write_latency: Duration::from_micros(200),
286 },
287
288 error_rate: 0.001, availability: 0.999, last_heartbeat: SystemTime::now(),
291 })
292 }
293
294 fn calculate_cluster_metrics(
296 &self,
297 node_metrics: &HashMap<u64, NodeMetrics>,
298 ) -> ClusterWideMetrics {
299 let total_nodes = node_metrics.len() as u32;
300 let active_nodes = node_metrics
301 .values()
302 .filter(|m| m.last_heartbeat.elapsed().unwrap_or_default() < Duration::from_secs(30))
303 .count() as u32;
304
305 let total_ops_per_second: f64 =
306 node_metrics.values().map(|m| m.operations_per_second).sum();
307
308 let average_latency = if !node_metrics.is_empty() {
309 let total_latency: Duration = node_metrics.values().map(|m| m.consensus_latency).sum();
310 total_latency / node_metrics.len() as u32
311 } else {
312 Duration::default()
313 };
314
315 let peak_latency = node_metrics
316 .values()
317 .map(|m| m.consensus_latency)
318 .max()
319 .unwrap_or_default();
320
321 let total_storage: u64 = node_metrics.values().map(|m| m.storage_size).sum();
322
323 let total_triples: u64 = node_metrics.values().map(|m| m.triple_count).sum();
324
325 let avg_availability: f64 =
327 node_metrics.values().map(|m| m.availability).sum::<f64>() / total_nodes.max(1) as f64;
328
329 let cluster_health = if active_nodes == total_nodes {
330 avg_availability
331 } else {
332 avg_availability * (active_nodes as f64 / total_nodes as f64)
333 };
334
335 ClusterWideMetrics {
336 total_nodes,
337 active_nodes,
338 cluster_health,
339 total_ops_per_second,
340 average_latency,
341 peak_latency,
342 total_storage,
343 total_triples,
344 cluster_uptime: self.start_time.elapsed().unwrap_or_default(),
345 consensus_stability: 0.99, data_consistency: 1.0, fault_tolerance_level: (active_nodes.saturating_sub(1) as f64)
348 / total_nodes.max(1) as f64,
349 }
350 }
351
352 async fn analyze_and_alert(&self) {
354 let metrics = self.metrics.read().unwrap_or_else(|e| e.into_inner());
355
356 if metrics.cluster_metrics.average_latency > self.thresholds.max_consensus_latency {
358 self.send_alert(PerformanceAlert {
359 alert_type: AlertType::HighLatency,
360 severity: AlertSeverity::Warning,
361 node_id: None,
362 message: format!(
363 "Cluster average latency ({:?}) exceeds threshold ({:?})",
364 metrics.cluster_metrics.average_latency, self.thresholds.max_consensus_latency
365 ),
366 timestamp: SystemTime::now(),
367 threshold_value: self.thresholds.max_consensus_latency.as_millis() as f64,
368 actual_value: metrics.cluster_metrics.average_latency.as_millis() as f64,
369 });
370 }
371
372 if metrics.cluster_metrics.total_ops_per_second < self.thresholds.min_ops_per_second {
373 self.send_alert(PerformanceAlert {
374 alert_type: AlertType::LowThroughput,
375 severity: AlertSeverity::Warning,
376 node_id: None,
377 message: format!(
378 "Cluster throughput ({:.2} ops/s) below threshold ({:.2} ops/s)",
379 metrics.cluster_metrics.total_ops_per_second,
380 self.thresholds.min_ops_per_second
381 ),
382 timestamp: SystemTime::now(),
383 threshold_value: self.thresholds.min_ops_per_second,
384 actual_value: metrics.cluster_metrics.total_ops_per_second,
385 });
386 }
387
388 if metrics.cluster_metrics.cluster_health < self.thresholds.min_cluster_health {
389 self.send_alert(PerformanceAlert {
390 alert_type: AlertType::ConsensusFailure,
391 severity: AlertSeverity::Critical,
392 node_id: None,
393 message: format!(
394 "Cluster health ({:.2}) below threshold ({:.2})",
395 metrics.cluster_metrics.cluster_health, self.thresholds.min_cluster_health
396 ),
397 timestamp: SystemTime::now(),
398 threshold_value: self.thresholds.min_cluster_health,
399 actual_value: metrics.cluster_metrics.cluster_health,
400 });
401 }
402
403 for (node_id, node_metrics) in &metrics.node_metrics {
405 if node_metrics.availability < self.thresholds.min_availability {
407 self.send_alert(PerformanceAlert {
408 alert_type: AlertType::NodeFailure,
409 severity: AlertSeverity::Critical,
410 node_id: Some(*node_id),
411 message: format!(
412 "Node {} availability ({:.2}) below threshold ({:.2})",
413 node_id, node_metrics.availability, self.thresholds.min_availability
414 ),
415 timestamp: SystemTime::now(),
416 threshold_value: self.thresholds.min_availability,
417 actual_value: node_metrics.availability,
418 });
419 }
420
421 let memory_usage_ratio = node_metrics.memory_usage as f64 / (1024.0 * 1024.0 * 1024.0); if memory_usage_ratio > self.thresholds.max_memory_usage {
424 self.send_alert(PerformanceAlert {
425 alert_type: AlertType::MemoryPressure,
426 severity: AlertSeverity::Warning,
427 node_id: Some(*node_id),
428 message: format!(
429 "Node {} memory usage ({:.2}) exceeds threshold ({:.2})",
430 node_id, memory_usage_ratio, self.thresholds.max_memory_usage
431 ),
432 timestamp: SystemTime::now(),
433 threshold_value: self.thresholds.max_memory_usage,
434 actual_value: memory_usage_ratio,
435 });
436 }
437 }
438 }
439
440 fn send_alert(&self, alert: PerformanceAlert) {
442 if let Err(e) = self.alert_sender.send(alert.clone()) {
443 eprintln!("Failed to send alert: {e}");
444 }
445
446 let mut metrics = self.metrics.write().unwrap_or_else(|e| e.into_inner());
448 metrics.alerts.push(alert);
449
450 if metrics.alerts.len() > 1000 {
452 let excess = metrics.alerts.len() - 1000;
453 metrics.alerts.drain(0..excess);
454 }
455 }
456
457 async fn update_historical_data(&self) {
459 let mut metrics = self.metrics.write().unwrap_or_else(|e| e.into_inner());
460
461 let current_slice = TimeSliceMetrics {
462 timestamp: SystemTime::now(),
463 avg_ops_per_second: metrics.cluster_metrics.total_ops_per_second,
464 avg_latency: metrics.cluster_metrics.average_latency,
465 peak_latency: metrics.cluster_metrics.peak_latency,
466 error_rate: metrics
467 .node_metrics
468 .values()
469 .map(|m| m.error_rate)
470 .sum::<f64>()
471 / metrics.node_metrics.len().max(1) as f64,
472 active_nodes: metrics.cluster_metrics.active_nodes,
473 total_operations: 0, };
475
476 metrics
478 .historical_data
479 .hourly_stats
480 .push_back(current_slice.clone());
481 if metrics.historical_data.hourly_stats.len() > 24 * 12 {
482 metrics.historical_data.hourly_stats.pop_front();
484 }
485
486 if metrics.historical_data.hourly_stats.len() % 12 == 0 {
488 metrics
489 .historical_data
490 .daily_stats
491 .push_back(current_slice.clone());
492 if metrics.historical_data.daily_stats.len() > 30 {
493 metrics.historical_data.daily_stats.pop_front();
495 }
496 }
497
498 if metrics.historical_data.daily_stats.len() % 7 == 0 {
500 metrics
501 .historical_data
502 .weekly_stats
503 .push_back(current_slice);
504 if metrics.historical_data.weekly_stats.len() > 52 {
505 metrics.historical_data.weekly_stats.pop_front();
507 }
508 }
509 }
510
511 pub fn get_metrics(&self) -> ClusterMetrics {
513 self.metrics
514 .read()
515 .unwrap_or_else(|e| e.into_inner())
516 .clone()
517 }
518
519 pub fn get_performance_summary(&self) -> PerformanceSummary {
521 let metrics = self.metrics.read().unwrap_or_else(|e| e.into_inner());
522
523 PerformanceSummary {
524 cluster_health: metrics.cluster_metrics.cluster_health,
525 total_ops_per_second: metrics.cluster_metrics.total_ops_per_second,
526 average_latency: metrics.cluster_metrics.average_latency,
527 active_nodes: metrics.cluster_metrics.active_nodes,
528 total_nodes: metrics.cluster_metrics.total_nodes,
529 uptime: metrics.cluster_metrics.cluster_uptime,
530 recent_alerts: metrics.alerts.iter().rev().take(10).cloned().collect(),
531 }
532 }
533}
534
535#[derive(Debug, Clone, Serialize, Deserialize)]
537pub struct PerformanceSummary {
538 pub cluster_health: f64,
539 pub total_ops_per_second: f64,
540 pub average_latency: Duration,
541 pub active_nodes: u32,
542 pub total_nodes: u32,
543 pub uptime: Duration,
544 pub recent_alerts: Vec<PerformanceAlert>,
545}
546
547impl Default for ClusterWideMetrics {
548 fn default() -> Self {
549 Self {
550 total_nodes: 0,
551 active_nodes: 0,
552 cluster_health: 1.0,
553 total_ops_per_second: 0.0,
554 average_latency: Duration::default(),
555 peak_latency: Duration::default(),
556 total_storage: 0,
557 total_triples: 0,
558 cluster_uptime: Duration::default(),
559 consensus_stability: 1.0,
560 data_consistency: 1.0,
561 fault_tolerance_level: 0.0,
562 }
563 }
564}
565
566impl Default for HistoricalMetrics {
567 fn default() -> Self {
568 Self {
569 hourly_stats: VecDeque::with_capacity(24 * 12), daily_stats: VecDeque::with_capacity(30), weekly_stats: VecDeque::with_capacity(52), }
573 }
574}
575
576#[cfg(test)]
577mod tests {
578 use super::*;
579
580 #[tokio::test]
581 async fn test_performance_monitor_creation() {
582 let thresholds = PerformanceThresholds::default();
583 let (monitor, _alert_receiver) = PerformanceMonitor::new(thresholds);
584
585 monitor.collect_metrics().await.unwrap();
587
588 let metrics = monitor.get_metrics();
589 assert!(!metrics.node_metrics.is_empty());
590 }
591
592 #[test]
593 fn test_alert_generation() {
594 let alert = PerformanceAlert {
595 alert_type: AlertType::HighLatency,
596 severity: AlertSeverity::Warning,
597 node_id: Some(1),
598 message: "Test alert".to_string(),
599 timestamp: SystemTime::now(),
600 threshold_value: 100.0,
601 actual_value: 150.0,
602 };
603
604 assert_eq!(alert.severity, AlertSeverity::Warning);
605 assert_eq!(alert.node_id, Some(1));
606 }
607
608 #[test]
609 fn test_metrics_calculation() {
610 let mut node_metrics = HashMap::new();
611
612 for i in 1..=3 {
613 node_metrics.insert(
614 i,
615 NodeMetrics {
616 node_id: i,
617 is_leader: i == 1,
618 uptime: Duration::from_secs(3600),
619 consensus_latency: Duration::from_millis(50),
620 leader_elections: if i == 1 { 1 } else { 0 },
621 raft_log_size: 1000,
622 commit_index: 500,
623 storage_size: 1024 * 1024 * 100,
624 triple_count: 10000,
625 shard_count: 5,
626 network_latency: Duration::from_millis(10),
627 bytes_sent: 1024 * 1024,
628 bytes_received: 1024 * 1024,
629 connection_count: 2,
630 operations_per_second: 100.0,
631 memory_usage: 1024 * 1024 * 200,
632 cpu_usage: 0.5,
633 disk_io: DiskIOMetrics {
634 reads_per_second: 50.0,
635 writes_per_second: 25.0,
636 read_bandwidth: 5.0,
637 write_bandwidth: 2.5,
638 average_read_latency: Duration::from_micros(100),
639 average_write_latency: Duration::from_micros(200),
640 },
641 error_rate: 0.001,
642 availability: 0.99,
643 last_heartbeat: SystemTime::now(),
644 },
645 );
646 }
647
648 let thresholds = PerformanceThresholds::default();
649 let (monitor, _) = PerformanceMonitor::new(thresholds);
650 let cluster_metrics = monitor.calculate_cluster_metrics(&node_metrics);
651
652 assert_eq!(cluster_metrics.total_nodes, 3);
653 assert_eq!(cluster_metrics.active_nodes, 3);
654 assert_eq!(cluster_metrics.total_ops_per_second, 300.0);
655 assert!(cluster_metrics.cluster_health > 0.9);
656 }
657
658 #[test]
665 fn get_metrics_survives_poisoned_lock() {
666 let thresholds = PerformanceThresholds::default();
667 let (monitor, _alert_receiver) = PerformanceMonitor::new(thresholds);
668
669 let metrics_lock = Arc::clone(&monitor.metrics);
670 let join_result = std::thread::spawn(move || {
671 let _guard = metrics_lock.write().unwrap_or_else(|e| e.into_inner());
672 panic!("intentional poison for regression test");
673 })
674 .join();
675 assert!(join_result.is_err(), "spawned thread should have panicked");
676 assert!(
677 monitor.metrics.is_poisoned(),
678 "lock should be poisoned after the panic"
679 );
680
681 let _ = monitor.get_metrics();
683 let _ = monitor.get_performance_summary();
684 }
685}