gcloud-observability 0.31.0

Google Cloud observability for Rust: OpenTelemetry exporters for Cloud Trace through the Cloud Trace API or OTLP, and a tracing layer for Cloud Logging and Error Reporting with entries correlated to traces
Documentation
//! Exports through OTLP to the Google Cloud Telemetry API
//! (`telemetry.googleapis.com`), authenticated with Google credentials.

mod auth;
mod endpoint;
#[cfg(feature = "logs-otlp")]
mod logs;
#[cfg(test)]
mod testing;
mod trace;

pub use auth::GcpAuthInterceptor;
pub use endpoint::TelemetryEndpoint;

/// The Google credentials' headers [`GcpAuthInterceptor::new`] and
/// [`GcpOtlpExporterBuilder::auth_headers`] take, re-exported so callers need not depend on
/// `gcloud-sdk` directly.
pub use gcloud_sdk::GoogleAuthHeaders;

use crate::common;
use crate::errors::{GcloudObservabilityError, GcloudObservabilityResult};
use gcloud_sdk::tonic::transport::Endpoint;
use opentelemetry::KeyValue;
use opentelemetry_otlp::tonic_types::transport::ClientTlsConfig;
use opentelemetry_otlp::{
    WithExportConfig, WithTonicConfig, OTEL_EXPORTER_OTLP_TIMEOUT,
    OTEL_EXPORTER_OTLP_TIMEOUT_DEFAULT,
};
use opentelemetry_sdk::Resource;
use rsb_derive::*;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::OnceCell;

const TELEMETRY_API_ENDPOINT: &str = "https://telemetry.googleapis.com";

/// OpenTelemetry's export timeout: `OTEL_EXPORTER_OTLP_TIMEOUT` in milliseconds when it holds
/// one, otherwise the specification's 10 seconds.
fn default_export_timeout() -> Duration {
    export_timeout_from(std::env::var(OTEL_EXPORTER_OTLP_TIMEOUT).ok().as_deref())
}

fn export_timeout_from(milliseconds: Option<&str>) -> Duration {
    milliseconds
        .and_then(|milliseconds| milliseconds.parse().ok())
        .map_or(OTEL_EXPORTER_OTLP_TIMEOUT_DEFAULT, Duration::from_millis)
}

/// Builds OpenTelemetry exporters and providers that send spans, and under the
/// `logs-otlp` feature log records, through OTLP to the Google Cloud Telemetry API.
#[derive(Debug, Builder)]
#[non_exhaustive]
pub struct GcpOtlpExporterBuilder {
    /// Set as `gcp.project_id` on the resource of every provider built here, over any
    /// value the resource already has. Checked when an exporter is built: an empty ID, or one
    /// with `/` or a control character, fails with [`InvalidParametersError`].
    ///
    /// [`InvalidParametersError`]: crate::errors::GcloudObservabilityError::InvalidParametersError
    pub google_project_id: String,
    /// Merged key by key over the resource of the provider builder, and under
    /// `gcp.project_id`. While unset, the provider builder's resource stands;
    /// `create_provider` and `create_logger_provider` start from the OpenTelemetry SDK's
    /// default resource. A builder passed to `create_provider_from_builder` or
    /// `create_logger_provider_from_builder` without a resource of its own does not get that
    /// default: its resource is this one and `gcp.project_id`, so set `service.name` here or
    /// on the builder.
    pub resource: Option<Resource>,
    /// Defaults to `https://telemetry.googleapis.com`. TLS is verified against the host of the
    /// endpoint.
    pub endpoint: Option<TelemetryEndpoint>,
    /// The longest a batch export may take before the batch is dropped. It is the timeout of
    /// connecting, TLS handshake included, and of every export request, and for spans also the
    /// batch processor's bound. Shutdown exports every batch queued ahead of it, one after the
    /// other, so it can take this long once per 512 queued spans or log records, rounded up.
    /// While unset, connecting, the TLS handshake and every request time out after the
    /// OpenTelemetry standard 10 seconds, or `OTEL_EXPORTER_OTLP_TIMEOUT` (milliseconds) when
    /// it is set, and the span processor gives up after 30 seconds, or
    /// `OTEL_BSP_EXPORT_TIMEOUT`.
    pub max_export_timeout: Option<Duration>,
    /// Exports span events, the `tracing` events inside a span among them, with their spans.
    /// Defaults to `false` since span events are commonly captured by a logging layer as well,
    /// and would show twice in Trace Explorer. Applies to [`Self::span_exporter`] and every
    /// provider built from it.
    pub span_events: Option<bool>,
    /// The credentials exports are authenticated with. Defaults to the Application Default
    /// Credentials with the `cloud-platform` scope. Read by the first exporter or
    /// [`Self::auth_interceptor`] call; every later one shares those credentials.
    pub auth_headers: Option<Arc<GoogleAuthHeaders>>,
    #[default = "OnceCell::new()"]
    shared_auth_interceptor: OnceCell<GcpAuthInterceptor>,
    /// The timeout of connecting and of requests while `max_export_timeout` is unset; settable
    /// so a test need not wait out the real default or change the process environment.
    #[default = "default_export_timeout()"]
    default_export_timeout: Duration,
}

