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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
//! A Rust client for interacting with Dogstatsd
//!
//! Dogstatsd is a custom `StatsD` implementation by `DataDog` for sending metrics and events to their
//! system. Through this client you can report any type of metric you want, tag it, and enjoy your
//! custom metrics.
//!
//! ## Usage
//!
//! Build an options struct and create a client:
//!
//! ```
//! use dogstatsd::{Client, Options, OptionsBuilder};
//!
//! // Binds to a udp socket on an available ephemeral port on 127.0.0.1 for
//! // transmitting, and sends to  127.0.0.1:8125, the default dogstatsd
//! // address.
//! let default_options = Options::default();
//! let default_client = Client::new(default_options).unwrap();
//!
//! // Binds to 127.0.0.1:9000 for transmitting and sends to 10.1.2.3:8125, with a
//! // namespace of "analytics".
//! let custom_options = Options::new("127.0.0.1:9000", "10.1.2.3:8125", "analytics", vec!(String::new()));
//! let custom_client = Client::new(custom_options).unwrap();
//!
//! // You can also use the OptionsBuilder API to avoid needing to specify every option.
//! let built_options = OptionsBuilder::new().from_addr(String::from("127.0.0.1:9001")).build();
//! let built_client = Client::new(built_options).unwrap();
//! ```
//!
//! Start sending metrics:
//!
//! ```
//! use dogstatsd::{Client, Options, ServiceCheckOptions, ServiceStatus};
//!
//! let client = Client::new(Options::default()).unwrap();
//! let tags = &["env:production"];
//!
//! // Increment a counter
//! client.incr("my_counter", tags).unwrap();
//!
//! // Decrement a counter
//! client.decr("my_counter", tags).unwrap();
//!
//! // Time a block of code (reports in ms)
//! client.time("my_time", tags, || {
//!     // Some time consuming code
//! }).unwrap();
//!
//! // Report your own timing in ms
//! client.timing("my_timing", 500, tags).unwrap();
//!
//! // Report an arbitrary value (a gauge)
//! client.gauge("my_gauge", "12345", tags).unwrap();
//!
//! // Report a sample of a histogram
//! client.histogram("my_histogram", "67890", tags).unwrap();
//!
//! // Report a sample of a distribution
//! client.distribution("distribution", "67890", tags).unwrap();
//!
//! // Report a member of a set
//! client.set("my_set", "13579", tags).unwrap();
//!
//! // Report a service check
//! let service_check_options = ServiceCheckOptions {
//!   hostname: Some("my-host.localhost"),
//!   ..Default::default()
//! };
//! client.service_check("redis.can_connect", ServiceStatus::OK, tags, Some(service_check_options)).unwrap();
//!
//! // Send a custom event
//! client.event("My Custom Event Title", "My Custom Event Body", tags).unwrap();
//! ```

#![cfg_attr(feature = "unstable", feature(test))]
#![deny(
    warnings,
    missing_debug_implementations,
    missing_copy_implementations,
    missing_docs
)]
extern crate chrono;

use std::borrow::Cow;
use std::future::Future;
use std::net::UdpSocket;

use chrono::Utc;

pub use self::error::DogstatsdError;
use self::metrics::*;
pub use self::metrics::{ServiceCheckOptions, ServiceStatus};

mod error;
mod metrics;

/// A type alias for returning a unit type or an error
pub type DogstatsdResult = Result<(), DogstatsdError>;

const DEFAULT_FROM_ADDR: &str = "0.0.0.0:0";
const DEFAULT_TO_ADDR: &str = "127.0.0.1:8125";

/// The struct that represents the options available for the Dogstatsd client.
#[derive(Debug, PartialEq)]
pub struct Options {
    /// The address of the udp socket we'll bind to for sending.
    pub from_addr: String,
    /// The address of the udp socket we'll send metrics and events to.
    pub to_addr: String,
    /// A namespace to prefix all metrics with, joined with a '.'.
    pub namespace: String,
    /// Default tags to include with every request.
    pub default_tags: Vec<String>,
}

impl Default for Options {
    /// Create a new options struct with all the default settings.
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::Options;
    ///
    ///   let options = Options::default();
    ///
    ///   assert_eq!(
    ///       Options {
    ///           from_addr: "0.0.0.0:0".into(),
    ///           to_addr: "127.0.0.1:8125".into(),
    ///           namespace: String::new(),
    ///           default_tags: vec!()
    ///       },
    ///       options
    ///   )
    /// ```
    fn default() -> Self {
        Options {
            from_addr: DEFAULT_FROM_ADDR.into(),
            to_addr: DEFAULT_TO_ADDR.into(),
            namespace: String::new(),
            default_tags: vec![],
        }
    }
}

