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