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
use std::collections::HashMap;
use std::sync::atomic::Ordering;
use std::sync::Arc;

use crate::common::Snapshot;
use crate::distribution::{Distribution, DistributionBuilder};
use crate::formatting::{key_to_parts, write_metric_line};
use crate::registry::GenerationalAtomicStorage;

use metrics::{Counter, Gauge, Histogram, Key, KeyName, Recorder, SharedString, Unit};
use metrics_util::registry::{Recency, Registry};

use indexmap::IndexMap;
use quanta::Instant;

pub(crate) struct Inner {
    pub prefix: Option<String>,
    pub registry: Registry<Key, GenerationalAtomicStorage>,
    pub recency: Recency<Key>,
    pub distribution_builder: DistributionBuilder,
    pub global_tags: IndexMap<String, String>,
}

type Distributions = HashMap<String, IndexMap<Vec<String>, Distribution>>;

impl Inner {
    fn get_recent_metrics(&self) -> Snapshot {
        let mut counters = HashMap::new();
        let counter_handles = self.registry.get_counter_handles();
        for (key, counter) in counter_handles {
            let gen = counter.get_generation();
            if !self.recency.should_store_counter(&key, gen, &self.registry) {
                continue;
            }
            let (name, labels) = key_to_parts(&key, Some(&self.global_tags));
            let value = counter.get_inner().swap(0, Ordering::Acquire);
            let entry = counters
                .entry(name)
                .or_insert_with(HashMap::new)
                .entry(labels)
                .or_insert(0);
            *entry = value;
        }

        let mut gauges = HashMap::new();
        let gauge_handles = self.registry.get_gauge_handles();
        for (key, gauge) in gauge_handles {
            let gen = gauge.get_generation();
            if !self.recency.should_store_gauge(&key, gen, &self.registry) {
                continue;
            }

            let (name, labels) = key_to_parts(&key, Some(&self.global_tags));
            let value = f64::from_bits(gauge.get_inner().swap(0, Ordering::Acquire));
            let entry = gauges
                .entry(name)
                .or_insert_with(HashMap::new)
                .entry(labels)
                .or_insert(0.0);
            *entry = value;
        }

        let histogram_handles = self.registry.get_histogram_handles();
        let mut distributions: Distributions = HashMap::new();
        for (key, histogram) in histogram_handles {
            let gen = histogram.get_generation();
            if !self
                .recency
                .should_store_histogram(&key, gen, &self.registry)
            {
                continue;
            }

            let (name, labels) = key_to_parts(&key, Some(&self.global_tags));

            let entry = distributions
                .entry(name.clone())
                .or_insert_with(IndexMap::new)
                .entry(labels)
                .or_insert_with(|| self.distribution_builder.get_distribution(name.as_str()));

            histogram
                .get_inner()
                .clear_with(|samples| entry.record_samples(samples));
        }

        Snapshot {
            counters,
            gauges,
            distributions,
        }
    }

