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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// Cadence - An extensible Statsd client for Rust!
//
// Copyright 2015-2021 Nick Pillitteri
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::builder::{MetricFormatter, MetricValue};
use std::error;
use std::fmt;
use std::io;

/// Trait for metrics to expose Statsd metric string slice representation.
///
/// Implementing metrics know how to turn themselves into one of the supported
/// types of metrics as defined in the [Statsd spec](https://github.com/b/statsd_spec).
pub trait Metric {
    fn as_metric_str(&self) -> &str;
}

/// Counters are simple values incremented or decremented by a client.
///
/// See the `Counted` trait for more information.
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
pub struct Counter {
    repr: String,
}

impl Counter {
    pub fn new(prefix: &str, key: &str, count: i64) -> Self {
        Self::from(MetricFormatter::counter(prefix, key, MetricValue::Signed(count)).format())
    }
}

impl From<String> for Counter {
    fn from(s: String) -> Self {
        Counter { repr: s }
    }
}

impl Metric for Counter {
    fn as_metric_str(&self) -> &str {
        &self.repr
    }
}

/// Timers are a positive number of milliseconds between a start and end point.
///
/// Statistical distribution of timer values is often computed by the server.
///
/// See the `Timed` trait for more information.
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
pub struct Timer {
    repr: String,
}

impl Timer {
    pub fn new(prefix: &str, key: &str, time: u64) -> Self {
        Self::from(MetricFormatter::timer(prefix, key, MetricValue::Unsigned(time)).format())
    }
}

impl From<String> for Timer {
    fn from(s: String) -> Self {
        Timer { repr: s }
    }
}

impl Metric for Timer {
    fn as_metric_str(&self) -> &str {
        &self.repr
    }
}

/// Gauges are an instantaneous value determined by the client.
///
/// See the `Gauged` trait for more information.
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
pub struct Gauge {
    repr: String,
}

impl Gauge {
    pub fn new(prefix: &str, key: &str, value: u64) -> Self {
        Self::from(MetricFormatter::gauge(prefix, key, MetricValue::Unsigned(value)).format())
    }

    pub fn new_f64(prefix: &str, key: &str, value: f64) -> Self {
        Self::from(MetricFormatter::gauge(prefix, key, MetricValue::Float(value)).format())
    }
}

impl From<String> for Gauge {
    fn from(s: String) -> Self {
        Gauge { repr: s }
    }
}

impl Metric for Gauge {
    fn as_metric_str(&self) -> &str {
        &self.repr
    }
}

/// Meters measure the rate at which events occur as determined by the server.
///
/// See the `Metered` trait for more information.
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
pub struct Meter {
    repr: String,
}

impl Meter {
    pub fn new(prefix: &str, key: &str, value: u64) -> Self {
        Self::from(MetricFormatter::meter(prefix, key, MetricValue::Unsigned(value)).format())
    }
}

impl From<String> for Meter {
    fn from(s: String) -> Self {
        Meter { repr: s }
    }
}

impl Metric for Meter {
    fn as_metric_str(&self) -> &str {
        &self.repr
    }
}

/// Histograms are values whose distribution is calculated by the server.
///
/// The distribution calculated for histograms is often similar to that of
/// timers. Histograms can be thought of as a more general (not limited to
/// timing things) form of timers.
///
/// See the `Histogrammed` trait for more information.
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
pub struct Histogram {
    repr: String,
}

impl Histogram {
    pub fn new(prefix: &str, key: &str, value: u64) -> Self {
        Self::from(MetricFormatter::histogram(prefix, key, MetricValue::Unsigned(value)).format())
    }

    pub fn new_f64(prefix: &str, key: &str, value: f64) -> Self {
        Self::from(MetricFormatter::histogram(prefix, key, MetricValue::Float(value)).format())
    }
}

impl From<String> for Histogram {
    fn from(s: String) -> Self {
        Histogram { repr: s }
    }
}

