Skip to main content

saluki_components/destinations/prometheus/
mod.rs

1//! Prometheus destination.
2
3use std::{
4    convert::Infallible,
5    num::NonZeroUsize,
6    sync::{Arc, LazyLock},
7};
8
9use async_trait::async_trait;
10use axum::{extract::Request, Router};
11use ddsketch::DDSketch;
12use http::{Response, StatusCode};
13use prometheus_exposition::{MetricType, PrometheusRenderer};
14use saluki_common::{collections::FastIndexMap, iter::ReusableDeduplicator};
15use saluki_core::{
16    accounting::{MemoryBounds, MemoryBoundsBuilder},
17    components::{destinations::*, BuildContext},
18    data_model::{
19        event::{
20            metric::{context::Context, Histogram, Metric, MetricValues},
21            EventType,
22        },
23        tags::Tag,
24    },
25    runtime,
26};
27use saluki_error::GenericError;
28use saluki_io::net::{server::http::HttpServer, ListenAddress};
29use serde::Deserialize;
30use stringtheory::{
31    interning::{FixedSizeInterner, Interner as _},
32    MetaString,
33};
34use tokio::{select, sync::RwLock};
35use tower::util::service_fn;
36use tracing::debug;
37
38const CONTEXT_LIMIT: usize = 10_000;
39const PAYLOAD_SIZE_LIMIT_BYTES: usize = 1024 * 1024;
40const TAGS_BUFFER_SIZE_LIMIT_BYTES: usize = 2048;
41const RAW_METRICS_PATH: &str = "/metrics";
42const LEGACY_RAW_METRICS_PATH: &str = "/";
43
44// Histogram-related constants and pre-calculated buckets.
45const TIME_HISTOGRAM_BUCKET_COUNT: usize = 30;
46static TIME_HISTOGRAM_BUCKETS: LazyLock<[(f64, &'static str); TIME_HISTOGRAM_BUCKET_COUNT]> =
47    LazyLock::new(|| histogram_buckets::<TIME_HISTOGRAM_BUCKET_COUNT>(0.000000128, 4.0));
48
49const NON_TIME_HISTOGRAM_BUCKET_COUNT: usize = 30;
50static NON_TIME_HISTOGRAM_BUCKETS: LazyLock<[(f64, &'static str); NON_TIME_HISTOGRAM_BUCKET_COUNT]> =
51    LazyLock::new(|| histogram_buckets::<NON_TIME_HISTOGRAM_BUCKET_COUNT>(1.0, 2.0));
52
53// SAFETY: This is obviously not zero.
54const METRIC_NAME_STRING_INTERNER_BYTES: NonZeroUsize = NonZeroUsize::new(65536).unwrap();
55
56/// Provides a Prometheus scrape payload for an additional route.
57pub trait PrometheusPayloadProvider: Send + Sync {
58    /// Renders the current Prometheus text payload.
59    fn render_payload(&self) -> String;
60}
61
62impl<F> PrometheusPayloadProvider for F
63where
64    F: Fn() -> String + Send + Sync,
65{
66    fn render_payload(&self) -> String {
67        self()
68    }
69}
70
71#[derive(Clone)]
72struct PrometheusAdditionalRoute {
73    path: String,
74    provider: Arc<dyn PrometheusPayloadProvider>,
75}
76
77/// Prometheus destination.
78///
79/// Exposes a Prometheus scrape endpoint that emits metrics in the Prometheus exposition format.
80///
81/// # Limits
82///
83/// - Number of contexts (unique series) is limited to 10,000.
84/// - Maximum size of scrape payload response is ~1MiB.
85///
86/// # Missing
87///
88/// - no support for expiring metrics (which we don't really need because the only use for this destination at the
89///   moment is internal metrics, which aren't dynamic since we don't use dynamic tags or have dynamic topology support,
90///   but... you know, we'll eventually need this)
91/// - full support for distributions (we can't convert a distribution to an aggregated histogram, and native histogram
92///   support is still too fresh for most clients, so we simply expose aggregated summaries as a stopgap)
93///
94#[derive(Deserialize)]
95pub struct PrometheusConfiguration {
96    #[serde(rename = "prometheus_listen_addr")]
97    listen_addr: ListenAddress,
98
99    #[serde(skip)]
100    additional_routes: Vec<PrometheusAdditionalRoute>,
101}
102
103impl PrometheusConfiguration {
104    /// Creates a new `PrometheusConfiguration` for the given listen address.
105    pub fn from_listen_address(listen_addr: ListenAddress) -> Self {
106        Self {
107            listen_addr,
108            additional_routes: Vec::new(),
109        }
110    }
111
112    /// Adds an additional scrape route backed by the given payload provider.
113    pub fn with_additional_route(
114        mut self, path: impl Into<String>, provider: Arc<dyn PrometheusPayloadProvider>,
115    ) -> Self {
116        self.additional_routes.push(PrometheusAdditionalRoute {
117            path: path.into(),
118            provider,
119        });
120        self
121    }
122}
123
124#[async_trait]
125impl DestinationBuilder for PrometheusConfiguration {
126    fn input_event_type(&self) -> EventType {
127        EventType::Metric
128    }
129
130    async fn build(&self, _context: BuildContext) -> Result<Box<dyn Destination + Send>, GenericError> {
131        Ok(Box::new(Prometheus {
132            listen_addr: self.listen_addr.clone(),
133            additional_routes: self.additional_routes.clone(),
134            metrics: FastIndexMap::default(),
135            payload: Arc::new(RwLock::new(String::new())),
136            renderer: PrometheusRenderer::new(),
137            interner: FixedSizeInterner::new(METRIC_NAME_STRING_INTERNER_BYTES),
138        }))
139    }
140}
141
142impl MemoryBounds for PrometheusConfiguration {
143    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
144        builder
145            .minimum()
146            // Capture the size of the heap allocation when the component is built.
147            .with_single_value::<Prometheus>("component struct");
148
149        builder
150            .firm()
151            // Even though our context map is really the Prometheus context to a map of context/value pairs, we're just
152            // simplifying things here because the ratio of true "contexts" to Prometheus contexts should be very high,
153            // high enough to make this a reasonable approximation.
154            .with_map::<Context, PrometheusValue>("state map", CONTEXT_LIMIT)
155            .with_fixed_amount("payload size", PAYLOAD_SIZE_LIMIT_BYTES)
156            .with_fixed_amount("tags buffer", TAGS_BUFFER_SIZE_LIMIT_BYTES);
157    }
158}
159
160struct Prometheus {
161    listen_addr: ListenAddress,
162    additional_routes: Vec<PrometheusAdditionalRoute>,
163    metrics: FastIndexMap<PrometheusContext, FastIndexMap<Context, PrometheusValue>>,
164    payload: Arc<RwLock<String>>,
165    renderer: PrometheusRenderer,
166    interner: FixedSizeInterner<1>,
167}
168
169#[async_trait]
170impl Destination for Prometheus {
171    async fn run(mut self: Box<Self>, mut context: DestinationContext) -> Result<(), GenericError> {
172        let Self {
173            listen_addr,
174            additional_routes,
175            mut metrics,
176            payload,
177            mut renderer,
178            interner,
179        } = *self;
180
181        let mut health = context.take_health_handle();
182
183        // The scrape endpoint runs as a supervised child of this component, not as a part of its body. When this
184        // component is done, the scrape endpoint stops and drains its in-flight connections.
185        runtime::nested_supervisor(
186            build_scrape_server(listen_addr, Arc::clone(&payload), additional_routes)
187                .with_worker_pool(context.topology_context().global_thread_pool().clone())
188                .into_supervisor(),
189        )
190        .needed()
191        .spawn();
192
193        health.mark_ready();
194
195        debug!("Prometheus destination started.");
196
197        let mut contexts = 0;
198        let mut tags_deduplicator = ReusableDeduplicator::new();
199
200        loop {
201            select! {
202                _ = health.live() => continue,
203                maybe_events = context.events().next() => match maybe_events {
204                    Some(events) => {
205                        // Process each metric event in the batch, either merging it with the existing value or
206                        // inserting it for the first time.
207                        for metric in events.into_events::<Metric>() {
208                            // Break apart our metric into its constituent parts, and then normalize it for
209                            // Prometheus: adjust the name if necessary, figuring out the equivalent Prometheus
210                            // metric type, and so on.
211                            let prom_context = match into_prometheus_metric(&metric, &mut renderer, &interner) {
212                                Some(prom_context) => prom_context,
213                                None => continue,
214                            };
215
216                            let (context, values, _) = metric.into_parts();
217
218                            // Create an entry for the context if we don't already have one, obeying our configured context limit.
219                            let existing_contexts = metrics.entry(prom_context.clone()).or_default();
220                            match existing_contexts.get_mut(&context) {
221                                Some(existing_prom_value) => merge_metric_values_with_prom_value(values, existing_prom_value),
222                                None => {
223                                    if contexts >= CONTEXT_LIMIT {
224                                        debug!("Prometheus destination reached context limit. Skipping metric '{}'.", context.name());
225                                        continue
226                                    }
227
228                                    let mut new_prom_value = get_prom_value_for_prom_context(&prom_context);
229                                    merge_metric_values_with_prom_value(values, &mut new_prom_value);
230
231                                    existing_contexts.insert(context, new_prom_value);
232                                    contexts += 1;
233                                }
234                            }
235                        }
236
237                        // Regenerate the scrape payload.
238                        regenerate_payload(&metrics, &payload, &mut renderer, &mut tags_deduplicator).await;
239                    },
240                    None => break,
241                },
242            }
243        }
244
245        debug!("Prometheus destination stopped.");
246
247        Ok(())
248    }
249}
250
251/// Builds the server that answers scrape requests.
252///
253/// Every path is answered by the same service rather than being routed: the raw metrics paths take precedence over the
254/// additional routes, so a path claimed by both is answered with the raw payload rather than being a conflict.
255fn build_scrape_server(
256    listen_addr: ListenAddress, payload: Arc<RwLock<String>>, additional_routes: Vec<PrometheusAdditionalRoute>,
257) -> HttpServer {
258    let additional_routes = Arc::new(additional_routes);
259    let service = service_fn(move |req: Request| {
260        let payload = Arc::clone(&payload);
261        let additional_routes = Arc::clone(&additional_routes);
262        async move {
263            Ok::<_, Infallible>(build_scrape_response(req.uri().path(), &payload, additional_routes.as_ref()).await)
264        }
265    });
266
267    HttpServer::from_listen_address(listen_addr).with_routes(Router::new().fallback_service(service))
268}
269
270async fn build_scrape_response(
271    path: &str, payload: &Arc<RwLock<String>>, additional_routes: &[PrometheusAdditionalRoute],
272) -> Response<axum::body::Body> {
273    if path == RAW_METRICS_PATH || path == LEGACY_RAW_METRICS_PATH {
274        let payload = payload.read().await;
275        return Response::new(axum::body::Body::from(payload.to_string()));
276    }
277
278    if let Some(route) = additional_routes.iter().find(|route| route.path == path) {
279        return Response::new(axum::body::Body::from(route.provider.render_payload()));
280    }
281
282    Response::builder()
283        .status(StatusCode::NOT_FOUND)
284        .body(axum::body::Body::empty())
285        .expect("response builder should accept static status and empty body")
286}
287
288#[allow(clippy::mutable_key_type)]
289async fn regenerate_payload(
290    metrics: &FastIndexMap<PrometheusContext, FastIndexMap<Context, PrometheusValue>>, payload: &Arc<RwLock<String>>,
291    renderer: &mut PrometheusRenderer, tags_deduplicator: &mut ReusableDeduplicator<Tag>,
292) {
293    renderer.clear();
294
295    for (prom_context, contexts) in metrics {
296        if !write_metrics(renderer, prom_context, contexts, tags_deduplicator) {
297            debug!("Failed to write metric to payload. Continuing...");
298            continue;
299        }
300
301        if renderer.output().len() > PAYLOAD_SIZE_LIMIT_BYTES {
302            debug!(
303                payload_len = renderer.output().len(),
304                "Payload size limit exceeded. Skipping remaining metrics."
305            );
306            break;
307        }
308    }
309
310    let mut payload = payload.write().await;
311    payload.clear();
312    payload.push_str(renderer.output());
313}
314
315fn write_metrics(
316    renderer: &mut PrometheusRenderer, prom_context: &PrometheusContext,
317    contexts: &FastIndexMap<Context, PrometheusValue>, tags_deduplicator: &mut ReusableDeduplicator<Tag>,
318) -> bool {
319    if contexts.is_empty() {
320        debug!("No contexts for metric '{}'. Skipping.", prom_context.metric_name);
321        return true;
322    }
323
324    renderer.begin_group(&prom_context.metric_name, prom_context.metric_type, None);
325
326    for (context, values) in contexts {
327        let labels = match collect_tags(context, tags_deduplicator) {
328            Some(labels) => labels,
329            None => return false,
330        };
331
332        match values {
333            PrometheusValue::Counter(value) | PrometheusValue::Gauge(value) => {
334                renderer.write_gauge_or_counter_series(labels, *value);
335            }
336            PrometheusValue::Histogram(histogram) => {
337                renderer.write_histogram_series(labels, histogram.buckets(), histogram.sum, histogram.count);
338            }
339            PrometheusValue::Summary(sketch) => {
340                let quantiles = [0.1, 0.25, 0.5, 0.95, 0.99, 0.999]
341                    .into_iter()
342                    .map(|q| (q, sketch.quantile(q).unwrap_or_default()));
343
344                renderer.write_summary_series(labels, quantiles, sketch.sum().unwrap_or_default(), sketch.count());
345            }
346        }
347    }
348
349    renderer.finish_group();
350    true
351}
352
353/// Collects tags from a context into key-value pairs suitable for the renderer.
354fn collect_tags<'a>(
355    context: &'a Context, tags_deduplicator: &mut ReusableDeduplicator<Tag>,
356) -> Option<Vec<(&'a str, &'a str)>> {
357    let mut labels = Vec::new();
358    let mut total_bytes = 0;
359
360    let chained_tags = context.tags().into_iter().chain(context.origin_tags());
361    let deduplicated_tags = tags_deduplicator.deduplicated(chained_tags);
362
363    for tag in deduplicated_tags {
364        let tag_name = tag.name();
365        let tag_value = match tag.value() {
366            Some(value) => value,
367            None => {
368                debug!("Skipping bare tag.");
369                continue;
370            }
371        };
372
373        // Can't exceed the tags buffer size limit: we calculate the addition as tag name/value length plus three bytes
374        // to account for having to format it as `name="value",`.
375        total_bytes += tag_name.len() + tag_value.len() + 4;
376        if total_bytes > TAGS_BUFFER_SIZE_LIMIT_BYTES {
377            debug!("Tags buffer size limit exceeded. Tags may be missing from this metric.");
378            return None;
379        }
380
381        labels.push((tag_name, tag_value));
382    }
383
384    Some(labels)
385}
386
387#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
388struct PrometheusContext {
389    metric_name: MetaString,
390    metric_type: MetricType,
391}
392
393enum PrometheusValue {
394    Counter(f64),
395    Gauge(f64),
396    Histogram(PrometheusHistogram),
397    Summary(DDSketch),
398}
399
400fn into_prometheus_metric(
401    metric: &Metric, renderer: &mut PrometheusRenderer, interner: &FixedSizeInterner<1>,
402) -> Option<PrometheusContext> {
403    // Normalize the metric name using the renderer, then intern it.
404    let normalized = renderer.normalize_metric_name(metric.context().name());
405    let metric_name = match interner.try_intern(normalized).map(MetaString::from) {
406        Some(name) => name,
407        None => {
408            debug!(
409                "Failed to intern normalized metric name. Skipping metric '{}'.",
410                metric.context().name()
411            );
412            return None;
413        }
414    };
415
416    let metric_type = match metric.values() {
417        MetricValues::Counter(_) => MetricType::Counter,
418        MetricValues::Gauge(_) | MetricValues::Set(_) => MetricType::Gauge,
419        MetricValues::Histogram(_) => MetricType::Histogram,
420        MetricValues::Distribution(_) => MetricType::Summary,
421        _ => return None,
422    };
423
424    Some(PrometheusContext {
425        metric_name,
426        metric_type,
427    })
428}
429
430fn get_prom_value_for_prom_context(prom_context: &PrometheusContext) -> PrometheusValue {
431    match prom_context.metric_type {
432        MetricType::Counter => PrometheusValue::Counter(0.0),
433        MetricType::Gauge => PrometheusValue::Gauge(0.0),
434        MetricType::Histogram => PrometheusValue::Histogram(PrometheusHistogram::new(&prom_context.metric_name)),
435        MetricType::Summary => PrometheusValue::Summary(DDSketch::default()),
436    }
437}
438
439fn merge_metric_values_with_prom_value(values: MetricValues, prom_value: &mut PrometheusValue) {
440    match (values, prom_value) {
441        (MetricValues::Counter(counter_values), PrometheusValue::Counter(prom_counter)) => {
442            for (_, value) in counter_values {
443                *prom_counter += value;
444            }
445        }
446        (MetricValues::Gauge(gauge_values), PrometheusValue::Gauge(prom_gauge)) => {
447            let latest_value = gauge_values
448                .into_iter()
449                .max_by_key(|(ts, _)| ts.map(|v| v.get()).unwrap_or_default())
450                .map(|(_, value)| value)
451                .unwrap_or_default();
452            *prom_gauge = latest_value;
453        }
454        (MetricValues::Set(set_values), PrometheusValue::Gauge(prom_gauge)) => {
455            let latest_value = set_values
456                .into_iter()
457                .max_by_key(|(ts, _)| ts.map(|v| v.get()).unwrap_or_default())
458                .map(|(_, value)| value)
459                .unwrap_or_default();
460            *prom_gauge = latest_value;
461        }
462        (MetricValues::Histogram(histogram_values), PrometheusValue::Histogram(prom_histogram)) => {
463            for (_, value) in histogram_values {
464                prom_histogram.merge_histogram(&value);
465            }
466        }
467        (MetricValues::Distribution(distribution_values), PrometheusValue::Summary(prom_summary)) => {
468            for (_, value) in distribution_values {
469                prom_summary.merge(&value);
470            }
471        }
472        _ => panic!("Mismatched metric types"),
473    }
474}
475
476#[derive(Clone)]
477struct PrometheusHistogram {
478    sum: f64,
479    count: u64,
480    buckets: Vec<(f64, &'static str, u64)>,
481}
482
483impl PrometheusHistogram {
484    fn new(metric_name: &str) -> Self {
485        // Super hacky but effective way to decide when to switch to the time-oriented buckets.
486        let base_buckets = if metric_name.ends_with("_seconds") {
487            &TIME_HISTOGRAM_BUCKETS[..]
488        } else {
489            &NON_TIME_HISTOGRAM_BUCKETS[..]
490        };
491
492        let buckets = base_buckets
493            .iter()
494            .map(|(upper_bound, upper_bound_str)| (*upper_bound, *upper_bound_str, 0))
495            .collect();
496
497        Self {
498            sum: 0.0,
499            count: 0,
500            buckets,
501        }
502    }
503
504    fn merge_histogram(&mut self, histogram: &Histogram) {
505        for sample in histogram.samples() {
506            self.add_sample(sample.value.into_inner(), sample.weight.0 as u64);
507        }
508    }
509
510    fn add_sample(&mut self, value: f64, weight: u64) {
511        self.sum += value * weight as f64;
512        self.count += weight;
513
514        // Add the value to each bucket that it falls into, up to the maximum number of buckets.
515        for (upper_bound, _, count) in &mut self.buckets {
516            if value <= *upper_bound {
517                *count += weight;
518            }
519        }
520    }
521
522    fn buckets(&self) -> impl Iterator<Item = (&'static str, u64)> + '_ {
523        self.buckets
524            .iter()
525            .map(|(_, upper_bound_str, count)| (*upper_bound_str, *count))
526    }
527}
528
529fn histogram_buckets<const N: usize>(base: f64, scale: f64) -> [(f64, &'static str); N] {
530    // We generate a set of "log-linear" buckets: logarithmically spaced values which are then subdivided linearly.
531    //
532    // As an example, with base=2 and scale=4, we would get: 2, 5, 8, 20, 32, 80, 128, 320, 512, and so on.
533    //
534    // We calculate buckets in pairs, where the n-th pair is `i` and `j`, such that `i` is `base * scale^n` and `j` is
535    // the midpoint between `i` and the next `i` (`base * scale^(n+1)`).
536
537    let mut buckets = [(0.0, ""); N];
538
539    let log_linear_buckets = std::iter::repeat(base).enumerate().flat_map(|(i, base)| {
540        let pow = scale.powf(i as f64);
541        let value = base * pow;
542
543        let next_pow = scale.powf((i + 1) as f64);
544        let next_value = base * next_pow;
545        let midpoint = (value + next_value) / 2.0;
546
547        [value, midpoint]
548    });
549
550    for (i, current_le) in log_linear_buckets.enumerate().take(N) {
551        let (bucket_le, bucket_le_str) = &mut buckets[i];
552        let current_le_str = format!("{}", current_le);
553
554        *bucket_le = current_le;
555        *bucket_le_str = current_le_str.leak();
556    }
557
558    buckets
559}
560
561#[cfg(test)]
562mod tests {
563    use std::collections::BTreeSet;
564
565    use http_body_util::BodyExt as _;
566    use saluki_core::data_model::tags::TagSet;
567
568    use super::*;
569
570    fn prom_context(metric_type: MetricType) -> PrometheusContext {
571        PrometheusContext {
572            metric_name: MetaString::from("test.metric"),
573            metric_type,
574        }
575    }
576
577    #[test]
578    fn histogram_buckets_are_monotonic_finite_and_labeled() {
579        // The pre-computed log-linear bucket tables back every Prometheus histogram we expose, so their invariants are
580        // load-bearing: exactly N upper bounds, strictly increasing, finite and positive, starting at the configured
581        // base, each paired with a string label that renders (and parses back to) its own float value. A regression
582        // producing NaN/inf bounds, non-monotonic spacing, or a mismatched label would silently corrupt the exposition
583        // output, so assert the contract rather than just printing the tables.
584        fn assert_bucket_table(buckets: &[(f64, &'static str)], base: f64) {
585            assert!(!buckets.is_empty(), "bucket table must not be empty");
586            assert_eq!(
587                buckets[0].0, base,
588                "first bucket upper bound must equal the configured base"
589            );
590
591            let mut previous = f64::NEG_INFINITY;
592            for (upper_bound, label) in buckets {
593                assert!(
594                    upper_bound.is_finite(),
595                    "bucket upper bound must be finite, got {upper_bound}"
596                );
597                assert!(
598                    *upper_bound > 0.0,
599                    "bucket upper bound must be positive, got {upper_bound}"
600                );
601                assert!(
602                    *upper_bound > previous,
603                    "bucket upper bounds must be strictly increasing ({upper_bound} !> {previous})"
604                );
605                previous = *upper_bound;
606
607                let parsed: f64 = label.parse().expect("bucket label must parse as an f64");
608                assert_eq!(
609                    parsed, *upper_bound,
610                    "bucket label {label:?} must render its own upper bound {upper_bound}"
611                );
612            }
613        }
614
615        assert_eq!(TIME_HISTOGRAM_BUCKETS.len(), TIME_HISTOGRAM_BUCKET_COUNT);
616        assert_eq!(NON_TIME_HISTOGRAM_BUCKETS.len(), NON_TIME_HISTOGRAM_BUCKET_COUNT);
617        assert_bucket_table(&TIME_HISTOGRAM_BUCKETS[..], 0.000000128);
618        assert_bucket_table(&NON_TIME_HISTOGRAM_BUCKETS[..], 1.0);
619    }
620
621    #[test]
622    fn prom_histogram_add_sample() {
623        let sample1 = (0.25, 1);
624        let sample2 = (1.0, 2);
625        let sample3 = (2.0, 3);
626
627        let mut histogram = PrometheusHistogram::new("time_metric_seconds");
628        histogram.add_sample(sample1.0, sample1.1);
629        histogram.add_sample(sample2.0, sample2.1);
630        histogram.add_sample(sample3.0, sample3.1);
631
632        let sample1_weighted_value = sample1.0 * sample1.1 as f64;
633        let sample2_weighted_value = sample2.0 * sample2.1 as f64;
634        let sample3_weighted_value = sample3.0 * sample3.1 as f64;
635        let expected_sum = sample1_weighted_value + sample2_weighted_value + sample3_weighted_value;
636        let expected_count = sample1.1 + sample2.1 + sample3.1;
637        assert_eq!(histogram.sum, expected_sum);
638        assert_eq!(histogram.count, expected_count);
639
640        // Go through and make sure we have things in the right buckets.
641        let mut expected_bucket_count = 0;
642        for sample in [sample1, sample2, sample3] {
643            for bucket in &histogram.buckets {
644                // If we've finally hit a bucket that includes our sample value, it's count should be equal to or
645                // greater than our expected bucket count when we account for the current sample.
646                if sample.0 <= bucket.0 {
647                    assert!(bucket.2 >= expected_bucket_count + sample.1);
648                }
649            }
650
651            // Adjust the expected bucket count to fully account for the current sample before moving on.
652            expected_bucket_count += sample.1;
653        }
654    }
655
656    #[tokio::test]
657    async fn scrape_routes_serve_raw_additional_and_404() {
658        let payload = Arc::new(RwLock::new("raw".to_string()));
659        let routes = vec![PrometheusAdditionalRoute {
660            path: "/additional/metrics".to_string(),
661            provider: Arc::new(|| "additional".to_string()),
662        }];
663
664        let raw_response = build_scrape_response("/metrics", &payload, &routes).await;
665        assert_eq!(raw_response.status(), StatusCode::OK);
666        let raw_body = raw_response
667            .into_body()
668            .collect()
669            .await
670            .expect("body should collect")
671            .to_bytes();
672        assert_eq!(&raw_body[..], b"raw");
673
674        let legacy_response = build_scrape_response("/", &payload, &routes).await;
675        assert_eq!(legacy_response.status(), StatusCode::OK);
676        let legacy_body = legacy_response
677            .into_body()
678            .collect()
679            .await
680            .expect("body should collect")
681            .to_bytes();
682        assert_eq!(&legacy_body[..], b"raw");
683
684        let additional_response = build_scrape_response("/additional/metrics", &payload, &routes).await;
685        assert_eq!(additional_response.status(), StatusCode::OK);
686        let additional_body = additional_response
687            .into_body()
688            .collect()
689            .await
690            .expect("body should collect")
691            .to_bytes();
692        assert_eq!(&additional_body[..], b"additional");
693
694        let missing_response = build_scrape_response("/missing", &payload, &routes).await;
695        assert_eq!(missing_response.status(), StatusCode::NOT_FOUND);
696    }
697
698    #[test]
699    fn into_prometheus_metric_maps_value_type_and_normalizes_name() {
700        let mut renderer = PrometheusRenderer::new();
701        let interner = FixedSizeInterner::<1>::new(METRIC_NAME_STRING_INTERNER_BYTES);
702
703        // The metric name is normalized to the Prometheus character set: the `.` separator is not a valid name
704        // character, so it is replaced (the renderer yields `my__counter`).
705        let counter = into_prometheus_metric(&Metric::counter("my.counter", 1.0), &mut renderer, &interner)
706            .expect("counter should translate");
707        assert_eq!("my__counter", counter.metric_name.as_ref());
708        assert!(matches!(counter.metric_type, MetricType::Counter));
709
710        // Gauges and sets both map to a Prometheus gauge.
711        let gauge =
712            into_prometheus_metric(&Metric::gauge("g", 1.0), &mut renderer, &interner).expect("gauge should translate");
713        assert!(matches!(gauge.metric_type, MetricType::Gauge));
714        let set =
715            into_prometheus_metric(&Metric::set("s", "a"), &mut renderer, &interner).expect("set should translate");
716        assert!(matches!(set.metric_type, MetricType::Gauge));
717
718        // Histograms map to a native Prometheus histogram.
719        let histogram = into_prometheus_metric(&Metric::histogram("h", [1.0]), &mut renderer, &interner)
720            .expect("histogram should translate");
721        assert!(matches!(histogram.metric_type, MetricType::Histogram));
722
723        // Distributions are exposed as a DDSketch-backed summary: the documented stopgap, since a distribution can't
724        // be converted to an aggregated histogram.
725        let distribution = into_prometheus_metric(&Metric::distribution("d", [1.0]), &mut renderer, &interner)
726            .expect("distribution should translate");
727        assert!(matches!(distribution.metric_type, MetricType::Summary));
728    }
729
730    #[test]
731    fn merge_counter_sums_all_points() {
732        let mut value = get_prom_value_for_prom_context(&prom_context(MetricType::Counter));
733        let (_, values, _) = Metric::counter("c", [(1, 1.0), (2, 2.0), (3, 4.0)]).into_parts();
734        merge_metric_values_with_prom_value(values, &mut value);
735        match value {
736            PrometheusValue::Counter(sum) => assert_eq!(7.0, sum),
737            _ => panic!("counter values should stay a counter"),
738        }
739    }
740
741    #[test]
742    fn merge_gauge_keeps_latest_by_timestamp() {
743        let mut value = get_prom_value_for_prom_context(&prom_context(MetricType::Gauge));
744        // Points are supplied out of timestamp order; the highest timestamp's value wins.
745        let (_, values, _) = Metric::gauge("g", [(10, 1.0), (30, 3.0), (20, 2.0)]).into_parts();
746        merge_metric_values_with_prom_value(values, &mut value);
747        match value {
748            PrometheusValue::Gauge(latest) => assert_eq!(3.0, latest),
749            _ => panic!("gauge values should stay a gauge"),
750        }
751    }
752
753    #[test]
754    fn merge_set_maps_cardinality_into_gauge() {
755        let mut value = get_prom_value_for_prom_context(&prom_context(MetricType::Gauge));
756        let (_, values, _) = Metric::set("s", "a").into_parts();
757        merge_metric_values_with_prom_value(values, &mut value);
758        match value {
759            PrometheusValue::Gauge(cardinality) => assert_eq!(1.0, cardinality),
760            _ => panic!("set values should merge into a gauge"),
761        }
762    }
763
764    #[test]
765    fn merge_histogram_accumulates_sum_and_count() {
766        let mut value = get_prom_value_for_prom_context(&prom_context(MetricType::Histogram));
767        let (_, values, _) = Metric::histogram("h", [1.0, 2.0, 3.0]).into_parts();
768        merge_metric_values_with_prom_value(values, &mut value);
769        match value {
770            PrometheusValue::Histogram(histogram) => {
771                assert_eq!(3, histogram.count);
772                assert_eq!(6.0, histogram.sum);
773            }
774            _ => panic!("histogram values should stay a histogram"),
775        }
776    }
777
778    #[test]
779    fn merge_distribution_folds_into_ddsketch_summary() {
780        let mut value = get_prom_value_for_prom_context(&prom_context(MetricType::Summary));
781        let (_, values, _) = Metric::distribution("d", [1.0, 2.0, 3.0, 4.0, 5.0]).into_parts();
782        merge_metric_values_with_prom_value(values, &mut value);
783        match value {
784            PrometheusValue::Summary(sketch) => {
785                assert_eq!(5, sketch.count());
786                let median = sketch.quantile(0.5).expect("median should be computable");
787                assert!((median - 3.0).abs() <= 0.5, "median should be ~= 3.0, got {median}");
788            }
789            _ => panic!("distribution values should merge into a summary"),
790        }
791    }
792
793    #[test]
794    #[should_panic(expected = "Mismatched metric types")]
795    fn merge_mismatched_value_and_accumulator_types_panics() {
796        // Feeding gauge values into a counter accumulator is an invariant violation and panics.
797        let mut value = get_prom_value_for_prom_context(&prom_context(MetricType::Counter));
798        let (_, values, _) = Metric::gauge("g", 1.0).into_parts();
799        merge_metric_values_with_prom_value(values, &mut value);
800    }
801
802    #[test]
803    fn collect_tags_skips_bare_tags_and_keeps_key_value_pairs() {
804        let mut tags_deduplicator = ReusableDeduplicator::new();
805        let context = Context::from_static_parts("m", &["env:prod", "bare", "team:core"]);
806
807        let labels = collect_tags(&context, &mut tags_deduplicator).expect("tags should collect");
808        let labels = labels.into_iter().collect::<BTreeSet<_>>();
809
810        // Key/value tags become labels; the bare `bare` tag (no value) is dropped.
811        assert_eq!(BTreeSet::from([("env", "prod"), ("team", "core")]), labels);
812    }
813
814    #[test]
815    fn collect_tags_returns_none_when_buffer_limit_exceeded() {
816        let mut tags_deduplicator = ReusableDeduplicator::new();
817        // A single tag larger than the 2048-byte buffer trips the size-limit bail-out.
818        let oversized_tag = format!("big:{}", "x".repeat(TAGS_BUFFER_SIZE_LIMIT_BYTES + 1));
819        let tags = std::iter::once(Tag::from(oversized_tag)).collect::<TagSet>();
820        let context = Context::from_parts("m", tags);
821
822        assert_eq!(None, collect_tags(&context, &mut tags_deduplicator));
823    }
824}