prometheus_metrics.rs 30.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

// NOTE: This file implements Python bindings for Prometheus metric types.
// It should be kept in sync with:
// - lib/bindings/python/src/dynamo/_metrics.pyi (Python type stubs - method signatures must match)
// - lib/runtime/src/metrics.rs (MetricsRegistry trait - metric types should align)
//
// When adding/modifying metric methods:
// 1. Update the Rust implementation here (#[pymethods])
// 2. Update the Python type stub in _metrics.pyi
// 3. Follow standard Prometheus API conventions (e.g., Counter.inc(), Gauge.set(), etc.)

use prometheus::core::Collector;
use pyo3::prelude::*;
use std::collections::HashMap;
use std::sync::Arc;

use crate::rs;

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/// Helper function to order label values according to variable_labels declaration.
/// This ensures labels are passed to with_label_values() in the correct order.
///
/// # Arguments
/// * `variable_labels` - The ordered list of label names as declared in the metric
/// * `labels` - The HashMap of label name-value pairs from Python
///
/// # Returns
/// * `Ok(Vec<&str>)` - Ordered vector of label values matching variable_labels order
/// * `Err(PyErr)` - If a required label is missing
fn collect_ordered_label_values<'a>(
    variable_labels: &[String],
    labels: &'a HashMap<String, String>,
) -> PyResult<Vec<&'a str>> {
    let mut ordered_values = Vec::with_capacity(variable_labels.len());
    for label_name in variable_labels {
        match labels.get(label_name) {
            Some(value) => ordered_values.push(value.as_str()),
            None => {
                return Err(pyo3::exceptions::PyValueError::new_err(format!(
                    "Missing required label '{}'. Expected labels: {:?}, Got: {:?}",
                    label_name,
                    variable_labels,
                    labels.keys().collect::<Vec<_>>()
                )));
            }
        }
    }
    Ok(ordered_values)
}

52
53
54
55
56
57
58
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// Python wrappers for Prometheus metric types.
//
// These wrapper structs are necessary because Prometheus types from the external `prometheus` crate
// cannot be directly exposed to Python via PyO3's #[pyclass] attribute. This is due to:
//
// 1. **Orphan Rule**: PyO3 requires implementing traits on types, but Rust's orphan rule prevents
//    implementing foreign traits (like PyClass) on foreign types (prometheus::Counter, etc.).
//
// 2. **Ownership**: #[pyclass] can only be applied to structs defined in your crate, not external types.
//
// 3. **PyO3 Requirements**: Types exposed to Python must satisfy specific trait bounds (Send, Sync)
//    and implement PyO3's internal traits, which we cannot add to external crate types.
//
// The solution is the newtype wrapper pattern: wrap each Prometheus type in our own struct,
// apply #[pyclass] to our wrapper, and delegate method calls to the inner Prometheus type.

/// Python wrapper for Counter metric
#[pyclass]
pub struct Counter {
    counter: prometheus::Counter,
}

/// Python wrapper for IntCounter metric
#[pyclass]
pub struct IntCounter {
    counter: prometheus::IntCounter,
}

/// Python wrapper for CounterVec metric
#[pyclass]
pub struct CounterVec {
    counter: prometheus::CounterVec,
}

/// Python wrapper for IntCounterVec metric
#[pyclass]
pub struct IntCounterVec {
    counter: prometheus::IntCounterVec,
}

/// Python wrapper for Gauge metric
#[pyclass]
pub struct Gauge {
    gauge: prometheus::Gauge,
}

/// Python wrapper for IntGauge metric
#[pyclass]
pub struct IntGauge {
    gauge: prometheus::IntGauge,
}

/// Python wrapper for GaugeVec metric
#[pyclass]
pub struct GaugeVec {
    gauge: prometheus::GaugeVec,
}

/// Python wrapper for IntGaugeVec metric
#[pyclass]
pub struct IntGaugeVec {
    gauge: prometheus::IntGaugeVec,
}

/// Python wrapper for Histogram metric
#[pyclass]
pub struct Histogram {
    histogram: prometheus::Histogram,
}

// ============================================================================
// Various PyMethod implementations below.
// ============================================================================

