-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathaggregation.rs
2625 lines (2344 loc) · 86 KB
/
aggregation.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
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{btree_map, hash_map::Entry, BTreeMap, BTreeSet, HashMap};
use std::fmt;
use std::iter::FromIterator;
use std::mem;
use std::time::{Duration, Instant};
use actix::prelude::*;
use failure::Fail;
use float_ord::FloatOrd;
use hash32::{FnvHasher, Hasher};
use serde::{Deserialize, Serialize};
use relay_common::{MonotonicResult, ProjectKey, UnixTimestamp};
use relay_system::{Controller, Shutdown};
use crate::statsd::{MetricCounters, MetricGauges, MetricHistograms, MetricSets, MetricTimers};
use crate::{
protocol, CounterType, DistributionType, GaugeType, Metric, MetricType, MetricUnit,
MetricValue, SetType,
};
/// Interval for the flush cycle of the [`Aggregator`].
const FLUSH_INTERVAL: Duration = Duration::from_millis(100);
/// A snapshot of values within a [`Bucket`].
#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
pub struct GaugeValue {
/// The maximum value reported in the bucket.
pub max: GaugeType,
/// The minimum value reported in the bucket.
pub min: GaugeType,
/// The sum of all values reported in the bucket.
pub sum: GaugeType,
/// The last value reported in the bucket.
///
/// This aggregation is not commutative.
pub last: GaugeType,
/// The number of times this bucket was updated with a new value.
pub count: u64,
}
impl GaugeValue {
/// Creates a gauge snapshot from a single value.
pub fn single(value: GaugeType) -> Self {
Self {
max: value,
min: value,
sum: value,
last: value,
count: 1,
}
}
/// Inserts a new value into the gauge.
pub fn insert(&mut self, value: GaugeType) {
self.max = self.max.max(value);
self.min = self.min.min(value);
self.sum += value;
self.last = value;
self.count += 1;
}
/// Merges two gauge snapshots.
pub fn merge(&mut self, other: Self) {
self.max = self.max.max(other.max);
self.min = self.min.min(other.min);
self.sum += other.sum;
self.last = other.last;
self.count += other.count;
}
/// Returns the average of all values reported in this bucket.
pub fn avg(&self) -> GaugeType {
if self.count > 0 {
self.sum / (self.count as GaugeType)
} else {
0.0
}
}
}
/// Type for counting duplicates in distributions.
type Count = u32;
/// A distribution of values within a [`Bucket`].
///
/// Distributions store a histogram of values. It allows to iterate both the distribution with
/// [`iter`](Self::iter) and individual values with [`iter_values`](Self::iter_values).
///
/// Based on individual reported values, distributions allow to query the maximum, minimum, or
/// average of the reported values, as well as statistical quantiles.
///
/// # Example
///
/// ```rust
/// use relay_metrics::dist;
///
/// let mut dist = dist![1.0, 1.0, 1.0, 2.0];
/// dist.insert(5.0);
/// dist.insert_multi(3.0, 7);
/// ```
///
/// Logically, this distribution is equivalent to this visualization:
///
/// ```plain
/// value | count
/// 1.0 | ***
/// 2.0 | *
/// 3.0 | *******
/// 4.0 |
/// 5.0 | *
/// ```
///
/// # Serialization
///
/// Distributions serialize as sorted lists of floating point values. The list contains one entry
/// for each value in the distribution, including duplicates.
#[derive(Clone, Default, PartialEq)]
pub struct DistributionValue {
values: BTreeMap<FloatOrd<DistributionType>, Count>,
length: Count,
}
impl DistributionValue {
/// Makes a new, empty `DistributionValue`.
///
/// Does not allocate anything on its own.
pub fn new() -> Self {
Self::default()
}
/// Returns the number of values in the map.
///
/// # Examples
///
/// ```
/// use relay_metrics::DistributionValue;
///
/// let mut dist = DistributionValue::new();
/// assert_eq!(dist.len(), 0);
/// dist.insert(1.0);
/// dist.insert(1.0);
/// assert_eq!(dist.len(), 2);
/// ```
pub fn len(&self) -> Count {
self.length
}
/// Returns the size of the map used to store the distribution.
///
/// This is only relevant for internal metrics.
fn internal_size(&self) -> usize {
self.values.len()
}
/// Returns `true` if the map contains no elements.
pub fn is_empty(&self) -> bool {
self.length == 0
}
/// Adds a value to the distribution.
///
/// Returns the number this value occurs in the distribution after inserting.
///
/// # Examples
///
/// ```
/// use relay_metrics::DistributionValue;
///
/// let mut dist = DistributionValue::new();
/// assert_eq!(dist.insert(1.0), 1);
/// assert_eq!(dist.insert(1.0), 2);
/// assert_eq!(dist.insert(2.0), 1);
/// ```
pub fn insert(&mut self, value: DistributionType) -> Count {
self.insert_multi(value, 1)
}
/// Adds a value multiple times to the distribution.
///
/// Returns the number this value occurs in the distribution after inserting.
///
/// # Examples
///
/// ```
/// use relay_metrics::DistributionValue;
///
/// let mut dist = DistributionValue::new();
/// assert_eq!(dist.insert_multi(1.0, 2), 2);
/// assert_eq!(dist.insert_multi(1.0, 3), 5);
/// ```
pub fn insert_multi(&mut self, value: DistributionType, count: Count) -> Count {
self.length += count;
if count == 0 {
return 0;
}
*self
.values
.entry(FloatOrd(value))
.and_modify(|c| *c += count)
.or_insert(count)
}
/// Returns `true` if the set contains a value.
///
/// # Examples
///
/// ```
/// use relay_metrics::dist;
///
/// let dist = dist![1.0];
///
/// assert_eq!(dist.contains(1.0), true);
/// assert_eq!(dist.contains(2.0), false);
/// ```
pub fn contains(&self, value: impl std::borrow::Borrow<DistributionType>) -> bool {
self.values.contains_key(&FloatOrd(*value.borrow()))
}
/// Returns how often the given value occurs in the distribution.
///
/// # Examples
///
/// ```
/// use relay_metrics::dist;
///
/// let dist = dist![1.0, 1.0];
///
/// assert_eq!(dist.get(1.0), 2);
/// assert_eq!(dist.get(2.0), 0);
/// ```
pub fn get(&self, value: impl std::borrow::Borrow<DistributionType>) -> Count {
let value = &FloatOrd(*value.borrow());
self.values.get(value).copied().unwrap_or(0)
}
/// Gets an iterator that visits unique values in the `DistributionValue` in ascending order.
///
/// The iterator yields pairs of values and their count in the distribution.
///
/// # Examples
///
/// ```
/// use relay_metrics::dist;
///
/// let dist = dist![2.0, 1.0, 3.0, 2.0];
///
/// let mut iter = dist.iter();
/// assert_eq!(iter.next(), Some((1.0, 1)));
/// assert_eq!(iter.next(), Some((2.0, 2)));
/// assert_eq!(iter.next(), Some((3.0, 1)));
/// assert_eq!(iter.next(), None);
/// ```
pub fn iter(&self) -> DistributionIter<'_> {
DistributionIter {
inner: self.values.iter(),
}
}
/// Gets an iterator that visits the values in the `DistributionValue` in ascending order.
///
/// # Examples
///
/// ```
/// use relay_metrics::dist;
///
/// let dist = dist![2.0, 1.0, 3.0, 2.0];
///
/// let mut iter = dist.iter_values();
/// assert_eq!(iter.next(), Some(1.0));
/// assert_eq!(iter.next(), Some(2.0));
/// assert_eq!(iter.next(), Some(2.0));
/// assert_eq!(iter.next(), Some(3.0));
/// assert_eq!(iter.next(), None);
/// ```
pub fn iter_values(&self) -> DistributionValuesIter<'_> {
DistributionValuesIter {
inner: self.iter(),
current: 0f64,
remaining: 0,
total: self.length,
}
}
}
impl<'a> IntoIterator for &'a DistributionValue {
type Item = (DistributionType, Count);
type IntoIter = DistributionIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl fmt::Debug for DistributionValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.iter()).finish()
}
}
impl Extend<f64> for DistributionValue {
fn extend<T: IntoIterator<Item = f64>>(&mut self, iter: T) {
for value in iter.into_iter() {
self.insert(value);
}
}
}
impl Extend<(f64, Count)> for DistributionValue {
fn extend<T: IntoIterator<Item = (DistributionType, Count)>>(&mut self, iter: T) {
for (value, count) in iter.into_iter() {
self.insert_multi(value, count);
}
}
}
impl Serialize for DistributionValue {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_seq(self.iter_values())
}
}
impl<'de> Deserialize<'de> for DistributionValue {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct DistributionVisitor;
impl<'d> serde::de::Visitor<'d> for DistributionVisitor {
type Value = DistributionValue;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a list of floating point values")
}
fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'d>,
{
let mut distribution = DistributionValue::new();
while let Some(value) = seq.next_element()? {
distribution.insert(value);
}
Ok(distribution)
}
}
deserializer.deserialize_seq(DistributionVisitor)
}
}
/// An iterator over distribution entries in a [`DistributionValue`].
///
/// This struct is created by the [`iter`](DistributionValue::iter) method on
/// `DistributionValue`. See its documentation for more.
#[derive(Clone)]
pub struct DistributionIter<'a> {
inner: btree_map::Iter<'a, FloatOrd<f64>, Count>,
}
impl Iterator for DistributionIter<'_> {
type Item = (DistributionType, Count);
fn next(&mut self) -> Option<Self::Item> {
let (value, count) = self.inner.next()?;
Some((value.0, *count))
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl ExactSizeIterator for DistributionIter<'_> {}
impl fmt::Debug for DistributionIter<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
/// An iterator over all individual values in a [`DistributionValue`].
///
/// This struct is created by the [`iter_values`](DistributionValue::iter_values) method on
/// `DistributionValue`. See its documentation for more.
#[derive(Clone)]
pub struct DistributionValuesIter<'a> {
inner: DistributionIter<'a>,
current: DistributionType,
remaining: Count,
total: Count,
}
impl Iterator for DistributionValuesIter<'_> {
type Item = DistributionType;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining > 0 {
self.remaining -= 1;
self.total -= 1;
return Some(self.current);
}
let (value, count) = self.inner.next()?;
self.current = value;
self.remaining = count - 1;
self.total -= 1;
Some(self.current)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.total as usize;
(len, Some(len))
}
}
impl ExactSizeIterator for DistributionValuesIter<'_> {}
impl fmt::Debug for DistributionValuesIter<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.clone()).finish()
}
}
/// Creates a [`DistributionValue`] containing the given arguments.
///
/// `dist!` allows `DistributionValue` to be defined with the same syntax as array expressions.
///
/// # Example
///
/// ```
/// let dist = relay_metrics::dist![1.0, 2.0];
/// ```
#[macro_export]
macro_rules! dist {
() => {
$crate::DistributionValue::new()
};
($($x:expr),+ $(,)?) => {{
let mut distribution = $crate::DistributionValue::new();
$( distribution.insert($x); )*
distribution
}};
}
/// The [aggregated value](Bucket::value) of a metric bucket.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value")]
pub enum BucketValue {
/// Aggregates [`MetricValue::Counter`] values by adding them into a single value.
///
/// ```text
/// 2, 1, 3, 2 => 8
/// ```
///
/// This variant serializes to a double precision float.
#[serde(rename = "c")]
Counter(CounterType),
/// Aggregates [`MetricValue::Distribution`] values by collecting their values.
///
/// ```text
/// 2, 1, 3, 2 => [1, 2, 2, 3]
/// ```
///
/// This variant serializes to a list of double precision floats, see [`DistributionValue`].
#[serde(rename = "d")]
Distribution(DistributionValue),
/// Aggregates [`MetricValue::Set`] values by storing their hash values in a set.
///
/// ```text
/// 2, 1, 3, 2 => {1, 2, 3}
/// ```
///
/// This variant serializes to a list of 32-bit integers.
#[serde(rename = "s")]
Set(BTreeSet<SetType>),
/// Aggregates [`MetricValue::Gauge`] values always retaining the maximum, minimum, and last
/// value, as well as the sum and count of all values.
///
/// **Note**: The "last" component of this aggregation is not commutative.
///
/// ```text
/// 1, 2, 3, 2 => {
/// max: 3,
/// min: 1,
/// sum: 8,
/// last: 2
/// count: 4,
/// }
/// ```
///
/// This variant serializes to a structure, see [`GaugeValue`].
#[serde(rename = "g")]
Gauge(GaugeValue),
}
impl BucketValue {
/// Returns the type of this value.
pub fn ty(&self) -> MetricType {
match self {
Self::Counter(_) => MetricType::Counter,
Self::Distribution(_) => MetricType::Distribution,
Self::Set(_) => MetricType::Set,
Self::Gauge(_) => MetricType::Gauge,
}
}
/// Returns the number of values needed to encode the bucket (a measure of bucket
/// complexity).
pub fn relative_size(&self) -> usize {
match self {
Self::Counter(_) => 1,
Self::Set(s) => s.len(),
Self::Gauge(_) => 5,
Self::Distribution(m) => m.internal_size(),
}
}
/// Estimates the number of bytes needed to encode the bucket value.
/// Note that this does not necessarily match the exact memory footprint of the value,
/// because datastructures might have a memory overhead.
///
/// This is very similar to [`BucketValue::relative_size`], which can possibly be removed.
pub fn cost(&self) -> usize {
// Beside the size of [`BucketValue`], we also need to account for the cost of values
// allocated dynamically.
let allocated_cost = match self {
Self::Counter(_) => 0,
Self::Set(s) => mem::size_of::<SetType>() * s.len(),
Self::Gauge(_) => 0,
Self::Distribution(m) => {
m.values.len() * (mem::size_of::<DistributionType>() + mem::size_of::<Count>())
}
};
mem::size_of::<Self>() + allocated_cost
}
}
impl From<MetricValue> for BucketValue {
fn from(value: MetricValue) -> Self {
match value {
MetricValue::Counter(value) => Self::Counter(value),
MetricValue::Distribution(value) => Self::Distribution(dist![value]),
MetricValue::Set(value) => Self::Set(std::iter::once(value).collect()),
MetricValue::Gauge(value) => Self::Gauge(GaugeValue::single(value)),
}
}
}
/// A value that can be merged into a [`BucketValue`].
///
/// Currently either a [`MetricValue`] or another `BucketValue`.
trait MergeValue: Into<BucketValue> {
/// Merges `self` into the given `bucket_value` and returns the additional cost for storing this value.
///
/// Aggregation is performed according to the rules documented in [`BucketValue`].
fn merge_into(self, bucket_value: &mut BucketValue) -> Result<(), AggregateMetricsError>;
}
impl MergeValue for BucketValue {
fn merge_into(self, bucket_value: &mut BucketValue) -> Result<(), AggregateMetricsError> {
match (bucket_value, self) {
(BucketValue::Counter(lhs), BucketValue::Counter(rhs)) => *lhs += rhs,
(BucketValue::Distribution(lhs), BucketValue::Distribution(rhs)) => lhs.extend(&rhs),
(BucketValue::Set(lhs), BucketValue::Set(rhs)) => lhs.extend(rhs),
(BucketValue::Gauge(lhs), BucketValue::Gauge(rhs)) => lhs.merge(rhs),
_ => return Err(AggregateMetricsErrorKind::InvalidTypes.into()),
}
Ok(())
}
}
impl MergeValue for MetricValue {
fn merge_into(self, bucket_value: &mut BucketValue) -> Result<(), AggregateMetricsError> {
match (bucket_value, self) {
(BucketValue::Counter(counter), MetricValue::Counter(value)) => {
*counter += value;
}
(BucketValue::Distribution(distribution), MetricValue::Distribution(value)) => {
distribution.insert(value);
}
(BucketValue::Set(set), MetricValue::Set(value)) => {
set.insert(value);
}
(BucketValue::Gauge(gauge), MetricValue::Gauge(value)) => {
gauge.insert(value);
}
_ => {
return Err(AggregateMetricsErrorKind::InvalidTypes.into());
}
}
Ok(())
}
}
/// Error returned when parsing or serializing a [`Bucket`].
#[derive(Debug, Fail)]
#[fail(display = "failed to parse metric bucket")]
pub struct ParseBucketError(#[cause] serde_json::Error);
/// An aggregation of metric values by the [`Aggregator`].
///
/// As opposed to single metric values, bucket aggregations can carry multiple values. See
/// [`MetricType`] for a description on how values are aggregated in buckets. Values are aggregated
/// by metric name, type, time window, and all tags. Particularly, this allows metrics to have the
/// same name even if their types differ.
///
/// See the [crate documentation](crate) for general information on Metrics.
///
/// # Values
///
/// The contents of a bucket, especially their representation and serialization, depend on the
/// metric type:
///
/// - [Counters](BucketValue::Counter) store a single value, serialized as floating point.
/// - [Distributions](MetricType::Distribution) and [sets](MetricType::Set) store the full set of
/// reported values.
/// - [Gauges](BucketValue::Gauge) store a snapshot of reported values, see [`GaugeValue`].
///
/// # Submission Protocol
///
/// Buckets are always represented as JSON. The data type of the `value` field is determined by the
/// metric type.
///
/// ```json
/// [
/// {
/// "timestamp": 1615889440,
/// "name": "endpoint.response_time",
/// "type": "d",
/// "unit": "millisecond",
/// "value": [36, 49, 57, 68],
/// "tags": {
/// "route": "user_index"
/// }
/// },
/// {
/// "timestamp": 1615889440,
/// "name": "endpoint.hits",
/// "type": "c",
/// "value": 4,
/// "tags": {
/// "route": "user_index"
/// }
/// },
/// {
/// "timestamp": 1615889440,
/// "name": "endpoint.parallel_requests",
/// "type": "g",
/// "value": {
/// "max": 42.0,
/// "min": 17.0,
/// "sum": 2210.0,
/// "last": 25.0,
/// "count": 85
/// }
/// },
/// {
/// "timestamp": 1615889440,
/// "name": "endpoint.users",
/// "type": "s",
/// "value": [
/// 3182887624,
/// 4267882815
/// ],
/// "tags": {
/// "route": "user_index"
/// }
/// }
/// ]
/// ```
///
/// To parse a submission payload, use [`Bucket::parse_all`].
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Bucket {
/// The start time of the time window.
pub timestamp: UnixTimestamp,
/// The length of the time window in seconds.
pub width: u64,
/// The name of the metric without its unit.
///
/// See [`Metric::name`].
pub name: String,
/// The unit of the metric value.
///
/// See [`Metric::unit`].
#[serde(default, skip_serializing_if = "MetricUnit::is_none")]
pub unit: MetricUnit,
/// The type and aggregated values of this bucket.
///
/// See [`Metric::value`] for a mapping to inbound data.
#[serde(flatten)]
pub value: BucketValue,
/// A list of tags adding dimensions to the metric for filtering and aggregation.
///
/// See [`Metric::tags`]. Every combination of tags results in a different bucket.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub tags: BTreeMap<String, String>,
}
impl Bucket {
fn from_parts(key: BucketKey, bucket_interval: u64, value: BucketValue) -> Self {
Self {
timestamp: key.timestamp,
width: bucket_interval,
name: key.metric_name,
unit: key.metric_unit,
value,
tags: key.tags,
}
}
/// Parses a single metric bucket from the JSON protocol.
pub fn parse(slice: &[u8]) -> Result<Self, ParseBucketError> {
serde_json::from_slice(slice).map_err(ParseBucketError)
}
/// Parses a set of metric bucket from the JSON protocol.
pub fn parse_all(slice: &[u8]) -> Result<Vec<Bucket>, ParseBucketError> {
serde_json::from_slice(slice).map_err(ParseBucketError)
}
/// Serializes the given buckets to the JSON protocol.
pub fn serialize_all(buckets: &[Self]) -> Result<String, ParseBucketError> {
serde_json::to_string(&buckets).map_err(ParseBucketError)
}
}
/// Any error that may occur during aggregation.
#[derive(Debug, Fail, PartialEq)]
#[fail(display = "failed to aggregate metrics: {}", kind)]
pub struct AggregateMetricsError {
kind: AggregateMetricsErrorKind,
}
impl From<AggregateMetricsErrorKind> for AggregateMetricsError {
fn from(kind: AggregateMetricsErrorKind) -> Self {
AggregateMetricsError { kind }
}
}
#[derive(Debug, Fail, PartialEq)]
#[allow(clippy::enum_variant_names)]
enum AggregateMetricsErrorKind {
/// A metric bucket had invalid characters in the metric name.
#[fail(display = "found invalid characters")]
InvalidCharacters,
/// A metric bucket's timestamp was out of the configured acceptable range.
#[fail(display = "found invalid timestamp")]
InvalidTimestamp,
/// Internal error: Attempted to merge two metric buckets of different types.
#[fail(display = "found incompatible metric types")]
InvalidTypes,
/// A metric bucket had a too long string (metric name or a tag key/value).
#[fail(display = "found invalid string")]
InvalidStringLength,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct BucketKey {
project_key: ProjectKey,
timestamp: UnixTimestamp,
metric_name: String,
metric_type: MetricType,
metric_unit: MetricUnit,
tags: BTreeMap<String, String>,
}
impl BucketKey {
/// An extremely hamfisted way to hash a bucket key into an integer.
///
/// This is necessary for (and probably only useful for) reporting unique bucket keys in a
/// cadence set metric, as cadence set metrics can only be constructed from values that
/// implement [`cadence::ext::ToSetValue`]. This trait is only implemented for [`i64`], and
/// while we could implement it directly for [`BucketKey`] the documentation advises us not to
/// interact with this trait.
///
/// [`cadence::ext::ToSetValue`]: https://docs.rs/cadence/*/cadence/ext/trait.ToSetValue.html
fn as_integer_lossy(&self) -> i64 {
// XXX: The way this hasher is used may be platform-dependent. If we want to produce the
// same hash across platforms, the `deterministic_hash` crate may be useful.
let mut hasher = crc32fast::Hasher::new();
std::hash::Hash::hash(self, &mut hasher);
hasher.finalize() as i64
}
/// Estimates the number of bytes needed to encode the bucket key.
/// Note that this does not necessarily match the exact memory footprint of the key,
/// because datastructures might have a memory overhead.
fn cost(&self) -> usize {
mem::size_of::<Self>()
+ self.metric_name.capacity()
+ self
.tags
.iter()
.fold(0, |acc, (k, v)| acc + k.capacity() + v.capacity())
}
}
/// Parameters used by the [`Aggregator`].
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default)]
pub struct AggregatorConfig {
/// Determines the wall clock time interval for buckets in seconds.
///
/// Defaults to `10` seconds. Every metric is sorted into a bucket of this size based on its
/// timestamp. This defines the minimum granularity with which metrics can be queried later.
pub bucket_interval: u64,
/// The initial delay in seconds to wait before flushing a bucket.
///
/// Defaults to `30` seconds. Before sending an aggregated bucket, this is the time Relay waits
/// for buckets that are being reported in real time. This should be higher than the
/// `debounce_delay`.
///
/// Relay applies up to a full `bucket_interval` of additional jitter after the initial delay to spread out flushing real time buckets.
pub initial_delay: u64,
/// The delay in seconds to wait before flushing a backdated buckets.
///
/// Defaults to `10` seconds. Metrics can be sent with a past timestamp. Relay wait this time
/// before sending such a backdated bucket to the upsteam. This should be lower than
/// `initial_delay`.
///
/// Unlike `initial_delay`, the debounce delay starts with the exact moment the first metric
/// is added to a backdated bucket.
pub debounce_delay: u64,
/// The age in seconds of the oldest allowed bucket timestamp.
///
/// Defaults to 5 days.
pub max_secs_in_past: u64,
/// The time in seconds that a timestamp may be in the future.
///
/// Defaults to 1 minute.
pub max_secs_in_future: u64,
/// The length the name of a metric is allowed to be.
///
/// Defaults to `200` bytes.
pub max_name_length: usize,
/// The length the tag key is allowed to be.
///
/// Defaults to `200` bytes.
pub max_tag_key_length: usize,
/// The length the tag value is allowed to be.
///
/// Defaults to `200` bytes.
pub max_tag_value_length: usize,
}
impl AggregatorConfig {
/// Returns the time width buckets.
fn bucket_interval(&self) -> Duration {
Duration::from_secs(self.bucket_interval)
}
/// Returns the initial flush delay after the end of a bucket's original time window.
fn initial_delay(&self) -> Duration {
Duration::from_secs(self.initial_delay)
}
/// The delay to debounce backdated flushes.
fn debounce_delay(&self) -> Duration {
Duration::from_secs(self.debounce_delay)
}
/// Determines the target bucket for an incoming bucket timestamp and bucket width.
///
/// We select the output bucket which overlaps with the center of the incoming bucket.
/// Fails if timestamp is too old or too far into the future.
fn get_bucket_timestamp(
&self,
timestamp: UnixTimestamp,
bucket_width: u64,
) -> Result<UnixTimestamp, AggregateMetricsError> {
// We know this must be UNIX timestamp because we need reliable match even with system
// clock skew over time.
let now = UnixTimestamp::now().as_secs();
let min_timestamp = UnixTimestamp::from_secs(now.saturating_sub(self.max_secs_in_past));
let max_timestamp = UnixTimestamp::from_secs(now.saturating_add(self.max_secs_in_future));
// Find middle of the input bucket to select a target
let ts = timestamp.as_secs().saturating_add(bucket_width / 2);
// Align target_timestamp to output bucket width
let ts = (ts / self.bucket_interval) * self.bucket_interval;
let output_timestamp = UnixTimestamp::from_secs(ts);
if output_timestamp < min_timestamp || output_timestamp > max_timestamp {
return Err(AggregateMetricsErrorKind::InvalidTimestamp.into());
}
Ok(output_timestamp)
}
/// Returns the instant at which a bucket should be flushed.
///
/// Recent buckets are flushed after a grace period of `initial_delay`. Backdated buckets, that
/// is, buckets that lie in the past, are flushed after the shorter `debounce_delay`.
fn get_flush_time(&self, bucket_timestamp: UnixTimestamp, project_key: ProjectKey) -> Instant {
let now = Instant::now();
let mut flush = None;
if let MonotonicResult::Instant(instant) = bucket_timestamp.to_instant() {
let bucket_end = instant + self.bucket_interval();
let initial_flush = bucket_end + self.initial_delay();
// If the initial flush is still pending, use that.
if initial_flush > now {
// Shift deterministically within one bucket interval based on the project key. This
// distributes buckets over time while also flushing all buckets of the same project
// key together.
let mut hasher = FnvHasher::default();
hasher.write(project_key.as_str().as_bytes());
let shift_millis = u64::from(hasher.finish()) % (self.bucket_interval * 1000);
flush = Some(initial_flush + Duration::from_millis(shift_millis));
}
}
let delay = UnixTimestamp::now().as_secs() as i64 - bucket_timestamp.as_secs() as i64;
relay_statsd::metric!(
histogram(MetricHistograms::BucketsDelay) = delay as f64,
backedated = if flush.is_none() { "true" } else { "false" },
);
// If the initial flush time has passed or cannot be represented, debounce future flushes
// with the `debounce_delay` starting now.
match flush {
Some(initial_flush) => initial_flush,
None => now + self.debounce_delay(),
}
}
}
impl Default for AggregatorConfig {
fn default() -> Self {
Self {
bucket_interval: 10,
initial_delay: 30,
debounce_delay: 10,
max_secs_in_past: 5 * 24 * 60 * 60, // 5 days, as for sessions
max_secs_in_future: 60, // 1 minute
max_name_length: 200,
max_tag_key_length: 200,
max_tag_value_length: 200,
}
}
}
/// Bucket in the [`Aggregator`] with a defined flush time.
///
/// This type implements an inverted total ordering. The maximum queued bucket has the lowest flush
/// time, which is suitable for using it in a [`BinaryHeap`].
///
/// [`BinaryHeap`]: std::collections::BinaryHeap
#[derive(Debug)]
struct QueuedBucket {
flush_at: Instant,
value: BucketValue,
}
impl QueuedBucket {
/// Creates a new `QueuedBucket` with a given flush time.
fn new(flush_at: Instant, value: BucketValue) -> Self {
Self { flush_at, value }
}
/// Returns `true` if the flush time has elapsed.
fn elapsed(&self) -> bool {
Instant::now() > self.flush_at
}
}
impl PartialEq for QueuedBucket {
fn eq(&self, other: &Self) -> bool {
self.flush_at.eq(&other.flush_at)
}
}
impl Eq for QueuedBucket {}