impl Options {
    /// Create a new options struct by supplying values for all fields.
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::Options;
    ///
    ///   let options = Options::new("127.0.0.1:9000", "127.0.0.1:9001", "", vec!(String::new()));
    /// ```
    pub fn new(from_addr: &str, to_addr: &str, namespace: &str, default_tags: Vec<String>) -> Self {
        Options {
            from_addr: from_addr.into(),
            to_addr: to_addr.into(),
            namespace: namespace.into(),
            default_tags,
        }
    }
}

/// Struct that allows build an `Options` for available for the Dogstatsd client.
#[derive(Default, Debug)]
pub struct OptionsBuilder {
    /// The address of the udp socket we'll bind to for sending.
    from_addr: Option<String>,
    /// The address of the udp socket we'll send metrics and events to.
    to_addr: Option<String>,
    /// A namespace to prefix all metrics with, joined with a '.'.
    namespace: Option<String>,
    /// Default tags to include with every request.
    default_tags: Vec<String>,
}

impl OptionsBuilder {
    /// Create a new `OptionsBuilder` struct.
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::OptionsBuilder;
    ///
    ///   let options_builder = OptionsBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Will allow the builder to generate an `Options` struct with the provided value.
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::OptionsBuilder;
    ///
    ///   let options_builder = OptionsBuilder::new().from_addr(String::from("127.0.0.1:9000"));
    /// ```
    pub fn from_addr(&mut self, from_addr: String) -> &mut OptionsBuilder {
        self.from_addr = Some(from_addr);
        self
    }

    /// Will allow the builder to generate an `Options` struct with the provided value.
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::OptionsBuilder;
    ///
    ///   let options_builder = OptionsBuilder::new().to_addr(String::from("127.0.0.1:9001"));
    /// ```
    pub fn to_addr(&mut self, to_addr: String) -> &mut OptionsBuilder {
        self.to_addr = Some(to_addr);
        self
    }

    /// Will allow the builder to generate an `Options` struct with the provided value.
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::OptionsBuilder;
    ///
    ///   let options_builder = OptionsBuilder::new().namespace(String::from("mynamespace"));
    /// ```
    pub fn namespace(&mut self, namespace: String) -> &mut OptionsBuilder {
        self.namespace = Some(namespace);
        self
    }

    /// Will allow the builder to generate an `Options` struct with the provided value. Can be called multiple times to add multiple `default_tags` to the `Options`.
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::OptionsBuilder;
    ///
    ///   let options_builder = OptionsBuilder::new().default_tag(String::from("tag1:tav1val")).default_tag(String::from("tag2:tag2val"));
    /// ```
    pub fn default_tag(&mut self, default_tag: String) -> &mut OptionsBuilder {
        self.default_tags.push(default_tag);
        self
    }

    /// Will construct an `Options` with all of the provided values and fall back to the default values if they aren't provided.
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::OptionsBuilder;
    ///   use dogstatsd::Options;
    ///
    ///   let options = OptionsBuilder::new().namespace(String::from("mynamespace")).default_tag(String::from("tag1:tav1val")).build();
    ///
    ///   assert_eq!(
    ///       Options {
    ///           from_addr: "0.0.0.0:0".into(),
    ///           to_addr: "127.0.0.1:8125".into(),
    ///           namespace: String::from("mynamespace"),
    ///           default_tags: vec!(String::from("tag1:tav1val"))
    ///       },
    ///       options
    ///   )
    /// ```
    pub fn build(&self) -> Options {
        Options::new(
            self.from_addr
                .as_ref()
                .unwrap_or(&String::from(DEFAULT_FROM_ADDR)),
            self.to_addr
                .as_ref()
                .unwrap_or(&String::from(DEFAULT_TO_ADDR)),
            self.namespace.as_ref().unwrap_or(&String::default()),
            self.default_tags.to_vec(),
        )
    }
}

/// The client struct that handles sending metrics to the Dogstatsd server.
#[derive(Debug)]
pub struct Client {
    socket: UdpSocket,
    from_addr: String,
    to_addr: String,
    namespace: String,
    default_tags: Vec<u8>,
}

impl PartialEq for Client {
    fn eq(&self, other: &Self) -> bool {
        // Ignore `socket`, which will never be the same
        self.from_addr == other.from_addr
            && self.to_addr == other.to_addr
            && self.namespace == other.namespace
            && self.default_tags == other.default_tags
    }
}

