camel_core/lifecycle/adapters/route_controller.rs
1//! Default implementation of RouteController.
2//!
3//! This module provides [`DefaultRouteController`], which manages route lifecycle
4//! including starting, stopping, suspending, and resuming routes.
5
6use std::collections::HashMap;
7use std::sync::{Arc, Weak};
8use std::time::Duration;
9
10use tokio::sync::mpsc;
11use tokio_util::sync::CancellationToken;
12use tower::{Layer, ServiceExt};
13use tracing::{debug, info, warn};
14
15use super::route_controller_trait::{
16 BindExposureAcks, bind_key_from_uri, enforce_bind_exposure_gate,
17};
18use camel_api::error_handler::ErrorHandlerConfig;
19use camel_api::metrics::MetricsCollector;
20#[allow(unused_imports)]
21use camel_api::{
22 BoxProcessor, CamelError, Exchange, FunctionInvoker, IdentityProcessor, InFlightClaim,
23 InFlightGauge, NoOpMetrics, NoopPlatformService, PlatformService, ProducerContext,
24 RouteController, RuntimeHandle, StepLifecycle,
25};
26use camel_component_api::{Consumer, ConsumerContext, consumer::ExchangeEnvelope};
27use camel_processor::aggregator::AggregatorService;
28pub use camel_processor::aggregator::SharedLanguageRegistry;
29use camel_processor::aggregator::{AggregateEmission, AggregationReceipt};
30
31use crate::health_registry::HealthCheckRegistry;
32use crate::intercept::InterceptRules;
33use crate::lifecycle::CohortActivationGate;
34use crate::lifecycle::adapters::controller_component_context::ControllerComponentContext;
35use crate::lifecycle::adapters::route_compiler::TracerPipelineGating;
36use crate::lifecycle::adapters::route_compiler_ext::{
37 RouteCompilerExt, build_eh_config_pipeline, route_is_http_consumer, transport_from_uri,
38};
39use crate::lifecycle::adapters::route_helpers::{
40 AggregateSplitInfo, CrashNotification, ManagedRoute, assert_no_mixed_top_level_splits,
41 handle_is_running, inferred_lifecycle_label, is_pending, send_reply_or_b_prime,
42};
43#[cfg(test)]
44pub(super) use crate::lifecycle::adapters::route_helpers::{
45 emit_start_route_event, set_start_route_event_hook,
46};
47use crate::lifecycle::adapters::route_registry::RouteRegistry;
48use crate::lifecycle::adapters::route_runtime_state;
49use crate::lifecycle::adapters::step_compilers::CompiledStep;
50use crate::lifecycle::application::route_definition::{BuilderStep, RouteDefinition};
51pub(crate) use crate::lifecycle::domain::CompiledPipeline;
52use crate::shared::components::domain::Registry;
53use crate::shared::observability::domain::{DetailLevel, TracerConfig};
54use camel_bean::BeanRegistry;
55
56/// Default implementation of [`RouteController`].
57///
58/// Manages route lifecycle with support for:
59/// - Starting/stopping individual routes
60/// - Suspending and resuming routes
61/// - Auto-startup with startup ordering
62/// - Graceful shutdown
63pub struct DefaultRouteController {
64 /// Routes indexed by route ID.
65 pub(super) routes: RouteRegistry,
66 /// Reference to the component registry for resolving endpoints.
67 pub(super) registry: Arc<std::sync::Mutex<Registry>>,
68 /// Shared language registry for resolving declarative language expressions.
69 pub(super) languages: SharedLanguageRegistry,
70 /// Bean registry for bean method invocation.
71 pub(super) beans: Arc<std::sync::Mutex<BeanRegistry>>,
72 /// Runtime handle injected into ProducerContext for command/query operations.
73 pub(super) runtime: Option<Weak<dyn RuntimeHandle>>,
74 /// Optional global error handler applied to all routes without a per-route handler.
75 pub(super) global_error_handler: Option<ErrorHandlerConfig>,
76 /// Optional crash notifier for supervision.
77 pub(super) crash_notifier: Option<mpsc::Sender<CrashNotification>>,
78 /// Whether tracing is enabled for route pipelines.
79 pub(super) tracer_gating: TracerPipelineGating,
80 /// Detail level for tracing when enabled.
81 pub(super) tracer_detail_level: DetailLevel,
82 /// Metrics collector for tracing processor.
83 pub(super) tracer_metrics: Option<Arc<dyn MetricsCollector>>,
84 pub(super) platform_service: Arc<dyn PlatformService>,
85 pub(super) function_invoker: Option<Arc<dyn FunctionInvoker>>,
86 pub(super) health_registry: Option<Arc<HealthCheckRegistry>>,
87 /// Shared idempotent repository registry. Defaults to an empty registry;
88 /// the CamelContext builder installs a populated handle that includes the
89 /// built-in `"memory"` repository.
90 pub(super) idempotent_repositories: crate::SharedIdempotentRegistry,
91 pub(super) claim_check_repositories: crate::SharedClaimCheckRegistry,
92 pub(super) cache_repositories: crate::SharedCacheRegistry,
93 /// F2 staging: prepared-but-not-inserted ManagedRoutes keyed by route_id.
94 /// `prepare_*` writes here; `insert_prepared_route` drains via `remove()`.
95 /// On insert-failure error paths, the caller (`reload_actions.rs`) must
96 /// explicitly drain to avoid orphan CancellationToken/SharedPipeline leaks.
97 pub(super) prepared_staging: HashMap<String, ManagedRoute>,
98 /// Source endpoint URI to route_id index (one-to-many).
99 pub(super) endpoint_index: super::endpoint_index::EndpointIndex,
100 /// Operator acknowledgements for per-bind public exposure (ADR-0061).
101 /// Empty by default → the gate fails closed on non-loopback binds.
102 pub(super) bind_acks: super::route_controller_trait::BindExposureAcks,
103 /// Route send-point interception rules captured by step compilation.
104 pub(super) intercept: InterceptRules,
105 /// Intercept-rules freeze. Trips on `add_route` success and on the
106 /// `MarkStarted` actor command; never reset (stop/restart included),
107 /// because compiled pipelines capture the rules at compile time.
108 pub(super) frozen: bool,
109 /// Startup-cohort activation barrier (rc-jxkj). Cloned into the
110 /// `RouteControllerHandle` at spawn; reset/activate act on this shared
111 /// gate directly, never through the actor.
112 pub(super) cohort: Arc<CohortActivationGate>,
113 /// Context-global accepted-not-completed gauge (drainclaim): the
114 /// SAME `Arc` the owning `CamelContext` exposes through
115 /// `total_in_flight()` (installed by the builder). Standalone
116 /// controllers keep an isolated zero gauge — claims flow, but only
117 /// the constructing scope can read them.
118 pub(super) in_flight_total: Arc<InFlightGauge>,
119}
120
121impl DefaultRouteController {
122 /// Open the startup-cohort activation barrier (rc-jxkj).
123 ///
124 /// The CamelContext lifecycle opens this automatically once the startup
125 /// cohort completes. Consumers that drive a bare `DefaultRouteController`
126 /// (outside a full context) must call this before dispatching
127 /// (typically after starting routes), or pipeline dispatch parks
128 /// every envelope until the caller's call timeout surfaces as a
129 /// failure.
130 pub fn activate_cohort(&self) {
131 self.cohort.open();
132 }
133
134 pub(super) fn health_registry(&self) -> Arc<HealthCheckRegistry> {
135 self.health_registry.clone().unwrap_or_else(|| {
136 debug!("health_registry not configured — creating isolated fallback");
137 Arc::new(HealthCheckRegistry::new(Duration::from_secs(5)))
138 })
139 }
140
141 /// Create a new `DefaultRouteController` with the given registry.
142 pub fn new(
143 registry: Arc<std::sync::Mutex<Registry>>,
144 platform_service: Arc<dyn PlatformService>,
145 ) -> Self {
146 Self::with_beans_and_platform_service(
147 registry,
148 Arc::new(std::sync::Mutex::new(BeanRegistry::new())),
149 platform_service,
150 )
151 }
152
153 /// Create a new `DefaultRouteController` with shared bean registry.
154 pub fn with_beans(
155 registry: Arc<std::sync::Mutex<Registry>>,
156 beans: Arc<std::sync::Mutex<BeanRegistry>>,
157 ) -> Self {
158 Self::with_beans_and_platform_service(
159 registry,
160 beans,
161 Arc::new(NoopPlatformService::default()),
162 )
163 }
164
165 fn with_beans_and_platform_service(
166 registry: Arc<std::sync::Mutex<Registry>>,
167 beans: Arc<std::sync::Mutex<BeanRegistry>>,
168 platform_service: Arc<dyn PlatformService>,
169 ) -> Self {
170 Self {
171 routes: RouteRegistry::new(),
172 registry,
173 languages: Arc::new(std::sync::Mutex::new(HashMap::new())),
174 beans,
175 runtime: None,
176 global_error_handler: None,
177 crash_notifier: None,
178 tracer_gating: TracerPipelineGating::off(),
179 tracer_detail_level: DetailLevel::Minimal,
180 tracer_metrics: None,
181 platform_service,
182 function_invoker: None,
183 health_registry: None,
184 idempotent_repositories: Arc::new(crate::IdempotentRegistry::new()),
185 claim_check_repositories: Arc::new(crate::ClaimCheckRegistry::new()),
186 cache_repositories: Arc::new(crate::CacheRegistry::new()),
187 prepared_staging: HashMap::new(),
188 endpoint_index: super::endpoint_index::EndpointIndex::new(),
189 bind_acks: Default::default(),
190 intercept: InterceptRules::default(),
191 frozen: false,
192 cohort: Arc::new(CohortActivationGate::new_closed()),
193 in_flight_total: Arc::new(InFlightGauge::new()),
194 }
195 }
196
197 /// Create a new `DefaultRouteController` with shared language registry.
198 pub fn with_languages(
199 registry: Arc<std::sync::Mutex<Registry>>,
200 languages: SharedLanguageRegistry,
201 platform_service: Arc<dyn PlatformService>,
202 ) -> Self {
203 Self {
204 routes: RouteRegistry::new(),
205 registry,
206 languages,
207 beans: Arc::new(std::sync::Mutex::new(BeanRegistry::new())),
208 runtime: None,
209 global_error_handler: None,
210 crash_notifier: None,
211 tracer_gating: TracerPipelineGating::off(),
212 tracer_detail_level: DetailLevel::Minimal,
213 tracer_metrics: None,
214 platform_service,
215 function_invoker: None,
216 health_registry: None,
217 idempotent_repositories: Arc::new(crate::IdempotentRegistry::new()),
218 claim_check_repositories: Arc::new(crate::ClaimCheckRegistry::new()),
219 cache_repositories: Arc::new(crate::CacheRegistry::new()),
220 prepared_staging: HashMap::new(),
221 endpoint_index: super::endpoint_index::EndpointIndex::new(),
222 bind_acks: Default::default(),
223 intercept: InterceptRules::default(),
224 frozen: false,
225 cohort: Arc::new(CohortActivationGate::new_closed()),
226 in_flight_total: Arc::new(InFlightGauge::new()),
227 }
228 }
229
230 pub fn with_languages_and_beans(
231 registry: Arc<std::sync::Mutex<Registry>>,
232 languages: SharedLanguageRegistry,
233 platform_service: Arc<dyn PlatformService>,
234 beans: Arc<std::sync::Mutex<BeanRegistry>>,
235 ) -> Self {
236 Self {
237 routes: RouteRegistry::new(),
238 registry,
239 languages,
240 beans,
241 runtime: None,
242 global_error_handler: None,
243 crash_notifier: None,
244 tracer_gating: TracerPipelineGating::off(),
245 tracer_detail_level: DetailLevel::Minimal,
246 tracer_metrics: None,
247 platform_service,
248 function_invoker: None,
249 health_registry: None,
250 idempotent_repositories: Arc::new(crate::IdempotentRegistry::new()),
251 claim_check_repositories: Arc::new(crate::ClaimCheckRegistry::new()),
252 cache_repositories: Arc::new(crate::CacheRegistry::new()),
253 prepared_staging: HashMap::new(),
254 endpoint_index: super::endpoint_index::EndpointIndex::new(),
255 bind_acks: Default::default(),
256 intercept: InterceptRules::default(),
257 frozen: false,
258 cohort: Arc::new(CohortActivationGate::new_closed()),
259 in_flight_total: Arc::new(InFlightGauge::new()),
260 }
261 }
262
263 pub fn with_function_invoker(mut self, function_invoker: Arc<dyn FunctionInvoker>) -> Self {
264 self.function_invoker = Some(function_invoker);
265 self
266 }
267
268 pub(crate) fn set_idempotent_repositories(
269 &mut self,
270 repositories: crate::SharedIdempotentRegistry,
271 ) {
272 self.idempotent_repositories = repositories;
273 }
274
275 pub(crate) fn set_claim_check_repositories(
276 &mut self,
277 repositories: crate::SharedClaimCheckRegistry,
278 ) {
279 self.claim_check_repositories = repositories;
280 }
281
282 pub(crate) fn set_cache_repositories(&mut self, repositories: crate::SharedCacheRegistry) {
283 self.cache_repositories = repositories;
284 }
285
286 pub fn set_health_registry(&mut self, registry: Arc<HealthCheckRegistry>) {
287 self.health_registry = Some(registry);
288 }
289
290 pub fn set_function_invoker(&mut self, invoker: Arc<dyn FunctionInvoker>) {
291 self.function_invoker = Some(invoker);
292 }
293
294 /// Set runtime handle for ProducerContext creation.
295 pub fn set_runtime_handle(&mut self, runtime: Arc<dyn RuntimeHandle>) {
296 self.runtime = Some(Arc::downgrade(&runtime));
297 }
298
299 /// Set the crash notifier for supervision.
300 ///
301 /// When set, the controller will send a `CrashNotification` whenever
302 /// a consumer crashes.
303 pub fn set_crash_notifier(&mut self, tx: mpsc::Sender<CrashNotification>) {
304 self.crash_notifier = Some(tx);
305 }
306
307 /// Set a global error handler applied to all routes without a per-route handler.
308 /// Install operator acknowledgements for per-bind public exposure
309 /// (ADR-0061). Built by the CLI from `CamelConfig.binds`.
310 pub fn set_bind_exposure_acks(&mut self, acks: BindExposureAcks) {
311 self.bind_acks = acks;
312 }
313
314 /// Install route send-point interception rules (pre-first-use only).
315 ///
316 /// Fails with `CamelError::Config` once the freeze has tripped: compiled
317 /// pipelines capture the rules at compile time, so the rule set must not
318 /// change after a route is added or the context is started.
319 pub fn set_intercept_rules(&mut self, rules: InterceptRules) -> Result<(), CamelError> {
320 if self.frozen {
321 return Err(CamelError::Config(
322 "intercept rules are frozen: a route was added or the context was started; \
323 rules cannot be changed after first use"
324 .into(),
325 ));
326 }
327 self.intercept = rules;
328 Ok(())
329 }
330
331 /// Builder-style build-time configuration on a fresh controller (which
332 /// is never frozen); mirrors `with_function_invoker`.
333 pub fn with_intercept_rules(mut self, rules: InterceptRules) -> Self {
334 self.intercept = rules;
335 self
336 }
337
338 /// Trip the intercept-rules freeze. Dispatched by the `MarkStarted`
339 /// actor command so the freeze applies even with zero routes. Never
340 /// unset.
341 pub fn mark_started(&mut self) {
342 self.frozen = true;
343 }
344
345 /// All compiled security plans whose routes bind the same listener
346 /// address (bind key), for the per-bind exposure gate. Routes still
347 /// staging (no plan yet) are skipped — classification failures already
348 /// aborted their own staging (Task 1.8).
349 pub(super) fn plans_for_bind(
350 &self,
351 bind_key: &str,
352 ) -> Vec<(String, camel_api::security_policy::RouteSecurityPlan)> {
353 self.routes
354 .iter()
355 .filter_map(|(route_id, managed)| {
356 let plan = managed.compiled.security_plan.as_ref()?;
357 let bind = bind_key_from_uri(&managed.from_uri)?;
358 if bind.key == bind_key {
359 Some((route_id.clone(), plan.clone()))
360 } else {
361 None
362 }
363 })
364 .collect()
365 }
366
367 /// Return whether a listener for `bind_key` is already serving a route.
368 ///
369 /// This is deliberately based on the consumer handle, rather than on the
370 /// presence of a compiled route: the exposure gate applies only to late
371 /// registration against an already-running bind (Task 2.2). Startup and
372 /// resume perform their own gate checks in the lifecycle implementation.
373 fn bind_is_running(&self, bind_key: &str) -> bool {
374 self.routes.iter().any(|(_, managed)| {
375 bind_key_from_uri(&managed.from_uri).is_some_and(|bind| {
376 bind.key == bind_key && handle_is_running(&managed.consumer_handle)
377 })
378 })
379 }
380
381 /// Gate a route before it is inserted into a listener that is already
382 /// running. The candidate is included with all sibling plans so the gate
383 /// has the same aggregation semantics as the start path.
384 fn enforce_late_registration_gate(
385 &self,
386 from_uri: &str,
387 route_id: &str,
388 plan: Option<&camel_api::security_policy::RouteSecurityPlan>,
389 ) -> Result<(), CamelError> {
390 let Some(bind) = bind_key_from_uri(from_uri) else {
391 return Ok(());
392 };
393 if !self.bind_is_running(&bind.key) {
394 return Ok(());
395 }
396
397 let mut owned = self.plans_for_bind(&bind.key);
398 if let Some(plan) = plan {
399 owned.push((route_id.to_string(), plan.clone()));
400 }
401 let plans: Vec<(&str, &camel_api::security_policy::RouteSecurityPlan)> =
402 owned.iter().map(|(id, plan)| (id.as_str(), plan)).collect();
403 enforce_bind_exposure_gate(
404 &bind.key,
405 bind.loopback,
406 &plans,
407 self.bind_acks.acknowledged(&bind.key),
408 )
409 .map_err(|err| {
410 CamelError::RouteError(format!(
411 "late registration of route '{route_id}' rejected for bind '{}': {err}",
412 bind.key
413 ))
414 })
415 }
416
417 pub fn set_error_handler(&mut self, config: ErrorHandlerConfig) {
418 self.global_error_handler = Some(config);
419 }
420
421 /// Configure tracing for this route controller.
422 pub fn set_tracer_config(&mut self, config: &TracerConfig) {
423 // Pipeline wrapping follows tracing unless the effective assembly
424 // raised it (exporter active); spans follow `enabled` alone.
425 self.tracer_gating = TracerPipelineGating {
426 pipeline_enabled: config.enabled || config.pipeline_enabled,
427 spans_enabled: config.enabled,
428 levers: config.metrics_levers.clone(),
429 };
430 self.tracer_detail_level = config.detail_level.clone();
431 }
432
433 /// Seed the tracer metrics collector — the shared late-bound
434 /// `MetricsHandle` built once by `CamelContextBuilder::build()`.
435 ///
436 /// Replaces the deleted `TracerConfig.metrics_collector` snapshot
437 /// injection: the collector is wired here, at construction, and late
438 /// registrations flow through the handle without re-snapshotting.
439 pub fn set_tracer_metrics(&mut self, metrics: Arc<dyn MetricsCollector>) {
440 self.tracer_metrics = Some(metrics);
441 }
442
443 /// Install the context-global accepted-not-completed gauge
444 /// (drainclaim) — the SAME `Arc<InFlightGauge>` the owning
445 /// `CamelContext` reads through `total_in_flight()`. Called once by
446 /// `CamelContextBuilder::build()`; contexts built without a builder
447 /// (or standalone controllers) keep the isolated zero gauge from
448 /// construction.
449 pub fn set_in_flight_total(&mut self, counter: Arc<InFlightGauge>) {
450 self.in_flight_total = counter;
451 }
452
453 fn build_producer_context(&self, route_id: &str) -> Result<ProducerContext, CamelError> {
454 let mut producer_ctx = ProducerContext::new().with_route_id(route_id);
455 if let Some(runtime) = self.runtime.as_ref().and_then(Weak::upgrade) {
456 producer_ctx = producer_ctx.with_runtime(runtime);
457 }
458 Ok(producer_ctx)
459 }
460
461 /// Create a transient [`RouteCompilerExt`] from this controller's fields.
462 fn route_compiler_ext(&self) -> RouteCompilerExt<'_> {
463 RouteCompilerExt {
464 registry: &self.registry,
465 languages: &self.languages,
466 beans: &self.beans,
467 function_invoker: &self.function_invoker,
468 tracer_gating: self.tracer_gating.clone(),
469 tracer_detail_level: &self.tracer_detail_level,
470 tracer_metrics: &self.tracer_metrics,
471 platform_service: &self.platform_service,
472 runtime: &self.runtime,
473 global_error_handler: &self.global_error_handler,
474 health_registry: &self.health_registry,
475 route_registry: &self.routes,
476 idempotent_repositories: Arc::clone(&self.idempotent_repositories),
477 claim_check_repositories: Arc::clone(&self.claim_check_repositories),
478 cache_repositories: Arc::clone(&self.cache_repositories),
479 intercept: &self.intercept,
480 in_flight_total: Arc::clone(&self.in_flight_total),
481 }
482 }
483
484 /// Resolve BuilderSteps into BoxProcessors.
485 #[allow(dead_code)] // used by tests and may be needed for future split paths
486 pub(crate) fn resolve_steps(
487 &self,
488 steps: Vec<BuilderStep>,
489 producer_ctx: &ProducerContext,
490 registry: &Arc<std::sync::Mutex<Registry>>,
491 route_id: Option<&str>,
492 staging_mode: &super::step_resolution::FunctionStagingMode,
493 ) -> Result<Vec<CompiledStep>, CamelError> {
494 let component_ctx = Arc::new(ControllerComponentContext::new(
495 Arc::clone(registry),
496 Arc::clone(&self.languages),
497 self.tracer_metrics
498 .clone()
499 .unwrap_or_else(|| Arc::new(NoOpMetrics)),
500 Arc::clone(&self.platform_service),
501 self.health_registry(),
502 route_id.map(|s| s.to_string()),
503 self.tracer_gating.levers.component_metrics_levers(),
504 ));
505 let rt: Arc<dyn camel_component_api::RuntimeObservability> =
506 Arc::clone(&component_ctx) as Arc<_>;
507
508 super::step_resolution::resolve_steps(
509 steps,
510 producer_ctx,
511 rt,
512 registry,
513 &self.languages,
514 &self.beans,
515 self.function_invoker.clone(),
516 component_ctx,
517 route_id,
518 staging_mode,
519 &self.idempotent_repositories,
520 &self.claim_check_repositories,
521 &self.cache_repositories,
522 self.intercept.clone(),
523 )
524 }
525
526 /// Add a route definition to the controller.
527 ///
528 /// Steps are resolved immediately using the registry.
529 ///
530 /// # Errors
531 ///
532 /// Returns an error if:
533 /// - A route with the same ID already exists
534 /// - Step resolution fails
535 pub async fn add_route(&mut self, definition: RouteDefinition) -> Result<(), CamelError> {
536 let route_id = definition.route_id().to_string();
537 let from_uri = definition.from_uri().to_string();
538
539 if self.routes.contains_key(&route_id) {
540 return Err(CamelError::RouteError(format!(
541 "duplicate route ID '{route_id}'"
542 )));
543 }
544
545 debug!(route_id = %route_id, "Adding route to controller");
546
547 let managed = match self.build_managed_route(
548 definition,
549 &super::step_resolution::FunctionStagingMode::DirectAdd,
550 ) {
551 Ok(managed) => managed,
552 Err(err) => {
553 self.discard_function_staging();
554 return Err(err);
555 }
556 };
557
558 // A running listener can observe a newly inserted route immediately.
559 // Gate the complete sibling set before committing function staging or
560 // inserting the route, so a rejected late registration is unreachable.
561 if let Err(err) = self.enforce_late_registration_gate(
562 &from_uri,
563 &route_id,
564 managed.compiled.security_plan.as_ref(),
565 ) {
566 self.discard_function_staging();
567 return Err(err);
568 }
569
570 if let Some(invoker) = &self.function_invoker
571 && let Err(err) = invoker.commit_staged().await
572 {
573 invoker.discard_staging(0);
574 return Err(CamelError::Config(err.to_string()));
575 }
576
577 self.routes
578 .insert(managed.definition.route_id().to_string(), managed);
579
580 self.endpoint_index.insert(&from_uri, &route_id);
581 // First successful route registration freezes the intercept rules:
582 // this route's pipeline compiled against the current rule set.
583 self.frozen = true;
584 Ok(())
585 }
586
587 pub(super) fn build_managed_route(
588 &self,
589 definition: RouteDefinition,
590 staging_mode: &super::step_resolution::FunctionStagingMode,
591 ) -> Result<ManagedRoute, CamelError> {
592 let route_id = definition.route_id().to_string();
593
594 let definition_info = definition.to_info();
595
596 // Security plan compilation (Task 1.8): consumer-backed routes get a
597 // plan BEFORE any consumer starts; a declared route that fails
598 // classification aborts staging (never a Public downgrade). Routes
599 // without a provider registry compile against an empty view.
600 let empty_providers;
601 let providers = match &definition.provider_registry {
602 Some(registry) => registry.as_ref(),
603 None => {
604 empty_providers = camel_auth::ProviderRegistry::new();
605 &empty_providers
606 }
607 };
608 let security_plan =
609 super::route_compiler_ext::compile_route_security_plan(&definition, providers)?;
610
611 let RouteDefinition {
612 from_uri,
613 steps,
614 error_handler,
615 circuit_breaker,
616 circuit_breaker_fallback,
617 security_policy,
618 security_authenticator,
619 provider_registry,
620 unit_of_work,
621 concurrency,
622 http_error_mapping,
623 ..
624 } = definition;
625
626 let producer_ctx = self.build_producer_context(&route_id)?;
627
628 // N2: reject mixed Aggregate + Resequence top-level splits
629 assert_no_mixed_top_level_splits(&steps)?;
630
631 let (aggregate_split, processors_with_contracts) = self
632 .route_compiler_ext()
633 .detect_and_validate_route_split(steps, &producer_ctx, &route_id, staging_mode)?;
634 let mut lifecycle = super::route_helpers::collect_lifecycle(&processors_with_contracts);
635
636 // CB fallback (mirrors on_miss lifecycle packing): attach via the
637 // shared helper, then merge the fallback lifecycle handles into the
638 // route vec.
639 let (circuit_breaker, fallback_lifecycle) = self.route_compiler_ext().attach_cb_fallback(
640 circuit_breaker,
641 circuit_breaker_fallback,
642 &producer_ctx,
643 &route_id,
644 staging_mode,
645 )?;
646 lifecycle.extend(fallback_lifecycle);
647 let route_id_for_tracing = route_id.clone();
648 // Business-error-model Task 2.2: capture the seam mapping BEFORE the
649 // handler configuration is consumed (eh_config resolution below) — the
650 // mapping is orthogonal to the error handler and must survive staging
651 // so BOTH start and resume registrations can install it.
652 let business_seam_bypass = http_error_mapping.is_some();
653 let eh_config = error_handler.or_else(|| self.global_error_handler.clone());
654 let transport = transport_from_uri(&from_uri);
655 // Reply ownership (bd rc-c3vds) is keyed on the consumer SCHEME, not
656 // on the mapping: an HTTP consumer finalizes every reply (plain and
657 // rest-lowered alike), so the handler must leave the propagate record
658 // to the finalizer.
659 let reply_seam = route_is_http_consumer(&from_uri);
660
661 let mut pipeline = build_eh_config_pipeline(
662 eh_config.as_ref(),
663 Arc::clone(&self.registry),
664 Arc::clone(&self.languages),
665 self.tracer_metrics.clone(),
666 Arc::clone(&self.platform_service),
667 self.health_registry(),
668 &route_id_for_tracing,
669 &producer_ctx,
670 processors_with_contracts,
671 self.tracer_gating.clone(),
672 self.tracer_detail_level.clone(),
673 security_policy.clone(),
674 transport,
675 circuit_breaker,
676 Arc::clone(&self.in_flight_total),
677 business_seam_bypass,
678 reply_seam,
679 )?;
680
681 let uow_counter = if let Some(uow_config) = &unit_of_work {
682 let component_ctx = Arc::new(
683 ControllerComponentContext::new(
684 Arc::clone(&self.registry),
685 Arc::clone(&self.languages),
686 self.tracer_metrics
687 .clone()
688 .unwrap_or_else(|| Arc::new(NoOpMetrics)),
689 Arc::clone(&self.platform_service),
690 self.health_registry(),
691 Some(route_id.clone()),
692 self.tracer_gating.levers.component_metrics_levers(),
693 )
694 .with_in_flight(Arc::clone(&self.in_flight_total)),
695 );
696 let rt: Arc<dyn camel_component_api::RuntimeObservability> =
697 Arc::clone(&component_ctx) as Arc<_>;
698 let (uow_layer, counter) = super::route_compiler_ext::resolve_uow_layer(
699 uow_config,
700 &producer_ctx,
701 rt,
702 component_ctx.as_ref(),
703 None,
704 )?;
705 pipeline = BoxProcessor::new(uow_layer.layer(pipeline));
706 Some(counter)
707 } else {
708 None
709 };
710
711 Ok(ManagedRoute {
712 definition: definition_info,
713 from_uri,
714 pipeline: super::pipeline_runtime::new_shared_pipeline_with_lifecycle(
715 pipeline, lifecycle,
716 ),
717 concurrency,
718 consumer_handle: None,
719 pipeline_handle: None,
720 consumer_cancel_token: CancellationToken::new(),
721 pipeline_cancel_token: CancellationToken::new(),
722 channel_sender: None,
723 in_flight: uow_counter,
724 drain_in_flight: Arc::new(std::sync::atomic::AtomicU64::new(0)),
725 aggregate_split,
726 agg_service: None,
727 stop_budget: None,
728 compiled: route_runtime_state::CompiledRoute {
729 security_policy,
730 security_authenticator,
731 provider_registry,
732 security_plan,
733 http_error_mapping,
734 },
735 })
736 }
737
738 pub async fn add_route_with_generation(
739 &mut self,
740 definition: RouteDefinition,
741 generation: u64,
742 ) -> Result<(), CamelError> {
743 let route_id = definition.route_id().to_string();
744 let from_uri = definition.from_uri().to_string();
745
746 if self.routes.contains_key(&route_id) {
747 return Err(CamelError::RouteError(format!(
748 "duplicate route ID '{route_id}'"
749 )));
750 }
751
752 debug!(route_id = %route_id, generation, "Adding route to controller with generation");
753
754 let managed = self.build_managed_route(
755 definition,
756 &super::step_resolution::FunctionStagingMode::HotReload { generation },
757 )?;
758
759 // Symmetric with `add_route`: an already-running bind must never
760 // observe an ungated insertion through the hot-reload path.
761 if let Err(err) = self.enforce_late_registration_gate(
762 &from_uri,
763 &route_id,
764 managed.compiled.security_plan.as_ref(),
765 ) {
766 self.discard_function_staging();
767 return Err(err);
768 }
769
770 self.routes.insert(route_id.clone(), managed);
771
772 self.endpoint_index.insert(&from_uri, &route_id);
773 Ok(())
774 }
775
776 pub async fn remove_route_preserving_functions(
777 &mut self,
778 route_id: &str,
779 ) -> Result<(), CamelError> {
780 let managed = self.routes.get(route_id).ok_or_else(|| {
781 CamelError::RouteError(format!("Route '{}' not found for removal", route_id))
782 })?;
783 if handle_is_running(&managed.consumer_handle)
784 || handle_is_running(&managed.pipeline_handle)
785 {
786 return Err(CamelError::RouteError(format!(
787 "Route '{}' must be stopped before removal (current execution lifecycle: {})",
788 route_id,
789 inferred_lifecycle_label(managed)
790 )));
791 }
792 self.routes.remove(route_id);
793 if let Some(reg) = &self.health_registry {
794 reg.unregister_for_route(route_id);
795 }
796 self.endpoint_index.remove(route_id);
797 debug!(route_id = %route_id, "Route removed from controller (functions preserved for reload finalize)");
798 Ok(())
799 }
800
801 /// Compile a route definition into a processor pipeline, without adding it
802 /// to the controller. Used for validation and testing.
803 pub fn compile_route_definition(
804 &self,
805 def: RouteDefinition,
806 ) -> Result<BoxProcessor, CamelError> {
807 self.route_compiler_ext().compile_route_definition(def)
808 }
809
810 /// Compile a route definition with a specific generation (for hot-reload).
811 pub fn compile_route_definition_with_generation(
812 &self,
813 def: RouteDefinition,
814 generation: u64,
815 ) -> Result<BoxProcessor, CamelError> {
816 self.route_compiler_ext()
817 .compile_route_definition_with_generation(def, generation)
818 }
819
820 /// Compile a route definition into a [`CompiledPipeline`] (processor +
821 /// lifecycle handles). Used by the hot-reload Restart path so that
822 /// lifecycle handles are threaded through
823 /// [`swap_pipeline_raw`](Self::swap_pipeline_raw).
824 pub(crate) fn compile_route_definition_pipeline(
825 &self,
826 def: RouteDefinition,
827 generation: u64,
828 ) -> Result<CompiledPipeline, CamelError> {
829 self.route_compiler_ext()
830 .compile_route_definition_pipeline(def, generation)
831 }
832
833 /// Compile without function generation, returning full [`CompiledPipeline`].
834 ///
835 /// Oracle Fix 1: used by the stateless hot-reload path so that
836 /// lifecycle-bearing routes have their handles preserved.
837 pub(crate) fn compile_route_definition_dry_pipeline(
838 &self,
839 def: RouteDefinition,
840 ) -> Result<CompiledPipeline, CamelError> {
841 self.route_compiler_ext()
842 .compile_route_definition_dry_pipeline(def)
843 }
844
845 /// Remove a route from the controller map.
846 ///
847 /// The route **must** be stopped before removal (status `Stopped` or `Failed`).
848 /// Returns an error if the route is still running or does not exist.
849 /// Does not cancel any running tasks — call `stop_route` first.
850 pub async fn remove_route(&mut self, route_id: &str) -> Result<(), CamelError> {
851 let managed = self.routes.get(route_id).ok_or_else(|| {
852 CamelError::RouteError(format!("Route '{}' not found for removal", route_id))
853 })?;
854 if handle_is_running(&managed.consumer_handle)
855 || handle_is_running(&managed.pipeline_handle)
856 {
857 return Err(CamelError::RouteError(format!(
858 "Route '{}' must be stopped before removal (current execution lifecycle: {})",
859 route_id,
860 inferred_lifecycle_label(managed)
861 )));
862 }
863 if let Some(invoker) = &self.function_invoker {
864 for (id, rid) in self.collect_function_refs(route_id) {
865 if let Err(e) = invoker.unregister(&id, rid.as_deref()).await {
866 warn!(route_id = %route_id, error = %e, "Failed to unregister function during route removal");
867 }
868 }
869 }
870 self.routes.remove(route_id);
871 if let Some(reg) = &self.health_registry {
872 reg.unregister_for_route(route_id);
873 }
874 self.endpoint_index.remove(route_id);
875 info!(route_id = %route_id, "Route removed from controller");
876 Ok(())
877 }
878
879 fn collect_function_refs(
880 &self,
881 route_id: &str,
882 ) -> Vec<(camel_api::FunctionId, Option<String>)> {
883 self.function_invoker
884 .as_ref()
885 .map(|invoker| invoker.function_refs_for_route(route_id))
886 .unwrap_or_default()
887 }
888
889 fn discard_function_staging(&self) {
890 if let Some(invoker) = &self.function_invoker {
891 invoker.discard_staging(0);
892 }
893 }
894
895 /// Returns the number of routes in the controller.
896 pub fn route_count(&self) -> usize {
897 self.routes.route_count()
898 }
899
900 pub fn in_flight_count(&self, route_id: &str) -> Option<u64> {
901 self.routes.in_flight_count(route_id)
902 }
903
904 /// Returns `true` if a route with the given ID exists.
905 pub fn route_exists(&self, route_id: &str) -> bool {
906 self.routes.route_exists(route_id)
907 }
908
909 /// Returns all route IDs.
910 pub fn route_ids(&self) -> Vec<String> {
911 self.routes.route_ids()
912 }
913
914 pub fn route_source_hash(&self, route_id: &str) -> Option<u64> {
915 self.routes.route_source_hash(route_id)
916 }
917
918 /// Returns route IDs that should auto-start, sorted by startup order (ascending).
919 pub fn auto_startup_route_ids(&self) -> Vec<String> {
920 self.routes.auto_startup_route_ids()
921 }
922
923 /// Returns route IDs sorted by shutdown order (startup order descending).
924 pub fn shutdown_route_ids(&self) -> Vec<String> {
925 self.routes.shutdown_route_ids()
926 }
927
928 /// Atomically swap the pipeline of a route (zero-downtime).
929 ///
930 /// In-flight requests finish with the old pipeline (kept alive by Arc).
931 /// New requests immediately use the new pipeline.
932 ///
933 /// ## Rejection policy
934 ///
935 /// Returns an error if the route has lifecycle-bearing steps or an active
936 /// aggregate — these require the **Restart path** (stop → swap → start).
937 ///
938 /// The caller (e.g. `reload_actions::apply_swap`) MUST catch this rejection
939 /// and fall back to:
940 /// 1. `stop_route_reload` — drain lifecycle, stop consumer
941 /// 2. `swap_pipeline_raw` — bypass the lifecycle check (route is stopped)
942 /// 3. `start_route_reload` — re-create consumer with the new pipeline
943 ///
944 /// This is the "reject, don't defer" policy (oracle Fix 3): the swap is
945 /// refused upfront rather than silently deferring or partially swapping.
946 pub fn swap_pipeline(
947 &self,
948 route_id: &str,
949 new_pipeline: BoxProcessor,
950 ) -> Result<(), CamelError> {
951 let managed = self
952 .routes
953 .get(route_id)
954 .ok_or_else(|| CamelError::RouteError(format!("Route '{}' not found", route_id)))?;
955
956 let assembly = managed.pipeline.load();
957 let has_lifecycle = !assembly.lifecycle.is_empty();
958
959 if has_lifecycle || managed.agg_service.is_some() {
960 warn!(
961 route_id = %route_id,
962 "Hot-swap rejected — route has lifecycle/agg steps; use Restart path"
963 );
964 return Err(CamelError::RouteError(format!(
965 "Route '{}' contains stateful steps (lifecycle-bearing). Hot-swap not supported — use restart.",
966 route_id
967 )));
968 }
969
970 drop(assembly);
971
972 if managed.aggregate_split.is_some() {
973 warn!(
974 route_id = %route_id,
975 "swap_pipeline: aggregate routes with timeout do not support hot-reload of pre/post segments"
976 );
977 }
978
979 super::pipeline_runtime::swap_pipeline_raw(&managed.pipeline, new_pipeline, vec![]);
980 debug!(route_id = %route_id, "Pipeline swapped atomically");
981 Ok(())
982 }
983
984 /// Non-checking raw pipeline swap — bypasses lifecycle/aggregate rejection.
985 ///
986 /// Only for use after the route has been stopped (Restart path).
987 /// Does NOT check for lifecycle handles or aggregate service — the caller
988 /// is responsible for ensuring the route is safe to swap.
989 ///
990 /// Accepts `lifecycle` so that the new pipeline assembly records the
991 /// lifecycle handles from the compiled steps. When the route is
992 /// subsequently stopped, these handles are drained.
993 pub(crate) fn swap_pipeline_raw(
994 &self,
995 route_id: &str,
996 new_pipeline: BoxProcessor,
997 lifecycle: Vec<Arc<dyn StepLifecycle>>,
998 ) -> Result<(), CamelError> {
999 let managed = self
1000 .routes
1001 .get(route_id)
1002 .ok_or_else(|| CamelError::RouteError(format!("Route '{}' not found", route_id)))?;
1003 super::pipeline_runtime::swap_pipeline_raw(&managed.pipeline, new_pipeline, lifecycle);
1004 debug!(route_id = %route_id, "Pipeline swapped (raw — lifecycle bypass)");
1005 Ok(())
1006 }
1007
1008 /// Returns the from_uri of a route, if it exists.
1009 pub fn route_from_uri(&self, route_id: &str) -> Option<String> {
1010 self.routes.route_from_uri(route_id)
1011 }
1012
1013 /// Return all route_ids that consume from the given source endpoint URI.
1014 pub fn routes_for_endpoint(&self, uri: &str) -> Vec<String> {
1015 self.endpoint_index.routes_for(uri)
1016 }
1017
1018 /// Return all registered source endpoint URIs.
1019 pub fn list_endpoint_uris(&self) -> Vec<String> {
1020 self.endpoint_index.list_uris()
1021 }
1022
1023 /// Get a clone of the current pipeline for a route.
1024 ///
1025 /// This is useful for testing and introspection.
1026 /// Returns `None` if the route doesn't exist.
1027 pub fn get_pipeline(&self, route_id: &str) -> Option<BoxProcessor> {
1028 self.routes.get_pipeline(route_id)
1029 }
1030
1031 /// Check whether the running route has lifecycle-bearing steps.
1032 ///
1033 /// Returns `false` when the route is missing.
1034 pub(crate) fn route_has_lifecycle(&self, route_id: &str) -> bool {
1035 self.routes
1036 .get(route_id)
1037 .map(|managed| !managed.pipeline.load().lifecycle.is_empty())
1038 .unwrap_or(false)
1039 }
1040
1041 /// Internal stop implementation that can set custom status.
1042 pub(super) async fn stop_route_internal(&mut self, route_id: &str) -> Result<(), CamelError> {
1043 self.routes.stop_route(route_id).await
1044 }
1045
1046 /// Internal stop with an explicit graceful drain budget.
1047 pub(super) async fn stop_route_with_budget_internal(
1048 &mut self,
1049 route_id: &str,
1050 budget: std::time::Duration,
1051 ) -> Result<(), CamelError> {
1052 self.routes.stop_route_with_budget(route_id, budget).await
1053 }
1054
1055 pub async fn start_route_reload(&mut self, route_id: &str) -> Result<(), CamelError> {
1056 self.start_route(route_id).await
1057 }
1058
1059 pub async fn stop_route_reload(&mut self, route_id: &str) -> Result<(), CamelError> {
1060 self.stop_route(route_id).await
1061 }
1062}
1063
1064// ── Aggregator route helpers ──
1065
1066impl DefaultRouteController {
1067 /// Start a route with an aggregate split (pre-pipeline → aggregator → post-pipeline).
1068 ///
1069 /// Spawns a biased-select forward loop that routes exchanges through the
1070 /// pre-pipeline, aggregator, and post-pipeline in sequence, with late-exchange
1071 /// handling and force-completion on stop.
1072 ///
1073 /// drainclaim claim propagation: the forward loop submits each
1074 /// envelope's [`InFlightClaim`] into the aggregator WITH its exchange
1075 /// ([`AggregatorService::submit_with_claim`]) — a pending stash parks
1076 /// the claim inside the bucket so the stashed exchange stays counted,
1077 /// and every emission path (sync completion, timeout `late_tx` fire,
1078 /// `force_complete_all` at stop) hands the bucket's claims back to
1079 /// this loop, which holds them across the post-pipeline
1080 /// continuation. Paths that drop a bucket without emitting (TTL
1081 /// eviction, unarmed-bucket release, discard-on-timeout, saturated
1082 /// late channel) release by dropping. Exactly one release per claim
1083 /// on every path. claimfamily (rc-e1a4f): every oneshot dispatch
1084 /// through the pre/post pipelines splits a sibling claim onto the
1085 /// exchange (in-band results take it back, stash emissions escape
1086 /// with theirs), so stash sites embedded in those pipelines stay
1087 /// counted.
1088 #[allow(clippy::too_many_arguments)]
1089 pub(super) async fn start_aggregate_route(
1090 &mut self,
1091 route_id: &str,
1092 split: AggregateSplitInfo,
1093 consumer: Box<dyn Consumer>,
1094 consumer_ctx: ConsumerContext,
1095 mut rx: mpsc::Receiver<ExchangeEnvelope>,
1096 crash_notifier: Option<mpsc::Sender<CrashNotification>>,
1097 runtime_for_consumer: Option<Weak<dyn RuntimeHandle>>,
1098 tx_for_storage: mpsc::Sender<ExchangeEnvelope>,
1099 // Pipeline cancellation — a child of the managed route's pipeline_cancel_token.
1100 pipeline_cancel: CancellationToken,
1101 drain_in_flight: Arc<std::sync::atomic::AtomicU64>,
1102 ) -> Result<(), CamelError> {
1103 // drainclaim claim propagation: the late channel carries each
1104 // emission's stashed claims alongside the aggregated exchange —
1105 // the loop holds them across the post-pipeline continuation.
1106 let (late_tx, late_rx) =
1107 mpsc::channel::<camel_processor::aggregator::AggregateEmission>(256);
1108
1109 let route_cancel_clone = pipeline_cancel.clone();
1110 let mut svc = AggregatorService::try_new(
1111 split.agg_config.clone(),
1112 late_tx,
1113 Arc::clone(&self.languages),
1114 route_cancel_clone,
1115 )?;
1116 // Queue-depth visibility: the TTL-sweep pass reports the buffered
1117 // group count as camel_queue_depth{queue="aggregator:<route>"}.
1118 if let Some(metrics) = self.tracer_metrics.clone() {
1119 svc = svc.with_queue_metrics(metrics, format!("aggregator:{route_id}"));
1120 }
1121 let agg = Arc::new(svc);
1122
1123 let pipeline_cancel_for_monitor = pipeline_cancel.clone();
1124 // rc-e2r9: capture route_id and metrics for b′ emission at reply-drop
1125 // sites inside the spawned task.
1126 let route_id_for_metrics = route_id.to_string();
1127 let metrics_for_reply_drop = self.tracer_metrics.clone();
1128 // rc-jxkj cohort gate: owned by the forward loop — the envelope arm
1129 // parks dispatch until the startup cohort opens the gate.
1130 let mut cohort_rx = self.cohort.subscribe();
1131 let agg_for_monitor = Arc::clone(&agg);
1132
1133 {
1134 let managed = self
1135 .routes
1136 .get_mut(route_id)
1137 .expect("invariant: route must exist"); // allow-unwrap
1138 managed.agg_service = Some(Arc::clone(&agg));
1139 }
1140
1141 let late_rx = Arc::new(tokio::sync::Mutex::new(late_rx));
1142 let pre_pipeline = split.pre_pipeline;
1143 let post_pipeline = split.post_pipeline;
1144
1145 // Spawn biased select forward loop
1146 let pipeline_handle = tokio::spawn(async move {
1147 loop {
1148 tokio::select! {
1149 biased;
1150
1151 // Ungated by design (D3, rc-jxkj): late exchanges exist
1152 // only after a dispatched envelope traversed the
1153 // aggregator — transitively post-activation. Gating here
1154 // would be dead code and a self-deadlock risk.
1155 late_ex = async {
1156 let mut rx = late_rx.lock().await;
1157 rx.recv().await
1158 } => {
1159 match late_ex {
1160 Some(emission) => {
1161 // drainclaim: hold the emission's stashed
1162 // claims across the post-pipeline — drop
1163 // at iteration end is the release.
1164 let AggregateEmission {
1165 mut exchange,
1166 claims: _in_flight_claims,
1167 } = emission;
1168 // claimfamily (rc-e1a4f): split a sibling onto the emission exchange so
1169 // residency inside stash sites embedded in the post-pipeline stays
1170 // counted after this iteration. An in-band result drops at iteration end
1171 // (its sibling releases with it); a stash emission escapes with its
1172 // sibling; an Err drops it with the exchange.
1173 exchange.in_flight_claim = _in_flight_claims
1174 .iter()
1175 .flatten()
1176 .next()
1177 .map(InFlightClaim::split);
1178 let pipe = post_pipeline.load();
1179 if let Err(e) =
1180 pipe.processor.clone_inner().oneshot(exchange).await
1181 {
1182 tracing::warn!(error = %e, "late exchange post-pipeline failed");
1183 }
1184 }
1185 None => return,
1186 }
1187 }
1188
1189 envelope_opt = rx.recv() => {
1190 match envelope_opt {
1191 Some(envelope) => {
1192 // rc-jxkj cohort gate: park dispatch until
1193 // the startup cohort completes (same guard
1194 // as the non-aggregate drain loops).
1195 // rc-z5qz: `biased` with the gate polled
1196 // FIRST — with the cohort open AND the
1197 // pipeline token cancelled, both branches
1198 // are ready and an unbiased select picks
1199 // randomly, letting the cancel arm drop a
1200 // deliverable envelope (force_complete_all
1201 // then sees no buckets). Gate-open must win
1202 // deterministically; a genuinely closed
1203 // gate still drops on cancel (rc-jxkj
1204 // semantics preserved).
1205 tokio::select! {
1206 biased;
1207 _ = cohort_rx.wait_for(|open| *open) => {}
1208 _ = pipeline_cancel.cancelled() => {
1209 // Drop the envelope; reply_tx (if
1210 // any) resolves to ChannelClosed for
1211 // the send_and_wait waiter.
1212 // `continue`, not `return`: the token
1213 // is already cancelled, so the next
1214 // loop iteration lands in the biased
1215 // outer select's cancel arm below,
1216 // which runs the force_complete_all +
1217 // late_rx cleanup. A `return` would
1218 // skip that cleanup and silently
1219 // drop a pending bucket across a
1220 // stop→restart gate re-arm.
1221 continue;
1222 }
1223 }
1224 let ExchangeEnvelope {
1225 exchange,
1226 reply_tx,
1227 in_flight_claim,
1228 } = envelope;
1229 let _drain_guard = super::route_helpers::DrainGuard::new(Arc::clone(&drain_in_flight));
1230 // drainclaim claim PROPAGATION: the
1231 // envelope's claim travels WITH the
1232 // exchange into the aggregator — a
1233 // pending stash parks it in the bucket
1234 // (counted until the bucket completes),
1235 // and a sync completion returns it (with
1236 // the rest of the bucket's claims) to be
1237 // held across the post-pipeline below.
1238 // Rejection paths drop it inside the
1239 // service — rejected = released.
1240 let pre_pipe = pre_pipeline.load();
1241 // claimfamily (rc-e1a4f): split a sibling claim onto the exchange so
1242 // residency inside stash sites embedded in the pre-pipeline stays
1243 // counted after this oneshot resolves. Taken back from an in-band Ok
1244 // result below — the envelope's own claim still travels with the
1245 // exchange into the aggregator; a stash emission escapes with its
1246 // sibling; an Err drops it with the exchange.
1247 let mut exchange = exchange;
1248 exchange.in_flight_claim = in_flight_claim.as_ref().map(InFlightClaim::split);
1249 let ex = match pre_pipe.processor.clone_inner().oneshot(exchange).await {
1250 // claimfamily: in-band completion — reclaim the sibling so release
1251 // stays at this loop iteration.
1252 Ok(mut ex) => {
1253 ex.in_flight_claim = None;
1254 ex
1255 }
1256 Err(e) => {
1257 // rc-e2r9: the real error rides with the
1258 // result so a dropped receiver still gets
1259 // it (ConsumerStopping suppressed).
1260 send_reply_or_b_prime(
1261 reply_tx,
1262 Err(e),
1263 &metrics_for_reply_drop,
1264 &route_id_for_metrics,
1265 "aggregate:pre-pipeline",
1266 );
1267 continue;
1268 }
1269 };
1270
1271 let AggregationReceipt { reply, claims } =
1272 agg.submit_with_claim(ex, in_flight_claim).await;
1273 // drainclaim: hold the completed bucket's
1274 // claims across the post-pipeline
1275 // continuation; dropped at iteration end or
1276 // any `continue`/`return` (scope exit).
1277 let _completed_bucket_claims = claims;
1278
1279 match reply {
1280 Ok(ex) => {
1281 if !is_pending(&ex) {
1282 let post_pipe = post_pipeline.load();
1283 // claimfamily (rc-e1a4f): split a sibling from the completed
1284 // bucket's claims onto the aggregated output so residency inside
1285 // stash sites embedded in the post-pipeline stays counted after
1286 // this iteration. Taken back from an in-band result before the
1287 // reply — release stays at iteration end; a stash emission
1288 // escapes with its sibling; an Err drops it with the exchange.
1289 let mut ex = ex;
1290 ex.in_flight_claim = _completed_bucket_claims
1291 .iter()
1292 .flatten()
1293 .next()
1294 .map(InFlightClaim::split);
1295 let mut out = post_pipe.processor.clone_inner().oneshot(ex).await;
1296 if let Ok(ref mut out_ex) = out {
1297 out_ex.in_flight_claim = None;
1298 }
1299 // rc-e2r9 review, Important 1: this site
1300 // previously `let _ = send`ed the
1301 // post-pipeline result — an Err with an
1302 // abandoned receiver vanished silently.
1303 // The helper closes that gap.
1304 send_reply_or_b_prime(
1305 reply_tx,
1306 out,
1307 &metrics_for_reply_drop,
1308 &route_id_for_metrics,
1309 "aggregate:post-pipeline",
1310 );
1311 } else {
1312 // Pending Ok: a dropped reply is silent —
1313 // b′ is an ERROR signal.
1314 send_reply_or_b_prime(
1315 reply_tx,
1316 Ok(ex),
1317 &metrics_for_reply_drop,
1318 &route_id_for_metrics,
1319 "aggregate:pending",
1320 );
1321 }
1322 }
1323 Err(e) => {
1324 send_reply_or_b_prime(
1325 reply_tx,
1326 Err(e),
1327 &metrics_for_reply_drop,
1328 &route_id_for_metrics,
1329 "aggregate:pipeline",
1330 );
1331 }
1332 }
1333 }
1334 None => return,
1335 }
1336 }
1337
1338 _ = pipeline_cancel.cancelled() => {
1339 agg.force_complete_all();
1340 let mut rx_guard = late_rx.lock().await;
1341 while let Ok(late_ex) = rx_guard.try_recv() {
1342 // drainclaim: each forced emission's claims are
1343 // held across its post-pipeline continuation —
1344 // dropped after the oneshot completes (or
1345 // immediately, which is also a release).
1346 let AggregateEmission {
1347 mut exchange,
1348 claims: _in_flight_claims,
1349 } = late_ex;
1350 // claimfamily (rc-e1a4f): split a sibling onto the forced emission so
1351 // residency inside stash sites embedded in the post-pipeline stays
1352 // counted. The discarded result releases an in-band sibling with its
1353 // drop; a stash emission escapes with its sibling.
1354 exchange.in_flight_claim = _in_flight_claims
1355 .iter()
1356 .flatten()
1357 .next()
1358 .map(InFlightClaim::split);
1359 let pipe = post_pipeline.load();
1360 let _ = pipe.processor.clone_inner().oneshot(exchange).await;
1361 }
1362 break;
1363 }
1364 }
1365 }
1366 });
1367 #[cfg(test)]
1368 emit_start_route_event("pipeline_spawned", route_id);
1369
1370 // Start consumer after pipeline loop is spawned to avoid startup races
1371 // where consumers emit exchanges before the route pipeline begins polling.
1372 // rc-kh7c cleanup parity: capture the consumer's cancel token before
1373 // consumer_ctx moves into the task so the failure arm can stop child
1374 // tasks spawned by consumer.start().
1375 let consumer_cancel_for_cleanup = consumer_ctx.cancel_token();
1376 let (consumer_handle, startup_rx, watcher_inputs, outer_inputs, stop_budget_tx) =
1377 super::consumer_management::spawn_consumer_task(
1378 route_id.to_string(),
1379 consumer,
1380 consumer_ctx,
1381 crash_notifier,
1382 runtime_for_consumer,
1383 false,
1384 );
1385
1386 // rc-w1u9: await consumer startup handshake for aggregate routes too
1387 // so bind failures surface as route-start errors.
1388 // For Immediate consumers the receiver is pre-resolved (rc-slvd).
1389 let startup_result =
1390 super::consumer_management::await_consumer_startup(startup_rx, "startup").await;
1391 // rc-kh7c: on failure, abort the orphaned consumer task and cancel the
1392 // pipeline so neither runs detached. The aggregate pipeline loop would
1393 // eventually self-clean via rx-drop + late_tx-drop, but cancelling
1394 // pipeline_cancel also triggers force_complete_all (aggregate cleanup).
1395 if let Err(e) = startup_result {
1396 consumer_handle.abort();
1397 pipeline_cancel_for_monitor.cancel();
1398 // Deliberate Explicit-failure cleanup parity with the trait start arm (rc-kh7c).
1399 consumer_cancel_for_cleanup.cancel();
1400 return Err(e);
1401 }
1402
1403 // Detached failure watcher for Immediate consumers (rc-slvd).
1404 if let Some(inputs) = watcher_inputs {
1405 super::consumer_management::spawn_failure_watcher(inputs);
1406 }
1407
1408 // Detached outer-task watcher for Explicit consumers (rc-a7rh):
1409 // spawned only after the handshake resolved Ok — rollback
1410 // terminations (abort-then-cancel above) happen before this point
1411 // and are never watched. Explicit consumers on aggregate routes
1412 // get identical coverage — no aggregate carve-out.
1413 if let Some(outer) = outer_inputs {
1414 super::consumer_management::spawn_outer_task_watcher(outer);
1415 }
1416
1417 // Extend the stored consumer handle through aggregate force-completion.
1418 // While this monitor drains pending buckets, handle_is_running still reports
1419 // the Route as running because forced exchanges may still be in post-pipeline.
1420 //
1421 // bd rc-iioeq: a natural consumer exit (e.g. timer repeatCount
1422 // exhausted) must NOT destroy buckets whose inactivity timeout is
1423 // armed. With `force_completion_on_stop=false` (the default),
1424 // `force_complete_all` CANCELS the armed timeout task and silently
1425 // discards the bucket, so the inactivity emission never happens.
1426 // The forward loop stays up (the stored channel sender keeps the
1427 // input channel open), so an armed bucket still emits downstream
1428 // when its timeout fires. Buckets with no armed timeout task —
1429 // size/predicate-only, or timeout-configured but over the
1430 // `max_timeout_tasks` cap — can never complete after the consumer
1431 // exits; `release_unarmed_buckets` discards them eagerly so they
1432 // are not orphaned (the bucket_ttl sweep only runs inside the
1433 // pipeline's next exchange, which never arrives).
1434 let force_on_stop = agg_for_monitor.config().force_completion_on_stop;
1435 let consumer_handle = tokio::spawn(async move {
1436 let _ = consumer_handle.await;
1437 if !pipeline_cancel_for_monitor.is_cancelled() {
1438 if force_on_stop {
1439 agg_for_monitor.force_complete_all();
1440 pipeline_cancel_for_monitor.cancel();
1441 } else {
1442 agg_for_monitor.release_unarmed_buckets();
1443 }
1444 }
1445 });
1446 #[cfg(test)]
1447 emit_start_route_event("consumer_spawned", route_id);
1448
1449 {
1450 let managed = self
1451 .routes
1452 .get_mut(route_id)
1453 .expect("invariant: route must exist"); // allow-unwrap
1454 managed.consumer_handle = Some(consumer_handle);
1455 managed.pipeline_handle = Some(pipeline_handle);
1456 managed.channel_sender = Some(tx_for_storage);
1457 managed.stop_budget = Some(stop_budget_tx);
1458 }
1459
1460 info!(route_id = %route_id, "Route started (aggregate with timeout)");
1461 Ok(())
1462 }
1463
1464 /// Test-only: inject lifecycle handles into an existing route's pipeline
1465 /// assembly. This makes the route lifecycle-bearing so that swap_pipeline
1466 /// rejects it, forcing callers (like reload_actions::apply_swap) to take
1467 /// the Restart path instead.
1468 #[cfg(test)]
1469 pub(crate) fn set_route_lifecycle_for_test(
1470 &mut self,
1471 route_id: &str,
1472 lifecycle: Vec<Arc<dyn StepLifecycle>>,
1473 ) -> Result<(), CamelError> {
1474 use super::pipeline_runtime::PipelineAssembly;
1475 use camel_api::SyncBoxProcessor;
1476 use std::sync::Arc;
1477
1478 let managed = self
1479 .routes
1480 .get_mut(route_id)
1481 .ok_or_else(|| CamelError::RouteError(format!("Route '{}' not found", route_id)))?;
1482 let old_processor = managed.pipeline.load().processor.clone_inner();
1483 managed.pipeline.store(Arc::new(PipelineAssembly::new(
1484 SyncBoxProcessor::new(old_processor),
1485 lifecycle,
1486 )));
1487 Ok(())
1488 }
1489}
1490
1491// ── rc-e2r9: b′ signal emission on reply-drop ──
1492// The shared `send_reply_or_b_prime` helper lives in
1493// `super::route_helpers` — it is used by both this module (aggregate drain
1494// loop) and `route_controller_trait` (Concurrent/Sequential pipelines).
1495
1496#[cfg(test)]
1497impl crate::hot_reload::ports::ReloadIntrospectionPort for DefaultRouteController {
1498 fn route_ids(&self) -> Vec<String> {
1499 self.route_ids() // inherent pub fn
1500 }
1501 fn route_from_uri(&self, route_id: &str) -> Option<String> {
1502 self.route_from_uri(route_id) // inherent pub fn
1503 }
1504 fn route_source_hash(&self, route_id: &str) -> Option<u64> {
1505 self.route_source_hash(route_id) // inherent pub fn
1506 }
1507}
1508
1509#[cfg(test)]
1510#[path = "route_controller_tests.rs"]
1511mod tests;
1512
1513#[cfg(test)]
1514#[path = "cohort_activation_regression.rs"]
1515mod cohort_activation_regression;