gemachain_metrics/
lib.rs

1#![allow(clippy::integer_arithmetic)]
2pub mod counter;
3pub mod datapoint;
4mod metrics;
5pub use crate::metrics::{flush, query, set_host_id, set_panic_hook, submit};
6
7use std::sync::Arc;
8
9/// A helper that sends the count of created tokens as a datapoint.
10#[allow(clippy::redundant_allocation)]
11pub struct TokenCounter(Arc<&'static str>);
12
13impl TokenCounter {
14    /// Creates a new counter with the specified metrics `name`.
15    pub fn new(name: &'static str) -> Self {
16        Self(Arc::new(name))
17    }
18
19    /// Creates a new token for this counter. The metric's value will be equal
20    /// to the number of `CounterToken`s.
21    pub fn create_token(&self) -> CounterToken {
22        // new_count = strong_count
23        //    - 1 (in TokenCounter)
24        //    + 1 (token that's being created)
25        datapoint_info!(*self.0, ("count", Arc::strong_count(&self.0), i64));
26        CounterToken(self.0.clone())
27    }
28}
29
30/// A token for `TokenCounter`.
31#[allow(clippy::redundant_allocation)]
32pub struct CounterToken(Arc<&'static str>);
33
34impl Clone for CounterToken {
35    fn clone(&self) -> Self {
36        // new_count = strong_count
37        //    - 1 (in TokenCounter)
38        //    + 1 (token that's being created)
39        datapoint_info!(*self.0, ("count", Arc::strong_count(&self.0), i64));
40        CounterToken(self.0.clone())
41    }
42}
43
44impl Drop for CounterToken {
45    fn drop(&mut self) {
46        // new_count = strong_count
47        //    - 1 (in TokenCounter, if it still exists)
48        //    - 1 (token that's being dropped)
49        datapoint_info!(
50            *self.0,
51            ("count", Arc::strong_count(&self.0).saturating_sub(2), i64)
52        );
53    }
54}
55
56impl Drop for TokenCounter {
57    fn drop(&mut self) {
58        datapoint_info!(
59            *self.0,
60            ("count", Arc::strong_count(&self.0).saturating_sub(2), i64)
61        );
62    }
63}