LCOV - code coverage report
Current view: top level - libs/metrics/src - lib.rs (source / functions) Coverage Total Hit
Test: b837401fb09d2d9818b70e630fdb67e9799b7b0d.info Lines: 16.7 % 251 42
Test Date: 2024-04-18 15:32:49 Functions: 15.4 % 78 12

            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, MetricValue},
      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              :         $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              :         $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            0 :     register_int_gauge_vec!(
      91            0 :         "libmetrics_disk_io_bytes_total",
      92            0 :         "Bytes written and read from disk, grouped by the operation (read|write)",
      93            0 :         &["io_operation"]
      94            0 :     )
      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            0 :     register_int_gauge!(
     100            0 :         "libmetrics_maxrss_kb",
     101            0 :         "Memory usage (Maximum Resident Set Size)"
     102            0 :     )
     103            0 :     .expect("Failed to register maxrss_kb int gauge")
     104            0 : });
     105              : 
     106              : pub const DISK_WRITE_SECONDS_BUCKETS: &[f64] = &[
     107              :     0.000_050, 0.000_100, 0.000_500, 0.001, 0.003, 0.005, 0.01, 0.05, 0.1, 0.3, 0.5,
     108              : ];
     109              : 
     110              : pub struct BuildInfo {
     111              :     pub revision: &'static str,
     112              :     pub build_tag: &'static str,
     113              : }
     114              : 
     115              : // todo: allow label group without the set
     116              : impl LabelGroup for BuildInfo {
     117            0 :     fn visit_values(&self, v: &mut impl LabelGroupVisitor) {
     118            0 :         const REVISION: &LabelName = LabelName::from_str("revision");
     119            0 :         v.write_value(REVISION, &self.revision);
     120            0 :         const BUILD_TAG: &LabelName = LabelName::from_str("build_tag");
     121            0 :         v.write_value(BUILD_TAG, &self.build_tag);
     122            0 :     }
     123              : }
     124              : 
     125              : impl<T: Encoding> MetricFamilyEncoding<T> for BuildInfo
     126              : where
     127              :     GaugeState: MetricEncoding<T>,
     128              : {
     129            0 :     fn collect_family_into(
     130            0 :         &self,
     131            0 :         name: impl measured::metric::name::MetricNameEncoder,
     132            0 :         enc: &mut T,
     133            0 :     ) -> Result<(), T::Err> {
     134            0 :         enc.write_help(&name, "Build/version information")?;
     135            0 :         GaugeState::write_type(&name, enc)?;
     136            0 :         GaugeState {
     137            0 :             count: std::sync::atomic::AtomicI64::new(1),
     138            0 :         }
     139            0 :         .collect_into(&(), self, name, enc)
     140            0 :     }
     141              : }
     142              : 
     143            0 : #[derive(MetricGroup)]
     144              : #[metric(new(build_info: BuildInfo))]
     145              : pub struct NeonMetrics {
     146              :     #[cfg(target_os = "linux")]
     147              :     #[metric(namespace = "process")]
     148              :     #[metric(init = measured_process::ProcessCollector::for_self())]
     149              :     process: measured_process::ProcessCollector,
     150              : 
     151              :     #[metric(namespace = "libmetrics")]
     152              :     #[metric(init = LibMetrics::new(build_info))]
     153              :     libmetrics: LibMetrics,
     154              : }
     155              : 
     156            0 : #[derive(MetricGroup)]
     157              : #[metric(new(build_info: BuildInfo))]
     158              : pub struct LibMetrics {
     159              :     #[metric(init = build_info)]
     160              :     build_info: BuildInfo,
     161              : 
     162              :     #[metric(flatten)]
     163              :     rusage: Rusage,
     164              : 
     165              :     serve_count: CollectionCounter,
     166              : }
     167              : 
     168            0 : fn write_gauge<Enc: Encoding>(
     169            0 :     x: i64,
     170            0 :     labels: impl LabelGroup,
     171            0 :     name: impl MetricNameEncoder,
     172            0 :     enc: &mut Enc,
     173            0 : ) -> Result<(), Enc::Err> {
     174            0 :     enc.write_metric_value(name, labels, MetricValue::Int(x))
     175            0 : }
     176              : 
     177              : #[derive(Default)]
     178              : struct Rusage;
     179              : 
     180            0 : #[derive(FixedCardinalityLabel, Clone, Copy)]
     181              : #[label(singleton = "io_operation")]
     182              : enum IoOp {
     183              :     Read,
     184              :     Write,
     185              : }
     186              : 
     187              : impl<T: Encoding> MetricGroup<T> for Rusage
     188              : where
     189              :     GaugeState: MetricEncoding<T>,
     190              : {
     191            0 :     fn collect_group_into(&self, enc: &mut T) -> Result<(), T::Err> {
     192            0 :         const DISK_IO: &MetricName = MetricName::from_str("disk_io_bytes_total");
     193            0 :         const MAXRSS: &MetricName = MetricName::from_str("maxrss_kb");
     194            0 : 
     195            0 :         let ru = get_rusage_stats();
     196            0 : 
     197            0 :         enc.write_help(
     198            0 :             DISK_IO,
     199            0 :             "Bytes written and read from disk, grouped by the operation (read|write)",
     200            0 :         )?;
     201            0 :         GaugeState::write_type(DISK_IO, enc)?;
     202            0 :         write_gauge(ru.ru_inblock * BYTES_IN_BLOCK, IoOp::Read, DISK_IO, enc)?;
     203            0 :         write_gauge(ru.ru_oublock * BYTES_IN_BLOCK, IoOp::Write, DISK_IO, enc)?;
     204              : 
     205            0 :         enc.write_help(MAXRSS, "Memory usage (Maximum Resident Set Size)")?;
     206            0 :         GaugeState::write_type(MAXRSS, enc)?;
     207            0 :         write_gauge(ru.ru_maxrss, IoOp::Read, MAXRSS, enc)?;
     208              : 
     209            0 :         Ok(())
     210            0 :     }
     211              : }
     212              : 
     213              : #[derive(Default)]
     214              : struct CollectionCounter(CounterState);
     215              : 
     216              : impl<T: Encoding> MetricFamilyEncoding<T> for CollectionCounter
     217              : where
     218              :     CounterState: MetricEncoding<T>,
     219              : {
     220            0 :     fn collect_family_into(
     221            0 :         &self,
     222            0 :         name: impl measured::metric::name::MetricNameEncoder,
     223            0 :         enc: &mut T,
     224            0 :     ) -> Result<(), T::Err> {
     225            0 :         self.0.inc();
     226            0 :         enc.write_help(&name, "Number of metric requests made")?;
     227            0 :         self.0.collect_into(&(), NoLabels, name, enc)
     228            0 :     }
     229              : }
     230              : 
     231            0 : pub fn set_build_info_metric(revision: &str, build_tag: &str) {
     232            0 :     let metric = register_int_gauge_vec!(
     233            0 :         "libmetrics_build_info",
     234            0 :         "Build/version information",
     235            0 :         &["revision", "build_tag"]
     236            0 :     )
     237            0 :     .expect("Failed to register build info metric");
     238            0 :     metric.with_label_values(&[revision, build_tag]).set(1);
     239            0 : }
     240              : const BYTES_IN_BLOCK: i64 = 512;
     241              : 
     242              : // Records I/O stats in a "cross-platform" way.
     243              : // Compiles both on macOS and Linux, but current macOS implementation always returns 0 as values for I/O stats.
     244              : // An alternative is to read procfs (`/proc/[pid]/io`) which does not work under macOS at all, hence abandoned.
     245              : //
     246              : // Uses https://www.freebsd.org/cgi/man.cgi?query=getrusage to retrieve the number of block operations
     247              : // performed by the process.
     248              : // We know the size of the block, so we can determine the I/O bytes out of it.
     249              : // The value might be not 100% exact, but should be fine for Prometheus metrics in this case.
     250            0 : fn update_rusage_metrics() {
     251            0 :     let rusage_stats = get_rusage_stats();
     252            0 : 
     253            0 :     DISK_IO_BYTES
     254            0 :         .with_label_values(&["read"])
     255            0 :         .set(rusage_stats.ru_inblock * BYTES_IN_BLOCK);
     256            0 :     DISK_IO_BYTES
     257            0 :         .with_label_values(&["write"])
     258            0 :         .set(rusage_stats.ru_oublock * BYTES_IN_BLOCK);
     259            0 :     MAXRSS_KB.set(rusage_stats.ru_maxrss);
     260            0 : }
     261              : 
     262            0 : fn get_rusage_stats() -> libc::rusage {
     263            0 :     let mut rusage = std::mem::MaybeUninit::uninit();
     264            0 : 
     265            0 :     // SAFETY: kernel will initialize the struct for us
     266            0 :     unsafe {
     267            0 :         let ret = libc::getrusage(libc::RUSAGE_SELF, rusage.as_mut_ptr());
     268            0 :         assert!(ret == 0, "getrusage failed: bad args");
     269            0 :         rusage.assume_init()
     270            0 :     }
     271            0 : }
     272              : 
     273              : /// Create an [`IntCounterPairVec`] and registers to default registry.
     274              : #[macro_export(local_inner_macros)]
     275              : macro_rules! register_int_counter_pair_vec {
     276              :     ($NAME1:expr, $HELP1:expr, $NAME2:expr, $HELP2:expr, $LABELS_NAMES:expr $(,)?) => {{
     277              :         match (
     278              :             $crate::register_int_counter_vec!($NAME1, $HELP1, $LABELS_NAMES),
     279              :             $crate::register_int_counter_vec!($NAME2, $HELP2, $LABELS_NAMES),
     280              :         ) {
     281              :             (Ok(inc), Ok(dec)) => Ok($crate::IntCounterPairVec::new(inc, dec)),
     282              :             (Err(e), _) | (_, Err(e)) => Err(e),
     283              :         }
     284              :     }};
     285              : }
     286              : 
     287              : /// Create an [`IntCounterPair`] and registers to default registry.
     288              : #[macro_export(local_inner_macros)]
     289              : macro_rules! register_int_counter_pair {
     290              :     ($NAME1:expr, $HELP1:expr, $NAME2:expr, $HELP2:expr $(,)?) => {{
     291              :         match (
     292              :             $crate::register_int_counter!($NAME1, $HELP1),
     293              :             $crate::register_int_counter!($NAME2, $HELP2),
     294              :         ) {
     295              :             (Ok(inc), Ok(dec)) => Ok($crate::IntCounterPair::new(inc, dec)),
     296              :             (Err(e), _) | (_, Err(e)) => Err(e),
     297              :         }
     298              :     }};
     299              : }
     300              : 
     301              : /// A Pair of [`GenericCounterVec`]s. Like an [`GenericGaugeVec`] but will always observe changes
     302              : pub struct GenericCounterPairVec<P: Atomic> {
     303              :     inc: GenericCounterVec<P>,
     304              :     dec: GenericCounterVec<P>,
     305              : }
     306              : 
     307              : /// A Pair of [`GenericCounter`]s. Like an [`GenericGauge`] but will always observe changes
     308              : pub struct GenericCounterPair<P: Atomic> {
     309              :     inc: GenericCounter<P>,
     310              :     dec: GenericCounter<P>,
     311              : }
     312              : 
     313              : impl<P: Atomic> GenericCounterPairVec<P> {
     314          110 :     pub fn new(inc: GenericCounterVec<P>, dec: GenericCounterVec<P>) -> Self {
     315          110 :         Self { inc, dec }
     316          110 :     }
     317              : 
     318              :     /// `get_metric_with_label_values` returns the [`GenericCounterPair<P>`] for the given slice
     319              :     /// of label values (same order as the VariableLabels in Desc). If that combination of
     320              :     /// label values is accessed for the first time, a new [`GenericCounterPair<P>`] is created.
     321              :     ///
     322              :     /// An error is returned if the number of label values is not the same as the
     323              :     /// number of VariableLabels in Desc.
     324         1064 :     pub fn get_metric_with_label_values(
     325         1064 :         &self,
     326         1064 :         vals: &[&str],
     327         1064 :     ) -> prometheus::Result<GenericCounterPair<P>> {
     328         1064 :         Ok(GenericCounterPair {
     329         1064 :             inc: self.inc.get_metric_with_label_values(vals)?,
     330         1064 :             dec: self.dec.get_metric_with_label_values(vals)?,
     331              :         })
     332         1064 :     }
     333              : 
     334              :     /// `with_label_values` works as `get_metric_with_label_values`, but panics if an error
     335              :     /// occurs.
     336          510 :     pub fn with_label_values(&self, vals: &[&str]) -> GenericCounterPair<P> {
     337          510 :         self.get_metric_with_label_values(vals).unwrap()
     338          510 :     }
     339              : 
     340           22 :     pub fn remove_label_values(&self, res: &mut [prometheus::Result<()>; 2], vals: &[&str]) {
     341           22 :         res[0] = self.inc.remove_label_values(vals);
     342           22 :         res[1] = self.dec.remove_label_values(vals);
     343           22 :     }
     344              : }
     345              : 
     346              : impl<P: Atomic> GenericCounterPair<P> {
     347            0 :     pub fn new(inc: GenericCounter<P>, dec: GenericCounter<P>) -> Self {
     348            0 :         Self { inc, dec }
     349            0 :     }
     350              : 
     351              :     /// Increment the gauge by 1, returning a guard that decrements by 1 on drop.
     352          510 :     pub fn guard(&self) -> GenericCounterPairGuard<P> {
     353          510 :         self.inc.inc();
     354          510 :         GenericCounterPairGuard(self.dec.clone())
     355          510 :     }
     356              : 
     357              :     /// Increment the gauge by n, returning a guard that decrements by n on drop.
     358            0 :     pub fn guard_by(&self, n: P::T) -> GenericCounterPairGuardBy<P> {
     359            0 :         self.inc.inc_by(n);
     360            0 :         GenericCounterPairGuardBy(self.dec.clone(), n)
     361            0 :     }
     362              : 
     363              :     /// Increase the gauge by 1.
     364              :     #[inline]
     365         2388 :     pub fn inc(&self) {
     366         2388 :         self.inc.inc();
     367         2388 :     }
     368              : 
     369              :     /// Decrease the gauge by 1.
     370              :     #[inline]
     371         2027 :     pub fn dec(&self) {
     372         2027 :         self.dec.inc();
     373         2027 :     }
     374              : 
     375              :     /// Add the given value to the gauge. (The value can be
     376              :     /// negative, resulting in a decrement of the gauge.)
     377              :     #[inline]
     378            0 :     pub fn inc_by(&self, v: P::T) {
     379            0 :         self.inc.inc_by(v);
     380            0 :     }
     381              : 
     382              :     /// Subtract the given value from the gauge. (The value can be
     383              :     /// negative, resulting in an increment of the gauge.)
     384              :     #[inline]
     385            0 :     pub fn dec_by(&self, v: P::T) {
     386            0 :         self.dec.inc_by(v);
     387            0 :     }
     388              : }
     389              : 
     390              : impl<P: Atomic> Clone for GenericCounterPair<P> {
     391         4389 :     fn clone(&self) -> Self {
     392         4389 :         Self {
     393         4389 :             inc: self.inc.clone(),
     394         4389 :             dec: self.dec.clone(),
     395         4389 :         }
     396         4389 :     }
     397              : }
     398              : 
     399              : /// Guard returned by [`GenericCounterPair::guard`]
     400              : pub struct GenericCounterPairGuard<P: Atomic>(GenericCounter<P>);
     401              : 
     402              : impl<P: Atomic> Drop for GenericCounterPairGuard<P> {
     403          510 :     fn drop(&mut self) {
     404          510 :         self.0.inc();
     405          510 :     }
     406              : }
     407              : /// Guard returned by [`GenericCounterPair::guard_by`]
     408              : pub struct GenericCounterPairGuardBy<P: Atomic>(GenericCounter<P>, P::T);
     409              : 
     410              : impl<P: Atomic> Drop for GenericCounterPairGuardBy<P> {
     411            0 :     fn drop(&mut self) {
     412            0 :         self.0.inc_by(self.1);
     413            0 :     }
     414              : }
     415              : 
     416              : /// A Pair of [`IntCounterVec`]s. Like an [`IntGaugeVec`] but will always observe changes
     417              : pub type IntCounterPairVec = GenericCounterPairVec<AtomicU64>;
     418              : 
     419              : /// A Pair of [`IntCounter`]s. Like an [`IntGauge`] but will always observe changes
     420              : pub type IntCounterPair = GenericCounterPair<AtomicU64>;
     421              : 
     422              : /// A guard for [`IntCounterPair`] that will decrement the gauge on drop
     423              : pub type IntCounterPairGuard = GenericCounterPairGuard<AtomicU64>;
     424              : 
     425              : pub trait CounterPairAssoc {
     426              :     const INC_NAME: &'static MetricName;
     427              :     const DEC_NAME: &'static MetricName;
     428              : 
     429              :     const INC_HELP: &'static str;
     430              :     const DEC_HELP: &'static str;
     431              : 
     432              :     type LabelGroupSet: LabelGroupSet;
     433              : }
     434              : 
     435              : pub struct CounterPairVec<A: CounterPairAssoc> {
     436              :     vec: measured::metric::MetricVec<MeasuredCounterPairState, A::LabelGroupSet>,
     437              : }
     438              : 
     439              : impl<A: CounterPairAssoc> Default for CounterPairVec<A>
     440              : where
     441              :     A::LabelGroupSet: Default,
     442              : {
     443          216 :     fn default() -> Self {
     444          216 :         Self {
     445          216 :             vec: Default::default(),
     446          216 :         }
     447          216 :     }
     448              : }
     449              : 
     450              : impl<A: CounterPairAssoc> CounterPairVec<A> {
     451            0 :     pub fn guard(
     452            0 :         &self,
     453            0 :         labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>,
     454            0 :     ) -> MeasuredCounterPairGuard<'_, A> {
     455            0 :         let id = self.vec.with_labels(labels);
     456            0 :         self.vec.get_metric(id).inc.inc();
     457            0 :         MeasuredCounterPairGuard { vec: &self.vec, id }
     458            0 :     }
     459            0 :     pub fn inc(&self, labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>) {
     460            0 :         let id = self.vec.with_labels(labels);
     461            0 :         self.vec.get_metric(id).inc.inc();
     462            0 :     }
     463            0 :     pub fn dec(&self, labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>) {
     464            0 :         let id = self.vec.with_labels(labels);
     465            0 :         self.vec.get_metric(id).dec.inc();
     466            0 :     }
     467            0 :     pub fn remove_metric(
     468            0 :         &self,
     469            0 :         labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>,
     470            0 :     ) -> Option<MeasuredCounterPairState> {
     471            0 :         let id = self.vec.with_labels(labels);
     472            0 :         self.vec.remove_metric(id)
     473            0 :     }
     474              : }
     475              : 
     476              : impl<T, A> ::measured::metric::group::MetricGroup<T> for CounterPairVec<A>
     477              : where
     478              :     T: ::measured::metric::group::Encoding,
     479              :     A: CounterPairAssoc,
     480              :     ::measured::metric::counter::CounterState: ::measured::metric::MetricEncoding<T>,
     481              : {
     482            0 :     fn collect_group_into(&self, enc: &mut T) -> Result<(), T::Err> {
     483            0 :         // write decrement first to avoid a race condition where inc - dec < 0
     484            0 :         T::write_help(enc, A::DEC_NAME, A::DEC_HELP)?;
     485            0 :         self.vec
     486            0 :             .collect_family_into(A::DEC_NAME, &mut Dec(&mut *enc))?;
     487              : 
     488            0 :         T::write_help(enc, A::INC_NAME, A::INC_HELP)?;
     489            0 :         self.vec
     490            0 :             .collect_family_into(A::INC_NAME, &mut Inc(&mut *enc))?;
     491              : 
     492            0 :         Ok(())
     493            0 :     }
     494              : }
     495              : 
     496              : #[derive(MetricGroup, Default)]
     497              : pub struct MeasuredCounterPairState {
     498              :     pub inc: CounterState,
     499              :     pub dec: CounterState,
     500              : }
     501              : 
     502              : impl measured::metric::MetricType for MeasuredCounterPairState {
     503              :     type Metadata = ();
     504              : }
     505              : 
     506              : pub struct MeasuredCounterPairGuard<'a, A: CounterPairAssoc> {
     507              :     vec: &'a measured::metric::MetricVec<MeasuredCounterPairState, A::LabelGroupSet>,
     508              :     id: measured::metric::LabelId<A::LabelGroupSet>,
     509              : }
     510              : 
     511              : impl<A: CounterPairAssoc> Drop for MeasuredCounterPairGuard<'_, A> {
     512            0 :     fn drop(&mut self) {
     513            0 :         self.vec.get_metric(self.id).dec.inc();
     514            0 :     }
     515              : }
     516              : 
     517              : /// [`MetricEncoding`] for [`MeasuredCounterPairState`] that only writes the inc counter to the inner encoder.
     518              : struct Inc<T>(T);
     519              : /// [`MetricEncoding`] for [`MeasuredCounterPairState`] that only writes the dec counter to the inner encoder.
     520              : struct Dec<T>(T);
     521              : 
     522              : impl<T: Encoding> Encoding for Inc<T> {
     523              :     type Err = T::Err;
     524              : 
     525            0 :     fn write_help(&mut self, name: impl MetricNameEncoder, help: &str) -> Result<(), Self::Err> {
     526            0 :         self.0.write_help(name, help)
     527            0 :     }
     528              : 
     529            0 :     fn write_metric_value(
     530            0 :         &mut self,
     531            0 :         name: impl MetricNameEncoder,
     532            0 :         labels: impl LabelGroup,
     533            0 :         value: MetricValue,
     534            0 :     ) -> Result<(), Self::Err> {
     535            0 :         self.0.write_metric_value(name, labels, value)
     536            0 :     }
     537              : }
     538              : 
     539              : impl<T: Encoding> MetricEncoding<Inc<T>> for MeasuredCounterPairState
     540              : where
     541              :     CounterState: MetricEncoding<T>,
     542              : {
     543            0 :     fn write_type(name: impl MetricNameEncoder, enc: &mut Inc<T>) -> Result<(), T::Err> {
     544            0 :         CounterState::write_type(name, &mut enc.0)
     545            0 :     }
     546            0 :     fn collect_into(
     547            0 :         &self,
     548            0 :         metadata: &(),
     549            0 :         labels: impl LabelGroup,
     550            0 :         name: impl MetricNameEncoder,
     551            0 :         enc: &mut Inc<T>,
     552            0 :     ) -> Result<(), T::Err> {
     553            0 :         self.inc.collect_into(metadata, labels, name, &mut enc.0)
     554            0 :     }
     555              : }
     556              : 
     557              : impl<T: Encoding> Encoding for Dec<T> {
     558              :     type Err = T::Err;
     559              : 
     560            0 :     fn write_help(&mut self, name: impl MetricNameEncoder, help: &str) -> Result<(), Self::Err> {
     561            0 :         self.0.write_help(name, help)
     562            0 :     }
     563              : 
     564            0 :     fn write_metric_value(
     565            0 :         &mut self,
     566            0 :         name: impl MetricNameEncoder,
     567            0 :         labels: impl LabelGroup,
     568            0 :         value: MetricValue,
     569            0 :     ) -> Result<(), Self::Err> {
     570            0 :         self.0.write_metric_value(name, labels, value)
     571            0 :     }
     572              : }
     573              : 
     574              : /// Write the dec counter to the encoder
     575              : impl<T: Encoding> MetricEncoding<Dec<T>> for MeasuredCounterPairState
     576              : where
     577              :     CounterState: MetricEncoding<T>,
     578              : {
     579            0 :     fn write_type(name: impl MetricNameEncoder, enc: &mut Dec<T>) -> Result<(), T::Err> {
     580            0 :         CounterState::write_type(name, &mut enc.0)
     581            0 :     }
     582            0 :     fn collect_into(
     583            0 :         &self,
     584            0 :         metadata: &(),
     585            0 :         labels: impl LabelGroup,
     586            0 :         name: impl MetricNameEncoder,
     587            0 :         enc: &mut Dec<T>,
     588            0 :     ) -> Result<(), T::Err> {
     589            0 :         self.dec.collect_into(metadata, labels, name, &mut enc.0)
     590            0 :     }
     591              : }
        

Generated by: LCOV version 2.1-beta