use super::{Alert, AlertSeverity};
use crate::error::Result;
use parking_lot::RwLock;
use std::sync::Arc;
#[derive(Clone)]
pub struct AlertRule {
pub name: String,
pub condition: Arc<dyn Fn() -> bool + Send + Sync>,
pub severity: AlertSeverity,
pub message: String,
}
pub struct AlertRuleEngine {
rules: Arc<RwLock<Vec<AlertRule>>>,
}
impl AlertRuleEngine {
pub fn new() -> Self {
Self {
rules: Arc::new(RwLock::new(Vec::new())),
}
}
pub fn add_rule(&mut self, rule: AlertRule) {
self.rules.write().push(rule);
}
pub async fn evaluate(&self) -> Result<Vec<Alert>> {
let rules = self.rules.read();
let mut alerts = Vec::new();
for rule in rules.iter() {
if (rule.condition)() {
let alert = Alert::new(rule.name.clone(), rule.severity, rule.message.clone());
alerts.push(alert);
}
}
Ok(alerts)
}
}
impl Default for AlertRuleEngine {
fn default() -> Self {
Self::new()
}
}