cognee_observability/
guard.rs1use std::time::Duration;
9
10#[cfg(feature = "telemetry")]
11use opentelemetry_sdk::trace::SdkTracerProvider;
12
13const DEFAULT_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
14
15#[must_use = "TelemetryGuard must be held for the lifetime of the process to flush spans on shutdown"]
22pub struct TelemetryGuard {
23 #[cfg(feature = "telemetry")]
24 provider: Option<SdkTracerProvider>,
25 timeout: Duration,
26}
27
28impl TelemetryGuard {
29 pub fn noop() -> Self {
31 Self {
32 #[cfg(feature = "telemetry")]
33 provider: None,
34 timeout: DEFAULT_SHUTDOWN_TIMEOUT,
35 }
36 }
37
38 #[cfg(feature = "telemetry")]
39 pub(crate) fn from_provider(provider: SdkTracerProvider) -> Self {
40 Self {
41 provider: Some(provider),
42 timeout: DEFAULT_SHUTDOWN_TIMEOUT,
43 }
44 }
45
46 pub fn with_timeout(mut self, timeout: Duration) -> Self {
48 self.timeout = timeout;
49 self
50 }
51
52 #[cfg(all(feature = "telemetry", any(test, debug_assertions)))]
54 pub fn has_provider(&self) -> bool {
55 self.provider.is_some()
56 }
57
58 #[cfg(all(not(feature = "telemetry"), any(test, debug_assertions)))]
60 pub fn has_provider(&self) -> bool {
61 false
62 }
63}
64
65impl Drop for TelemetryGuard {
66 fn drop(&mut self) {
67 #[cfg(feature = "telemetry")]
68 {
69 if let Some(provider) = self.provider.take() {
70 if let Err(err) = provider.force_flush() {
71 tracing::warn!(
72 target: "cognee.observability",
73 ?err,
74 "OTEL force_flush failed during TelemetryGuard drop"
75 );
76 }
77 if let Err(err) = provider.shutdown_with_timeout(self.timeout) {
78 tracing::warn!(
79 target: "cognee.observability",
80 ?err,
81 "OTEL shutdown_with_timeout failed during TelemetryGuard drop"
82 );
83 }
84 }
85 }
86 let _ = self.timeout;
89 }
90}