use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, RwLock};
pub mod atomic;
pub const MAX_METRIC_SERIES: usize = 100_000;
const INTERNAL_METRIC_SERIES: usize = 2 * SAMPLE_REJECTION_REASONS.len();
const MAX_LABEL_VALUE_BYTES: usize = 4 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MetricKind {
Counter,
Gauge,
Histogram,
}
impl MetricKind {
fn prometheus_type(self) -> &'static str {
match self {
MetricKind::Counter => "counter",
MetricKind::Gauge => "gauge",
MetricKind::Histogram => "histogram",
}
}
}
#[derive(Debug)]
pub struct MetricDescriptor {
pub name: &'static str,
pub help: &'static str,
pub unit: &'static str,
pub kind: MetricKind,
pub label_names: &'static [&'static str],
pub histogram_bounds: &'static [f64],
}
static SAMPLE_REJECTIONS_TOTAL: MetricDescriptor = MetricDescriptor {
name: "nametrics_samples_rejected_total",
help: "统一指标目录拒绝的不合规样本累计数。",
unit: "",
kind: MetricKind::Counter,
label_names: &["source", "reason"],
histogram_bounds: &[],
};
#[derive(Clone, Copy)]
#[repr(usize)]
enum SampleRejectionReason {
UnknownFamily,
LabelShape,
LabelValueTooLong,
ValueKind,
HistogramShape,
UnregisteredDescriptor,
CardinalityLimit,
}
const SAMPLE_REJECTION_REASONS: [SampleRejectionReason; 7] = [
SampleRejectionReason::UnknownFamily,
SampleRejectionReason::LabelShape,
SampleRejectionReason::LabelValueTooLong,
SampleRejectionReason::ValueKind,
SampleRejectionReason::HistogramShape,
SampleRejectionReason::UnregisteredDescriptor,
SampleRejectionReason::CardinalityLimit,
];
impl SampleRejectionReason {
const fn index(self) -> usize {
self as usize
}
const fn label(self) -> &'static str {
match self {
Self::UnknownFamily => "unknown_family",
Self::LabelShape => "label_shape",
Self::LabelValueTooLong => "label_value_too_long",
Self::ValueKind => "value_kind",
Self::HistogramShape => "histogram_shape",
Self::UnregisteredDescriptor => "unregistered_descriptor",
Self::CardinalityLimit => "cardinality_limit",
}
}
}
#[derive(Clone, Copy)]
enum SampleRejectionSource {
Native,
Legacy,
}
impl SampleRejectionSource {
const fn label(self) -> &'static str {
match self {
Self::Native => "native",
Self::Legacy => "legacy",
}
}
}
struct SampleRejectionCounters {
native: [AtomicU64; SAMPLE_REJECTION_REASONS.len()],
legacy: [AtomicU64; SAMPLE_REJECTION_REASONS.len()],
}
impl SampleRejectionCounters {
fn new() -> Self {
Self {
native: std::array::from_fn(|_| AtomicU64::new(0)),
legacy: std::array::from_fn(|_| AtomicU64::new(0)),
}
}
fn increment(&self, source: SampleRejectionSource, reason: SampleRejectionReason) {
let counters = match source {
SampleRejectionSource::Native => &self.native,
SampleRejectionSource::Legacy => &self.legacy,
};
let counter = &counters[reason.index()];
let _ = counter.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
Some(value.saturating_add(1))
});
}
fn snapshot(&self) -> Vec<MetricSample> {
let mut samples = Vec::new();
for (source, counters) in [
(SampleRejectionSource::Native, &self.native),
(SampleRejectionSource::Legacy, &self.legacy),
] {
for reason in SAMPLE_REJECTION_REASONS {
let value = counters[reason.index()].load(Ordering::Relaxed);
if value == 0 {
continue;
}
samples.push(MetricSample {
name: SAMPLE_REJECTIONS_TOTAL.name,
labels: vec![
("source", source.label().to_owned()),
("reason", reason.label().to_owned()),
],
value: MetricValue::Counter(value),
});
}
}
samples
}
}
impl MetricDescriptor {
fn semantically_eq(&self, other: &MetricDescriptor) -> bool {
self.kind == other.kind
&& self.unit == other.unit
&& self.help == other.help
&& self.label_names == other.label_names
&& self.histogram_bounds == other.histogram_bounds
}
}
pub trait MetricRecorder: Send + Sync {
fn counter(&self, descriptor: &'static MetricDescriptor, delta: u64, labels: &[&str]);
fn gauge(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]);
fn histogram(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]);
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetricConflict {
pub name: &'static str,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetricSourceRegistrationError {
Conflict(MetricConflict),
SeriesBudgetExceeded,
}
impl From<MetricConflict> for MetricSourceRegistrationError {
fn from(conflict: MetricConflict) -> Self {
Self::Conflict(conflict)
}
}
impl fmt::Display for MetricSourceRegistrationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Conflict(conflict) => {
write!(formatter, "metric descriptor `{}` conflicts", conflict.name)
}
Self::SeriesBudgetExceeded => formatter.write_str("metric series budget is exceeded"),
}
}
}
impl std::error::Error for MetricSourceRegistrationError {}
pub trait LegacyMetricsSource: Send + Sync {
fn descriptors(&self) -> &'static [&'static MetricDescriptor];
fn snapshot(&self) -> Option<Vec<MetricSample>> {
None
}
fn render_prometheus(&self, output: &mut String);
}
enum Cell {
Counter(u64),
Gauge(f64),
Histogram {
buckets: Vec<u64>,
sum: f64,
count: u64,
},
}
#[derive(Clone)]
struct RegisteredSource {
source: Arc<dyn LegacyMetricsSource>,
budget: Option<usize>,
}
pub struct MetricHub {
descriptors: RwLock<BTreeMap<&'static str, &'static MetricDescriptor>>,
cells: RwLock<BTreeMap<(&'static str, Vec<String>), Cell>>,
sources: RwLock<Vec<RegisteredSource>>,
native_series: AtomicUsize,
reserved_series: Mutex<usize>,
rejections: SampleRejectionCounters,
}
impl MetricHub {
pub fn new() -> Self {
let mut descriptors = BTreeMap::new();
descriptors.insert(SAMPLE_REJECTIONS_TOTAL.name, &SAMPLE_REJECTIONS_TOTAL);
Self {
descriptors: RwLock::new(descriptors),
cells: RwLock::new(BTreeMap::new()),
sources: RwLock::new(Vec::new()),
native_series: AtomicUsize::new(0),
reserved_series: Mutex::new(INTERNAL_METRIC_SERIES),
rejections: SampleRejectionCounters::new(),
}
}
pub fn register(&self, descriptor: &'static MetricDescriptor) -> Result<(), MetricConflict> {
validate_descriptor(descriptor)?;
if descriptor.name == SAMPLE_REJECTIONS_TOTAL.name
&& !std::ptr::eq(descriptor, &SAMPLE_REJECTIONS_TOTAL)
{
return Err(MetricConflict {
name: descriptor.name,
});
}
let mut descriptors = self
.descriptors
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(existing) = descriptors.get(descriptor.name) {
if existing.semantically_eq(descriptor) {
return Ok(());
}
return Err(MetricConflict {
name: descriptor.name,
});
}
descriptors.insert(descriptor.name, descriptor);
Ok(())
}
pub fn register_legacy_source(
&self,
source: Arc<dyn LegacyMetricsSource>,
) -> Result<(), MetricConflict> {
{
let sources = self
.sources
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if sources
.iter()
.any(|existing| Arc::ptr_eq(&existing.source, &source))
{
return Ok(());
}
}
let candidates = source.descriptors();
for descriptor in candidates {
validate_descriptor(descriptor)?;
}
let mut descriptors = self
.descriptors
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(conflict) = candidates
.iter()
.find(|descriptor| descriptors.contains_key(descriptor.name))
{
return Err(MetricConflict {
name: conflict.name,
});
}
for descriptor in source.descriptors() {
descriptors.insert(descriptor.name, descriptor);
}
drop(descriptors);
self.sources
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(RegisteredSource {
source,
budget: None,
});
Ok(())
}
pub fn register_legacy_source_reserved(
&self,
source: Arc<dyn LegacyMetricsSource>,
worst_case_series: usize,
) -> Result<(), MetricSourceRegistrationError> {
let candidates = source.descriptors();
for descriptor in candidates {
validate_descriptor(descriptor)?;
}
let mut descriptors = self
.descriptors
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let mut sources = self
.sources
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if sources
.iter()
.any(|existing| Arc::ptr_eq(&existing.source, &source))
{
return Ok(());
}
if let Some(conflict) = candidates
.iter()
.find(|descriptor| descriptors.contains_key(descriptor.name))
{
return Err(MetricConflict {
name: conflict.name,
}
.into());
}
let cells = self
.cells
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let mut reserved = self
.reserved_series
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let next = reserved
.checked_add(worst_case_series)
.and_then(|total| {
total
.checked_add(self.native_series.load(Ordering::Relaxed))
.map(|used| (total, used))
})
.filter(|(_, used)| *used <= MAX_METRIC_SERIES)
.map(|(total, _)| total)
.ok_or(MetricSourceRegistrationError::SeriesBudgetExceeded)?;
for descriptor in candidates {
descriptors.insert(descriptor.name, descriptor);
}
sources.push(RegisteredSource {
source,
budget: Some(worst_case_series),
});
drop(cells);
*reserved = next;
Ok(())
}
pub fn reserved_series(&self) -> usize {
*self
.reserved_series
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn committed_series(&self) -> usize {
let _cells = self
.cells
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let reserved = self
.reserved_series
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
reserved.saturating_add(self.native_series.load(Ordering::Relaxed))
}
fn validate_labels(
descriptor: &MetricDescriptor,
labels: &[&str],
) -> Result<(), SampleRejectionReason> {
if labels.len() != descriptor.label_names.len() {
return Err(SampleRejectionReason::LabelShape);
}
if labels
.iter()
.any(|value| value.len() > MAX_LABEL_VALUE_BYTES)
{
return Err(SampleRejectionReason::LabelValueTooLong);
}
Ok(())
}
fn is_registered(&self, descriptor: &MetricDescriptor) -> bool {
if descriptor.name == SAMPLE_REJECTIONS_TOTAL.name {
return std::ptr::eq(descriptor, &SAMPLE_REJECTIONS_TOTAL);
}
self.descriptors
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.get(descriptor.name)
.is_some_and(|registered| registered.semantically_eq(descriptor))
}
fn can_insert_cell(
&self,
cells: &BTreeMap<(&'static str, Vec<String>), Cell>,
key: &(&'static str, Vec<String>),
descriptor: &MetricDescriptor,
) -> bool {
if cells.contains_key(key) {
return true;
}
let reserved = *self
.reserved_series
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let used = self.native_series.load(Ordering::Relaxed);
let cost = descriptor_series(descriptor);
if used
.checked_add(cost)
.and_then(|total| total.checked_add(reserved))
.is_none_or(|total| total > MAX_METRIC_SERIES)
{
return false;
}
self.native_series.store(used + cost, Ordering::Relaxed);
true
}
fn key(descriptor: &MetricDescriptor, labels: &[&str]) -> (&'static str, Vec<String>) {
(
descriptor.name,
labels.iter().map(|value| (*value).to_owned()).collect(),
)
}
pub fn snapshot(&self) -> Vec<MetricSample> {
self.collect_snapshot().0
}
fn collect_snapshot(&self) -> (Vec<MetricSample>, Vec<Arc<dyn LegacyMetricsSource>>) {
let mut out = Vec::new();
let mut text_only_sources = Vec::new();
let sources = self
.sources
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
let native = self.native_snapshot();
let native_count = native
.iter()
.filter(|sample| sample.name != SAMPLE_REJECTIONS_TOTAL.name)
.map(sample_series)
.sum::<usize>();
let reserved = sources
.iter()
.filter_map(|entry| entry.budget)
.sum::<usize>();
let mut remaining = MAX_METRIC_SERIES
.saturating_sub(INTERNAL_METRIC_SERIES)
.saturating_sub(native_count)
.saturating_sub(reserved);
for entry in sources {
let source = entry.source;
let Some(mut samples) = source.snapshot() else {
text_only_sources.push(source);
continue;
};
let owned: BTreeMap<&'static str, &'static MetricDescriptor> = source
.descriptors()
.iter()
.map(|descriptor| (descriptor.name, *descriptor))
.collect();
samples.sort_by(|left, right| {
left.name
.cmp(right.name)
.then_with(|| left.labels.cmp(&right.labels))
});
let mut available = entry.budget.unwrap_or(remaining);
for sample in samples {
let Some(descriptor) = owned.get(sample.name).copied() else {
self.rejections.increment(
SampleRejectionSource::Legacy,
SampleRejectionReason::UnknownFamily,
);
continue;
};
match validate_sample(&sample, descriptor) {
Ok(()) => {
let cost = sample_series(&sample);
if cost > available {
self.rejections.increment(
SampleRejectionSource::Legacy,
SampleRejectionReason::CardinalityLimit,
);
continue;
}
available -= cost;
out.push(sample);
}
Err(reason) => self
.rejections
.increment(SampleRejectionSource::Legacy, reason),
}
}
if entry.budget.is_none() {
remaining = available;
}
}
out.extend(
native
.into_iter()
.filter(|sample| sample.name != SAMPLE_REJECTIONS_TOTAL.name),
);
out.extend(self.rejections.snapshot());
out.sort_by(|left, right| {
left.name
.cmp(right.name)
.then_with(|| left.labels.cmp(&right.labels))
});
(out, text_only_sources)
}
fn native_snapshot(&self) -> Vec<MetricSample> {
let descriptors = self
.descriptors
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let cells = self
.cells
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let mut out = Vec::with_capacity(cells.len());
for ((name, label_values), cell) in cells.iter() {
let Some(descriptor) = descriptors.get(name) else {
continue;
};
let labels: Vec<(&'static str, String)> = descriptor
.label_names
.iter()
.copied()
.zip(label_values.iter().cloned())
.collect();
let value = match cell {
Cell::Counter(v) => MetricValue::Counter(*v),
Cell::Gauge(v) => MetricValue::Gauge(*v),
Cell::Histogram {
buckets,
sum,
count,
} => MetricValue::Histogram {
bounds: descriptor.histogram_bounds,
buckets: buckets.clone(),
sum: *sum,
count: *count,
},
};
out.push(MetricSample {
name,
labels,
value,
});
}
drop(cells);
drop(descriptors);
out.extend(self.rejections.snapshot());
out
}
pub fn family_snapshot(&self) -> Vec<MetricFamilySnapshot> {
let samples = self.snapshot();
let descriptors = self
.descriptors
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let mut families: BTreeMap<&'static str, MetricFamilySnapshot> = BTreeMap::new();
for sample in samples {
let Some(descriptor) = descriptors.get(sample.name).copied() else {
continue;
};
families
.entry(descriptor.name)
.or_insert_with(|| MetricFamilySnapshot {
name: descriptor.name,
description: descriptor.help,
unit: descriptor.unit,
kind: descriptor.kind,
histogram_bounds: descriptor.histogram_bounds,
samples: Vec::new(),
})
.samples
.push(sample);
}
families.into_values().collect()
}
pub fn render_prometheus(&self, output: &mut String) {
use std::fmt::Write as _;
let (samples, text_only_sources) = self.collect_snapshot();
let text_only_names: BTreeSet<&'static str> = text_only_sources
.iter()
.flat_map(|source| source.descriptors().iter().map(|d| d.name))
.collect();
let descriptors = self
.descriptors
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
for (name, descriptor) in descriptors.iter() {
if text_only_names.contains(name) {
continue;
}
if *name == SAMPLE_REJECTIONS_TOTAL.name
&& !samples.iter().any(|sample| sample.name == *name)
{
continue;
}
let _ = writeln!(output, "# HELP {name} {}", descriptor.help);
let _ = writeln!(
output,
"# TYPE {name} {}",
descriptor.kind.prometheus_type()
);
for sample in samples.iter().filter(|s| s.name == *name) {
sample.render_prometheus(output);
}
}
drop(descriptors);
for source in text_only_sources {
source.render_prometheus(output);
}
}
}
fn descriptor_series(descriptor: &MetricDescriptor) -> usize {
if descriptor.kind == MetricKind::Histogram {
descriptor.histogram_bounds.len() + 3
} else {
1
}
}
fn sample_series(sample: &MetricSample) -> usize {
match &sample.value {
MetricValue::Histogram {
bounds,
..
} => bounds.len() + 3,
_ => 1,
}
}
fn validate_sample(
sample: &MetricSample,
descriptor: &MetricDescriptor,
) -> Result<(), SampleRejectionReason> {
if sample.name != descriptor.name
|| sample.labels.len() != descriptor.label_names.len()
|| sample
.labels
.iter()
.zip(descriptor.label_names)
.any(|((actual, _), expected)| actual != expected)
{
return Err(SampleRejectionReason::LabelShape);
}
if sample
.labels
.iter()
.any(|(_, value)| value.len() > MAX_LABEL_VALUE_BYTES)
{
return Err(SampleRejectionReason::LabelValueTooLong);
}
match (&sample.value, descriptor.kind) {
(MetricValue::Counter(_), MetricKind::Counter)
| (MetricValue::Gauge(_), MetricKind::Gauge) => Ok(()),
(
MetricValue::Histogram {
bounds,
buckets,
count,
..
},
MetricKind::Histogram,
) => {
if *bounds == descriptor.histogram_bounds
&& buckets.len() == bounds.len() + 1
&& buckets.iter().copied().fold(0_u64, u64::saturating_add) == *count
{
Ok(())
} else {
Err(SampleRejectionReason::HistogramShape)
}
}
_ => Err(SampleRejectionReason::ValueKind),
}
}
impl Default for MetricHub {
fn default() -> Self {
Self::new()
}
}
impl MetricRecorder for MetricHub {
fn counter(&self, descriptor: &'static MetricDescriptor, delta: u64, labels: &[&str]) {
if let Err(reason) = Self::validate_labels(descriptor, labels) {
self.rejections
.increment(SampleRejectionSource::Native, reason);
return;
}
if !self.is_registered(descriptor) {
self.rejections.increment(
SampleRejectionSource::Native,
SampleRejectionReason::UnregisteredDescriptor,
);
return;
}
let mut cells = self
.cells
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let key = Self::key(descriptor, labels);
if !self.can_insert_cell(&cells, &key, descriptor) {
self.rejections.increment(
SampleRejectionSource::Native,
SampleRejectionReason::CardinalityLimit,
);
return;
}
match cells.entry(key).or_insert(Cell::Counter(0)) {
Cell::Counter(v) => *v = v.saturating_add(delta),
_ => debug_assert!(false, "metric `{}` kind mismatch", descriptor.name),
}
}
fn gauge(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]) {
if let Err(reason) = Self::validate_labels(descriptor, labels) {
self.rejections
.increment(SampleRejectionSource::Native, reason);
return;
}
if !self.is_registered(descriptor) {
self.rejections.increment(
SampleRejectionSource::Native,
SampleRejectionReason::UnregisteredDescriptor,
);
return;
}
let mut cells = self
.cells
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let key = Self::key(descriptor, labels);
if !self.can_insert_cell(&cells, &key, descriptor) {
self.rejections.increment(
SampleRejectionSource::Native,
SampleRejectionReason::CardinalityLimit,
);
return;
}
match cells.entry(key).or_insert(Cell::Gauge(0.0)) {
Cell::Gauge(v) => *v = value,
_ => debug_assert!(false, "metric `{}` kind mismatch", descriptor.name),
}
}
fn histogram(&self, descriptor: &'static MetricDescriptor, value: f64, labels: &[&str]) {
if let Err(reason) = Self::validate_labels(descriptor, labels) {
self.rejections
.increment(SampleRejectionSource::Native, reason);
return;
}
if !self.is_registered(descriptor) {
self.rejections.increment(
SampleRejectionSource::Native,
SampleRejectionReason::UnregisteredDescriptor,
);
return;
}
let bounds = descriptor.histogram_bounds;
let mut cells = self
.cells
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let key = Self::key(descriptor, labels);
if !self.can_insert_cell(&cells, &key, descriptor) {
self.rejections.increment(
SampleRejectionSource::Native,
SampleRejectionReason::CardinalityLimit,
);
return;
}
let cell = cells.entry(key).or_insert_with(|| Cell::Histogram {
buckets: vec![0; bounds.len() + 1],
sum: 0.0,
count: 0,
});
if let Cell::Histogram {
buckets,
sum,
count,
} = cell
{
let index = bounds
.iter()
.position(|bound| value <= *bound)
.unwrap_or(bounds.len());
buckets[index] = buckets[index].saturating_add(1);
*sum += value;
*count = count.saturating_add(1);
} else {
debug_assert!(false, "metric `{}` kind mismatch", descriptor.name);
}
}
}
fn validate_descriptor(descriptor: &'static MetricDescriptor) -> Result<(), MetricConflict> {
let valid_name = |name: &str| {
let mut bytes = name.bytes();
bytes
.next()
.is_some_and(|byte| byte.is_ascii_alphabetic() || matches!(byte, b'_' | b':'))
&& bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b':'))
};
let valid_label = |name: &str| {
let mut bytes = name.bytes();
bytes
.next()
.is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
&& bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
};
let labels: BTreeSet<&str> = descriptor.label_names.iter().copied().collect();
let invalid = !valid_name(descriptor.name)
|| descriptor.help.is_empty()
|| descriptor.help.contains(['\n', '\r'])
|| labels.len() != descriptor.label_names.len()
|| descriptor
.label_names
.iter()
.any(|name| !valid_label(name) || *name == "le")
|| match descriptor.kind {
MetricKind::Histogram => {
descriptor.histogram_bounds.is_empty()
|| descriptor
.histogram_bounds
.iter()
.any(|bound| !bound.is_finite())
|| descriptor
.histogram_bounds
.windows(2)
.any(|pair| pair[0] >= pair[1])
}
MetricKind::Counter | MetricKind::Gauge => !descriptor.histogram_bounds.is_empty(),
};
if invalid {
Err(MetricConflict {
name: descriptor.name,
})
} else {
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct MetricSample {
pub name: &'static str,
pub labels: Vec<(&'static str, String)>,
pub value: MetricValue,
}
#[derive(Debug, Clone)]
pub struct MetricFamilySnapshot {
pub name: &'static str,
pub description: &'static str,
pub unit: &'static str,
pub kind: MetricKind,
pub histogram_bounds: &'static [f64],
pub samples: Vec<MetricSample>,
}
impl MetricSample {
fn render_prometheus(&self, output: &mut String) {
use std::fmt::Write as _;
match &self.value {
MetricValue::Counter(v) => {
output.push_str(self.name);
self.render_labels(output, &[]);
let _ = writeln!(output, " {v}");
}
MetricValue::Gauge(v) => {
output.push_str(self.name);
self.render_labels(output, &[]);
let _ = writeln!(output, " {v}");
}
MetricValue::Histogram {
bounds,
buckets,
sum,
count,
} => {
let mut cumulative = 0u64;
for (i, bound) in bounds.iter().enumerate() {
cumulative = cumulative.saturating_add(buckets[i]);
let le = format!("{bound}");
let _ = write!(output, "{}_bucket", self.name);
self.render_labels(output, &[("le", le.as_str())]);
let _ = writeln!(output, " {cumulative}");
}
cumulative = cumulative.saturating_add(buckets[bounds.len()]);
let _ = write!(output, "{}_bucket", self.name);
self.render_labels(output, &[("le", "+Inf")]);
let _ = writeln!(output, " {cumulative}");
let _ = write!(output, "{}_sum", self.name);
self.render_labels(output, &[]);
let _ = writeln!(output, " {sum}");
let _ = write!(output, "{}_count", self.name);
self.render_labels(output, &[]);
let _ = writeln!(output, " {count}");
}
}
}
fn render_labels(&self, output: &mut String, extra: &[(&str, &str)]) {
if self.labels.is_empty() && extra.is_empty() {
return;
}
output.push('{');
for (index, (key, value)) in self
.labels
.iter()
.map(|(key, value)| (*key, value.as_str()))
.chain(extra.iter().copied())
.enumerate()
{
if index != 0 {
output.push(',');
}
output.push_str(key);
output.push_str("=\"");
append_escaped_label(output, value);
output.push('"');
}
output.push('}');
}
}
fn append_escaped_label(output: &mut String, value: &str) {
let mut start = 0;
for (index, byte) in value.bytes().enumerate() {
let escaped = match byte {
b'\\' => "\\\\",
b'"' => "\\\"",
b'\n' => "\\n",
_ => continue,
};
output.push_str(&value[start..index]);
output.push_str(escaped);
start = index + 1;
}
output.push_str(&value[start..]);
}
#[derive(Debug, Clone)]
pub enum MetricValue {
Counter(u64),
Gauge(f64),
Histogram {
bounds: &'static [f64],
buckets: Vec<u64>,
sum: f64,
count: u64,
},
}