impl GcpOtlpExporterBuilder {
    /// Starts a builder for the project of the environment the process runs in, as
    /// [`gcloud_sdk::GoogleEnvironment::detect_google_project_id`] finds it.
    pub async fn for_default_project_id() -> GcloudObservabilityResult<Self> {
        Ok(Self::new(common::detect_google_project_id().await?))
    }

    /// The interceptor every exporter built here authenticates with, created over
    /// [`Self::auth_headers`] on the first call and cloned after it. All of them share one
    /// set of credentials and one refresh task, which ends once this builder and every
    /// exporter and interceptor built from it are dropped.
    pub async fn auth_interceptor(&self) -> GcloudObservabilityResult<GcpAuthInterceptor> {
        self.shared_auth_interceptor
            .get_or_try_init(|| async {
                match &self.auth_headers {
                    Some(auth_headers) => GcpAuthInterceptor::new(Arc::clone(auth_headers)).await,
                    None => GcpAuthInterceptor::from_adc().await,
                }
            })
            .await
            .cloned()
    }

    async fn configure_exporter<B>(&self, exporter: B) -> GcloudObservabilityResult<B>
    where
        B: WithExportConfig + WithTonicConfig,
    {
        common::validate_google_project_id(&self.google_project_id)?;
        let endpoint = match &self.endpoint {
            Some(endpoint) => endpoint.to_string(),
            None => TELEMETRY_API_ENDPOINT.to_string(),
        };
        let tls_config = ClientTlsConfig::new().with_enabled_roots();
        let export_timeout = self
            .max_export_timeout
            .unwrap_or(self.default_export_timeout);
        // The exporter's own timeout starts once a request is sent, so a server that takes
        // the connection and never completes the TLS handshake is bounded only by timeouts
        // set on the channel. A channel passed in replaces the exporter's endpoint and TLS
        // configuration, which therefore move onto it.
        let channel = Endpoint::from_shared(endpoint)
            .map_err(|error| {
                GcloudObservabilityError::invalid_parameters("endpoint", error.to_string())
            })?
            .tls_config(tls_config.timeout(export_timeout))
            .map_err(|error| GcloudObservabilityError::system_caused_by("OTLP TLS error", error))?
            .connect_timeout(export_timeout)
            .timeout(export_timeout)
            .connect_lazy();
        let exporter = exporter.with_channel(channel).with_timeout(export_timeout);
        Ok(exporter.with_interceptor(self.auth_interceptor().await?))
    }

    // In the order they are merged into a provider, so that `gcp.project_id` always names
    // `google_project_id`.
    fn provider_resources(&self) -> impl Iterator<Item = Resource> {
        let project = Resource::builder_empty()
            .with_attribute(KeyValue::new(
                "gcp.project_id",
                self.google_project_id.clone(),
            ))
            .build();
        self.resource.clone().into_iter().chain([project])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::errors::GcloudObservabilityError;
    use crate::otlp::testing::{ScriptedAccessToken, ORDERS_PROJECT};

    #[test]
    fn export_timeout_is_taken_in_milliseconds_or_defaults_to_ten_seconds() {
        assert_eq!(
            export_timeout_from(Some("2500")),
            Duration::from_millis(2500)
        );
        assert_eq!(export_timeout_from(Some("soon")), Duration::from_secs(10));
        assert_eq!(export_timeout_from(None), Duration::from_secs(10));
    }

    #[tokio::test]
    async fn exporters_of_one_builder_share_one_refresh_task() {
        let auth_headers = ScriptedAccessToken::new("first-token").auth_headers();
        let builder = GcpOtlpExporterBuilder::new(ORDERS_PROJECT.to_string())
            .with_auth_headers(Arc::clone(&auth_headers));

        let _spans = builder.auth_interceptor().await.unwrap();
        let _logs = builder.auth_interceptor().await.unwrap();

        // Held here, by the builder and by the one refresh task.
        assert_eq!(Arc::strong_count(&auth_headers), 3);
    }

    #[tokio::test]
    async fn invalid_project_id_is_refused_before_credentials_are_read() {
        let result = GcpOtlpExporterBuilder::new("orders/prod".to_string())
            .span_exporter()
            .await;

        assert!(matches!(
            result,
            Err(GcloudObservabilityError::InvalidParametersError(error))
                if error.field == "google_project_id"
        ));
    }
}