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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// Cadence - An extensible Statsd client for Rust!
//
// Copyright 2018 Philip Jenvey <pjenvey@mozilla.com>
// Copyright 2018 TSH Labs
//
// 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 std::fmt::{self, Write};
use std::marker::PhantomData;
use client::StatsdClient;
use types::{Metric, MetricError, MetricResult};

const DATADOG_TAGS_PREFIX: &str = "|#";

/// Uniform holder for values that knows how to display itself
#[derive(PartialEq, Eq, Debug, Hash, Clone, Copy)]
enum MetricValue {
    Signed(i64),
    Unsigned(u64),
}

impl fmt::Display for MetricValue {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            MetricValue::Signed(i) => i.fmt(f),
            MetricValue::Unsigned(i) => i.fmt(f),
        }
    }
}

/// Type of metric that knows how to display itself
#[derive(PartialEq, Eq, Debug, Hash, Clone, Copy)]
enum MetricType {
    Counter,
    Timer,
    Gauge,
    Meter,
    Histogram,
}

impl fmt::Display for MetricType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            MetricType::Counter => "c".fmt(f),
            MetricType::Timer => "ms".fmt(f),
            MetricType::Gauge => "g".fmt(f),
            MetricType::Meter => "m".fmt(f),
            MetricType::Histogram => "h".fmt(f),
        }
    }
}

#[derive(PartialEq, Eq, Debug, Hash, Clone)]
pub(crate) struct MetricFormatter<'a, T>
where
    T: Metric + From<String>,
{
    metric: PhantomData<T>,
    prefix: &'a str,
    key: &'a str,
    val: MetricValue,
    type_: MetricType,
    tags: Option<Vec<(Option<&'a str>, &'a str)>>,
}

impl<'a, T> MetricFormatter<'a, T>
where
    T: Metric + From<String>,
{
    pub(crate) fn counter(prefix: &'a str, key: &'a str, val: i64) -> Self {
        Self::from_i64(prefix, key, val, MetricType::Counter)
    }

    pub(crate) fn timer(prefix: &'a str, key: &'a str, val: u64) -> Self {
        Self::from_u64(prefix, key, val, MetricType::Timer)
    }

    pub(crate) fn gauge(prefix: &'a str, key: &'a str, val: u64) -> Self {
        Self::from_u64(prefix, key, val, MetricType::Gauge)
    }

    pub(crate) fn meter(prefix: &'a str, key: &'a str, val: u64) -> Self {
        Self::from_u64(prefix, key, val, MetricType::Meter)
    }

    pub(crate) fn histogram(prefix: &'a str, key: &'a str, val: u64) -> Self {
        Self::from_u64(prefix, key, val, MetricType::Histogram)
    }

    fn from_u64(prefix: &'a str, key: &'a str, val: u64, type_: MetricType) -> Self {
        MetricFormatter {
            metric: PhantomData,
            prefix: prefix,
            key: key,
            val: MetricValue::Unsigned(val),
            type_: type_,
            tags: None,
        }
    }

    fn from_i64(prefix: &'a str, key: &'a str, val: i64, type_: MetricType) -> Self {
        MetricFormatter {
            metric: PhantomData,
            prefix: prefix,
            key: key,
            val: MetricValue::Signed(val),
            type_: type_,
            tags: None,
        }
    }

    fn with_tag(&mut self, key: &'a str, value: &'a str) {
        self.tags
            .get_or_insert_with(Vec::new)
            .push((Some(key), value));
    }

    fn with_tag_value(&mut self, value: &'a str) {
        self.tags
            .get_or_insert_with(Vec::new)
            .push((None, value));
    }

    fn write_base_metric(&self, out: &mut String) {
        let _ = write!(
            out,
            "{}.{}:{}|{}",
            self.prefix, self.key, self.val, self.type_
        );
    }

    fn write_tags(&self, out: &mut String) {
        if let Some(tags) = self.tags.as_ref() {
            write_datadog_tags(out, tags);
        }
    }

    fn size_hint(&self) -> usize {
        // Note: This isn't actually the number of bytes required, it's just
        // a guess (♪ this is just a tribute ♪). This is probably sufficient in
        // most cases and guessing is faster than actually doing the math to find
        // the exact number of bytes required.
        //
        // Justification for "10" bytes: the max number of digits we could possibly
        // need for the string representation of our value is 20 (for both u64::MAX
        // and i64::MIN including the minus sign). So, 10 digits covers a pretty
        // large range of values that will actually be seen in practice. Plus, using
        // a constant is faster than computing the `val.log(10)` of our value which
        // we would need to know exactly how many digits it takes up.
        let size = self.prefix.len() + 1 /* . */ + self.key.len()
            + 1 /* : */ + 10 /* see above */ + 1 /* | */ + 2 /* type */;

        if let Some(tags) = self.tags.as_ref() {
            size + datadog_tags_size_hint(tags)
        } else {
            size
        }
    }

    pub(crate) fn build(&self) -> T {
        let mut metric_string = String::with_capacity(self.size_hint());
        self.write_base_metric(&mut metric_string);
        self.write_tags(&mut metric_string);
        T::from(metric_string)
    }
}

