grow-apache-skywalking 0.2.0

Rust SDK for Apache SkyWalking by Grow Codes
Documentation
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! OTLP exporter factory for services that ingest OTLP (`grpc` or `http/protobuf`).
//!
//! gRPC TLS needs the `otlp-tls` crate feature (opentelemetry-otlp `tls-roots`); a crate that
//! does not declare it still builds, without gRPC TLS. `make lint` also runs
//! `cargo clippy --lib --no-default-features`, so service code that builds its own tonic
//! exporter must not name tonic TLS types (`ClientTlsConfig`, `Certificate`, `Identity`,
//! `with_tls_config`) outside `#[cfg(feature = "otlp-tls")]`. Prefer [`apply_grpc_tls`]: it
//! compiles with and without the feature (without it, TLS for an `https` endpoint is `CONFIG`).
#![allow(unexpected_cfgs)]

use std::collections::HashMap;

use opentelemetry_otlp::{SpanExporter, WithExportConfig, WithHttpConfig, WithTonicConfig};

use super::{Compression, Protocol, TracingConfig};
use crate::core::{Error, Result, TlsConfig};

/// Builds an OTLP span exporter from the config, for use with
/// [`init_tracing_with`](super::init_tracing_with).
///
/// - `http/protobuf`: an endpoint without a path (`http://collector:4318`) gets `/v1/traces`
///   appended; an endpoint with a path (`https://host/api/otlp/v1/traces`, `https://host/otlp`)
///   is used as it is. Headers are sent as HTTP headers. `config.tls` (CA, client certificate,
///   `insecure_skip_verify`) applies to the HTTP client.
/// - `grpc`: headers are sent as gRPC metadata (invalid names/values → `CONFIG`). `https`
///   endpoints and `config.tls` (CA, client certificate) need the crate feature `otlp-tls`
///   (opentelemetry-otlp `tls-roots`); `insecure_skip_verify` is not available for gRPC
///   (`CONFIG`).
/// - `native`: `CONFIG` — the service package provides its own exporter.
///
/// Without an endpoint the standard `OTEL_EXPORTER_OTLP_*` variables and defaults apply.
pub fn otlp_exporter(config: &TracingConfig) -> Result<SpanExporter> {
    let built = match config.protocol {
        Protocol::HttpProtobuf => {
            let mut b = SpanExporter::builder()
                .with_http()
                .with_timeout(config.batch.export_timeout)
                .with_headers(
                    config
                        .headers
                        .clone()
                        .into_iter()
                        .collect::<HashMap<_, _>>(),
                );
            if let Some(endpoint) = &config.endpoint {
                b = b.with_endpoint(http_traces_endpoint(endpoint));
            }
            if let Some(tls) = config.tls.as_ref().filter(|t| **t != TlsConfig::default()) {
                let client = crate::core::transport::apply_tls(reqwest::Client::builder(), tls)?
                    .timeout(config.batch.export_timeout)
                    .build()
                    .map_err(|e| {
                        Error::config("cannot build the OTLP HTTP client").with_source(e)
                    })?;
                b = b.with_http_client(client);
            }
            if config.compression == Compression::Gzip {
                b = b.with_compression(opentelemetry_otlp::Compression::Gzip);
            }
            b.build()
        }
        Protocol::Grpc => {
            use opentelemetry_otlp::tonic_types::metadata::MetadataMap;
            let mut headers = http::HeaderMap::new();
            for (k, v) in &config.headers {
                let name = http::header::HeaderName::from_bytes(k.as_bytes())
                    .map_err(|_| Error::config(format!("invalid tracing header name {k:?}")))?;
                let value = http::header::HeaderValue::from_str(v).map_err(|_| {
                    Error::config(format!("invalid value for tracing header {k:?}"))
                })?;
                headers.insert(name, value);
            }
            let metadata = MetadataMap::from_headers(headers);
            let mut b = SpanExporter::builder()
                .with_tonic()
                .with_timeout(config.batch.export_timeout)
                .with_metadata(metadata);
            if let Some(endpoint) = &config.endpoint {
                b = b.with_endpoint(endpoint.clone());
            }
            if let Some(tls) = config.tls.as_ref().filter(|t| **t != TlsConfig::default()) {
                b = grpc_tls(b, config.endpoint.as_deref(), tls)?;
            }
            if config.compression == Compression::Gzip {
                b = b.with_compression(opentelemetry_otlp::Compression::Gzip);
            }
            b.build()
        }
        Protocol::Native => {
            return Err(Error::config(
                "tracing protocol \"native\" needs the service package's exporter",
            ))
        }
    };
    built.map_err(|e| Error::config(format!("cannot build the OTLP exporter: {e}")))
}

