-
Notifications
You must be signed in to change notification settings - Fork 385
/
array.rs
221 lines (197 loc) · 6.84 KB
/
array.rs
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
use crate::metrics::{AtomicNumber, Descriptor, MetricsError, Number, NumberKind, Result};
use crate::sdk::{
export::metrics::{Count, Distribution, Max, Min, MinMaxSumCount, Points, Quantile, Sum},
metrics::Aggregator,
};
use std::any::Any;
use std::mem;
use std::sync::{Arc, Mutex};
/// Create a new default `ArrayAggregator`
pub fn array() -> ArrayAggregator {
ArrayAggregator::default()
}
/// An aggregator which stores metrics in an array.
#[derive(Debug, Default)]
pub struct ArrayAggregator {
inner: Mutex<Inner>,
}
impl Min for ArrayAggregator {
fn min(&self) -> Result<Number> {
self.inner.lock().map_err(Into::into).and_then(|inner| {
inner
.points
.as_ref()
.map_or(Ok(0u64.into()), |p| p.quantile(0.0))
})
}
}
impl Max for ArrayAggregator {
fn max(&self) -> Result<Number> {
self.inner.lock().map_err(Into::into).and_then(|inner| {
inner
.points
.as_ref()
.map_or(Ok(0u64.into()), |p| p.quantile(1.0))
})
}
}
impl Sum for ArrayAggregator {
fn sum(&self) -> Result<Number> {
self.inner
.lock()
.map_err(Into::into)
.map(|inner| inner.sum.load())
}
}
impl Count for ArrayAggregator {
fn count(&self) -> Result<u64> {
self.inner
.lock()
.map_err(Into::into)
.map(|inner| inner.points.as_ref().map_or(0, |p| p.len() as u64))
}
}
impl MinMaxSumCount for ArrayAggregator {}
impl Quantile for ArrayAggregator {
fn quantile(&self, q: f64) -> Result<Number> {
self.inner.lock().map_err(Into::into).and_then(|inner| {
inner
.points
.as_ref()
.map_or(Ok(0u64.into()), |p| p.quantile(q))
})
}
}
impl Distribution for ArrayAggregator {}
impl Points for ArrayAggregator {
fn points(&self) -> Result<Vec<Number>> {
self.inner
.lock()
.map_err(Into::into)
.map(|inner| inner.points.as_ref().map_or_else(Vec::new, |p| p.0.clone()))
}
}
impl Aggregator for ArrayAggregator {
fn update(&self, number: &Number, descriptor: &Descriptor) -> Result<()> {
self.inner.lock().map_err(Into::into).map(|mut inner| {
if let Some(points) = inner.points.as_mut() {
points.push(number.clone());
} else {
inner.points = Some(PointsData::with_number(number.clone()));
}
inner.sum.fetch_add(descriptor.number_kind(), number)
})
}
fn synchronized_move(
&self,
other: &Arc<dyn Aggregator + Send + Sync>,
descriptor: &Descriptor,
) -> Result<()> {
if let Some(other) = other.as_any().downcast_ref::<Self>() {
other
.inner
.lock()
.map_err(Into::into)
.and_then(|mut other| {
self.inner.lock().map_err(Into::into).map(|mut inner| {
other.points = mem::take(&mut inner.points);
other.sum = mem::replace(
&mut inner.sum,
descriptor.number_kind().zero().to_atomic(),
);
// TODO: This sort should be done lazily, only when quantiles are
// requested. The SDK specification says you can use this aggregator to
// simply list values in the order they were received as an alternative to
// requesting quantile information.
if let Some(points) = &mut other.points {
points.sort(descriptor.number_kind());
}
})
})
} else {
Err(MetricsError::InconsistentAggregator(format!(
"Expected {:?}, got: {:?}",
self, other
)))
}
}
fn merge(&self, other: &(dyn Aggregator + Send + Sync), desc: &Descriptor) -> Result<()> {
if let Some(other) = other.as_any().downcast_ref::<Self>() {
self.inner.lock().map_err(Into::into).and_then(|mut inner| {
other.inner.lock().map_err(From::from).map(|other_inner| {
// Note: Current assumption is that `o` was checkpointed,
// therefore is already sorted. See the TODO above, since
// this is an open question.
inner
.sum
.fetch_add(desc.number_kind(), &other_inner.sum.load());
match (inner.points.as_mut(), other_inner.points.as_ref()) {
(Some(points), Some(other_points)) => {
points.combine(desc.number_kind(), other_points)
}
(None, Some(other_points)) => inner.points = Some(other_points.clone()),
_ => (),
}
})
})
} else {
Err(MetricsError::InconsistentAggregator(format!(
"Expected {:?}, got: {:?}",
self, other
)))
}
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Debug, Default)]
struct Inner {
sum: AtomicNumber,
points: Option<PointsData>,
}
#[derive(Clone, Debug, Default)]
struct PointsData(Vec<Number>);
impl PointsData {
fn with_number(number: Number) -> Self {
PointsData(vec![number])
}
fn len(&self) -> usize {
self.0.len()
}
fn push(&mut self, number: Number) {
self.0.push(number)
}
fn sort(&mut self, kind: &NumberKind) {
match kind {
NumberKind::I64 => self.0.sort_by_key(|a| a.to_u64(kind)),
NumberKind::F64 => self.0.sort_by(|a, b| {
a.to_f64(kind)
.partial_cmp(&b.to_f64(kind))
.expect("nan values should be rejected. This is a bug.")
}),
NumberKind::U64 => self.0.sort_by_key(|a| a.to_u64(kind)),
}
}
fn combine(&mut self, kind: &NumberKind, other: &PointsData) {
self.0.append(&mut other.0.clone());
self.sort(kind)
}
}
impl Quantile for PointsData {
fn quantile(&self, q: f64) -> Result<Number> {
if self.0.is_empty() {
return Err(MetricsError::NoDataCollected);
}
if !(0.0..=1.0).contains(&q) {
return Err(MetricsError::InvalidQuantile);
}
if q == 0.0 || self.0.len() == 1 {
return Ok(self.0[0].clone());
} else if (q - 1.0).abs() < std::f64::EPSILON {
return Ok(self.0[self.0.len() - 1].clone());
}
let position = (self.0.len() as f64 - 1.0) * q;
Ok(self.0[position.ceil() as usize].clone())
}
}