iroh_metrics/
metrics.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! This module defines the individual metric types.
//!
//! If the `metrics` feature is enabled, they contain metric types based on atomics
//! which can be modified without needing mutable access.
//!
//! If the `metrics` feature is disabled, all operations defined on these types are noops,
//! and the structs don't collect actual data.

use std::any::Any;
#[cfg(feature = "metrics")]
use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};

use serde::{Deserialize, Serialize};

/// The types of metrics supported by this crate.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum MetricType {
    /// A [`Counter`].
    Counter,
    /// A [`Gauge`].
    Gauge,
    /// A [`Histogram`].
    Histogram,
}

impl MetricType {
    /// Returns the given metric type's str representation.
    pub fn as_str(&self) -> &str {
        match self {
            MetricType::Counter => "counter",
            MetricType::Gauge => "gauge",
            MetricType::Histogram => "histogram",
        }
    }
}

/// The value of an individual metric item.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum MetricValue {
    /// A [`Counter`] value.
    Counter(u64),
    /// A [`Gauge`] value.
    Gauge(i64),
}

impl MetricValue {
    /// Returns the value as [`f32`].
    pub fn to_f32(&self) -> f32 {
        match self {
            MetricValue::Counter(value) => *value as f32,
            MetricValue::Gauge(value) => *value as f32,
        }
    }

    /// Returns the [`MetricType`] for this metric value.
    pub fn r#type(&self) -> MetricType {
        match self {
            MetricValue::Counter(_) => MetricType::Counter,
            MetricValue::Gauge(_) => MetricType::Gauge,
        }
    }
}

impl Metric for MetricValue {
    fn r#type(&self) -> MetricType {
        self.r#type()
    }

    fn value(&self) -> MetricValue {
        *self
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Trait for metric items.
pub trait Metric: std::fmt::Debug {
    /// Returns the type of this metric.
    fn r#type(&self) -> MetricType;

    /// Returns the current value of this metric.
    fn value(&self) -> MetricValue;

    /// Casts this metric to [`Any`] for downcasting to concrete types.
    fn as_any(&self) -> &dyn Any;
}

/// OpenMetrics [`Counter`] to measure discrete events.
///
/// Single monotonically increasing value metric.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Counter {
    /// The counter value.
    #[cfg(feature = "metrics")]
    pub(crate) value: AtomicU64,
}

impl Metric for Counter {
    fn value(&self) -> MetricValue {
        MetricValue::Counter(self.get())
    }

    fn r#type(&self) -> MetricType {
        MetricType::Counter
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl Counter {
    /// Constructs a new counter, based on the given `help`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Increases the [`Counter`] by 1, returning the previous value.
    pub fn inc(&self) -> u64 {
        #[cfg(feature = "metrics")]
        {
            self.value.fetch_add(1, Ordering::Relaxed)
        }
        #[cfg(not(feature = "metrics"))]
        0
    }

    /// Increases the [`Counter`] by `u64`, returning the previous value.
    pub fn inc_by(&self, v: u64) -> u64 {
        #[cfg(feature = "metrics")]
        {
            self.value.fetch_add(v, Ordering::Relaxed)
        }
        #[cfg(not(feature = "metrics"))]
        {
            let _ = v;
            0
        }
    }

    /// Sets the [`Counter`] value, returning the previous value.
    ///
    /// Warning: this is not default behavior for a counter that should always be monotonically increasing.
    pub fn set(&self, v: u64) -> u64 {
        #[cfg(feature = "metrics")]
        {
            self.value.swap(v, Ordering::Relaxed)
        }
        #[cfg(not(feature = "metrics"))]
        {
            let _ = v;
            0
        }
    }

    /// Returns the current value of the [`Counter`].
    pub fn get(&self) -> u64 {
        #[cfg(feature = "metrics")]
        {
            self.value.load(Ordering::Relaxed)
        }
        #[cfg(not(feature = "metrics"))]
        0
    }
}

/// OpenMetrics [`Gauge`].
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Gauge {
    /// The gauge value.
    #[cfg(feature = "metrics")]
    pub(crate) value: AtomicI64,
}

/// OpenMetrics [`Histogram`] to track distributions of values.
#[derive(Debug, Serialize, Deserialize)]
pub struct Histogram {
    /// Bucket upper bounds.
    #[cfg(feature = "metrics")]
    pub(crate) buckets: Vec<f64>,
    /// Individual counts for each bucket.
    #[cfg(feature = "metrics")]
    pub(crate) counts: Vec<AtomicU64>,
    /// Sum of all observed values (stored as bits for atomic operations).
    #[cfg(feature = "metrics")]
    pub(crate) sum: AtomicU64,
    /// Total count of observations.
    #[cfg(feature = "metrics")]
    pub(crate) count: AtomicU64,
}

impl Histogram {
    /// Constructs a new histogram with the given bucket boundaries.
    ///
    /// The `buckets` parameter defines the upper bounds for each bucket.
    /// Buckets should be in ascending order. An infinity bucket is automatically
    /// added if not present to ensure all observations are captured.
    #[cfg_attr(not(feature = "metrics"), allow(unused_mut))]
    pub fn new(mut buckets: Vec<f64>) -> Self {
        #[cfg(feature = "metrics")]
        {
            // Ensure there's an infinity bucket to catch all values
            if buckets.is_empty() || !buckets.last().unwrap().is_infinite() {
                buckets.push(f64::INFINITY);
            }

            let counts = buckets.iter().map(|_| AtomicU64::new(0)).collect();
            Self {
                buckets,
                counts,
                sum: AtomicU64::new(0.0_f64.to_bits()),
                count: AtomicU64::new(0),
            }
        }
        #[cfg(not(feature = "metrics"))]
        {
            let _ = buckets;
            Self {}
        }
    }

