Skip to main content

saluki_components/transforms/metric_router/
mod.rs

1use std::{collections::HashSet, sync::LazyLock};
2
3use async_trait::async_trait;
4use saluki_core::accounting::{MemoryBounds, MemoryBoundsBuilder};
5use saluki_core::{
6    components::{
7        transforms::{Transform, TransformBuilder, TransformContext},
8        BuildContext,
9    },
10    data_model::event::{metric::Metric, Event, EventType},
11    topology::{EventsBuffer, OutputDefinition},
12};
13use saluki_error::{generic_error, GenericError};
14use serde::Deserialize;
15use tokio::select;
16use tracing::{debug, error};
17
18/// Metric router transform configuration.
19#[derive(Deserialize, Clone)]
20pub struct MetricRouterConfiguration {
21    /// List of metric names to match against.
22    pub metric_names: Vec<String>,
23}
24
25/// Routes incoming events based on exact metric name matching to one of two
26/// named outputs: "matched" for metrics with names that exactly match the
27/// configured list, and "unmatched" for all other events. This transform
28/// demonstrates the use of named outputs without a default output.
29#[derive(Debug)]
30pub struct MetricRouter {
31    metric_names: HashSet<String>,
32}
33
34impl MetricRouter {
35    fn new(config: MetricRouterConfiguration) -> Result<Self, GenericError> {
36        for name in &config.metric_names {
37            if name.trim().is_empty() {
38                return Err(generic_error!("Metric names cannot be empty or whitespace-only"));
39            }
40        }
41
42        Ok(Self {
43            metric_names: config.metric_names.into_iter().collect(),
44        })
45    }
46
47    /// Evaluates whether the metric should be routed to the matched output.
48    ///
49    /// Returns true if the metric name exactly matches one of the configured metric names, false otherwise.
50    fn should_route_to_matched(&self, metric: &Metric) -> bool {
51        self.metric_names.contains(metric.context().name().as_ref())
52    }
53
54    /// Processes a batch of events by routing them to matched or unmatched outputs.
55    async fn process_event_batch(
56        &self, mut events: EventsBuffer, context: &mut TransformContext,
57    ) -> Result<(), GenericError> {
58        // Extract matched metrics from the buffer, leaving unmatched metrics and all non-metric events behind
59        let matched_events = events
60            .extract_events::<Metric, _>(|metric| self.should_route_to_matched(metric))
61            .map(Event::Metric);
62
63        let matched_count = context
64            .dispatcher()
65            .buffered_named("matched")?
66            .send_all(matched_events)
67            .await?;
68
69        let unmatched_count = context
70            .dispatcher()
71            .buffered_named("unmatched")?
72            .send_all(events)
73            .await?;
74
75        debug!(
76            matched_events = matched_count,
77            unmatched_events = unmatched_count,
78            "Successfully processed event batch."
79        );
80
81        Ok(())
82    }
83}
84
85#[async_trait]
86impl TransformBuilder for MetricRouterConfiguration {
87    async fn build(&self, _context: BuildContext) -> Result<Box<dyn Transform + Send>, GenericError> {
88        Ok(Box::new(MetricRouter::new(self.clone())?))
89    }
90
91    fn input_event_type(&self) -> EventType {
92        EventType::all_bits()
93    }
94
95    fn outputs(&self) -> &[OutputDefinition<EventType>] {
96        static OUTPUTS: LazyLock<Vec<OutputDefinition<EventType>>> = LazyLock::new(|| {
97            vec![
98                OutputDefinition::named_output("matched", EventType::all_bits()),
99                OutputDefinition::named_output("unmatched", EventType::all_bits()),
100            ]
101        });
102        &OUTPUTS
103    }
104}
105
106impl MemoryBounds for MetricRouterConfiguration {
107    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
108        builder
109            .minimum()
110            // Account for the MetricRouter struct itself when heap-allocated
111            .with_single_value::<MetricRouter>("component struct")
112            // Account for the HashSet<String> that stores metric names
113            // HashSet has overhead beyond just the strings themselves
114            .with_fixed_amount(
115                "hashset overhead",
116                std::mem::size_of::<std::collections::HashSet<String>>(),
117            )
118            // Account for the String allocations for each metric name
119            // This approximates the heap usage of the strings themselves
120            .with_fixed_amount(
121                "metric names strings",
122                self.metric_names
123                    .iter()
124                    .map(|name| name.len() + std::mem::size_of::<String>())
125                    .sum::<usize>(),
126            )
127            // Account for HashSet bucket overhead (rough approximation)
128            // HashSet typically allocates more buckets than items for good performance
129            .with_fixed_amount(
130                "hashset buckets",
131                self.metric_names.len() * std::mem::size_of::<Option<String>>() * 2, // Rough 2x bucket overhead
132            );
133    }
134}
135
136#[async_trait]
137impl Transform for MetricRouter {
138    async fn run(self: Box<Self>, mut context: TransformContext) -> Result<(), GenericError> {
139        let mut health = context.take_health_handle();
140
141        health.mark_ready();
142        debug!(
143            metric_names = ?self.metric_names,
144            "Metric Router transform started."
145        );
146
147        loop {
148            select! {
149                _ = health.live() => continue,
150                maybe_events = context.events().next() => match maybe_events {
151                    Some(events) => {
152                        // Process the batch of events with proper error handling
153                        if let Err(e) = self.process_event_batch(events, &mut context).await {
154                            error!(error = %e, "Failed to process event batch.");
155                            // Continue processing subsequent batches even if one fails
156                        }
157                    }
158                    None => {
159                        debug!("Event stream terminated, shutting down metric router transform");
160                        break;
161                    }
162                }
163            }
164        }
165
166        debug!("Metric Router transform stopped.");
167        Ok(())
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn exact_metric_name_matching() {
177        let router = MetricRouter::new(MetricRouterConfiguration {
178            metric_names: vec!["test.counter".to_string(), "another.metric".to_string()],
179        })
180        .expect("Should create router successfully");
181
182        // Test metric event with matching name
183        let matching_metric = Metric::counter("test.counter", 1.0);
184        assert!(router.should_route_to_matched(&matching_metric));
185
186        // Test metric event with another matching name
187        let another_matching_metric = Metric::counter("another.metric", 5.0);
188        assert!(router.should_route_to_matched(&another_matching_metric));
189
190        // Test metric event with non-matching name
191        let non_matching_metric = Metric::counter("different.metric", 1.0);
192        assert!(!router.should_route_to_matched(&non_matching_metric));
193
194        // Test partial match (should fail - we want exact matching)
195        let partial_match_metric = Metric::counter("test.counter.extra", 1.0);
196        assert!(!router.should_route_to_matched(&partial_match_metric));
197    }
198
199    #[test]
200    fn empty_metric_names_list() {
201        let router = MetricRouter::new(MetricRouterConfiguration { metric_names: vec![] })
202            .expect("Should create router successfully");
203
204        // No metrics should be routed to matched when the list is empty
205        let metric_event = Metric::counter("any.metric", 1.0);
206        assert!(!router.should_route_to_matched(&metric_event));
207    }
208
209    #[test]
210    fn test_input_validation() {
211        // Test empty string validation
212        let result = MetricRouter::new(MetricRouterConfiguration {
213            metric_names: vec!["valid.metric".to_string(), "".to_string()],
214        });
215        assert!(result.is_err());
216        if let Err(error) = result {
217            assert!(error.to_string().contains("empty"));
218        }
219
220        // Test whitespace-only string validation
221        let result = MetricRouter::new(MetricRouterConfiguration {
222            metric_names: vec!["valid.metric".to_string(), "   ".to_string()],
223        });
224        assert!(result.is_err());
225        if let Err(error) = result {
226            assert!(error.to_string().contains("empty"));
227        }
228
229        // Test valid configuration
230        let result = MetricRouter::new(MetricRouterConfiguration {
231            metric_names: vec!["valid.metric".to_string(), "another.valid".to_string()],
232        });
233        assert!(result.is_ok());
234    }
235}