gnort 0.2.0

Datadog statsd client library that provides efficient in-process metrics aggregation
Documentation
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
use std::{collections::BTreeSet, marker::PhantomData};

use dogstatsd::DogstatsdResult;
use maplit::btreeset;

use crate::{
    instrument::{Count, Gauge, Instrument, TimingCount},
    GnortClient,
};

#[allow(non_snake_case)]
pub mod MetricType {
    /// Implemented exclusively by members of this phantom type enum
    /// This is for use as a trait bound
    pub trait Impl {
        fn name() -> String;
    }
    /// Count
    #[derive(Copy, Clone)]
    pub enum Count {}
    impl Impl for Count {
        fn name() -> String {
            "count".to_string()
        }
    }

    /// Gauge
    #[derive(Copy, Clone)]
    pub enum Gauge {}
    impl Impl for Gauge {
        fn name() -> String {
            "gauge".to_string()
        }
    }

    /// TimingCount
    #[derive(Copy, Clone)]
    pub enum TimingCount {}
    impl Impl for TimingCount {
        fn name() -> String {
            "timing_count".to_string()
        }
    }
}

#[derive(Clone)]
pub struct MetricName<'a, T: MetricType::Impl>(&'a str, PhantomData<T>);
impl<'a, T: MetricType::Impl> MetricName<'a, T> {
    pub const fn new(name: &'a str) -> Self {
        Self(name, PhantomData)
    }
    pub fn get_name(&self) -> &'a str {
        self.0
    }
}

impl<'a> MetricName<'a, MetricType::Count> {
    pub const fn count(name: &'a str) -> Self {
        Self(name, PhantomData)
    }
}
impl<'a> MetricName<'a, MetricType::Gauge> {
    pub const fn gauge(name: &'a str) -> Self {
        Self(name, PhantomData)
    }
}
impl<'a> MetricName<'a, MetricType::TimingCount> {
    pub const fn timing_count(name: &'a str) -> Self {
        Self(name, PhantomData)
    }
    // This is an alias so the generic paste macro doesn't have to get weird.
    // pub const fn timingcount(name: &'a str) -> Self {
    //     Self::timing_count(name)
    // }
}

impl From<MetricName<'static, MetricType::Count>> for Metric<MetricType::Count> {
    fn from(m: MetricName<'static, MetricType::Count>) -> Metric<MetricType::Count> {
        Metric::new_count(m)
    }
}

impl<T: MetricType::Impl> From<MetricName<'static, T>> for &'static str {
    fn from(m: MetricName<'static, T>) -> Self {
        m.0
    }
}

impl From<MetricName<'static, MetricType::Gauge>> for Metric<MetricType::Gauge> {
    fn from(m: MetricName<'static, MetricType::Gauge>) -> Metric<MetricType::Gauge> {
        Metric::new_gauge(m)
    }
}

impl From<MetricName<'static, MetricType::TimingCount>> for Metric<MetricType::TimingCount> {
    fn from(m: MetricName<'static, MetricType::TimingCount>) -> Metric<MetricType::TimingCount> {
        Metric::new_timing_count(m)
    }
}

// TODO: Histogram/Distribution is needed before we can do non-count timings
#[derive(Clone, Debug, Default, Hash, PartialEq, Eq)]
pub struct Metric<T: MetricType::Impl> {
    /// Name of the metric, called stat in dogstatsd
    metric_name: &'static str,
    /// What kind of metric is it?
    metric_type: PhantomData<T>,
    /// Tags for the metric
    metric_tags: BTreeSet<String>,
    // metric_tags: &'static [&'static str],
}

impl From<&'static str> for Metric<MetricType::Count> {
    // Default metrics derived from bare names to counts
    fn from(metric_name: &'static str) -> Metric<MetricType::Count> {
        Metric::new_count(MetricName::count(metric_name))
    }
}

impl From<&'static str> for Metric<MetricType::Gauge> {
    // Default metrics derived from bare names to counts
    fn from(metric_name: &'static str) -> Metric<MetricType::Gauge> {
        Metric::new_gauge(MetricName::gauge(metric_name))
    }
}

impl From<&'static str> for Metric<MetricType::TimingCount> {
    // Default metrics derived from bare names to counts
    fn from(metric_name: &'static str) -> Metric<MetricType::TimingCount> {
        Metric::new_timing_count(MetricName::timing_count(metric_name))
    }
}

impl Metric<MetricType::Count> {
    pub fn new_count(metric_name: MetricName<'static, MetricType::Count>) -> Self {
        Self {
            metric_name: metric_name.into(),
            // metric_tags: &[],
            metric_tags: btreeset![],
            metric_type: PhantomData,
        }
    }
    pub fn adhoc_count(
        &self,
        client: &GnortClient,
        count: i64,
        adhoc_tags: BTreeSet<String>,
    ) -> DogstatsdResult {
        let emission_tags = self.metric_tags.union(&adhoc_tags);
        client.count(self.metric_name, count, emission_tags)
    }
}

