use std::time::Duration;
#[cfg(feature = "telemetry")]
use opentelemetry_sdk::trace::SdkTracerProvider;
const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
#[must_use = "TelemetryGuard must be held for the lifetime of the process to flush spans on shutdown"]
pub struct TelemetryGuard {
#[cfg(feature = "telemetry")]
provider: Option<SdkTracerProvider>,
timeout: Duration,
}
impl TelemetryGuard {
pub fn noop() -> Self {
Self {
#[cfg(feature = "telemetry")]
provider: None,
timeout: DEFAULT_SHUTDOWN_TIMEOUT,
}
}
#[cfg(feature = "telemetry")]
pub(crate) fn from_provider(provider: SdkTracerProvider) -> Self {
Self {
provider: Some(provider),
timeout: DEFAULT_SHUTDOWN_TIMEOUT,
}
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
#[cfg(all(feature = "telemetry", any(test, debug_assertions)))]
pub fn has_provider(&self) -> bool {
self.provider.is_some()
}
#[cfg(all(not(feature = "telemetry"), any(test, debug_assertions)))]
pub fn has_provider(&self) -> bool {
false
}
}
impl Drop for TelemetryGuard {
fn drop(&mut self) {
#[cfg(feature = "telemetry")]
{
if let Some(provider) = self.provider.take() {
if let Err(err) = provider.force_flush() {
tracing::warn!(
target: "cognee.observability",
?err,
"OTEL force_flush failed during TelemetryGuard drop"
);
}
if let Err(err) = provider.shutdown_with_timeout(self.timeout) {
tracing::warn!(
target: "cognee.observability",
?err,
"OTEL shutdown_with_timeout failed during TelemetryGuard drop"
);
}
}
}
let _ = self.timeout;
}
}