Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Error cleanups continued #2838

Merged
merged 6 commits into from
Mar 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions opentelemetry-otlp/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
`Error` which contained many variants unrelated to building an exporter, the
new one returns specific variants applicable to building an exporter. Some
variants might be applicable only on select features.
Also, now unused `Error` enum is removed.
- **Breaking** `ExportConfig`'s `timeout` field is now optional(`Option<Duration>`)
- **Breaking** Export configuration done via code is final. ENV variables cannot be used to override the code config.
Do not use code based config, if there is desire to control the settings via ENV variables.
Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-otlp/src/exporter/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@
fn build_trace_export_body(
&self,
spans: Vec<SpanData>,
) -> opentelemetry_sdk::trace::TraceResult<(Vec<u8>, &'static str)> {
) -> Result<(Vec<u8>, &'static str), String> {

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L290 was not covered by tests
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
let resource_spans = group_spans_by_resource_and_scope(spans, &self.resource);

Expand All @@ -296,7 +296,7 @@
#[cfg(feature = "http-json")]
Protocol::HttpJson => match serde_json::to_string_pretty(&req) {
Ok(json) => Ok((json.into_bytes(), "application/json")),
Err(e) => Err(opentelemetry_sdk::trace::TraceError::from(e.to_string())),
Err(e) => Err(e.to_string()),

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L299 was not covered by tests
},
_ => Ok((req.encode_to_vec(), "application/x-protobuf")),
}
Expand Down
100 changes: 0 additions & 100 deletions opentelemetry-otlp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -362,8 +362,6 @@ pub use crate::exporter::{
OTEL_EXPORTER_OTLP_TIMEOUT_DEFAULT,
};

use opentelemetry_sdk::ExportError;

/// Type to indicate the builder does not have a client set.
#[derive(Debug, Default, Clone)]
pub struct NoExporterBuilderSet;
Expand Down Expand Up @@ -391,104 +389,6 @@ pub use crate::exporter::tonic::{TonicConfig, TonicExporterBuilder};
#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};

