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 // Business failures are breaker-neutral (they count as a success) and
202 // skip the error family exactly like `CircuitOpen`; the exchange and
203 // duration families still count.
204 if error_class != CIRCUIT_OPEN && !matches!(e, CamelError::Business { .. }) {
205 // allow-open-label rc-otxh (classify() returns a closed &'static str set: exhaustive match in CamelError::classify)
206 metrics.increment_errors(route_id, error_class);
207 }
208 }
209}
210
211/// Emit the `language_eval_failures_total` counter for a top-level
212/// [`CamelError::ExpressionFailed`] owned by `current_route_id`.
213///
214/// Counting contract (language-value-boundary spec, "Evaluation failure
215/// metrics"):
216/// - A failure that a route error handler recovers after the step failed
217/// still counts — the evaluation failed.
218/// - Handler retries do not re-enter `run_steps`'s `Failed` arm, so one
219/// exhausted retry sequence counts once.
220/// - Failures raised by the handler itself (catch/onWhen predicate) and
221/// `ExpressionFailed` values wrapped inside another error's cause chain
222/// are out of scope: they never reach this helper.
223///
224/// All label values are config-derived: the language name, the route id, the
225/// DSL verb and the closed `ExpressionErrorClass` name. Exchange data, cause
226/// text, conversion detail and position are never labels.
227pub(crate) fn record_language_eval_failure(
228 metrics: &dyn MetricsCollector,
229 current_route_id: &str,
230 error: &CamelError,
231) {
232 let CamelError::ExpressionFailed {
233 language,
234 route_id,
235 verb,
236 class,
237 ..
238 } = error
239 else {
240 return;
241 };
242 if route_id != current_route_id {
243 return;
244 }
245 // allow-open-label rc-5r117 (language/route/verb: operator-authored route config, bounded by route definitions; class: closed ExpressionErrorClass set)
246 metrics.record_counter(
247 "language_eval_failures_total",
248 1.0,
249 &[
250 ("language", language.as_str()),
251 ("route", route_id.as_str()),
252 ("verb", verb.as_str()),
253 ("class", class.as_str()),
254 ],
255 );
256}
257
258impl Service<Exchange> for TracingProcessor {
259 type Response = Exchange;
260 type Error = CamelError;
261 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
262
263 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
264 let start = Instant::now();
265 match self.inner.poll_ready(cx) {
266 Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
267 Poll::Pending => Poll::Pending,
268 Poll::Ready(Err(e)) => {
269 // rc-mn8n: readiness-phase producer failures (e.g.
270 // DirectProducer with the default failIfNoConsumers=true)
271 // surface here, BEFORE the traced call — so the call-time
272 // Err arm never runs for them. Record the exchange count
273 // and the error class with the same labels (CIRCUIT_OPEN
274 // still excluded — the breaker counts its own rejections).
275 // Duration is NOT recorded here: the
276 // camel_exchange_duration_seconds population stays
277 // call-time only (ADR-0066 population contracts).
278 record_step_metrics(
279 self.metrics.as_ref(),
280 &self.route_id,
281 self.to_uri.as_deref(),
282 &self.metric_levers,
283 start.elapsed(),
284 &Err(e.clone()),
285 false,
286 );
287 Poll::Ready(Err(e))
288 }
289 }
290 }
291
292 fn call(&mut self, mut exchange: Exchange) -> Self::Future {
293 let start = Instant::now();
294
295 // Metrics-only mode (dashboard-observability D3): spans are gated by
296 // `tracer.enabled`, but the pipeline adapter still runs so metric
297 // families — errors unconditionally — keep flowing.
298 if !self.spans_enabled {
299 return self.call_metrics_only(exchange, start);
300 }
301
302 let span_name = self.span_name.clone();
303 let span_kind = self.span_kind.clone();
304
305 // Get the global tracer (noop if no provider is configured)
306 let tracer = global::tracer_with_scope(
307 InstrumentationScope::builder("camel-core")
308 .with_version(env!("CARGO_PKG_VERSION"))
309 .build(),
310 );
311
312 // Extract parent context from exchange.otel_context
313 let parent_cx = exchange.otel_context.clone();
314
315 // Build span attributes (Minimal set; Medium/Full extras appended below)
316 let mut attributes =
317 step_span_attributes(&self.route_id, self.step_index, exchange.correlation_id());
318
319 if self.detail_level >= DetailLevel::Medium {
320 attributes.push(KeyValue::new(
321 "headers_count",
322 exchange.input.headers.len() as i64,
323 ));
324 attributes.push(KeyValue::new(
325 "body_type",
326 body_type_name(&exchange.input.body),
327 ));
328 attributes.push(KeyValue::new("has_error", exchange.has_error()));
329 }
330
331 // Start a new span as a child of the parent context
332 let span = tracer
333 .span_builder(span_name)
334 .with_kind(span_kind)
335 .with_attributes(attributes.iter().cloned())
336 .start_with_context(&tracer, &parent_cx);
337
338 // Derive the step context from the parent (not from the ambient
339 // current context): parent entries such as baggage stay attached, and
340 // the parent context is restored on the result exchange after the step.
341 let cx = parent_cx.with_span(span);
342
343 // Store back into exchange so downstream processors inherit this context
344 exchange.otel_context = cx.clone();
345
346 // Also create a tracing span for local dev logging
347 let tracing_span = tracing::info_span!(
348 target: "camel_tracer",
349 "step",
350 correlation_id = %exchange.correlation_id(),
351 route_id = %self.route_id,
352 step_id = %self.step_id,
353 step_index = self.step_index,
354 duration_ms = tracing::field::Empty,
355 status = tracing::field::Empty,
356 headers_count = tracing::field::Empty,
357 body_type = tracing::field::Empty,
358 has_error = tracing::field::Empty,
359 output_body_type = tracing::field::Empty,
360 header_0 = tracing::field::Empty,
361 header_1 = tracing::field::Empty,
362 header_2 = tracing::field::Empty,
363 error = tracing::field::Empty,
364 error_type = tracing::field::Empty,
365 expression_class = tracing::field::Empty,
366 expression_position = tracing::field::Empty,
367 );
368
369 if self.detail_level >= DetailLevel::Medium {
370 tracing_span.record("headers_count", exchange.input.headers.len() as u64);
371 tracing_span.record("body_type", body_type_name(&exchange.input.body));
372 tracing_span.record("has_error", exchange.has_error());
373 }
374
375 if self.detail_level >= DetailLevel::Full {
376 let headers: Vec<_> = exchange.input.headers.iter().take(3).collect();
377 if let Some((k, v)) = headers.first() {
378 tracing_span.record("header_0", format!("{k}={v:?}"));
379 }
380 if let Some((k, v)) = headers.get(1) {
381 tracing_span.record("header_1", format!("{k}={v:?}"));
382 }
383 if let Some((k, v)) = headers.get(2) {
384 tracing_span.record("header_2", format!("{k}={v:?}"));
385 }
386 }
387
388 // Consume the ORIGINAL inner that `poll_ready` readied: its
389 // reservations (e.g. DirectProducer's pending semaphore permit)
390 // belong to that instance, so re-readying a clone would drop them.
391 // The fresh clone stays in `self.inner` as the unreadied placeholder
392 // for the next ready/call cycle.
393 let fresh = self.inner.clone();
394 let mut inner = std::mem::replace(&mut self.inner, fresh);
395 let detail_level = self.detail_level.clone();
396 let metrics = self.metrics.clone();
397 let route_id = self.route_id.clone();
398 let to_uri = self.to_uri.clone();
399 let levers = self.metric_levers.clone();
400
401 Box::pin(
402 async move {
403 // Note: ContextGuard is not Send (it uses thread-local storage), so we cannot
404 // hold it across await points in an async fn. Instead, we propagate the OTel
405 // context through exchange.otel_context, which is Send + Sync.
406
407 // Create guard to ensure span is ended even on panic
408 let _guard = SpanEndGuard(cx.clone());
409
410 let result = inner.call(exchange).await;
411
412 let duration = start.elapsed();
413 let duration_ms = duration.as_millis() as u64;
414 tracing::Span::current().record("duration_ms", duration_ms);
415
416 // Record metric families per the levers (errors never gated).
417 record_step_metrics(
418 metrics.as_ref(),
419 &route_id,
420 to_uri.as_deref(),
421 &levers,
422 duration,
423 &result,
424 true,
425 );
426
427 match result {
428 Ok(mut ex) => {
429 tracing::Span::current().record("status", "success");
430 cx.span().set_status(Status::Ok);
431
432 if detail_level >= DetailLevel::Medium {
433 tracing::Span::current()
434 .record("output_body_type", body_type_name(&ex.input.body));
435 cx.span().set_attribute(KeyValue::new(
436 "output_body_type",
437 body_type_name(&ex.input.body),
438 ));
439 }
440
441 // Restore the caller's context: the step span ends with
442 // this future, so downstream steps must not chain onto it.
443 ex.otel_context = parent_cx.clone();
444 Ok(ex)
445 }
446 Err(e) => {
447 record_exception(&cx.span(), &e);
448 let error_class = e.classify();
449 tracing::Span::current().record("status", "error");
450 tracing::Span::current().record("error", e.to_string());
451 tracing::Span::current().record("error_type", error_class);
452 if let CamelError::ExpressionFailed {
453 class, position, ..
454 } = &e
455 {
456 tracing::Span::current().record("expression_class", class.as_str());
457 if let Some(position) = position {
458 tracing::Span::current().record(
459 "expression_position",
460 format!("{}:{}", position.line, position.column),
461 );
462 }
463 }
464 Err(e)
465 }
466 }
467 }
468 .instrument(tracing_span),
469 )
470 }
471}
472
473impl Clone for TracingProcessor {
474 fn clone(&self) -> Self {
475 Self {
476 inner: self.inner.clone(),
477 route_id: self.route_id.clone(),
478 step_id: self.step_id.clone(),
479 span_name: self.span_name.clone(),
480 step_index: self.step_index,
481 detail_level: self.detail_level.clone(),
482 metrics: self.metrics.clone(),
483 to_uri: self.to_uri.clone(),
484 span_kind: self.span_kind.clone(),
485 spans_enabled: self.spans_enabled,
486 metric_levers: self.metric_levers.clone(),
487 }
488 }
489}
490
491/// R4-L8: cap only the span-attr representation. Exchange.correlation_id is untouched.
492pub(crate) fn capped_correlation_id(id: &str) -> &str {
493 const CAP: usize = 128;
494 if id.len() > CAP {
495 "<oversized:correlation_id>"
496 } else {
497 id
498 }
499}
500
501/// Minimal-level span attributes for a pipeline step span.
502///
503/// `correlation_id` is the raw exchange correlation id; this is the single
504/// capping site for its span-attribute representation (R4-L8). Medium/Full
505/// extras (`headers_count`, `body_type`, `has_error`) are appended by the
506/// caller, not here.
507pub(crate) fn step_span_attributes(
508 route_id: &str,
509 step_index: usize,
510 correlation_id: &str,
511) -> Vec<KeyValue> {
512 vec![
513 KeyValue::new("messaging.system", "camel"),
514 KeyValue::new(
515 "correlation_id",
516 capped_correlation_id(correlation_id).to_string(),
517 ),
518 KeyValue::new("route_id", route_id.to_string()),
519 KeyValue::new("step_index", step_index as i64),
520 ]
521}
522
523/// Record an error on an OTel span: status, `exception` event, and — for
524/// [`CamelError::ExpressionFailed`] — the typed `camel.expression.class`
525/// and, when the language reports one, `camel.expression.position`
526/// (`line:column`, 1-based) attributes.
527///
528/// This helper is shared by process step spans, segment step spans,
529/// `finish_span_outcome`'s route root span and `trace_restart` split-item
530/// spans. The two expression attributes are accepted on all of them on
531/// purpose: they describe the failure carried by that span, and the spec
532/// does not restrict them to step spans.
533pub(crate) fn record_exception(span: &SpanRef<'_>, e: &CamelError) {
534 let error_class = e.classify();
535 span.set_status(Status::error(e.to_string()));
536 span.add_event(
537 "exception",
538 vec![
539 KeyValue::new("exception.type", error_class.to_string()),
540 KeyValue::new("exception.message", e.to_string()),
541 ],
542 );
543 if let CamelError::ExpressionFailed {
544 class, position, ..
545 } = e
546 {
547 span.set_attribute(KeyValue::new("camel.expression.class", class.as_str()));
548 if let Some(position) = position {
549 span.set_attribute(KeyValue::new(
550 "camel.expression.position",
551 format!("{}:{}", position.line, position.column),
552 ));
553 }
554 }
555}
556
557#[cfg(test)]
558#[path = "tracer_tests.rs"]
559mod tests;