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