AWS SDK

AWS SDK

rev. 05bb688fced53156d14a86b12259a8bc7949d70c

Files changed:

tmp-codegen-diff/aws-sdk/sdk/aws-smithy-observability/README.md

@@ -0,1 +0,7 @@
           1  +
# aws-smithy-observability
           2  +
           3  +
This crate contains traits allowing for the implementation of `TelemetryProvider`s for the AWS SDK for Rust. It also contains a `global` module for setting and interacting with the current `GlobalTelemetryProvider`.
           4  +
           5  +
<!-- anchor_start:footer -->
           6  +
This crate is part of the [AWS SDK for Rust](https://awslabs.github.io/aws-sdk-rust/) and the [smithy-rs](https://github.com/smithy-lang/smithy-rs) code generator. In most cases, it should not be used directly.
           7  +
<!-- anchor_end:footer -->

tmp-codegen-diff/aws-sdk/sdk/aws-smithy-observability/external-types.toml

@@ -0,1 +0,3 @@
           1  +
allowed_external_types = [
           2  +
    "aws_smithy_runtime_api::box_error::BoxError",
           3  +
]

tmp-codegen-diff/aws-sdk/sdk/aws-smithy-observability/src/attributes.rs

@@ -0,1 +0,80 @@
           1  +
/*
           2  +
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
           3  +
 * SPDX-License-Identifier: Apache-2.0
           4  +
 */
           5  +
           6  +
//! Attributes (also referred to as tags or annotations in other telemetry systems) are structured
           7  +
//! key-value pairs that annotate a span or event. Structured data allows observability backends
           8  +
//! to index and process telemetry data in ways that simple log messages lack.
           9  +
          10  +
use std::collections::HashMap;
          11  +
          12  +
/// The valid types of values accepted by [Attributes].
          13  +
#[non_exhaustive]
          14  +
#[derive(Clone, Debug, PartialEq)]
          15  +
pub enum AttributeValue {
          16  +
    /// Holds an [i64]
          17  +
    I64(i64),
          18  +
    /// Holds an [f64]
          19  +
    F64(f64),
          20  +
    /// Holds a [String]
          21  +
    String(String),
          22  +
    /// Holds a [bool]
          23  +
    Bool(bool),
          24  +
}
          25  +
          26  +
/// Structured telemetry metadata.
          27  +
#[non_exhaustive]
          28  +
#[derive(Clone, Default)]
          29  +
pub struct Attributes {
          30  +
    attrs: HashMap<String, AttributeValue>,
          31  +
}
          32  +
          33  +
impl Attributes {
          34  +
    /// Create a new empty instance of [Attributes].
          35  +
    pub fn new() -> Self {
          36  +
        Self::default()
          37  +
    }
          38  +
          39  +
    /// Set an attribute.
          40  +
    pub fn set(&mut self, key: impl Into<String>, value: impl Into<AttributeValue>) {
          41  +
        self.attrs.insert(key.into(), value.into());
          42  +
    }
          43  +
          44  +
    /// Get an attribute.
          45  +
    pub fn get(&self, key: impl Into<String>) -> Option<&AttributeValue> {
          46  +
        self.attrs.get(&key.into())
          47  +
    }
          48  +
          49  +
    /// Get all of the attribute key value pairs.
          50  +
    pub fn attributes(&self) -> &HashMap<String, AttributeValue> {
          51  +
        &self.attrs
          52  +
    }
          53  +
          54  +
    /// Get an owned [Iterator] of ([String], [AttributeValue]).
          55  +
    pub fn into_attributes(self) -> impl Iterator<Item = (String, AttributeValue)> {
          56  +
        self.attrs.into_iter()
          57  +
    }
          58  +
}
          59  +
          60  +
/// Delineates a logical scope that has some beginning and end
          61  +
/// (e.g. a function or block of code).
          62  +
pub trait Scope {
          63  +
    /// invoke when the scope has ended.
          64  +
    fn end(&self);
          65  +
}
          66  +
          67  +
/// A cross cutting concern for carrying execution-scoped values across API
          68  +
/// boundaries (both in-process and distributed).
          69  +
pub trait Context {
          70  +
    /// Make this context the currently active context.
          71  +
    /// The returned handle is used to return the previous
          72  +
    /// context (if one existed) as active.
          73  +
    fn make_current(&self) -> &dyn Scope;
          74  +
}
          75  +
          76  +
/// Keeps track of the current [Context].
          77  +
pub trait ContextManager {
          78  +
    ///Get the currently active context.
          79  +
    fn current(&self) -> &dyn Context;
          80  +
}

tmp-codegen-diff/aws-sdk/sdk/aws-smithy-observability/src/error.rs

@@ -0,1 +0,86 @@
           1  +
/*
           2  +
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
           3  +
 * SPDX-License-Identifier: Apache-2.0
           4  +
 */
           5  +
           6  +
//! Observability Errors
           7  +
           8  +
use std::fmt;
           9  +
          10  +
use aws_smithy_runtime_api::box_error::BoxError;
          11  +
          12  +
/// An error in the SDKs Observability providers
          13  +
#[non_exhaustive]
          14  +
#[derive(Debug)]
          15  +
pub struct ObservabilityError {
          16  +
    kind: ErrorKind,
          17  +
    source: BoxError,
          18  +
}
          19  +
          20  +
/// The types of errors associated with [ObservabilityError]
          21  +
#[non_exhaustive]
          22  +
#[derive(Debug)]
          23  +
pub enum ErrorKind {
          24  +
    /// An error setting the global [crate::TelemetryProvider]
          25  +
    SettingGlobalProvider,
          26  +
    /// An error getting the global [crate::TelemetryProvider]
          27  +
    GettingGlobalProvider,
          28  +
    /// Error flushing metrics pipeline
          29  +
    MetricsFlush,
          30  +
    /// Error gracefully shutting down Metrics Provider
          31  +
    MetricsShutdown,
          32  +
    /// A custom error that does not fall under any other error kind
          33  +
    Other,
          34  +
}
          35  +
          36  +
impl ObservabilityError {
          37  +
    /// Create a new [`ObservabilityError`] from an [ErrorKind] and a [BoxError]
          38  +
    pub fn new<E>(kind: ErrorKind, err: E) -> Self
          39  +
    where
          40  +
        E: Into<BoxError>,
          41  +
    {
          42  +
        Self {
          43  +
            kind,
          44  +
            source: err.into(),
          45  +
        }
          46  +
    }
          47  +
          48  +
    /// Returns the corresponding [`ErrorKind`] for this error.
          49  +
    pub fn kind(&self) -> &ErrorKind {
          50  +
        &self.kind
          51  +
    }
          52  +
}
          53  +
          54  +
impl fmt::Display for ObservabilityError {
          55  +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
          56  +
        match &self.kind {
          57  +
            ErrorKind::Other => write!(f, "unclassified error"),
          58  +
            ErrorKind::SettingGlobalProvider => {
          59  +
                write!(f, "failed to set global TelemetryProvider")
          60  +
            }
          61  +
            ErrorKind::GettingGlobalProvider => {
          62  +
                write!(f, "failed to get global TelemetryProvider")
          63  +
            }
          64  +
            ErrorKind::MetricsFlush => write!(f, "failed to flush metrics pipeline"),
          65  +
            ErrorKind::MetricsShutdown => write!(f, "failed to shutdown metrics provider"),
          66  +
        }
          67  +
    }
          68  +
}
          69  +
          70  +
