Skip to main content

saluki_core/observability/metrics/
aggregated.rs

1//! Aggregated metrics state.
2//!
3//! Builds on the [`reflector`][super::reflector] machinery to maintain a long-lived view of every
4//! internal metric, keyed by metric context. Counters are summed, gauges keep the latest value by
5//! timestamp, and histograms accumulate into fixed-bucket [`AggregatedHistogram`]s.
6
7use std::{
8    iter::Once,
9    pin::Pin,
10    sync::{Arc, OnceLock},
11};
12
13use futures::{stream::StreamExt as _, Stream};
14use papaya::HashMap;
15use saluki_error::{generic_error, GenericError};
16
17use super::histogram::AggregatedHistogram;
18use super::reflector::{Processor, Reflector, ReflectorWorker};
19use super::{MetricsSnapshot, MetricsStream};
20use crate::data_model::event::metric::{context::Context, MetricValues};
21
22/// Aggregated metric value.
23#[derive(Clone, Debug)]
24pub enum AggregatedMetricValue {
25    /// A counter.
26    Counter(f64),
27
28    /// A gauge.
29    Gauge(f64),
30
31    /// A histogram with fixed buckets.
32    Histogram(AggregatedHistogram),
33}
34
35impl AggregatedMetricValue {
36    /// Returns the scalar value of the metric, if this is a counter or gauge.
37    ///
38    /// Returns `0.0` for histograms.
39    pub fn value(&self) -> f64 {
40        match self {
41            AggregatedMetricValue::Counter(value) => *value,
42            AggregatedMetricValue::Gauge(value) => *value,
43            AggregatedMetricValue::Histogram(_) => 0.0,
44        }
45    }
46
47    /// Merges two aggregated metric values.
48    ///
49    /// Counters are summed, gauges use last-write-wins (the incoming value is kept), histograms are merged per-bucket and
50    /// by sum/count.
51    pub fn merge(&mut self, incoming: &AggregatedMetricValue) {
52        match (self, incoming) {
53            (Self::Counter(a), Self::Counter(b)) => {
54                *a += *b;
55            }
56            (Self::Histogram(a), Self::Histogram(b)) => {
57                a.merge(b);
58            }
59            (Self::Gauge(a), Self::Gauge(b)) => *a = *b,
60            // When the existing and incoming type _don't_ match, take the incoming value.
61            (existing, incoming) => *existing = incoming.clone(),
62        }
63    }
64
65    /// Merges `incoming` into this value like [`merge`][Self::merge], except that gauges are summed.
66    pub fn merge_summing_gauges(&mut self, incoming: &AggregatedMetricValue) {
67        match (&mut *self, incoming) {
68            (Self::Gauge(a), Self::Gauge(b)) => *a += *b,
69            _ => self.merge(incoming),
70        }
71    }
72}
73
74#[derive(Clone)]
75pub(crate) struct AggregatedMetric {
76    pub(crate) timestamp: Option<u64>,
77    pub(crate) value: AggregatedMetricValue,
78}
79
80impl AggregatedMetric {
81    fn counter(value: f64) -> Self {
82        Self {
83            timestamp: None,
84            value: AggregatedMetricValue::Counter(value),
85        }
86    }
87
88    fn gauge(timestamp: u64, value: f64) -> Self {
89        Self {
90            timestamp: Some(timestamp),
91            value: AggregatedMetricValue::Gauge(value),
92        }
93    }
94
95    fn histogram(histogram: AggregatedHistogram) -> Self {
96        Self {
97            timestamp: None,
98            value: AggregatedMetricValue::Histogram(histogram),
99        }
100    }
101
102    fn merge(&self, other: Self) -> Self {
103        match (&self.value, other.value) {
104            (AggregatedMetricValue::Counter(a), AggregatedMetricValue::Counter(b)) => Self {
105                timestamp: None,
106                value: AggregatedMetricValue::Counter(a + b),
107            },
108            (AggregatedMetricValue::Gauge(a), AggregatedMetricValue::Gauge(b)) => {
109                let ts_a = self.timestamp.unwrap_or(0);
110                let ts_b = other.timestamp.unwrap_or(0);
111                let (new_ts, new_value) = if ts_a > ts_b { (ts_a, *a) } else { (ts_b, b) };
112
113                Self {
114                    timestamp: Some(new_ts),
115                    value: AggregatedMetricValue::Gauge(new_value),
116                }
117            }
118            (AggregatedMetricValue::Histogram(a), AggregatedMetricValue::Histogram(b)) => {
119                let mut merged = a.clone();
120                merged.merge(&b);
121                Self {
122                    timestamp: None,
123                    value: AggregatedMetricValue::Histogram(merged),
124                }
125            }
126            (_, other_value) => Self {
127                timestamp: other.timestamp,
128                value: other_value,
129            },
130        }
131    }
132}
133
134struct Inner {
135    metrics: HashMap<Context, AggregatedMetric>,
136}
137
138/// Aggregated metrics state.
139pub struct AggregatedMetricsState {
140    inner: Arc<Inner>,
141}
142
143impl AggregatedMetricsState {
144    /// Visits all metrics.
145    pub fn visit_metrics<F>(&self, mut visitor: F)
146    where
147        F: FnMut(&Context, &AggregatedMetricValue),
148    {
149        self.inner
150            .metrics
151            .pin()
152            .iter()
153            .for_each(|(context, value)| visitor(context, &value.value));
154    }
155
156    /// Searches the state for a single metric with a matching name and tags.
157    ///
158    /// The latest value for the metric is returned. Histograms are skipped.
159    ///
160    /// If no metric is found with a matching name and tags, or if multiple metrics are found with a matching name and
161    /// tags, `None` is returned. Tags are matched on a partial basis: a metric must at least have the tags provided,
162    /// but may have additional tags as well.
163    pub fn find_single_with_tags(&self, name: &str, tags: &[&str]) -> Option<f64> {
164        let mut had_existing = false;
165        let mut maybe_metric = None;
166
167        self.visit_metrics(|context, value| {
168            if context.name() == name {
169                for tag in tags {
170                    if !context.tags().has_tag(tag) {
171                        return;
172                    }
173                }
174
175                match value {
176                    AggregatedMetricValue::Counter(v) | AggregatedMetricValue::Gauge(v) => {
177                        had_existing = maybe_metric.is_some();
178                        maybe_metric = Some(*v);
179                    }
180                    AggregatedMetricValue::Histogram(_) => {}
181                }
182            }
183        });
184
185        if had_existing {
186            None
187        } else {
188            maybe_metric
189        }
190    }
191
192    /// Searches the state for all counter metrics with a matching name and returns their aggregated value.
193    ///
194    /// This method allows rolling up counter metrics that share a common name. For example, a metric may be emitted
195    /// with the same name, but N different values for a specific tag, potentially as a way to break down the metric by
196    /// a certain facet. This method can allow re-aggregating the value of each different facet value into a single
197    /// value.
198    ///
199    /// If multiple metrics are found with a matching name, but they're not all counter metrics, or if no metrics are
200    /// found with a matching name, `0.0` is returned.
201    pub fn get_aggregated_with_tags(&self, name: &str, tags: &[&str]) -> f64 {
202        let mut total = 0.0;
203
204        self.visit_metrics(|context, value| {
205            if context.name() == name {
206                for tag in tags {
207                    if !context.tags().has_tag(tag) {
208                        return;
209                    }
210                }
211
212                if let AggregatedMetricValue::Counter(value) = value {
213                    total += *value;
214                }
215            }
216        });
217
218        total
219    }
220}
221
222/// Aggregated metrics processor.
223///
224/// This processor maintains a map of aggregated metrics, where each metric is represented by its context (name and
225/// tags), and the aggregated value of the metric. Counters, gauges, and histograms are supported; all other metric
226/// types are ignored.
227///
228/// Aggregation follows the following rules:
229///
230/// - Counters are summed together.
231/// - Gauges are represented by the latest value (by timestamp).
232/// - Histograms are merged: per-bucket counts, sum, and total count are summed.
233///
234/// Aggregated values have no concept of "points" -- specific values at a specific timestamp -- or multiple data
235/// points: each metric simply has a single value that represents the aggregated amount since the processor was created.
236#[derive(Clone)]
237pub struct AggregatedMetricsProcessor;
238
239impl Processor for AggregatedMetricsProcessor {
240    type Input = MetricsSnapshot;
241    type State = AggregatedMetricsState;
242
243    fn build_initial_state(&self) -> Self::State {
244        AggregatedMetricsState {
245            inner: Arc::new(Inner {
246                metrics: HashMap::new(),
247            }),
248        }
249    }
250
251    fn process(&self, input: Self::Input, state: &Self::State) {
252        let metrics = state.inner.metrics.pin();
253
254        // Record (or merge) the metric values produced this flush.
255        for event in input.upserts {
256            if let Some(metric) = event.try_into_metric() {
257                let (context, values, _) = metric.into_parts();
258                if let Some(agg_metric) = metric_values_to_aggregated(context.name(), values) {
259                    metrics.update_or_insert_with(
260                        context,
261                        |existing| existing.merge(agg_metric.clone()),
262                        || agg_metric.clone(),
263                    );
264                }
265            }
266        }
267
268        // Remove any "evicted" metrics: they were idle long enough without anyone holding a handle to them,
269        // so they're considered dead and should be be removed to avoid unbounded growth.
270        for context in input.evictions {
271            metrics.remove(&context);
272        }
273    }
274}
275
276fn metric_values_to_aggregated(metric_name: &str, values: MetricValues) -> Option<AggregatedMetric> {
277    match values {
278        MetricValues::Counter(points) => {
279            // Extract all points and sum their values together.
280            let value = points.into_iter().map(|(_, value)| value).sum();
281            Some(AggregatedMetric::counter(value))
282        }
283        MetricValues::Gauge(points) => {
284            // Take the last point value, which will be the latest timestamped point, to represent the "current" value.
285            points
286                .into_iter()
287                .last()
288                .map(|(ts, value)| AggregatedMetric::gauge(ts.map(|ts| ts.get()).unwrap_or(0), value))
289        }
290        MetricValues::Histogram(points) => {
291            let mut aggregated = AggregatedHistogram::new(metric_name);
292            for (_, histogram) in points {
293                aggregated.merge_histogram(&histogram);
294            }
295            if aggregated.count() == 0 {
296                None
297            } else {
298                Some(AggregatedMetric::histogram(aggregated))
299            }
300        }
301        _ => None,
302    }
303}
304
305/// The source feeding the shared metrics reflector.
306///
307/// Boxed so that the worker driving it has a nameable type: the adapters applied to [`MetricsStream`] are otherwise
308/// unnameable.
309type SharedMetricsSource = Pin<Box<dyn Stream<Item = Once<MetricsSnapshot>> + Send>>;
310
311/// The worker that drives the shared metrics reflector. See [`initialize_shared_metrics_state`].
312pub type SharedMetricsWorker = ReflectorWorker<AggregatedMetricsProcessor, SharedMetricsSource>;
313
314static SHARED_METRICS_STATE: OnceLock<Reflector<AggregatedMetricsProcessor>> = OnceLock::new();
315
316/// Initializes the shared metrics state, returning the worker that drives it.
317///
318/// Must be called after [`initialize_metrics`][super::initialize_metrics] has installed the global recorder, and
319/// before any caller reaches for [`get_shared_metrics_state`]. The returned worker must be added to a
320/// [`Supervisor`][crate::runtime::Supervisor] -- as a transient child, per [`ReflectorWorker`] -- and until it runs,
321/// the shared state stays empty.
322///
323/// The subscription to the internal metrics registry is taken here rather than when the worker starts, so flushes
324/// that land between initialization and the supervisor starting are still observed.
325///
326/// # Errors
327///
328/// If the shared metrics state was already initialized, an error is returned.
329pub fn initialize_shared_metrics_state() -> Result<SharedMetricsWorker, GenericError> {
330    let source: SharedMetricsSource =
331        Box::pin(MetricsStream::register().map(Arc::unwrap_or_clone).map(std::iter::once));
332    let (reflector, worker) = Reflector::new(source, AggregatedMetricsProcessor);
333
334    SHARED_METRICS_STATE
335        .set(reflector)
336        .map_err(|_| generic_error!("Shared metrics state was already initialized."))?;
337
338    Ok(worker)
339}
340
341/// Gets the shared metrics state, which provides unified access to internal metrics in a simplified interface.
342///
343/// # Panics
344///
345/// Panics if [`initialize_shared_metrics_state`] has not been called.
346pub fn get_shared_metrics_state() -> Reflector<AggregatedMetricsProcessor> {
347    SHARED_METRICS_STATE
348        .get()
349        .expect("shared metrics state should be initialized before it is accessed")
350        .clone()
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356    use crate::data_model::event::{
357        metric::{context::Context, Metric},
358        Event,
359    };
360
361    fn process_metrics(metrics: Vec<Event>) -> Vec<(String, AggregatedMetricValue)> {
362        let state = super::super::aggregate_upserts(metrics);
363
364        let mut result = Vec::new();
365        state.visit_metrics(|context, value| {
366            result.push((context.name().to_string(), value.clone()));
367        });
368
369        result.sort_by(|(name_a, _), (name_b, _)| name_a.cmp(name_b));
370
371        result
372    }
373
374    fn assert_counter(value: &AggregatedMetricValue, expected: f64) {
375        match value {
376            AggregatedMetricValue::Counter(v) => assert_eq!(*v, expected),
377            other => panic!("expected counter, got {other:?}"),
378        }
379    }
380
381    fn assert_gauge(value: &AggregatedMetricValue, expected: f64) {
382        match value {
383            AggregatedMetricValue::Gauge(v) => assert_eq!(*v, expected),
384            other => panic!("expected gauge, got {other:?}"),
385        }
386    }
387
388    fn assert_histogram<F: FnOnce(&AggregatedHistogram)>(value: &AggregatedMetricValue, check: F) {
389        match value {
390            AggregatedMetricValue::Histogram(h) => check(h),
391            other => panic!("expected histogram, got {other:?}"),
392        }
393    }
394
395    #[test]
396    fn aggregate_multiple() {
397        let input_metrics = vec![
398            Event::Metric(Metric::counter("counter", 14.0)),
399            Event::Metric(Metric::gauge("gauge", 28.0)),
400        ];
401
402        let aggregated_metrics = process_metrics(input_metrics);
403        assert_eq!(aggregated_metrics.len(), 2);
404        assert_eq!(aggregated_metrics[0].0, "counter");
405        assert_counter(&aggregated_metrics[0].1, 14.0);
406        assert_eq!(aggregated_metrics[1].0, "gauge");
407        assert_gauge(&aggregated_metrics[1].1, 28.0);
408    }
409
410    #[test]
411    fn aggregate_counters() {
412        let input_metrics = vec![
413            Event::Metric(Metric::counter("counter", 14.0)),
414            Event::Metric(Metric::counter("counter", [(123456, 22.0)])),
415            Event::Metric(Metric::counter("counter", [(123456, 67.0), (123457, 44.0)])),
416        ];
417
418        let aggregated_metrics = process_metrics(input_metrics);
419        assert_eq!(aggregated_metrics.len(), 1);
420        assert_eq!(aggregated_metrics[0].0, "counter");
421        assert_counter(&aggregated_metrics[0].1, 147.0);
422    }
423
424    #[test]
425    fn aggregate_gauges() {
426        let input_metrics = vec![
427            Event::Metric(Metric::gauge("gauge", 14.0)),
428            Event::Metric(Metric::gauge("gauge", [(123458, 44.0)])),
429            Event::Metric(Metric::gauge("gauge", [(123455, 67.0), (123457, 88.0)])),
430        ];
431
432        let aggregated_metrics = process_metrics(input_metrics);
433        assert_eq!(aggregated_metrics.len(), 1);
434        assert_gauge(&aggregated_metrics[0].1, 44.0);
435    }
436
437    #[test]
438    fn aggregate_gauges_bias_incoming() {
439        let input_metrics = vec![
440            Event::Metric(Metric::gauge("gauge", [(123456, 33.0)])),
441            Event::Metric(Metric::gauge("gauge", [(123456, 66.0)])),
442        ];
443
444        let aggregated_metrics = process_metrics(input_metrics);
445        assert_eq!(aggregated_metrics.len(), 1);
446        assert_gauge(&aggregated_metrics[0].1, 66.0);
447    }
448
449    #[test]
450    fn aggregate_type_change() {
451        // When aggregating metrics with identical contexts but different types (i.e. counter vs gauge), the aggregated
452        // metric should be the last type seen.
453        let input_metrics = vec![
454            Event::Metric(Metric::gauge("my_metric", 33.0)),
455            Event::Metric(Metric::counter("my_metric", 42.0)),
456        ];
457
458        let aggregated_metrics = process_metrics(input_metrics);
459        assert_eq!(aggregated_metrics.len(), 1);
460        assert_counter(&aggregated_metrics[0].1, 42.0);
461    }
462
463    #[test]
464    fn aggregate_histograms() {
465        // Histograms with the same context should merge: counts, sums, and per-bucket counts accumulate.
466        let input_metrics = vec![
467            Event::Metric(Metric::histogram("h", [1.0, 2.0, 3.0])),
468            Event::Metric(Metric::histogram("h", [4.0, 5.0])),
469        ];
470
471        let aggregated_metrics = process_metrics(input_metrics);
472        assert_eq!(aggregated_metrics.len(), 1);
473        assert_histogram(&aggregated_metrics[0].1, |hist| {
474            assert_eq!(hist.count(), 5);
475            assert_eq!(hist.sum(), 15.0);
476        });
477    }
478
479    #[test]
480    fn evict_removes_metric() {
481        let processor = AggregatedMetricsProcessor;
482        let state = processor.build_initial_state();
483
484        let context = Context::from_static_parts("counter", &[]);
485        processor.process(
486            MetricsSnapshot {
487                upserts: vec![Event::Metric(Metric::counter(context.clone(), 14.0))],
488                evictions: Vec::new(),
489            },
490            &state,
491        );
492
493        let count_named = |name: &str| {
494            let mut count = 0;
495            state.visit_metrics(|ctx, _| {
496                if ctx.name() == name {
497                    count += 1;
498                }
499            });
500            count
501        };
502
503        // The metric is present after the upsert.
504        assert_eq!(count_named("counter"), 1);
505
506        // Evicting its context removes it from the aggregated state.
507        processor.process(
508            MetricsSnapshot {
509                upserts: Vec::new(),
510                evictions: vec![context],
511            },
512            &state,
513        );
514        assert_eq!(count_named("counter"), 0);
515    }
516}