#[pymethods]
impl Counter {
    /// Get the metric name
    fn name(&self) -> PyResult<String> {
        let desc = self.counter.desc();
        Ok(desc[0].fq_name.clone())
    }

    /// Get the constant labels
    fn const_labels(&self) -> PyResult<HashMap<String, String>> {
        let desc = self.counter.desc();
        let labels: HashMap<String, String> = desc[0]
            .const_label_pairs
            .iter()
            .map(|pair| (pair.name().to_string(), pair.value().to_string()))
            .collect();
        Ok(labels)
    }

    /// Increment counter by 1
    fn inc(&self) -> PyResult<()> {
        self.counter.inc();
        Ok(())
    }

    /// Increment counter by value
    fn inc_by(&self, value: f64) -> PyResult<()> {
        self.counter.inc_by(value);
        Ok(())
    }

    /// Get counter value
    fn get(&self) -> PyResult<f64> {
        Ok(self.counter.get())
    }
}

impl Counter {
    fn from_prometheus(counter: prometheus::Counter) -> Self {
        Self { counter }
    }
}

#[pymethods]
impl IntCounter {
    /// Get the metric name
    fn name(&self) -> PyResult<String> {
        let desc = self.counter.desc();
        Ok(desc[0].fq_name.clone())
    }

    /// Get the constant labels
    fn const_labels(&self) -> PyResult<HashMap<String, String>> {
        let desc = self.counter.desc();
        let labels: HashMap<String, String> = desc[0]
            .const_label_pairs
            .iter()
            .map(|pair| (pair.name().to_string(), pair.value().to_string()))
            .collect();
        Ok(labels)
    }

    /// Increment counter by 1
    fn inc(&self) -> PyResult<()> {
        self.counter.inc();
        Ok(())
    }

    /// Increment counter by value
    fn inc_by(&self, value: u64) -> PyResult<()> {
        self.counter.inc_by(value);
        Ok(())
    }

    /// Get counter value
    fn get(&self) -> PyResult<u64> {
        Ok(self.counter.get())
    }
}

impl IntCounter {
    fn from_prometheus(counter: prometheus::IntCounter) -> Self {
        Self { counter }
    }
}

#[pymethods]
impl CounterVec {
    /// Get the metric name
    fn name(&self) -> PyResult<String> {
        let desc = self.counter.desc();
        Ok(desc[0].fq_name.clone())
    }

    /// Get the constant labels
    fn const_labels(&self) -> PyResult<HashMap<String, String>> {
        let desc = self.counter.desc();
        let labels: HashMap<String, String> = desc[0]
            .const_label_pairs
            .iter()
            .map(|pair| (pair.name().to_string(), pair.value().to_string()))
            .collect();
        Ok(labels)
    }

    /// Get the variable label names
    fn variable_labels(&self) -> PyResult<Vec<String>> {
        let desc = self.counter.desc();
        Ok(desc[0].variable_labels.clone())
    }

    /// Increment counter by 1 with labels
    fn inc(&self, labels: HashMap<String, String>) -> PyResult<()> {
239
240
        let desc = self.counter.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
241
242
243
244
245
246
        self.counter.with_label_values(&label_values).inc();
        Ok(())
    }

    /// Increment counter by value with labels
    fn inc_by(&self, labels: HashMap<String, String>, value: f64) -> PyResult<()> {
247
248
        let desc = self.counter.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
249
250
251
252
253
254
        self.counter.with_label_values(&label_values).inc_by(value);
        Ok(())
    }

    /// Get counter value with labels
    fn get(&self, labels: HashMap<String, String>) -> PyResult<f64> {
255
256
        let desc = self.counter.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
        Ok(self.counter.with_label_values(&label_values).get())
    }
}

impl CounterVec {
    fn from_prometheus(counter: prometheus::CounterVec) -> Self {
        Self { counter }
    }
}

#[pymethods]
impl IntCounterVec {
    /// Get the metric name
    fn name(&self) -> PyResult<String> {
        let desc = self.counter.desc();
        Ok(desc[0].fq_name.clone())
    }

    /// Get the constant labels
    fn const_labels(&self) -> PyResult<HashMap<String, String>> {
        let desc = self.counter.desc();
        let labels: HashMap<String, String> = desc[0]
            .const_label_pairs
            .iter()
            .map(|pair| (pair.name().to_string(), pair.value().to_string()))
            .collect();
        Ok(labels)
    }

