Skip to main content

reth_tracing_otlp/
lib.rs

1//! With the `otlp` feature, provides tracing layers for `OpenTelemetry` that export spans, logs,
2//! and metrics to an OTLP endpoint.
3//!
4//! This module simplifies the integration of `OpenTelemetry` with OTLP export in Rust
5//! applications. It allows for easily capturing and exporting distributed traces, logs,
6//! and metrics to compatible backends like Jaeger, Zipkin, or any other
7//! OpenTelemetry-compatible system.
8
9use clap::ValueEnum;
10use eyre::ensure;
11use std::path::PathBuf;
12use url::Url;
13
14#[cfg(feature = "otlp")]
15mod file;
16#[cfg(feature = "otlp")]
17mod otlp;
18#[cfg(feature = "otlp")]
19pub use otlp::*;
20
21// Otlp http endpoint is expected to end with this path.
22// See also <https://opentelemetry.io/docs/languages/sdk-configuration/otlp-exporter/#otel_exporter_otlp_traces_endpoint>.
23const HTTP_TRACE_ENDPOINT: &str = "/v1/traces";
24const HTTP_LOGS_ENDPOINT: &str = "/v1/logs";
25
26/// OTLP transport protocol type
27#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
28pub enum OtlpProtocol {
29    /// HTTP/Protobuf transport, port 4318, requires `/v1/traces` path
30    // `http/protobuf` is the OpenTelemetry-specified spelling of this value for
31    // `OTEL_EXPORTER_OTLP_PROTOCOL`.
32    #[value(alias = "http/protobuf")]
33    Http,
34    /// gRPC transport, port 4317
35    Grpc,
36}
37
38impl OtlpProtocol {
39    /// Validate and correct the URL to match protocol requirements for traces.
40    ///
41    /// For HTTP: Ensures the path ends with `/v1/traces`, appending it if necessary.
42    /// For gRPC: Ensures the path does NOT include `/v1/traces`.
43    /// For file URLs: Requires a local absolute path without a query or fragment.
44    /// The protocol is ignored for file export.
45    pub fn validate_endpoint(&self, url: &mut Url) -> eyre::Result<()> {
46        if url.scheme() == "file" {
47            trace_file_path(url)?;
48            return Ok(());
49        }
50        self.validate_endpoint_with_path(url, HTTP_TRACE_ENDPOINT)
51    }
52
53    /// Validate and correct the URL to match protocol requirements for logs.
54    ///
55    /// For HTTP: Ensures the path ends with `/v1/logs`, appending it if necessary.
56    /// For gRPC: Ensures the path does NOT include `/v1/logs`.
57    pub fn validate_logs_endpoint(&self, url: &mut Url) -> eyre::Result<()> {
58        ensure!(url.scheme() != "file", "OTLP logs do not support file endpoints");
59        self.validate_endpoint_with_path(url, HTTP_LOGS_ENDPOINT)
60    }
61
62    fn validate_endpoint_with_path(&self, url: &mut Url, http_path: &str) -> eyre::Result<()> {
63        match self {
64            Self::Http => {
65                if !url.path().ends_with(http_path) {
66                    let path = url.path().trim_end_matches('/');
67                    url.set_path(&format!("{}{}", path, http_path));
68                }
69            }
70            Self::Grpc => {
71                ensure!(
72                    !url.path().ends_with(http_path),
73                    "OTLP gRPC endpoint should not include {} path, got: {}",
74                    http_path,
75                    url
76                );
77            }
78        }
79        Ok(())
80    }
81}
82
83/// Validates a local trace file URL without applying network endpoint path rules.
84fn trace_file_path(url: &Url) -> eyre::Result<PathBuf> {
85    ensure!(url.scheme() == "file", "OTLP trace file endpoint must use the file scheme");
86    ensure!(
87        url.host_str().is_none() && url.query().is_none() && url.fragment().is_none(),
88        "OTLP trace file endpoint must be local and have no query or fragment"
89    );
90    let path = url.to_file_path().map_err(|()| eyre::eyre!("Invalid OTLP trace file path"))?;
91    ensure!(
92        path.is_absolute() && path.file_name().is_some(),
93        "OTLP trace file path must be absolute and name a file"
94    );
95    Ok(path)
96}