/// The OTLP/HTTP traces URL for `endpoint`: `/v1/traces` is appended only when the endpoint has
/// no path (or just `/`); an endpoint with a path is kept as it is (minus trailing slashes).
pub fn http_traces_endpoint(endpoint: &str) -> String {
    match url::Url::parse(endpoint) {
        Ok(url) if url.query().is_none() => {
            let base = endpoint.trim_end_matches('/');
            if url.path().trim_matches('/').is_empty() {
                format!("{base}/v1/traces")
            } else {
                base.to_string()
            }
        }
        _ => endpoint.to_string(),
    }
}

fn is_https(endpoint: &str) -> bool {
    endpoint
        .get(..8)
        .is_some_and(|p| p.eq_ignore_ascii_case("https://"))
}

/// The opentelemetry-otlp span exporter builder after `.with_tonic()` (OTLP/gRPC).
pub type OtlpGrpcExporterBuilder =
    opentelemetry_otlp::SpanExporterBuilder<opentelemetry_otlp::TonicExporterBuilderSet>;

/// Applies `tls` (extra CA certificates, client certificate, native roots) to an OTLP/gRPC
/// span exporter builder, the way [`otlp_exporter`] does, for services that build their own
/// tonic exporter. `endpoint` is the exporter endpoint (`None` = environment/default).
///
/// Builds with and without the crate feature `otlp-tls`, so service code needs no
/// `#[cfg(feature = "otlp-tls")]` of its own (`make lint` runs clippy with
/// `--no-default-features`):
/// - with `otlp-tls`: tonic uses the settings for `https` endpoints;
///   `insecure_skip_verify` with an `https` endpoint is `CONFIG` (use `http/protobuf`).
/// - without it: plaintext (or unset) endpoints are returned unchanged; an `https` endpoint is
///   `CONFIG` (needs the crate feature `otlp-tls`).
pub fn apply_grpc_tls(
    builder: OtlpGrpcExporterBuilder,
    endpoint: Option<&str>,
    tls: &TlsConfig,
) -> Result<OtlpGrpcExporterBuilder> {
    grpc_tls(builder, endpoint, tls)
}

#[cfg(feature = "otlp-tls")]
fn grpc_tls(
    b: OtlpGrpcExporterBuilder,
    endpoint: Option<&str>,
    tls: &TlsConfig,
) -> Result<OtlpGrpcExporterBuilder> {
    use opentelemetry_otlp::tonic_types::transport::{Certificate, ClientTlsConfig, Identity};
    // tonic uses the TLS settings for `https` endpoints only.
    if tls.insecure_skip_verify && endpoint.is_some_and(is_https) {
        return Err(Error::config(
            "tracing: insecure_skip_verify is not supported for grpc; use http/protobuf",
        ));
    }
    let read = |path: &std::path::Path, what: &str| {
        std::fs::read(path).map_err(|e| {
            Error::config(format!("{what} file {} cannot be read", path.display())).with_source(e)
        })
    };
    let mut cfg = ClientTlsConfig::new().with_enabled_roots();
    let mut ca = Vec::new();
    if let Some(path) = &tls.ca_cert_path {
        ca.extend(read(path, "CA certificate")?);
        ca.push(b'\n');
    }
    if let Some(pem) = &tls.ca_cert_pem {
        ca.extend_from_slice(pem.as_bytes());
    }
    if !ca.is_empty() {
        cfg = cfg.ca_certificate(Certificate::from_pem(ca));
    }
    if let (Some(cert), Some(key)) = (&tls.client_cert_path, &tls.client_key_path) {
        cfg = cfg.identity(Identity::from_pem(
            read(cert, "client certificate")?,
            read(key, "client key")?,
        ));
    }
    Ok(b.with_tls_config(cfg))
}

#[cfg(not(feature = "otlp-tls"))]
fn grpc_tls(
    b: OtlpGrpcExporterBuilder,
    endpoint: Option<&str>,
    tls: &TlsConfig,
) -> Result<OtlpGrpcExporterBuilder> {
    let _ = tls;
    if !endpoint.is_some_and(is_https) {
        return Ok(b); // plaintext (or environment-chosen) endpoint: TLS settings do not apply
    }
    Err(Error::config(
        "tracing: TLS settings for grpc need the crate feature \"otlp-tls\"; use http/protobuf",
    ))
}