Skip to content

Commit f3be05b

Browse files
refactor: update metrics Result to be MetricResult (#2241)
Co-authored-by: Cijo Thomas <cijo.thomas@gmail.com>
1 parent 9382bfb commit f3be05b

File tree

25 files changed

+162
-159
lines changed

25 files changed

+162
-159
lines changed

CONTRIBUTING.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ For a deeper discussion, see:
140140

141141
Currently, the Opentelemetry Rust SDK has two ways to handle errors. In the situation where errors are not allowed to return. One should call global error handler to process the errors. Otherwise, one should return the errors.
142142

143-
The Opentelemetry Rust SDK comes with an error type `opentelemetry::Error`. For different function, one error has been defined. All error returned by trace module MUST be wrapped in `opentelemetry::trace::TraceError`. All errors returned by metrics module MUST be wrapped in `opentelemetry::metrics::MetricsError`. All errors returned by logs module MUST be wrapped in `opentelemetry::logs::LogsError`.
143+
The Opentelemetry Rust SDK comes with an error type `opentelemetry::Error`. For different function, one error has been defined. All error returned by trace module MUST be wrapped in `opentelemetry::trace::TraceError`. All errors returned by metrics module MUST be wrapped in `opentelemetry::metrics::MetricError`. All errors returned by logs module MUST be wrapped in `opentelemetry::logs::LogsError`.
144144

145145
For users that want to implement their own exporters. It's RECOMMENDED to wrap all errors from the exporter into a crate-level error type, and implement `ExporterError` trait.
146146

opentelemetry-otlp/examples/basic-otlp-http/src/main.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use once_cell::sync::Lazy;
22
use opentelemetry::{
33
global,
4-
metrics::MetricsError,
4+
metrics::MetricError,
55
trace::{TraceContextExt, TraceError, Tracer},
66
InstrumentationScope, KeyValue,
77
};
@@ -65,7 +65,7 @@ fn init_tracer_provider() -> Result<sdktrace::TracerProvider, TraceError> {
6565
.build())
6666
}
6767

