LCOV - code coverage report
Current view: top level - libs/metrics/src - lib.rs (source / functions) Coverage Total Hit
Test: 86c536b7fe84b2afe03c3bb264199e9c319ae0f8.info Lines: 17.1 % 257 44
Test Date: 2024-06-24 16:38:41 Functions: 26.0 % 96 25

            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          785 :         $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          481 :         $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              : 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              :         "libmetrics_build_info",
     234              :         "Build/version information",
     235              :         &["revision", "build_tag"]
     236              :     )
     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 : 
     260            0 :     // On macOS, the unit of maxrss is bytes; on Linux, it's kilobytes. https://stackoverflow.com/a/59915669
     261            0 :     #[cfg(target_os = "macos")]
     262            0 :     {
     263            0 :         MAXRSS_KB.set(rusage_stats.ru_maxrss / 1024);
     264            0 :     }
     265            0 :     #[cfg(not(target_os = "macos"))]
     266            0 :     {
     267            0 :         MAXRSS_KB.set(rusage_stats.ru_maxrss);
     268            0 :     }
     269            0 : }
     270              : 
     271            0 : fn get_rusage_stats() -> libc::rusage {
     272            0 :     let mut rusage = std::mem::MaybeUninit::uninit();
     273            0 : 
     274            0 :     // SAFETY: kernel will initialize the struct for us
     275            0 :     unsafe {
     276            0 :         let ret = libc::getrusage(libc::RUSAGE_SELF, rusage.as_mut_ptr());
     277            0 :         assert!(ret == 0, "getrusage failed: bad args");
     278            0 :         rusage.assume_init()
     279            0 :     }
     280            0 : }
     281              : 
     282              : /// Create an [`IntCounterPairVec`] and registers to default registry.
     283              : #[macro_export(local_inner_macros)]
     284              : macro_rules! register_int_counter_pair_vec {
     285              :     ($NAME1:expr, $HELP1:expr, $NAME2:expr, $HELP2:expr, $LABELS_NAMES:expr $(,)?) => {{
     286              :         match (
     287              :             $crate::register_int_counter_vec!($NAME1, $HELP1, $LABELS_NAMES),
     288              :             $crate::register_int_counter_vec!($NAME2, $HELP2, $LABELS_NAMES),
     289              :         ) {
     290              :             (Ok(inc), Ok(dec)) => Ok($crate::IntCounterPairVec::new(inc, dec)),
     291              :             (Err(e), _) | (_, Err(e)) => Err(e),
     292              :         }
     293              :     }};
     294              : }
     295              : 
     296              : /// Create an [`IntCounterPair`] and registers to default registry.
     297              : #[macro_export(local_inner_macros)]
     298              : macro_rules! register_int_counter_pair {
     299              :     ($NAME1:expr, $HELP1:expr, $NAME2:expr, $HELP2:expr $(,)?) => {{
     300              :         match (
     301              :             $crate::register_int_counter!($NAME1, $HELP1),
     302              :             $crate::register_int_counter!($NAME2, $HELP2),
     303              :         ) {
     304              :             (Ok(inc), Ok(dec)) => Ok($crate::IntCounterPair::new(inc, dec)),
     305              :             (Err(e), _) | (_, Err(e)) => Err(e),
     306              :         }
     307              :     }};
     308              : }
     309              : 
     310              : /// A Pair of [`GenericCounterVec`]s. Like an [`GenericGaugeVec`] but will always observe changes
     311              : pub struct GenericCounterPairVec<P: Atomic> {
     312              :     inc: GenericCounterVec<P>,
     313              :     dec: GenericCounterVec<P>,
     314              : }
     315              : 
     316              : /// A Pair of [`GenericCounter`]s. Like an [`GenericGauge`] but will always observe changes
     317              : pub struct GenericCounterPair<P: Atomic> {
     318              :     inc: GenericCounter<P>,
     319              :     dec: GenericCounter<P>,
     320              : }
     321              : 
     322              : impl<P: Atomic> GenericCounterPairVec<P> {
     323          157 :     pub fn new(inc: GenericCounterVec<P>, dec: GenericCounterVec<P>) -> Self {
     324          157 :         Self { inc, dec }
     325          157 :     }
     326              : 
     327              :     /// `get_metric_with_label_values` returns the [`GenericCounterPair<P>`] for the given slice
     328              :     /// of label values (same order as the VariableLabels in Desc). If that combination of
     329              :     /// label values is accessed for the first time, a new [`GenericCounterPair<P>`] is created.
     330              :     ///
     331              :     /// An error is returned if the number of label values is not the same as the
     332              :     /// number of VariableLabels in Desc.
     333          856 :     pub fn get_metric_with_label_values(
     334          856 :         &self,
     335          856 :         vals: &[&str],
     336          856 :     ) -> prometheus::Result<GenericCounterPair<P>> {
     337          856 :         Ok(GenericCounterPair {
     338          856 :             inc: self.inc.get_metric_with_label_values(vals)?,
     339          856 :             dec: self.dec.get_metric_with_label_values(vals)?,
     340              :         })
     341          856 :     }
     342              : 
     343              :     /// `with_label_values` works as `get_metric_with_label_values`, but panics if an error
     344              :     /// occurs.
     345          180 :     pub fn with_label_values(&self, vals: &[&str]) -> GenericCounterPair<P> {
     346          180 :         self.get_metric_with_label_values(vals).unwrap()
     347          180 :     }
     348              : 
     349           24 :     pub fn remove_label_values(&self, res: &mut [prometheus::Result<()>; 2], vals: &[&str]) {
     350           24 :         res[0] = self.inc.remove_label_values(vals);
     351           24 :         res[1] = self.dec.remove_label_values(vals);
     352           24 :     }
     353              : }
     354              : 
     355              : impl<P: Atomic> GenericCounterPair<P> {
     356            0 :     pub fn new(inc: GenericCounter<P>, dec: GenericCounter<P>) -> Self {
     357            0 :         Self { inc, dec }
     358            0 :     }
     359              : 
     360              :     /// Increment the gauge by 1, returning a guard that decrements by 1 on drop.
     361          364 :     pub fn guard(&self) -> GenericCounterPairGuard<P> {
     362          364 :         self.inc.inc();
     363          364 :         GenericCounterPairGuard(self.dec.clone())
     364          364 :     }
     365              : 
     366              :     /// Increment the gauge by n, returning a guard that decrements by n on drop.
     367            0 :     pub fn guard_by(&self, n: P::T) -> GenericCounterPairGuardBy<P> {
     368            0 :         self.inc.inc_by(n);
     369            0 :         GenericCounterPairGuardBy(self.dec.clone(), n)
     370            0 :     }
     371              : 
     372              :     /// Increase the gauge by 1.
     373              :     #[inline]
     374         3336 :     pub fn inc(&self) {
     375         3336 :         self.inc.inc();
     376         3336 :     }
     377              : 
     378              :     /// Decrease the gauge by 1.
     379              :     #[inline]
     380         2771 :     pub fn dec(&self) {
     381         2771 :         self.dec.inc();
     382         2771 :     }
     383              : 
     384              :     /// Add the given value to the gauge. (The value can be
     385              :     /// negative, resulting in a decrement of the gauge.)
     386              :     #[inline]
     387            0 :     pub fn inc_by(&self, v: P::T) {
     388            0 :         self.inc.inc_by(v);
     389            0 :     }
     390              : 
     391              :     /// Subtract the given value from the gauge. (The value can be
     392              :     /// negative, resulting in an increment of the gauge.)
     393              :     #[inline]
     394            0 :     pub fn dec_by(&self, v: P::T) {
     395            0 :         self.dec.inc_by(v);
     396            0 :     }
     397              : }
     398              : 
     399              : impl<P: Atomic> Clone for GenericCounterPair<P> {
     400         6081 :     fn clone(&self) -> Self {
     401         6081 :         Self {
     402         6081 :             inc: self.inc.clone(),
     403         6081 :             dec: self.dec.clone(),
     404         6081 :         }
     405         6081 :     }
     406              : }
     407              : 
     408              : /// Guard returned by [`GenericCounterPair::guard`]
     409              : pub struct GenericCounterPairGuard<P: Atomic>(GenericCounter<P>);
     410              : 
     411              : impl<P: Atomic> Drop for GenericCounterPairGuard<P> {
     412          364 :     fn drop(&mut self) {
     413          364 :         self.0.inc();
     414          364 :     }
     415              : }
     416              : /// Guard returned by [`GenericCounterPair::guard_by`]
     417              : pub struct GenericCounterPairGuardBy<P: Atomic>(GenericCounter<P>, P::T);
     418              : 
     419              : impl<P: Atomic> Drop for GenericCounterPairGuardBy<P> {
     420            0 :     fn drop(&mut self) {
     421            0 :         self.0.inc_by(self.1);
     422            0 :     }
     423              : }
     424              : 
     425              : /// A Pair of [`IntCounterVec`]s. Like an [`IntGaugeVec`] but will always observe changes
     426              : pub type IntCounterPairVec = GenericCounterPairVec<AtomicU64>;
     427              : 
     428              : /// A Pair of [`IntCounter`]s. Like an [`IntGauge`] but will always observe changes
     429              : pub type IntCounterPair = GenericCounterPair<AtomicU64>;
     430              : 
     431              : /// A guard for [`IntCounterPair`] that will decrement the gauge on drop
     432              : pub type IntCounterPairGuard = GenericCounterPairGuard<AtomicU64>;
     433              : 
     434              : pub trait CounterPairAssoc {
     435              :     const INC_NAME: &'static MetricName;
     436              :     const DEC_NAME: &'static MetricName;
     437              : 
     438              :     const INC_HELP: &'static str;
     439              :     const DEC_HELP: &'static str;
     440              : 
     441              :     type LabelGroupSet: LabelGroupSet;
     442              : }
     443              : 
     444              : pub struct CounterPairVec<A: CounterPairAssoc> {
     445              :     vec: measured::metric::MetricVec<MeasuredCounterPairState, A::LabelGroupSet>,
     446              : }
     447              : 
     448              : impl<A: CounterPairAssoc> Default for CounterPairVec<A>
     449              : where
     450              :     A::LabelGroupSet: Default,
     451              : {
     452          216 :     fn default() -> Self {
     453          216 :         Self {
     454          216 :             vec: Default::default(),
     455          216 :         }
     456          216 :     }
     457              : }
     458              : 
     459              : impl<A: CounterPairAssoc> CounterPairVec<A> {
     460            0 :     pub fn guard(
     461            0 :         &self,
     462            0 :         labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>,
     463            0 :     ) -> MeasuredCounterPairGuard<'_, A> {
     464            0 :         let id = self.vec.with_labels(labels);
     465            0 :         self.vec.get_metric(id).inc.inc();
     466            0 :         MeasuredCounterPairGuard { vec: &self.vec, id }
     467            0 :     }
     468            0 :     pub fn inc(&self, labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>) {
     469            0 :         let id = self.vec.with_labels(labels);
     470            0 :         self.vec.get_metric(id).inc.inc();
     471            0 :     }
     472            0 :     pub fn dec(&self, labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>) {
     473            0 :         let id = self.vec.with_labels(labels);
     474            0 :         self.vec.get_metric(id).dec.inc();
     475            0 :     }
     476            0 :     pub fn remove_metric(
     477            0 :         &self,
     478            0 :         labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>,
     479            0 :     ) -> Option<MeasuredCounterPairState> {
     480            0 :         let id = self.vec.with_labels(labels);
     481            0 :         self.vec.remove_metric(id)
     482            0 :     }
     483              : 
     484            0 :     pub fn sample(&self, labels: <A::LabelGroupSet as LabelGroupSet>::Group<'_>) -> u64 {
     485            0 :         let id = self.vec.with_labels(labels);
     486            0 :         let metric = self.vec.get_metric(id);
     487            0 : 
     488            0 :         let inc = metric.inc.count.load(std::sync::atomic::Ordering::Relaxed);
     489            0 :         let dec = metric.dec.count.load(std::sync::atomic::Ordering::Relaxed);
     490            0 :         inc.saturating_sub(dec)
     491            0 :     }
     492              : }
     493              : 
     494              : impl<T, A> ::measured::metric::group::MetricGroup<T> for CounterPairVec<A>
     495              : where
     496              :     T: ::measured::metric::group::Encoding,
     497              :     A: CounterPairAssoc,
     498              :     ::measured::metric::counter::CounterState: ::measured::metric::MetricEncoding<T>,
     499              : {
     500            0 :     fn collect_group_into(&self, enc: &mut T) -> Result<(), T::Err> {
     501            0 :         // write decrement first to avoid a race condition where inc - dec < 0
     502            0 :         T::write_help(enc, A::DEC_NAME, A::DEC_HELP)?;
     503            0 :         self.vec
     504            0 :             .collect_family_into(A::DEC_NAME, &mut Dec(&mut *enc))?;
     505              : 
     506            0 :         T::write_help(enc, A::INC_NAME, A::INC_HELP)?;
     507            0 :         self.vec
     508            0 :             .collect_family_into(A::INC_NAME, &mut Inc(&mut *enc))?;
     509              : 
     510            0 :         Ok(())
     511            0 :     }
     512              : }
     513              : 
     514              : #[derive(MetricGroup, Default)]
     515              : pub struct MeasuredCounterPairState {
     516              :     pub inc: CounterState,
     517              :     pub dec: CounterState,
     518              : }
     519              : 
     520              : impl measured::metric::MetricType for MeasuredCounterPairState {
     521              :     type Metadata = ();
     522              : }
     523              : 
     524              : pub struct MeasuredCounterPairGuard<'a, A: CounterPairAssoc> {
     525              :     vec: &'a measured::metric::MetricVec<MeasuredCounterPairState, A::LabelGroupSet>,
     526              :     id: measured::metric::LabelId<A::LabelGroupSet>,
     527              : }
     528              : 
     529              : impl<A: CounterPairAssoc> Drop for MeasuredCounterPairGuard<'_, A> {
     530            0 :     fn drop(&mut self) {
     531            0 :         self.vec.get_metric(self.id).dec.inc();
     532            0 :     }
     533              : }
     534              : 
     535              : /// [`MetricEncoding`] for [`MeasuredCounterPairState`] that only writes the inc counter to the inner encoder.
     536              : struct Inc<T>(T);
     537              : /// [`MetricEncoding`] for [`MeasuredCounterPairState`] that only writes the dec counter to the inner encoder.
     538              : struct Dec<T>(T);
     539              : 
     540              : impl<T: Encoding> Encoding for Inc<T> {
     541              :     type Err = T::Err;
     542              : 
     543            0 :     fn write_help(&mut self, name: impl MetricNameEncoder, help: &str) -> Result<(), Self::Err> {
     544            0 :         self.0.write_help(name, help)
     545            0 :     }
     546              : 
     547            0 :     fn write_metric_value(
     548            0 :         &mut self,
     549            0 :         name: impl MetricNameEncoder,
     550            0 :         labels: impl LabelGroup,
     551            0 :         value: MetricValue,
     552            0 :     ) -> Result<(), Self::Err> {
     553            0 :         self.0.write_metric_value(name, labels, value)
     554            0 :     }
     555              : }
     556              : 
     557              : impl<T: Encoding> MetricEncoding<Inc<T>> for MeasuredCounterPairState
     558              : where
     559              :     CounterState: MetricEncoding<T>,
     560              : {
     561            0 :     fn write_type(name: impl MetricNameEncoder, enc: &mut Inc<T>) -> Result<(), T::Err> {
     562            0 :         CounterState::write_type(name, &mut enc.0)
     563            0 :     }
     564            0 :     fn collect_into(
     565            0 :         &self,
     566            0 :         metadata: &(),
     567            0 :         labels: impl LabelGroup,
     568            0 :         name: impl MetricNameEncoder,
     569            0 :         enc: &mut Inc<T>,
     570            0 :     ) -> Result<(), T::Err> {
     571            0 :         self.inc.collect_into(metadata, labels, name, &mut enc.0)
     572            0 :     }
     573              : }
     574              : 
     575              : impl<T: Encoding> Encoding for Dec<T> {
     576              :     type Err = T::Err;
     577              : 
     578            0 :     fn write_help(&mut self, name: impl MetricNameEncoder, help: &str) -> Result<(), Self::Err> {
     579            0 :         self.0.write_help(name, help)
     580            0 :     }
     581              : 
     582            0 :     fn write_metric_value(
     583            0 :         &mut self,
     584            0 :         name: impl MetricNameEncoder,
     585            0 :         labels: impl LabelGroup,
     586            0 :         value: MetricValue,
     587            0 :     ) -> Result<(), Self::Err> {
     588            0 :         self.0.write_metric_value(name, labels, value)
     589            0 :     }
     590              : }
     591              : 
     592              : /// Write the dec counter to the encoder
     593              : impl<T: Encoding> MetricEncoding<Dec<T>> for MeasuredCounterPairState
     594              : where
     595              :     CounterState: MetricEncoding<T>,
     596              : {
     597            0 :     fn write_type(name: impl MetricNameEncoder, enc: &mut Dec<T>) -> Result<(), T::Err> {
     598            0 :         CounterState::write_type(name, &mut enc.0)
     599            0 :     }
     600            0 :     fn collect_into(
     601            0 :         &self,
     602            0 :         metadata: &(),
     603            0 :         labels: impl LabelGroup,
     604            0 :         name: impl MetricNameEncoder,
     605            0 :         enc: &mut Dec<T>,
     606            0 :     ) -> Result<(), T::Err> {
     607            0 :         self.dec.collect_into(metadata, labels, name, &mut enc.0)
     608            0 :     }
     609              : }
        

Generated by: LCOV version 2.1-beta