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