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
//! This is an opinionated library to share code and approach to Datadog logging in prima.it
//!
//! ### Getting started
//!
//! You need to call [Datadog::init] in your main binary, and to do so you'll need as argument a type that implements the [Configuration] trait.
//! If you never call [Datadog::init] in your binary NO metrics will be sent.
//!
//! Inside the [configuration] you'll find an [implementation of this trait][configuration::PrimaConfiguration] tailored for prima.it needs.
//!
//! ```
//! use prima_datadog::{*, configuration::PrimaConfiguration};
//!
//! // initializes the PrimaConfiguration struct
//! let configuration = PrimaConfiguration::new(
//!     "0.0.0.0:1234", // to address
//!     "0.0.0.0:0", // from address
//!     "service_name", // namespace for all metrics
//!     "production".parse().unwrap() // environment
//! );
//!
//! // Initializes a Datadog instance
//! Datadog::init(configuration);
//! ```
//!
//! Then you can use the macros exposed at the base level of the module.
//! All macros accepts
//! - a string value or a path to a type that implements AsRef<str> as first argument.
//! - zero or more arguments, separated by comma `,`, for the metrics that needs more data.
//!     For example `count!` and `timing!` accepts a number while `service_check!` accepts a [ServiceStatus] and a [ServiceCheckOptions]
//! - a list of tags (which is separated from the rest of the arguments by semicolon `;`) in the form of `"name" => "value"`
//!
//! ```
//! # use prima_datadog::{*, configuration::PrimaConfiguration};
//! # let configuration = PrimaConfiguration::new(
//! #     "0.0.0.0:1234", // to address
//! #     "0.0.0.0:0", // from address
//! #     "service_name", // namespace for all metrics
//! #     "production".parse().unwrap() // environment
//! # );
//! # Datadog::init(configuration);
//! incr!("test");
//! # incr!("test"; "some" => "data");
//! # decr!("test");
//! decr!("test"; "some" => "data");
//! count!("test", 20);
//! count!("test", 10; "some" => "data");
//! time!("test", || { println!("expensive computation");});
//! time!("test", || { println!("expensive computation");}; "some" => "data");
//! # timing!("test", 20);
//! timing!("test", 20; "some" => "data");
//! # gauge!("test", "gauge value");
//! gauge!("test", "gauge value"; "some" => "data");
//! # histogram!("test", "histogram value");
//! histogram!("test", "histogram value"; "some" => "data");
//! # distribution!("test", "distribution value");
//! distribution!("test", "distribution value"; "some" => "data");
//! # set!("test", "set value");
//! set!("test", "set value"; "some" => "data");
//! service_check!("test", ServiceStatus::OK);
//! service_check!("test", ServiceStatus::OK, ServiceCheckOptions::default());
//! # event!("test", "test event");
//! event!("test", "test event"; "some" => "data");
//! ```
//!
//! This is an example of a custom metric, in this case based on an enum type, but it can really be whatever you want, as long as it implements AsRef<str>
//!
//! ```
//! # use prima_datadog::{*, configuration::PrimaConfiguration};
//! # let configuration = PrimaConfiguration::new(
//! #     "0.0.0.0:1234", // to address
//! #     "0.0.0.0:0", // from address
//! #     "service_name", // namespace for all metrics
//! #     "production".parse().unwrap() // environment
//! # );
//! # Datadog::init(configuration);
//! enum Metric {
//!     John,
//!     Paul,
//!     George,
//!     Ringo,
//! }
//!
//! impl AsRef<str> for Metric {
//!     fn as_ref(&self) -> &str {
//!         match self {
//!             Metric::John => "john",
//!             Metric::Paul => "paul",
//!             Metric::George => "george",
//!             Metric::Ringo => "ringo",
//!         }
//!     }
//! }
//!
//! // now you can do
//! incr!(Metric::John; "play" => "guitar");
//! incr!(Metric::Paul; "play" => "bass");
//! incr!(Metric::George; "play" => "sitar");
//! incr!(Metric::Ringo; "play" => "drums");
//! ```
//!
//! ## References
//!
//!   - [Datadog docs](https://docs.datadoghq.com/getting_started/)
//!   - [Getting started with Datadog tags](https://docs.datadoghq.com/getting_started/tagging/)
#![doc(issue_tracker_base_url = "https://github.com/primait/prima_datadog.rs/issues")]

pub use dogstatsd::{ServiceCheckOptions, ServiceStatus};
use once_cell::sync::OnceCell;

