use super::config::TraceConfig;
use crate::{Error, Result};
use opentelemetry_http::{Bytes, HttpClient, HttpError, Request, Response};
use opentelemetry_otlp::{Protocol, RetryPolicy, WithExportConfig, WithHttpConfig};
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceResponse;
use prost::Message;
#[derive(Debug)]
struct Transport {
config: TraceConfig,
client: reqwest::Client,
}
pub(super) fn build(config: &TraceConfig) -> Result<opentelemetry_otlp::SpanExporter> {
if [
"OTEL_EXPORTER_OTLP_COMPRESSION",
"OTEL_EXPORTER_OTLP_TRACES_COMPRESSION",
]
.iter()
.any(|key| std::env::var_os(key).is_some())
{
return Err(Error::Telemetry(
"OTLP compression environment overrides are unsupported",
));
}
let client = reqwest::Client::builder()
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.retry(reqwest::retry::never())
.timeout(config.limits.export_timeout)
.connect_timeout(config.limits.export_timeout)
.read_timeout(config.limits.export_timeout)
.pool_max_idle_per_host(1)
.no_gzip()
.no_brotli()
.no_deflate()
.no_zstd()
.build()
.map_err(|_| Error::Telemetry("trace HTTP client initialization failed"))?;
opentelemetry_otlp::SpanExporter::builder()
.with_http()
.with_endpoint(config.endpoint.as_str())
.with_protocol(Protocol::HttpBinary)
.with_timeout(config.limits.export_timeout)
.with_retry_policy(RetryPolicy::disabled())
.with_max_request_body_size(8 * 1024 * 1024)
.with_http_client(Transport {
config: config.clone(),
client,
})
.build()
.map_err(|_| Error::Telemetry("trace exporter initialization failed"))
}
#[async_trait::async_trait]
impl HttpClient for Transport {
async fn send_bytes(
&self,
request: Request<Bytes>,
) -> std::result::Result<Response<Bytes>, HttpError> {
let mut response = self
.client
.post(self.config.endpoint.clone())
.headers(self.config.headers.clone())
.header("content-type", "application/x-protobuf")
.body(request.into_body())
.send()
.await
.map_err(|_| failure())?;
let status = response.status();
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|_| failure())? {
if bytes.len().saturating_add(chunk.len()) > 65536 {
return Err(failure());
}
bytes.extend_from_slice(&chunk);
}
if status.is_success() {
let ack =
ExportTraceServiceResponse::decode(bytes.as_slice()).map_err(|_| failure())?;
if ack
.partial_success
.is_some_and(|s| s.rejected_spans != 0 || !s.error_message.is_empty())
{
return Err(failure());
}
}
Response::builder()
.status(status)
.body(Bytes::new())
.map_err(|_| failure())
}
}
fn failure() -> HttpError {
std::io::Error::other("trace export failed").into()
}