impl Metric<MetricType::Gauge> {
    pub fn new_gauge(metric_name: MetricName<'static, MetricType::Gauge>) -> Self {
        Self {
            metric_name: metric_name.into(),
            metric_tags: btreeset![],
            metric_type: PhantomData,
        }
    }
    pub fn adhoc_gauge(
        &self,
        client: &GnortClient,
        value: f64,
        adhoc_tags: BTreeSet<String>,
    ) -> DogstatsdResult {
        let emission_tags = self.metric_tags.union(&adhoc_tags);
        client.gauge(self.metric_name, value.to_string(), emission_tags)
    }
}

impl Metric<MetricType::TimingCount> {
    pub fn new_timing_count(metric_name: MetricName<'static, MetricType::TimingCount>) -> Self {
        Self {
            metric_name: metric_name.into(),
            metric_tags: btreeset![],
            metric_type: PhantomData,
        }
    }
    pub fn adhoc_timing_count(
        &self,
        client: &GnortClient,
        sum: i64,
        count: i64,
        adhoc_tags: BTreeSet<String>,
    ) -> DogstatsdResult {
        let emission_tags = self.metric_tags.union(&adhoc_tags);
        client.count(self.metric_name, sum, emission_tags.clone())?;
        client.count(self.metric_name, count, emission_tags)
    }
}

#[allow(dead_code)]
impl<T: MetricType::Impl + MakeInstrument> Metric<T> {
    pub fn make_instrument(&self) -> T::InstrumentType {
        <T as MakeInstrument>::make_instrument()
    }
    pub fn with_tags<I, S>(self, metric_tags: I) -> Self
    where
        S: AsRef<str>,
        I: IntoIterator<Item = S>,
    {
        let metric_tags: BTreeSet<String> = metric_tags
            .into_iter()
            .map(|t| t.as_ref().to_string())
            .collect();
        Self {
            metric_tags,
            ..self
        }
    }
    pub fn with_array_tags<S, const N: usize>(self, metric_tags: [S; N]) -> Self
    where
        S: AsRef<str> + Into<String>,
    {
        let metric_tags: BTreeSet<String> = metric_tags.into_iter().map(|t| t.into()).collect();
        Self {
            metric_tags,
            ..self
        }
    }
    pub fn with_vec_tags(self, metric_tags: Vec<String>) -> Self {
        let metric_tags: BTreeSet<String> = metric_tags.into_iter().map(|t| t).collect();
        Self {
            metric_tags,
            ..self
        }
    }
    pub fn with_set_tags(self, metric_tags: BTreeSet<String>) -> Self {
        Self {
            metric_tags,
            ..self
        }
    }
    pub fn get_name(&self) -> &'static str {
        self.metric_name
    }
    pub fn get_tags(&self) -> &BTreeSet<String> {
        &self.metric_tags
    }
}

pub trait MakeInstrument {
    type InstrumentType;
    fn make_instrument() -> Self::InstrumentType;
}

impl MakeInstrument for MetricType::Count {
    type InstrumentType = Count;
    fn make_instrument() -> Self::InstrumentType {
        Instrument::count()
    }
}

impl MakeInstrument for MetricType::Gauge {
    type InstrumentType = Gauge;
    fn make_instrument() -> Self::InstrumentType {
        Instrument::gauge()
    }
}

impl MakeInstrument for MetricType::TimingCount {
    type InstrumentType = TimingCount;
    fn make_instrument() -> Self::InstrumentType {
        Instrument::timing_count()
    }
}

/// Type-erased Metric type for the metric map
#[derive(Clone, Debug, Default, Hash, PartialEq, Eq)]
pub(crate) struct MetricKey {
    /// Name of the metric, called stat in dogstatsd
    metric_name: &'static str,
    /// Tags for the metric
    metric_tags: BTreeSet<String>,
}

impl MetricKey {
    pub fn new(metric_name: &'static str, metric_tags: BTreeSet<String>) -> Self {
        Self {
            metric_name,
            metric_tags,
        }
    }
    pub fn get_name(&self) -> &'static str {
        self.metric_name
    }
    pub fn get_tags(&self) -> &BTreeSet<String> {
        &self.metric_tags
    }
}

