hesione 0.1.1

A Prometheus client
Documentation
use once_cell::sync::Lazy;
use regex::Regex;

static VALID_NAME_REGEX: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"^[[:alpha:]_][[:alnum:]_]*$").unwrap());

/// Error for when an invalid metric or label name is supplied
///
/// See [here][0] for details. Note that `:` is disallowed for metric names
/// because those are reserved for use by whomever is running Prometheus itself,
/// and not intended for use in instrumentation (which is what this crate is
/// for).
///
/// [0]: https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels
#[derive(thiserror::Error, Debug)]
#[error("invalid metric or label name")]
pub struct NameError;

/// Whether a string is a valid metric or label name
pub fn is_valid_name<S: AsRef<str>>(name: S) -> bool {
    let name = name.as_ref();

    if name.starts_with("__") {
        false
    } else {
        VALID_NAME_REGEX.is_match(name.as_ref())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn good_metric_name() {
        assert!(is_valid_name("test"));
    }

    #[test]
    fn good_alnum_metric_name() {
        assert!(is_valid_name("test_0"));
    }

    #[test]
    fn bad_alnum_metric_name() {
        assert!(!is_valid_name("0_test"));
    }

    #[test]
    fn dubious_metric_name() {
        assert!(is_valid_name("test__"));
    }

    #[test]
    fn very_dubious_metric_name() {
        assert!(is_valid_name("_test"));
    }

    #[test]
    fn bad_metric_name() {
        assert!(!is_valid_name("__test"));
    }
}