mod auth;
mod endpoint;
#[cfg(feature = "logs-otlp")]
mod logs;
#[cfg(test)]
mod testing;
mod trace;
pub use auth::GcpAuthInterceptor;
pub use endpoint::TelemetryEndpoint;
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";
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)
}
#[derive(Debug, Builder)]
#[non_exhaustive]
pub struct GcpOtlpExporterBuilder {
pub google_project_id: String,
pub resource: Option<Resource>,
pub endpoint: Option<TelemetryEndpoint>,
pub max_export_timeout: Option<Duration>,
pub span_events: Option<bool>,
pub auth_headers: Option<Arc<GoogleAuthHeaders>>,
#[default = "OnceCell::new()"]
shared_auth_interceptor: OnceCell<GcpAuthInterceptor>,
#[default = "default_export_timeout()"]
default_export_timeout: Duration,
}
impl GcpOtlpExporterBuilder {
pub async fn for_default_project_id() -> GcloudObservabilityResult<Self> {
Ok(Self::new(common::detect_google_project_id().await?))
}
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);
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?))
}
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();
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"
));
}
}