impl<T: MetricType::Impl> From<Metric<T>> for MetricKey {
    fn from(m: Metric<T>) -> MetricKey {
        MetricKey::new(m.metric_name, m.metric_tags)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{
        adhoc_metrics_struct, metric, metrics_module, metrics_struct, MetricRegistrationError,
        MetricsRegistry, RegistryConfig,
    };

    metric!(TEST_COUNT_METRIC, "gnort.test.bench.incr", Count);
    metric!(TEST_GAUGE_METRIC, "gnort.test.bench.gauge", Gauge);
    metric!(
        TEST_TIMING_COUNT_METRIC,
        "gnort.test.bench.timing_count",
        TimingCount
    );

    metrics_struct![
        TaglessMetrics,
        (test_count, "gnort.test.bench.count", Count),
        // You can have multiple metrics with the same name as long as the tags are different.
        (_test_count_success, "gnort.test.commit.count", Count),
        (test_gauge, "gnort.test.bench.gauge", Gauge),
        (
            test_timing_count,
            "gnort.test.bench.timing_count",
            TimingCount
        )
    ];

    // Should be able to mix and match tags and no tags.
    metrics_struct![
        TestMetrics,
        (test_count, "gnort.test.bench.count", Count),
        // You can have multiple metrics with the same name as long as the tags are different.
        (
            _test_count_success,
            "gnort.test.commit.count",
            Count,
            ["outcome:success"]
        ),
        (
            _test_count_failure,
            "gnort.test.commit.count",
            Count,
            ["outcome:failure"]
        ),
        (test_gauge, "gnort.test.bench.gauge", Gauge),
        (
            test_timing_count,
            "gnort.test.bench.timing_count",
            TimingCount
        )
    ];

    #[test]
    fn test_metrics_macros() {
        let registry = MetricsRegistry::new(RegistryConfig::default());
        let test_metrics = TestMetrics::register(&registry).expect("Failed to register metrics!");
        assert_eq!(TEST_COUNT_METRIC.get_name(), "gnort.test.bench.incr");
        assert_eq!(TEST_GAUGE_METRIC.get_name(), "gnort.test.bench.gauge");
        assert_eq!(
            TEST_TIMING_COUNT_METRIC.get_name(),
            "gnort.test.bench.timing_count"
        );
        assert_eq!(test_metrics.test_count.increment(), 0);
        assert_eq!(test_metrics.test_count.increment(), 1);
        assert_eq!(test_metrics.test_gauge.swap(5.5), 0.0);
        assert_eq!(test_metrics.test_gauge.swap(6.5), 5.5);
        assert_eq!(
            test_metrics
                .test_timing_count
                .add_timing(&std::time::Duration::from_secs(5)),
            (0, 0)
        );
        // microseconds is the default unit of time
        assert_eq!(
            test_metrics
                .test_timing_count
                .add_timing(&std::time::Duration::from_secs(10)),
            (5_000, 1)
        );
    }

    #[test]
    fn test_tagless_metrics() {
        let registry = MetricsRegistry::new(RegistryConfig::default());
        let test_metrics =
            TaglessMetrics::register(&registry).expect("Failed to register metrics!");
        assert_eq!(test_metrics.test_count.increment(), 0);
        assert_eq!(test_metrics.test_count.increment(), 1);
        assert_eq!(test_metrics.test_gauge.swap(5.5), 0.0);
        assert_eq!(test_metrics.test_gauge.swap(6.5), 5.5);
        assert_eq!(
            test_metrics
                .test_timing_count
                .add_timing(&std::time::Duration::from_secs(5)),
            (0, 0)
        );
        assert_eq!(
            test_metrics
                .test_timing_count
                .add_timing(&std::time::Duration::from_secs(10)),
            (5_000, 1)
        );
    }

    metrics_module![
        test_module,
        (test_count, "gnort.test.bench.count", Count),
        // You can have multiple metrics with the same name as long as the tags are different.
        (_test_count_success, "gnort.test.commit.count", Count),
        (test_gauge, "gnort.test.bench.gauge", Gauge),
        (
            test_timing_count,
            "gnort.test.bench.timing_count",
            TimingCount
        )
    ];

    #[test]
    fn test_module_metrics() {
        let registry = MetricsRegistry::new(RegistryConfig::default());
        let test_instruments =
            test_module::Instruments::register(&registry).expect("Failed to register metrics!");
        assert_eq!(test_instruments.test_count.increment(), 0);
        assert_eq!(test_instruments.test_gauge.swap(5.5), 0.0);
        assert_eq!(
            test_instruments
                .test_timing_count
                .add_timing(&std::time::Duration::from_secs(5)),
            (0, 0)
        );

        let registry = MetricsRegistry::new(RegistryConfig::default());
        let mut test_metrics = test_module::Metrics::new();
        test_metrics.test_count = test_metrics.test_count.with_tags(vec!["outcome:cornholio"]);
        let test_instruments = test_metrics.register(&registry).unwrap();
        assert_eq!(test_instruments.test_count.increment(), 0);
        assert_eq!(test_instruments.test_gauge.swap(5.5), 0.0);
        assert_eq!(
            test_instruments
                .test_timing_count
                .add_timing(&std::time::Duration::from_secs(5)),
            (0, 0)
        );
    }

    adhoc_metrics_struct![
        TestAdhocMetrics,
        (test_count, "gnort.test.bench.count", Count),
        // You can have multiple metrics with the same name as long as the tags are different.
        (
            test_count_success,
            "gnort.test.commit.count",
            Count,
            ["outcome:success"]
        ),
        (
            test_count_failure,
            "gnort.test.commit.count",
            Count,
            ["outcome:failure"]
        )
    ];

    #[test]
    fn test_metrics_name_macro() {
        // Don't need to register, you'd usually use this with the ad-hoc client
        let test_name_metrics = TestAdhocMetrics::new();
        assert_eq!(
            test_name_metrics.test_count.get_name(),
            "gnort.test.bench.count"
        );
        assert_eq!(
            test_name_metrics.test_count_success.get_name(),
            "gnort.test.commit.count"
        );
        assert_eq!(
            test_name_metrics.test_count_failure.get_name(),
            "gnort.test.commit.count"
        );
    }
}