leptos_sync_core/reliability/monitoring/
config.rs

1//! Configuration types for monitoring system
2
3use serde::{Deserialize, Serialize};
4use super::alerts::AlertConfig;
5use super::health::HealthConfig;
6use super::metrics::MetricsConfig;
7
8/// Main configuration for the monitoring system
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct MonitorConfig {
11    /// Metrics collection configuration
12    pub metrics_config: MetricsConfig,
13    /// Alert management configuration
14    pub alert_config: AlertConfig,
15    /// Health reporting configuration
16    pub health_config: HealthConfig,
17    /// Whether the monitoring system is enabled
18    pub enabled: bool,
19    /// Global monitoring interval (in seconds)
20    pub monitoring_interval_seconds: u64,
21    /// Maximum number of monitoring statistics to keep
22    pub max_stats_history: usize,
23}
24
25impl MonitorConfig {
26    /// Create a new monitoring configuration
27    pub fn new() -> Self {
28        Self {
29            metrics_config: MetricsConfig::default(),
30            alert_config: AlertConfig::default(),
31            health_config: HealthConfig::default(),
32            enabled: true,
33            monitoring_interval_seconds: 60,
34            max_stats_history: 1000,
35        }
36    }
37
38    /// Create a configuration with custom settings
39    pub fn with_settings(
40        metrics_config: MetricsConfig,
41        alert_config: AlertConfig,
42        health_config: HealthConfig,
43    ) -> Self {
44        Self {
45            metrics_config,
46            alert_config,
47            health_config,
48            enabled: true,
49            monitoring_interval_seconds: 60,
50            max_stats_history: 1000,
51        }
52    }
53
54    /// Set the monitoring interval
55    pub fn with_monitoring_interval(mut self, interval_seconds: u64) -> Self {
56        self.monitoring_interval_seconds = interval_seconds;
57        self
58    }
59
60    /// Set the maximum stats history
61    pub fn with_max_stats_history(mut self, max_history: usize) -> Self {
62        self.max_stats_history = max_history;
63        self
64    }
65
66    /// Enable or disable monitoring
67    pub fn set_enabled(mut self, enabled: bool) -> Self {
68        self.enabled = enabled;
69        self
70    }
71}
72
73impl Default for MonitorConfig {
74    fn default() -> Self {
75        Self::new()
76    }
77}
78
79/// Monitoring statistics
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct MonitoringStats {
82    /// Total number of metrics collected
83    pub total_metrics_collected: u64,
84    /// Total number of alerts triggered
85    pub total_alerts_triggered: u64,
86    /// Total number of health checks performed
87    pub total_health_checks: u64,
88    /// System uptime in seconds
89    pub system_uptime_seconds: u64,
90    /// Last monitoring update timestamp
91    pub last_update_timestamp: u64,
92    /// Monitoring system start time
93    pub start_time: u64,
94}
95
96impl MonitoringStats {
97    /// Create new monitoring statistics
98    pub fn new() -> Self {
99        let now = std::time::SystemTime::now()
100            .duration_since(std::time::UNIX_EPOCH)
101            .unwrap()
102            .as_secs();
103
104        Self {
105            total_metrics_collected: 0,
106            total_alerts_triggered: 0,
107            total_health_checks: 0,
108            system_uptime_seconds: 0,
109            last_update_timestamp: now,
110            start_time: now,
111        }
112    }
113
114    /// Update the statistics
115    pub fn update(&mut self) {
116        let now = std::time::SystemTime::now()
117            .duration_since(std::time::UNIX_EPOCH)
118            .unwrap()
119            .as_secs();
120        
121        self.system_uptime_seconds = now - self.start_time;
122        self.last_update_timestamp = now;
123    }
124
125    /// Increment metrics collected count
126    pub fn increment_metrics_collected(&mut self) {
127        self.total_metrics_collected += 1;
128        self.update();
129    }
130
131    /// Increment alerts triggered count
132    pub fn increment_alerts_triggered(&mut self) {
133        self.total_alerts_triggered += 1;
134        self.update();
135    }
136
137    /// Increment health checks count
138    pub fn increment_health_checks(&mut self) {
139        self.total_health_checks += 1;
140        self.update();
141    }
142
143    /// Get the monitoring system uptime
144    pub fn get_uptime(&self) -> std::time::Duration {
145        std::time::Duration::from_secs(self.system_uptime_seconds)
146    }
147
148    /// Get metrics collection rate (metrics per minute)
149    pub fn get_metrics_rate(&self) -> f64 {
150        if self.system_uptime_seconds == 0 {
151            return 0.0;
152        }
153        (self.total_metrics_collected as f64) / (self.system_uptime_seconds as f64 / 60.0)
154    }
155
156    /// Get alert rate (alerts per hour)
157    pub fn get_alert_rate(&self) -> f64 {
158        if self.system_uptime_seconds == 0 {
159            return 0.0;
160        }
161        (self.total_alerts_triggered as f64) / (self.system_uptime_seconds as f64 / 3600.0)
162    }
163
164    /// Get health check rate (checks per minute)
165    pub fn get_health_check_rate(&self) -> f64 {
166        if self.system_uptime_seconds == 0 {
167            return 0.0;
168        }
169        (self.total_health_checks as f64) / (self.system_uptime_seconds as f64 / 60.0)
170    }
171}
172
173impl Default for MonitoringStats {
174    fn default() -> Self {
175        Self::new()
176    }
177}
178
179/// Performance monitoring configuration
180#[derive(Debug, Clone, Serialize, Deserialize)]
181pub struct PerformanceConfig {
182    /// Whether to enable performance monitoring
183    pub enabled: bool,
184    /// Sampling rate for performance metrics (0.0 to 1.0)
185    pub sampling_rate: f64,
186    /// Maximum number of performance samples to keep
187    pub max_samples: usize,
188    /// Performance threshold for warnings (in milliseconds)
189    pub warning_threshold_ms: u64,
190    /// Performance threshold for errors (in milliseconds)
191    pub error_threshold_ms: u64,
192}
193
194impl PerformanceConfig {
195    /// Create a new performance configuration
196    pub fn new() -> Self {
197        Self {
198            enabled: true,
199            sampling_rate: 1.0,
200            max_samples: 10000,
201            warning_threshold_ms: 1000,
202            error_threshold_ms: 5000,
203        }
204    }
205
206    /// Set the sampling rate
207    pub fn with_sampling_rate(mut self, rate: f64) -> Self {
208        self.sampling_rate = rate.clamp(0.0, 1.0);
209        self
210    }
211
212    /// Set the maximum samples
213    pub fn with_max_samples(mut self, max_samples: usize) -> Self {
214        self.max_samples = max_samples;
215        self
216    }
217
218    /// Set the performance thresholds
219    pub fn with_thresholds(mut self, warning_ms: u64, error_ms: u64) -> Self {
220        self.warning_threshold_ms = warning_ms;
221        self.error_threshold_ms = error_ms;
222        self
223    }
224}
225
226impl Default for PerformanceConfig {
227    fn default() -> Self {
228        Self::new()
229    }
230}
231
232/// Resource monitoring configuration
233#[derive(Debug, Clone, Serialize, Deserialize)]
234pub struct ResourceConfig {
235    /// Whether to monitor CPU usage
236    pub monitor_cpu: bool,
237    /// Whether to monitor memory usage
238    pub monitor_memory: bool,
239    /// Whether to monitor disk usage
240    pub monitor_disk: bool,
241    /// Whether to monitor network usage
242    pub monitor_network: bool,
243    /// CPU usage warning threshold (percentage)
244    pub cpu_warning_threshold: f64,
245    /// CPU usage error threshold (percentage)
246    pub cpu_error_threshold: f64,
247    /// Memory usage warning threshold (percentage)
248    pub memory_warning_threshold: f64,
249    /// Memory usage error threshold (percentage)
250    pub memory_error_threshold: f64,
251    /// Disk usage warning threshold (percentage)
252    pub disk_warning_threshold: f64,
253    /// Disk usage error threshold (percentage)
254    pub disk_error_threshold: f64,
255}
256
257impl ResourceConfig {
258    /// Create a new resource configuration
259    pub fn new() -> Self {
260        Self {
261            monitor_cpu: true,
262            monitor_memory: true,
263            monitor_disk: true,
264            monitor_network: false,
265            cpu_warning_threshold: 80.0,
266            cpu_error_threshold: 95.0,
267            memory_warning_threshold: 85.0,
268            memory_error_threshold: 95.0,
269            disk_warning_threshold: 80.0,
270            disk_error_threshold: 90.0,
271        }
272    }
273
274    /// Enable or disable CPU monitoring
275    pub fn with_cpu_monitoring(mut self, enabled: bool) -> Self {
276        self.monitor_cpu = enabled;
277        self
278    }
279
280    /// Enable or disable memory monitoring
281    pub fn with_memory_monitoring(mut self, enabled: bool) -> Self {
282        self.monitor_memory = enabled;
283        self
284    }
285
286    /// Enable or disable disk monitoring
287    pub fn with_disk_monitoring(mut self, enabled: bool) -> Self {
288        self.monitor_disk = enabled;
289        self
290    }
291
292    /// Enable or disable network monitoring
293    pub fn with_network_monitoring(mut self, enabled: bool) -> Self {
294        self.monitor_network = enabled;
295        self
296    }
297
298    /// Set CPU thresholds
299    pub fn with_cpu_thresholds(mut self, warning: f64, error: f64) -> Self {
300        self.cpu_warning_threshold = warning.clamp(0.0, 100.0);
301        self.cpu_error_threshold = error.clamp(0.0, 100.0);
302        self
303    }
304
305    /// Set memory thresholds
306    pub fn with_memory_thresholds(mut self, warning: f64, error: f64) -> Self {
307        self.memory_warning_threshold = warning.clamp(0.0, 100.0);
308        self.memory_error_threshold = error.clamp(0.0, 100.0);
309        self
310    }
311
312    /// Set disk thresholds
313    pub fn with_disk_thresholds(mut self, warning: f64, error: f64) -> Self {
314        self.disk_warning_threshold = warning.clamp(0.0, 100.0);
315        self.disk_error_threshold = error.clamp(0.0, 100.0);
316        self
317    }
318}
319
320impl Default for ResourceConfig {
321    fn default() -> Self {
322        Self::new()
323    }
324}
325
326/// Extended monitoring configuration
327#[derive(Debug, Clone, Serialize, Deserialize)]
328pub struct ExtendedMonitorConfig {
329    /// Base monitoring configuration
330    pub base_config: MonitorConfig,
331    /// Performance monitoring configuration
332    pub performance_config: PerformanceConfig,
333    /// Resource monitoring configuration
334    pub resource_config: ResourceConfig,
335    /// Whether to enable detailed logging
336    pub detailed_logging: bool,
337    /// Log level for monitoring (debug, info, warn, error)
338    pub log_level: String,
339}
340
341impl ExtendedMonitorConfig {
342    /// Create a new extended monitoring configuration
343    pub fn new() -> Self {
344        Self {
345            base_config: MonitorConfig::new(),
346            performance_config: PerformanceConfig::new(),
347            resource_config: ResourceConfig::new(),
348            detailed_logging: false,
349            log_level: "info".to_string(),
350        }
351    }
352
353    /// Enable detailed logging
354    pub fn with_detailed_logging(mut self, enabled: bool) -> Self {
355        self.detailed_logging = enabled;
356        self
357    }
358
359    /// Set the log level
360    pub fn with_log_level(mut self, level: String) -> Self {
361        self.log_level = level;
362        self
363    }
364}
365
366impl Default for ExtendedMonitorConfig {
367    fn default() -> Self {
368        Self::new()
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    #[test]
377    fn test_monitor_config_creation() {
378        let config = MonitorConfig::new();
379        assert!(config.enabled);
380        assert_eq!(config.monitoring_interval_seconds, 60);
381        assert_eq!(config.max_stats_history, 1000);
382    }
383
384    #[test]
385    fn test_monitor_config_customization() {
386        let config = MonitorConfig::new()
387            .with_monitoring_interval(30)
388            .with_max_stats_history(500)
389            .set_enabled(false);
390
391        assert!(!config.enabled);
392        assert_eq!(config.monitoring_interval_seconds, 30);
393        assert_eq!(config.max_stats_history, 500);
394    }
395
396    #[test]
397    fn test_monitoring_stats() {
398        let mut stats = MonitoringStats::new();
399        
400        assert_eq!(stats.total_metrics_collected, 0);
401        assert_eq!(stats.total_alerts_triggered, 0);
402        assert_eq!(stats.total_health_checks, 0);
403
404        // Increment counters
405        stats.increment_metrics_collected();
406        stats.increment_alerts_triggered();
407        stats.increment_health_checks();
408
409        assert_eq!(stats.total_metrics_collected, 1);
410        assert_eq!(stats.total_alerts_triggered, 1);
411        assert_eq!(stats.total_health_checks, 1);
412
413        // Test rates
414        let metrics_rate = stats.get_metrics_rate();
415        let alert_rate = stats.get_alert_rate();
416        let health_check_rate = stats.get_health_check_rate();
417
418        assert!(metrics_rate >= 0.0);
419        assert!(alert_rate >= 0.0);
420        assert!(health_check_rate >= 0.0);
421    }
422
423    #[test]
424    fn test_performance_config() {
425        let config = PerformanceConfig::new()
426            .with_sampling_rate(0.5)
427            .with_max_samples(5000)
428            .with_thresholds(500, 2000);
429
430        assert_eq!(config.sampling_rate, 0.5);
431        assert_eq!(config.max_samples, 5000);
432        assert_eq!(config.warning_threshold_ms, 500);
433        assert_eq!(config.error_threshold_ms, 2000);
434    }
435
436    #[test]
437    fn test_resource_config() {
438        let config = ResourceConfig::new()
439            .with_cpu_monitoring(true)
440            .with_memory_monitoring(false)
441            .with_cpu_thresholds(70.0, 90.0)
442            .with_memory_thresholds(80.0, 95.0);
443
444        assert!(config.monitor_cpu);
445        assert!(!config.monitor_memory);
446        assert_eq!(config.cpu_warning_threshold, 70.0);
447        assert_eq!(config.cpu_error_threshold, 90.0);
448        assert_eq!(config.memory_warning_threshold, 80.0);
449        assert_eq!(config.memory_error_threshold, 95.0);
450    }
451
452    #[test]
453    fn test_extended_monitor_config() {
454        let config = ExtendedMonitorConfig::new()
455            .with_detailed_logging(true)
456            .with_log_level("debug".to_string());
457
458        assert!(config.detailed_logging);
459        assert_eq!(config.log_level, "debug");
460        assert!(config.base_config.enabled);
461        assert!(config.performance_config.enabled);
462        assert!(config.resource_config.monitor_cpu);
463    }
464
465    #[test]
466    fn test_config_serialization() {
467        let config = MonitorConfig::new();
468        let serialized = serde_json::to_string(&config).unwrap();
469        let deserialized: MonitorConfig = serde_json::from_str(&serialized).unwrap();
470        
471        assert_eq!(config.enabled, deserialized.enabled);
472        assert_eq!(config.monitoring_interval_seconds, deserialized.monitoring_interval_seconds);
473    }
474}