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