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
use std::{cell::RefCell, collections::HashMap};

use crate::{
    dispatcher::root_id,
    hostcalls::{self, MetricType},
    log_concern, Status,
};

#[derive(Default)]
pub struct MetricsInfo {
    counters: HashMap<String, u32>,
    gauges: HashMap<String, u32>,
    histograms: HashMap<String, u32>,
}

thread_local! {
    static METRICS: RefCell<HashMap<u32, MetricsInfo>> = RefCell::default();
}

/// Envoy counter metric handle
#[derive(Clone, Copy, Debug)]
pub struct Counter(u32);

/// Const wrapper for [`Counter`]
pub struct ConstCounter {
    name: &'static str,
}

impl ConstCounter {
    /// Const wrapper for [`Counter::define`]
    pub const fn define(name: &'static str) -> Self {
        Self { name }
    }

    pub fn get(&self) -> Counter {
        Counter::define(self.name)
    }
}

impl Counter {
    /// Defines a new counter, reusing an old handle if it already exists. It is safe to call this multiple times with the same name.
    pub fn define(name: impl AsRef<str>) -> Self {
        METRICS.with_borrow_mut(|metrics| {
            let metrics = metrics.entry(root_id()).or_default();
            if let Some(counter) = metrics.counters.get(name.as_ref()) {
                return Self(*counter);
            }
            let out = log_concern(
                "define-metric",
                hostcalls::define_metric(MetricType::Counter, name.as_ref()),
            );
            metrics.counters.insert(name.as_ref().to_string(), out);
            Self(out)
        })
    }

    /// Retrieves the current metric value
    pub fn get(&self) -> Result<u64, Status> {
        hostcalls::get_metric(self.0)
    }

    /// Records an absolute count of this metric
    pub fn record(&self, value: u64) {
        log_concern("record-metric", hostcalls::record_metric(self.0, value));
    }

    /// Increments the count of this metric by `offset`
    pub fn increment(&self, offset: i64) {
        log_concern(
            "increment-metric",
            hostcalls::increment_metric(self.0, offset),
        );
    }
}

/// Envoy gauge metric handle
#[derive(Clone, Copy, Debug)]
pub struct Gauge(u32);

/// Const wrapper for [`Gauge`]
pub struct ConstGauge {
    name: &'static str,
}

impl ConstGauge {
    /// Const wrapper for [`Gauge::define`]
    pub const fn define(name: &'static str) -> Self {
        Self { name }
    }

    pub fn get(&self) -> Gauge {
        Gauge::define(self.name)
    }
}

impl Gauge {
    /// Defines a new gauge, reusing an old handle if it already exists. It is safe to call this multiple times with the same name.
    pub fn define(name: impl AsRef<str>) -> Self {
        METRICS.with_borrow_mut(|metrics| {
            let metrics = metrics.entry(root_id()).or_default();
            if let Some(gauge) = metrics.gauges.get(name.as_ref()) {
                return Self(*gauge);
            }
            let out = log_concern(
                "define-metric",
                hostcalls::define_metric(MetricType::Gauge, name.as_ref()),
            );
            metrics.gauges.insert(name.as_ref().to_string(), out);
            Self(out)
        })
    }

    /// Retrieves the current metric value
    pub fn get(&self) -> Result<u64, Status> {
        hostcalls::get_metric(self.0)
    }

    /// Records an absolute count of this metric
    pub fn record(&self, value: u64) {
        log_concern("record-metric", hostcalls::record_metric(self.0, value));
    }

    /// Increments the count of this metric by `offset`
    pub fn increment(&self, offset: i64) {
        log_concern(
            "increment-metric",
            hostcalls::increment_metric(self.0, offset),
        );
    }
}

/// Envoy histogram metric handle
#[derive(Clone, Copy, Debug)]
pub struct Histogram(u32);

/// Const wrapper for [`Histogram`]
pub struct ConstHistogram {
    name: &'static str,
}

impl ConstHistogram {
    /// Const wrapper for [`Histogram::define`]
    pub const fn define(name: &'static str) -> Self {
        Self { name }
    }

    pub fn get(&self) -> Histogram {
        Histogram::define(self.name)
    }
}

impl Histogram {
    /// Defines a new histogram, reusing an old handle if it already exists. It is safe to call this multiple times with the same name.
    pub fn define(name: impl AsRef<str>) -> Self {
        METRICS.with_borrow_mut(|metrics| {
            let metrics = metrics.entry(root_id()).or_default();
            if let Some(histogram) = metrics.histograms.get(name.as_ref()) {
                return Self(*histogram);
            }
            let out = log_concern(
                "define-metric",
                hostcalls::define_metric(MetricType::Histogram, name.as_ref()),
            );
            metrics.histograms.insert(name.as_ref().to_string(), out);
            Self(out)
        })
    }

    /// Records a new item for this histogram
    pub fn record(&self, value: u64) {
        log_concern("record-metric", hostcalls::record_metric(self.0, value));
    }
}