use std::sync::Arc;
use crate::telemetry::histogram_config::HistogramConfig;
use crate::telemetry::metrics::counter::Counter;
use crate::telemetry::metrics::error::MetricError;
use crate::telemetry::metrics::histogram::Histogram;
use crate::telemetry::metrics::names::{check_metric_name, check_reserved_suffix};
use crate::telemetry::metrics::read::Read;
use crate::telemetry::metrics::registry::Registry;
use crate::telemetry::metrics::unit::Unit;
const RESERVED_SUFFIXES: [(&str, &str); 5] = [
(
"_seconds",
"the unit suffix is added by the meter based on Unit",
),
(
"_bytes",
"the unit suffix is added by the meter based on Unit",
),
(
"_ratio",
"the unit suffix is added by the meter based on Unit",
),
(
"_total",
"the suffix is added by the Prometheus exposition for counters",
),
(
"_ms",
"milliseconds are not allowed, seconds are the unit of time",
),
];
const HISTOGRAM_SUFFIXES: [(&str, &str); 3] = [
(
"_bucket",
"the suffix is reserved for histogram bucket series",
),
("_sum", "the suffix is reserved for histogram sum series"),
(
"_count",
"the suffix is reserved for histogram count series",
),
];
pub struct Meter {
registry: Arc<Registry>,
prefix: String,
histogram: HistogramConfig,
}
impl Meter {
pub(crate) fn new(
registry: Arc<Registry>,
prefix: impl Into<String>,
histogram: HistogramConfig,
) -> Self {
Self {
registry,
prefix: prefix.into(),
histogram,
}
}
pub fn counter(&self, name: &str, unit: Unit, help: &str) -> Result<Counter, MetricError> {
check_module_name(name, false)?;
let metric = full_name(&self.prefix, name, unit);
self.registry.counter(&metric, help)
}
pub fn gauge(&self, name: &str, unit: Unit, help: &str, read: Read) -> Result<(), MetricError> {
check_module_name(name, false)?;
let metric = full_name(&self.prefix, name, unit);
self.registry.observable(&metric, help, read)
}
pub fn histogram(&self, name: &str, unit: Unit, help: &str) -> Result<Histogram, MetricError> {
check_module_name(name, true)?;
let metric = full_name(&self.prefix, name, unit);
let buckets = self.histogram.buckets_for(&self.prefixed(name), unit);
self.registry.histogram(&metric, help, Some(buckets))
}
fn prefixed(&self, name: &str) -> String {
format!("{}_{}", self.prefix, name)
}
}
fn full_name(prefix: &str, name: &str, unit: Unit) -> String {
format!("{}_{}{}", prefix, name, unit.suffix())
}
fn check_module_name(name: &str, histogram: bool) -> Result<(), MetricError> {
check_metric_name(name)?;
let suffixes = RESERVED_SUFFIXES
.iter()
.chain(HISTOGRAM_SUFFIXES.iter().filter(|_| histogram));
for (suffix, reason) in suffixes {
check_reserved_suffix(name, suffix, reason)?;
}
Ok(())
}