Skip to main content

camel_core/lifecycle/application/
route_definition.rs

1// lifecycle/application/route_definition.rs
2// Route definition and builder-step types. Route (compiled artifact) lives in adapters.
3
4use std::sync::Arc;
5
6use camel_api::UnitOfWorkConfig;
7use camel_api::circuit_breaker::CircuitBreakerConfig;
8use camel_api::error_handler::ErrorHandlerConfig;
9use camel_api::loop_eip::LoopConfig;
10use camel_api::security_policy::SecurityPolicyConfig;
11use camel_api::{
12    AggregatorConfig, FilterPredicate, LayerFactory, MulticastConfig, OpaqueProcessor,
13    ResequencePolicyConfig, SpanKindHint, SplitterConfig,
14};
15use camel_auth::TokenAuthenticator;
16use camel_component_api::ConcurrencyModel;
17
18/// An unresolved when-clause: predicate + nested steps for the sub-pipeline.
19#[derive(Clone)]
20pub struct WhenStep {
21    pub predicate: FilterPredicate,
22    pub steps: Vec<BuilderStep>,
23}
24
25impl std::fmt::Debug for WhenStep {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        f.debug_struct("WhenStep")
28            .field("predicate", &self.predicate)
29            .field("steps", &self.steps)
30            .finish()
31    }
32}
33
34pub use camel_api::declarative::{LanguageExpressionDef, ValueSourceDef};
35
36/// Declarative `when` clause resolved later by the runtime.
37#[derive(Debug, Clone)]
38pub struct DeclarativeWhenStep {
39    pub predicate: LanguageExpressionDef,
40    pub steps: Vec<BuilderStep>,
41}
42
43/// Builder struct for a single `doCatch` clause in the declarative pipeline.
44#[derive(Debug, Clone)]
45pub struct DoTryCatchClauseBuilder {
46    pub exception: Option<Vec<String>>,
47    pub when: Option<LanguageExpressionDef>,
48    /// Match a `CamelError::Business` whose `code` equals this value.
49    pub code: Option<String>,
50    /// Match a `CamelError::Business` whose `kind` equals this value.
51    pub business_kind: Option<String>,
52    pub on_when: Option<LanguageExpressionDef>,
53    pub disposition: camel_api::error_handler::ExceptionDisposition,
54    pub steps: Vec<BuilderStep>,
55}
56
57/// Builder struct for the `doFinally` block in the declarative pipeline.
58#[derive(Debug, Clone)]
59pub struct DoTryFinallyBuilder {
60    pub on_when: Option<LanguageExpressionDef>,
61    pub steps: Vec<BuilderStep>,
62}
63
64/// A single `doCatch` clause in the programmatic (builder) pipeline.
65#[derive(Clone)]
66pub struct DoTryCatchClause {
67    pub matcher: camel_processor::CatchMatcher,
68    pub on_when: Option<camel_api::PredicateSource>,
69    pub disposition: camel_api::error_handler::ExceptionDisposition,
70    pub steps: Vec<BuilderStep>,
71}
72
73impl std::fmt::Debug for DoTryCatchClause {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        f.debug_struct("DoTryCatchClause")
76            .field("matcher", &"<compiled>")
77            .field("on_when", &self.on_when.is_some())
78            .field("disposition", &self.disposition)
79            .field("steps", &self.steps)
80            .finish()
81    }
82}
83
84/// The `doFinally` block in the programmatic (builder) pipeline.
85#[derive(Clone)]
86pub struct DoTryFinallyClause {
87    pub on_when: Option<camel_api::PredicateSource>,
88    pub steps: Vec<BuilderStep>,
89}
90
91impl std::fmt::Debug for DoTryFinallyClause {
92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93        f.debug_struct("DoTryFinallyClause")
94            .field("on_when", &self.on_when.is_some())
95            .field("steps", &self.steps)
96            .finish()
97    }
98}
99
100/// Opaque wrapper for a programmatic streaming-split expression.
101///
102/// `camel_api::StreamingSplitExpression` is a bare `Arc<dyn Fn …>` and has no
103/// `Debug` implementation; wrapping it keeps `BuilderStep`'s derived `Debug`
104/// while rendering the closure as opaque, mirroring `OpaqueProcessor`.
105#[derive(Clone)]
106pub struct StreamSplitExpression(pub camel_api::StreamingSplitExpression);
107
108impl std::fmt::Debug for StreamSplitExpression {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        f.write_str("StreamingSplitExpression(...)")
111    }
112}
113
114impl From<camel_api::StreamingSplitExpression> for StreamSplitExpression {
115    fn from(expression: camel_api::StreamingSplitExpression) -> Self {
116        Self(expression)
117    }
118}
119
120/// A step in an unresolved route definition.
121#[derive(Debug, Clone)]
122pub enum BuilderStep {
123    /// A pre-built Tower processor service.
124    Processor(OpaqueProcessor),
125    /// A destination URI — resolved at start time by CamelContext.
126    To(String),
127    /// A stop step that halts processing immediately.
128    Stop,
129    /// A static log step.
130    Log {
131        level: camel_processor::LogLevel,
132        message: String,
133    },
134    /// Declarative set_header (literal or language-based value), resolved at route-add time.
135    DeclarativeSetHeader {
136        key: String,
137        value: ValueSourceDef,
138    },
139    /// Declarative set_header_if_absent (internal-only), resolved at route-add time.
140    DeclarativeSetHeaderIfAbsent {
141        key: String,
142        value: ValueSourceDef,
143    },
144    /// Declarative throw: raises `CamelError::Business` at route-add time.
145    /// `message` and the string leaves of `data` are evaluated per exchange.
146    DeclarativeThrow {
147        /// Stable machine-readable business code (required, non-blank).
148        code: String,
149        /// Optional business kind; `None` means `failed`.
150        kind: Option<String>,
151        /// Optional message template; defaults to the `code` value.
152        message: Option<ValueSourceDef>,
153        /// Optional diagnostics object; its string leaves are templates.
154        data: Option<serde_json::Value>,
155    },
156    /// Declarative remove_header, resolved at route-add time.
157    DeclarativeRemoveHeader {
158        key: String,
159    },
160    DeclarativeSetProperty {
161        key: String,
162        value_source: ValueSourceDef,
163    },
164    /// Declarative set_body (literal or language-based value), resolved at route-add time.
165    DeclarativeSetBody {
166        value: ValueSourceDef,
167    },
168    /// Declarative filter using a language predicate, resolved at route-add time.
169    DeclarativeFilter {
170        predicate: LanguageExpressionDef,
171        steps: Vec<BuilderStep>,
172    },
173    /// Declarative choice/when/otherwise using language predicates, resolved at route-add time.
174    DeclarativeChoice {
175        whens: Vec<DeclarativeWhenStep>,
176        otherwise: Option<Vec<BuilderStep>>,
177    },
178    /// Declarative script step. The language must support mutating expressions,
179    /// and the step writes the Exchange back.
180    DeclarativeScript {
181        expression: LanguageExpressionDef,
182    },
183    DeclarativeFunction {
184        definition: camel_api::FunctionDefinition,
185    },
186    /// Declarative split using a language expression, resolved at route-add time.
187    DeclarativeSplit {
188        expression: LanguageExpressionDef,
189        aggregation: camel_api::splitter::AggregationStrategy,
190        parallel: bool,
191        parallel_limit: Option<usize>,
192        /// Threshold above which split fragments start new traces (None =
193        /// `DEFAULT_TRACE_ITEM_THRESHOLD` applies at compile time).
194        trace_item_threshold: Option<usize>,
195        stop_on_exception: bool,
196        steps: Vec<BuilderStep>,
197    },
198    /// Declarative stream split using a streaming split expression, resolved at route-add time.
199    DeclarativeStreamSplit {
200        stream_config: camel_api::StreamSplitConfig,
201        aggregation: camel_api::splitter::AggregationStrategy,
202        stop_on_exception: bool,
203        steps: Vec<BuilderStep>,
204    },
205    /// Programmatic stream split: the caller supplies the fragment expression directly
206    /// (e.g. built from `camel_processor::stream_codec` or `zip_splitter`). The expression
207    /// encapsulates the stream configuration; the compiled segment applies the same
208    /// aggregation and stop-on-exception semantics as the declarative form.
209    StreamSplit {
210        expression: StreamSplitExpression,
211        aggregation: camel_api::splitter::AggregationStrategy,
212        stop_on_exception: bool,
213        steps: Vec<BuilderStep>,
214    },
215    DeclarativeDynamicRouter {
216        expression: LanguageExpressionDef,
217        uri_delimiter: String,
218        cache_size: i32,
219        ignore_invalid_endpoints: bool,
220        max_iterations: usize,
221    },
222    DeclarativeRoutingSlip {
223        expression: LanguageExpressionDef,
224        uri_delimiter: String,
225        cache_size: i32,
226        ignore_invalid_endpoints: bool,
227    },
228    /// A Splitter sub-pipeline: config + nested steps to execute per fragment.
229    Split {
230        config: SplitterConfig,
231        steps: Vec<BuilderStep>,
232    },
233    /// An Aggregator step: collects exchanges by correlation key, emits when complete.
234    Aggregate {
235        config: AggregatorConfig,
236    },
237    /// A Filter sub-pipeline: predicate + nested steps executed only when predicate is true.
238    Filter {
239        predicate: FilterPredicate,
240        steps: Vec<BuilderStep>,
241    },
242    /// A Choice step: evaluates when-clauses in order, routes to the first match.
243    /// If no when matches, the optional otherwise branch is used.
244    Choice {
245        whens: Vec<WhenStep>,
246        otherwise: Option<Vec<BuilderStep>>,
247    },
248    /// A WireTap step: sends a clone of the exchange to a tap endpoint (fire-and-forget).
249    WireTap {
250        uri: String,
251    },
252    /// A Multicast step: sends the same exchange to multiple destinations.
253    Multicast {
254        steps: Vec<BuilderStep>,
255        config: MulticastConfig,
256    },
257    /// Declarative log step with a language-evaluated message, resolved at route-add time.
258    DeclarativeLog {
259        level: camel_processor::LogLevel,
260        message: ValueSourceDef,
261    },
262    /// Bean invocation step — resolved at route-add time.
263    Bean {
264        name: String,
265        method: String,
266    },
267    /// Script step: executes a script that can mutate the exchange.
268    /// The script has access to `headers`, `properties`, and `body`.
269    Script {
270        language: String,
271        script: String,
272    },
273    /// Throttle step: rate limiting with configurable behavior when limit exceeded.
274    Throttle {
275        config: camel_api::ThrottlerConfig,
276        steps: Vec<BuilderStep>,
277    },
278    /// LoadBalance step: distributes exchanges across multiple endpoints using a strategy.
279    LoadBalance {
280        config: camel_api::LoadBalancerConfig,
281        steps: Vec<BuilderStep>,
282    },
283    /// DynamicRouter step: routes exchanges dynamically based on expression evaluation.
284    DynamicRouter {
285        config: camel_api::DynamicRouterConfig,
286    },
287    RoutingSlip {
288        config: camel_api::RoutingSlipConfig,
289    },
290    RecipientList {
291        config: camel_api::recipient_list::RecipientListConfig,
292    },
293    DeclarativeRecipientList {
294        expression: LanguageExpressionDef,
295        delimiter: String,
296        parallel: bool,
297        parallel_limit: Option<usize>,
298        stop_on_exception: bool,
299        aggregation: String,
300    },
301    Delay {
302        config: camel_api::DelayConfig,
303    },
304    /// Runtime loop with closure-based predicate (programmatic DSL).
305    Loop {
306        config: LoopConfig,
307        steps: Vec<BuilderStep>,
308    },
309    /// Declarative loop with optional language-based while predicate (YAML DSL).
310    DeclarativeLoop {
311        count: Option<usize>,
312        while_predicate: Option<LanguageExpressionDef>,
313        steps: Vec<BuilderStep>,
314        max_iterations: Option<usize>,
315    },
316    /// EIP-7 enrich: synchronous content enrichment via a resolved producer.
317    Enrich {
318        uri: String,
319        strategy: Option<String>,
320        timeout_ms: Option<u64>,
321    },
322    /// EIP-7 pollEnrich: blocking poll of a PollingConsumer with timeout.
323    PollEnrich {
324        uri: String,
325        strategy: Option<String>,
326        timeout_ms: Option<u64>,
327    },
328    /// Validate step: evaluates a language expression as predicate.
329    /// Exchange passes if predicate returns true; else CamelError::ValidationError.
330    Validate {
331        predicate: LanguageExpressionDef,
332    },
333    /// Claim Check step (EIP). Transforms the exchange body to/from a
334    /// `ClaimCheckRepository` by key. Process-mode, no child pipeline.
335    /// `filter` enables selective merge-back of body/headers during checkout.
336    ClaimCheck {
337        repository: String,
338        operation: String,
339        key: LanguageExpressionDef,
340        filter: Option<String>,
341    },
342    /// Sampling step (EIP). Passes 1 of every N exchanges (counter-based,
343    /// deterministic). Non-sampled exchanges get CamelStop=true (drop semantics).
344    /// Process-mode, stateless. No StepLifecycle — counter is route-scoped.
345    Sampling {
346        period: usize,
347    },
348    /// Sort step (EIP). Orders a body array by extracting a sort key
349    /// from each element via a language expression. Process-mode, stateless.
350    Sort {
351        expression: LanguageExpressionDef,
352        reverse: bool,
353    },
354    /// Idempotent Consumer step (EIP). Wraps a child sub-pipeline that runs
355    /// only when the message-id is NOT present in the named repository.
356    /// Compiled to a `IdempotentConsumerSegment` (OutcomePipeline, segment-mode).
357    IdempotentConsumer {
358        repository: String,
359        expression: LanguageExpressionDef,
360        steps: Vec<BuilderStep>,
361        eager: bool,
362        remove_on_failure: bool,
363    },
364    /// Cache step (EIP). Wraps a child sub-pipeline that runs only on cache
365    /// miss; on hit the stored body is reconstructed and the child is skipped.
366    /// Compiled to a `CacheService` (OutcomePipeline, segment-mode).
367    Cache {
368        repository: Option<String>,
369        key: LanguageExpressionDef,
370        ttl: Option<String>,
371        max_entry_bytes: Option<usize>,
372        /// Coalesce concurrent misses on the same key into one `on_miss` run.
373        coalesce_misses: bool,
374        on_miss: Vec<BuilderStep>,
375    },
376    /// Cache Invalidate step (EIP). Removes a single cache entry by exact key
377    /// (`key`) or every entry under a namespace prefix (`key_prefix`) — exactly
378    /// one of the two. Compiled to a `CacheInvalidateService` (OutcomePipeline,
379    /// segment-mode).
380    CacheInvalidate {
381        repository: Option<String>,
382        key: Option<LanguageExpressionDef>,
383        key_prefix: Option<LanguageExpressionDef>,
384    },
385    /// Cache Clear step (EIP). Removes all entries from the repository.
386    /// Compiled to a `CacheClearService` (OutcomePipeline, segment-mode).
387    CacheClear {
388        repository: Option<String>,
389    },
390    /// Cache Stats step (EIP). Emits the repository stats as a JSON body.
391    /// Compiled to a `CacheStatsService` (OutcomePipeline, segment-mode).
392    CacheStats {
393        repository: Option<String>,
394    },
395    /// Cache Peek Stale step (EIP). Serves a stale (post-expiry) cache entry.
396    /// Compiled to a `CachePeekStaleService` (OutcomePipeline, segment-mode).
397    CachePeekStale {
398        repository: Option<String>,
399        key: LanguageExpressionDef,
400        on_miss: camel_processor::PeekStaleMissPolicy,
401    },
402    /// Declarative doTry/doCatch/doFinally, resolved at route-add time.
403    DeclarativeDoTry {
404        try_steps: Vec<BuilderStep>,
405        catch: Vec<DoTryCatchClauseBuilder>,
406        finally: Option<DoTryFinallyBuilder>,
407    },
408    /// Programmatic doTry/doCatch/doFinally EIP, compiled to a `DoTrySegment`
409    /// (outcome-aware).
410    DoTry {
411        try_steps: Vec<BuilderStep>,
412        catches: Vec<DoTryCatchClause>,
413        finally: Option<DoTryFinallyClause>,
414    },
415    /// Resequencer EIP: resequences exchanges by sequence number.
416    /// Must be a top-level step (not nested inside structural EIPs).
417    Resequence {
418        policy_config: ResequencePolicyConfig,
419    },
420    /// A `to(uri)` send wrapped in a Tower middleware layer. The layer wraps
421    /// the resolved producer at route-add time; the step is still a send, so
422    /// span and latency metadata mirror `To`.
423    LayeredTo {
424        /// Authored destination URI — resolved like `To` at route-add time,
425        /// then wrapped with `factory`.
426        uri: String,
427        /// Type-erased tower layer applied around the resolved producer.
428        factory: LayerFactory,
429    },
430    /// A middleware layer wrapping a nested sub-pipeline (`layered`).
431    Layered {
432        /// Type-erased tower layer applied around the compiled section.
433        factory: LayerFactory,
434        /// Section steps compiled into one outcome-aware segment, wrapped
435        /// with `factory`.
436        steps: Vec<BuilderStep>,
437    },
438}
439
440impl BuilderStep {
441    /// Stable span name for this step (span-name-enrichment, task 1.2).
442    ///
443    /// `To` and its middleware-wrapped twin `LayeredTo` yield `to:{scheme}`
444    /// where scheme is the AUTHORED URI before the first `:` — a pure string
445    /// split, no endpoint resolution, so a `SkipTo` interception never
446    /// rewrites the label. EIP variants yield their
447    /// kebab-case EIP name; declarative twins share the label of their
448    /// programmatic sibling (`DeclarativeSplit` and `Split` are both
449    /// `"split"`). Genuinely anonymous variants (opaque processors, the Stop
450    /// marker) yield `None` — spans fall back to the positional
451    /// `step-{index}` name.
452    ///
453    /// The match is exhaustive by design (no catch-all) so a future variant
454    /// forces a label decision here.
455    pub(crate) fn span_label(&self) -> Option<String> {
456        match self {
457            // Anonymous.
458            Self::Processor(_) | Self::Stop => None,
459
460            Self::To(uri) => uri.contains(':').then(|| {
461                let scheme = uri.split(':').next().unwrap_or_default();
462                format!("to:{scheme}")
463            }),
464
465            // A layered send is still a send: same authored-scheme label.
466            Self::LayeredTo { uri, .. } => uri.contains(':').then(|| {
467                let scheme = uri.split(':').next().unwrap_or_default();
468                format!("to:{scheme}")
469            }),
470
471            Self::Log { .. } | Self::DeclarativeLog { .. } => Some("log".into()),
472
473            Self::DeclarativeSetHeader { .. } => Some("set-header".into()),
474            Self::DeclarativeSetHeaderIfAbsent { .. } => Some("set-header-if-absent".into()),
475            Self::DeclarativeThrow { .. } => Some("throw".into()),
476            Self::DeclarativeRemoveHeader { .. } => Some("remove-header".into()),
477            Self::DeclarativeSetProperty { .. } => Some("set-property".into()),
478            Self::DeclarativeSetBody { .. } => Some("set-body".into()),
479
480            Self::DeclarativeFilter { .. } | Self::Filter { .. } => Some("filter".into()),
481            Self::DeclarativeChoice { .. } | Self::Choice { .. } => Some("choice".into()),
482            Self::DeclarativeScript { .. } | Self::Script { .. } => Some("script".into()),
483            Self::DeclarativeFunction { .. } => Some("function".into()),
484
485            Self::DeclarativeSplit { .. }
486            | Self::DeclarativeStreamSplit { .. }
487            | Self::StreamSplit { .. }
488            | Self::Split { .. } => Some("split".into()),
489
490            Self::DeclarativeDynamicRouter { .. } | Self::DynamicRouter { .. } => {
491                Some("dynamic-router".into())
492            }
493            Self::DeclarativeRoutingSlip { .. } | Self::RoutingSlip { .. } => {
494                Some("routing-slip".into())
495            }
496            Self::DeclarativeRecipientList { .. } | Self::RecipientList { .. } => {
497                Some("recipient-list".into())
498            }
499
500            Self::Aggregate { .. } => Some("aggregate".into()),
501            Self::WireTap { .. } => Some("wire-tap".into()),
502            Self::Multicast { .. } => Some("multicast".into()),
503            Self::Bean { .. } => Some("bean".into()),
504            Self::Throttle { .. } => Some("throttle".into()),
505            Self::LoadBalance { .. } => Some("load-balance".into()),
506            Self::Delay { .. } => Some("delay".into()),
507            Self::Loop { .. } | Self::DeclarativeLoop { .. } => Some("loop".into()),
508            Self::Enrich { .. } => Some("enrich".into()),
509            Self::PollEnrich { .. } => Some("poll-enrich".into()),
510            Self::Validate { .. } => Some("validate".into()),
511            Self::ClaimCheck { .. } => Some("claim-check".into()),
512            Self::Sampling { .. } => Some("sampling".into()),
513            Self::Sort { .. } => Some("sort".into()),
514            Self::IdempotentConsumer { .. } => Some("idempotent-consumer".into()),
515            Self::Cache { .. } => Some("cache".into()),
516            Self::CacheInvalidate { .. } => Some("cache-invalidate".into()),
517            Self::CacheClear { .. } => Some("cache-clear".into()),
518            Self::CacheStats { .. } => Some("cache-stats".into()),
519            Self::CachePeekStale { .. } => Some("cache-peek-stale".into()),
520            Self::DeclarativeDoTry { .. } | Self::DoTry { .. } => Some("do-try".into()),
521            Self::Resequence { .. } => Some("resequence".into()),
522            Self::Layered { .. } => Some("layered".into()),
523        }
524    }
525
526    /// Declared send URI retained on the compiled step for step-latency
527    /// attribution (steplatency task 1.1). Only `To` and `LayeredTo` carry
528    /// one: the RAW AUTHORED URI, extracted as a pure string copy with no
529    /// endpoint
530    /// resolution, so a `SkipTo` interception never rewrites it — the
531    /// compiled step keeps the URI the route author wrote, not the
532    /// intercept target. Stored as shared immutable text (`Arc<str>`).
533    /// Every other variant yields `None`.
534    ///
535    /// The match is exhaustive by design (no catch-all) so a future
536    /// variant forces a declared-URI decision here.
537    pub(crate) fn to_uri_metadata(&self) -> Option<Arc<str>> {
538        match self {
539            Self::To(uri) => Some(Arc::from(uri.as_str())),
540            Self::LayeredTo { uri, .. } => Some(Arc::from(uri.as_str())),
541
542            // rc-4mz7: every remaining variant is named explicitly — no
543            // wildcard. A new BuilderStep variant fails to compile until it
544            // is classified here.
545            Self::Processor(..)
546            | Self::Stop
547            | Self::Log { .. }
548            | Self::DeclarativeSetHeader { .. }
549            | Self::DeclarativeSetHeaderIfAbsent { .. }
550            | Self::DeclarativeThrow { .. }
551            | Self::DeclarativeRemoveHeader { .. }
552            | Self::DeclarativeSetProperty { .. }
553            | Self::DeclarativeSetBody { .. }
554            | Self::DeclarativeFilter { .. }
555            | Self::DeclarativeChoice { .. }
556            | Self::DeclarativeScript { .. }
557            | Self::DeclarativeFunction { .. }
558            | Self::DeclarativeSplit { .. }
559            | Self::DeclarativeStreamSplit { .. }
560            | Self::StreamSplit { .. }
561            | Self::DeclarativeDynamicRouter { .. }
562            | Self::DeclarativeRoutingSlip { .. }
563            | Self::Split { .. }
564            | Self::Aggregate { .. }
565            | Self::Filter { .. }
566            | Self::Choice { .. }
567            | Self::Multicast { .. }
568            | Self::DeclarativeLog { .. }
569            | Self::Bean { .. }
570            | Self::Script { .. }
571            | Self::Throttle { .. }
572            | Self::LoadBalance { .. }
573            | Self::DynamicRouter { .. }
574            | Self::RoutingSlip { .. }
575            | Self::RecipientList { .. }
576            | Self::DeclarativeRecipientList { .. }
577            | Self::Delay { .. }
578            | Self::Loop { .. }
579            | Self::DeclarativeLoop { .. }
580            | Self::Enrich { .. }
581            | Self::PollEnrich { .. }
582            | Self::WireTap { .. }
583            | Self::Validate { .. }
584            | Self::ClaimCheck { .. }
585            | Self::Sampling { .. }
586            | Self::Sort { .. }
587            | Self::IdempotentConsumer { .. }
588            | Self::Cache { .. }
589            | Self::CacheInvalidate { .. }
590            | Self::CacheClear { .. }
591            | Self::CacheStats { .. }
592            | Self::CachePeekStale { .. }
593            | Self::DeclarativeDoTry { .. }
594            | Self::DoTry { .. }
595            | Self::Layered { .. }
596            | Self::Resequence { .. } => None,
597        }
598    }
599
600    /// Span kind hint for this step's step span (span-kind-hint, task 1.2).
601    ///
602    /// Endpoint-bearing variants (`To`, `LayeredTo`, `Enrich`, `PollEnrich`,
603    /// `WireTap`) classify the AUTHORED URI scheme — the text before the
604    /// first `:`,
605    /// compared with `eq_ignore_ascii_case`, no endpoint resolution — so a
606    /// `SkipTo` interception never rewrites the kind. Messaging broker
607    /// schemes map to `Producer` (async, one-way send) and synchronous
608    /// outbound protocols to `Client`; every other scheme and scheme-less
609    /// URIs stay `Internal` route processing.
610    ///
611    /// Every non-endpoint variant is internal route processing. The match is
612    /// exhaustive by design (no `_` wildcard): adding a `BuilderStep` variant
613    /// without an explicit span-kind decision here is a compile error
614    /// (rc-4mz7). `BuilderStep` is defined in this crate and carries no
615    /// `#[non_exhaustive]`, so same-crate exhaustiveness holds.
616    pub(crate) fn span_kind_hint(&self) -> SpanKindHint {
617        match self {
618            // A layered send classifies exactly like `To`: authored scheme only.
619            Self::To(uri)
620            | Self::LayeredTo { uri, .. }
621            | Self::Enrich { uri, .. }
622            | Self::PollEnrich { uri, .. }
623            | Self::WireTap { uri, .. } => uri_span_kind(uri),
624
625            // rc-4mz7: every remaining variant is named explicitly — no
626            // wildcard. A new BuilderStep variant fails to compile until it
627            // is classified here.
628            Self::Processor(..)
629            | Self::Stop
630            | Self::Log { .. }
631            | Self::DeclarativeSetHeader { .. }
632            | Self::DeclarativeSetHeaderIfAbsent { .. }
633            | Self::DeclarativeThrow { .. }
634            | Self::DeclarativeRemoveHeader { .. }
635            | Self::DeclarativeSetProperty { .. }
636            | Self::DeclarativeSetBody { .. }
637            | Self::DeclarativeFilter { .. }
638            | Self::DeclarativeChoice { .. }
639            | Self::DeclarativeScript { .. }
640            | Self::DeclarativeFunction { .. }
641            | Self::DeclarativeSplit { .. }
642            | Self::DeclarativeStreamSplit { .. }
643            | Self::StreamSplit { .. }
644            | Self::DeclarativeDynamicRouter { .. }
645            | Self::DeclarativeRoutingSlip { .. }
646            | Self::Split { .. }
647            | Self::Aggregate { .. }
648            | Self::Filter { .. }
649            | Self::Choice { .. }
650            | Self::Multicast { .. }
651            | Self::DeclarativeLog { .. }
652            | Self::Bean { .. }
653            | Self::Script { .. }
654            | Self::Throttle { .. }
655            | Self::LoadBalance { .. }
656            | Self::DynamicRouter { .. }
657            | Self::RoutingSlip { .. }
658            | Self::RecipientList { .. }
659            | Self::DeclarativeRecipientList { .. }
660            | Self::Delay { .. }
661            | Self::Loop { .. }
662            | Self::DeclarativeLoop { .. }
663            | Self::Validate { .. }
664            | Self::ClaimCheck { .. }
665            | Self::Sampling { .. }
666            | Self::Sort { .. }
667            | Self::IdempotentConsumer { .. }
668            | Self::Cache { .. }
669            | Self::CacheInvalidate { .. }
670            | Self::CacheClear { .. }
671            | Self::CacheStats { .. }
672            | Self::CachePeekStale { .. }
673            | Self::DeclarativeDoTry { .. }
674            | Self::DoTry { .. }
675            | Self::Layered { .. }
676            | Self::Resequence { .. } => SpanKindHint::Internal,
677        }
678    }
679}
680
681/// Classify an AUTHORED endpoint URI by its scheme — the text before the
682/// first `:`, compared with `eq_ignore_ascii_case`, no endpoint resolution.
683///
684/// Messaging broker schemes map to `Producer` (async, one-way send) and
685/// synchronous outbound protocols to `Client`; every other scheme and
686/// scheme-less URIs stay `Internal` — the kind is never guessed.
687fn uri_span_kind(uri: &str) -> SpanKindHint {
688    /// Broker-style destinations: an async, one-way send.
689    const PRODUCER_SCHEMES: [&str; 5] = ["kafka", "jms", "activemq", "artemis", "mqtt"];
690    /// Synchronous outbound request/response protocols.
691    const CLIENT_SCHEMES: [&str; 12] = [
692        "http",
693        "https",
694        "grpc",
695        "grpcs",
696        "ws",
697        "redis",
698        "opensearch",
699        "sql",
700        "surrealdb",
701        "cxf",
702        "llm",
703        "mcp",
704    ];
705
706    let scheme = uri.split(':').next().unwrap_or_default();
707    if PRODUCER_SCHEMES
708        .iter()
709        .any(|s| s.eq_ignore_ascii_case(scheme))
710    {
711        SpanKindHint::Producer
712    } else if CLIENT_SCHEMES
713        .iter()
714        .any(|s| s.eq_ignore_ascii_case(scheme))
715    {
716        SpanKindHint::Client
717    } else {
718        SpanKindHint::Internal
719    }
720}
721
722/// An unresolved route definition. "to" URIs have not been resolved to producers yet.
723pub struct RouteDefinition {
724    pub(crate) from_uri: String,
725    pub(crate) steps: Vec<BuilderStep>,
726    /// Optional per-route error handler config. Takes precedence over the global one.
727    pub(crate) error_handler: Option<ErrorHandlerConfig>,
728    /// Optional circuit breaker config. Applied between error handler and step pipeline.
729    pub(crate) circuit_breaker: Option<CircuitBreakerConfig>,
730    /// Circuit breaker fallback sub-pipeline, as UNRESOLVED steps.
731    ///
732    /// Sibling of [`RouteDefinition::circuit_breaker`]: the DSL layers thread
733    /// `Vec<BuilderStep>` here (same rule as `cache_peek_stale.on_miss`) and
734    /// camel-core compiles it via the `StepCompilerRegistry` when the route is
735    /// compiled. The resolved `CircuitBreakerConfig.fallback` (`BoxProcessor`)
736    /// stays `None` until that compile — the DSL never constructs processors.
737    pub(crate) circuit_breaker_fallback: Vec<BuilderStep>,
738    pub(crate) security_policy: Option<SecurityPolicyConfig>,
739    /// Optional token authenticator for validating JWT/OAuth tokens.
740    pub(crate) security_authenticator: Option<Arc<dyn TokenAuthenticator>>,
741    /// Named authentication providers for this route, injected into the
742    /// consumer `SecurityContext` so Phase-2 transports can resolve them.
743    pub(crate) provider_registry: Option<Arc<camel_auth::ProviderRegistry>>,
744    /// Declared provider name for plan compilation (`security_policy.provider`
745    /// in the DSL). Resolved against the provider registry at staging time;
746    /// a missing name fails compilation instead of downgrading to `Public`.
747    pub(crate) security_provider: Option<String>,
748    /// Route-level audience override for plan compilation. When present the
749    /// compiled `RouteSecurityPlan.audience_binding` uses these audiences
750    /// (issuers still come from the provider); when absent the resolved
751    /// provider's binding is copied verbatim.
752    pub(crate) security_audiences: Option<Vec<String>>,
753    /// Optional Unit of Work config for in-flight tracking and completion hooks.
754    pub(crate) unit_of_work: Option<UnitOfWorkConfig>,
755    /// Route-level business error to HTTP status mapping
756    /// ([`camel_api::HttpErrorMapping`], business-error-model Task 2.2).
757    /// Set ONLY by the rest-lowering seam (via the DSL compile); camel-core
758    /// installs it as an immutable snapshot on the consumer registration
759    /// ([`camel_component_api::ConsumerContext`]) at start AND resume so the
760    /// transport's reply finalizer maps business errors per route.
761    pub(crate) http_error_mapping: Option<camel_api::HttpErrorMapping>,
762    /// User override for the consumer's concurrency model. `None` means
763    /// "use whatever the consumer declares".
764    pub(crate) concurrency: Option<ConcurrencyModel>,
765    /// Unique identifier for this route. Required.
766    pub(crate) route_id: String,
767    /// Whether this route should start automatically when the context starts.
768    pub(crate) auto_startup: bool,
769    /// Order in which routes are started. Lower values start first.
770    pub(crate) startup_order: i32,
771    pub(crate) source_hash: Option<u64>,
772}
773
774impl RouteDefinition {
775    /// Create a new route definition with the required route ID.
776    pub fn new(from_uri: impl Into<String>, steps: Vec<BuilderStep>) -> Self {
777        Self {
778            from_uri: from_uri.into(),
779            steps,
780            error_handler: None,
781            circuit_breaker: None,
782            circuit_breaker_fallback: Vec::new(),
783            security_policy: None,
784            security_authenticator: None,
785            provider_registry: None,
786            security_provider: None,
787            security_audiences: None,
788            unit_of_work: None,
789            http_error_mapping: None,
790            concurrency: None,
791            route_id: String::new(), // Will be set by with_route_id()
792            auto_startup: true,
793            startup_order: 1000,
794            source_hash: None,
795        }
796    }
797
798    /// The source endpoint URI.
799    pub fn from_uri(&self) -> &str {
800        &self.from_uri
801    }
802
803    /// The steps in this route definition.
804    pub fn steps(&self) -> &[BuilderStep] {
805        &self.steps
806    }
807
808    pub fn circuit_breaker_fallback(&self) -> &[BuilderStep] {
809        &self.circuit_breaker_fallback
810    }
811
812    /// Transform the step list, consuming and returning self.
813    /// Used for post-parse instrumentation (e.g. benchmark timing injection
814    /// around `To` steps). The field stays private; callers rebuild via this
815    /// consuming method rather than holding a `&mut` alias.
816    pub fn map_steps(mut self, f: impl FnOnce(Vec<BuilderStep>) -> Vec<BuilderStep>) -> Self {
817        self.steps = f(self.steps);
818        self
819    }
820
821    /// Set a per-route error handler, overriding the global one.
822    pub fn with_error_handler(mut self, config: ErrorHandlerConfig) -> Self {
823        self.error_handler = Some(config);
824        self
825    }
826
827    /// Get the route-level error handler config, if set.
828    pub fn error_handler_config(&self) -> Option<&ErrorHandlerConfig> {
829        self.error_handler.as_ref()
830    }
831
832    /// Set a circuit breaker for this route.
833    pub fn with_circuit_breaker(mut self, config: CircuitBreakerConfig) -> Self {
834        self.circuit_breaker = Some(config);
835        self
836    }
837
838    /// Set the circuit breaker fallback sub-pipeline (unresolved steps).
839    ///
840    /// Mirror of [`RouteDefinition::with_circuit_breaker`]: the steps are
841    /// compiled by camel-core at route-compile time (registry monopoly) and
842    /// attached to the resolved `CircuitBreakerConfig.fallback`. Empty when no
843    /// CB is configured or the CB has no fallback.
844    pub fn with_circuit_breaker_fallback(mut self, steps: Vec<BuilderStep>) -> Self {
845        self.circuit_breaker_fallback = steps;
846        self
847    }
848
849    /// Set a security policy for this route.
850    pub fn with_security_policy(mut self, config: SecurityPolicyConfig) -> Self {
851        self.security_policy = Some(config);
852        self
853    }
854
855    /// Set a token authenticator for this route.
856    pub fn with_security_authenticator(
857        mut self,
858        authenticator: Arc<dyn TokenAuthenticator>,
859    ) -> Self {
860        self.security_authenticator = Some(authenticator);
861        self
862    }
863
864    /// Set the named authentication providers for this route.
865    ///
866    /// The registry is injected into the consumer `SecurityContext` so
867    /// Phase-2 transports can resolve providers without holding their own
868    /// authenticator.
869    pub fn with_provider_registry(mut self, registry: Arc<camel_auth::ProviderRegistry>) -> Self {
870        self.provider_registry = Some(registry);
871        self
872    }
873
874    /// Set the declared provider name used by plan compilation.
875    pub fn with_security_provider(mut self, name: impl Into<String>) -> Self {
876        self.security_provider = Some(name.into());
877        self
878    }
879
880    /// Set the route-level audience override used by plan compilation.
881    pub fn with_security_audiences(mut self, audiences: Vec<String>) -> Self {
882        self.security_audiences = Some(audiences);
883        self
884    }
885
886    /// The declared provider name, if any.
887    pub fn security_provider(&self) -> Option<&str> {
888        self.security_provider.as_deref()
889    }
890
891    /// The route-level audience override, if any.
892    pub fn security_audiences(&self) -> Option<&[String]> {
893        self.security_audiences.as_deref()
894    }
895
896    /// Set a unit of work config for this route.
897    pub fn with_unit_of_work(mut self, config: UnitOfWorkConfig) -> Self {
898        self.unit_of_work = Some(config);
899        self
900    }
901
902    /// Set the route-level business error to HTTP status mapping
903    /// (business-error-model Task 2.2). Produced by the rest-lowering seam;
904    /// camel-core snapshots it onto the consumer registration at start and
905    /// resume so suspend/resume preserves it.
906    pub fn with_http_error_mapping(mut self, mapping: camel_api::HttpErrorMapping) -> Self {
907        self.http_error_mapping = Some(mapping);
908        self
909    }
910
911    /// The route-level business error mapping, if set.
912    pub fn http_error_mapping(&self) -> Option<&camel_api::HttpErrorMapping> {
913        self.http_error_mapping.as_ref()
914    }
915
916    /// Get the unit of work config, if set.
917    pub fn unit_of_work_config(&self) -> Option<&UnitOfWorkConfig> {
918        self.unit_of_work.as_ref()
919    }
920
921    /// Get the circuit breaker config, if set.
922    pub fn circuit_breaker_config(&self) -> Option<&CircuitBreakerConfig> {
923        self.circuit_breaker.as_ref()
924    }
925
926    pub fn security_policy_config(&self) -> Option<&SecurityPolicyConfig> {
927        self.security_policy.as_ref()
928    }
929
930    pub fn security_authenticator(&self) -> Option<&Arc<dyn TokenAuthenticator>> {
931        self.security_authenticator.as_ref()
932    }
933
934    /// User-specified concurrency override, if any.
935    pub fn concurrency_override(&self) -> Option<&ConcurrencyModel> {
936        self.concurrency.as_ref()
937    }
938
939    /// Override the consumer's concurrency model for this route.
940    pub fn with_concurrency(mut self, model: ConcurrencyModel) -> Self {
941        self.concurrency = Some(model);
942        self
943    }
944
945    /// Get the route ID.
946    pub fn route_id(&self) -> &str {
947        &self.route_id
948    }
949
950    /// Whether this route should start automatically when the context starts.
951    pub fn auto_startup(&self) -> bool {
952        self.auto_startup
953    }
954
955    /// Order in which routes are started. Lower values start first.
956    pub fn startup_order(&self) -> i32 {
957        self.startup_order
958    }
959
960    /// Set a unique identifier for this route.
961    pub fn with_route_id(mut self, id: impl Into<String>) -> Self {
962        self.route_id = id.into();
963        self
964    }
965
966    /// Set whether this route should start automatically.
967    pub fn with_auto_startup(mut self, auto: bool) -> Self {
968        self.auto_startup = auto;
969        self
970    }
971
972    /// Set the startup order. Lower values start first.
973    pub fn with_startup_order(mut self, order: i32) -> Self {
974        self.startup_order = order;
975        self
976    }
977
978    pub fn with_source_hash(mut self, hash: u64) -> Self {
979        self.source_hash = Some(hash);
980        self
981    }
982
983    pub fn source_hash(&self) -> Option<u64> {
984        self.source_hash
985    }
986
987    /// Extract the metadata fields needed for introspection.
988    /// This is used by RouteController to store route info without the non-Sync steps.
989    pub fn to_info(&self) -> RouteDefinitionInfo {
990        RouteDefinitionInfo {
991            route_id: self.route_id.clone(),
992            auto_startup: self.auto_startup,
993            startup_order: self.startup_order,
994            source_hash: self.source_hash,
995        }
996    }
997}
998
999/// Minimal route definition metadata for introspection.
1000///
1001/// This struct contains only the metadata fields from [`RouteDefinition`]
1002/// that are needed for route lifecycle management, without the `steps` field
1003/// (which contains non-Sync types and cannot be stored in a Sync struct).
1004#[derive(Clone)]
1005pub struct RouteDefinitionInfo {
1006    route_id: String,
1007    auto_startup: bool,
1008    startup_order: i32,
1009    pub(crate) source_hash: Option<u64>,
1010}
1011
1012impl RouteDefinitionInfo {
1013    /// Get the route ID.
1014    pub fn route_id(&self) -> &str {
1015        &self.route_id
1016    }
1017
1018    /// Whether this route should start automatically when the context starts.
1019    pub fn auto_startup(&self) -> bool {
1020        self.auto_startup
1021    }
1022
1023    /// Order in which routes are started. Lower values start first.
1024    pub fn startup_order(&self) -> i32 {
1025        self.startup_order
1026    }
1027
1028    pub fn source_hash(&self) -> Option<u64> {
1029        self.source_hash
1030    }
1031}
1032
1033#[cfg(test)]
1034mod tests {
1035    use super::*;
1036    use camel_api::{RecipientSource, TargetSource};
1037
1038    /// Task 1.2 (span-name-enrichment): `BuilderStep::span_label` mapping.
1039    ///
1040    /// `To` labels carry the authored URI scheme (before the first `:`, no
1041    /// interception resolution); EIP variants map to kebab-case EIP names
1042    /// (declarative twins share the label of their programmatic sibling);
1043    /// anonymous variants (opaque processors) carry no label.
1044    #[test]
1045    fn builder_step_span_label_mapping() {
1046        use camel_api::declarative::LanguageExpressionDef;
1047        use camel_api::splitter::AggregationStrategy;
1048        use camel_api::{BoxProcessor, IdentityProcessor, OpaqueProcessor};
1049
1050        let expr = LanguageExpressionDef {
1051            language: "simple".into(),
1052            source: "${body}".into(),
1053        };
1054
1055        // To: scheme is the authored URI before the first ':'.
1056        assert_eq!(
1057            BuilderStep::To("direct:tree-sub".into())
1058                .span_label()
1059                .as_deref(),
1060            Some("to:direct")
1061        );
1062        assert_eq!(
1063            BuilderStep::To("http://api.example/x".into())
1064                .span_label()
1065                .as_deref(),
1066            Some("to:http")
1067        );
1068        // Scheme-less URI: no label — never leak the full text.
1069        assert_eq!(BuilderStep::To("garbage".into()).span_label(), None);
1070
1071        // EIP variants → kebab-case EIP name.
1072        assert_eq!(
1073            BuilderStep::Log {
1074                level: camel_processor::LogLevel::Info,
1075                message: "m".into(),
1076            }
1077            .span_label()
1078            .as_deref(),
1079            Some("log")
1080        );
1081        assert_eq!(
1082            BuilderStep::Split {
1083                config: camel_api::splitter::SplitterConfig::new(
1084                    camel_api::splitter::split_body_lines()
1085                ),
1086                steps: vec![BuilderStep::Stop],
1087            }
1088            .span_label()
1089            .as_deref(),
1090            Some("split")
1091        );
1092        assert_eq!(
1093            BuilderStep::DeclarativeSplit {
1094                expression: expr.clone(),
1095                aggregation: AggregationStrategy::Original,
1096                parallel: false,
1097                parallel_limit: None,
1098                trace_item_threshold: None,
1099                stop_on_exception: true,
1100                steps: vec![BuilderStep::Stop],
1101            }
1102            .span_label()
1103            .as_deref(),
1104            Some("split")
1105        );
1106        assert_eq!(
1107            BuilderStep::DeclarativeStreamSplit {
1108                stream_config: camel_api::StreamSplitConfig::default(),
1109                aggregation: AggregationStrategy::Original,
1110                stop_on_exception: true,
1111                steps: vec![BuilderStep::Stop],
1112            }
1113            .span_label()
1114            .as_deref(),
1115            Some("split")
1116        );
1117        assert_eq!(BuilderStep::Stop.span_label(), None);
1118
1119        // Anonymous variants → None.
1120        assert_eq!(
1121            BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(IdentityProcessor)))
1122                .span_label(),
1123            None
1124        );
1125    }
1126
1127    /// Task 1.2 (span-kind-hint): `BuilderStep::span_kind_hint` mapping.
1128    ///
1129    /// Endpoint-bearing variants (`To`, `Enrich`, `PollEnrich`, `WireTap`)
1130    /// classify the AUTHORED URI scheme (text before the first `:`,
1131    /// compared case-insensitively, no endpoint resolution): messaging
1132    /// brokers map to `Producer`, synchronous outbound protocols to
1133    /// `Client`. Every other scheme, scheme-less URIs, and every
1134    /// non-endpoint variant stay `Internal` route processing. The
1135    /// exhaustive match (no wildcard) in `span_kind_hint` is the rc-4mz7
1136    /// contract: a new `BuilderStep` variant cannot compile without a
1137    /// classification here.
1138    #[test]
1139    fn builder_step_span_kind_hint_mapping() {
1140        use camel_api::splitter::split_body_lines;
1141        use camel_api::{Exchange, FilterPredicate, SpanKindHint};
1142
1143        let kind = |uri: &str| BuilderStep::To(uri.into()).span_kind_hint();
1144
1145        // Messaging brokers → Producer.
1146        assert_eq!(kind("kafka:orders"), SpanKindHint::Producer);
1147        assert_eq!(kind("jms:q"), SpanKindHint::Producer);
1148        assert_eq!(kind("activemq:q"), SpanKindHint::Producer);
1149        assert_eq!(kind("artemis:q"), SpanKindHint::Producer);
1150        assert_eq!(kind("mqtt:t"), SpanKindHint::Producer);
1151        // Scheme comparison is case-insensitive.
1152        assert_eq!(kind("KAFKA:orders"), SpanKindHint::Producer);
1153
1154        // Synchronous outbound protocols → Client.
1155        assert_eq!(kind("http://x"), SpanKindHint::Client);
1156        assert_eq!(kind("https://x"), SpanKindHint::Client);
1157        assert_eq!(kind("grpc://x"), SpanKindHint::Client);
1158        assert_eq!(kind("grpcs://x"), SpanKindHint::Client);
1159        assert_eq!(kind("ws://x"), SpanKindHint::Client);
1160        assert_eq!(kind("redis://x"), SpanKindHint::Client);
1161        assert_eq!(kind("opensearch://x"), SpanKindHint::Client);
1162        assert_eq!(kind("sql:db"), SpanKindHint::Client);
1163        assert_eq!(kind("surrealdb://x"), SpanKindHint::Client);
1164        assert_eq!(kind("cxf://x"), SpanKindHint::Client);
1165        assert_eq!(kind("llm://x"), SpanKindHint::Client);
1166        assert_eq!(kind("mcp://x"), SpanKindHint::Client);
1167
1168        // In-process and unknown schemes → Internal.
1169        assert_eq!(kind("direct:y"), SpanKindHint::Internal);
1170        assert_eq!(kind("timer:z"), SpanKindHint::Internal);
1171        // Scheme-less URI: the kind is never guessed.
1172        assert_eq!(kind("garbage"), SpanKindHint::Internal);
1173
1174        // Non-`To` variants are internal route processing.
1175        assert_eq!(
1176            BuilderStep::Log {
1177                level: camel_processor::LogLevel::Info,
1178                message: "m".into(),
1179            }
1180            .span_kind_hint(),
1181            SpanKindHint::Internal
1182        );
1183        assert_eq!(
1184            BuilderStep::Filter {
1185                predicate: FilterPredicate::new(|_: &Exchange| true),
1186                steps: vec![BuilderStep::Stop],
1187            }
1188            .span_kind_hint(),
1189            SpanKindHint::Internal
1190        );
1191        assert_eq!(
1192            BuilderStep::Split {
1193                config: camel_api::splitter::SplitterConfig::new(split_body_lines()),
1194                steps: vec![BuilderStep::Stop],
1195            }
1196            .span_kind_hint(),
1197            SpanKindHint::Internal
1198        );
1199
1200        // rc-2heu: endpoint-bearing EIP steps share the `To` scheme
1201        // classification. Each covers a Client scheme, a Producer scheme,
1202        // and an Internal (in-process) scheme.
1203        let enrich = |uri: &str| BuilderStep::Enrich {
1204            uri: uri.into(),
1205            strategy: None,
1206            timeout_ms: None,
1207        };
1208        let poll_enrich = |uri: &str| BuilderStep::PollEnrich {
1209            uri: uri.into(),
1210            strategy: None,
1211            timeout_ms: None,
1212        };
1213        let wire_tap = |uri: &str| BuilderStep::WireTap { uri: uri.into() };
1214
1215        // Client scheme.
1216        assert_eq!(enrich("http://x").span_kind_hint(), SpanKindHint::Client);
1217        assert_eq!(
1218            poll_enrich("http://x").span_kind_hint(),
1219            SpanKindHint::Client
1220        );
1221        assert_eq!(wire_tap("http://x").span_kind_hint(), SpanKindHint::Client);
1222        // Producer scheme.
1223        assert_eq!(
1224            enrich("kafka:orders").span_kind_hint(),
1225            SpanKindHint::Producer
1226        );
1227        assert_eq!(
1228            poll_enrich("kafka:orders").span_kind_hint(),
1229            SpanKindHint::Producer
1230        );
1231        assert_eq!(
1232            wire_tap("kafka:orders").span_kind_hint(),
1233            SpanKindHint::Producer
1234        );
1235        // Internal (in-process) scheme.
1236        assert_eq!(enrich("direct:y").span_kind_hint(), SpanKindHint::Internal);
1237        assert_eq!(
1238            poll_enrich("seda:q").span_kind_hint(),
1239            SpanKindHint::Internal
1240        );
1241        assert_eq!(
1242            wire_tap("direct:y").span_kind_hint(),
1243            SpanKindHint::Internal
1244        );
1245    }
1246
1247    /// Golden debug output for EVERY BuilderStep variant.
1248    ///
1249    /// Before refactoring the manual `Debug` impl to `#[derive(Debug)]`, this test
1250    /// locks the exact output of every variant so the refactor can be verified.
1251    #[test]
1252    fn golden_debug_output_all_variants() {
1253        use camel_api::declarative::LanguageExpressionDef;
1254        use camel_api::loop_eip::LoopMode;
1255        use camel_api::recipient_list::RecipientListConfig;
1256        use camel_api::splitter::{AggregationStrategy, StreamSplitConfig, StreamSplitFormat};
1257        use camel_api::{
1258            BoxProcessor, DynamicRouterConfig, Exchange, FilterPredicate, FunctionDefinition,
1259            FunctionId, IdentityProcessor, MulticastConfig, OpaqueProcessor, RoutingSlipConfig,
1260            Value,
1261        };
1262        use std::sync::Arc;
1263
1264        let expr = LanguageExpressionDef {
1265            language: "simple".into(),
1266            source: "${body}".into(),
1267        };
1268
1269        // -- group A: trivial / non-recursive ----------------------------------
1270        // derive(Debug) emits the variant without the enum name for unit/tuple variants.
1271        assert_eq!(format!("{:?}", BuilderStep::Stop), "Stop");
1272        assert_eq!(
1273            format!(
1274                "{:?}",
1275                BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(IdentityProcessor)))
1276            ),
1277            "Processor(BoxProcessor(...))"
1278        );
1279        assert_eq!(
1280            format!("{:?}", BuilderStep::To("mock:out".into())),
1281            "To(\"mock:out\")"
1282        );
1283
1284        // -- group B: variant with named fields (no sub-steps) -----------------
1285        // derive(Debug) emits ALL fields, not the redacted `..` form.
1286        assert_eq!(
1287            format!(
1288                "{:?}",
1289                BuilderStep::Log {
1290                    level: camel_processor::LogLevel::Info,
1291                    message: "hello".into(),
1292                }
1293            ),
1294            "Log { level: Info, message: \"hello\" }"
1295        );
1296
1297        assert_eq!(
1298            format!(
1299                "{:?}",
1300                BuilderStep::DeclarativeSetHeader {
1301                    key: "k".into(),
1302                    value: ValueSourceDef::Literal(Value::String("v".into())),
1303                }
1304            ),
1305            "DeclarativeSetHeader { key: \"k\", value: Literal(String(\"v\")) }"
1306        );
1307
1308        assert_eq!(
1309            format!(
1310                "{:?}",
1311                BuilderStep::DeclarativeSetHeaderIfAbsent {
1312                    key: "k".into(),
1313                    value: ValueSourceDef::Literal(Value::String("v".into())),
1314                }
1315            ),
1316            "DeclarativeSetHeaderIfAbsent { key: \"k\", value: Literal(String(\"v\")) }"
1317        );
1318
1319        assert_eq!(
1320            format!(
1321                "{:?}",
1322                BuilderStep::DeclarativeSetBody {
1323                    value: ValueSourceDef::Literal(Value::String("v".into())),
1324                }
1325            ),
1326            "DeclarativeSetBody { value: Literal(String(\"v\")) }"
1327        );
1328
1329        assert_eq!(
1330            format!(
1331                "{:?}",
1332                BuilderStep::DeclarativeSetProperty {
1333                    key: "prop".into(),
1334                    value_source: ValueSourceDef::Literal(Value::String("v".into())),
1335                }
1336            ),
1337            "DeclarativeSetProperty { key: \"prop\", value_source: Literal(String(\"v\")) }"
1338        );
1339
1340        assert_eq!(
1341            format!(
1342                "{:?}",
1343                BuilderStep::DeclarativeScript {
1344                    expression: expr.clone(),
1345                }
1346            ),
1347            "DeclarativeScript { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" } }"
1348        );
1349
1350        // DeclarativeFunction needs a FunctionDefinition
1351        let func_def = FunctionDefinition {
1352            id: FunctionId("test-id".into()),
1353            runtime: "my_runtime".into(),
1354            source: "${body}".into(),
1355            timeout_ms: 5000,
1356            route_id: None,
1357            step_index: None,
1358        };
1359        assert_eq!(
1360            format!(
1361                "{:?}",
1362                BuilderStep::DeclarativeFunction {
1363                    definition: func_def,
1364                }
1365            ),
1366            "DeclarativeFunction { definition: FunctionDefinition { id: FunctionId(\"test-id\"), runtime: \"my_runtime\", source: \"${body}\", timeout_ms: 5000, route_id: None, step_index: None } }"
1367        );
1368
1369        assert_eq!(
1370            format!(
1371                "{:?}",
1372                BuilderStep::WireTap {
1373                    uri: "mock:tap".into(),
1374                }
1375            ),
1376            "WireTap { uri: \"mock:tap\" }"
1377        );
1378
1379        assert_eq!(
1380            format!(
1381                "{:?}",
1382                BuilderStep::DeclarativeLog {
1383                    level: camel_processor::LogLevel::Info,
1384                    message: ValueSourceDef::Expression(expr.clone()),
1385                }
1386            ),
1387            "DeclarativeLog { level: Info, message: Expression(LanguageExpressionDef { language: \"simple\", source: \"${body}\" }) }"
1388        );
1389
1390        assert_eq!(
1391            format!(
1392                "{:?}",
1393                BuilderStep::Bean {
1394                    name: "myBean".into(),
1395                    method: "process".into(),
1396                }
1397            ),
1398            "Bean { name: \"myBean\", method: \"process\" }"
1399        );
1400
1401        assert_eq!(
1402            format!(
1403                "{:?}",
1404                BuilderStep::Script {
1405                    language: "js".into(),
1406                    script: "body".into(),
1407                }
1408            ),
1409            "Script { language: \"js\", script: \"body\" }"
1410        );
1411
1412        assert_eq!(
1413            format!(
1414                "{:?}",
1415                BuilderStep::Aggregate {
1416                    config: camel_api::AggregatorConfig::correlate_by("id")
1417                        .complete_when_size(1)
1418                        .build()
1419                        .unwrap(),
1420                }
1421            ),
1422            "Aggregate { config: AggregatorConfig { header_name: \"id\", completion: Single(Size(1)), correlation: HeaderName(\"id\"), strategy: CollectAll, max_buckets: Some(10000), max_bucket_size: Some(10000), bucket_ttl: Some(300s), force_completion_on_stop: false, discard_on_timeout: false, max_timeout_tasks: 1024 } }"
1423        );
1424
1425        assert_eq!(
1426            format!(
1427                "{:?}",
1428                BuilderStep::DynamicRouter {
1429                    config: DynamicRouterConfig::new(TargetSource::Sync(Arc::new(
1430                        |_: &Exchange| Some("mock:dr".into())
1431                    ))),
1432                }
1433            ),
1434            "DynamicRouter { config: DynamicRouterConfig { uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false, max_iterations: 1000, timeout: Some(60s) } }"
1435        );
1436
1437        assert_eq!(
1438            format!(
1439                "{:?}",
1440                BuilderStep::RoutingSlip {
1441                    config: RoutingSlipConfig::new(TargetSource::Sync(Arc::new(|_: &Exchange| {
1442                        Some("mock:rs".into())
1443                    }))),
1444                }
1445            ),
1446            "RoutingSlip { config: RoutingSlipConfig { uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false } }"
1447        );
1448
1449        assert_eq!(
1450            format!(
1451                "{:?}",
1452                BuilderStep::RecipientList {
1453                    config: RecipientListConfig::new(RecipientSource::Sync(Arc::new(
1454                        |_: &Exchange| String::new()
1455                    ))),
1456                }
1457            ),
1458            "RecipientList { config: RecipientListConfig { delimiter: \",\", parallel: false, parallel_limit: None, stop_on_exception: false, max_recipients: 1000 } }"
1459        );
1460
1461        assert_eq!(
1462            format!(
1463                "{:?}",
1464                BuilderStep::Enrich {
1465                    uri: "mock:enrich".into(),
1466                    strategy: Some("agg".into()),
1467                    timeout_ms: Some(1000),
1468                }
1469            ),
1470            "Enrich { uri: \"mock:enrich\", strategy: Some(\"agg\"), timeout_ms: Some(1000) }"
1471        );
1472
1473        assert_eq!(
1474            format!(
1475                "{:?}",
1476                BuilderStep::PollEnrich {
1477                    uri: "mock:poll".into(),
1478                    strategy: None,
1479                    timeout_ms: None,
1480                }
1481            ),
1482            "PollEnrich { uri: \"mock:poll\", strategy: None, timeout_ms: None }"
1483        );
1484
1485        assert_eq!(
1486            format!(
1487                "{:?}",
1488                BuilderStep::Validate {
1489                    predicate: expr.clone(),
1490                }
1491            ),
1492            "Validate { predicate: LanguageExpressionDef { language: \"simple\", source: \"${body}\" } }"
1493        );
1494
1495        assert_eq!(
1496            format!("{:?}", BuilderStep::Sampling { period: 100 }),
1497            "Sampling { period: 100 }"
1498        );
1499
1500        assert_eq!(
1501            format!(
1502                "{:?}",
1503                BuilderStep::Resequence {
1504                    policy_config: Default::default(),
1505                }
1506            ),
1507            "Resequence { policy_config: ResequencePolicyConfig { mode: Batch { correlation: \"header.id\", sort: \"header.id\", completion: SizeOrTimeout(100, 30000) } } }"
1508        );
1509
1510        // -- group C: variants with named fields (sub-steps is Vec) ------------
1511        assert_eq!(
1512            format!(
1513                "{:?}",
1514                BuilderStep::DeclarativeFilter {
1515                    predicate: expr.clone(),
1516                    steps: vec![BuilderStep::Stop],
1517                }
1518            ),
1519            "DeclarativeFilter { predicate: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, steps: [Stop] }"
1520        );
1521
1522        assert_eq!(
1523            format!(
1524                "{:?}",
1525                BuilderStep::DeclarativeSplit {
1526                    expression: expr.clone(),
1527                    aggregation: AggregationStrategy::Original,
1528                    parallel: false,
1529                    parallel_limit: Some(2),
1530                    trace_item_threshold: None,
1531                    stop_on_exception: true,
1532                    steps: vec![BuilderStep::Stop],
1533                }
1534            ),
1535            "DeclarativeSplit { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, aggregation: Original, parallel: false, parallel_limit: Some(2), trace_item_threshold: None, stop_on_exception: true, steps: [Stop] }"
1536        );
1537
1538        assert_eq!(
1539            format!(
1540                "{:?}",
1541                BuilderStep::Split {
1542                    config: camel_api::splitter::SplitterConfig::new(
1543                        camel_api::splitter::split_body_lines()
1544                    ),
1545                    steps: vec![BuilderStep::Stop],
1546                }
1547            ),
1548            "Split { config: SplitterConfig { expression: \"<split-expression>\", aggregation: LastWins, parallel: false, parallel_limit: None, stop_on_exception: true, max_fragments: 100000, trace_item_threshold: 100 }, steps: [Stop] }"
1549        );
1550
1551        assert_eq!(
1552            format!(
1553                "{:?}",
1554                BuilderStep::Filter {
1555                    predicate: FilterPredicate::new(|_: &Exchange| true),
1556                    steps: vec![BuilderStep::Stop],
1557                }
1558            ),
1559            "Filter { predicate: FilterPredicate(..), steps: [Stop] }"
1560        );
1561
1562        assert_eq!(
1563            format!(
1564                "{:?}",
1565                BuilderStep::Throttle {
1566                    config: camel_api::ThrottlerConfig::new(
1567                        10,
1568                        std::time::Duration::from_millis(10)
1569                    ),
1570                    steps: vec![BuilderStep::Stop],
1571                }
1572            ),
1573            "Throttle { config: ThrottlerConfig { max_requests: 10, period: 10ms, strategy: Delay }, steps: [Stop] }"
1574        );
1575
1576        assert_eq!(
1577            format!(
1578                "{:?}",
1579                BuilderStep::LoadBalance {
1580                    config: camel_api::LoadBalancerConfig::round_robin(),
1581                    steps: vec![BuilderStep::To("mock:l1".into())],
1582                }
1583            ),
1584            "LoadBalance { config: LoadBalancerConfig { strategy: RoundRobin }, steps: [To(\"mock:l1\")] }"
1585        );
1586
1587        assert_eq!(
1588            format!(
1589                "{:?}",
1590                BuilderStep::Delay {
1591                    config: camel_api::DelayConfig::new(500),
1592                }
1593            ),
1594            "Delay { config: DelayConfig { delay_ms: 500, dynamic_header: None, max_delay_ms: 3600000 } }"
1595        );
1596
1597        // -- group D: Choice / DeclarativeChoice --------------------------------
1598        // derive(Debug) emits full field enumeration; WhenStep Debug is a
1599        // full struct listing; nested BuilderStep::Stop stays as `Stop`.
1600        assert_eq!(
1601            format!(
1602                "{:?}",
1603                BuilderStep::Choice {
1604                    whens: vec![WhenStep {
1605                        predicate: FilterPredicate::new(|_: &Exchange| true),
1606                        steps: vec![BuilderStep::To("mock:a".into())],
1607                    }],
1608                    otherwise: None,
1609                }
1610            ),
1611            "Choice { whens: [WhenStep { predicate: FilterPredicate(..), steps: [To(\"mock:a\")] }], otherwise: None }"
1612        );
1613
1614        assert_eq!(
1615            format!(
1616                "{:?}",
1617                BuilderStep::DeclarativeChoice {
1618                    whens: vec![DeclarativeWhenStep {
1619                        predicate: expr.clone(),
1620                        steps: vec![BuilderStep::Stop],
1621                    }],
1622                    otherwise: Some(vec![BuilderStep::Stop]),
1623                }
1624            ),
1625            "DeclarativeChoice { whens: [DeclarativeWhenStep { predicate: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, steps: [Stop] }], otherwise: Some([Stop]) }"
1626        );
1627
1628        // -- group E: Multicast -------------------------------------------------
1629        assert_eq!(
1630            format!(
1631                "{:?}",
1632                BuilderStep::Multicast {
1633                    steps: vec![BuilderStep::To("direct:a".into())],
1634                    config: MulticastConfig::new(),
1635                }
1636            ),
1637            "Multicast { steps: [To(\"direct:a\")], config: MulticastConfig { parallel: false, parallel_limit: None, stop_on_exception: false, timeout: None, aggregation: LastWins } }"
1638        );
1639
1640        // -- group F: DeclarativeDynamicRouter / DeclarativeRoutingSlip --------
1641        assert_eq!(
1642            format!(
1643                "{:?}",
1644                BuilderStep::DeclarativeDynamicRouter {
1645                    expression: expr.clone(),
1646                    uri_delimiter: ",".into(),
1647                    cache_size: 1000,
1648                    ignore_invalid_endpoints: false,
1649                    max_iterations: 1000,
1650                }
1651            ),
1652            "DeclarativeDynamicRouter { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false, max_iterations: 1000 }"
1653        );
1654
1655        assert_eq!(
1656            format!(
1657                "{:?}",
1658                BuilderStep::DeclarativeRoutingSlip {
1659                    expression: expr.clone(),
1660                    uri_delimiter: ",".into(),
1661                    cache_size: 1000,
1662                    ignore_invalid_endpoints: false,
1663                }
1664            ),
1665            "DeclarativeRoutingSlip { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, uri_delimiter: \",\", cache_size: 1000, ignore_invalid_endpoints: false }"
1666        );
1667
1668        // -- group G: DeclarativeRecipientList ---------------------------------
1669        assert_eq!(
1670            format!(
1671                "{:?}",
1672                BuilderStep::DeclarativeRecipientList {
1673                    expression: expr.clone(),
1674                    delimiter: ",".into(),
1675                    parallel: false,
1676                    parallel_limit: None,
1677                    stop_on_exception: false,
1678                    aggregation: "original".into(),
1679                }
1680            ),
1681            "DeclarativeRecipientList { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, delimiter: \",\", parallel: false, parallel_limit: None, stop_on_exception: false, aggregation: \"original\" }"
1682        );
1683
1684        // -- group H: Loop / DeclarativeLoop -----------------------------------
1685        assert_eq!(
1686            format!(
1687                "{:?}",
1688                BuilderStep::Loop {
1689                    config: camel_api::loop_eip::LoopConfig::new(LoopMode::Count(3)),
1690                    steps: vec![],
1691                }
1692            ),
1693            "Loop { config: LoopConfig { mode: Count(3), max_iterations: 10000 }, steps: [] }"
1694        );
1695
1696        assert_eq!(
1697            format!(
1698                "{:?}",
1699                BuilderStep::DeclarativeLoop {
1700                    count: Some(5),
1701                    while_predicate: None,
1702                    steps: vec![],
1703                    max_iterations: Some(100),
1704                }
1705            ),
1706            "DeclarativeLoop { count: Some(5), while_predicate: None, steps: [], max_iterations: Some(100) }"
1707        );
1708
1709        // -- group I: ClaimCheck -----------------------------------------------
1710        assert_eq!(
1711            format!(
1712                "{:?}",
1713                BuilderStep::ClaimCheck {
1714                    repository: "myRepo".into(),
1715                    operation: "checkout".into(),
1716                    key: expr.clone(),
1717                    filter: None,
1718                }
1719            ),
1720            "ClaimCheck { repository: \"myRepo\", operation: \"checkout\", key: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, filter: None }"
1721        );
1722
1723        // -- group J: Sort -----------------------------------------------------
1724        assert_eq!(
1725            format!(
1726                "{:?}",
1727                BuilderStep::Sort {
1728                    expression: expr.clone(),
1729                    reverse: false,
1730                }
1731            ),
1732            "Sort { expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, reverse: false }"
1733        );
1734
1735        // -- group K: IdempotentConsumer ---------------------------------------
1736        assert_eq!(
1737            format!(
1738                "{:?}",
1739                BuilderStep::IdempotentConsumer {
1740                    repository: "myRepo".into(),
1741                    expression: expr.clone(),
1742                    steps: vec![],
1743                    eager: true,
1744                    remove_on_failure: false,
1745                }
1746            ),
1747            "IdempotentConsumer { repository: \"myRepo\", expression: LanguageExpressionDef { language: \"simple\", source: \"${body}\" }, steps: [], eager: true, remove_on_failure: false }"
1748        );
1749
1750        // -- group L: DeclarativeDoTry -----------------------------------------
1751        assert_eq!(
1752            format!(
1753                "{:?}",
1754                BuilderStep::DeclarativeDoTry {
1755                    try_steps: vec![BuilderStep::Stop],
1756                    catch: vec![],
1757                    finally: None,
1758                }
1759            ),
1760            "DeclarativeDoTry { try_steps: [Stop], catch: [], finally: None }"
1761        );
1762
1763        // -- group M: DeclarativeStreamSplit -----------------------------------
1764        assert_eq!(
1765            format!(
1766                "{:?}",
1767                BuilderStep::DeclarativeStreamSplit {
1768                    stream_config: StreamSplitConfig {
1769                        format: StreamSplitFormat::Ndjson,
1770                        max_record_bytes: 1024 * 1024,
1771                        batch_size: 1,
1772                        chunk_size: None,
1773                        max_parts: None,
1774                        max_part_size: None,
1775                        content_types: None,
1776                        include_origin: true,
1777                    },
1778                    aggregation: AggregationStrategy::Original,
1779                    stop_on_exception: true,
1780                    steps: vec![BuilderStep::Stop],
1781                }
1782            ),
1783            "DeclarativeStreamSplit { stream_config: StreamSplitConfig { format: Ndjson, max_record_bytes: 1048576, batch_size: 1, chunk_size: None, max_parts: None, max_part_size: None, content_types: None, include_origin: true }, aggregation: Original, stop_on_exception: true, steps: [Stop] }"
1784        );
1785    }
1786
1787    #[test]
1788    fn test_builder_step_multicast_variant() {
1789        use camel_api::MulticastConfig;
1790
1791        let step = BuilderStep::Multicast {
1792            steps: vec![BuilderStep::To("direct:a".into())],
1793            config: MulticastConfig::new(),
1794        };
1795
1796        assert!(matches!(step, BuilderStep::Multicast { .. }));
1797    }
1798
1799    #[test]
1800    fn test_route_definition_defaults() {
1801        let def = RouteDefinition::new("direct:test", vec![]).with_route_id("test-route");
1802        assert_eq!(def.route_id(), "test-route");
1803        assert!(def.auto_startup());
1804        assert_eq!(def.startup_order(), 1000);
1805    }
1806
1807    #[test]
1808    fn test_route_definition_builders() {
1809        let def = RouteDefinition::new("direct:test", vec![])
1810            .with_route_id("my-route")
1811            .with_auto_startup(false)
1812            .with_startup_order(50);
1813        assert_eq!(def.route_id(), "my-route");
1814        assert!(!def.auto_startup());
1815        assert_eq!(def.startup_order(), 50);
1816    }
1817
1818    #[test]
1819    fn test_route_definition_accessors_cover_core_fields() {
1820        let def = RouteDefinition::new("direct:in", vec![BuilderStep::To("mock:out".into())])
1821            .with_route_id("accessor-route");
1822
1823        assert_eq!(def.from_uri(), "direct:in");
1824        assert_eq!(def.steps().len(), 1);
1825        assert!(matches!(def.steps()[0], BuilderStep::To(_)));
1826    }
1827
1828    #[test]
1829    fn test_route_definition_error_handler_circuit_breaker_and_concurrency_accessors() {
1830        use camel_api::circuit_breaker::CircuitBreakerConfig;
1831        use camel_api::error_handler::ErrorHandlerConfig;
1832        use camel_component_api::ConcurrencyModel;
1833
1834        let def = RouteDefinition::new("direct:test", vec![])
1835            .with_route_id("eh-route")
1836            .with_error_handler(ErrorHandlerConfig::dead_letter_channel("log:dlc"))
1837            .with_circuit_breaker(CircuitBreakerConfig::new())
1838            .with_concurrency(ConcurrencyModel::Concurrent { max: Some(4) });
1839
1840        let eh = def
1841            .error_handler_config()
1842            .expect("error handler should be set");
1843        assert_eq!(eh.dlc_uri.as_deref(), Some("log:dlc"));
1844        assert!(def.circuit_breaker_config().is_some());
1845        assert!(matches!(
1846            def.concurrency_override(),
1847            Some(ConcurrencyModel::Concurrent { max: Some(4) })
1848        ));
1849    }
1850
1851    #[test]
1852    fn test_builder_step_debug_covers_many_variants() {
1853        use camel_api::splitter::{AggregationStrategy, SplitterConfig, split_body_lines};
1854        use camel_api::{
1855            BoxProcessor, DynamicRouterConfig, Exchange, FilterPredicate, IdentityProcessor,
1856            OpaqueProcessor, RoutingSlipConfig, Value,
1857        };
1858        use std::sync::Arc;
1859
1860        let expr = LanguageExpressionDef {
1861            language: "simple".into(),
1862            source: "${body}".into(),
1863        };
1864
1865        let steps = vec![
1866            BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(IdentityProcessor))),
1867            BuilderStep::To("mock:out".into()),
1868            BuilderStep::Stop,
1869            BuilderStep::Log {
1870                level: camel_processor::LogLevel::Info,
1871                message: "hello".into(),
1872            },
1873            BuilderStep::DeclarativeSetHeader {
1874                key: "k".into(),
1875                value: ValueSourceDef::Literal(Value::String("v".into())),
1876            },
1877            BuilderStep::DeclarativeSetBody {
1878                value: ValueSourceDef::Expression(expr.clone()),
1879            },
1880            BuilderStep::DeclarativeFilter {
1881                predicate: expr.clone(),
1882                steps: vec![BuilderStep::Stop],
1883            },
1884            BuilderStep::DeclarativeChoice {
1885                whens: vec![DeclarativeWhenStep {
1886                    predicate: expr.clone(),
1887                    steps: vec![BuilderStep::Stop],
1888                }],
1889                otherwise: Some(vec![BuilderStep::Stop]),
1890            },
1891            BuilderStep::DeclarativeScript {
1892                expression: expr.clone(),
1893            },
1894            BuilderStep::DeclarativeSplit {
1895                expression: expr.clone(),
1896                aggregation: AggregationStrategy::Original,
1897                parallel: false,
1898                parallel_limit: Some(2),
1899                trace_item_threshold: None,
1900                stop_on_exception: true,
1901                steps: vec![BuilderStep::Stop],
1902            },
1903            BuilderStep::Split {
1904                config: SplitterConfig::new(split_body_lines()),
1905                steps: vec![BuilderStep::Stop],
1906            },
1907            BuilderStep::Aggregate {
1908                config: camel_api::AggregatorConfig::correlate_by("id")
1909                    .complete_when_size(1)
1910                    .build()
1911                    .unwrap(),
1912            },
1913            BuilderStep::Filter {
1914                predicate: FilterPredicate::new(|_: &Exchange| true),
1915                steps: vec![BuilderStep::Stop],
1916            },
1917            BuilderStep::WireTap {
1918                uri: "mock:tap".into(),
1919            },
1920            BuilderStep::DeclarativeLog {
1921                level: camel_processor::LogLevel::Info,
1922                message: ValueSourceDef::Expression(expr.clone()),
1923            },
1924            BuilderStep::Bean {
1925                name: "bean".into(),
1926                method: "call".into(),
1927            },
1928            BuilderStep::Script {
1929                language: "rhai".into(),
1930                script: "body".into(),
1931            },
1932            BuilderStep::Throttle {
1933                config: camel_api::ThrottlerConfig::new(10, std::time::Duration::from_millis(10)),
1934                steps: vec![BuilderStep::Stop],
1935            },
1936            BuilderStep::LoadBalance {
1937                config: camel_api::LoadBalancerConfig::round_robin(),
1938                steps: vec![BuilderStep::To("mock:l1".into())],
1939            },
1940            BuilderStep::DynamicRouter {
1941                config: DynamicRouterConfig::new(TargetSource::Sync(Arc::new(|_| {
1942                    Some("mock:dr".into())
1943                }))),
1944            },
1945            BuilderStep::RoutingSlip {
1946                config: RoutingSlipConfig::new(TargetSource::Sync(Arc::new(|_| {
1947                    Some("mock:rs".into())
1948                }))),
1949            },
1950        ];
1951
1952        for step in steps {
1953            let dbg = format!("{step:?}");
1954            assert!(!dbg.is_empty());
1955        }
1956    }
1957
1958    #[test]
1959    fn test_route_definition_to_info_preserves_metadata() {
1960        let info = RouteDefinition::new("direct:test", vec![])
1961            .with_route_id("meta-route")
1962            .with_auto_startup(false)
1963            .with_startup_order(7)
1964            .to_info();
1965
1966        assert_eq!(info.route_id(), "meta-route");
1967        assert!(!info.auto_startup());
1968        assert_eq!(info.startup_order(), 7);
1969    }
1970
1971    #[test]
1972    fn test_choice_builder_step_debug() {
1973        use camel_api::FilterPredicate;
1974
1975        fn always_true(_: &camel_api::Exchange) -> bool {
1976            true
1977        }
1978
1979        let step = BuilderStep::Choice {
1980            whens: vec![WhenStep {
1981                predicate: FilterPredicate::new(always_true),
1982                steps: vec![BuilderStep::To("mock:a".into())],
1983            }],
1984            otherwise: None,
1985        };
1986        let debug = format!("{step:?}");
1987        assert!(debug.contains("Choice"));
1988    }
1989
1990    #[test]
1991    fn test_route_definition_unit_of_work() {
1992        use camel_api::UnitOfWorkConfig;
1993        let config = UnitOfWorkConfig {
1994            on_complete: Some("log:complete".into()),
1995            on_failure: Some("log:failed".into()),
1996        };
1997        let def = RouteDefinition::new("direct:test", vec![])
1998            .with_route_id("uow-test")
1999            .with_unit_of_work(config.clone());
2000        assert_eq!(
2001            def.unit_of_work_config().unwrap().on_complete.as_deref(),
2002            Some("log:complete")
2003        );
2004        assert_eq!(
2005            def.unit_of_work_config().unwrap().on_failure.as_deref(),
2006            Some("log:failed")
2007        );
2008
2009        let def_no_uow = RouteDefinition::new("direct:test", vec![]).with_route_id("no-uow");
2010        assert!(def_no_uow.unit_of_work_config().is_none());
2011    }
2012
2013    #[test]
2014    fn test_route_definition_security_policy_accessor() {
2015        use async_trait::async_trait;
2016        use camel_api::CamelError;
2017        use camel_api::Exchange;
2018        use camel_api::security_policy::{
2019            AuthContext, AuthorizationDecision, Principal, SecurityPolicy, SecurityPolicyConfig,
2020        };
2021
2022        struct StubPolicy;
2023        #[async_trait]
2024        impl SecurityPolicy for StubPolicy {
2025            async fn evaluate(
2026                &self,
2027                _exchange: &mut Exchange,
2028                _auth: &AuthContext<'_>,
2029            ) -> Result<AuthorizationDecision, CamelError> {
2030                Ok(AuthorizationDecision::Granted {
2031                    principal: Principal {
2032                        subject: "test".into(),
2033                        issuer: "test".into(),
2034                        audience: vec![],
2035                        scopes: vec![],
2036                        roles: vec![],
2037                        claims: serde_json::Value::Null,
2038                    },
2039                })
2040            }
2041        }
2042
2043        let def_no_sp = RouteDefinition::new("direct:test", vec![]).with_route_id("no-sp");
2044        assert!(def_no_sp.security_policy_config().is_none());
2045
2046        let def = RouteDefinition::new("direct:test", vec![])
2047            .with_route_id("sp-test")
2048            .with_security_policy(SecurityPolicyConfig::new(StubPolicy));
2049        assert!(def.security_policy_config().is_some());
2050    }
2051
2052    #[test]
2053    fn test_route_definition_security_authenticator_accessor() {
2054        use camel_api::security_policy::Principal;
2055
2056        struct TestAuth;
2057        #[async_trait::async_trait]
2058        impl TokenAuthenticator for TestAuth {
2059            async fn authenticate_bearer(
2060                &self,
2061                _token: &str,
2062            ) -> Result<Principal, camel_api::CamelError> {
2063                Ok(Principal {
2064                    subject: "test".into(),
2065                    issuer: "test".into(),
2066                    audience: vec![],
2067                    scopes: vec![],
2068                    roles: vec![],
2069                    claims: serde_json::Value::Null,
2070                })
2071            }
2072        }
2073
2074        let def_no_auth = RouteDefinition::new("direct:test".to_string(), vec![]);
2075        assert!(def_no_auth.security_authenticator().is_none());
2076
2077        let auth = Arc::new(TestAuth);
2078        let def = RouteDefinition::new("direct:test".to_string(), vec![])
2079            .with_security_authenticator(auth);
2080        assert!(def.security_authenticator().is_some());
2081    }
2082
2083    #[test]
2084    fn test_map_steps_swaps_steps_and_preserves_other_fields() {
2085        let original = RouteDefinition::new(
2086            "direct:test".to_string(),
2087            vec![BuilderStep::To("mock:a".into()), BuilderStep::Stop],
2088        )
2089        .with_route_id("my-route");
2090
2091        let mapped = original.map_steps(|steps| {
2092            let mut out = Vec::with_capacity(steps.len() + 1);
2093            out.push(BuilderStep::To("mock:prefix".into()));
2094            out.extend(steps);
2095            out
2096        });
2097
2098        // Steps were transformed.
2099        assert_eq!(mapped.steps().len(), 3);
2100        assert!(matches!(mapped.steps()[0], BuilderStep::To(ref s) if s == "mock:prefix"));
2101        assert!(matches!(mapped.steps()[1], BuilderStep::To(ref s) if s == "mock:a"));
2102        // Other fields preserved.
2103        assert_eq!(mapped.route_id(), "my-route");
2104    }
2105
2106    #[test]
2107    fn circuit_breaker_fallback_accessor_returns_steps() {
2108        let def = RouteDefinition::new("direct:start", vec![])
2109            .with_circuit_breaker_fallback(vec![BuilderStep::To("mock:out".into())]);
2110        assert_eq!(def.circuit_breaker_fallback().len(), 1);
2111    }
2112
2113    /// Task 2.1 (builder-layer-middleware): a layered send is still a send.
2114    ///
2115    /// `LayeredTo` must expose the same span label, declared send URI, and
2116    /// span-kind classification as the equivalent plain `To` — the middleware
2117    /// layer never changes the authored endpoint metadata.
2118    #[test]
2119    fn builder_step_layered_to_metadata_parity() {
2120        let layered = BuilderStep::LayeredTo {
2121            uri: "kafka:topic".into(),
2122            factory: LayerFactory::new(tower::limit::ConcurrencyLimitLayer::new(2)),
2123        };
2124        let plain = BuilderStep::To("kafka:topic".into());
2125
2126        assert_eq!(layered.span_label(), Some("to:kafka".to_string()));
2127        assert_eq!(layered.to_uri_metadata(), Some(Arc::from("kafka:topic")));
2128        assert_eq!(layered.span_kind_hint(), SpanKindHint::Producer);
2129
2130        // Parity with the plain send on all three accessors.
2131        assert_eq!(layered.span_label(), plain.span_label());
2132        assert_eq!(layered.to_uri_metadata(), plain.to_uri_metadata());
2133        assert_eq!(layered.span_kind_hint(), plain.span_kind_hint());
2134    }
2135
2136    /// Task 2.1 (builder-layer-middleware): a wrapping layer is not a send.
2137    ///
2138    /// `Layered` carries no endpoint of its own: it labels `layered`, exposes
2139    /// no declared URI, and is internal route processing.
2140    #[test]
2141    fn builder_step_layered_label_and_internal_hint() {
2142        let step = BuilderStep::Layered {
2143            factory: LayerFactory::new(tower::limit::ConcurrencyLimitLayer::new(2)),
2144            steps: vec![],
2145        };
2146
2147        assert_eq!(step.span_label(), Some("layered".to_string()));
2148        assert_eq!(step.to_uri_metadata(), None);
2149        assert_eq!(step.span_kind_hint(), SpanKindHint::Internal);
2150    }
2151}