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