Skip to main content

rusty_otel/
lib.rs

1//! # rusty-otel
2//!
3//! OpenTelemetry export layer for the [`rusty_agent_runtime`] engine.
4//!
5//! `rusty-agent-runtime` already emits structured `tracing` spans from its
6//! executor (`rusty.run` → `rusty.super_step` → `rusty.node`). This crate
7//! wires a global [`tracing_subscriber`] that routes those spans to
8//! two sinks:
9//!
10//! - a human-readable `fmt` layer on stderr (always on), gated by an
11//!   [`EnvFilter`], and
12//! - an OTLP/HTTP span exporter (only when [`OTelConfig::otlp_endpoint`] is
13//!   set), so the same spans show up in a collector / Jaeger / any
14//!   OTLP-compatible backend.
15//!
16//! ## Quick start
17//!
18//! ```no_run
19//! // Local development: pretty logs only.
20//! let _guard = rusty_otel::init_local("my-agent").unwrap();
21//!
22//! // With a collector: logs + OTLP spans.
23//! let _guard = rusty_otel::init(rusty_otel::OTelConfig {
24//!     service_name: "my-agent".into(),
25//!     otlp_endpoint: Some("http://localhost:4318/v1/traces".into()),
26//!     log_filter: None, // RUST_LOG, defaulting to a sensible rusty filter
27//! })
28//! .unwrap();
29//! ```
30//!
31//! Keep the returned [`OTelGuard`] alive for the duration of the process and
32//! call [`OTelGuard::shutdown`] before exit to flush any buffered spans.
33
34use opentelemetry::global;
35use opentelemetry::trace::TracerProvider;
36use opentelemetry_otlp::{SpanExporter, WithExportConfig};
37use opentelemetry_sdk::trace::SdkTracerProvider;
38use opentelemetry_sdk::Resource;
39use tracing_subscriber::layer::{Layer, SubscriberExt};
40use tracing_subscriber::util::SubscriberInitExt;
41use tracing_subscriber::{fmt, EnvFilter, Registry};
42
43/// Default log filter used when neither [`OTelConfig::log_filter`] nor the
44/// `RUST_LOG` environment variable provides one. `rusty.super_step` spans
45/// are emitted at DEBUG, so the `rusty_agent_runtime=debug` directive
46/// surfaces the full span taxonomy locally without drowning other crates in
47/// noise.
48pub const DEFAULT_FILTER: &str = "info,rusty_agent_runtime=debug";
49
50/// Errors returned by [`init`] and [`init_local`].
51#[derive(Debug, thiserror::Error)]
52pub enum OTelError {
53    /// A global tracing subscriber is already installed. `init` may only be
54    /// called once per process; the second call fails with this error.
55    #[error("a global tracing subscriber is already installed")]
56    SubscriberAlreadyInstalled,
57    /// The OTLP span exporter could not be built (bad endpoint, transport
58    /// configuration failure, ...).
59    #[error("failed to build the OTLP span exporter: {0}")]
60    ExporterBuild(String),
61    /// An explicit [`OTelConfig::log_filter`] directive failed to parse.
62    #[error("invalid log filter directive `{directive}`: {reason}")]
63    FilterParse {
64        /// The offending directive string.
65        directive: String,
66        /// The parser's explanation.
67        reason: String,
68    },
69}
70
71/// Convenient result alias for this crate.
72pub type Result<T> = std::result::Result<T, OTelError>;
73
74/// Configuration for [`init`].
75#[derive(Debug, Clone, Default)]
76pub struct OTelConfig {
77    /// Logical service name attached to every exported span as the OTel
78    /// `service.name` resource attribute (e.g. `"support-agent"`).
79    pub service_name: String,
80    /// OTLP/HTTP endpoint for span export, e.g.
81    /// `http://localhost:4318/v1/traces`. When `None`, no OTLP exporter is
82    /// installed and only the local `fmt` layer runs.
83    pub otlp_endpoint: Option<String>,
84    /// Log filter directive for the stderr `fmt` layer (the `EnvFilter`
85    /// syntax, e.g. `"info,rusty_agent_runtime=trace"`). When `None`, the
86    /// `RUST_LOG` environment variable is honored, falling back to
87    /// [`DEFAULT_FILTER`].
88    ///
89    /// The filter gates **local logging only**; OTLP span export is
90    /// unfiltered so a restrictive `RUST_LOG` (e.g. `warn`) never starves the
91    /// collector of traces.
92    pub log_filter: Option<String>,
93}
94
95impl OTelConfig {
96    /// Resolve the effective [`EnvFilter`]: explicit `log_filter` first,
97    /// then `RUST_LOG`, then [`DEFAULT_FILTER`].
98    fn env_filter(&self) -> Result<EnvFilter> {
99        match &self.log_filter {
100            Some(directive) => EnvFilter::try_new(directive).map_err(|e| OTelError::FilterParse {
101                directive: directive.clone(),
102                reason: e.to_string(),
103            }),
104            None => Ok(EnvFilter::try_from_default_env()
105                .unwrap_or_else(|_| EnvFilter::new(DEFAULT_FILTER))),
106        }
107    }
108}
109
110/// Handle returned by [`init`]/[`init_local`]. Shuts down the tracer
111/// provider (flushing any buffered spans) on [`OTelGuard::shutdown`] or on
112/// drop. Shutdown is idempotent.
113#[derive(Debug)]
114pub struct OTelGuard {
115    provider: Option<SdkTracerProvider>,
116}
117
118impl OTelGuard {
119    /// Flush and shut down the tracer provider. Calling this more than once
120    /// is a no-op after the first call; dropping the guard after an explicit
121    /// shutdown is also safe.
122    ///
123    /// Blocking: waits for the batch processor's final export (up to the
124    /// exporter timeout), so call it during process teardown rather than on
125    /// a hot async path.
126    pub fn shutdown(&mut self) {
127        if let Some(provider) = self.provider.take() {
128            // A shutdown error only means spans may be lost on the way out;
129            // there is nothing useful to recover into, so log and move on.
130            if let Err(err) = provider.shutdown() {
131                eprintln!("rusty-otel: tracer provider shutdown error: {err}");
132            }
133        }
134    }
135}
136
137impl Drop for OTelGuard {
138    fn drop(&mut self) {
139        self.shutdown();
140    }
141}
142
143/// Install the global tracing subscriber.
144///
145/// The subscriber is a filtered `fmt` layer on stderr (gated by the resolved
146/// [`EnvFilter`]) plus an unfiltered OTLP span layer when
147/// `config.otlp_endpoint` is `Some`. Filtering is per-layer: the log filter
148/// never throttles span export to the collector. Because the subscriber is
149/// global, this function may only succeed **once per process**; a second
150/// call returns [`OTelError::SubscriberAlreadyInstalled`] and leaves both
151/// the existing subscriber and the global OTel tracer provider untouched.
152///
153/// The OTLP exporter uses a batch span processor running on its own
154/// dedicated thread, so `init` works both inside and outside a Tokio
155/// runtime.
156pub fn init(config: OTelConfig) -> Result<OTelGuard> {
157    let filter = config.env_filter()?;
158    let fmt_layer = fmt::layer()
159        .with_writer(std::io::stderr)
160        .with_filter(filter);
161
162    match &config.otlp_endpoint {
163        Some(endpoint) => {
164            let provider = build_tracer_provider(&config.service_name, endpoint)?;
165            let tracer = provider.tracer("rusty-otel");
166            let otel_layer = tracing_opentelemetry::layer().with_tracer(tracer);
167            let installed = Registry::default()
168                .with(fmt_layer)
169                .with(otel_layer)
170                .try_init();
171            match installed {
172                Ok(()) => {
173                    // Publish the provider globally only after the subscriber
174                    // is actually installed; the layer itself holds the
175                    // tracer and does not need the global provider.
176                    global::set_tracer_provider(provider.clone());
177                    Ok(OTelGuard {
178                        provider: Some(provider),
179                    })
180                }
181                Err(_) => {
182                    // A failed re-init must not leak: shut the fresh provider
183                    // down so its exporter and batch-processor threads are
184                    // flushed and joined rather than detached.
185                    let _ = provider.shutdown();
186                    Err(OTelError::SubscriberAlreadyInstalled)
187                }
188            }
189        }
190        None => {
191            Registry::default()
192                .with(fmt_layer)
193                .try_init()
194                .map_err(|_| OTelError::SubscriberAlreadyInstalled)?;
195            Ok(OTelGuard { provider: None })
196        }
197    }
198}
199
200/// Install the global tracing subscriber with a local-only configuration:
201/// `fmt` layer + [`EnvFilter`], no OTLP export. Equivalent to calling
202/// [`init`] with only a service name.
203pub fn init_local(service_name: &str) -> Result<OTelGuard> {
204    init(OTelConfig {
205        service_name: service_name.to_owned(),
206        otlp_endpoint: None,
207        log_filter: None,
208    })
209}
210
211/// Build an [`SdkTracerProvider`] with a batch OTLP/HTTP span exporter and a
212/// `service.name` resource attribute.
213fn build_tracer_provider(service_name: &str, endpoint: &str) -> Result<SdkTracerProvider> {
214    let exporter = SpanExporter::builder()
215        .with_http()
216        .with_endpoint(endpoint)
217        .build()
218        .map_err(|e| OTelError::ExporterBuild(e.to_string()))?;
219
220    let resource = Resource::builder()
221        .with_service_name(service_name.to_owned())
222        .build();
223
224    let provider = SdkTracerProvider::builder()
225        .with_batch_exporter(exporter)
226        .with_resource(resource)
227        .build();
228    Ok(provider)
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn explicit_log_filter_wins() {
237        let config = OTelConfig {
238            service_name: "svc".into(),
239            otlp_endpoint: None,
240            log_filter: Some("rusty_agent_runtime=trace".into()),
241        };
242        assert_eq!(
243            config.env_filter().unwrap().to_string(),
244            "rusty_agent_runtime=trace"
245        );
246    }
247
248    #[test]
249    fn invalid_explicit_log_filter_is_an_error_not_a_panic() {
250        let config = OTelConfig {
251            service_name: "svc".into(),
252            otlp_endpoint: None,
253            log_filter: Some("info,,,bogus===".into()),
254        };
255        match config.env_filter() {
256            Err(OTelError::FilterParse { directive, .. }) => {
257                assert_eq!(directive, "info,,,bogus===");
258            }
259            other => panic!("expected FilterParse, got: {other:?}"),
260        }
261    }
262
263    #[test]
264    fn filter_defaults_when_unset_and_no_rust_log() {
265        // Only meaningful when RUST_LOG is absent; when the harness exports
266        // RUST_LOG the filter honors it instead of DEFAULT_FILTER. Either
267        // way the result must be a valid, non-empty directive set.
268        let config = OTelConfig::default();
269        let filter = config.env_filter().unwrap().to_string();
270        assert!(!filter.is_empty());
271        if std::env::var_os("RUST_LOG").is_none() {
272            // EnvFilter normalizes directive ordering in its Display impl,
273            // so compare the directive set rather than the raw string.
274            let mut got: Vec<&str> = filter.split(',').collect();
275            let mut want: Vec<&str> = DEFAULT_FILTER.split(',').collect();
276            got.sort_unstable();
277            want.sort_unstable();
278            assert_eq!(got, want);
279        }
280    }
281
282    #[test]
283    fn default_filter_includes_rusty_debug() {
284        assert!(DEFAULT_FILTER.contains("rusty_agent_runtime=debug"));
285    }
286}