impl Client {
    /// Create a new client from an options struct.
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    /// ```
    pub fn new(options: Options) -> Result<Self, DogstatsdError> {
        Ok(Client {
            socket: UdpSocket::bind(&options.from_addr)?,
            from_addr: options.from_addr,
            to_addr: options.to_addr,
            namespace: options.namespace,
            default_tags: options.default_tags.join(",").into_bytes(),
        })
    }

    /// Increment a StatsD counter
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.incr("counter", &["tag:counter"])
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn incr<'a, I, S, T>(&self, stat: S, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        self.send(&CountMetric::Incr(stat.into().as_ref(), 1), tags)
    }

    /// Increment a StatsD counter by the provided amount
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.incr_by_value("counter", 123, &["tag:counter"])
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn incr_by_value<'a, I, S, T>(&self, stat: S, value: i64, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        self.send(&CountMetric::Incr(stat.into().as_ref(), value), tags)
    }

    /// Decrement a StatsD counter
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.decr("counter", &["tag:counter"])
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn decr<'a, I, S, T>(&self, stat: S, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        self.send(&CountMetric::Decr(stat.into().as_ref(), 1), tags)
    }

    /// Decrement a StatsD counter by the provided amount
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.decr_by_value("counter", 23, &["tag:counter"])
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn decr_by_value<'a, I, S, T>(&self, stat: S, value: i64, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        self.send(&CountMetric::Decr(stat.into().as_ref(), value), tags)
    }

    /// Make an arbitrary change to a StatsD counter
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.count("counter", 42, &["tag:counter"])
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn count<'a, I, S, T>(&self, stat: S, count: i64, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        self.send(&CountMetric::Arbitrary(stat.into().as_ref(), count), tags)
    }

    /// Time how long it takes for a block of code to execute.
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///   use std::thread;
    ///   use std::time::Duration;
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.time("timer", &["tag:time"], || {
    ///       thread::sleep(Duration::from_millis(200))
    ///   }).unwrap_or_else(|(_, e)| println!("Encountered error: {}", e))
    /// ```
    pub fn time<'a, F, O, I, S, T>(
        &self,
        stat: S,
        tags: I,
        block: F,
    ) -> Result<O, (O, DogstatsdError)>
    where
        F: FnOnce() -> O,
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        let start_time = Utc::now();
        let output = block();
        let end_time = Utc::now();
        let stat = stat.into();
        let metric = TimeMetric::new(stat.as_ref(), &start_time, &end_time);
        match self.send(&metric, tags) {
            Ok(()) => Ok(output),
            Err(error) => Err((output, error)),
        }
    }

    /// Time how long it takes for an async block of code to execute.
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///   use std::thread;
    ///   use std::time::Duration;
    ///
    /// # async fn do_work() {}
    ///   async fn timer() {
    ///       let client = Client::new(Options::default()).unwrap();
    ///       client.async_time("timer", &["tag:time"], do_work)
    ///       .await
    ///       .unwrap_or_else(|(_, e)| println!("Encountered error: {}", e))
    ///   }
    /// ```
    pub async fn async_time<'a, Fn, Fut, O, I, S, T>(
        &self,
        stat: S,
        tags: I,
        block: Fn,
    ) -> Result<O, (O, DogstatsdError)>
    where
        Fn: FnOnce() -> Fut,
        Fut: Future<Output = O>,
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        let start_time = Utc::now();
        let output = block().await;
        let end_time = Utc::now();
        let stat = stat.into();
        match self.send(
            &TimeMetric::new(stat.as_ref(), &start_time, &end_time),
            tags,
        ) {
            Ok(()) => Ok(output),
            Err(error) => Err((output, error)),
        }
    }

    /// Send your own timing metric in milliseconds
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.timing("timing", 350, &["tag:timing"])
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn timing<'a, I, S, T>(&self, stat: S, ms: i64, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        self.send(&TimingMetric::new(stat.into().as_ref(), ms), tags)
    }

    /// Report an arbitrary value as a gauge
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.gauge("gauge", "12345", &["tag:gauge"])
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn gauge<'a, I, S, SS, T>(&self, stat: S, val: SS, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        SS: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        self.send(
            &GaugeMetric::new(stat.into().as_ref(), val.into().as_ref()),
            tags,
        )
    }

    /// Report a value in a histogram
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.histogram("histogram", "67890", &["tag:histogram"])
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn histogram<'a, I, S, SS, T>(&self, stat: S, val: SS, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        SS: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        self.send(
            &HistogramMetric::new(stat.into().as_ref(), val.into().as_ref()),
            tags,
        )
    }

    /// Report a value in a distribution
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.distribution("distribution", "67890", &["tag:distribution"])
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn distribution<'a, I, S, SS, T>(&self, stat: S, val: SS, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        SS: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        self.send(
            &DistributionMetric::new(stat.into().as_ref(), val.into().as_ref()),
            tags,
        )
    }

    /// Report a value in a set
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.set("set", "13579", &["tag:set"])
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn set<'a, I, S, SS, T>(&self, stat: S, val: SS, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        SS: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        self.send(
            &SetMetric::new(stat.into().as_ref(), val.into().as_ref()),
            tags,
        )
    }

    /// Report the status of a service
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options, ServiceStatus, ServiceCheckOptions};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.service_check("redis.can_connect", ServiceStatus::OK, &["tag:service"], None)
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    ///
    ///   let options = ServiceCheckOptions {
    ///     hostname: Some("my-host.localhost"),
    ///     ..Default::default()
    ///   };
    ///   client.service_check("redis.can_connect", ServiceStatus::OK, &["tag:service"], Some(options))
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    ///
    ///   let all_options = ServiceCheckOptions {
    ///     hostname: Some("my-host.localhost"),
    ///     timestamp: Some(1510326433),
    ///     message: Some("Message about the check or service")
    ///   };
    ///   client.service_check("redis.can_connect", ServiceStatus::OK, &["tag:service"], Some(all_options))
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn service_check<'a, I, S, T>(
        &self,
        stat: S,
        val: ServiceStatus,
        tags: I,
        options: Option<ServiceCheckOptions>,
    ) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        let unwrapped_options = options.unwrap_or_default();
        self.send(
            &ServiceCheck::new(stat.into().as_ref(), val, unwrapped_options),
            tags,
        )
    }

    /// Send a custom event as a title and a body
    ///
    /// # Examples
    ///
    /// ```
    ///   use dogstatsd::{Client, Options};
    ///
    ///   let client = Client::new(Options::default()).unwrap();
    ///   client.event("Event Title", "Event Body", &["tag:event"])
    ///       .unwrap_or_else(|e| println!("Encountered error: {}", e));
    /// ```
    pub fn event<'a, I, S, SS, T>(&self, title: S, text: SS, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = T>,
        S: Into<Cow<'a, str>>,
        SS: Into<Cow<'a, str>>,
        T: AsRef<str>,
    {
        self.send(
            &Event::new(title.into().as_ref(), text.into().as_ref()),
            tags,
        )
    }

    fn send<I, M, S>(&self, metric: &M, tags: I) -> DogstatsdResult
    where
        I: IntoIterator<Item = S>,
        M: Metric,
        S: AsRef<str>,
    {
        let formatted_metric = format_for_send(metric, &self.namespace, tags, &self.default_tags);
        self.socket
            .send_to(formatted_metric.as_slice(), &self.to_addr)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use metrics::GaugeMetric;

    use super::*;

    #[test]
    fn test_options_default() {
        let options = Options::default();
        let expected_options = Options {
            from_addr: DEFAULT_FROM_ADDR.into(),
            to_addr: DEFAULT_TO_ADDR.into(),
            namespace: String::new(),
            ..Default::default()
        };

        assert_eq!(expected_options, options)
    }

    #[test]
    fn test_options_builder_none() {
        let options = OptionsBuilder::new().build();
        let expected_options = Options {
            from_addr: DEFAULT_FROM_ADDR.into(),
            to_addr: DEFAULT_TO_ADDR.into(),
            namespace: String::new(),
            ..Default::default()
        };

        assert_eq!(expected_options, options);
    }

    #[test]
    fn teset_options_builder_all() {
        let options = OptionsBuilder::new()
            .from_addr("127.0.0.2:0".into())
            .to_addr("127.0.0.2:8125".into())
            .namespace("mynamespace".into())
            .default_tag(String::from("tag1:tag1val"))
            .build();
        let expected_options = Options {
            from_addr: "127.0.0.2:0".into(),
            to_addr: "127.0.0.2:8125".into(),
            namespace: "mynamespace".into(),
            default_tags: vec!["tag1:tag1val".into()].to_vec(),
        };

        assert_eq!(expected_options, options);
    }

    #[test]
    fn test_new() {
        let client = Client::new(Options::default()).unwrap();
        let expected_client = Client {
            socket: UdpSocket::bind(DEFAULT_FROM_ADDR).unwrap(),
            from_addr: DEFAULT_FROM_ADDR.into(),
            to_addr: DEFAULT_TO_ADDR.into(),
            namespace: String::new(),
            default_tags: String::new().into_bytes(),
        };

        assert_eq!(expected_client, client)
    }

    #[test]
    fn test_new_default_tags() {
        let options = Options::new(
            DEFAULT_FROM_ADDR,
            DEFAULT_TO_ADDR,
            "",
            vec![String::from("tag1:tag1val")],
        );
        let client = Client::new(options).unwrap();
        let expected_client = Client {
            socket: UdpSocket::bind(DEFAULT_FROM_ADDR).unwrap(),
            from_addr: DEFAULT_FROM_ADDR.into(),
            to_addr: DEFAULT_TO_ADDR.into(),
            namespace: String::new(),
            default_tags: String::from("tag1:tag1val").into_bytes(),
        };

        assert_eq!(expected_client, client)
    }

    #[test]
    fn test_send() {
        let options = Options::new("127.0.0.1:9001", "127.0.0.1:9002", "", vec![]);
        let client = Client::new(options).unwrap();
        // Shouldn't panic or error
        client
            .send(
                &GaugeMetric::new("gauge".into(), "1234".into()),
                &["tag1", "tag2"],
            )
            .unwrap();
    }
}

