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