/// Internal state of a `MetricBuilder`
///
/// The builder can either be in the process of formatting a metric to send
/// via a client or it can be simply holding on to an error that it will return
/// to a caller when `.send()` is finally invoked.
#[derive(Debug)]
enum BuilderRepr<'m, 'c, T> where T: Metric + From<String> {
    Success(MetricFormatter<'m, T>, &'c StatsdClient),
    Error(MetricError),
}

/// Builder for adding tags to in-progress metrics.
///
/// The only way to instantiate an instance of this builder is via methods in
/// in the `StatsdClient` client.
///
/// This builder adds tags, key-value pairs or just values, to a metric that
/// was previously constructed by a called to method on `StatsdClient`. The
/// tags are added to metrics and sent via the client when `MetricBuilder::send()`
/// is invoked. Adding tags via this builder will typically result in one or
/// more extra heap allocations.
///
/// Any errors countered constructing or validating the metrics will be propagated
/// here through the `::send()` call.
///
/// Currently, only Datadog style tags are supported. For more information on the
/// exact format used, see the
/// [Datadog docs](https://docs.datadoghq.com/developers/dogstatsd/#datagram-format).
///
/// # Example
///
/// An example of how the metric builder is used with a `StatsdClient` instance
/// is given below.
///
/// ```
/// use cadence::prelude::*;
/// use cadence::{StatsdClient, NopMetricSink, Metric};
///
/// let client = StatsdClient::from_sink("some.prefix", NopMetricSink);
/// let res = client.incr_with_tags("some.key")
///    .with_tag("host", "app11.example.com")
///    .with_tag("segment", "23")
///    .with_tag_value("beta")
///    .send();
///
/// assert_eq!(
///     concat!(
///         "some.prefix.some.key:1|c|#",
///         "host:app11.example.com,",
///         "segment:23,",
///         "beta"
///     ),
///     res.unwrap().as_metric_str()
/// );
/// ```
///
/// In this example, two key-value tags and one value tag are added to the
/// metric before it is finally sent to the Statsd server.
#[derive(Debug)]
pub struct MetricBuilder<'m, 'c, T>
where
    T: Metric + From<String>,
{
    repr: BuilderRepr<'m, 'c, T>
}

