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
use core::*;
use core::Kind::*;
use aggregate::{AggregateSource, ScoreType};
use aggregate::ScoreType::*;
use std::time::Duration;
use schedule::{schedule, CancelHandle};
pub fn publish_every<E, M, S>(
duration: Duration,
source: AggregateSource,
target: S,
export: E,
) -> CancelHandle
where
S: Sink<M> + 'static + Send + Sync,
M: Clone + Send + Sync,
E: Fn(Kind, &str, ScoreType) -> Option<(Kind, Vec<&str>, Value)> + Send + Sync + 'static,
{
schedule(duration, move || publish(&source, &target, &export))
}
pub fn publish<E, M, S>(source: &AggregateSource, target: &S, export: &E)
where
S: Sink<M>,
M: Clone + Send + Sync,
E: Fn(Kind, &str, ScoreType) -> Option<(Kind, Vec<&str>, Value)> + Send + Sync + 'static,
{
let publish_scope_fn = target.new_scope(false);
source.for_each(|metric| {
let snapshot = metric.read_and_reset();
if snapshot.is_empty() {
} else {
for score in snapshot {
if let Some(ex) = export(metric.kind, &metric.name, score) {
let temp_metric = target.new_metric(ex.0, &ex.1.concat(), 1.0);
publish_scope_fn(Scope::Write(&temp_metric, ex.2));
}
}
}
});
source.cleanup();
publish_scope_fn(Scope::Flush)
}
pub fn all_stats(kind: Kind, name: &str, score: ScoreType) -> Option<(Kind, Vec<&str>, Value)> {
match score {
HitCount(hit) => Some((Counter, vec![name, ".hit"], hit)),
SumOfValues(sum) => Some((kind, vec![name, ".sum"], sum)),
AverageValue(avg) => Some((kind, vec![name, ".avg"], avg.round() as Value)),
MaximumValue(max) => Some((Gauge, vec![name, ".max"], max)),
MinimumValue(min) => Some((Gauge, vec![name, ".min"], min)),
MeanRate(rate) => Some((Gauge, vec![name, ".rate"], rate.round() as Value))
}
}
pub fn average(kind: Kind, name: &str, score: ScoreType) -> Option<(Kind, Vec<&str>, Value)> {
match kind {
Marker => {
match score {
HitCount(hit) => Some((Counter, vec![name], hit)),
_ => None,
}
}
_ => {
match score {
AverageValue(avg) => Some((Gauge, vec![name], avg.round() as Value)),
_ => None,
}
}
}
}
pub fn summary(kind: Kind, name: &str, score: ScoreType) -> Option<(Kind, Vec<&str>, Value)> {
match kind {
Marker => {
match score {
HitCount(hit) => Some((Counter, vec![name], hit)),
_ => None,
}
}
Counter | Timer => {
match score {
SumOfValues(sum) => Some((kind, vec![name], sum)),
_ => None,
}
}
Gauge => {
match score {
AverageValue(avg) => Some((Gauge, vec![name], avg.round() as Value)),
_ => None,
}
}
}
}