impl std::error::Error for ObservabilityError {
          71  +
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
          72  +
        Some(self.source.as_ref())
          73  +
    }
          74  +
}
          75  +
          76  +
/// An simple error to represent issues with the global [crate::TelemetryProvider].
          77  +
#[derive(Debug)]
          78  +
pub struct GlobalTelemetryProviderError;
          79  +
          80  +
impl std::error::Error for GlobalTelemetryProviderError {}
          81  +
          82  +
impl fmt::Display for GlobalTelemetryProviderError {
          83  +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
          84  +
        write!(f, "GlobalTelemetryProviderError")
          85  +
    }
          86  +
}

tmp-codegen-diff/aws-sdk/sdk/aws-smithy-observability/src/global.rs

@@ -0,1 +0,84 @@
           1  +
/*
           2  +
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
           3  +
 * SPDX-License-Identifier: Apache-2.0
           4  +
 */
           5  +
           6  +
//! Utilities for interacting with the currently set `GlobalTelemetryProvider`
           7  +
           8  +
use once_cell::sync::Lazy;
           9  +
use std::{
          10  +
    mem,
          11  +
    sync::{Arc, RwLock},
          12  +
};
          13  +
          14  +
use crate::{
          15  +
    error::{ErrorKind, GlobalTelemetryProviderError},
          16  +
    provider::{GlobalTelemetryProvider, TelemetryProvider},
          17  +
    ObservabilityError,
          18  +
};
          19  +
          20  +
