1pub mod frontend_perf;
10pub mod otlp_export;
11pub mod prom_typed;
12pub mod prometheus_names;
13pub mod quic_response;
14pub mod request_plane;
15pub mod tokio_perf;
16pub mod transport_metrics;
17pub mod work_handler_perf;
18pub mod work_handler_pool;
19
20use parking_lot::Mutex;
21use std::collections::HashSet;
22use std::sync::Arc;
23
24use crate::component::ComponentBuilder;
25use anyhow;
26use anyhow::Context as _;
27use once_cell::sync::Lazy;
28use regex::Regex;
29use std::any::Any;
30use std::collections::HashMap;
31
32use prometheus_names::{
34 build_metric_name, labels, name_prefix, sanitize_prometheus_label, sanitize_prometheus_name,
35 work_handler,
36};
37
38use crate::pipeline::{
40 AsyncEngine, AsyncEngineContextProvider, Error, ManyOut, ResponseStream, SingleIn, async_trait,
41 network::Ingress,
42};
43use crate::protocols::annotated::Annotated;
44use crate::stream;
45use crate::stream::StreamExt;
46
47use prometheus::Encoder;
49
50fn validate_no_duplicate_label_keys(labels: &[(&str, &str)]) -> anyhow::Result<()> {
53 let mut seen_keys = std::collections::HashSet::new();
54 for (key, _) in labels {
55 if !seen_keys.insert(*key) {
56 return Err(anyhow::anyhow!(
57 "Duplicate label key '{}' found in labels",
58 key
59 ));
60 }
61 }
62 Ok(())
63}
64
65pub trait PrometheusMetric: prometheus::core::Collector + Clone + Send + Sync + 'static {
70 fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error>
72 where
73 Self: Sized;
74
75 fn with_histogram_opts_and_buckets(
78 _opts: prometheus::HistogramOpts,
79 _buckets: Option<Vec<f64>>,
80 ) -> Result<Self, prometheus::Error>
81 where
82 Self: Sized,
83 {
84 panic!("with_histogram_opts_and_buckets is not implemented for this metric type");
85 }
86
87 fn with_histogram_opts_buckets_and_label_names(
89 _opts: prometheus::HistogramOpts,
90 _buckets: Option<Vec<f64>>,
91 _label_names: &[&str],
92 ) -> Result<Self, prometheus::Error>
93 where
94 Self: Sized,
95 {
96 panic!(
97 "with_histogram_opts_buckets_and_label_names is not implemented for this metric type"
98 );
99 }
100
101 fn with_opts_and_label_names(
104 _opts: prometheus::Opts,
105 _label_names: &[&str],
106 ) -> Result<Self, prometheus::Error>
107 where
108 Self: Sized,
109 {
110 panic!("with_opts_and_label_names is not implemented for this metric type");
111 }
112}
113
114impl PrometheusMetric for prometheus::Counter {
116 fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
117 prometheus::Counter::with_opts(opts)
118 }
119}
120
121impl PrometheusMetric for prometheus::IntCounter {
122 fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
123 prometheus::IntCounter::with_opts(opts)
124 }
125}
126
127impl PrometheusMetric for prometheus::Gauge {
128 fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
129 prometheus::Gauge::with_opts(opts)
130 }
131}
132
133impl PrometheusMetric for prometheus::IntGauge {
134 fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
135 prometheus::IntGauge::with_opts(opts)
136 }
137}
138
139impl PrometheusMetric for prometheus::GaugeVec {
140 fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
141 Err(prometheus::Error::Msg(
142 "GaugeVec requires label names, use with_opts_and_label_names instead".to_string(),
143 ))
144 }
145
146 fn with_opts_and_label_names(
147 opts: prometheus::Opts,
148 label_names: &[&str],
149 ) -> Result<Self, prometheus::Error> {
150 prometheus::GaugeVec::new(opts, label_names)
151 }
152}
153
154impl PrometheusMetric for prometheus::IntGaugeVec {
155 fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
156 Err(prometheus::Error::Msg(
157 "IntGaugeVec requires label names, use with_opts_and_label_names instead".to_string(),
158 ))
159 }
160
161 fn with_opts_and_label_names(
162 opts: prometheus::Opts,
163 label_names: &[&str],
164 ) -> Result<Self, prometheus::Error> {
165 prometheus::IntGaugeVec::new(opts, label_names)
166 }
167}
168
169impl PrometheusMetric for prometheus::IntCounterVec {
170 fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
171 Err(prometheus::Error::Msg(
172 "IntCounterVec requires label names, use with_opts_and_label_names instead".to_string(),
173 ))
174 }
175
176 fn with_opts_and_label_names(
177 opts: prometheus::Opts,
178 label_names: &[&str],
179 ) -> Result<Self, prometheus::Error> {
180 prometheus::IntCounterVec::new(opts, label_names)
181 }
182}
183
184impl PrometheusMetric for prometheus::Histogram {
186 fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
187 let histogram_opts = prometheus::HistogramOpts::new(opts.name, opts.help);
189 prometheus::Histogram::with_opts(histogram_opts)
190 }
191
192 fn with_histogram_opts_and_buckets(
193 mut opts: prometheus::HistogramOpts,
194 buckets: Option<Vec<f64>>,
195 ) -> Result<Self, prometheus::Error> {
196 if let Some(custom_buckets) = buckets {
197 opts = opts.buckets(custom_buckets);
198 }
199 prometheus::Histogram::with_opts(opts)
200 }
201}
202
203impl PrometheusMetric for prometheus::HistogramVec {
204 fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
205 Err(prometheus::Error::Msg(
206 "HistogramVec requires histogram options and label names".to_string(),
207 ))
208 }
209
210 fn with_histogram_opts_buckets_and_label_names(
211 mut opts: prometheus::HistogramOpts,
212 buckets: Option<Vec<f64>>,
213 label_names: &[&str],
214 ) -> Result<Self, prometheus::Error> {
215 if let Some(custom_buckets) = buckets {
216 opts = opts.buckets(custom_buckets);
217 }
218 prometheus::HistogramVec::new(opts, label_names)
219 }
220}
221
222impl PrometheusMetric for prometheus::CounterVec {
224 fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
225 panic!("CounterVec requires label names, use with_opts_and_label_names instead");
227 }
228
229 fn with_opts_and_label_names(
230 opts: prometheus::Opts,
231 label_names: &[&str],
232 ) -> Result<Self, prometheus::Error> {
233 prometheus::CounterVec::new(opts, label_names)
234 }
235}
236
237pub fn create_metric<T: PrometheusMetric, H: MetricsHierarchy + ?Sized>(
242 hierarchy: &H,
243 metric_name: &str,
244 metric_desc: &str,
245 labels: &[(&str, &str)],
246 buckets: Option<Vec<f64>>,
247 const_labels: Option<&[&str]>,
248) -> anyhow::Result<T> {
249 create_metric_with_options(
250 hierarchy,
251 MetricOptions::default(),
252 metric_name,
253 metric_desc,
254 labels,
255 buckets,
256 const_labels,
257 )
258}
259
260#[derive(Clone, Copy, Debug)]
263pub struct MetricOptions {
264 pub prefix: &'static str,
267 pub warn_on_registration_failure: bool,
271}
272
273impl Default for MetricOptions {
274 fn default() -> Self {
275 Self {
276 prefix: name_prefix::COMPONENT,
277 warn_on_registration_failure: false,
278 }
279 }
280}
281
282pub fn create_metric_with_options<T: PrometheusMetric, H: MetricsHierarchy + ?Sized>(
285 hierarchy: &H,
286 options: MetricOptions,
287 metric_name: &str,
288 metric_desc: &str,
289 labels: &[(&str, &str)],
290 buckets: Option<Vec<f64>>,
291 const_labels: Option<&[&str]>,
292) -> anyhow::Result<T> {
293 validate_no_duplicate_label_keys(labels)?;
295 let basename = hierarchy.basename();
298 let parent_hierarchies = hierarchy.parent_hierarchies();
299
300 let mut hierarchy_names: Vec<String> =
302 parent_hierarchies.iter().map(|p| p.basename()).collect();
303 hierarchy_names.push(basename.clone());
304
305 let metric_name = build_metric_name(options.prefix, metric_name);
306
307 let mut updated_labels: Vec<(String, String)> = Vec::new();
309
310 for (key, _) in labels {
317 if *key == labels::NAMESPACE
318 || *key == labels::COMPONENT
319 || *key == labels::ENDPOINT
320 || *key == labels::WORKER_ID
321 {
322 return Err(anyhow::anyhow!(
323 "Label '{}' is automatically added by auto-label injection and cannot be manually set",
324 key
325 ));
326 }
327 }
328
329 if let Some(label_names) = const_labels {
333 for name in label_names.iter() {
334 if *name == labels::NAMESPACE
335 || *name == labels::COMPONENT
336 || *name == labels::ENDPOINT
337 || *name == labels::WORKER_ID
338 {
339 return Err(anyhow::anyhow!(
340 "Variable label name '{}' conflicts with auto-injected const label and cannot be used",
341 name
342 ));
343 }
344 }
345 }
346
347 if hierarchy_names.len() > 1 {
350 let namespace = &hierarchy_names[1];
351 if !namespace.is_empty() {
352 let valid_namespace = sanitize_prometheus_label(namespace)?;
353 if !valid_namespace.is_empty() {
354 updated_labels.push((labels::NAMESPACE.to_string(), valid_namespace));
355 }
356 }
357 }
358 if hierarchy_names.len() > 2 {
359 let component = &hierarchy_names[2];
360 if !component.is_empty() {
361 let valid_component = sanitize_prometheus_label(component)?;
362 if !valid_component.is_empty() {
363 updated_labels.push((labels::COMPONENT.to_string(), valid_component));
364 }
365 }
366 }
367 if hierarchy_names.len() > 3 {
368 let endpoint = &hierarchy_names[3];
369 if !endpoint.is_empty() {
370 let valid_endpoint = sanitize_prometheus_label(endpoint)?;
371 if !valid_endpoint.is_empty() {
372 updated_labels.push((labels::ENDPOINT.to_string(), valid_endpoint));
373 }
374 }
375 }
376
377 if let Some(conn_id) = hierarchy.connection_id() {
381 updated_labels.push((labels::WORKER_ID.to_string(), format!("{:x}", conn_id)));
382 }
383
384 updated_labels.extend(
386 labels
387 .iter()
388 .map(|(k, v)| ((*k).to_string(), (*v).to_string())),
389 );
390 let prometheus_metric = if std::any::TypeId::of::<T>()
394 == std::any::TypeId::of::<prometheus::CounterVec>()
395 {
396 if buckets.is_some() {
399 return Err(anyhow::anyhow!(
400 "buckets parameter is not valid for CounterVec"
401 ));
402 }
403 let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
404 for (key, value) in &updated_labels {
405 opts = opts.const_label(key.clone(), value.clone());
406 }
407 let label_names = const_labels
408 .ok_or_else(|| anyhow::anyhow!("CounterVec requires const_labels parameter"))?;
409 T::with_opts_and_label_names(opts, label_names)?
410 } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::GaugeVec>() {
411 if buckets.is_some() {
414 return Err(anyhow::anyhow!(
415 "buckets parameter is not valid for GaugeVec"
416 ));
417 }
418 let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
419 for (key, value) in &updated_labels {
420 opts = opts.const_label(key.clone(), value.clone());
421 }
422 let label_names = const_labels
423 .ok_or_else(|| anyhow::anyhow!("GaugeVec requires const_labels parameter"))?;
424 T::with_opts_and_label_names(opts, label_names)?
425 } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::HistogramVec>() {
426 let mut opts = prometheus::HistogramOpts::new(&metric_name, metric_desc);
427 for (key, value) in &updated_labels {
428 opts = opts.const_label(key.clone(), value.clone());
429 }
430 let label_names = const_labels
431 .ok_or_else(|| anyhow::anyhow!("HistogramVec requires const_labels parameter"))?;
432 T::with_histogram_opts_buckets_and_label_names(opts, buckets, label_names)?
433 } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::Histogram>() {
434 if const_labels.is_some() {
437 return Err(anyhow::anyhow!(
438 "const_labels parameter is not valid for Histogram"
439 ));
440 }
441 let mut opts = prometheus::HistogramOpts::new(&metric_name, metric_desc);
442 for (key, value) in &updated_labels {
443 opts = opts.const_label(key.clone(), value.clone());
444 }
445 T::with_histogram_opts_and_buckets(opts, buckets)?
446 } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::IntCounterVec>() {
447 if buckets.is_some() {
450 return Err(anyhow::anyhow!(
451 "buckets parameter is not valid for IntCounterVec"
452 ));
453 }
454 let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
455 for (key, value) in &updated_labels {
456 opts = opts.const_label(key.clone(), value.clone());
457 }
458 let label_names = const_labels
459 .ok_or_else(|| anyhow::anyhow!("IntCounterVec requires const_labels parameter"))?;
460 T::with_opts_and_label_names(opts, label_names)?
461 } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::IntGaugeVec>() {
462 if buckets.is_some() {
465 return Err(anyhow::anyhow!(
466 "buckets parameter is not valid for IntGaugeVec"
467 ));
468 }
469 let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
470 for (key, value) in &updated_labels {
471 opts = opts.const_label(key.clone(), value.clone());
472 }
473 let label_names = const_labels
474 .ok_or_else(|| anyhow::anyhow!("IntGaugeVec requires const_labels parameter"))?;
475 T::with_opts_and_label_names(opts, label_names)?
476 } else {
477 if buckets.is_some() {
480 return Err(anyhow::anyhow!(
481 "buckets parameter is not valid for Counter, IntCounter, Gauge, or IntGauge"
482 ));
483 }
484 if const_labels.is_some() {
485 return Err(anyhow::anyhow!(
486 "const_labels parameter is not valid for Counter, IntCounter, Gauge, or IntGauge"
487 ));
488 }
489 let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
490 for (key, value) in &updated_labels {
491 opts = opts.const_label(key.clone(), value.clone());
492 }
493 T::with_opts(opts)?
494 };
495
496 let collector: Box<dyn prometheus::core::Collector> = Box::new(prometheus_metric.clone());
497 let registry = hierarchy.get_metrics_registry();
498 if options.warn_on_registration_failure {
499 registry.add_metric_or_warn(collector, &metric_name);
500 } else {
501 registry.add_metric(collector)?;
502 }
503
504 Ok(prometheus_metric)
505}
506
507pub struct Metrics<H: MetricsHierarchy> {
510 hierarchy: H,
511}
512
513impl<H: MetricsHierarchy> Metrics<H> {
514 pub fn new(hierarchy: H) -> Self {
515 Self { hierarchy }
516 }
517
518 pub fn create_counter(
541 &self,
542 name: &str,
543 description: &str,
544 labels: &[(&str, &str)],
545 ) -> anyhow::Result<prometheus::Counter> {
546 create_metric(&self.hierarchy, name, description, labels, None, None)
547 }
548
549 pub fn create_countervec(
551 &self,
552 name: &str,
553 description: &str,
554 const_labels: &[&str],
555 const_label_values: &[(&str, &str)],
556 ) -> anyhow::Result<prometheus::CounterVec> {
557 create_metric(
558 &self.hierarchy,
559 name,
560 description,
561 const_label_values,
562 None,
563 Some(const_labels),
564 )
565 }
566
567 pub fn create_gauge(
569 &self,
570 name: &str,
571 description: &str,
572 labels: &[(&str, &str)],
573 ) -> anyhow::Result<prometheus::Gauge> {
574 create_metric(&self.hierarchy, name, description, labels, None, None)
575 }
576
577 pub fn create_gaugevec(
579 &self,
580 name: &str,
581 description: &str,
582 const_labels: &[&str],
583 const_label_values: &[(&str, &str)],
584 ) -> anyhow::Result<prometheus::GaugeVec> {
585 create_metric(
586 &self.hierarchy,
587 name,
588 description,
589 const_label_values,
590 None,
591 Some(const_labels),
592 )
593 }
594
595 pub fn create_histogram(
597 &self,
598 name: &str,
599 description: &str,
600 labels: &[(&str, &str)],
601 buckets: Option<Vec<f64>>,
602 ) -> anyhow::Result<prometheus::Histogram> {
603 create_metric(&self.hierarchy, name, description, labels, buckets, None)
604 }
605
606 pub fn create_histogramvec(
608 &self,
609 name: &str,
610 description: &str,
611 label_names: &[&str],
612 labels: &[(&str, &str)],
613 buckets: Option<Vec<f64>>,
614 ) -> anyhow::Result<prometheus::HistogramVec> {
615 create_metric(
616 &self.hierarchy,
617 name,
618 description,
619 labels,
620 buckets,
621 Some(label_names),
622 )
623 }
624
625 pub fn create_intcounter(
627 &self,
628 name: &str,
629 description: &str,
630 labels: &[(&str, &str)],
631 ) -> anyhow::Result<prometheus::IntCounter> {
632 create_metric(&self.hierarchy, name, description, labels, None, None)
633 }
634
635 pub fn create_intcountervec(
637 &self,
638 name: &str,
639 description: &str,
640 const_labels: &[&str],
641 const_label_values: &[(&str, &str)],
642 ) -> anyhow::Result<prometheus::IntCounterVec> {
643 create_metric(
644 &self.hierarchy,
645 name,
646 description,
647 const_label_values,
648 None,
649 Some(const_labels),
650 )
651 }
652
653 pub fn create_intgauge(
655 &self,
656 name: &str,
657 description: &str,
658 labels: &[(&str, &str)],
659 ) -> anyhow::Result<prometheus::IntGauge> {
660 create_metric(&self.hierarchy, name, description, labels, None, None)
661 }
662
663 pub fn create_intgaugevec(
665 &self,
666 name: &str,
667 description: &str,
668 const_labels: &[&str],
669 const_label_values: &[(&str, &str)],
670 ) -> anyhow::Result<prometheus::IntGaugeVec> {
671 create_metric(
672 &self.hierarchy,
673 name,
674 description,
675 const_label_values,
676 None,
677 Some(const_labels),
678 )
679 }
680
681 pub fn prometheus_expfmt(&self) -> anyhow::Result<String> {
683 self.hierarchy
684 .get_metrics_registry()
685 .prometheus_expfmt_combined()
686 }
687}
688
689use crate::traits::DistributedRuntimeProvider;
693
694pub trait MetricsHierarchy: Send + Sync {
695 fn basename(&self) -> String;
701
702 fn parent_hierarchies(&self) -> Vec<&dyn MetricsHierarchy>;
706
707 fn get_metrics_registry(&self) -> &MetricsRegistry;
709
710 fn connection_id(&self) -> Option<u64> {
720 None
721 }
722
723 fn metrics(&self) -> Metrics<&Self>
726 where
727 Self: Sized,
728 {
729 Metrics::new(self)
730 }
731}
732
733impl<T: MetricsHierarchy + ?Sized> MetricsHierarchy for &T {
735 fn basename(&self) -> String {
736 (**self).basename()
737 }
738
739 fn parent_hierarchies(&self) -> Vec<&dyn MetricsHierarchy> {
740 (**self).parent_hierarchies()
741 }
742
743 fn get_metrics_registry(&self) -> &MetricsRegistry {
744 (**self).get_metrics_registry()
745 }
746
747 fn connection_id(&self) -> Option<u64> {
748 (**self).connection_id()
749 }
750}
751
752pub type PrometheusUpdateCallback = Arc<dyn Fn() -> anyhow::Result<()> + Send + Sync + 'static>;
761
762pub struct CollectedFamilies {
769 pub families: Vec<prometheus::proto::MetricFamily>,
770 pub units: HashMap<String, String>,
772 pub prom_types: HashMap<String, String>,
776}
777
778pub type PrometheusExpositionFormatCallback =
780 Arc<dyn Fn() -> anyhow::Result<String> + Send + Sync + 'static>;
781
782pub type PrometheusTypedCallback = Arc<
785 dyn Fn() -> anyhow::Result<Vec<crate::metrics::prom_typed::BuiltFamily>>
786 + Send
787 + Sync
788 + 'static,
789>;
790
791#[derive(Clone)]
796pub struct MetricsRegistry {
797 pub prometheus_registry: Arc<std::sync::RwLock<prometheus::Registry>>,
800
801 child_registries: Arc<std::sync::RwLock<Vec<MetricsRegistry>>>,
815
816 pub prometheus_update_callbacks: Arc<std::sync::RwLock<Vec<PrometheusUpdateCallback>>>,
819
820 #[allow(clippy::type_complexity)]
822 pub prometheus_expfmt_callbacks:
823 Arc<std::sync::RwLock<Vec<PrometheusExpositionFormatCallback>>>,
824
825 pub prometheus_typed_callbacks: Arc<std::sync::RwLock<Vec<PrometheusTypedCallback>>>,
829}
830
831impl std::fmt::Debug for MetricsRegistry {
832 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
833 f.debug_struct("MetricsRegistry")
834 .field("prometheus_registry", &"<RwLock<Registry>>")
835 .field(
836 "prometheus_update_callbacks",
837 &format!(
838 "<RwLock<Vec<Callback>>> with {} callbacks",
839 self.prometheus_update_callbacks.read().unwrap().len()
840 ),
841 )
842 .field(
843 "prometheus_expfmt_callbacks",
844 &format!(
845 "<RwLock<Vec<Callback>>> with {} callbacks",
846 self.prometheus_expfmt_callbacks.read().unwrap().len()
847 ),
848 )
849 .field(
850 "prometheus_typed_callbacks",
851 &format!(
852 "<RwLock<Vec<Callback>>> with {} callbacks",
853 self.prometheus_typed_callbacks.read().unwrap().len()
854 ),
855 )
856 .finish()
857 }
858}
859
860impl MetricsRegistry {
861 pub fn new() -> Self {
863 Self {
864 prometheus_registry: Arc::new(std::sync::RwLock::new(prometheus::Registry::new())),
865 child_registries: Arc::new(std::sync::RwLock::new(Vec::new())),
866 prometheus_update_callbacks: Arc::new(std::sync::RwLock::new(Vec::new())),
867 prometheus_expfmt_callbacks: Arc::new(std::sync::RwLock::new(Vec::new())),
868 prometheus_typed_callbacks: Arc::new(std::sync::RwLock::new(Vec::new())),
869 }
870 }
871
872 pub fn add_child_registry(&self, child: &MetricsRegistry) {
876 let child_ptr = Arc::as_ptr(&child.prometheus_registry);
877 let mut guard = self.child_registries.write().unwrap();
878 if guard
879 .iter()
880 .any(|r| Arc::as_ptr(&r.prometheus_registry) == child_ptr)
881 {
882 return;
883 }
884 guard.push(child.clone());
885 }
886
887 fn registries_for_combined_scrape(&self) -> Vec<MetricsRegistry> {
888 fn visit(
894 registry: &MetricsRegistry,
895 out: &mut Vec<MetricsRegistry>,
896 seen: &mut HashSet<*const std::sync::RwLock<prometheus::Registry>>,
897 ) {
898 let ptr = Arc::as_ptr(®istry.prometheus_registry);
899 if !seen.insert(ptr) {
900 return;
901 }
902
903 out.push(registry.clone());
904
905 let children: Vec<MetricsRegistry> = registry
906 .child_registries
907 .read()
908 .unwrap()
909 .iter()
910 .cloned()
911 .collect();
912 for child in children {
913 visit(&child, out, seen);
914 }
915 }
916
917 let mut out = Vec::new();
918 let mut seen: HashSet<*const std::sync::RwLock<prometheus::Registry>> = HashSet::new();
919 visit(self, &mut out, &mut seen);
920 out
921 }
922
923 pub fn prometheus_expfmt_combined(&self) -> anyhow::Result<String> {
933 let registries = self.registries_for_combined_scrape();
934 run_update_callbacks(®istries);
935
936 let merged = FamilyMerger::from_gathered(®istries)?.into_sorted();
937
938 let encoder = prometheus::TextEncoder::new();
939 let mut buffer = Vec::new();
940 encoder.encode(&merged, &mut buffer)?;
941 let mut result = String::from_utf8(buffer)?;
942
943 let mut expfmt = String::new();
945 for registry in ®istries {
946 let text = registry.execute_expfmt_callbacks();
947 if !text.is_empty() {
948 if !expfmt.is_empty() && !expfmt.ends_with('\n') {
949 expfmt.push('\n');
950 }
951 expfmt.push_str(&text);
952 }
953 }
954
955 if !expfmt.is_empty() {
956 if !result.ends_with('\n') {
957 result.push('\n');
958 }
959 result.push_str(&expfmt);
960 }
961
962 Ok(result)
963 }
964
965 pub fn metric_families_combined(&self) -> anyhow::Result<CollectedFamilies> {
975 let registries = self.registries_for_combined_scrape();
976 run_update_callbacks(®istries);
977
978 let mut merger = FamilyMerger::from_gathered(®istries)?;
979
980 let mut units: HashMap<String, String> = HashMap::new();
983 let mut prom_types: HashMap<String, String> = HashMap::new();
984 for registry in ®istries {
985 for built in registry.execute_typed_callbacks() {
986 let name = built.family.name().to_string();
987 if let Err(error) = merger.add_family(built.family) {
993 tracing::warn!(metric_name = %name, %error, "skipping typed metric family");
994 continue;
995 }
996 if !built.unit.is_empty() {
1003 units.entry(name.clone()).or_insert(built.unit);
1004 }
1005 prom_types.entry(name).or_insert(built.prom_type);
1006 }
1007 }
1008
1009 Ok(CollectedFamilies {
1010 families: merger.into_sorted(),
1011 units,
1012 prom_types,
1013 })
1014 }
1015
1016 pub fn add_update_callback(&self, callback: PrometheusUpdateCallback) {
1018 self.prometheus_update_callbacks
1019 .write()
1020 .unwrap()
1021 .push(callback);
1022 }
1023
1024 pub fn add_expfmt_callback(&self, callback: PrometheusExpositionFormatCallback) {
1029 self.prometheus_expfmt_callbacks
1030 .write()
1031 .unwrap()
1032 .push(callback);
1033 }
1034
1035 pub fn execute_expfmt_callbacks(&self) -> String {
1037 let callbacks: Vec<PrometheusExpositionFormatCallback> = self
1041 .prometheus_expfmt_callbacks
1042 .read()
1043 .unwrap()
1044 .iter()
1045 .cloned()
1046 .collect();
1047 let mut result = String::new();
1048 for callback in callbacks.iter() {
1049 match callback() {
1050 Ok(text) => {
1051 if !text.is_empty() {
1052 if !result.is_empty() && !result.ends_with('\n') {
1053 result.push('\n');
1054 }
1055 result.push_str(&text);
1056 }
1057 }
1058 Err(e) => {
1059 tracing::error!("Error executing exposition text callback: {e}");
1060 }
1061 }
1062 }
1063 result
1064 }
1065
1066 pub fn add_typed_callback(&self, callback: PrometheusTypedCallback) {
1070 self.prometheus_typed_callbacks
1071 .write()
1072 .unwrap()
1073 .push(callback);
1074 }
1075
1076 pub fn execute_typed_callbacks(&self) -> Vec<crate::metrics::prom_typed::BuiltFamily> {
1079 let callbacks: Vec<PrometheusTypedCallback> = self
1084 .prometheus_typed_callbacks
1085 .read()
1086 .unwrap()
1087 .iter()
1088 .cloned()
1089 .collect();
1090
1091 callbacks
1092 .iter()
1093 .filter_map(|callback| match callback() {
1094 Ok(families) => Some(families),
1095 Err(error) => {
1096 tracing::warn!(%error, "typed metrics callback failed");
1097 None
1098 }
1099 })
1100 .flatten()
1101 .collect()
1102 }
1103
1104 pub fn execute_update_callbacks(&self) -> Vec<anyhow::Result<()>> {
1106 let callbacks: Vec<PrometheusUpdateCallback> = self
1111 .prometheus_update_callbacks
1112 .read()
1113 .unwrap()
1114 .iter()
1115 .cloned()
1116 .collect();
1117
1118 callbacks.iter().map(|callback| callback()).collect()
1119 }
1120
1121 pub fn add_metric(
1123 &self,
1124 collector: Box<dyn prometheus::core::Collector>,
1125 ) -> anyhow::Result<()> {
1126 self.prometheus_registry
1127 .write()
1128 .unwrap()
1129 .register(collector)
1130 .map_err(|e| anyhow::anyhow!("Failed to register metric: {}", e))
1131 }
1132
1133 pub fn add_metric_or_warn(&self, collector: Box<dyn prometheus::core::Collector>, name: &str) {
1135 if let Err(e) = self.add_metric(collector) {
1136 tracing::warn!(error = %e, metric = name, "Failed to register metric");
1137 }
1138 }
1139
1140 pub fn get_prometheus_registry(&self) -> std::sync::RwLockReadGuard<'_, prometheus::Registry> {
1142 self.prometheus_registry.read().unwrap()
1143 }
1144
1145 pub fn has_metric_named(&self, metric_name: &str) -> bool {
1147 self.prometheus_registry
1148 .read()
1149 .unwrap()
1150 .gather()
1151 .iter()
1152 .any(|mf| mf.name() == metric_name)
1153 }
1154}
1155
1156fn run_update_callbacks(registries: &[MetricsRegistry]) {
1159 for registry in registries {
1160 for result in registry.execute_update_callbacks() {
1161 if let Err(error) = result {
1162 tracing::error!(%error, "metrics update callback failed");
1163 }
1164 }
1165 }
1166}
1167
1168struct FamilyMerger {
1174 by_name: HashMap<String, prometheus::proto::MetricFamily>,
1175 seen_series: HashSet<String>,
1176}
1177
1178impl FamilyMerger {
1179 fn from_gathered(registries: &[MetricsRegistry]) -> anyhow::Result<Self> {
1180 let mut merger = Self {
1181 by_name: HashMap::new(),
1182 seen_series: HashSet::new(),
1183 };
1184 for (idx, registry) in registries.iter().enumerate() {
1185 for family in registry.get_prometheus_registry().gather() {
1186 merger
1187 .add_family(family)
1188 .with_context(|| format!("gathering from registry {idx}"))?;
1189 }
1190 }
1191 Ok(merger)
1192 }
1193
1194 fn add_family(&mut self, mut family: prometheus::proto::MetricFamily) -> anyhow::Result<()> {
1195 let name = family.name().to_string();
1196
1197 let entry = self.by_name.entry(name.clone()).or_insert_with(|| {
1198 let mut out = prometheus::proto::MetricFamily::new();
1199 out.set_name(name.clone());
1200 out.set_help(family.help().to_string());
1201 out.set_field_type(family.get_field_type());
1202 out
1203 });
1204
1205 if entry.help() != family.help() || entry.get_field_type() != family.get_field_type() {
1206 return Err(anyhow::anyhow!(
1207 "Metric family '{}' has inconsistent help/type across sources",
1208 name
1209 ));
1210 }
1211
1212 for metric in family.take_metric() {
1213 let mut labels: Vec<(String, String)> = metric
1214 .get_label()
1215 .iter()
1216 .map(|lp| (lp.name().to_string(), lp.value().to_string()))
1217 .collect();
1218 labels.sort_by(|(ka, va), (kb, vb)| (ka, va).cmp(&(kb, vb)));
1219
1220 let key = format!(
1221 "{}|{}",
1222 name,
1223 labels
1224 .iter()
1225 .map(|(k, v)| format!("{}={}", k, v))
1226 .collect::<Vec<_>>()
1227 .join(",")
1228 );
1229
1230 if !self.seen_series.insert(key) {
1231 tracing::warn!(
1232 metric_name = %name,
1233 labels = ?labels,
1234 "Duplicate Prometheus series while merging; dropping later sample"
1235 );
1236 continue;
1237 }
1238
1239 entry.mut_metric().push(metric);
1240 }
1241
1242 Ok(())
1243 }
1244
1245 fn into_sorted(self) -> Vec<prometheus::proto::MetricFamily> {
1246 let mut merged: Vec<prometheus::proto::MetricFamily> = self.by_name.into_values().collect();
1247 merged.sort_by(|a, b| a.name().cmp(b.name()));
1248 merged
1249 }
1250}
1251
1252impl Default for MetricsRegistry {
1253 fn default() -> Self {
1254 Self::new()
1255 }
1256}
1257
1258#[cfg(test)]
1259mod test_helpers {
1260 use super::prometheus_names::name_prefix;
1261 use super::*;
1262
1263 fn filter_prometheus_lines<F>(input: &str, mut predicate: F) -> Vec<String>
1266 where
1267 F: FnMut(&str) -> bool,
1268 {
1269 input
1270 .lines()
1271 .filter(|line| predicate(line))
1272 .map(|line| line.to_string())
1273 .collect::<Vec<_>>()
1274 }
1275
1276 pub fn extract_metrics(input: &str) -> Vec<String> {
1279 filter_prometheus_lines(input, |line| {
1280 line.starts_with(&format!("{}_", name_prefix::COMPONENT))
1281 && !line.starts_with("#")
1282 && !line.trim().is_empty()
1283 })
1284 }
1285
1286 pub fn parse_prometheus_metric(
1298 line: &str,
1299 ) -> Option<(String, std::collections::HashMap<String, String>, f64)> {
1300 if line.trim().is_empty() || line.starts_with('#') {
1301 return None;
1302 }
1303
1304 let parts: Vec<&str> = line.split_whitespace().collect();
1305 if parts.len() < 2 {
1306 return None;
1307 }
1308
1309 let metric_part = parts[0];
1310 let value: f64 = parts[1].parse().ok()?;
1311
1312 let (name, labels) = if metric_part.contains('{') {
1313 let brace_start = metric_part.find('{').unwrap();
1314 let brace_end = metric_part.rfind('}').unwrap_or(metric_part.len());
1315 let name = &metric_part[..brace_start];
1316 let labels_str = &metric_part[brace_start + 1..brace_end];
1317
1318 let mut labels = std::collections::HashMap::new();
1319 for pair in labels_str.split(',') {
1320 if let Some((k, v)) = pair.split_once('=') {
1321 let v = v.trim_matches('"');
1322 labels.insert(k.trim().to_string(), v.to_string());
1323 }
1324 }
1325 (name.to_string(), labels)
1326 } else {
1327 (metric_part.to_string(), std::collections::HashMap::new())
1328 };
1329
1330 Some((name, labels, value))
1331 }
1332
1333 pub fn inject_worker_id(expected: &str, wid: &str) -> String {
1339 let wid_label = format!(",worker_id=\"{}\"", wid);
1340 expected
1341 .lines()
1342 .map(|line| {
1343 if line.starts_with('#') || line.trim().is_empty() || !line.contains('{') {
1344 line.to_string()
1345 } else if let Some(le_pos) = line.find(",le=") {
1346 let mut s = line.to_string();
1349 s.insert_str(le_pos, &wid_label);
1350 s
1351 } else {
1352 line.replacen("}", &format!("{}}}", wid_label), 1)
1353 }
1354 })
1355 .collect::<Vec<_>>()
1356 .join("\n")
1357 }
1358}
1359
1360#[cfg(test)]
1361mod test_metricsregistry_units {
1362 use super::prometheus_names::build_component_metric_name;
1363 use super::*;
1364
1365 #[test]
1366 fn test_build_component_metric_name_with_prefix() {
1367 let result = build_component_metric_name("requests");
1369 assert_eq!(result, "dynamo_component_requests");
1370
1371 let result = build_component_metric_name("counter");
1372 assert_eq!(result, "dynamo_component_counter");
1373 }
1374
1375 #[test]
1376 fn test_parse_prometheus_metric() {
1377 use super::test_helpers::parse_prometheus_metric;
1378 use std::collections::HashMap;
1379
1380 let line = "http_requests_total{method=\"GET\",status=\"200\"} 1234";
1382 let parsed = parse_prometheus_metric(line);
1383 assert!(parsed.is_some());
1384
1385 let (name, labels, value) = parsed.unwrap();
1386 assert_eq!(name, "http_requests_total");
1387
1388 let mut expected_labels = HashMap::new();
1389 expected_labels.insert("method".to_string(), "GET".to_string());
1390 expected_labels.insert("status".to_string(), "200".to_string());
1391 assert_eq!(labels, expected_labels);
1392
1393 assert_eq!(value, 1234.0);
1394
1395 let line = "cpu_usage 98.5";
1397 let parsed = parse_prometheus_metric(line);
1398 assert!(parsed.is_some());
1399
1400 let (name, labels, value) = parsed.unwrap();
1401 assert_eq!(name, "cpu_usage");
1402 assert!(labels.is_empty());
1403 assert_eq!(value, 98.5);
1404
1405 let line = "response_time{service=\"api\"} 0.123";
1407 let parsed = parse_prometheus_metric(line);
1408 assert!(parsed.is_some());
1409
1410 let (name, labels, value) = parsed.unwrap();
1411 assert_eq!(name, "response_time");
1412
1413 let mut expected_labels = HashMap::new();
1414 expected_labels.insert("service".to_string(), "api".to_string());
1415 assert_eq!(labels, expected_labels);
1416
1417 assert_eq!(value, 0.123);
1418
1419 assert!(parse_prometheus_metric("").is_none()); assert!(parse_prometheus_metric("# HELP metric description").is_none()); assert!(parse_prometheus_metric("# TYPE metric counter").is_none()); assert!(parse_prometheus_metric("metric_name").is_none()); println!("✓ Prometheus metric parsing works correctly!");
1426 }
1427
1428 #[test]
1429 fn test_metrics_registry_entry_callbacks() {
1430 use crate::MetricsRegistry;
1431 use std::sync::atomic::{AtomicUsize, Ordering};
1432
1433 {
1435 let registry = MetricsRegistry::new();
1436 let counter = Arc::new(AtomicUsize::new(0));
1437
1438 for increment in [1, 10, 100] {
1440 let counter_clone = counter.clone();
1441 registry.add_update_callback(Arc::new(move || {
1442 counter_clone.fetch_add(increment, Ordering::SeqCst);
1443 Ok(())
1444 }));
1445 }
1446
1447 assert_eq!(counter.load(Ordering::SeqCst), 0);
1449
1450 let results = registry.execute_update_callbacks();
1452 assert_eq!(results.len(), 3);
1453 assert!(results.iter().all(|r| r.is_ok()));
1454 assert_eq!(counter.load(Ordering::SeqCst), 111); let results = registry.execute_update_callbacks();
1458 assert_eq!(results.len(), 3);
1459 assert_eq!(counter.load(Ordering::SeqCst), 222); let cloned = registry.clone();
1463 assert_eq!(cloned.execute_update_callbacks().len(), 3);
1464 assert_eq!(counter.load(Ordering::SeqCst), 333); registry.execute_update_callbacks();
1468 assert_eq!(counter.load(Ordering::SeqCst), 444); }
1470
1471 {
1473 let registry = MetricsRegistry::new();
1474 let counter = Arc::new(AtomicUsize::new(0));
1475
1476 let counter_clone = counter.clone();
1478 registry.add_update_callback(Arc::new(move || {
1479 counter_clone.fetch_add(1, Ordering::SeqCst);
1480 Ok(())
1481 }));
1482
1483 registry.add_update_callback(Arc::new(|| Err(anyhow::anyhow!("Simulated error"))));
1485
1486 let counter_clone = counter.clone();
1488 registry.add_update_callback(Arc::new(move || {
1489 counter_clone.fetch_add(10, Ordering::SeqCst);
1490 Ok(())
1491 }));
1492
1493 let results = registry.execute_update_callbacks();
1495 assert_eq!(results.len(), 3);
1496 assert!(results[0].is_ok());
1497 assert!(results[1].is_err());
1498 assert!(results[2].is_ok());
1499
1500 assert_eq!(
1502 results[1].as_ref().unwrap_err().to_string(),
1503 "Simulated error"
1504 );
1505
1506 assert_eq!(counter.load(Ordering::SeqCst), 11); let results = registry.execute_update_callbacks();
1511 assert!(results[1].is_err());
1512 assert_eq!(counter.load(Ordering::SeqCst), 22); }
1514
1515 {
1517 let registry = MetricsRegistry::new();
1518 let results = registry.execute_update_callbacks();
1519 assert_eq!(results.len(), 0);
1520 }
1521 }
1522}
1523
1524#[cfg(test)]
1525mod test_create_metric_with_options {
1526 use super::*;
1527 use prometheus::core::Collector;
1528
1529 struct Level {
1531 name: &'static str,
1532 parents: Vec<Level>,
1533 registry: MetricsRegistry,
1534 connection_id: Option<u64>,
1535 }
1536
1537 impl Level {
1538 fn new(name: &'static str, parents: Vec<Level>, connection_id: Option<u64>) -> Self {
1539 Self {
1540 name,
1541 parents,
1542 registry: MetricsRegistry::new(),
1543 connection_id,
1544 }
1545 }
1546
1547 fn component() -> Self {
1549 let root = Self::new("", Vec::new(), None);
1550 let namespace = Self::new("ns-1", Vec::new(), None);
1551 Self::new("comp", vec![root, namespace], Some(0x1a))
1552 }
1553 }
1554
1555 impl MetricsHierarchy for Level {
1556 fn basename(&self) -> String {
1557 self.name.to_string()
1558 }
1559
1560 fn parent_hierarchies(&self) -> Vec<&dyn MetricsHierarchy> {
1561 self.parents
1562 .iter()
1563 .map(|parent| parent as &dyn MetricsHierarchy)
1564 .collect()
1565 }
1566
1567 fn get_metrics_registry(&self) -> &MetricsRegistry {
1568 &self.registry
1569 }
1570
1571 fn connection_id(&self) -> Option<u64> {
1572 self.connection_id
1573 }
1574 }
1575
1576 const CUSTOM: MetricOptions = MetricOptions {
1577 prefix: "dynamo_custom",
1578 warn_on_registration_failure: false,
1579 };
1580
1581 fn described(metric: &impl Collector) -> (String, Vec<String>) {
1583 let desc = metric.desc()[0];
1584 let labels = desc
1585 .const_label_pairs
1586 .iter()
1587 .map(|pair| format!("{}={}", pair.name(), pair.value()))
1588 .collect();
1589 (desc.fq_name.clone(), labels)
1590 }
1591
1592 #[test]
1595 fn an_explicit_prefix_names_the_metric_and_keeps_the_hierarchy_labels() {
1596 let component = Level::component();
1597 let custom: prometheus::IntCounterVec = create_metric_with_options(
1598 &component,
1599 CUSTOM,
1600 "requests_total",
1601 "help",
1602 &[],
1603 None,
1604 Some(&["dp_rank"]),
1605 )
1606 .unwrap();
1607 let default = component
1608 .metrics()
1609 .create_intcountervec("requests_total", "help", &["dp_rank"], &[])
1610 .unwrap();
1611 let lookalike: prometheus::IntCounter =
1613 create_metric(&component, "dynamo_custom_total", "help", &[], None, None).unwrap();
1614
1615 let (name, labels) = described(&custom);
1616 assert_eq!(name, "dynamo_custom_requests_total");
1617 assert_eq!(
1618 labels,
1619 [
1620 "dynamo_component=comp",
1621 "dynamo_namespace=ns_1",
1622 "worker_id=1a"
1623 ]
1624 );
1625 assert_eq!(
1626 described(&default),
1627 ("dynamo_component_requests_total".to_string(), labels)
1628 );
1629 assert_eq!(
1630 described(&lookalike).0,
1631 "dynamo_component_dynamo_custom_total"
1632 );
1633 }
1634
1635 #[test]
1638 fn explicit_options_keep_validation_and_choose_how_a_refusal_ends() {
1639 let component = Level::component();
1640 let gauge = |options, labels: &[(&str, &str)], label_names: &[&str]| {
1641 create_metric_with_options::<prometheus::IntGaugeVec, _>(
1642 &component,
1643 options,
1644 "depth",
1645 "help",
1646 labels,
1647 None,
1648 Some(label_names),
1649 )
1650 };
1651 assert!(gauge(CUSTOM, &[("worker_id", "7")], &["dp_rank"]).is_err());
1652 assert!(gauge(CUSTOM, &[], &["dynamo_namespace"]).is_err());
1653 assert!(gauge(CUSTOM, &[("a", "1"), ("a", "2")], &["dp_rank"]).is_err());
1654
1655 let first = gauge(CUSTOM, &[], &["dp_rank"]).unwrap();
1656 assert!(gauge(CUSTOM, &[], &["dp_rank"]).is_err());
1657 let warn = MetricOptions {
1658 warn_on_registration_failure: true,
1659 ..CUSTOM
1660 };
1661 let refused = gauge(warn, &[], &["dp_rank"]).unwrap();
1662 first.with_label_values(&["0"]).set(3);
1663 refused.with_label_values(&["0"]).set(5);
1664
1665 let exposed = component.registry.prometheus_expfmt_combined().unwrap();
1667 let samples: Vec<&str> = exposed
1668 .lines()
1669 .filter(|line| !line.starts_with('#'))
1670 .collect();
1671 assert_eq!(
1672 samples,
1673 [
1674 r#"dynamo_custom_depth{dp_rank="0",dynamo_component="comp",dynamo_namespace="ns_1",worker_id="1a"} 3"#
1675 ]
1676 );
1677 assert_eq!(refused.with_label_values(&["0"]).get(), 5);
1678 }
1679}
1680
1681#[cfg(feature = "integration")]
1682#[cfg(test)]
1683mod test_metricsregistry_prefixes {
1684 use super::*;
1685 use crate::distributed::distributed_test_utils::create_test_drt_async;
1686 use prometheus::core::Collector;
1687
1688 #[tokio::test]
1689 async fn test_hierarchical_prefixes_and_parent_hierarchies() {
1690 let drt = create_test_drt_async().await;
1691
1692 const DRT_NAME: &str = "";
1693 const NAMESPACE_NAME: &str = "ns901";
1694 const COMPONENT_NAME: &str = "comp901";
1695 const ENDPOINT_NAME: &str = "ep901";
1696 let namespace = drt.namespace(NAMESPACE_NAME).unwrap();
1697 let component = namespace.component(COMPONENT_NAME).unwrap();
1698 let endpoint = component.endpoint(ENDPOINT_NAME);
1699
1700 assert_eq!(drt.basename(), DRT_NAME);
1702 assert_eq!(drt.parent_hierarchies().len(), 0);
1703 assert_eq!(namespace.basename(), NAMESPACE_NAME);
1707 assert_eq!(namespace.parent_hierarchies().len(), 1);
1708 assert_eq!(namespace.parent_hierarchies()[0].basename(), DRT_NAME);
1709 assert_eq!(component.basename(), COMPONENT_NAME);
1713 assert_eq!(component.parent_hierarchies().len(), 2);
1714 assert_eq!(component.parent_hierarchies()[0].basename(), DRT_NAME);
1715 assert_eq!(component.parent_hierarchies()[1].basename(), NAMESPACE_NAME);
1716 assert_eq!(endpoint.basename(), ENDPOINT_NAME);
1720 assert_eq!(endpoint.parent_hierarchies().len(), 3);
1721 assert_eq!(endpoint.parent_hierarchies()[0].basename(), DRT_NAME);
1722 assert_eq!(endpoint.parent_hierarchies()[1].basename(), NAMESPACE_NAME);
1723 assert_eq!(endpoint.parent_hierarchies()[2].basename(), COMPONENT_NAME);
1724 assert!(
1728 namespace
1729 .parent_hierarchies()
1730 .iter()
1731 .any(|h| h.basename() == drt.basename())
1732 );
1733 assert!(
1734 component
1735 .parent_hierarchies()
1736 .iter()
1737 .any(|h| h.basename() == namespace.basename())
1738 );
1739 assert!(
1740 endpoint
1741 .parent_hierarchies()
1742 .iter()
1743 .any(|h| h.basename() == component.basename())
1744 );
1745
1746 assert_eq!(drt.parent_hierarchies().len(), 0);
1748 assert_eq!(namespace.parent_hierarchies().len(), 1);
1749 assert_eq!(component.parent_hierarchies().len(), 2);
1750 assert_eq!(endpoint.parent_hierarchies().len(), 3);
1751
1752 let invalid_namespace = drt.namespace("@@123").unwrap();
1756 let result =
1757 invalid_namespace
1758 .metrics()
1759 .create_counter("test_counter", "A test counter", &[]);
1760 assert!(result.is_ok());
1761 if let Ok(counter) = &result {
1762 let desc = counter.desc();
1764 let namespace_label = desc[0]
1765 .const_label_pairs
1766 .iter()
1767 .find(|l| l.name() == "dynamo_namespace")
1768 .expect("Should have dynamo_namespace label");
1769 assert_eq!(namespace_label.value(), "_123");
1770 }
1771
1772 let valid_namespace = drt.namespace("ns567").unwrap();
1774 assert!(
1775 valid_namespace
1776 .metrics()
1777 .create_counter("test_counter", "A test counter", &[])
1778 .is_ok()
1779 );
1780 }
1781
1782 #[tokio::test]
1783 async fn test_typed_callback_only_registered_on_endpoint_is_collected_once() {
1784 let drt = create_test_drt_async().await;
1789 let namespace = drt.namespace("ns_typed_ep_only").unwrap();
1790 let component = namespace.component("comp_typed_ep_only").unwrap();
1791 let endpoint = component.endpoint("ep_typed_ep_only");
1792
1793 let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1794 let counter = calls.clone();
1795 let callback: PrometheusTypedCallback = Arc::new(move || {
1796 counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1797 let mut family = prometheus::proto::MetricFamily::new();
1798 family.set_name("dynamo_component_active_decode_blocks".to_string());
1799 family.set_field_type(prometheus::proto::MetricType::GAUGE);
1800 let mut metric = prometheus::proto::Metric::new();
1801 let mut label = prometheus::proto::LabelPair::new();
1802 label.set_name("dp_rank".to_string());
1803 label.set_value("0".to_string());
1804 metric.set_label(vec![label]);
1805 metric.set_gauge(prometheus::proto::Gauge::new());
1806 family.mut_metric().push(metric);
1807 Ok(vec![crate::metrics::prom_typed::BuiltFamily {
1808 family,
1809 unit: String::new(),
1810 prom_type: "gauge".to_string(),
1811 }])
1812 });
1813
1814 endpoint.get_metrics_registry().add_typed_callback(callback);
1815
1816 let families = drt
1818 .get_metrics_registry()
1819 .metric_families_combined()
1820 .unwrap();
1821
1822 assert_eq!(
1823 calls.load(std::sync::atomic::Ordering::SeqCst),
1824 1,
1825 "endpoint-registered typed callback should be collected once"
1826 );
1827 assert!(
1828 families
1829 .families
1830 .iter()
1831 .any(|f| f.name() == "dynamo_component_active_decode_blocks"),
1832 "typed family missing from the combined collection"
1833 );
1834 }
1835
1836 #[tokio::test]
1837 async fn test_recursive_namespace() {
1838 let drt = create_test_drt_async().await;
1840
1841 let ns1 = drt.namespace("ns1").unwrap();
1843 let ns2 = ns1.namespace("ns2").unwrap();
1844 let ns3 = ns2.namespace("ns3").unwrap();
1845
1846 let component = ns3.component("test-component").unwrap();
1848
1849 assert_eq!(ns1.basename(), "ns1");
1851 assert_eq!(ns1.parent_hierarchies().len(), 1);
1852 assert_eq!(ns1.parent_hierarchies()[0].basename(), "");
1853 assert_eq!(ns2.basename(), "ns2");
1856 assert_eq!(ns2.parent_hierarchies().len(), 2);
1857 assert_eq!(ns2.parent_hierarchies()[0].basename(), "");
1858 assert_eq!(ns2.parent_hierarchies()[1].basename(), "ns1");
1859 assert_eq!(ns3.basename(), "ns3");
1862 assert_eq!(ns3.parent_hierarchies().len(), 3);
1863 assert_eq!(ns3.parent_hierarchies()[0].basename(), "");
1864 assert_eq!(ns3.parent_hierarchies()[1].basename(), "ns1");
1865 assert_eq!(ns3.parent_hierarchies()[2].basename(), "ns2");
1866 assert_eq!(component.basename(), "test-component");
1869 assert_eq!(component.parent_hierarchies().len(), 4);
1870 assert_eq!(component.parent_hierarchies()[0].basename(), "");
1871 assert_eq!(component.parent_hierarchies()[1].basename(), "ns1");
1872 assert_eq!(component.parent_hierarchies()[2].basename(), "ns2");
1873 assert_eq!(component.parent_hierarchies()[3].basename(), "ns3");
1874 println!("✓ Chained namespace test passed - all prefixes correct");
1877 }
1878}
1879
1880#[cfg(feature = "integration")]
1881#[cfg(test)]
1882mod test_metricsregistry_prometheus_fmt_outputs {
1883 use super::prometheus_names::name_prefix;
1884 use super::*;
1885 use crate::distributed::distributed_test_utils::create_test_drt_async;
1886 use prometheus::Counter;
1887 use std::sync::Arc;
1888
1889 #[tokio::test]
1890 async fn test_prometheusfactory_using_metrics_registry_trait() {
1891 let drt = create_test_drt_async().await;
1893
1894 let namespace_name = "ns345";
1896
1897 let namespace = drt.namespace(namespace_name).unwrap();
1898 let component = namespace.component("comp345").unwrap();
1899 let endpoint = component.endpoint("ep345");
1900
1901 let counter = endpoint
1903 .metrics()
1904 .create_counter("testcounter", "A test counter", &[])
1905 .unwrap();
1906 counter.inc_by(123.456789);
1907 let epsilon = 0.01;
1908 assert!((counter.get() - 123.456789).abs() < epsilon);
1909
1910 let endpoint_output_raw = endpoint.metrics().prometheus_expfmt().unwrap();
1911 println!("Endpoint output:");
1912 println!("{}", endpoint_output_raw);
1913
1914 let wid = format!("{:x}", drt.connection_id());
1917 use super::test_helpers::inject_worker_id;
1918
1919 let expected_endpoint_output = inject_worker_id(
1920 r#"# HELP dynamo_component_testcounter A test counter
1921# TYPE dynamo_component_testcounter counter
1922dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789"#,
1923 &wid,
1924 );
1925
1926 assert_eq!(
1927 endpoint_output_raw.trim_end_matches('\n'),
1928 expected_endpoint_output.trim_end_matches('\n'),
1929 "\n=== ENDPOINT COMPARISON FAILED ===\n\
1930 Actual:\n{}\n\
1931 Expected:\n{}\n\
1932 ==============================",
1933 endpoint_output_raw,
1934 expected_endpoint_output
1935 );
1936
1937 let gauge = component
1939 .metrics()
1940 .create_gauge("testgauge", "A test gauge", &[])
1941 .unwrap();
1942 gauge.set(50000.0);
1943 assert_eq!(gauge.get(), 50000.0);
1944
1945 let component_output_raw = component.metrics().prometheus_expfmt().unwrap();
1947 println!("Component output:");
1948 println!("{}", component_output_raw);
1949
1950 let expected_component_output = inject_worker_id(
1951 r#"# HELP dynamo_component_testcounter A test counter
1952# TYPE dynamo_component_testcounter counter
1953dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789
1954# HELP dynamo_component_testgauge A test gauge
1955# TYPE dynamo_component_testgauge gauge
1956dynamo_component_testgauge{dynamo_component="comp345",dynamo_namespace="ns345"} 50000"#,
1957 &wid,
1958 );
1959
1960 assert_eq!(
1961 component_output_raw.trim_end_matches('\n'),
1962 expected_component_output.trim_end_matches('\n'),
1963 "\n=== COMPONENT COMPARISON FAILED ===\n\
1964 Actual:\n{}\n\
1965 Expected:\n{}\n\
1966 ==============================",
1967 component_output_raw,
1968 expected_component_output
1969 );
1970
1971 let intcounter = namespace
1972 .metrics()
1973 .create_intcounter("testintcounter", "A test int counter", &[])
1974 .unwrap();
1975 intcounter.inc_by(12345);
1976 assert_eq!(intcounter.get(), 12345);
1977
1978 let namespace_output_raw = namespace.metrics().prometheus_expfmt().unwrap();
1980 println!("Namespace output:");
1981 println!("{}", namespace_output_raw);
1982
1983 let expected_namespace_output = inject_worker_id(
1984 r#"# HELP dynamo_component_testcounter A test counter
1985# TYPE dynamo_component_testcounter counter
1986dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789
1987# HELP dynamo_component_testgauge A test gauge
1988# TYPE dynamo_component_testgauge gauge
1989dynamo_component_testgauge{dynamo_component="comp345",dynamo_namespace="ns345"} 50000
1990# HELP dynamo_component_testintcounter A test int counter
1991# TYPE dynamo_component_testintcounter counter
1992dynamo_component_testintcounter{dynamo_namespace="ns345"} 12345"#,
1993 &wid,
1994 );
1995
1996 assert_eq!(
1997 namespace_output_raw.trim_end_matches('\n'),
1998 expected_namespace_output.trim_end_matches('\n'),
1999 "\n=== NAMESPACE COMPARISON FAILED ===\n\
2000 Actual:\n{}\n\
2001 Expected:\n{}\n\
2002 ==============================",
2003 namespace_output_raw,
2004 expected_namespace_output
2005 );
2006
2007 let intgauge = namespace
2009 .metrics()
2010 .create_intgauge("testintgauge", "A test int gauge", &[])
2011 .unwrap();
2012 intgauge.set(42);
2013 assert_eq!(intgauge.get(), 42);
2014
2015 let intgaugevec = namespace
2017 .metrics()
2018 .create_intgaugevec(
2019 "testintgaugevec",
2020 "A test int gauge vector",
2021 &["instance", "status"],
2022 &[("service", "api")],
2023 )
2024 .unwrap();
2025 intgaugevec
2026 .with_label_values(&["server1", "active"])
2027 .set(10);
2028 intgaugevec
2029 .with_label_values(&["server2", "inactive"])
2030 .set(0);
2031
2032 let countervec = endpoint
2034 .metrics()
2035 .create_countervec(
2036 "testcountervec",
2037 "A test counter vector",
2038 &["method", "status"],
2039 &[("service", "api")],
2040 )
2041 .unwrap();
2042 countervec.with_label_values(&["GET", "200"]).inc_by(10.0);
2043 countervec.with_label_values(&["POST", "201"]).inc_by(5.0);
2044
2045 let histogram = component
2047 .metrics()
2048 .create_histogram("testhistogram", "A test histogram", &[], None)
2049 .unwrap();
2050 histogram.observe(1.0);
2051 histogram.observe(2.5);
2052 histogram.observe(4.0);
2053
2054 let drt_output_raw = drt.metrics().prometheus_expfmt().unwrap();
2056 println!("DRT output:");
2057 println!("{}", drt_output_raw);
2058
2059 let expected_drt_output_without_uptime = inject_worker_id(
2062 r#"# HELP dynamo_component_testcounter A test counter
2063# TYPE dynamo_component_testcounter counter
2064dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789
2065# HELP dynamo_component_testcountervec A test counter vector
2066# TYPE dynamo_component_testcountervec counter
2067dynamo_component_testcountervec{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345",method="GET",service="api",status="200"} 10
2068dynamo_component_testcountervec{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345",method="POST",service="api",status="201"} 5
2069# HELP dynamo_component_testgauge A test gauge
2070# TYPE dynamo_component_testgauge gauge
2071dynamo_component_testgauge{dynamo_component="comp345",dynamo_namespace="ns345"} 50000
2072# HELP dynamo_component_testhistogram A test histogram
2073# TYPE dynamo_component_testhistogram histogram
2074dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.005"} 0
2075dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.01"} 0
2076dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.025"} 0
2077dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.05"} 0
2078dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.1"} 0
2079dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.25"} 0
2080dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.5"} 0
2081dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="1"} 1
2082dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="2.5"} 2
2083dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="5"} 3
2084dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="10"} 3
2085dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="+Inf"} 3
2086dynamo_component_testhistogram_sum{dynamo_component="comp345",dynamo_namespace="ns345"} 7.5
2087dynamo_component_testhistogram_count{dynamo_component="comp345",dynamo_namespace="ns345"} 3
2088# HELP dynamo_component_testintcounter A test int counter
2089# TYPE dynamo_component_testintcounter counter
2090dynamo_component_testintcounter{dynamo_namespace="ns345"} 12345
2091# HELP dynamo_component_testintgauge A test int gauge
2092# TYPE dynamo_component_testintgauge gauge
2093dynamo_component_testintgauge{dynamo_namespace="ns345"} 42
2094# HELP dynamo_component_testintgaugevec A test int gauge vector
2095# TYPE dynamo_component_testintgaugevec gauge
2096dynamo_component_testintgaugevec{dynamo_namespace="ns345",instance="server1",service="api",status="active"} 10
2097dynamo_component_testintgaugevec{dynamo_namespace="ns345",instance="server2",service="api",status="inactive"} 0"#,
2098 &wid,
2099 );
2100
2101 let mut non_uptime_lines = Vec::new();
2105 let mut saw_uptime_value = false;
2106 for line in drt_output_raw.trim_end_matches('\n').lines() {
2107 if line.starts_with("dynamo_component_uptime_seconds") && !line.starts_with('#') {
2108 let val_str = line.split_whitespace().last().unwrap();
2109 val_str.parse::<f64>().expect("uptime should be a float");
2110 saw_uptime_value = true;
2111 } else if line.starts_with("# HELP dynamo_component_uptime_seconds")
2112 || line.starts_with("# TYPE dynamo_component_uptime_seconds")
2113 {
2114 } else {
2116 non_uptime_lines.push(line);
2117 }
2118 }
2119 assert!(
2120 saw_uptime_value,
2121 "uptime_seconds metric should be present in initial scrape"
2122 );
2123
2124 let actual_without_uptime = non_uptime_lines.join("\n");
2125 assert_eq!(
2126 actual_without_uptime,
2127 expected_drt_output_without_uptime.trim_end_matches('\n'),
2128 "\n=== DRT COMPARISON FAILED (excluding uptime) ===\n\
2129 Expected:\n{}\n\
2130 Actual:\n{}\n\
2131 ==============================",
2132 expected_drt_output_without_uptime,
2133 actual_without_uptime
2134 );
2135
2136 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
2138 let drt_output_after = drt.metrics().prometheus_expfmt().unwrap();
2139 let uptime_line = drt_output_after
2140 .lines()
2141 .find(|l| l.starts_with("dynamo_component_uptime_seconds") && !l.starts_with('#'))
2142 .expect("uptime_seconds metric should be present after sleep");
2143 let uptime_after: f64 = uptime_line
2144 .split_whitespace()
2145 .last()
2146 .unwrap()
2147 .parse()
2148 .expect("uptime should be a float");
2149 assert!(
2150 uptime_after > 0.0,
2151 "uptime_seconds should be > 0 after 10ms sleep, got {}",
2152 uptime_after
2153 );
2154
2155 println!("✓ All Prometheus format outputs verified successfully!");
2156 }
2157
2158 #[test]
2159 fn test_refactored_filter_functions() {
2160 let test_input = r#"# HELP dynamo_component_requests Total requests
2162# TYPE dynamo_component_requests counter
2163dynamo_component_requests 42
2164# HELP dynamo_component_latency Response latency
2165# TYPE dynamo_component_latency histogram
2166dynamo_component_latency_bucket{le="0.1"} 10
2167dynamo_component_latency_bucket{le="0.5"} 25
2168dynamo_component_errors_total 5"#;
2169
2170 let metrics_only = super::test_helpers::extract_metrics(test_input);
2172 assert_eq!(metrics_only.len(), 4); assert!(
2174 metrics_only
2175 .iter()
2176 .all(|line| line.starts_with("dynamo_component") && !line.starts_with("#"))
2177 );
2178
2179 println!("✓ All refactored filter functions work correctly!");
2180 }
2181
2182 #[tokio::test]
2183 async fn test_same_metric_name_different_endpoints() {
2184 let drt = create_test_drt_async().await;
2188 let namespace = drt.namespace("ns_test").unwrap();
2189 let component = namespace.component("comp_test").unwrap();
2190
2191 let ep1 = component.endpoint("ep1");
2193 let ep2 = component.endpoint("ep2");
2194
2195 let counter1 = ep1
2196 .metrics()
2197 .create_counter("requests_total", "Total requests", &[])
2198 .unwrap();
2199 counter1.inc_by(100.0);
2200
2201 let counter2 = ep2
2202 .metrics()
2203 .create_counter("requests_total", "Total requests", &[])
2204 .unwrap();
2205 counter2.inc_by(200.0);
2206
2207 let output = component.metrics().prometheus_expfmt().unwrap();
2209
2210 let wid = format!("{:x}", drt.connection_id());
2211 use super::test_helpers::inject_worker_id;
2212
2213 let expected_output = inject_worker_id(
2214 r#"# HELP dynamo_component_requests_total Total requests
2215# TYPE dynamo_component_requests_total counter
2216dynamo_component_requests_total{dynamo_component="comp_test",dynamo_endpoint="ep1",dynamo_namespace="ns_test"} 100
2217dynamo_component_requests_total{dynamo_component="comp_test",dynamo_endpoint="ep2",dynamo_namespace="ns_test"} 200"#,
2218 &wid,
2219 );
2220
2221 assert_eq!(
2222 output.trim_end_matches('\n'),
2223 expected_output.trim_end_matches('\n'),
2224 "\n=== MULTI-REGISTRY COMPARISON FAILED ===\n\
2225 Actual:\n{}\n\
2226 Expected:\n{}\n\
2227 ==============================",
2228 output,
2229 expected_output
2230 );
2231
2232 println!("✓ Multi-registry prevents Prometheus collisions!");
2233 }
2234
2235 #[tokio::test]
2236 async fn test_duplicate_series_warning() {
2237 let drt = create_test_drt_async().await;
2240 let namespace = drt.namespace("ns_dup").unwrap();
2241 let component = namespace.component("comp_dup").unwrap();
2242
2243 let ep1 = component.endpoint("ep_same");
2245 let ep2 = component.endpoint("ep_same"); let counter1 = ep1
2248 .metrics()
2249 .create_counter("dup_metric", "Duplicate metric test", &[])
2250 .unwrap();
2251 counter1.inc_by(50.0);
2252
2253 let counter2 = ep2
2254 .metrics()
2255 .create_counter("dup_metric", "Duplicate metric test", &[])
2256 .unwrap();
2257 counter2.inc_by(75.0);
2258
2259 let output = component.metrics().prometheus_expfmt().unwrap();
2261
2262 let wid = format!("{:x}", drt.connection_id());
2263 use super::test_helpers::inject_worker_id;
2264
2265 let expected_output = inject_worker_id(
2266 r#"# HELP dynamo_component_dup_metric Duplicate metric test
2267# TYPE dynamo_component_dup_metric counter
2268dynamo_component_dup_metric{dynamo_component="comp_dup",dynamo_endpoint="ep_same",dynamo_namespace="ns_dup"} 50"#,
2269 &wid,
2270 );
2271
2272 assert_eq!(
2273 output.trim_end_matches('\n'),
2274 expected_output.trim_end_matches('\n'),
2275 "\n=== DEDUPLICATION COMPARISON FAILED ===\n\
2276 Actual:\n{}\n\
2277 Expected:\n{}\n\
2278 ==============================",
2279 output,
2280 expected_output
2281 );
2282
2283 println!("✓ Duplicate series detection and deduplication works!");
2284 }
2285}
2286
2287#[cfg(test)]
2288mod test_metric_families_combined {
2289 use super::*;
2290 use std::sync::Arc as StdArc;
2291
2292 fn gauge_family(name: &str, help: &str, value: f64) -> prometheus::proto::MetricFamily {
2293 let mut family = prometheus::proto::MetricFamily::new();
2294 family.set_name(name.to_string());
2295 family.set_help(help.to_string());
2296 family.set_field_type(prometheus::proto::MetricType::GAUGE);
2297 let mut metric = prometheus::proto::Metric::new();
2298 let mut gauge = prometheus::proto::Gauge::new();
2299 gauge.set_value(value);
2300 metric.set_gauge(gauge);
2301 family.mut_metric().push(metric);
2302 family
2303 }
2304
2305 fn registry() -> MetricsRegistry {
2306 let registry = MetricsRegistry::new();
2307 let counter = prometheus::IntCounter::new("dynamo_native_total", "Native counter").unwrap();
2308 counter.inc_by(7);
2309 registry
2310 .get_prometheus_registry()
2311 .register(Box::new(counter))
2312 .unwrap();
2313 registry.add_typed_callback(StdArc::new(|| {
2314 Ok(vec![crate::metrics::prom_typed::BuiltFamily {
2315 unit: String::new(),
2316 prom_type: "gauge".to_string(),
2317 family: gauge_family("vllm:num_requests_running", "Running requests", 4.0),
2318 }])
2319 }));
2320 registry
2321 }
2322
2323 fn names(fs: &[prometheus::proto::MetricFamily]) -> Vec<&str> {
2324 fs.iter().map(|f| f.name()).collect()
2325 }
2326
2327 #[test]
2328 fn typed_and_native_families_share_one_collection() {
2329 let collected = registry().metric_families_combined().expect("combined");
2330 assert!(names(&collected.families).contains(&"vllm:num_requests_running"));
2331 assert!(names(&collected.families).contains(&"dynamo_native_total"));
2332 }
2333
2334 #[test]
2346 fn metadata_from_a_source_that_contributed_no_samples_does_not_win() {
2347 let registry = MetricsRegistry::new();
2348 registry.add_typed_callback(StdArc::new(|| {
2349 Ok(vec![
2350 crate::metrics::prom_typed::BuiltFamily {
2351 unit: "bytes".to_string(),
2352 prom_type: "gauge".to_string(),
2353 family: gauge_family("vllm:probe", "Same help", 1.0),
2354 },
2355 crate::metrics::prom_typed::BuiltFamily {
2358 unit: "seconds".to_string(),
2359 prom_type: "gauge".to_string(),
2360 family: gauge_family("vllm:probe", "Same help", 2.0),
2361 },
2362 ])
2363 }));
2364
2365 let collected = registry.metric_families_combined().expect("combined");
2366
2367 let family = collected
2368 .families
2369 .iter()
2370 .find(|f| f.name() == "vllm:probe")
2371 .expect("family");
2372 assert_eq!(
2373 family.get_metric()[0].get_gauge().value(),
2374 1.0,
2375 "the surviving sample should be the first source's"
2376 );
2377 assert_eq!(
2378 collected.units.get("vllm:probe").map(String::as_str),
2379 Some("bytes"),
2380 "unit came from a source whose samples were all dropped"
2381 );
2382 }
2383
2384 #[test]
2385 fn rejected_family_leaves_no_metadata_behind() {
2386 let registry = MetricsRegistry::new();
2387 registry.add_typed_callback(StdArc::new(|| {
2388 Ok(vec![
2389 crate::metrics::prom_typed::BuiltFamily {
2390 unit: String::new(),
2391 prom_type: "gauge".to_string(),
2392 family: gauge_family("vllm:cache_usage", "Cache usage", 0.5),
2393 },
2394 crate::metrics::prom_typed::BuiltFamily {
2396 unit: "seconds".to_string(),
2397 prom_type: "info".to_string(),
2398 family: gauge_family("vllm:cache_usage", "A different help", 1.0),
2399 },
2400 ])
2401 }));
2402
2403 let collected = registry.metric_families_combined().expect("combined");
2404
2405 assert_eq!(
2406 collected
2407 .prom_types
2408 .get("vllm:cache_usage")
2409 .map(String::as_str),
2410 Some("gauge"),
2411 "the rejected family's type overwrote the accepted family's"
2412 );
2413 assert!(
2414 !collected.units.contains_key("vllm:cache_usage"),
2415 "the rejected family's unit was published for a family that has none"
2416 );
2417 }
2418
2419 #[test]
2424 fn typed_callbacks_feed_otlp_and_not_the_scrape() {
2425 let registry = registry();
2426
2427 let text = registry.prometheus_expfmt_combined().expect("text");
2428 assert!(
2429 text.contains("dynamo_native_total"),
2430 "native metrics must still render on /metrics"
2431 );
2432 assert!(
2433 !text.contains("vllm:num_requests_running"),
2434 "typed callbacks feed OTLP only; /metrics is fed by expfmt callbacks"
2435 );
2436
2437 registry.add_expfmt_callback(StdArc::new(|| {
2438 Ok("# HELP vllm:num_requests_running Running requests\n\
2439 # TYPE vllm:num_requests_running gauge\n\
2440 vllm:num_requests_running 4\n"
2441 .to_string())
2442 }));
2443 let text = registry.prometheus_expfmt_combined().expect("text");
2444 assert!(
2445 text.contains("vllm:num_requests_running"),
2446 "engine exposition text must be appended verbatim"
2447 );
2448 }
2449
2450 #[test]
2461 fn collection_does_not_hold_the_callback_lock() {
2462 for (name, collect) in [
2463 (
2464 "typed",
2465 Box::new(|r: &MetricsRegistry| {
2466 r.execute_typed_callbacks();
2467 }) as Box<dyn Fn(&MetricsRegistry) + Send>,
2468 ),
2469 (
2470 "expfmt",
2471 Box::new(|r: &MetricsRegistry| {
2472 r.execute_expfmt_callbacks();
2473 }),
2474 ),
2475 ] {
2476 let (tx, rx) = std::sync::mpsc::channel();
2477 std::thread::spawn(move || {
2478 let registry = MetricsRegistry::new();
2479 let reentrant = registry.clone();
2480 registry.add_typed_callback(StdArc::new(move || {
2481 reentrant.add_typed_callback(StdArc::new(|| Ok(Vec::new())));
2482 Ok(Vec::new())
2483 }));
2484 let reentrant = registry.clone();
2485 registry.add_expfmt_callback(StdArc::new(move || {
2486 reentrant.add_expfmt_callback(StdArc::new(|| Ok(String::new())));
2487 Ok(String::new())
2488 }));
2489 collect(®istry);
2490 let _ = tx.send(());
2491 });
2492
2493 assert!(
2494 rx.recv_timeout(std::time::Duration::from_secs(10)).is_ok(),
2495 "{name} collection deadlocked: the callback lock was held while a \
2496 callback registered another"
2497 );
2498 }
2499 }
2500
2501 #[test]
2504 fn failing_typed_callback_is_skipped() {
2505 let registry = MetricsRegistry::new();
2506 registry.add_typed_callback(StdArc::new(|| anyhow::bail!("engine exploded")));
2507 assert!(
2508 registry
2509 .metric_families_combined()
2510 .expect("collection survives")
2511 .families
2512 .is_empty()
2513 );
2514 }
2515}