1use crate::{
6 backend_traits::BackendCapabilities, calibration::DeviceCalibration,
7 topology::HardwareTopology, DeviceError, DeviceResult,
8};
9#[cfg(not(feature = "scirs2"))]
10use fallback_scirs2::*;
11use quantrs2_circuit::prelude::*;
12use scirs2_core::ndarray::{Array1, Array2, ArrayView1};
13use serde::{Deserialize, Serialize};
14use std::collections::{BTreeMap, HashMap, VecDeque};
15use std::sync::{Arc, Mutex, RwLock};
16use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
17
18use super::functions::{AnomalyDetector, MetricCollector, NotificationChannel};
19#[cfg(feature = "scheduling")]
20use tokio::sync::{broadcast, mpsc};
21#[cfg(feature = "scheduling")]
22use tokio::time::interval;
23
24#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
26pub enum AlertSeverity {
27 Info,
28 Warning,
29 Critical,
30 Emergency,
31}
32pub struct RealTimeMonitor {
34 config: MonitoringConfig,
36 current_metrics: HashMap<String, MetricSnapshot>,
38 metric_history: HashMap<String, VecDeque<MetricSnapshot>>,
40 anomaly_detectors: HashMap<String, Box<dyn AnomalyDetector + Send + Sync>>,
42 health_status: HashMap<String, HealthStatus>,
44 suppression_state: HashMap<String, SystemTime>,
46}
47impl RealTimeMonitor {
48 fn new(config: MonitoringConfig) -> Self {
49 Self {
50 config,
51 current_metrics: HashMap::new(),
52 metric_history: HashMap::new(),
53 anomaly_detectors: HashMap::new(),
54 health_status: HashMap::new(),
55 suppression_state: HashMap::new(),
56 }
57 }
58 fn get_system_health(&self) -> SystemHealth {
59 let overall_status = if self
60 .health_status
61 .values()
62 .any(|h| h.status == SystemStatus::Critical)
63 {
64 SystemStatus::Critical
65 } else if self
66 .health_status
67 .values()
68 .any(|h| h.status == SystemStatus::Degraded)
69 {
70 SystemStatus::Degraded
71 } else {
72 SystemStatus::Healthy
73 };
74 let health_score = if self.health_status.is_empty() {
75 1.0
76 } else {
77 self.health_status
78 .values()
79 .map(|h| h.health_score)
80 .sum::<f64>()
81 / self.health_status.len() as f64
82 };
83 let critical_issues: Vec<HealthIssue> = self
84 .health_status
85 .values()
86 .flat_map(|h| {
87 h.issues
88 .iter()
89 .filter(|i| i.severity == AlertSeverity::Critical)
90 })
91 .cloned()
92 .collect();
93 SystemHealth {
94 overall_status,
95 component_health: self.health_status.clone(),
96 health_score,
97 critical_issues,
98 last_assessment: SystemTime::now(),
99 }
100 }
101}
102#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct MetricReport {
105 pub name: String,
107 pub summary: StatisticalSummary,
109 pub trend: TrendAnalysis,
111 pub anomalies: Vec<AnomalyResult>,
113 pub correlations: HashMap<String, f64>,
115}
116#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct PredictiveModel {
119 pub model_type: PredictiveModelType,
121 pub parameters: Array1<f64>,
123 pub accuracy: f64,
125 pub feature_importance: HashMap<String, f64>,
127 pub last_trained: SystemTime,
129}
130#[derive(Debug, Clone, Serialize, Deserialize)]
132pub struct HealthIssue {
133 pub description: String,
135 pub severity: AlertSeverity,
137 pub first_detected: SystemTime,
139 pub last_seen: SystemTime,
141 pub count: u32,
143}
144#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct EscalationState {
147 pub level: u32,
149 pub next_escalation: SystemTime,
151 pub history: Vec<EscalationEvent>,
153}
154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
156pub enum InsightType {
157 Performance,
158 Efficiency,
159 Cost,
160 Reliability,
161 Capacity,
162 Security,
163 Trend,
164 Anomaly,
165}
166#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct Pattern {
169 pub pattern_type: PatternType,
171 pub confidence: f64,
173 pub parameters: HashMap<String, f64>,
175 pub duration: Duration,
177 pub frequency: Option<Duration>,
179}
180#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct MonitoringTarget {
183 pub name: String,
185 pub target_type: MonitoringTargetType,
187 pub metrics: Vec<String>,
189 pub frequency: Duration,
191 pub health_check: Option<HealthCheckConfig>,
193}
194#[derive(Debug, Clone, Serialize, Deserialize)]
196pub enum ExportAuth {
197 ApiKey(String),
198 BasicAuth { username: String, password: String },
199 BearerToken(String),
200 Custom(HashMap<String, String>),
201}
202#[derive(Debug, Clone, Serialize, Deserialize)]
204pub enum SuppressionCondition {
205 MaintenanceWindow,
206 DuplicateAlert,
207 SystemStartup(Duration),
208 MetricValue(String, f64),
209}
210#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct StorageStatistics {
213 pub total_metrics: u64,
215 pub storage_size_bytes: u64,
217 pub compression_ratio: f64,
219 pub write_rate: f64,
221 pub read_rate: f64,
223 pub cache_hit_rate: f64,
225}
226#[derive(Debug, Clone, Serialize, Deserialize)]
228pub struct SystemHealth {
229 pub overall_status: SystemStatus,
231 pub component_health: HashMap<String, HealthStatus>,
233 pub health_score: f64,
235 pub critical_issues: Vec<HealthIssue>,
237 pub last_assessment: SystemTime,
239}
240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
242pub enum ImpactLevel {
243 Low,
244 Medium,
245 High,
246 Critical,
247}
248#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
250pub enum AnomalyType {
251 Outlier,
252 ChangePoint,
253 Drift,
254 Seasonality,
255 Spike,
256 Drop,
257 Pattern,
258 Custom(String),
259}
260#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
262pub enum PredictiveModelType {
263 LinearRegression,
264 PolynomialRegression,
265 ExponentialSmoothing,
266 ARIMA,
267 NeuralNetwork,
268 RandomForest,
269 Custom(String),
270}
271#[derive(Debug, Clone, Serialize, Deserialize)]
273pub struct AnomalyDetectorConfig {
274 pub detector_type: AnomalyDetectorType,
276 pub sensitivity: f64,
278 pub window_size: usize,
280 pub training_period: Duration,
282 pub parameters: HashMap<String, f64>,
284}
285#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
287pub enum PatternType {
288 Periodic,
289 Cyclic,
290 Seasonal,
291 Trend,
292 Burst,
293 Anomaly,
294 Custom(String),
295}
296#[derive(Debug, Clone, Serialize, Deserialize)]
298pub struct AnomalyResult {
299 pub score: f64,
301 pub anomaly_type: AnomalyType,
303 pub index: usize,
305 pub confidence: f64,
307 pub description: String,
309}
310#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312pub enum CompressionAlgorithm {
313 None,
314 Gzip,
315 Zstd,
316 Lz4,
317 Snappy,
318}
319pub struct AlertManager {
321 config: AlertConfig,
323 active_alerts: HashMap<String, Alert>,
325 alert_history: VecDeque<Alert>,
327 notification_channels: HashMap<String, Box<dyn NotificationChannel + Send + Sync>>,
329 escalation_state: HashMap<String, EscalationState>,
331 suppression_state: HashMap<String, SystemTime>,
333}
334impl AlertManager {
335 fn new(config: AlertConfig) -> Self {
336 Self {
337 config,
338 active_alerts: HashMap::new(),
339 alert_history: VecDeque::new(),
340 notification_channels: HashMap::new(),
341 escalation_state: HashMap::new(),
342 suppression_state: HashMap::new(),
343 }
344 }
345}
346#[derive(Debug, Clone, Serialize, Deserialize)]
348pub enum TelemetryCommand {
349 StartCollection,
350 StopCollection,
351 CollectMetric(String),
352 UpdateConfig(TelemetryConfig),
353 TriggerAnalysis,
354 GenerateReport(ReportType),
355 ExportData(ExportFormat, String),
356 TestAlert(String),
357 SetMaintenanceMode(bool),
358}
359#[derive(Debug, Clone, Serialize, Deserialize)]
361pub struct ExportConfig {
362 pub enable_prometheus: bool,
364 pub enable_influxdb: bool,
366 pub enable_grafana: bool,
368 pub enable_custom_exports: bool,
370 pub export_endpoints: HashMap<String, ExportEndpoint>,
372}
373#[derive(Debug, Clone, Serialize, Deserialize)]
375pub enum TelemetryEvent {
376 MetricCollected {
377 metric_name: String,
378 value: f64,
379 timestamp: SystemTime,
380 metadata: HashMap<String, String>,
381 },
382 AlertTriggered {
383 alert_id: String,
384 severity: AlertSeverity,
385 message: String,
386 timestamp: SystemTime,
387 },
388 AlertResolved {
389 alert_id: String,
390 timestamp: SystemTime,
391 },
392 AnomalyDetected {
393 metric_name: String,
394 anomaly_score: f64,
395 timestamp: SystemTime,
396 },
397 HealthCheckFailed {
398 target: String,
399 reason: String,
400 timestamp: SystemTime,
401 },
402 SystemStatusChanged {
403 component: String,
404 old_status: SystemStatus,
405 new_status: SystemStatus,
406 timestamp: SystemTime,
407 },
408}
409#[derive(Debug)]
411pub struct TelemetryAnalytics {
412 config: AnalyticsConfig,
414 statistical_models: HashMap<String, StatisticalModel>,
416 predictive_models: HashMap<String, PredictiveModel>,
418 correlation_matrices: HashMap<String, Array2<f64>>,
420 trend_analysis: HashMap<String, TrendAnalysis>,
422 patterns: HashMap<String, Vec<Pattern>>,
424}
425impl TelemetryAnalytics {
426 fn new(config: AnalyticsConfig) -> Self {
427 Self {
428 config,
429 statistical_models: HashMap::new(),
430 predictive_models: HashMap::new(),
431 correlation_matrices: HashMap::new(),
432 trend_analysis: HashMap::new(),
433 patterns: HashMap::new(),
434 }
435 }
436 async fn generate_report(&self, report_type: ReportType) -> DeviceResult<TelemetryReport> {
437 Ok(TelemetryReport {
438 report_type,
439 period: (
440 SystemTime::now() - Duration::from_secs(86400),
441 SystemTime::now(),
442 ),
443 summary: ReportSummary {
444 kpis: HashMap::new(),
445 highlights: vec!["System performing within normal parameters".to_string()],
446 issues: Vec::new(),
447 assessment: "Good".to_string(),
448 },
449 metrics: HashMap::new(),
450 insights: Vec::new(),
451 recommendations: Vec::new(),
452 generated_at: SystemTime::now(),
453 })
454 }
455}
456#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
458pub enum TrendDirection {
459 Increasing,
460 Decreasing,
461 Stable,
462 Volatile,
463 Unknown,
464}
465#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
467pub enum ReportType {
468 Performance,
469 Resource,
470 Error,
471 Cost,
472 Health,
473 Security,
474 Comprehensive,
475}
476#[derive(Debug, Clone, Serialize, Deserialize)]
478pub struct CompressionConfig {
479 pub enabled: bool,
481 pub algorithm: CompressionAlgorithm,
483 pub ratio_threshold: f64,
485}
486#[derive(Debug, Clone, Serialize, Deserialize)]
488pub struct EscalationRule {
489 pub name: String,
491 pub condition: EscalationCondition,
493 pub delay: Duration,
495 pub target_severity: AlertSeverity,
497 pub actions: Vec<EscalationAction>,
499}
500#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
502pub enum SystemStatus {
503 Healthy,
504 Degraded,
505 Critical,
506 Offline,
507 Maintenance,
508 Unknown,
509}
510pub struct QuantumTelemetrySystem {
512 config: TelemetryConfig,
514 collectors: Arc<RwLock<HashMap<String, Box<dyn MetricCollector + Send + Sync>>>>,
516 monitor: Arc<RwLock<RealTimeMonitor>>,
518 analytics: Arc<RwLock<TelemetryAnalytics>>,
520 alert_manager: Arc<RwLock<AlertManager>>,
522 storage: Arc<RwLock<TelemetryStorage>>,
524 event_sender: broadcast::Sender<TelemetryEvent>,
526 command_receiver: Arc<Mutex<mpsc::UnboundedReceiver<TelemetryCommand>>>,
528}
529impl QuantumTelemetrySystem {
530 pub fn new(config: TelemetryConfig) -> Self {
532 let (event_sender, _) = broadcast::channel(1000);
533 let (command_sender, command_receiver) = mpsc::unbounded_channel();
534 Self {
535 config: config.clone(),
536 collectors: Arc::new(RwLock::new(HashMap::new())),
537 monitor: Arc::new(RwLock::new(RealTimeMonitor::new(
538 config.monitoring_config.clone(),
539 ))),
540 analytics: Arc::new(RwLock::new(TelemetryAnalytics::new(
541 config.analytics_config.clone(),
542 ))),
543 alert_manager: Arc::new(RwLock::new(AlertManager::new(config.alert_config))),
544 storage: Arc::new(RwLock::new(TelemetryStorage::new(StorageConfig::default()))),
545 event_sender,
546 command_receiver: Arc::new(Mutex::new(command_receiver)),
547 }
548 }
549 pub async fn start(&self) -> DeviceResult<()> {
551 if !self.config.enabled {
552 return Ok(());
553 }
554 self.start_metric_collection().await?;
555 if self.config.enable_realtime_monitoring {
556 self.start_realtime_monitoring().await?;
557 }
558 if self.config.enable_analytics {
559 self.start_analytics_processing().await?;
560 }
561 if self.config.enable_alerting {
562 self.start_alert_processing().await?;
563 }
564 Ok(())
565 }
566 pub async fn stop(&self) -> DeviceResult<()> {
568 Ok(())
569 }
570 pub fn register_collector(
572 &self,
573 collector: Box<dyn MetricCollector + Send + Sync>,
574 ) -> DeviceResult<()> {
575 let mut collectors = self.collectors.write().map_err(|e| {
576 DeviceError::LockError(format!("Failed to acquire write lock on collectors: {e}"))
577 })?;
578 collectors.insert(collector.name().to_string(), collector);
579 Ok(())
580 }
581 pub async fn collect_metrics(&self) -> DeviceResult<Vec<Metric>> {
583 let collectors = self.collectors.read().map_err(|e| {
584 DeviceError::LockError(format!("Failed to acquire read lock on collectors: {e}"))
585 })?;
586 let mut all_metrics = Vec::new();
587 for collector in collectors.values() {
588 if collector.is_enabled() {
589 match collector.collect() {
590 Ok(mut metrics) => all_metrics.append(&mut metrics),
591 Err(e) => {
592 eprintln!(
593 "Error collecting metrics from {}: {:?}",
594 collector.name(),
595 e
596 );
597 }
598 }
599 }
600 }
601 {
602 let mut storage = self.storage.write().map_err(|e| {
603 DeviceError::LockError(format!("Failed to acquire write lock on storage: {e}"))
604 })?;
605 storage.store_metrics(&all_metrics)?;
606 }
607 for metric in &all_metrics {
608 let _ = self.event_sender.send(TelemetryEvent::MetricCollected {
609 metric_name: metric.name.clone(),
610 value: metric.value,
611 timestamp: metric.timestamp,
612 metadata: metric.metadata.clone(),
613 });
614 }
615 Ok(all_metrics)
616 }
617 pub fn get_system_health(&self) -> DeviceResult<SystemHealth> {
619 let monitor = self.monitor.read().map_err(|e| {
620 DeviceError::LockError(format!("Failed to acquire read lock on monitor: {e}"))
621 })?;
622 Ok(monitor.get_system_health())
623 }
624 pub async fn generate_report(&self, report_type: ReportType) -> DeviceResult<TelemetryReport> {
626 let analytics = self.analytics.read().map_err(|e| {
627 DeviceError::LockError(format!("Failed to acquire read lock on analytics: {e}"))
628 })?;
629 analytics.generate_report(report_type).await
630 }
631 async fn start_metric_collection(&self) -> DeviceResult<()> {
632 let interval_duration = Duration::from_secs(self.config.collection_interval);
633 let mut interval = interval(interval_duration);
634 Ok(())
635 }
636 async fn start_realtime_monitoring(&self) -> DeviceResult<()> {
637 Ok(())
638 }
639 async fn start_analytics_processing(&self) -> DeviceResult<()> {
640 Ok(())
641 }
642 async fn start_alert_processing(&self) -> DeviceResult<()> {
643 Ok(())
644 }
645}
646#[derive(Debug, Clone, Serialize, Deserialize)]
648pub struct HealthCriterion {
649 pub metric: String,
651 pub operator: ComparisonOperator,
653 pub value: f64,
655 pub severity: AlertSeverity,
657}
658#[derive(Debug, Clone, Serialize, Deserialize)]
660pub struct MonitoringConfig {
661 pub dashboard_refresh_rate: u64,
663 pub health_check_interval: u64,
665 pub anomaly_sensitivity: f64,
667 pub enable_trend_analysis: bool,
669 pub monitoring_targets: Vec<MonitoringTarget>,
671}
672#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
674pub enum ExportFormat {
675 JSON,
676 Prometheus,
677 InfluxDB,
678 CSV,
679 Binary,
680 Custom(String),
681}
682#[derive(Debug, Clone, Serialize, Deserialize)]
684pub struct RetentionConfig {
685 pub realtime_retention_hours: u32,
687 pub historical_retention_days: u32,
689 pub aggregated_retention_months: u32,
691 pub enable_compression: bool,
693 pub archive_threshold_gb: f64,
695}
696#[derive(Debug, Clone, Serialize, Deserialize)]
698pub struct AlertConfig {
699 pub enable_email_alerts: bool,
701 pub enable_sms_alerts: bool,
703 pub enable_webhook_alerts: bool,
705 pub enable_slack_alerts: bool,
707 pub thresholds: HashMap<String, AlertThreshold>,
709 pub escalation_rules: Vec<EscalationRule>,
711 pub suppression_rules: Vec<SuppressionRule>,
713}
714#[derive(Debug, Clone, Serialize, Deserialize)]
716pub struct EscalationEvent {
717 pub timestamp: SystemTime,
719 pub from_level: u32,
721 pub to_level: u32,
723 pub reason: String,
725 pub actions: Vec<String>,
727}
728#[derive(Debug, Clone, Serialize, Deserialize)]
730pub struct AggregatedData {
731 pub interval: Duration,
733 pub summary: StatisticalSummary,
735 pub data_points: Vec<(SystemTime, f64)>,
737 pub last_updated: SystemTime,
739}
740#[derive(Debug, Clone, Serialize, Deserialize)]
742pub enum EscalationAction {
743 NotifyAdministrator,
744 TriggerAutomatedResponse,
745 DisableAffectedComponent,
746 IncreaseMonitoringFrequency,
747 CreateIncident,
748}
749#[derive(Debug, Clone, Serialize, Deserialize)]
751pub struct SuppressionRule {
752 pub name: String,
754 pub condition: SuppressionCondition,
756 pub duration: Duration,
758 pub alert_types: Vec<String>,
760}
761#[derive(Debug, Clone, Serialize, Deserialize)]
763pub struct ExportEndpoint {
764 pub url: String,
766 pub auth: Option<ExportAuth>,
768 pub format: ExportFormat,
770 pub frequency: Duration,
772 pub batch_size: usize,
774}
775#[derive(Debug, Clone, Serialize, Deserialize)]
777pub struct TelemetryConfig {
778 pub enabled: bool,
780 pub collection_interval: u64,
782 pub enable_realtime_monitoring: bool,
784 pub enable_analytics: bool,
786 pub enable_alerting: bool,
788 pub retention_config: RetentionConfig,
790 pub metric_config: MetricConfig,
792 pub monitoring_config: MonitoringConfig,
794 pub analytics_config: AnalyticsConfig,
796 pub alert_config: AlertConfig,
798 pub export_config: ExportConfig,
800}
801#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
803pub enum AnomalyDetectorType {
804 Statistical,
805 MachineLearning,
806 Threshold,
807 Isolation,
808 LSTM,
809 AutoEncoder,
810 Custom(String),
811}
812#[derive(Debug, Clone, Serialize, Deserialize)]
814pub struct ThresholdRule {
815 pub value: f64,
817 pub operator: ComparisonOperator,
819 pub duration: Duration,
821 pub recovery_value: Option<f64>,
823}
824#[derive(Debug, Clone, Serialize, Deserialize)]
826pub struct TrendAnalysis {
827 pub direction: TrendDirection,
829 pub strength: f64,
831 pub slope: f64,
833 pub r_squared: f64,
835 pub confidence_interval: (f64, f64),
837 pub projection: Vec<(SystemTime, f64)>,
839}
840#[derive(Debug, Clone, Serialize, Deserialize)]
842pub struct Alert {
843 pub id: String,
845 pub name: String,
847 pub severity: AlertSeverity,
849 pub message: String,
851 pub metric: String,
853 pub current_value: f64,
855 pub threshold_value: f64,
857 pub state: AlertState,
859 pub first_triggered: SystemTime,
861 pub last_triggered: SystemTime,
863 pub acknowledgment: Option<AlertAcknowledgment>,
865 pub metadata: HashMap<String, String>,
867}
868#[derive(Debug, Clone, Serialize, Deserialize)]
870pub struct StorageConfig {
871 pub realtime_buffer_size: usize,
873 pub aggregation_intervals: Vec<Duration>,
875 pub compression: CompressionConfig,
877 pub persistence: PersistenceConfig,
879}
880#[derive(Debug, Clone, Serialize, Deserialize)]
882pub struct HealthStatus {
883 pub status: SystemStatus,
885 pub last_check: SystemTime,
887 pub details: HashMap<String, String>,
889 pub health_score: f64,
891 pub issues: Vec<HealthIssue>,
893}
894#[derive(Debug)]
896pub struct TelemetryStorage {
897 config: StorageConfig,
899 realtime_buffer: HashMap<String, VecDeque<Metric>>,
901 aggregated_cache: HashMap<String, AggregatedData>,
903 time_series_index: BTreeMap<SystemTime, Vec<String>>,
905 statistics: StorageStatistics,
907}
908impl TelemetryStorage {
909 fn new(config: StorageConfig) -> Self {
910 Self {
911 config,
912 realtime_buffer: HashMap::new(),
913 aggregated_cache: HashMap::new(),
914 time_series_index: BTreeMap::new(),
915 statistics: StorageStatistics {
916 total_metrics: 0,
917 storage_size_bytes: 0,
918 compression_ratio: 1.0,
919 write_rate: 0.0,
920 read_rate: 0.0,
921 cache_hit_rate: 0.0,
922 },
923 }
924 }
925 fn store_metrics(&mut self, metrics: &[Metric]) -> DeviceResult<()> {
926 for metric in metrics {
927 let buffer = self.realtime_buffer.entry(metric.name.clone()).or_default();
928 buffer.push_back(metric.clone());
929 while buffer.len() > self.config.realtime_buffer_size {
930 buffer.pop_front();
931 }
932 let metric_names = self.time_series_index.entry(metric.timestamp).or_default();
933 metric_names.push(metric.name.clone());
934 }
935 self.statistics.total_metrics += metrics.len() as u64;
936 Ok(())
937 }
938}
939#[derive(Debug, Clone, Serialize, Deserialize)]
941pub struct StatisticalSummary {
942 pub count: usize,
944 pub mean: f64,
946 pub std_dev: f64,
948 pub min: f64,
950 pub max: f64,
952 pub percentiles: HashMap<u8, f64>,
954 pub variance: f64,
956 pub skewness: f64,
958 pub kurtosis: f64,
960}
961#[derive(Debug, Clone, Serialize, Deserialize)]
963pub struct AnalyticsConfig {
964 pub enable_statistical_analysis: bool,
966 pub enable_predictive_analytics: bool,
968 pub enable_correlation_analysis: bool,
970 pub processing_interval_minutes: u64,
972 pub confidence_level: f64,
974 pub prediction_horizon_hours: u64,
976}
977#[derive(Debug, Clone, Serialize, Deserialize)]
979pub struct AlertThreshold {
980 pub warning: Option<ThresholdRule>,
982 pub critical: Option<ThresholdRule>,
984 pub emergency: Option<ThresholdRule>,
986}
987#[derive(Debug, Clone, Serialize, Deserialize)]
989pub struct ReportInsight {
990 pub insight_type: InsightType,
992 pub description: String,
994 pub data: HashMap<String, f64>,
996 pub confidence: f64,
998 pub impact: ImpactLevel,
1000}
1001#[derive(Debug, Clone, Serialize, Deserialize)]
1003pub enum EscalationCondition {
1004 UnresolvedAfter(Duration),
1005 RepeatedFailures(u32),
1006 SeverityIncrease,
1007 MetricThreshold(String, f64),
1008}
1009#[derive(Debug, Clone, Serialize, Deserialize)]
1011pub struct MetricConfig {
1012 pub enable_performance_metrics: bool,
1014 pub enable_resource_metrics: bool,
1016 pub enable_error_metrics: bool,
1018 pub enable_cost_metrics: bool,
1020 pub enable_custom_metrics: bool,
1022 pub sampling_rate: f64,
1024 pub batch_size: usize,
1026}
1027#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1029pub enum MonitoringTargetType {
1030 Device,
1031 Circuit,
1032 Job,
1033 Provider,
1034 Resource,
1035 Application,
1036 Custom(String),
1037}
1038#[derive(Debug, Clone, Serialize, Deserialize)]
1040pub struct PersistenceConfig {
1041 pub enabled: bool,
1043 pub backend: StorageBackend,
1045 pub batch_size: usize,
1047 pub write_interval: Duration,
1049}
1050#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1052pub enum StatisticalModelType {
1053 Normal,
1054 Exponential,
1055 Gamma,
1056 ChiSquared,
1057 Weibull,
1058 Beta,
1059 LogNormal,
1060 Custom(String),
1061}
1062#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1064pub enum AlertState {
1065 Triggered,
1066 Acknowledged,
1067 Resolved,
1068 Suppressed,
1069 Escalated,
1070}
1071#[derive(Debug, Clone, Serialize, Deserialize)]
1073pub struct AlertAcknowledgment {
1074 pub acknowledged_by: String,
1076 pub acknowledged_at: SystemTime,
1078 pub message: String,
1080}
1081#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1083pub enum StorageBackend {
1084 Memory,
1085 File,
1086 Database,
1087 TimeSeries,
1088 Cloud,
1089}
1090#[derive(Debug, Clone, Serialize, Deserialize)]
1092pub struct ReportSummary {
1093 pub kpis: HashMap<String, f64>,
1095 pub highlights: Vec<String>,
1097 pub issues: Vec<String>,
1099 pub assessment: String,
1101}
1102#[derive(Debug, Clone, Serialize, Deserialize)]
1104pub struct MetricSnapshot {
1105 pub value: f64,
1107 pub timestamp: SystemTime,
1109 pub rate: Option<f64>,
1111 pub trend: TrendDirection,
1113 pub anomaly_score: Option<f64>,
1115}
1116#[derive(Debug, Clone, Serialize, Deserialize)]
1118pub struct StatisticalModel {
1119 pub model_type: StatisticalModelType,
1121 pub parameters: HashMap<String, f64>,
1123 pub fit_metrics: FitMetrics,
1125 pub last_updated: SystemTime,
1127 pub training_size: usize,
1129}
1130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1132pub enum ComparisonOperator {
1133 GreaterThan,
1134 LessThan,
1135 Equals,
1136 NotEquals,
1137 GreaterThanOrEqual,
1138 LessThanOrEqual,
1139 Between(f64, f64),
1140 Outside(f64, f64),
1141}
1142#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1144pub enum MetricType {
1145 Counter,
1146 Gauge,
1147 Histogram,
1148 Summary,
1149 Timer,
1150 Custom(String),
1151}
1152#[derive(Debug, Clone, Serialize, Deserialize)]
1154pub struct TelemetryReport {
1155 pub report_type: ReportType,
1157 pub period: (SystemTime, SystemTime),
1159 pub summary: ReportSummary,
1161 pub metrics: HashMap<String, MetricReport>,
1163 pub insights: Vec<ReportInsight>,
1165 pub recommendations: Vec<String>,
1167 pub generated_at: SystemTime,
1169}
1170#[derive(Debug, Clone, Serialize, Deserialize)]
1172pub struct Metric {
1173 pub name: String,
1175 pub value: f64,
1177 pub unit: String,
1179 pub metric_type: MetricType,
1181 pub timestamp: SystemTime,
1183 pub labels: HashMap<String, String>,
1185 pub metadata: HashMap<String, String>,
1187}
1188#[derive(Debug, Clone, Serialize, Deserialize)]
1190pub struct FitMetrics {
1191 pub r_squared: f64,
1193 pub aic: f64,
1195 pub bic: f64,
1197 pub log_likelihood: f64,
1199 pub p_value: f64,
1201}
1202#[derive(Debug, Clone, Serialize, Deserialize)]
1204pub struct HealthCheckConfig {
1205 pub endpoint: String,
1207 pub timeout: Duration,
1209 pub expected_response: Option<String>,
1211 pub criteria: Vec<HealthCriterion>,
1213}