    /// Get the variable label names
    fn variable_labels(&self) -> PyResult<Vec<String>> {
        let desc = self.counter.desc();
        Ok(desc[0].variable_labels.clone())
    }

    /// Increment counter by 1 with labels
    fn inc(&self, labels: HashMap<String, String>) -> PyResult<()> {
294
295
        let desc = self.counter.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
296
297
298
299
300
301
        self.counter.with_label_values(&label_values).inc();
        Ok(())
    }

    /// Increment counter by value with labels
    fn inc_by(&self, labels: HashMap<String, String>, value: u64) -> PyResult<()> {
302
303
        let desc = self.counter.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
304
305
306
307
308
309
        self.counter.with_label_values(&label_values).inc_by(value);
        Ok(())
    }

    /// Get counter value with labels
    fn get(&self, labels: HashMap<String, String>) -> PyResult<u64> {
310
311
        let desc = self.counter.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
        Ok(self.counter.with_label_values(&label_values).get())
    }
}

impl IntCounterVec {
    fn from_prometheus(counter: prometheus::IntCounterVec) -> Self {
        Self { counter }
    }
}

#[pymethods]
impl Gauge {
    /// Get the metric name
    fn name(&self) -> PyResult<String> {
        let desc = self.gauge.desc();
        Ok(desc[0].fq_name.clone())
    }

    /// Get the constant labels
    fn const_labels(&self) -> PyResult<HashMap<String, String>> {
        let desc = self.gauge.desc();
        let labels: HashMap<String, String> = desc[0]
            .const_label_pairs
            .iter()
            .map(|pair| (pair.name().to_string(), pair.value().to_string()))
            .collect();
        Ok(labels)
    }

    /// Set gauge value
    fn set(&self, value: f64) -> PyResult<()> {
        self.gauge.set(value);
        Ok(())
    }

    /// Get gauge value
    fn get(&self) -> PyResult<f64> {
        Ok(self.gauge.get())
    }

    /// Increment gauge by 1
    fn inc(&self) -> PyResult<()> {
        self.gauge.inc();
        Ok(())
    }

    /// Increment gauge by value
    fn inc_by(&self, value: f64) -> PyResult<()> {
        self.gauge.add(value);
        Ok(())
    }

    /// Decrement gauge by 1
    fn dec(&self) -> PyResult<()> {
        self.gauge.dec();
        Ok(())
    }

    /// Decrement gauge by value
    fn dec_by(&self, value: f64) -> PyResult<()> {
        self.gauge.sub(value);
        Ok(())
    }

    /// Add value to gauge
    fn add(&self, value: f64) -> PyResult<()> {
        self.gauge.add(value);
        Ok(())
    }

    /// Subtract value from gauge
    fn sub(&self, value: f64) -> PyResult<()> {
        self.gauge.sub(value);
        Ok(())
    }
}

impl Gauge {
    fn from_prometheus(gauge: prometheus::Gauge) -> Self {
        Self { gauge }
    }
}

#[pymethods]
impl IntGauge {
    /// Get the metric name
    fn name(&self) -> PyResult<String> {
        let desc = self.gauge.desc();
        Ok(desc[0].fq_name.clone())
    }

    /// Get the constant labels
    fn const_labels(&self) -> PyResult<HashMap<String, String>> {
        let desc = self.gauge.desc();
        let labels: HashMap<String, String> = desc[0]
            .const_label_pairs
            .iter()
            .map(|pair| (pair.name().to_string(), pair.value().to_string()))
            .collect();
        Ok(labels)
    }

    /// Set gauge value
    fn set(&self, value: i64) -> PyResult<()> {
        self.gauge.set(value);
        Ok(())
    }

    /// Get gauge value
    fn get(&self) -> PyResult<i64> {
        Ok(self.gauge.get())
    }

    /// Increment gauge by 1
    fn inc(&self) -> PyResult<()> {
        self.gauge.inc();
        Ok(())
    }

    /// Decrement gauge by 1
    fn dec(&self) -> PyResult<()> {
        self.gauge.dec();
        Ok(())
    }

    /// Add value to gauge
    fn add(&self, value: i64) -> PyResult<()> {
        self.gauge.add(value);
        Ok(())
    }