impl Metric for Histogram {
    fn as_metric_str(&self) -> &str {
        &self.repr
    }
}

/// Distributions represent a global statistical distribution of a set of values.
///
/// See the `Distributed` trait for more information.
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
pub struct Distribution {
    repr: String,
}

impl Distribution {
    pub fn new(prefix: &str, key: &str, value: u64) -> Self {
        Self::from(MetricFormatter::distribution(prefix, key, MetricValue::Unsigned(value)).format())
    }

    pub fn new_f64(prefix: &str, key: &str, value: f64) -> Self {
        Self::from(MetricFormatter::distribution(prefix, key, MetricValue::Float(value)).format())
    }
}

impl From<String> for Distribution {
    fn from(s: String) -> Self {
        Distribution { repr: s }
    }
}

impl Metric for Distribution {
    fn as_metric_str(&self) -> &str {
        &self.repr
    }
}

/// Sets count the number of unique elements in a group.
///
/// See the `Setted` trait for more information.
#[derive(PartialEq, Eq, Debug, Hash, Clone)]
pub struct Set {
    repr: String,
}

impl Set {
    pub fn new(prefix: &str, key: &str, value: i64) -> Self {
        Self::from(MetricFormatter::set(prefix, key, MetricValue::Signed(value)).format())
    }
}

impl From<String> for Set {
    fn from(s: String) -> Self {
        Set { repr: s }
    }
}

impl Metric for Set {
    fn as_metric_str(&self) -> &str {
        &self.repr
    }
}

/// Potential categories an error from this library falls into.
#[derive(PartialEq, Eq, Debug, Hash, Clone, Copy)]
pub enum ErrorKind {
    InvalidInput,
    IoError,
}

/// Error generated by this library potentially wrapping another
/// type of error (exposed via the `Error` trait).
#[derive(Debug)]
pub struct MetricError {
    repr: ErrorRepr,
}

#[derive(Debug)]
enum ErrorRepr {
    WithDescription(ErrorKind, &'static str),
    IoError(io::Error),
}

impl MetricError {
    /// Return the kind of the error
    pub fn kind(&self) -> ErrorKind {
        match self.repr {
            ErrorRepr::IoError(_) => ErrorKind::IoError,
            ErrorRepr::WithDescription(kind, _) => kind,
        }
    }
}

impl fmt::Display for MetricError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.repr {
            ErrorRepr::IoError(ref err) => err.fmt(f),
            ErrorRepr::WithDescription(_, desc) => desc.fmt(f),
        }
    }
}

impl error::Error for MetricError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self.repr {
            ErrorRepr::IoError(ref err) => Some(err),
            _ => None,
        }
    }

    // Deprecated in 1.42 but we'd like to support it and older versions of
    // Rust where this method wasn't deprecated. There's no easy way to return
    // a `&str` based on the result of `Display` or similar so we're stuck with
    // this API for a while.
    #[allow(deprecated, deprecated_in_future)]
    fn description(&self) -> &str {
        match self.repr {
            ErrorRepr::IoError(ref err) => err.description(),
            ErrorRepr::WithDescription(_, desc) => desc,
        }
    }

    fn cause(&self) -> Option<&dyn error::Error> {
        self.source()
    }
}

impl From<io::Error> for MetricError {
    fn from(err: io::Error) -> MetricError {
        MetricError {
            repr: ErrorRepr::IoError(err),
        }
    }
}

