From 72a012c97a29a8fc3f80a08a2449ea8db1bf552a Mon Sep 17 00:00:00 2001 From: David Pitoniak Date: Thu, 24 Oct 2024 18:34:41 -0400 Subject: [PATCH] refactor: update MetricsError to be MetricError this is consistent with LogError and TraceError --- CONTRIBUTING.md | 2 +- .../examples/basic-otlp-http/src/main.rs | 4 +-- .../examples/basic-otlp/src/main.rs | 4 +-- .../src/exporter/http/metrics.rs | 6 ++-- opentelemetry-otlp/src/exporter/http/mod.rs | 2 +- .../src/exporter/tonic/metrics.rs | 6 ++-- opentelemetry-proto/src/transform/metrics.rs | 6 ++-- opentelemetry-sdk/src/metrics/aggregation.rs | 12 ++++---- opentelemetry-sdk/src/metrics/internal/mod.rs | 4 +-- .../src/metrics/manual_reader.rs | 4 +-- opentelemetry-sdk/src/metrics/meter.rs | 24 ++++++++-------- .../src/metrics/meter_provider.rs | 4 +-- .../src/metrics/periodic_reader.rs | 24 ++++++++-------- opentelemetry-sdk/src/metrics/pipeline.rs | 28 +++++++++---------- opentelemetry-sdk/src/metrics/view.rs | 10 +++---- .../src/testing/metrics/in_memory_exporter.rs | 10 +++---- opentelemetry-stdout/src/metrics/exporter.rs | 4 +-- opentelemetry/src/global/error_handler.rs | 4 +-- opentelemetry/src/metrics/mod.rs | 12 ++++---- 19 files changed, 85 insertions(+), 85 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 930bf727c3..eb6a38ca80 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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. diff --git a/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs b/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs index 029efaaa30..916bd713df 100644 --- a/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs +++ b/opentelemetry-otlp/examples/basic-otlp-http/src/main.rs @@ -1,7 +1,7 @@ use once_cell::sync::Lazy; use opentelemetry::{ global, - metrics::MetricsError, + metrics::MetricError, trace::{TraceContextExt, TraceError, Tracer}, InstrumentationScope, KeyValue, }; @@ -65,7 +65,7 @@ fn init_tracer_provider() -> Result { .build()) } -fn init_metrics() -> Result { +fn init_metrics() -> Result { let exporter = MetricsExporter::builder() .with_http() .with_protocol(Protocol::HttpBinary) //can be changed to `Protocol::HttpJson` to export in JSON format diff --git a/opentelemetry-otlp/examples/basic-otlp/src/main.rs b/opentelemetry-otlp/examples/basic-otlp/src/main.rs index 60f2922a35..979eaf36f3 100644 --- a/opentelemetry-otlp/examples/basic-otlp/src/main.rs +++ b/opentelemetry-otlp/examples/basic-otlp/src/main.rs @@ -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}; @@ -33,7 +33,7 @@ fn init_tracer_provider() -> Result { .build()) } -fn init_metrics() -> Result { +fn init_metrics() -> Result { let exporter = MetricsExporter::builder().with_tonic().build()?; let reader = PeriodicReader::builder(exporter, runtime::Tokio).build(); diff --git a/opentelemetry-otlp/src/exporter/http/metrics.rs b/opentelemetry-otlp/src/exporter/http/metrics.rs index 9a682f94d0..b047cd4f32 100644 --- a/opentelemetry-otlp/src/exporter/http/metrics.rs +++ b/opentelemetry-otlp/src/exporter/http/metrics.rs @@ -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}; @@ -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())), })?; let (body, content_type) = self.build_metrics_export_body(metrics)?; @@ -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))))?; Ok(()) } diff --git a/opentelemetry-otlp/src/exporter/http/mod.rs b/opentelemetry-otlp/src/exporter/http/mod.rs index abfb725053..b8cd8fe614 100644 --- a/opentelemetry-otlp/src/exporter/http/mod.rs +++ b/opentelemetry-otlp/src/exporter/http/mod.rs @@ -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())), }, _ => Ok((req.encode_to_vec(), "application/x-protobuf")), } diff --git a/opentelemetry-otlp/src/exporter/tonic/metrics.rs b/opentelemetry-otlp/src/exporter/tonic/metrics.rs index f2aa4bbf5d..b8a59858eb 100644 --- a/opentelemetry-otlp/src/exporter/tonic/metrics.rs +++ b/opentelemetry-otlp/src/exporter/tonic/metrics.rs @@ -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, }; @@ -62,14 +62,14 @@ impl MetricsClient for TonicMetricsClient { .interceptor .call(Request::new(())) .map_err(|e| { - MetricsError::Other(format!( + MetricError::Other(format!( "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())), })?; client diff --git a/opentelemetry-proto/src/transform/metrics.rs b/opentelemetry-proto/src/transform/metrics.rs index f718c96280..66db88a1d4 100644 --- a/opentelemetry-proto/src/transform/metrics.rs +++ b/opentelemetry-proto/src/transform/metrics.rs @@ -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, @@ -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!( "Unknown temporality {:?}, using default instead.", other ))); @@ -184,7 +184,7 @@ pub mod tonic { } else if let Some(gauge) = data.downcast_ref::>() { Ok(TonicMetricData::Gauge(gauge.into())) } else { - global::handle_error(MetricsError::Other("unknown aggregator".into())); + global::handle_error(MetricError::Other("unknown aggregator".into())); Err(()) } } diff --git a/opentelemetry-sdk/src/metrics/aggregation.rs b/opentelemetry-sdk/src/metrics/aggregation.rs index 6282f7509f..6ccd564870 100644 --- a/opentelemetry-sdk/src/metrics/aggregation.rs +++ b/opentelemetry-sdk/src/metrics/aggregation.rs @@ -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)] @@ -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, ))); @@ -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, ))); @@ -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() { @@ -163,7 +163,7 @@ mod tests { check: Box) -> 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 = vec![ TestCase { diff --git a/opentelemetry-sdk/src/metrics/internal/mod.rs b/opentelemetry-sdk/src/metrics/internal/mod.rs index 7a79fe4653..84547d80a6 100644 --- a/opentelemetry-sdk/src/metrics/internal/mod.rs +++ b/opentelemetry-sdk/src/metrics/internal/mod.rs @@ -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; @@ -146,7 +146,7 @@ impl, T: Number, O: Operation> ValueMap { 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." ); diff --git a/opentelemetry-sdk/src/metrics/manual_reader.rs b/opentelemetry-sdk/src/metrics/manual_reader.rs index 99aacc0683..f64c61b91d 100644 --- a/opentelemetry-sdk/src/metrics/manual_reader.rs +++ b/opentelemetry-sdk/src/metrics/manual_reader.rs @@ -4,7 +4,7 @@ use std::{ }; use opentelemetry::{ - metrics::{MetricResult, MetricsError}, + metrics::{MetricError, MetricResult}, otel_debug, }; @@ -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( "reader is shut down or not registered".into(), )) } diff --git a/opentelemetry-sdk/src/metrics/meter.rs b/opentelemetry-sdk/src/metrics/meter.rs index 00c202f959..d0647709e0 100644 --- a/opentelemetry-sdk/src/metrics/meter.rs +++ b/opentelemetry-sdk/src/metrics/meter.rs @@ -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, @@ -499,24 +499,24 @@ fn validate_instrument_config(name: &str, unit: &Option>) -> M fn validate_instrument_name(name: &str) -> MetricResult<()> { if name.is_empty() { - return Err(MetricsError::InvalidInstrumentConfiguration( + return Err(MetricError::InvalidInstrumentConfiguration( 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, )); } @@ -526,12 +526,12 @@ fn validate_instrument_name(name: &str) -> MetricResult<()> { fn validate_instrument_unit(unit: &Option>) -> 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, )); } @@ -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, @@ -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 )); } }; @@ -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 )); } }; diff --git a/opentelemetry-sdk/src/metrics/meter_provider.rs b/opentelemetry-sdk/src/metrics/meter_provider.rs index f344715c57..4c53e8d12e 100644 --- a/opentelemetry-sdk/src/metrics/meter_provider.rs +++ b/opentelemetry-sdk/src/metrics/meter_provider.rs @@ -8,7 +8,7 @@ use std::{ }; use opentelemetry::{ - metrics::{Meter, MeterProvider, MetricResult, MetricsError}, + metrics::{Meter, MeterProvider, MetricError, MetricResult}, otel_debug, otel_error, InstrumentationScope, }; @@ -125,7 +125,7 @@ impl SdkMeterProviderInner { { self.pipes.shutdown() } else { - Err(MetricsError::Other( + Err(MetricError::Other( "metrics provider already shut down".into(), )) } diff --git a/opentelemetry-sdk/src/metrics/periodic_reader.rs b/opentelemetry-sdk/src/metrics/periodic_reader.rs index 9a4c6c3026..0fcea11252 100644 --- a/opentelemetry-sdk/src/metrics/periodic_reader.rs +++ b/opentelemetry-sdk/src/metrics/periodic_reader.rs @@ -12,7 +12,7 @@ use futures_util::{ StreamExt, }; use opentelemetry::{ - metrics::{MetricResult, MetricsError}, + metrics::{MetricError, MetricResult}, otel_debug, otel_error, }; @@ -244,7 +244,7 @@ impl PeriodicReaderWorker { Either::Left((res, _)) => { res // return the status of export. } - Either::Right(_) => Err(MetricsError::Other("export timed out".into())), + Either::Right(_) => Err(MetricError::Other("export timed out".into())), } } @@ -318,7 +318,7 @@ impl MetricReader for PeriodicReader { fn collect(&self, rm: &mut ResourceMetrics) -> MetricResult<()> { let inner = self.inner.lock()?; if inner.is_shutdown { - return Err(MetricsError::Other("reader is shut down".into())); + return Err(MetricError::Other("reader is shut down".into())); } if let Some(producer) = match &inner.sdk_producer_or_worker { @@ -327,7 +327,7 @@ impl MetricReader for PeriodicReader { } { producer.produce(rm)?; } else { - return Err(MetricsError::Other("reader is not registered".into())); + return Err(MetricError::Other("reader is not registered".into())); } Ok(()) @@ -336,36 +336,36 @@ impl MetricReader for PeriodicReader { fn force_flush(&self) -> MetricResult<()> { let mut inner = self.inner.lock()?; if inner.is_shutdown { - return Err(MetricsError::Other("reader is shut down".into())); + return Err(MetricError::Other("reader is shut down".into())); } let (sender, receiver) = oneshot::channel(); inner .message_sender .try_send(Message::Flush(sender)) - .map_err(|e| MetricsError::Other(e.to_string()))?; + .map_err(|e| MetricError::Other(e.to_string()))?; drop(inner); // don't hold lock when blocking on future futures_executor::block_on(receiver) - .map_err(|err| MetricsError::Other(err.to_string())) + .map_err(|err| MetricError::Other(err.to_string())) .and_then(|res| res) } fn shutdown(&self) -> MetricResult<()> { let mut inner = self.inner.lock()?; if inner.is_shutdown { - return Err(MetricsError::Other("reader is already shut down".into())); + return Err(MetricError::Other("reader is already shut down".into())); } let (sender, receiver) = oneshot::channel(); inner .message_sender .try_send(Message::Shutdown(sender)) - .map_err(|e| MetricsError::Other(e.to_string()))?; + .map_err(|e| MetricError::Other(e.to_string()))?; drop(inner); // don't hold lock when blocking on future let shutdown_result = futures_executor::block_on(receiver) - .map_err(|err| MetricsError::Other(err.to_string()))?; + .map_err(|err| MetricError::Other(err.to_string()))?; // Acquire the lock again to set the shutdown flag let mut inner = self.inner.lock()?; @@ -393,7 +393,7 @@ mod tests { metrics::data::ResourceMetrics, metrics::reader::MetricReader, metrics::SdkMeterProvider, runtime, testing::metrics::InMemoryMetricsExporter, Resource, }; - use opentelemetry::metrics::{MeterProvider, MetricsError}; + use opentelemetry::metrics::{MeterProvider, MetricError}; use std::sync::mpsc; #[test] @@ -449,7 +449,7 @@ mod tests { // Assert assert!( - matches!(result.unwrap_err(), MetricsError::Other(err) if err == "reader is not registered") + matches!(result.unwrap_err(), MetricError::Other(err) if err == "reader is not registered") ); } diff --git a/opentelemetry-sdk/src/metrics/pipeline.rs b/opentelemetry-sdk/src/metrics/pipeline.rs index 9e5d1be2d9..1f60b2c1af 100644 --- a/opentelemetry-sdk/src/metrics/pipeline.rs +++ b/opentelemetry-sdk/src/metrics/pipeline.rs @@ -7,7 +7,7 @@ use std::{ use opentelemetry::{ global, - metrics::{MetricResult, MetricsError}, + metrics::{MetricError, MetricResult}, InstrumentationScope, KeyValue, }; @@ -253,7 +253,7 @@ where let mut errs = vec![]; let kind = match inst.kind { Some(kind) => kind, - None => return Err(MetricsError::Other("instrument must have a kind".into())), + None => return Err(MetricError::Other("instrument must have a kind".into())), }; // The cache will return the same Aggregator instance. Use stream ids to de duplicate. @@ -286,7 +286,7 @@ where if errs.is_empty() { return Ok(measures); } else { - return Err(MetricsError::Other(format!("{errs:?}"))); + return Err(MetricError::Other(format!("{errs:?}"))); } } @@ -315,12 +315,12 @@ where } Ok(measures) } else { - Err(MetricsError::Other(format!("{errs:?}"))) + Err(MetricError::Other(format!("{errs:?}"))) } } Err(err) => { errs.push(err); - Err(MetricsError::Other(format!("{errs:?}"))) + Err(MetricError::Other(format!("{errs:?}"))) } } } @@ -355,7 +355,7 @@ where } if let Err(err) = is_aggregator_compatible(&kind, &agg) { - return Err(MetricsError::Other(format!( + return Err(MetricError::Other(format!( "creating aggregator with instrumentKind: {:?}, aggregation {:?}: {:?}", kind, stream.aggregation, err, ))); @@ -400,7 +400,7 @@ where match cached { Ok(opt) => Ok(opt.clone()), - Err(err) => Err(MetricsError::Other(err.to_string())), + Err(err) => Err(MetricError::Other(err.to_string())), } } @@ -414,7 +414,7 @@ where return; } - global::handle_error(MetricsError::Other(format!( + global::handle_error(MetricError::Other(format!( "duplicate metric stream definitions, names: ({} and {}), descriptions: ({} and {}), kinds: ({:?} and {:?}), units: ({:?} and {:?}), and numbers: ({} and {})", existing.name, id.name, existing.description, id.description, @@ -573,7 +573,7 @@ fn is_aggregator_compatible( ) { return Ok(()); } - Err(MetricsError::Other("incompatible aggregation".into())) + Err(MetricError::Other("incompatible aggregation".into())) } Aggregation::Sum => { match kind { @@ -585,7 +585,7 @@ fn is_aggregator_compatible( _ => { // TODO: review need for aggregation check after // https://github.com/open-telemetry/opentelemetry-specification/issues/2710 - Err(MetricsError::Other("incompatible aggregation".into())) + Err(MetricError::Other("incompatible aggregation".into())) } } } @@ -595,7 +595,7 @@ fn is_aggregator_compatible( _ => { // TODO: review need for aggregation check after // https://github.com/open-telemetry/opentelemetry-specification/issues/2710 - Err(MetricsError::Other("incompatible aggregation".into())) + Err(MetricError::Other("incompatible aggregation".into())) } } } @@ -650,7 +650,7 @@ impl Pipelines { if errs.is_empty() { Ok(()) } else { - Err(MetricsError::Other(format!("{errs:?}"))) + Err(MetricError::Other(format!("{errs:?}"))) } } @@ -666,7 +666,7 @@ impl Pipelines { if errs.is_empty() { Ok(()) } else { - Err(MetricsError::Other(format!("{errs:?}"))) + Err(MetricError::Other(format!("{errs:?}"))) } } } @@ -717,7 +717,7 @@ where } Ok(measures) } else { - Err(MetricsError::Other(format!("{errs:?}"))) + Err(MetricError::Other(format!("{errs:?}"))) } } } diff --git a/opentelemetry-sdk/src/metrics/view.rs b/opentelemetry-sdk/src/metrics/view.rs index 2271bf2afc..8bc0801a96 100644 --- a/opentelemetry-sdk/src/metrics/view.rs +++ b/opentelemetry-sdk/src/metrics/view.rs @@ -2,7 +2,7 @@ use super::instrument::{Instrument, Stream}; use glob::Pattern; use opentelemetry::{ global, - metrics::{MetricResult, MetricsError}, + metrics::{MetricError, MetricResult}, }; fn empty_view(_inst: &Instrument) -> Option { @@ -102,7 +102,7 @@ impl View for Box { /// ``` pub fn new_view(criteria: Instrument, mask: Stream) -> MetricResult> { if criteria.is_empty() { - global::handle_error(MetricsError::Config(format!( + global::handle_error(MetricError::Config(format!( "no criteria provided, dropping view. mask: {mask:?}" ))); return Ok(Box::new(empty_view)); @@ -112,7 +112,7 @@ pub fn new_view(criteria: Instrument, mask: Stream) -> MetricResult bool + Send + Sync> = if contains_wildcard { if mask.name != "" { - global::handle_error(MetricsError::Config(format!( + global::handle_error(MetricError::Config(format!( "name replacement for multiple instruments, dropping view, criteria: {criteria:?}, mask: {mask:?}" ))); return Ok(Box::new(empty_view)); @@ -120,7 +120,7 @@ pub fn new_view(criteria: Instrument, mask: Stream) -> MetricResult MetricResult agg = Some(ma.clone()), Err(err) => { - global::handle_error(MetricsError::Other(format!( + global::handle_error(MetricError::Other(format!( "{}, proceeding as if view did not exist. criteria: {:?}, mask: {:?}", err, err_msg_criteria, mask ))); diff --git a/opentelemetry-sdk/src/testing/metrics/in_memory_exporter.rs b/opentelemetry-sdk/src/testing/metrics/in_memory_exporter.rs index 16008968f1..a119a2ce98 100644 --- a/opentelemetry-sdk/src/testing/metrics/in_memory_exporter.rs +++ b/opentelemetry-sdk/src/testing/metrics/in_memory_exporter.rs @@ -2,8 +2,8 @@ use crate::metrics::data; use crate::metrics::data::{Histogram, Metric, ResourceMetrics, ScopeMetrics, Temporality}; use crate::metrics::exporter::PushMetricsExporter; use async_trait::async_trait; +use opentelemetry::metrics::MetricError; use opentelemetry::metrics::MetricResult; -use opentelemetry::metrics::MetricsError; use std::collections::VecDeque; use std::fmt; use std::sync::{Arc, Mutex}; @@ -132,7 +132,7 @@ impl InMemoryMetricsExporter { /// /// # Errors /// - /// Returns a `MetricsError` if the internal lock cannot be acquired. + /// Returns a `MetricError` if the internal lock cannot be acquired. /// /// # Example /// @@ -146,7 +146,7 @@ impl InMemoryMetricsExporter { self.metrics .lock() .map(|metrics_guard| metrics_guard.iter().map(Self::clone_metrics).collect()) - .map_err(MetricsError::from) + .map_err(MetricError::from) } /// Clears the internal storage of finished metrics. @@ -251,7 +251,7 @@ impl PushMetricsExporter for InMemoryMetricsExporter { .map(|mut metrics_guard| { metrics_guard.push_back(InMemoryMetricsExporter::clone_metrics(metrics)) }) - .map_err(MetricsError::from) + .map_err(MetricError::from) } async fn force_flush(&self) -> MetricResult<()> { @@ -262,7 +262,7 @@ impl PushMetricsExporter for InMemoryMetricsExporter { self.metrics .lock() .map(|mut metrics_guard| metrics_guard.clear()) - .map_err(MetricsError::from)?; + .map_err(MetricError::from)?; Ok(()) } diff --git a/opentelemetry-stdout/src/metrics/exporter.rs b/opentelemetry-stdout/src/metrics/exporter.rs index 9fa069945f..35a5658950 100644 --- a/opentelemetry-stdout/src/metrics/exporter.rs +++ b/opentelemetry-stdout/src/metrics/exporter.rs @@ -1,7 +1,7 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use core::{f64, fmt}; -use opentelemetry::metrics::{MetricResult, MetricsError}; +use opentelemetry::metrics::{MetricError, MetricResult}; use opentelemetry_sdk::metrics::{ data::{self, ScopeMetrics, Temporality}, exporter::PushMetricsExporter, @@ -38,7 +38,7 @@ impl PushMetricsExporter for MetricsExporter { /// Write Metrics to stdout async fn export(&self, metrics: &mut data::ResourceMetrics) -> MetricResult<()> { if self.is_shutdown.load(atomic::Ordering::SeqCst) { - Err(MetricsError::Other("exporter is shut down".into())) + Err(MetricError::Other("exporter is shut down".into())) } else { println!("Metrics"); println!("Resource"); diff --git a/opentelemetry/src/global/error_handler.rs b/opentelemetry/src/global/error_handler.rs index 87149c1b39..3a717154bf 100644 --- a/opentelemetry/src/global/error_handler.rs +++ b/opentelemetry/src/global/error_handler.rs @@ -4,7 +4,7 @@ use std::sync::RwLock; #[cfg(feature = "logs")] use crate::logs::LogError; #[cfg(feature = "metrics")] -use crate::metrics::MetricsError; +use crate::metrics::MetricError; use crate::propagation::PropagationError; #[cfg(feature = "trace")] use crate::trace::TraceError; @@ -25,7 +25,7 @@ pub enum Error { #[cfg_attr(docsrs, doc(cfg(feature = "metrics")))] #[error(transparent)] /// An issue raised by the metrics module. - Metric(#[from] MetricsError), + Metric(#[from] MetricError), #[cfg(feature = "logs")] #[cfg_attr(docsrs, doc(cfg(feature = "logs")))] diff --git a/opentelemetry/src/metrics/mod.rs b/opentelemetry/src/metrics/mod.rs index 3b604a4ebf..6c3a4381fb 100644 --- a/opentelemetry/src/metrics/mod.rs +++ b/opentelemetry/src/metrics/mod.rs @@ -22,12 +22,12 @@ pub use instruments::{ pub use meter::{Meter, MeterProvider}; /// A specialized `Result` type for metric operations. -pub type MetricResult = result::Result; +pub type MetricResult = result::Result; /// Errors returned by the metrics API. #[derive(Error, Debug)] #[non_exhaustive] -pub enum MetricsError { +pub enum MetricError { /// Other errors not covered by specific cases. #[error("Metrics error: {0}")] Other(String), @@ -44,15 +44,15 @@ pub enum MetricsError { InvalidInstrumentConfiguration(&'static str), } -impl From for MetricsError { +impl From for MetricError { fn from(err: T) -> Self { - MetricsError::ExportErr(Box::new(err)) + MetricError::ExportErr(Box::new(err)) } } -impl From> for MetricsError { +impl From> for MetricError { fn from(err: PoisonError) -> Self { - MetricsError::Other(err.to_string()) + MetricError::Other(err.to_string()) } }