use std::sync::{Mutex, MutexGuard};
use crate::telemetry::metrics::error::MetricError;
use crate::telemetry::metrics::labels::Labels;
use crate::telemetry::metrics::names::check_label_name;
#[derive(Debug)]
pub(crate) struct InstrumentState<F> {
pub(crate) name: String,
pub(crate) family: F,
composition: Mutex<Option<Vec<String>>>,
}
impl<F> InstrumentState<F> {
pub(crate) fn new(name: String, family: F) -> Self {
Self {
name,
family,
composition: Mutex::new(None),
}
}
pub(crate) fn bind(&self, labels: &Labels) -> Result<(), MetricError> {
let names = labels.names();
for name in &names {
check_label_name(name)?;
}
if names.is_empty() {
return Ok(());
}
let mut composition = lock_mutex(&self.composition);
match composition.as_ref() {
Some(remembered) if *remembered != names => Err(MetricError::new(format!(
"metric '{}': label names {:?} do not match the bound label names {:?}",
self.name, names, remembered
))),
Some(_) => Ok(()),
None => {
*composition = Some(names.iter().map(|name| (*name).to_owned()).collect());
Ok(())
}
}
}
}
pub(crate) fn lock_mutex<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
match mutex.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
}
}