metrics.rs 67.4 KB
Newer Older
1
2
3
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

4
//! Metrics registry trait and implementation for Prometheus metrics
5
//!
6
7
//! This module provides a trait-based interface for creating and managing Prometheus metrics
//! with automatic label injection and hierarchical naming support.
8

9
10
pub mod prometheus_names;

11
use parking_lot::Mutex;
12
13
14
15
16
use std::collections::HashSet;
use std::sync::Arc;

use crate::component::ComponentBuilder;
use anyhow;
17
18
use once_cell::sync::Lazy;
use regex::Regex;
19
20
21
use std::any::Any;
use std::collections::HashMap;

22
23
// Import commonly used items to avoid verbose prefixes
use prometheus_names::{
24
25
    COMPONENT_NATS_METRICS, DRT_NATS_METRICS, build_component_metric_name, labels, name_prefix,
    nats_client, nats_service, sanitize_prometheus_label, sanitize_prometheus_name, work_handler,
26
27
28
29
};

// Pipeline imports for endpoint creation
use crate::pipeline::{
30
31
    AsyncEngine, AsyncEngineContextProvider, Error, ManyOut, ResponseStream, SingleIn, async_trait,
    network::Ingress,
32
33
34
35
36
37
};
use crate::protocols::annotated::Annotated;
use crate::stream;
use crate::stream::StreamExt;

// If set to true, then metrics will be labeled with the namespace, component, and endpoint labels.
38
// These labels are prefixed with "dynamo_" to avoid collisions with Kubernetes and other monitoring system labels.
39
40
41
42
43
pub const USE_AUTO_LABELS: bool = true;

// Prometheus imports
use prometheus::Encoder;

44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/// Validate that a label slice has no duplicate keys.
/// Returns Ok(()) when all keys are unique; otherwise returns an error naming the duplicate key.
fn validate_no_duplicate_label_keys(labels: &[(&str, &str)]) -> anyhow::Result<()> {
    let mut seen_keys = std::collections::HashSet::new();
    for (key, _) in labels {
        if !seen_keys.insert(*key) {
            return Err(anyhow::anyhow!(
                "Duplicate label key '{}' found in labels",
                key
            ));
        }
    }
    Ok(())
}

59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/// Trait that defines common behavior for Prometheus metric types
pub trait PrometheusMetric: prometheus::core::Collector + Clone + Send + Sync + 'static {
    /// Create a new metric with the given options
    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error>
    where
        Self: Sized;

    /// Create a new metric with histogram options and custom buckets
    /// This is a default implementation that will panic for non-histogram metrics
    fn with_histogram_opts_and_buckets(
        _opts: prometheus::HistogramOpts,
        _buckets: Option<Vec<f64>>,
    ) -> Result<Self, prometheus::Error>
    where
        Self: Sized,
    {
        panic!("with_histogram_opts_and_buckets is not implemented for this metric type");
    }

    /// Create a new metric with counter options and label names (for CounterVec)
    /// This is a default implementation that will panic for non-countervec metrics
    fn with_opts_and_label_names(
        _opts: prometheus::Opts,
        _label_names: &[&str],
    ) -> Result<Self, prometheus::Error>
    where
        Self: Sized,
    {
        panic!("with_opts_and_label_names is not implemented for this metric type");
    }
}

// Implement the trait for Counter, IntCounter, and Gauge
impl PrometheusMetric for prometheus::Counter {
    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
        prometheus::Counter::with_opts(opts)
    }
}

impl PrometheusMetric for prometheus::IntCounter {
    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
        prometheus::IntCounter::with_opts(opts)
    }
}

impl PrometheusMetric for prometheus::Gauge {
    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
        prometheus::Gauge::with_opts(opts)
    }
}

impl PrometheusMetric for prometheus::IntGauge {
    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
        prometheus::IntGauge::with_opts(opts)
    }
}

116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
impl PrometheusMetric for prometheus::GaugeVec {
    fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
        Err(prometheus::Error::Msg(
            "GaugeVec requires label names, use with_opts_and_label_names instead".to_string(),
        ))
    }

    fn with_opts_and_label_names(
        opts: prometheus::Opts,
        label_names: &[&str],
    ) -> Result<Self, prometheus::Error> {
        prometheus::GaugeVec::new(opts, label_names)
    }
}

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
impl PrometheusMetric for prometheus::IntGaugeVec {
    fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
        Err(prometheus::Error::Msg(
            "IntGaugeVec requires label names, use with_opts_and_label_names instead".to_string(),
        ))
    }

    fn with_opts_and_label_names(
        opts: prometheus::Opts,
        label_names: &[&str],
    ) -> Result<Self, prometheus::Error> {
        prometheus::IntGaugeVec::new(opts, label_names)
    }
}

146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
impl PrometheusMetric for prometheus::IntCounterVec {
    fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
        Err(prometheus::Error::Msg(
            "IntCounterVec requires label names, use with_opts_and_label_names instead".to_string(),
        ))
    }

    fn with_opts_and_label_names(
        opts: prometheus::Opts,
        label_names: &[&str],
    ) -> Result<Self, prometheus::Error> {
        prometheus::IntCounterVec::new(opts, label_names)
    }
}

161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// Implement the trait for Histogram
impl PrometheusMetric for prometheus::Histogram {
    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
        // Convert Opts to HistogramOpts
        let histogram_opts = prometheus::HistogramOpts::new(opts.name, opts.help);
        prometheus::Histogram::with_opts(histogram_opts)
    }

    fn with_histogram_opts_and_buckets(
        mut opts: prometheus::HistogramOpts,
        buckets: Option<Vec<f64>>,
    ) -> Result<Self, prometheus::Error> {
        if let Some(custom_buckets) = buckets {
            opts = opts.buckets(custom_buckets);
        }
        prometheus::Histogram::with_opts(opts)
    }
}

// Implement the trait for CounterVec
impl PrometheusMetric for prometheus::CounterVec {
    fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
        // This will panic - CounterVec needs label names
        panic!("CounterVec requires label names, use with_opts_and_label_names instead");
    }

    fn with_opts_and_label_names(
        opts: prometheus::Opts,
        label_names: &[&str],
    ) -> Result<Self, prometheus::Error> {
        prometheus::CounterVec::new(opts, label_names)
    }
}

/// Private helper function to create metrics - not accessible to trait implementors
fn create_metric<T: PrometheusMetric, R: MetricsRegistry + ?Sized>(
    registry: &R,
    metric_name: &str,
    metric_desc: &str,
    labels: &[(&str, &str)],
    buckets: Option<Vec<f64>>,
    const_labels: Option<&[&str]>,
203
) -> anyhow::Result<T> {
204
    // Validate that user-provided labels don't have duplicate keys
205
    validate_no_duplicate_label_keys(labels)?;
206
    // Note: stored labels functionality has been removed
207
208
209
210

    let basename = registry.basename();
    let parent_hierarchy = registry.parent_hierarchy();

211
212
213
    // Build hierarchy: parent_hierarchy + [basename]
    let hierarchy = [parent_hierarchy.clone(), vec![basename.clone()]].concat();

214
    let metric_name = build_component_metric_name(metric_name);
215

216
    // Build updated_labels: auto-labels first, then `labels` + stored labels
217
218
219
220
221
    let mut updated_labels: Vec<(String, String)> = Vec::new();

    if USE_AUTO_LABELS {
        // Validate that user-provided labels don't conflict with auto-generated labels
        for (key, _) in labels {
222
            if *key == labels::NAMESPACE || *key == labels::COMPONENT || *key == labels::ENDPOINT {
223
224
225
226
227
228
229
                return Err(anyhow::anyhow!(
                    "Label '{}' is automatically added by auto_label feature and cannot be manually set",
                    key
                ));
            }
        }

230
        // Add auto-generated labels with sanitized values
231
232
233
        if hierarchy.len() > 1 {
            let namespace = &hierarchy[1];
            if !namespace.is_empty() {
234
                let valid_namespace = sanitize_prometheus_label(namespace)?;
235
                if !valid_namespace.is_empty() {
236
                    updated_labels.push((labels::NAMESPACE.to_string(), valid_namespace));
237
238
                }
            }
239
240
241
242
        }
        if hierarchy.len() > 2 {
            let component = &hierarchy[2];
            if !component.is_empty() {
243
                let valid_component = sanitize_prometheus_label(component)?;
244
                if !valid_component.is_empty() {
245
                    updated_labels.push((labels::COMPONENT.to_string(), valid_component));
246
                }
247
248
249
250
251
            }
        }
        if hierarchy.len() > 3 {
            let endpoint = &hierarchy[3];
            if !endpoint.is_empty() {
252
                let valid_endpoint = sanitize_prometheus_label(endpoint)?;
253
                if !valid_endpoint.is_empty() {
254
                    updated_labels.push((labels::ENDPOINT.to_string(), valid_endpoint));
255
                }
256
257
258
259
260
261
262
263
264
265
            }
        }
    }

    // Add user labels
    updated_labels.extend(
        labels
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string())),
    );