    /// Subtract value from gauge
    fn sub(&self, value: i64) -> PyResult<()> {
        self.gauge.sub(value);
        Ok(())
    }
}

impl IntGauge {
    fn from_prometheus(gauge: prometheus::IntGauge) -> Self {
        Self { gauge }
    }
}

#[pymethods]
impl GaugeVec {
    /// Get the metric name
    fn name(&self) -> PyResult<String> {
        let desc = self.gauge.desc();
        Ok(desc[0].fq_name.clone())
    }

    /// Get the constant labels
    fn const_labels(&self) -> PyResult<HashMap<String, String>> {
        let desc = self.gauge.desc();
        let labels: HashMap<String, String> = desc[0]
            .const_label_pairs
            .iter()
            .map(|pair| (pair.name().to_string(), pair.value().to_string()))
            .collect();
        Ok(labels)
    }

    /// Get the variable label names
    fn variable_labels(&self) -> PyResult<Vec<String>> {
        let desc = self.gauge.desc();
        Ok(desc[0].variable_labels.clone())
    }

    /// Set gauge value with labels
    fn set(&self, value: f64, labels: HashMap<String, String>) -> PyResult<()> {
483
484
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
485
486
487
488
489
490
        self.gauge.with_label_values(&label_values).set(value);
        Ok(())
    }

    /// Get gauge value with labels
    fn get(&self, labels: HashMap<String, String>) -> PyResult<f64> {
491
492
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
493
494
495
496
497
        Ok(self.gauge.with_label_values(&label_values).get())
    }

    /// Increment gauge by 1 with labels
    fn inc(&self, labels: HashMap<String, String>) -> PyResult<()> {
498
499
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
500
501
502
503
504
505
        self.gauge.with_label_values(&label_values).inc();
        Ok(())
    }

    /// Decrement gauge by 1 with labels
    fn dec(&self, labels: HashMap<String, String>) -> PyResult<()> {
506
507
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
508
509
510
511
512
513
        self.gauge.with_label_values(&label_values).dec();
        Ok(())
    }

    /// Add value to gauge with labels
    fn add(&self, labels: HashMap<String, String>, value: f64) -> PyResult<()> {
514
515
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
516
517
518
519
520
521
        self.gauge.with_label_values(&label_values).add(value);
        Ok(())
    }

    /// Subtract value from gauge with labels
    fn sub(&self, labels: HashMap<String, String>, value: f64) -> PyResult<()> {
522
523
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
        self.gauge.with_label_values(&label_values).sub(value);
        Ok(())
    }
}

impl GaugeVec {
    fn from_prometheus(gauge: prometheus::GaugeVec) -> Self {
        Self { gauge }
    }
}

#[pymethods]
impl IntGaugeVec {
    /// Get the metric name
    fn name(&self) -> PyResult<String> {
        let desc = self.gauge.desc();
        Ok(desc[0].fq_name.clone())
    }

    /// Get the constant labels
    fn const_labels(&self) -> PyResult<HashMap<String, String>> {
        let desc = self.gauge.desc();
        let labels: HashMap<String, String> = desc[0]
            .const_label_pairs
            .iter()
            .map(|pair| (pair.name().to_string(), pair.value().to_string()))
            .collect();
        Ok(labels)
    }

    /// Get the variable label names
    fn variable_labels(&self) -> PyResult<Vec<String>> {
        let desc = self.gauge.desc();
        Ok(desc[0].variable_labels.clone())
    }

    /// Set gauge value with labels
    fn set(&self, value: i64, labels: HashMap<String, String>) -> PyResult<()> {
562
563
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
564
565
566
567
568
569
        self.gauge.with_label_values(&label_values).set(value);
        Ok(())
    }

    /// Get gauge value with labels
    fn get(&self, labels: HashMap<String, String>) -> PyResult<i64> {
570
571
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
572
573
574
575
576
        Ok(self.gauge.with_label_values(&label_values).get())
    }

    /// Increment gauge by 1 with labels
    fn inc(&self, labels: HashMap<String, String>) -> PyResult<()> {
577
578
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
579
580
581
582
583
584
        self.gauge.with_label_values(&label_values).inc();
        Ok(())
    }