#[cfg(all(feature = "unstable", test))]
mod bench {
    extern crate test;

    use super::*;

    use self::test::Bencher;

    #[bench]
    fn bench_incr(b: &mut Bencher) {
        let options = Options::default();
        let client = Client::new(options).unwrap();
        let tags = &["name1:value1"];
        b.iter(|| {
            client.incr("bench.incr", tags).unwrap();
        })
    }

    #[bench]
    fn bench_decr(b: &mut Bencher) {
        let options = Options::default();
        let client = Client::new(options).unwrap();
        let tags = &["name1:value1"];
        b.iter(|| {
            client.decr("bench.decr", tags).unwrap();
        })
    }

    #[bench]
    fn bench_count(b: &mut Bencher) {
        let options = Options::default();
        let client = Client::new(options).unwrap();
        let tags = &["name1:value1"];
        let mut i = 0;
        b.iter(|| {
            client.count("bench.count", i, tags).unwrap();
            i += 1;
        })
    }

    #[bench]
    fn bench_timing(b: &mut Bencher) {
        let options = Options::default();
        let client = Client::new(options).unwrap();
        let tags = &["name1:value1"];
        let mut i = 0;
        b.iter(|| {
            client.timing("bench.timing", i, tags).unwrap();
            i += 1;
        })
    }