68-
fn init_metrics() -> Result<opentelemetry_sdk::metrics::SdkMeterProvider, MetricsError> {
68+
fn init_metrics() -> Result<opentelemetry_sdk::metrics::SdkMeterProvider, MetricError> {
6969
let exporter = MetricsExporter::builder()
7070
.with_http()
7171
.with_protocol(Protocol::HttpBinary) //can be changed to `Protocol::HttpJson` to export in JSON format

opentelemetry-otlp/examples/basic-otlp/src/main.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use once_cell::sync::Lazy;
22
use opentelemetry::logs::LogError;
3-
use opentelemetry::metrics::MetricsError;
3+
use opentelemetry::metrics::MetricError;
44
use opentelemetry::trace::{TraceContextExt, TraceError, Tracer};
55
use opentelemetry::KeyValue;
66
use opentelemetry::{global, InstrumentationScope};
@@ -33,7 +33,7 @@ fn init_tracer_provider() -> Result<sdktrace::TracerProvider, TraceError> {
3333
.build())
3434
}
3535

36-
fn init_metrics() -> Result<opentelemetry_sdk::metrics::SdkMeterProvider, MetricsError> {
36+
fn init_metrics() -> Result<opentelemetry_sdk::metrics::SdkMeterProvider, MetricError> {
3737
let exporter = MetricsExporter::builder().with_tonic().build()?;
3838

3939
let reader = PeriodicReader::builder(exporter, runtime::Tokio).build();

opentelemetry-otlp/src/exporter/http/metrics.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::sync::Arc;
22

33
use async_trait::async_trait;
44
use http::{header::CONTENT_TYPE, Method};
5-
use opentelemetry::metrics::{MetricsError, Result};
5+
use opentelemetry::metrics::{MetricError, MetricResult};
66
use opentelemetry_sdk::metrics::data::ResourceMetrics;
77

88
use crate::{metric::MetricsClient, Error};
@@ -11,14 +11,14 @@ use super::OtlpHttpClient;
1111

1212
#[async_trait]
1313
impl MetricsClient for OtlpHttpClient {
14-
async fn export(&self, metrics: &mut ResourceMetrics) -> Result<()> {
14+
async fn export(&self, metrics: &mut ResourceMetrics) -> MetricResult<()> {
1515
let client = self
1616
.client
1717
.lock()
1818
.map_err(Into::into)
1919
.and_then(|g| match &*g {
2020
Some(client) => Ok(Arc::clone(client)),
21-
_ => Err(MetricsError::Other("exporter is already shut down".into())),
21+
_ => Err(MetricError::Other("exporter is already shut down".into())),
2222
})?;
2323

2424
let (body, content_type) = self.build_metrics_export_body(metrics)?;
@@ -36,12 +36,12 @@ impl MetricsClient for OtlpHttpClient {
3636
client
3737
.send(request)
3838
.await
39-
.map_err(|e| MetricsError::ExportErr(Box::new(Error::RequestFailed(e))))?;
39+
.map_err(|e| MetricError::ExportErr(Box::new(Error::RequestFailed(e))))?;
4040

4141
Ok(())
4242
}
4343

44-
fn shutdown(&self) -> Result<()> {
44+
fn shutdown(&self) -> MetricResult<()> {
4545
let _ = self.client.lock()?.take();
4646

4747
Ok(())

opentelemetry-otlp/src/exporter/http/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ impl HttpExporterBuilder {
221221
pub fn build_metrics_exporter(
222222
mut self,
223223
temporality: opentelemetry_sdk::metrics::data::Temporality,
224-
) -> opentelemetry::metrics::Result<crate::MetricsExporter> {
224+
) -> opentelemetry::metrics::MetricResult<crate::MetricsExporter> {
225225
use crate::{
226226
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, OTEL_EXPORTER_OTLP_METRICS_HEADERS,
227227
OTEL_EXPORTER_OTLP_METRICS_TIMEOUT,
@@ -311,7 +311,7 @@ impl OtlpHttpClient {
311311
fn build_metrics_export_body(
312312
&self,
313313
metrics: &mut opentelemetry_sdk::metrics::data::ResourceMetrics,
314-
) -> opentelemetry::metrics::Result<(Vec<u8>, &'static str)> {
314+
) -> opentelemetry::metrics::MetricResult<(Vec<u8>, &'static str)> {
315315
use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest;
316316

317317
let req: ExportMetricsServiceRequest = (&*metrics).into();
@@ -320,7 +320,7 @@ impl OtlpHttpClient {
320320
#[cfg(feature = "http-json")]
321321
Protocol::HttpJson => match serde_json::to_string_pretty(&req) {
322322
Ok(json) => Ok((json.into(), "application/json")),
323-
Err(e) => Err(opentelemetry::metrics::MetricsError::Other(e.to_string())),
323+
Err(e) => Err(opentelemetry::metrics::MetricError::Other(e.to_string())),
324324
},
325325
_ => Ok((req.encode_to_vec(), "application/x-protobuf")),
326326
}

opentelemetry-otlp/src/exporter/tonic/metrics.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use core::fmt;
22
use std::sync::Mutex;
33

44
use async_trait::async_trait;
5-
use opentelemetry::metrics::{MetricsError, Result};
5+
use opentelemetry::metrics::{MetricError, MetricResult};
66
use opentelemetry_proto::tonic::collector::metrics::v1::{
77
metrics_service_client::MetricsServiceClient, ExportMetricsServiceRequest,
88
};
@@ -51,7 +51,7 @@ impl TonicMetricsClient {
5151

5252
#[async_trait]
5353
impl MetricsClient for TonicMetricsClient {
54-
async fn export(&self, metrics: &mut ResourceMetrics) -> Result<()> {
54+
async fn export(&self, metrics: &mut ResourceMetrics) -> MetricResult<()> {
5555
let (mut client, metadata, extensions) =
5656
self.inner
5757
.lock()
@@ -62,14 +62,14 @@ impl MetricsClient for TonicMetricsClient {
6262
.interceptor
6363
.call(Request::new(()))
6464
.map_err(|e| {
65-
MetricsError::Other(format!(
65+
MetricError::Other(format!(
6666
"unexpected status while exporting {e:?}"
6767
))
6868
})?
6969
.into_parts();
7070
Ok((inner.client.clone(), m, e))
7171
}
72-
None => Err(MetricsError::Other("exporter is already shut down".into())),
72+
None => Err(MetricError::Other("exporter is already shut down".into())),
7373
})?;
7474

7575
client
@@ -84,7 +84,7 @@ impl MetricsClient for TonicMetricsClient {
8484
Ok(())
8585
}
8686

87-
fn shutdown(&self) -> Result<()> {
87+
fn shutdown(&self) -> MetricResult<()> {
8888
let _ = self.inner.lock()?.take();
8989

9090
Ok(())

opentelemetry-otlp/src/exporter/tonic/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ impl TonicExporterBuilder {
274274
pub(crate) fn build_metrics_exporter(
275275
self,
276276
temporality: opentelemetry_sdk::metrics::data::Temporality,
277-
) -> opentelemetry::metrics::Result<crate::MetricsExporter> {
277+
) -> opentelemetry::metrics::MetricResult<crate::MetricsExporter> {
278278
use crate::MetricsExporter;
279279
use metrics::TonicMetricsClient;
280280

opentelemetry-otlp/src/metric.rs

+8-8
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use crate::NoExporterBuilderSet;
1616

1717
use async_trait::async_trait;
1818
use core::fmt;
19-
use opentelemetry::metrics::Result;
19+
use opentelemetry::metrics::MetricResult;
2020

2121
use opentelemetry_sdk::metrics::{
2222
data::{ResourceMetrics, Temporality},
@@ -77,15 +77,15 @@ impl<C> MetricsExporterBuilder<C> {
7777

7878
#[cfg(feature = "grpc-tonic")]
7979
impl MetricsExporterBuilder<TonicExporterBuilderSet> {
80-
pub fn build(self) -> Result<MetricsExporter> {
80+
pub fn build(self) -> MetricResult<MetricsExporter> {
8181
let exporter = self.client.0.build_metrics_exporter(self.temporality)?;
8282
Ok(exporter)
8383
}
8484
}
8585

8686
#[cfg(any(feature = "http-proto", feature = "http-json"))]
8787
impl MetricsExporterBuilder<HttpExporterBuilderSet> {
88-
pub fn build(self) -> Result<MetricsExporter> {
88+
pub fn build(self) -> MetricResult<MetricsExporter> {
8989
let exporter = self.client.0.build_metrics_exporter(self.temporality)?;
9090
Ok(exporter)
9191
}
@@ -122,8 +122,8 @@ impl HasHttpConfig for MetricsExporterBuilder<HttpExporterBuilderSet> {
122122
/// An interface for OTLP metrics clients
123123
#[async_trait]
124124
pub trait MetricsClient: fmt::Debug + Send + Sync + 'static {
125-
async fn export(&self, metrics: &mut ResourceMetrics) -> Result<()>;
126-
fn shutdown(&self) -> Result<()>;
125+
async fn export(&self, metrics: &mut ResourceMetrics) -> MetricResult<()>;
126+
fn shutdown(&self) -> MetricResult<()>;
127127
}
128128

129129
/// Export metrics in OTEL format.
@@ -140,16 +140,16 @@ impl Debug for MetricsExporter {
140140

141141
#[async_trait]
142142
impl PushMetricsExporter for MetricsExporter {
143-
async fn export(&self, metrics: &mut ResourceMetrics) -> Result<()> {
143+
async fn export(&self, metrics: &mut ResourceMetrics) -> MetricResult<()> {
144144
self.client.export(metrics).await
145145
}
146146

147-
async fn force_flush(&self) -> Result<()> {
147+
async fn force_flush(&self) -> MetricResult<()> {
148148
// this component is stateless
149149
Ok(())
150150
}
151151

152-
fn shutdown(&self) -> Result<()> {
152+
fn shutdown(&self) -> MetricResult<()> {
153153
self.client.shutdown()
154154
}
155155

opentelemetry-proto/src/transform/metrics.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ pub mod tonic {
88
use std::any::Any;
99
use std::fmt;
1010

11-
use opentelemetry::{global, metrics::MetricsError, Key, Value};
11+
use opentelemetry::{global, metrics::MetricError, Key, Value};
1212
use opentelemetry_sdk::metrics::data::{
1313
self, Exemplar as SdkExemplar, ExponentialHistogram as SdkExponentialHistogram,
1414
Gauge as SdkGauge, Histogram as SdkHistogram, Metric as SdkMetric,
@@ -97,7 +97,7 @@ pub mod tonic {
9797
Temporality::Cumulative => AggregationTemporality::Cumulative,
9898
Temporality::Delta => AggregationTemporality::Delta,
9999
other => {
100-
opentelemetry::global::handle_error(MetricsError::Other(format!(
100+
opentelemetry::global::handle_error(MetricError::Other(format!(
101101
"Unknown temporality {:?}, using default instead.",
102102
other
103103
)));
@@ -184,7 +184,7 @@ pub mod tonic {
184184
} else if let Some(gauge) = data.downcast_ref::<SdkGauge<f64>>() {
185185
Ok(TonicMetricData::Gauge(gauge.into()))
186186
} else {
187-
global::handle_error(MetricsError::Other("unknown aggregator".into()));
187+
global::handle_error(MetricError::Other("unknown aggregator".into()));
188188
Err(())
189189
}
190190
}

opentelemetry-sdk/benches/metric.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::sync::{Arc, Weak};
33

44
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
55
use opentelemetry::{
6-
metrics::{Counter, Histogram, MeterProvider as _, Result},
6+
metrics::{Counter, Histogram, MeterProvider as _, MetricResult},
77
Key, KeyValue,
88
};
99
use opentelemetry_sdk::{
@@ -25,15 +25,15 @@ impl MetricReader for SharedReader {
2525
self.0.register_pipeline(pipeline)
2626
}
2727

28-
fn collect(&self, rm: &mut ResourceMetrics) -> Result<()> {
28+
fn collect(&self, rm: &mut ResourceMetrics) -> MetricResult<()> {
2929
self.0.collect(rm)
3030
}
3131

32-
fn force_flush(&self) -> Result<()> {
32+
fn force_flush(&self) -> MetricResult<()> {
3333
self.0.force_flush()
3434
}
3535

36-
fn shutdown(&self) -> Result<()> {
36+
fn shutdown(&self) -> MetricResult<()> {
3737
self.0.shutdown()
3838
}
3939

opentelemetry-sdk/src/metrics/aggregation.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::fmt;
22

33
use crate::metrics::internal::{EXPO_MAX_SCALE, EXPO_MIN_SCALE};
4-
use opentelemetry::metrics::{MetricsError, Result};
4+
use opentelemetry::metrics::{MetricError, MetricResult};
55

66
/// The way recorded measurements are summarized.
77
#[derive(Clone, Debug, PartialEq)]
@@ -109,7 +109,7 @@ impl fmt::Display for Aggregation {
109109

110110
impl Aggregation {
111111
/// Validate that this aggregation has correct configuration
112-
pub fn validate(&self) -> Result<()> {
112+
pub fn validate(&self) -> MetricResult<()> {
113113
match self {
114114
Aggregation::Drop => Ok(()),
115115
Aggregation::Default => Ok(()),
@@ -118,7 +118,7 @@ impl Aggregation {
118118
Aggregation::ExplicitBucketHistogram { boundaries, .. } => {
119119
for x in boundaries.windows(2) {
120120
if x[0] >= x[1] {
121-
return Err(MetricsError::Config(format!(
121+
return Err(MetricError::Config(format!(
122122
"aggregation: explicit bucket histogram: non-monotonic boundaries: {:?}",
123123
boundaries,
124124
)));
@@ -129,13 +129,13 @@ impl Aggregation {
129129
}
130130
Aggregation::Base2ExponentialHistogram { max_scale, .. } => {
131131
if *max_scale > EXPO_MAX_SCALE {
132-
return Err(MetricsError::Config(format!(
132+
return Err(MetricError::Config(format!(
133133
"aggregation: exponential histogram: max scale ({}) is greater than 20",
134134
max_scale,
135135
)));
136136
}
137137
if *max_scale < EXPO_MIN_SCALE {
138-
return Err(MetricsError::Config(format!(
138+
return Err(MetricError::Config(format!(
139139
"aggregation: exponential histogram: max scale ({}) is less than -10",
140140
max_scale,
141141
)));
@@ -153,17 +153,17 @@ mod tests {
153153
internal::{EXPO_MAX_SCALE, EXPO_MIN_SCALE},
154154
Aggregation,
155155
};
156-
use opentelemetry::metrics::{MetricsError, Result};
156+
use opentelemetry::metrics::{MetricError, MetricResult};
157157

158158
#[test]
159159
fn validate_aggregation() {
160160
struct TestCase {
161161
name: &'static str,
162162
input: Aggregation,
163-
check: Box<dyn Fn(Result<()>) -> bool>,
163+
check: Box<dyn Fn(MetricResult<()>) -> bool>,
164164
}
165-
let ok = Box::new(|result: Result<()>| result.is_ok());
166-
let config_error = Box::new(|result| matches!(result, Err(MetricsError::Config(_))));
165+
let ok = Box::new(|result: MetricResult<()>| result.is_ok());
166+
let config_error = Box::new(|result| matches!(result, Err(MetricError::Config(_))));
167167

168168
let test_cases: Vec<TestCase> = vec![
169169
TestCase {

opentelemetry-sdk/src/metrics/exporter.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Interfaces for exporting metrics
22
use async_trait::async_trait;
33

4-
use opentelemetry::metrics::Result;
4+
use opentelemetry::metrics::MetricResult;
55

66
use crate::metrics::data::ResourceMetrics;
77

@@ -18,16 +18,16 @@ pub trait PushMetricsExporter: Send + Sync + 'static {
1818
/// implement any retry logic. All errors returned by this function are
1919
/// considered unrecoverable and will be reported to a configured error
2020
/// Handler.
21-
async fn export(&self, metrics: &mut ResourceMetrics) -> Result<()>;
21+
async fn export(&self, metrics: &mut ResourceMetrics) -> MetricResult<()>;
2222

2323
/// Flushes any metric data held by an exporter.
24-
async fn force_flush(&self) -> Result<()>;
24+
async fn force_flush(&self) -> MetricResult<()>;
2525

2626
/// Releases any held computational resources.
2727
///
2828
/// After Shutdown is called, calls to Export will perform no operation and
2929
/// instead will return an error indicating the shutdown state.
30-
fn shutdown(&self) -> Result<()>;
30+
fn shutdown(&self) -> MetricResult<()>;
3131

3232
/// Access the [Temporality] of the MetricsExporter.
3333
fn temporality(&self) -> Temporality;

opentelemetry-sdk/src/metrics/internal/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use aggregate::is_under_cardinality_limit;
1616
pub(crate) use aggregate::{AggregateBuilder, ComputeAggregation, Measure};
1717
pub(crate) use exponential_histogram::{EXPO_MAX_SCALE, EXPO_MIN_SCALE};
1818
use once_cell::sync::Lazy;
19-
use opentelemetry::metrics::MetricsError;
19+
use opentelemetry::metrics::MetricError;
2020
use opentelemetry::{global, otel_warn, KeyValue};
2121

2222
use crate::metrics::AttributeSet;
@@ -146,7 +146,7 @@ impl<AU: AtomicallyUpdate<T>, T: Number, O: Operation> ValueMap<AU, T, O> {
146146
let new_tracker = AU::new_atomic_tracker(self.buckets_count);
147147
O::update_tracker(&new_tracker, measurement, index);
148148
trackers.insert(STREAM_OVERFLOW_ATTRIBUTES.clone(), Arc::new(new_tracker));
149-
global::handle_error(MetricsError::Other("Warning: Maximum data points for metric stream exceeded. Entry added to overflow. Subsequent overflows to same metric until next collect will not be logged.".into()));
149+
global::handle_error(MetricError::Other("Warning: Maximum data points for metric stream exceeded. Entry added to overflow. Subsequent overflows to same metric until next collect will not be logged.".into()));
150150
otel_warn!( name: "ValueMap.measure",
151151
message = "Maximum data points for metric stream exceeded. Entry added to overflow. Subsequent overflows to same metric until next collect will not be logged."
152152
);

0 commit comments

Comments
 (0)