    /// Decrement gauge by 1 with labels
    fn dec(&self, labels: HashMap<String, String>) -> PyResult<()> {
585
586
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
587
588
589
590
591
592
        self.gauge.with_label_values(&label_values).dec();
        Ok(())
    }

    /// Add value to gauge with labels
    fn add(&self, labels: HashMap<String, String>, value: i64) -> PyResult<()> {
593
594
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
595
596
597
598
599
600
        self.gauge.with_label_values(&label_values).add(value);
        Ok(())
    }

    /// Subtract value from gauge with labels
    fn sub(&self, labels: HashMap<String, String>, value: i64) -> PyResult<()> {
601
602
        let desc = self.gauge.desc();
        let label_values = collect_ordered_label_values(&desc[0].variable_labels, &labels)?;
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
        self.gauge.with_label_values(&label_values).sub(value);
        Ok(())
    }
}

impl IntGaugeVec {
    fn from_prometheus(gauge: prometheus::IntGaugeVec) -> Self {
        Self { gauge }
    }
}

#[pymethods]
impl Histogram {
    /// Get the metric name
    fn name(&self) -> PyResult<String> {
        let desc = self.histogram.desc();
        Ok(desc[0].fq_name.clone())
    }

    /// Get the constant labels
    fn const_labels(&self) -> PyResult<HashMap<String, String>> {
        let desc = self.histogram.desc();
        let labels: HashMap<String, String> = desc[0]
            .const_label_pairs
            .iter()
            .map(|pair| (pair.name().to_string(), pair.value().to_string()))
            .collect();
        Ok(labels)
    }

    /// Observe a value
    fn observe(&self, value: f64) -> PyResult<()> {
        self.histogram.observe(value);
        Ok(())
    }
}

impl Histogram {
    fn from_prometheus(histogram: prometheus::Histogram) -> Self {
        Self { histogram }
    }
}

/// RuntimeMetrics provides factory methods for creating typed Prometheus metrics
/// and utilities for registering metrics callbacks.
/// Exposed as endpoint.metrics, component.metrics, and namespace.metrics in Python.
///
650
/// NOTE: The create_* methods in RuntimeMetrics must stay in sync with the MetricsRegistry trait
651
652
653
/// in lib/runtime/src/metrics.rs. When adding new metric types, update both locations.
#[pyclass]
#[derive(Clone)]
654
pub struct RuntimeMetrics {
655
656
657
    metricsregistry: Arc<dyn rs::metrics::MetricsRegistry>,
}

658
impl RuntimeMetrics {
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
    /// Create from Endpoint
    pub fn from_endpoint(endpoint: dynamo_runtime::component::Endpoint) -> Self {
        Self {
            metricsregistry: Arc::new(endpoint),
        }
    }

    /// Create from Component
    pub fn from_component(component: dynamo_runtime::component::Component) -> Self {
        Self {
            metricsregistry: Arc::new(component),
        }
    }

    /// Create from Namespace
    pub fn from_namespace(namespace: dynamo_runtime::component::Namespace) -> Self {
        Self {
            metricsregistry: Arc::new(namespace),
        }
    }

    /// Helper to convert Python labels (String, String) to Rust labels (&str, &str)
    fn convert_py_to_rust_labels(labels: &Option<Vec<(String, String)>>) -> Vec<(&str, &str)> {
        labels
            .as_ref()
            .map(|v| v.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect())
            .unwrap_or_default()
    }

    /// Helper to convert Python label names Vec<String> to Vec<&str>
    fn convert_py_to_rust_label_names(names: &[String]) -> Vec<&str> {
        names.iter().map(|s| s.as_str()).collect()
    }

    /// Generic helper to register metrics callbacks for any type implementing MetricsRegistry
    /// This allows Endpoint, Component, and Namespace to share the same callback registration logic
    pub fn register_callback_for<T>(registry_item: &T, callback: PyObject) -> PyResult<()>
    where
        T: rs::metrics::MetricsRegistry + rs::traits::DistributedRuntimeProvider + ?Sized,
    {
        let hierarchy = registry_item.hierarchy();

        // Store the callback in the DRT's metrics callback registry using the registry_item's hierarchy
702
703
704
        // TODO: rename this to register_callback, once we move the the MetricsRegistry trait
        //       out of the runtime, and make it into a composed module.
        registry_item.drt().register_prometheus_update_callback(
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
            vec![hierarchy.clone()],
            Arc::new(move || {
                // Execute the Python callback in the Python event loop
                Python::with_gil(|py| {
                    if let Err(e) = callback.call0(py) {
                        tracing::error!("Metrics callback failed: {}", e);
                    }
                });
                Ok(())
            }),
        );

        Ok(())
    }
}

