Skip to main content

pipeflow/common/
types.rs

1//! Common types shared across pipeline components
2//!
3//! This module contains data structures used by multiple modules (sources, sinks, engine)
4//! to avoid circular dependencies.
5
6use std::collections::HashMap;
7
8use serde::{Deserialize, Serialize};
9
10// ============================================================================
11// Severity - unified severity level for events and notifications
12// ============================================================================
13
14/// Severity level for events and notifications
15#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
16#[serde(rename_all = "lowercase")]
17pub enum Severity {
18    /// Debug level
19    Debug,
20    /// Informational level
21    #[default]
22    Info,
23    /// Warning level
24    Warning,
25    /// Error level
26    Error,
27    /// Critical level requiring immediate attention
28    Critical,
29}
30
31// ============================================================================
32// Event data structure
33// ============================================================================
34
35/// System event data
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct Event {
38    /// Event name/type
39    pub name: String,
40    /// Event severity level
41    #[serde(default)]
42    pub severity: Severity,
43    /// Event payload
44    pub payload: serde_json::Value,
45    /// Event labels/tags
46    #[serde(default)]
47    pub labels: HashMap<String, String>,
48    /// Timestamp in milliseconds
49    pub timestamp: i64,
50}
51
52impl Event {
53    /// Create a new event with default Info severity
54    pub fn new(name: impl Into<String>, payload: serde_json::Value) -> Self {
55        Self {
56            name: name.into(),
57            severity: Severity::Info,
58            payload,
59            labels: HashMap::new(),
60            timestamp: chrono::Utc::now().timestamp_millis(),
61        }
62    }
63
64    /// Set the event severity
65    pub fn with_severity(mut self, severity: Severity) -> Self {
66        self.severity = severity;
67        self
68    }
69
70    /// Add a label to the event
71    pub fn with_label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
72        self.labels.insert(key.into(), value.into());
73        self
74    }
75}
76
77// ============================================================================
78// Audit data structure
79// ============================================================================
80
81/// Audit record status
82#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
83#[serde(rename_all = "lowercase")]
84pub enum AuditStatus {
85    /// Operation completed successfully
86    Success,
87    /// Operation failed
88    Failure,
89}
90
91/// Audit record for tracking pipeline operations
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct Audit {
94    /// Node ID that performed the operation
95    pub node_id: String,
96    /// Node type ("source", "transform", "sink")
97    pub node_type: String,
98    /// Operation type ("emit", "process", "write")
99    pub operation: String,
100    /// Operation status
101    pub status: AuditStatus,
102    /// Associated message ID (if applicable)
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub message_id: Option<String>,
105    /// Operation duration in milliseconds
106    pub duration_ms: u64,
107    /// Error message (if status is Failure)
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub error: Option<String>,
110    /// Additional labels/tags
111    #[serde(default)]
112    pub labels: HashMap<String, String>,
113    /// Timestamp in milliseconds
114    pub timestamp: i64,
115}
116
117impl Audit {
118    /// Create a new audit record
119    pub fn new(
120        node_id: impl Into<String>,
121        node_type: impl Into<String>,
122        operation: impl Into<String>,
123    ) -> Self {
124        Self {
125            node_id: node_id.into(),
126            node_type: node_type.into(),
127            operation: operation.into(),
128            status: AuditStatus::Success,
129            message_id: None,
130            duration_ms: 0,
131            error: None,
132            labels: HashMap::new(),
133            timestamp: chrono::Utc::now().timestamp_millis(),
134        }
135    }
136
137    /// Mark as successful with duration
138    pub fn success(mut self, duration_ms: u64) -> Self {
139        self.status = AuditStatus::Success;
140        self.duration_ms = duration_ms;
141        self
142    }
143
144    /// Mark as failed with duration and error message
145    pub fn failure(mut self, duration_ms: u64, error: impl Into<String>) -> Self {
146        self.status = AuditStatus::Failure;
147        self.duration_ms = duration_ms;
148        self.error = Some(error.into());
149        self
150    }
151
152    /// Set the associated message ID
153    pub fn with_message_id(mut self, id: impl Into<String>) -> Self {
154        self.message_id = Some(id.into());
155        self
156    }
157
158    /// Add a label to the audit record
159    pub fn with_label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
160        self.labels.insert(key.into(), value.into());
161        self
162    }
163}
164
165// ============================================================================
166// Notify data structure (used by sink::notify for message parsing)
167// ============================================================================
168
169/// Notification message structure for sink::notify
170///
171/// This structure is used by the notify sink to parse incoming messages
172/// and extract notification details.
173#[derive(Debug, Clone, Serialize, Deserialize)]
174pub struct Notify {
175    /// Notification name/type
176    pub name: String,
177    /// Notification severity
178    pub severity: Severity,
179    /// Notification message
180    pub message: String,
181    /// Notification labels/tags
182    #[serde(default)]
183    pub labels: HashMap<String, String>,
184    /// Timestamp in milliseconds
185    pub timestamp: i64,
186}
187
188impl Notify {
189    /// Create a new notification
190    pub fn new(name: impl Into<String>, severity: Severity, message: impl Into<String>) -> Self {
191        Self {
192            name: name.into(),
193            severity,
194            message: message.into(),
195            labels: HashMap::new(),
196            timestamp: chrono::Utc::now().timestamp_millis(),
197        }
198    }
199
200    /// Add a label to the notification
201    pub fn with_label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
202        self.labels.insert(key.into(), value.into());
203        self
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210
211    #[test]
212    fn test_severity_serde() {
213        let json = serde_json::to_string(&Severity::Critical).unwrap();
214        assert_eq!(json, "\"critical\"");
215
216        let severity: Severity = serde_json::from_str("\"warning\"").unwrap();
217        assert_eq!(severity, Severity::Warning);
218
219        let debug: Severity = serde_json::from_str("\"debug\"").unwrap();
220        assert_eq!(debug, Severity::Debug);
221    }
222
223    #[test]
224    fn test_severity_default() {
225        assert_eq!(Severity::default(), Severity::Info);
226    }
227
228    #[test]
229    fn test_event_new() {
230        let event = Event::new("test_event", serde_json::json!({"value": 42}));
231
232        assert_eq!(event.name, "test_event");
233        assert_eq!(event.severity, Severity::Info);
234        assert_eq!(event.payload["value"], 42);
235        assert!(event.labels.is_empty());
236        assert!(event.timestamp > 0);
237    }
238
239    #[test]
240    fn test_event_with_severity() {
241        let event = Event::new("alert", serde_json::json!({})).with_severity(Severity::Critical);
242
243        assert_eq!(event.severity, Severity::Critical);
244    }
245
246    #[test]
247    fn test_event_with_label() {
248        let event = Event::new("evt", serde_json::json!({}))
249            .with_label("key1", "val1")
250            .with_label("key2", "val2");
251
252        assert_eq!(event.labels.get("key1"), Some(&"val1".to_string()));
253        assert_eq!(event.labels.get("key2"), Some(&"val2".to_string()));
254    }
255
256    #[test]
257    fn test_event_serialization() {
258        let event = Event::new("test", serde_json::json!({"x": 1}))
259            .with_severity(Severity::Warning)
260            .with_label("env", "prod");
261
262        let json = serde_json::to_string(&event).unwrap();
263        let parsed: Event = serde_json::from_str(&json).unwrap();
264
265        assert_eq!(parsed.name, "test");
266        assert_eq!(parsed.severity, Severity::Warning);
267        assert_eq!(parsed.labels.get("env"), Some(&"prod".to_string()));
268    }
269
270    #[test]
271    fn test_audit_new() {
272        let audit = Audit::new("my_sink", "sink", "write");
273
274        assert_eq!(audit.node_id, "my_sink");
275        assert_eq!(audit.node_type, "sink");
276        assert_eq!(audit.operation, "write");
277        assert_eq!(audit.status, AuditStatus::Success);
278        assert!(audit.message_id.is_none());
279        assert_eq!(audit.duration_ms, 0);
280        assert!(audit.error.is_none());
281        assert!(audit.timestamp > 0);
282    }
283
284    #[test]
285    fn test_audit_success() {
286        let audit = Audit::new("transform_1", "transform", "process").success(150);
287
288        assert_eq!(audit.status, AuditStatus::Success);
289        assert_eq!(audit.duration_ms, 150);
290        assert!(audit.error.is_none());
291    }
292
293    #[test]
294    fn test_audit_failure() {
295        let audit = Audit::new("sink_db", "sink", "write").failure(50, "Connection timeout");
296
297        assert_eq!(audit.status, AuditStatus::Failure);
298        assert_eq!(audit.duration_ms, 50);
299        assert_eq!(audit.error, Some("Connection timeout".to_string()));
300    }
301
302    #[test]
303    fn test_audit_with_message_id() {
304        let audit = Audit::new("source_1", "source", "emit")
305            .with_message_id("msg-123")
306            .success(10);
307
308        assert_eq!(audit.message_id, Some("msg-123".to_string()));
309    }
310
311    #[test]
312    fn test_audit_serialization() {
313        let audit = Audit::new("test_sink", "sink", "write")
314            .with_message_id("msg-456")
315            .with_label("batch", "1")
316            .success(100);
317
318        let json = serde_json::to_string(&audit).unwrap();
319        let parsed: Audit = serde_json::from_str(&json).unwrap();
320
321        assert_eq!(parsed.node_id, "test_sink");
322        assert_eq!(parsed.status, AuditStatus::Success);
323        assert_eq!(parsed.message_id, Some("msg-456".to_string()));
324        assert_eq!(parsed.labels.get("batch"), Some(&"1".to_string()));
325    }
326
327    #[test]
328    fn test_audit_status_serde() {
329        let json = serde_json::to_string(&AuditStatus::Success).unwrap();
330        assert_eq!(json, "\"success\"");
331
332        let status: AuditStatus = serde_json::from_str("\"failure\"").unwrap();
333        assert_eq!(status, AuditStatus::Failure);
334    }
335
336    #[test]
337    fn test_notify_new() {
338        let notify = Notify::new("alert", Severity::Warning, "Test message");
339
340        assert_eq!(notify.name, "alert");
341        assert_eq!(notify.severity, Severity::Warning);
342        assert_eq!(notify.message, "Test message");
343        assert!(notify.labels.is_empty());
344        assert!(notify.timestamp > 0);
345    }
346
347    #[test]
348    fn test_notify_with_label() {
349        let notify = Notify::new("alert", Severity::Error, "Error occurred")
350            .with_label("service", "api")
351            .with_label("env", "prod");
352
353        assert_eq!(notify.labels.get("service"), Some(&"api".to_string()));
354        assert_eq!(notify.labels.get("env"), Some(&"prod".to_string()));
355    }
356
357    #[test]
358    fn test_notify_serialization() {
359        let notify = Notify::new("test_notify", Severity::Critical, "Critical alert")
360            .with_label("region", "us-east");
361
362        let json = serde_json::to_string(&notify).unwrap();
363        let parsed: Notify = serde_json::from_str(&json).unwrap();
364
365        assert_eq!(parsed.name, "test_notify");
366        assert_eq!(parsed.severity, Severity::Critical);
367        assert_eq!(parsed.message, "Critical alert");
368        assert_eq!(parsed.labels.get("region"), Some(&"us-east".to_string()));
369    }
370}