solana_metrics/
lib.rs

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