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