use std::{collections::BTreeMap, convert::Infallible, fmt, sync::Mutex};
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;
use crate::result::{ClassifyError, ErrorKind};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum MetricKind {
Counter,
Gauge,
Histogram,
}
#[derive(Clone, PartialEq, Serialize)]
#[non_exhaustive]
pub struct MetricSample {
name: String,
kind: MetricKind,
value: f64,
labels: Vec<(String, String)>,
#[serde(skip_serializing_if = "Option::is_none")]
count: Option<u64>,
}
impl fmt::Debug for MetricSample {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("MetricSample")
.field("name", &self.name)
.field("kind", &self.kind)
.field("value", &self.value)
.field("label_count", &self.labels.len())
.field("count", &self.count)
.finish()
}
}
impl MetricSample {
pub fn new(
name: impl Into<String>,
kind: MetricKind,
value: f64,
) -> Result<Self, MetricsError> {
validate_metric_value(value)?;
let name = normalize_metric_name(name)?;
Ok(Self::from_valid_parts(name, kind, value))
}
fn from_valid_parts(name: String, kind: MetricKind, value: f64) -> Self {
Self {
name,
kind,
value,
labels: Vec::new(),
count: None,
}
}
pub fn counter(name: impl Into<String>, value: u64) -> Result<Self, MetricsError> {
let name = normalize_metric_name(name)?;
Ok(Self::from_valid_parts(
name,
MetricKind::Counter,
value as f64,
))
}
pub fn gauge(name: impl Into<String>, value: f64) -> Result<Self, MetricsError> {
Self::new(name, MetricKind::Gauge, value)
}
pub fn histogram(name: impl Into<String>, count: u64, sum: f64) -> Result<Self, MetricsError> {
Ok(Self::new(name, MetricKind::Histogram, sum)?.with_count(count))
}
#[must_use]
pub fn with_label(mut self, key: &'static str, value: impl Into<String>) -> Self {
self.labels = MetricLabels::from_lossy(
self.labels
.into_iter()
.chain([(key.to_owned(), value.into())]),
)
.into_vec();
self
}
pub fn try_with_label(
mut self,
key: impl Into<String>,
value: impl Into<String>,
) -> Result<Self, MetricsError> {
self.labels.push((key.into(), value.into()));
self.labels = MetricLabels::new(self.labels)?.into_vec();
Ok(self)
}
#[must_use]
pub fn with_labels(mut self, labels: MetricLabels) -> Self {
self.labels = labels.into_vec();
self
}
#[must_use]
pub const fn with_count(mut self, count: u64) -> Self {
self.count = Some(count);
self
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub const fn kind(&self) -> MetricKind {
self.kind
}
#[must_use]
pub const fn value(&self) -> f64 {
self.value
}
#[must_use]
pub const fn count(&self) -> Option<u64> {
self.count
}
#[must_use]
pub fn labels(&self) -> &[(String, String)] {
&self.labels
}
}
impl<'de> Deserialize<'de> for MetricSample {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct MetricSampleWire {
name: String,
kind: MetricKind,
value: f64,
#[serde(default)]
labels: MetricLabels,
#[serde(default)]
count: Option<u64>,
}
let wire = MetricSampleWire::deserialize(deserializer)?;
let mut sample =
Self::new(wire.name, wire.kind, wire.value).map_err(serde::de::Error::custom)?;
sample = sample.with_labels(wire.labels);
if let Some(count) = wire.count {
sample = sample.with_count(count);
}
Ok(sample)
}
}
#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[non_exhaustive]
pub struct MetricLabels(Vec<(String, String)>);
impl fmt::Debug for MetricLabels {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("MetricLabels")
.field("label_count", &self.0.len())
.finish_non_exhaustive()
}
}
impl MetricLabels {
pub fn new(
labels: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
) -> Result<Self, MetricsError> {
let mut normalized = BTreeMap::<String, String>::new();
for (key, value) in labels {
let key = normalize_metric_name(key)?;
normalized.insert(key, value.into());
}
Ok(Self(normalized.into_iter().collect()))
}
#[must_use]
pub fn from_lossy(
labels: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
) -> Self {
let mut normalized = BTreeMap::<String, String>::new();
for (key, value) in labels {
if let Ok(key) = normalize_metric_name(key) {
normalized.insert(key, value.into());
}
}
Self(normalized.into_iter().collect())
}
pub fn single(key: impl Into<String>, value: impl Into<String>) -> Result<Self, MetricsError> {
Self::new([(key, value)])
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[must_use]
pub fn as_slice(&self) -> &[(String, String)] {
&self.0
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&str> {
let key = normalize_metric_name(key).ok()?;
self.0
.iter()
.find(|(name, _)| name == &key)
.map(|(_, value)| value.as_str())
}
#[must_use]
pub fn to_btree_map(&self) -> BTreeMap<String, String> {
self.0.iter().cloned().collect()
}
#[must_use]
pub fn into_vec(self) -> Vec<(String, String)> {
self.0
}
}
impl<'de> Deserialize<'de> for MetricLabels {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Self::new(Vec::<(String, String)>::deserialize(deserializer)?)
.map_err(serde::de::Error::custom)
}
}
#[derive(Clone, Default, PartialEq, Serialize)]
#[non_exhaustive]
pub struct MetricsSnapshot {
samples: Vec<MetricSample>,
}
impl fmt::Debug for MetricsSnapshot {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("MetricsSnapshot")
.field("sample_count", &self.samples.len())
.finish_non_exhaustive()
}
}
impl MetricsSnapshot {
#[must_use]
pub fn new(samples: Vec<MetricSample>) -> Self {
Self { samples }
}
pub fn push(&mut self, sample: MetricSample) {
self.samples.push(sample);
}
#[must_use]
pub fn samples(&self) -> &[MetricSample] {
&self.samples
}
}
impl<'de> Deserialize<'de> for MetricsSnapshot {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Ok(Self::new(Vec::<MetricSample>::deserialize(deserializer)?))
}
}
pub trait MetricRecorder: Send + Sync + 'static {
fn increment_counter(
&self,
name: &str,
value: u64,
labels: MetricLabels,
) -> Result<(), MetricsError>;
fn set_gauge(&self, name: &str, value: f64, labels: MetricLabels) -> Result<(), MetricsError>;
fn observe_histogram(
&self,
name: &str,
value: f64,
labels: MetricLabels,
) -> Result<(), MetricsError>;
fn snapshot(&self) -> Result<MetricsSnapshot, MetricsError>;
}
#[derive(Default)]
#[non_exhaustive]
pub struct MetricRegistry {
values: Mutex<BTreeMap<MetricIdentity, MetricAggregate>>,
}
impl fmt::Debug for MetricRegistry {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("MetricRegistry")
.field(
"metric_count",
&self.values.try_lock().ok().map(|values| values.len()),
)
.finish_non_exhaustive()
}
}
impl MetricRegistry {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn increment_counter(
&self,
name: &str,
value: u64,
labels: MetricLabels,
) -> Result<(), MetricsError> {
MetricRecorder::increment_counter(self, name, value, labels)
}
pub fn set_gauge(
&self,
name: &str,
value: f64,
labels: MetricLabels,
) -> Result<(), MetricsError> {
MetricRecorder::set_gauge(self, name, value, labels)
}
pub fn observe_histogram(
&self,
name: &str,
value: f64,
labels: MetricLabels,
) -> Result<(), MetricsError> {
MetricRecorder::observe_histogram(self, name, value, labels)
}
pub fn snapshot(&self) -> Result<MetricsSnapshot, MetricsError> {
MetricRecorder::snapshot(self)
}
}
impl MetricRecorder for MetricRegistry {
fn increment_counter(
&self,
name: &str,
value: u64,
labels: MetricLabels,
) -> Result<(), MetricsError> {
let identity = MetricIdentity::new(name, MetricKind::Counter, labels)?;
let mut values = self.values.lock().map_err(|_| MetricsError::LockPoisoned)?;
match values.entry(identity) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
let aggregate = entry.get_mut();
aggregate.value = finite_metric_sum(aggregate.value, value as f64)?;
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(MetricAggregate {
value: value as f64,
count: None,
});
}
}
Ok(())
}
fn set_gauge(&self, name: &str, value: f64, labels: MetricLabels) -> Result<(), MetricsError> {
validate_metric_value(value)?;
let identity = MetricIdentity::new(name, MetricKind::Gauge, labels)?;
let mut values = self.values.lock().map_err(|_| MetricsError::LockPoisoned)?;
values.insert(identity, MetricAggregate { value, count: None });
Ok(())
}
fn observe_histogram(
&self,
name: &str,
value: f64,
labels: MetricLabels,
) -> Result<(), MetricsError> {
validate_metric_value(value)?;
let identity = MetricIdentity::new(name, MetricKind::Histogram, labels)?;
let mut values = self.values.lock().map_err(|_| MetricsError::LockPoisoned)?;
match values.entry(identity) {
std::collections::btree_map::Entry::Occupied(mut entry) => {
let aggregate = entry.get_mut();
aggregate.value = finite_metric_sum(aggregate.value, value)?;
aggregate.count = Some(aggregate.count.map_or(1, |count| count.saturating_add(1)));
}
std::collections::btree_map::Entry::Vacant(entry) => {
entry.insert(MetricAggregate {
value,
count: Some(1),
});
}
}
Ok(())
}
fn snapshot(&self) -> Result<MetricsSnapshot, MetricsError> {
let values = self.values.lock().map_err(|_| MetricsError::LockPoisoned)?;
let samples = values
.iter()
.map(|(identity, aggregate)| {
let mut sample =
MetricSample::new(identity.name.clone(), identity.kind, aggregate.value)?
.with_labels(identity.labels.clone());
if let Some(count) = aggregate.count {
sample = sample.with_count(count);
}
Ok(sample)
})
.collect::<Result<_, MetricsError>>()?;
Ok(MetricsSnapshot::new(samples))
}
}
fn finite_metric_sum(left: f64, right: f64) -> Result<f64, MetricsError> {
let sum = left + right;
validate_metric_value(sum)?;
Ok(sum)
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct MetricIdentity {
name: String,
kind: MetricKind,
labels: MetricLabels,
}
impl MetricIdentity {
fn new(
name: impl Into<String>,
kind: MetricKind,
labels: MetricLabels,
) -> Result<Self, MetricsError> {
Ok(Self {
name: normalize_metric_name(name)?,
kind,
labels,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct MetricAggregate {
value: f64,
count: Option<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum MetricsError {
#[error("metrics registry lock is poisoned")]
LockPoisoned,
#[error("metric name must not be empty")]
InvalidName,
#[error("metric value must be finite")]
InvalidValue,
}
impl ClassifyError for MetricsError {
fn error_kind(&self) -> ErrorKind {
match self {
Self::LockPoisoned => ErrorKind::Unavailable,
Self::InvalidName | Self::InvalidValue => ErrorKind::Validation,
}
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal(match self {
Self::LockPoisoned => "metrics_registry_unavailable",
Self::InvalidName => "metric_name_invalid",
Self::InvalidValue => "metric_value_invalid",
})
}
}
#[must_use]
pub fn encode_openmetrics(snapshot: &MetricsSnapshot) -> String {
let mut output = String::new();
let mut emitted_types = BTreeMap::<String, MetricKind>::new();
for sample in snapshot.samples() {
let name = sample.name();
if let std::collections::btree_map::Entry::Vacant(entry) =
emitted_types.entry(name.to_owned())
{
entry.insert(sample.kind());
output.push_str("# TYPE ");
output.push_str(name);
output.push(' ');
output.push_str(openmetrics_kind(sample.kind()));
output.push('\n');
}
match (sample.kind(), sample.count()) {
(MetricKind::Histogram, Some(count)) => {
output.push_str(name);
output.push_str("_sum");
output.push_str(&encode_labels(sample.labels()));
output.push(' ');
output.push_str(&format_float(sample.value()));
output.push('\n');
output.push_str(name);
output.push_str("_count");
output.push_str(&encode_labels(sample.labels()));
output.push(' ');
output.push_str(&count.to_string());
output.push('\n');
}
_ => {
output.push_str(name);
output.push_str(&encode_labels(sample.labels()));
output.push(' ');
output.push_str(&format_float(sample.value()));
output.push('\n');
}
}
}
output.push_str("# EOF\n");
output
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MetricsExport {
content_type: String,
body: String,
}
impl fmt::Debug for MetricsExport {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("MetricsExport")
.field("content_type", &self.content_type)
.field("body_bytes", &self.body.len())
.finish()
}
}
impl MetricsExport {
#[must_use]
pub fn new(content_type: impl Into<String>, body: impl Into<String>) -> Self {
Self {
content_type: content_type.into(),
body: body.into(),
}
}
#[must_use]
pub fn content_type(&self) -> &str {
&self.content_type
}
#[must_use]
pub fn body(&self) -> &str {
&self.body
}
#[must_use]
pub fn into_body(self) -> String {
self.body
}
}
pub trait MetricsExporter {
type Error;
fn export(&self, snapshot: &MetricsSnapshot) -> Result<MetricsExport, Self::Error>;
}
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub struct OpenMetricsExporter;
impl OpenMetricsExporter {
pub const CONTENT_TYPE: &'static str =
"application/openmetrics-text; version=1.0.0; charset=utf-8";
}
impl MetricsExporter for OpenMetricsExporter {
type Error = Infallible;
fn export(&self, snapshot: &MetricsSnapshot) -> Result<MetricsExport, Self::Error> {
Ok(MetricsExport::new(
Self::CONTENT_TYPE,
encode_openmetrics(snapshot),
))
}
}
fn normalize_metric_name(value: impl Into<String>) -> Result<String, MetricsError> {
let value = value.into();
let value = value.trim();
if value.is_empty() {
return Err(MetricsError::InvalidName);
}
let mut normalized = String::with_capacity(value.len().max(1));
for byte in value.bytes() {
if byte.is_ascii_alphanumeric() || byte == b':' || byte == b'_' {
normalized.push(char::from(byte));
} else {
normalized.push('_');
}
}
if normalized.as_bytes().first().is_none_or(u8::is_ascii_digit) {
normalized.insert(0, '_');
}
Ok(normalized)
}
fn validate_metric_value(value: f64) -> Result<(), MetricsError> {
if value.is_finite() {
Ok(())
} else {
Err(MetricsError::InvalidValue)
}
}
fn openmetrics_kind(kind: MetricKind) -> &'static str {
match kind {
MetricKind::Counter => "counter",
MetricKind::Gauge => "gauge",
MetricKind::Histogram => "histogram",
}
}
fn encode_labels(labels: &[(String, String)]) -> String {
if labels.is_empty() {
return String::new();
}
let mut output = String::from("{");
for (index, (key, value)) in labels.iter().enumerate() {
if index > 0 {
output.push(',');
}
output.push_str(key);
output.push_str("=\"");
output.push_str(&escape_label_value(value));
output.push('"');
}
output.push('}');
output
}
fn escape_label_value(value: &str) -> String {
let mut escaped = String::with_capacity(value.len());
for character in value.chars() {
match character {
'\\' => escaped.push_str("\\\\"),
'"' => escaped.push_str("\\\""),
'\n' => escaped.push_str("\\n"),
_ => escaped.push(character),
}
}
escaped
}
fn format_float(value: f64) -> String {
if value.is_finite() {
value.to_string()
} else {
"0".to_owned()
}
}