#[pymethods]
722
impl RuntimeMetrics {
723
724
    /// Register a Python callback to be invoked before metrics are scraped
    /// This callback will be called for this endpoint's metrics hierarchy
725
    fn register_callback(&self, callback: PyObject, _py: Python) -> PyResult<()> {
726
727
728
        Self::register_callback_for(self.metricsregistry.as_ref(), callback)
    }

729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
    /// Register a Python callback that returns Prometheus exposition text
    /// The returned text will be appended to the /metrics endpoint output
    /// The callback should return a string in Prometheus text exposition format
    fn register_prometheus_expfmt_callback(&self, callback: PyObject, _py: Python) -> PyResult<()> {
        let hierarchy = self.metricsregistry.hierarchy();

        // Store the callback in the DRT's metrics exposition text callback registry
        self.metricsregistry.drt().register_prometheus_expfmt_callback(
            vec![hierarchy.clone()],
            Arc::new(move || {
                // Execute the Python callback in the Python event loop
                Python::with_gil(|py| {
                    match callback.call0(py) {
                        Ok(result) => {
                            // Try to extract a string from the result
                            match result.extract::<String>(py) {
                                Ok(text) => Ok(text),
                                Err(e) => {
                                    tracing::error!("Metrics exposition text callback must return a string: {}", e);
                                    Ok(String::new())
                                }
                            }
                        }
                        Err(e) => {
                            tracing::error!("Metrics exposition text callback failed: {}", e);
                            Ok(String::new())
                        }
                    }
                })
            }),
        );

        Ok(())
    }

764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
    // NOTE: The order of create_* methods below matches lib/runtime/src/metrics.rs::MetricsRegistry trait
    // Keep them synchronized when adding new metric types

    /// Create a Counter metric
    #[pyo3(signature = (name, description, labels=None))]
    fn create_counter(
        &self,
        name: String,
        description: String,
        labels: Option<Vec<(String, String)>>,
        py: Python,
    ) -> PyResult<Py<Counter>> {
        let labels_vec = Self::convert_py_to_rust_labels(&labels);
        let counter = self
            .metricsregistry
            .create_counter(&name, &description, &labels_vec)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;

        let metric = Counter::from_prometheus(counter);
        Py::new(py, metric)
    }

    /// Create a CounterVec metric
    #[pyo3(signature = (name, description, label_names, const_labels=None))]
    fn create_countervec(
        &self,
        name: String,
        description: String,
        label_names: Vec<String>,
        const_labels: Option<Vec<(String, String)>>,
        py: Python,
    ) -> PyResult<Py<CounterVec>> {
        let label_names_str = Self::convert_py_to_rust_label_names(&label_names);
        let const_labels_vec = Self::convert_py_to_rust_labels(&const_labels);
        let counter_vec = self
            .metricsregistry
            .create_countervec(&name, &description, &label_names_str, &const_labels_vec)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;

        let metric = CounterVec::from_prometheus(counter_vec);
        Py::new(py, metric)
    }

    /// Create a Gauge metric
    #[pyo3(signature = (name, description, labels=None))]
    fn create_gauge(
        &self,
        name: String,
        description: String,
        labels: Option<Vec<(String, String)>>,
        py: Python,
    ) -> PyResult<Py<Gauge>> {
        let labels_vec = Self::convert_py_to_rust_labels(&labels);

        let gauge = self
            .metricsregistry
            .create_gauge(&name, &description, &labels_vec)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;

        let metric = Gauge::from_prometheus(gauge);
        Py::new(py, metric)
    }