    fn render(&self) -> String {
        let Snapshot {
            mut counters,
            mut distributions,
            mut gauges,
        } = self.get_recent_metrics();

        let mut output = String::new();

        for (name, mut by_labels) in counters.drain() {
            let mut wrote = false;
            for (labels, value) in by_labels.drain() {
                if value == 0 {
                    continue;
                }
                wrote = true;
                write_metric_line::<&str, u64>(
                    &mut output,
                    self.prefix.as_deref(),
                    &name,
                    None,
                    "c",
                    &labels,
                    None,
                    value,
                    None,
                    None,
                );
            }
            if wrote {
                output.push('\n');
            }
        }

        for (name, mut by_labels) in gauges.drain() {
            let mut wrote = false;
            for (labels, value) in by_labels.drain() {
                if value == 0.0 {
                    continue;
                }
                wrote = true;
                write_metric_line::<&str, f64>(
                    &mut output,
                    self.prefix.as_deref(),
                    &name,
                    None,
                    "g",
                    &labels,
                    None,
                    value,
                    None,
                    None,
                );
            }
            if wrote {
                output.push('\n');
            }
        }

        for (name, mut by_labels) in distributions.drain() {
            let mut wrote = false;
            for (labels, distribution) in by_labels.drain(..) {
                let (sum, count) = match distribution {
                    Distribution::Summary(summary, quantiles, sum) => {
                        let count = summary.count();
                        if count == 0 {
                            continue;
                        }
                        wrote = true;
                        let snapshot = summary.snapshot(Instant::now());
                        for quantile in quantiles.iter() {
                            let value = snapshot.quantile(quantile.value()).unwrap_or(0.0);
                            let qv = quantile.value().to_string();
                            let quantile_name = if qv == "0" {
                                "min"
                            } else if qv == "0.5" {
                                "median"
                            } else if qv == "1" {
                                "max"
                            } else {
                                qv.as_str()
                            };

                            write_metric_line(
                                &mut output,
                                self.prefix.as_deref(),
                                &name,
                                None,
                                "g",
                                &labels,
                                Some(quantile_name),
                                value,
                                None,
                                None,
                            );
                        }

                        (sum, count as u64)
                    }
                    Distribution::Histogram(histogram) => {
                        let count = histogram.count();
                        if count == 0 {
                            continue;
                        }
                        wrote = true;
                        for (le, count) in histogram.buckets() {
                            write_metric_line(
                                &mut output,
                                self.prefix.as_deref(),
                                &name,
                                None,
                                "g",
                                &labels,
                                Some(le),
                                count,
                                None,
                                None,
                            );
                        }
                        write_metric_line(
                            &mut output,
                            self.prefix.as_deref(),
                            &name,
                            None,
                            "g",
                            &labels,
                            Some("+Inf"),
                            histogram.count(),
                            None,
                            None,
                        );

                        (histogram.sum(), count)
                    }
                };

                write_metric_line::<&str, f64>(
                    &mut output,
                    self.prefix.as_deref(),
                    &name,
                    Some("avg"),
                    "g",
                    &labels,
                    None,
                    sum / count as f64,
                    None,
                    None,
                );
                write_metric_line::<&str, f64>(
                    &mut output,
                    self.prefix.as_deref(),
                    &name,
                    Some("sum"),
                    "g",
                    &labels,
                    None,
                    sum,
                    None,
                    None,
                );
                write_metric_line::<&str, u64>(
                    &mut output,
                    self.prefix.as_deref(),
                    &name,
                    Some("count"),
                    "g",
                    &labels,
                    None,
                    count,
                    None,
                    None,
                );
            }
            if wrote {
                output.push('\n');
            }
        }

        output
    }
}

pub struct StatsdRecorder {
    inner: Arc<Inner>,
}

impl StatsdRecorder {
    pub fn handle(&self) -> StatsdHandle {
        StatsdHandle {
            inner: self.inner.clone(),
        }
    }
}

impl From<Inner> for StatsdRecorder {
    fn from(inner: Inner) -> Self {
        StatsdRecorder {
            inner: Arc::new(inner),
        }
    }
}

impl Recorder for StatsdRecorder {
    fn describe_counter(&self, _k: KeyName, _u: Option<Unit>, _d: SharedString) {}
    fn describe_gauge(&self, _k: KeyName, _u: Option<Unit>, _d: SharedString) {}
    fn describe_histogram(&self, _k: KeyName, _u: Option<Unit>, _d: SharedString) {}

    fn register_counter(&self, key: &Key) -> Counter {
        self.inner
            .registry
            .get_or_create_counter(key, |c| c.clone().into())
    }

    fn register_gauge(&self, key: &Key) -> Gauge {
        self.inner
            .registry
            .get_or_create_gauge(key, |c| c.clone().into())
    }

    fn register_histogram(&self, key: &Key) -> Histogram {
        self.inner
            .registry
            .get_or_create_histogram(key, |c| c.clone().into())
    }
}

/// Handle for accessing metrics stored via [`StatsdRecorder`].
///
/// In certain scenarios, it may be necessary to directly handle requests that would otherwise be
/// handled directly by the HTTP listener, or push gateway background task.  [`StatsdHandle`]
/// allows rendering a snapshot of the current metrics stored by an installed [`StatsdRecorder`]
/// as a payload conforming to the Statsd exposition format.
#[derive(Clone)]
pub struct StatsdHandle {
    inner: Arc<Inner>,
}

impl StatsdHandle {
    /// Takes a snapshot of the metrics held by the recorder and generates a payload conforming to
    /// the Statsd exposition format.
    pub fn render(&self) -> String {
        self.inner.render()
    }
}