use crate::{
backend_traits::BackendCapabilities, calibration::DeviceCalibration,
topology::HardwareTopology, DeviceError, DeviceResult,
};
#[cfg(not(feature = "scirs2"))]
use fallback_scirs2::*;
use quantrs2_circuit::prelude::*;
use scirs2_core::ndarray::{Array1, Array2, ArrayView1};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::{Arc, Mutex, RwLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use super::functions::{AnomalyDetector, MetricCollector, NotificationChannel};
#[cfg(feature = "scheduling")]
use tokio::sync::{broadcast, mpsc};
#[cfg(feature = "scheduling")]
use tokio::time::interval;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum AlertSeverity {
Info,
Warning,
Critical,
Emergency,
}
pub struct RealTimeMonitor {
config: MonitoringConfig,
current_metrics: HashMap<String, MetricSnapshot>,
metric_history: HashMap<String, VecDeque<MetricSnapshot>>,
anomaly_detectors: HashMap<String, Box<dyn AnomalyDetector + Send + Sync>>,
health_status: HashMap<String, HealthStatus>,
suppression_state: HashMap<String, SystemTime>,
}
impl RealTimeMonitor {
fn new(config: MonitoringConfig) -> Self {
Self {
config,
current_metrics: HashMap::new(),
metric_history: HashMap::new(),
anomaly_detectors: HashMap::new(),
health_status: HashMap::new(),
suppression_state: HashMap::new(),
}
}
fn get_system_health(&self) -> SystemHealth {
let overall_status = if self
.health_status
.values()
.any(|h| h.status == SystemStatus::Critical)
{
SystemStatus::Critical
} else if self
.health_status
.values()
.any(|h| h.status == SystemStatus::Degraded)
{
SystemStatus::Degraded
} else {
SystemStatus::Healthy
};
let health_score = if self.health_status.is_empty() {
1.0
} else {
self.health_status
.values()
.map(|h| h.health_score)
.sum::<f64>()
/ self.health_status.len() as f64
};
let critical_issues: Vec<HealthIssue> = self
.health_status
.values()
.flat_map(|h| {
h.issues
.iter()
.filter(|i| i.severity == AlertSeverity::Critical)
})
.cloned()
.collect();
SystemHealth {
overall_status,
component_health: self.health_status.clone(),
health_score,
critical_issues,
last_assessment: SystemTime::now(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricReport {
pub name: String,
pub summary: StatisticalSummary,
pub trend: TrendAnalysis,
pub anomalies: Vec<AnomalyResult>,
pub correlations: HashMap<String, f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PredictiveModel {
pub model_type: PredictiveModelType,
pub parameters: Array1<f64>,
pub accuracy: f64,
pub feature_importance: HashMap<String, f64>,
pub last_trained: SystemTime,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthIssue {
pub description: String,
pub severity: AlertSeverity,
pub first_detected: SystemTime,
pub last_seen: SystemTime,
pub count: u32,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EscalationState {
pub level: u32,
pub next_escalation: SystemTime,
pub history: Vec<EscalationEvent>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum InsightType {
Performance,
Efficiency,
Cost,
Reliability,
Capacity,
Security,
Trend,
Anomaly,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Pattern {
pub pattern_type: PatternType,
pub confidence: f64,
pub parameters: HashMap<String, f64>,
pub duration: Duration,
pub frequency: Option<Duration>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringTarget {
pub name: String,
pub target_type: MonitoringTargetType,
pub metrics: Vec<String>,
pub frequency: Duration,
pub health_check: Option<HealthCheckConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ExportAuth {
ApiKey(String),
BasicAuth { username: String, password: String },
BearerToken(String),
Custom(HashMap<String, String>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SuppressionCondition {
MaintenanceWindow,
DuplicateAlert,
SystemStartup(Duration),
MetricValue(String, f64),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageStatistics {
pub total_metrics: u64,
pub storage_size_bytes: u64,
pub compression_ratio: f64,
pub write_rate: f64,
pub read_rate: f64,
pub cache_hit_rate: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemHealth {
pub overall_status: SystemStatus,
pub component_health: HashMap<String, HealthStatus>,
pub health_score: f64,
pub critical_issues: Vec<HealthIssue>,
pub last_assessment: SystemTime,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ImpactLevel {
Low,
Medium,
High,
Critical,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnomalyType {
Outlier,
ChangePoint,
Drift,
Seasonality,
Spike,
Drop,
Pattern,
Custom(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PredictiveModelType {
LinearRegression,
PolynomialRegression,
ExponentialSmoothing,
ARIMA,
NeuralNetwork,
RandomForest,
Custom(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnomalyDetectorConfig {
pub detector_type: AnomalyDetectorType,
pub sensitivity: f64,
pub window_size: usize,
pub training_period: Duration,
pub parameters: HashMap<String, f64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PatternType {
Periodic,
Cyclic,
Seasonal,
Trend,
Burst,
Anomaly,
Custom(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnomalyResult {
pub score: f64,
pub anomaly_type: AnomalyType,
pub index: usize,
pub confidence: f64,
pub description: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompressionAlgorithm {
None,
Gzip,
Zstd,
Lz4,
Snappy,
}
pub struct AlertManager {
config: AlertConfig,
active_alerts: HashMap<String, Alert>,
alert_history: VecDeque<Alert>,
notification_channels: HashMap<String, Box<dyn NotificationChannel + Send + Sync>>,
escalation_state: HashMap<String, EscalationState>,
suppression_state: HashMap<String, SystemTime>,
}
impl AlertManager {
fn new(config: AlertConfig) -> Self {
Self {
config,
active_alerts: HashMap::new(),
alert_history: VecDeque::new(),
notification_channels: HashMap::new(),
escalation_state: HashMap::new(),
suppression_state: HashMap::new(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TelemetryCommand {
StartCollection,
StopCollection,
CollectMetric(String),
UpdateConfig(TelemetryConfig),
TriggerAnalysis,
GenerateReport(ReportType),
ExportData(ExportFormat, String),
TestAlert(String),
SetMaintenanceMode(bool),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportConfig {
pub enable_prometheus: bool,
pub enable_influxdb: bool,
pub enable_grafana: bool,
pub enable_custom_exports: bool,
pub export_endpoints: HashMap<String, ExportEndpoint>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TelemetryEvent {
MetricCollected {
metric_name: String,
value: f64,
timestamp: SystemTime,
metadata: HashMap<String, String>,
},
AlertTriggered {
alert_id: String,
severity: AlertSeverity,
message: String,
timestamp: SystemTime,
},
AlertResolved {
alert_id: String,
timestamp: SystemTime,
},
AnomalyDetected {
metric_name: String,
anomaly_score: f64,
timestamp: SystemTime,
},
HealthCheckFailed {
target: String,
reason: String,
timestamp: SystemTime,
},
SystemStatusChanged {
component: String,
old_status: SystemStatus,
new_status: SystemStatus,
timestamp: SystemTime,
},
}
#[derive(Debug)]
pub struct TelemetryAnalytics {
config: AnalyticsConfig,
statistical_models: HashMap<String, StatisticalModel>,
predictive_models: HashMap<String, PredictiveModel>,
correlation_matrices: HashMap<String, Array2<f64>>,
trend_analysis: HashMap<String, TrendAnalysis>,
patterns: HashMap<String, Vec<Pattern>>,
}
impl TelemetryAnalytics {
fn new(config: AnalyticsConfig) -> Self {
Self {
config,
statistical_models: HashMap::new(),
predictive_models: HashMap::new(),
correlation_matrices: HashMap::new(),
trend_analysis: HashMap::new(),
patterns: HashMap::new(),
}
}
async fn generate_report(&self, report_type: ReportType) -> DeviceResult<TelemetryReport> {
Ok(TelemetryReport {
report_type,
period: (
SystemTime::now() - Duration::from_secs(86400),
SystemTime::now(),
),
summary: ReportSummary {
kpis: HashMap::new(),
highlights: vec!["System performing within normal parameters".to_string()],
issues: Vec::new(),
assessment: "Good".to_string(),
},
metrics: HashMap::new(),
insights: Vec::new(),
recommendations: Vec::new(),
generated_at: SystemTime::now(),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TrendDirection {
Increasing,
Decreasing,
Stable,
Volatile,
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReportType {
Performance,
Resource,
Error,
Cost,
Health,
Security,
Comprehensive,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompressionConfig {
pub enabled: bool,
pub algorithm: CompressionAlgorithm,
pub ratio_threshold: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EscalationRule {
pub name: String,
pub condition: EscalationCondition,
pub delay: Duration,
pub target_severity: AlertSeverity,
pub actions: Vec<EscalationAction>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SystemStatus {
Healthy,
Degraded,
Critical,
Offline,
Maintenance,
Unknown,
}
pub struct QuantumTelemetrySystem {
config: TelemetryConfig,
collectors: Arc<RwLock<HashMap<String, Box<dyn MetricCollector + Send + Sync>>>>,
monitor: Arc<RwLock<RealTimeMonitor>>,
analytics: Arc<RwLock<TelemetryAnalytics>>,
alert_manager: Arc<RwLock<AlertManager>>,
storage: Arc<RwLock<TelemetryStorage>>,
event_sender: broadcast::Sender<TelemetryEvent>,
command_receiver: Arc<Mutex<mpsc::UnboundedReceiver<TelemetryCommand>>>,
}
impl QuantumTelemetrySystem {
pub fn new(config: TelemetryConfig) -> Self {
let (event_sender, _) = broadcast::channel(1000);
let (command_sender, command_receiver) = mpsc::unbounded_channel();
Self {
config: config.clone(),
collectors: Arc::new(RwLock::new(HashMap::new())),
monitor: Arc::new(RwLock::new(RealTimeMonitor::new(
config.monitoring_config.clone(),
))),
analytics: Arc::new(RwLock::new(TelemetryAnalytics::new(
config.analytics_config.clone(),
))),
alert_manager: Arc::new(RwLock::new(AlertManager::new(config.alert_config))),
storage: Arc::new(RwLock::new(TelemetryStorage::new(StorageConfig::default()))),
event_sender,
command_receiver: Arc::new(Mutex::new(command_receiver)),
}
}
pub async fn start(&self) -> DeviceResult<()> {
if !self.config.enabled {
return Ok(());
}
self.start_metric_collection().await?;
if self.config.enable_realtime_monitoring {
self.start_realtime_monitoring().await?;
}
if self.config.enable_analytics {
self.start_analytics_processing().await?;
}
if self.config.enable_alerting {
self.start_alert_processing().await?;
}
Ok(())
}
pub async fn stop(&self) -> DeviceResult<()> {
Ok(())
}
pub fn register_collector(
&self,
collector: Box<dyn MetricCollector + Send + Sync>,
) -> DeviceResult<()> {
let mut collectors = self.collectors.write().map_err(|e| {
DeviceError::LockError(format!("Failed to acquire write lock on collectors: {e}"))
})?;
collectors.insert(collector.name().to_string(), collector);
Ok(())
}
pub async fn collect_metrics(&self) -> DeviceResult<Vec<Metric>> {
let collectors = self.collectors.read().map_err(|e| {
DeviceError::LockError(format!("Failed to acquire read lock on collectors: {e}"))
})?;
let mut all_metrics = Vec::new();
for collector in collectors.values() {
if collector.is_enabled() {
match collector.collect() {
Ok(mut metrics) => all_metrics.append(&mut metrics),
Err(e) => {
eprintln!(
"Error collecting metrics from {}: {:?}",
collector.name(),
e
);
}
}
}
}
{
let mut storage = self.storage.write().map_err(|e| {
DeviceError::LockError(format!("Failed to acquire write lock on storage: {e}"))
})?;
storage.store_metrics(&all_metrics)?;
}
for metric in &all_metrics {
let _ = self.event_sender.send(TelemetryEvent::MetricCollected {
metric_name: metric.name.clone(),
value: metric.value,
timestamp: metric.timestamp,
metadata: metric.metadata.clone(),
});
}
Ok(all_metrics)
}
pub fn get_system_health(&self) -> DeviceResult<SystemHealth> {
let monitor = self.monitor.read().map_err(|e| {
DeviceError::LockError(format!("Failed to acquire read lock on monitor: {e}"))
})?;
Ok(monitor.get_system_health())
}
pub async fn generate_report(&self, report_type: ReportType) -> DeviceResult<TelemetryReport> {
let analytics = self.analytics.read().map_err(|e| {
DeviceError::LockError(format!("Failed to acquire read lock on analytics: {e}"))
})?;
analytics.generate_report(report_type).await
}
async fn start_metric_collection(&self) -> DeviceResult<()> {
let interval_duration = Duration::from_secs(self.config.collection_interval);
let mut interval = interval(interval_duration);
Ok(())
}
async fn start_realtime_monitoring(&self) -> DeviceResult<()> {
Ok(())
}
async fn start_analytics_processing(&self) -> DeviceResult<()> {
Ok(())
}
async fn start_alert_processing(&self) -> DeviceResult<()> {
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCriterion {
pub metric: String,
pub operator: ComparisonOperator,
pub value: f64,
pub severity: AlertSeverity,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonitoringConfig {
pub dashboard_refresh_rate: u64,
pub health_check_interval: u64,
pub anomaly_sensitivity: f64,
pub enable_trend_analysis: bool,
pub monitoring_targets: Vec<MonitoringTarget>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ExportFormat {
JSON,
Prometheus,
InfluxDB,
CSV,
Binary,
Custom(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetentionConfig {
pub realtime_retention_hours: u32,
pub historical_retention_days: u32,
pub aggregated_retention_months: u32,
pub enable_compression: bool,
pub archive_threshold_gb: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertConfig {
pub enable_email_alerts: bool,
pub enable_sms_alerts: bool,
pub enable_webhook_alerts: bool,
pub enable_slack_alerts: bool,
pub thresholds: HashMap<String, AlertThreshold>,
pub escalation_rules: Vec<EscalationRule>,
pub suppression_rules: Vec<SuppressionRule>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EscalationEvent {
pub timestamp: SystemTime,
pub from_level: u32,
pub to_level: u32,
pub reason: String,
pub actions: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AggregatedData {
pub interval: Duration,
pub summary: StatisticalSummary,
pub data_points: Vec<(SystemTime, f64)>,
pub last_updated: SystemTime,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EscalationAction {
NotifyAdministrator,
TriggerAutomatedResponse,
DisableAffectedComponent,
IncreaseMonitoringFrequency,
CreateIncident,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuppressionRule {
pub name: String,
pub condition: SuppressionCondition,
pub duration: Duration,
pub alert_types: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportEndpoint {
pub url: String,
pub auth: Option<ExportAuth>,
pub format: ExportFormat,
pub frequency: Duration,
pub batch_size: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TelemetryConfig {
pub enabled: bool,
pub collection_interval: u64,
pub enable_realtime_monitoring: bool,
pub enable_analytics: bool,
pub enable_alerting: bool,
pub retention_config: RetentionConfig,
pub metric_config: MetricConfig,
pub monitoring_config: MonitoringConfig,
pub analytics_config: AnalyticsConfig,
pub alert_config: AlertConfig,
pub export_config: ExportConfig,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnomalyDetectorType {
Statistical,
MachineLearning,
Threshold,
Isolation,
LSTM,
AutoEncoder,
Custom(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThresholdRule {
pub value: f64,
pub operator: ComparisonOperator,
pub duration: Duration,
pub recovery_value: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrendAnalysis {
pub direction: TrendDirection,
pub strength: f64,
pub slope: f64,
pub r_squared: f64,
pub confidence_interval: (f64, f64),
pub projection: Vec<(SystemTime, f64)>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Alert {
pub id: String,
pub name: String,
pub severity: AlertSeverity,
pub message: String,
pub metric: String,
pub current_value: f64,
pub threshold_value: f64,
pub state: AlertState,
pub first_triggered: SystemTime,
pub last_triggered: SystemTime,
pub acknowledgment: Option<AlertAcknowledgment>,
pub metadata: HashMap<String, String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
pub realtime_buffer_size: usize,
pub aggregation_intervals: Vec<Duration>,
pub compression: CompressionConfig,
pub persistence: PersistenceConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthStatus {
pub status: SystemStatus,
pub last_check: SystemTime,
pub details: HashMap<String, String>,
pub health_score: f64,
pub issues: Vec<HealthIssue>,
}
#[derive(Debug)]
pub struct TelemetryStorage {
config: StorageConfig,
realtime_buffer: HashMap<String, VecDeque<Metric>>,
aggregated_cache: HashMap<String, AggregatedData>,
time_series_index: BTreeMap<SystemTime, Vec<String>>,
statistics: StorageStatistics,
}
impl TelemetryStorage {
fn new(config: StorageConfig) -> Self {
Self {
config,
realtime_buffer: HashMap::new(),
aggregated_cache: HashMap::new(),
time_series_index: BTreeMap::new(),
statistics: StorageStatistics {
total_metrics: 0,
storage_size_bytes: 0,
compression_ratio: 1.0,
write_rate: 0.0,
read_rate: 0.0,
cache_hit_rate: 0.0,
},
}
}
fn store_metrics(&mut self, metrics: &[Metric]) -> DeviceResult<()> {
for metric in metrics {
let buffer = self.realtime_buffer.entry(metric.name.clone()).or_default();
buffer.push_back(metric.clone());
while buffer.len() > self.config.realtime_buffer_size {
buffer.pop_front();
}
let metric_names = self.time_series_index.entry(metric.timestamp).or_default();
metric_names.push(metric.name.clone());
}
self.statistics.total_metrics += metrics.len() as u64;
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatisticalSummary {
pub count: usize,
pub mean: f64,
pub std_dev: f64,
pub min: f64,
pub max: f64,
pub percentiles: HashMap<u8, f64>,
pub variance: f64,
pub skewness: f64,
pub kurtosis: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalyticsConfig {
pub enable_statistical_analysis: bool,
pub enable_predictive_analytics: bool,
pub enable_correlation_analysis: bool,
pub processing_interval_minutes: u64,
pub confidence_level: f64,
pub prediction_horizon_hours: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertThreshold {
pub warning: Option<ThresholdRule>,
pub critical: Option<ThresholdRule>,
pub emergency: Option<ThresholdRule>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportInsight {
pub insight_type: InsightType,
pub description: String,
pub data: HashMap<String, f64>,
pub confidence: f64,
pub impact: ImpactLevel,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EscalationCondition {
UnresolvedAfter(Duration),
RepeatedFailures(u32),
SeverityIncrease,
MetricThreshold(String, f64),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricConfig {
pub enable_performance_metrics: bool,
pub enable_resource_metrics: bool,
pub enable_error_metrics: bool,
pub enable_cost_metrics: bool,
pub enable_custom_metrics: bool,
pub sampling_rate: f64,
pub batch_size: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MonitoringTargetType {
Device,
Circuit,
Job,
Provider,
Resource,
Application,
Custom(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PersistenceConfig {
pub enabled: bool,
pub backend: StorageBackend,
pub batch_size: usize,
pub write_interval: Duration,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum StatisticalModelType {
Normal,
Exponential,
Gamma,
ChiSquared,
Weibull,
Beta,
LogNormal,
Custom(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AlertState {
Triggered,
Acknowledged,
Resolved,
Suppressed,
Escalated,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertAcknowledgment {
pub acknowledged_by: String,
pub acknowledged_at: SystemTime,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum StorageBackend {
Memory,
File,
Database,
TimeSeries,
Cloud,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportSummary {
pub kpis: HashMap<String, f64>,
pub highlights: Vec<String>,
pub issues: Vec<String>,
pub assessment: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricSnapshot {
pub value: f64,
pub timestamp: SystemTime,
pub rate: Option<f64>,
pub trend: TrendDirection,
pub anomaly_score: Option<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatisticalModel {
pub model_type: StatisticalModelType,
pub parameters: HashMap<String, f64>,
pub fit_metrics: FitMetrics,
pub last_updated: SystemTime,
pub training_size: usize,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ComparisonOperator {
GreaterThan,
LessThan,
Equals,
NotEquals,
GreaterThanOrEqual,
LessThanOrEqual,
Between(f64, f64),
Outside(f64, f64),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MetricType {
Counter,
Gauge,
Histogram,
Summary,
Timer,
Custom(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TelemetryReport {
pub report_type: ReportType,
pub period: (SystemTime, SystemTime),
pub summary: ReportSummary,
pub metrics: HashMap<String, MetricReport>,
pub insights: Vec<ReportInsight>,
pub recommendations: Vec<String>,
pub generated_at: SystemTime,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Metric {
pub name: String,
pub value: f64,
pub unit: String,
pub metric_type: MetricType,
pub timestamp: SystemTime,
pub labels: HashMap<String, String>,
pub metadata: HashMap<String, String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FitMetrics {
pub r_squared: f64,
pub aic: f64,
pub bic: f64,
pub log_likelihood: f64,
pub p_value: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthCheckConfig {
pub endpoint: String,
pub timeout: Duration,
pub expected_response: Option<String>,
pub criteria: Vec<HealthCriterion>,
}