    /// Create a GaugeVec metric
    #[pyo3(signature = (name, description, label_names, const_labels=None))]
    fn create_gaugevec(
        &self,
        name: String,
        description: String,
        label_names: Vec<String>,
        const_labels: Option<Vec<(String, String)>>,
        py: Python,
    ) -> PyResult<Py<GaugeVec>> {
        let label_names_str = Self::convert_py_to_rust_label_names(&label_names);
        let const_labels_vec = Self::convert_py_to_rust_labels(&const_labels);
        let gauge_vec = self
            .metricsregistry
            .create_gaugevec(&name, &description, &label_names_str, &const_labels_vec)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;

        let metric = GaugeVec::from_prometheus(gauge_vec);
        Py::new(py, metric)
    }

    /// Create a Histogram metric
    #[pyo3(signature = (name, description, labels=None))]
    fn create_histogram(
        &self,
        name: String,
        description: String,
        labels: Option<Vec<(String, String)>>,
        py: Python,
    ) -> PyResult<Py<Histogram>> {
        let labels_vec = Self::convert_py_to_rust_labels(&labels);

        let histogram = self
            .metricsregistry
            .create_histogram(&name, &description, &labels_vec, None)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;

        let metric = Histogram::from_prometheus(histogram);
        Py::new(py, metric)
    }

    /// Create an IntCounter metric
    #[pyo3(signature = (name, description, labels=None))]
    fn create_intcounter(
        &self,
        name: String,
        description: String,
        labels: Option<Vec<(String, String)>>,
        py: Python,
    ) -> PyResult<Py<IntCounter>> {
        let labels_vec = Self::convert_py_to_rust_labels(&labels);

        let counter = self
            .metricsregistry
            .create_intcounter(&name, &description, &labels_vec)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;

        let metric = IntCounter::from_prometheus(counter);
        Py::new(py, metric)
    }

    /// Create an IntCounterVec metric
    #[pyo3(signature = (name, description, label_names, const_labels=None))]
    fn create_intcountervec(
        &self,
        name: String,
        description: String,
        label_names: Vec<String>,
        const_labels: Option<Vec<(String, String)>>,
        py: Python,
    ) -> PyResult<Py<IntCounterVec>> {
        let label_names_str = Self::convert_py_to_rust_label_names(&label_names);
        let const_labels_vec = Self::convert_py_to_rust_labels(&const_labels);
        let counter_vec = self
            .metricsregistry
            .create_intcountervec(&name, &description, &label_names_str, &const_labels_vec)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;

        let metric = IntCounterVec::from_prometheus(counter_vec);
        Py::new(py, metric)
    }

    /// Create an IntGauge metric
    #[pyo3(signature = (name, description, labels=None))]
    fn create_intgauge(
        &self,
        name: String,
        description: String,
        labels: Option<Vec<(String, String)>>,
        py: Python,
    ) -> PyResult<Py<IntGauge>> {
        let labels_vec = Self::convert_py_to_rust_labels(&labels);

        let gauge = self
            .metricsregistry
            .create_intgauge(&name, &description, &labels_vec)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;

        let metric = IntGauge::from_prometheus(gauge);
        Py::new(py, metric)
    }

    /// Create an IntGaugeVec metric
    #[pyo3(signature = (name, description, label_names, const_labels=None))]
    fn create_intgaugevec(
        &self,
        name: String,
        description: String,
        label_names: Vec<String>,
        const_labels: Option<Vec<(String, String)>>,
        py: Python,
    ) -> PyResult<Py<IntGaugeVec>> {
        let label_names_str = Self::convert_py_to_rust_label_names(&label_names);
        let const_labels_vec = Self::convert_py_to_rust_labels(&const_labels);
        let gauge_vec = self
            .metricsregistry
            .create_intgaugevec(&name, &description, &label_names_str, &const_labels_vec)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;

        let metric = IntGaugeVec::from_prometheus(gauge_vec);
        Py::new(py, metric)
    }
}

pub fn add_to_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    // Add specific metric type classes
    m.add_class::<Counter>()?;
    m.add_class::<IntCounter>()?;
    m.add_class::<CounterVec>()?;
    m.add_class::<IntCounterVec>()?;
    m.add_class::<Gauge>()?;
    m.add_class::<IntGauge>()?;
    m.add_class::<GaugeVec>()?;
    m.add_class::<IntGaugeVec>()?;
    m.add_class::<Histogram>()?;

    Ok(())
}