impl<'m, 'c, T> MetricBuilder<'m, 'c, T>
where
    T: Metric + From<String>,
{
    pub(crate) fn new(formatter: MetricFormatter<'m, T>, client: &'c StatsdClient) -> Self {
        MetricBuilder {
            repr: BuilderRepr::Success(formatter, client)
        }
    }

    pub(crate) fn from_error(err: MetricError) -> Self {
        MetricBuilder {
            repr: BuilderRepr::Error(err)
        }
    }

    /// Add a key-value tag to this metric.
    ///
    /// # Example
    ///
    /// ```
    /// use cadence::prelude::*;
    /// use cadence::{StatsdClient, NopMetricSink, Metric};
    ///
    /// let client = StatsdClient::from_sink("some.prefix", NopMetricSink);
    /// let res = client.decr_with_tags("some.key")
    ///    .with_tag("type", "user-signup")
    ///    .send();
    ///
    /// assert_eq!(
    ///    "some.prefix.some.key:-1|c|#type:user-signup",
    ///    res.unwrap().as_metric_str()
    /// );
    /// ```
    pub fn with_tag(mut self, key: &'m str, value: &'m str) -> Self {
        if let BuilderRepr::Success(ref mut formatter, _) = self.repr {
            formatter.with_tag(key, value);
        }
        self
    }

    /// Add a value tag to this metric.
    ///
    /// # Example
    ///
    /// ```
    /// use cadence::prelude::*;
    /// use cadence::{StatsdClient, NopMetricSink, Metric};
    ///
    /// let client = StatsdClient::from_sink("some.prefix", NopMetricSink);
    /// let res = client.count_with_tags("some.key", 4)
    ///    .with_tag_value("beta-testing")
    ///    .send();
    ///
    /// assert_eq!(
    ///    "some.prefix.some.key:4|c|#beta-testing",
    ///    res.unwrap().as_metric_str()
    /// );
    /// ```
    pub fn with_tag_value(mut self, value: &'m str) -> Self {
        if let BuilderRepr::Success(ref mut formatter, _) = self.repr {
            formatter.with_tag_value(value);
        }
        self
    }

    /// Send a metric using the client that created this builder.
    ///
    /// Note that the builder is consumed by this method and thus `.send()` can
    /// only be called a single time per builder.
    ///
    /// # Example
    ///
    /// ```
    /// use cadence::prelude::*;
    /// use cadence::{StatsdClient, NopMetricSink, Metric};
    ///
    /// let client = StatsdClient::from_sink("some.prefix", NopMetricSink);
    /// let res = client.gauge_with_tags("some.key", 7)
    ///    .with_tag("test-segment", "12345")
    ///    .send();
    ///
    /// assert_eq!(
    ///    "some.prefix.some.key:7|g|#test-segment:12345",
    ///    res.unwrap().as_metric_str()
    /// );
    /// ```
    pub fn send(self) -> MetricResult<T> {
        match self.repr {
            BuilderRepr::Error(err) => Err(err),
            BuilderRepr::Success(ref formatter, client) => {
                let metric: T = formatter.build();
                client.send_metric(&metric)?;
                Ok(metric)
            }
        }
    }
}

fn datadog_tags_size_hint(tags: &[(Option<&str>, &str)]) -> usize {
    // enough space for prefix, tags/: separators and commas
    let kv_size: usize = tags.iter()
        .map(|tag| {
            tag.0.map_or(0, |k| k.len() + 1) // +1 for : separator
             + tag.1.len()
        })
        .sum();
    DATADOG_TAGS_PREFIX.len() + kv_size + tags.len() - 1
}

fn write_datadog_tags(metric: &mut String, tags: &[(Option<&str>, &str)]) {
    metric.push_str(DATADOG_TAGS_PREFIX);
    for (i, &(key, value)) in tags.iter().enumerate() {
        if i > 0 {
            metric.push(',');
        }
        if let Some(key) = key {
            metric.push_str(key);
            metric.push(':');
        }
        metric.push_str(value);
    }
}

#[cfg(test)]
mod tests {
    use types::{Counter, Gauge, Histogram, Meter, Metric, Timer};
    use super::{write_datadog_tags, MetricFormatter};

    #[test]
    fn test_metric_formatter_counter_no_tags() {
        let fmt = MetricFormatter::counter("prefix", "some.key", 4);
        let counter: Counter = fmt.build();

        assert_eq!("prefix.some.key:4|c", counter.as_metric_str());
    }

