1use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::time::{Duration, SystemTime, UNIX_EPOCH};
7use thiserror::Error;
8use zeroize::Zeroizing;
9
10#[derive(Debug, Error)]
11pub enum MonitoringError {
12 #[error("Metric collection error: {0}")]
13 MetricCollection(String),
14 #[error("Exporter error: {0}")]
15 Exporter(String),
16 #[error("Alert manager error: {0}")]
17 AlertManager(String),
18 #[error("Dashboard error: {0}")]
19 Dashboard(String),
20 #[error("Configuration error: {0}")]
21 Configuration(String),
22 #[error("Network error: {0}")]
23 Network(String),
24 #[error("IO error: {0}")]
25 Io(#[from] std::io::Error),
26 #[error("Serialization error: {0}")]
27 Serialization(#[from] serde_json::Error),
28}
29
30#[derive(Debug, Clone, Serialize, Deserialize)]
32pub enum MetricType {
33 Counter,
34 Gauge,
35 Histogram,
36 Summary,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct MetricValue {
42 pub value: f64,
43 pub timestamp: u64,
44 pub labels: HashMap<String, String>,
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize)]
49pub struct Metric {
50 pub name: String,
51 pub metric_type: MetricType,
52 pub description: String,
53 pub unit: String,
54 pub values: Vec<MetricValue>,
55 pub retention: Duration,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct AlertRule {
61 pub name: String,
62 pub metric_name: String,
63 pub condition: AlertCondition,
64 pub threshold: f64,
65 pub duration: Duration,
66 pub severity: AlertSeverity,
67 pub enabled: bool,
68 pub labels: HashMap<String, String>,
69 pub annotations: HashMap<String, String>,
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
73pub enum AlertCondition {
74 GreaterThan,
75 LessThan,
76 Equal,
77 NotEqual,
78 GreaterThanOrEqual,
79 LessThanOrEqual,
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub enum AlertSeverity {
84 Critical,
85 Warning,
86 Info,
87}
88
89#[derive(Debug, Clone, Serialize, Deserialize)]
91pub struct Alert {
92 pub rule_name: String,
93 pub metric_name: String,
94 pub current_value: f64,
95 pub threshold: f64,
96 pub severity: AlertSeverity,
97 pub message: String,
98 pub started_at: u64,
99 pub resolved_at: Option<u64>,
100 pub labels: HashMap<String, String>,
101}
102
103#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct Dashboard {
106 pub id: String,
107 pub title: String,
108 pub description: String,
109 pub panels: Vec<DashboardPanel>,
110 pub refresh_interval: Duration,
111 pub time_range: TimeRange,
112 pub variables: HashMap<String, String>,
113}
114
115#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct DashboardPanel {
117 pub id: String,
118 pub title: String,
119 pub panel_type: PanelType,
120 pub metric_queries: Vec<String>,
121 pub position: PanelPosition,
122 pub options: HashMap<String, serde_json::Value>,
123}
124
125#[derive(Debug, Clone, Serialize, Deserialize)]
126pub enum PanelType {
127 LineGraph,
128 BarChart,
129 Gauge,
130 SingleStat,
131 Table,
132 HeatMap,
133 Alert,
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize)]
137pub struct PanelPosition {
138 pub x: u32,
139 pub y: u32,
140 pub width: u32,
141 pub height: u32,
142}
143
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub struct TimeRange {
146 pub from: String,
147 pub to: String,
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
152pub struct MonitoringConfig {
153 pub enabled: bool,
154 pub prometheus: PrometheusConfig,
155 pub grafana: GrafanaConfig,
156 pub alertmanager: AlertManagerConfig,
157 pub custom_exporters: Vec<ExporterConfig>,
158 pub dashboards: Vec<Dashboard>,
159 pub retention_policy: RetentionPolicy,
160}
161
162#[derive(Debug, Clone, Serialize, Deserialize)]
163pub struct PrometheusConfig {
164 pub endpoint: String,
165 pub scrape_interval: Duration,
166 pub evaluation_interval: Duration,
167 pub external_labels: HashMap<String, String>,
168 pub rule_files: Vec<String>,
169}
170
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct GrafanaConfig {
173 pub endpoint: String,
174 pub api_key: Zeroizing<String>,
175 pub organization: String,
176 pub datasource: String,
177 pub auto_provision: bool,
178}
179
180#[derive(Debug, Clone, Serialize, Deserialize)]
181pub struct AlertManagerConfig {
182 pub endpoint: String,
183 pub receivers: Vec<AlertReceiver>,
184 pub routing: AlertRouting,
185 pub inhibit_rules: Vec<InhibitRule>,
186}
187
188#[derive(Debug, Clone, Serialize, Deserialize)]
189pub struct AlertReceiver {
190 pub name: String,
191 pub webhook_configs: Vec<WebhookConfig>,
192 pub email_configs: Vec<EmailConfig>,
193 pub slack_configs: Vec<SlackConfig>,
194}
195
196#[derive(Clone, Serialize, Deserialize)]
197pub struct WebhookConfig {
198 pub url: String,
199 pub http_config: Option<HttpConfig>,
200}
201
202impl std::fmt::Debug for WebhookConfig {
203 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204 let mut d = f.debug_struct("WebhookConfig");
205 d.field("url", &crate::utils::redact::redacted(&self.url));
206 d.field("http_config", &self.http_config);
207 d.finish()
208 }
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct EmailConfig {
213 pub to: Vec<String>,
214 pub from: String,
215 pub subject: String,
216 pub body: String,
217}
218
219#[derive(Clone, Serialize, Deserialize)]
220pub struct SlackConfig {
221 pub api_url: String,
222 pub channel: String,
223 pub username: String,
224 pub title: String,
225 pub text: String,
226}
227
228impl std::fmt::Debug for SlackConfig {
230 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231 let mut d = f.debug_struct("SlackConfig");
232 d.field("api_url", &crate::utils::redact::redacted(&self.api_url));
233 d.field("channel", &self.channel);
234 d.field("username", &self.username);
235 d.field("title", &self.title);
236 d.field("text", &self.text);
237 d.finish()
238 }
239}
240
241#[derive(Clone, Serialize, Deserialize)]
242pub struct HttpConfig {
243 pub basic_auth: Option<BasicAuth>,
244 pub bearer_token: Option<String>,
245 pub tls_config: Option<TlsConfig>,
246}
247
248impl std::fmt::Debug for HttpConfig {
249 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250 let mut d = f.debug_struct("HttpConfig");
251 d.field("basic_auth", &self.basic_auth);
252 d.field(
253 "bearer_token",
254 &crate::utils::redact::redacted(&self.bearer_token),
255 );
256 d.field("tls_config", &self.tls_config);
257 d.finish()
258 }
259}
260
261#[derive(Clone, Serialize, Deserialize)]
262pub struct BasicAuth {
263 pub username: String,
264 pub password: String,
265}
266
267impl std::fmt::Debug for BasicAuth {
268 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
269 let mut d = f.debug_struct("BasicAuth");
270 d.field("username", &self.username);
271 d.field("password", &crate::utils::redact::redacted(&self.password));
272 d.finish()
273 }
274}
275
276#[derive(Debug, Clone, Serialize, Deserialize)]
277pub struct TlsConfig {
278 pub ca_file: Option<String>,
279 pub cert_file: Option<String>,
280 pub key_file: Option<String>,
281 pub insecure_skip_verify: bool,
282}
283
284#[derive(Debug, Clone, Serialize, Deserialize)]
285pub struct AlertRouting {
286 pub group_by: Vec<String>,
287 pub group_wait: Duration,
288 pub group_interval: Duration,
289 pub repeat_interval: Duration,
290 pub receiver: String,
291 pub routes: Vec<Route>,
292}
293
294#[derive(Debug, Clone, Serialize, Deserialize)]
295pub struct Route {
296 pub matchers: HashMap<String, String>,
297 pub receiver: String,
298 pub group_by: Vec<String>,
299 pub continue_route: bool,
300}
301
302#[derive(Debug, Clone, Serialize, Deserialize)]
303pub struct InhibitRule {
304 pub source_matchers: HashMap<String, String>,
305 pub target_matchers: HashMap<String, String>,
306 pub equal: Vec<String>,
307}
308
309#[derive(Debug, Clone, Serialize, Deserialize)]
310pub struct ExporterConfig {
311 pub name: String,
312 pub endpoint: String,
313 pub interval: Duration,
314 pub timeout: Duration,
315 pub labels: HashMap<String, String>,
316}
317
318#[derive(Debug, Clone, Serialize, Deserialize)]
319pub struct RetentionPolicy {
320 pub default_retention: Duration,
321 pub metric_retentions: HashMap<String, Duration>,
322 pub downsampling_rules: Vec<DownsamplingRule>,
323}
324
325#[derive(Debug, Clone, Serialize, Deserialize)]
326pub struct DownsamplingRule {
327 pub resolution: Duration,
328 pub retention: Duration,
329 pub aggregation: AggregationType,
330}
331
332#[derive(Debug, Clone, Serialize, Deserialize)]
333pub enum AggregationType {
334 Average,
335 Sum,
336 Min,
337 Max,
338 Count,
339}
340
341pub struct MonitoringSystem {
343 config: MonitoringConfig,
344 metrics: HashMap<String, Metric>,
345 alert_rules: Vec<AlertRule>,
346 active_alerts: Vec<Alert>,
347 dashboards: Vec<Dashboard>,
348}
349
350impl MonitoringSystem {
351 pub fn new(config: MonitoringConfig) -> Self {
353 Self {
354 config,
355 metrics: HashMap::new(),
356 alert_rules: Vec::new(),
357 active_alerts: Vec::new(),
358 dashboards: Vec::new(),
359 }
360 }
361
362 pub async fn initialize(&mut self) -> Result<(), MonitoringError> {
364 if !self.config.enabled {
365 return Ok(());
366 }
367
368 self.initialize_prometheus().await?;
370
371 self.initialize_grafana().await?;
373
374 self.initialize_alertmanager().await?;
376
377 self.setup_default_metrics().await?;
379
380 self.load_dashboards().await?;
382
383 Ok(())
384 }
385
386 async fn initialize_prometheus(&self) -> Result<(), MonitoringError> {
388 tracing::info!(
390 endpoint = %self.config.prometheus.endpoint,
391 "Initializing Prometheus"
392 );
393 Ok(())
394 }
395
396 async fn initialize_grafana(&self) -> Result<(), MonitoringError> {
398 if self.config.grafana.auto_provision {
399 self.provision_grafana_dashboards().await?;
401 }
402 Ok(())
403 }
404
405 async fn initialize_alertmanager(&self) -> Result<(), MonitoringError> {
407 tracing::info!(
409 endpoint = %self.config.alertmanager.endpoint,
410 "Initializing AlertManager"
411 );
412 Ok(())
413 }
414
415 async fn setup_default_metrics(&mut self) -> Result<(), MonitoringError> {
417 self.register_metric(Metric {
419 name: "auth_requests_total".to_string(),
420 metric_type: MetricType::Counter,
421 description: "Total number of authentication requests".to_string(),
422 unit: "requests".to_string(),
423 values: Vec::new(),
424 retention: Duration::from_secs(30 * 24 * 3600), });
426
427 self.register_metric(Metric {
428 name: "auth_success_total".to_string(),
429 metric_type: MetricType::Counter,
430 description: "Total number of successful authentications".to_string(),
431 unit: "requests".to_string(),
432 values: Vec::new(),
433 retention: Duration::from_secs(30 * 24 * 3600),
434 });
435
436 self.register_metric(Metric {
437 name: "auth_failures_total".to_string(),
438 metric_type: MetricType::Counter,
439 description: "Total number of failed authentications".to_string(),
440 unit: "requests".to_string(),
441 values: Vec::new(),
442 retention: Duration::from_secs(30 * 24 * 3600),
443 });
444
445 self.register_metric(Metric {
447 name: "authz_checks_total".to_string(),
448 metric_type: MetricType::Counter,
449 description: "Total number of authorization checks".to_string(),
450 unit: "checks".to_string(),
451 values: Vec::new(),
452 retention: Duration::from_secs(30 * 24 * 3600),
453 });
454
455 self.register_metric(Metric {
456 name: "authz_denied_total".to_string(),
457 metric_type: MetricType::Counter,
458 description: "Total number of denied authorization checks".to_string(),
459 unit: "checks".to_string(),
460 values: Vec::new(),
461 retention: Duration::from_secs(30 * 24 * 3600),
462 });
463
464 self.register_metric(Metric {
466 name: "request_duration_seconds".to_string(),
467 metric_type: MetricType::Histogram,
468 description: "Request duration in seconds".to_string(),
469 unit: "seconds".to_string(),
470 values: Vec::new(),
471 retention: Duration::from_secs(7 * 24 * 3600), });
473
474 self.register_metric(Metric {
475 name: "active_sessions".to_string(),
476 metric_type: MetricType::Gauge,
477 description: "Number of active user sessions".to_string(),
478 unit: "sessions".to_string(),
479 values: Vec::new(),
480 retention: Duration::from_secs(24 * 3600), });
482
483 Ok(())
484 }
485
486 pub fn register_metric(&mut self, metric: Metric) {
488 self.metrics.insert(metric.name.clone(), metric);
489 }
490
491 pub fn record_metric(
493 &mut self,
494 name: &str,
495 value: f64,
496 labels: HashMap<String, String>,
497 ) -> Result<(), MonitoringError> {
498 if let Some(metric) = self.metrics.get_mut(name) {
499 let now = SystemTime::now()
500 .duration_since(UNIX_EPOCH)
501 .unwrap_or_default();
502
503 let metric_value = MetricValue {
504 value,
505 timestamp: now.as_secs(),
506 labels,
507 };
508
509 metric.values.push(metric_value);
510
511 let cutoff = now.as_secs() - metric.retention.as_secs();
513 metric.values.retain(|v| v.timestamp > cutoff);
514
515 Ok(())
516 } else {
517 Err(MonitoringError::MetricCollection(format!(
518 "Metric not found: {}",
519 name
520 )))
521 }
522 }
523
524 pub fn add_alert_rule(&mut self, rule: AlertRule) {
526 self.alert_rules.push(rule);
527 }
528
529 pub async fn evaluate_alerts(&mut self) -> Result<(), MonitoringError> {
531 let now = SystemTime::now()
532 .duration_since(UNIX_EPOCH)
533 .unwrap_or_default();
534
535 for rule in &self.alert_rules {
536 if !rule.enabled {
537 continue;
538 }
539
540 if let Some(metric) = self.metrics.get(&rule.metric_name)
541 && let Some(latest_value) = metric.values.last()
542 {
543 let should_alert = match rule.condition {
544 AlertCondition::GreaterThan => latest_value.value > rule.threshold,
545 AlertCondition::LessThan => latest_value.value < rule.threshold,
546 AlertCondition::Equal => {
547 (latest_value.value - rule.threshold).abs() < f64::EPSILON
548 }
549 AlertCondition::NotEqual => {
550 (latest_value.value - rule.threshold).abs() > f64::EPSILON
551 }
552 AlertCondition::GreaterThanOrEqual => latest_value.value >= rule.threshold,
553 AlertCondition::LessThanOrEqual => latest_value.value <= rule.threshold,
554 };
555
556 if should_alert {
557 let existing_alert = self
559 .active_alerts
560 .iter()
561 .find(|alert| alert.rule_name == rule.name && alert.resolved_at.is_none());
562
563 if existing_alert.is_none() {
564 let alert = Alert {
565 rule_name: rule.name.clone(),
566 metric_name: rule.metric_name.clone(),
567 current_value: latest_value.value,
568 threshold: rule.threshold,
569 severity: rule.severity.clone(),
570 message: format!(
571 "Alert: {} - Current value: {}, Threshold: {}",
572 rule.name, latest_value.value, rule.threshold
573 ),
574 started_at: now.as_secs(),
575 resolved_at: None,
576 labels: rule.labels.clone(),
577 };
578
579 self.active_alerts.push(alert.clone());
580 self.send_alert(&alert).await?;
581 }
582 } else {
583 let mut alerts_to_resolve = Vec::new();
585 for alert in &mut self.active_alerts {
586 if alert.rule_name == rule.name && alert.resolved_at.is_none() {
587 alert.resolved_at = Some(now.as_secs());
588 alerts_to_resolve.push(alert.clone());
589 }
590 }
591
592 for alert in &alerts_to_resolve {
594 self.send_alert_resolution(alert).await?;
595 }
596 }
597 }
598 }
599 Ok(())
600 }
601
602 async fn send_alert(&self, alert: &Alert) -> Result<(), MonitoringError> {
604 tracing::warn!(rule = %alert.rule_name, message = %alert.message, "ALERT triggered");
606
607 for receiver in &self.config.alertmanager.receivers {
609 self.send_to_receiver(receiver, alert).await?;
610 }
611
612 Ok(())
613 }
614
615 async fn send_alert_resolution(&self, alert: &Alert) -> Result<(), MonitoringError> {
617 tracing::info!(rule = %alert.rule_name, message = %alert.message, "ALERT resolved");
618 Ok(())
619 }
620
621 async fn send_to_receiver(
623 &self,
624 receiver: &AlertReceiver,
625 alert: &Alert,
626 ) -> Result<(), MonitoringError> {
627 for webhook in &receiver.webhook_configs {
629 self.send_webhook_alert(webhook, alert).await?;
630 }
631
632 for email in &receiver.email_configs {
634 self.send_email_alert(email, alert).await?;
635 }
636
637 for slack in &receiver.slack_configs {
639 self.send_slack_alert(slack, alert).await?;
640 }
641
642 Ok(())
643 }
644
645 async fn send_webhook_alert(
647 &self,
648 _webhook: &WebhookConfig,
649 _alert: &Alert,
650 ) -> Result<(), MonitoringError> {
651 Ok(())
653 }
654
655 async fn send_email_alert(
657 &self,
658 _email: &EmailConfig,
659 _alert: &Alert,
660 ) -> Result<(), MonitoringError> {
661 Ok(())
663 }
664
665 async fn send_slack_alert(
667 &self,
668 _slack: &SlackConfig,
669 _alert: &Alert,
670 ) -> Result<(), MonitoringError> {
671 Ok(())
673 }
674
675 async fn load_dashboards(&mut self) -> Result<(), MonitoringError> {
677 self.dashboards = self.config.dashboards.clone();
678 Ok(())
679 }
680
681 async fn provision_grafana_dashboards(&self) -> Result<(), MonitoringError> {
683 for dashboard in &self.config.dashboards {
684 tracing::info!(title = %dashboard.title, "Provisioning Grafana dashboard");
685 }
686 Ok(())
687 }
688
689 pub fn export_prometheus_metrics(&self) -> String {
691 let mut output = String::new();
692
693 for (name, metric) in &self.metrics {
694 output.push_str(&format!("# HELP {} {}\n", name, metric.description));
696 output.push_str(&format!(
697 "# TYPE {} {}\n",
698 name,
699 match metric.metric_type {
700 MetricType::Counter => "counter",
701 MetricType::Gauge => "gauge",
702 MetricType::Histogram => "histogram",
703 MetricType::Summary => "summary",
704 }
705 ));
706
707 for value in &metric.values {
709 let labels = if value.labels.is_empty() {
710 String::new()
711 } else {
712 let label_pairs: Vec<String> = value
713 .labels
714 .iter()
715 .map(|(k, v)| format!("{}=\"{}\"", k, v))
716 .collect();
717 format!("{{{}}}", label_pairs.join(","))
718 };
719
720 output.push_str(&format!(
721 "{}{} {} {}\n",
722 name,
723 labels,
724 value.value,
725 value.timestamp * 1000
726 ));
727 }
728 }
729
730 output
731 }
732
733 pub fn get_metrics(&self) -> &HashMap<String, Metric> {
735 &self.metrics
736 }
737
738 pub fn get_active_alerts(&self) -> &Vec<Alert> {
740 &self.active_alerts
741 }
742
743 pub fn get_dashboards(&self) -> &Vec<Dashboard> {
745 &self.dashboards
746 }
747}
748
749impl Default for MonitoringConfig {
750 fn default() -> Self {
751 Self {
752 enabled: true,
753 prometheus: PrometheusConfig {
754 endpoint: "http://localhost:9090".to_string(),
755 scrape_interval: Duration::from_secs(15),
756 evaluation_interval: Duration::from_secs(15),
757 external_labels: HashMap::new(),
758 rule_files: vec!["alerts.yml".to_string()],
759 },
760 grafana: GrafanaConfig {
761 endpoint: "http://localhost:3000".to_string(),
762 api_key: "".to_string().into(),
763 organization: "Main Org.".to_string(),
764 datasource: "Prometheus".to_string(),
765 auto_provision: true,
766 },
767 alertmanager: AlertManagerConfig {
768 endpoint: "http://localhost:9093".to_string(),
769 receivers: vec![AlertReceiver {
770 name: "default".to_string(),
771 webhook_configs: Vec::new(),
772 email_configs: Vec::new(),
773 slack_configs: Vec::new(),
774 }],
775 routing: AlertRouting {
776 group_by: vec!["alertname".to_string()],
777 group_wait: Duration::from_secs(10),
778 group_interval: Duration::from_secs(10),
779 repeat_interval: Duration::from_secs(3600),
780 receiver: "default".to_string(),
781 routes: Vec::new(),
782 },
783 inhibit_rules: Vec::new(),
784 },
785 custom_exporters: Vec::new(),
786 dashboards: Vec::new(),
787 retention_policy: RetentionPolicy {
788 default_retention: Duration::from_secs(30 * 24 * 3600), metric_retentions: HashMap::new(),
790 downsampling_rules: Vec::new(),
791 },
792 }
793 }
794}
795
796#[cfg(test)]
797mod tests {
798 use super::*;
799
800 #[test]
801 fn test_monitoring_system_creation() {
802 let config = MonitoringConfig::default();
803 let system = MonitoringSystem::new(config);
804
805 assert!(system.metrics.is_empty());
806 assert!(system.alert_rules.is_empty());
807 assert!(system.active_alerts.is_empty());
808 }
809
810 #[tokio::test]
811 async fn test_metric_registration() {
812 let config = MonitoringConfig::default();
813 let mut system = MonitoringSystem::new(config);
814
815 let metric = Metric {
816 name: "test_metric".to_string(),
817 metric_type: MetricType::Counter,
818 description: "Test metric".to_string(),
819 unit: "count".to_string(),
820 values: Vec::new(),
821 retention: Duration::from_secs(3600),
822 };
823
824 system.register_metric(metric);
825 assert!(system.metrics.contains_key("test_metric"));
826 }
827
828 #[tokio::test]
829 async fn test_metric_recording() {
830 let config = MonitoringConfig::default();
831 let mut system = MonitoringSystem::new(config);
832
833 let metric = Metric {
834 name: "test_counter".to_string(),
835 metric_type: MetricType::Counter,
836 description: "Test counter".to_string(),
837 unit: "count".to_string(),
838 values: Vec::new(),
839 retention: Duration::from_secs(3600),
840 };
841
842 system.register_metric(metric);
843
844 let mut labels = HashMap::new();
845 labels.insert("service".to_string(), "auth".to_string());
846
847 let result = system.record_metric("test_counter", 1.0, labels);
848 assert!(result.is_ok());
849
850 let metric = system.metrics.get("test_counter").unwrap();
851 assert_eq!(metric.values.len(), 1);
852 assert_eq!(metric.values[0].value, 1.0);
853 }
854
855 #[test]
856 fn test_prometheus_export() {
857 let config = MonitoringConfig::default();
858 let mut system = MonitoringSystem::new(config);
859
860 let metric = Metric {
861 name: "test_gauge".to_string(),
862 metric_type: MetricType::Gauge,
863 description: "Test gauge".to_string(),
864 unit: "value".to_string(),
865 values: vec![MetricValue {
866 value: 42.0,
867 timestamp: 1640995200,
868 labels: HashMap::new(),
869 }],
870 retention: Duration::from_secs(3600),
871 };
872
873 system.register_metric(metric);
874
875 let export = system.export_prometheus_metrics();
876 assert!(export.contains("# HELP test_gauge Test gauge"));
877 assert!(export.contains("# TYPE test_gauge gauge"));
878 assert!(export.contains("test_gauge 42"));
879 }
880}