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