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
use std::sync::Arc;

use metrics::{
    Counter, CounterFn, Gauge, GaugeFn, Histogram, HistogramFn, Key, KeyName, Recorder, Unit,
};

struct FanoutCounter {
    counters: Vec<Counter>,
}

impl FanoutCounter {
    pub fn from_counters(counters: Vec<Counter>) -> Self {
        Self { counters }
    }
}

impl CounterFn for FanoutCounter {
    fn increment(&self, value: u64) {
        for counter in &self.counters {
            counter.increment(value);
        }
    }

    fn absolute(&self, value: u64) {
        for counter in &self.counters {
            counter.absolute(value);
        }
    }
}

impl From<FanoutCounter> for Counter {
    fn from(counter: FanoutCounter) -> Counter {
        Counter::from_arc(Arc::new(counter))
    }
}

struct FanoutGauge {
    gauges: Vec<Gauge>,
}

impl FanoutGauge {
    pub fn from_gauges(gauges: Vec<Gauge>) -> Self {
        Self { gauges }
    }
}

impl GaugeFn for FanoutGauge {
    fn increment(&self, value: f64) {
        for gauge in &self.gauges {
            gauge.increment(value);
        }
    }

    fn decrement(&self, value: f64) {
        for gauge in &self.gauges {
            gauge.decrement(value);
        }
    }

    fn set(&self, value: f64) {
        for gauge in &self.gauges {
            gauge.set(value);
        }
    }
}

impl From<FanoutGauge> for Gauge {
    fn from(gauge: FanoutGauge) -> Gauge {
        Gauge::from_arc(Arc::new(gauge))
    }
}

struct FanoutHistogram {
    histograms: Vec<Histogram>,
}

impl FanoutHistogram {
    pub fn from_histograms(histograms: Vec<Histogram>) -> Self {
        Self { histograms }
    }
}

impl HistogramFn for FanoutHistogram {
    fn record(&self, value: f64) {
        for histogram in &self.histograms {
            histogram.record(value);
        }
    }
}

impl From<FanoutHistogram> for Histogram {
    fn from(histogram: FanoutHistogram) -> Histogram {
        Histogram::from_arc(Arc::new(histogram))
    }
}

/// Fans out metrics to multiple recorders.
pub struct Fanout {
    recorders: Vec<Box<dyn Recorder>>,
}

impl Recorder for Fanout {
    fn describe_counter(&self, key_name: KeyName, unit: Option<Unit>, description: &'static str) {
        for recorder in &self.recorders {
            recorder.describe_counter(key_name.clone(), unit, description);
        }
    }

    fn describe_gauge(&self, key_name: KeyName, unit: Option<Unit>, description: &'static str) {
        for recorder in &self.recorders {
            recorder.describe_gauge(key_name.clone(), unit, description);
        }
    }

    fn describe_histogram(&self, key_name: KeyName, unit: Option<Unit>, description: &'static str) {
        for recorder in &self.recorders {
            recorder.describe_histogram(key_name.clone(), unit, description);
        }
    }

    fn register_counter(&self, key: &Key) -> Counter {
        let counters =
            self.recorders.iter().map(|recorder| recorder.register_counter(key)).collect();

        FanoutCounter::from_counters(counters).into()
    }

    fn register_gauge(&self, key: &Key) -> Gauge {
        let gauges = self.recorders.iter().map(|recorder| recorder.register_gauge(key)).collect();

        FanoutGauge::from_gauges(gauges).into()
    }

    fn register_histogram(&self, key: &Key) -> Histogram {
        let histograms =
            self.recorders.iter().map(|recorder| recorder.register_histogram(key)).collect();

        FanoutHistogram::from_histograms(histograms).into()
    }
}

/// A layer for fanning out metrics to multiple recorders.
///
/// More information on the behavior of the layer can be found in [`Fanout`].
#[derive(Default)]
pub struct FanoutBuilder {
    recorders: Vec<Box<dyn Recorder>>,
}

impl FanoutBuilder {
    /// Adds a recorder to the fanout list.
    pub fn add_recorder<R>(mut self, recorder: R) -> FanoutBuilder
    where
        R: Recorder + 'static,
    {
        self.recorders.push(Box::new(recorder));
        self
    }

    /// Builds the `Fanout` layer.
    pub fn build(self) -> Fanout {
        Fanout { recorders: self.recorders }
    }
}

#[cfg(test)]
mod tests {
    use super::FanoutBuilder;
    use crate::test_util::*;
    use metrics::{Counter, Gauge, Histogram, Unit};

    #[test]
    fn test_basic_functionality() {
        let operations = vec![
            RecorderOperation::DescribeCounter(
                "counter_key".into(),
                Some(Unit::Count),
                "counter desc",
            ),
            RecorderOperation::DescribeGauge("gauge_key".into(), Some(Unit::Bytes), "gauge desc"),
            RecorderOperation::DescribeHistogram(
                "histogram_key".into(),
                Some(Unit::Nanoseconds),
                "histogram desc",
            ),
            RecorderOperation::RegisterCounter("counter_key".into(), Counter::noop()),
            RecorderOperation::RegisterGauge("gauge_key".into(), Gauge::noop()),
            RecorderOperation::RegisterHistogram("histogram_key".into(), Histogram::noop()),
        ];

        let recorder1 = MockBasicRecorder::from_operations(operations.clone());
        let recorder2 = MockBasicRecorder::from_operations(operations.clone());
        let fanout =
            FanoutBuilder::default().add_recorder(recorder1).add_recorder(recorder2).build();

        for operation in operations {
            operation.apply_to_recorder(&fanout);
        }
    }
}