impl From<(ErrorKind, &'static str)> for MetricError {
    fn from((kind, desc): (ErrorKind, &'static str)) -> MetricError {
        MetricError {
            repr: ErrorRepr::WithDescription(kind, desc),
        }
    }
}

pub type MetricResult<T> = Result<T, MetricError>;

#[cfg(test)]
mod tests {
    #![allow(deprecated, deprecated_in_future)]

    use super::{Counter, ErrorKind, Gauge, Histogram, Meter, Metric, MetricError, Set, Timer};
    use std::error::Error;
    use std::io;

    #[test]
    fn test_counter_to_metric_string() {
        let counter = Counter::new("my.app.", "test.counter", 4);
        assert_eq!("my.app.test.counter:4|c", counter.as_metric_str());
    }

    #[test]
    fn test_counter_no_prefix_to_metric_string() {
        let counter = Counter::new("", "test.counter", 4);
        assert_eq!("test.counter:4|c", counter.as_metric_str());
    }

    #[test]
    fn test_timer_to_metric_string() {
        let timer = Timer::new("my.app.", "test.timer", 34);
        assert_eq!("my.app.test.timer:34|ms", timer.as_metric_str());
    }

    #[test]
    fn test_timer_no_prefix_to_metric_string() {
        let timer = Timer::new("", "test.timer", 34);
        assert_eq!("test.timer:34|ms", timer.as_metric_str());
    }

    #[test]
    fn test_gauge_to_metric_string() {
        let gauge = Gauge::new("my.app.", "test.gauge", 2);
        assert_eq!("my.app.test.gauge:2|g", gauge.as_metric_str());
    }

    #[test]
    fn test_gauge_no_prefix_to_metric_string() {
        let gauge = Gauge::new("", "test.gauge", 2);
        assert_eq!("test.gauge:2|g", gauge.as_metric_str());
    }

    #[test]
    fn test_meter_to_metric_string() {
        let meter = Meter::new("my.app.", "test.meter", 5);
        assert_eq!("my.app.test.meter:5|m", meter.as_metric_str());
    }

    #[test]
    fn test_meter_no_prefix_to_metric_string() {
        let meter = Meter::new("", "test.meter", 5);
        assert_eq!("test.meter:5|m", meter.as_metric_str());
    }

    #[test]
    fn test_histogram_to_metric_string() {
        let histogram = Histogram::new("my.app.", "test.histogram", 45);
        assert_eq!("my.app.test.histogram:45|h", histogram.as_metric_str());
    }

    #[test]
    fn test_histogram_no_prefix_to_metric_string() {
        let histogram = Histogram::new("", "test.histogram", 45);
        assert_eq!("test.histogram:45|h", histogram.as_metric_str());
    }

    #[test]
    fn test_set_to_metric_string() {
        let set = Set::new("my.app.", "test.set", 4);
        assert_eq!("my.app.test.set:4|s", set.as_metric_str());
    }

    #[test]
    fn test_set_no_prefix_to_metric_string() {
        let set = Set::new("", "test.set", 4);
        assert_eq!("test.set:4|s", set.as_metric_str());
    }

    #[test]
    fn test_metric_error_kind_io_error() {
        let io_err = io::Error::new(io::ErrorKind::BrokenPipe, "Broken pipe");
        let our_err = MetricError::from(io_err);
        assert_eq!(ErrorKind::IoError, our_err.kind());
    }

    #[test]
    fn test_metric_error_kind_invalid_input() {
        let our_err = MetricError::from((ErrorKind::InvalidInput, "Nope"));
        assert_eq!(ErrorKind::InvalidInput, our_err.kind());
    }

    #[test]
    fn test_metric_error_description_io_error() {
        let io_err = io::Error::new(io::ErrorKind::PermissionDenied, "Permission!");
        let our_err = MetricError::from(io_err);
        assert_eq!("Permission!", our_err.description());
    }

    #[test]
    fn test_metric_error_description_other() {
        let our_err = MetricError::from((ErrorKind::InvalidInput, "Something!"));
        assert_eq!("Something!", our_err.description());
    }

    #[test]
    fn test_metric_error_cause_io_error() {
        let io_err = io::Error::new(io::ErrorKind::TimedOut, "Timeout!");
        let our_err = MetricError::from(io_err);
        assert_eq!("Timeout!", our_err.source().unwrap().description());
    }

    #[test]
    fn test_metric_error_cause_other() {
        let our_err = MetricError::from((ErrorKind::InvalidInput, "Nope!"));
        assert!(our_err.source().is_none());
    }
}