Skip to main content

guardrail_proxy/
telemetry.rs

1//! OpenTelemetry distributed tracing support.
2//!
3//! When `observability.otlp_endpoint` is set, `guardrail-rs` exports traces
4//! to an OpenTelemetry-compatible collector (Jaeger, Grafana Tempo, OTLP
5//! gRPC endpoint, etc.) via the OTLP gRPC protocol.
6//!
7//! ## Span hierarchy
8//!
9//! Each scanned request produces one root span, one child span per pipeline
10//! stage, and one for the upstream call:
11//!
12//! ```text
13//! guardrail.request              {request_id, model, provider, decision, http.status_code, entities_found}
14//! ├── guardrail.stage.<stage>    {stage, decision, entities_found}   (one per stage, in order)
15//! └── guardrail.upstream.forward {upstream_url, http.status_code}
16//! ```
17//!
18//! Stage spans are opened by [`guardrail_core::Pipeline`] itself, around
19//! each stage's `evaluate`. All three use the `tracing` target
20//! [`TRACE_TARGET`]; [`otel_layer`] exports only spans with that target.
21//!
22//! ## Enabling tracing
23//!
24//! Set `observability.otlp_endpoint` in your `guardrail.toml`:
25//!
26//! ```toml
27//! [observability]
28//! otlp_endpoint = "http://localhost:4317"   # gRPC OTLP
29//! ```
30//!
31//! Leave the field empty (or omit it) to disable OTLP export. The
32//! `tracing`/`tracing-subscriber` spans used for log correlation are always
33//! emitted regardless of this setting.
34
35use guardrail_config::ObservabilityConfig;
36use opentelemetry::trace::TracerProvider as _;
37use opentelemetry_otlp::WithExportConfig;
38pub use opentelemetry_sdk::trace::SdkTracerProvider;
39use tracing_subscriber::{filter::filter_fn, registry::LookupSpan, Layer};
40
41/// Name used for all guardrail-rs spans in the trace backend, and the
42/// `service.name` of the exported resource.
43pub const TRACER_NAME: &str = "guardrail-rs";
44
45/// `tracing` target of every span exported to OpenTelemetry.
46pub const TRACE_TARGET: &str = "guardrail::trace";
47
48/// A `tracing-subscriber` layer that exports guardrail-rs's spans (target
49/// [`TRACE_TARGET`]) through `provider`. Add it to the subscriber next to
50/// the log layers.
51///
52/// # Examples
53///
54/// ```rust,no_run
55/// use guardrail_config::ObservabilityConfig;
56/// use guardrail_proxy::telemetry;
57/// use tracing_subscriber::prelude::*;
58///
59/// let obs = ObservabilityConfig::default();
60/// if let Some(provider) = telemetry::build_otel_layer(&obs).unwrap() {
61///     tracing_subscriber::registry()
62///         .with(telemetry::otel_layer(&provider))
63///         .init();
64/// }
65/// ```
66pub fn otel_layer<S>(provider: &SdkTracerProvider) -> impl Layer<S> + Send + Sync
67where
68    S: tracing::Subscriber + for<'span> LookupSpan<'span> + Send + Sync,
69{
70    tracing_opentelemetry::layer()
71        .with_tracer(provider.tracer(TRACER_NAME))
72        .with_filter(filter_fn(|metadata| {
73            metadata.is_span() && metadata.target() == TRACE_TARGET
74        }))
75}
76
77/// Errors that can occur while setting up the OpenTelemetry tracer.
78#[derive(Debug, thiserror::Error)]
79pub enum OtelError {
80    /// The OTLP exporter could not be built.
81    #[error("failed to build OTLP exporter: {0}")]
82    ExporterBuild(String),
83    /// The tracer provider could not be installed.
84    #[error("failed to install global tracer provider: {0}")]
85    ProviderInstall(String),
86}
87
88/// Build the tracer provider that exports traces to an OTLP gRPC endpoint,
89/// with `service.name = "guardrail-rs"`. Pass it to [`otel_layer`].
90///
91/// Returns `Ok(None)` if `config.otlp_endpoint` is empty or absent — OTLP
92/// export is disabled and callers should skip adding the layer.
93///
94/// The returned [`SdkTracerProvider`] **must** be shut down gracefully on
95/// process exit by calling `provider.shutdown()`, or buffered spans may be
96/// lost. Pass it to [`shutdown_tracer_provider`].
97///
98/// # Errors
99///
100/// Returns [`OtelError`] if the OTLP pipeline cannot be built (e.g. the
101/// endpoint URL is malformed or the tonic transport layer cannot start).
102///
103/// # Examples
104///
105/// ```rust,no_run
106/// use guardrail_config::ObservabilityConfig;
107/// use guardrail_proxy::telemetry;
108/// use tracing_subscriber::prelude::*;
109///
110/// let obs = ObservabilityConfig::default();
111/// if let Some(provider) = telemetry::build_otel_layer(&obs).unwrap() {
112///     tracing_subscriber::registry()
113///         .with(telemetry::otel_layer(&provider))
114///         .init();
115///     // ... run ...
116///     telemetry::shutdown_tracer_provider(provider);
117/// }
118/// ```
119pub fn build_otel_layer(
120    config: &ObservabilityConfig,
121) -> Result<Option<SdkTracerProvider>, OtelError> {
122    let endpoint = config.otlp_endpoint.trim();
123    if endpoint.is_empty() {
124        return Ok(None);
125    }
126
127    let exporter = opentelemetry_otlp::SpanExporter::builder()
128        .with_tonic()
129        .with_endpoint(endpoint)
130        .build()
131        .map_err(|e| OtelError::ExporterBuild(e.to_string()))?;
132
133    let resource = opentelemetry_sdk::Resource::builder()
134        .with_service_name(TRACER_NAME)
135        .build();
136    let provider = SdkTracerProvider::builder()
137        .with_resource(resource)
138        .with_batch_exporter(exporter)
139        .build();
140
141    Ok(Some(provider))
142}
143
144/// Flush all buffered spans and shut down the tracer provider.
145///
146/// Call this once at process exit, after the server has stopped accepting
147/// new requests, to ensure no spans are lost.
148///
149/// # Examples
150///
151/// ```rust,no_run
152/// use guardrail_proxy::telemetry;
153/// # let provider: telemetry::SdkTracerProvider = todo!();
154/// telemetry::shutdown_tracer_provider(provider);
155/// ```
156pub fn shutdown_tracer_provider(provider: SdkTracerProvider) {
157    if let Err(e) = provider.shutdown() {
158        tracing::warn!(error = %e, "failed to shut down OTel tracer provider");
159    }
160}
161
162/// The span for one pipeline stage evaluation. The pipeline opens one
163/// around every stage itself; this is the same span, for custom pipelines.
164///
165/// # Examples
166///
167/// ```rust
168/// use guardrail_proxy::telemetry;
169///
170/// let stage_span = telemetry::stage_span("regex_injection");
171/// let _guard = stage_span.entered();
172/// ```
173pub fn stage_span(stage_name: &str) -> tracing::Span {
174    guardrail_core::pipeline::stage_span(stage_name)
175}
176
177/// Create the root span for an entire request lifecycle.
178///
179/// The span covers the full round-trip including pipeline evaluation and
180/// upstream forwarding.
181///
182/// # Examples
183///
184/// ```rust
185/// use guardrail_proxy::telemetry;
186///
187/// let request_span = telemetry::request_span("req-abc123", "gpt-4o", "openai");
188/// let _guard = request_span.entered();
189/// ```
190pub fn request_span(request_id: &str, model: &str, provider: &str) -> tracing::Span {
191    tracing::info_span!(
192        target: "guardrail::trace",
193        "guardrail.request",
194        otel.name = "guardrail.request",
195        request_id = request_id,
196        model = model,
197        provider = provider,
198        decision = tracing::field::Empty,
199        http.status_code = tracing::field::Empty,
200        entities_found = tracing::field::Empty,
201    )
202}
203
204/// The request span as the proxy opens it, before the body is parsed:
205/// `request_id` and `model` are recorded once they are known.
206pub(crate) fn incoming_request_span(provider: &str) -> tracing::Span {
207    tracing::info_span!(
208        target: "guardrail::trace",
209        "guardrail.request",
210        otel.name = "guardrail.request",
211        request_id = tracing::field::Empty,
212        model = tracing::field::Empty,
213        provider = provider,
214        decision = tracing::field::Empty,
215        http.status_code = tracing::field::Empty,
216        entities_found = tracing::field::Empty,
217    )
218}
219
220/// Create a span for the upstream forwarding step.
221///
222/// # Examples
223///
224/// ```rust
225/// use guardrail_proxy::telemetry;
226///
227/// let span = telemetry::upstream_span("https://api.openai.com");
228/// let _guard = span.entered();
229/// ```
230pub fn upstream_span(upstream_url: &str) -> tracing::Span {
231    tracing::info_span!(
232        target: "guardrail::trace",
233        "guardrail.upstream.forward",
234        otel.name = "guardrail.upstream.forward",
235        upstream_url = upstream_url,
236        http.status_code = tracing::field::Empty,
237    )
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243    use guardrail_config::ObservabilityConfig;
244
245    #[test]
246    fn test_empty_otlp_endpoint_returns_none() {
247        let config = ObservabilityConfig::default();
248        // default otlp_endpoint is empty string
249        let result = build_otel_layer(&config).unwrap();
250        assert!(result.is_none());
251    }
252
253    #[test]
254    fn test_whitespace_only_otlp_endpoint_returns_none() {
255        // `.trim()` in build_otel_layer should treat a whitespace-only
256        // endpoint the same as an absent one, rather than attempting to
257        // build an exporter against an empty address.
258        let config = ObservabilityConfig {
259            otlp_endpoint: "   ".to_string(),
260            ..Default::default()
261        };
262        let result = build_otel_layer(&config).unwrap();
263        assert!(result.is_none());
264    }
265
266    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
267    async fn test_build_otel_layer_with_endpoint_returns_provider() {
268        // Building the tonic gRPC exporter is lazy — it does not connect
269        // eagerly — so this succeeds even with no collector listening on
270        // the endpoint. This exercises the `Some` path (the tracer provider
271        // is actually constructed) and the `shutdown_tracer_provider` call.
272        //
273        // Requires an active Tokio runtime: `Endpoint::connect_lazy()`
274        // spawns a background connection-management task via
275        // `tokio::task::spawn` even though it doesn't block on an actual
276        // handshake, so a plain `#[test]` panics with "there is no reactor
277        // running".
278        //
279        // Requires a MULTI-THREADED runtime specifically: this test body
280        // has no `.await` points, and `shutdown_tracer_provider` below
281        // blocks synchronously waiting for that same background task to
282        // acknowledge shutdown. On the default current-thread runtime, the
283        // one and only executor thread is the thread doing that blocking
284        // wait — it can never also poll the background task to let it make
285        // progress, so the test hangs and times out rather than panicking.
286        // A multi-thread runtime has a separate worker thread free to drive
287        // the background task while the main thread blocks.
288        let config = ObservabilityConfig {
289            otlp_endpoint: "http://localhost:4317".to_string(),
290            ..Default::default()
291        };
292        let provider = build_otel_layer(&config)
293            .expect("building the OTLP exporter should not require a live collector")
294            .expect("a non-empty endpoint should produce Some(provider)");
295        shutdown_tracer_provider(provider);
296    }
297
298    #[test]
299    fn test_otel_error_display() {
300        let exporter_err = OtelError::ExporterBuild("bad endpoint".to_string());
301        assert_eq!(
302            exporter_err.to_string(),
303            "failed to build OTLP exporter: bad endpoint"
304        );
305
306        let provider_err = OtelError::ProviderInstall("already installed".to_string());
307        assert_eq!(
308            provider_err.to_string(),
309            "failed to install global tracer provider: already installed"
310        );
311    }
312
313    #[test]
314    fn test_stage_span_is_created() {
315        let span = stage_span("regex_injection");
316        assert!(span.metadata().is_some() || span.is_disabled());
317    }
318
319    #[test]
320    fn test_request_span_is_created() {
321        let span = request_span("req-1", "gpt-4o", "openai");
322        assert!(span.metadata().is_some() || span.is_disabled());
323    }
324
325    #[test]
326    fn test_upstream_span_is_created() {
327        let span = upstream_span("https://api.openai.com");
328        assert!(span.metadata().is_some() || span.is_disabled());
329    }
330}