Skip to main content

made_core/value_objects/
metric_name.rs

1use std::fmt;
2
3use crate::error::DomainError;
4
5/// A Prometheus metric or sample name.
6#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
7pub struct MetricName(String);
8
9impl MetricName {
10    pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
11        let value = value.into();
12        let mut chars = value.chars();
13        let valid_first = chars.next().is_some_and(|character| {
14            character.is_ascii_alphabetic() || matches!(character, '_' | ':')
15        });
16        if !valid_first
17            || !chars.all(|character| {
18                character.is_ascii_alphanumeric() || matches!(character, '_' | ':')
19            })
20        {
21            return Err(DomainError::InvariantViolated {
22                reason: "metric name must use the Prometheus identifier alphabet",
23            });
24        }
25        Ok(Self(value))
26    }
27
28    #[must_use]
29    pub fn as_str(&self) -> &str {
30        &self.0
31    }
32}
33
34impl fmt::Display for MetricName {
35    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
36        formatter.write_str(self.as_str())
37    }
38}