// Statically store the global provider
          21  +
static GLOBAL_TELEMETRY_PROVIDER: Lazy<RwLock<GlobalTelemetryProvider>> =
          22  +
    Lazy::new(|| RwLock::new(GlobalTelemetryProvider::new(TelemetryProvider::default())));
          23  +
          24  +
/// Set the current global [TelemetryProvider].
          25  +
///
          26  +
/// This is meant to be run once at the beginning of an application. Will return an [Err] if the
          27  +
/// [RwLock] holding the global [TelemetryProvider] is locked or poisoned.
          28  +
pub fn set_telemetry_provider(new_provider: TelemetryProvider) -> Result<(), ObservabilityError> {
          29  +
    if let Ok(mut old_provider) = GLOBAL_TELEMETRY_PROVIDER.try_write() {
          30  +
        let new_global_provider = GlobalTelemetryProvider::new(new_provider);
          31  +
          32  +
        let _ = mem::replace(&mut *old_provider, new_global_provider);
          33  +
          34  +
        Ok(())
          35  +
    } else {
          36  +
        Err(ObservabilityError::new(
          37  +
            ErrorKind::GettingGlobalProvider,
          38  +
            GlobalTelemetryProviderError,
          39  +
        ))
          40  +
    }
          41  +
}
          42  +
          43  +
/// Get an [Arc] reference to the current global [TelemetryProvider]. Will return an [Err] if the
          44  +
/// [RwLock] holding the global [TelemetryProvider] is locked or poisoned.
          45  +
pub fn get_telemetry_provider() -> Result<Arc<TelemetryProvider>, ObservabilityError> {
          46  +
    if let Ok(tp) = GLOBAL_TELEMETRY_PROVIDER.try_read() {
          47  +
        Ok(tp.telemetry_provider().clone())
          48  +
    } else {
          49  +
        Err(ObservabilityError::new(
          50  +
            ErrorKind::GettingGlobalProvider,
          51  +
            GlobalTelemetryProviderError,
          52  +
        ))
          53  +
    }
          54  +
}
          55  +
          56  +
#[cfg(test)]
          57  +
mod tests {
          58  +
    use super::*;
          59  +
    use crate::provider::TelemetryProvider;
          60  +
    use serial_test::serial;
          61  +
          62  +
    // Note: the tests in this module are run serially to prevent them from stepping on each other and poisoning the
          63  +
    // RwLock holding the GlobalTelemetryProvider
          64  +
    #[test]
          65  +
    #[serial]
          66  +
    fn can_set_global_telemetry_provider() {
          67  +
        let my_provider = TelemetryProvider::default();
          68  +
          69  +
        // Set the new counter and get a reference to the old one
          70  +
        set_telemetry_provider(my_provider).unwrap();
          71  +
    }
          72  +
          73  +
    #[test]
          74  +
    #[serial]
          75  +
    fn can_get_global_telemetry_provider() {
          76  +
        let curr_provider = get_telemetry_provider().unwrap();
          77  +
          78  +
        // Use the global provider to create an instrument and record a value with it
          79  +
        let curr_mp = curr_provider.meter_provider();
          80  +
        let curr_meter = curr_mp.get_meter("TestMeter", None);
          81  +
        let instrument = curr_meter.create_monotonic_counter("TestMonoCounter".into(), None, None);
          82  +
        instrument.add(4, None, None);
          83  +
    }
          84  +
}

