camel_core/shared/observability/adapters/tracer.rs
1use std::future::Future;
2use std::pin::Pin;
3use std::sync::Arc;
4use std::task::{Context, Poll};
5use std::time::Instant;
6
7use opentelemetry::trace::{SpanKind, SpanRef, Status, TraceContextExt, Tracer};
8use opentelemetry::{Context as OtelContext, InstrumentationScope, KeyValue, global};
9use tower::Service;
10use tracing::Instrument;
11
12use crate::shared::observability::domain::{DetailLevel, MetricsLeversConfig};
13use camel_api::metrics::MetricsCollector;
14use camel_api::{BoxProcessor, CIRCUIT_OPEN, CamelError, Exchange, SpanKindHint, body_type_name};
15
16/// RAII guard that ensures an OTel span is ended when dropped.
17///
18/// This prevents span leaks if the inner processor panics or returns early.
19/// `pub(crate)` so the route compiler can reuse it for the route root span.
20pub(crate) struct SpanEndGuard(pub(crate) OtelContext);
21
22impl Drop for SpanEndGuard {
23 fn drop(&mut self) {
24 self.0.span().end();
25 }
26}
27
28/// A processor wrapper that emits tracing spans for each step.
29///
30/// This processor wraps another processor and adds distributed tracing by:
31/// 1. Starting a native OpenTelemetry span for each exchange
32/// 2. Propagating the OTel context through `exchange.otel_context`
33/// 3. Recording errors and status on the span
34///
35/// When no OTel provider is configured (noop provider), spans are no-ops with minimal overhead.
36pub struct TracingProcessor {
37 inner: BoxProcessor,
38 route_id: String,
39 step_id: String,
40 span_name: String,
41 step_index: usize,
42 detail_level: DetailLevel,
43 metrics: Option<Arc<dyn MetricsCollector>>,
44 /// Declared (authored) endpoint URI for `To` steps; `None` for every
45 /// other step kind. Labels the per-step `step_duration_secs` histogram
46 /// (steplatency 2.1) — the operator-authored URI, not a
47 /// runtime/resolved value, so label cardinality is bounded by the
48 /// route configuration.
49 to_uri: Option<Arc<str>>,
50 /// OTel span kind precomputed from `SpanKindHint` at construction.
51 span_kind: SpanKind,
52 /// Whether step spans are created. Gates SPANS only — metric families
53 /// (errors unconditionally) keep flowing when false
54 /// (metrics-configuration Req 1).
55 spans_enabled: bool,
56 /// Per-family metric levers; `increment_errors` is never gated.
57 metric_levers: MetricsLeversConfig,
58}
59
60/// Positional fallback span-name fragment for unlabeled steps. Shared by
61/// `TracingProcessor` (process steps) and `segment_span` (segment steps).
62pub(crate) fn step_id_for(index: usize) -> String {
63 format!("step-{index}")
64}
65
66impl TracingProcessor {
67 /// Wrap a processor with tracing.
68 ///
69 /// `label` names the span after the DSL step it wraps (e.g. `log`,
70 /// `to:direct`); when `None` the span falls back to the positional
71 /// `step-{index}` id. `kind_hint` selects the OTel span kind for the
72 /// step span and is converted once here. `to_uri` carries the declared
73 /// endpoint URI for `To` steps (steplatency 2.1) and labels the
74 /// call-time `step_duration_secs` histogram; `None` for non-To steps.
75 #[allow(clippy::too_many_arguments)]
76 pub fn new(
77 inner: BoxProcessor,
78 route_id: String,
79 step_index: usize,
80 detail_level: DetailLevel,
81 metrics: Option<Arc<dyn MetricsCollector>>,
82 label: Option<Arc<str>>,
83 to_uri: Option<Arc<str>>,
84 kind_hint: SpanKindHint,
85 ) -> Self {
86 let step_id = step_id_for(step_index);
87 let span_name = format!("{route_id}:{}", label.as_deref().unwrap_or(&step_id));
88 let span_kind = match kind_hint {
89 SpanKindHint::Internal => SpanKind::Internal,
90 SpanKindHint::Producer => SpanKind::Producer,
91 SpanKindHint::Consumer => SpanKind::Consumer,
92 SpanKindHint::Client => SpanKind::Client,
93 SpanKindHint::Server => SpanKind::Server,
94 // `SpanKindHint` is `#[non_exhaustive]`: unknown future variants
95 // degrade to `Internal` (the promised forward-compat behavior).
96 _ => SpanKind::Internal,
97 };
98 Self {
99 inner,
100 route_id,
101 step_id,
102 span_name,
103 step_index,
104 detail_level,
105 metrics,
106 to_uri,
107 span_kind,
108 // Defaults preserve the fully-traced behavior for direct
109 // constructors; the pipeline composer overrides per the
110 // effective tracer config.
111 spans_enabled: true,
112 metric_levers: MetricsLeversConfig::default(),
113 }
114 }
115
116 /// Sets whether step spans are created (metrics still flow when off).
117 pub fn with_spans_enabled(mut self, enabled: bool) -> Self {
118 self.spans_enabled = enabled;
119 self
120 }
121
122 /// Sets the per-family metric levers. The error family ignores them.
123 pub fn with_metric_levers(mut self, levers: MetricsLeversConfig) -> Self {
124 self.metric_levers = levers;
125 self
126 }
127
128 /// Metrics-only fast path (`spans_enabled = false`): no OTel span, no
129 /// local tracing span, context passes through untouched; metric
130 /// families are recorded per the levers.
131 fn call_metrics_only(
132 &mut self,
133 exchange: Exchange,
134 start: Instant,
135 ) -> Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>> {
136 let fresh = self.inner.clone();
137 let mut inner = std::mem::replace(&mut self.inner, fresh);
138 let metrics = self.metrics.clone();
139 let route_id = self.route_id.clone();
140 let to_uri = self.to_uri.clone();
141 let levers = self.metric_levers.clone();
142 Box::pin(async move {
143 let result = inner.call(exchange).await;
144 record_step_metrics(
145 metrics.as_ref(),
146 &route_id,
147 to_uri.as_deref(),
148 &levers,
149 start.elapsed(),
150 &result,
151 true,
152 );
153 result
154 })
155 }
156}
157
158/// Emits the step metric families per the levers: `record_exchange_duration`
159/// and the per-To `step_duration_secs` histogram only when the duration
160/// family is enabled AND the attempt is a call-time attempt
161/// (`include_duration`), `increment_exchanges` only when the exchange
162/// family is enabled, and `increment_errors` NEVER gated
163/// (metrics-configuration Req 2). Circuit-open rejections are excluded here
164/// as well (dashboard-observability D2): the breaker counts them.
165///
166/// The `step_duration_secs` histogram is emitted only for `To` steps
167/// (`to_uri` is `Some`), labeled with the route id and the DECLARED
168/// (operator-authored) endpoint URI — never a resolved or
169/// exchange-derived value (steplatency 2.1, ADR-0074).
170///
171/// Readiness-phase attempts pass `include_duration = false`: the duration
172/// histogram population is call-time only (ADR-0066 population contracts),
173/// while the exchange count and error increment are required on the
174/// readiness path too (rc-mn8n).
175fn record_step_metrics(
176 metrics: Option<&Arc<dyn MetricsCollector>>,
177 route_id: &str,
178 to_uri: Option<&str>,
179 levers: &MetricsLeversConfig,
180 duration: std::time::Duration,
181 result: &Result<Exchange, CamelError>,
182 include_duration: bool,
183) {
184 let Some(metrics) = metrics else { return };
185 if include_duration && levers.durations_enabled() {
186 metrics.record_exchange_duration(route_id, duration);
187 if let Some(uri) = to_uri {
188 // allow-open-label rc-cd7o (declared To URI: operator-authored route config, bounded by route steps)
189 metrics.record_histogram(
190 "step_duration_secs",
191 duration.as_secs_f64(),
192 &[("route", route_id), ("to_uri", uri)],
193 );
194 }
195 }
196 if levers.exchanges_enabled() {
197 metrics.increment_exchanges(route_id);
198 }
199 if let Err(e) = result {
200 let error_class = e.classify();
201 if error_class != CIRCUIT_OPEN {
202 // allow-open-label rc-otxh (classify() returns a closed &'static str set: exhaustive match in CamelError::classify)
203 metrics.increment_errors(route_id, error_class);
204 }
205 }
206}
207
208/// Emit the `language_eval_failures_total` counter for a top-level
209/// [`CamelError::ExpressionFailed`] owned by `current_route_id`.
210///
211/// Counting contract (language-value-boundary spec, "Evaluation failure
212/// metrics"):
213/// - A failure that a route error handler recovers after the step failed
214/// still counts — the evaluation failed.
215/// - Handler retries do not re-enter `run_steps`'s `Failed` arm, so one
216/// exhausted retry sequence counts once.
217/// - Failures raised by the handler itself (catch/onWhen predicate) and
218/// `ExpressionFailed` values wrapped inside another error's cause chain
219/// are out of scope: they never reach this helper.
220///
221/// All label values are config-derived: the language name, the route id, the
222/// DSL verb and the closed `ExpressionErrorClass` name. Exchange data, cause
223/// text, conversion detail and position are never labels.
224pub(crate) fn record_language_eval_failure(
225 metrics: &dyn MetricsCollector,
226 current_route_id: &str,
227 error: &CamelError,
228) {
229 let CamelError::ExpressionFailed {
230 language,
231 route_id,
232 verb,
233 class,
234 ..
235 } = error
236 else {
237 return;
238 };
239 if route_id != current_route_id {
240 return;
241 }
242 // allow-open-label rc-5r117 (language/route/verb: operator-authored route config, bounded by route definitions; class: closed ExpressionErrorClass set)
243 metrics.record_counter(
244 "language_eval_failures_total",
245 1.0,
246 &[
247 ("language", language.as_str()),
248 ("route", route_id.as_str()),
249 ("verb", verb.as_str()),
250 ("class", class.as_str()),
251 ],
252 );
253}
254
255impl Service<Exchange> for TracingProcessor {
256 type Response = Exchange;
257 type Error = CamelError;
258 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
259
260 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
261 let start = Instant::now();
262 match self.inner.poll_ready(cx) {
263 Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
264 Poll::Pending => Poll::Pending,
265 Poll::Ready(Err(e)) => {
266 // rc-mn8n: readiness-phase producer failures (e.g.
267 // DirectProducer with the default failIfNoConsumers=true)
268 // surface here, BEFORE the traced call — so the call-time
269 // Err arm never runs for them. Record the exchange count
270 // and the error class with the same labels (CIRCUIT_OPEN
271 // still excluded — the breaker counts its own rejections).
272 // Duration is NOT recorded here: the
273 // camel_exchange_duration_seconds population stays
274 // call-time only (ADR-0066 population contracts).
275 record_step_metrics(
276 self.metrics.as_ref(),
277 &self.route_id,
278 self.to_uri.as_deref(),
279 &self.metric_levers,
280 start.elapsed(),
281 &Err(e.clone()),
282 false,
283 );
284 Poll::Ready(Err(e))
285 }
286 }
287 }
288
289 fn call(&mut self, mut exchange: Exchange) -> Self::Future {
290 let start = Instant::now();
291
292 // Metrics-only mode (dashboard-observability D3): spans are gated by
293 // `tracer.enabled`, but the pipeline adapter still runs so metric
294 // families — errors unconditionally — keep flowing.
295 if !self.spans_enabled {
296 return self.call_metrics_only(exchange, start);
297 }
298
299 let span_name = self.span_name.clone();
300 let span_kind = self.span_kind.clone();
301
302 // Get the global tracer (noop if no provider is configured)
303 let tracer = global::tracer_with_scope(
304 InstrumentationScope::builder("camel-core")
305 .with_version(env!("CARGO_PKG_VERSION"))
306 .build(),
307 );
308
309 // Extract parent context from exchange.otel_context
310 let parent_cx = exchange.otel_context.clone();
311
312 // Build span attributes (Minimal set; Medium/Full extras appended below)
313 let mut attributes =
314 step_span_attributes(&self.route_id, self.step_index, exchange.correlation_id());
315
316 if self.detail_level >= DetailLevel::Medium {
317 attributes.push(KeyValue::new(
318 "headers_count",
319 exchange.input.headers.len() as i64,
320 ));
321 attributes.push(KeyValue::new(
322 "body_type",
323 body_type_name(&exchange.input.body),
324 ));
325 attributes.push(KeyValue::new("has_error", exchange.has_error()));
326 }
327
328 // Start a new span as a child of the parent context
329 let span = tracer
330 .span_builder(span_name)
331 .with_kind(span_kind)
332 .with_attributes(attributes.iter().cloned())
333 .start_with_context(&tracer, &parent_cx);
334
335 // Derive the step context from the parent (not from the ambient
336 // current context): parent entries such as baggage stay attached, and
337 // the parent context is restored on the result exchange after the step.
338 let cx = parent_cx.with_span(span);
339
340 // Store back into exchange so downstream processors inherit this context
341 exchange.otel_context = cx.clone();
342
343 // Also create a tracing span for local dev logging
344 let tracing_span = tracing::info_span!(
345 target: "camel_tracer",
346 "step",
347 correlation_id = %exchange.correlation_id(),
348 route_id = %self.route_id,
349 step_id = %self.step_id,
350 step_index = self.step_index,
351 duration_ms = tracing::field::Empty,
352 status = tracing::field::Empty,
353 headers_count = tracing::field::Empty,
354 body_type = tracing::field::Empty,
355 has_error = tracing::field::Empty,
356 output_body_type = tracing::field::Empty,
357 header_0 = tracing::field::Empty,
358 header_1 = tracing::field::Empty,
359 header_2 = tracing::field::Empty,
360 error = tracing::field::Empty,
361 error_type = tracing::field::Empty,
362 expression_class = tracing::field::Empty,
363 expression_position = tracing::field::Empty,
364 );
365
366 if self.detail_level >= DetailLevel::Medium {
367 tracing_span.record("headers_count", exchange.input.headers.len() as u64);
368 tracing_span.record("body_type", body_type_name(&exchange.input.body));
369 tracing_span.record("has_error", exchange.has_error());
370 }
371
372 if self.detail_level >= DetailLevel::Full {
373 let headers: Vec<_> = exchange.input.headers.iter().take(3).collect();
374 if let Some((k, v)) = headers.first() {
375 tracing_span.record("header_0", format!("{k}={v:?}"));
376 }
377 if let Some((k, v)) = headers.get(1) {
378 tracing_span.record("header_1", format!("{k}={v:?}"));
379 }
380 if let Some((k, v)) = headers.get(2) {
381 tracing_span.record("header_2", format!("{k}={v:?}"));
382 }
383 }
384
385 // Consume the ORIGINAL inner that `poll_ready` readied: its
386 // reservations (e.g. DirectProducer's pending semaphore permit)
387 // belong to that instance, so re-readying a clone would drop them.
388 // The fresh clone stays in `self.inner` as the unreadied placeholder
389 // for the next ready/call cycle.
390 let fresh = self.inner.clone();
391 let mut inner = std::mem::replace(&mut self.inner, fresh);
392 let detail_level = self.detail_level.clone();
393 let metrics = self.metrics.clone();
394 let route_id = self.route_id.clone();
395 let to_uri = self.to_uri.clone();
396 let levers = self.metric_levers.clone();
397
398 Box::pin(
399 async move {
400 // Note: ContextGuard is not Send (it uses thread-local storage), so we cannot
401 // hold it across await points in an async fn. Instead, we propagate the OTel
402 // context through exchange.otel_context, which is Send + Sync.
403
404 // Create guard to ensure span is ended even on panic
405 let _guard = SpanEndGuard(cx.clone());
406
407 let result = inner.call(exchange).await;
408
409 let duration = start.elapsed();
410 let duration_ms = duration.as_millis() as u64;
411 tracing::Span::current().record("duration_ms", duration_ms);
412
413 // Record metric families per the levers (errors never gated).
414 record_step_metrics(
415 metrics.as_ref(),
416 &route_id,
417 to_uri.as_deref(),
418 &levers,
419 duration,
420 &result,
421 true,
422 );
423
424 match result {
425 Ok(mut ex) => {
426 tracing::Span::current().record("status", "success");
427 cx.span().set_status(Status::Ok);
428
429 if detail_level >= DetailLevel::Medium {
430 tracing::Span::current()
431 .record("output_body_type", body_type_name(&ex.input.body));
432 cx.span().set_attribute(KeyValue::new(
433 "output_body_type",
434 body_type_name(&ex.input.body),
435 ));
436 }
437
438 // Restore the caller's context: the step span ends with
439 // this future, so downstream steps must not chain onto it.
440 ex.otel_context = parent_cx.clone();
441 Ok(ex)
442 }
443 Err(e) => {
444 record_exception(&cx.span(), &e);
445 let error_class = e.classify();
446 tracing::Span::current().record("status", "error");
447 tracing::Span::current().record("error", e.to_string());
448 tracing::Span::current().record("error_type", error_class);
449 if let CamelError::ExpressionFailed {
450 class, position, ..
451 } = &e
452 {
453 tracing::Span::current().record("expression_class", class.as_str());
454 if let Some(position) = position {
455 tracing::Span::current().record(
456 "expression_position",
457 format!("{}:{}", position.line, position.column),
458 );
459 }
460 }
461 Err(e)
462 }
463 }
464 }
465 .instrument(tracing_span),
466 )
467 }
468}
469
470impl Clone for TracingProcessor {
471 fn clone(&self) -> Self {
472 Self {
473 inner: self.inner.clone(),
474 route_id: self.route_id.clone(),
475 step_id: self.step_id.clone(),
476 span_name: self.span_name.clone(),
477 step_index: self.step_index,
478 detail_level: self.detail_level.clone(),
479 metrics: self.metrics.clone(),
480 to_uri: self.to_uri.clone(),
481 span_kind: self.span_kind.clone(),
482 spans_enabled: self.spans_enabled,
483 metric_levers: self.metric_levers.clone(),
484 }
485 }
486}
487
488/// R4-L8: cap only the span-attr representation. Exchange.correlation_id is untouched.
489pub(crate) fn capped_correlation_id(id: &str) -> &str {
490 const CAP: usize = 128;
491 if id.len() > CAP {
492 "<oversized:correlation_id>"
493 } else {
494 id
495 }
496}
497
498/// Minimal-level span attributes for a pipeline step span.
499///
500/// `correlation_id` is the raw exchange correlation id; this is the single
501/// capping site for its span-attribute representation (R4-L8). Medium/Full
502/// extras (`headers_count`, `body_type`, `has_error`) are appended by the
503/// caller, not here.
504pub(crate) fn step_span_attributes(
505 route_id: &str,
506 step_index: usize,
507 correlation_id: &str,
508) -> Vec<KeyValue> {
509 vec![
510 KeyValue::new("messaging.system", "camel"),
511 KeyValue::new(
512 "correlation_id",
513 capped_correlation_id(correlation_id).to_string(),
514 ),
515 KeyValue::new("route_id", route_id.to_string()),
516 KeyValue::new("step_index", step_index as i64),
517 ]
518}
519
520/// Record an error on an OTel span: status, `exception` event, and — for
521/// [`CamelError::ExpressionFailed`] — the typed `camel.expression.class`
522/// and, when the language reports one, `camel.expression.position`
523/// (`line:column`, 1-based) attributes.
524///
525/// This helper is shared by process step spans, segment step spans,
526/// `finish_span_outcome`'s route root span and `trace_restart` split-item
527/// spans. The two expression attributes are accepted on all of them on
528/// purpose: they describe the failure carried by that span, and the spec
529/// does not restrict them to step spans.
530pub(crate) fn record_exception(span: &SpanRef<'_>, e: &CamelError) {
531 let error_class = e.classify();
532 span.set_status(Status::error(e.to_string()));
533 span.add_event(
534 "exception",
535 vec![
536 KeyValue::new("exception.type", error_class.to_string()),
537 KeyValue::new("exception.message", e.to_string()),
538 ],
539 );
540 if let CamelError::ExpressionFailed {
541 class, position, ..
542 } = e
543 {
544 span.set_attribute(KeyValue::new("camel.expression.class", class.as_str()));
545 if let Some(position) = position {
546 span.set_attribute(KeyValue::new(
547 "camel.expression.position",
548 format!("{}:{}", position.line, position.column),
549 ));
550 }
551 }
552}
553
554#[cfg(test)]
555#[path = "tracer_tests.rs"]
556mod tests;