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
use {Message, Metric, ServiceCheck, Status};
use super::{Parser, ParseError};

pub trait ServiceStatusParser {
    fn parse(self) -> Result<Message, ParseError>;
}

impl ServiceStatusParser for Parser {
    fn parse(mut self) -> Result<Message, ParseError> {
        if self.chars.is_empty() {
            return Err(ParseError::EmptyInput)
        }

        // Start with the service check tag
        self.take_until(vec!['|']);

        // Get the name
        let name = self.take_until(vec!['|']);
        if name.is_empty() {
            return Err(ParseError::NoName)
        }

        // Get the status
        let status = match self.take_until(vec!['|']).as_ref() {
            "0" => Status::OK,
            "1" => Status::WARNING,
            "2" => Status::CRITICAL,
            _ => Status::UNKNOWN
        };

        // Peek the string to see if we need to parse a timestamp
        let timestamp = if Some('d') == self.peek() {
            self.skip();
            self.skip();
            match self.take_float_until(vec!['|']) {
                Ok(v) => Some(v),
                Err(_) => return Err(ParseError::ValueNotFloat)
            }
        } else {
            None
        };

        // Peek the string to see if we need to parse a hostname
        let hostname = if Some('h') == self.peek() {
            self.skip();
            self.skip();
            Some(self.take_until(vec!['|']))
        } else {
            None
        };

        // Peek the string to see if we need to parse tags
        let tags = if Some('#') == self.peek() {
            Some(self.parse_tags())
        } else {
            None
        };

        // Peek the string to see if we need to parse a message
        let message = if Some('m') == self.peek() {
            self.skip();
            self.skip();
            Some(self.take_until(vec!['|']))
        } else {
            None
        };

        let service_check = ServiceCheck {
            status: status,
            timestamp: timestamp,
            hostname: hostname,
            message: message
        };

        Ok(Message {
            name: name,
            tags: tags,
            metric: Metric::ServiceCheck(service_check)
        })
    }
}

pub fn parse(input: String) -> Result<Message, ParseError> {
    Parser::new(input).parse()
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::parse;
    use {Message, Metric, ServiceCheck, Status};

    #[test]
    fn test_parse_with_tags() {
        let result = parse("_sc|Redis connection|2|d:10101|h:frontend1|#redis_instance:10.0.0.16:6379|m:Redis connection timed out after 10s".to_string());

        let mut tags = BTreeMap::new();
        tags.insert("redis_instance".to_string(), "10.0.0.16:6379".to_string());

        let expected = Message {
            name: "Redis connection".to_string(),
            tags: Some(tags),
            metric: Metric::ServiceCheck(ServiceCheck {
                status: Status::CRITICAL,
                timestamp: Some(10101f64),
                hostname: Some("frontend1".to_string()),
                message: Some("Redis connection timed out after 10s".to_string()),
            })
        };

        assert_eq!(result, Ok(expected));
    }

    #[test]
    fn test_parse_without_tags() {
        let result = parse("_sc|Redis connection|0|d:10101|h:frontend1|m:Redis connection timed out after 10s".to_string());

        let expected = Message {
            name: "Redis connection".to_string(),
            tags: None,
            metric: Metric::ServiceCheck(ServiceCheck {
                status: Status::OK,
                timestamp: Some(10101f64),
                hostname: Some("frontend1".to_string()),
                message: Some("Redis connection timed out after 10s".to_string()),
            })
        };

        assert_eq!(result, Ok(expected));
    }

    #[test]
    fn test_parse_without_duration() {
        let result = parse("_sc|Redis connection|1|h:frontend1|m:Redis connection timed out after 10s".to_string());

        let expected = Message {
            name: "Redis connection".to_string(),
            tags: None,
            metric: Metric::ServiceCheck(ServiceCheck {
                status: Status::WARNING,
                timestamp: None,
                hostname: Some("frontend1".to_string()),
                message: Some("Redis connection timed out after 10s".to_string()),
            })
        };

        assert_eq!(result, Ok(expected));
    }

    #[test]
    fn test_parse_minimum_required() {
        let result = parse("_sc|Redis connection".to_string());

        let expected = Message {
            name: "Redis connection".to_string(),
            tags: None,
            metric:  Metric::ServiceCheck(ServiceCheck {
                status: Status::UNKNOWN,
                timestamp: None,
                hostname: None,
                message: None,
            })
        };

        assert_eq!(result, Ok(expected));
    }

    #[test]
    fn test_parse_invalid() {
        let result = parse("Redis connection".to_string());
        println!("{:?}", result);
        assert!(result.is_err());
    }
}