    #[bench]
    fn bench_gauge(b: &mut Bencher) {
        let options = Options::default();
        let client = Client::new(options).unwrap();
        let tags = vec!["name1:value1"];
        let mut i = 0;
        b.iter(|| {
            client.gauge("bench.guage", &i.to_string(), &tags).unwrap();
            i += 1;
        })
    }

    #[bench]
    fn bench_histogram(b: &mut Bencher) {
        let options = Options::default();
        let client = Client::new(options).unwrap();
        let tags = vec!["name1:value1"];
        let mut i = 0;
        b.iter(|| {
            client
                .histogram("bench.histogram", &i.to_string(), &tags)
                .unwrap();
            i += 1;
        })
    }

    #[bench]
    fn bench_distribution(b: &mut Bencher) {
        let options = Options::default();
        let client = Client::new(options).unwrap();
        let tags = vec!["name1:value1"];
        let mut i = 0;
        b.iter(|| {
            client
                .distribution("bench.distribution", &i.to_string(), &tags)
                .unwrap();
            i += 1;
        })
    }

    #[bench]
    fn bench_set(b: &mut Bencher) {
        let options = Options::default();
        let client = Client::new(options).unwrap();
        let tags = vec!["name1:value1"];
        let mut i = 0;
        b.iter(|| {
            client.set("bench.set", &i.to_string(), &tags).unwrap();
            i += 1;
        })
    }

    #[bench]
    fn bench_service_check(b: &mut Bencher) {
        let options = Options::default();
        let client = Client::new(options).unwrap();
        let tags = vec!["name1:value1"];
        let all_options = ServiceCheckOptions {
            hostname: Some("my-host.localhost"),
            timestamp: Some(1510326433),
            message: Some("Message about the check or service"),
        };
        b.iter(|| {
            client
                .service_check(
                    "bench.service_check",
                    ServiceStatus::Critical,
                    &tags,
                    Some(all_options),
                )
                .unwrap();
        })
    }

    #[bench]
    fn bench_event(b: &mut Bencher) {
        let options = Options::default();
        let client = Client::new(options).unwrap();
        let tags = vec!["name1:value1"];
        b.iter(|| {
            client
                .event("Test Event Title", "Test Event Message", &tags)
                .unwrap();
        })
    }
}