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
use crate::sdk::InstrumentationLibrary;
use crate::{
    metrics::{
        sdk_api, AsyncRunner, BatchObserver, BatchObserverResult, CounterBuilder, Descriptor,
        Measurement, NumberKind, ObserverResult, Result, SumObserverBuilder, UpDownCounterBuilder,
        UpDownSumObserverBuilder, ValueObserverBuilder, ValueRecorderBuilder,
    },
    Context, KeyValue,
};
use std::fmt;
use std::sync::Arc;

/// Returns named meter instances
pub trait MeterProvider: fmt::Debug {
    /// Creates an implementation of the [`Meter`] interface. The
    /// instrumentation name must be the name of the library providing
    /// instrumentation. This name may be the same as the instrumented code only if
    /// that code provides built-in instrumentation. If the instrumentation name is
    /// empty, then a implementation defined default name will be used instead.
    ///
    fn meter(
        &self,
        instrumentation_name: &'static str,
        instrumentation_version: Option<&'static str>,
    ) -> Meter;
}

/// Meter is the OpenTelemetry metric API, based on a sdk-defined `MeterCore`
/// implementation and the `Meter` library name.
///
/// # Instruments
///
/// | **Name** | Instrument kind | Function(argument) | Default aggregation | Notes |
/// | ----------------------- | ----- | --------- | ------------- | --- |
/// | **Counter**             | Synchronous adding monotonic | Add(increment) | Sum | Per-request, part of a monotonic sum |
/// | **UpDownCounter**       | Synchronous adding | Add(increment) | Sum | Per-request, part of a non-monotonic sum |
/// | **ValueRecorder**       | Synchronous  | Record(value) | [TBD issue 636](https://github.com/open-telemetry/opentelemetry-specification/issues/636)  | Per-request, any grouping measurement |
/// | **SumObserver**         | Asynchronous adding monotonic | Observe(sum) | Sum | Per-interval, reporting a monotonic sum |
/// | **UpDownSumObserver**   | Asynchronous adding | Observe(sum) | Sum | Per-interval, reporting a non-monotonic sum |
/// | **ValueObserver**       | Asynchronous | Observe(value) | LastValue  | Per-interval, any grouping measurement |
#[derive(Debug)]
pub struct Meter {
    instrumentation_library: InstrumentationLibrary,
    core: Arc<dyn sdk_api::MeterCore + Send + Sync>,
}

