opentelemetry_sdk/metrics/reader.rs
1//! Interfaces for reading and producing metrics
2use std::{fmt, sync::Weak};
3
4use crate::{error::OTelSdkResult, metrics::MetricResult};
5
6use super::{data::ResourceMetrics, pipeline::Pipeline, InstrumentKind, Temporality};
7
8/// The interface used between the SDK and an exporter.
9///
10/// Control flow is bi-directional through the `MetricReader`, since the SDK
11/// initiates `force_flush` and `shutdown` while the reader initiates
12/// collection. The `register_pipeline` method here informs the metric reader
13/// that it can begin reading, signaling the start of bi-directional control
14/// flow.
15///
16/// Typically, push-based exporters that are periodic will implement
17/// `MetricExporter` themselves and construct a `PeriodicReader` to satisfy this
18/// interface.
19///
20/// Pull-based exporters will typically implement `MetricReader` themselves,
21/// since they read on demand.
22pub trait MetricReader: fmt::Debug + Send + Sync + 'static {
23 /// Registers a [MetricReader] with a [Pipeline].
24 ///
25 /// The pipeline argument allows the `MetricReader` to signal the sdk to collect
26 /// and send aggregated metric measurements.
27 fn register_pipeline(&self, pipeline: Weak<Pipeline>);
28
29 /// Gathers and returns all metric data related to the [MetricReader] from the
30 /// SDK and stores it in the provided [ResourceMetrics] reference.
31 ///
32 /// An error is returned if this is called after shutdown.
33 fn collect(&self, rm: &mut ResourceMetrics) -> MetricResult<()>;
34
35 /// Flushes all metric measurements held in an export pipeline.
36 ///
37 /// There is no guaranteed that all telemetry be flushed or all resources have
38 /// been released on error.
39 fn force_flush(&self) -> OTelSdkResult;
40
41 /// Flushes all metric measurements held in an export pipeline and releases any
42 /// held computational resources.
43 ///
44 /// There is no guaranteed that all telemetry be flushed or all resources have
45 /// been released on error.
46 ///
47 /// After `shutdown` is called, calls to `collect` will perform no operation and
48 /// instead will return an error indicating the shutdown state.
49 fn shutdown(&self) -> OTelSdkResult;
50
51 /// The output temporality, a function of instrument kind.
52 /// This SHOULD be obtained from the exporter.
53 ///
54 /// If not configured, the Cumulative temporality SHOULD be used.
55 fn temporality(&self, kind: InstrumentKind) -> Temporality;
56}
57
58/// Produces metrics for a [MetricReader].
59pub(crate) trait SdkProducer: fmt::Debug + Send + Sync {
60 /// Returns aggregated metrics from a single collection.
61 fn produce(&self, rm: &mut ResourceMetrics) -> MetricResult<()>;
62}