266
    // Note: stored labels functionality has been removed
267
268

    // Handle different metric types
269
    let prometheus_metric = if std::any::TypeId::of::<T>()
270
        == std::any::TypeId::of::<prometheus::CounterVec>()
271
    {
272
273
274
275
276
277
278
279
280
281
282
283
284
285
        // Special handling for CounterVec with label names
        // const_labels parameter is required for CounterVec
        if buckets.is_some() {
            return Err(anyhow::anyhow!(
                "buckets parameter is not valid for CounterVec"
            ));
        }
        let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
        for (key, value) in &updated_labels {
            opts = opts.const_label(key.clone(), value.clone());
        }
        let label_names = const_labels
            .ok_or_else(|| anyhow::anyhow!("CounterVec requires const_labels parameter"))?;
        T::with_opts_and_label_names(opts, label_names)?
286
287
288
    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::GaugeVec>() {
        // Special handling for GaugeVec with label names
        // const_labels parameter is required for GaugeVec
289
290
        if buckets.is_some() {
            return Err(anyhow::anyhow!(
291
                "buckets parameter is not valid for GaugeVec"
292
293
294
295
296
297
298
            ));
        }
        let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
        for (key, value) in &updated_labels {
            opts = opts.const_label(key.clone(), value.clone());
        }
        let label_names = const_labels
299
            .ok_or_else(|| anyhow::anyhow!("GaugeVec requires const_labels parameter"))?;
300
        T::with_opts_and_label_names(opts, label_names)?
301
302
303
304
305
306
307
308
309
310
311
312
313
    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::Histogram>() {
        // Special handling for Histogram with custom buckets
        // buckets parameter is valid for Histogram, const_labels is not used
        if const_labels.is_some() {
            return Err(anyhow::anyhow!(
                "const_labels parameter is not valid for Histogram"
            ));
        }
        let mut opts = prometheus::HistogramOpts::new(&metric_name, metric_desc);
        for (key, value) in &updated_labels {
            opts = opts.const_label(key.clone(), value.clone());
        }
        T::with_histogram_opts_and_buckets(opts, buckets)?
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::IntCounterVec>() {
        // Special handling for IntCounterVec with label names
        // const_labels parameter is required for IntCounterVec
        if buckets.is_some() {
            return Err(anyhow::anyhow!(
                "buckets parameter is not valid for IntCounterVec"
            ));
        }
        let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
        for (key, value) in &updated_labels {
            opts = opts.const_label(key.clone(), value.clone());
        }
        let label_names = const_labels
            .ok_or_else(|| anyhow::anyhow!("IntCounterVec requires const_labels parameter"))?;
        T::with_opts_and_label_names(opts, label_names)?
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::IntGaugeVec>() {
        // Special handling for IntGaugeVec with label names
        // const_labels parameter is required for IntGaugeVec
        if buckets.is_some() {
            return Err(anyhow::anyhow!(
                "buckets parameter is not valid for IntGaugeVec"
            ));
        }
        let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
        for (key, value) in &updated_labels {
            opts = opts.const_label(key.clone(), value.clone());
        }
        let label_names = const_labels
            .ok_or_else(|| anyhow::anyhow!("IntGaugeVec requires const_labels parameter"))?;
        T::with_opts_and_label_names(opts, label_names)?
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
    } else {
        // Standard handling for Counter, IntCounter, Gauge, IntGauge
        // buckets and const_labels parameters are not valid for these types
        if buckets.is_some() {
            return Err(anyhow::anyhow!(
                "buckets parameter is not valid for Counter, IntCounter, Gauge, or IntGauge"
            ));
        }
        if const_labels.is_some() {
            return Err(anyhow::anyhow!(
                "const_labels parameter is not valid for Counter, IntCounter, Gauge, or IntGauge"
            ));
        }
        let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
        for (key, value) in &updated_labels {
            opts = opts.const_label(key.clone(), value.clone());
        }
        T::with_opts(opts)?
    };

    // Iterate over the DRT's registry and register this metric across all hierarchical levels.
365
366
367
    // The accumulated hierarchy is structured as: ["", "testnamespace", "testnamespace_testcomponent", "testnamespace_testcomponent_testendpoint"]
    // This accumulation is essential to differentiate between the names of children and grandchildren.
    // Build accumulated hierarchy and register metrics in a single loop
368
    // current_prefix accumulates the hierarchical path as we iterate through hierarchy
369
    // For example, if hierarchy = ["", "testnamespace", "testcomponent"], then:
370
    // - Iteration 1: current_prefix = "" (empty string from DRT)
371
372
    // - Iteration 2: current_prefix = "testnamespace"
    // - Iteration 3: current_prefix = "testnamespace_testcomponent"
373
    let mut current_hierarchy = String::new();
374
    for name in &hierarchy {
375
376
        if !current_hierarchy.is_empty() && !name.is_empty() {
            current_hierarchy.push('_');
377
        }
378
        current_hierarchy.push_str(name);
379

380
        // Register metric at this hierarchical level using the new helper function
381
        let collector: Box<dyn prometheus::core::Collector> = Box::new(prometheus_metric.clone());
382
383
        registry
            .drt()
384
            .add_prometheus_metric(&current_hierarchy, collector)?;
385
386
    }

387
    Ok(prometheus_metric)
388
389
390
391
392
}

/// This trait should be implemented by all metric registries, including Prometheus, Envy, OpenTelemetry, and others.
/// It offers a unified interface for creating and managing metrics, organizing sub-registries, and
/// generating output in Prometheus text format.
393
use crate::traits::DistributedRuntimeProvider;
394

395
396
397
pub trait MetricsRegistry: Send + Sync + DistributedRuntimeProvider {
    // Get the name of this registry (without any hierarchy prefix)
    fn basename(&self) -> String;
398

399
    /// Retrieve the complete hierarchy and basename for this registry. Currently, the hierarchy for drt is an empty string,
400
401
    /// so we must account for the leading underscore. The existing code remains unchanged to accommodate any future
    /// scenarios where drt's prefix might be assigned a value.
402
    fn hierarchy(&self) -> String {
403
404
405
406
407
408
409
        [self.parent_hierarchy(), vec![self.basename()]]
            .concat()
            .join("_")
            .trim_start_matches('_')
            .to_string()
    }

410
    // Get the parent hierarchy for this registry (just the base names, NOT the flattened hierarchy key)
411
412
413
414
415
416
    fn parent_hierarchy(&self) -> Vec<String>;

    // TODO: Add support for additional Prometheus metric types:
    // - Counter: ✅ IMPLEMENTED - create_counter()
    // - CounterVec: ✅ IMPLEMENTED - create_countervec()
    // - Gauge: ✅ IMPLEMENTED - create_gauge()
417
    // - GaugeHistogram: create_gauge_histogram() - for gauge histograms
418
419
420
    // - Histogram: ✅ IMPLEMENTED - create_histogram()
    // - HistogramVec with custom buckets: create_histogram_with_buckets()
    // - Info: create_info() - for info metrics with labels
421
422
423
424
    // - IntCounter: ✅ IMPLEMENTED - create_intcounter()
    // - IntCounterVec: ✅ IMPLEMENTED - create_intcountervec()
    // - IntGauge: ✅ IMPLEMENTED - create_intgauge()
    // - IntGaugeVec: ✅ IMPLEMENTED - create_intgaugevec()
425
    // - Stateset: create_stateset() - for state-based metrics
426
427
428
    // - Summary: create_summary() - for quantiles and sum/count metrics
    // - SummaryVec: create_summary_vec() - for labeled summaries
    // - Untyped: create_untyped() - for untyped metrics
429
430
431
    //
    // NOTE: The order of create_* methods below is mirrored in lib/bindings/python/rust/lib.rs::Metrics
    // Keep them synchronized when adding new metric types
432
433
434
435
436
437
438

    /// Create a Counter metric
    fn create_counter(
        &self,
        name: &str,
        description: &str,
        labels: &[(&str, &str)],
439
    ) -> anyhow::Result<prometheus::Counter> {
440
441
442
        create_metric(self, name, description, labels, None, None)
    }

443
444
    /// Create a CounterVec metric with label names (for dynamic labels)
    fn create_countervec(
445
446
447
        &self,
        name: &str,
        description: &str,
448
449
        const_labels: &[&str],
        const_label_values: &[(&str, &str)],
450
    ) -> anyhow::Result<prometheus::CounterVec> {
451
452
453
454
455
456
457
458
        create_metric(
            self,
            name,
            description,
            const_label_values,
            None,
            Some(const_labels),
        )
459
460
    }

461
462
    /// Create a Gauge metric
    fn create_gauge(
463
464
465
466
        &self,
        name: &str,
        description: &str,
        labels: &[(&str, &str)],
467
    ) -> anyhow::Result<prometheus::Gauge> {
468
469
470
        create_metric(self, name, description, labels, None, None)
    }

471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
    /// Create a GaugeVec metric with label names (for dynamic labels)
    fn create_gaugevec(
        &self,
        name: &str,
        description: &str,
        const_labels: &[&str],
        const_label_values: &[(&str, &str)],
    ) -> anyhow::Result<prometheus::GaugeVec> {
        create_metric(
            self,
            name,
            description,
            const_label_values,
            None,
            Some(const_labels),
        )
    }

489
490
491
492
493
494
495
    /// Create a Histogram metric with custom buckets
    fn create_histogram(
        &self,
        name: &str,
        description: &str,
        labels: &[(&str, &str)],
        buckets: Option<Vec<f64>>,
496
    ) -> anyhow::Result<prometheus::Histogram> {
497
498
499
        create_metric(self, name, description, labels, buckets, None)
    }

500
501
502
503
504
505
    /// Create an IntCounter metric
    fn create_intcounter(
        &self,
        name: &str,
        description: &str,
        labels: &[(&str, &str)],
506
    ) -> anyhow::Result<prometheus::IntCounter> {
507
508
509
510
511
        create_metric(self, name, description, labels, None, None)
    }

    /// Create an IntCounterVec metric with label names (for dynamic labels)
    fn create_intcountervec(
512
513
514
515
516
        &self,
        name: &str,
        description: &str,
        const_labels: &[&str],
        const_label_values: &[(&str, &str)],
517
    ) -> anyhow::Result<prometheus::IntCounterVec> {
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
        create_metric(
            self,
            name,
            description,
            const_label_values,
            None,
            Some(const_labels),
        )
    }

    /// Create an IntGauge metric
    fn create_intgauge(
        &self,
        name: &str,
        description: &str,
        labels: &[(&str, &str)],
534
    ) -> anyhow::Result<prometheus::IntGauge> {
535
536
537
538
539
540
541
542
543
544
        create_metric(self, name, description, labels, None, None)
    }

    /// Create an IntGaugeVec metric with label names (for dynamic labels)
    fn create_intgaugevec(
        &self,
        name: &str,
        description: &str,
        const_labels: &[&str],
        const_label_values: &[(&str, &str)],
545
    ) -> anyhow::Result<prometheus::IntGaugeVec> {
546
547
548
549
550
551
552
553
554
555
556
        create_metric(
            self,
            name,
            description,
            const_label_values,
            None,
            Some(const_labels),
        )
    }

    /// Get metrics in Prometheus text format
557
    fn prometheus_expfmt(&self) -> anyhow::Result<String> {
558
        // Execute callbacks first to ensure any new metrics are added to the registry
559
560
561
        let callback_results = self
            .drt()
            .execute_prometheus_update_callbacks(&self.hierarchy());
562
563
564
565
566
567
568
569

        // Log any callback errors but continue
        for result in callback_results {
            if let Err(e) = result {
                tracing::error!("Error executing metrics callback: {}", e);
            }
        }

570
571
        // Get the Prometheus registry for this hierarchy and execute exposition text callbacks
        let (prometheus_registry, expfmt) = {
572
            let mut registry_entry = self.drt().hierarchy_to_metricsregistry.write().unwrap();
573
574
575
576
            let entry = registry_entry.entry(self.hierarchy()).or_default();
            let registry = entry.prometheus_registry.clone();
            let text = entry.execute_prometheus_expfmt_callbacks();
            (registry, text)
577
        };
578
579

        // Encode metrics from the registry
580
581
582
583
        let metric_families = prometheus_registry.gather();
        let encoder = prometheus::TextEncoder::new();
        let mut buffer = Vec::new();
        encoder.encode(&metric_families, &mut buffer)?;
584
585
586
587
588
589
590
591
592
593
594
        let mut result = String::from_utf8(buffer)?;

        // Append exposition text callback results if any
        if !expfmt.is_empty() {
            if !result.ends_with('\n') {
                result.push('\n');
            }
            result.push_str(&expfmt);
        }

        Ok(result)
595
596
597
598
    }
}

#[cfg(test)]
599
600
mod test_helpers {
    use super::prometheus_names::name_prefix;
601
    use super::prometheus_names::{nats_client, nats_service};
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
    use super::*;

    /// Base function to filter Prometheus output lines based on a predicate.
    /// Returns lines that match the predicate, converted to String.
    fn filter_prometheus_lines<F>(input: &str, mut predicate: F) -> Vec<String>
    where
        F: FnMut(&str) -> bool,
    {
        input
            .lines()
            .filter(|line| predicate(line))
            .map(|line| line.to_string())
            .collect::<Vec<_>>()
    }

    /// Filters out all NATS metrics from Prometheus output for test comparisons.
    pub fn remove_nats_lines(input: &str) -> Vec<String> {
        filter_prometheus_lines(input, |line| {
            !line.contains(&format!(
621
                "{}_{}",
622
                name_prefix::COMPONENT,
623
624
                nats_client::PREFIX
            )) && !line.contains(&format!(
625
                "{}_{}",
626
627
                name_prefix::COMPONENT,
                nats_service::PREFIX
628
629
630
631
632
633
634
635
            )) && !line.trim().is_empty()
        })
    }

    /// Filters to only include NATS metrics from Prometheus output for test comparisons.
    pub fn extract_nats_lines(input: &str) -> Vec<String> {
        filter_prometheus_lines(input, |line| {
            line.contains(&format!(
636
                "{}_{}",
637
                name_prefix::COMPONENT,
638
639
                nats_client::PREFIX
            )) || line.contains(&format!(
640
                "{}_{}",
641
642
                name_prefix::COMPONENT,
                nats_service::PREFIX
643
644
645
646
647
648
649
650
            ))
        })
    }

    /// Extracts all component metrics (excluding help text and type definitions).
    /// Returns only the actual metric lines with values.
    pub fn extract_metrics(input: &str) -> Vec<String> {
        filter_prometheus_lines(input, |line| {
651
            line.starts_with(&format!("{}_", name_prefix::COMPONENT))
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
                && !line.starts_with("#")
                && !line.trim().is_empty()
        })
    }

    /// Parses a Prometheus metric line and extracts the name, labels, and value.
    /// Used instead of fetching metrics directly to test end-to-end results, not intermediate state.
    ///
    /// # Example
    /// ```
    /// let line = "http_requests_total{method=\"GET\"} 1234";
    /// let (name, labels, value) = parse_prometheus_metric(line).unwrap();
    /// assert_eq!(name, "http_requests_total");
    /// assert_eq!(labels.get("method"), Some(&"GET".to_string()));
    /// assert_eq!(value, 1234.0);
    /// ```
    pub fn parse_prometheus_metric(
        line: &str,
    ) -> Option<(String, std::collections::HashMap<String, String>, f64)> {
        if line.trim().is_empty() || line.starts_with('#') {
            return None;
        }

        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() < 2 {
            return None;
        }

        let metric_part = parts[0];
        let value: f64 = parts[1].parse().ok()?;

        let (name, labels) = if metric_part.contains('{') {
            let brace_start = metric_part.find('{').unwrap();
            let brace_end = metric_part.rfind('}').unwrap_or(metric_part.len());
            let name = &metric_part[..brace_start];
            let labels_str = &metric_part[brace_start + 1..brace_end];

            let mut labels = std::collections::HashMap::new();
            for pair in labels_str.split(',') {
                if let Some((k, v)) = pair.split_once('=') {
                    let v = v.trim_matches('"');
                    labels.insert(k.trim().to_string(), v.to_string());
                }
            }
            (name.to_string(), labels)
        } else {
            (metric_part.to_string(), std::collections::HashMap::new())
        };

        Some((name, labels, value))
    }
703
704
}

705
#[cfg(test)]
706
mod test_metricsregistry_units {
707
708
709
    use super::*;

    #[test]
710
711
712
    fn test_build_component_metric_name_with_prefix() {
        // Test that build_component_metric_name correctly prepends the dynamo_component prefix
        let result = build_component_metric_name("requests");
713
        assert_eq!(result, "dynamo_component_requests");
714

715
        let result = build_component_metric_name("counter");
716
        assert_eq!(result, "dynamo_component_counter");
717
718
    }

719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
    #[test]
    fn test_parse_prometheus_metric() {
        use super::test_helpers::parse_prometheus_metric;
        use std::collections::HashMap;

        // Test parsing a metric with labels
        let line = "http_requests_total{method=\"GET\",status=\"200\"} 1234";
        let parsed = parse_prometheus_metric(line);
        assert!(parsed.is_some());

        let (name, labels, value) = parsed.unwrap();
        assert_eq!(name, "http_requests_total");

        let mut expected_labels = HashMap::new();
        expected_labels.insert("method".to_string(), "GET".to_string());
        expected_labels.insert("status".to_string(), "200".to_string());
        assert_eq!(labels, expected_labels);

        assert_eq!(value, 1234.0);

        // Test parsing a metric without labels
        let line = "cpu_usage 98.5";
        let parsed = parse_prometheus_metric(line);
        assert!(parsed.is_some());

        let (name, labels, value) = parsed.unwrap();
        assert_eq!(name, "cpu_usage");
        assert!(labels.is_empty());
        assert_eq!(value, 98.5);
748

749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
        // Test parsing a metric with float value
        let line = "response_time{service=\"api\"} 0.123";
        let parsed = parse_prometheus_metric(line);
        assert!(parsed.is_some());

        let (name, labels, value) = parsed.unwrap();
        assert_eq!(name, "response_time");

        let mut expected_labels = HashMap::new();
        expected_labels.insert("service".to_string(), "api".to_string());
        assert_eq!(labels, expected_labels);

        assert_eq!(value, 0.123);

        // Test parsing invalid lines
        assert!(parse_prometheus_metric("").is_none()); // Empty line
        assert!(parse_prometheus_metric("# HELP metric description").is_none()); // Help text
        assert!(parse_prometheus_metric("# TYPE metric counter").is_none()); // Type definition
        assert!(parse_prometheus_metric("metric_name").is_none()); // No value

        println!("✓ Prometheus metric parsing works correctly!");
    }

772
    #[test]
773
774
775
    fn test_metrics_registry_entry_callbacks() {
        use crate::MetricsRegistryEntry;
        use std::sync::atomic::{AtomicUsize, Ordering};
776

777
778
779
780
781
782
783
784
        // Test 1: Basic callback execution with counter increments
        {
            let mut entry = MetricsRegistryEntry::new();
            let counter = Arc::new(AtomicUsize::new(0));

            // Add callbacks with different increment values
            for increment in [1, 10, 100] {
                let counter_clone = counter.clone();
785
                entry.add_prometheus_update_callback(Arc::new(move || {
786
787
788
789
                    counter_clone.fetch_add(increment, Ordering::SeqCst);
                    Ok(())
                }));
            }
790

791
792
            // Verify counter starts at 0
            assert_eq!(counter.load(Ordering::SeqCst), 0);
793

794
            // First execution
795
            let results = entry.execute_prometheus_update_callbacks();
796
797
798
            assert_eq!(results.len(), 3);
            assert!(results.iter().all(|r| r.is_ok()));
            assert_eq!(counter.load(Ordering::SeqCst), 111); // 1 + 10 + 100
799

800
            // Second execution - callbacks should be reusable
801
            let results = entry.execute_prometheus_update_callbacks();
802
803
            assert_eq!(results.len(), 3);
            assert_eq!(counter.load(Ordering::SeqCst), 222); // 111 + 111
804

805
806
            // Test cloning - cloned entry should have no callbacks
            let cloned = entry.clone();
807
            assert_eq!(cloned.execute_prometheus_update_callbacks().len(), 0);
808
            assert_eq!(counter.load(Ordering::SeqCst), 222); // No change
809

810
            // Original still has callbacks
811
            entry.execute_prometheus_update_callbacks();
812
813
            assert_eq!(counter.load(Ordering::SeqCst), 333); // 222 + 111
        }
814

815
816
817
818
819
820
821
        // Test 2: Mixed success and error callbacks
        {
            let mut entry = MetricsRegistryEntry::new();
            let counter = Arc::new(AtomicUsize::new(0));

            // Successful callback
            let counter_clone = counter.clone();
822
            entry.add_prometheus_update_callback(Arc::new(move || {
823
824
825
826
827
                counter_clone.fetch_add(1, Ordering::SeqCst);
                Ok(())
            }));

            // Error callback
828
829
830
            entry.add_prometheus_update_callback(Arc::new(|| {
                Err(anyhow::anyhow!("Simulated error"))
            }));
831
832
833

            // Another successful callback
            let counter_clone = counter.clone();
834
            entry.add_prometheus_update_callback(Arc::new(move || {
835
836
837
838
839
                counter_clone.fetch_add(10, Ordering::SeqCst);
                Ok(())
            }));

            // Execute and verify mixed results
840
            let results = entry.execute_prometheus_update_callbacks();
841
842
843
844
845
846
847
848
849
850
            assert_eq!(results.len(), 3);
            assert!(results[0].is_ok());
            assert!(results[1].is_err());
            assert!(results[2].is_ok());

            // Verify error message
            assert_eq!(
                results[1].as_ref().unwrap_err().to_string(),
                "Simulated error"
            );
851

852
853
            // Verify successful callbacks still executed
            assert_eq!(counter.load(Ordering::SeqCst), 11); // 1 + 10
854

855
            // Execute again - errors should be consistent
856
            let results = entry.execute_prometheus_update_callbacks();
857
858
859
            assert!(results[1].is_err());
            assert_eq!(counter.load(Ordering::SeqCst), 22); // 11 + 11
        }
860

861
862
863
        // Test 3: Empty registry
        {
            let entry = MetricsRegistryEntry::new();
864
            let results = entry.execute_prometheus_update_callbacks();
865
866
867
868
            assert_eq!(results.len(), 0);
        }
    }
}
869

870
871
872
873
#[cfg(feature = "integration")]
#[cfg(test)]
mod test_metricsregistry_prefixes {
    use super::*;
874
    use crate::distributed::distributed_test_utils::create_test_drt_async;
875
876
    use prometheus::core::Collector;

877
878
    #[tokio::test]
    async fn test_hierarchical_prefixes_and_parent_hierarchies() {
879
        let drt = create_test_drt_async().await;
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900

        const DRT_NAME: &str = "";
        const NAMESPACE_NAME: &str = "ns901";
        const COMPONENT_NAME: &str = "comp901";
        const ENDPOINT_NAME: &str = "ep901";
        let namespace = drt.namespace(NAMESPACE_NAME).unwrap();
        let component = namespace.component(COMPONENT_NAME).unwrap();
        let endpoint = component.endpoint(ENDPOINT_NAME);

        // DRT
        assert_eq!(drt.basename(), DRT_NAME);
        assert_eq!(drt.parent_hierarchy(), Vec::<String>::new());
        assert_eq!(drt.hierarchy(), DRT_NAME);

        // Namespace
        assert_eq!(namespace.basename(), NAMESPACE_NAME);
        assert_eq!(namespace.parent_hierarchy(), vec!["".to_string()]);
        assert_eq!(namespace.hierarchy(), NAMESPACE_NAME);

        // Component
        assert_eq!(component.basename(), COMPONENT_NAME);
901
902
        assert_eq!(
            component.parent_hierarchy(),
903
            vec!["".to_string(), NAMESPACE_NAME.to_string()]
904
905
        );
        assert_eq!(
906
907
            component.hierarchy(),
            format!("{}_{}", NAMESPACE_NAME, COMPONENT_NAME)
908
909
        );

910
911
        // Endpoint
        assert_eq!(endpoint.basename(), ENDPOINT_NAME);
912
913
        assert_eq!(
            endpoint.parent_hierarchy(),
914
915
916
917
918
            vec![
                "".to_string(),
                NAMESPACE_NAME.to_string(),
                COMPONENT_NAME.to_string(),
            ]
919
920
        );
        assert_eq!(
921
922
            endpoint.hierarchy(),
            format!("{}_{}_{}", NAMESPACE_NAME, COMPONENT_NAME, ENDPOINT_NAME)
923
924
        );

925
926
927
928
        // Relationships
        assert!(namespace.parent_hierarchy().contains(&drt.basename()));
        assert!(component.parent_hierarchy().contains(&namespace.basename()));
        assert!(endpoint.parent_hierarchy().contains(&component.basename()));
929

930
931
932
933
934
        // Depth
        assert_eq!(drt.parent_hierarchy().len(), 0);
        assert_eq!(namespace.parent_hierarchy().len(), 1);
        assert_eq!(component.parent_hierarchy().len(), 2);
        assert_eq!(endpoint.parent_hierarchy().len(), 3);
935

936
937
938
        // Invalid namespace behavior - sanitizes to "_123" and succeeds
        // @ryanolson intended to enable validation (see TODO comment in component.rs) but didn't turn it on,
        // so invalid characters are sanitized in MetricsRegistry rather than rejected.
939
940
        let invalid_namespace = drt.namespace("@@123").unwrap();
        let result = invalid_namespace.create_counter("test_counter", "A test counter", &[]);
941
942
943
944
945
946
947
948
949
950
        assert!(result.is_ok());
        if let Ok(counter) = &result {
            // Verify the namespace was sanitized to "_123" in the label
            let desc = counter.desc();
            let namespace_label = desc[0]
                .const_label_pairs
                .iter()
                .find(|l| l.name() == "dynamo_namespace")
                .expect("Should have dynamo_namespace label");
            assert_eq!(namespace_label.value(), "_123");
951
        }
952

953
954
        // Valid namespace works
        let valid_namespace = drt.namespace("ns567").unwrap();
955
956
957
958
959
        assert!(
            valid_namespace
                .create_counter("test_counter", "A test counter", &[])
                .is_ok()
        );
960
    }
961

962
963
    #[tokio::test]
    async fn test_recursive_namespace() {
964
        // Create a distributed runtime for testing
965
        let drt = create_test_drt_async().await;
966

967
968
969
970
        // Create a deeply chained namespace: ns1.ns2.ns3
        let ns1 = drt.namespace("ns1").unwrap();
        let ns2 = ns1.namespace("ns2").unwrap();
        let ns3 = ns2.namespace("ns3").unwrap();
971

972
973
        // Create a component in the deepest namespace
        let component = ns3.component("test-component").unwrap();
974

975
976
977
978
979
980
981
982
983
        // Verify the hierarchy structure
        assert_eq!(ns1.basename(), "ns1");
        assert_eq!(ns1.parent_hierarchy(), vec!("".to_string()));
        assert_eq!(ns1.hierarchy(), "ns1");

        assert_eq!(ns2.basename(), "ns2");
        assert_eq!(
            ns2.parent_hierarchy(),
            vec!["".to_string(), "ns1".to_string()]
984
        );
985
        assert_eq!(ns2.hierarchy(), "ns1_ns2");
986

987
988
989
990
991
992
        assert_eq!(ns3.basename(), "ns3");
        assert_eq!(
            ns3.parent_hierarchy(),
            vec!["".to_string(), "ns1".to_string(), "ns2".to_string()]
        );
        assert_eq!(ns3.hierarchy(), "ns1_ns2_ns3");
993

994
995
996
997
998
999
1000
1001
1002
        assert_eq!(component.basename(), "test-component");
        assert_eq!(
            component.parent_hierarchy(),
            vec![
                "".to_string(),
                "ns1".to_string(),
                "ns2".to_string(),
                "ns3".to_string()
            ]
1003
        );
1004
        assert_eq!(component.hierarchy(), "ns1_ns2_ns3_test-component");
1005

1006
        println!("✓ Chained namespace test passed - all prefixes correct");
1007
1008
1009
1010
1011
    }
}

#[cfg(feature = "integration")]
#[cfg(test)]
1012
1013
1014
mod test_metricsregistry_prometheus_fmt_outputs {
    use super::prometheus_names::name_prefix;
    use super::prometheus_names::{COMPONENT_NATS_METRICS, DRT_NATS_METRICS};
1015
    use super::prometheus_names::{nats_client, nats_service};
1016
    use super::*;
1017
    use crate::distributed::distributed_test_utils::create_test_drt_async;
1018
1019
1020
    use prometheus::Counter;
    use std::sync::Arc;

1021
1022
    #[tokio::test]
    async fn test_prometheusfactory_using_metrics_registry_trait() {
1023
        // Setup real DRT and registry using the test-friendly constructor
1024
        let drt = create_test_drt_async().await;
1025

1026
        // Use a simple constant namespace name
1027
        let namespace_name = "ns345";
1028

1029
        let namespace = drt.namespace(namespace_name).unwrap();
1030
1031
        let component = namespace.component("comp345").unwrap();
        let endpoint = component.endpoint("ep345");
1032
1033
1034

        // Test Counter creation
        let counter = endpoint
1035
            .create_counter("testcounter", "A test counter", &[])
1036
1037
1038
1039
1040
            .unwrap();
        counter.inc_by(123.456789);
        let epsilon = 0.01;
        assert!((counter.get() - 123.456789).abs() < epsilon);

1041
        let endpoint_output_raw = endpoint.prometheus_expfmt().unwrap();
1042
        println!("Endpoint output:");
1043
1044
1045
1046
1047
        println!("{}", endpoint_output_raw);

        // Filter out NATS service metrics for test comparison
        let endpoint_output =
            super::test_helpers::remove_nats_lines(&endpoint_output_raw).join("\n");
1048

1049
        let expected_endpoint_output = r#"# HELP dynamo_component_testcounter A test counter
1050
# TYPE dynamo_component_testcounter counter
1051
dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789"#.to_string();
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063

        assert_eq!(
            endpoint_output, expected_endpoint_output,
            "\n=== ENDPOINT COMPARISON FAILED ===\n\
             Expected:\n{}\n\
             Actual:\n{}\n\
             ==============================",
            expected_endpoint_output, endpoint_output
        );

        // Test Gauge creation
        let gauge = component
1064
            .create_gauge("testgauge", "A test gauge", &[])
1065
1066
1067
1068
1069
            .unwrap();
        gauge.set(50000.0);
        assert_eq!(gauge.get(), 50000.0);

        // Test Prometheus format output for Component (gauge + histogram)
1070
        let component_output_raw = component.prometheus_expfmt().unwrap();
1071
        println!("Component output:");
1072
1073
1074
1075
1076
        println!("{}", component_output_raw);

        // Filter out NATS service metrics for test comparison
        let component_output =
            super::test_helpers::remove_nats_lines(&component_output_raw).join("\n");
1077

1078
        let expected_component_output = r#"# HELP dynamo_component_testcounter A test counter
1079
# TYPE dynamo_component_testcounter counter
1080
dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789
1081
1082
# HELP dynamo_component_testgauge A test gauge
# TYPE dynamo_component_testgauge gauge
1083
dynamo_component_testgauge{dynamo_component="comp345",dynamo_namespace="ns345"} 50000"#.to_string();
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094

        assert_eq!(
            component_output, expected_component_output,
            "\n=== COMPONENT COMPARISON FAILED ===\n\
             Expected:\n{}\n\
             Actual:\n{}\n\
             ==============================",
            expected_component_output, component_output
        );

        let intcounter = namespace
1095
            .create_intcounter("testintcounter", "A test int counter", &[])
1096
1097
1098
1099
1100
            .unwrap();
        intcounter.inc_by(12345);
        assert_eq!(intcounter.get(), 12345);

        // Test Prometheus format output for Namespace (int_counter + gauge + histogram)
1101
        let namespace_output_raw = namespace.prometheus_expfmt().unwrap();
1102
        println!("Namespace output:");
1103
1104
1105
1106
1107
        println!("{}", namespace_output_raw);

        // Filter out NATS service metrics for test comparison
        let namespace_output =
            super::test_helpers::remove_nats_lines(&namespace_output_raw).join("\n");
1108

1109
        let expected_namespace_output = r#"# HELP dynamo_component_testcounter A test counter
1110
# TYPE dynamo_component_testcounter counter
1111
dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789
1112
1113
# HELP dynamo_component_testgauge A test gauge
# TYPE dynamo_component_testgauge gauge
1114
dynamo_component_testgauge{dynamo_component="comp345",dynamo_namespace="ns345"} 50000
1115
1116
# HELP dynamo_component_testintcounter A test int counter
# TYPE dynamo_component_testintcounter counter
1117
dynamo_component_testintcounter{dynamo_namespace="ns345"} 12345"#.to_string();
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128

        assert_eq!(
            namespace_output, expected_namespace_output,
            "\n=== NAMESPACE COMPARISON FAILED ===\n\
             Expected:\n{}\n\
             Actual:\n{}\n\
             ==============================",
            expected_namespace_output, namespace_output
        );

        // Test IntGauge creation
1129
        let intgauge = namespace
1130
            .create_intgauge("testintgauge", "A test int gauge", &[])
1131
1132
1133
1134
1135
            .unwrap();
        intgauge.set(42);
        assert_eq!(intgauge.get(), 42);

        // Test IntGaugeVec creation
1136
        let intgaugevec = namespace
1137
            .create_intgaugevec(
1138
                "testintgaugevec",
1139
                "A test int gauge vector",
1140
                &["instance", "status"],
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
                &[("service", "api")],
            )
            .unwrap();
        intgaugevec
            .with_label_values(&["server1", "active"])
            .set(10);
        intgaugevec
            .with_label_values(&["server2", "inactive"])
            .set(0);

1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
        // Test CounterVec creation
        let countervec = endpoint
            .create_countervec(
                "testcountervec",
                "A test counter vector",
                &["method", "status"],
                &[("service", "api")],
            )
            .unwrap();
        countervec.with_label_values(&["GET", "200"]).inc_by(10.0);
        countervec.with_label_values(&["POST", "201"]).inc_by(5.0);

        // Test Histogram creation
        let histogram = component
            .create_histogram("testhistogram", "A test histogram", &[], None)
            .unwrap();
        histogram.observe(1.0);
        histogram.observe(2.5);
        histogram.observe(4.0);

        // Test Prometheus format output for DRT (all metrics combined)
1172
        let drt_output_raw = drt.prometheus_expfmt().unwrap();
1173
        println!("DRT output:");
1174
1175
1176
1177
1178
        println!("{}", drt_output_raw);

        // Filter out all NATS metrics for comparison
        let filtered_drt_output =
            super::test_helpers::remove_nats_lines(&drt_output_raw).join("\n");
1179

1180
        let expected_drt_output = r#"# HELP dynamo_component_testcounter A test counter
1181
# TYPE dynamo_component_testcounter counter
1182
dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789
1183
1184
# HELP dynamo_component_testcountervec A test counter vector
# TYPE dynamo_component_testcountervec counter
1185
1186
dynamo_component_testcountervec{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345",method="GET",service="api",status="200"} 10
dynamo_component_testcountervec{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345",method="POST",service="api",status="201"} 5
1187
1188
# HELP dynamo_component_testgauge A test gauge
# TYPE dynamo_component_testgauge gauge
1189
dynamo_component_testgauge{dynamo_component="comp345",dynamo_namespace="ns345"} 50000
1190
1191
# HELP dynamo_component_testhistogram A test histogram
# TYPE dynamo_component_testhistogram histogram
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.005"} 0
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.01"} 0
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.025"} 0
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.05"} 0
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.1"} 0
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.25"} 0
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.5"} 0
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="1"} 1
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="2.5"} 2
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="5"} 3
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="10"} 3
dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="+Inf"} 3
dynamo_component_testhistogram_sum{dynamo_component="comp345",dynamo_namespace="ns345"} 7.5
dynamo_component_testhistogram_count{dynamo_component="comp345",dynamo_namespace="ns345"} 3
1206
1207
# HELP dynamo_component_testintcounter A test int counter
# TYPE dynamo_component_testintcounter counter
1208
dynamo_component_testintcounter{dynamo_namespace="ns345"} 12345
1209
1210
# HELP dynamo_component_testintgauge A test int gauge
# TYPE dynamo_component_testintgauge gauge
1211
dynamo_component_testintgauge{dynamo_namespace="ns345"} 42
1212
1213
# HELP dynamo_component_testintgaugevec A test int gauge vector
# TYPE dynamo_component_testintgaugevec gauge
1214
dynamo_component_testintgaugevec{dynamo_namespace="ns345",instance="server1",service="api",status="active"} 10
1215
1216
1217
1218
dynamo_component_testintgaugevec{dynamo_namespace="ns345",instance="server2",service="api",status="inactive"} 0
# HELP dynamo_component_uptime_seconds Total uptime of the DistributedRuntime in seconds
# TYPE dynamo_component_uptime_seconds gauge
dynamo_component_uptime_seconds 0"#.to_string();
1219
1220

        assert_eq!(
1221
            filtered_drt_output, expected_drt_output,
1222
1223
            "\n=== DRT COMPARISON FAILED ===\n\
             Expected:\n{}\n\
1224
             Actual (filtered):\n{}\n\
1225
             ==============================",
1226
            expected_drt_output, filtered_drt_output
1227
1228
1229
1230
        );

        println!("✓ All Prometheus format outputs verified successfully!");
    }
1231
1232
1233
1234
1235
1236
1237

    #[test]
    fn test_refactored_filter_functions() {
        // Test data with mixed content
        let test_input = r#"# HELP dynamo_component_requests Total requests
# TYPE dynamo_component_requests counter
dynamo_component_requests 42
1238
1239
1240
# HELP dynamo_component_nats_client_connection_state Connection state
# TYPE dynamo_component_nats_client_connection_state gauge
dynamo_component_nats_client_connection_state 1
1241
1242
1243
1244
# HELP dynamo_component_latency Response latency
# TYPE dynamo_component_latency histogram
dynamo_component_latency_bucket{le="0.1"} 10
dynamo_component_latency_bucket{le="0.5"} 25
1245
1246
dynamo_component_nats_service_requests_total 100
dynamo_component_nats_service_errors_total 5"#;
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260

        // Test remove_nats_lines (excludes NATS lines but keeps help/type)
        let filtered_out = super::test_helpers::remove_nats_lines(test_input);
        assert_eq!(filtered_out.len(), 7); // 7 non-NATS lines
        assert!(!filtered_out.iter().any(|line| line.contains("nats")));

        // Test extract_nats_lines (includes all NATS lines including help/type)
        let filtered_only = super::test_helpers::extract_nats_lines(test_input);
        assert_eq!(filtered_only.len(), 5); // 5 NATS lines
        assert!(filtered_only.iter().all(|line| line.contains("nats")));

        // Test extract_metrics (only actual metric lines, excluding help/type)
        let metrics_only = super::test_helpers::extract_metrics(test_input);
        assert_eq!(metrics_only.len(), 6); // 6 actual metric lines (excluding help/type)
1261
1262
1263
1264
1265
        assert!(
            metrics_only
                .iter()
                .all(|line| line.starts_with("dynamo_component") && !line.starts_with("#"))
        );
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275

        println!("✓ All refactored filter functions work correctly!");
    }
}

