Skip to main content

gcloud_observability/trace_api/
mod.rs

1//! Exports spans to Google Cloud Trace through the Cloud Trace API v2
2//! (`cloudtrace.googleapis.com`).
3
4mod client;
5mod exporter;
6
7pub use exporter::GcpCloudTraceExporter;
8
9use crate::common;
10use crate::errors::{GcloudObservabilityError, GcloudObservabilityResult};
11use opentelemetry_sdk::runtime;
12use opentelemetry_sdk::trace::span_processor_with_async_runtime::BatchSpanProcessor;
13use opentelemetry_sdk::trace::{SdkTracerProvider, SpanExporter, Tracer, TracerProviderBuilder};
14use opentelemetry_sdk::Resource;
15use rsb_derive::*;
16use std::time::Duration;
17
18#[derive(Debug, Builder)]
19#[non_exhaustive]
20pub struct GcpCloudTraceExporterBuilder {
21    /// Checked when the exporter is built: an empty ID, or one with `/` or a control character,
22    /// fails with [`InvalidParametersError`].
23    ///
24    /// [`InvalidParametersError`]: crate::errors::GcloudObservabilityError::InvalidParametersError
25    pub google_project_id: String,
26    pub resource: Option<Resource>,
27    /// Exports span events to Cloud Trace as `time_events` annotations. Defaults to `false`
28    /// since span events are commonly captured by a logging layer as well.
29    pub span_events: Option<bool>,
30    /// The longest a batch export may take before the batch is dropped. Shutdown exports every
31    /// batch queued ahead of it, one after the other, so it can take this long once per 512
32    /// queued spans, rounded up. Defaults to the OpenTelemetry SDK default of 30 seconds, or
33    /// `OTEL_BSP_EXPORT_TIMEOUT` when set.
34    pub max_export_timeout: Option<Duration>,
35}
36
37impl GcpCloudTraceExporterBuilder {
38    /// Starts a builder for the project of the environment the process runs in, as
39    /// [`gcloud_sdk::GoogleEnvironment::detect_google_project_id`] finds it.
40    pub async fn for_default_project_id() -> GcloudObservabilityResult<Self> {
41        Ok(Self::new(common::detect_google_project_id().await?))
42    }
43
44    /// [`Self::create_provider_from_builder`] over the OpenTelemetry SDK's default builder.
45    ///
46    /// Shut the provider down before the process ends. `shutdown`, `force_flush` and dropping it
47    /// block the calling thread until the batch task, which runs on the Tokio runtime the
48    /// provider was created on, is done, so on a current-thread runtime they never return.
49    /// Call them on a multi-threaded runtime, or from a thread outside the runtime.
50    pub async fn create_provider(&self) -> Result<SdkTracerProvider, GcloudObservabilityError> {
51        self.create_provider_from_builder(SdkTracerProvider::builder())
52            .await
53    }
54
55    /// Adds a batch processor over the Cloud Trace API exporter to `builder`, and
56    /// [`Self::resource`] as the exporter's resource.
57    ///
58    /// Shut the provider down before the process ends. `shutdown`, `force_flush` and dropping it
59    /// block the calling thread until the batch task, which runs on the Tokio runtime the
60    /// provider was created on, is done, so on a current-thread runtime they never return.
61    /// Call them on a multi-threaded runtime, or from a thread outside the runtime.
62    pub async fn create_provider_from_builder(
63        &self,
64        builder: TracerProviderBuilder,
65    ) -> Result<SdkTracerProvider, GcloudObservabilityError> {
66        let exporter = GcpCloudTraceExporter::new(
67            self.google_project_id.clone(),
68            self.resource
69                .clone()
70                .unwrap_or_else(|| Resource::builder_empty().build()),
71            self.span_events.unwrap_or(false),
72        )
73        .await?;
74
75        let tracer_provider = builder
76            .with_span_processor(self.batch_span_processor(exporter))
77            .build();
78
79        Ok(tracer_provider)
80    }
81
82    fn batch_span_processor(
83        &self,
84        exporter: impl SpanExporter + 'static,
85    ) -> BatchSpanProcessor<runtime::Tokio> {
86        common::batch_span_processor(exporter, self.max_export_timeout)
87    }
88
89    pub fn install(&self, provider: &SdkTracerProvider) -> Tracer {
90        common::tracer(provider)
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use opentelemetry::trace::{Tracer, TracerProvider};
98    use opentelemetry_sdk::error::OTelSdkResult;
99    use opentelemetry_sdk::trace::SpanData;
100    use std::time::Instant;
101
102    #[derive(Debug)]
103    struct HungExporter;
104
105    impl SpanExporter for HungExporter {
106        fn export(
107            &self,
108            _batch: Vec<SpanData>,
109        ) -> impl std::future::Future<Output = OTelSdkResult> + Send {
110            std::future::pending()
111        }
112    }
113
114    #[tokio::test(flavor = "multi_thread")]
115    async fn configured_export_timeout_bounds_shutdown() {
116        let builder = GcpCloudTraceExporterBuilder::new("test-project".to_string())
117            .with_max_export_timeout(Duration::from_millis(200));
118        let provider = SdkTracerProvider::builder()
119            .with_span_processor(builder.batch_span_processor(HungExporter))
120            .build();
121        provider.tracer("test").start("hung");
122
123        let started = Instant::now();
124        provider
125            .shutdown()
126            .expect_err("an abandoned export is reported");
127
128        assert!(started.elapsed() < Duration::from_secs(5));
129    }
130
131    #[tokio::test]
132    async fn invalid_project_id_is_refused_before_credentials_are_read() {
133        let result = GcpCloudTraceExporterBuilder::new("orders/prod".to_string())
134            .create_provider()
135            .await;
136
137        assert!(matches!(
138            result,
139            Err(GcloudObservabilityError::InvalidParametersError(error))
140                if error.field == "google_project_id"
141        ));
142    }
143}