use super::{Family, Labels, MetricError};
use prometheus::{
Encoder,
core::{Collector, MetricVec, MetricVecBuilder},
};
use std::{
collections::BTreeSet,
io::{self, Write},
sync::{Arc, Mutex},
};
struct State {
native: prometheus::Registry,
names: BTreeSet<String>,
definitions: usize,
series: usize,
attached: bool,
sealed: bool,
}
#[derive(Clone)]
pub struct Registry(Arc<Mutex<State>>);
impl Default for Registry {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for Registry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let state = self.0.lock().unwrap_or_else(|error| error.into_inner());
f.debug_struct("Registry")
.field("definitions", &state.definitions)
.field("series", &state.series)
.field("sealed", &state.sealed)
.finish()
}
}
impl Registry {
pub fn new() -> Self {
Self(Arc::new(Mutex::new(State {
native: prometheus::Registry::new(),
names: BTreeSet::new(),
definitions: 0,
series: 0,
attached: false,
sealed: false,
})))
}
pub(crate) fn owned() -> Self {
let registry = Self::new();
registry.attach().expect("fresh registry is unowned");
registry
}
pub(crate) fn attach(&self) -> Result<(), MetricError> {
let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
if state.attached {
return Err(MetricError::AlreadyAttached);
}
state.attached = true;
Ok(())
}
pub(crate) fn seal(&self) {
self.0
.lock()
.unwrap_or_else(|error| error.into_inner())
.sealed = true;
}
pub fn encode(&self) -> Result<String, MetricError> {
let native = self
.0
.lock()
.unwrap_or_else(|error| error.into_inner())
.native
.clone();
let mut output = Bounded(Vec::new());
prometheus::TextEncoder::new()
.encode(&native.gather(), &mut output)
.map_err(|_| MetricError::Encoding)?;
String::from_utf8(output.0).map_err(|_| MetricError::Encoding)
}
#[cfg(any(feature = "postgres", feature = "client"))]
pub(crate) fn register_managed(
&self,
collector: Box<dyn Collector>,
definitions: usize,
series: usize,
) -> Result<(), MetricError> {
let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
if state.sealed {
return Err(MetricError::Sealed);
}
if state.definitions + definitions > 128 || state.series + series > 4096 {
return Err(MetricError::Capacity);
}
state
.native
.register(collector)
.map_err(|_| MetricError::NameConflict)?;
state.definitions += definitions;
state.series += series;
Ok(())
}
pub(super) fn install<B: MetricVecBuilder>(
&self,
name: &str,
help: &str,
labels: &[Labels],
histogram: Option<usize>,
build: impl FnOnce(&[&str]) -> prometheus::Result<MetricVec<B>>,
) -> Result<Family<B::M>, MetricError>
where
MetricVec<B>: 'static,
{
super::validation::definition(name, help, labels)?;
let names = if histogram.is_some() {
vec![
name.to_owned(),
format!("{name}_bucket"),
format!("{name}_sum"),
format!("{name}_count"),
]
} else {
vec![name.to_owned()]
};
let series = labels.len() * histogram.map_or(1, |buckets| buckets + 3);
let mut state = self.0.lock().unwrap_or_else(|error| error.into_inner());
if state.sealed {
return Err(MetricError::Sealed);
}
if state.definitions >= 128 || state.series + series > 4096 {
return Err(MetricError::Capacity);
}
if names.iter().any(|name| state.names.contains(name)) {
return Err(MetricError::NameConflict);
}
let label_names: Vec<&str> = labels[0].0.iter().map(|(name, _)| name.as_str()).collect();
let collector = build(&label_names).map_err(|_| MetricError::InvalidDefinition)?;
let metrics = labels
.iter()
.map(|labels| {
collector
.get_metric_with_label_values(&labels.values())
.map_err(|_| MetricError::InvalidDefinition)
})
.collect::<Result<Vec<_>, _>>()?;
let children: usize = collector
.collect()
.iter()
.map(|family| family.get_metric().len())
.sum();
if children != labels.len() {
return Err(MetricError::InvalidDefinition);
}
state
.native
.register(Box::new(collector))
.map_err(|_| MetricError::NameConflict)?;
state.names.extend(names);
state.definitions += 1;
state.series += series;
Ok(Family {
members: labels.iter().cloned().zip(metrics).collect(),
})
}
}
struct Bounded(Vec<u8>);
impl Write for Bounded {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
if self.0.len() + bytes.len() > 4 * 1024 * 1024 {
return Err(io::Error::other("metric output limit exceeded"));
}
self.0.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[cfg(test)]
#[path = "registry_test.rs"]
mod registry_test;