impl Meter {
    /// Create a new named meter from a sdk implemented core
    pub fn new<T: Into<&'static str>>(
        instrumentation_name: T,
        instrumentation_version: Option<T>,
        core: Arc<dyn sdk_api::MeterCore + Send + Sync>,
    ) -> Self {
        Meter {
            instrumentation_library: InstrumentationLibrary::new(
                instrumentation_name.into(),
                instrumentation_version.map(Into::into),
            ),
            core,
        }
    }

    pub(crate) fn instrumentation_library(&self) -> InstrumentationLibrary {
        self.instrumentation_library
    }

    /// Creates a new integer `CounterBuilder` for `u64` values with the given name.
    pub fn u64_counter<T>(&self, name: T) -> CounterBuilder<'_, u64>
    where
        T: Into<String>,
    {
        CounterBuilder::new(self, name.into(), NumberKind::U64)
    }

    /// Creates a new floating point `CounterBuilder` for `f64` values with the given name.
    pub fn f64_counter<T>(&self, name: T) -> CounterBuilder<'_, f64>
    where
        T: Into<String>,
    {
        CounterBuilder::new(self, name.into(), NumberKind::F64)
    }

    /// Creates a new integer `UpDownCounterBuilder` for an `i64` up down counter with the given name.
    pub fn i64_up_down_counter<T>(&self, name: T) -> UpDownCounterBuilder<'_, i64>
    where
        T: Into<String>,
    {
        UpDownCounterBuilder::new(self, name.into(), NumberKind::I64)
    }

    /// Creates a new floating point `UpDownCounterBuilder` for an `f64` up down counter with the given name.
    pub fn f64_up_down_counter<T>(&self, name: T) -> UpDownCounterBuilder<'_, f64>
    where
        T: Into<String>,
    {
        UpDownCounterBuilder::new(self, name.into(), NumberKind::F64)
    }

    /// Creates a new `ValueRecorderBuilder` for `i64` values with the given name.
    pub fn i64_value_recorder<T>(&self, name: T) -> ValueRecorderBuilder<'_, i64>
    where
        T: Into<String>,
    {
        ValueRecorderBuilder::new(self, name.into(), NumberKind::I64)
    }

    /// Creates a new `ValueRecorderBuilder` for `u64` values with the given name.
    pub fn u64_value_recorder<T>(&self, name: T) -> ValueRecorderBuilder<'_, u64>
    where
        T: Into<String>,
    {
        ValueRecorderBuilder::new(self, name.into(), NumberKind::U64)
    }

    /// Creates a new `ValueRecorderBuilder` for `f64` values with the given name.
    pub fn f64_value_recorder<T>(&self, name: T) -> ValueRecorderBuilder<'_, f64>
    where
        T: Into<String>,
    {
        ValueRecorderBuilder::new(self, name.into(), NumberKind::F64)
    }

    /// Creates a new integer `SumObserverBuilder` for `u64` values with the given
    /// name and callback
    pub fn u64_sum_observer<T, F>(&self, name: T, callback: F) -> SumObserverBuilder<'_, u64>
    where
        T: Into<String>,
        F: Fn(ObserverResult<u64>) + Send + Sync + 'static,
    {
        SumObserverBuilder::new(
            self,
            name.into(),
            Some(AsyncRunner::U64(Box::new(callback))),
            NumberKind::U64,
        )
    }

    /// Creates a new floating point `SumObserverBuilder` for `f64` values with the
    /// given name and callback
    pub fn f64_sum_observer<T, F>(&self, name: T, callback: F) -> SumObserverBuilder<'_, f64>
    where
        T: Into<String>,
        F: Fn(ObserverResult<f64>) + Send + Sync + 'static,
    {
        SumObserverBuilder::new(
            self,
            name.into(),
            Some(AsyncRunner::F64(Box::new(callback))),
            NumberKind::F64,
        )
    }

    /// Creates a new integer `UpDownSumObserverBuilder` for `i64` values with the
    /// given name and callback.
    pub fn i64_up_down_sum_observer<T, F>(
        &self,
        name: T,
        callback: F,
    ) -> UpDownSumObserverBuilder<'_, i64>
    where
        T: Into<String>,
        F: Fn(ObserverResult<i64>) + Send + Sync + 'static,
    {
        UpDownSumObserverBuilder::new(
            self,
            name.into(),
            Some(AsyncRunner::I64(Box::new(callback))),
            NumberKind::I64,
        )
    }

    /// Creates a new floating point `UpDownSumObserverBuilder` for `f64` values
    /// with the given name and callback
    pub fn f64_up_down_sum_observer<T, F>(
        &self,
        name: T,
        callback: F,
    ) -> UpDownSumObserverBuilder<'_, f64>
    where
        T: Into<String>,
        F: Fn(ObserverResult<f64>) + Send + Sync + 'static,
    {
        UpDownSumObserverBuilder::new(
            self,
            name.into(),
            Some(AsyncRunner::F64(Box::new(callback))),
            NumberKind::F64,
        )
    }

    /// Creates a new integer `ValueObserverBuilder` for `u64` values with the given
    /// name and callback
    pub fn u64_value_observer<T, F>(&self, name: T, callback: F) -> ValueObserverBuilder<'_, u64>
    where
        T: Into<String>,
        F: Fn(ObserverResult<u64>) + Send + Sync + 'static,
    {
        ValueObserverBuilder::new(
            self,
            name.into(),
            Some(AsyncRunner::U64(Box::new(callback))),
            NumberKind::U64,
        )
    }

    /// Creates a new integer `ValueObserverBuilder` for `i64` values with the given
    /// name and callback
    pub fn i64_value_observer<T, F>(&self, name: T, callback: F) -> ValueObserverBuilder<'_, i64>
    where
        T: Into<String>,
        F: Fn(ObserverResult<i64>) + Send + Sync + 'static,
    {
        ValueObserverBuilder::new(
            self,
            name.into(),
            Some(AsyncRunner::I64(Box::new(callback))),
            NumberKind::I64,
        )
    }

    /// Creates a new floating point `ValueObserverBuilder` for `f64` values with
    /// the given name and callback
    pub fn f64_value_observer<T, F>(&self, name: T, callback: F) -> ValueObserverBuilder<'_, f64>
    where
        T: Into<String>,
        F: Fn(ObserverResult<f64>) + Send + Sync + 'static,
    {
        ValueObserverBuilder::new(
            self,
            name.into(),
            Some(AsyncRunner::F64(Box::new(callback))),
            NumberKind::F64,
        )
    }

    /// Creates a new `BatchObserver` that supports making batches of observations
    /// for multiple instruments or returns an error if instrument initialization
    /// fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use opentelemetry::{global, metrics::BatchObserverResult, KeyValue};
    ///
    /// # fn init_observer() -> opentelemetry::metrics::Result<()> {
    /// let meter = global::meter("test");
    ///
    /// meter.build_batch_observer(|batch| {
    ///   let instrument = batch.u64_value_observer("test_instrument").try_init()?;
    ///
    ///   Ok(move |result: BatchObserverResult| {
    ///     result.observe(&[KeyValue::new("my-key", "my-value")], &[instrument.observation(1)]);
    ///   })
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn build_batch_observer<B, F>(&self, builder: B) -> Result<()>
    where
        B: Fn(BatchObserver<'_>) -> Result<F>,
        F: Fn(BatchObserverResult) + Send + Sync + 'static,
    {
        let observer = builder(BatchObserver::new(self))?;
        self.core
            .new_batch_observer(AsyncRunner::Batch(Box::new(observer)))
    }

    /// Creates a new `BatchObserver` that supports making batches of observations
    /// for multiple instruments.
    ///
    /// # Panics
    ///
    /// Panics if instrument initialization or observer registration returns an
    /// error.
    ///
    /// # Examples
    ///
    /// ```
    /// use opentelemetry::{global, metrics::BatchObserverResult, KeyValue};
    ///
    /// let meter = global::meter("test");
    ///
    /// meter.batch_observer(|batch| {
    ///   let instrument = batch.u64_value_observer("test_instrument").init();
    ///
    ///   move |result: BatchObserverResult| {
    ///     result.observe(&[KeyValue::new("my-key", "my-value")], &[instrument.observation(1)]);
    ///   }
    /// });
    /// ```
    pub fn batch_observer<B, F>(&self, builder: B)
    where
        B: Fn(BatchObserver<'_>) -> F,
        F: Fn(BatchObserverResult) + Send + Sync + 'static,
    {
        let observer = builder(BatchObserver::new(self));
        self.core
            .new_batch_observer(AsyncRunner::Batch(Box::new(observer)))
            .unwrap()
    }

    /// Atomically record a batch of measurements.
    pub fn record_batch<T: IntoIterator<Item = Measurement>>(
        &self,
        labels: &[KeyValue],
        measurements: T,
    ) {
        self.record_batch_with_context(&Context::current(), labels, measurements)
    }

    /// Atomically record a batch of measurements with a given context
    pub fn record_batch_with_context<T: IntoIterator<Item = Measurement>>(
        &self,
        cx: &Context,
        labels: &[KeyValue],
        measurements: T,
    ) {
        self.core
            .record_batch_with_context(cx, labels, measurements.into_iter().collect())
    }

    pub(crate) fn new_sync_instrument(
        &self,
        descriptor: Descriptor,
    ) -> Result<Arc<dyn sdk_api::SyncInstrumentCore>> {
        self.core.new_sync_instrument(descriptor)
    }

    pub(crate) fn new_async_instrument(
        &self,
        descriptor: Descriptor,
        runner: Option<AsyncRunner>,
    ) -> Result<Arc<dyn sdk_api::AsyncInstrumentCore>> {
        self.core.new_async_instrument(descriptor, runner)
    }
}