1use 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#[derive(Debug, Error)]
53pub enum AlertingError {
54 #[error("Configuration error: {0}")]
56 ConfigError(String),
57
58 #[error("Alert channel error: {0}")]
60 ChannelError(String),
61
62 #[error("Failed to send email: {0}")]
64 EmailError(String),
65
66 #[error("Failed to send Slack message: {0}")]
68 SlackError(String),
69
70 #[error("Webhook error: {0}")]
72 WebhookError(String),
73
74 #[error("Template error: {0}")]
76 TemplateError(String),
77
78 #[error("Alerting error: {0}")]
80 Other(String),
81}
82
83pub type Result<T> = std::result::Result<T, AlertingError>;
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
87pub enum AlertSeverity {
88 Info,
90 Warning,
92 Error,
94 Critical,
96}
97
98impl AlertSeverity {
99 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 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 pub fn color(&self) -> &'static str {
121 match self {
122 Self::Info => "#36a64f", Self::Warning => "#ff9900", Self::Error => "#ff0000", Self::Critical => "#8b0000", }
127 }
128}
129
130#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
132pub enum AlertCategory {
133 NodeHealth,
135 Consensus,
137 Replication,
139 Performance,
141 Security,
143 Storage,
145 Network,
147 Custom(String),
149}
150
151#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct Alert {
154 pub id: String,
156 pub severity: AlertSeverity,
158 pub category: AlertCategory,
160 pub title: String,
162 pub message: String,
164 pub metadata: HashMap<String, String>,
166 pub timestamp: DateTime<Utc>,
168 pub node_id: Option<u64>,
170 pub acknowledged: bool,
172 pub acknowledged_at: Option<DateTime<Utc>>,
174}
175
176impl Alert {
177 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 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 pub fn with_node_id(mut self, node_id: u64) -> Self {
206 self.node_id = Some(node_id);
207 self
208 }
209
210 pub fn acknowledge(&mut self) {
212 self.acknowledged = true;
213 self.acknowledged_at = Some(Utc::now());
214 }
215
216 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#[derive(Debug, Clone, Serialize, Deserialize)]
245pub struct EmailChannelConfig {
246 pub smtp_server: String,
248 pub smtp_port: u16,
250 pub username: String,
252 pub password: String,
254 pub from_address: String,
256 pub to_addresses: Vec<String>,
258 pub use_tls: bool,
260}
261
262#[derive(Debug, Clone, Serialize, Deserialize)]
264pub struct SlackChannelConfig {
265 pub webhook_url: String,
267 pub channel: Option<String>,
269 pub username: Option<String>,
271 pub icon_emoji: Option<String>,
273}
274
275#[derive(Debug, Clone, Serialize, Deserialize)]
277pub struct WebhookChannelConfig {
278 pub url: String,
280 pub method: String,
282 pub headers: HashMap<String, String>,
284 pub timeout_ms: u64,
286}
287
288#[derive(Debug, Clone, Serialize, Deserialize)]
290pub struct ThrottlingConfig {
291 pub enabled: bool,
293 pub window_seconds: u64,
295 pub max_alerts_per_window: usize,
297 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#[derive(Debug, Clone, Serialize, Deserialize)]
314pub struct AlertingConfig {
315 pub enabled: bool,
317 pub email_channel: Option<EmailChannelConfig>,
319 pub slack_channel: Option<SlackChannelConfig>,
321 pub webhook_channels: Vec<WebhookChannelConfig>,
323 pub min_severity: AlertSeverity,
325 pub throttling: ThrottlingConfig,
327 pub max_history_size: usize,
329 pub enable_anomaly_detection: bool,
331 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 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 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 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 pub fn with_min_severity(mut self, severity: AlertSeverity) -> Self {
398 self.min_severity = severity;
399 self
400 }
401}
402
403#[derive(Debug, Clone)]
405struct AlertHistoryEntry {
406 alert: Alert,
407 #[allow(dead_code)] sent_at: DateTime<Utc>,
409}
410
411pub 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 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 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 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 self.start_background_tasks().await;
489
490 Ok(())
491 }
492
493 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 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 if severity < self.config.min_severity {
520 return Ok(());
521 }
522
523 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 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 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 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 if self.config.email_channel.is_some() {
594 self.send_email_alert(&alert).await?;
595 }
596
597 if self.config.slack_channel.is_some() {
599 self.send_slack_alert(&alert).await?;
600 }
601
602 for webhook_config in &self.config.webhook_channels {
604 self.send_webhook_alert(&alert, webhook_config).await?;
605 }
606
607 self.add_to_history(alert).await;
609
610 Ok(())
611 }
612
613 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 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 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 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 for (key, value) in &config.headers {
715 request = request.header(key, value);
716 }
717
718 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 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 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 state.in_cooldown = false;
756 state.cooldown_start = None;
757 state.alert_count = 0;
758 state.window_start = now;
759 }
760 }
761
762 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 state.alert_count = 0;
772 state.window_start = now;
773 }
774
775 if state.alert_count >= self.config.throttling.max_alerts_per_window {
777 state.in_cooldown = true;
779 state.cooldown_start = Some(now);
780 return false;
781 }
782
783 state.alert_count += 1;
785
786 true
787 }
788
789 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 while history.len() > self.config.max_history_size {
800 history.pop_front();
801 }
802 }
803
804 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 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 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
857pub struct AlertingStatistics {
858 pub total_alerts: usize,
860 pub alerts_by_severity: HashMap<AlertSeverity, usize>,
862 pub alerts_by_category: HashMap<AlertCategory, usize>,
864 pub is_throttled: bool,
866 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}