pub use client::DogstatsdClient;
pub use macros::*;

use crate::configuration::Configuration;
use crate::error::Error;

mod client;
pub mod configuration;
pub mod error;
mod macros;

#[cfg(test)]
#[path = "tests/mod.rs"]
mod tests;

static INSTANCE: OnceCell<Datadog> = OnceCell::new();

/// The Datadog struct is the main entry point for the library
pub struct Datadog {
    /// an instance of a dogstatsd::Client
    client: Box<dyn DogstatsdClient + Send + Sync>,
    /// tells if metric should be reported. If false, nothing is sent to the udp socket.
    is_reporting_enabled: bool,
}

impl Datadog {
    /// Initializes a Datadog instance with a struct that implements the [Configuration] trait.
    /// Make sure that you run it only once otherwise you will get an error.
    pub fn init(configuration: impl Configuration) -> Result<(), Error> {
        let mut initialized: bool = false;

        // the closure is guaranteed to execute only once
        let _ = INSTANCE.get_or_try_init::<_, Error>(|| {
            initialized = true;

            let dogstatsd_client_options: dogstatsd::Options = dogstatsd::Options::new(
                configuration.from_addr(),
                configuration.to_addr(),
                configuration.namespace(),
                configuration.default_tags(),
            );

            let client: dogstatsd::Client = dogstatsd::Client::new(dogstatsd_client_options)?;
            Ok(Self::new(client, configuration.is_reporting_enabled()))
        })?;

        if initialized {
            Ok(())
        } else {
            Err(Error::OnceCellAlreadyInitialized)
        }
    }

    fn new(client: impl 'static + DogstatsdClient + Send + Sync, is_reporting_enabled: bool) -> Self {
        Self {
            client: Box::new(client),
            is_reporting_enabled,
        }
    }

    /// Increment a StatsD counter
    pub fn incr(metric: impl AsRef<str>, tags: impl IntoIterator<Item = String>) {
        if let Some(instance) = INSTANCE.get() {
            instance.do_incr(metric.as_ref(), tags.into_iter().collect::<Vec<String>>());
        }
    }

    pub(crate) fn do_incr(&self, metric: impl AsRef<str>, tags: impl IntoIterator<Item = String>) {
        if self.is_reporting_enabled {
            self.client
                .incr(metric.as_ref(), tags.into_iter().collect::<Vec<String>>());
        }
    }

    /// Decrement a StatsD counter
    pub fn decr(metric: impl AsRef<str>, tags: impl IntoIterator<Item = String>) {
        if let Some(instance) = INSTANCE.get() {
            instance.do_decr(metric.as_ref(), tags.into_iter().collect::<Vec<String>>());
        }
    }

    pub(crate) fn do_decr(&self, metric: impl AsRef<str>, tags: impl IntoIterator<Item = String>) {
        if self.is_reporting_enabled {
            self.client
                .decr(metric.as_ref(), tags.into_iter().collect::<Vec<String>>());
        }
    }

    /// Make an arbitrary change to a StatsD counter
    pub fn count(metric: impl AsRef<str>, count: i64, tags: impl IntoIterator<Item = String>) {
        if let Some(instance) = INSTANCE.get() {
            instance.do_count(metric.as_ref(), count, tags.into_iter().collect::<Vec<String>>());
        }
    }

    pub(crate) fn do_count(&self, metric: impl AsRef<str>, count: i64, tags: impl IntoIterator<Item = String>) {
        if self.is_reporting_enabled {
            self.client
                .count(metric.as_ref(), count, tags.into_iter().collect::<Vec<String>>());
        }
    }

    /// Time a block of code (reports in ms)
    pub fn time(metric: impl AsRef<str>, tags: impl IntoIterator<Item = String>, block: impl FnOnce() + 'static) {
        if let Some(instance) = INSTANCE.get() {
            instance.do_time(
                metric.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
                Box::new(block),
            );
        }
    }

    pub(crate) fn do_time(
        &self,
        metric: impl AsRef<str>,
        tags: impl IntoIterator<Item = String>,
        block: impl FnOnce() + 'static,
    ) {
        if self.is_reporting_enabled {
            self.client.time(
                metric.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
                Box::new(block),
            );
        }
    }

    /// Send your own timing metric in milliseconds
    pub fn timing(metric: impl AsRef<str>, ms: i64, tags: impl IntoIterator<Item = String>) {
        if let Some(instance) = INSTANCE.get() {
            instance.do_timing(metric.as_ref(), ms, tags.into_iter().collect::<Vec<String>>());
        }
    }

