Skip to main content

allsource_core/application/services/
pipeline.rs

1use crate::{
2    domain::entities::{Event, event::value_heap_bytes},
3    error::{AllSourceError, Result},
4    infrastructure::{
5        memory::ledger::{MapCharge, Owner, Tally},
6        observability::{
7            heap::{hash_entry_bytes, json_heap_bytes},
8            metrics::MetricsRegistry,
9        },
10    },
11};
12use chrono::{DateTime, Duration, Utc};
13use dashmap::DashMap;
14use parking_lot::RwLock;
15use serde::{Deserialize, Serialize};
16use serde_json::Value as JsonValue;
17use std::{
18    collections::{HashMap, VecDeque},
19    mem::size_of,
20    sync::Arc,
21};
22use uuid::Uuid;
23
24/// Window type for time-based aggregations
25#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
26#[serde(rename_all = "lowercase")]
27pub enum WindowType {
28    /// Tumbling window (non-overlapping)
29    Tumbling,
30    /// Sliding window (overlapping)
31    Sliding,
32    /// Session window (activity-based)
33    Session,
34}
35
36/// Window configuration
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct WindowConfig {
39    /// Type of window
40    pub window_type: WindowType,
41
42    /// Window size in seconds
43    pub size_seconds: i64,
44
45    /// Slide interval in seconds (for sliding windows)
46    pub slide_seconds: Option<i64>,
47
48    /// Session timeout in seconds (for session windows)
49    pub session_timeout_seconds: Option<i64>,
50}
51
52/// Pipeline operator types
53#[derive(Debug, Clone, Serialize, Deserialize)]
54#[serde(tag = "type", rename_all = "lowercase")]
55pub enum PipelineOperator {
56    /// Filter events based on a condition
57    Filter {
58        /// Field path to check (e.g., "payload.status")
59        field: String,
60        /// Expected value
61        value: JsonValue,
62        /// Operator: eq, ne, gt, lt, contains
63        op: String,
64    },
65
66    /// Transform event payload
67    Map {
68        /// Field to transform
69        field: String,
70        /// Transformation expression (simple for now)
71        transform: String,
72    },
73
74    /// Aggregate events
75    Reduce {
76        /// Field to aggregate
77        field: String,
78        /// Aggregation function: sum, count, avg, min, max
79        function: String,
80        /// Group by field (optional)
81        group_by: Option<String>,
82    },
83
84    /// Window-based aggregation
85    Window {
86        /// Window configuration
87        config: WindowConfig,
88        /// Aggregation to apply within window
89        aggregation: Box<PipelineOperator>,
90    },
91
92    /// Enrich event with external data
93    Enrich {
94        /// Source to enrich from
95        source: String,
96        /// Fields to add
97        fields: Vec<String>,
98    },
99
100    /// Split stream based on condition
101    Branch {
102        /// Condition field
103        field: String,
104        /// Branch mapping
105        branches: HashMap<String, String>,
106    },
107}
108
109/// Pipeline configuration
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct PipelineConfig {
112    /// Pipeline ID
113    pub id: Uuid,
114
115    /// Pipeline name
116    pub name: String,
117
118    /// Description
119    pub description: Option<String>,
120
121    /// Source event types to process
122    pub source_event_types: Vec<String>,
123
124    /// Pipeline operators in order
125    pub operators: Vec<PipelineOperator>,
126
127    /// Whether pipeline is enabled
128    pub enabled: bool,
129
130    /// Output destination (projection name or topic)
131    pub output: String,
132}
133
134/// Pipeline execution statistics
135#[derive(Debug, Clone, Serialize, Deserialize)]
136pub struct PipelineStats {
137    pub pipeline_id: Uuid,
138    pub events_processed: u64,
139    pub events_filtered: u64,
140    pub events_failed: u64,
141    pub last_processed: Option<DateTime<Utc>>,
142}
143
144/// Stateful operator for maintaining state across events
145pub struct StatefulOperator {
146    /// Operator state storage
147    state: Arc<RwLock<HashMap<String, JsonValue>>>,
148    state_charge: Tally,
149
150    /// Window buffers for time-based operations
151    windows: Arc<RwLock<HashMap<String, VecDeque<(DateTime<Utc>, Event)>>>>,
152    windows_charge: Tally,
153}
154
155/// Heap one state entry holds: its table slot, its key, and the value's owned heap.
156fn state_entry_bytes(key_len: usize, value: &JsonValue) -> u64 {
157    (hash_entry_bytes::<String, JsonValue>() + key_len + json_heap_bytes(value)) as u64
158}
159
160impl StatefulOperator {
161    pub fn new() -> Self {
162        Self {
163            state: Arc::new(RwLock::new(HashMap::new())),
164            state_charge: Tally::new(Owner::PipelineState),
165            windows: Arc::new(RwLock::new(HashMap::new())),
166            windows_charge: Tally::new(Owner::PipelineWindows),
167        }
168    }
169
170    /// Store state value
171    pub fn set_state(&self, key: String, value: JsonValue) {
172        let key_len = key.len();
173        let added = state_entry_bytes(key_len, &value);
174        // Every charge and release of state and windows happens under that map's
175        // write guard; otherwise a concurrent replace or clear releases bytes
176        // before they are added, and the clamped sub loses them.
177        let mut state = self.state.write();
178        self.state_charge.add(added);
179        if let Some(old) = state.insert(key, value) {
180            self.state_charge.sub(state_entry_bytes(key_len, &old));
181        }
182    }
183
184    /// Get state value
185    pub fn get_state(&self, key: &str) -> Option<JsonValue> {
186        self.state.read().get(key).cloned()
187    }
188
189    /// Add event to window
190    pub fn add_to_window(&self, window_key: &str, event: Event, timestamp: DateTime<Utc>) {
191        let bytes = event.resident_bytes();
192        let mut windows = self.windows.write();
193        self.windows_charge.add(bytes);
194        windows
195            .entry(window_key.to_string())
196            .or_default()
197            .push_back((timestamp, event));
198    }
199
200    /// Get events in window
201    pub fn get_window(&self, window_key: &str) -> Vec<Event> {
202        self.windows
203            .read()
204            .get(window_key)
205            .map(|w| w.iter().map(|(_, e)| e.clone()).collect())
206            .unwrap_or_default()
207    }
208
209    /// Evict expired events from window
210    pub fn evict_window(&self, window_key: &str, cutoff: DateTime<Utc>) {
211        if let Some(window) = self.windows.write().get_mut(window_key) {
212            let released: u64 = window
213                .iter()
214                .filter(|(ts, _)| *ts <= cutoff)
215                .map(|(_, event)| event.resident_bytes())
216                .sum();
217            window.retain(|(ts, _)| *ts > cutoff);
218            self.windows_charge.sub(released);
219        }
220    }
221
222    /// Clear all state
223    pub fn clear(&self) {
224        let mut state = self.state.write();
225        state.clear();
226        self.state_charge.take();
227        drop(state);
228        let mut windows = self.windows.write();
229        windows.clear();
230        self.windows_charge.take();
231    }
232}
233
234impl Default for StatefulOperator {
235    fn default() -> Self {
236        Self::new()
237    }
238}
239
240/// Pipeline execution engine
241pub struct Pipeline {
242    config: PipelineConfig,
243    state: StatefulOperator,
244    stats: Arc<RwLock<PipelineStats>>,
245}
246
247impl Pipeline {
248    pub fn new(config: PipelineConfig) -> Self {
249        let stats = PipelineStats {
250            pipeline_id: config.id,
251            events_processed: 0,
252            events_filtered: 0,
253            events_failed: 0,
254            last_processed: None,
255        };
256
257        Self {
258            config,
259            state: StatefulOperator::new(),
260            stats: Arc::new(RwLock::new(stats)),
261        }
262    }
263
264    /// Process an event through the pipeline
265    pub fn process(&self, event: &Event) -> Result<Option<JsonValue>> {
266        // Check if event type matches source filter
267        if !self.config.source_event_types.is_empty()
268            && !self
269                .config
270                .source_event_types
271                .iter()
272                .any(|t| t == event.event_type_str())
273        {
274            return Ok(None);
275        }
276
277        if !self.config.enabled {
278            return Ok(None);
279        }
280
281        let mut current_value = event.payload.clone();
282        let mut filtered = false;
283
284        // Apply operators in sequence
285        for operator in &self.config.operators {
286            match self.apply_operator(operator, &current_value, event) {
287                Ok(Some(result)) => {
288                    current_value = result;
289                }
290                Ok(None) => {
291                    // Event was filtered out
292                    filtered = true;
293                    self.stats.write().events_filtered += 1;
294                    break;
295                }
296                Err(e) => {
297                    self.stats.write().events_failed += 1;
298                    tracing::error!("Pipeline {} operator failed: {}", self.config.name, e);
299                    return Err(e);
300                }
301            }
302        }
303
304        // Update stats
305        let mut stats = self.stats.write();
306        stats.events_processed += 1;
307        stats.last_processed = Some(Utc::now());
308
309        if filtered {
310            Ok(None)
311        } else {
312            Ok(Some(current_value))
313        }
314    }
315
316    /// Apply a single operator
317    fn apply_operator(
318        &self,
319        operator: &PipelineOperator,
320        value: &JsonValue,
321        event: &Event,
322    ) -> Result<Option<JsonValue>> {
323        match operator {
324            PipelineOperator::Filter {
325                field,
326                value: expected,
327                op,
328            } => self.apply_filter(field, expected, op, value),
329
330            PipelineOperator::Map { field, transform } => self.apply_map(field, transform, value),
331
332            PipelineOperator::Reduce {
333                field,
334                function,
335                group_by,
336            } => self.apply_reduce(field, function, group_by.as_deref(), value, event),
337
338            PipelineOperator::Window {
339                config,
340                aggregation,
341            } => self.apply_window(config, aggregation, event),
342
343            PipelineOperator::Enrich { source, fields } => self.apply_enrich(source, fields, value),
344
345            PipelineOperator::Branch { field, branches } => {
346                self.apply_branch(field, branches, value)
347            }
348        }
349    }
350
351    /// Apply filter operator
352    fn apply_filter(
353        &self,
354        field: &str,
355        expected: &JsonValue,
356        op: &str,
357        value: &JsonValue,
358    ) -> Result<Option<JsonValue>> {
359        let field_value = self.get_field(value, field);
360
361        let matches = match op {
362            "eq" => field_value == Some(expected),
363            "ne" => field_value != Some(expected),
364            "gt" => {
365                if let (Some(JsonValue::Number(a)), JsonValue::Number(b)) =
366                    (field_value.as_ref(), expected)
367                {
368                    a.as_f64().unwrap_or(0.0) > b.as_f64().unwrap_or(0.0)
369                } else {
370                    false
371                }
372            }
373            "lt" => {
374                if let (Some(JsonValue::Number(a)), JsonValue::Number(b)) =
375                    (field_value.as_ref(), expected)
376                {
377                    a.as_f64().unwrap_or(0.0) < b.as_f64().unwrap_or(0.0)
378                } else {
379                    false
380                }
381            }
382            "contains" => {
383                if let (Some(JsonValue::String(a)), JsonValue::String(b)) =
384                    (field_value.as_ref(), expected)
385                {
386                    a.contains(b)
387                } else {
388                    false
389                }
390            }
391            _ => {
392                return Err(AllSourceError::ValidationError(format!(
393                    "Unknown filter operator: {op}"
394                )));
395            }
396        };
397
398        if matches {
399            Ok(Some(value.clone()))
400        } else {
401            Ok(None) // Filtered out
402        }
403    }
404
405    /// Apply map transformation
406    fn apply_map(
407        &self,
408        field: &str,
409        transform: &str,
410        value: &JsonValue,
411    ) -> Result<Option<JsonValue>> {
412        let mut result = value.clone();
413
414        // Simple transformations
415        let field_value = self.get_field(value, field);
416
417        let transformed = match transform {
418            "uppercase" => field_value
419                .and_then(|v| v.as_str())
420                .map(|s| JsonValue::String(s.to_uppercase())),
421            "lowercase" => field_value
422                .and_then(|v| v.as_str())
423                .map(|s| JsonValue::String(s.to_lowercase())),
424            "trim" => field_value
425                .and_then(|v| v.as_str())
426                .map(|s| JsonValue::String(s.trim().to_string())),
427            _ => {
428                // Try to parse as number operation
429                if let Some(stripped) = transform.strip_prefix("multiply:") {
430                    if let Ok(multiplier) = stripped.parse::<f64>() {
431                        field_value.and_then(serde_json::Value::as_f64).map(|n| {
432                            JsonValue::Number(serde_json::Number::from_f64(n * multiplier).unwrap())
433                        })
434                    } else {
435                        None
436                    }
437                } else if let Some(stripped) = transform.strip_prefix("add:") {
438                    if let Ok(addend) = stripped.parse::<f64>() {
439                        field_value.and_then(serde_json::Value::as_f64).map(|n| {
440                            JsonValue::Number(serde_json::Number::from_f64(n + addend).unwrap())
441                        })
442                    } else {
443                        None
444                    }
445                } else {
446                    None
447                }
448            }
449        };
450
451        if let Some(new_value) = transformed {
452            self.set_field(&mut result, field, new_value);
453        }
454
455        Ok(Some(result))
456    }
457
458    /// Apply reduce aggregation
459    fn apply_reduce(
460        &self,
461        field: &str,
462        function: &str,
463        group_by: Option<&str>,
464        value: &JsonValue,
465        event: &Event,
466    ) -> Result<Option<JsonValue>> {
467        // Get group key
468        let group_key = if let Some(group_field) = group_by {
469            self.get_field(value, group_field)
470                .and_then(|v| v.as_str())
471                .unwrap_or("default")
472                .to_string()
473        } else {
474            "default".to_string()
475        };
476
477        let state_key = format!("reduce_{function}_{group_key}");
478
479        // Get current aggregate value
480        let current = self.state.get_state(&state_key);
481
482        // Get field value to aggregate
483        let field_value = self.get_field(value, field);
484
485        let new_value = match function {
486            "count" => {
487                let count = current.and_then(|v| v.as_u64()).unwrap_or(0) + 1;
488                JsonValue::Number(count.into())
489            }
490            "sum" => {
491                let current_sum = current.and_then(|v| v.as_f64()).unwrap_or(0.0);
492                let value_to_add = field_value
493                    .and_then(serde_json::Value::as_f64)
494                    .unwrap_or(0.0);
495                JsonValue::Number(serde_json::Number::from_f64(current_sum + value_to_add).unwrap())
496            }
497            "avg" => {
498                // Store sum and count separately
499                let sum_key = format!("{state_key}_sum");
500                let count_key = format!("{state_key}_count");
501
502                let current_sum = self
503                    .state
504                    .get_state(&sum_key)
505                    .and_then(|v| v.as_f64())
506                    .unwrap_or(0.0);
507                let current_count = self
508                    .state
509                    .get_state(&count_key)
510                    .and_then(|v| v.as_u64())
511                    .unwrap_or(0);
512
513                let value_to_add = field_value
514                    .and_then(serde_json::Value::as_f64)
515                    .unwrap_or(0.0);
516
517                let new_sum = current_sum + value_to_add;
518                let new_count = current_count + 1;
519
520                self.state.set_state(
521                    sum_key,
522                    JsonValue::Number(serde_json::Number::from_f64(new_sum).unwrap()),
523                );
524                self.state
525                    .set_state(count_key, JsonValue::Number(new_count.into()));
526
527                let avg = new_sum / new_count as f64;
528                JsonValue::Number(serde_json::Number::from_f64(avg).unwrap())
529            }
530            "min" => {
531                let current_min = current.and_then(|v| v.as_f64());
532                let new_val = field_value.and_then(serde_json::Value::as_f64);
533
534                match (current_min, new_val) {
535                    (Some(curr), Some(new)) => {
536                        JsonValue::Number(serde_json::Number::from_f64(curr.min(new)).unwrap())
537                    }
538                    (None, Some(new)) => {
539                        JsonValue::Number(serde_json::Number::from_f64(new).unwrap())
540                    }
541                    (Some(curr), None) => {
542                        JsonValue::Number(serde_json::Number::from_f64(curr).unwrap())
543                    }
544                    (None, None) => JsonValue::Null,
545                }
546            }
547            "max" => {
548                let current_max = current.and_then(|v| v.as_f64());
549                let new_val = field_value.and_then(serde_json::Value::as_f64);
550
551                match (current_max, new_val) {
552                    (Some(curr), Some(new)) => {
553                        JsonValue::Number(serde_json::Number::from_f64(curr.max(new)).unwrap())
554                    }
555                    (None, Some(new)) => {
556                        JsonValue::Number(serde_json::Number::from_f64(new).unwrap())
557                    }
558                    (Some(curr), None) => {
559                        JsonValue::Number(serde_json::Number::from_f64(curr).unwrap())
560                    }
561                    (None, None) => JsonValue::Null,
562                }
563            }
564            _ => {
565                return Err(AllSourceError::ValidationError(format!(
566                    "Unknown reduce function: {function}"
567                )));
568            }
569        };
570
571        // Update state
572        self.state.set_state(state_key.clone(), new_value.clone());
573
574        // Return aggregated result
575        let result = serde_json::json!({
576            "group": group_key,
577            "function": function,
578            "value": new_value
579        });
580
581        Ok(Some(result))
582    }
583
584    /// Apply window aggregation
585    fn apply_window(
586        &self,
587        config: &WindowConfig,
588        aggregation: &PipelineOperator,
589        event: &Event,
590    ) -> Result<Option<JsonValue>> {
591        let window_key = format!("window_{}", self.config.id);
592        let now = Utc::now();
593
594        // Add event to window
595        self.state
596            .add_to_window(&window_key, event.clone(), event.timestamp);
597
598        // Evict expired events based on window type
599        let cutoff = match config.window_type {
600            WindowType::Tumbling => now - Duration::seconds(config.size_seconds),
601            WindowType::Sliding => {
602                let slide = config.slide_seconds.unwrap_or(config.size_seconds);
603                now - Duration::seconds(slide)
604            }
605            WindowType::Session => {
606                let timeout = config.session_timeout_seconds.unwrap_or(300);
607                now - Duration::seconds(timeout)
608            }
609        };
610
611        self.state.evict_window(&window_key, cutoff);
612
613        // Get events in current window
614        let window_events = self.state.get_window(&window_key);
615
616        // Apply aggregation to window
617        let mut aggregate_value = JsonValue::Null;
618        for window_event in &window_events {
619            if let Ok(Some(result)) =
620                self.apply_operator(aggregation, &window_event.payload, window_event)
621            {
622                aggregate_value = result;
623            }
624        }
625
626        Ok(Some(serde_json::json!({
627            "window_type": config.window_type,
628            "window_size_seconds": config.size_seconds,
629            "events_in_window": window_events.len(),
630            "aggregation": aggregate_value
631        })))
632    }
633
634    /// Apply enrichment
635    fn apply_enrich(
636        &self,
637        _source: &str,
638        fields: &[String],
639        value: &JsonValue,
640    ) -> Result<Option<JsonValue>> {
641        // Placeholder for enrichment logic
642        // In production, this would fetch data from external sources
643        let mut result = value.clone();
644
645        for field in fields {
646            let enriched_value = JsonValue::String(format!("enriched_{field}"));
647            self.set_field(&mut result, field, enriched_value);
648        }
649
650        Ok(Some(result))
651    }
652
653    /// Apply branch routing
654    fn apply_branch(
655        &self,
656        field: &str,
657        branches: &HashMap<String, String>,
658        value: &JsonValue,
659    ) -> Result<Option<JsonValue>> {
660        let field_value = self.get_field(value, field);
661
662        if let Some(JsonValue::String(val)) = field_value
663            && let Some(route) = branches.get(val)
664        {
665            let mut result = value.clone();
666            if let JsonValue::Object(ref mut obj) = result {
667                obj.insert("_route".to_string(), JsonValue::String(route.clone()));
668            }
669            return Ok(Some(result));
670        }
671
672        Ok(Some(value.clone()))
673    }
674
675    /// Helper: Get nested field from JSON
676    fn get_field<'a>(&self, value: &'a JsonValue, field: &str) -> Option<&'a JsonValue> {
677        let parts: Vec<&str> = field.split('.').collect();
678        let mut current = value;
679
680        for part in parts {
681            current = current.get(part)?;
682        }
683
684        Some(current)
685    }
686
687    /// Helper: Set nested field in JSON
688    fn set_field(&self, value: &mut JsonValue, field: &str, new_value: JsonValue) {
689        let parts: Vec<&str> = field.split('.').collect();
690
691        if parts.len() == 1 {
692            if let JsonValue::Object(obj) = value {
693                obj.insert(field.to_string(), new_value);
694            }
695            return;
696        }
697
698        // Navigate to parent
699        let mut current = value;
700        for part in &parts[..parts.len() - 1] {
701            if let JsonValue::Object(obj) = current {
702                current = obj
703                    .entry((*part).to_string())
704                    .or_insert(JsonValue::Object(Default::default()));
705            }
706        }
707
708        // Set final value
709        if let JsonValue::Object(obj) = current {
710            obj.insert((*parts.last().unwrap()).to_string(), new_value);
711        }
712    }
713
714    /// Get pipeline statistics
715    pub fn stats(&self) -> PipelineStats {
716        self.stats.read().clone()
717    }
718
719    /// Get pipeline configuration
720    pub fn config(&self) -> &PipelineConfig {
721        &self.config
722    }
723
724    /// Reset pipeline state
725    pub fn reset(&self) {
726        self.state.clear();
727        let mut stats = self.stats.write();
728        stats.events_processed = 0;
729        stats.events_filtered = 0;
730        stats.events_failed = 0;
731        stats.last_processed = None;
732    }
733}
734
735/// Manages multiple pipelines
736pub struct PipelineManager {
737    // Using DashMap for lock-free concurrent access
738    pipelines: Arc<DashMap<Uuid, Arc<Pipeline>>>,
739    pipelines_charge: MapCharge,
740    metrics: Arc<MetricsRegistry>,
741}
742
743/// Owned heap of a pipeline's configuration, measured on its JSON form.
744fn config_heap(config: &PipelineConfig) -> u64 {
745    serde_json::to_value(config).map_or(0, |value| value_heap_bytes(&value) as u64)
746}
747
748impl PipelineManager {
749    pub fn new() -> Self {
750        Self::with_metrics(MetricsRegistry::new())
751    }
752
753    pub fn with_metrics(metrics: Arc<MetricsRegistry>) -> Self {
754        Self {
755            pipelines: Arc::new(DashMap::new()),
756            pipelines_charge: MapCharge::new(Owner::Misc, size_of::<(Uuid, Arc<Pipeline>)>()),
757            metrics,
758        }
759    }
760
761    /// Register a new pipeline
762    pub fn register(&self, config: PipelineConfig) -> Uuid {
763        let id = config.id;
764        let name = config.name.clone();
765        let pipeline = Arc::new(Pipeline::new(config));
766        self.pipelines_charge
767            .insert(&self.pipelines, id, pipeline, |_, p| config_heap(&p.config));
768
769        let count = self.pipelines.len();
770        self.metrics.pipelines_registered_total.set(count as i64);
771
772        tracing::info!("📊 Registered pipeline: {} ({})", name, id);
773        id
774    }
775
776    /// Get a pipeline by ID
777    pub fn get(&self, id: Uuid) -> Option<Arc<Pipeline>> {
778        self.pipelines.get(&id).map(|entry| entry.value().clone())
779    }
780
781    /// Process event through all matching pipelines
782    pub fn process_event(&self, event: &Event) -> Vec<(Uuid, JsonValue)> {
783        let timer = self.metrics.pipeline_duration_seconds.start_timer();
784
785        let mut results = Vec::new();
786
787        for entry in self.pipelines.iter() {
788            let id = entry.key();
789            let pipeline = entry.value();
790            let pipeline_name = &pipeline.config().name;
791            let pipeline_id = id.to_string();
792
793            match pipeline.process(event) {
794                Ok(Some(result)) => {
795                    self.metrics
796                        .pipeline_events_processed
797                        .with_label_values(&[&pipeline_id, pipeline_name])
798                        .inc();
799                    results.push((*id, result));
800                }
801                Ok(None) => {
802                    // Event filtered out or didn't match - not an error
803                }
804                Err(e) => {
805                    self.metrics
806                        .pipeline_errors_total
807                        .with_label_values(&[pipeline_name])
808                        .inc();
809                    tracing::error!(
810                        "Pipeline '{}' ({}) failed to process event: {}",
811                        pipeline_name,
812                        id,
813                        e
814                    );
815                }
816            }
817        }
818
819        timer.observe_duration();
820        results
821    }
822
823    /// List all pipelines
824    pub fn list(&self) -> Vec<PipelineConfig> {
825        self.pipelines
826            .iter()
827            .map(|entry| entry.value().config().clone())
828            .collect()
829    }
830
831    /// Remove a pipeline
832    pub fn remove(&self, id: Uuid) -> bool {
833        let removed = self
834            .pipelines_charge
835            .remove_entry(&self.pipelines, &id, |_, p| config_heap(&p.config))
836            .is_some();
837
838        if removed {
839            let count = self.pipelines.len();
840            self.metrics.pipelines_registered_total.set(count as i64);
841        }
842
843        removed
844    }
845
846    /// Get statistics for all pipelines
847    pub fn all_stats(&self) -> Vec<PipelineStats> {
848        self.pipelines
849            .iter()
850            .map(|entry| entry.value().stats())
851            .collect()
852    }
853}
854
855impl Default for PipelineManager {
856    fn default() -> Self {
857        Self::new()
858    }
859}
860
861#[cfg(test)]
862mod tests {
863    use super::*;
864    use serde_json::json;
865
866    #[test]
867    fn test_filter_operator() {
868        let config = PipelineConfig {
869            id: Uuid::new_v4(),
870            name: "test_filter".to_string(),
871            description: None,
872            source_event_types: vec!["test".to_string()],
873            operators: vec![PipelineOperator::Filter {
874                field: "status".to_string(),
875                value: json!("active"),
876                op: "eq".to_string(),
877            }],
878            enabled: true,
879            output: "test_output".to_string(),
880        };
881
882        let pipeline = Pipeline::new(config);
883        let event = Event::from_strings(
884            "test".to_string(),
885            "entity1".to_string(),
886            "default".to_string(),
887            json!({"status": "active"}),
888            None,
889        )
890        .unwrap();
891
892        let result = pipeline.process(&event).unwrap();
893        assert!(result.is_some());
894    }
895
896    #[test]
897    fn test_map_operator() {
898        let config = PipelineConfig {
899            id: Uuid::new_v4(),
900            name: "test_map".to_string(),
901            description: None,
902            source_event_types: vec!["test".to_string()],
903            operators: vec![PipelineOperator::Map {
904                field: "name".to_string(),
905                transform: "uppercase".to_string(),
906            }],
907            enabled: true,
908            output: "test_output".to_string(),
909        };
910
911        let pipeline = Pipeline::new(config);
912        let event = Event::from_strings(
913            "test".to_string(),
914            "entity1".to_string(),
915            "default".to_string(),
916            json!({"name": "hello"}),
917            None,
918        )
919        .unwrap();
920
921        let result = pipeline.process(&event).unwrap().unwrap();
922        assert_eq!(result["name"], "HELLO");
923    }
924
925    #[test]
926    fn test_reduce_count() {
927        let config = PipelineConfig {
928            id: Uuid::new_v4(),
929            name: "test_reduce".to_string(),
930            description: None,
931            source_event_types: vec!["test".to_string()],
932            operators: vec![PipelineOperator::Reduce {
933                field: "value".to_string(),
934                function: "count".to_string(),
935                group_by: None,
936            }],
937            enabled: true,
938            output: "test_output".to_string(),
939        };
940
941        let pipeline = Pipeline::new(config);
942
943        for i in 0..5 {
944            let event = Event::from_strings(
945                "test".to_string(),
946                "entity1".to_string(),
947                "default".to_string(),
948                json!({"value": i}),
949                None,
950            )
951            .unwrap();
952            pipeline.process(&event).unwrap();
953        }
954
955        let result = pipeline
956            .process(
957                &Event::from_strings(
958                    "test".to_string(),
959                    "entity1".to_string(),
960                    "default".to_string(),
961                    json!({"value": 5}),
962                    None,
963                )
964                .unwrap(),
965            )
966            .unwrap()
967            .unwrap();
968
969        assert_eq!(result["value"], 6);
970    }
971}