use serde::{Deserialize, Serialize};
use torvyn_types::{ComponentId, FlowId, Severity, StreamId, TraceContext};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DiagnosticEvent {
pub timestamp_ns: u64,
pub severity: Severity,
pub category: EventCategory,
pub flow_id: Option<FlowId>,
pub component_id: Option<ComponentId>,
pub trace_context: Option<TraceContext>,
pub payload: EventPayload,
pub is_critical: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum EventCategory {
Lifecycle,
Performance,
Error,
Security,
Resource,
}
impl std::fmt::Display for EventCategory {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Lifecycle => write!(f, "lifecycle"),
Self::Performance => write!(f, "performance"),
Self::Error => write!(f, "error"),
Self::Security => write!(f, "security"),
Self::Resource => write!(f, "resource"),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "event_type")]
pub enum EventPayload {
FlowCreated {
topology: Vec<ComponentId>,
config_hash: u64,
},
FlowStarted {
component_count: u32,
},
FlowDraining {
reason: String,
},
FlowCompleted {
duration_ns: u64,
elements_total: u64,
},
FlowCancelled {
reason: String,
duration_ns: u64,
},
FlowFailed {
error: String,
failing_component: Option<ComponentId>,
},
ComponentInstantiated {
wit_interface: String,
memory_limit: u64,
},
ComponentLinked {
imports_satisfied: u32,
exports_provided: u32,
},
ComponentTerminated {
reason: String,
invocation_count: u64,
},
BackpressureActivated {
stream_id: StreamId,
producer: ComponentId,
consumer: ComponentId,
queue_depth: u32,
},
BackpressureDeactivated {
stream_id: StreamId,
duration_ns: u64,
},
ComponentSlow {
processing_time_ns: u64,
threshold_ns: u64,
},
SchedulerStarvation {
starved_component: ComponentId,
duration_ns: u64,
},
FlowLatencySpike {
element_sequence: u64,
latency_ns: u64,
threshold_ns: u64,
},
ComponentError {
error_variant: String,
error_message: String,
},
ComponentTrap {
trap_type: String,
trap_message: String,
},
ComponentTimeout {
timeout_ns: u64,
processing_time_ns: u64,
},
ComponentFuelExhausted {
fuel_limit: u64,
},
FlowErrorBudgetExceeded {
error_count: u64,
error_budget: u64,
},
CapabilityDenied {
capability: String,
context: String,
},
CapabilityExercised {
capability: String,
},
SignatureVerified {
signer: String,
algorithm: String,
},
SignatureFailed {
reason: String,
},
ResourceAllocated {
resource_id_raw: u64,
pool_id: u32,
size_bytes: u64,
},
ResourceCopied {
resource_id_raw: u64,
from: ComponentId,
to: ComponentId,
copy_bytes: u64,
reason: String,
},
ResourceTransferred {
resource_id_raw: u64,
from: String,
to: String,
transfer_type: String,
},
ResourceFreed {
resource_id_raw: u64,
pool_id: u32,
},
PoolExhausted {
pool_id: u32,
requested_size: u64,
pool_capacity: u32,
},
ResourceLeakSuspected {
resource_id_raw: u64,
owner: String,
age_ns: u64,
},
}
impl DiagnosticEvent {
pub fn new(severity: Severity, category: EventCategory, payload: EventPayload) -> Self {
Self {
timestamp_ns: current_time_ns(),
severity,
category,
flow_id: None,
component_id: None,
trace_context: None,
payload,
is_critical: false,
}
}
pub fn with_flow(mut self, flow_id: FlowId) -> Self {
self.flow_id = Some(flow_id);
self
}
pub fn with_component(mut self, component_id: ComponentId) -> Self {
self.component_id = Some(component_id);
self
}
pub fn with_trace(mut self, ctx: TraceContext) -> Self {
self.trace_context = Some(ctx);
self
}
pub fn critical(mut self) -> Self {
self.is_critical = true;
self
}
pub fn event_name(&self) -> &'static str {
match &self.payload {
EventPayload::FlowCreated { .. } => "flow.created",
EventPayload::FlowStarted { .. } => "flow.started",
EventPayload::FlowDraining { .. } => "flow.draining",
EventPayload::FlowCompleted { .. } => "flow.completed",
EventPayload::FlowCancelled { .. } => "flow.cancelled",
EventPayload::FlowFailed { .. } => "flow.failed",
EventPayload::ComponentInstantiated { .. } => "component.instantiated",
EventPayload::ComponentLinked { .. } => "component.linked",
EventPayload::ComponentTerminated { .. } => "component.terminated",
EventPayload::BackpressureActivated { .. } => "backpressure.activated",
EventPayload::BackpressureDeactivated { .. } => "backpressure.deactivated",
EventPayload::ComponentSlow { .. } => "component.slow",
EventPayload::SchedulerStarvation { .. } => "scheduler.starvation",
EventPayload::FlowLatencySpike { .. } => "flow.latency_spike",
EventPayload::ComponentError { .. } => "component.error",
EventPayload::ComponentTrap { .. } => "component.trap",
EventPayload::ComponentTimeout { .. } => "component.timeout",
EventPayload::ComponentFuelExhausted { .. } => "component.fuel_exhausted",
EventPayload::FlowErrorBudgetExceeded { .. } => "flow.error_budget_exceeded",
EventPayload::CapabilityDenied { .. } => "capability.denied",
EventPayload::CapabilityExercised { .. } => "capability.exercised",
EventPayload::SignatureVerified { .. } => "component.signature_verified",
EventPayload::SignatureFailed { .. } => "component.signature_failed",
EventPayload::ResourceAllocated { .. } => "resource.allocated",
EventPayload::ResourceCopied { .. } => "resource.copied",
EventPayload::ResourceTransferred { .. } => "resource.transferred",
EventPayload::ResourceFreed { .. } => "resource.freed",
EventPayload::PoolExhausted { .. } => "pool.exhausted",
EventPayload::ResourceLeakSuspected { .. } => "resource.leak_suspected",
}
}
}
#[inline]
pub fn current_time_ns() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos() as u64
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_diagnostic_event_new() {
let event = DiagnosticEvent::new(
Severity::Info,
EventCategory::Lifecycle,
EventPayload::FlowStarted { component_count: 3 },
);
assert_eq!(event.severity, Severity::Info);
assert_eq!(event.category, EventCategory::Lifecycle);
assert!(event.timestamp_ns > 0);
assert!(!event.is_critical);
}
#[test]
fn test_diagnostic_event_builder() {
let event = DiagnosticEvent::new(
Severity::Error,
EventCategory::Error,
EventPayload::ComponentTrap {
trap_type: "OOM".into(),
trap_message: "out of memory".into(),
},
)
.with_flow(FlowId::new(1))
.with_component(ComponentId::new(2))
.critical();
assert_eq!(event.flow_id, Some(FlowId::new(1)));
assert_eq!(event.component_id, Some(ComponentId::new(2)));
assert!(event.is_critical);
}
#[test]
fn test_event_name() {
let event = DiagnosticEvent::new(
Severity::Warn,
EventCategory::Performance,
EventPayload::BackpressureActivated {
stream_id: StreamId::new(1),
producer: ComponentId::new(1),
consumer: ComponentId::new(2),
queue_depth: 64,
},
);
assert_eq!(event.event_name(), "backpressure.activated");
}
#[test]
fn test_event_category_display() {
assert_eq!(format!("{}", EventCategory::Lifecycle), "lifecycle");
assert_eq!(format!("{}", EventCategory::Security), "security");
}
#[test]
fn test_event_serde_roundtrip() {
let event = DiagnosticEvent::new(
Severity::Info,
EventCategory::Resource,
EventPayload::ResourceAllocated {
resource_id_raw: 42,
pool_id: 0,
size_bytes: 4096,
},
);
let json = serde_json::to_string(&event).unwrap();
let parsed: DiagnosticEvent = serde_json::from_str(&json).unwrap();
assert_eq!(parsed.event_name(), "resource.allocated");
}
#[test]
fn test_current_time_ns_positive() {
let ts = current_time_ns();
assert!(ts > 0);
}
}