/// Wrap type for errors from this crate.
#[derive(thiserror::Error, Debug)]
pub enum Error {
/// Wrap error from [`tonic::transport::Error`]
#[cfg(feature = "grpc-tonic")]
#[error("transport error {0}")]
Transport(#[from] tonic::transport::Error),

/// Wrap the [`tonic::codegen::http::uri::InvalidUri`] error
#[cfg(any(feature = "grpc-tonic", feature = "http-proto", feature = "http-json"))]
#[error("invalid URI {0}")]
InvalidUri(#[from] http::uri::InvalidUri),

/// Wrap type for [`tonic::Status`]
#[cfg(feature = "grpc-tonic")]
#[error("the grpc server returns error ({code}): {message}")]
Status {
/// grpc status code
code: tonic::Code,
/// error message
message: String,
},

/// Http requests failed because no http client is provided.
#[cfg(any(feature = "http-proto", feature = "http-json"))]
#[error(
"no http client, you must select one from features or provide your own implementation"
)]
NoHttpClient,

/// Http requests failed.
#[cfg(any(feature = "http-proto", feature = "http-json"))]
#[error("http request failed with {0}")]
RequestFailed(#[from] opentelemetry_http::HttpError),

/// The provided value is invalid in HTTP headers.
#[cfg(any(feature = "grpc-tonic", feature = "http-proto", feature = "http-json"))]
#[error("http header value error {0}")]
InvalidHeaderValue(#[from] http::header::InvalidHeaderValue),

/// The provided name is invalid in HTTP headers.
#[cfg(any(feature = "grpc-tonic", feature = "http-proto", feature = "http-json"))]
#[error("http header name error {0}")]
InvalidHeaderName(#[from] http::header::InvalidHeaderName),

/// Prost encode failed
#[cfg(any(
feature = "http-proto",
all(feature = "http-json", not(feature = "trace"))
))]
#[error("prost encoding error {0}")]
EncodeError(#[from] prost::EncodeError),

/// The lock in exporters has been poisoned.
#[cfg(feature = "metrics")]
#[error("the lock of the {0} has been poisoned")]
PoisonedLock(&'static str),

/// Unsupported compression algorithm.
#[error("unsupported compression algorithm '{0}'")]
UnsupportedCompressionAlgorithm(String),

/// Feature required to use the specified compression algorithm.
#[cfg(any(not(feature = "gzip-tonic"), not(feature = "zstd-tonic")))]
#[error("feature '{0}' is required to use the compression algorithm '{1}'")]
FeatureRequiredForCompressionAlgorithm(&'static str, Compression),
}

#[cfg(feature = "grpc-tonic")]
impl From<tonic::Status> for Error {
fn from(status: tonic::Status) -> Error {
Error::Status {
code: status.code(),
message: {
if !status.message().is_empty() {
let mut result = ", detailed error message: ".to_string() + status.message();
if status.code() == tonic::Code::Unknown {
let source = (&status as &dyn std::error::Error)
.source()
.map(|e| format!("{:?}", e));
result.push(' ');
result.push_str(source.unwrap_or_default().as_ref());
}
result
} else {
String::new()
}
},
}
}
}

impl ExportError for Error {
fn exporter_name(&self) -> &'static str {
"otlp"
}
}

/// The communication protocol to use when exporting data.
#[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
Expand Down
5 changes: 4 additions & 1 deletion opentelemetry-sdk/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,10 @@
- **Breaking** for custom `LogProcessor` authors: Changed `set_resource`
to require mutable ref.
`fn set_resource(&mut self, _resource: &Resource) {}`
- **Breaking** Removed deprecated functions and methods related to `trace::Config`
- **Breaking**: InMemoryExporter's return type change.
- `TraceResult<Vec<SpanData>>` to `Result<Vec<SpanData>, InMemoryExporterError>`
- `MetricResult<Vec<ResourceMetrics>>` to `Result<Vec<ResourceMetrics>, InMemoryExporterError>`
- `LogResult<Vec<LogDataWithResource>>` to `Result<Vec<LogDataWithResource>, InMemoryExporterError>`

## 0.28.0

Expand Down
21 changes: 21 additions & 0 deletions opentelemetry-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,3 +146,24 @@

pub mod error;
pub use error::ExportError;

#[cfg(any(feature = "testing", test))]
#[derive(thiserror::Error, Debug)]
/// Errors that can occur during when returning telemetry from InMemoryLogExporter
pub enum InMemoryExporterError {
/// Operation failed due to an internal error.
///
/// The error message is intended for logging purposes only and should not
/// be used to make programmatic decisions. It is implementation-specific
/// and subject to change without notice. Consumers of this error should not
/// rely on its content beyond logging.
#[error("Unable to obtain telemetry. Reason: {0}")]
InternalFailure(String),
}

#[cfg(any(feature = "testing", test))]
impl<T> From<std::sync::PoisonError<T>> for InMemoryExporterError {
fn from(err: std::sync::PoisonError<T>) -> Self {
InMemoryExporterError::InternalFailure(format!("Mutex poison error: {}", err))
}

Check warning on line 168 in opentelemetry-sdk/src/lib.rs

View check run for this annotation

Codecov / codecov/patch

opentelemetry-sdk/src/lib.rs#L166-L168

Added lines #L166 - L168 were not covered by tests
}
14 changes: 4 additions & 10 deletions opentelemetry-sdk/src/logs/in_memory_exporter.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
use crate::error::{OTelSdkError, OTelSdkResult};
use crate::logs::SdkLogRecord;
use crate::logs::{LogBatch, LogExporter};
use crate::InMemoryExporterError;
use crate::Resource;
use opentelemetry::InstrumentationScope;
use std::borrow::Cow;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};

type LogResult<T> = Result<T, OTelSdkError>;

/// An in-memory logs exporter that stores logs data in memory..
///
/// This exporter is useful for testing and debugging purposes.
Expand Down Expand Up @@ -157,14 +156,9 @@ impl InMemoryLogExporter {
/// let emitted_logs = exporter.get_emitted_logs().unwrap();
/// ```
///
pub fn get_emitted_logs(&self) -> LogResult<Vec<LogDataWithResource>> {
let logs_guard = self
.logs
.lock()
.map_err(|e| OTelSdkError::InternalFailure(format!("Failed to lock logs: {}", e)))?;
let resource_guard = self.resource.lock().map_err(|e| {
OTelSdkError::InternalFailure(format!("Failed to lock resource: {}", e))
})?;
pub fn get_emitted_logs(&self) -> Result<Vec<LogDataWithResource>, InMemoryExporterError> {
let logs_guard = self.logs.lock().map_err(InMemoryExporterError::from)?;
let resource_guard = self.resource.lock().map_err(InMemoryExporterError::from)?;
let logs: Vec<LogDataWithResource> = logs_guard
.iter()
.map(|log_data| LogDataWithResource {
Expand Down
11 changes: 6 additions & 5 deletions opentelemetry-sdk/src/metrics/in_memory_exporter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ use crate::error::{OTelSdkError, OTelSdkResult};
use crate::metrics::data::{self, Gauge, Sum};
use crate::metrics::data::{Histogram, Metric, ResourceMetrics, ScopeMetrics};
use crate::metrics::exporter::PushMetricExporter;
use crate::metrics::MetricError;
use crate::metrics::MetricResult;
use crate::metrics::Temporality;
use crate::InMemoryExporterError;
use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex};
Expand Down Expand Up @@ -143,11 +142,13 @@ impl InMemoryMetricExporter {
/// let exporter = InMemoryMetricExporter::default();
/// let finished_metrics = exporter.get_finished_metrics().unwrap();
/// ```
pub fn get_finished_metrics(&self) -> MetricResult<Vec<ResourceMetrics>> {
self.metrics
pub fn get_finished_metrics(&self) -> Result<Vec<ResourceMetrics>, InMemoryExporterError> {
let metrics = self
.metrics
.lock()
.map(|metrics_guard| metrics_guard.iter().map(Self::clone_metrics).collect())
.map_err(MetricError::from)
.map_err(InMemoryExporterError::from)?;
Ok(metrics)
}

/// Clears the internal storage of finished metrics.
Expand Down
10 changes: 6 additions & 4 deletions opentelemetry-sdk/src/trace/in_memory_exporter.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::error::{OTelSdkError, OTelSdkResult};
use crate::resource::Resource;
use crate::trace::error::{TraceError, TraceResult};
use crate::trace::{SpanData, SpanExporter};
use crate::InMemoryExporterError;
use std::sync::{Arc, Mutex};

/// An in-memory span exporter that stores span data in memory.
Expand Down Expand Up @@ -104,11 +104,13 @@ impl InMemorySpanExporter {
/// let exporter = InMemorySpanExporter::default();
/// let finished_spans = exporter.get_finished_spans().unwrap();
/// ```
pub fn get_finished_spans(&self) -> TraceResult<Vec<SpanData>> {
self.spans
pub fn get_finished_spans(&self) -> Result<Vec<SpanData>, InMemoryExporterError> {
let spans = self
.spans
.lock()
.map(|spans_guard| spans_guard.iter().cloned().collect())
.map_err(TraceError::from)
.map_err(InMemoryExporterError::from)?;
Ok(spans)
}

/// Clears the internal storage of finished spans.
Expand Down