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
//! # OpenTelemetry Metrics API

use std::any::Any;
use std::result;
use std::sync::PoisonError;
use std::{borrow::Cow, sync::Arc};
use thiserror::Error;

mod instruments;
mod meter;
pub mod noop;

use crate::ExportError;
pub use instruments::{
    counter::{Counter, ObservableCounter, SyncCounter},
    gauge::ObservableGauge,
    histogram::{Histogram, SyncHistogram},
    up_down_counter::{ObservableUpDownCounter, SyncUpDownCounter, UpDownCounter},
    AsyncInstrument, AsyncInstrumentBuilder, Callback, InstrumentBuilder,
};
pub use meter::{CallbackRegistration, Meter, MeterProvider, Observer};

/// A specialized `Result` type for metric operations.
pub type Result<T> = result::Result<T, MetricsError>;

/// Errors returned by the metrics API.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum MetricsError {
    /// Other errors not covered by specific cases.
    #[error("Metrics error: {0}")]
    Other(String),
    /// Invalid configuration
    #[error("Config error {0}")]
    Config(String),
    /// Fail to export metrics
    #[error("Metrics exporter {} failed with {0}", .0.exporter_name())]
    ExportErr(Box<dyn ExportError>),
    /// Invalid instrument configuration such invalid instrument name, invalid instrument description, invalid instrument unit, etc.
    /// See [spec](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#general-characteristics)
    /// for full list of requirements.
    #[error("Invalid instrument configuration: {0}")]
    InvalidInstrumentConfiguration(&'static str),
}

impl<T: ExportError> From<T> for MetricsError {
    fn from(err: T) -> Self {
        MetricsError::ExportErr(Box::new(err))
    }
}

impl<T> From<PoisonError<T>> for MetricsError {
    fn from(err: PoisonError<T>) -> Self {
        MetricsError::Other(err.to_string())
    }
}

/// Units denote underlying data units tracked by `Meter`s.
#[derive(Clone, Default, Debug, PartialEq, Eq, Hash)]
pub struct Unit(Cow<'static, str>);

impl Unit {
    /// Create a new `Unit` from an `Into<String>`
    pub fn new<S>(value: S) -> Self
    where
        S: Into<Cow<'static, str>>,
    {
        Unit(value.into())
    }

    /// View unit as &str
    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }
}

impl AsRef<str> for Unit {
    #[inline]
    fn as_ref(&self) -> &str {
        self.0.as_ref()
    }
}

/// SDK implemented trait for creating instruments
pub trait InstrumentProvider {
    /// creates an instrument for recording increasing values.
    fn u64_counter(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
    ) -> Result<Counter<u64>> {
        Ok(Counter::new(Arc::new(noop::NoopSyncInstrument::new())))
    }

    /// creates an instrument for recording increasing values.
    fn f64_counter(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
    ) -> Result<Counter<f64>> {
        Ok(Counter::new(Arc::new(noop::NoopSyncInstrument::new())))
    }

    /// creates an instrument for recording increasing values via callback.
    fn u64_observable_counter(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
        _callback: Vec<Callback<u64>>,
    ) -> Result<ObservableCounter<u64>> {
        Ok(ObservableCounter::new(Arc::new(
            noop::NoopAsyncInstrument::new(),
        )))
    }

    /// creates an instrument for recording increasing values via callback.
    fn f64_observable_counter(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
        _callback: Vec<Callback<f64>>,
    ) -> Result<ObservableCounter<f64>> {
        Ok(ObservableCounter::new(Arc::new(
            noop::NoopAsyncInstrument::new(),
        )))
    }

    /// creates an instrument for recording changes of a value.
    fn i64_up_down_counter(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
    ) -> Result<UpDownCounter<i64>> {
        Ok(UpDownCounter::new(
            Arc::new(noop::NoopSyncInstrument::new()),
        ))
    }

    /// creates an instrument for recording changes of a value.
    fn f64_up_down_counter(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
    ) -> Result<UpDownCounter<f64>> {
        Ok(UpDownCounter::new(
            Arc::new(noop::NoopSyncInstrument::new()),
        ))
    }

    /// creates an instrument for recording changes of a value.
    fn i64_observable_up_down_counter(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
        _callback: Vec<Callback<i64>>,
    ) -> Result<ObservableUpDownCounter<i64>> {
        Ok(ObservableUpDownCounter::new(Arc::new(
            noop::NoopAsyncInstrument::new(),
        )))
    }

    /// creates an instrument for recording changes of a value via callback.
    fn f64_observable_up_down_counter(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
        _callback: Vec<Callback<f64>>,
    ) -> Result<ObservableUpDownCounter<f64>> {
        Ok(ObservableUpDownCounter::new(Arc::new(
            noop::NoopAsyncInstrument::new(),
        )))
    }

    /// creates an instrument for recording the current value via callback.
    fn u64_observable_gauge(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
        _callback: Vec<Callback<u64>>,
    ) -> Result<ObservableGauge<u64>> {
        Ok(ObservableGauge::new(Arc::new(
            noop::NoopAsyncInstrument::new(),
        )))
    }

    /// creates an instrument for recording the current value via callback.
    fn i64_observable_gauge(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
        _callback: Vec<Callback<i64>>,
    ) -> Result<ObservableGauge<i64>> {
        Ok(ObservableGauge::new(Arc::new(
            noop::NoopAsyncInstrument::new(),
        )))
    }

    /// creates an instrument for recording the current value via callback.
    fn f64_observable_gauge(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
        _callback: Vec<Callback<f64>>,
    ) -> Result<ObservableGauge<f64>> {
        Ok(ObservableGauge::new(Arc::new(
            noop::NoopAsyncInstrument::new(),
        )))
    }

    /// creates an instrument for recording a distribution of values.
    fn f64_histogram(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
    ) -> Result<Histogram<f64>> {
        Ok(Histogram::new(Arc::new(noop::NoopSyncInstrument::new())))
    }

    /// creates an instrument for recording a distribution of values.
    fn u64_histogram(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
    ) -> Result<Histogram<u64>> {
        Ok(Histogram::new(Arc::new(noop::NoopSyncInstrument::new())))
    }

    /// creates an instrument for recording a distribution of values.
    fn i64_histogram(
        &self,
        _name: Cow<'static, str>,
        _description: Option<Cow<'static, str>>,
        _unit: Option<Unit>,
    ) -> Result<Histogram<i64>> {
        Ok(Histogram::new(Arc::new(noop::NoopSyncInstrument::new())))
    }

    /// Captures the function that will be called during data collection.
    ///
    /// It is only valid to call `observe` within the scope of the passed function.
    fn register_callback(
        &self,
        instruments: &[Arc<dyn Any>],
        callbacks: Box<MultiInstrumentCallback>,
    ) -> Result<Box<dyn CallbackRegistration>>;
}

type MultiInstrumentCallback = dyn Fn(&dyn Observer) + Send + Sync;