Skip to main content

rialo_s_metrics/
lib.rs

1// Copyright (c) Subzero Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3// This file is either (a) original to Subzero Labs, Inc. or (b) derived from the Anza codebase and modified by Subzero Labs, Inc.
4
5#![allow(clippy::arithmetic_side_effects)]
6pub mod counter;
7pub mod datapoint;
8pub mod metrics;
9pub mod poh_timing_point;
10use std::sync::{
11    atomic::{AtomicU64, Ordering},
12    Arc,
13};
14
15pub use crate::metrics::{flush, query, set_host_id, set_panic_hook, submit};
16
17// To track an external counter which cannot be reset and is always increasing
18#[derive(Default)]
19pub struct MovingStat {
20    value: AtomicU64,
21}
22
23impl MovingStat {
24    pub fn update_stat(&self, old_value: &MovingStat, new_value: u64) {
25        let old = old_value.value.swap(new_value, Ordering::Acquire);
26        self.value
27            .fetch_add(new_value.saturating_sub(old), Ordering::Release);
28    }
29
30    pub fn load_and_reset(&self) -> u64 {
31        self.value.swap(0, Ordering::Acquire)
32    }
33}
34
35/// A helper that sends the count of created tokens as a datapoint.
36#[allow(clippy::redundant_allocation)]
37pub struct TokenCounter(Arc<&'static str>);
38
39impl TokenCounter {
40    /// Creates a new counter with the specified metrics `name`.
41    pub fn new(name: &'static str) -> Self {
42        Self(Arc::new(name))
43    }
44
45    /// Creates a new token for this counter. The metric's value will be equal
46    /// to the number of `CounterToken`s.
47    pub fn create_token(&self) -> CounterToken {
48        // new_count = strong_count
49        //    - 1 (in TokenCounter)
50        //    + 1 (token that's being created)
51        datapoint_info!(*self.0, ("count", Arc::strong_count(&self.0), i64));
52        CounterToken(self.0.clone())
53    }
54}
55
56/// A token for `TokenCounter`.
57#[allow(clippy::redundant_allocation)]
58pub struct CounterToken(Arc<&'static str>);
59
60impl Clone for CounterToken {
61    fn clone(&self) -> Self {
62        // new_count = strong_count
63        //    - 1 (in TokenCounter)
64        //    + 1 (token that's being created)
65        datapoint_info!(*self.0, ("count", Arc::strong_count(&self.0), i64));
66        CounterToken(self.0.clone())
67    }
68}
69
70impl Drop for CounterToken {
71    fn drop(&mut self) {
72        // new_count = strong_count
73        //    - 1 (in TokenCounter, if it still exists)
74        //    - 1 (token that's being dropped)
75        datapoint_info!(
76            *self.0,
77            ("count", Arc::strong_count(&self.0).saturating_sub(2), i64)
78        );
79    }
80}
81
82impl Drop for TokenCounter {
83    fn drop(&mut self) {
84        datapoint_info!(
85            *self.0,
86            ("count", Arc::strong_count(&self.0).saturating_sub(2), i64)
87        );
88    }
89}