1use 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#[derive(Clone, Debug)]
24pub enum AggregatedMetricValue {
25 Counter(f64),
27
28 Gauge(f64),
30
31 Histogram(AggregatedHistogram),
33}
34
35impl AggregatedMetricValue {
36 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 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 (existing, incoming) => *existing = incoming.clone(),
62 }
63 }
64
65 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
138pub struct AggregatedMetricsState {
140 inner: Arc<Inner>,
141}
142
143impl AggregatedMetricsState {
144 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 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 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#[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 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 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 let value = points.into_iter().map(|(_, value)| value).sum();
281 Some(AggregatedMetric::counter(value))
282 }
283 MetricValues::Gauge(points) => {
284 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
305type SharedMetricsSource = Pin<Box<dyn Stream<Item = Once<MetricsSnapshot>> + Send>>;
310
311pub type SharedMetricsWorker = ReflectorWorker<AggregatedMetricsProcessor, SharedMetricsSource>;
313
314static SHARED_METRICS_STATE: OnceLock<Reflector<AggregatedMetricsProcessor>> = OnceLock::new();
315
316pub 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
341pub 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 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 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 assert_eq!(count_named("counter"), 1);
505
506 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}