#[cfg(feature = "integration")]
#[cfg(test)]
mod test_metricsregistry_nats {
    use super::prometheus_names::name_prefix;
    use super::prometheus_names::{COMPONENT_NATS_METRICS, DRT_NATS_METRICS};
1276
    use super::prometheus_names::{nats_client, nats_service};
1277
    use super::*;
1278
    use crate::distributed::distributed_test_utils::create_test_drt_async;
1279
1280
    use crate::pipeline::PushRouter;
    use crate::{DistributedRuntime, Runtime};
1281
    use tokio::time::{Duration, sleep};
1282
1283
    #[tokio::test]
    async fn test_drt_nats_metrics() {
1284
        // Setup real DRT and registry using the test-friendly constructor
1285
        let drt = create_test_drt_async().await;
1286
1287

        // Get DRT output which should include NATS client metrics
1288
        let drt_output = drt.prometheus_expfmt().unwrap();
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
        println!("DRT output with NATS metrics:");
        println!("{}", drt_output);

        // Additional checks for NATS client metrics (without checking specific values)
        let drt_nats_metrics = super::test_helpers::extract_nats_lines(&drt_output);

        // Check that NATS client metrics are present
        assert!(
            !drt_nats_metrics.is_empty(),
            "NATS client metrics should be present"
        );

        // Check for specific NATS client metric names (without values)
1302
1303
1304
1305
        // Extract only the metric lines from the already-filtered NATS metrics
        let drt_nats_metric_lines =
            super::test_helpers::extract_metrics(&drt_nats_metrics.join("\n"));
        let actual_drt_nats_metrics_sorted: Vec<&str> = drt_nats_metric_lines
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
            .iter()
            .map(|line| {
                let without_labels = line.split('{').next().unwrap_or(line);
                // Remove the value part (everything after the last space)
                without_labels.split(' ').next().unwrap_or(without_labels)
            })
            .collect();

        let expect_drt_nats_metrics_sorted = {
            let mut temp = DRT_NATS_METRICS
                .iter()
1317
                .map(|metric| build_component_metric_name(metric))
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
                .collect::<Vec<_>>();
            temp.sort();
            temp
        };

        // Print both lists for comparison
        println!(
            "actual_drt_nats_metrics_sorted: {:?}",
            actual_drt_nats_metrics_sorted
        );
        println!(
            "expect_drt_nats_metrics_sorted: {:?}",
            expect_drt_nats_metrics_sorted
        );

        // Compare the sorted lists
        assert_eq!(
1335
            actual_drt_nats_metrics_sorted, expect_drt_nats_metrics_sorted,
1336
1337
1338
1339
1340
1341
            "DRT_NATS_METRICS with prefix and expected_nats_metrics should be identical when sorted"
        );

        println!("✓ DistributedRuntime NATS metrics integration test passed!");
    }

1342
1343
    #[tokio::test]
    async fn test_nats_metric_names() {
1344
1345
1346
1347
        // This test only tests the existence of the NATS metrics. It does not check
        // the values of the metrics.

        // Setup real DRT and registry using the test-friendly constructor
1348
        let drt = create_test_drt_async().await;
1349

1350
        // Create a namespace and component from the DRT
1351
        let namespace = drt.namespace("ns789").unwrap();
1352
        let mut component = namespace.component("comp789").unwrap();
1353

1354
        // Create a service to trigger metrics callback registration
1355
        component.add_stats_service().await.unwrap();
1356

1357
        // Get component output which should include NATS client metrics
1358
1359
        // Additional checks for NATS client metrics (without checking specific values)
        let component_nats_metrics =
1360
            super::test_helpers::extract_nats_lines(&component.prometheus_expfmt().unwrap());
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
        println!(
            "Component NATS metrics count: {}",
            component_nats_metrics.len()
        );

        // Check that NATS client metrics are present
        assert!(
            !component_nats_metrics.is_empty(),
            "NATS client metrics should be present"
        );

        // Check for specific NATS client metric names (without values)
        let component_metrics =
1374
            super::test_helpers::extract_metrics(&component.prometheus_expfmt().unwrap());
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
        let actual_component_nats_metrics_sorted: Vec<&str> = component_metrics
            .iter()
            .map(|line| {
                let without_labels = line.split('{').next().unwrap_or(line);
                // Remove the value part (everything after the last space)
                without_labels.split(' ').next().unwrap_or(without_labels)
            })
            .collect();

        let expect_component_nats_metrics_sorted = {
            let mut temp = COMPONENT_NATS_METRICS
                .iter()
1387
                .map(|metric| build_component_metric_name(metric))
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
                .collect::<Vec<_>>();
            temp.sort();
            temp
        };

        // Print both lists for comparison
        println!(
            "actual_component_nats_metrics_sorted: {:?}",
            actual_component_nats_metrics_sorted
        );
        println!(
            "expect_component_nats_metrics_sorted: {:?}",
            expect_component_nats_metrics_sorted
        );

        // Compare the sorted lists
        assert_eq!(
1405
            actual_component_nats_metrics_sorted, expect_component_nats_metrics_sorted,
1406
1407
1408
            "COMPONENT_NATS_METRICS with prefix and expected_nats_metrics should be identical when sorted"
        );

1409
        // Get both DRT and component output and filter for NATS metrics only
1410
        let drt_output = drt.prometheus_expfmt().unwrap();
1411
1412
1413
        let drt_nats_lines = super::test_helpers::extract_nats_lines(&drt_output);
        let drt_and_component_nats_metrics =
            super::test_helpers::extract_metrics(&drt_nats_lines.join("\n"));
1414
        println!(
1415
1416
            "DRT and component NATS metrics count: {}",
            drt_and_component_nats_metrics.len()
1417
1418
1419
1420
        );

        // Check that the NATS metrics are present in the component output
        assert_eq!(
1421
            drt_and_component_nats_metrics.len(),
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
            DRT_NATS_METRICS.len() + COMPONENT_NATS_METRICS.len(),
            "DRT at this point should have both the DRT and component NATS metrics"
        );

        // Check that the NATS metrics are present in the component output
        println!("✓ Component NATS metrics integration test passed!");
    }