    #[test]
    fn test_metric_formatter_counter_with_tags() {
        let mut fmt = MetricFormatter::counter("prefix", "some.key", 4);
        fmt.with_tag("host", "app03.example.com");
        fmt.with_tag("bucket", "2");
        fmt.with_tag_value("beta");

        let counter: Counter = fmt.build();

        assert_eq!(
            concat!(
                "prefix.some.key:4|c|#",
                "host:app03.example.com,",
                "bucket:2,",
                "beta",
            ),
            counter.as_metric_str()
        );
    }

    #[test]
    fn test_metric_formatter_timer_no_tags() {
        let fmt = MetricFormatter::timer("prefix", "some.method", 21);
        let timer: Timer = fmt.build();

        assert_eq!("prefix.some.method:21|ms", timer.as_metric_str());
    }

    #[test]
    fn test_metric_formatter_timer_with_tags() {
        let mut fmt = MetricFormatter::timer("prefix", "some.method", 21);
        fmt.with_tag("app", "metrics");
        fmt.with_tag_value("async");

        let timer: Timer = fmt.build();

        assert_eq!(
            "prefix.some.method:21|ms|#app:metrics,async",
            timer.as_metric_str()
        );
    }

    #[test]
    fn test_metric_formatter_gauge_no_tags() {
        let fmt = MetricFormatter::gauge("prefix", "num.failures", 7);
        let gauge: Gauge = fmt.build();

        assert_eq!("prefix.num.failures:7|g", gauge.as_metric_str());
    }

    #[test]
    fn test_metric_formatter_gauge_with_tags() {
        let mut fmt = MetricFormatter::gauge("prefix", "num.failures", 7);
        fmt.with_tag("window", "300");
        fmt.with_tag_value("best-effort");

        let gauge: Gauge = fmt.build();

        assert_eq!(
            "prefix.num.failures:7|g|#window:300,best-effort",
            gauge.as_metric_str()
        );
    }

    #[test]
    fn test_metric_formatter_meter_no_tags() {
        let fmt = MetricFormatter::meter("prefix", "user.logins", 3);
        let meter: Meter = fmt.build();

        assert_eq!("prefix.user.logins:3|m", meter.as_metric_str());
    }

    #[test]
    fn test_metric_formatter_meter_with_tags() {
        let mut fmt = MetricFormatter::meter("prefix", "user.logins", 3);
        fmt.with_tag("user-type", "verified");
        fmt.with_tag_value("bucket1");

        let meter: Meter = fmt.build();

        assert_eq!(
            "prefix.user.logins:3|m|#user-type:verified,bucket1",
            meter.as_metric_str()
        );
    }

    #[test]
    fn test_metric_formatter_histogram_no_tags() {
        let fmt = MetricFormatter::histogram("prefix", "num.results", 44);
        let histogram: Histogram = fmt.build();

        assert_eq!("prefix.num.results:44|h", histogram.as_metric_str());
    }

    #[test]
    fn test_metric_formatter_histogram_with_tags() {
        let mut fmt = MetricFormatter::histogram("prefix", "num.results", 44);
        fmt.with_tag("user-type", "authenticated");
        fmt.with_tag_value("source=search");

        let histogram: Histogram = fmt.build();

        assert_eq!(
            concat!(
                "prefix.num.results:44|h|#",
                "user-type:authenticated,",
                "source=search"
            ),
            histogram.as_metric_str()
        );
    }

    #[test]
    fn test_write_datadog_tags() {
        let mut m = String::from("some.counter:1|c");
        write_datadog_tags(&mut m, &vec![(Some("host"), "app01.example.com")]);
        assert_eq!(m, "some.counter:1|c|#host:app01.example.com");

        let mut m = String::new();
        write_datadog_tags(
            &mut m,
            &vec![
                (Some("host"), "app01.example.com"),
                (Some("bucket"), "A"),
                (None, "file-server"),
            ],
        );
        assert_eq!(m, "|#host:app01.example.com,bucket:A,file-server",);
    }
}