use serde::{Deserialize, Serialize};
use std::fmt;
use std::time::SystemTime;
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum EventType {
ServerFault,
NetworkAttack,
ServiceException,
ResourceWarning,
SecurityVulnerability,
Custom(String),
}
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum EventPriority {
Low,
Medium,
High,
Emergency,
}
impl fmt::Display for EventPriority {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
EventPriority::Low => write!(f, "Low"),
EventPriority::Medium => write!(f, "Medium"),
EventPriority::High => write!(f, "High"),
EventPriority::Emergency => write!(f, "Emergency"),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum ImpactScope {
Component(String),
Instance(String),
MultipleInstances(Vec<String>),
Service(String),
MultipleServices(Vec<String>),
System,
Custom(String),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
pub id: String,
pub event_type: EventType,
pub priority: EventPriority,
pub scope: ImpactScope,
pub source: String,
pub description: String,
pub timestamp: SystemTime,
pub data: serde_json::Value,
pub status: EventStatus,
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum EventStatus {
New,
Processing,
Resolved,
Ignored,
ManualInterventionNeeded,
}
impl Event {
pub fn new(
event_type: EventType,
priority: EventPriority,
scope: ImpactScope,
source: String,
description: String,
data: serde_json::Value,
) -> Self {
Self {
id: uuid::Uuid::now_v7().to_string(),
event_type,
priority,
scope,
source,
description,
timestamp: SystemTime::now(),
data,
status: EventStatus::New,
}
}
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string(self)
}
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(json)
}
pub fn update_status(&mut self, new_status: EventStatus) {
self.status = new_status;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_event_creation() {
let event = Event::new(
EventType::ServerFault,
EventPriority::Emergency,
ImpactScope::System,
"monitoring-system".to_string(),
"Database server crash detected".to_string(),
serde_json::json!({ "server": "db-01", "reason": "OOM" }),
);
assert_eq!(event.event_type, EventType::ServerFault);
assert_eq!(event.priority, EventPriority::Emergency);
assert_eq!(event.status, EventStatus::New);
assert!(!event.id.is_empty());
}
#[test]
fn test_event_serialization() {
let event = Event::new(
EventType::NetworkAttack,
EventPriority::High,
ImpactScope::Service("api-gateway".to_string()),
"ids-system".to_string(),
"DDoS attack detected".to_string(),
serde_json::json!({ "source_ip": "192.168.1.100", "traffic": "10Gbps" }),
);
let json = event.to_json().unwrap();
let deserialized = Event::from_json(&json).unwrap();
assert_eq!(deserialized.event_type, EventType::NetworkAttack);
assert_eq!(deserialized.priority, EventPriority::High);
}
}