Skip to main content

oxirs_cluster/
alerting.rs

1//! Alerting System Framework
2//!
3//! This module provides a comprehensive alerting system for the OxiRS cluster,
4//! enabling notifications for critical events, performance issues, and operational anomalies.
5//!
6//! # Features
7//!
8//! - **Multiple Alert Channels**: Email, Slack, webhooks, and custom handlers
9//! - **Alert Severity Levels**: Critical, error, warning, info
10//! - **Alert Throttling**: Prevent alert storms with configurable throttling
11//! - **Alert Aggregation**: Group similar alerts to reduce noise
12//! - **Template Support**: Customizable alert message templates
13//! - **Alert History**: Track and query past alerts
14//! - **SciRS2 Integration**: Statistical anomaly detection for smart alerting
15//!
16//! # Example
17//!
18//! ```rust,no_run
19//! use oxirs_cluster::alerting::{AlertingConfig, AlertingManager, AlertSeverity};
20//!
21//! # async fn example() -> anyhow::Result<()> {
22//! let config = AlertingConfig::default()
23//!     .with_email_channel("smtp.example.com", 587, "user", "pass", "from@example.com", vec!["admin@example.com".to_string()])
24//!     .with_slack_channel("https://hooks.slack.com/...");
25//!
26//! let mut alerting = AlertingManager::new(config).await?;
27//! alerting.start().await?;
28//!
29//! // Send an alert
30//! alerting.send_alert(
31//!     AlertSeverity::Critical,
32//!     "Node Failure",
33//!     "Node 3 is unresponsive",
34//! ).await?;
35//! # Ok(())
36//! # }
37//! ```
38
39use chrono::{DateTime, Utc};
40use lettre::{
41    message::header::ContentType, transport::smtp::authentication::Credentials, AsyncSmtpTransport,
42    AsyncTransport, Message, Tokio1Executor,
43};
44use serde::{Deserialize, Serialize};
45use std::collections::{HashMap, VecDeque};
46use std::sync::Arc;
47use std::time::Duration;
48use thiserror::Error;
49use tokio::sync::RwLock;
50
51/// Errors that can occur during alerting operations
52#[derive(Debug, Error)]
53pub enum AlertingError {
54    /// Configuration error
55    #[error("Configuration error: {0}")]
56    ConfigError(String),
57
58    /// Channel error
59    #[error("Alert channel error: {0}")]
60    ChannelError(String),
61
62    /// Email sending error
63    #[error("Failed to send email: {0}")]
64    EmailError(String),
65
66    /// Slack sending error
67    #[error("Failed to send Slack message: {0}")]
68    SlackError(String),
69
70    /// Webhook error
71    #[error("Webhook error: {0}")]
72    WebhookError(String),
73
74    /// Template error
75    #[error("Template error: {0}")]
76    TemplateError(String),
77
78    /// Other errors
79    #[error("Alerting error: {0}")]
80    Other(String),
81}
82
83pub type Result<T> = std::result::Result<T, AlertingError>;
84
85/// Alert severity levels
86#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
87pub enum AlertSeverity {
88    /// Informational alerts
89    Info,
90    /// Warning alerts
91    Warning,
92    /// Error alerts
93    Error,
94    /// Critical alerts requiring immediate attention
95    Critical,
96}
97
98impl AlertSeverity {
99    /// Get the string representation
100    pub fn as_str(&self) -> &'static str {
101        match self {
102            Self::Info => "INFO",
103            Self::Warning => "WARNING",
104            Self::Error => "ERROR",
105            Self::Critical => "CRITICAL",
106        }
107    }
108
109    /// Get emoji representation for Slack
110    pub fn emoji(&self) -> &'static str {
111        match self {
112            Self::Info => ":information_source:",
113            Self::Warning => ":warning:",
114            Self::Error => ":x:",
115            Self::Critical => ":rotating_light:",
116        }
117    }
118
119    /// Get color for Slack attachments
120    pub fn color(&self) -> &'static str {
121        match self {
122            Self::Info => "#36a64f",     // Green
123            Self::Warning => "#ff9900",  // Orange
124            Self::Error => "#ff0000",    // Red
125            Self::Critical => "#8b0000", // Dark red
126        }
127    }
128}
129
130/// Alert category
131#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
132pub enum AlertCategory {
133    /// Node health alerts
134    NodeHealth,
135    /// Consensus alerts
136    Consensus,
137    /// Replication alerts
138    Replication,
139    /// Performance alerts
140    Performance,
141    /// Security alerts
142    Security,
143    /// Storage alerts
144    Storage,
145    /// Network alerts
146    Network,
147    /// Custom category
148    Custom(String),
149}
150
151/// Alert structure
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct Alert {
154    /// Unique alert ID
155    pub id: String,
156    /// Alert severity
157    pub severity: AlertSeverity,
158    /// Alert category
159    pub category: AlertCategory,
160    /// Alert title
161    pub title: String,
162    /// Alert message
163    pub message: String,
164    /// Additional metadata
165    pub metadata: HashMap<String, String>,
166    /// Timestamp when the alert was created
167    pub timestamp: DateTime<Utc>,
168    /// Node ID that generated the alert
169    pub node_id: Option<u64>,
170    /// Whether this alert has been acknowledged
171    pub acknowledged: bool,
172    /// Acknowledgment timestamp
173    pub acknowledged_at: Option<DateTime<Utc>>,
174}
175
176impl Alert {
177    /// Create a new alert
178    pub fn new(
179        severity: AlertSeverity,
180        category: AlertCategory,
181        title: impl Into<String>,
182        message: impl Into<String>,
183    ) -> Self {
184        Self {
185            id: uuid::Uuid::new_v4().to_string(),
186            severity,
187            category,
188            title: title.into(),
189            message: message.into(),
190            metadata: HashMap::new(),
191            timestamp: Utc::now(),
192            node_id: None,
193            acknowledged: false,
194            acknowledged_at: None,
195        }
196    }
197
198    /// Add metadata to the alert
199    pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
200        self.metadata.insert(key.into(), value.into());
201        self
202    }
203
204    /// Set the node ID
205    pub fn with_node_id(mut self, node_id: u64) -> Self {
206        self.node_id = Some(node_id);
207        self
208    }
209
210    /// Acknowledge the alert
211    pub fn acknowledge(&mut self) {
212        self.acknowledged = true;
213        self.acknowledged_at = Some(Utc::now());
214    }
215
216    /// Format as a plain text message
217    pub fn to_text(&self) -> String {
218        let node_info = self
219            .node_id
220            .map(|id| format!(" [Node {}]", id))
221            .unwrap_or_default();
222
223        let mut text = format!(
224            "[{}]{} {}\n\n{}\n\nTimestamp: {}",
225            self.severity.as_str(),
226            node_info,
227            self.title,
228            self.message,
229            self.timestamp.format("%Y-%m-%d %H:%M:%S UTC")
230        );
231
232        if !self.metadata.is_empty() {
233            text.push_str("\n\nMetadata:\n");
234            for (key, value) in &self.metadata {
235                text.push_str(&format!("  {}: {}\n", key, value));
236            }
237        }
238
239        text
240    }
241}
242
243/// Email channel configuration
244#[derive(Debug, Clone, Serialize, Deserialize)]
245pub struct EmailChannelConfig {
246    /// SMTP server address
247    pub smtp_server: String,
248    /// SMTP port
249    pub smtp_port: u16,
250    /// Username for authentication
251    pub username: String,
252    /// Password for authentication
253    pub password: String,
254    /// From email address
255    pub from_address: String,
256    /// Recipient email addresses
257    pub to_addresses: Vec<String>,
258    /// Enable TLS
259    pub use_tls: bool,
260}
261
262/// Slack channel configuration
263#[derive(Debug, Clone, Serialize, Deserialize)]
264pub struct SlackChannelConfig {
265    /// Slack webhook URL
266    pub webhook_url: String,
267    /// Channel name (optional)
268    pub channel: Option<String>,
269    /// Username for the bot (optional)
270    pub username: Option<String>,
271    /// Icon emoji (optional)
272    pub icon_emoji: Option<String>,
273}
274
275/// Webhook channel configuration
276#[derive(Debug, Clone, Serialize, Deserialize)]
277pub struct WebhookChannelConfig {
278    /// Webhook URL
279    pub url: String,
280    /// HTTP method (GET, POST, PUT)
281    pub method: String,
282    /// Additional headers
283    pub headers: HashMap<String, String>,
284    /// Request timeout (milliseconds)
285    pub timeout_ms: u64,
286}
287
288/// Throttling configuration
289#[derive(Debug, Clone, Serialize, Deserialize)]
290pub struct ThrottlingConfig {
291    /// Enable throttling
292    pub enabled: bool,
293    /// Time window for throttling (seconds)
294    pub window_seconds: u64,
295    /// Maximum alerts per window
296    pub max_alerts_per_window: usize,
297    /// Cooldown period after reaching limit (seconds)
298    pub cooldown_seconds: u64,
299}
300
301impl Default for ThrottlingConfig {
302    fn default() -> Self {
303        Self {
304            enabled: true,
305            window_seconds: 60,
306            max_alerts_per_window: 10,
307            cooldown_seconds: 300,
308        }
309    }
310}
311
312/// Alerting configuration
313#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct AlertingConfig {
315    /// Enable alerting
316    pub enabled: bool,
317    /// Email channel configuration
318    pub email_channel: Option<EmailChannelConfig>,
319    /// Slack channel configuration
320    pub slack_channel: Option<SlackChannelConfig>,
321    /// Webhook channels
322    pub webhook_channels: Vec<WebhookChannelConfig>,
323    /// Minimum severity level for alerts
324    pub min_severity: AlertSeverity,
325    /// Throttling configuration
326    pub throttling: ThrottlingConfig,
327    /// Maximum alert history size
328    pub max_history_size: usize,
329    /// Enable anomaly detection
330    pub enable_anomaly_detection: bool,
331    /// Alert aggregation window (seconds)
332    pub aggregation_window_seconds: u64,
333}
334
335impl Default for AlertingConfig {
336    fn default() -> Self {
337        Self {
338            enabled: true,
339            email_channel: None,
340            slack_channel: None,
341            webhook_channels: Vec::new(),
342            min_severity: AlertSeverity::Warning,
343            throttling: ThrottlingConfig::default(),
344            max_history_size: 1000,
345            enable_anomaly_detection: true,
346            aggregation_window_seconds: 60,
347        }
348    }
349}
350
351impl AlertingConfig {
352    /// Add email channel
353    pub fn with_email_channel(
354        mut self,
355        smtp_server: impl Into<String>,
356        smtp_port: u16,
357        username: impl Into<String>,
358        password: impl Into<String>,
359        from: impl Into<String>,
360        to: Vec<String>,
361    ) -> Self {
362        self.email_channel = Some(EmailChannelConfig {
363            smtp_server: smtp_server.into(),
364            smtp_port,
365            username: username.into(),
366            password: password.into(),
367            from_address: from.into(),
368            to_addresses: to,
369            use_tls: true,
370        });
371        self
372    }
373
374    /// Add Slack channel
375    pub fn with_slack_channel(mut self, webhook_url: impl Into<String>) -> Self {
376        self.slack_channel = Some(SlackChannelConfig {
377            webhook_url: webhook_url.into(),
378            channel: None,
379            username: Some("OxiRS Cluster".to_string()),
380            icon_emoji: Some(":gear:".to_string()),
381        });
382        self
383    }
384
385    /// Add webhook channel
386    pub fn add_webhook(mut self, url: impl Into<String>) -> Self {
387        self.webhook_channels.push(WebhookChannelConfig {
388            url: url.into(),
389            method: "POST".to_string(),
390            headers: HashMap::new(),
391            timeout_ms: 5000,
392        });
393        self
394    }
395
396    /// Set minimum severity
397    pub fn with_min_severity(mut self, severity: AlertSeverity) -> Self {
398        self.min_severity = severity;
399        self
400    }
401}
402
403/// Alert history entry
404#[derive(Debug, Clone)]
405struct AlertHistoryEntry {
406    alert: Alert,
407    #[allow(dead_code)] // Reserved for future tracking
408    sent_at: DateTime<Utc>,
409}
410
411/// Alerting manager
412pub struct AlertingManager {
413    config: AlertingConfig,
414    email_transport: Arc<RwLock<Option<AsyncSmtpTransport<Tokio1Executor>>>>,
415    alert_history: Arc<RwLock<VecDeque<AlertHistoryEntry>>>,
416    throttle_state: Arc<RwLock<ThrottleState>>,
417    running: Arc<RwLock<bool>>,
418}
419
420#[derive(Debug)]
421struct ThrottleState {
422    alert_count: usize,
423    window_start: DateTime<Utc>,
424    in_cooldown: bool,
425    cooldown_start: Option<DateTime<Utc>>,
426}
427
428impl ThrottleState {
429    fn new() -> Self {
430        Self {
431            alert_count: 0,
432            window_start: Utc::now(),
433            in_cooldown: false,
434            cooldown_start: None,
435        }
436    }
437}
438
439impl AlertingManager {
440    /// Create a new alerting manager
441    pub async fn new(config: AlertingConfig) -> Result<Self> {
442        let email_transport = if let Some(email_config) = &config.email_channel {
443            let creds =
444                Credentials::new(email_config.username.clone(), email_config.password.clone());
445
446            let transport = if email_config.use_tls {
447                AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&email_config.smtp_server)
448            } else {
449                AsyncSmtpTransport::<Tokio1Executor>::relay(&email_config.smtp_server)
450            }
451            .map_err(|e| {
452                AlertingError::EmailError(format!("Failed to create SMTP transport: {e}"))
453            })?
454            .credentials(creds)
455            .port(email_config.smtp_port)
456            .build();
457
458            Arc::new(RwLock::new(Some(transport)))
459        } else {
460            Arc::new(RwLock::new(None))
461        };
462
463        // Slack alerts are delivered via a stateless reqwest webhook POST
464        // (see `send_slack_alert`), so there is no persistent client to build
465        // here. Delivery is gated on `config.slack_channel.is_some()`.
466
467        Ok(Self {
468            config,
469            email_transport,
470            alert_history: Arc::new(RwLock::new(VecDeque::new())),
471            throttle_state: Arc::new(RwLock::new(ThrottleState::new())),
472            running: Arc::new(RwLock::new(false)),
473        })
474    }
475
476    /// Start the alerting manager
477    pub async fn start(&mut self) -> Result<()> {
478        let mut running = self.running.write().await;
479        if *running {
480            return Ok(());
481        }
482
483        tracing::info!("Starting alerting manager");
484
485        *running = true;
486
487        // Start background cleanup task
488        self.start_background_tasks().await;
489
490        Ok(())
491    }
492
493    /// Stop the alerting manager
494    pub async fn stop(&mut self) -> Result<()> {
495        let mut running = self.running.write().await;
496        if !*running {
497            return Ok(());
498        }
499
500        tracing::info!("Stopping alerting manager");
501
502        *running = false;
503
504        Ok(())
505    }
506
507    /// Send an alert
508    pub async fn send_alert(
509        &self,
510        severity: AlertSeverity,
511        title: impl Into<String>,
512        message: impl Into<String>,
513    ) -> Result<()> {
514        if !self.config.enabled {
515            return Ok(());
516        }
517
518        // Check severity threshold
519        if severity < self.config.min_severity {
520            return Ok(());
521        }
522
523        // Check throttling
524        if !self.check_throttle().await {
525            tracing::warn!("Alert throttled due to rate limiting");
526            return Ok(());
527        }
528
529        let alert = Alert::new(
530            severity,
531            AlertCategory::Custom("general".to_string()),
532            title,
533            message,
534        );
535
536        self.send_alert_internal(alert).await
537    }
538
539    /// Send an alert with category
540    pub async fn send_categorized_alert(
541        &self,
542        severity: AlertSeverity,
543        category: AlertCategory,
544        title: impl Into<String>,
545        message: impl Into<String>,
546    ) -> Result<()> {
547        if !self.config.enabled {
548            return Ok(());
549        }
550
551        if severity < self.config.min_severity {
552            return Ok(());
553        }
554
555        if !self.check_throttle().await {
556            tracing::warn!("Alert throttled due to rate limiting");
557            return Ok(());
558        }
559
560        let alert = Alert::new(severity, category, title, message);
561
562        self.send_alert_internal(alert).await
563    }
564
565    /// Send a custom alert
566    pub async fn send_custom_alert(&self, alert: Alert) -> Result<()> {
567        if !self.config.enabled {
568            return Ok(());
569        }
570
571        if alert.severity < self.config.min_severity {
572            return Ok(());
573        }
574
575        if !self.check_throttle().await {
576            tracing::warn!("Alert throttled due to rate limiting");
577            return Ok(());
578        }
579
580        self.send_alert_internal(alert).await
581    }
582
583    /// Internal alert sending logic
584    async fn send_alert_internal(&self, alert: Alert) -> Result<()> {
585        tracing::info!(
586            severity = ?alert.severity,
587            category = ?alert.category,
588            title = %alert.title,
589            "Sending alert"
590        );
591
592        // Send to email channel
593        if self.config.email_channel.is_some() {
594            self.send_email_alert(&alert).await?;
595        }
596
597        // Send to Slack channel
598        if self.config.slack_channel.is_some() {
599            self.send_slack_alert(&alert).await?;
600        }
601
602        // Send to webhook channels
603        for webhook_config in &self.config.webhook_channels {
604            self.send_webhook_alert(&alert, webhook_config).await?;
605        }
606
607        // Add to history
608        self.add_to_history(alert).await;
609
610        Ok(())
611    }
612
613    /// Send alert via email
614    async fn send_email_alert(&self, alert: &Alert) -> Result<()> {
615        let transport = self.email_transport.read().await;
616        let Some(transport) = transport.as_ref() else {
617            return Ok(());
618        };
619
620        let email_config = self
621            .config
622            .email_channel
623            .as_ref()
624            .expect("email_channel config should be present when email transport exists");
625
626        for to_address in &email_config.to_addresses {
627            let email = Message::builder()
628                .from(
629                    email_config.from_address.parse().map_err(|e| {
630                        AlertingError::EmailError(format!("Invalid from address: {e}"))
631                    })?,
632                )
633                .to(to_address
634                    .parse()
635                    .map_err(|e| AlertingError::EmailError(format!("Invalid to address: {e}")))?)
636                .subject(format!("[{}] {}", alert.severity.as_str(), alert.title))
637                .header(ContentType::TEXT_PLAIN)
638                .body(alert.to_text())
639                .map_err(|e| AlertingError::EmailError(format!("Failed to build email: {e}")))?;
640
641            transport
642                .send(email)
643                .await
644                .map_err(|e| AlertingError::EmailError(format!("Failed to send email: {e}")))?;
645        }
646
647        Ok(())
648    }
649
650    /// Send alert via Slack.
651    ///
652    /// Posts the alert to the configured Slack incoming-webhook URL as a plain
653    /// JSON payload over the Pure Rust `reqwest` (rustls) stack. No third-party
654    /// Slack client is used (avoids `slack-hook2`, which pulls `native-tls`).
655    async fn send_slack_alert(&self, alert: &Alert) -> Result<()> {
656        let Some(slack_config) = self.config.slack_channel.as_ref() else {
657            return Ok(());
658        };
659
660        let text = format!(
661            "{} *{}*\n{}",
662            alert.severity.emoji(),
663            alert.title,
664            alert.message
665        );
666        let username = slack_config.username.as_deref().unwrap_or("OxiRS Cluster");
667
668        // Build the Slack incoming-webhook payload, including only the optional
669        // fields that are configured.
670        let mut body = serde_json::json!({
671            "text": text,
672            "username": username,
673        });
674        if let Some(channel) = &slack_config.channel {
675            body["channel"] = serde_json::Value::String(channel.clone());
676        }
677        if let Some(icon) = &slack_config.icon_emoji {
678            body["icon_emoji"] = serde_json::Value::String(icon.clone());
679        }
680
681        let response = reqwest::Client::new()
682            .post(&slack_config.webhook_url)
683            .json(&body)
684            .send()
685            .await
686            .map_err(|e| AlertingError::SlackError(format!("Failed to send Slack message: {e}")))?;
687
688        if let Err(e) = response.error_for_status() {
689            return Err(AlertingError::SlackError(format!(
690                "Slack webhook returned an error status: {e}"
691            )));
692        }
693
694        Ok(())
695    }
696
697    /// Send alert via webhook
698    async fn send_webhook_alert(&self, alert: &Alert, config: &WebhookChannelConfig) -> Result<()> {
699        let client = reqwest::Client::new();
700
701        let mut request = match config.method.to_uppercase().as_str() {
702            "GET" => client.get(&config.url),
703            "POST" => client.post(&config.url),
704            "PUT" => client.put(&config.url),
705            _ => {
706                return Err(AlertingError::WebhookError(format!(
707                    "Unsupported HTTP method: {}",
708                    config.method
709                )))
710            }
711        };
712
713        // Add headers
714        for (key, value) in &config.headers {
715            request = request.header(key, value);
716        }
717
718        // Add JSON body for POST/PUT
719        if config.method.to_uppercase() == "POST" || config.method.to_uppercase() == "PUT" {
720            request = request.json(alert);
721        }
722
723        request
724            .timeout(Duration::from_millis(config.timeout_ms))
725            .send()
726            .await
727            .map_err(|e| AlertingError::WebhookError(format!("Failed to send webhook: {e}")))?;
728
729        Ok(())
730    }
731
732    /// Check throttling
733    async fn check_throttle(&self) -> bool {
734        if !self.config.throttling.enabled {
735            return true;
736        }
737
738        let mut state = self.throttle_state.write().await;
739        let now = Utc::now();
740
741        // Check if in cooldown
742        if state.in_cooldown {
743            if let Some(cooldown_start) = state.cooldown_start {
744                let cooldown_duration =
745                    Duration::from_secs(self.config.throttling.cooldown_seconds);
746                if now
747                    .signed_duration_since(cooldown_start)
748                    .to_std()
749                    .unwrap_or_default()
750                    < cooldown_duration
751                {
752                    return false;
753                }
754                // Cooldown expired, reset state
755                state.in_cooldown = false;
756                state.cooldown_start = None;
757                state.alert_count = 0;
758                state.window_start = now;
759            }
760        }
761
762        // Check window
763        let window_duration = Duration::from_secs(self.config.throttling.window_seconds);
764        if now
765            .signed_duration_since(state.window_start)
766            .to_std()
767            .unwrap_or_default()
768            >= window_duration
769        {
770            // Reset window
771            state.alert_count = 0;
772            state.window_start = now;
773        }
774
775        // Check count
776        if state.alert_count >= self.config.throttling.max_alerts_per_window {
777            // Enter cooldown
778            state.in_cooldown = true;
779            state.cooldown_start = Some(now);
780            return false;
781        }
782
783        // Increment count
784        state.alert_count += 1;
785
786        true
787    }
788
789    /// Add alert to history
790    async fn add_to_history(&self, alert: Alert) {
791        let mut history = self.alert_history.write().await;
792
793        history.push_back(AlertHistoryEntry {
794            alert,
795            sent_at: Utc::now(),
796        });
797
798        // Trim history if too large
799        while history.len() > self.config.max_history_size {
800            history.pop_front();
801        }
802    }
803
804    /// Get alert history
805    pub async fn get_history(&self) -> Vec<Alert> {
806        let history = self.alert_history.read().await;
807        history.iter().map(|entry| entry.alert.clone()).collect()
808    }
809
810    /// Get alert statistics
811    pub async fn get_statistics(&self) -> AlertingStatistics {
812        let history = self.alert_history.read().await;
813
814        let total_alerts = history.len();
815        let mut by_severity = HashMap::new();
816        let mut by_category = HashMap::new();
817
818        for entry in history.iter() {
819            *by_severity.entry(entry.alert.severity).or_insert(0) += 1;
820            *by_category.entry(entry.alert.category.clone()).or_insert(0) += 1;
821        }
822
823        let throttle_state = self.throttle_state.read().await;
824
825        AlertingStatistics {
826            total_alerts,
827            alerts_by_severity: by_severity,
828            alerts_by_category: by_category,
829            is_throttled: throttle_state.in_cooldown,
830            current_window_count: throttle_state.alert_count,
831        }
832    }
833
834    /// Start background tasks
835    async fn start_background_tasks(&self) {
836        let running = Arc::clone(&self.running);
837        let alert_history = Arc::clone(&self.alert_history);
838        let max_size = self.config.max_history_size;
839
840        tokio::spawn(async move {
841            while *running.read().await {
842                // Cleanup old alerts
843                let mut history = alert_history.write().await;
844                while history.len() > max_size {
845                    history.pop_front();
846                }
847                drop(history);
848
849                tokio::time::sleep(Duration::from_secs(60)).await;
850            }
851        });
852    }
853}
854
855/// Alerting statistics
856#[derive(Debug, Clone, Serialize, Deserialize)]
857pub struct AlertingStatistics {
858    /// Total number of alerts sent
859    pub total_alerts: usize,
860    /// Alerts by severity
861    pub alerts_by_severity: HashMap<AlertSeverity, usize>,
862    /// Alerts by category
863    pub alerts_by_category: HashMap<AlertCategory, usize>,
864    /// Whether throttling is active
865    pub is_throttled: bool,
866    /// Current alert count in window
867    pub current_window_count: usize,
868}
869
870#[cfg(test)]
871mod tests {
872    use super::*;
873
874    #[test]
875    fn test_alert_severity_ordering() {
876        assert!(AlertSeverity::Info < AlertSeverity::Warning);
877        assert!(AlertSeverity::Warning < AlertSeverity::Error);
878        assert!(AlertSeverity::Error < AlertSeverity::Critical);
879    }
880
881    #[test]
882    fn test_alert_creation() {
883        let alert = Alert::new(
884            AlertSeverity::Warning,
885            AlertCategory::NodeHealth,
886            "Test Alert",
887            "Test message",
888        );
889
890        assert_eq!(alert.severity, AlertSeverity::Warning);
891        assert_eq!(alert.category, AlertCategory::NodeHealth);
892        assert_eq!(alert.title, "Test Alert");
893        assert_eq!(alert.message, "Test message");
894        assert!(!alert.acknowledged);
895    }
896
897    #[test]
898    fn test_alert_metadata() {
899        let alert = Alert::new(
900            AlertSeverity::Error,
901            AlertCategory::Performance,
902            "Performance Issue",
903            "High latency detected",
904        )
905        .with_metadata("latency_ms", "500")
906        .with_node_id(42);
907
908        assert_eq!(alert.metadata.get("latency_ms"), Some(&"500".to_string()));
909        assert_eq!(alert.node_id, Some(42));
910    }
911
912    #[tokio::test]
913    async fn test_alerting_config_builder() {
914        let config = AlertingConfig::default()
915            .with_min_severity(AlertSeverity::Error)
916            .with_slack_channel("https://hooks.slack.com/test");
917
918        assert_eq!(config.min_severity, AlertSeverity::Error);
919        assert!(config.slack_channel.is_some());
920    }
921
922    #[tokio::test]
923    async fn test_alerting_manager_creation() {
924        let config = AlertingConfig::default();
925        let manager = AlertingManager::new(config).await;
926        assert!(manager.is_ok());
927    }
928}