tmp-codegen-diff/aws-sdk/sdk/aws-smithy-observability/src/lib.rs

@@ -0,1 +0,28 @@
           1  +
/*
           2  +
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
           3  +
 * SPDX-License-Identifier: Apache-2.0
           4  +
 */
           5  +
           6  +
/* Automatically managed default lints */
           7  +
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
           8  +
/* End of automatically managed default lints */
           9  +
#![warn(
          10  +
    missing_docs,
          11  +
    rustdoc::missing_crate_level_docs,
          12  +
    unreachable_pub,
          13  +
    rust_2018_idioms
          14  +
)]
          15  +
          16  +
//! Smithy Observability
          17  +
// TODO(smithyobservability): once we have finalized everything and integrated metrics with our runtime
          18  +
// libraries update this with detailed usage docs and examples
          19  +
          20  +
pub mod attributes;
          21  +
pub use attributes::{AttributeValue, Attributes};
          22  +
pub mod error;
          23  +
pub use error::{ErrorKind, ObservabilityError};
          24  +
pub mod global;
          25  +
pub mod meter;
          26  +
mod noop;
          27  +
pub mod provider;
          28  +
pub use provider::{TelemetryProvider, TelemetryProviderBuilder};

tmp-codegen-diff/aws-sdk/sdk/aws-smithy-observability/src/meter.rs

@@ -0,1 +0,111 @@
           1  +
/*
           2  +
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
           3  +
 * SPDX-License-Identifier: Apache-2.0
           4  +
 */
           5  +
           6  +
//! Metrics are used to gain insight into the operational performance and health of a system in
           7  +
//! real time.
           8  +
           9  +
use crate::attributes::{Attributes, Context};
          10  +
use std::{fmt::Debug, sync::Arc};
          11  +
          12  +
/// Provides named instances of [Meter].
          13  +
