1use std::collections::{BTreeMap, BTreeSet};
23use std::fmt;
24use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
25use std::sync::{Arc, Mutex, RwLock};
26
27pub mod atomic;
29
30pub const MAX_METRIC_SERIES: usize = 100_000;
32const INTERNAL_METRIC_SERIES: usize = 2 * SAMPLE_REJECTION_REASONS.len();
34
35const MAX_LABEL_VALUE_BYTES: usize = 4 * 1024;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum MetricKind {
43 Counter,
45 Gauge,
47 Histogram,
49}
50
51impl MetricKind {
52 fn prometheus_type(self) -> &'static str {
58 match self {
59 MetricKind::Counter => "counter",
60 MetricKind::Gauge => "gauge",
61 MetricKind::Histogram => "histogram",
62 }
63 }
64}
65
66#[derive(Debug)]
68pub struct MetricDescriptor {
69 pub name: &'static str,
71 pub help: &'static str,
73 pub unit: &'static str,
75 pub kind: MetricKind,
77 pub label_names: &'static [&'static str],
79 pub histogram_bounds: &'static [f64],
81}
82
83static SAMPLE_REJECTIONS_TOTAL: MetricDescriptor = MetricDescriptor {
84 name: "nametrics_samples_rejected_total",
85 help: "统一指标目录拒绝的不合规样本累计数。",
86 unit: "",
87 kind: MetricKind::Counter,
88 label_names: &["source", "reason"],
89 histogram_bounds: &[],
90};
91
92#[derive(Clone, Copy)]
93#[repr(usize)]
94enum SampleRejectionReason {
95 UnknownFamily,
96 LabelShape,
97 LabelValueTooLong,
98 ValueKind,
99 HistogramShape,
100 UnregisteredDescriptor,
101 CardinalityLimit,
102}
103
104const SAMPLE_REJECTION_REASONS: [SampleRejectionReason; 7] = [
105 SampleRejectionReason::UnknownFamily,
106 SampleRejectionReason::LabelShape,
107 SampleRejectionReason::LabelValueTooLong,
108 SampleRejectionReason::ValueKind,
109 SampleRejectionReason::HistogramShape,
110 SampleRejectionReason::UnregisteredDescriptor,
111 SampleRejectionReason::CardinalityLimit,
112];
113
114impl SampleRejectionReason {
115 const fn index(self) -> usize {
121 self as usize
122 }
123
124 const fn label(self) -> &'static str {
130 match self {
131 Self::UnknownFamily => "unknown_family",
132 Self::LabelShape => "label_shape",
133 Self::LabelValueTooLong => "label_value_too_long",
134 Self::ValueKind => "value_kind",
135 Self::HistogramShape => "histogram_shape",
136 Self::UnregisteredDescriptor => "unregistered_descriptor",
137 Self::CardinalityLimit => "cardinality_limit",
138 }
139 }
140}
141
142#[derive(Clone, Copy)]
143enum SampleRejectionSource {
144 Native,
145 Legacy,
146}
147
148impl SampleRejectionSource {
149 const fn label(self) -> &'static str {
155 match self {
156 Self::Native => "native",
157 Self::Legacy => "legacy",
158 }
159 }
160}
161
162struct SampleRejectionCounters {
164 native: [AtomicU64; SAMPLE_REJECTION_REASONS.len()],
165 legacy: [AtomicU64; SAMPLE_REJECTION_REASONS.len()],
166}
167
168impl SampleRejectionCounters {
169 fn new() -> Self {
175 Self {
176 native: std::array::from_fn(|_| AtomicU64::new(0)),
177 legacy: std::array::from_fn(|_| AtomicU64::new(0)),
178 }
179 }
180
181 fn increment(&self, source: SampleRejectionSource, reason: SampleRejectionReason) {
189 let counters = match source {
190 SampleRejectionSource::Native => &self.native,
191 SampleRejectionSource::Legacy => &self.legacy,
192 };
193 let counter = &counters[reason.index()];
194 let _ = counter.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
195 Some(value.saturating_add(1))
196 });
197 }
198
199 fn snapshot(&self) -> Vec<MetricSample> {
205 let mut samples = Vec::new();
206 for (source, counters) in [
207 (SampleRejectionSource::Native, &self.native),
208 (SampleRejectionSource::Legacy, &self.legacy),
209 ] {
210 for reason in SAMPLE_REJECTION_REASONS {
211 let value = counters[reason.index()].load(Ordering::Relaxed);
212 if value == 0 {
213 continue;
214 }
215 samples.push(MetricSample {
216 name: SAMPLE_REJECTIONS_TOTAL.name,
217 labels: vec![
218 ("source", source.label().to_owned()),
219 ("reason", reason.label().to_owned()),
220 ],
221 value: MetricValue::Counter(value),
222 });
223 }
224 }
225 samples
226 }
227}
228
229impl MetricDescriptor {
230 fn semantically_eq(&self, other: &MetricDescriptor) -> bool {
237 self.kind == other.kind
238 && self.unit == other.unit
239 && self.help == other.help
240 && self.label_names == other.label_names
241 && self.histogram_bounds == other.histogram_bounds
242 }
243}
244
245pub trait MetricRecorder: Send + Sync {
247 fn counter(&self, descriptor: &'static MetricDescriptor, delta: u64, labels: &[&str]);
256 fn gauge(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]);
265 fn histogram(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]);
274}
275
276#[derive(Debug, Clone, PartialEq, Eq)]
278pub struct MetricConflict {
279 pub name: &'static str,
281}
282
283#[derive(Debug, Clone, PartialEq, Eq)]
285pub enum MetricSourceRegistrationError {
286 Conflict(MetricConflict),
288 SeriesBudgetExceeded,
290}
291
292impl From<MetricConflict> for MetricSourceRegistrationError {
293 fn from(conflict: MetricConflict) -> Self {
300 Self::Conflict(conflict)
301 }
302}
303
304impl fmt::Display for MetricSourceRegistrationError {
305 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
312 match self {
313 Self::Conflict(conflict) => {
314 write!(formatter, "metric descriptor `{}` conflicts", conflict.name)
315 }
316 Self::SeriesBudgetExceeded => formatter.write_str("metric series budget is exceeded"),
317 }
318 }
319}
320
321impl std::error::Error for MetricSourceRegistrationError {}
322
323pub trait LegacyMetricsSource: Send + Sync {
327 fn descriptors(&self) -> &'static [&'static MetricDescriptor];
333 fn snapshot(&self) -> Option<Vec<MetricSample>> {
340 None
341 }
342 fn render_prometheus(&self, output: &mut String);
349}
350
351enum Cell {
353 Counter(u64),
354 Gauge(f64),
355 Histogram {
356 buckets: Vec<u64>,
358 sum: f64,
359 count: u64,
360 },
361}
362
363#[derive(Clone)]
364struct RegisteredSource {
365 source: Arc<dyn LegacyMetricsSource>,
366 budget: Option<usize>,
367}
368
369pub struct MetricHub {
371 descriptors: RwLock<BTreeMap<&'static str, &'static MetricDescriptor>>,
372 cells: RwLock<BTreeMap<(&'static str, Vec<String>), Cell>>,
374 sources: RwLock<Vec<RegisteredSource>>,
377 native_series: AtomicUsize,
379 reserved_series: Mutex<usize>,
381 rejections: SampleRejectionCounters,
383}
384
385impl MetricHub {
386 pub fn new() -> Self {
392 let mut descriptors = BTreeMap::new();
393 descriptors.insert(SAMPLE_REJECTIONS_TOTAL.name, &SAMPLE_REJECTIONS_TOTAL);
394 Self {
395 descriptors: RwLock::new(descriptors),
396 cells: RwLock::new(BTreeMap::new()),
397 sources: RwLock::new(Vec::new()),
398 native_series: AtomicUsize::new(0),
399 reserved_series: Mutex::new(INTERNAL_METRIC_SERIES),
401 rejections: SampleRejectionCounters::new(),
402 }
403 }
404
405 pub fn register(&self, descriptor: &'static MetricDescriptor) -> Result<(), MetricConflict> {
418 validate_descriptor(descriptor)?;
419 if descriptor.name == SAMPLE_REJECTIONS_TOTAL.name
420 && !std::ptr::eq(descriptor, &SAMPLE_REJECTIONS_TOTAL)
421 {
422 return Err(MetricConflict {
423 name: descriptor.name,
424 });
425 }
426 let mut descriptors = self
427 .descriptors
428 .write()
429 .unwrap_or_else(std::sync::PoisonError::into_inner);
430 if let Some(existing) = descriptors.get(descriptor.name) {
431 if existing.semantically_eq(descriptor) {
432 return Ok(());
433 }
434 return Err(MetricConflict {
435 name: descriptor.name,
436 });
437 }
438 descriptors.insert(descriptor.name, descriptor);
439 Ok(())
440 }
441
442 pub fn register_legacy_source(
457 &self,
458 source: Arc<dyn LegacyMetricsSource>,
459 ) -> Result<(), MetricConflict> {
460 {
461 let sources = self
462 .sources
463 .read()
464 .unwrap_or_else(std::sync::PoisonError::into_inner);
465 if sources
466 .iter()
467 .any(|existing| Arc::ptr_eq(&existing.source, &source))
468 {
469 return Ok(());
470 }
471 }
472 let candidates = source.descriptors();
473 for descriptor in candidates {
474 validate_descriptor(descriptor)?;
475 }
476 let mut descriptors = self
477 .descriptors
478 .write()
479 .unwrap_or_else(std::sync::PoisonError::into_inner);
480 if let Some(conflict) = candidates
482 .iter()
483 .find(|descriptor| descriptors.contains_key(descriptor.name))
484 {
485 return Err(MetricConflict {
486 name: conflict.name,
487 });
488 }
489 for descriptor in source.descriptors() {
490 descriptors.insert(descriptor.name, descriptor);
491 }
492 drop(descriptors);
493 self.sources
494 .write()
495 .unwrap_or_else(std::sync::PoisonError::into_inner)
496 .push(RegisteredSource {
497 source,
498 budget: None,
499 });
500 Ok(())
501 }
502
503 pub fn register_legacy_source_reserved(
512 &self,
513 source: Arc<dyn LegacyMetricsSource>,
514 worst_case_series: usize,
515 ) -> Result<(), MetricSourceRegistrationError> {
516 let candidates = source.descriptors();
517 for descriptor in candidates {
518 validate_descriptor(descriptor)?;
519 }
520 let mut descriptors = self
521 .descriptors
522 .write()
523 .unwrap_or_else(std::sync::PoisonError::into_inner);
524 let mut sources = self
525 .sources
526 .write()
527 .unwrap_or_else(std::sync::PoisonError::into_inner);
528 if sources
529 .iter()
530 .any(|existing| Arc::ptr_eq(&existing.source, &source))
531 {
532 return Ok(());
533 }
534 if let Some(conflict) = candidates
535 .iter()
536 .find(|descriptor| descriptors.contains_key(descriptor.name))
537 {
538 return Err(MetricConflict {
539 name: conflict.name,
540 }
541 .into());
542 }
543 let cells = self
544 .cells
545 .read()
546 .unwrap_or_else(std::sync::PoisonError::into_inner);
547 let mut reserved = self
548 .reserved_series
549 .lock()
550 .unwrap_or_else(std::sync::PoisonError::into_inner);
551 let next = reserved
552 .checked_add(worst_case_series)
553 .and_then(|total| {
554 total
555 .checked_add(self.native_series.load(Ordering::Relaxed))
556 .map(|used| (total, used))
557 })
558 .filter(|(_, used)| *used <= MAX_METRIC_SERIES)
559 .map(|(total, _)| total)
560 .ok_or(MetricSourceRegistrationError::SeriesBudgetExceeded)?;
561
562 for descriptor in candidates {
564 descriptors.insert(descriptor.name, descriptor);
565 }
566 sources.push(RegisteredSource {
567 source,
568 budget: Some(worst_case_series),
569 });
570 drop(cells);
571 *reserved = next;
572 Ok(())
573 }
574
575 pub fn reserved_series(&self) -> usize {
581 *self
582 .reserved_series
583 .lock()
584 .unwrap_or_else(std::sync::PoisonError::into_inner)
585 }
586
587 pub fn committed_series(&self) -> usize {
594 let _cells = self
597 .cells
598 .read()
599 .unwrap_or_else(std::sync::PoisonError::into_inner);
600 let reserved = self
601 .reserved_series
602 .lock()
603 .unwrap_or_else(std::sync::PoisonError::into_inner);
604 reserved.saturating_add(self.native_series.load(Ordering::Relaxed))
605 }
606
607 fn validate_labels(
615 descriptor: &MetricDescriptor,
616 labels: &[&str],
617 ) -> Result<(), SampleRejectionReason> {
618 if labels.len() != descriptor.label_names.len() {
619 return Err(SampleRejectionReason::LabelShape);
620 }
621 if labels
622 .iter()
623 .any(|value| value.len() > MAX_LABEL_VALUE_BYTES)
624 {
625 return Err(SampleRejectionReason::LabelValueTooLong);
626 }
627 Ok(())
628 }
629
630 fn is_registered(&self, descriptor: &MetricDescriptor) -> bool {
637 if descriptor.name == SAMPLE_REJECTIONS_TOTAL.name {
638 return std::ptr::eq(descriptor, &SAMPLE_REJECTIONS_TOTAL);
639 }
640 self.descriptors
641 .read()
642 .unwrap_or_else(std::sync::PoisonError::into_inner)
643 .get(descriptor.name)
644 .is_some_and(|registered| registered.semantically_eq(descriptor))
645 }
646
647 fn can_insert_cell(
656 &self,
657 cells: &BTreeMap<(&'static str, Vec<String>), Cell>,
658 key: &(&'static str, Vec<String>),
659 descriptor: &MetricDescriptor,
660 ) -> bool {
661 if cells.contains_key(key) {
662 return true;
663 }
664 let reserved = *self
665 .reserved_series
666 .lock()
667 .unwrap_or_else(std::sync::PoisonError::into_inner);
668 let used = self.native_series.load(Ordering::Relaxed);
669 let cost = descriptor_series(descriptor);
670 if used
672 .checked_add(cost)
673 .and_then(|total| total.checked_add(reserved))
674 .is_none_or(|total| total > MAX_METRIC_SERIES)
675 {
676 return false;
677 }
678 self.native_series.store(used + cost, Ordering::Relaxed);
679 true
680 }
681
682 fn key(descriptor: &MetricDescriptor, labels: &[&str]) -> (&'static str, Vec<String>) {
690 (
691 descriptor.name,
692 labels.iter().map(|value| (*value).to_owned()).collect(),
693 )
694 }
695
696 pub fn snapshot(&self) -> Vec<MetricSample> {
706 self.collect_snapshot().0
707 }
708
709 fn collect_snapshot(&self) -> (Vec<MetricSample>, Vec<Arc<dyn LegacyMetricsSource>>) {
716 let mut out = Vec::new();
717 let mut text_only_sources = Vec::new();
718 let sources = self
719 .sources
720 .read()
721 .unwrap_or_else(std::sync::PoisonError::into_inner)
722 .clone();
723 let native = self.native_snapshot();
724 let native_count = native
725 .iter()
726 .filter(|sample| sample.name != SAMPLE_REJECTIONS_TOTAL.name)
727 .map(sample_series)
728 .sum::<usize>();
729 let reserved = sources
730 .iter()
731 .filter_map(|entry| entry.budget)
732 .sum::<usize>();
733 let mut remaining = MAX_METRIC_SERIES
734 .saturating_sub(INTERNAL_METRIC_SERIES)
735 .saturating_sub(native_count)
736 .saturating_sub(reserved);
737 for entry in sources {
738 let source = entry.source;
739 let Some(mut samples) = source.snapshot() else {
740 text_only_sources.push(source);
741 continue;
742 };
743 let owned: BTreeMap<&'static str, &'static MetricDescriptor> = source
744 .descriptors()
745 .iter()
746 .map(|descriptor| (descriptor.name, *descriptor))
747 .collect();
748 samples.sort_by(|left, right| {
750 left.name
751 .cmp(right.name)
752 .then_with(|| left.labels.cmp(&right.labels))
753 });
754 let mut available = entry.budget.unwrap_or(remaining);
755 for sample in samples {
756 let Some(descriptor) = owned.get(sample.name).copied() else {
757 self.rejections.increment(
758 SampleRejectionSource::Legacy,
759 SampleRejectionReason::UnknownFamily,
760 );
761 continue;
762 };
763 match validate_sample(&sample, descriptor) {
764 Ok(()) => {
765 let cost = sample_series(&sample);
766 if cost > available {
768 self.rejections.increment(
769 SampleRejectionSource::Legacy,
770 SampleRejectionReason::CardinalityLimit,
771 );
772 continue;
773 }
774 available -= cost;
775 out.push(sample);
776 }
777 Err(reason) => self
778 .rejections
779 .increment(SampleRejectionSource::Legacy, reason),
780 }
781 }
782 if entry.budget.is_none() {
783 remaining = available;
784 }
785 }
786 out.extend(
787 native
788 .into_iter()
789 .filter(|sample| sample.name != SAMPLE_REJECTIONS_TOTAL.name),
790 );
791 out.extend(self.rejections.snapshot());
793 out.sort_by(|left, right| {
794 left.name
795 .cmp(right.name)
796 .then_with(|| left.labels.cmp(&right.labels))
797 });
798 (out, text_only_sources)
799 }
800
801 fn native_snapshot(&self) -> Vec<MetricSample> {
807 let descriptors = self
808 .descriptors
809 .read()
810 .unwrap_or_else(std::sync::PoisonError::into_inner);
811 let cells = self
812 .cells
813 .read()
814 .unwrap_or_else(std::sync::PoisonError::into_inner);
815 let mut out = Vec::with_capacity(cells.len());
816 for ((name, label_values), cell) in cells.iter() {
817 let Some(descriptor) = descriptors.get(name) else {
818 continue;
819 };
820 let labels: Vec<(&'static str, String)> = descriptor
821 .label_names
822 .iter()
823 .copied()
824 .zip(label_values.iter().cloned())
825 .collect();
826 let value = match cell {
827 Cell::Counter(v) => MetricValue::Counter(*v),
828 Cell::Gauge(v) => MetricValue::Gauge(*v),
829 Cell::Histogram {
830 buckets,
831 sum,
832 count,
833 } => MetricValue::Histogram {
834 bounds: descriptor.histogram_bounds,
835 buckets: buckets.clone(),
836 sum: *sum,
837 count: *count,
838 },
839 };
840 out.push(MetricSample {
841 name,
842 labels,
843 value,
844 });
845 }
846 drop(cells);
847 drop(descriptors);
848 out.extend(self.rejections.snapshot());
849 out
850 }
851
852 pub fn family_snapshot(&self) -> Vec<MetricFamilySnapshot> {
859 let samples = self.snapshot();
860 let descriptors = self
861 .descriptors
862 .read()
863 .unwrap_or_else(std::sync::PoisonError::into_inner);
864 let mut families: BTreeMap<&'static str, MetricFamilySnapshot> = BTreeMap::new();
865 for sample in samples {
866 let Some(descriptor) = descriptors.get(sample.name).copied() else {
867 continue;
868 };
869 families
870 .entry(descriptor.name)
871 .or_insert_with(|| MetricFamilySnapshot {
872 name: descriptor.name,
873 description: descriptor.help,
874 unit: descriptor.unit,
875 kind: descriptor.kind,
876 histogram_bounds: descriptor.histogram_bounds,
877 samples: Vec::new(),
878 })
879 .samples
880 .push(sample);
881 }
882 families.into_values().collect()
883 }
884
885 pub fn render_prometheus(&self, output: &mut String) {
896 use std::fmt::Write as _;
897 let (samples, text_only_sources) = self.collect_snapshot();
899 let text_only_names: BTreeSet<&'static str> = text_only_sources
900 .iter()
901 .flat_map(|source| source.descriptors().iter().map(|d| d.name))
902 .collect();
903 let descriptors = self
904 .descriptors
905 .read()
906 .unwrap_or_else(std::sync::PoisonError::into_inner);
907 for (name, descriptor) in descriptors.iter() {
909 if text_only_names.contains(name) {
910 continue;
911 }
912 if *name == SAMPLE_REJECTIONS_TOTAL.name
913 && !samples.iter().any(|sample| sample.name == *name)
914 {
915 continue;
916 }
917 let _ = writeln!(output, "# HELP {name} {}", descriptor.help);
918 let _ = writeln!(
919 output,
920 "# TYPE {name} {}",
921 descriptor.kind.prometheus_type()
922 );
923 for sample in samples.iter().filter(|s| s.name == *name) {
924 sample.render_prometheus(output);
925 }
926 }
927 drop(descriptors);
928 for source in text_only_sources {
930 source.render_prometheus(output);
931 }
932 }
933}
934
935fn descriptor_series(descriptor: &MetricDescriptor) -> usize {
942 if descriptor.kind == MetricKind::Histogram {
943 descriptor.histogram_bounds.len() + 3
944 } else {
945 1
946 }
947}
948
949fn sample_series(sample: &MetricSample) -> usize {
956 match &sample.value {
957 MetricValue::Histogram {
958 bounds,
959 ..
960 } => bounds.len() + 3,
961 _ => 1,
962 }
963}
964
965fn validate_sample(
973 sample: &MetricSample,
974 descriptor: &MetricDescriptor,
975) -> Result<(), SampleRejectionReason> {
976 if sample.name != descriptor.name
977 || sample.labels.len() != descriptor.label_names.len()
978 || sample
979 .labels
980 .iter()
981 .zip(descriptor.label_names)
982 .any(|((actual, _), expected)| actual != expected)
983 {
984 return Err(SampleRejectionReason::LabelShape);
985 }
986 if sample
987 .labels
988 .iter()
989 .any(|(_, value)| value.len() > MAX_LABEL_VALUE_BYTES)
990 {
991 return Err(SampleRejectionReason::LabelValueTooLong);
992 }
993 match (&sample.value, descriptor.kind) {
994 (MetricValue::Counter(_), MetricKind::Counter)
995 | (MetricValue::Gauge(_), MetricKind::Gauge) => Ok(()),
996 (
997 MetricValue::Histogram {
998 bounds,
999 buckets,
1000 count,
1001 ..
1002 },
1003 MetricKind::Histogram,
1004 ) => {
1005 if *bounds == descriptor.histogram_bounds
1006 && buckets.len() == bounds.len() + 1
1007 && buckets.iter().copied().fold(0_u64, u64::saturating_add) == *count
1008 {
1009 Ok(())
1010 } else {
1011 Err(SampleRejectionReason::HistogramShape)
1012 }
1013 }
1014 _ => Err(SampleRejectionReason::ValueKind),
1015 }
1016}
1017
1018impl Default for MetricHub {
1019 fn default() -> Self {
1025 Self::new()
1026 }
1027}
1028
1029impl MetricRecorder for MetricHub {
1030 fn counter(&self, descriptor: &'static MetricDescriptor, delta: u64, labels: &[&str]) {
1039 if let Err(reason) = Self::validate_labels(descriptor, labels) {
1040 self.rejections
1041 .increment(SampleRejectionSource::Native, reason);
1042 return;
1043 }
1044 if !self.is_registered(descriptor) {
1045 self.rejections.increment(
1046 SampleRejectionSource::Native,
1047 SampleRejectionReason::UnregisteredDescriptor,
1048 );
1049 return;
1050 }
1051 let mut cells = self
1052 .cells
1053 .write()
1054 .unwrap_or_else(std::sync::PoisonError::into_inner);
1055 let key = Self::key(descriptor, labels);
1056 if !self.can_insert_cell(&cells, &key, descriptor) {
1057 self.rejections.increment(
1058 SampleRejectionSource::Native,
1059 SampleRejectionReason::CardinalityLimit,
1060 );
1061 return;
1062 }
1063 match cells.entry(key).or_insert(Cell::Counter(0)) {
1064 Cell::Counter(v) => *v = v.saturating_add(delta),
1065 _ => debug_assert!(false, "metric `{}` kind mismatch", descriptor.name),
1066 }
1067 }
1068
1069 fn gauge(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]) {
1078 if let Err(reason) = Self::validate_labels(descriptor, labels) {
1079 self.rejections
1080 .increment(SampleRejectionSource::Native, reason);
1081 return;
1082 }
1083 if !self.is_registered(descriptor) {
1084 self.rejections.increment(
1085 SampleRejectionSource::Native,
1086 SampleRejectionReason::UnregisteredDescriptor,
1087 );
1088 return;
1089 }
1090 let mut cells = self
1091 .cells
1092 .write()
1093 .unwrap_or_else(std::sync::PoisonError::into_inner);
1094 let key = Self::key(descriptor, labels);
1095 if !self.can_insert_cell(&cells, &key, descriptor) {
1096 self.rejections.increment(
1097 SampleRejectionSource::Native,
1098 SampleRejectionReason::CardinalityLimit,
1099 );
1100 return;
1101 }
1102 match cells.entry(key).or_insert(Cell::Gauge(0.0)) {
1103 Cell::Gauge(v) => *v = value,
1104 _ => debug_assert!(false, "metric `{}` kind mismatch", descriptor.name),
1105 }
1106 }
1107
1108 fn histogram(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]) {
1117 if let Err(reason) = Self::validate_labels(descriptor, labels) {
1118 self.rejections
1119 .increment(SampleRejectionSource::Native, reason);
1120 return;
1121 }
1122 if !self.is_registered(descriptor) {
1123 self.rejections.increment(
1124 SampleRejectionSource::Native,
1125 SampleRejectionReason::UnregisteredDescriptor,
1126 );
1127 return;
1128 }
1129 let bounds = descriptor.histogram_bounds;
1130 let mut cells = self
1131 .cells
1132 .write()
1133 .unwrap_or_else(std::sync::PoisonError::into_inner);
1134 let key = Self::key(descriptor, labels);
1135 if !self.can_insert_cell(&cells, &key, descriptor) {
1136 self.rejections.increment(
1137 SampleRejectionSource::Native,
1138 SampleRejectionReason::CardinalityLimit,
1139 );
1140 return;
1141 }
1142 let cell = cells.entry(key).or_insert_with(|| Cell::Histogram {
1143 buckets: vec![0; bounds.len() + 1],
1144 sum: 0.0,
1145 count: 0,
1146 });
1147 if let Cell::Histogram {
1148 buckets,
1149 sum,
1150 count,
1151 } = cell
1152 {
1153 let index = bounds
1155 .iter()
1156 .position(|bound| value <= *bound)
1157 .unwrap_or(bounds.len());
1158 buckets[index] = buckets[index].saturating_add(1);
1159 *sum += value;
1160 *count = count.saturating_add(1);
1161 } else {
1162 debug_assert!(false, "metric `{}` kind mismatch", descriptor.name);
1163 }
1164 }
1165}
1166
1167fn validate_descriptor(descriptor: &'static MetricDescriptor) -> Result<(), MetricConflict> {
1174 let valid_name = |name: &str| {
1175 let mut bytes = name.bytes();
1176 bytes
1177 .next()
1178 .is_some_and(|byte| byte.is_ascii_alphabetic() || matches!(byte, b'_' | b':'))
1179 && bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b':'))
1180 };
1181 let valid_label = |name: &str| {
1182 let mut bytes = name.bytes();
1183 bytes
1184 .next()
1185 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
1186 && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
1187 };
1188 let labels: BTreeSet<&str> = descriptor.label_names.iter().copied().collect();
1189 let invalid = !valid_name(descriptor.name)
1190 || descriptor.help.is_empty()
1191 || descriptor.help.contains(['\n', '\r'])
1192 || labels.len() != descriptor.label_names.len()
1193 || descriptor
1194 .label_names
1195 .iter()
1196 .any(|name| !valid_label(name) || *name == "le")
1197 || match descriptor.kind {
1198 MetricKind::Histogram => {
1199 descriptor.histogram_bounds.is_empty()
1200 || descriptor
1201 .histogram_bounds
1202 .iter()
1203 .any(|bound| !bound.is_finite())
1204 || descriptor
1205 .histogram_bounds
1206 .windows(2)
1207 .any(|pair| pair[0] >= pair[1])
1208 }
1209 MetricKind::Counter | MetricKind::Gauge => !descriptor.histogram_bounds.is_empty(),
1210 };
1211 if invalid {
1212 Err(MetricConflict {
1213 name: descriptor.name,
1214 })
1215 } else {
1216 Ok(())
1217 }
1218}
1219
1220#[derive(Debug, Clone)]
1222pub struct MetricSample {
1223 pub name: &'static str,
1225 pub labels: Vec<(&'static str, String)>,
1227 pub value: MetricValue,
1229}
1230
1231#[derive(Debug, Clone)]
1233pub struct MetricFamilySnapshot {
1234 pub name: &'static str,
1236 pub description: &'static str,
1238 pub unit: &'static str,
1240 pub kind: MetricKind,
1242 pub histogram_bounds: &'static [f64],
1244 pub samples: Vec<MetricSample>,
1246}
1247
1248impl MetricSample {
1249 fn render_prometheus(&self, output: &mut String) {
1256 use std::fmt::Write as _;
1257 match &self.value {
1258 MetricValue::Counter(v) => {
1259 output.push_str(self.name);
1260 self.render_labels(output, &[]);
1261 let _ = writeln!(output, " {v}");
1262 }
1263 MetricValue::Gauge(v) => {
1264 output.push_str(self.name);
1265 self.render_labels(output, &[]);
1266 let _ = writeln!(output, " {v}");
1267 }
1268 MetricValue::Histogram {
1269 bounds,
1270 buckets,
1271 sum,
1272 count,
1273 } => {
1274 let mut cumulative = 0u64;
1276 for (i, bound) in bounds.iter().enumerate() {
1277 cumulative = cumulative.saturating_add(buckets[i]);
1278 let le = format!("{bound}");
1279 let _ = write!(output, "{}_bucket", self.name);
1280 self.render_labels(output, &[("le", le.as_str())]);
1281 let _ = writeln!(output, " {cumulative}");
1282 }
1283 cumulative = cumulative.saturating_add(buckets[bounds.len()]);
1284 let _ = write!(output, "{}_bucket", self.name);
1285 self.render_labels(output, &[("le", "+Inf")]);
1286 let _ = writeln!(output, " {cumulative}");
1287 let _ = write!(output, "{}_sum", self.name);
1288 self.render_labels(output, &[]);
1289 let _ = writeln!(output, " {sum}");
1290 let _ = write!(output, "{}_count", self.name);
1291 self.render_labels(output, &[]);
1292 let _ = writeln!(output, " {count}");
1293 }
1294 }
1295 }
1296
1297 fn render_labels(&self, output: &mut String, extra: &[(&str, &str)]) {
1305 if self.labels.is_empty() && extra.is_empty() {
1306 return;
1307 }
1308 output.push('{');
1309 for (index, (key, value)) in self
1310 .labels
1311 .iter()
1312 .map(|(key, value)| (*key, value.as_str()))
1313 .chain(extra.iter().copied())
1314 .enumerate()
1315 {
1316 if index != 0 {
1317 output.push(',');
1318 }
1319 output.push_str(key);
1320 output.push_str("=\"");
1321 append_escaped_label(output, value);
1322 output.push('"');
1323 }
1324 output.push('}');
1325 }
1326}
1327
1328fn append_escaped_label(output: &mut String, value: &str) {
1336 let mut start = 0;
1337 for (index, byte) in value.bytes().enumerate() {
1338 let escaped = match byte {
1339 b'\\' => "\\\\",
1340 b'"' => "\\\"",
1341 b'\n' => "\\n",
1342 _ => continue,
1343 };
1344 output.push_str(&value[start..index]);
1346 output.push_str(escaped);
1347 start = index + 1;
1348 }
1349 output.push_str(&value[start..]);
1350}
1351
1352#[derive(Debug, Clone)]
1354pub enum MetricValue {
1355 Counter(u64),
1357 Gauge(f64),
1359 Histogram {
1361 bounds: &'static [f64],
1363 buckets: Vec<u64>,
1365 sum: f64,
1367 count: u64,
1369 },
1370}