Skip to main content

camel_builder/
lib.rs

1//! Fluent builder API for constructing Camel routes programmatically with EIP patterns.
2//!
3//! Main types: `RouteBuilder`, `StepAccumulator`, `SectionBuilder`, `SplitBuilder`,
4//! `ChoiceBuilder`, `MulticastBuilder`, `ThrottleBuilder`, `LoopBuilder`,
5//! `LoadBalancerBuilder`, `OnExceptionBuilder`.
6
7use std::collections::BTreeMap;
8use std::sync::Arc;
9
10use camel_api::DelayConfig;
11use camel_api::aggregator::{
12    AggregationStrategy, AggregatorConfig, CompletionCondition, CompletionMode, CorrelationStrategy,
13};
14use camel_api::body::Body;
15use camel_api::body_converter::BodyType;
16use camel_api::circuit_breaker::CircuitBreakerConfig;
17use camel_api::dynamic_router::DynamicRouterConfig;
18use camel_api::error_handler::{ErrorHandlerConfig, RedeliveryPolicy};
19use camel_api::load_balancer::LoadBalancerConfig;
20use camel_api::loop_eip::{LoopConfig, LoopMode};
21use camel_api::multicast::{MulticastConfig, MulticastStrategy};
22use camel_api::recipient_list::RecipientListConfig;
23use camel_api::routing_slip::RoutingSlipConfig;
24use camel_api::splitter::SplitterConfig;
25use camel_api::throttler::{ThrottleStrategy, ThrottlerConfig};
26use camel_api::{
27    BoxProcessor, CamelError, CanonicalRouteSpec, EndpointUri, Exchange, FilterPredicate,
28    IdentityProcessor, LanguageExpressionDef, LayerFactory, OpaqueProcessor, ProcessorFn,
29    ProcessorLayer, Value,
30    runtime::{
31        CanonicalAggregateSpec, CanonicalAggregateStrategySpec, CanonicalCircuitBreakerSpec,
32        CanonicalSplitAggregationSpec, CanonicalSplitExpressionSpec, CanonicalStepSpec,
33        CanonicalTransactedSpec, CanonicalWhenSpec,
34    },
35};
36use camel_component_api::ConcurrencyModel;
37use camel_core::route::{
38    BuilderStep, DeclarativeWhenStep, RouteDefinition, StreamSplitExpression, WhenStep,
39};
40use camel_processor::{
41    ConvertBodyTo, DynamicSetHeader, LogLevel, MapBody, MarshalService, SetHeader,
42    StreamCacheService, UnmarshalService, builtin_data_format,
43};
44
45// ── Module declarations ─────────────────────────────────────────────────────
46pub mod do_try;
47pub use do_try::{DoCatchBuilder, DoFinallyBuilder, DoTryBuilder};
48
49/// Shared step-accumulation methods for all builder types.
50///
51/// Implementors provide `steps_mut()` and get step-adding methods for free.
52/// `filter()` and other branching methods are NOT included — they return
53/// different types per builder and stay as per-builder methods.
54pub trait StepAccumulator: Sized {
55    fn steps_mut(&mut self) -> &mut Vec<BuilderStep>;
56
57    fn to(mut self, endpoint: impl Into<String>) -> Self {
58        self.steps_mut().push(BuilderStep::To(endpoint.into()));
59        self
60    }
61
62    fn process<F, Fut>(mut self, f: F) -> Self
63    where
64        F: Fn(Exchange) -> Fut + Send + Sync + 'static,
65        Fut: std::future::Future<Output = Result<Exchange, CamelError>> + Send + 'static,
66    {
67        let svc = ProcessorFn::new(f);
68        self.steps_mut()
69            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
70                svc,
71            ))));
72        self
73    }
74
75    fn process_fn(mut self, processor: BoxProcessor) -> Self {
76        self.steps_mut()
77            .push(BuilderStep::Processor(OpaqueProcessor(processor)));
78        self
79    }
80
81    fn set_header(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
82        let svc = SetHeader::new(IdentityProcessor, key, value);
83        self.steps_mut()
84            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
85                svc,
86            ))));
87        self
88    }
89
90    fn map_body<F>(mut self, mapper: F) -> Self
91    where
92        F: Fn(Body) -> Body + Clone + Send + Sync + 'static,
93    {
94        let svc = MapBody::new(IdentityProcessor, mapper);
95        self.steps_mut()
96            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
97                svc,
98            ))));
99        self
100    }
101
102    fn set_body<B>(mut self, body: B) -> Self
103    where
104        B: Into<Body> + Clone + Send + Sync + 'static,
105    {
106        let body: Body = body.into();
107        // Static Body (may be Bytes/Stream/Xml): assign directly. The
108        // `SetBody` service is reserved for `Value`-shaped sources —
109        // arbitrary Body variants do not round-trip through `Value`.
110        let svc = ProcessorFn::new(move |mut ex: Exchange| {
111            let body = body.clone();
112            async move {
113                ex.input.body = body;
114                Ok(ex)
115            }
116        });
117        self.steps_mut()
118            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
119                svc,
120            ))));
121        self
122    }
123
124    /// Apache Camel-compatible alias for [`set_body`](Self::set_body).
125    ///
126    /// Transforms the message body using the given value. Semantically identical
127    /// to `set_body` — provided for familiarity with Apache Camel route DSLs.
128    fn transform<B>(self, body: B) -> Self
129    where
130        B: Into<Body> + Clone + Send + Sync + 'static,
131    {
132        self.set_body(body)
133    }
134
135    fn set_body_fn<F>(mut self, expr: F) -> Self
136    where
137        F: Fn(&Exchange) -> Body + Clone + Send + Sync + 'static,
138    {
139        // Body-producing closure: assign directly (see `set_body` for why
140        // this no longer routes through the Value-shaped `SetBody`).
141        let svc = ProcessorFn::new(move |mut ex: Exchange| {
142            let body = expr(&ex);
143            async move {
144                ex.input.body = body;
145                Ok(ex)
146            }
147        });
148        self.steps_mut()
149            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
150                svc,
151            ))));
152        self
153    }
154
155    fn set_header_fn<F>(mut self, key: impl Into<String>, expr: F) -> Self
156    where
157        F: Fn(&Exchange) -> Value + Clone + Send + Sync + 'static,
158    {
159        let svc = DynamicSetHeader::new(
160            IdentityProcessor,
161            key,
162            camel_api::ValueSource::Sync(Arc::new(expr)),
163        );
164        self.steps_mut()
165            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
166                svc,
167            ))));
168        self
169    }
170
171    fn aggregate(mut self, config: AggregatorConfig) -> Self {
172        self.steps_mut().push(BuilderStep::Aggregate { config });
173        self
174    }
175
176    /// Stop processing this exchange immediately. No further steps in the
177    /// current pipeline will run.
178    ///
179    /// Can be used at any point in the route: directly on RouteBuilder,
180    /// inside `.filter()`, inside `.split()`, etc.
181    fn stop(mut self) -> Self {
182        self.steps_mut().push(BuilderStep::Stop);
183        self
184    }
185
186    fn delay(mut self, duration: std::time::Duration) -> Self {
187        self.steps_mut().push(BuilderStep::Delay {
188            config: DelayConfig::from_duration(duration),
189        });
190        self
191    }
192
193    fn delay_with_header(
194        mut self,
195        duration: std::time::Duration,
196        header: impl Into<String>,
197    ) -> Self {
198        self.steps_mut().push(BuilderStep::Delay {
199            config: DelayConfig::from_duration_with_header(duration, header),
200        });
201        self
202    }
203
204    /// Log a message at the specified level.
205    ///
206    /// The message will be logged when an exchange passes through this step.
207    fn log(mut self, message: impl Into<String>, level: LogLevel) -> Self {
208        self.steps_mut().push(BuilderStep::Log {
209            level,
210            message: message.into(),
211        });
212        self
213    }
214
215    /// Convert the message body to the target type.
216    ///
217    /// Supported: Text ↔ Json ↔ Bytes. `Body::Stream` always fails.
218    /// Returns `TypeConversionFailed` if conversion is not possible.
219    ///
220    /// # Example
221    /// ```ignore
222    /// route.set_body(Value::String(r#"{"x":1}"#.into()))
223    ///      .convert_body_to(BodyType::Json)
224    ///      .to("direct:next")
225    /// ```
226    fn convert_body_to(mut self, target: BodyType) -> Self {
227        let svc = ConvertBodyTo::new(IdentityProcessor, target);
228        self.steps_mut()
229            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
230                svc,
231            ))));
232        self
233    }
234
235    fn stream_cache(mut self, threshold: usize) -> Self {
236        let config = camel_api::stream_cache::StreamCacheConfig::new(threshold);
237        let svc = StreamCacheService::new(IdentityProcessor, config);
238        self.steps_mut()
239            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
240                svc,
241            ))));
242        self
243    }
244
245    /// Materialize `Body::Stream` into `Body::Bytes` using the default threshold (128 KB).
246    ///
247    /// Equivalent to `.stream_cache(camel_api::stream_cache::DEFAULT_STREAM_CACHE_THRESHOLD)`.
248    fn stream_cache_default(self) -> Self {
249        self.stream_cache(camel_api::stream_cache::DEFAULT_STREAM_CACHE_THRESHOLD)
250    }
251
252    /// Marshal the message body using the specified data format.
253    ///
254    /// Supported formats: `"json"`, `"xml"`, `"csv"`, `"zip"`, `"tar"`, `"gzip"`, `"tar.gz"`.
255    /// Returns `Err(CamelError::Config)` if the format name is unknown.
256    /// Converts a structured body (e.g., `Body::Json`) to a wire-format body (e.g., `Body::Text`).
257    ///
258    /// # Example
259    /// ```ignore
260    /// route.marshal("json")?.to("direct:next")
261    /// ```
262    fn marshal(mut self, format: impl Into<String>) -> Result<Self, CamelError> {
263        let name = format.into();
264        let df = builtin_data_format(&name)
265            .ok_or_else(|| CamelError::Config(format!("unknown data format: '{name}'")))?;
266        let svc = MarshalService::new(IdentityProcessor, df);
267        self.steps_mut()
268            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
269                svc,
270            ))));
271        Ok(self)
272    }
273
274    /// Unmarshal the message body using the specified data format.
275    ///
276    /// Supported formats: `"json"`, `"xml"`, `"csv"`, `"zip"`, `"tar"`, `"gzip"`, `"tar.gz"`.
277    /// Returns `Err(CamelError::Config)` if the format name is unknown.
278    /// Converts a wire-format body (e.g., `Body::Text`) to a structured body (e.g., `Body::Json`).
279    ///
280    /// # Example
281    /// ```ignore
282    /// route.unmarshal("json")?.to("direct:next")
283    /// ```
284    fn unmarshal(mut self, format: impl Into<String>) -> Result<Self, CamelError> {
285        let name = format.into();
286        let df = builtin_data_format(&name)
287            .ok_or_else(|| CamelError::Config(format!("unknown data format: '{name}'")))?;
288        let svc = UnmarshalService::new(IdentityProcessor, df);
289        self.steps_mut()
290            .push(BuilderStep::Processor(OpaqueProcessor(BoxProcessor::new(
291                svc,
292            ))));
293        Ok(self)
294    }
295
296    /// Validate the exchange using a predicate expression.
297    ///
298    /// If the expression evaluates to `true`, the exchange continues.
299    /// If `false`, a `CamelError::ValidationError` is returned into the route error handler.
300    ///
301    /// # Example
302    /// ```ignore
303    /// route.validate("${body} != null").to("direct:out")
304    /// ```
305    fn validate(mut self, expression: impl Into<String>) -> Self {
306        let source = expression.into();
307        let expression = LanguageExpressionDef {
308            language: "simple".into(),
309            source,
310        };
311        self.steps_mut().push(BuilderStep::Validate {
312            predicate: expression,
313        });
314        self
315    }
316
317    /// Execute a script that can modify the exchange (headers, properties, body).
318    ///
319    /// The script has access to `headers`, `properties`, and `body` variables
320    /// and can modify them with assignment syntax: `headers["k"] = v`.
321    ///
322    /// # Example
323    /// ```ignore
324    /// // ignore: requires full CamelContext setup with registered language
325    /// route.script("rhai", r#"headers["tenant"] = "acme"; body = body + "_processed""#)
326    /// ```
327    fn script(mut self, language: impl Into<String>, script: impl Into<String>) -> Self {
328        self.steps_mut().push(BuilderStep::Script {
329            language: language.into(),
330            script: script.into(),
331        });
332        self
333    }
334
335    /// EIP-7 enrich: synchronous content enrichment via a resolved producer.
336    ///
337    /// Calls the given endpoint URI as a producer, then merges the response
338    /// back into the original exchange body using the default `UseEnrichedBody`
339    /// strategy (original headers/properties are preserved).
340    fn enrich(mut self, uri: impl Into<String>) -> Self {
341        self.steps_mut().push(BuilderStep::Enrich {
342            uri: uri.into(),
343            strategy: None,
344            timeout_ms: None,
345        });
346        self
347    }
348
349    /// EIP-7 pollEnrich: blocking poll of a PollingConsumer with timeout.
350    ///
351    /// Reads from a polling endpoint (e.g., file) and merges the result
352    /// into the exchange body using the default `UseEnrichedBody` strategy.
353    /// `timeout_ms` controls how long to wait for data.
354    fn poll_enrich(mut self, uri: impl Into<String>, timeout_ms: u64) -> Self {
355        self.steps_mut().push(BuilderStep::PollEnrich {
356            uri: uri.into(),
357            strategy: None,
358            timeout_ms: Some(timeout_ms),
359        });
360        self
361    }
362
363    fn bean(mut self, name: impl Into<String>, method: impl Into<String>) -> Self {
364        self.steps_mut().push(BuilderStep::Bean {
365            name: name.into(),
366            method: method.into(),
367        });
368        self
369    }
370
371    /// Send to `uri` through a Tower middleware layer.
372    ///
373    /// The layer wraps the producer resolved for `uri` at route-add time. For
374    /// span and latency metadata the step is still a send, so it mirrors
375    /// [`to`](Self::to).
376    ///
377    /// # Example
378    ///
379    /// ```
380    /// use camel_builder::{RouteBuilder, StepAccumulator};
381    /// use camel_core::route::BuilderStep;
382    /// use tower::limit::ConcurrencyLimitLayer;
383    ///
384    /// let route = RouteBuilder::from("direct:a")
385    ///     .route_id("doctest")
386    ///     .to_layered("mock:b", ConcurrencyLimitLayer::new(2))
387    ///     .build()
388    ///     .unwrap();
389    ///
390    /// match &route.steps()[0] {
391    ///     BuilderStep::LayeredTo { uri, .. } => assert_eq!(uri, "mock:b"),
392    ///     other => panic!("expected LayeredTo, got {other:?}"),
393    /// }
394    /// ```
395    fn to_layered(mut self, uri: impl Into<String>, layer: impl ProcessorLayer + 'static) -> Self {
396        self.steps_mut().push(BuilderStep::LayeredTo {
397            uri: uri.into(),
398            factory: LayerFactory::new(layer),
399        });
400        self
401    }
402
403    /// Wrap a nested sub-pipeline in a Tower middleware layer.
404    ///
405    /// The closure receives a [`SectionBuilder`] — a step accumulator without
406    /// route metadata, `.parameters()`, `.route_layer()` or `.build()` — so the
407    /// scope can only add steps. Nested [`layered`](Self::layered) calls work.
408    ///
409    /// The section's steps run as ONE segment wrapped by `layer`:
410    ///
411    /// - [`stop`](Self::stop) inside the section stops the route.
412    /// - The route error handler treats the section as one retry unit.
413    ///
414    /// # Example
415    ///
416    /// A single-step section:
417    ///
418    /// ```
419    /// use camel_builder::{RouteBuilder, StepAccumulator};
420    /// use camel_core::route::BuilderStep;
421    /// use tower::limit::ConcurrencyLimitLayer;
422    ///
423    /// let route = RouteBuilder::from("direct:a")
424    ///     .route_id("doctest")
425    ///     .layered(ConcurrencyLimitLayer::new(2), |section| section.to("mock:1"))
426    ///     .build()
427    ///     .unwrap();
428    ///
429    /// match &route.steps()[0] {
430    ///     BuilderStep::Layered { steps, .. } => {
431    ///         assert!(matches!(steps[0], BuilderStep::To(_)));
432    ///     }
433    ///     other => panic!("expected Layered, got {other:?}"),
434    /// }
435    /// ```
436    ///
437    /// See [`SectionBuilder`] for nested sections.
438    fn layered(
439        mut self,
440        layer: impl ProcessorLayer + 'static,
441        section: impl FnOnce(SectionBuilder) -> SectionBuilder,
442    ) -> Self {
443        let section_builder = section(SectionBuilder::new());
444        self.steps_mut().push(BuilderStep::Layered {
445            factory: LayerFactory::new(layer),
446            steps: section_builder.into_steps(),
447        });
448        self
449    }
450}
451
452/// Step accumulator handed to the closure of [`StepAccumulator::layered`].
453///
454/// A `SectionBuilder` inherits every step-adding method from
455/// [`StepAccumulator`] (`to`, `process`, `set_header`, `map_body`, nested
456/// `to_layered`/`layered`, `stop`, …) but deliberately exposes **no**
457/// `.parameters()`, **no** `.route_layer()` and **no** `.build()`, and carries
458/// no route metadata. Deferred-parameter and whole-route-middleware misuse
459/// therefore cannot be expressed inside a section.
460///
461/// # Example
462///
463/// Nested sections produce nested [`BuilderStep::Layered`] steps:
464///
465/// ```
466/// use camel_builder::{RouteBuilder, StepAccumulator};
467/// use camel_core::route::BuilderStep;
468/// use tower::limit::ConcurrencyLimitLayer;
469///
470/// let route = RouteBuilder::from("direct:a")
471///     .route_id("doctest")
472///     .layered(ConcurrencyLimitLayer::new(2), |section| {
473///         section.layered(ConcurrencyLimitLayer::new(3), |inner| {
474///             inner.to_layered("mock:b", ConcurrencyLimitLayer::new(4))
475///         })
476///     })
477///     .build()
478///     .unwrap();
479///
480/// match &route.steps()[0] {
481///     BuilderStep::Layered { steps, .. } => match &steps[0] {
482///         BuilderStep::Layered { steps, .. } => {
483///             assert!(matches!(steps[0], BuilderStep::LayeredTo { .. }));
484///         }
485///         other => panic!("expected nested Layered, got {other:?}"),
486///     },
487///     other => panic!("expected Layered, got {other:?}"),
488/// }
489/// ```
490pub struct SectionBuilder {
491    steps: Vec<BuilderStep>,
492}
493
494impl SectionBuilder {
495    pub(crate) fn new() -> Self {
496        Self { steps: Vec::new() }
497    }
498
499    pub(crate) fn into_steps(self) -> Vec<BuilderStep> {
500        self.steps
501    }
502}
503
504impl StepAccumulator for SectionBuilder {
505    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
506        &mut self.steps
507    }
508}
509
510/// Identifies the endpoint slot a `.parameters()` call attaches to.
511#[derive(Debug, Clone, PartialEq, Eq)]
512enum EndpointSlot {
513    /// The route's `from` endpoint.
514    From,
515    /// A step in `RouteBuilder::steps`, by index.
516    Step(usize),
517}
518
519/// A fluent builder for constructing routes.
520///
521/// # Example
522///
523/// ```ignore
524/// let definition = RouteBuilder::from("timer:tick?period=1000")
525///     .set_header("source", Value::String("timer".into()))
526///     .filter(|ex| ex.input.body.as_text().is_some())
527///     .to("log:info?showHeaders=true")
528///     .build()?;
529/// ```
530/// `RouteBuilder` is `Clone`: a partially-built route can be cloned and reused as a
531/// template for multiple routes (mirrors Apache Camel's cloneable `RouteBuilder`).
532/// Clone is a deep copy of the step list; step closures live behind `Arc`/`BoxProcessor`
533/// so cloning shares the closure and duplicates only the light wrapper (rc-8m5o).
534#[derive(Clone)]
535pub struct RouteBuilder {
536    from_uri: String,
537    steps: Vec<BuilderStep>,
538    /// Whole-route middleware layers, in call order (first added is innermost).
539    route_layers: Vec<LayerFactory>,
540    /// Pending `.parameters()` maps, each attached to a specific endpoint slot.
541    parameter_assignments: Vec<(EndpointSlot, BTreeMap<String, String>)>,
542    /// Misuse recorded at `.parameters()` call time and surfaced at `build()`.
543    parameter_misuse: Option<String>,
544    error_handler: Option<ErrorHandlerConfig>,
545    error_handler_mode: ErrorHandlerMode,
546    circuit_breaker_config: Option<CircuitBreakerConfig>,
547    security_policy_config: Option<camel_api::security_policy::SecurityPolicyConfig>,
548    security_authenticator: Option<std::sync::Arc<dyn camel_auth::TokenAuthenticator>>,
549    provider_registry: Option<std::sync::Arc<camel_auth::ProviderRegistry>>,
550    concurrency: Option<ConcurrencyModel>,
551    route_id: Option<String>,
552    auto_startup: Option<bool>,
553    startup_order: Option<i32>,
554}
555
556#[derive(Default, Clone)]
557enum ErrorHandlerMode {
558    #[default]
559    None,
560    ExplicitConfig,
561    Shorthand {
562        dlc_uri: Option<String>,
563        specs: Vec<OnExceptionSpec>,
564    },
565    Mixed,
566}
567
568#[derive(Clone)]
569struct OnExceptionSpec {
570    matches: std::sync::Arc<dyn Fn(&CamelError) -> bool + Send + Sync>,
571    retry: Option<RedeliveryPolicy>,
572    handled_by: Option<String>,
573}
574
575impl RouteBuilder {
576    /// Start building a route from the given source endpoint URI.
577    pub fn from(endpoint: &str) -> Self {
578        Self {
579            from_uri: endpoint.to_string(),
580            steps: Vec::new(),
581            route_layers: Vec::new(),
582            parameter_assignments: Vec::new(),
583            parameter_misuse: None,
584            error_handler: None,
585            error_handler_mode: ErrorHandlerMode::None,
586            circuit_breaker_config: None,
587            security_policy_config: None,
588            security_authenticator: None,
589            provider_registry: None,
590            concurrency: None,
591            route_id: None,
592            auto_startup: None,
593            startup_order: None,
594        }
595    }
596
597    /// Open a filter scope. Only exchanges matching `predicate` will be processed
598    /// by the steps inside the scope. Non-matching exchanges skip the scope entirely
599    /// and continue to steps after `.end_filter()`.
600    pub fn filter<F>(self, predicate: F) -> FilterBuilder
601    where
602        F: Fn(&Exchange) -> bool + Send + Sync + 'static,
603    {
604        FilterBuilder {
605            parent: self,
606            predicate: camel_api::FilterPredicate::new(predicate),
607            steps: vec![],
608        }
609    }
610
611    /// Open a choice scope for content-based routing.
612    ///
613    /// Within the choice, you can define multiple `.when()` clauses and an
614    /// optional `.otherwise()` clause. The first matching `when` predicate
615    /// determines which sub-pipeline executes.
616    pub fn choice(self) -> ChoiceBuilder {
617        ChoiceBuilder {
618            parent: self,
619            whens: vec![],
620            _otherwise: None,
621        }
622    }
623
624    /// Add a WireTap step that sends a clone of the exchange to the given
625    /// endpoint URI (fire-and-forget). The original exchange continues
626    /// downstream unchanged.
627    pub fn wire_tap(mut self, endpoint: &str) -> Self {
628        self.steps.push(BuilderStep::WireTap {
629            uri: endpoint.to_string(),
630        });
631        self
632    }
633
634    /// Attach a `parameters:` map to the most recent endpoint slot — the `from`
635    /// endpoint when called before any step, otherwise the last added step.
636    ///
637    /// Parameters on different endpoints each persist independently; none
638    /// overwrites another. Misuse (a second `.parameters()` on the same slot,
639    /// or a call with no pending endpoint step) is deferred and surfaced as a
640    /// `CamelError::RouteError` at `build()` / `build_canonical()`, never a panic.
641    pub fn parameters(mut self, params: BTreeMap<String, String>) -> Self {
642        let slot = if self.steps.is_empty() {
643            EndpointSlot::From
644        } else {
645            EndpointSlot::Step(self.steps.len() - 1)
646        };
647
648        if self
649            .parameter_assignments
650            .iter()
651            .any(|(existing, _)| *existing == slot)
652        {
653            self.parameter_misuse =
654                Some("multiple .parameters() calls attached to the same endpoint".to_string());
655        } else if !endpoint_slot_bears_uri(&slot, &self.steps) {
656            self.parameter_misuse =
657                Some(".parameters() called with no pending endpoint step".to_string());
658        }
659
660        self.parameter_assignments.push((slot, params));
661        self
662    }
663
664    /// Set a per-route error handler. Overrides the global error handler on `CamelContext`.
665    pub fn error_handler(mut self, config: ErrorHandlerConfig) -> Self {
666        self.error_handler_mode = match self.error_handler_mode {
667            ErrorHandlerMode::None | ErrorHandlerMode::ExplicitConfig => {
668                ErrorHandlerMode::ExplicitConfig
669            }
670            ErrorHandlerMode::Shorthand { .. } | ErrorHandlerMode::Mixed => ErrorHandlerMode::Mixed,
671        };
672        self.error_handler = Some(config);
673        self
674    }
675
676    /// Set a dead letter channel URI for shorthand error handler mode.
677    pub fn dead_letter_channel(mut self, uri: impl Into<String>) -> Self {
678        let uri = uri.into();
679        self.error_handler_mode = match self.error_handler_mode {
680            ErrorHandlerMode::None => ErrorHandlerMode::Shorthand {
681                dlc_uri: Some(uri),
682                specs: Vec::new(),
683            },
684            ErrorHandlerMode::Shorthand { specs, .. } => ErrorHandlerMode::Shorthand {
685                dlc_uri: Some(uri),
686                specs,
687            },
688            ErrorHandlerMode::ExplicitConfig | ErrorHandlerMode::Mixed => ErrorHandlerMode::Mixed,
689        };
690        self
691    }
692
693    /// Add a shorthand exception policy scope. Call `.end_on_exception()` to return to route builder.
694    pub fn on_exception<F>(mut self, matches: F) -> OnExceptionBuilder
695    where
696        F: Fn(&CamelError) -> bool + Send + Sync + 'static,
697    {
698        self.error_handler_mode = match self.error_handler_mode {
699            ErrorHandlerMode::None => ErrorHandlerMode::Shorthand {
700                dlc_uri: None,
701                specs: Vec::new(),
702            },
703            ErrorHandlerMode::ExplicitConfig | ErrorHandlerMode::Mixed => ErrorHandlerMode::Mixed,
704            shorthand @ ErrorHandlerMode::Shorthand { .. } => shorthand,
705        };
706
707        OnExceptionBuilder {
708            parent: self,
709            policy: OnExceptionSpec {
710                matches: std::sync::Arc::new(matches),
711                retry: None,
712                handled_by: None,
713            },
714        }
715    }
716
717    /// Set a circuit breaker for this route.
718    pub fn circuit_breaker(mut self, config: CircuitBreakerConfig) -> Self {
719        self.circuit_breaker_config = Some(config);
720        self
721    }
722
723    pub fn security_policy(
724        mut self,
725        config: camel_api::security_policy::SecurityPolicyConfig,
726    ) -> Self {
727        self.security_policy_config = Some(config);
728        self
729    }
730
731    pub fn security_authenticator(
732        mut self,
733        auth: std::sync::Arc<dyn camel_auth::TokenAuthenticator>,
734    ) -> Self {
735        self.security_authenticator = Some(auth);
736        self
737    }
738
739    /// Named provider registry for security plan compilation (ADR-0061):
740    /// routes declaring security resolve their provider here; staging
741    /// aborts when the registry cannot satisfy the declaration.
742    pub fn provider_registry(
743        mut self,
744        registry: std::sync::Arc<camel_auth::ProviderRegistry>,
745    ) -> Self {
746        self.provider_registry = Some(registry);
747        self
748    }
749
750    /// Override the consumer's default concurrency model.
751    ///
752    /// When set, the pipeline spawns a task per exchange, processing them
753    /// concurrently. `max` limits the number of simultaneously active
754    /// pipeline executions (0 = unbounded, channel buffer is backpressure).
755    ///
756    /// # Example
757    /// ```ignore
758    /// RouteBuilder::from("http://0.0.0.0:8080/api")
759    ///     .concurrent(16)  // max 16 in-flight pipeline executions
760    ///     .process(handle_request)
761    ///     .build()
762    /// ```
763    pub fn concurrent(mut self, max: usize) -> Self {
764        let max = if max == 0 { None } else { Some(max) };
765        self.concurrency = Some(ConcurrencyModel::Concurrent { max });
766        self
767    }
768
769    /// Force sequential processing, overriding a concurrent-capable consumer.
770    ///
771    /// Useful for HTTP routes that mutate shared state and need ordering
772    /// guarantees.
773    pub fn sequential(mut self) -> Self {
774        self.concurrency = Some(ConcurrencyModel::Sequential);
775        self
776    }
777
778    /// Set the route ID for this route.
779    ///
780    /// If not set, the route will be assigned an auto-generated ID.
781    pub fn route_id(mut self, id: impl Into<String>) -> Self {
782        self.route_id = Some(id.into());
783        self
784    }
785
786    /// Set whether this route should automatically start when the context starts.
787    ///
788    /// Default is `true`.
789    pub fn auto_startup(mut self, auto: bool) -> Self {
790        self.auto_startup = Some(auto);
791        self
792    }
793
794    /// Set the startup order for this route.
795    ///
796    /// Routes with lower values start first. Default is 1000.
797    pub fn startup_order(mut self, order: i32) -> Self {
798        self.startup_order = Some(order);
799        self
800    }
801
802    /// Begin a Splitter sub-pipeline. Steps added after this call (until
803    /// `.end_split()`) will be executed per-fragment.
804    ///
805    /// Returns a `SplitBuilder` — you cannot call `.build()` until
806    /// `.end_split()` closes the split scope (enforced by the type system).
807    pub fn split(self, config: SplitterConfig) -> SplitBuilder {
808        SplitBuilder {
809            parent: self,
810            config,
811            steps: Vec::new(),
812        }
813    }
814
815    /// Begin a streaming-split sub-pipeline. The caller supplies the fragment
816    /// expression directly (e.g. built from `camel_processor::stream_codec` or
817    /// `zip_splitter`); steps added after this call (until `.end_stream_split()`)
818    /// run once per fragment. Defaults: aggregation `LastWins`,
819    /// `stop_on_exception` true.
820    ///
821    /// Returns a `StreamSplitBuilder` — you cannot call `.build()` until
822    /// `.end_stream_split()` closes the split scope (enforced by the type system).
823    pub fn stream_split(
824        self,
825        expression: camel_api::StreamingSplitExpression,
826    ) -> StreamSplitBuilder {
827        StreamSplitBuilder {
828            parent: self,
829            expression: expression.into(),
830            aggregation: camel_api::splitter::AggregationStrategy::LastWins,
831            stop_on_exception: true,
832            steps: Vec::new(),
833        }
834    }
835
836    /// Begin a Multicast sub-pipeline. Steps added after this call (until
837    /// `.end_multicast()`) will each receive a copy of the exchange.
838    ///
839    /// Returns a `MulticastBuilder` — you cannot call `.build()` until
840    /// `.end_multicast()` closes the multicast scope (enforced by the type system).
841    pub fn multicast(self) -> MulticastBuilder {
842        MulticastBuilder {
843            parent: self,
844            steps: Vec::new(),
845            config: MulticastConfig::new(),
846        }
847    }
848
849    /// Add a transacted database block.
850    ///
851    /// Every step in `steps` runs inside one database transaction bound to
852    /// `datasource`. Unlike [`split`](Self::split) and
853    /// [`multicast`](Self::multicast) there is no sub-builder: a block exposes
854    /// no configuration beyond its datasource and body, so the steps are
855    /// passed inline.
856    ///
857    /// Dark in slice 1: nothing registers a transaction manager, so a route
858    /// carrying this block fails closed at start with
859    /// `TransactionError::ManagerMissing`; camel-sql registers managers in
860    /// slice 2 (`rc-qv2iz.6`).
861    ///
862    /// # Example
863    /// ```ignore
864    /// RouteBuilder::from("direct:orders")
865    ///     .route_id("orders")
866    ///     .transacted("pg", [
867    ///         BuilderStep::To("sql:insert into orders values (1)?datasource=pg".into()),
868    ///         BuilderStep::To("sql:insert into audit values (1)?datasource=pg".into()),
869    ///     ])
870    ///     .build()
871    /// ```
872    pub fn transacted(
873        mut self,
874        datasource: impl Into<String>,
875        steps: impl IntoIterator<Item = impl Into<BuilderStep>>,
876    ) -> Self {
877        self.steps.push(BuilderStep::Transacted {
878            datasource: datasource.into(),
879            steps: steps.into_iter().map(Into::into).collect(),
880        });
881        self
882    }
883
884    /// Begin a Throttle sub-pipeline. Rate limits message processing to at most
885    /// `max_requests` per `period`. Steps inside the throttle scope are only
886    /// executed when the rate limit allows.
887    ///
888    /// Returns a `ThrottleBuilder` — you cannot call `.build()` until
889    /// `.end_throttle()` closes the throttle scope (enforced by the type system).
890    pub fn throttle(self, max_requests: usize, period: std::time::Duration) -> ThrottleBuilder {
891        ThrottleBuilder {
892            parent: self,
893            config: ThrottlerConfig::new(max_requests, period),
894            steps: Vec::new(),
895        }
896    }
897
898    /// Begin a Loop sub-pipeline that iterates a fixed number of times.
899    pub fn loop_count(self, count: usize) -> LoopBuilder {
900        LoopBuilder {
901            parent: self,
902            config: LoopConfig::new(LoopMode::Count(count)),
903            steps: vec![],
904        }
905    }
906
907    /// Begin a Loop sub-pipeline that iterates while a predicate is true.
908    pub fn loop_while<F>(self, predicate: F) -> LoopBuilder
909    where
910        F: Fn(&Exchange) -> bool + Send + Sync + 'static,
911    {
912        LoopBuilder {
913            parent: self,
914            config: LoopConfig::new(LoopMode::While(camel_api::PredicateSource::Sync(
915                camel_api::FilterPredicate::new(predicate),
916            ))),
917            steps: vec![],
918        }
919    }
920
921    /// Begin a LoadBalance sub-pipeline. Distributes exchanges across multiple
922    /// endpoints using a configurable strategy (round-robin, random, weighted, failover).
923    ///
924    /// Returns a `LoadBalancerBuilder` — you cannot call `.build()` until
925    /// `.end_load_balance()` closes the load balance scope (enforced by the type system).
926    pub fn load_balance(self) -> LoadBalancerBuilder {
927        LoadBalancerBuilder {
928            parent: self,
929            config: LoadBalancerConfig::round_robin(),
930            steps: Vec::new(),
931        }
932    }
933
934    /// Add a dynamic router step that routes exchanges dynamically based on
935    /// expression evaluation at runtime.
936    ///
937    /// The expression source resolves each exchange to `Some(uri)` to route
938    /// to the next endpoint, or `None` to stop routing. Language-backed
939    /// fallible sources are built with `TargetSource::Async`; evaluation
940    /// failures fail the step instead of silently stopping the route.
941    ///
942    /// # Example
943    /// ```ignore
944    /// RouteBuilder::from("timer:tick")
945    ///     .route_id("test-route")
946    ///     .dynamic_router(TargetSource::Sync(Arc::new(|ex| {
947    ///         ex.input.header("dest").and_then(|v| v.as_str().map(|s| s.to_string()))
948    ///     })))
949    ///     .build()
950    /// ```
951    pub fn dynamic_router(self, expression: impl Into<camel_api::TargetSource>) -> Self {
952        self.dynamic_router_with_config(DynamicRouterConfig::new(expression))
953    }
954
955    /// Add a dynamic router step with full configuration.
956    ///
957    /// Allows customization of URI delimiter, cache size, timeout, and other options.
958    pub fn dynamic_router_with_config(mut self, config: DynamicRouterConfig) -> Self {
959        self.steps.push(BuilderStep::DynamicRouter { config });
960        self
961    }
962
963    pub fn routing_slip(self, expression: impl Into<camel_api::TargetSource>) -> Self {
964        self.routing_slip_with_config(RoutingSlipConfig::new(expression))
965    }
966
967    pub fn routing_slip_with_config(mut self, config: RoutingSlipConfig) -> Self {
968        self.steps.push(BuilderStep::RoutingSlip { config });
969        self
970    }
971
972    pub fn recipient_list(self, expression: impl Into<camel_api::RecipientSource>) -> Self {
973        self.recipient_list_with_config(RecipientListConfig::new(expression))
974    }
975
976    pub fn recipient_list_with_config(mut self, config: RecipientListConfig) -> Self {
977        self.steps.push(BuilderStep::RecipientList { config });
978        self
979    }
980
981    /// Wrap the whole route in a Tower middleware layer.
982    ///
983    /// Repeated calls nest: each added layer wraps the previously wrapped
984    /// route, so the last-added layer is the OUTERMOST. The whole compiled
985    /// route becomes ONE wrapped unit for the error handler.
986    ///
987    /// # Example
988    ///
989    /// ```
990    /// use camel_builder::{RouteBuilder, StepAccumulator};
991    /// use camel_core::route::BuilderStep;
992    /// use tower::limit::ConcurrencyLimitLayer;
993    ///
994    /// let route = RouteBuilder::from("direct:a")
995    ///     .route_id("doctest")
996    ///     .to("mock:b")
997    ///     .route_layer(ConcurrencyLimitLayer::new(2))
998    ///     .route_layer(ConcurrencyLimitLayer::new(5))
999    ///     .build()
1000    ///     .unwrap();
1001    ///
1002    /// // The last-added layer is the outermost wrapper.
1003    /// match &route.steps()[0] {
1004    ///     BuilderStep::Layered { steps, .. } => {
1005    ///         assert!(matches!(&steps[0], BuilderStep::Layered { .. }));
1006    ///     }
1007    ///     other => panic!("expected Layered, got {other:?}"),
1008    /// }
1009    /// ```
1010    pub fn route_layer(mut self, layer: impl ProcessorLayer + 'static) -> Self {
1011        self.route_layers.push(LayerFactory::new(layer));
1012        self
1013    }
1014
1015    /// Consume the builder and produce a [`RouteDefinition`].
1016    // Duplicate route IDs are detected at `CamelContext::add_route_definition` time
1017    // (RouteController rejects atomically with CamelError::RouteError).
1018    pub fn build(mut self) -> Result<RouteDefinition, CamelError> {
1019        validate_uri(&self.from_uri)?;
1020        let route_id = self
1021            .route_id
1022            .filter(|s| !s.trim().is_empty())
1023            .ok_or_else(|| {
1024                CamelError::RouteError(
1025                    "route must have a non-empty 'route_id' — call .route_id(\"name\") on the builder"
1026                        .to_string(),
1027                )
1028            })?;
1029        let resolved_error_handler = match self.error_handler_mode {
1030            ErrorHandlerMode::None => self.error_handler,
1031            ErrorHandlerMode::ExplicitConfig => self.error_handler,
1032            ErrorHandlerMode::Mixed => {
1033                return Err(CamelError::RouteError(
1034                    "mixed error handler modes: cannot combine .error_handler(config) with shorthand methods".into(),
1035                ));
1036            }
1037            ErrorHandlerMode::Shorthand { dlc_uri, specs } => {
1038                let mut config = if let Some(uri) = dlc_uri {
1039                    ErrorHandlerConfig::dead_letter_channel(uri)
1040                } else {
1041                    ErrorHandlerConfig::log_only()
1042                };
1043
1044                for spec in specs {
1045                    let matcher = spec.matches.clone();
1046                    let mut builder = config.on_exception(move |e| matcher(e));
1047
1048                    if let Some(retry) = spec.retry {
1049                        builder = builder.retry(retry.max_attempts).with_backoff(
1050                            retry.initial_delay,
1051                            retry.multiplier,
1052                            retry.max_delay,
1053                        );
1054                        if retry.jitter_factor > 0.0 {
1055                            builder = builder.with_jitter(retry.jitter_factor);
1056                        }
1057                    }
1058
1059                    if let Some(uri) = spec.handled_by {
1060                        builder = builder.handled_by(uri);
1061                    }
1062
1063                    config = builder.build();
1064                }
1065
1066                Some(config)
1067            }
1068        };
1069
1070        // Deferred `.parameters()` validation and merge: misuse is a RouteError,
1071        // URI merge failures surface as CamelError::EndpointUri via `?`.
1072        apply_parameter_assignments(
1073            &mut self.from_uri,
1074            &mut self.steps,
1075            std::mem::take(&mut self.parameter_assignments),
1076            std::mem::take(&mut self.parameter_misuse),
1077        )?;
1078
1079        // Whole-route middleware: iterate in call order so the FIRST added
1080        // layer is innermost and the LAST added is outermost.
1081        let mut steps = self.steps;
1082        for factory in self.route_layers {
1083            steps = vec![BuilderStep::Layered { factory, steps }];
1084        }
1085
1086        let definition = RouteDefinition::new(self.from_uri, steps);
1087        let definition = if let Some(eh) = resolved_error_handler {
1088            definition.with_error_handler(eh)
1089        } else {
1090            definition
1091        };
1092        let definition = if let Some(cb) = self.circuit_breaker_config {
1093            definition.with_circuit_breaker(cb)
1094        } else {
1095            definition
1096        };
1097        let definition = if let Some(sp) = self.security_policy_config {
1098            definition.with_security_policy(sp)
1099        } else {
1100            definition
1101        };
1102        let definition = if let Some(auth) = self.security_authenticator {
1103            definition.with_security_authenticator(auth)
1104        } else {
1105            definition
1106        };
1107        let definition = if let Some(registry) = self.provider_registry {
1108            definition.with_provider_registry(registry)
1109        } else {
1110            definition
1111        };
1112        let definition = if let Some(concurrency) = self.concurrency {
1113            definition.with_concurrency(concurrency)
1114        } else {
1115            definition
1116        };
1117        let definition = definition.with_route_id(route_id);
1118        let definition = if let Some(auto) = self.auto_startup {
1119            definition.with_auto_startup(auto)
1120        } else {
1121            definition
1122        };
1123        let definition = if let Some(order) = self.startup_order {
1124            definition.with_startup_order(order)
1125        } else {
1126            definition
1127        };
1128        Ok(definition)
1129    }
1130
1131    /// Compile this builder route into canonical spec.
1132    pub fn build_canonical(mut self) -> Result<CanonicalRouteSpec, CamelError> {
1133        validate_uri(&self.from_uri)?;
1134        let route_id = self
1135            .route_id
1136            .filter(|s| !s.trim().is_empty())
1137            .ok_or_else(|| {
1138                CamelError::RouteError(
1139                    "route must have a non-empty 'route_id' — call .route_id(\"name\") on the builder"
1140                        .to_string(),
1141                )
1142            })?;
1143
1144        // Canonical v2 has no whole-route wrapper step: reject BEFORE
1145        // canonicalizing, otherwise the plain steps would be emitted and the
1146        // middleware silently dropped.
1147        if !self.route_layers.is_empty() {
1148            return Err(CamelError::RouteError(
1149                "route_layer(...) layers are not representable in canonical v2; use build() for layered routes"
1150                    .into(),
1151            ));
1152        }
1153
1154        // Deferred `.parameters()` validation and merge (same path as `build()`).
1155        apply_parameter_assignments(
1156            &mut self.from_uri,
1157            &mut self.steps,
1158            std::mem::take(&mut self.parameter_assignments),
1159            std::mem::take(&mut self.parameter_misuse),
1160        )?;
1161
1162        let steps = canonicalize_steps(self.steps)?;
1163        let circuit_breaker = self
1164            .circuit_breaker_config
1165            .map(canonicalize_circuit_breaker)
1166            .transpose()?;
1167
1168        if self.security_policy_config.is_some() {
1169            return Err(CamelError::RouteError(
1170                "routes with security_policy cannot use the canonical/hot-reload path (not yet supported)"
1171                    .into(),
1172            ));
1173        }
1174
1175        let spec = CanonicalRouteSpec {
1176            route_id,
1177            from: self.from_uri,
1178            steps,
1179            circuit_breaker,
1180            auto_startup: None,
1181            startup_order: None,
1182            concurrency: None,
1183            version: camel_api::CANONICAL_CONTRACT_VERSION,
1184        };
1185        spec.validate_contract()?;
1186        Ok(spec)
1187    }
1188}
1189
1190pub struct OnExceptionBuilder {
1191    parent: RouteBuilder,
1192    policy: OnExceptionSpec,
1193}
1194
1195impl OnExceptionBuilder {
1196    pub fn retry(mut self, max_attempts: u32) -> Self {
1197        self.policy.retry = Some(RedeliveryPolicy::new(max_attempts));
1198        self
1199    }
1200
1201    pub fn with_backoff(
1202        mut self,
1203        initial: std::time::Duration,
1204        multiplier: f64,
1205        max: std::time::Duration,
1206    ) -> Self {
1207        if let Some(ref mut retry) = self.policy.retry {
1208            retry.initial_delay = initial;
1209            retry.multiplier = multiplier;
1210            retry.max_delay = max;
1211        } else {
1212            tracing::warn!("backoff/jitter configuration has no effect when retry_count is 0");
1213        }
1214        self
1215    }
1216
1217    pub fn with_jitter(mut self, jitter_factor: f64) -> Self {
1218        if let Some(ref mut retry) = self.policy.retry {
1219            retry.jitter_factor = jitter_factor.clamp(0.0, 1.0);
1220        } else {
1221            tracing::warn!("backoff/jitter configuration has no effect when retry_count is 0");
1222        }
1223        self
1224    }
1225
1226    pub fn handled_by(mut self, uri: impl Into<String>) -> Self {
1227        self.policy.handled_by = Some(uri.into());
1228        self
1229    }
1230
1231    pub fn end_on_exception(mut self) -> RouteBuilder {
1232        if let ErrorHandlerMode::Shorthand { ref mut specs, .. } = self.parent.error_handler_mode {
1233            specs.push(self.policy);
1234        }
1235        self.parent
1236    }
1237}
1238
1239/// True when `slot` names an endpoint-bearing position: the `from` endpoint, or
1240/// a step of one of the endpoint kinds (`To`, `LayeredTo`, `WireTap`, `Enrich`,
1241/// `PollEnrich`).
1242fn endpoint_slot_bears_uri(slot: &EndpointSlot, steps: &[BuilderStep]) -> bool {
1243    match slot {
1244        EndpointSlot::From => true,
1245        EndpointSlot::Step(i) => steps.get(*i).is_some_and(|step| {
1246            matches!(
1247                step,
1248                BuilderStep::To(_)
1249                    | BuilderStep::LayeredTo { .. }
1250                    | BuilderStep::WireTap { .. }
1251                    | BuilderStep::Enrich { .. }
1252                    | BuilderStep::PollEnrich { .. }
1253            )
1254        }),
1255    }
1256}
1257
1258/// Merge each pending `.parameters()` assignment into its endpoint slot's URI.
1259///
1260/// A recorded misuse flag aborts first (builder misuse → `RouteError`). Each
1261/// endpoint slot is then verified endpoint-bearing and its URI re-rendered via
1262/// [`EndpointUri::try_from_uri_and_params`]; URI merge failures propagate as
1263/// `CamelError::EndpointUri` (never folded into `RouteError`). Empty parameter
1264/// maps are skipped entirely, preserving URI bytes (parity with the DSL
1265/// lowering); misuse for such calls is still surfaced via `misuse`.
1266fn apply_parameter_assignments(
1267    from_uri: &mut String,
1268    steps: &mut [BuilderStep],
1269    assignments: Vec<(EndpointSlot, BTreeMap<String, String>)>,
1270    misuse: Option<String>,
1271) -> Result<(), CamelError> {
1272    if let Some(reason) = misuse {
1273        return Err(CamelError::RouteError(reason));
1274    }
1275
1276    for (slot, params) in assignments {
1277        // Empty maps are no-ops: re-rendering would still route through
1278        // `EndpointUri` and could normalize URI bytes, diverging from the DSL
1279        // lowering which skips empty maps for byte-identity/passthrough.
1280        if params.is_empty() {
1281            continue;
1282        }
1283
1284        let uri = match slot {
1285            EndpointSlot::From => &mut *from_uri,
1286            EndpointSlot::Step(i) => match steps.get_mut(i) {
1287                Some(BuilderStep::To(uri)) => uri,
1288                Some(BuilderStep::LayeredTo { uri, .. }) => uri,
1289                Some(BuilderStep::WireTap { uri, .. }) => uri,
1290                Some(BuilderStep::Enrich { uri, .. }) => uri,
1291                Some(BuilderStep::PollEnrich { uri, .. }) => uri,
1292                Some(other) => {
1293                    return Err(CamelError::RouteError(format!(
1294                        ".parameters() attached to a non-endpoint step (`{}`)",
1295                        canonical_step_name(other)
1296                    )));
1297                }
1298                None => {
1299                    return Err(CamelError::RouteError(
1300                        ".parameters() attached to an out-of-range step index".to_string(),
1301                    ));
1302                }
1303            },
1304        };
1305        let merged = EndpointUri::try_from_uri_and_params(uri, params)?.to_canonical_string();
1306        *uri = merged;
1307    }
1308
1309    Ok(())
1310}
1311
1312/// Validate that a URI is non-empty and contains a scheme component.
1313fn validate_uri(uri: &str) -> Result<(), CamelError> {
1314    let trimmed = uri.trim();
1315    if trimmed.is_empty() {
1316        return Err(CamelError::RouteError(
1317            "route must have a 'from' URI".to_string(),
1318        ));
1319    }
1320    if !trimmed.contains(':') {
1321        return Err(CamelError::RouteError(
1322            "URI must have a scheme (e.g. 'timer:tick')".to_string(),
1323        ));
1324    }
1325    let scheme = trimmed.split(':').next().unwrap_or("");
1326    if scheme.trim().is_empty() {
1327        return Err(CamelError::RouteError(
1328            "URI scheme must not be empty".to_string(),
1329        ));
1330    }
1331    Ok(())
1332}
1333
1334fn canonicalize_steps(steps: Vec<BuilderStep>) -> Result<Vec<CanonicalStepSpec>, CamelError> {
1335    let mut canonical = Vec::with_capacity(steps.len());
1336    for step in steps {
1337        canonical.push(canonicalize_step(step)?);
1338    }
1339    Ok(canonical)
1340}
1341
1342fn canonicalize_step(step: BuilderStep) -> Result<CanonicalStepSpec, CamelError> {
1343    match step {
1344        BuilderStep::To(uri) => Ok(CanonicalStepSpec::To { uri }),
1345        BuilderStep::Log { message, .. } => Ok(CanonicalStepSpec::Log { message }),
1346        BuilderStep::Stop => Ok(CanonicalStepSpec::Stop),
1347        BuilderStep::WireTap { uri } => Ok(CanonicalStepSpec::WireTap { uri }),
1348        BuilderStep::Delay { config } => Ok(CanonicalStepSpec::Delay {
1349            delay_ms: config.delay_ms,
1350            dynamic_header: config.dynamic_header,
1351        }),
1352        BuilderStep::DeclarativeScript { expression } => {
1353            Ok(CanonicalStepSpec::Script { expression })
1354        }
1355        BuilderStep::DeclarativeFilter { predicate, steps } => Ok(CanonicalStepSpec::Filter {
1356            predicate,
1357            steps: canonicalize_steps(steps)?,
1358        }),
1359        BuilderStep::DeclarativeChoice { whens, otherwise } => {
1360            let mut canonical_whens = Vec::with_capacity(whens.len());
1361            for DeclarativeWhenStep { predicate, steps } in whens {
1362                canonical_whens.push(CanonicalWhenSpec {
1363                    predicate,
1364                    steps: canonicalize_steps(steps)?,
1365                });
1366            }
1367            let otherwise = match otherwise {
1368                Some(steps) => Some(canonicalize_steps(steps)?),
1369                None => None,
1370            };
1371            Ok(CanonicalStepSpec::Choice {
1372                whens: canonical_whens,
1373                otherwise,
1374            })
1375        }
1376        BuilderStep::DeclarativeSplit {
1377            expression,
1378            aggregation,
1379            parallel,
1380            parallel_limit,
1381            // The programmatic language-split builder has no knob source;
1382            // the default applies at wrap time (asymmetry deferred).
1383            trace_item_threshold: _,
1384            stop_on_exception,
1385            steps,
1386        } => Ok(CanonicalStepSpec::Split {
1387            expression: CanonicalSplitExpressionSpec::Language(expression),
1388            aggregation: canonicalize_split_aggregation(aggregation)?,
1389            parallel,
1390            parallel_limit,
1391            trace_item_threshold: None,
1392            stop_on_exception,
1393            steps: canonicalize_steps(steps)?,
1394        }),
1395        BuilderStep::Aggregate { config } => Ok(CanonicalStepSpec::Aggregate(
1396            canonicalize_aggregate(config)?,
1397        )),
1398        BuilderStep::Transacted { datasource, steps } => {
1399            Ok(CanonicalStepSpec::Transacted(CanonicalTransactedSpec {
1400                datasource,
1401                steps: canonicalize_steps(steps)?,
1402            }))
1403        }
1404        other => {
1405            let step_name = canonical_step_name(&other);
1406            let detail = camel_api::canonical_contract_rejection_reason(step_name)
1407                .unwrap_or("not included in canonical v2");
1408            Err(CamelError::RouteError(format!(
1409                "canonical v2 does not support step `{step_name}`: {detail}"
1410            )))
1411        }
1412    }
1413}
1414
1415fn canonicalize_split_aggregation(
1416    strategy: camel_api::splitter::AggregationStrategy,
1417) -> Result<CanonicalSplitAggregationSpec, CamelError> {
1418    match strategy {
1419        camel_api::splitter::AggregationStrategy::LastWins => {
1420            Ok(CanonicalSplitAggregationSpec::LastWins)
1421        }
1422        camel_api::splitter::AggregationStrategy::CollectAll => {
1423            Ok(CanonicalSplitAggregationSpec::CollectAll)
1424        }
1425        camel_api::splitter::AggregationStrategy::Custom(_) => Err(CamelError::RouteError(
1426            "canonical v2 does not support custom split aggregation".to_string(),
1427        )),
1428        camel_api::splitter::AggregationStrategy::Original => {
1429            Ok(CanonicalSplitAggregationSpec::Original)
1430        }
1431        _ => Err(CamelError::RouteError(
1432            "canonical v2 does not support this split aggregation strategy".to_string(),
1433        )),
1434    }
1435}
1436
1437fn extract_completion_fields(
1438    mode: &CompletionMode,
1439) -> Result<(Option<usize>, Option<u64>), CamelError> {
1440    match mode {
1441        CompletionMode::Single(cond) => match cond {
1442            CompletionCondition::Size(n) => Ok((Some(*n), None)),
1443            CompletionCondition::Timeout(d) => Ok((None, Some(d.as_millis() as u64))),
1444            CompletionCondition::Predicate(_) | CompletionCondition::PredicateExpr { .. } => {
1445                Err(CamelError::RouteError(
1446                    "aggregate PredicateExpr/Predicate completion cannot reverse-map to canonical \
1447                     (forward-only in rc-zit); build the canonical spec directly"
1448                        .to_string(),
1449                ))
1450            }
1451            _ => Err(CamelError::RouteError(
1452                "unsupported completion condition".to_string(),
1453            )),
1454        },
1455        CompletionMode::Any(conds) => {
1456            let mut size = None;
1457            let mut timeout_ms = None;
1458            for cond in conds {
1459                match cond {
1460                    CompletionCondition::Size(n) => size = Some(*n),
1461                    CompletionCondition::Timeout(d) => timeout_ms = Some(d.as_millis() as u64),
1462                    CompletionCondition::Predicate(_)
1463                    | CompletionCondition::PredicateExpr { .. } => {
1464                        return Err(CamelError::RouteError(
1465                            "aggregate PredicateExpr/Predicate completion cannot reverse-map to \
1466                             canonical (forward-only in rc-zit); build the canonical spec directly"
1467                                .to_string(),
1468                        ));
1469                    }
1470                    _ => {
1471                        return Err(CamelError::RouteError(
1472                            "unsupported completion condition".to_string(),
1473                        ));
1474                    }
1475                }
1476            }
1477            Ok((size, timeout_ms))
1478        }
1479        _ => Err(CamelError::RouteError(
1480            "unsupported completion mode".to_string(),
1481        )),
1482    }
1483}
1484
1485fn canonicalize_aggregate(config: AggregatorConfig) -> Result<CanonicalAggregateSpec, CamelError> {
1486    let (completion_size, completion_timeout_ms) = extract_completion_fields(&config.completion)?;
1487
1488    let header = match &config.correlation {
1489        CorrelationStrategy::HeaderName(h) => h.clone(),
1490        CorrelationStrategy::Expression { expr, .. } => expr.clone(),
1491        CorrelationStrategy::Fn(_) => {
1492            return Err(CamelError::RouteError(
1493                "canonical v2 does not support Fn correlation strategy".to_string(),
1494            ));
1495        }
1496        _ => {
1497            return Err(CamelError::RouteError(
1498                "canonical v2 does not support this correlation strategy".to_string(),
1499            ));
1500        }
1501    };
1502
1503    let correlation_key = match &config.correlation {
1504        CorrelationStrategy::HeaderName(_) => None,
1505        CorrelationStrategy::Expression { expr, .. } => Some(expr.clone()),
1506        // INVARIANT: every other correlation variant (Fn and any future
1507        // variant) is rejected by the `header` match above, which returns
1508        // early — so this branch is unreachable here.
1509        _ => unreachable!(),
1510    };
1511
1512    let strategy = match config.strategy {
1513        AggregationStrategy::CollectAll => CanonicalAggregateStrategySpec::CollectAll,
1514        AggregationStrategy::Custom(_) => {
1515            return Err(CamelError::RouteError(
1516                "canonical v2 does not support custom aggregate strategy".to_string(),
1517            ));
1518        }
1519        _ => {
1520            return Err(CamelError::RouteError(
1521                "canonical v2 does not support this aggregate strategy".to_string(),
1522            ));
1523        }
1524    };
1525    let bucket_ttl_ms = config
1526        .bucket_ttl
1527        .map(|ttl| u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX));
1528
1529    Ok(CanonicalAggregateSpec {
1530        header,
1531        completion_size,
1532        completion_timeout_ms,
1533        correlation_key,
1534        force_completion_on_stop: if config.force_completion_on_stop {
1535            Some(true)
1536        } else {
1537            None
1538        },
1539        discard_on_timeout: if config.discard_on_timeout {
1540            Some(true)
1541        } else {
1542            None
1543        },
1544        strategy,
1545        max_buckets: config.max_buckets,
1546        max_bucket_size: config.max_bucket_size,
1547        bucket_ttl_ms,
1548        completion_predicate: None,
1549    })
1550}
1551
1552fn canonicalize_circuit_breaker(
1553    config: CircuitBreakerConfig,
1554) -> Result<CanonicalCircuitBreakerSpec, CamelError> {
1555    if config.fallback.is_some() {
1556        return Err(CamelError::RouteError(
1557            "canonical v2 does not support circuit breaker `fallback` (opaque BoxProcessor \
1558             cannot reverse-map to canonical steps); build the canonical spec directly"
1559                .to_string(),
1560        ));
1561    }
1562    Ok(CanonicalCircuitBreakerSpec {
1563        failure_threshold: config.failure_threshold,
1564        open_duration_ms: u64::try_from(config.open_duration.as_millis()).unwrap_or(u64::MAX),
1565        fallback: Vec::new(),
1566    })
1567}
1568
1569fn canonical_step_name(step: &BuilderStep) -> &'static str {
1570    match step {
1571        BuilderStep::Processor(_) => "processor",
1572        BuilderStep::To(_) => "to",
1573        BuilderStep::Stop => "stop",
1574        BuilderStep::Log { .. } => "log",
1575        BuilderStep::DeclarativeSetHeader { .. } => "set_header",
1576        BuilderStep::DeclarativeSetHeaderIfAbsent { .. } => "set_header_if_absent",
1577        BuilderStep::DeclarativeRemoveHeader { .. } => "remove_header",
1578        BuilderStep::DeclarativeSetBody { .. } => "set_body",
1579        BuilderStep::DeclarativeThrow { .. } => "throw",
1580        BuilderStep::DeclarativeFilter { .. } => "filter",
1581        BuilderStep::DeclarativeChoice { .. } => "choice",
1582        BuilderStep::DeclarativeScript { .. } => "script",
1583        BuilderStep::DeclarativeFunction { .. } => "function",
1584        BuilderStep::DeclarativeSplit { .. } => "split",
1585        BuilderStep::Split { .. } => "split",
1586        BuilderStep::Loop { .. } | BuilderStep::DeclarativeLoop { .. } => "loop",
1587        BuilderStep::Aggregate { .. } => "aggregate",
1588        BuilderStep::Filter { .. } => "filter",
1589        BuilderStep::Choice { .. } => "choice",
1590        BuilderStep::WireTap { .. } => "wire_tap",
1591        BuilderStep::Delay { .. } => "delay",
1592        BuilderStep::Multicast { .. } => "multicast",
1593        BuilderStep::DeclarativeLog { .. } => "log",
1594        BuilderStep::Bean { .. } => "bean",
1595        BuilderStep::Script { .. } => "script",
1596        BuilderStep::Throttle { .. } => "throttle",
1597        BuilderStep::LoadBalance { .. } => "load_balancer",
1598        BuilderStep::DynamicRouter { .. } => "dynamic_router",
1599        BuilderStep::RoutingSlip { .. } => "routing_slip",
1600        BuilderStep::DeclarativeDynamicRouter { .. } => "declarative_dynamic_router",
1601        BuilderStep::DeclarativeRoutingSlip { .. } => "declarative_routing_slip",
1602        BuilderStep::RecipientList { .. } => "recipient_list",
1603        BuilderStep::DeclarativeRecipientList { .. } => "declarative_recipient_list",
1604        BuilderStep::DeclarativeSetProperty { .. } => "set_property",
1605        BuilderStep::DeclarativeStreamSplit { .. } | BuilderStep::StreamSplit { .. } => {
1606            "stream_split"
1607        }
1608        BuilderStep::Enrich { .. } => "enrich",
1609        BuilderStep::PollEnrich { .. } => "poll_enrich",
1610        BuilderStep::Validate { .. } => "validate",
1611        BuilderStep::IdempotentConsumer { .. } => "idempotent_consumer",
1612        BuilderStep::ClaimCheck { .. } => "claim_check",
1613        BuilderStep::Cache { .. } => "cache",
1614        BuilderStep::CacheInvalidate { .. } => "cache_invalidate",
1615        BuilderStep::CacheClear { .. } => "cache_clear",
1616        BuilderStep::CacheStats { .. } => "cache_stats",
1617        BuilderStep::CachePeekStale { .. } => "cache_peek_stale",
1618        BuilderStep::Sampling { .. } => "sampling",
1619        BuilderStep::Sort { .. } => "sort",
1620        BuilderStep::DeclarativeDoTry { .. } => "do_try",
1621        BuilderStep::DoTry { .. } => "do_try",
1622        BuilderStep::Resequence { .. } => "resequence",
1623        BuilderStep::LayeredTo { .. } => "to_layered",
1624        BuilderStep::Layered { .. } => "layered",
1625        BuilderStep::Transacted { .. } => "transacted",
1626    }
1627}
1628
1629impl StepAccumulator for RouteBuilder {
1630    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1631        &mut self.steps
1632    }
1633}
1634
1635/// Builder for the sub-pipeline within a `.split()` ... `.end_split()` block.
1636///
1637/// Exposes the same step methods as `RouteBuilder` (to, process, filter, etc.)
1638/// but NOT `.build()` and NOT `.split()` (no nested splits).
1639///
1640/// Calling `.end_split()` packages the sub-steps into a `BuilderStep::Split`
1641/// and returns the parent `RouteBuilder`.
1642pub struct SplitBuilder {
1643    parent: RouteBuilder,
1644    config: SplitterConfig,
1645    steps: Vec<BuilderStep>,
1646}
1647
1648impl SplitBuilder {
1649    /// Open a filter scope within the split sub-pipeline.
1650    pub fn filter<F>(self, predicate: F) -> FilterInSplitBuilder
1651    where
1652        F: Fn(&Exchange) -> bool + Send + Sync + 'static,
1653    {
1654        FilterInSplitBuilder {
1655            parent: self,
1656            predicate: camel_api::FilterPredicate::new(predicate),
1657            steps: vec![],
1658        }
1659    }
1660
1661    /// Close the split scope. Packages the accumulated sub-steps into a
1662    /// `BuilderStep::Split` and returns the parent `RouteBuilder`.
1663    pub fn end_split(mut self) -> RouteBuilder {
1664        let split_step = BuilderStep::Split {
1665            config: self.config,
1666            steps: self.steps,
1667        };
1668        self.parent.steps.push(split_step);
1669        self.parent
1670    }
1671}
1672
1673impl StepAccumulator for SplitBuilder {
1674    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1675        &mut self.steps
1676    }
1677}
1678
1679/// Builder for the sub-pipeline within a `.filter()` ... `.end_filter()` block.
1680pub struct FilterBuilder {
1681    parent: RouteBuilder,
1682    predicate: FilterPredicate,
1683    steps: Vec<BuilderStep>,
1684}
1685
1686impl FilterBuilder {
1687    /// Close the filter scope. Packages the accumulated sub-steps into a
1688    /// `BuilderStep::Filter` and returns the parent `RouteBuilder`.
1689    pub fn end_filter(mut self) -> RouteBuilder {
1690        let step = BuilderStep::Filter {
1691            predicate: self.predicate,
1692            steps: self.steps,
1693        };
1694        self.parent.steps.push(step);
1695        self.parent
1696    }
1697}
1698
1699impl StepAccumulator for FilterBuilder {
1700    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1701        &mut self.steps
1702    }
1703}
1704
1705/// Builder for a filter scope nested inside a `.split()` block.
1706pub struct FilterInSplitBuilder {
1707    parent: SplitBuilder,
1708    predicate: FilterPredicate,
1709    steps: Vec<BuilderStep>,
1710}
1711
1712impl FilterInSplitBuilder {
1713    /// Close the filter scope and return the parent `SplitBuilder`.
1714    pub fn end_filter(mut self) -> SplitBuilder {
1715        let step = BuilderStep::Filter {
1716            predicate: self.predicate,
1717            steps: self.steps,
1718        };
1719        self.parent.steps.push(step);
1720        self.parent
1721    }
1722}
1723
1724impl StepAccumulator for FilterInSplitBuilder {
1725    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1726        &mut self.steps
1727    }
1728}
1729
1730/// Builder for the sub-pipeline within a `.stream_split()` ... `.end_stream_split()`
1731/// block.
1732///
1733/// The caller supplies the streaming fragment expression directly; sub-steps
1734/// added here run once per fragment. Calling `.end_stream_split()` packages
1735/// the sub-steps into a `BuilderStep::StreamSplit` and returns the parent
1736/// `RouteBuilder`.
1737pub struct StreamSplitBuilder {
1738    parent: RouteBuilder,
1739    expression: StreamSplitExpression,
1740    aggregation: camel_api::splitter::AggregationStrategy,
1741    stop_on_exception: bool,
1742    steps: Vec<BuilderStep>,
1743}
1744
1745impl StreamSplitBuilder {
1746    /// Set the aggregation strategy applied to fragment results.
1747    pub fn aggregation(mut self, strategy: camel_api::splitter::AggregationStrategy) -> Self {
1748        self.aggregation = strategy;
1749        self
1750    }
1751
1752    /// Set whether the first fragment error stops the split. Defaults to `true`.
1753    pub fn stop_on_exception(mut self, stop: bool) -> Self {
1754        self.stop_on_exception = stop;
1755        self
1756    }
1757
1758    /// Close the stream-split scope. Packages the accumulated sub-steps into a
1759    /// `BuilderStep::StreamSplit` and returns the parent `RouteBuilder`.
1760    pub fn end_stream_split(mut self) -> RouteBuilder {
1761        let step = BuilderStep::StreamSplit {
1762            expression: self.expression,
1763            aggregation: self.aggregation,
1764            stop_on_exception: self.stop_on_exception,
1765            steps: self.steps,
1766        };
1767        self.parent.steps.push(step);
1768        self.parent
1769    }
1770}
1771
1772impl StepAccumulator for StreamSplitBuilder {
1773    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1774        &mut self.steps
1775    }
1776}
1777
1778// ── Choice/When/Otherwise builders ─────────────────────────────────────────
1779
1780/// Builder for a `.choice()` ... `.end_choice()` block.
1781///
1782/// Accumulates `when` clauses and an optional `otherwise` clause.
1783/// Cannot call `.build()` until `.end_choice()` is called.
1784pub struct ChoiceBuilder {
1785    parent: RouteBuilder,
1786    whens: Vec<WhenStep>,
1787    _otherwise: Option<Vec<BuilderStep>>,
1788}
1789
1790impl ChoiceBuilder {
1791    /// Open a `when` clause. Only exchanges matching `predicate` will be
1792    /// processed by the steps inside the `.when()` ... `.end_when()` scope.
1793    pub fn when<F>(self, predicate: F) -> WhenBuilder
1794    where
1795        F: Fn(&Exchange) -> bool + Send + Sync + 'static,
1796    {
1797        WhenBuilder {
1798            parent: self,
1799            predicate: camel_api::FilterPredicate::new(predicate),
1800            steps: vec![],
1801        }
1802    }
1803
1804    /// Open an `otherwise` clause. Executed when no `when` predicate matched.
1805    ///
1806    /// Only one `otherwise` is allowed per `choice`. Call this after all `.when()` clauses.
1807    pub fn otherwise(self) -> OtherwiseBuilder {
1808        OtherwiseBuilder {
1809            parent: self,
1810            steps: vec![],
1811        }
1812    }
1813
1814    /// Close the choice scope. Packages all accumulated `when` clauses and
1815    /// optional `otherwise` into a `BuilderStep::Choice` and returns the
1816    /// parent `RouteBuilder`.
1817    pub fn end_choice(mut self) -> RouteBuilder {
1818        let step = BuilderStep::Choice {
1819            whens: self.whens,
1820            otherwise: self._otherwise,
1821        };
1822        self.parent.steps.push(step);
1823        self.parent
1824    }
1825}
1826
1827/// Builder for the sub-pipeline within a `.when()` ... `.end_when()` block.
1828pub struct WhenBuilder {
1829    parent: ChoiceBuilder,
1830    predicate: camel_api::FilterPredicate,
1831    steps: Vec<BuilderStep>,
1832}
1833
1834impl WhenBuilder {
1835    /// Close the when scope. Packages the accumulated sub-steps into a
1836    /// `WhenStep` and returns the parent `ChoiceBuilder`.
1837    pub fn end_when(mut self) -> ChoiceBuilder {
1838        self.parent.whens.push(WhenStep {
1839            predicate: self.predicate,
1840            steps: self.steps,
1841        });
1842        self.parent
1843    }
1844}
1845
1846impl StepAccumulator for WhenBuilder {
1847    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1848        &mut self.steps
1849    }
1850}
1851
1852/// Builder for the sub-pipeline within an `.otherwise()` ... `.end_otherwise()` block.
1853pub struct OtherwiseBuilder {
1854    parent: ChoiceBuilder,
1855    steps: Vec<BuilderStep>,
1856}
1857
1858impl OtherwiseBuilder {
1859    /// Close the otherwise scope and return the parent `ChoiceBuilder`.
1860    pub fn end_otherwise(self) -> ChoiceBuilder {
1861        let OtherwiseBuilder { mut parent, steps } = self;
1862        parent._otherwise = Some(steps);
1863        parent
1864    }
1865}
1866
1867impl StepAccumulator for OtherwiseBuilder {
1868    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1869        &mut self.steps
1870    }
1871}
1872
1873/// Builder for the sub-pipeline within a `.multicast()` ... `.end_multicast()` block.
1874///
1875/// Exposes the same step methods as `RouteBuilder` (to, process, filter, etc.)
1876/// but NOT `.build()` and NOT `.multicast()` (no nested multicasts).
1877///
1878/// Calling `.end_multicast()` packages the sub-steps into a `BuilderStep::Multicast`
1879/// and returns the parent `RouteBuilder`.
1880pub struct MulticastBuilder {
1881    parent: RouteBuilder,
1882    steps: Vec<BuilderStep>,
1883    config: MulticastConfig,
1884}
1885
1886impl MulticastBuilder {
1887    pub fn parallel(mut self, parallel: bool) -> Self {
1888        self.config = self.config.parallel(parallel);
1889        self
1890    }
1891
1892    pub fn parallel_limit(mut self, limit: usize) -> Self {
1893        self.config = self.config.parallel_limit(limit);
1894        self
1895    }
1896
1897    pub fn stop_on_exception(mut self, stop: bool) -> Self {
1898        self.config = self.config.stop_on_exception(stop);
1899        self
1900    }
1901
1902    pub fn timeout(mut self, duration: std::time::Duration) -> Self {
1903        self.config = self.config.timeout(duration);
1904        self
1905    }
1906
1907    pub fn aggregation(mut self, strategy: MulticastStrategy) -> Self {
1908        self.config = self.config.aggregation(strategy);
1909        self
1910    }
1911
1912    pub fn end_multicast(mut self) -> RouteBuilder {
1913        let step = BuilderStep::Multicast {
1914            steps: self.steps,
1915            config: self.config,
1916        };
1917        self.parent.steps.push(step);
1918        self.parent
1919    }
1920}
1921
1922impl StepAccumulator for MulticastBuilder {
1923    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1924        &mut self.steps
1925    }
1926}
1927
1928/// Builder for the sub-pipeline within a `.throttle()` ... `.end_throttle()` block.
1929///
1930/// Exposes the same step methods as `RouteBuilder` (to, process, filter, etc.)
1931/// but NOT `.build()` and NOT `.throttle()` (no nested throttles).
1932///
1933/// Calling `.end_throttle()` packages the sub-steps into a `BuilderStep::Throttle`
1934/// and returns the parent `RouteBuilder`.
1935pub struct ThrottleBuilder {
1936    parent: RouteBuilder,
1937    config: ThrottlerConfig,
1938    steps: Vec<BuilderStep>,
1939}
1940
1941impl ThrottleBuilder {
1942    /// Set the throttle strategy. Default is `Delay`.
1943    ///
1944    /// - `Delay`: Queue messages until capacity available
1945    /// - `Reject`: Return error immediately when throttled
1946    /// - `Drop`: Silently discard excess messages
1947    pub fn strategy(mut self, strategy: ThrottleStrategy) -> Self {
1948        self.config = self.config.strategy(strategy);
1949        self
1950    }
1951
1952    /// Close the throttle scope. Packages the accumulated sub-steps into a
1953    /// `BuilderStep::Throttle` and returns the parent `RouteBuilder`.
1954    pub fn end_throttle(mut self) -> RouteBuilder {
1955        let step = BuilderStep::Throttle {
1956            config: self.config,
1957            steps: self.steps,
1958        };
1959        self.parent.steps.push(step);
1960        self.parent
1961    }
1962}
1963
1964impl StepAccumulator for ThrottleBuilder {
1965    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
1966        &mut self.steps
1967    }
1968}
1969
1970/// Builder for the sub-pipeline within a `.loop_count()` / `.loop_while()` ... `.end_loop()` block.
1971pub struct LoopBuilder {
1972    parent: RouteBuilder,
1973    config: LoopConfig,
1974    steps: Vec<BuilderStep>,
1975}
1976
1977impl LoopBuilder {
1978    pub fn loop_count(self, count: usize) -> LoopInLoopBuilder {
1979        LoopInLoopBuilder {
1980            parent: self,
1981            config: LoopConfig::new(LoopMode::Count(count)),
1982            steps: vec![],
1983        }
1984    }
1985
1986    pub fn loop_while<F>(self, predicate: F) -> LoopInLoopBuilder
1987    where
1988        F: Fn(&Exchange) -> bool + Send + Sync + 'static,
1989    {
1990        LoopInLoopBuilder {
1991            parent: self,
1992            config: LoopConfig::new(LoopMode::While(camel_api::PredicateSource::Sync(
1993                camel_api::FilterPredicate::new(predicate),
1994            ))),
1995            steps: vec![],
1996        }
1997    }
1998
1999    pub fn end_loop(mut self) -> RouteBuilder {
2000        let step = BuilderStep::Loop {
2001            config: self.config,
2002            steps: self.steps,
2003        };
2004        self.parent.steps.push(step);
2005        self.parent
2006    }
2007}
2008
2009impl StepAccumulator for LoopBuilder {
2010    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
2011        &mut self.steps
2012    }
2013}
2014
2015pub struct LoopInLoopBuilder {
2016    parent: LoopBuilder,
2017    config: LoopConfig,
2018    steps: Vec<BuilderStep>,
2019}
2020
2021impl LoopInLoopBuilder {
2022    pub fn end_loop(mut self) -> LoopBuilder {
2023        let step = BuilderStep::Loop {
2024            config: self.config,
2025            steps: self.steps,
2026        };
2027        self.parent.steps.push(step);
2028        self.parent
2029    }
2030}
2031
2032impl StepAccumulator for LoopInLoopBuilder {
2033    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
2034        &mut self.steps
2035    }
2036}
2037
2038/// Builder for the sub-pipeline within a `.load_balance()` ... `.end_load_balance()` block.
2039///
2040/// Exposes the same step methods as `RouteBuilder` (to, process, filter, etc.)
2041/// but NOT `.build()` and NOT `.load_balance()` (no nested load balancers).
2042///
2043/// Calling `.end_load_balance()` packages the sub-steps into a `BuilderStep::LoadBalance`
2044/// and returns the parent `RouteBuilder`.
2045pub struct LoadBalancerBuilder {
2046    parent: RouteBuilder,
2047    config: LoadBalancerConfig,
2048    steps: Vec<BuilderStep>,
2049}
2050
2051impl LoadBalancerBuilder {
2052    /// Set the load balance strategy to round-robin (default).
2053    pub fn round_robin(mut self) -> Self {
2054        self.config = LoadBalancerConfig::round_robin();
2055        self
2056    }
2057
2058    /// Set the load balance strategy to random selection.
2059    pub fn random(mut self) -> Self {
2060        self.config = LoadBalancerConfig::random();
2061        self
2062    }
2063
2064    /// Set the load balance strategy to weighted selection.
2065    ///
2066    /// Each endpoint is assigned a weight that determines its probability
2067    /// of being selected.
2068    pub fn weighted(mut self, weights: Vec<(String, u32)>) -> Self {
2069        self.config = LoadBalancerConfig::weighted(weights);
2070        self
2071    }
2072
2073    /// Set the load balance strategy to failover.
2074    ///
2075    /// Exchanges are sent to the first endpoint; on failure, the next endpoint
2076    /// is tried.
2077    pub fn failover(mut self) -> Self {
2078        self.config = LoadBalancerConfig::failover();
2079        self
2080    }
2081
2082    /// Close the load balance scope. Packages the accumulated sub-steps into a
2083    /// `BuilderStep::LoadBalance` and returns the parent `RouteBuilder`.
2084    pub fn end_load_balance(mut self) -> RouteBuilder {
2085        let step = BuilderStep::LoadBalance {
2086            config: self.config,
2087            steps: self.steps,
2088        };
2089        self.parent.steps.push(step);
2090        self.parent
2091    }
2092}
2093
2094impl StepAccumulator for LoadBalancerBuilder {
2095    fn steps_mut(&mut self) -> &mut Vec<BuilderStep> {
2096        &mut self.steps
2097    }
2098}
2099
2100// ---------------------------------------------------------------------------
2101// Tests
2102// ---------------------------------------------------------------------------
2103
2104#[cfg(test)]
2105mod tests {
2106    use super::*;
2107    use camel_api::SpanKindHint;
2108    use camel_api::error_handler::ErrorHandlerConfig;
2109    use camel_api::load_balancer::LoadBalanceStrategy;
2110    use camel_api::{Exchange, Message};
2111    use camel_core::route::BuilderStep;
2112    use std::sync::Arc;
2113    use std::time::Duration;
2114    use tower::{Service, ServiceExt};
2115
2116    #[test]
2117    fn test_builder_from_creates_definition() {
2118        let definition = RouteBuilder::from("timer:tick")
2119            .route_id("test-route")
2120            .build()
2121            .unwrap();
2122        assert_eq!(definition.from_uri(), "timer:tick");
2123    }
2124
2125    #[test]
2126    fn test_builder_empty_from_uri_errors() {
2127        let result = RouteBuilder::from("").route_id("test-route").build();
2128        assert!(result.is_err());
2129    }
2130
2131    #[test]
2132    fn test_build_rejects_schemeless_uri() {
2133        let result = RouteBuilder::from("no-scheme-here")
2134            .route_id("test-route")
2135            .build();
2136        match result {
2137            Err(err) => {
2138                let err_msg = format!("{err}");
2139                assert!(
2140                    err_msg.contains("scheme"),
2141                    "expected scheme-related error, got: {err_msg}"
2142                );
2143            }
2144            Ok(_) => panic!("schemeless URI should fail"),
2145        }
2146    }
2147
2148    #[test]
2149    fn test_build_rejects_empty_scheme_uri() {
2150        let result = RouteBuilder::from(":missing-scheme")
2151            .route_id("test-route")
2152            .build();
2153        match result {
2154            Err(err) => {
2155                let err_msg = format!("{err}");
2156                assert!(
2157                    err_msg.contains("scheme"),
2158                    "expected scheme-related error, got: {err_msg}"
2159                );
2160            }
2161            Ok(_) => panic!("empty-scheme URI should fail"),
2162        }
2163    }
2164
2165    #[test]
2166    fn test_build_accepts_valid_uri() {
2167        let result = RouteBuilder::from("timer:tick")
2168            .route_id("test-route")
2169            .build();
2170        assert!(result.is_ok());
2171    }
2172
2173    #[test]
2174    fn test_build_canonical_rejects_schemeless_uri() {
2175        let result = RouteBuilder::from("no-scheme-here")
2176            .route_id("test-route")
2177            .build_canonical();
2178        assert!(result.is_err());
2179    }
2180
2181    #[test]
2182    fn test_builder_to_adds_step() {
2183        let definition = RouteBuilder::from("timer:tick")
2184            .route_id("test-route")
2185            .to("log:info")
2186            .build()
2187            .unwrap();
2188
2189        assert_eq!(definition.from_uri(), "timer:tick");
2190        // We can verify steps were added by checking the structure
2191        assert!(matches!(&definition.steps()[0], BuilderStep::To(uri) if uri == "log:info"));
2192    }
2193
2194    #[test]
2195    fn test_builder_filter_adds_filter_step() {
2196        let definition = RouteBuilder::from("timer:tick")
2197            .route_id("test-route")
2198            .filter(|_ex| true)
2199            .to("mock:result")
2200            .end_filter()
2201            .build()
2202            .unwrap();
2203
2204        assert!(matches!(&definition.steps()[0], BuilderStep::Filter { .. }));
2205    }
2206
2207    #[test]
2208    fn test_builder_set_header_adds_processor_step() {
2209        let definition = RouteBuilder::from("timer:tick")
2210            .route_id("test-route")
2211            .set_header("key", Value::String("value".into()))
2212            .build()
2213            .unwrap();
2214
2215        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
2216    }
2217
2218    #[test]
2219    fn test_builder_map_body_adds_processor_step() {
2220        let definition = RouteBuilder::from("timer:tick")
2221            .route_id("test-route")
2222            .map_body(|body| body)
2223            .build()
2224            .unwrap();
2225
2226        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
2227    }
2228
2229    #[test]
2230    fn test_builder_process_adds_processor_step() {
2231        let definition = RouteBuilder::from("timer:tick")
2232            .route_id("test-route")
2233            .process(|ex| async move { Ok(ex) })
2234            .build()
2235            .unwrap();
2236
2237        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
2238    }
2239
2240    #[test]
2241    fn test_builder_chain_multiple_steps() {
2242        let definition = RouteBuilder::from("timer:tick")
2243            .route_id("test-route")
2244            .set_header("source", Value::String("timer".into()))
2245            .filter(|ex| ex.input.header("source").is_some())
2246            .to("log:info")
2247            .end_filter()
2248            .to("mock:result")
2249            .build()
2250            .unwrap();
2251
2252        assert_eq!(definition.steps().len(), 3); // set_header + Filter + To("mock:result")
2253        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_))); // set_header
2254        assert!(matches!(&definition.steps()[1], BuilderStep::Filter { .. })); // filter
2255        assert!(matches!(&definition.steps()[2], BuilderStep::To(uri) if uri == "mock:result"));
2256    }
2257
2258    #[test]
2259    fn test_loop_count_builder() {
2260        use camel_api::loop_eip::LoopMode;
2261
2262        let def = RouteBuilder::from("direct:start")
2263            .route_id("loop-test")
2264            .loop_count(3)
2265            .to("mock:inside")
2266            .end_loop()
2267            .to("mock:after")
2268            .build()
2269            .unwrap();
2270
2271        assert_eq!(def.steps().len(), 2);
2272        match &def.steps()[0] {
2273            BuilderStep::Loop { config, steps } => {
2274                assert!(matches!(config.mode, LoopMode::Count(3)));
2275                assert_eq!(steps.len(), 1);
2276            }
2277            other => panic!("Expected Loop, got {:?}", other),
2278        }
2279        assert!(matches!(def.steps()[1], BuilderStep::To(_)));
2280    }
2281
2282    #[test]
2283    fn test_loop_while_builder() {
2284        use camel_api::loop_eip::LoopMode;
2285
2286        let def = RouteBuilder::from("direct:start")
2287            .route_id("loop-while-test")
2288            .loop_while(|_ex| true)
2289            .to("mock:retry")
2290            .end_loop()
2291            .build()
2292            .unwrap();
2293
2294        assert_eq!(def.steps().len(), 1);
2295        match &def.steps()[0] {
2296            BuilderStep::Loop { config, steps } => {
2297                assert!(matches!(config.mode, LoopMode::While(_)));
2298                assert_eq!(steps.len(), 1);
2299            }
2300            other => panic!("Expected Loop, got {:?}", other),
2301        }
2302    }
2303
2304    #[test]
2305    fn test_nested_loop_builder() {
2306        use camel_api::loop_eip::LoopMode;
2307
2308        let def = RouteBuilder::from("direct:start")
2309            .route_id("nested-loop-test")
2310            .loop_count(2)
2311            .to("mock:outer")
2312            .loop_count(3)
2313            .to("mock:inner")
2314            .end_loop()
2315            .end_loop()
2316            .to("mock:after")
2317            .build()
2318            .unwrap();
2319
2320        assert_eq!(def.steps().len(), 2);
2321        match &def.steps()[0] {
2322            BuilderStep::Loop { steps, .. } => {
2323                assert_eq!(steps.len(), 2);
2324                match &steps[1] {
2325                    BuilderStep::Loop {
2326                        config,
2327                        steps: inner_steps,
2328                    } => {
2329                        assert!(matches!(config.mode, LoopMode::Count(3)));
2330                        assert_eq!(inner_steps.len(), 1);
2331                    }
2332                    other => panic!("Expected nested Loop, got {:?}", other),
2333                }
2334            }
2335            other => panic!("Expected outer Loop, got {:?}", other),
2336        }
2337    }
2338
2339    // -----------------------------------------------------------------------
2340    // Processor behavior tests — exercise the real Tower services directly
2341    // -----------------------------------------------------------------------
2342
2343    #[tokio::test]
2344    async fn test_set_header_processor_works() {
2345        let mut svc = SetHeader::new(IdentityProcessor, "greeting", Value::String("hello".into()));
2346        let exchange = Exchange::new(Message::new("test"));
2347        let result = svc.call(exchange).await.unwrap();
2348        assert_eq!(
2349            result.input.header("greeting"),
2350            Some(&Value::String("hello".into()))
2351        );
2352    }
2353
2354    #[derive(Clone)]
2355    struct CompletedBody;
2356
2357    impl camel_api::OutcomePipeline for CompletedBody {
2358        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
2359            Box::new(self.clone())
2360        }
2361        fn run<'a>(
2362            &'a mut self,
2363            exchange: Exchange,
2364        ) -> std::pin::Pin<
2365            Box<dyn std::future::Future<Output = camel_api::PipelineOutcome> + Send + 'a>,
2366        > {
2367            Box::pin(async move { camel_api::PipelineOutcome::Completed(exchange) })
2368        }
2369    }
2370
2371    #[derive(Clone)]
2372    struct FailedBody;
2373
2374    impl camel_api::OutcomePipeline for FailedBody {
2375        fn clone_box(&self) -> Box<dyn camel_api::OutcomePipeline> {
2376            Box::new(self.clone())
2377        }
2378        fn run<'a>(
2379            &'a mut self,
2380            _exchange: Exchange,
2381        ) -> std::pin::Pin<
2382            Box<dyn std::future::Future<Output = camel_api::PipelineOutcome> + Send + 'a>,
2383        > {
2384            Box::pin(async move {
2385                camel_api::PipelineOutcome::Failed(CamelError::ProcessorError(
2386                    "should not reach".into(),
2387                ))
2388            })
2389        }
2390    }
2391
2392    fn filter_segment(
2393        predicate: impl Fn(&Exchange) -> bool + Send + Sync + 'static,
2394        body: Box<dyn camel_api::OutcomePipeline>,
2395    ) -> camel_processor::FilterSegment {
2396        camel_processor::FilterSegment {
2397            predicate: camel_api::PredicateSource::Sync(camel_api::FilterPredicate::new(predicate)),
2398            body: camel_api::OutcomeSegment::new(body),
2399        }
2400    }
2401
2402    #[tokio::test]
2403    async fn test_filter_processor_passes() {
2404        use camel_api::OutcomePipeline;
2405
2406        let mut seg = filter_segment(
2407            |ex: &Exchange| ex.input.body.as_text() == Some("pass"),
2408            Box::new(CompletedBody),
2409        );
2410        let exchange = Exchange::new(Message::new("pass"));
2411        let result = seg.run(exchange).await;
2412        match result {
2413            camel_api::PipelineOutcome::Completed(ex) => {
2414                assert_eq!(ex.input.body.as_text(), Some("pass"));
2415            }
2416            other => panic!("expected Completed, got {other:?}"),
2417        }
2418    }
2419
2420    #[tokio::test]
2421    async fn test_filter_processor_blocks() {
2422        use camel_api::OutcomePipeline;
2423
2424        let mut seg = filter_segment(
2425            |ex: &Exchange| ex.input.body.as_text() == Some("pass"),
2426            Box::new(FailedBody),
2427        );
2428        let exchange = Exchange::new(Message::new("reject"));
2429        let result = seg.run(exchange).await;
2430        match result {
2431            camel_api::PipelineOutcome::Completed(ex) => {
2432                assert_eq!(ex.input.body.as_text(), Some("reject"));
2433            }
2434            other => panic!("expected Completed, got {other:?}"),
2435        }
2436    }
2437
2438    #[tokio::test]
2439    async fn test_map_body_processor_works() {
2440        let mapper = MapBody::new(IdentityProcessor, |body: Body| {
2441            if let Some(text) = body.as_text() {
2442                Body::Text(text.to_uppercase())
2443            } else {
2444                body
2445            }
2446        });
2447        let exchange = Exchange::new(Message::new("hello"));
2448        let result = mapper.oneshot(exchange).await.unwrap();
2449        assert_eq!(result.input.body.as_text(), Some("HELLO"));
2450    }
2451
2452    #[tokio::test]
2453    async fn test_process_custom_processor_works() {
2454        let processor = ProcessorFn::new(|mut ex: Exchange| async move {
2455            ex.set_property("custom", Value::Bool(true));
2456            Ok(ex)
2457        });
2458        let exchange = Exchange::new(Message::default());
2459        let result = processor.oneshot(exchange).await.unwrap();
2460        assert_eq!(result.property("custom"), Some(&Value::Bool(true)));
2461    }
2462
2463    // -----------------------------------------------------------------------
2464    // Sequential pipeline test
2465    // -----------------------------------------------------------------------
2466
2467    #[tokio::test]
2468    async fn test_compose_pipeline_runs_steps_in_order() {
2469        use camel_core::route::{CompiledStep, PipelineRuntimeCtx, compose_pipeline};
2470
2471        let processors = vec![
2472            CompiledStep::Process {
2473                kind_hint: SpanKindHint::Internal,
2474                processor: BoxProcessor::new(SetHeader::new(
2475                    IdentityProcessor,
2476                    "step",
2477                    Value::String("one".into()),
2478                )),
2479                body_contract: None,
2480                lifecycle: None,
2481                label: None,
2482                to_uri: None,
2483            },
2484            CompiledStep::Process {
2485                kind_hint: SpanKindHint::Internal,
2486                processor: BoxProcessor::new(MapBody::new(IdentityProcessor, |body: Body| {
2487                    if let Some(text) = body.as_text() {
2488                        Body::Text(format!("{}-processed", text))
2489                    } else {
2490                        body
2491                    }
2492                })),
2493                body_contract: None,
2494                lifecycle: None,
2495                label: None,
2496                to_uri: None,
2497            },
2498        ];
2499
2500        let pipeline = compose_pipeline(processors, PipelineRuntimeCtx::compile_time());
2501        let exchange = Exchange::new(Message::new("hello"));
2502        let result = pipeline.oneshot(exchange).await.unwrap();
2503
2504        assert_eq!(
2505            result.input.header("step"),
2506            Some(&Value::String("one".into()))
2507        );
2508        assert_eq!(result.input.body.as_text(), Some("hello-processed"));
2509    }
2510
2511    #[tokio::test]
2512    async fn test_compose_pipeline_empty_is_identity() {
2513        use camel_core::route::{PipelineRuntimeCtx, compose_pipeline};
2514
2515        let pipeline = compose_pipeline(vec![], PipelineRuntimeCtx::compile_time());
2516        let exchange = Exchange::new(Message::new("unchanged"));
2517        let result = pipeline.oneshot(exchange).await.unwrap();
2518        assert_eq!(result.input.body.as_text(), Some("unchanged"));
2519    }
2520
2521    // -----------------------------------------------------------------------
2522    // Circuit breaker builder tests
2523    // -----------------------------------------------------------------------
2524
2525    #[test]
2526    fn test_builder_circuit_breaker_sets_config() {
2527        use camel_api::circuit_breaker::CircuitBreakerConfig;
2528
2529        let config = CircuitBreakerConfig::new().failure_threshold(5);
2530        let definition = RouteBuilder::from("timer:tick")
2531            .route_id("test-route")
2532            .circuit_breaker(config)
2533            .build()
2534            .unwrap();
2535
2536        let cb = definition
2537            .circuit_breaker_config()
2538            .expect("circuit breaker should be set");
2539        assert_eq!(cb.failure_threshold, 5);
2540    }
2541
2542    #[test]
2543    fn test_builder_circuit_breaker_with_error_handler() {
2544        use camel_api::circuit_breaker::CircuitBreakerConfig;
2545        use camel_api::error_handler::ErrorHandlerConfig;
2546
2547        let cb_config = CircuitBreakerConfig::new().failure_threshold(3);
2548        let eh_config = ErrorHandlerConfig::log_only();
2549
2550        let definition = RouteBuilder::from("timer:tick")
2551            .route_id("test-route")
2552            .to("log:info")
2553            .circuit_breaker(cb_config)
2554            .error_handler(eh_config)
2555            .build()
2556            .unwrap();
2557
2558        assert!(
2559            definition.circuit_breaker_config().is_some(),
2560            "circuit breaker config should be set"
2561        );
2562        // Route definition was built successfully with both configs.
2563    }
2564
2565    #[test]
2566    fn test_builder_on_exception_shorthand_multiple_clauses_preserve_order() {
2567        let definition = RouteBuilder::from("direct:start")
2568            .route_id("test-route")
2569            .dead_letter_channel("log:dlc")
2570            .on_exception(|e| matches!(e, CamelError::Io(_)))
2571            .retry(3)
2572            .handled_by("log:io")
2573            .end_on_exception()
2574            .on_exception(|e| matches!(e, CamelError::ProcessorError(_)))
2575            .retry(1)
2576            .end_on_exception()
2577            .to("mock:out")
2578            .build()
2579            .expect("route should build");
2580
2581        let cfg = definition
2582            .error_handler_config()
2583            .expect("error handler should be set");
2584        assert_eq!(cfg.policies.len(), 2);
2585        assert_eq!(cfg.dlc_uri.as_deref(), Some("log:dlc"));
2586        assert_eq!(
2587            cfg.policies[0].retry.as_ref().map(|p| p.max_attempts),
2588            Some(3)
2589        );
2590        assert_eq!(cfg.policies[0].handled_by.as_deref(), Some("log:io"));
2591        assert_eq!(
2592            cfg.policies[1].retry.as_ref().map(|p| p.max_attempts),
2593            Some(1)
2594        );
2595    }
2596
2597    #[test]
2598    fn test_builder_on_exception_mixed_mode_rejected() {
2599        let result = RouteBuilder::from("direct:start")
2600            .route_id("test-route")
2601            .error_handler(ErrorHandlerConfig::log_only())
2602            .on_exception(|_e| true)
2603            .end_on_exception()
2604            .to("mock:out")
2605            .build();
2606
2607        let err = result.err().expect("mixed mode should fail with an error");
2608
2609        assert!(
2610            format!("{err}").contains("mixed error handler modes"),
2611            "unexpected error: {err}"
2612        );
2613    }
2614
2615    #[test]
2616    fn test_builder_on_exception_backoff_and_jitter_without_retry_noop() {
2617        let definition = RouteBuilder::from("direct:start")
2618            .route_id("test-route")
2619            .on_exception(|_e| true)
2620            .with_backoff(Duration::from_millis(5), 3.0, Duration::from_millis(100))
2621            .with_jitter(0.5)
2622            .end_on_exception()
2623            .to("mock:out")
2624            .build()
2625            .expect("route should build");
2626
2627        let cfg = definition
2628            .error_handler_config()
2629            .expect("error handler should be set");
2630        assert_eq!(cfg.policies.len(), 1);
2631        assert!(cfg.policies[0].retry.is_none());
2632    }
2633
2634    #[test]
2635    fn test_builder_dead_letter_channel_without_on_exception_sets_dlc() {
2636        let definition = RouteBuilder::from("direct:start")
2637            .route_id("test-route")
2638            .dead_letter_channel("log:dlc")
2639            .to("mock:out")
2640            .build()
2641            .expect("route should build");
2642
2643        let cfg = definition
2644            .error_handler_config()
2645            .expect("error handler should be set");
2646        assert_eq!(cfg.dlc_uri.as_deref(), Some("log:dlc"));
2647        assert!(cfg.policies.is_empty());
2648    }
2649
2650    #[test]
2651    fn test_builder_dead_letter_channel_called_twice_uses_latest_and_keeps_policies() {
2652        let definition = RouteBuilder::from("direct:start")
2653            .route_id("test-route")
2654            .dead_letter_channel("log:first")
2655            .on_exception(|e| matches!(e, CamelError::Io(_)))
2656            .retry(2)
2657            .end_on_exception()
2658            .dead_letter_channel("log:second")
2659            .to("mock:out")
2660            .build()
2661            .expect("route should build");
2662
2663        let cfg = definition
2664            .error_handler_config()
2665            .expect("error handler should be set");
2666        assert_eq!(cfg.dlc_uri.as_deref(), Some("log:second"));
2667        assert_eq!(cfg.policies.len(), 1);
2668        assert_eq!(
2669            cfg.policies[0].retry.as_ref().map(|p| p.max_attempts),
2670            Some(2)
2671        );
2672    }
2673
2674    #[test]
2675    fn test_builder_on_exception_without_dlc_defaults_to_log_only() {
2676        let definition = RouteBuilder::from("direct:start")
2677            .route_id("test-route")
2678            .on_exception(|e| matches!(e, CamelError::ProcessorError(_)))
2679            .retry(1)
2680            .end_on_exception()
2681            .to("mock:out")
2682            .build()
2683            .expect("route should build");
2684
2685        let cfg = definition
2686            .error_handler_config()
2687            .expect("error handler should be set");
2688        assert!(cfg.dlc_uri.is_none());
2689        assert_eq!(cfg.policies.len(), 1);
2690    }
2691
2692    #[test]
2693    fn test_builder_error_handler_explicit_overwrite_stays_explicit_mode() {
2694        let first = ErrorHandlerConfig::dead_letter_channel("log:first");
2695        let second = ErrorHandlerConfig::dead_letter_channel("log:second");
2696
2697        let definition = RouteBuilder::from("direct:start")
2698            .route_id("test-route")
2699            .error_handler(first)
2700            .error_handler(second)
2701            .to("mock:out")
2702            .build()
2703            .expect("route should build");
2704
2705        let cfg = definition
2706            .error_handler_config()
2707            .expect("error handler should be set");
2708        assert_eq!(cfg.dlc_uri.as_deref(), Some("log:second"));
2709    }
2710
2711    // --- Splitter builder tests ---
2712
2713    #[test]
2714    fn test_split_builder_typestate() {
2715        use camel_api::splitter::{SplitterConfig, split_body_lines};
2716
2717        // .split() returns SplitBuilder, .end_split() returns RouteBuilder
2718        let definition = RouteBuilder::from("timer:test?period=1000")
2719            .route_id("test-route")
2720            .split(SplitterConfig::new(split_body_lines()))
2721            .to("mock:per-fragment")
2722            .end_split()
2723            .to("mock:final")
2724            .build()
2725            .unwrap();
2726
2727        // Should have 2 top-level steps: Split + To("mock:final")
2728        assert_eq!(definition.steps().len(), 2);
2729    }
2730
2731    #[test]
2732    fn test_split_builder_steps_collected() {
2733        use camel_api::splitter::{SplitterConfig, split_body_lines};
2734
2735        let definition = RouteBuilder::from("timer:test?period=1000")
2736            .route_id("test-route")
2737            .split(SplitterConfig::new(split_body_lines()))
2738            .set_header("fragment", Value::String("yes".into()))
2739            .to("mock:per-fragment")
2740            .end_split()
2741            .build()
2742            .unwrap();
2743
2744        // Should have 1 top-level step: Split (containing 2 sub-steps)
2745        assert_eq!(definition.steps().len(), 1);
2746        match &definition.steps()[0] {
2747            BuilderStep::Split { steps, .. } => {
2748                assert_eq!(steps.len(), 2); // SetHeader + To
2749            }
2750            other => panic!("Expected Split, got {:?}", other),
2751        }
2752    }
2753
2754    #[test]
2755    fn test_split_builder_config_propagated() {
2756        use camel_api::splitter::{AggregationStrategy, SplitterConfig, split_body_lines};
2757
2758        let definition = RouteBuilder::from("timer:test?period=1000")
2759            .route_id("test-route")
2760            .split(
2761                SplitterConfig::new(split_body_lines())
2762                    .parallel(true)
2763                    .parallel_limit(4)
2764                    .aggregation(AggregationStrategy::CollectAll),
2765            )
2766            .to("mock:per-fragment")
2767            .end_split()
2768            .build()
2769            .unwrap();
2770
2771        match &definition.steps()[0] {
2772            BuilderStep::Split { config, .. } => {
2773                assert!(config.parallel);
2774                assert_eq!(config.parallel_limit, Some(4));
2775                assert!(matches!(
2776                    config.aggregation,
2777                    AggregationStrategy::CollectAll
2778                ));
2779            }
2780            other => panic!("Expected Split, got {:?}", other),
2781        }
2782    }
2783
2784    #[test]
2785    fn test_aggregate_builder_adds_step() {
2786        use camel_api::aggregator::AggregatorConfig;
2787        use camel_core::route::BuilderStep;
2788
2789        let definition = RouteBuilder::from("timer:tick")
2790            .route_id("test-route")
2791            .aggregate(
2792                AggregatorConfig::correlate_by("key")
2793                    .complete_when_size(2)
2794                    .build()
2795                    .unwrap(),
2796            )
2797            .build()
2798            .unwrap();
2799
2800        assert_eq!(definition.steps().len(), 1);
2801        assert!(matches!(
2802            definition.steps()[0],
2803            BuilderStep::Aggregate { .. }
2804        ));
2805    }
2806
2807    #[test]
2808    fn test_aggregate_in_split_builder() {
2809        use camel_api::aggregator::AggregatorConfig;
2810        use camel_api::splitter::{SplitterConfig, split_body_lines};
2811        use camel_core::route::BuilderStep;
2812
2813        let definition = RouteBuilder::from("timer:tick")
2814            .route_id("test-route")
2815            .split(SplitterConfig::new(split_body_lines()))
2816            .aggregate(
2817                AggregatorConfig::correlate_by("key")
2818                    .complete_when_size(1)
2819                    .build()
2820                    .unwrap(),
2821            )
2822            .end_split()
2823            .build()
2824            .unwrap();
2825
2826        assert_eq!(definition.steps().len(), 1);
2827        if let BuilderStep::Split { steps, .. } = &definition.steps()[0] {
2828            assert!(matches!(steps[0], BuilderStep::Aggregate { .. }));
2829        } else {
2830            panic!("expected Split step");
2831        }
2832    }
2833
2834    // ── set_body / set_body_fn / set_header_fn builder tests ────────────────────
2835
2836    #[test]
2837    fn test_builder_set_body_static_adds_processor() {
2838        let definition = RouteBuilder::from("timer:tick")
2839            .route_id("test-route")
2840            .set_body("fixed")
2841            .build()
2842            .unwrap();
2843        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
2844    }
2845
2846    #[test]
2847    fn test_builder_set_body_fn_adds_processor() {
2848        let definition = RouteBuilder::from("timer:tick")
2849            .route_id("test-route")
2850            .set_body_fn(|_ex: &Exchange| Body::Text("dynamic".into()))
2851            .build()
2852            .unwrap();
2853        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
2854    }
2855
2856    #[test]
2857    fn transform_alias_produces_same_as_set_body() {
2858        let route_transform = RouteBuilder::from("timer:tick")
2859            .route_id("test-route")
2860            .transform("hello")
2861            .build()
2862            .unwrap();
2863
2864        let route_set_body = RouteBuilder::from("timer:tick")
2865            .route_id("test-route")
2866            .set_body("hello")
2867            .build()
2868            .unwrap();
2869
2870        assert_eq!(route_transform.steps().len(), route_set_body.steps().len());
2871    }
2872
2873    #[test]
2874    fn test_builder_set_header_fn_adds_processor() {
2875        let definition = RouteBuilder::from("timer:tick")
2876            .route_id("test-route")
2877            .set_header_fn("k", |_ex: &Exchange| Value::String("v".into()))
2878            .build()
2879            .unwrap();
2880        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
2881    }
2882
2883    #[tokio::test]
2884    async fn test_set_body_static_processor_works() {
2885        use camel_core::route::{CompiledStep, PipelineRuntimeCtx, compose_pipeline};
2886        let def = RouteBuilder::from("t:t")
2887            .route_id("test-route")
2888            .set_body("replaced")
2889            .build()
2890            .unwrap();
2891        let pipeline = compose_pipeline(
2892            def.steps()
2893                .iter()
2894                .filter_map(|s| {
2895                    if let BuilderStep::Processor(op) = s {
2896                        Some(op.0.clone())
2897                    } else {
2898                        None
2899                    }
2900                })
2901                .map(|p| CompiledStep::Process {
2902                    kind_hint: SpanKindHint::Internal,
2903                    processor: p,
2904                    body_contract: None,
2905                    lifecycle: None,
2906                    label: None,
2907                    to_uri: None,
2908                })
2909                .collect(),
2910            PipelineRuntimeCtx::compile_time(),
2911        );
2912        let exchange = Exchange::new(Message::new("original"));
2913        let result = pipeline.oneshot(exchange).await.unwrap();
2914        assert_eq!(result.input.body.as_text(), Some("replaced"));
2915    }
2916
2917    #[tokio::test]
2918    async fn test_set_body_fn_processor_works() {
2919        use camel_core::route::{CompiledStep, PipelineRuntimeCtx, compose_pipeline};
2920        let def = RouteBuilder::from("t:t")
2921            .route_id("test-route")
2922            .set_body_fn(|ex: &Exchange| {
2923                Body::Text(ex.input.body.as_text().unwrap_or("").to_uppercase())
2924            })
2925            .build()
2926            .unwrap();
2927        let pipeline = compose_pipeline(
2928            def.steps()
2929                .iter()
2930                .filter_map(|s| {
2931                    if let BuilderStep::Processor(op) = s {
2932                        Some(op.0.clone())
2933                    } else {
2934                        None
2935                    }
2936                })
2937                .map(|p| CompiledStep::Process {
2938                    kind_hint: SpanKindHint::Internal,
2939                    processor: p,
2940                    body_contract: None,
2941                    lifecycle: None,
2942                    label: None,
2943                    to_uri: None,
2944                })
2945                .collect(),
2946            PipelineRuntimeCtx::compile_time(),
2947        );
2948        let exchange = Exchange::new(Message::new("hello"));
2949        let result = pipeline.oneshot(exchange).await.unwrap();
2950        assert_eq!(result.input.body.as_text(), Some("HELLO"));
2951    }
2952
2953    #[tokio::test]
2954    async fn test_set_header_fn_processor_works() {
2955        use camel_core::route::{CompiledStep, PipelineRuntimeCtx, compose_pipeline};
2956        let def = RouteBuilder::from("t:t")
2957            .route_id("test-route")
2958            .set_header_fn("echo", |ex: &Exchange| {
2959                ex.input
2960                    .body
2961                    .as_text()
2962                    .map(|t| Value::String(t.into()))
2963                    .unwrap_or(Value::Null)
2964            })
2965            .build()
2966            .unwrap();
2967        let pipeline = compose_pipeline(
2968            def.steps()
2969                .iter()
2970                .filter_map(|s| {
2971                    if let BuilderStep::Processor(op) = s {
2972                        Some(op.0.clone())
2973                    } else {
2974                        None
2975                    }
2976                })
2977                .map(|p| CompiledStep::Process {
2978                    kind_hint: SpanKindHint::Internal,
2979                    processor: p,
2980                    body_contract: None,
2981                    lifecycle: None,
2982                    label: None,
2983                    to_uri: None,
2984                })
2985                .collect(),
2986            PipelineRuntimeCtx::compile_time(),
2987        );
2988        let exchange = Exchange::new(Message::new("ping"));
2989        let result = pipeline.oneshot(exchange).await.unwrap();
2990        assert_eq!(
2991            result.input.header("echo"),
2992            Some(&Value::String("ping".into()))
2993        );
2994    }
2995
2996    // ── FilterBuilder typestate tests ─────────────────────────────────────
2997
2998    #[test]
2999    fn test_filter_builder_typestate() {
3000        let result = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
3001            .route_id("test-route")
3002            .filter(|_ex| true)
3003            .to("mock:inner")
3004            .end_filter()
3005            .to("mock:outer")
3006            .build();
3007        assert!(result.is_ok());
3008    }
3009
3010    #[test]
3011    fn test_filter_builder_steps_collected() {
3012        let definition = RouteBuilder::from("timer:tick?period=50&repeatCount=1")
3013            .route_id("test-route")
3014            .filter(|_ex| true)
3015            .to("mock:inner")
3016            .end_filter()
3017            .build()
3018            .unwrap();
3019
3020        assert_eq!(definition.steps().len(), 1);
3021        assert!(matches!(&definition.steps()[0], BuilderStep::Filter { .. }));
3022    }
3023
3024    #[test]
3025    fn test_wire_tap_builder_adds_step() {
3026        let definition = RouteBuilder::from("timer:tick")
3027            .route_id("test-route")
3028            .wire_tap("mock:tap")
3029            .to("mock:result")
3030            .build()
3031            .unwrap();
3032
3033        assert_eq!(definition.steps().len(), 2);
3034        assert!(
3035            matches!(&definition.steps()[0], BuilderStep::WireTap { uri } if uri == "mock:tap")
3036        );
3037        assert!(matches!(&definition.steps()[1], BuilderStep::To(uri) if uri == "mock:result"));
3038    }
3039
3040    // ── MulticastBuilder typestate tests ─────────────────────────────────────
3041
3042    #[test]
3043    fn test_multicast_builder_typestate() {
3044        let definition = RouteBuilder::from("timer:tick")
3045            .route_id("test-route")
3046            .multicast()
3047            .to("direct:a")
3048            .to("direct:b")
3049            .end_multicast()
3050            .to("mock:result")
3051            .build()
3052            .unwrap();
3053
3054        assert_eq!(definition.steps().len(), 2); // Multicast + To("mock:result")
3055    }
3056
3057    #[test]
3058    fn test_multicast_builder_steps_collected() {
3059        let definition = RouteBuilder::from("timer:tick")
3060            .route_id("test-route")
3061            .multicast()
3062            .to("direct:a")
3063            .to("direct:b")
3064            .end_multicast()
3065            .build()
3066            .unwrap();
3067
3068        match &definition.steps()[0] {
3069            BuilderStep::Multicast { steps, .. } => {
3070                assert_eq!(steps.len(), 2);
3071            }
3072            other => panic!("Expected Multicast, got {:?}", other),
3073        }
3074    }
3075
3076    // ── Concurrency builder tests ─────────────────────────────────────
3077
3078    #[test]
3079    fn test_builder_concurrent_sets_concurrency() {
3080        use camel_component_api::ConcurrencyModel;
3081
3082        let definition = RouteBuilder::from("http://0.0.0.0:8080/test")
3083            .route_id("test-route")
3084            .concurrent(16)
3085            .to("log:info")
3086            .build()
3087            .unwrap();
3088
3089        assert_eq!(
3090            definition.concurrency_override(),
3091            Some(&ConcurrencyModel::Concurrent { max: Some(16) })
3092        );
3093    }
3094
3095    #[test]
3096    fn test_builder_concurrent_zero_means_unbounded() {
3097        use camel_component_api::ConcurrencyModel;
3098
3099        let definition = RouteBuilder::from("http://0.0.0.0:8080/test")
3100            .route_id("test-route")
3101            .concurrent(0)
3102            .to("log:info")
3103            .build()
3104            .unwrap();
3105
3106        assert_eq!(
3107            definition.concurrency_override(),
3108            Some(&ConcurrencyModel::Concurrent { max: None })
3109        );
3110    }
3111
3112    #[test]
3113    fn test_builder_sequential_sets_concurrency() {
3114        use camel_component_api::ConcurrencyModel;
3115
3116        let definition = RouteBuilder::from("http://0.0.0.0:8080/test")
3117            .route_id("test-route")
3118            .sequential()
3119            .to("log:info")
3120            .build()
3121            .unwrap();
3122
3123        assert_eq!(
3124            definition.concurrency_override(),
3125            Some(&ConcurrencyModel::Sequential)
3126        );
3127    }
3128
3129    #[test]
3130    fn test_builder_default_concurrency_is_none() {
3131        let definition = RouteBuilder::from("timer:tick")
3132            .route_id("test-route")
3133            .to("log:info")
3134            .build()
3135            .unwrap();
3136
3137        assert_eq!(definition.concurrency_override(), None);
3138    }
3139
3140    // ── Route lifecycle builder tests ─────────────────────────────────────
3141
3142    #[test]
3143    fn test_builder_route_id_sets_id() {
3144        let definition = RouteBuilder::from("timer:tick")
3145            .route_id("my-route")
3146            .build()
3147            .unwrap();
3148
3149        assert_eq!(definition.route_id(), "my-route");
3150    }
3151
3152    #[test]
3153    fn test_build_without_route_id_fails() {
3154        let result = RouteBuilder::from("timer:tick?period=1000")
3155            .to("log:info")
3156            .build();
3157        let err = match result {
3158            Err(e) => e.to_string(),
3159            Ok(_) => panic!("build() should fail without route_id"),
3160        };
3161        assert!(
3162            err.contains("route_id"),
3163            "error should mention route_id, got: {}",
3164            err
3165        );
3166    }
3167
3168    #[test]
3169    fn test_builder_empty_route_id_rejected() {
3170        let result = RouteBuilder::from("timer:tick").route_id("").build();
3171        let err = result.err().expect("empty route_id should be rejected");
3172        assert!(matches!(err, CamelError::RouteError(_)));
3173    }
3174
3175    #[test]
3176    fn test_builder_whitespace_route_id_rejected() {
3177        let result = RouteBuilder::from("timer:tick").route_id("   ").build();
3178        assert!(result.is_err());
3179    }
3180
3181    #[test]
3182    fn test_builder_auto_startup_false() {
3183        let definition = RouteBuilder::from("timer:tick")
3184            .route_id("test-route")
3185            .auto_startup(false)
3186            .build()
3187            .unwrap();
3188
3189        assert!(!definition.auto_startup());
3190    }
3191
3192    #[test]
3193    fn test_builder_startup_order_custom() {
3194        let definition = RouteBuilder::from("timer:tick")
3195            .route_id("test-route")
3196            .startup_order(50)
3197            .build()
3198            .unwrap();
3199
3200        assert_eq!(definition.startup_order(), 50);
3201    }
3202
3203    #[test]
3204    fn test_builder_defaults() {
3205        let definition = RouteBuilder::from("timer:tick")
3206            .route_id("test-route")
3207            .build()
3208            .unwrap();
3209
3210        assert_eq!(definition.route_id(), "test-route");
3211        assert!(definition.auto_startup());
3212        assert_eq!(definition.startup_order(), 1000);
3213    }
3214
3215    // ── Choice typestate tests ──────────────────────────────────────────────────
3216
3217    #[test]
3218    fn test_choice_builder_single_when() {
3219        let definition = RouteBuilder::from("timer:tick")
3220            .route_id("test-route")
3221            .choice()
3222            .when(|ex: &Exchange| ex.input.header("type").is_some())
3223            .to("mock:typed")
3224            .end_when()
3225            .end_choice()
3226            .build()
3227            .unwrap();
3228        assert_eq!(definition.steps().len(), 1);
3229        assert!(
3230            matches!(&definition.steps()[0], BuilderStep::Choice { whens, otherwise }
3231            if whens.len() == 1 && otherwise.is_none())
3232        );
3233    }
3234
3235    #[test]
3236    fn test_choice_builder_when_otherwise() {
3237        let definition = RouteBuilder::from("timer:tick")
3238            .route_id("test-route")
3239            .choice()
3240            .when(|ex: &Exchange| ex.input.header("a").is_some())
3241            .to("mock:a")
3242            .end_when()
3243            .otherwise()
3244            .to("mock:fallback")
3245            .end_otherwise()
3246            .end_choice()
3247            .build()
3248            .unwrap();
3249        assert!(
3250            matches!(&definition.steps()[0], BuilderStep::Choice { whens, otherwise }
3251            if whens.len() == 1 && otherwise.is_some())
3252        );
3253    }
3254
3255    #[test]
3256    fn test_choice_builder_multiple_whens() {
3257        let definition = RouteBuilder::from("timer:tick")
3258            .route_id("test-route")
3259            .choice()
3260            .when(|ex: &Exchange| ex.input.header("a").is_some())
3261            .to("mock:a")
3262            .end_when()
3263            .when(|ex: &Exchange| ex.input.header("b").is_some())
3264            .to("mock:b")
3265            .end_when()
3266            .end_choice()
3267            .build()
3268            .unwrap();
3269        assert!(
3270            matches!(&definition.steps()[0], BuilderStep::Choice { whens, .. }
3271            if whens.len() == 2)
3272        );
3273    }
3274
3275    #[test]
3276    fn test_choice_step_after_choice() {
3277        // Steps after end_choice() are added to the outer pipeline, not inside choice.
3278        let definition = RouteBuilder::from("timer:tick")
3279            .route_id("test-route")
3280            .choice()
3281            .when(|_ex: &Exchange| true)
3282            .to("mock:inner")
3283            .end_when()
3284            .end_choice()
3285            .to("mock:outer") // must be step[1], not inside choice
3286            .build()
3287            .unwrap();
3288        assert_eq!(definition.steps().len(), 2);
3289        assert!(matches!(&definition.steps()[1], BuilderStep::To(uri) if uri == "mock:outer"));
3290    }
3291
3292    // ── Throttle typestate tests ──────────────────────────────────────────────────
3293
3294    #[test]
3295    fn test_throttle_builder_typestate() {
3296        let definition = RouteBuilder::from("timer:tick")
3297            .route_id("test-route")
3298            .throttle(10, std::time::Duration::from_secs(1))
3299            .to("mock:result")
3300            .end_throttle()
3301            .build()
3302            .unwrap();
3303
3304        assert_eq!(definition.steps().len(), 1);
3305        assert!(matches!(
3306            &definition.steps()[0],
3307            BuilderStep::Throttle { .. }
3308        ));
3309    }
3310
3311    #[test]
3312    fn test_throttle_builder_with_strategy() {
3313        let definition = RouteBuilder::from("timer:tick")
3314            .route_id("test-route")
3315            .throttle(10, std::time::Duration::from_secs(1))
3316            .strategy(ThrottleStrategy::Reject)
3317            .to("mock:result")
3318            .end_throttle()
3319            .build()
3320            .unwrap();
3321
3322        if let BuilderStep::Throttle { config, .. } = &definition.steps()[0] {
3323            assert_eq!(config.strategy, ThrottleStrategy::Reject);
3324        } else {
3325            panic!("Expected Throttle step");
3326        }
3327    }
3328
3329    #[test]
3330    fn test_throttle_builder_steps_collected() {
3331        let definition = RouteBuilder::from("timer:tick")
3332            .route_id("test-route")
3333            .throttle(5, std::time::Duration::from_secs(1))
3334            .set_header("throttled", Value::Bool(true))
3335            .to("mock:throttled")
3336            .end_throttle()
3337            .build()
3338            .unwrap();
3339
3340        match &definition.steps()[0] {
3341            BuilderStep::Throttle { steps, .. } => {
3342                assert_eq!(steps.len(), 2); // SetHeader + To
3343            }
3344            other => panic!("Expected Throttle, got {:?}", other),
3345        }
3346    }
3347
3348    #[test]
3349    fn test_throttle_step_after_throttle() {
3350        // Steps after end_throttle() are added to the outer pipeline, not inside throttle.
3351        let definition = RouteBuilder::from("timer:tick")
3352            .route_id("test-route")
3353            .throttle(10, std::time::Duration::from_secs(1))
3354            .to("mock:inner")
3355            .end_throttle()
3356            .to("mock:outer")
3357            .build()
3358            .unwrap();
3359
3360        assert_eq!(definition.steps().len(), 2);
3361        assert!(matches!(&definition.steps()[1], BuilderStep::To(uri) if uri == "mock:outer"));
3362    }
3363
3364    // ── LoadBalance typestate tests ──────────────────────────────────────────────────
3365
3366    #[test]
3367    fn test_load_balance_builder_typestate() {
3368        let definition = RouteBuilder::from("timer:tick")
3369            .route_id("test-route")
3370            .load_balance()
3371            .round_robin()
3372            .to("mock:a")
3373            .to("mock:b")
3374            .end_load_balance()
3375            .build()
3376            .unwrap();
3377
3378        assert_eq!(definition.steps().len(), 1);
3379        assert!(matches!(
3380            &definition.steps()[0],
3381            BuilderStep::LoadBalance { .. }
3382        ));
3383    }
3384
3385    #[test]
3386    fn test_load_balance_builder_with_strategy() {
3387        let definition = RouteBuilder::from("timer:tick")
3388            .route_id("test-route")
3389            .load_balance()
3390            .random()
3391            .to("mock:result")
3392            .end_load_balance()
3393            .build()
3394            .unwrap();
3395
3396        if let BuilderStep::LoadBalance { config, .. } = &definition.steps()[0] {
3397            assert_eq!(config.strategy, LoadBalanceStrategy::Random);
3398        } else {
3399            panic!("Expected LoadBalance step");
3400        }
3401    }
3402
3403    #[test]
3404    fn test_load_balance_builder_steps_collected() {
3405        let definition = RouteBuilder::from("timer:tick")
3406            .route_id("test-route")
3407            .load_balance()
3408            .set_header("lb", Value::Bool(true))
3409            .to("mock:a")
3410            .end_load_balance()
3411            .build()
3412            .unwrap();
3413
3414        match &definition.steps()[0] {
3415            BuilderStep::LoadBalance { steps, .. } => {
3416                assert_eq!(steps.len(), 2); // SetHeader + To
3417            }
3418            other => panic!("Expected LoadBalance, got {:?}", other),
3419        }
3420    }
3421
3422    #[test]
3423    fn test_load_balance_step_after_load_balance() {
3424        // Steps after end_load_balance() are added to the outer pipeline, not inside load_balance.
3425        let definition = RouteBuilder::from("timer:tick")
3426            .route_id("test-route")
3427            .load_balance()
3428            .to("mock:inner")
3429            .end_load_balance()
3430            .to("mock:outer")
3431            .build()
3432            .unwrap();
3433
3434        assert_eq!(definition.steps().len(), 2);
3435        assert!(matches!(&definition.steps()[1], BuilderStep::To(uri) if uri == "mock:outer"));
3436    }
3437
3438    // ── DynamicRouter typestate tests ──────────────────────────────────────────────────
3439
3440    #[test]
3441    fn test_dynamic_router_builder() {
3442        let definition = RouteBuilder::from("timer:tick")
3443            .route_id("test-route")
3444            .dynamic_router(camel_api::TargetSource::Sync(Arc::new(|_| {
3445                Some("mock:result".to_string())
3446            })))
3447            .build()
3448            .unwrap();
3449
3450        assert_eq!(definition.steps().len(), 1);
3451        assert!(matches!(
3452            &definition.steps()[0],
3453            BuilderStep::DynamicRouter { .. }
3454        ));
3455    }
3456
3457    #[test]
3458    fn test_dynamic_router_builder_with_config() {
3459        let config = DynamicRouterConfig::new(camel_api::TargetSource::Sync(Arc::new(|_| {
3460            Some("mock:a".to_string())
3461        })))
3462        .max_iterations(100)
3463        .cache_size(500);
3464
3465        let definition = RouteBuilder::from("timer:tick")
3466            .route_id("test-route")
3467            .dynamic_router_with_config(config)
3468            .build()
3469            .unwrap();
3470
3471        assert_eq!(definition.steps().len(), 1);
3472        if let BuilderStep::DynamicRouter { config } = &definition.steps()[0] {
3473            assert_eq!(config.max_iterations, 100);
3474            assert_eq!(config.cache_size, 500);
3475        } else {
3476            panic!("Expected DynamicRouter step");
3477        }
3478    }
3479
3480    #[test]
3481    fn test_dynamic_router_step_after_router() {
3482        // Steps after dynamic_router() are added to the outer pipeline.
3483        let definition = RouteBuilder::from("timer:tick")
3484            .route_id("test-route")
3485            .dynamic_router(camel_api::TargetSource::Sync(Arc::new(|_| {
3486                Some("mock:inner".to_string())
3487            })))
3488            .to("mock:outer")
3489            .build()
3490            .unwrap();
3491
3492        assert_eq!(definition.steps().len(), 2);
3493        assert!(matches!(
3494            &definition.steps()[0],
3495            BuilderStep::DynamicRouter { .. }
3496        ));
3497        assert!(matches!(&definition.steps()[1], BuilderStep::To(uri) if uri == "mock:outer"));
3498    }
3499
3500    #[test]
3501    fn routing_slip_builder_creates_step() {
3502        use camel_api::TargetSource;
3503
3504        let expression = TargetSource::Sync(Arc::new(|_| Some("direct:a,direct:b".to_string())));
3505
3506        let route = RouteBuilder::from("direct:start")
3507            .route_id("routing-slip-test")
3508            .routing_slip(expression)
3509            .build()
3510            .unwrap();
3511
3512        assert!(
3513            matches!(route.steps()[0], BuilderStep::RoutingSlip { .. }),
3514            "Expected RoutingSlip step"
3515        );
3516    }
3517
3518    #[test]
3519    fn routing_slip_with_config_builder_creates_step() {
3520        use camel_api::RoutingSlipConfig;
3521
3522        let config = RoutingSlipConfig::new(camel_api::TargetSource::Sync(Arc::new(|_| {
3523            Some("mock:a".to_string())
3524        })))
3525        .uri_delimiter("|")
3526        .cache_size(50)
3527        .ignore_invalid_endpoints(true);
3528
3529        let route = RouteBuilder::from("direct:start")
3530            .route_id("routing-slip-config-test")
3531            .routing_slip_with_config(config)
3532            .build()
3533            .unwrap();
3534
3535        if let BuilderStep::RoutingSlip { config } = &route.steps()[0] {
3536            assert_eq!(config.uri_delimiter, "|");
3537            assert_eq!(config.cache_size, 50);
3538            assert!(config.ignore_invalid_endpoints);
3539        } else {
3540            panic!("Expected RoutingSlip step");
3541        }
3542    }
3543
3544    #[test]
3545    fn test_builder_marshal_adds_processor_step() {
3546        let definition = RouteBuilder::from("timer:tick")
3547            .route_id("test-route")
3548            .marshal("json")
3549            .unwrap()
3550            .build()
3551            .unwrap();
3552        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
3553    }
3554
3555    #[test]
3556    fn test_builder_unmarshal_adds_processor_step() {
3557        let definition = RouteBuilder::from("timer:tick")
3558            .route_id("test-route")
3559            .unmarshal("json")
3560            .unwrap()
3561            .build()
3562            .unwrap();
3563        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
3564    }
3565
3566    #[test]
3567    fn test_builder_stream_cache_adds_processor_step() {
3568        let definition = RouteBuilder::from("timer:tick")
3569            .route_id("test-route")
3570            .stream_cache(1024)
3571            .build()
3572            .unwrap();
3573        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
3574    }
3575
3576    #[test]
3577    fn validate_adds_validate_step() {
3578        let def = RouteBuilder::from("direct:in")
3579            .route_id("test")
3580            .validate("schemas/order.xsd")
3581            .build()
3582            .unwrap();
3583        let steps = def.steps();
3584        assert_eq!(steps.len(), 1);
3585        assert!(
3586            matches!(&steps[0], BuilderStep::Validate { predicate } if predicate.language == "simple" && predicate.source == "schemas/order.xsd"),
3587            "got: {:?}",
3588            steps[0]
3589        );
3590    }
3591
3592    #[test]
3593    fn test_builder_marshal_returns_err_for_unknown_format() {
3594        let result = RouteBuilder::from("timer:tick")
3595            .route_id("test-route")
3596            .marshal("protobuf");
3597        let err = match result {
3598            Err(e) => e,
3599            Ok(_) => panic!("marshal with unknown format should return Err"),
3600        };
3601        let msg = err.to_string();
3602        assert!(
3603            msg.contains("unknown data format"),
3604            "error should mention unknown format, got: {msg}"
3605        );
3606        assert!(
3607            msg.contains("protobuf"),
3608            "error should mention format name, got: {msg}"
3609        );
3610    }
3611
3612    #[test]
3613    fn test_builder_unmarshal_returns_err_for_unknown_format() {
3614        let result = RouteBuilder::from("timer:tick")
3615            .route_id("test-route")
3616            .unmarshal("protobuf");
3617        let err = match result {
3618            Err(e) => e,
3619            Ok(_) => panic!("unmarshal with unknown format should return Err"),
3620        };
3621        let msg = err.to_string();
3622        assert!(
3623            msg.contains("unknown data format"),
3624            "error should mention unknown format, got: {msg}"
3625        );
3626        assert!(
3627            msg.contains("protobuf"),
3628            "error should mention format name, got: {msg}"
3629        );
3630    }
3631
3632    #[test]
3633    fn test_builder_recipient_list_creates_step() {
3634        let route = RouteBuilder::from("direct:start")
3635            .route_id("recipient-list-test")
3636            .recipient_list(camel_api::RecipientSource::Sync(Arc::new(|_| {
3637                "direct:a,direct:b".to_string()
3638            })))
3639            .build()
3640            .unwrap();
3641
3642        assert!(matches!(
3643            &route.steps()[0],
3644            BuilderStep::RecipientList { .. }
3645        ));
3646    }
3647
3648    #[test]
3649    fn test_builder_recipient_list_with_config_creates_step() {
3650        let config = RecipientListConfig::new(camel_api::RecipientSource::Sync(Arc::new(|_| {
3651            "mock:a".to_string()
3652        })));
3653
3654        let route = RouteBuilder::from("direct:start")
3655            .route_id("recipient-list-config-test")
3656            .recipient_list_with_config(config)
3657            .build()
3658            .unwrap();
3659
3660        assert!(matches!(
3661            &route.steps()[0],
3662            BuilderStep::RecipientList { .. }
3663        ));
3664    }
3665
3666    #[test]
3667    fn test_builder_script_adds_script_step() {
3668        let route = RouteBuilder::from("direct:start")
3669            .route_id("script-test")
3670            .script("rhai", "headers[\"x\"] = \"y\"")
3671            .build()
3672            .unwrap();
3673
3674        assert!(matches!(
3675            &route.steps()[0],
3676            BuilderStep::Script { language, script }
3677            if language == "rhai" && script == "headers[\"x\"] = \"y\""
3678        ));
3679    }
3680
3681    #[test]
3682    fn test_builder_delay_and_delay_with_header_add_steps() {
3683        let route = RouteBuilder::from("direct:start")
3684            .route_id("delay-test")
3685            .delay(Duration::from_millis(250))
3686            .delay_with_header(Duration::from_millis(500), "x-delay")
3687            .build()
3688            .unwrap();
3689
3690        assert_eq!(route.steps().len(), 2);
3691        assert!(matches!(&route.steps()[0], BuilderStep::Delay { .. }));
3692        assert!(matches!(&route.steps()[1], BuilderStep::Delay { .. }));
3693    }
3694
3695    #[test]
3696    fn test_builder_log_and_stop_add_steps_in_order() {
3697        let route = RouteBuilder::from("direct:start")
3698            .route_id("log-stop-test")
3699            .log("hello", LogLevel::Info)
3700            .stop()
3701            .to("mock:after")
3702            .build()
3703            .unwrap();
3704
3705        assert_eq!(route.steps().len(), 3);
3706        assert!(matches!(
3707            &route.steps()[0],
3708            BuilderStep::Log { message, .. } if message == "hello"
3709        ));
3710        assert!(matches!(&route.steps()[1], BuilderStep::Stop));
3711        assert!(matches!(&route.steps()[2], BuilderStep::To(uri) if uri == "mock:after"));
3712    }
3713
3714    #[test]
3715    fn test_builder_stream_cache_default_adds_processor_step() {
3716        let route = RouteBuilder::from("direct:start")
3717            .route_id("stream-cache-default-test")
3718            .stream_cache_default()
3719            .build()
3720            .unwrap();
3721
3722        assert!(matches!(&route.steps()[0], BuilderStep::Processor(_)));
3723    }
3724
3725    #[test]
3726    fn test_validate_creates_validate_step_with_expression() {
3727        let route = RouteBuilder::from("direct:in")
3728            .route_id("validate-prefix-test")
3729            .validate("${body} != null")
3730            .build()
3731            .unwrap();
3732
3733        assert!(matches!(
3734            &route.steps()[0],
3735            BuilderStep::Validate { predicate } if predicate.language == "simple" && predicate.source == "${body} != null"
3736        ));
3737    }
3738
3739    #[test]
3740    fn test_load_balance_builder_weighted_failover_config() {
3741        let route = RouteBuilder::from("direct:start")
3742            .route_id("lb-weighted-failover")
3743            .load_balance()
3744            .weighted(vec![
3745                ("direct:a".to_string(), 3),
3746                ("direct:b".to_string(), 1),
3747            ])
3748            .failover()
3749            .to("mock:result")
3750            .end_load_balance()
3751            .build()
3752            .unwrap();
3753
3754        if let BuilderStep::LoadBalance { config, .. } = &route.steps()[0] {
3755            assert_eq!(config.strategy, LoadBalanceStrategy::Failover);
3756        } else {
3757            panic!("Expected LoadBalance step");
3758        }
3759    }
3760
3761    #[test]
3762    fn test_multicast_builder_all_config_setters() {
3763        let route = RouteBuilder::from("direct:start")
3764            .route_id("multicast-config-test")
3765            .multicast()
3766            .parallel(true)
3767            .parallel_limit(4)
3768            .stop_on_exception(true)
3769            .timeout(Duration::from_millis(300))
3770            .aggregation(MulticastStrategy::Original)
3771            .to("mock:a")
3772            .end_multicast()
3773            .build()
3774            .unwrap();
3775
3776        if let BuilderStep::Multicast { config, .. } = &route.steps()[0] {
3777            assert!(config.parallel);
3778            assert_eq!(config.parallel_limit, Some(4));
3779            assert!(config.stop_on_exception);
3780            assert_eq!(config.timeout, Some(Duration::from_millis(300)));
3781            assert!(matches!(config.aggregation, MulticastStrategy::Original));
3782        } else {
3783            panic!("Expected Multicast step");
3784        }
3785    }
3786
3787    #[test]
3788    fn test_build_canonical_rejects_unsupported_processor_step() {
3789        let err = RouteBuilder::from("direct:start")
3790            .route_id("canonical-reject")
3791            .set_header("k", Value::String("v".into()))
3792            .build_canonical()
3793            .unwrap_err();
3794
3795        assert!(format!("{err}").contains("does not support step `processor`"));
3796    }
3797
3798    // ── LoadBalance strategy-specific tests ─────────────────────────────────────
3799
3800    #[test]
3801    fn test_load_balance_builder_weighted_strategy() {
3802        let route = RouteBuilder::from("direct:start")
3803            .route_id("lb-weighted")
3804            .load_balance()
3805            .weighted(vec![
3806                ("direct:a".to_string(), 5),
3807                ("direct:b".to_string(), 2),
3808                ("direct:c".to_string(), 1),
3809            ])
3810            .to("mock:result")
3811            .end_load_balance()
3812            .build()
3813            .unwrap();
3814
3815        if let BuilderStep::LoadBalance { config, .. } = &route.steps()[0] {
3816            assert!(matches!(config.strategy, LoadBalanceStrategy::Weighted(_)));
3817        } else {
3818            panic!("Expected LoadBalance step");
3819        }
3820    }
3821
3822    #[test]
3823    fn test_load_balance_builder_failover_strategy() {
3824        let route = RouteBuilder::from("direct:start")
3825            .route_id("lb-failover")
3826            .load_balance()
3827            .failover()
3828            .to("mock:primary")
3829            .end_load_balance()
3830            .build()
3831            .unwrap();
3832
3833        if let BuilderStep::LoadBalance { config, .. } = &route.steps()[0] {
3834            assert_eq!(config.strategy, LoadBalanceStrategy::Failover);
3835        } else {
3836            panic!("Expected LoadBalance step");
3837        }
3838    }
3839
3840    // ── FilterInSplitBuilder tests ──────────────────────────────────────────────
3841
3842    #[test]
3843    fn test_filter_in_split_builder_typestate() {
3844        use camel_api::splitter::{SplitterConfig, split_body_lines};
3845
3846        let definition = RouteBuilder::from("timer:test")
3847            .route_id("filter-in-split")
3848            .split(SplitterConfig::new(split_body_lines()))
3849            .filter(|_ex| true)
3850            .to("mock:filtered")
3851            .end_filter()
3852            .end_split()
3853            .build()
3854            .unwrap();
3855
3856        assert_eq!(definition.steps().len(), 1);
3857        if let BuilderStep::Split { steps, .. } = &definition.steps()[0] {
3858            assert_eq!(steps.len(), 1);
3859            assert!(matches!(&steps[0], BuilderStep::Filter { .. }));
3860        } else {
3861            panic!("Expected Split step");
3862        }
3863    }
3864
3865    #[test]
3866    fn test_filter_in_split_builder_multiple_steps() {
3867        use camel_api::splitter::{SplitterConfig, split_body_lines};
3868
3869        let definition = RouteBuilder::from("timer:test")
3870            .route_id("filter-in-split-multi")
3871            .split(SplitterConfig::new(split_body_lines()))
3872            .to("mock:before-filter")
3873            .filter(|_ex| true)
3874            .to("mock:inside-filter")
3875            .end_filter()
3876            .to("mock:after-filter")
3877            .end_split()
3878            .build()
3879            .unwrap();
3880
3881        if let BuilderStep::Split { steps, .. } = &definition.steps()[0] {
3882            // To("before-filter") + Filter{...} + To("after-filter") = 3
3883            assert_eq!(steps.len(), 3);
3884        } else {
3885            panic!("Expected Split step");
3886        }
3887    }
3888
3889    // ── build_canonical tests ───────────────────────────────────────────────────
3890
3891    #[test]
3892    fn test_build_canonical_with_circuit_breaker() {
3893        use camel_api::circuit_breaker::CircuitBreakerConfig;
3894
3895        let spec = RouteBuilder::from("direct:start")
3896            .route_id("canonical-cb")
3897            .circuit_breaker(CircuitBreakerConfig::new().failure_threshold(10))
3898            .to("mock:result")
3899            .build_canonical()
3900            .unwrap();
3901
3902        let cb = spec.circuit_breaker.expect("circuit breaker should be set");
3903        assert_eq!(cb.failure_threshold, 10);
3904    }
3905
3906    #[test]
3907    fn test_build_canonical_rejects_custom_split_aggregation() {
3908        use camel_api::splitter::{SplitterConfig, split_body_lines};
3909
3910        let err = RouteBuilder::from("direct:start")
3911            .route_id("canonical-custom-split")
3912            .split(SplitterConfig::new(split_body_lines()).aggregation(
3913                camel_api::splitter::AggregationStrategy::Custom(Arc::new(|_, ex| ex)),
3914            ))
3915            .to("mock:frag")
3916            .end_split()
3917            .build_canonical()
3918            .unwrap_err();
3919
3920        // Split with closure-based expression is rejected in canonical v2.
3921        assert!(format!("{err}").contains("canonical v2 does not support step `split`"));
3922    }
3923
3924    #[test]
3925    fn test_build_canonical_rejects_custom_aggregate_strategy() {
3926        let err = RouteBuilder::from("direct:start")
3927            .route_id("canonical-custom-agg")
3928            .aggregate(
3929                AggregatorConfig::correlate_by("key")
3930                    .complete_when_size(2)
3931                    .strategy(AggregationStrategy::Custom(Arc::new(|_, ex| ex)))
3932                    .build()
3933                    .unwrap(),
3934            )
3935            .build_canonical()
3936            .unwrap_err();
3937
3938        assert!(format!("{err}").contains("custom aggregate strategy"));
3939    }
3940
3941    #[test]
3942    fn test_build_canonical_rejects_fn_correlation_strategy() {
3943        let err = RouteBuilder::from("direct:start")
3944            .route_id("canonical-fn-corr")
3945            .aggregate(AggregatorConfig {
3946                header_name: "key".to_string(),
3947                completion: CompletionMode::Single(CompletionCondition::Size(1)),
3948                correlation: CorrelationStrategy::Fn(Arc::new(|_| Some("key".to_string()))),
3949                strategy: AggregationStrategy::CollectAll,
3950                max_buckets: None,
3951                max_bucket_size: None,
3952                bucket_ttl: None,
3953                force_completion_on_stop: false,
3954                discard_on_timeout: false,
3955                max_timeout_tasks: 1024,
3956            })
3957            .build_canonical()
3958            .unwrap_err();
3959
3960        assert!(format!("{err}").contains("Fn correlation strategy"));
3961    }
3962
3963    #[test]
3964    fn test_build_canonical_rejects_predicate_completion() {
3965        let err = RouteBuilder::from("direct:start")
3966            .route_id("canonical-pred-completion")
3967            .aggregate(AggregatorConfig {
3968                header_name: "key".to_string(),
3969                completion: CompletionMode::Single(CompletionCondition::Predicate(Arc::new(
3970                    |_| false,
3971                ))),
3972                correlation: CorrelationStrategy::HeaderName("key".to_string()),
3973                strategy: AggregationStrategy::CollectAll,
3974                max_buckets: None,
3975                max_bucket_size: None,
3976                bucket_ttl: None,
3977                force_completion_on_stop: false,
3978                discard_on_timeout: false,
3979                max_timeout_tasks: 1024,
3980            })
3981            .build_canonical()
3982            .unwrap_err();
3983
3984        assert!(
3985            format!("{err}").contains("cannot reverse-map"),
3986            "reject message must explain forward-only: {}",
3987            err
3988        );
3989    }
3990
3991    #[test]
3992    fn extract_completion_fields_rejects_predicate_expr() {
3993        let mode = CompletionMode::Single(CompletionCondition::PredicateExpr {
3994            expr: "${body} == 'DONE'".to_string(),
3995            language: "simple".to_string(),
3996        });
3997        let result = extract_completion_fields(&mode);
3998        assert!(
3999            result.is_err(),
4000            "PredicateExpr must be rejected (forward-only)"
4001        );
4002        let msg = format!("{}", result.unwrap_err());
4003        assert!(
4004            msg.contains("cannot reverse-map"),
4005            "reject message must explain forward-only: {}",
4006            msg
4007        );
4008    }
4009
4010    #[test]
4011    fn extract_completion_fields_rejects_predicate_expr_any_mode() {
4012        let mode = CompletionMode::Any(vec![
4013            CompletionCondition::Size(5),
4014            CompletionCondition::PredicateExpr {
4015                expr: "${body} == 'DONE'".to_string(),
4016                language: "simple".to_string(),
4017            },
4018        ]);
4019        let result = extract_completion_fields(&mode);
4020        assert!(
4021            result.is_err(),
4022            "PredicateExpr in Any must be rejected (forward-only)"
4023        );
4024        let msg = format!("{}", result.unwrap_err());
4025        assert!(
4026            msg.contains("cannot reverse-map"),
4027            "reject message must explain forward-only: {}",
4028            msg
4029        );
4030    }
4031
4032    #[test]
4033    fn test_build_canonical_with_expression_correlation() {
4034        let spec = RouteBuilder::from("direct:start")
4035            .route_id("canonical-expr-corr")
4036            .aggregate(AggregatorConfig {
4037                header_name: "key".to_string(),
4038                completion: CompletionMode::Single(CompletionCondition::Size(1)),
4039                correlation: CorrelationStrategy::Expression {
4040                    expr: "header.key".to_string(),
4041                    language: "simple".to_string(),
4042                },
4043                strategy: AggregationStrategy::CollectAll,
4044                max_buckets: None,
4045                max_bucket_size: None,
4046                bucket_ttl: None,
4047                force_completion_on_stop: false,
4048                discard_on_timeout: false,
4049                max_timeout_tasks: 1024,
4050            })
4051            .build_canonical()
4052            .unwrap();
4053
4054        assert!(spec.steps.iter().any(|s| matches!(s, CanonicalStepSpec::Aggregate(a) if a.correlation_key == Some("header.key".to_string()))));
4055    }
4056
4057    #[test]
4058    fn test_build_canonical_split_rejected_with_closure_expression() {
4059        use camel_api::splitter::{AggregationStrategy, SplitterConfig, split_body_lines};
4060
4061        // Builder-based split uses closure expressions, which are not serializable.
4062        let err = RouteBuilder::from("direct:start")
4063            .route_id("canonical-split-last")
4064            .split(
4065                SplitterConfig::new(split_body_lines()).aggregation(AggregationStrategy::LastWins),
4066            )
4067            .to("mock:frag")
4068            .end_split()
4069            .build_canonical()
4070            .unwrap_err();
4071
4072        assert!(format!("{err}").contains("canonical v2 does not support step `split`"));
4073    }
4074
4075    // ── OnExceptionBuilder full chain tests ─────────────────────────────────────
4076
4077    #[test]
4078    fn test_on_exception_full_chain_retry_backoff_jitter_handled_by() {
4079        let definition = RouteBuilder::from("direct:start")
4080            .route_id("on-exception-full")
4081            .dead_letter_channel("log:dlc")
4082            .on_exception(|e| matches!(e, CamelError::Io(_)))
4083            .retry(5)
4084            .with_backoff(Duration::from_millis(10), 2.0, Duration::from_millis(500))
4085            .with_jitter(0.3)
4086            .handled_by("log:io-handler")
4087            .end_on_exception()
4088            .to("mock:out")
4089            .build()
4090            .unwrap();
4091
4092        let cfg = definition
4093            .error_handler_config()
4094            .expect("error handler should be set");
4095        assert_eq!(cfg.policies.len(), 1);
4096        let policy = &cfg.policies[0];
4097        let retry = policy.retry.as_ref().expect("retry should be set");
4098        assert_eq!(retry.max_attempts, 5);
4099        assert_eq!(retry.initial_delay, Duration::from_millis(10));
4100        assert_eq!(retry.multiplier, 2.0);
4101        assert_eq!(retry.max_delay, Duration::from_millis(500));
4102        assert!((retry.jitter_factor - 0.3).abs() < f64::EPSILON);
4103        assert_eq!(policy.handled_by.as_deref(), Some("log:io-handler"));
4104    }
4105
4106    #[test]
4107    fn test_on_exception_jitter_clamped_to_valid_range() {
4108        let definition = RouteBuilder::from("direct:start")
4109            .route_id("jitter-clamp")
4110            .on_exception(|_e| true)
4111            .retry(1)
4112            .with_jitter(5.0)
4113            .end_on_exception()
4114            .to("mock:out")
4115            .build()
4116            .unwrap();
4117
4118        let cfg = definition.error_handler_config().unwrap();
4119        let retry = cfg.policies[0].retry.as_ref().unwrap();
4120        assert!((retry.jitter_factor - 1.0).abs() < f64::EPSILON);
4121    }
4122
4123    // ── StepAccumulator: process_fn, convert_body_to, bean ──────────────────────
4124
4125    #[test]
4126    fn test_builder_process_fn_adds_processor_step() {
4127        use camel_api::BoxProcessorExt;
4128        let processor = BoxProcessor::from_fn(|ex| Box::pin(async move { Ok(ex) }));
4129        let definition = RouteBuilder::from("timer:tick")
4130            .route_id("process-fn-test")
4131            .process_fn(processor)
4132            .build()
4133            .unwrap();
4134
4135        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
4136    }
4137
4138    #[test]
4139    fn test_builder_convert_body_to_adds_processor_step() {
4140        let definition = RouteBuilder::from("timer:tick")
4141            .route_id("convert-body-test")
4142            .convert_body_to(BodyType::Json)
4143            .build()
4144            .unwrap();
4145
4146        assert!(matches!(&definition.steps()[0], BuilderStep::Processor(_)));
4147    }
4148
4149    #[test]
4150    fn test_builder_bean_adds_bean_step() {
4151        let definition = RouteBuilder::from("timer:tick")
4152            .route_id("bean-test")
4153            .bean("myBean", "process")
4154            .build()
4155            .unwrap();
4156
4157        assert!(
4158            matches!(&definition.steps()[0], BuilderStep::Bean { name, method }
4159            if name == "myBean" && method == "process")
4160        );
4161    }
4162
4163    // ── Throttle strategy-specific tests ────────────────────────────────────────
4164
4165    #[test]
4166    fn test_throttle_builder_delay_strategy() {
4167        let definition = RouteBuilder::from("timer:tick")
4168            .route_id("throttle-delay")
4169            .throttle(10, Duration::from_secs(1))
4170            .strategy(ThrottleStrategy::Delay)
4171            .to("mock:result")
4172            .end_throttle()
4173            .build()
4174            .unwrap();
4175
4176        if let BuilderStep::Throttle { config, .. } = &definition.steps()[0] {
4177            assert_eq!(config.strategy, ThrottleStrategy::Delay);
4178        } else {
4179            panic!("Expected Throttle step");
4180        }
4181    }
4182
4183    #[test]
4184    fn test_throttle_builder_drop_strategy() {
4185        let definition = RouteBuilder::from("timer:tick")
4186            .route_id("throttle-drop")
4187            .throttle(10, Duration::from_secs(1))
4188            .strategy(ThrottleStrategy::Drop)
4189            .to("mock:result")
4190            .end_throttle()
4191            .build()
4192            .unwrap();
4193
4194        if let BuilderStep::Throttle { config, .. } = &definition.steps()[0] {
4195            assert_eq!(config.strategy, ThrottleStrategy::Drop);
4196        } else {
4197            panic!("Expected Throttle step");
4198        }
4199    }
4200
4201    // ── LoopInLoopBuilder with loop_while ───────────────────────────────────────
4202
4203    #[test]
4204    fn test_nested_loop_while_builder() {
4205        use camel_api::loop_eip::LoopMode;
4206
4207        let def = RouteBuilder::from("direct:start")
4208            .route_id("nested-loop-while")
4209            .loop_count(2)
4210            .to("mock:outer")
4211            .loop_while(|_ex| true)
4212            .to("mock:inner")
4213            .end_loop()
4214            .end_loop()
4215            .build()
4216            .unwrap();
4217
4218        assert_eq!(def.steps().len(), 1);
4219        if let BuilderStep::Loop { steps, .. } = &def.steps()[0] {
4220            assert_eq!(steps.len(), 2);
4221            if let BuilderStep::Loop { config, .. } = &steps[1] {
4222                assert!(matches!(config.mode, LoopMode::While(_)));
4223            } else {
4224                panic!("Expected inner Loop step");
4225            }
4226        } else {
4227            panic!("Expected outer Loop step");
4228        }
4229    }
4230
4231    // ── Choice with multiple whens + otherwise ──────────────────────────────────
4232
4233    #[test]
4234    fn test_choice_builder_multiple_whens_with_otherwise() {
4235        let definition = RouteBuilder::from("timer:tick")
4236            .route_id("choice-multi-otherwise")
4237            .choice()
4238            .when(|ex: &Exchange| ex.input.header("a").is_some())
4239            .to("mock:a")
4240            .end_when()
4241            .when(|ex: &Exchange| ex.input.header("b").is_some())
4242            .to("mock:b")
4243            .end_when()
4244            .when(|ex: &Exchange| ex.input.header("c").is_some())
4245            .to("mock:c")
4246            .end_when()
4247            .otherwise()
4248            .to("mock:fallback")
4249            .end_otherwise()
4250            .end_choice()
4251            .build()
4252            .unwrap();
4253
4254        if let BuilderStep::Choice { whens, otherwise } = &definition.steps()[0] {
4255            assert_eq!(whens.len(), 3);
4256            assert!(otherwise.is_some());
4257            assert_eq!(otherwise.as_ref().unwrap().len(), 1);
4258        } else {
4259            panic!("Expected Choice step");
4260        }
4261    }
4262
4263    // ── Multicast individual config tests ───────────────────────────────────────
4264
4265    #[test]
4266    fn test_multicast_builder_parallel_only() {
4267        let route = RouteBuilder::from("direct:start")
4268            .route_id("multicast-parallel")
4269            .multicast()
4270            .parallel(true)
4271            .to("mock:a")
4272            .end_multicast()
4273            .build()
4274            .unwrap();
4275
4276        if let BuilderStep::Multicast { config, .. } = &route.steps()[0] {
4277            assert!(config.parallel);
4278            assert_eq!(config.parallel_limit, None);
4279        } else {
4280            panic!("Expected Multicast step");
4281        }
4282    }
4283
4284    #[test]
4285    fn test_multicast_builder_timeout_only() {
4286        let route = RouteBuilder::from("direct:start")
4287            .route_id("multicast-timeout")
4288            .multicast()
4289            .timeout(Duration::from_secs(5))
4290            .to("mock:a")
4291            .end_multicast()
4292            .build()
4293            .unwrap();
4294
4295        if let BuilderStep::Multicast { config, .. } = &route.steps()[0] {
4296            assert_eq!(config.timeout, Some(Duration::from_secs(5)));
4297        } else {
4298            panic!("Expected Multicast step");
4299        }
4300    }
4301
4302    #[test]
4303    fn test_multicast_builder_aggregation_collect_all() {
4304        let route = RouteBuilder::from("direct:start")
4305            .route_id("multicast-collect")
4306            .multicast()
4307            .aggregation(MulticastStrategy::CollectAll)
4308            .to("mock:a")
4309            .end_multicast()
4310            .build()
4311            .unwrap();
4312
4313        if let BuilderStep::Multicast { config, .. } = &route.steps()[0] {
4314            assert!(matches!(config.aggregation, MulticastStrategy::CollectAll));
4315        } else {
4316            panic!("Expected Multicast step");
4317        }
4318    }
4319
4320    // ── extract_completion_fields: Any mode with multiple conditions ────────────
4321
4322    #[test]
4323    fn test_build_canonical_aggregate_any_completion_mode() {
4324        let spec = RouteBuilder::from("direct:start")
4325            .route_id("canonical-any-completion")
4326            .aggregate(
4327                AggregatorConfig::correlate_by("key")
4328                    .complete_on_size_or_timeout(10, Duration::from_secs(30))
4329                    .build()
4330                    .unwrap(),
4331            )
4332            .build_canonical()
4333            .unwrap();
4334
4335        if let CanonicalStepSpec::Aggregate(agg) = &spec.steps[0] {
4336            assert_eq!(agg.completion_size, Some(10));
4337            assert_eq!(agg.completion_timeout_ms, Some(30_000));
4338        } else {
4339            panic!("Expected Aggregate step");
4340        }
4341    }
4342
4343    #[test]
4344    fn test_build_canonical_aggregate_timeout_completion() {
4345        let spec = RouteBuilder::from("direct:start")
4346            .route_id("canonical-timeout-completion")
4347            .aggregate(
4348                AggregatorConfig::correlate_by("key")
4349                    .complete_on_timeout(Duration::from_millis(500))
4350                    .build()
4351                    .unwrap(),
4352            )
4353            .build_canonical()
4354            .unwrap();
4355
4356        if let CanonicalStepSpec::Aggregate(agg) = &spec.steps[0] {
4357            assert_eq!(agg.completion_size, None);
4358            assert_eq!(agg.completion_timeout_ms, Some(500));
4359        } else {
4360            panic!("Expected Aggregate step");
4361        }
4362    }
4363
4364    // ── canonicalize_aggregate: discard_on_timeout and force_completion_on_stop ─
4365
4366    #[test]
4367    fn test_build_canonical_aggregate_discard_on_timeout() {
4368        use camel_api::aggregator::AggregatorConfig;
4369
4370        let spec = RouteBuilder::from("direct:start")
4371            .route_id("canonical-discard-timeout")
4372            .aggregate(
4373                AggregatorConfig::correlate_by("key")
4374                    .complete_when_size(1)
4375                    .discard_on_timeout(true)
4376                    .build()
4377                    .unwrap(),
4378            )
4379            .build_canonical()
4380            .unwrap();
4381
4382        if let CanonicalStepSpec::Aggregate(agg) = &spec.steps[0] {
4383            assert_eq!(agg.discard_on_timeout, Some(true));
4384        } else {
4385            panic!("Expected Aggregate step");
4386        }
4387    }
4388
4389    #[test]
4390    fn test_build_canonical_aggregate_force_completion_on_stop() {
4391        use camel_api::aggregator::AggregatorConfig;
4392
4393        let spec = RouteBuilder::from("direct:start")
4394            .route_id("canonical-force-stop")
4395            .aggregate(
4396                AggregatorConfig::correlate_by("key")
4397                    .complete_when_size(1)
4398                    .force_completion_on_stop(true)
4399                    .build()
4400                    .unwrap(),
4401            )
4402            .build_canonical()
4403            .unwrap();
4404
4405        if let CanonicalStepSpec::Aggregate(agg) = &spec.steps[0] {
4406            assert_eq!(agg.force_completion_on_stop, Some(true));
4407        } else {
4408            panic!("Expected Aggregate step");
4409        }
4410    }
4411
4412    // ── build_canonical: max_buckets and bucket_ttl ─────────────────────────────
4413
4414    #[test]
4415    fn test_build_canonical_aggregate_max_buckets_and_ttl() {
4416        use camel_api::aggregator::AggregatorConfig;
4417
4418        let spec = RouteBuilder::from("direct:start")
4419            .route_id("canonical-buckets-ttl")
4420            .aggregate(
4421                AggregatorConfig::correlate_by("key")
4422                    .complete_when_size(1)
4423                    .max_buckets(100)
4424                    .bucket_ttl(Duration::from_secs(60))
4425                    .build()
4426                    .unwrap(),
4427            )
4428            .build_canonical()
4429            .unwrap();
4430
4431        if let CanonicalStepSpec::Aggregate(agg) = &spec.steps[0] {
4432            assert_eq!(agg.max_buckets, Some(100));
4433            assert_eq!(agg.bucket_ttl_ms, Some(60_000));
4434        } else {
4435            panic!("Expected Aggregate step");
4436        }
4437    }
4438
4439    // ── canonicalize_aggregate: correlation strategy → correlation_key mapping ──
4440    //
4441    // These tests pin the canonicalize half of the expression round-trip
4442    // scenario. The recompile half is
4443    // `canonical_recompile_of_canonicalized_expression_config_yields_expression`
4444    // in camel-dsl compile.rs (task 2.4) — camel-builder has no camel-dsl
4445    // dependency, so the two halves live in their own crates.
4446
4447    #[test]
4448    fn canonicalize_aggregate_expression_maps_correlation_key() {
4449        use camel_api::aggregator::AggregatorConfig;
4450
4451        let config = AggregatorConfig::correlate_by("seed")
4452            .correlate_by_expr("${header.orderId}", "simple")
4453            .complete_when_size(2)
4454            .build()
4455            .unwrap();
4456
4457        let spec = canonicalize_aggregate(config).unwrap();
4458
4459        assert_eq!(spec.correlation_key, Some("${header.orderId}".to_string()));
4460        assert_eq!(spec.header, "${header.orderId}");
4461    }
4462
4463    #[test]
4464    fn canonicalize_aggregate_header_only_maps_no_correlation_key() {
4465        use camel_api::aggregator::AggregatorConfig;
4466
4467        let config = AggregatorConfig::correlate_by("orderId")
4468            .complete_when_size(2)
4469            .build()
4470            .unwrap();
4471
4472        let spec = canonicalize_aggregate(config).unwrap();
4473
4474        assert_eq!(spec.correlation_key, None);
4475        assert_eq!(spec.header, "orderId");
4476    }
4477
4478    // ── SplitBuilder with filter inside ─────────────────────────────────────────
4479
4480    #[test]
4481    fn test_split_builder_with_filter_inside() {
4482        use camel_api::splitter::{SplitterConfig, split_body_lines};
4483
4484        let definition = RouteBuilder::from("timer:test")
4485            .route_id("split-with-filter")
4486            .split(SplitterConfig::new(split_body_lines()))
4487            .filter(|_ex| true)
4488            .to("mock:filtered-frag")
4489            .end_filter()
4490            .end_split()
4491            .build()
4492            .unwrap();
4493
4494        if let BuilderStep::Split { steps, .. } = &definition.steps()[0] {
4495            assert_eq!(steps.len(), 1);
4496            assert!(matches!(&steps[0], BuilderStep::Filter { .. }));
4497        } else {
4498            panic!("Expected Split step");
4499        }
4500    }
4501
4502    // ── WireTap additional tests ────────────────────────────────────────────────
4503
4504    #[test]
4505    fn test_wire_tap_multiple_taps() {
4506        let definition = RouteBuilder::from("timer:tick")
4507            .route_id("multi-wire-tap")
4508            .wire_tap("mock:tap1")
4509            .wire_tap("mock:tap2")
4510            .to("mock:result")
4511            .build()
4512            .unwrap();
4513
4514        assert_eq!(definition.steps().len(), 3);
4515        assert!(
4516            matches!(&definition.steps()[0], BuilderStep::WireTap { uri } if uri == "mock:tap1")
4517        );
4518        assert!(
4519            matches!(&definition.steps()[1], BuilderStep::WireTap { uri } if uri == "mock:tap2")
4520        );
4521    }
4522
4523    // ── Error handler: explicit config after shorthand → Mixed mode ─────────────
4524
4525    #[test]
4526    fn test_builder_shorthand_then_explicit_mixed_mode() {
4527        let result = RouteBuilder::from("direct:start")
4528            .route_id("mixed-mode-2")
4529            .dead_letter_channel("log:dlc")
4530            .error_handler(ErrorHandlerConfig::log_only())
4531            .to("mock:out")
4532            .build();
4533
4534        let err = result.err().expect("mixed mode should fail");
4535        assert!(format!("{err}").contains("mixed error handler modes"));
4536    }
4537
4538    // ── build_canonical: empty from_uri error ───────────────────────────────────
4539
4540    #[test]
4541    fn test_build_canonical_empty_from_uri_errors() {
4542        let result = RouteBuilder::from("").route_id("test").build_canonical();
4543        assert!(result.is_err());
4544    }
4545
4546    #[test]
4547    fn test_build_canonical_missing_route_id_errors() {
4548        let result = RouteBuilder::from("direct:start").build_canonical();
4549        assert!(result.is_err());
4550        let err = result.unwrap_err().to_string();
4551        assert!(err.contains("route_id"));
4552    }
4553
4554    // ── SplitBuilder: aggregate inside split ────────────────────────────────────
4555
4556    #[test]
4557    fn test_split_builder_with_aggregate_inside() {
4558        use camel_api::aggregator::AggregatorConfig;
4559        use camel_api::splitter::{SplitterConfig, split_body_lines};
4560
4561        let definition = RouteBuilder::from("timer:test")
4562            .route_id("split-agg")
4563            .split(SplitterConfig::new(split_body_lines()))
4564            .aggregate(
4565                AggregatorConfig::correlate_by("frag-key")
4566                    .complete_when_size(3)
4567                    .build()
4568                    .unwrap(),
4569            )
4570            .end_split()
4571            .build()
4572            .unwrap();
4573
4574        if let BuilderStep::Split { steps, .. } = &definition.steps()[0] {
4575            assert_eq!(steps.len(), 1);
4576            assert!(matches!(&steps[0], BuilderStep::Aggregate { .. }));
4577        } else {
4578            panic!("Expected Split step");
4579        }
4580    }
4581
4582    // ── Throttle: steps collected inside throttle scope ─────────────────────────
4583
4584    #[test]
4585    fn test_throttle_builder_with_steps_inside() {
4586        let definition = RouteBuilder::from("timer:tick")
4587            .route_id("throttle-steps")
4588            .throttle(10, Duration::from_secs(1))
4589            .set_header("throttled", Value::Bool(true))
4590            .to("mock:throttled")
4591            .end_throttle()
4592            .build()
4593            .unwrap();
4594
4595        if let BuilderStep::Throttle { steps, .. } = &definition.steps()[0] {
4596            assert_eq!(steps.len(), 2);
4597        } else {
4598            panic!("Expected Throttle step");
4599        }
4600    }
4601
4602    // ── LoadBalance: steps collected inside scope ───────────────────────────────
4603
4604    #[test]
4605    fn test_load_balance_builder_with_steps_inside() {
4606        let definition = RouteBuilder::from("timer:tick")
4607            .route_id("lb-steps")
4608            .load_balance()
4609            .round_robin()
4610            .set_header("lb", Value::Bool(true))
4611            .to("mock:lb")
4612            .end_load_balance()
4613            .build()
4614            .unwrap();
4615
4616        if let BuilderStep::LoadBalance { steps, .. } = &definition.steps()[0] {
4617            assert_eq!(steps.len(), 2);
4618        } else {
4619            panic!("Expected LoadBalance step");
4620        }
4621    }
4622
4623    // ── Multicast: steps collected inside scope ─────────────────────────────────
4624
4625    #[test]
4626    fn test_multicast_builder_with_steps_inside() {
4627        let definition = RouteBuilder::from("timer:tick")
4628            .route_id("multicast-steps")
4629            .multicast()
4630            .set_header("mc", Value::Bool(true))
4631            .to("mock:multicast")
4632            .end_multicast()
4633            .build()
4634            .unwrap();
4635
4636        if let BuilderStep::Multicast { steps, .. } = &definition.steps()[0] {
4637            assert_eq!(steps.len(), 2);
4638        } else {
4639            panic!("Expected Multicast step");
4640        }
4641    }
4642
4643    // ── LoopBuilder: steps collected inside loop scope ──────────────────────────
4644
4645    #[test]
4646    fn test_loop_builder_with_steps_inside() {
4647        let definition = RouteBuilder::from("timer:tick")
4648            .route_id("loop-steps")
4649            .loop_count(3)
4650            .set_header("loop", Value::Bool(true))
4651            .to("mock:loop")
4652            .end_loop()
4653            .build()
4654            .unwrap();
4655
4656        if let BuilderStep::Loop { steps, .. } = &definition.steps()[0] {
4657            assert_eq!(steps.len(), 2);
4658        } else {
4659            panic!("Expected Loop step");
4660        }
4661    }
4662
4663    // ── canonical_step_name coverage for remaining variants ─────────────────────
4664
4665    #[test]
4666    fn test_build_canonical_rejects_loop_step() {
4667        let err = RouteBuilder::from("direct:start")
4668            .route_id("canonical-loop")
4669            .loop_count(3)
4670            .to("mock:loop")
4671            .end_loop()
4672            .build_canonical()
4673            .unwrap_err();
4674
4675        assert!(format!("{err}").contains("does not support step `loop`"));
4676    }
4677
4678    #[test]
4679    fn test_build_canonical_rejects_multicast_step() {
4680        let err = RouteBuilder::from("direct:start")
4681            .route_id("canonical-multicast")
4682            .multicast()
4683            .to("mock:a")
4684            .end_multicast()
4685            .build_canonical()
4686            .unwrap_err();
4687
4688        assert!(format!("{err}").contains("does not support step `multicast`"));
4689    }
4690
4691    #[test]
4692    fn test_build_canonical_rejects_throttle_step() {
4693        let err = RouteBuilder::from("direct:start")
4694            .route_id("canonical-throttle")
4695            .throttle(10, Duration::from_secs(1))
4696            .to("mock:result")
4697            .end_throttle()
4698            .build_canonical()
4699            .unwrap_err();
4700
4701        assert!(format!("{err}").contains("does not support step `throttle`"));
4702    }
4703
4704    #[test]
4705    fn test_build_canonical_rejects_load_balancer_step() {
4706        let err = RouteBuilder::from("direct:start")
4707            .route_id("canonical-lb")
4708            .load_balance()
4709            .round_robin()
4710            .to("mock:result")
4711            .end_load_balance()
4712            .build_canonical()
4713            .unwrap_err();
4714
4715        assert!(format!("{err}").contains("does not support step `load_balancer`"));
4716    }
4717
4718    #[test]
4719    fn test_build_canonical_rejects_bean_step() {
4720        let err = RouteBuilder::from("direct:start")
4721            .route_id("canonical-bean")
4722            .bean("myBean", "process")
4723            .build_canonical()
4724            .unwrap_err();
4725
4726        assert!(format!("{err}").contains("does not support step `bean`"));
4727    }
4728
4729    #[test]
4730    fn test_build_canonical_rejects_script_step() {
4731        let err = RouteBuilder::from("direct:start")
4732            .route_id("canonical-script")
4733            .script("rhai", "x = 1")
4734            .build_canonical()
4735            .unwrap_err();
4736
4737        assert!(format!("{err}").contains("does not support step `script`"));
4738    }
4739
4740    #[test]
4741    fn test_build_canonical_accepts_delay_step() {
4742        let spec = RouteBuilder::from("direct:start")
4743            .route_id("canonical-delay")
4744            .delay(Duration::from_millis(100))
4745            .build_canonical()
4746            .unwrap();
4747
4748        assert!(
4749            spec.steps.iter().any(
4750                |s| matches!(s, CanonicalStepSpec::Delay { delay_ms, .. } if *delay_ms == 100)
4751            )
4752        );
4753    }
4754
4755    #[test]
4756    fn test_build_canonical_accepts_wire_tap_step() {
4757        let spec = RouteBuilder::from("direct:start")
4758            .route_id("canonical-wiretap")
4759            .wire_tap("mock:tap")
4760            .build_canonical()
4761            .unwrap();
4762
4763        assert!(
4764            spec.steps
4765                .iter()
4766                .any(|s| matches!(s, CanonicalStepSpec::WireTap { uri } if uri == "mock:tap"))
4767        );
4768    }
4769
4770    #[test]
4771    fn test_build_canonical_rejects_dynamic_router_step() {
4772        let err = RouteBuilder::from("direct:start")
4773            .route_id("canonical-dyn-router")
4774            .dynamic_router(camel_api::TargetSource::Sync(Arc::new(|_| {
4775                Some("mock:a".to_string())
4776            })))
4777            .build_canonical()
4778            .unwrap_err();
4779
4780        assert!(format!("{err}").contains("does not support step `dynamic_router`"));
4781    }
4782
4783    #[test]
4784    fn test_build_canonical_rejects_routing_slip_step() {
4785        let err = RouteBuilder::from("direct:start")
4786            .route_id("canonical-routing-slip")
4787            .routing_slip(camel_api::TargetSource::Sync(Arc::new(|_| {
4788                Some("mock:a".to_string())
4789            })))
4790            .build_canonical()
4791            .unwrap_err();
4792
4793        assert!(format!("{err}").contains("does not support step `routing_slip`"));
4794    }
4795
4796    #[test]
4797    fn test_build_canonical_rejects_recipient_list_step() {
4798        let err = RouteBuilder::from("direct:start")
4799            .route_id("canonical-recipient")
4800            .recipient_list(camel_api::RecipientSource::Sync(Arc::new(|_| {
4801                "mock:a".to_string()
4802            })))
4803            .build_canonical()
4804            .unwrap_err();
4805
4806        assert!(format!("{err}").contains("does not support step `recipient_list`"));
4807    }
4808
4809    // ── extract_completion_fields: Any mode with predicate → error ──────────────
4810
4811    #[test]
4812    fn test_build_canonical_rejects_any_mode_with_predicate() {
4813        let err = RouteBuilder::from("direct:start")
4814            .route_id("canonical-any-pred")
4815            .aggregate(AggregatorConfig {
4816                header_name: "key".to_string(),
4817                completion: CompletionMode::Any(vec![
4818                    CompletionCondition::Size(5),
4819                    CompletionCondition::Predicate(Arc::new(|_| false)),
4820                ]),
4821                correlation: CorrelationStrategy::HeaderName("key".to_string()),
4822                strategy: AggregationStrategy::CollectAll,
4823                max_buckets: None,
4824                max_bucket_size: None,
4825                bucket_ttl: None,
4826                force_completion_on_stop: false,
4827                discard_on_timeout: false,
4828                max_timeout_tasks: 1024,
4829            })
4830            .build_canonical()
4831            .unwrap_err();
4832
4833        assert!(
4834            format!("{err}").contains("cannot reverse-map"),
4835            "reject message must explain forward-only: {}",
4836            err
4837        );
4838    }
4839
4840    // ── BUILDER-004: Validation errors for missing required fields ────────────
4841
4842    #[test]
4843    fn test_builder_validation_missing_from_uri() {
4844        let result = RouteBuilder::from("")
4845            .route_id("missing-uri-route")
4846            .to("log:info")
4847            .build();
4848        assert!(result.is_err(), "empty from URI should fail validation");
4849        let err = result.err().unwrap().to_string();
4850        assert!(
4851            err.contains("'from'") || err.contains("URI"),
4852            "error should mention from/URI, got: {err}"
4853        );
4854    }
4855
4856    #[test]
4857    fn test_builder_validation_invalid_step_uri_scheme() {
4858        let result = RouteBuilder::from("timer:tick")
4859            .route_id("bad-step-route")
4860            .to("not-a-valid-uri") // no scheme
4861            .build();
4862        // The builder itself accepts any URI string; validation happens at
4863        // resolution time. Verify the build succeeds (step URI is deferred).
4864        assert!(
4865            result.is_ok(),
4866            "builder should accept opaque step URIs; resolution happens later"
4867        );
4868    }
4869
4870    // ── rc-p9vq: Duplicate route IDs ──────────────────────────────────────
4871
4872    #[test]
4873    fn test_builder_duplicate_route_ids_produce_identical_definitions() {
4874        // The builder itself doesn't check for duplicates (that's context-level).
4875        // Verify both builds succeed with the same ID — detection is TODO(rc-p9vq).
4876        let route1 = RouteBuilder::from("direct:a")
4877            .route_id("dup-route")
4878            .to("mock:out")
4879            .build();
4880        let route2 = RouteBuilder::from("direct:b")
4881            .route_id("dup-route")
4882            .to("mock:out")
4883            .build();
4884
4885        assert!(route1.is_ok());
4886        assert!(route2.is_ok());
4887        assert_eq!(route1.unwrap().route_id(), route2.unwrap().route_id());
4888    }
4889
4890    #[test]
4891    fn test_builder_clone_reuse_as_template() {
4892        // rc-8m5o: a partially-built RouteBuilder can be cloned and reused as a
4893        // template, then each clone varied independently before build().
4894        let template = RouteBuilder::from("direct:in")
4895            .set_header("stage", Value::String("shared".into()))
4896            .log("shared prefix", LogLevel::Info);
4897
4898        let route_a = template
4899            .clone()
4900            .route_id("route-a")
4901            .to("mock:a")
4902            .build()
4903            .expect("clone A builds");
4904        let route_b = template
4905            .route_id("route-b")
4906            .to("mock:b")
4907            .build()
4908            .expect("clone B builds");
4909
4910        assert_eq!(route_a.route_id(), "route-a");
4911        assert_eq!(route_b.route_id(), "route-b");
4912        // Shared template steps (set_header + log) are present in both, plus the
4913        // per-clone `to` step: the clone is a deep copy, not an alias.
4914        assert_eq!(route_a.steps().len(), route_b.steps().len());
4915        assert_eq!(route_a.from_uri(), route_b.from_uri());
4916    }
4917
4918    // ── stream_split builder tests ──────────────────────────────────────────
4919
4920    fn test_stream_split_expression() -> camel_api::StreamingSplitExpression {
4921        camel_processor::zip_splitter::zip_splitter(
4922            camel_processor::zip_splitter::ZipSplitConfig::default(),
4923        )
4924    }
4925
4926    #[test]
4927    fn stream_split_builder_emits_variant_with_defaults() {
4928        let definition = RouteBuilder::from("direct:start")
4929            .route_id("stream-split-defaults")
4930            .stream_split(test_stream_split_expression())
4931            .log("fragment", LogLevel::Info)
4932            .end_stream_split()
4933            .build()
4934            .expect("route should build");
4935
4936        let steps = definition.steps();
4937        assert_eq!(steps.len(), 1);
4938        match &steps[0] {
4939            BuilderStep::StreamSplit {
4940                aggregation,
4941                stop_on_exception,
4942                steps,
4943                ..
4944            } => {
4945                assert!(matches!(
4946                    aggregation,
4947                    camel_api::splitter::AggregationStrategy::LastWins
4948                ));
4949                assert!(*stop_on_exception);
4950                assert_eq!(steps.len(), 1);
4951            }
4952            other => panic!("expected StreamSplit step, got {other:?}"),
4953        }
4954    }
4955
4956    #[test]
4957    fn stream_split_builder_setters_override() {
4958        let definition = RouteBuilder::from("direct:start")
4959            .route_id("stream-split-overrides")
4960            .stream_split(test_stream_split_expression())
4961            .aggregation(camel_api::splitter::AggregationStrategy::CollectAll)
4962            .stop_on_exception(false)
4963            .log("fragment", LogLevel::Info)
4964            .end_stream_split()
4965            .build()
4966            .expect("route should build");
4967
4968        let steps = definition.steps();
4969        assert_eq!(steps.len(), 1);
4970        match &steps[0] {
4971            BuilderStep::StreamSplit {
4972                aggregation,
4973                stop_on_exception,
4974                steps,
4975                ..
4976            } => {
4977                assert!(matches!(
4978                    aggregation,
4979                    camel_api::splitter::AggregationStrategy::CollectAll
4980                ));
4981                assert!(!*stop_on_exception);
4982                assert_eq!(steps.len(), 1);
4983            }
4984            other => panic!("expected StreamSplit step, got {other:?}"),
4985        }
4986    }
4987
4988    #[test]
4989    fn to_layered_pushes_layered_to_step() {
4990        use tower::limit::ConcurrencyLimitLayer;
4991
4992        let route = RouteBuilder::from("direct:a")
4993            .route_id("t")
4994            .to_layered("mock:b", ConcurrencyLimitLayer::new(2))
4995            .build()
4996            .unwrap();
4997
4998        assert_eq!(route.steps().len(), 1);
4999        match &route.steps()[0] {
5000            BuilderStep::LayeredTo { uri, .. } => assert_eq!(uri, "mock:b"),
5001            other => panic!("expected LayeredTo step, got {other:?}"),
5002        }
5003    }
5004
5005    #[test]
5006    fn layered_closure_scopes_section_steps() {
5007        use tower::limit::ConcurrencyLimitLayer;
5008
5009        let route = RouteBuilder::from("direct:a")
5010            .route_id("t")
5011            .layered(ConcurrencyLimitLayer::new(2), |s| {
5012                s.to("mock:1").to("mock:2")
5013            })
5014            .build()
5015            .unwrap();
5016
5017        match &route.steps()[0] {
5018            BuilderStep::Layered { steps, .. } => assert_eq!(steps.len(), 2),
5019            other => panic!("expected Layered step, got {other:?}"),
5020        }
5021    }
5022
5023    #[test]
5024    fn route_layer_nests_last_outermost() {
5025        use tower::limit::ConcurrencyLimitLayer;
5026
5027        let l1 = ConcurrencyLimitLayer::new(2);
5028        let l2 = ConcurrencyLimitLayer::new(5);
5029        let builder = RouteBuilder::from("direct:a")
5030            .route_id("t")
5031            .to("mock:b")
5032            .route_layer(l1)
5033            .route_layer(l2);
5034        // Same Arcs the fold moves into the step tree.
5035        let f1 = builder.route_layers[0].clone();
5036        let f2 = builder.route_layers[1].clone();
5037
5038        let route = builder.build().unwrap();
5039
5040        match &route.steps()[0] {
5041            BuilderStep::Layered { factory, steps } => {
5042                assert_eq!(factory, &f2, "last-added layer must be outermost");
5043                match &steps[0] {
5044                    BuilderStep::Layered { factory, steps } => {
5045                        assert_eq!(factory, &f1, "first-added layer must be innermost");
5046                        assert_eq!(steps.len(), 1);
5047                        assert!(
5048                            matches!(&steps[0], BuilderStep::To(uri) if uri == "mock:b"),
5049                            "innermost steps must be the route body"
5050                        );
5051                    }
5052                    other => panic!("expected inner Layered step, got {other:?}"),
5053                }
5054            }
5055            other => panic!("expected outer Layered step, got {other:?}"),
5056        }
5057    }
5058
5059    #[test]
5060    fn build_canonical_rejects_layered_to_route() {
5061        use tower::limit::ConcurrencyLimitLayer;
5062
5063        let result = RouteBuilder::from("direct:a")
5064            .route_id("t")
5065            .to_layered("mock:b", ConcurrencyLimitLayer::new(2))
5066            .build_canonical();
5067
5068        match result {
5069            Err(CamelError::RouteError(msg)) => {
5070                assert!(msg.contains("to_layered"), "msg was: {msg}");
5071                assert!(msg.contains("canonical"), "msg was: {msg}");
5072            }
5073            other => panic!("expected canonical rejection, got {other:?}"),
5074        }
5075    }
5076
5077    #[test]
5078    fn build_canonical_rejects_layered_section_route() {
5079        use tower::limit::ConcurrencyLimitLayer;
5080
5081        let result = RouteBuilder::from("direct:a")
5082            .route_id("t")
5083            .layered(ConcurrencyLimitLayer::new(2), |s| s.to("mock:1"))
5084            .build_canonical();
5085
5086        match result {
5087            Err(CamelError::RouteError(msg)) => {
5088                assert!(msg.contains("layered"), "msg was: {msg}");
5089                assert!(msg.contains("canonical"), "msg was: {msg}");
5090            }
5091            other => panic!("expected canonical rejection, got {other:?}"),
5092        }
5093    }
5094
5095    #[test]
5096    fn build_canonical_rejects_route_layer() {
5097        use tower::limit::ConcurrencyLimitLayer;
5098
5099        let result = RouteBuilder::from("direct:a")
5100            .route_id("t")
5101            .to("mock:b")
5102            .route_layer(ConcurrencyLimitLayer::new(2))
5103            .build_canonical();
5104
5105        match result {
5106            Err(CamelError::RouteError(msg)) => {
5107                assert!(msg.contains("route_layer"), "msg was: {msg}");
5108                assert!(msg.contains("canonical"), "msg was: {msg}");
5109            }
5110            other => panic!("expected canonical rejection, got {other:?}"),
5111        }
5112    }
5113}