    /// Tests NATS metrics values before and after endpoint activity with large message processing.
    /// Creates endpoint, sends test messages + 10k byte message, validates metrics (NATS + work handler)
    /// at initial state and post-activity state. Ensures byte thresholds, message counts, and processing
    /// times are within expected ranges. Tests end-to-end client-server communication and metrics collection.
    #[tokio::test]
    async fn test_nats_metrics_values() -> anyhow::Result<()> {
        struct MessageHandler {}
        impl MessageHandler {
            fn new() -> std::sync::Arc<Self> {
                std::sync::Arc::new(Self {})
            }
        }

        #[async_trait]
        impl AsyncEngine<SingleIn<String>, ManyOut<Annotated<String>>, Error> for MessageHandler {
            async fn generate(
                &self,
                input: SingleIn<String>,
            ) -> Result<ManyOut<Annotated<String>>, Error> {
                let (data, ctx) = input.into_parts();
1450
                let response = data.to_string();
1451
1452
1453
1454
1455
1456
1457
1458
1459
                let stream = stream::iter(vec![Annotated::from_data(response)]);
                Ok(ResponseStream::new(Box::pin(stream), ctx.context()))
            }
        }

        println!("\n=== Initializing DistributedRuntime ===");
        let runtime = Runtime::from_current()?;
        let drt = DistributedRuntime::from_settings(runtime.clone()).await?;
        let namespace = drt.namespace("ns123").unwrap();
1460
        let mut component = namespace.component("comp123").unwrap();
1461
1462
1463
        let ingress = Ingress::for_engine(MessageHandler::new()).unwrap();

        let _backend_handle = tokio::spawn(async move {
1464
1465
1466
1467
1468
            component.add_stats_service().await.unwrap();
            let endpoint = component
                .endpoint("echo")
                .endpoint_builder()
                .handler(ingress);
1469
1470
1471
1472
1473
1474
            endpoint.start().await.unwrap();
        });

        sleep(Duration::from_millis(500)).await;
        println!("✓ Launched endpoint service in background successfully");

1475
        let drt_output = drt.prometheus_expfmt().unwrap();
1476
1477
        let parsed_metrics: Vec<_> = drt_output
            .lines()
1478
            .filter_map(super::test_helpers::parse_prometheus_metric)
1479
1480
1481
1482
1483
1484
1485
1486
1487
            .collect();

        println!("=== Initial DRT metrics output ===");
        println!("{}", drt_output);

        println!("\n=== Checking Initial Metric Values ===");

        let initial_expected_metric_values = [
            // DRT NATS metrics (ordered to match DRT_NATS_METRICS)
1488
            (
1489
1490
1491
1492
                build_component_metric_name(nats_client::CONNECTION_STATE),
                1.0,
                1.0,
            ), // Should be connected
1493
1494
1495
1496
1497
            (
                build_component_metric_name(nats_client::CURRENT_CONNECTIONS),
                1.0,
                1.0,
            ), // Should have 1 connection
1498
1499
            (
                build_component_metric_name(nats_client::IN_TOTAL_BYTES),
1500
1501
1502
                800.0,
                4000.0,
            ), // Wide range around observed value of 1888
1503
            (
1504
1505
1506
1507
1508
1509
                build_component_metric_name(nats_client::IN_MESSAGES),
                0.0,
                5.0,
            ), // Wide range around 2
            (
                build_component_metric_name(nats_client::OUT_OVERHEAD_BYTES),
1510
1511
1512
                1500.0,
                5000.0,
            ), // Wide range around observed value of 2752
1513
1514
1515
1516
1517
            (
                build_component_metric_name(nats_client::OUT_MESSAGES),
                0.0,
                5.0,
            ), // Wide range around 2
1518
            // Component NATS metrics (ordered to match COMPONENT_NATS_METRICS)
1519
            (
1520
                build_component_metric_name(nats_service::PROCESSING_MS_AVG),
1521
1522
1523
1524
                0.0,
                0.0,
            ), // No processing yet
            (
1525
                build_component_metric_name(nats_service::ERRORS_TOTAL),
1526
1527
1528
1529
                0.0,
                0.0,
            ), // No errors yet
            (
1530
                build_component_metric_name(nats_service::REQUESTS_TOTAL),
1531
1532
1533
1534
                0.0,
                0.0,
            ), // No requests yet
            (
1535
                build_component_metric_name(nats_service::PROCESSING_MS_TOTAL),
1536
1537
1538
                0.0,
                0.0,
            ), // No processing yet
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
            (
                build_component_metric_name(nats_service::ACTIVE_SERVICES),
                0.0,
                2.0,
            ), // Service may not be fully active yet
            (
                build_component_metric_name(nats_service::ACTIVE_ENDPOINTS),
                0.0,
                2.0,
            ), // Endpoint may not be fully active yet
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
        ];

        for (metric_name, min_value, max_value) in &initial_expected_metric_values {
            let actual_value = parsed_metrics
                .iter()
                .find(|(name, _, _)| name == metric_name)
                .map(|(_, _, value)| *value)
                .unwrap_or_else(|| panic!("Could not find expected metric: {}", metric_name));

            assert!(
                actual_value >= *min_value && actual_value <= *max_value,
                "Initial metric {} should be between {} and {}, but got {}",
                metric_name,
                min_value,
                max_value,
                actual_value
            );
        }

        println!("\n=== Client Runtime to hit the endpoint ===");
        let client_runtime = Runtime::from_current()?;
        let client_distributed = DistributedRuntime::from_settings(client_runtime.clone()).await?;
        let namespace = client_distributed.namespace("ns123")?;
        let component = namespace.component("comp123")?;
        let client = component.endpoint("echo").client().await?;

        client.wait_for_instances().await?;
        println!("✓ Connected to endpoint, waiting for instances...");

        let router =
            PushRouter::<String, Annotated<String>>::from_client(client, Default::default())
                .await?;

        for i in 0..10 {
            let msg = i.to_string().repeat(2000); // 2k bytes message
            let mut stream = router.random(msg.clone().into()).await?;
            while let Some(resp) = stream.next().await {
                // Check if response matches the original message
                if let Some(data) = &resp.data {
                    let is_same = data == &msg;
                    println!(
                        "Response {}: {} bytes, matches original: {}",
                        i,
                        data.len(),
                        is_same
                    );
                }
            }
        }
        println!("✓ Sent messages and received responses successfully");

1600
1601
1602
1603
        println!("\n=== Waiting 500ms for metrics to update ===");
        sleep(Duration::from_millis(500)).await;
        println!("✓ Wait complete, getting final metrics...");

1604
        let final_drt_output = drt.prometheus_expfmt().unwrap();
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
        println!("\n=== Final Prometheus DRT output ===");
        println!("{}", final_drt_output);

        let final_drt_nats_output = super::test_helpers::extract_nats_lines(&final_drt_output);
        println!("\n=== Filtered NATS metrics from final DRT output ===");
        for line in &final_drt_nats_output {
            println!("{}", line);
        }

        let final_parsed_metrics: Vec<_> = super::test_helpers::extract_metrics(&final_drt_output)
            .iter()
1616
            .filter_map(|line| super::test_helpers::parse_prometheus_metric(line.as_str()))
1617
1618
1619
            .collect();

        let post_expected_metric_values = [
1620
            // DRT NATS metrics
1621
            (
1622
1623
1624
1625
                build_component_metric_name(nats_client::CONNECTION_STATE),
                1.0,
                1.0,
            ), // Connected
1626
1627
1628
1629
1630
            (
                build_component_metric_name(nats_client::CURRENT_CONNECTIONS),
                1.0,
                1.0,
            ), // 1 connection
1631
1632
            (
                build_component_metric_name(nats_client::IN_TOTAL_BYTES),
1633
1634
1635
1636
                20000.0,
                32000.0,
            ), // Wide range around 26117
            (
1637
1638
1639
1640
1641
1642
                build_component_metric_name(nats_client::IN_MESSAGES),
                8.0,
                20.0,
            ), // Wide range around 16
            (
                build_component_metric_name(nats_client::OUT_OVERHEAD_BYTES),
1643
1644
1645
                2500.0,
                8000.0,
            ), // Wide range around 5524
1646
1647
1648
1649
1650
            (
                build_component_metric_name(nats_client::OUT_MESSAGES),
                8.0,
                20.0,
            ), // Wide range around 16
1651
            // Component NATS metrics
1652
            (
1653
                build_component_metric_name(nats_service::PROCESSING_MS_AVG),
1654
1655
1656
1657
                0.0,
                1.0,
            ), // Low processing time
            (
1658
                build_component_metric_name(nats_service::ERRORS_TOTAL),
1659
1660
1661
1662
                0.0,
                0.0,
            ), // No errors
            (
1663
                build_component_metric_name(nats_service::REQUESTS_TOTAL),
1664
                0.0,
1665
1666
                10.0,
            ), // NATS service stats requests (may differ from work handler count)
1667
            (
1668
                build_component_metric_name(nats_service::PROCESSING_MS_TOTAL),
1669
1670
1671
                0.0,
                5.0,
            ), // Low total processing time
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
            (
                build_component_metric_name(nats_service::ACTIVE_SERVICES),
                0.0,
                2.0,
            ), // Service may not be fully active
            (
                build_component_metric_name(nats_service::ACTIVE_ENDPOINTS),
                0.0,
                2.0,
            ), // Endpoint may not be fully active
1682
            // Work handler metrics
1683
            (
1684
1685
1686
1687
1688
1689
                build_component_metric_name(work_handler::REQUESTS_TOTAL),
                10.0,
                10.0,
            ), // 10 messages
            (
                build_component_metric_name(work_handler::REQUEST_BYTES_TOTAL),
1690
1691
                21000.0,
                26000.0,
1692
            ), // ~75-125% of 23520
1693
            (
1694
                build_component_metric_name(work_handler::RESPONSE_BYTES_TOTAL),
1695
1696
                18000.0,
                23000.0,
1697
            ), // ~75-125% of 20660
1698
1699
1700
1701
1702
            (
                build_component_metric_name(work_handler::INFLIGHT_REQUESTS),
                0.0,
                1.0,
            ), // 0 or very low
1703
            // Histograms have _{count,sum} suffixes
1704
1705
1706
            (
                format!(
                    "{}_count",
1707
                    build_component_metric_name(work_handler::REQUEST_DURATION_SECONDS)
1708
1709
1710
                ),
                10.0,
                10.0,
1711
            ), // 10 messages
1712
1713
1714
            (
                format!(
                    "{}_sum",
1715
                    build_component_metric_name(work_handler::REQUEST_DURATION_SECONDS)
1716
                ),
1717
1718
1719
                0.0001,
                1.0,
            ), // Processing time sum (wide range)
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
        ];

        println!("\n=== Checking Post-Activity All Metrics (NATS + Work Handler) ===");
        for (metric_name, min_value, max_value) in &post_expected_metric_values {
            let actual_value = final_parsed_metrics
                .iter()
                .find(|(name, _, _)| name == metric_name)
                .map(|(_, _, value)| *value)
                .unwrap_or_else(|| {
                    panic!(
                        "Could not find expected post-activity metric: {}",
                        metric_name
                    )
                });

            assert!(
                actual_value >= *min_value && actual_value <= *max_value,
                "Post-activity metric {} should be between {} and {}, but got {}",
                metric_name,
                min_value,
                max_value,
                actual_value
            );
            println!(
                "✓ {}: {} (range: {} to {})",
                metric_name, actual_value, min_value, max_value
            );
        }

        println!("✓ All NATS and component metrics parsed successfully!");
        println!("✓ Byte metrics verified to be >= 100 bytes!");
        println!("✓ Post-activity metrics verified with higher thresholds!");
        println!("✓ Work handler metrics reflect increased activity!");

        Ok(())
    }
1756
}