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
//! Metrics Registry API
use crate::{
    metrics::{
        sdk_api::{AsyncInstrumentCore, MeterCore, SyncInstrumentCore},
        Meter, MeterProvider,
    },
    metrics::{AsyncRunner, Descriptor, Measurement, MetricsError, Result},
    Context, KeyValue,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

/// Create a new `RegistryMeterProvider` from a `MeterCore`.
pub fn meter_provider(core: Arc<dyn MeterCore + Send + Sync>) -> RegistryMeterProvider {
    RegistryMeterProvider(Arc::new(UniqueInstrumentMeterCore::wrap(core)))
}

/// A standard `MeterProvider` for wrapping a `MeterCore`.
#[derive(Debug, Clone)]
pub struct RegistryMeterProvider(Arc<dyn MeterCore + Send + Sync>);

impl MeterProvider for RegistryMeterProvider {
    fn meter(&self, name: &'static str, version: Option<&'static str>) -> Meter {
        Meter::new(name, version, self.0.clone())
    }
}

#[derive(Debug)]
struct UniqueInstrumentMeterCore {
    inner: Arc<dyn MeterCore + Send + Sync>,
    sync_state: Mutex<HashMap<UniqueInstrumentKey, UniqueSyncInstrument>>,
    async_state: Mutex<HashMap<UniqueInstrumentKey, UniqueAsyncInstrument>>,
}

impl UniqueInstrumentMeterCore {
    fn wrap(inner: Arc<dyn MeterCore + Send + Sync>) -> Self {
        UniqueInstrumentMeterCore {
            inner,
            sync_state: Mutex::new(HashMap::default()),
            async_state: Mutex::new(HashMap::default()),
        }
    }
}

impl MeterCore for UniqueInstrumentMeterCore {
    fn record_batch_with_context(
        &self,
        cx: &Context,
        attributes: &[KeyValue],
        measurements: Vec<Measurement>,
    ) {
        self.inner
            .record_batch_with_context(cx, attributes, measurements)
    }

    fn new_sync_instrument(&self, descriptor: Descriptor) -> Result<UniqueSyncInstrument> {
        self.sync_state
            .lock()
            .map_err(Into::into)
            .and_then(|mut state| {
                let key = UniqueInstrumentKey::from(&descriptor);
                check_sync_uniqueness(&state, &descriptor, &key).and_then(|instrument| {
                    match instrument {
                        Some(instrument) => Ok(instrument),
                        None => {
                            let instrument = self.inner.new_sync_instrument(descriptor)?;
                            state.insert(key, instrument.clone());

                            Ok(instrument)
                        }
                    }
                })
            })
    }

    fn new_async_instrument(
        &self,
        descriptor: Descriptor,
        runner: Option<AsyncRunner>,
    ) -> super::Result<UniqueAsyncInstrument> {
        self.async_state
            .lock()
            .map_err(Into::into)
            .and_then(|mut state| {
                let key = UniqueInstrumentKey::from(&descriptor);
                check_async_uniqueness(&state, &descriptor, &key).and_then(|instrument| {
                    match instrument {
                        Some(instrument) => Ok(instrument),
                        None => {
                            let instrument = self.inner.new_async_instrument(descriptor, runner)?;
                            state.insert(key, instrument.clone());

                            Ok(instrument)
                        }
                    }
                })
            })
    }

    fn new_batch_observer(&self, runner: AsyncRunner) -> Result<()> {
        self.inner.new_batch_observer(runner)
    }
}

fn check_sync_uniqueness(
    instruments: &HashMap<UniqueInstrumentKey, UniqueSyncInstrument>,
    desc: &Descriptor,
    key: &UniqueInstrumentKey,
) -> Result<Option<UniqueSyncInstrument>> {
    if let Some(instrument) = instruments.get(key) {
        if is_equal(instrument.descriptor(), desc) {
            Ok(Some(instrument.clone()))
        } else {
            Err(MetricsError::MetricKindMismatch(format!(
                "metric was {} ({}), registered as a {:?} {:?}",
                desc.name(),
                desc.instrumentation_name(),
                desc.number_kind(),
                desc.instrument_kind()
            )))
        }
    } else {
        Ok(None)
    }
}

fn check_async_uniqueness(
    instruments: &HashMap<UniqueInstrumentKey, UniqueAsyncInstrument>,
    desc: &Descriptor,
    key: &UniqueInstrumentKey,
) -> Result<Option<UniqueAsyncInstrument>> {
    if let Some(instrument) = instruments.get(key) {
        if is_equal(instrument.descriptor(), desc) {
            Ok(Some(instrument.clone()))
        } else {
            Err(MetricsError::MetricKindMismatch(format!(
                "metric was {} ({}), registered as a {:?} {:?}",
                desc.name(),
                desc.instrumentation_name(),
                desc.number_kind(),
                desc.instrument_kind()
            )))
        }
    } else {
        Ok(None)
    }
}

fn is_equal(a: &Descriptor, b: &Descriptor) -> bool {
    a.instrument_kind() == b.instrument_kind() && a.number_kind() == b.number_kind()
}

#[derive(Debug, PartialEq, Eq, Hash)]
struct UniqueInstrumentKey {
    instrument_name: String,
    instrumentation_name: String,
}

impl From<&Descriptor> for UniqueInstrumentKey {
    fn from(desc: &Descriptor) -> Self {
        UniqueInstrumentKey {
            instrument_name: desc.name().to_string(),
            instrumentation_name: desc.instrumentation_name().to_string(),
        }
    }
}

type UniqueSyncInstrument = Arc<dyn SyncInstrumentCore>;
type UniqueAsyncInstrument = Arc<dyn AsyncInstrumentCore>;