Skip to content

Commit

Permalink
refactor: update MetricsError to be MetricError
Browse files Browse the repository at this point in the history
this is consistent with LogError and TraceError
  • Loading branch information
pitoniak32 committed Oct 25, 2024
1 parent bd55114 commit 2c0e00f
Show file tree
Hide file tree
Showing 19 changed files with 85 additions and 85 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ For a deeper discussion, see:

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.

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`.
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`.

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.

Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-otlp/examples/basic-otlp-http/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use once_cell::sync::Lazy;
use opentelemetry::{
global,
metrics::MetricsError,
metrics::MetricError,
trace::{TraceContextExt, TraceError, Tracer},
InstrumentationScope, KeyValue,
};
Expand Down Expand Up @@ -65,7 +65,7 @@ fn init_tracer_provider() -> Result<sdktrace::TracerProvider, TraceError> {
.build())
}

fn init_metrics() -> Result<opentelemetry_sdk::metrics::SdkMeterProvider, MetricsError> {
fn init_metrics() -> Result<opentelemetry_sdk::metrics::SdkMeterProvider, MetricError> {
let exporter = MetricsExporter::builder()
.with_http()
.with_protocol(Protocol::HttpBinary) //can be changed to `Protocol::HttpJson` to export in JSON format
Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-otlp/examples/basic-otlp/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use once_cell::sync::Lazy;
use opentelemetry::logs::LogError;
use opentelemetry::metrics::MetricsError;
use opentelemetry::metrics::MetricError;
use opentelemetry::trace::{TraceContextExt, TraceError, Tracer};
use opentelemetry::KeyValue;
use opentelemetry::{global, InstrumentationScope};
Expand Down Expand Up @@ -33,7 +33,7 @@ fn init_tracer_provider() -> Result<sdktrace::TracerProvider, TraceError> {
.build())
}

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

let reader = PeriodicReader::builder(exporter, runtime::Tokio).build();
Expand Down
6 changes: 3 additions & 3 deletions opentelemetry-otlp/src/exporter/http/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::sync::Arc;

use async_trait::async_trait;
use http::{header::CONTENT_TYPE, Method};
use opentelemetry::metrics::{MetricResult, MetricsError};
use opentelemetry::metrics::{MetricError, MetricResult};
use opentelemetry_sdk::metrics::data::ResourceMetrics;

use crate::{metric::MetricsClient, Error};
Expand All @@ -18,7 +18,7 @@ impl MetricsClient for OtlpHttpClient {
.map_err(Into::into)
.and_then(|g| match &*g {
Some(client) => Ok(Arc::clone(client)),
_ => Err(MetricsError::Other("exporter is already shut down".into())),
_ => Err(MetricError::Other("exporter is already shut down".into())),

Check warning on line 21 in opentelemetry-otlp/src/exporter/http/metrics.rs

View check run for this annotation

Codecov / codecov/patch

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

Added line #L21 was not covered by tests
})?;

let (body, content_type) = self.build_metrics_export_body(metrics)?;
Expand All @@ -36,7 +36,7 @@ impl MetricsClient for OtlpHttpClient {
client
.send(request)
.await
.map_err(|e| MetricsError::ExportErr(Box::new(Error::RequestFailed(e))))?;
.map_err(|e| MetricError::ExportErr(Box::new(Error::RequestFailed(e))))?;

Check warning on line 39 in opentelemetry-otlp/src/exporter/http/metrics.rs

View check run for this annotation

Codecov / codecov/patch

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

Added line #L39 was not covered by tests

Ok(())
}
Expand Down
2 changes: 1 addition & 1 deletion opentelemetry-otlp/src/exporter/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ impl OtlpHttpClient {
#[cfg(feature = "http-json")]
Protocol::HttpJson => match serde_json::to_string_pretty(&req) {
Ok(json) => Ok((json.into(), "application/json")),
Err(e) => Err(opentelemetry::metrics::MetricsError::Other(e.to_string())),
Err(e) => Err(opentelemetry::metrics::MetricError::Other(e.to_string())),

Check warning on line 323 in opentelemetry-otlp/src/exporter/http/mod.rs

View check run for this annotation

Codecov / codecov/patch

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

Added line #L323 was not covered by tests
},
_ => Ok((req.encode_to_vec(), "application/x-protobuf")),
}
Expand Down
6 changes: 3 additions & 3 deletions opentelemetry-otlp/src/exporter/tonic/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use core::fmt;
use std::sync::Mutex;

use async_trait::async_trait;
use opentelemetry::metrics::{MetricResult, MetricsError};
use opentelemetry::metrics::{MetricError, MetricResult};
use opentelemetry_proto::tonic::collector::metrics::v1::{
metrics_service_client::MetricsServiceClient, ExportMetricsServiceRequest,
};
Expand Down Expand Up @@ -62,14 +62,14 @@ impl MetricsClient for TonicMetricsClient {
.interceptor
.call(Request::new(()))
.map_err(|e| {
MetricsError::Other(format!(
MetricError::Other(format!(

Check warning on line 65 in opentelemetry-otlp/src/exporter/tonic/metrics.rs

View check run for this annotation

Codecov / codecov/patch

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

Added line #L65 was not covered by tests
"unexpected status while exporting {e:?}"
))
})?
.into_parts();
Ok((inner.client.clone(), m, e))
}
None => Err(MetricsError::Other("exporter is already shut down".into())),
None => Err(MetricError::Other("exporter is already shut down".into())),

Check warning on line 72 in opentelemetry-otlp/src/exporter/tonic/metrics.rs

View check run for this annotation

Codecov / codecov/patch

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

Added line #L72 was not covered by tests
})?;

client
Expand Down
6 changes: 3 additions & 3 deletions opentelemetry-proto/src/transform/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub mod tonic {
use std::any::Any;
use std::fmt;

use opentelemetry::{global, metrics::MetricsError, Key, Value};
use opentelemetry::{global, metrics::MetricError, Key, Value};
use opentelemetry_sdk::metrics::data::{
self, Exemplar as SdkExemplar, ExponentialHistogram as SdkExponentialHistogram,
Gauge as SdkGauge, Histogram as SdkHistogram, Metric as SdkMetric,
Expand Down Expand Up @@ -97,7 +97,7 @@ pub mod tonic {
Temporality::Cumulative => AggregationTemporality::Cumulative,
Temporality::Delta => AggregationTemporality::Delta,
other => {
opentelemetry::global::handle_error(MetricsError::Other(format!(
opentelemetry::global::handle_error(MetricError::Other(format!(

Check warning on line 100 in opentelemetry-proto/src/transform/metrics.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-proto/src/transform/metrics.rs#L100

Added line #L100 was not covered by tests
"Unknown temporality {:?}, using default instead.",
other
)));
Expand Down Expand Up @@ -184,7 +184,7 @@ pub mod tonic {
} else if let Some(gauge) = data.downcast_ref::<SdkGauge<f64>>() {
Ok(TonicMetricData::Gauge(gauge.into()))
} else {
global::handle_error(MetricsError::Other("unknown aggregator".into()));
global::handle_error(MetricError::Other("unknown aggregator".into()));

Check warning on line 187 in opentelemetry-proto/src/transform/metrics.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-proto/src/transform/metrics.rs#L187

Added line #L187 was not covered by tests
Err(())
}
}
Expand Down
12 changes: 6 additions & 6 deletions opentelemetry-sdk/src/metrics/aggregation.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fmt;

use crate::metrics::internal::{EXPO_MAX_SCALE, EXPO_MIN_SCALE};
use opentelemetry::metrics::{MetricResult, MetricsError};
use opentelemetry::metrics::{MetricError, MetricResult};

/// The way recorded measurements are summarized.
#[derive(Clone, Debug, PartialEq)]
Expand Down Expand Up @@ -118,7 +118,7 @@ impl Aggregation {
Aggregation::ExplicitBucketHistogram { boundaries, .. } => {
for x in boundaries.windows(2) {
if x[0] >= x[1] {
return Err(MetricsError::Config(format!(
return Err(MetricError::Config(format!(
"aggregation: explicit bucket histogram: non-monotonic boundaries: {:?}",
boundaries,
)));
Expand All @@ -129,13 +129,13 @@ impl Aggregation {
}
Aggregation::Base2ExponentialHistogram { max_scale, .. } => {
if *max_scale > EXPO_MAX_SCALE {
return Err(MetricsError::Config(format!(
return Err(MetricError::Config(format!(
"aggregation: exponential histogram: max scale ({}) is greater than 20",
max_scale,
)));
}
if *max_scale < EXPO_MIN_SCALE {
return Err(MetricsError::Config(format!(
return Err(MetricError::Config(format!(
"aggregation: exponential histogram: max scale ({}) is less than -10",
max_scale,
)));
Expand All @@ -153,7 +153,7 @@ mod tests {
internal::{EXPO_MAX_SCALE, EXPO_MIN_SCALE},
Aggregation,
};
use opentelemetry::metrics::{MetricResult, MetricsError};
use opentelemetry::metrics::{MetricError, MetricResult};

#[test]
fn validate_aggregation() {
Expand All @@ -163,7 +163,7 @@ mod tests {
check: Box<dyn Fn(MetricResult<()>) -> bool>,
}
let ok = Box::new(|result: MetricResult<()>| result.is_ok());
let config_error = Box::new(|result| matches!(result, Err(MetricsError::Config(_))));
let config_error = Box::new(|result| matches!(result, Err(MetricError::Config(_))));

let test_cases: Vec<TestCase> = vec![
TestCase {
Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-sdk/src/metrics/internal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use aggregate::is_under_cardinality_limit;
pub(crate) use aggregate::{AggregateBuilder, ComputeAggregation, Measure};
pub(crate) use exponential_histogram::{EXPO_MAX_SCALE, EXPO_MIN_SCALE};
use once_cell::sync::Lazy;
use opentelemetry::metrics::MetricsError;
use opentelemetry::metrics::MetricError;
use opentelemetry::{global, otel_warn, KeyValue};

use crate::metrics::AttributeSet;
Expand Down Expand Up @@ -146,7 +146,7 @@ impl<AU: AtomicallyUpdate<T>, T: Number, O: Operation> ValueMap<AU, T, O> {
let new_tracker = AU::new_atomic_tracker(self.buckets_count);
O::update_tracker(&new_tracker, measurement, index);
trackers.insert(STREAM_OVERFLOW_ATTRIBUTES.clone(), Arc::new(new_tracker));
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()));
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()));
otel_warn!( name: "ValueMap.measure",
message = "Maximum data points for metric stream exceeded. Entry added to overflow. Subsequent overflows to same metric until next collect will not be logged."
);
Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-sdk/src/metrics/manual_reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::{
};

use opentelemetry::{
metrics::{MetricResult, MetricsError},
metrics::{MetricError, MetricResult},
otel_debug,
};

Expand Down Expand Up @@ -93,7 +93,7 @@ impl MetricReader for ManualReader {
match &inner.sdk_producer.as_ref().and_then(|w| w.upgrade()) {
Some(producer) => producer.produce(rm)?,
None => {
return Err(MetricsError::Other(
return Err(MetricError::Other(

Check warning on line 96 in opentelemetry-sdk/src/metrics/manual_reader.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-sdk/src/metrics/manual_reader.rs#L96

Added line #L96 was not covered by tests
"reader is shut down or not registered".into(),
))
}
Expand Down
24 changes: 12 additions & 12 deletions opentelemetry-sdk/src/metrics/meter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use opentelemetry::{
global,
metrics::{
AsyncInstrumentBuilder, Counter, Gauge, Histogram, HistogramBuilder, InstrumentBuilder,
InstrumentProvider, MetricResult, MetricsError, ObservableCounter, ObservableGauge,
InstrumentProvider, MetricError, MetricResult, ObservableCounter, ObservableGauge,
ObservableUpDownCounter, UpDownCounter,
},
otel_error, InstrumentationScope,
Expand Down Expand Up @@ -499,24 +499,24 @@ fn validate_instrument_config(name: &str, unit: &Option<Cow<'static, str>>) -> M

fn validate_instrument_name(name: &str) -> MetricResult<()> {
if name.is_empty() {
return Err(MetricsError::InvalidInstrumentConfiguration(
return Err(MetricError::InvalidInstrumentConfiguration(

Check warning on line 502 in opentelemetry-sdk/src/metrics/meter.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-sdk/src/metrics/meter.rs#L502

Added line #L502 was not covered by tests
INSTRUMENT_NAME_EMPTY,
));
}
if name.len() > INSTRUMENT_NAME_MAX_LENGTH {
return Err(MetricsError::InvalidInstrumentConfiguration(
return Err(MetricError::InvalidInstrumentConfiguration(
INSTRUMENT_NAME_LENGTH,
));
}
if name.starts_with(|c: char| !c.is_ascii_alphabetic()) {
return Err(MetricsError::InvalidInstrumentConfiguration(
return Err(MetricError::InvalidInstrumentConfiguration(
INSTRUMENT_NAME_FIRST_ALPHABETIC,
));
}
if name.contains(|c: char| {
!c.is_ascii_alphanumeric() && !INSTRUMENT_NAME_ALLOWED_NON_ALPHANUMERIC_CHARS.contains(&c)
}) {
return Err(MetricsError::InvalidInstrumentConfiguration(
return Err(MetricError::InvalidInstrumentConfiguration(
INSTRUMENT_NAME_INVALID_CHAR,
));
}
Expand All @@ -526,12 +526,12 @@ fn validate_instrument_name(name: &str) -> MetricResult<()> {
fn validate_instrument_unit(unit: &Option<Cow<'static, str>>) -> MetricResult<()> {
if let Some(unit) = unit {
if unit.len() > INSTRUMENT_UNIT_NAME_MAX_LENGTH {
return Err(MetricsError::InvalidInstrumentConfiguration(
return Err(MetricError::InvalidInstrumentConfiguration(
INSTRUMENT_UNIT_LENGTH,
));
}
if unit.contains(|c: char| !c.is_ascii()) {
return Err(MetricsError::InvalidInstrumentConfiguration(
return Err(MetricError::InvalidInstrumentConfiguration(
INSTRUMENT_UNIT_INVALID_CHAR,
));
}
Expand Down Expand Up @@ -598,7 +598,7 @@ where
mod tests {
use std::borrow::Cow;

use opentelemetry::metrics::MetricsError;
use opentelemetry::metrics::MetricError;

use super::{
validate_instrument_name, validate_instrument_unit, INSTRUMENT_NAME_FIRST_ALPHABETIC,
Expand All @@ -621,13 +621,13 @@ mod tests {
("allow.dots.ok", ""),
];
for (name, expected_error) in instrument_name_test_cases {
let assert = |result: Result<_, MetricsError>| {
let assert = |result: Result<_, MetricError>| {
if expected_error.is_empty() {
assert!(result.is_ok());
} else {
assert!(matches!(
result.unwrap_err(),
MetricsError::InvalidInstrumentConfiguration(msg) if msg == expected_error
MetricError::InvalidInstrumentConfiguration(msg) if msg == expected_error
));
}
};
Expand All @@ -652,13 +652,13 @@ mod tests {
];

for (unit, expected_error) in instrument_unit_test_cases {
let assert = |result: Result<_, MetricsError>| {
let assert = |result: Result<_, MetricError>| {
if expected_error.is_empty() {
assert!(result.is_ok());
} else {
assert!(matches!(
result.unwrap_err(),
MetricsError::InvalidInstrumentConfiguration(msg) if msg == expected_error
MetricError::InvalidInstrumentConfiguration(msg) if msg == expected_error
));
}
};
Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-sdk/src/metrics/meter_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::{
};

use opentelemetry::{
metrics::{Meter, MeterProvider, MetricResult, MetricsError},
metrics::{Meter, MeterProvider, MetricResult, MetricError},
otel_debug, otel_error, InstrumentationScope,
};

Expand Down Expand Up @@ -125,7 +125,7 @@ impl SdkMeterProviderInner {
{
self.pipes.shutdown()
} else {
Err(MetricsError::Other(
Err(MetricError::Other(
"metrics provider already shut down".into(),
))
}
Expand Down
Loading

0 comments on commit 2c0e00f

Please sign in to comment.