ruvector_memopt/monitor/
realtime.rs1use std::sync::Arc;
4use std::time::Duration;
5use tokio::sync::RwLock;
6use crate::windows::memory::{MemoryStatus, WindowsMemoryOptimizer};
7
8pub struct RealtimeMonitor {
9 interval: Duration,
10 history: Arc<RwLock<Vec<MemorySnapshot>>>,
11 max_history: usize,
12}
13
14#[derive(Debug, Clone)]
15pub struct MemorySnapshot {
16 pub timestamp: chrono::DateTime<chrono::Local>,
17 pub status: MemoryStatus,
18}
19
20impl RealtimeMonitor {
21 pub fn new(interval_secs: u64) -> Self {
22 Self {
23 interval: Duration::from_secs(interval_secs),
24 history: Arc::new(RwLock::new(Vec::new())),
25 max_history: 3600, }
27 }
28
29 pub async fn start(&self) {
30 loop {
31 if let Ok(status) = WindowsMemoryOptimizer::get_memory_status() {
32 let snapshot = MemorySnapshot {
33 timestamp: chrono::Local::now(),
34 status,
35 };
36
37 let mut history = self.history.write().await;
38 if history.len() >= self.max_history {
39 history.remove(0);
40 }
41 history.push(snapshot);
42 }
43
44 tokio::time::sleep(self.interval).await;
45 }
46 }
47
48 pub async fn get_current(&self) -> Option<MemorySnapshot> {
49 let history = self.history.read().await;
50 history.last().cloned()
51 }
52
53 pub async fn get_history(&self, count: usize) -> Vec<MemorySnapshot> {
54 let history = self.history.read().await;
55 history.iter().rev().take(count).cloned().collect()
56 }
57
58 pub async fn get_stats(&self) -> MonitorStats {
59 let history = self.history.read().await;
60
61 if history.is_empty() {
62 return MonitorStats::default();
63 }
64
65 let loads: Vec<u32> = history.iter().map(|s| s.status.memory_load_percent).collect();
66 let avg_load = loads.iter().sum::<u32>() as f64 / loads.len() as f64;
67 let max_load = *loads.iter().max().unwrap_or(&0);
68 let min_load = *loads.iter().min().unwrap_or(&0);
69
70 MonitorStats {
71 sample_count: history.len(),
72 avg_memory_load: avg_load,
73 max_memory_load: max_load,
74 min_memory_load: min_load,
75 }
76 }
77}
78
79#[derive(Debug, Clone, Default)]
80pub struct MonitorStats {
81 pub sample_count: usize,
82 pub avg_memory_load: f64,
83 pub max_memory_load: u32,
84 pub min_memory_load: u32,
85}