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
//! Bucket for [histogram][histogram] metric.
//!
//! [histogram]: https://prometheus.io/docs/concepts/metric_types/#histogram
use std;
use std::iter::Peekable;
use std::slice;

use {ErrorKind, Result};
use atomic::AtomicU64;
use metrics::Histogram;

/// A bucket in which a [histogram][histogram] counts samples.
///
/// Note that this bucket is not cumulative.
///
/// [histogram]: https://prometheus.io/docs/concepts/metric_types/#histogram
#[derive(Debug)]
pub struct Bucket {
    count: AtomicU64,
    upper_bound: f64,
}
impl Bucket {
    /// Returns the count of samples in this bucket.
    #[inline]
    pub fn count(&self) -> u64 {
        self.count.get()
    }

    /// Returns the upper bound of this bucket.
    ///
    /// This method never return a NaN value.
    #[inline]
    pub fn upper_bound(&self) -> f64 {
        self.upper_bound
    }

    pub(crate) fn new(upper_bound: f64) -> Result<Self> {
        track_assert!(!upper_bound.is_nan(), ErrorKind::InvalidInput);
        Ok(Bucket {
            count: AtomicU64::new(0),
            upper_bound,
        })
    }

    #[inline]
    pub(crate) fn increment(&self) {
        self.count.inc();
    }
}

/// Cumulative bucket.
#[derive(Debug, Clone)]
pub struct CumulativeBucket {
    cumulative_count: u64,
    upper_bound: f64,
}
impl CumulativeBucket {
    /// Returns the cumulative count of samples.
    pub fn cumulative_count(&self) -> u64 {
        self.cumulative_count
    }

    /// Returns the upper bound of this bucket.
    ///
    /// This method never return a NaN value.
    pub fn upper_bound(&self) -> f64 {
        self.upper_bound
    }
}

/// An iterator which iterates cumulative buckets in a histogram.
#[derive(Debug)]
pub struct CumulativeBuckets<'a> {
    cumulative_count: u64,
    iter: slice::Iter<'a, Bucket>,
}
impl<'a> CumulativeBuckets<'a> {
    pub(crate) fn new(buckets: &'a [Bucket]) -> Self {
        CumulativeBuckets {
            cumulative_count: 0,
            iter: buckets.iter(),
        }
    }
}
impl<'a> Iterator for CumulativeBuckets<'a> {
    type Item = CumulativeBucket;
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|b| {
            self.cumulative_count += b.count();
            CumulativeBucket {
                cumulative_count: self.cumulative_count,
                upper_bound: b.upper_bound(),
            }
        })
    }
}

/// An iterator which iterates cumulative buckets in an aggregation of histograms.
#[derive(Debug)]
pub struct AggregatedCumulativeBuckets<'a> {
    cumulative_count: u64,
    iters: Vec<Peekable<slice::Iter<'a, Bucket>>>,
}
impl<'a> AggregatedCumulativeBuckets<'a> {
    pub(crate) fn new(histograms: &'a [Histogram]) -> Self {
        AggregatedCumulativeBuckets {
            cumulative_count: 0,
            iters: histograms
                .iter()
                .map(|h| h.buckets().iter().peekable())
                .collect(),
        }
    }
}
impl<'a> Iterator for AggregatedCumulativeBuckets<'a> {
    type Item = CumulativeBucket;
    fn next(&mut self) -> Option<Self::Item> {
        let mut min = std::f64::INFINITY;
        let mut i = 0;
        while i < self.iters.len() {
            if let Some(bound) = self.iters[i].peek().map(|b| b.upper_bound()) {
                if bound < min {
                    min = bound;
                }
                i += 1;
            } else {
                let _ = self.iters.swap_remove(i);
            }
        }
        if self.iters.is_empty() {
            return None;
        }

        for buckets in &mut self.iters {
            let upper_bound = buckets.peek().expect("Never fails").upper_bound();
            if min.is_infinite() || (upper_bound - min).abs() < std::f64::EPSILON {
                let bucket = buckets.next().expect("Never fails");
                self.cumulative_count += bucket.count();
            }
        }

        Some(CumulativeBucket {
            cumulative_count: self.cumulative_count,
            upper_bound: min,
        })
    }
}