LCOV - code coverage report
Current view: top level - libs/metrics/src - lib.rs (source / functions) Coverage Total Hit
Test: 42f947419473a288706e86ecdf7c2863d760d5d7.info Lines: 18.0 % 244 44
Test Date: 2024-08-02 21:34:27 Functions: 30.7 % 101 31

            Line data    Source code
       1              : //! We re-export those from prometheus crate to
       2              : //! make sure that we use the same dep version everywhere.
       3              : //! Otherwise, we might not see all metrics registered via
       4              : //! a default registry.
       5              : #![deny(clippy::undocumented_unsafe_blocks)]
       6              : 
       7              : use measured::{
       8              :     label::{LabelGroupSet, LabelGroupVisitor, LabelName, NoLabels},
       9              :     metric::{
      10              :         counter::CounterState,
      11              :         gauge::GaugeState,
      12              :         group::Encoding,
      13              :         name::{MetricName, MetricNameEncoder},
      14              :         MetricEncoding, MetricFamilyEncoding,
      15              :     },
      16              :     FixedCardinalityLabel, LabelGroup, MetricGroup,
      17              : };
      18              : use once_cell::sync::Lazy;
      19              : use prometheus::core::{
      20              :     Atomic, AtomicU64, Collector, GenericCounter, GenericCounterVec, GenericGauge, GenericGaugeVec,
      21              : };
      22              : pub use prometheus::opts;
      23              : pub use prometheus::register;
      24              : pub use prometheus::Error;
      25              : use prometheus::Registry;
      26              : pub use prometheus::{core, default_registry, proto};
      27              : pub use prometheus::{exponential_buckets, linear_buckets};
      28              : pub use prometheus::{register_counter_vec, Counter, CounterVec};
      29              : pub use prometheus::{register_gauge, Gauge};
      30              : pub use prometheus::{register_gauge_vec, GaugeVec};
      31              : pub use prometheus::{register_histogram, Histogram};
      32              : pub use prometheus::{register_histogram_vec, HistogramVec};
      33              : pub use prometheus::{register_int_counter, IntCounter};
      34              : pub use prometheus::{register_int_counter_vec, IntCounterVec};
      35              : pub use prometheus::{register_int_gauge, IntGauge};
      36              : pub use prometheus::{register_int_gauge_vec, IntGaugeVec};
      37              : pub use prometheus::{Encoder, TextEncoder};
      38              : 
      39              : pub mod launch_timestamp;
      40              : mod wrappers;
      41              : pub use wrappers::{CountedReader, CountedWriter};
      42              : mod hll;
      43              : pub use hll::{HyperLogLog, HyperLogLogState, HyperLogLogVec};
      44              : #[cfg(target_os = "linux")]
      45              : pub mod more_process_metrics;
      46              : 
      47              : pub type UIntGauge = GenericGauge<AtomicU64>;
      48              : pub type UIntGaugeVec = GenericGaugeVec<AtomicU64>;
      49              : 
      50              : #[macro_export]
      51              : macro_rules! register_uint_gauge_vec {
      52              :     ($NAME:expr, $HELP:expr, $LABELS_NAMES:expr $(,)?) => {{
      53              :         let gauge_vec = UIntGaugeVec::new($crate::opts!($NAME, $HELP), $LABELS_NAMES).unwrap();
      54         1798 :         $crate::register(Box::new(gauge_vec.clone())).map(|_| gauge_vec)
      55              :     }};
      56              : }
      57              : 
      58              : #[macro_export]
      59              : macro_rules! register_uint_gauge {
      60              :     ($NAME:expr, $HELP:expr $(,)?) => {{
      61              :         let gauge = $crate::UIntGauge::new($NAME, $HELP).unwrap();
      62          540 :         $crate::register(Box::new(gauge.clone())).map(|_| gauge)
      63              :     }};
      64              : }
      65              : 
      66              : /// Special internal registry, to collect metrics independently from the default registry.
      67              : /// Was introduced to fix deadlock with lazy registration of metrics in the default registry.
      68              : static INTERNAL_REGISTRY: Lazy<Registry> = Lazy::new(Registry::new);
      69              : 
      70              : /// Register a collector in the internal registry. MUST be called before the first call to `gather()`.
      71              : /// Otherwise, we can have a deadlock in the `gather()` call, trying to register a new collector
      72              : /// while holding the lock.
      73            0 : pub fn register_internal(c: Box<dyn Collector>) -> prometheus::Result<()> {
      74            0 :     INTERNAL_REGISTRY.register(c)
      75            0 : }
      76              : 
      77              : /// Gathers all Prometheus metrics and records the I/O stats just before that.
      78              : ///
      79              : /// Metrics gathering is a relatively simple and standalone operation, so
      80              : /// it might be fine to do it this way to keep things simple.
      81            0 : pub fn gather() -> Vec<prometheus::proto::MetricFamily> {
      82            0 :     update_rusage_metrics();
      83            0 :     let mut mfs = prometheus::gather();
      84            0 :     let mut internal_mfs = INTERNAL_REGISTRY.gather();
      85            0 :     mfs.append(&mut internal_mfs);
      86            0 :     mfs
      87            0 : }
      88              : 
      89            0 : static DISK_IO_BYTES: Lazy<IntGaugeVec> = Lazy::new(|| {
      90              :     register_int_gauge_vec!(
      91              :         "libmetrics_disk_io_bytes_total",
      92              :         "Bytes written and read from disk, grouped by the operation (read|write)",
      93              :         &["io_operation"]
      94              :     )
      95            0 :     .expect("Failed to register disk i/o bytes int gauge vec")
      96            0 : });
      97              : 
      98            0 : static MAXRSS_KB: Lazy<IntGauge> = Lazy::new(|| {
      99              :     register_int_gauge!(
     100              :         "libmetrics_maxrss_kb",
     101              :         "Memory usage (Maximum Resident Set Size)"
     102              :     )
     103            0 :     .expect("Failed to register maxrss_kb int gauge")
     104            0 : });
     105              : 
     106              : /// Most common fsync latency is 50 µs - 100 µs, but it can be much higher,
     107              : /// especially during many concurrent disk operations.
     108              : pub const DISK_FSYNC_SECONDS_BUCKETS: &[f64] =
     109              :     &[0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 30.0];
     110              : 
     111              : pub struct BuildInfo {
     112              :     pub revision: &'static str,
     113              :     pub build_tag: &'static str,
     114              : }
     115              : 
     116              : // todo: allow label group without the set
     117              : impl LabelGroup for BuildInfo {
     118            0 :     fn visit_values(&self, v: &mut impl LabelGroupVisitor) {
     119            0 :         const REVISION: &LabelName = LabelName::from_str("revision");
     120            0 :         v.write_value(REVISION, &self.revision);
     121            0 :         const BUILD_TAG: &LabelName = LabelName::from_str("build_tag");
     122            0 :         v.write_value(BUILD_TAG, &self.build_tag);
     123            0 :     }
     124              : }
     125              : 
     126              : impl<T: Encoding> MetricFamilyEncoding<T> for BuildInfo
     127              : where
     128              :     GaugeState: MetricEncoding<T>,
     129              : {
     130            0 :     fn collect_family_into(
     131            0 :         &self,
     132            0 :         name: impl measured::metric::name::MetricNameEncoder,
     133            0 :         enc: &mut T,
     134            0 :     ) -> Result<(), T::Err> {
     135            0 :         enc.write_help(&name, "Build/version information")?;
     136            0 :         GaugeState::write_type(&name, enc)?;
     137            0 :         GaugeState {
     138            0 :             count: std::sync::atomic::AtomicI64::new(1),
     139            0 :         }
     140            0 :         .collect_into(&(), self, name, enc)
     141            0 :     }
     142              : }
     143              : 
     144            0 : #[derive(MetricGroup)]
     145              : #[metric(new(build_info: BuildInfo))]
     146              : pub struct NeonMetrics {
     147              :     #[cfg(target_os = "linux")]
     148              :     #[metric(namespace = "process")]
     149              :     #[metric(init = measured_process::ProcessCollector::for_self())]
     150              :     process: measured_process::ProcessCollector,
     151              : 
     152              :     #[metric(namespace = "libmetrics")]
     153              :     #[metric(init = LibMetrics::new(build_info))]
     154              :     libmetrics: LibMetrics,
     155              : }
     156              : 
     157            0 : #[derive(MetricGroup)]
     158              : #[metric(new(build_info: BuildInfo))]
     159              : pub struct LibMetrics {
     160              :     #[metric(init = build_info)]
     161              :     build_info: BuildInfo,
     162              : 
     163              :     #[metric(flatten)]
     164              :     rusage: Rusage,
     165              : 
     166              :     serve_count: CollectionCounter,
     167              : }
     168              : 
     169            0 : fn write_gauge<Enc: Encoding>(
     170            0 :     x: i64,
     171            0 :     labels: impl LabelGroup,
     172            0 :     name: impl MetricNameEncoder,
     173            0 :     enc: &mut Enc,
     174            0 : ) -> Result<(), Enc::Err>
     175            0 : where
     176            0 :     GaugeState: MetricEncoding<Enc>,
     177            0 : {
     178            0 :     GaugeState::new(x).collect_into(&(), labels, name, enc)
     179            0 : }
     180              : 
     181              : #[derive(Default)]
     182              : struct Rusage;
     183              : 
     184            0 : #[derive(FixedCardinalityLabel, Clone, Copy)]
     185              : #[label(singleton = "io_operation")]
     186              : enum IoOp {
     187              :     Read,
     188              :     Write,
     189              : }
     190              : 
     191              : impl<T: Encoding> MetricGroup<T> for Rusage
     192              : where
     193              :     GaugeState: MetricEncoding<T>,
     194              : {
     195            0 :     fn collect_group_into(&self, enc: &mut T) -> Result<(), T::Err> {
     196            0 :         const DISK_IO: &MetricName = MetricName::from_str("disk_io_bytes_total");
     197            0 :         const MAXRSS: &MetricName = MetricName::from_str("maxrss_kb");
     198            0 : 
     199            0 :         let ru = get_rusage_stats();
     200            0 : 
     201            0 :         enc.write_help(
     202            0 :             DISK_IO,
     203            0 :             "Bytes written and read from disk, grouped by the operation (read|write)",
     204            0 :         )?;
     205            0 :         GaugeState::write_type(DISK_IO, enc)?;
     206            0 :         write_gauge(ru.ru_inblock * BYTES_IN_BLOCK, IoOp::Read, DISK_IO, enc)?;
     207            0 :         write_gauge(ru.ru_oublock * BYTES_IN_BLOCK, IoOp::Write, DISK_IO, enc)?;
     208              : 
     209            0 :         enc.write_help(MAXRSS, "Memory usage (Maximum Resident Set Size)")?;
     210            0 :         GaugeState::write_type(MAXRSS, enc)?;
     211            0 :         write_gauge(ru.ru_maxrss, IoOp::Read, MAXRSS, enc)?;
     212              : 
     213            0 :         Ok(())
     214            0 :     }
     215              : }
     216              : 
     217              : #[derive(Default)]
     218              : struct CollectionCounter(CounterState);
     219              : 
     220              : impl<T: Encoding> MetricFamilyEncoding<T> for CollectionCounter
     221              : where
     222              :     CounterState: MetricEncoding<T>,
     223              : {
     224            0 :     fn collect_family_into(
     225            0 :         &self,
     226            0 :         name: impl measured::metric::name::MetricNameEncoder,
     227            0 :         enc: &mut T,
     228            0 :     ) -> Result<(), T::Err> {
     229            0 :         self.0.inc();
     230            0 :         enc.write_help(&name, "Number of metric requests made")?;
     231            0 :         self.0.collect_into(&(), NoLabels, name, enc)
     232            0 :     }
     233              : }
     234              : 
     235            0 : pub fn set_build_info_metric(revision: &str, build_tag: &str) {
     236            0 :     let metric = register_int_gauge_vec!(
     237              :         "libmetrics_build_info",
     238              :         "Build/version information",
     239              :         &["revision", "build_tag"]
     240              :     )
     241            0 :     .expect("Failed to register build info metric");
     242            0 :     metric.with_label_values(&[revision, build_tag]).set(1);
     243            0 : }
     244              : const BYTES_IN_BLOCK: i64 = 512;
     245              : 
     246              : // Records I/O stats in a "cross-platform" way.
     247              : // Compiles both on macOS and Linux, but current macOS implementation always returns 0 as values for I/O stats.
     248              : // An alternative is to read procfs (`/proc/[pid]/io`) which does not work under macOS at all, hence abandoned.
     249              : //
     250              : // Uses https://www.freebsd.org/cgi/man.cgi?query=getrusage to retrieve the number of block operations
     251              : // performed by the process.
     252              : // We know the size of the block, so we can determine the I/O bytes out of it.
     253              : // The value might be not 100% exact, but should be fine for Prometheus metrics in this case.
     254            0 : fn update_rusage_metrics() {
     255            0 :     let rusage_stats = get_rusage_stats();
     256            0 : 
     257            0 :     DISK_IO_BYTES
     258            0 :         .with_label_values(&["read"])
     259            0 :         .set(rusage_stats.ru_inblock * BYTES_IN_BLOCK);
     260            0 :     DISK_IO_BYTES
     261            0 :         .with_label_values(&["write"])
     262            0 :         .set(rusage_stats.ru_oublock * BYTES_IN_BLOCK);
     263            0 : 
     264            0 :     // On macOS, the unit of maxrss is bytes; on Linux, it's kilobytes. https://stackoverflow.com/a/59915669
     265            0 :     #[cfg(target_os = "macos")]
     266            0 :     {
     267            0 :         MAXRSS_KB.set(rusage_stats.ru_maxrss / 1024);
     268            0 :     }
     269            0 :     #[cfg(not(target_os = "macos"))]
     270            0 :     {
     271            0 :         MAXRSS_KB.set(rusage_stats.ru_maxrss);
     272            0 :     }
     273            0 : }
     274              : 
     275            0 : fn get_rusage_stats() -> libc::rusage {
     276            0 :     let mut rusage = std::mem::MaybeUninit::uninit();
     277            0 : 
     278            0 :     // SAFETY: kernel will initialize the struct for us
     279            0 :     unsafe {
     280            0 :         let ret = libc::getrusage(libc::RUSAGE_SELF, rusage.as_mut_ptr());
     281            0 :         assert!(ret == 0, "getrusage failed: bad args");
     282            0 :         rusage.assume_init()
     283            0 :     }
     284            0 : }
     285              : 
     286              : /// Create an [`IntCounterPairVec`] and registers to default registry.
     287              : #[macro_export(local_inner_macros)]
     288              : macro_rules! register_int_counter_pair_vec {
     289              :     ($NAME1:expr, $HELP1:expr, $NAME2:expr, $HELP2:expr, $LABELS_NAMES:expr $(,)?) => {{
     290              :         match (
     291              :             $crate::register_int_counter_vec!($NAME1, $HELP1, $LABELS_NAMES),
     292              :             $crate::register_int_counter_vec!($NAME2, $HELP2, $LABELS_NAMES),
     293              :         ) {
     294              :             (Ok(inc), Ok(dec)) => Ok($crate::IntCounterPairVec::new(inc, dec)),
     295              :             (Err(e), _) | (_, Err(e)) => Err(e),
     296              :         }
     297              :     }};
     298              : }
     299              : 
     300              : /// Create an [`IntCounterPair`] and registers to default registry.
     301              : #[macro_export(local_inner_macros)]
     302              : macro_rules! register_int_counter_pair {
     303              :     ($NAME1:expr, $HELP1:expr, $NAME2:expr, $HELP2:expr $(,)?) => {{
     304              :         match (
     305              :             $crate::register_int_counter!($NAME1, $HELP1),
     306              :             $crate::register_int_counter!($NAME2, $HELP2),
     307              :         ) {
     308              :             (Ok(inc), Ok(dec)) => Ok($crate::IntCounterPair::new(inc, dec)),
     309              :             (Err(e), _) | (_, Err(e)) => Err(e),
     310              :         }
     311              :     }};
     312              : }
     313              : 
     314              : /// A Pair of [`GenericCounterVec`]s. Like an [`GenericGaugeVec`] but will always observe changes
     315              : pub struct GenericCounterPairVec<P: Atomic> {
     316              :     inc: GenericCounterVec<P>,
     317              :     dec: GenericCounterVec<P>,
     318              : }
     319              : 
     320              : /// A Pair of [`GenericCounter`]s. Like an [`GenericGauge`] but will always observe changes
     321              : pub struct GenericCounterPair<P: Atomic> {
     322              :     inc: GenericCounter<P>,
     323              :     dec: GenericCounter<P>,
     324              : }
     325              : 
     326              : impl<P: Atomic> GenericCounterPairVec<P> {
     327          172 :     pub fn new(inc: GenericCounterVec<P>, dec: GenericCounterVec<P>) -> Self {
     328          172 :         Self { inc, dec }
     329          172 :     }
     330              : 
     331              :     /// `get_metric_with_label_values` returns the [`GenericCounterPair<P>`] for the given slice
     332              :     /// of label values (same order as the VariableLabels in Desc). If that combination of
     333              :     /// label values is accessed for the first time, a new [`GenericCounterPair<P>`] is created.
     334              :     ///
     335              :     /// An error is returned if the number of label values is not the same as the
     336              :     /// number of VariableLabels in Desc.
     337          894 :     pub fn get_metric_with_label_values(
     338          894 :         &self,
     339          894 :         vals: &[&str],
     340          894 :     ) -> prometheus::Result<GenericCounterPair<P>> {
     341          894 :         Ok(GenericCounterPair {
     342          894 :             inc: self.inc.get_metric_with_label_values(vals)?,
     343          894 :             dec: self.dec.get_metric_with_label_values(vals)?,
     344              :         })
     345          894 :     }
     346              : 
     347              :     /// `with_label_values` works as `get_metric_with_label_values`, but panics if an error
     348              :     /// occurs.
     349          180 :     pub fn with_label_values(&self, vals: &[&str]) -> GenericCounterPair<P> {
     350          180 :         self.get_metric_with_label_values(vals).unwrap()
     351          180 :     }
     352              : 
     353           24 :     pub fn remove_label_values(&self, res: &mut [prometheus::Result<()>; 2], vals: &[&str]) {
     354           24 :         res[0] = self.inc.remove_label_values(vals);
     355           24 :         res[1] = self.dec.remove_label_values(vals);
     356           24 :     }
     357              : }
     358              : 
     359              : impl<P: Atomic> GenericCounterPair<P> {
     360            0 :     pub fn new(inc: GenericCounter<P>, dec: GenericCounter<P>) -> Self {
     361            0 :         Self { inc, dec }
     362            0 :     }
     363              : 
     364              :     /// Increment the gauge by 1, returning a guard that decrements by 1 on drop.
     365          364 :     pub fn guard(&self) -> GenericCounterPairGuard<P> {
     366          364 :         self.inc.inc();
     367          364 :         GenericCounterPairGuard(self.dec.clone())
     368          364 :     }
     369              : 
     370              :     /// Increment the gauge by n, returning a guard that decrements by n on drop.
     371            0 :     pub fn guard_by(&self, n: P::T) -> GenericCounterPairGuardBy<P> {
     372            0 :         self.inc.inc_by(n);
     373            0 :         GenericCounterPairGuardBy(self.dec.clone(), n)
     374            0 :     }
     375              : 
     376              :     /// Increase the gauge by 1.
     377              :     #[inline]
     378         3438 :     pub fn inc(&self) {
     379         3438 :         self.inc.inc();
     380         3438 :     }
     381              : 
     382              :     /// Decrease the gauge by 1.
     383              :     #[inline]
     384         2867 :     pub fn dec(&self) {
     385         2867 :         self.dec.inc();
     386         2867 :     }
     387              : 
     388              :     /// Add the given value to the gauge. (The value can be
     389              :     /// negative, resulting in a decrement of the gauge.)
     390              :     #[inline]
     391            0 :     pub fn inc_by(&self, v: P::T) {
     392            0 :         self.inc.inc_by(v);
     393            0 :     }
     394              : 
     395              :     /// Subtract the given value from the gauge. (The value can be
     396              :     /// negative, resulting in an increment of the gauge.)
     397              :     #[inline]
     398            0 :     pub fn dec_by(&self, v: P::T) {
     399            0 :         self.dec.inc_by(v);
     400            0 :     }
     401              : }
     402              : 
     403              : impl<P: Atomic> Clone for GenericCounterPair<P> {
     404         6279 :     fn clone(&self) -> Self {
     405         6279 :         Self {
     406         6279 :             inc: self.inc.clone(),
     407         6279 :             dec: self.dec.clone(),
     408         6279 :         }
     409         6279 :     }
     410              : }
     411              : 
     412              : /// Guard returned by [`GenericCounterPair::guard`]
     413              : pub struct GenericCounterPairGuard<P: Atomic>(GenericCounter<P>);
     414              : 
     415              : impl<P: Atomic> Drop for GenericCounterPairGuard<P> {
     416          364 :     fn drop(&mut self) {
     417          364 :         self.0.inc();
     418          364 :     }
     419              : }
     420              : /// Guard returned by [`GenericCounterPair::guard_by`]
     421              : pub struct GenericCounterPairGuardBy<P: Atomic>(GenericCounter<P>, P::T);
     422              : 
     423              : impl<P: Atomic> Drop for GenericCounterPairGuardBy<P> {
     424            0 :     fn drop(&mut self) {
     425            0 :         self.0.inc_by(self.1);
     426            0 :     }
     427              : }
     428              : 
     429              : /// A Pair of [`IntCounterVec`]s. Like an [`IntGaugeVec`] but will always observe changes
     430              : pub type IntCounterPairVec = GenericCounterPairVec<AtomicU64>;
     431              : 
     432              : /// A Pair of [`IntCounter`]s. Like an [`IntGauge`] but will always observe changes
     433              : pub type IntCounterPair = GenericCounterPair<AtomicU64>;
     434              : 
     435              : /// A guard for [`IntCounterPair`] that will decrement the gauge on drop
     436              : pub type IntCounterPairGuard = GenericCounterPairGuard<AtomicU64>;
     437              : 
     438              : pub trait CounterPairAssoc {
     439              :     const INC_NAME: &'static MetricName;
     440              :     const DEC_NAME: &'static MetricName;
     441              : 
     442              :     const INC_HELP: &'static str;
     443              :     const DEC_HELP: &'static str;
     444              : 
     445              :     type LabelGroupSet: LabelGroupSet;
     446              : }
     447              : 
     448              : pub struct CounterPairVec<A: CounterPairAssoc> {
     449              :     vec: measured::metric::MetricVec<MeasuredCounterPairState, A::LabelGroupSet>,
     450              : }
     451              : 
     452              : impl<A: CounterPairAssoc> Default for CounterPairVec<A>
     453              : where
     454              :     A::LabelGroupSet: Default,
     455              : {
     456          216 :     fn default() -> Self {
     457          216 :         Self {
     458          216 :             vec: Default::default(),
     459          216 :         }
     460          216 :     }
     461              : }
     462              : 
     463              : impl<A: CounterPairAssoc> CounterPairVec<A> {
     464            0 :     pub fn guard(
     465            0 :         &self,
     466            0 :         labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>,
     467            0 :     ) -> MeasuredCounterPairGuard<'_, A> {
     468            0 :         let id = self.vec.with_labels(labels);
     469            0 :         self.vec.get_metric(id).inc.inc();
     470            0 :         MeasuredCounterPairGuard { vec: &self.vec, id }
     471            0 :     }
     472            0 :     pub fn inc(&self, labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>) {
     473            0 :         let id = self.vec.with_labels(labels);
     474            0 :         self.vec.get_metric(id).inc.inc();
     475            0 :     }
     476            0 :     pub fn dec(&self, labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>) {
     477            0 :         let id = self.vec.with_labels(labels);
     478            0 :         self.vec.get_metric(id).dec.inc();
     479            0 :     }
     480            0 :     pub fn remove_metric(
     481            0 :         &self,
     482            0 :         labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>,
     483            0 :     ) -> Option<MeasuredCounterPairState> {
     484            0 :         let id = self.vec.with_labels(labels);
     485            0 :         self.vec.remove_metric(id)
     486            0 :     }
     487              : 
     488            0 :     pub fn sample(&self, labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>) -> u64 {
     489            0 :         let id = self.vec.with_labels(labels);
     490            0 :         let metric = self.vec.get_metric(id);
     491            0 : 
     492            0 :         let inc = metric.inc.count.load(std::sync::atomic::Ordering::Relaxed);
     493            0 :         let dec = metric.dec.count.load(std::sync::atomic::Ordering::Relaxed);
     494            0 :         inc.saturating_sub(dec)
     495            0 :     }
     496              : }
     497              : 
     498              : impl<T, A> ::measured::metric::group::MetricGroup<T> for CounterPairVec<A>
     499              : where
     500              :     T: ::measured::metric::group::Encoding,
     501              :     A: CounterPairAssoc,
     502              :     ::measured::metric::counter::CounterState: ::measured::metric::MetricEncoding<T>,
     503              : {
     504            0 :     fn collect_group_into(&self, enc: &mut T) -> Result<(), T::Err> {
     505            0 :         // write decrement first to avoid a race condition where inc - dec < 0
     506            0 :         T::write_help(enc, A::DEC_NAME, A::DEC_HELP)?;
     507            0 :         self.vec
     508            0 :             .collect_family_into(A::DEC_NAME, &mut Dec(&mut *enc))?;
     509              : 
     510            0 :         T::write_help(enc, A::INC_NAME, A::INC_HELP)?;
     511            0 :         self.vec
     512            0 :             .collect_family_into(A::INC_NAME, &mut Inc(&mut *enc))?;
     513              : 
     514            0 :         Ok(())
     515            0 :     }
     516              : }
     517              : 
     518              : #[derive(MetricGroup, Default)]
     519              : pub struct MeasuredCounterPairState {
     520              :     pub inc: CounterState,
     521              :     pub dec: CounterState,
     522              : }
     523              : 
     524              : impl measured::metric::MetricType for MeasuredCounterPairState {
     525              :     type Metadata = ();
     526              : }
     527              : 
     528              : pub struct MeasuredCounterPairGuard<'a, A: CounterPairAssoc> {
     529              :     vec: &'a measured::metric::MetricVec<MeasuredCounterPairState, A::LabelGroupSet>,
     530              :     id: measured::metric::LabelId<A::LabelGroupSet>,
     531              : }
     532              : 
     533              : impl<A: CounterPairAssoc> Drop for MeasuredCounterPairGuard<'_, A> {
     534            0 :     fn drop(&mut self) {
     535            0 :         self.vec.get_metric(self.id).dec.inc();
     536            0 :     }
     537              : }
     538              : 
     539              : /// [`MetricEncoding`] for [`MeasuredCounterPairState`] that only writes the inc counter to the inner encoder.
     540              : struct Inc<T>(T);
     541              : /// [`MetricEncoding`] for [`MeasuredCounterPairState`] that only writes the dec counter to the inner encoder.
     542              : struct Dec<T>(T);
     543              : 
     544              : impl<T: Encoding> Encoding for Inc<T> {
     545              :     type Err = T::Err;
     546              : 
     547            0 :     fn write_help(&mut self, name: impl MetricNameEncoder, help: &str) -> Result<(), Self::Err> {
     548            0 :         self.0.write_help(name, help)
     549            0 :     }
     550              : }
     551              : 
     552              : impl<T: Encoding> MetricEncoding<Inc<T>> for MeasuredCounterPairState
     553              : where
     554              :     CounterState: MetricEncoding<T>,
     555              : {
     556            0 :     fn write_type(name: impl MetricNameEncoder, enc: &mut Inc<T>) -> Result<(), T::Err> {
     557            0 :         CounterState::write_type(name, &mut enc.0)
     558            0 :     }
     559            0 :     fn collect_into(
     560            0 :         &self,
     561            0 :         metadata: &(),
     562            0 :         labels: impl LabelGroup,
     563            0 :         name: impl MetricNameEncoder,
     564            0 :         enc: &mut Inc<T>,
     565            0 :     ) -> Result<(), T::Err> {
     566            0 :         self.inc.collect_into(metadata, labels, name, &mut enc.0)
     567            0 :     }
     568              : }
     569              : 
     570              : impl<T: Encoding> Encoding for Dec<T> {
     571              :     type Err = T::Err;
     572              : 
     573            0 :     fn write_help(&mut self, name: impl MetricNameEncoder, help: &str) -> Result<(), Self::Err> {
     574            0 :         self.0.write_help(name, help)
     575            0 :     }
     576              : }
     577              : 
     578              : /// Write the dec counter to the encoder
     579              : impl<T: Encoding> MetricEncoding<Dec<T>> for MeasuredCounterPairState
     580              : where
     581              :     CounterState: MetricEncoding<T>,
     582              : {
     583            0 :     fn write_type(name: impl MetricNameEncoder, enc: &mut Dec<T>) -> Result<(), T::Err> {
     584            0 :         CounterState::write_type(name, &mut enc.0)
     585            0 :     }
     586            0 :     fn collect_into(
     587            0 :         &self,
     588            0 :         metadata: &(),
     589            0 :         labels: impl LabelGroup,
     590            0 :         name: impl MetricNameEncoder,
     591            0 :         enc: &mut Dec<T>,
     592            0 :     ) -> Result<(), T::Err> {
     593            0 :         self.dec.collect_into(metadata, labels, name, &mut enc.0)
     594            0 :     }
     595              : }
        

Generated by: LCOV version 2.1-beta