wrapped/
wrapped.rs

1// Cadence - An extensible Statsd client for Rust!
2//
3// To the extent possible under law, the author(s) have dedicated all copyright and
4// related and neighboring rights to this file to the public domain worldwide.
5// This software is distributed without any warranty.
6//
7// You should have received a copy of the CC0 Public Domain Dedication along with this
8// software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
9
10use std::io;
11use std::panic::RefUnwindSafe;
12use std::sync::Arc;
13use std::time::Duration;
14
15use cadence::prelude::*;
16use cadence::{MetricSink, NopMetricSink, StatsdClient};
17
18// This example shows how you might use a `MetricSink` with Cadence while
19// retaining a reference to it in order to periodically call it's `flush`
20// method.
21
22/// MetricSink implementation that delegates to another referenced counted
23/// implementation.
24#[derive(Clone)]
25pub struct CloneableSink {
26    wrapped: Arc<dyn MetricSink + Send + Sync + RefUnwindSafe + 'static>,
27}
28
29impl CloneableSink {
30    pub fn new<T>(wrapped: T) -> Self
31    where
32        T: MetricSink + Send + Sync + RefUnwindSafe + 'static,
33    {
34        Self {
35            wrapped: Arc::new(wrapped),
36        }
37    }
38}
39
40impl MetricSink for CloneableSink {
41    fn emit(&self, metric: &str) -> io::Result<usize> {
42        self.wrapped.emit(metric)
43    }
44
45    fn flush(&self) -> io::Result<()> {
46        self.wrapped.flush()
47    }
48}
49
50fn main() {
51    let real_sink = NopMetricSink;
52    let reference1 = CloneableSink::new(real_sink);
53    let reference2 = reference1.clone();
54    let client = StatsdClient::from_sink("prefix", reference1);
55
56    let _ = reference2.flush();
57
58    client.count("example.counter", 1).unwrap();
59    client.gauge("example.gauge", 5).unwrap();
60    client.gauge("example.gauge", 5.0).unwrap();
61    client.time("example.timer", 32).unwrap();
62    client.time("example.timer", Duration::from_millis(32)).unwrap();
63    client.histogram("example.histogram", 22).unwrap();
64    client.histogram("example.histogram", Duration::from_nanos(22)).unwrap();
65    client.histogram("example.histogram", 22.0).unwrap();
66    client.distribution("example.distribution", 33).unwrap();
67    client.distribution("example.distribution", 33.0).unwrap();
68    client.meter("example.meter", 8).unwrap();
69    client.set("example.set", 44).unwrap();
70
71    let _ = reference2.flush();
72}