trait-net 0.7.1

A collection of traits for client libraries for reducing boilerplate
Documentation
use crate::metrics::Observer;
use prometheus::{
    core::{AtomicI64, Collector, Desc, GenericGauge},
    proto::MetricFamily,
    IntGaugeVec, Opts,
};
use std::ops::Deref;

// `Switch` can be emulated using `ActiveCount`.
#[derive(Clone)]
pub struct ActiveCount(IntGaugeVec);

impl ActiveCount {
    pub fn new(opts: Opts, label_names: &[&str]) -> prometheus::Result<Self> {
        Ok(Self(IntGaugeVec::new(opts, label_names)?))
    }

    pub fn make_observer(&self, labels: &[&str]) -> ActiveCountObserver {
        ActiveCountObserver(self.0.with_label_values(labels))
    }
}

impl Deref for ActiveCount {
    type Target = IntGaugeVec;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Collector for ActiveCount {
    fn desc(&self) -> Vec<&Desc> {
        self.0.desc()
    }

    fn collect(&self) -> Vec<MetricFamily> {
        self.0.collect()
    }
}

pub struct ActiveCountObserver(GenericGauge<AtomicI64>);

impl<Out: ?Sized> Observer<Out> for ActiveCountObserver {
    fn on_first_poll(&mut self) {
        self.0.inc();
    }

    fn on_finish(&mut self, _: Option<&Out>) {
        self.0.dec();
    }
}