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
use crate::layers::Layer;
use metrics::{Counter, Gauge, Histogram, Key, KeyName, Recorder, SharedString, Unit};

/// Applies a prefix to every metric key.
///
/// Keys will be prefixed in the format of `<prefix>.<remaining>`.
pub struct Prefix<R> {
    prefix: SharedString,
    inner: R,
}

impl<R> Prefix<R> {
    fn prefix_key(&self, key: &Key) -> Key {
        let mut new_name = String::with_capacity(self.prefix.len() + 1 + key.name().len());
        new_name.push_str(self.prefix.as_ref());
        new_name.push('.');
        new_name.push_str(key.name());

        Key::from_parts(new_name, key.labels())
    }

    fn prefix_key_name(&self, key_name: KeyName) -> KeyName {
        let mut new_name = String::with_capacity(self.prefix.len() + 1 + key_name.as_str().len());
        new_name.push_str(self.prefix.as_ref());
        new_name.push('.');
        new_name.push_str(key_name.as_str());

        KeyName::from(new_name)
    }
}

impl<R: Recorder> Recorder for Prefix<R> {
    fn describe_counter(&self, key_name: KeyName, unit: Option<Unit>, description: &'static str) {
        let new_key_name = self.prefix_key_name(key_name);
        self.inner.describe_counter(new_key_name, unit, description)
    }

    fn describe_gauge(&self, key_name: KeyName, unit: Option<Unit>, description: &'static str) {
        let new_key_name = self.prefix_key_name(key_name);
        self.inner.describe_gauge(new_key_name, unit, description)
    }

    fn describe_histogram(&self, key_name: KeyName, unit: Option<Unit>, description: &'static str) {
        let new_key_name = self.prefix_key_name(key_name);
        self.inner.describe_histogram(new_key_name, unit, description)
    }

    fn register_counter(&self, key: &Key) -> Counter {
        let new_key = self.prefix_key(key);
        self.inner.register_counter(&new_key)
    }

    fn register_gauge(&self, key: &Key) -> Gauge {
        let new_key = self.prefix_key(key);
        self.inner.register_gauge(&new_key)
    }

    fn register_histogram(&self, key: &Key) -> Histogram {
        let new_key = self.prefix_key(key);
        self.inner.register_histogram(&new_key)
    }
}

/// A layer for applying a prefix to every metric key.
///
/// More information on the behavior of the layer can be found in [`Prefix`].
pub struct PrefixLayer(&'static str);

impl PrefixLayer {
    /// Creates a new `PrefixLayer` based on the given prefix.
    pub fn new<S: Into<String>>(prefix: S) -> PrefixLayer {
        PrefixLayer(Box::leak(prefix.into().into_boxed_str()))
    }
}

impl<R> Layer<R> for PrefixLayer {
    type Output = Prefix<R>;

    fn layer(&self, inner: R) -> Self::Output {
        Prefix { prefix: self.0.into(), inner }
    }
}

#[cfg(test)]
mod tests {
    use super::{Prefix, PrefixLayer};
    use crate::layers::Layer;
    use crate::test_util::*;
    use metrics::{Counter, Gauge, Histogram, Key, KeyName, Unit};

    #[test]
    fn test_basic_functionality() {
        let inputs = 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 expectations = vec![
            RecorderOperation::DescribeCounter(
                "testing.counter_key".into(),
                Some(Unit::Count),
                "counter desc",
            ),
            RecorderOperation::DescribeGauge(
                "testing.gauge_key".into(),
                Some(Unit::Bytes),
                "gauge desc",
            ),
            RecorderOperation::DescribeHistogram(
                "testing.histogram_key".into(),
                Some(Unit::Nanoseconds),
                "histogram desc",
            ),
            RecorderOperation::RegisterCounter("testing.counter_key".into(), Counter::noop()),
            RecorderOperation::RegisterGauge("testing.gauge_key".into(), Gauge::noop()),
            RecorderOperation::RegisterHistogram("testing.histogram_key".into(), Histogram::noop()),
        ];

        let recorder = MockBasicRecorder::from_operations(expectations);
        let prefix = PrefixLayer::new("testing");
        let prefix = prefix.layer(recorder);

        for operation in inputs {
            operation.apply_to_recorder(&prefix);
        }
    }

    #[test]
    fn test_key_vs_key_name() {
        let prefix = Prefix { prefix: "foobar".into(), inner: () };

        let key_name = KeyName::from("my_key");
        let key = Key::from_name(key_name.clone());

        let prefixed_key = prefix.prefix_key(&key);
        let prefixed_key_name = prefix.prefix_key_name(key_name);

        assert_eq!(
            prefixed_key.name(),
            prefixed_key_name.as_str(),
            "prefixed key and prefixed key name should match"
        );
    }
}