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
use std;
use std::fmt;
use std::iter;
use std::sync::{Arc, Weak};
use std::time::Instant;
use {Collect, ErrorKind, Registry, Result};
use default_registry;
use atomic::{AtomicF64, AtomicU64};
use bucket::{Bucket, CumulativeBuckets};
use label::{Label, Labels, LabelsMut};
use metric::{Metric, MetricName, MetricValue};
use timestamp::{self, Timestamp, TimestampMut};
#[derive(Debug, Clone)]
pub struct Histogram(Arc<Inner>);
impl Histogram {
pub fn new(name: &str) -> Result<Self> {
HistogramBuilder::new(name).finish()
}
pub fn metric_name(&self) -> &MetricName {
&self.0.bucket_name
}
pub fn help(&self) -> Option<&str> {
self.0.help.as_ref().map(|h| h.as_ref())
}
pub fn labels(&self) -> &Labels {
&self.0.labels
}
pub fn labels_mut(&mut self) -> LabelsMut {
LabelsMut::new(&self.0.labels, Some("le"))
}
pub fn timestamp(&self) -> &Timestamp {
&self.0.timestamp
}
pub fn timestamp_mut(&mut self) -> TimestampMut {
TimestampMut::new(&self.0.timestamp)
}
pub fn buckets(&self) -> &[Bucket] {
&self.0.buckets
}
pub fn cumulative_buckets(&self) -> CumulativeBuckets {
CumulativeBuckets::new(&self.0.buckets)
}
#[inline]
pub fn count(&self) -> u64 {
self.0.buckets.iter().map(|b| b.count()).sum()
}
#[inline]
pub fn sum(&self) -> f64 {
self.0.sum.get()
}
#[inline]
pub fn observe(&self, value: f64) {
assert!(!value.is_nan());
let i = self.0
.buckets
.binary_search_by(|b| b.upper_bound().partial_cmp(&value).expect("Never fails"))
.unwrap_or_else(|i| i);
self.0.buckets.get(i).map(|b| b.increment());
self.0.sum.update(|v| v + value);
}
#[inline]
pub fn time<F, T>(&self, f: F) -> T
where
F: FnOnce() -> T,
{
let start = Instant::now();
let result = f();
let elapsed = timestamp::duration_to_seconds(start.elapsed());
self.observe(elapsed);
result
}
pub fn collector(&self) -> HistogramCollector {
HistogramCollector(Arc::downgrade(&self.0))
}
}
impl fmt::Display for Histogram {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let labels = if !self.labels().is_empty() {
self.labels().to_string()
} else {
"".to_string()
};
let timestamp = if let Some(t) = self.timestamp().get() {
format!(" {}", t)
} else {
"".to_string()
};
for bucket in self.cumulative_buckets() {
write!(
f,
"{}_bucket{{le=\"{}\"",
self.metric_name(),
MetricValue(bucket.upper_bound())
)?;
for label in self.labels().iter() {
write!(f, ",{}={:?}", label.name(), label.value())?;
}
writeln!(f, "}} {}{}", bucket.cumulative_count(), timestamp)?;
}
writeln!(
f,
"{}_sum{} {}{}",
self.metric_name(),
labels,
MetricValue(self.sum()),
timestamp
)?;
write!(
f,
"{}_count{} {}{}",
self.metric_name(),
labels,
self.count(),
timestamp
)?;
Ok(())
}
}
#[derive(Debug)]
pub struct HistogramBuilder {
namespace: Option<String>,
subsystem: Option<String>,
name: String,
help: Option<String>,
labels: Vec<(String, String)>,
bucket_upper_bounds: Vec<f64>,
registries: Vec<Registry>,
}
impl HistogramBuilder {
pub fn new(name: &str) -> Self {
HistogramBuilder {
namespace: None,
subsystem: None,
name: name.to_string(),
help: None,
labels: Vec::new(),
bucket_upper_bounds: vec![std::f64::INFINITY],
registries: Vec::new(),
}
}
pub fn with_linear_buckets(name: &str, start: f64, width: f64, count: usize) -> Self {
let mut this = Self::new(name);
for x in (0..count).map(|i| start + i as f64 * width) {
this.bucket(x);
}
this
}
pub fn with_exponential_buckets(name: &str, start: f64, factor: f64, count: usize) -> Self {
let mut this = Self::new(name);
for x in (0..count).map(|i| start + factor.powi(i as i32)) {
this.bucket(x);
}
this
}
pub fn namespace(&mut self, namespace: &str) -> &mut Self {
self.namespace = Some(namespace.to_string());
self
}
pub fn subsystem(&mut self, subsystem: &str) -> &mut Self {
self.subsystem = Some(subsystem.to_string());
self
}
pub fn help(&mut self, help: &str) -> &mut Self {
self.help = Some(help.to_string());
self
}
pub fn label(&mut self, name: &str, value: &str) -> &mut Self {
self.labels.retain(|l| l.0 != name);
self.labels.push((name.to_string(), value.to_string()));
self.labels.sort();
self
}
pub fn registry(&mut self, registry: Registry) -> &mut Self {
self.registries.push(registry);
self
}
pub fn default_registry(&mut self) -> &mut Self {
self.registry(default_registry())
}
pub fn bucket(&mut self, upper_bound: f64) -> &mut Self {
self.bucket_upper_bounds.push(upper_bound);
self
}
pub fn finish(&self) -> Result<Histogram> {
let namespace = self.namespace.as_ref().map(AsRef::as_ref);
let subsystem = self.subsystem.as_ref().map(AsRef::as_ref);
let bucket_name = track!(MetricName::new(namespace, subsystem, &self.name))?;
let labels = track!(
self.labels
.iter()
.map(|&(ref name, ref value)| {
track_assert_ne!(name, "le", ErrorKind::InvalidInput);
track!(Label::new(name, value))
})
.collect::<Result<_>>()
)?;
let mut buckets = track!(
self.bucket_upper_bounds
.iter()
.map(|upper_bound| track!(Bucket::new(*upper_bound)))
.collect::<Result<Vec<_>>>()
)?;
buckets.sort_by(|a, b| {
a.upper_bound()
.partial_cmp(&b.upper_bound())
.expect("Never fails")
});
let inner = Inner {
bucket_name,
labels: Labels::new(labels),
help: self.help.clone(),
timestamp: Timestamp::new(),
buckets,
count: AtomicU64::new(0),
sum: AtomicF64::new(0.0),
};
let histogram = Histogram(Arc::new(inner));
for r in &self.registries {
r.register(histogram.collector());
}
Ok(histogram)
}
}
#[derive(Debug, Clone)]
pub struct HistogramCollector(Weak<Inner>);
impl Collect for HistogramCollector {
type Metrics = iter::Once<Metric>;
fn collect(&mut self) -> Option<Self::Metrics> {
self.0
.upgrade()
.map(|inner| iter::once(Metric::Histogram(Histogram(inner))))
}
}
#[derive(Debug)]
struct Inner {
bucket_name: MetricName,
labels: Labels,
help: Option<String>,
timestamp: Timestamp,
buckets: Vec<Bucket>,
count: AtomicU64,
sum: AtomicF64,
}
#[cfg(test)]
mod test {
use std::f64::INFINITY;
use super::*;
#[test]
fn it_works() {
let histogram =
track_try_unwrap!(HistogramBuilder::with_linear_buckets("foo", 0.0, 10.0, 5).finish());
assert_eq!(histogram.metric_name().to_string(), "foo");
histogram.observe(7.0);
histogram.observe(12.0);
histogram.observe(50.1);
histogram.observe(10.0);
assert_eq!(
histogram
.cumulative_buckets()
.map(|b| (b.upper_bound(), b.cumulative_count()))
.collect::<Vec<_>>(),
[
(0.0, 0),
(10.0, 2),
(20.0, 3),
(30.0, 3),
(40.0, 3),
(INFINITY, 4),
]
);
assert_eq!(histogram.count(), 4);
assert_eq!(histogram.sum(), 79.1);
assert_eq!(
histogram.to_string(),
r#"foo_bucket{le="0"} 0
foo_bucket{le="10"} 2
foo_bucket{le="20"} 3
foo_bucket{le="30"} 3
foo_bucket{le="40"} 3
foo_bucket{le="+Inf"} 4
foo_sum 79.1
foo_count 4"#
);
}
}