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
use core::name::MetricName;
use core::input::InputKind;
use core::MetricValue;
use self::LineOp::*;

use std::io;
use std::sync::Arc;

/// Print commands are steps in the execution of output templates.
pub enum LineOp {
    /// Print a string.
    Literal(Vec<u8>),
    /// Lookup and print label value for key, if it exists.
    LabelExists(String, Vec<LabelOp>),
    /// Print metric value as text.
    ValueAsText,
    /// Print metric value, divided by the given scale, as text.
    ScaledValueAsText(f64),
    /// Print the newline character.labels.lookup(key)
    NewLine,
}

/// Print commands are steps in the execution of output templates.
pub enum LabelOp {
    /// Print a string.
    Literal(Vec<u8>),
    /// Print the label key.
    LabelKey,
    /// Print the label value.
    LabelValue,
}

/// An sequence of print commands, embodying an output strategy for a single metric.
pub struct LineTemplate {
    ops: Vec<LineOp>
}

impl From<Vec<LineOp>> for LineTemplate {
    fn from(ops: Vec<LineOp>) -> Self {
        LineTemplate { ops }
    }
}

impl LineTemplate {
    /// Template execution applies commands in turn, writing to the output.
    pub fn print<L>(&self, output: &mut io::Write, value: MetricValue, lookup: L) -> Result<(), io::Error>
    where L: Fn(&str) -> Option<Arc<String>>
    {
        for cmd in &self.ops {
            match cmd {
                Literal(src) => output.write_all(src.as_ref())?,
                ValueAsText => output.write_all(format!("{}", value).as_ref())?,
                ScaledValueAsText(scale) => {
                    let scaled = value as f64 / scale;
                    output.write_all(format!("{}", scaled).as_ref())?
                },
                NewLine => writeln!(output)?,
                LabelExists(label_key, print_label) => {
                    if let Some(label_value) = lookup(label_key.as_ref()) {
                        for label_cmd in print_label {
                            match label_cmd {
                                LabelOp::LabelValue =>
                                    output.write_all(label_value.as_bytes())?,
                                LabelOp::LabelKey =>
                                    output.write_all(label_key.as_bytes())?,
                                LabelOp::Literal(src) =>
                                    output.write_all(src.as_ref())?,
                            }
                        }
                    }
                },
            };
        }
        Ok(())
    }
}

/// Format output config support.
pub trait Formatting {
    /// Specify formatting of output.
    fn formatting(&self, format: impl LineFormat + 'static) -> Self;
}

/// Forges metric-specific printers
pub trait LineFormat: Send + Sync {

    /// Prepare a template for output of metric values.
    fn template(&self, name: &MetricName, kind: InputKind) -> LineTemplate;
}

/// A simple metric output format of "MetricName {Value}"
#[derive(Default)]
pub struct SimpleFormat {
    // TODO make separator configurable
//    separator: String,
}

impl LineFormat for SimpleFormat {
    fn template(&self, name: &MetricName, _kind: InputKind) -> LineTemplate {
        let mut header = name.join(".");
        header.push(' ');
        LineTemplate {
            ops: vec![
                Literal(header.into_bytes()),
                ValueAsText,
                NewLine,
            ]
        }
    }
}

#[cfg(test)]
pub mod test {
    use super::*;
    use core::label::Labels;

    pub struct TestFormat;

    impl LineFormat for TestFormat {
        fn template(&self, name: &MetricName, kind: InputKind) -> LineTemplate {
            let mut header: String = format!("{:?}", kind);
            header.push('/');
            header.push_str(&name.join("."));
            header.push(' ');
            LineTemplate {
                ops: vec![
                    Literal(header.into()),
                    ValueAsText,
                    Literal(" ".into()),
                    ScaledValueAsText(1000.0),
                    Literal(" ".into()),
                    LabelExists("test_key".into(), vec![
                        LabelOp::LabelKey,
                        LabelOp::Literal("=".into()),
                        LabelOp::LabelValue]),
                    NewLine,
                ]
            }
        }
    }

    #[test]
    fn print_label_exists() {
        let labels: Labels = labels!("test_key" => "456");
        let format = TestFormat {};
        let mut name = MetricName::from("abc");
        name = name.prepend("xyz");
        let template = format.template(&name, InputKind::Counter);
        let mut out = vec![];
        template.print(&mut out, 123000, |key| labels.lookup(key)).unwrap();
        assert_eq!("Counter/xyz.abc 123000 123 test_key=456\n", String::from_utf8(out).unwrap());
    }

    #[test]
    fn print_label_not_exists() {
        let format = TestFormat {};
        let mut name = MetricName::from("abc");
        name = name.prepend("xyz");
        let template = format.template(&name, InputKind::Counter);
        let mut out = vec![];
        template.print(&mut out, 123000, |_key| None).unwrap();
        assert_eq!("Counter/xyz.abc 123000 123 \n", String::from_utf8(out).unwrap());
    }
}