    pub(crate) fn do_timing(&self, metric: impl AsRef<str>, ms: i64, tags: impl IntoIterator<Item = String>) {
        if self.is_reporting_enabled {
            self.client
                .timing(metric.as_ref(), ms, tags.into_iter().collect::<Vec<String>>());
        }
    }

    /// Report an arbitrary value as a gauge
    pub fn gauge(metric: impl AsRef<str>, value: impl AsRef<str>, tags: impl IntoIterator<Item = String>) {
        if let Some(instance) = INSTANCE.get() {
            instance.do_gauge(
                metric.as_ref(),
                value.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
            );
        }
    }

    pub(crate) fn do_gauge(
        &self,
        metric: impl AsRef<str>,
        value: impl AsRef<str>,
        tags: impl IntoIterator<Item = String>,
    ) {
        if self.is_reporting_enabled {
            self.client.gauge(
                metric.as_ref(),
                value.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
            );
        }
    }

    /// Report a value in a histogram
    pub fn histogram(metric: impl AsRef<str>, value: impl AsRef<str>, tags: impl IntoIterator<Item = String>) {
        if let Some(instance) = INSTANCE.get() {
            instance.do_histogram(
                metric.as_ref(),
                value.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
            );
        }
    }

    pub(crate) fn do_histogram(
        &self,
        metric: impl AsRef<str>,
        value: impl AsRef<str>,
        tags: impl IntoIterator<Item = String>,
    ) {
        if self.is_reporting_enabled {
            self.client.histogram(
                metric.as_ref(),
                value.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
            );
        }
    }

    /// Report a value in a distribution
    pub fn distribution(metric: impl AsRef<str>, value: impl AsRef<str>, tags: impl IntoIterator<Item = String>) {
        if let Some(instance) = INSTANCE.get() {
            instance.do_distribution(
                metric.as_ref(),
                value.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
            );
        }
    }

    pub(crate) fn do_distribution(
        &self,
        metric: impl AsRef<str>,
        value: impl AsRef<str>,
        tags: impl IntoIterator<Item = String>,
    ) {
        if self.is_reporting_enabled {
            self.client.distribution(
                metric.as_ref(),
                value.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
            );
        }
    }

    /// Report a value in a set
    pub fn set(metric: impl AsRef<str>, value: impl AsRef<str>, tags: impl IntoIterator<Item = String>) {
        if let Some(instance) = INSTANCE.get() {
            instance.do_set(
                metric.as_ref(),
                value.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
            );
        }
    }

    pub(crate) fn do_set(
        &self,
        metric: impl AsRef<str>,
        value: impl AsRef<str>,
        tags: impl IntoIterator<Item = String>,
    ) {
        if self.is_reporting_enabled {
            self.client.set(
                metric.as_ref(),
                value.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
            );
        }
    }

    /// Report the status of a service
    pub fn service_check(
        metric: impl AsRef<str>,
        value: ServiceStatus,
        tags: impl IntoIterator<Item = String>,
        options: Option<ServiceCheckOptions>,
    ) {
        if let Some(instance) = INSTANCE.get() {
            instance.do_service_check(
                metric.as_ref(),
                value,
                tags.into_iter().collect::<Vec<String>>(),
                options,
            );
        }
    }

    pub(crate) fn do_service_check(
        &self,
        metric: impl AsRef<str>,
        value: ServiceStatus,
        tags: impl IntoIterator<Item = String>,
        options: Option<ServiceCheckOptions>,
    ) {
        if self.is_reporting_enabled {
            self.client.service_check(
                metric.as_ref(),
                value,
                tags.into_iter().collect::<Vec<String>>(),
                options,
            );
        }
    }

    /// Send a custom event as a title and a body
    pub fn event(metric: impl AsRef<str>, text: impl AsRef<str>, tags: impl IntoIterator<Item = String>) {
        if let Some(instance) = INSTANCE.get() {
            instance.do_event(
                metric.as_ref(),
                text.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
            );
        }
    }

    pub(crate) fn do_event(
        &self,
        metric: impl AsRef<str>,
        text: impl AsRef<str>,
        tags: impl IntoIterator<Item = String>,
    ) {
        if self.is_reporting_enabled {
            self.client.event(
                metric.as_ref(),
                text.as_ref(),
                tags.into_iter().collect::<Vec<String>>(),
            );
        }
    }
}