Skip to content

Commit 3e77a22

Browse files
authored
fix: Error cleanups continued (#2838)
1 parent 36c48db commit 3e77a22

File tree

8 files changed

+44
-122
lines changed

8 files changed

+44
-122
lines changed

opentelemetry-otlp/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
`Error` which contained many variants unrelated to building an exporter, the
1818
new one returns specific variants applicable to building an exporter. Some
1919
variants might be applicable only on select features.
20+
Also, now unused `Error` enum is removed.
2021
- **Breaking** `ExportConfig`'s `timeout` field is now optional(`Option<Duration>`)
2122
- **Breaking** Export configuration done via code is final. ENV variables cannot be used to override the code config.
2223
Do not use code based config, if there is desire to control the settings via ENV variables.

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

+2-2
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ impl OtlpHttpClient {
287287
fn build_trace_export_body(
288288
&self,
289289
spans: Vec<SpanData>,
290-
) -> opentelemetry_sdk::trace::TraceResult<(Vec<u8>, &'static str)> {
290+
) -> Result<(Vec<u8>, &'static str), String> {
291291
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
292292
let resource_spans = group_spans_by_resource_and_scope(spans, &self.resource);
293293

@@ -296,7 +296,7 @@ impl OtlpHttpClient {
296296
#[cfg(feature = "http-json")]
297297
Protocol::HttpJson => match serde_json::to_string_pretty(&req) {
298298
Ok(json) => Ok((json.into_bytes(), "application/json")),
299-
Err(e) => Err(opentelemetry_sdk::trace::TraceError::from(e.to_string())),
299+
Err(e) => Err(e.to_string()),
300300
},
301301
_ => Ok((req.encode_to_vec(), "application/x-protobuf")),
302302
}

opentelemetry-otlp/src/lib.rs

-100
Original file line numberDiff line numberDiff line change
@@ -362,8 +362,6 @@ pub use crate::exporter::{
362362
OTEL_EXPORTER_OTLP_TIMEOUT_DEFAULT,
363363
};
364364

365-
use opentelemetry_sdk::ExportError;
366-
367365
/// Type to indicate the builder does not have a client set.
368366
#[derive(Debug, Default, Clone)]
369367
pub struct NoExporterBuilderSet;
@@ -391,104 +389,6 @@ pub use crate::exporter::tonic::{TonicConfig, TonicExporterBuilder};
391389
#[cfg(feature = "serialize")]
392390
use serde::{Deserialize, Serialize};
393391

394-
/// Wrap type for errors from this crate.
395-
#[derive(thiserror::Error, Debug)]
396-
pub enum Error {
397-
/// Wrap error from [`tonic::transport::Error`]
398-
#[cfg(feature = "grpc-tonic")]
399-
#[error("transport error {0}")]
400-
Transport(#[from] tonic::transport::Error),
401-
402-
/// Wrap the [`tonic::codegen::http::uri::InvalidUri`] error
403-
#[cfg(any(feature = "grpc-tonic", feature = "http-proto", feature = "http-json"))]
404-
#[error("invalid URI {0}")]
405-
InvalidUri(#[from] http::uri::InvalidUri),
406-
407-
/// Wrap type for [`tonic::Status`]
408-
#[cfg(feature = "grpc-tonic")]
409-
#[error("the grpc server returns error ({code}): {message}")]
410-
Status {
411-
/// grpc status code
412-
code: tonic::Code,
413-
/// error message
414-
message: String,
415-
},
416-
417-
/// Http requests failed because no http client is provided.
418-
#[cfg(any(feature = "http-proto", feature = "http-json"))]
419-
#[error(
420-
"no http client, you must select one from features or provide your own implementation"
421-
)]
422-
NoHttpClient,
423-
424-
/// Http requests failed.
425-
#[cfg(any(feature = "http-proto", feature = "http-json"))]
426-
#[error("http request failed with {0}")]
427-
RequestFailed(#[from] opentelemetry_http::HttpError),
428-
429-
/// The provided value is invalid in HTTP headers.
430-
#[cfg(any(feature = "grpc-tonic", feature = "http-proto", feature = "http-json"))]
431-
#[error("http header value error {0}")]
432-
InvalidHeaderValue(#[from] http::header::InvalidHeaderValue),
433-
434-
/// The provided name is invalid in HTTP headers.
435-
#[cfg(any(feature = "grpc-tonic", feature = "http-proto", feature = "http-json"))]
436-
#[error("http header name error {0}")]
437-
InvalidHeaderName(#[from] http::header::InvalidHeaderName),
438-
439-
/// Prost encode failed
440-
#[cfg(any(
441-
feature = "http-proto",
442-
all(feature = "http-json", not(feature = "trace"))
443-
))]
444-
#[error("prost encoding error {0}")]
445-
EncodeError(#[from] prost::EncodeError),
446-
447-
/// The lock in exporters has been poisoned.
448-
#[cfg(feature = "metrics")]
449-
#[error("the lock of the {0} has been poisoned")]
450-
PoisonedLock(&'static str),
451-
452-
/// Unsupported compression algorithm.
453-
#[error("unsupported compression algorithm '{0}'")]
454-
UnsupportedCompressionAlgorithm(String),
455-
456-
/// Feature required to use the specified compression algorithm.
457-
#[cfg(any(not(feature = "gzip-tonic"), not(feature = "zstd-tonic")))]
458-
#[error("feature '{0}' is required to use the compression algorithm '{1}'")]
459-
FeatureRequiredForCompressionAlgorithm(&'static str, Compression),
460-
}
461-
462-
#[cfg(feature = "grpc-tonic")]
463-
impl From<tonic::Status> for Error {
464-
fn from(status: tonic::Status) -> Error {
465-
Error::Status {
466-
code: status.code(),
467-
message: {
468-
if !status.message().is_empty() {
469-
let mut result = ", detailed error message: ".to_string() + status.message();
470-
if status.code() == tonic::Code::Unknown {
471-
let source = (&status as &dyn std::error::Error)
472-
.source()
473-
.map(|e| format!("{:?}", e));
474-
result.push(' ');
475-
result.push_str(source.unwrap_or_default().as_ref());
476-
}
477-
result
478-
} else {
479-
String::new()
480-
}
481-
},
482-
}
483-
}
484-
}
485-
486-
impl ExportError for Error {
487-
fn exporter_name(&self) -> &'static str {
488-
"otlp"
489-
}
490-
}
491-
492392
/// The communication protocol to use when exporting data.
493393
#[cfg_attr(feature = "serialize", derive(Deserialize, Serialize))]
494394
#[derive(Clone, Copy, Debug, Eq, PartialEq)]

opentelemetry-sdk/CHANGELOG.md

+4-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,10 @@
7575
- **Breaking** for custom `LogProcessor` authors: Changed `set_resource`
7676
to require mutable ref.
7777
`fn set_resource(&mut self, _resource: &Resource) {}`
78-
- **Breaking** Removed deprecated functions and methods related to `trace::Config`
78+
- **Breaking**: InMemoryExporter's return type change.
79+
- `TraceResult<Vec<SpanData>>` to `Result<Vec<SpanData>, InMemoryExporterError>`
80+
- `MetricResult<Vec<ResourceMetrics>>` to `Result<Vec<ResourceMetrics>, InMemoryExporterError>`
81+
- `LogResult<Vec<LogDataWithResource>>` to `Result<Vec<LogDataWithResource>, InMemoryExporterError>`
7982

8083
## 0.28.0
8184

opentelemetry-sdk/src/lib.rs

+21
Original file line numberDiff line numberDiff line change
@@ -146,3 +146,24 @@ pub use resource::Resource;
146146

147147
pub mod error;
148148
pub use error::ExportError;
149+
150+
#[cfg(any(feature = "testing", test))]
151+
#[derive(thiserror::Error, Debug)]
152+
/// Errors that can occur during when returning telemetry from InMemoryLogExporter
153+
pub enum InMemoryExporterError {
154+
/// Operation failed due to an internal error.
155+
///
156+
/// The error message is intended for logging purposes only and should not
157+
/// be used to make programmatic decisions. It is implementation-specific
158+
/// and subject to change without notice. Consumers of this error should not
159+
/// rely on its content beyond logging.
160+
#[error("Unable to obtain telemetry. Reason: {0}")]
161+
InternalFailure(String),
162+
}
163+
164+
#[cfg(any(feature = "testing", test))]
165+
impl<T> From<std::sync::PoisonError<T>> for InMemoryExporterError {
166+
fn from(err: std::sync::PoisonError<T>) -> Self {
167+
InMemoryExporterError::InternalFailure(format!("Mutex poison error: {}", err))
168+
}
169+
}

opentelemetry-sdk/src/logs/in_memory_exporter.rs

+4-10
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
use crate::error::{OTelSdkError, OTelSdkResult};
22
use crate::logs::SdkLogRecord;
33
use crate::logs::{LogBatch, LogExporter};
4+
use crate::InMemoryExporterError;
45
use crate::Resource;
56
use opentelemetry::InstrumentationScope;
67
use std::borrow::Cow;
78
use std::sync::atomic::AtomicBool;
89
use std::sync::{Arc, Mutex};
910

10-
type LogResult<T> = Result<T, OTelSdkError>;
11-
1211
/// An in-memory logs exporter that stores logs data in memory..
1312
///
1413
/// This exporter is useful for testing and debugging purposes.
@@ -157,14 +156,9 @@ impl InMemoryLogExporter {
157156
/// let emitted_logs = exporter.get_emitted_logs().unwrap();
158157
/// ```
159158
///
160-
pub fn get_emitted_logs(&self) -> LogResult<Vec<LogDataWithResource>> {
161-
let logs_guard = self
162-
.logs
163-
.lock()
164-
.map_err(|e| OTelSdkError::InternalFailure(format!("Failed to lock logs: {}", e)))?;
165-
let resource_guard = self.resource.lock().map_err(|e| {
166-
OTelSdkError::InternalFailure(format!("Failed to lock resource: {}", e))
167-
})?;
159+
pub fn get_emitted_logs(&self) -> Result<Vec<LogDataWithResource>, InMemoryExporterError> {
160+
let logs_guard = self.logs.lock().map_err(InMemoryExporterError::from)?;
161+
let resource_guard = self.resource.lock().map_err(InMemoryExporterError::from)?;
168162
let logs: Vec<LogDataWithResource> = logs_guard
169163
.iter()
170164
.map(|log_data| LogDataWithResource {

opentelemetry-sdk/src/metrics/in_memory_exporter.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,8 @@ use crate::error::{OTelSdkError, OTelSdkResult};
22
use crate::metrics::data::{self, Gauge, Sum};
33
use crate::metrics::data::{Histogram, Metric, ResourceMetrics, ScopeMetrics};
44
use crate::metrics::exporter::PushMetricExporter;
5-
use crate::metrics::MetricError;
6-
use crate::metrics::MetricResult;
75
use crate::metrics::Temporality;
6+
use crate::InMemoryExporterError;
87
use std::collections::VecDeque;
98
use std::fmt;
109
use std::sync::{Arc, Mutex};
@@ -143,11 +142,13 @@ impl InMemoryMetricExporter {
143142
/// let exporter = InMemoryMetricExporter::default();
144143
/// let finished_metrics = exporter.get_finished_metrics().unwrap();
145144
/// ```
146-
pub fn get_finished_metrics(&self) -> MetricResult<Vec<ResourceMetrics>> {
147-
self.metrics
145+
pub fn get_finished_metrics(&self) -> Result<Vec<ResourceMetrics>, InMemoryExporterError> {
146+
let metrics = self
147+
.metrics
148148
.lock()
149149
.map(|metrics_guard| metrics_guard.iter().map(Self::clone_metrics).collect())
150-
.map_err(MetricError::from)
150+
.map_err(InMemoryExporterError::from)?;
151+
Ok(metrics)
151152
}
152153

153154
/// Clears the internal storage of finished metrics.

opentelemetry-sdk/src/trace/in_memory_exporter.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use crate::error::{OTelSdkError, OTelSdkResult};
22
use crate::resource::Resource;
3-
use crate::trace::error::{TraceError, TraceResult};
43
use crate::trace::{SpanData, SpanExporter};
4+
use crate::InMemoryExporterError;
55
use std::sync::{Arc, Mutex};
66

77
/// An in-memory span exporter that stores span data in memory.
@@ -104,11 +104,13 @@ impl InMemorySpanExporter {
104104
/// let exporter = InMemorySpanExporter::default();
105105
/// let finished_spans = exporter.get_finished_spans().unwrap();
106106
/// ```
107-
pub fn get_finished_spans(&self) -> TraceResult<Vec<SpanData>> {
108-
self.spans
107+
pub fn get_finished_spans(&self) -> Result<Vec<SpanData>, InMemoryExporterError> {
108+
let spans = self
109+
.spans
109110
.lock()
110111
.map(|spans_guard| spans_guard.iter().cloned().collect())
111-
.map_err(TraceError::from)
112+
.map_err(InMemoryExporterError::from)?;
113+
Ok(spans)
112114
}
113115

114116
/// Clears the internal storage of finished spans.

0 commit comments

Comments
 (0)