commonware_runtime/telemetry/metrics/status.rs
1//! Recording metrics with a status.
2
3use prometheus_client::{
4 encoding::{EncodeLabelSet, EncodeLabelValue},
5 metrics::{counter::Counter as DefaultCounter, family::Family},
6};
7
8/// Metric label that indicates status.
9#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
10pub struct Label {
11 /// The value of the label.
12 status: Status,
13}
14
15/// Possible values for the status label.
16#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, EncodeLabelValue)]
17pub enum Status {
18 /// Processed successfully.
19 Success,
20 /// Processing failed.
21 Failure,
22 /// Input was malformed or invalid in some way. Indicates a client error.
23 Invalid,
24 /// Input was valid, but intentionally not processed.
25 /// For example due to a rate limit, being a duplicate, etc.
26 Dropped,
27 /// Processing returned no result before some deadline.
28 Timeout,
29}
30
31/// A counter metric with a status label.
32pub type Counter = Family<Label, DefaultCounter>;
33
34/// Trait providing convenience methods for `Counter`.
35pub trait CounterExt {
36 fn guard(&self, status: Status) -> CounterGuard;
37 fn inc(&self, status: Status);
38}
39
40impl CounterExt for Counter {
41 /// Create a new CounterGuard with a given status.
42 fn guard(&self, status: Status) -> CounterGuard {
43 CounterGuard {
44 metric: self.clone(),
45 status,
46 }
47 }
48
49 /// Increment the metric with a given status.
50 fn inc(&self, status: Status) {
51 self.get_or_create(&Label { status }).inc();
52 }
53}
54
55/// Increments a `Counter` metric when dropped.
56///
57/// Can be used to ensure that counters are incremented regardless of the control flow. For example,
58/// if a function returns early, the metric will still be incremented.
59pub struct CounterGuard {
60 /// The metric to increment.
61 metric: Counter,
62
63 /// The status at which the metric is set to be incremented.
64 status: Status,
65}
66
67impl CounterGuard {
68 /// Modify the status at which the metric will be incremented.
69 pub fn set(&mut self, status: Status) {
70 self.status = status;
71 }
72}
73
74impl Drop for CounterGuard {
75 fn drop(&mut self) {
76 self.metric.inc(self.status);
77 }
78}