use crate::error::{RusTorchError, RusTorchResult};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
#[derive(Debug, Clone)]
pub struct MonitorConfig {
pub sampling_interval: Duration,
pub alert_thresholds: AlertThresholds,
pub enable_system_monitoring: bool,
}
impl Default for MonitorConfig {
fn default() -> Self {
Self {
sampling_interval: Duration::from_millis(100),
alert_thresholds: AlertThresholds::default(),
enable_system_monitoring: true,
}
}
}
#[derive(Debug, Clone)]
pub struct AlertThresholds {
pub cpu_threshold: f64,
pub memory_threshold: f64,
pub gpu_threshold: f64,
}
impl Default for AlertThresholds {
fn default() -> Self {
Self {
cpu_threshold: 90.0,
memory_threshold: 85.0,
gpu_threshold: 95.0,
}
}
}
#[derive(Debug, Clone)]
pub struct SystemAlert {
pub alert_type: AlertType,
pub message: String,
pub current_value: f64,
pub threshold: f64,
pub timestamp: Instant,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AlertType {
HighCpuUsage,
HighMemoryUsage,
HighGpuUsage,
PerformanceDegradation,
SystemOverload,
}
pub struct RealTimeMonitor {
config: MonitorConfig,
is_running: Arc<Mutex<bool>>,
alerts: Arc<Mutex<Vec<SystemAlert>>>,
}
impl RealTimeMonitor {
pub fn new(config: MonitorConfig) -> Self {
Self {
config,
is_running: Arc::new(Mutex::new(false)),
alerts: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn start(&self) -> RusTorchResult<()> {
let mut running = self
.is_running
.lock()
.map_err(|_| RusTorchError::Profiling {
message: "Failed to acquire running lock".to_string(),
})?;
if *running {
return Err(RusTorchError::Profiling {
message: "Monitor already running".to_string(),
});
}
*running = true;
println!("📡 Real-time monitoring started");
Ok(())
}
pub fn stop(&self) -> RusTorchResult<()> {
let mut running = self
.is_running
.lock()
.map_err(|_| RusTorchError::Profiling {
message: "Failed to acquire running lock".to_string(),
})?;
*running = false;
println!("📡 Real-time monitoring stopped");
Ok(())
}
pub fn get_alerts(&self) -> RusTorchResult<Vec<SystemAlert>> {
let alerts = self.alerts.lock().map_err(|_| RusTorchError::Profiling {
message: "Failed to acquire alerts lock".to_string(),
})?;
Ok(alerts.clone())
}
pub fn clear_alerts(&self) -> RusTorchResult<()> {
let mut alerts = self.alerts.lock().map_err(|_| RusTorchError::Profiling {
message: "Failed to acquire alerts lock".to_string(),
})?;
alerts.clear();
Ok(())
}
}
impl Default for RealTimeMonitor {
fn default() -> Self {
Self::new(MonitorConfig::default())
}
}