    /// Records a value in the histogram.
    pub fn observe(&self, value: f64) {
        #[cfg(feature = "metrics")]
        {
            self.count.fetch_add(1, Ordering::Relaxed);

            self.sum
                .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                    let current_sum = f64::from_bits(current);
                    Some((current_sum + value).to_bits())
                })
                .ok();

            for (i, &upper_bound) in self.buckets.iter().enumerate() {
                if value <= upper_bound {
                    self.counts[i].fetch_add(1, Ordering::Relaxed);
                    break;
                }
            }
        }
        #[cfg(not(feature = "metrics"))]
        {
            let _ = value;
        }
    }

    /// Returns the total count of observations.
    pub fn count(&self) -> u64 {
        #[cfg(feature = "metrics")]
        {
            self.count.load(Ordering::Relaxed)
        }
        #[cfg(not(feature = "metrics"))]
        0
    }

    /// Returns the sum of all observed values.
    pub fn sum(&self) -> f64 {
        #[cfg(feature = "metrics")]
        {
            f64::from_bits(self.sum.load(Ordering::Relaxed))
        }
        #[cfg(not(feature = "metrics"))]
        0.0
    }

    /// Returns the bucket counts as a vector of (upper_bound, cumulative_count) pairs.
    ///
    /// The counts are cumulative, meaning each bucket contains the count of all
    /// observations less than or equal to its upper bound.
    pub fn buckets(&self) -> Vec<(f64, u64)> {
        #[cfg(feature = "metrics")]
        {
            let mut cumulative = 0u64;
            self.buckets
                .iter()
                .zip(self.counts.iter())
                .map(|(&bound, count)| {
                    cumulative += count.load(Ordering::Relaxed);
                    (bound, cumulative)
                })
                .collect()
        }
        #[cfg(not(feature = "metrics"))]
        Vec::new()
    }

    /// Calculates the approximate percentile value.
    ///
    /// Returns the bucket upper bound where the percentile falls.
    /// For example, `percentile(0.99)` returns the p99 value.
    pub fn percentile(&self, p: f64) -> f64 {
        #[cfg(feature = "metrics")]
        {
            let total = self.count.load(Ordering::Relaxed);
            if total == 0 {
                return 0.0;
            }

            let target = (total as f64 * p) as u64;
            let mut cumulative = 0u64;

            for (i, count) in self.counts.iter().enumerate() {
                cumulative += count.load(Ordering::Relaxed);
                if cumulative >= target {
                    return self.buckets[i];
                }
            }

            self.buckets.last().copied().unwrap_or(0.0)
        }
        #[cfg(not(feature = "metrics"))]
        {
            let _ = p;
            0.0
        }
    }
}

impl Metric for Histogram {
    fn r#type(&self) -> MetricType {
        MetricType::Histogram
    }

    fn value(&self) -> MetricValue {
        MetricValue::Gauge(self.count() as i64)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl Metric for Gauge {
    fn r#type(&self) -> MetricType {
        MetricType::Gauge
    }

    fn value(&self) -> MetricValue {
        MetricValue::Gauge(self.get())
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl Gauge {
    /// Constructs a new gauge, based on the given `help`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Increases the [`Gauge`] by 1, returning the previous value.
    pub fn inc(&self) -> i64 {
        #[cfg(feature = "metrics")]
        {
            self.value.fetch_add(1, Ordering::Relaxed)
        }
        #[cfg(not(feature = "metrics"))]
        0
    }

    /// Increases the [`Gauge`] by `i64`, returning the previous value.
    pub fn inc_by(&self, v: i64) -> i64 {
        #[cfg(feature = "metrics")]
        {
            self.value.fetch_add(v, Ordering::Relaxed)
        }
        #[cfg(not(feature = "metrics"))]
        {
            let _ = v;
            0
        }
    }

    /// Decreases the [`Gauge`] by 1, returning the previous value.
    pub fn dec(&self) -> i64 {
        #[cfg(feature = "metrics")]
        {
            self.value.fetch_sub(1, Ordering::Relaxed)
        }
        #[cfg(not(feature = "metrics"))]
        0
    }

    /// Decreases the [`Gauge`] by `i64`, returning the previous value.
    pub fn dec_by(&self, v: i64) -> i64 {
        #[cfg(feature = "metrics")]
        {
            self.value.fetch_sub(v, Ordering::Relaxed)
        }
        #[cfg(not(feature = "metrics"))]
        {
            let _ = v;
            0
        }
    }

    /// Sets the [`Gauge`] to `v`, returning the previous value.
    pub fn set(&self, v: i64) -> i64 {
        #[cfg(feature = "metrics")]
        {
            self.value.swap(v, Ordering::Relaxed)
        }
        #[cfg(not(feature = "metrics"))]
        {
            let _ = v;
            0
        }
    }

    /// Returns the [`Gauge`] value.
    pub fn get(&self) -> i64 {
        #[cfg(feature = "metrics")]
        {
            self.value.load(Ordering::Relaxed)
        }
        #[cfg(not(feature = "metrics"))]
        0
    }
}