Skip to main content

camel_core/lifecycle/adapters/
route_compiler.rs

1// adapters/route_compiler.rs
2// Pipeline compilation functions: compose BuilderSteps into a Tower BoxProcessor.
3// Tower types live here as this is the adapter layer responsible for
4// translating declarative route definitions into executable pipelines.
5
6use std::future::Future;
7use std::pin::Pin;
8use std::sync::Arc;
9use std::task::{Context, Poll};
10
11use tokio_util::sync::CancellationToken;
12use tower::Service;
13
14use camel_api::metrics::MetricsCollector;
15use camel_api::{
16    BoxProcessor, CamelError, Exchange, IdentityProcessor, Message, NoOpMetrics,
17    ORIGINAL_MESSAGE_EXTENSION, PipelineOutcome,
18};
19
20use camel_api::error_handler::{BoundaryKind, RetryOutcome, StepDisposition};
21use camel_processor::{
22    CircuitBreakerDecision, CircuitBreakerGate, RouteErrorHandler, invoke_processor,
23};
24use opentelemetry::trace::{SpanKind, Status, TraceContextExt, Tracer};
25use opentelemetry::{Context as OtelContext, InstrumentationScope, KeyValue, global};
26use tracing::Instrument;
27
28use crate::lifecycle::adapters::body_coercing::wrap_if_needed;
29use crate::lifecycle::adapters::step_compilers::CompiledStep;
30use crate::shared::observability::adapters::TracingProcessor;
31use crate::shared::observability::adapters::tracer::{
32    SpanEndGuard, capped_correlation_id, record_exception, step_id_for, step_span_attributes,
33};
34use crate::shared::observability::domain::{DetailLevel, MetricsLeversConfig};
35
36// Re-export outcome composition types so existing step_compiler import paths
37// (`route_compiler::BoxProcessorSegment`, etc.) continue to work.
38pub(crate) use super::outcome_composition::{
39    BodyCoercingSegment, BoxProcessorSegment, StopSegment, compose_outcome_segment,
40};
41
42// Task-local cancel token — set by the pipeline task per-start, checked by
43// `run_steps` between steps. Absent in direct tests (skip check).
44//
45// Design: per-start task-local, NOT compiled into the pipeline struct, to
46// avoid the lifecycle bug where a compiled-in child token stays cancelled
47// after stop→restart (the new start would inherit the cancelled state).
48// ADR-0043.
49tokio::task_local! {
50    pub(crate) static CANCEL_TOKEN: CancellationToken;
51}
52
53/// Runtime context for metrics + route_id (B3). Cancel is via task-local (B1).
54#[derive(Clone)]
55pub struct PipelineRuntimeCtx {
56    pub metrics: Arc<dyn MetricsCollector>,
57    pub route_id: Arc<str>,
58}
59
60impl PipelineRuntimeCtx {
61    /// Constructor for compile-time contexts where no MetricsCollector is available.
62    /// The resulting pipeline will emit disposition counters to NoOpMetrics (no-op).
63    /// Prefer constructing PipelineRuntimeCtx with real metrics at route startup.
64    pub fn compile_time() -> Self {
65        Self {
66            metrics: Arc::new(NoOpMetrics),
67            route_id: Arc::from(""),
68        }
69    }
70}
71
72/// Newtype around `Arc<[CompiledStep]>`.
73///
74/// `CompiledStep` contains `BoxProcessor` (`tower::util::BoxCloneSyncService`),
75/// whose erased inner trait object is bounded `Send + Sync`. `CompiledStep` is
76/// therefore `Send + Sync` by construction, and `SharedSnapshot` derives both
77/// auto traits from `Arc<[CompiledStep]>` — the snapshot is shareable across
78/// threads with auto-derived traits alone.
79#[derive(Clone)]
80struct SharedSnapshot(Arc<[CompiledStep]>);
81
82// Compile-time guard: CompiledStep must remain Send + Sync so the snapshot
83// stays shareable via auto-derivation. `Send` keeps the future returned by
84// `run_steps` Send; `Sync` covers concurrent `&self` reads on
85// `SequentialPipeline`/`TracedPipeline` clones (e.g. `poll_ready` on one
86// thread, `call` on another).
87#[allow(dead_code)]
88const _: () = {
89    fn assert_send<T: Send>() {}
90    fn assert_sync<T: Sync>() {}
91    fn _check() {
92        assert_send::<CompiledStep>();
93        assert_sync::<CompiledStep>();
94    }
95};
96
97/// Compose a list of CompiledSteps into a sub-pipeline (EIP internal).
98///
99/// Uses `into_tower_result()` so `PipelineOutcome::Stopped` maps to `Ok(ex)`.
100/// Use [`compose_pipeline_with_handler`] for the top-level consumer-facing pipeline.
101pub fn compose_pipeline(processors: Vec<CompiledStep>, ctx: PipelineRuntimeCtx) -> BoxProcessor {
102    if processors.is_empty() {
103        return BoxProcessor::new(IdentityProcessor);
104    }
105    BoxProcessor::new(SequentialPipeline {
106        steps: SharedSnapshot(processors.into()),
107        handler: None,
108        ctx,
109    })
110}
111
112/// Compose a list of CompiledSteps with an optional route error handler.
113///
114/// When a handler is present, step readiness errors are swallowed (poll_ready
115/// returns Ready) and the handler's retry/recovery logic is invoked on step
116/// failures. Otherwise, step readiness errors propagate immediately.
117pub fn compose_pipeline_with_handler(
118    processors: Vec<CompiledStep>,
119    handler: Option<Arc<dyn RouteErrorHandler>>,
120    ctx: PipelineRuntimeCtx,
121) -> BoxProcessor {
122    if processors.is_empty() {
123        return BoxProcessor::new(IdentityProcessor);
124    }
125    BoxProcessor::new(SequentialPipeline {
126        steps: SharedSnapshot(processors.into()),
127        handler,
128        ctx,
129    })
130}
131
132/// Effective span/metric gating for the traced pipeline, derived once from
133/// the effective tracer config (dashboard-observability D3).
134///
135/// `pipeline_enabled` decides whether routes are wrapped with the
136/// observability adapters at all; `spans_enabled` gates SPAN creation only
137/// (explicit `tracer.enabled = false` with an exporter on yields
138/// `pipeline_enabled && !spans_enabled`, so metric families — errors
139/// unconditionally — keep flowing); `levers` gate individual non-error
140/// families.
141#[derive(Clone, Debug)]
142pub struct TracerPipelineGating {
143    pub pipeline_enabled: bool,
144    pub spans_enabled: bool,
145    pub levers: MetricsLeversConfig,
146}
147
148impl TracerPipelineGating {
149    /// Fully traced pipeline with default levers (legacy `trace_enabled = true`).
150    pub fn traced() -> Self {
151        Self {
152            pipeline_enabled: true,
153            spans_enabled: true,
154            levers: MetricsLeversConfig::default(),
155        }
156    }
157
158    /// No observability wrapping (legacy `trace_enabled = false`).
159    pub fn off() -> Self {
160        Self {
161            pipeline_enabled: false,
162            spans_enabled: false,
163            levers: MetricsLeversConfig::default(),
164        }
165    }
166}
167
168/// Legacy bool call sites keep their meaning: `true` = fully traced,
169/// `false` = no wrapping.
170impl From<bool> for TracerPipelineGating {
171    fn from(trace_enabled: bool) -> Self {
172        if trace_enabled {
173            Self::traced()
174        } else {
175            Self::off()
176        }
177    }
178}
179
180/// Compose a list of CompiledSteps into a traced pipeline with Stop→Ok translation.
181///
182/// Each processor is wrapped with TracingProcessor to emit spans for observability,
183/// and the pipeline opens one Internal route root span per invocation (named after
184/// `route_id`) that parents every step span. Step spans are named
185/// `{route_id}:{label}` when the compiled step carries a DSL label (e.g.
186/// `to:direct`, `split`); unlabeled steps fall back to the positional
187/// `{route_id}:step-{index}` name. Empty traced routes still return a
188/// `TracedPipeline` so the root span records the route invocation with zero steps.
189/// When the pipeline is disabled, falls back to [`compose_pipeline_with_handler`]
190/// with zero overhead; when only spans are disabled, steps are still wrapped for
191/// metric families but no route root span is opened.
192pub fn compose_traced_pipeline(
193    processors: Vec<CompiledStep>,
194    route_id: &str,
195    gating: impl Into<TracerPipelineGating>,
196    detail_level: DetailLevel,
197    metrics: Option<Arc<dyn MetricsCollector>>,
198    handler: Option<Arc<dyn RouteErrorHandler>>,
199    ctx: PipelineRuntimeCtx,
200) -> BoxProcessor {
201    let gating = gating.into();
202    if !gating.pipeline_enabled {
203        return compose_pipeline_with_handler(processors, handler, ctx);
204    }
205
206    let wrapped: Vec<CompiledStep> = processors
207        .into_iter()
208        .enumerate()
209        .map(|(idx, step)| {
210            let (p, c, lc, lbl, kh) = match step {
211                CompiledStep::Process {
212                    processor,
213                    body_contract,
214                    lifecycle,
215                    label,
216                    kind_hint,
217                } => (processor, body_contract, lifecycle, label, kind_hint),
218                CompiledStep::Stop => return CompiledStep::Stop,
219                CompiledStep::Segment { .. } => return step,
220            };
221            let traced = BoxProcessor::new(
222                TracingProcessor::new(
223                    p,
224                    route_id.to_string(),
225                    idx,
226                    detail_level.clone(),
227                    metrics.clone(),
228                    lbl.clone(),
229                    // Thread the registry-stamped kind hint (span-kind-hint
230                    // 1.3) so `to:http` steps export Client spans and broker
231                    // sends export Producer spans; unlabeled/non-To steps keep
232                    // the Internal default.
233                    kh,
234                )
235                .with_spans_enabled(gating.spans_enabled)
236                .with_metric_levers(gating.levers.clone()),
237            );
238            CompiledStep::Process {
239                processor: traced,
240                body_contract: c,
241                lifecycle: lc,
242                label: lbl,
243                kind_hint: kh,
244            }
245        })
246        .collect();
247
248    // Spans off: no route root span — a plain sequential pipeline over the
249    // metrics-emitting step wrappers.
250    if !gating.spans_enabled {
251        return BoxProcessor::new(SequentialPipeline {
252            steps: SharedSnapshot(wrapped.into()),
253            handler,
254            ctx,
255        });
256    }
257
258    BoxProcessor::new(TracedPipeline {
259        steps: SharedSnapshot(wrapped.into()),
260        route_id: route_id.to_string(),
261        handler,
262        ctx,
263    })
264}
265
266/// Compose a list of `CompiledStep` items into a single pipeline with body coercion.
267///
268/// Each processor is optionally wrapped with `BodyCoercingProcessor` based on its
269/// contract. Processors with `None` contract are passed through with zero overhead.
270/// `CompiledStep::Stop` passes through without coercion.
271pub fn compose_pipeline_with_contracts(
272    processors: Vec<CompiledStep>,
273    handler: Option<Arc<dyn RouteErrorHandler>>,
274    ctx: PipelineRuntimeCtx,
275) -> BoxProcessor {
276    let wrapped: Vec<CompiledStep> = processors
277        .into_iter()
278        .map(|step| match step {
279            CompiledStep::Process {
280                processor,
281                body_contract,
282                lifecycle,
283                label,
284                kind_hint,
285            } => {
286                let coerced = wrap_if_needed(processor, body_contract);
287                CompiledStep::Process {
288                    processor: coerced,
289                    body_contract: None,
290                    lifecycle,
291                    label,
292                    kind_hint,
293                }
294            }
295            CompiledStep::Stop => CompiledStep::Stop,
296            CompiledStep::Segment { .. } => step,
297        })
298        .collect();
299    compose_pipeline_with_handler(wrapped, handler, ctx)
300}
301
302/// Compose a list of `CompiledStep` items into a single pipeline with body coercion.
303///
304/// Applies body coercion contracts first, then wraps with `TracingProcessor`.
305/// The pipeline opens one Internal route root span per invocation (named after
306/// `route_id`); empty traced routes still return a `TracedPipeline` so the
307/// root span records the route invocation with zero steps.
308/// When the pipeline is disabled, falls back to [`compose_pipeline_with_contracts`].
309pub(crate) fn compose_traced_pipeline_with_contracts(
310    processors: Vec<CompiledStep>,
311    route_id: &str,
312    gating: impl Into<TracerPipelineGating>,
313    detail_level: DetailLevel,
314    metrics: Option<Arc<dyn MetricsCollector>>,
315    handler: Option<Arc<dyn RouteErrorHandler>>,
316    ctx: PipelineRuntimeCtx,
317) -> BoxProcessor {
318    let gating = gating.into();
319    if !gating.pipeline_enabled {
320        return compose_pipeline_with_contracts(processors, handler, ctx);
321    }
322
323    let coerced: Vec<CompiledStep> = processors
324        .into_iter()
325        .map(|step| match step {
326            CompiledStep::Process {
327                processor,
328                body_contract,
329                lifecycle,
330                label,
331                kind_hint,
332            } => {
333                let processor = wrap_if_needed(processor, body_contract);
334                CompiledStep::Process {
335                    processor,
336                    body_contract: None,
337                    lifecycle,
338                    label,
339                    kind_hint,
340                }
341            }
342            CompiledStep::Stop => CompiledStep::Stop,
343            CompiledStep::Segment { .. } => step,
344        })
345        .collect();
346
347    compose_traced_pipeline(
348        coerced,
349        route_id,
350        gating,
351        detail_level,
352        metrics,
353        handler,
354        ctx,
355    )
356}
357
358/// A service that executes a sequence of CompiledSteps in order.
359///
360/// Uses `into_tower_result()` so `PipelineOutcome::Stopped(ex)` maps to
361/// `Ok(ex)` — the Bug B fix that makes Stop indistinguishable from Completed
362/// at the consumer boundary.
363#[derive(Clone)]
364struct SequentialPipeline {
365    steps: SharedSnapshot,
366    handler: Option<Arc<dyn RouteErrorHandler>>,
367    ctx: PipelineRuntimeCtx,
368}
369
370impl Service<Exchange> for SequentialPipeline {
371    type Response = Exchange;
372    type Error = CamelError;
373    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
374
375    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
376        match self.steps.0.first() {
377            Some(CompiledStep::Process { processor, .. }) => {
378                let mut proc = processor.clone();
379                match proc.poll_ready(cx) {
380                    Poll::Pending => Poll::Pending,
381                    Poll::Ready(Err(_)) if self.handler.is_some() => Poll::Ready(Ok(())),
382                    Poll::Ready(other) => Poll::Ready(other),
383                }
384            }
385            Some(CompiledStep::Stop) => Poll::Ready(Ok(())),
386            Some(CompiledStep::Segment { .. }) => Poll::Ready(Ok(())),
387            None => Poll::Ready(Ok(())),
388        }
389    }
390
391    // ADR-0024 reply-channel adapter: PipelineOutcome → Result<Exchange, CamelError>.
392    // Completed(ex) and Stopped(ex) both map to Ok(ex); Failed(err) maps to Err.
393    // Downstream consumers (RouteChannelService, ExchangeUoWLayer, HTTP/Kafka reply
394    // finalisers) see Result<Exchange, CamelError> and treat Stop as success.
395    fn call(&mut self, exchange: Exchange) -> Self::Future {
396        // Cheap Arc::clone (refcount bump) on the SharedSnapshot newtype.
397        // `SharedSnapshot: Send` so the future returned by `run_steps`
398        // captures it directly without needing a Send-asserting wrapper.
399        let steps = self.steps.clone();
400        let handler = self.handler.clone();
401        let ctx = self.ctx.clone();
402        Box::pin(async move {
403            run_steps(steps, exchange, handler, false, &ctx.route_id, &ctx)
404                .await
405                .into_tower_result()
406        })
407    }
408}
409
410/// A traced service pipeline for wrapped CompiledSteps.
411///
412/// Each invocation opens one Internal route root span named after the route;
413/// step spans (from `TracingProcessor`) nest under it. The root span handle
414/// lives inside the `call` async body — never on `self` — so hot-reload
415/// pipeline swaps are unaffected.
416#[derive(Clone)]
417struct TracedPipeline {
418    steps: SharedSnapshot,
419    route_id: String,
420    handler: Option<Arc<dyn RouteErrorHandler>>,
421    ctx: PipelineRuntimeCtx,
422}
423
424impl Service<Exchange> for TracedPipeline {
425    type Response = Exchange;
426    type Error = CamelError;
427    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
428
429    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
430        match self.steps.0.first() {
431            Some(CompiledStep::Process { processor, .. }) => {
432                let mut proc = processor.clone();
433                match proc.poll_ready(cx) {
434                    Poll::Pending => Poll::Pending,
435                    Poll::Ready(Err(_)) if self.handler.is_some() => Poll::Ready(Ok(())),
436                    Poll::Ready(other) => Poll::Ready(other),
437                }
438            }
439            Some(CompiledStep::Stop) => Poll::Ready(Ok(())),
440            Some(CompiledStep::Segment { .. }) => Poll::Ready(Ok(())),
441            None => Poll::Ready(Ok(())),
442        }
443    }
444
445    // ADR-0024 reply-channel adapter (same as SequentialPipeline::call):
446    // Completed(ex) and Stopped(ex) both map to Ok(ex). Bug B fix.
447    //
448    // Route root span (trace-model-tree T1.3): one Internal span per route
449    // invocation, named after the route, parenting every step span. Derived
450    // from the entry context (not the ambient current context) so parent
451    // entries such as baggage stay attached; the entry context is restored
452    // on the result exchange when one comes back.
453    fn call(&mut self, exchange: Exchange) -> Self::Future {
454        let steps = self.steps.clone();
455        let route_id = self.route_id.clone();
456        let handler = self.handler.clone();
457        let ctx = self.ctx.clone();
458        Box::pin(async move {
459            let tracer = global::tracer_with_scope(
460                InstrumentationScope::builder("camel-core")
461                    .with_version(env!("CARGO_PKG_VERSION"))
462                    .build(),
463            );
464            let entry_cx = exchange.otel_context.clone();
465            let root_span = tracer
466                .span_builder(route_id.clone())
467                .with_kind(SpanKind::Internal)
468                .with_attributes([
469                    KeyValue::new("messaging.system", "camel"),
470                    KeyValue::new("route_id", route_id.clone()),
471                    KeyValue::new(
472                        "correlation_id",
473                        capped_correlation_id(exchange.correlation_id()).to_string(),
474                    ),
475                ])
476                .start_with_context(&tracer, &entry_cx);
477            let root_cx = entry_cx.with_span(root_span);
478            // Guard ends the root span even if a step panics.
479            let _root_guard = SpanEndGuard(root_cx.clone());
480            let mut exchange = exchange;
481            exchange.otel_context = root_cx.clone();
482
483            let outcome = run_steps(steps, exchange, handler, true, &route_id, &ctx).await;
484            finish_span_outcome(outcome, &root_cx, entry_cx).into_tower_result()
485        })
486    }
487}
488
489/// Run a sequence of CompiledSteps with optional error recovery.
490///
491/// Each step is unified under [`OwnedRetryable`] — Process and
492/// Segment variants are treated uniformly via a stack-allocated enum
493/// that dispatches to the existing `RetryableStep` impls on
494/// `BoxProcessor` and `OutcomeSegment`. This eliminates the per-step
495/// `Box::new(...) as Box<dyn RetryableStep>` heap allocation that the
496/// pre-A2 implementation paid for every step of every Exchange (A2).
497///
498/// On the traced path (`trace == true`, `route_id` from the traced
499/// pipeline), Segment steps dispatch through [`TracedSegmentStep`]
500/// instead, so the initial invocation AND every retry attempt opened by
501/// the error handler runs through the same span wrapper (T1.4).
502///
503/// On failure:
504/// 1. If a handler is present, `match_policy` selects a retry policy.
505/// 2. `retry_step` attempts recovery; if exhausted, `handle_step` determines
506///    the disposition:
507///    - `Propagate` — return the error
508///    - `Handled` — return the exchange early (success)
509///    - `Continued` — clear the error and continue to the next step
510/// 3. If no handler is present, the error is propagated directly.
511///
512/// CompiledStep::Stop short-circuits to `PipelineOutcome::Stopped(ex)` — the
513/// handler is bypassed and no Tower service is invoked (ADR-0024 §3.5).
514async fn run_steps(
515    steps: SharedSnapshot,
516    exchange: Exchange,
517    handler: Option<Arc<dyn RouteErrorHandler>>,
518    trace: bool,
519    route_id: &str,
520    ctx: &PipelineRuntimeCtx,
521) -> PipelineOutcome {
522    use camel_api::error_handler::RetryableStep;
523    let mut ex = exchange;
524    // Index-based loop (not `for (i, step) in steps.0.iter().enumerate()`):
525    // retained to avoid holding a `&[CompiledStep]` borrow across the
526    // `.await` below — `&steps.0[i]` is consumed by the `match` scrutinee
527    // and drops before the await, so no borrow is live across the await
528    // point. The original `CompiledStep: !Sync` rationale is gone
529    // (`BoxProcessor` is now `Send + Sync` via `BoxCloneSyncService`);
530    // the loop shape is kept purely for borrow hygiene — no behavior change.
531    let len = steps.0.len();
532    for i in 0..len {
533        // B1: cooperative cancellation between steps via task-local.
534        // If the task-local is not set (direct test calls), skip the check.
535        let cancelled = CANCEL_TOKEN.try_with(|t| t.is_cancelled()).unwrap_or(false);
536        if cancelled {
537            return PipelineOutcome::Failed(CamelError::ConsumerStopping);
538        }
539        // A2: dispatch to existing `RetryableStep` impls through a stack
540        // enum instead of paying `Box::new(...) as Box<dyn RetryableStep>`
541        // per step. `OwnedRetryable` is `enum { Processor, Segment }` with
542        // discriminant-by-value layout — no extra heap alloc. On the traced
543        // path, Segment steps take the `TracedSegment` variant so every
544        // attempt (initial + retries) gets its own step span (T1.4).
545        let mut retryable: OwnedRetryable = match &steps.0[i] {
546            CompiledStep::Stop => return PipelineOutcome::Stopped(ex),
547            CompiledStep::Process { processor, .. } => OwnedRetryable::Processor(processor.clone()),
548            CompiledStep::Segment { segment, label, .. } => {
549                if trace {
550                    OwnedRetryable::TracedSegment(TracedSegmentStep {
551                        segment: segment.clone(),
552                        route_id: route_id.to_string(),
553                        index: i,
554                        label: label.clone(),
555                    })
556                } else {
557                    OwnedRetryable::Segment(segment.clone())
558                }
559            }
560        };
561
562        let original = handler.as_ref().map(|_| ex.clone());
563        let outcome = if trace {
564            invoke_with_span(&mut retryable, ex, i).await
565        } else {
566            retryable.invoke(ex).await
567        };
568
569        match outcome {
570            PipelineOutcome::Completed(next) => {
571                if camel_api::is_camel_stop(&next) {
572                    return PipelineOutcome::Stopped(next);
573                }
574                ex = next;
575            }
576            PipelineOutcome::Stopped(stopped_ex) => {
577                return PipelineOutcome::Stopped(stopped_ex);
578            }
579            PipelineOutcome::Failed(err) => {
580                let (Some(handler), Some(original)) = (handler.as_ref(), original) else {
581                    return PipelineOutcome::Failed(err);
582                };
583                let policy = handler.match_policy(&err);
584                // `&mut retryable` auto-coerces from `&mut OwnedRetryable` to
585                // `&mut dyn RetryableStep` via the trait impl on the enum.
586                match handler
587                    .retry_step(policy, &mut retryable, original, err)
588                    .await
589                {
590                    RetryOutcome::Recovered(exchange) => {
591                        // allow-open-label rc-xl5k (route label: user-defined route id, bounded by route count)
592                        ctx.metrics.record_counter(
593                            "pipeline_disposition",
594                            1.0,
595                            &[("disposition", "recovered"), ("route_id", &ctx.route_id)],
596                        );
597                        ex = exchange;
598                    }
599                    RetryOutcome::Stopped(stopped_ex) => {
600                        // allow-open-label rc-xl5k (route label: user-defined route id, bounded by route count)
601                        ctx.metrics.record_counter(
602                            "pipeline_disposition",
603                            1.0,
604                            &[("disposition", "stopped"), ("route_id", &ctx.route_id)],
605                        );
606                        return PipelineOutcome::Stopped(stopped_ex);
607                    }
608                    RetryOutcome::Exhausted {
609                        exchange,
610                        error,
611                        policy,
612                    } => {
613                        let disposition = if trace {
614                            handler
615                                .handle_step(policy, exchange, error)
616                                .instrument(tracing::debug_span!("error_handler", step_index = i))
617                                .await
618                        } else {
619                            handler.handle_step(policy, exchange, error).await
620                        };
621                        match disposition {
622                            Ok(StepDisposition::Propagate(e)) => {
623                                // allow-open-label rc-xl5k (route label: user-defined route id, bounded by route count)
624                                ctx.metrics.record_counter(
625                                    "pipeline_disposition",
626                                    1.0,
627                                    &[("disposition", "propagated"), ("route_id", &ctx.route_id)],
628                                );
629                                return PipelineOutcome::Failed(e);
630                            }
631                            Ok(StepDisposition::Handled(done)) => {
632                                // allow-open-label rc-xl5k (route label: user-defined route id, bounded by route count)
633                                ctx.metrics.record_counter(
634                                    "pipeline_disposition",
635                                    1.0,
636                                    &[("disposition", "handled"), ("route_id", &ctx.route_id)],
637                                );
638                                return PipelineOutcome::Completed(done);
639                            }
640                            Ok(StepDisposition::Continued(next)) => {
641                                // allow-open-label rc-xl5k (route label: user-defined route id, bounded by route count)
642                                ctx.metrics.record_counter(
643                                    "pipeline_disposition",
644                                    1.0,
645                                    &[("disposition", "continued"), ("route_id", &ctx.route_id)],
646                                );
647                                ex = next;
648                            }
649                            Err(e) => {
650                                // allow-open-label rc-xl5k (route label: user-defined route id, bounded by route count)
651                                ctx.metrics.record_counter(
652                                    "pipeline_disposition",
653                                    1.0,
654                                    &[
655                                        ("disposition", "handler_error"),
656                                        ("route_id", &ctx.route_id),
657                                    ],
658                                );
659                                return PipelineOutcome::Failed(e);
660                            }
661                            // Future StepDisposition variants fail the pipeline.
662                            _ => {
663                                return PipelineOutcome::Failed(CamelError::ProcessorError(
664                                    "unknown step disposition".to_string(),
665                                ));
666                            }
667                        }
668                    }
669                    // Future RetryOutcome variants fail the pipeline.
670                    _ => {
671                        return PipelineOutcome::Failed(CamelError::ProcessorError(
672                            "unknown retry outcome".to_string(),
673                        ));
674                    }
675                }
676            }
677        }
678    }
679    PipelineOutcome::Completed(ex)
680}
681
682/// Stack-allocated dispatcher that unifies `BoxProcessor` and
683/// `OutcomeSegment` for the retry path without the heap allocation a
684/// `Box<dyn RetryableStep>` would require. Sized by-value, dispatched
685/// through a single trait method that fans out to the existing
686/// `RetryableStep` impls on each variant.
687///
688/// A2: replaces `Box::new(processor.clone()) as Box<dyn RetryableStep>`
689/// (and the equivalent for segments) with this enum, saving one heap
690/// allocation per pipeline step per Exchange invocation.
691enum OwnedRetryable {
692    Processor(camel_api::BoxProcessor),
693    Segment(camel_api::OutcomeSegment),
694    /// Traced segment dispatch (T1.4): every attempt — the initial
695    /// invocation and each retry opened by the error handler — goes
696    /// through `TracedSegmentStep` so each gets its own step span.
697    TracedSegment(TracedSegmentStep),
698}
699
700impl camel_api::error_handler::RetryableStep for OwnedRetryable {
701    fn invoke<'a>(
702        &'a mut self,
703        exchange: Exchange,
704    ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
705        match self {
706            OwnedRetryable::Processor(p) => p.invoke(exchange),
707            OwnedRetryable::Segment(s) => s.invoke(exchange),
708            OwnedRetryable::TracedSegment(s) => s.invoke(exchange),
709        }
710    }
711}
712
713/// Start an Internal span for one segment step attempt, parented by
714/// `entry_cx` (the traced pipeline's root context) with the Minimal-level
715/// attribute set from `step_span_attributes` (trace-model-tree T1.4).
716///
717/// Named `{route_id}:{label}` when the segment step carries a DSL label
718/// (e.g. `split`); unlabeled segments fall back to the positional
719/// `{route_id}:step-{index}` name — same contract as process step spans.
720fn segment_span(
721    tracer: &global::BoxedTracer,
722    route_id: &str,
723    index: usize,
724    label: Option<Arc<str>>,
725    entry_cx: &OtelContext,
726    correlation_id: &str,
727) -> global::BoxedSpan {
728    tracer
729        .span_builder(format!(
730            "{route_id}:{}",
731            label.as_deref().unwrap_or(&step_id_for(index))
732        ))
733        .with_kind(SpanKind::Internal)
734        .with_attributes(step_span_attributes(route_id, index, correlation_id))
735        .start_with_context(tracer, entry_cx)
736}
737
738/// Per-attempt span adapter for `CompiledStep::Segment` on traced
739/// pipelines (trace-model-tree T1.4).
740///
741/// Implements `RetryableStep` so BOTH the initial invocation and every
742/// retry attempt dispatched by `RouteErrorHandler::retry_step` run
743/// through the same wrapper: each `invoke` opens one fresh Internal span
744/// parented by the incoming context (the route root), named
745/// `{route_id}:{label}` when the segment step carries a DSL label (e.g.
746/// `split`) and `{route_id}:step-{index}` otherwise. It runs the inner
747/// segment with that span active, restores the incoming context on
748/// outcomes that carry the exchange, and ends the span with the future —
749/// spans never outlive the attempt.
750///
751/// Retry inputs are the error handler's preserved pre-attempt exchange,
752/// which still carries the route root context (restored by a previous
753/// attempt's Ok path, or never left on the first attempt), so every
754/// attempt span nests under the route root, not under each other.
755struct TracedSegmentStep {
756    segment: camel_api::OutcomeSegment,
757    route_id: String,
758    index: usize,
759    label: Option<Arc<str>>,
760}
761
762fn finish_span_outcome(
763    outcome: PipelineOutcome,
764    span_cx: &OtelContext,
765    entry_cx: OtelContext,
766) -> PipelineOutcome {
767    match outcome {
768        PipelineOutcome::Completed(mut ex) => {
769            span_cx.span().set_status(Status::Ok);
770            ex.otel_context = entry_cx;
771            PipelineOutcome::Completed(ex)
772        }
773        PipelineOutcome::Stopped(mut ex) => {
774            span_cx.span().set_status(Status::Ok);
775            ex.otel_context = entry_cx;
776            PipelineOutcome::Stopped(ex)
777        }
778        PipelineOutcome::Failed(e) => {
779            record_exception(&span_cx.span(), &e);
780            PipelineOutcome::Failed(e)
781        }
782    }
783}
784
785impl camel_api::error_handler::RetryableStep for TracedSegmentStep {
786    fn invoke<'a>(
787        &'a mut self,
788        mut exchange: Exchange,
789    ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
790        Box::pin(async move {
791            let tracer = global::tracer_with_scope(
792                InstrumentationScope::builder("camel-core")
793                    .with_version(env!("CARGO_PKG_VERSION"))
794                    .build(),
795            );
796            let entry_cx = exchange.otel_context.clone();
797            let span = segment_span(
798                &tracer,
799                &self.route_id,
800                self.index,
801                self.label.clone(),
802                &entry_cx,
803                exchange.correlation_id(),
804            );
805            let cx = entry_cx.with_span(span);
806            // Guard ends the attempt span even if the segment panics.
807            let _guard = SpanEndGuard(cx.clone());
808            exchange.otel_context = cx.clone();
809            finish_span_outcome(self.segment.run(exchange).await, &cx, entry_cx)
810        })
811    }
812}
813
814async fn invoke_with_span(
815    retryable: &mut dyn camel_api::error_handler::RetryableStep,
816    exchange: Exchange,
817    idx: usize,
818) -> PipelineOutcome {
819    retryable
820        .invoke(exchange)
821        .instrument(tracing::debug_span!("pipeline_step", index = idx))
822        .await
823}
824
825/// Route channel with explicit security and circuit-breaker gates.
826///
827/// Gate order: Security → CB(before_call) → Pipeline → CB(after_result).
828/// Errors from Security/CB gates go to `handler.handle_boundary`.
829/// Errors from Pipeline go through the injected handler's retry/handle_step.
830/// Pipeline Propagate returns Err — passed through to upstream.
831#[derive(Clone)]
832pub struct RouteChannelService {
833    handler: Arc<dyn RouteErrorHandler>,
834    security: Option<BoxProcessor>,
835    cb_gate: Option<CircuitBreakerGate>,
836    pipeline: BoxProcessor,
837    /// When true, stash the original Message as `ORIGINAL_MESSAGE_EXTENSION`
838    /// before any gate runs, so the error handler can restore it on failure.
839    use_original_message: bool,
840}
841
842impl RouteChannelService {
843    pub fn new(
844        handler: Arc<dyn RouteErrorHandler>,
845        security: Option<BoxProcessor>,
846        cb_gate: Option<CircuitBreakerGate>,
847        pipeline: BoxProcessor,
848        use_original_message: bool,
849    ) -> Self {
850        Self {
851            handler,
852            security,
853            cb_gate,
854            pipeline,
855            use_original_message,
856        }
857    }
858}
859
860impl Service<Exchange> for RouteChannelService {
861    type Response = Exchange;
862    type Error = CamelError;
863    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
864
865    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), CamelError>> {
866        // Swallow readiness errors from security gate — deferred to call()
867        if let Some(ref mut sec) = self.security {
868            match sec.clone().poll_ready(cx) {
869                Poll::Pending => return Poll::Pending,
870                Poll::Ready(Err(_)) | Poll::Ready(Ok(())) => {}
871            }
872        }
873        // Pipeline readiness — swallow errors when handler present
874        match self.pipeline.clone().poll_ready(cx) {
875            Poll::Pending => return Poll::Pending,
876            Poll::Ready(Err(_)) | Poll::Ready(Ok(())) => {}
877        }
878        Poll::Ready(Ok(()))
879    }
880
881    fn call(&mut self, exchange: Exchange) -> Self::Future {
882        let handler = self.handler.clone();
883        let security = self.security.clone();
884        let cb_gate = self.cb_gate.clone();
885        let mut pipeline = self.pipeline.clone();
886        let use_original_message = self.use_original_message;
887
888        Box::pin(async move {
889            let mut ex = exchange;
890
891            // Stash original message for use_original_message support.
892            // Done BEFORE any gate so the DLC can restore the pre-route message.
893            // Only stashes when the flag is true to avoid perf regression on every Exchange.
894            if use_original_message {
895                let original: Arc<Message> = Arc::new(ex.input.clone());
896                ex.set_extension(ORIGINAL_MESSAGE_EXTENSION, original);
897            }
898
899            // Gate 1: Security
900            if let Some(mut sec) = security {
901                let original = ex.clone();
902                match invoke_processor(&mut sec, ex).await {
903                    Ok(next) => ex = next,
904                    Err(err) => {
905                        return handler
906                            .handle_boundary(BoundaryKind::Security, original, err)
907                            .await;
908                    }
909                }
910            }
911
912            // Gate 2: CircuitBreaker — before_call
913            if let Some(ref cb) = cb_gate {
914                match cb.before_call() {
915                    CircuitBreakerDecision::Allow => { /* proceed to pipeline */ }
916                    CircuitBreakerDecision::Fallback(mut fb) => {
917                        // Circuit open with fallback — call fallback.
918                        // Fallback errors go through handle_boundary, not raw to upstream.
919                        let original = ex.clone();
920                        match invoke_processor(&mut fb, ex).await {
921                            Ok(result) => return Ok(result),
922                            Err(err) => {
923                                return handler
924                                    .handle_boundary(BoundaryKind::CircuitBreaker, original, err)
925                                    .await;
926                            }
927                        }
928                    }
929                    CircuitBreakerDecision::Reject(err) => {
930                        let original = ex.clone();
931                        return handler
932                            .handle_boundary(BoundaryKind::CircuitBreaker, original, err)
933                            .await;
934                    }
935                }
936            }
937
938            // Pipeline (handler already injected for step errors)
939            let result = invoke_processor(&mut pipeline, ex).await;
940
941            // Gate 2: CircuitBreaker — after_result
942            if let Some(ref cb) = cb_gate {
943                cb.after_result(&result);
944            }
945
946            // Propagate from inner handler — pass through to upstream
947            result
948        })
949    }
950}
951
952#[cfg(test)]
953#[path = "route_compiler_tests.rs"]
954mod tests;