Skip to content

Commit d4c6467

Browse files
authored
fix: cleanup MetricError (#2906)
1 parent df26240 commit d4c6467

File tree

8 files changed

+41
-22
lines changed

8 files changed

+41
-22
lines changed

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ impl MetricsClient for OtlpHttpClient {
1919
_ => Err(OTelSdkError::AlreadyShutdown),
2020
})?;
2121

22-
let (body, content_type) = self.build_metrics_export_body(metrics).map_err(|e| {
23-
OTelSdkError::InternalFailure(format!("Failed to serialize metrics: {e:?}"))
22+
let (body, content_type) = self.build_metrics_export_body(metrics).ok_or_else(|| {
23+
OTelSdkError::InternalFailure("Failed to serialize metrics".to_string())
2424
})?;
2525
let mut request = http::Request::builder()
2626
.method(Method::POST)

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

+9-6
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ use super::{
44
};
55
use crate::{ExportConfig, Protocol, OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_HEADERS};
66
use http::{HeaderName, HeaderValue, Uri};
7+
#[cfg(feature = "http-json")]
8+
use opentelemetry::otel_debug;
79
use opentelemetry_http::HttpClient;
810
use opentelemetry_proto::transform::common::tonic::ResourceAttributesWithSchema;
911
#[cfg(feature = "logs")]
@@ -325,20 +327,21 @@ impl OtlpHttpClient {
325327
fn build_metrics_export_body(
326328
&self,
327329
metrics: &mut ResourceMetrics,
328-
) -> opentelemetry_sdk::metrics::MetricResult<(Vec<u8>, &'static str)> {
330+
) -> Option<(Vec<u8>, &'static str)> {
329331
use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest;
330332

331333
let req: ExportMetricsServiceRequest = (&*metrics).into();
332334

333335
match self.protocol {
334336
#[cfg(feature = "http-json")]
335337
Protocol::HttpJson => match serde_json::to_string_pretty(&req) {
336-
Ok(json) => Ok((json.into(), "application/json")),
337-
Err(e) => Err(opentelemetry_sdk::metrics::MetricError::Other(
338-
e.to_string(),
339-
)),
338+
Ok(json) => Some((json.into(), "application/json")),
339+
Err(e) => {
340+
otel_debug!(name: "JsonSerializationFaied", error = e.to_string());
341+
None
342+
}
340343
},
341-
_ => Ok((req.encode_to_vec(), "application/x-protobuf")),
344+
_ => Some((req.encode_to_vec(), "application/x-protobuf")),
342345
}
343346
}
344347
}

opentelemetry-sdk/CHANGELOG.md

+5
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ also modified to suppress telemetry before invoking exporters.
2424
- *Breaking* change for custom `MetricReader` authors.
2525
The `shutdown_with_timeout` method is added to `MetricReader` trait.
2626
`collect` method on `MetricReader` modified to return `OTelSdkResult`.
27+
[#2905](https://github.com/open-telemetry/opentelemetry-rust/pull/2905)
28+
- *Breaking* `MetricError`, `MetricResult` no longer public (except when
29+
`spec_unstable_metrics_views` feature flag is enabled). `OTelSdkResult` should
30+
be used instead, wherever applicable.
31+
[#2905](https://github.com/open-telemetry/opentelemetry-rust/pull/2905)
2732

2833
## 0.29.0
2934

opentelemetry-sdk/src/metrics/aggregation.rs

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

3+
use crate::metrics::error::{MetricError, MetricResult};
34
use crate::metrics::internal::{EXPO_MAX_SCALE, EXPO_MIN_SCALE};
4-
use crate::metrics::{MetricError, MetricResult};
55

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

110110
impl Aggregation {
111111
/// Validate that this aggregation has correct configuration
112-
pub fn validate(&self) -> MetricResult<()> {
112+
#[allow(unused)]
113+
pub(crate) fn validate(&self) -> MetricResult<()> {
113114
match self {
114115
Aggregation::Drop => Ok(()),
115116
Aggregation::Default => Ok(()),
@@ -149,11 +150,11 @@ impl Aggregation {
149150

150151
#[cfg(test)]
151152
mod tests {
153+
use crate::metrics::error::{MetricError, MetricResult};
152154
use crate::metrics::{
153155
internal::{EXPO_MAX_SCALE, EXPO_MIN_SCALE},
154156
Aggregation,
155157
};
156-
use crate::metrics::{MetricError, MetricResult};
157158

158159
#[test]
159160
fn validate_aggregation() {

opentelemetry-sdk/src/metrics/error.rs

+18-9
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@ use std::result;
22
use std::sync::PoisonError;
33
use thiserror::Error;
44

5-
use crate::ExportError;
6-
75
/// A specialized `Result` type for metric operations.
6+
#[cfg(feature = "spec_unstable_metrics_views")]
87
pub type MetricResult<T> = result::Result<T, MetricError>;
8+
#[cfg(not(feature = "spec_unstable_metrics_views"))]
9+
pub(crate) type MetricResult<T> = result::Result<T, MetricError>;
910

1011
/// Errors returned by the metrics API.
12+
#[cfg(feature = "spec_unstable_metrics_views")]
1113
#[derive(Error, Debug)]
1214
#[non_exhaustive]
1315
pub enum MetricError {
@@ -17,20 +19,27 @@ pub enum MetricError {
1719
/// Invalid configuration
1820
#[error("Config error {0}")]
1921
Config(String),
20-
/// Fail to export metrics
21-
#[error("Metrics exporter {0} failed with {name}", name = .0.exporter_name())]
22-
ExportErr(Box<dyn ExportError>),
2322
/// Invalid instrument configuration such invalid instrument name, invalid instrument description, invalid instrument unit, etc.
2423
/// See [spec](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#general-characteristics)
2524
/// for full list of requirements.
2625
#[error("Invalid instrument configuration: {0}")]
2726
InvalidInstrumentConfiguration(&'static str),
2827
}
2928

30-
impl<T: ExportError> From<T> for MetricError {
31-
fn from(err: T) -> Self {
32-
MetricError::ExportErr(Box::new(err))
33-
}
29+
#[cfg(not(feature = "spec_unstable_metrics_views"))]
30+
#[derive(Error, Debug)]
31+
pub(crate) enum MetricError {
32+
/// Other errors not covered by specific cases.
33+
#[error("Metrics error: {0}")]
34+
Other(String),
35+
/// Invalid configuration
36+
#[error("Config error {0}")]
37+
Config(String),
38+
/// Invalid instrument configuration such invalid instrument name, invalid instrument description, invalid instrument unit, etc.
39+
/// See [spec](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#general-characteristics)
40+
/// for full list of requirements.
41+
#[error("Invalid instrument configuration: {0}")]
42+
InvalidInstrumentConfiguration(&'static str),
3443
}
3544

3645
impl<T> From<PoisonError<T>> for MetricError {

opentelemetry-sdk/src/metrics/meter.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@ use opentelemetry::{
1212
};
1313

1414
use crate::metrics::{
15+
error::{MetricError, MetricResult},
1516
instrument::{Instrument, InstrumentKind, Observable, ResolvedMeasures},
1617
internal::{self, Number},
1718
pipeline::{Pipelines, Resolver},
18-
MetricError, MetricResult,
1919
};
2020

2121
use super::noop::NoopSyncInstrument;

opentelemetry-sdk/src/metrics/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ pub mod in_memory_exporter;
6666
pub use in_memory_exporter::{InMemoryMetricExporter, InMemoryMetricExporterBuilder};
6767

6868
pub use aggregation::*;
69+
#[cfg(feature = "spec_unstable_metrics_views")]
6970
pub use error::{MetricError, MetricResult};
7071
pub use manual_reader::*;
7172
pub use meter_provider::*;

opentelemetry-sdk/src/metrics/pipeline.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,11 @@ use crate::{
1212
metrics::{
1313
aggregation,
1414
data::{Metric, ResourceMetrics, ScopeMetrics},
15+
error::{MetricError, MetricResult},
1516
instrument::{Instrument, InstrumentId, InstrumentKind, Stream},
1617
internal::{self, AggregateBuilder, Number},
1718
reader::{MetricReader, SdkProducer},
1819
view::View,
19-
MetricError, MetricResult,
2020
},
2121
Resource,
2222
};

0 commit comments

Comments
 (0)