pub trait ProvideMeter: Send + Sync + Debug {
          14  +
    /// Get or create a named [Meter].
          15  +
    fn get_meter(&self, scope: &'static str, attributes: Option<&Attributes>) -> Arc<dyn Meter>;
          16  +
          17  +
    /// Foo
          18  +
    fn as_any(&self) -> &dyn std::any::Any;
          19  +
}
          20  +
          21  +
/// The entry point to creating instruments. A grouping of related metrics.
          22  +
pub trait Meter: Send + Sync + Debug {
          23  +
    /// Create a new Gauge.
          24  +
    #[allow(clippy::type_complexity)]
          25  +
    fn create_gauge(
          26  +
        &self,
          27  +
        name: String,
          28  +
        callback: Box<dyn Fn(&dyn AsyncMeasure<Value = f64>) + Send + Sync>,
          29  +
        units: Option<String>,
          30  +
        description: Option<String>,
          31  +
    ) -> Arc<dyn AsyncMeasure<Value = f64>>;
          32  +
          33  +
    /// Create a new [UpDownCounter].
          34  +
    fn create_up_down_counter(
          35  +
        &self,
          36  +
        name: String,
          37  +
        units: Option<String>,
          38  +
        description: Option<String>,
          39  +
    ) -> Arc<dyn UpDownCounter>;
          40  +
          41  +
    /// Create a new AsyncUpDownCounter.
          42  +
    #[allow(clippy::type_complexity)]
          43  +
    fn create_async_up_down_counter(
          44  +
        &self,
          45  +
        name: String,
          46  +
        callback: Box<dyn Fn(&dyn AsyncMeasure<Value = i64>) + Send + Sync>,
          47  +
        units: Option<String>,
          48  +
        description: Option<String>,
          49  +
    ) -> Arc<dyn AsyncMeasure<Value = i64>>;
          50  +
          51  +
    /// Create a new [MonotonicCounter].
          52  +
    fn create_monotonic_counter(
          53  +
        &self,
          54  +
        name: String,
          55  +
        units: Option<String>,
          56  +
        description: Option<String>,
          57  +
    ) -> Arc<dyn MonotonicCounter>;
          58  +
          59  +
    /// Create a new AsyncMonotonicCounter.
          60  +
    #[allow(clippy::type_complexity)]
          61  +
    fn create_async_monotonic_counter(
          62  +
        &self,
          63  +
        name: String,
          64  +
        callback: Box<dyn Fn(&dyn AsyncMeasure<Value = u64>) + Send + Sync>,
          65  +
        units: Option<String>,
          66  +
        description: Option<String>,
          67  +
    ) -> Arc<dyn AsyncMeasure<Value = u64>>;
          68  +
          69  +
    /// Create a new [Histogram].
          70  +
    fn create_histogram(
          71  +
        &self,
          72  +
        name: String,
          73  +
        units: Option<String>,
          74  +
        description: Option<String>,
          75  +
    ) -> Arc<dyn Histogram>;
          76  +
}
          77  +
          78  +
/// Collects a set of events with an event count and sum for all events.
          79  +
pub trait Histogram: Send + Sync + Debug {
          80  +
    /// Record a value.
          81  +
    fn record(&self, value: f64, attributes: Option<&Attributes>, context: Option<&dyn Context>);
          82  +
}
          83  +
          84  +
/// A counter that monotonically increases.
          85  +
pub trait MonotonicCounter: Send + Sync + Debug {
          86  +
    /// Increment a counter by a fixed amount.
          87  +
    fn add(&self, value: u64, attributes: Option<&Attributes>, context: Option<&dyn Context>);
          88  +
}
          89  +
          90  +
/// A counter that can increase or decrease.
          91  +
pub trait UpDownCounter: Send + Sync + Debug {
          92  +
    /// Increment or decrement a counter by a fixed amount.
          93  +
    fn add(&self, value: i64, attributes: Option<&Attributes>, context: Option<&dyn Context>);
          94  +
}
          95  +
          96  +
/// A measurement that can be taken asynchronously.
          97  +
pub trait AsyncMeasure: Send + Sync + Debug {
          98  +
    /// The type recorded by the measurement.
          99  +
    type Value;
         100  +
         101  +
    /// Record a value
         102  +
    fn record(
         103  +
        &self,
         104  +
        value: Self::Value,
         105  +
        attributes: Option<&Attributes>,
         106  +
        context: Option<&dyn Context>,
         107  +
    );
         108  +
         109  +
    /// Stop recording, unregister callback.
         110  +
    fn stop(&self);
         111  +
}

tmp-codegen-diff/aws-sdk/sdk/aws-smithy-observability/src/noop.rs

@@ -0,1 +0,121 @@
           1  +
/*
           2  +
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
           3  +
 * SPDX-License-Identifier: Apache-2.0
           4  +
 */
           5  +
           6  +
//! An noop implementation of the Meter traits
           7  +
           8  +
use std::marker::PhantomData;
           9  +
use std::{fmt::Debug, sync::Arc};
          10  +
          11  +
use crate::{
          12  +
    attributes::{Attributes, Context},
          13  +
    meter::{AsyncMeasure, Histogram, Meter, MonotonicCounter, ProvideMeter, UpDownCounter},
          14  +
};
          15  +
          16  +
#[derive(Debug)]
          17  +
pub(crate) struct NoopMeterProvider;
          18  +
impl ProvideMeter for NoopMeterProvider {
          19  +
    fn get_meter(&self, _scope: &'static str, _attributes: Option<&Attributes>) -> Arc<dyn Meter> {
          20  +
        Arc::new(NoopMeter)
          21  +
    }
          22  +
          23  +
    fn as_any(&self) -> &dyn std::any::Any {
          24  +
        self
          25  +
    }
          26  +
}
          27  +
          28  +
#[derive(Debug)]
          29  +
pub(crate) struct NoopMeter;
          30  +
impl Meter for NoopMeter {
          31  +
    fn create_gauge(
          32  +
        &self,
          33  +
        _name: String,
          34  +
        _callback: Box<dyn Fn(&dyn AsyncMeasure<Value = f64>) + Send + Sync>,
          35  +
        _units: Option<String>,
          36  +
        _description: Option<String>,
          37  +
    ) -> Arc<dyn AsyncMeasure<Value = f64>> {
          38  +
        Arc::new(NoopAsyncMeasurement(PhantomData::<f64>))
          39  +
    }
          40  +
          41  +
    fn create_up_down_counter(
          42  +
        &self,
          43  +
        _name: String,
          44  +
        _units: Option<String>,
          45  +
        _description: Option<String>,
          46  +
    ) -> Arc<dyn UpDownCounter> {
          47  +
        Arc::new(NoopUpDownCounter)
          48  +
    }
          49  +
          50  +
    fn create_async_up_down_counter(
          51  +
        &self,
          52  +
        _name: String,
          53  +
        _callback: Box<dyn Fn(&dyn AsyncMeasure<Value = i64>) + Send + Sync>,
          54  +
        _units: Option<String>,
          55  +
        _description: Option<String>,
          56  +
    ) -> Arc<dyn AsyncMeasure<Value = i64>> {
          57  +
        Arc::new(NoopAsyncMeasurement(PhantomData::<i64>))
          58  +
    }
          59  +
          60  +
    fn create_monotonic_counter(
          61  +
        &self,
          62  +
        _name: String,
          63  +
        _units: Option<String>,
          64  +
        _description: Option<String>,
          65  +
    ) -> Arc<dyn MonotonicCounter> {
          66  +
        Arc::new(NoopMonotonicCounter)
          67  +
    }
          68  +
          69  +
    fn create_async_monotonic_counter(
          70  +
        &self,
          71  +
        _name: String,
          72  +
        _callback: Box<dyn Fn(&dyn AsyncMeasure<Value = u64>) + Send + Sync>,
          73  +
        _units: Option<String>,
          74  +
        _description: Option<String>,
          75  +
    ) -> Arc<dyn AsyncMeasure<Value = u64>> {
          76  +
        Arc::new(NoopAsyncMeasurement(PhantomData::<u64>))
          77  +
    }
          78  +
          79  +
    fn create_histogram(
          80  +
        &self,
          81  +
        _name: String,
          82  +
        _units: Option<String>,
          83  +
        _description: Option<String>,
          84  +
    ) -> Arc<dyn Histogram> {
          85  +
        Arc::new(NoopHistogram)
          86  +
    }
          87  +
}
          88  +
          89  +
#[derive(Debug)]
          90  +
struct NoopAsyncMeasurement<T: Send + Sync + Debug>(PhantomData<T>);
          91  +
impl<T: Send + Sync + Debug> AsyncMeasure for NoopAsyncMeasurement<T> {
          92  +
    type Value = T;
          93  +
          94  +
    fn record(&self, _value: T, _attributes: Option<&Attributes>, _context: Option<&dyn Context>) {}
          95  +
          96  +
    fn stop(&self) {}
          97  +
}
          98  +
          99  +
#[derive(Debug)]
         100  +
struct NoopUpDownCounter;
         101  +
impl UpDownCounter for NoopUpDownCounter {
         102  +
    fn add(&self, _value: i64, _attributes: Option<&Attributes>, _context: Option<&dyn Context>) {}
         103  +
}
         104  +
         105  +
#[derive(Debug)]
         106  +
struct NoopMonotonicCounter;
         107  +
impl MonotonicCounter for NoopMonotonicCounter {
         108  +
    fn add(&self, _value: u64, _attributes: Option<&Attributes>, _context: Option<&dyn Context>) {}
         109  +
}
         110  +
         111  +
#[derive(Debug)]
         112  +
struct NoopHistogram;
         113  +
impl Histogram for NoopHistogram {
         114  +
    fn record(
         115  +
        &self,
         116  +
        _value: f64,
         117  +
        _attributes: Option<&Attributes>,
         118  +
        _context: Option<&dyn Context>,
         119  +
    ) {
         120  +
    }
         121  +
}

tmp-codegen-diff/aws-sdk/sdk/aws-smithy-observability/src/provider.rs

@@ -0,1 +0,89 @@
           1  +
/*
           2  +
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
           3  +
 * SPDX-License-Identifier: Apache-2.0
           4  +
 */
           5  +
           6  +
//! Definitions of high level Telemetry Providers.
           7  +
           8  +
use std::sync::Arc;
           9  +
          10  +
use crate::{meter::ProvideMeter, noop::NoopMeterProvider};
          11  +
          12  +
/// A struct to hold the various types of telemetry providers.
          13  +
#[non_exhaustive]
          14  +
pub struct TelemetryProvider {
          15  +
    meter_provider: Box<dyn ProvideMeter + Send + Sync>,
          16  +
}
          17  +
          18  +
impl TelemetryProvider {
          19  +
    /// Returns a builder struct for [TelemetryProvider]
          20  +
    pub fn builder() -> TelemetryProviderBuilder {
          21  +
        TelemetryProviderBuilder {
          22  +
            meter_provider: Box::new(NoopMeterProvider),
          23  +
        }
          24  +
    }
          25  +
          26  +
    /// Returns a noop [TelemetryProvider]
          27  +
    pub fn noop() -> TelemetryProvider {
          28  +
        Self {
          29  +
            meter_provider: Box::new(NoopMeterProvider),
          30  +
        }
          31  +
    }
          32  +
          33  +
    /// Get the set [ProvideMeter]
          34  +
    pub fn meter_provider(&self) -> &(dyn ProvideMeter + Send + Sync) {
          35  +
        self.meter_provider.as_ref()
          36  +
    }
          37  +
}
          38  +
          39  +
// If we choose to expand our Telemetry provider and make Logging and Tracing
          40  +
// configurable at some point in the future we can do that by adding default
          41  +
// logger_provider and tracer_providers based on `tracing` to maintain backwards
          42  +
// compatibilty with what we have today.
          43  +
impl Default for TelemetryProvider {
          44  +
    fn default() -> Self {
          45  +
        Self {
          46  +
            meter_provider: Box::new(NoopMeterProvider),
          47  +
        }
          48  +
    }
          49  +
}
          50  +
          51  +
/// A builder for [TelemetryProvider].
          52  +
#[non_exhaustive]
          53  +
pub struct TelemetryProviderBuilder {
          54  +
    meter_provider: Box<dyn ProvideMeter + Send + Sync>,
          55  +
}
          56  +
          57  +
impl TelemetryProviderBuilder {
          58  +
    /// Set the [ProvideMeter].
          59  +
    pub fn meter_provider(mut self, meter_provider: impl ProvideMeter + 'static) -> Self {
          60  +
        self.meter_provider = Box::new(meter_provider);
          61  +
        self
          62  +
    }
          63  +
          64  +
    /// Build the [TelemetryProvider].
          65  +
    pub fn build(self) -> TelemetryProvider {
          66  +
        TelemetryProvider {
          67  +
            meter_provider: self.meter_provider,
          68  +
        }
          69  +
    }
          70  +
}
          71  +
          72  +
/// Wrapper type to hold a implementer of TelemetryProvider in an Arc so that
          73  +
/// it can be safely used across threads.
          74  +
#[non_exhaustive]
          75  +
pub(crate) struct GlobalTelemetryProvider {
          76  +
    pub(crate) telemetry_provider: Arc<TelemetryProvider>,
          77  +
}
          78  +
          79  +
impl GlobalTelemetryProvider {
          80  +
    pub(crate) fn new(telemetry_provider: TelemetryProvider) -> Self {
          81  +
        Self {
          82  +
            telemetry_provider: Arc::new(telemetry_provider),
          83  +
        }
          84  +
    }
          85  +
          86  +
    pub(crate) fn telemetry_provider(&self) -> &Arc<TelemetryProvider> {
          87  +
        &self.telemetry_provider
          88  +
    }
          89  +
}