camel_core/lifecycle/adapters/route_controller_trait.rs
1//! `RouteController` trait implementation for `DefaultRouteController`.
2//!
3//! Extracted from `route_controller.rs` to reduce file size. All lifecycle methods
4//! (start, stop, suspend, resume, etc.) live here.
5
6use std::sync::Arc;
7use std::time::Duration;
8
9use tokio::sync::mpsc;
10use tokio_util::sync::CancellationToken;
11use tower::Service;
12use tracing::{error, info, warn};
13
14use camel_api::metrics::MetricsCollector;
15use camel_api::security_policy::RouteSecurityPlan;
16use camel_api::{CamelError, NoOpMetrics, StepLifecycle, StepShutdownReason};
17use camel_component_api::Consumer;
18use camel_component_api::{ConcurrencyModel, ConsumerContext, consumer::ExchangeEnvelope};
19
20use crate::lifecycle::adapters::consumer_management;
21use crate::lifecycle::adapters::controller_component_context::ControllerComponentContext;
22use crate::lifecycle::adapters::inline_dispatcher::RouteInlineDispatcher;
23use crate::lifecycle::adapters::route_compiler::CANCEL_TOKEN;
24use crate::lifecycle::adapters::route_controller::DefaultRouteController;
25#[cfg(test)]
26use crate::lifecycle::adapters::route_helpers::emit_start_route_event;
27use crate::lifecycle::adapters::route_helpers::{
28 DrainGuard, handle_is_running, inferred_lifecycle_label, ready_with_backoff,
29 send_reply_or_b_prime,
30};
31use crate::lifecycle::adapters::route_registry::DEFAULT_SHUTDOWN_TIMEOUT;
32use crate::lifecycle::adapters::route_runtime_state::CompiledRoute;
33
34/// Operator acknowledgements for public exposure per bind address and the
35/// per-bind exposure gate (ADR-0061).
36///
37/// Canonical home is `camel_auth::bind_gate` (moved in Task 2.6 so
38/// transports — which may not reference `camel_core::`, see
39/// `xtask lint-component-deps` — enforce the same gate; MCP's registry is
40/// the first). Re-exported here so controller call sites, the CLI, and the
41/// gate tests keep their historical import paths.
42pub use camel_auth::bind_gate::{BindExposureAcks, enforce_bind_exposure_gate};
43
44/// Canonical gate key + loopback classification for a listener `from` URI.
45/// Only listener schemes (http/https/ws/wss/grpc) bind sockets, so only they gate;
46/// `mcp:` binds live in `McpServerConfig` (gated at the McpServerRegistry level,
47/// Task 2.6) and everything else (timer, direct) never binds.
48pub(super) struct BindKey {
49 pub(super) key: String,
50 pub(super) loopback: bool,
51}
52
53pub(super) fn bind_key_from_uri(uri: &str) -> Option<BindKey> {
54 let scheme = uri.split(':').next()?;
55 if !matches!(scheme, "http" | "https" | "ws" | "wss" | "grpc") {
56 return None;
57 }
58 let authority = uri.split("://").nth(1)?;
59 let authority = authority.split('/').next()?;
60 if authority.is_empty() {
61 return None;
62 }
63 if let Ok(addr) = authority.parse::<std::net::SocketAddr>() {
64 return Some(BindKey {
65 key: addr.to_string(),
66 loopback: addr.ip().is_loopback(),
67 });
68 }
69 // Hostname authority: loopback only for `localhost` (deterministic,
70 // fail-closed for every other hostname — no DNS). The host is the
71 // authority minus its port; bracketed IPv6 authorities are stripped
72 // to the bare host before the check.
73 let host = authority
74 .rsplit_once(':')
75 .map(|(h, _)| h)
76 .unwrap_or(authority)
77 .trim_matches(['[', ']']);
78 let loopback = host.eq_ignore_ascii_case("localhost");
79 Some(BindKey {
80 key: authority.to_string(),
81 loopback,
82 })
83}
84
85/// Wire the route's security context onto a freshly created consumer —
86/// the start and resume paths share this delivery.
87///
88/// Policy-backed routes (`sp_config` + authenticator marker) receive the
89/// policy with its credential sources, the named providers, and the
90/// compiled plan. Without a policy, every staged server route still
91/// carries a compiled plan (Task 1.2) — deliver it plan-only so consumers
92/// enforce the kernel classification (e.g. strict dispatch) from day one.
93/// Routes with neither get no context.
94fn deliver_security_context(consumer: &mut dyn Consumer, compiled: &CompiledRoute) {
95 use camel_component_api::SecurityContext;
96
97 if let (Some(sp_config), Some(_)) = (
98 compiled.security_policy.as_ref(),
99 compiled.security_authenticator.as_ref(),
100 ) {
101 let mut sec_ctx = SecurityContext::from_arc(Arc::clone(&sp_config.policy))
102 .with_credential_sources(sp_config.credential_sources.clone());
103 // Inject the route's named providers so Phase-2 transports (grpc
104 // 2.1, mcp 2.6, ws 2.8, http 2.9) can resolve them from the
105 // SecurityContext instead of holding their own authenticator.
106 if let Some(registry) = &compiled.provider_registry {
107 sec_ctx = sec_ctx.with_providers(Arc::clone(registry));
108 }
109 // Thread the compiled plan (Task 1.8) so transports drive
110 // per-route dispatch enforcement from it.
111 if let Some(plan) = &compiled.security_plan {
112 sec_ctx = sec_ctx.with_plan(plan.clone());
113 }
114 consumer.set_security_context(sec_ctx);
115 } else if let Some(plan) = compiled.security_plan.clone() {
116 // Plan-only delivery (Task 1.2): every staged server route
117 // carries a compiled plan even without a policy declaration —
118 // deliver it so consumers enforce the kernel classification
119 // (e.g. strict dispatch) from day one.
120 let mut sec_ctx = SecurityContext::from_plan(plan);
121 if let Some(registry) = &compiled.provider_registry {
122 sec_ctx = sec_ctx.with_providers(Arc::clone(registry));
123 }
124 consumer.set_security_context(sec_ctx);
125 }
126}
127
128/// ADR-0061 Task 2.9 strict-mode dispatch check (the flip deferred from
129/// Task 2.2): every transport mints the typed carrier at its request
130/// boundary (grpc 2.1, mcp 2.6, ws 2.8, http 2.9), so a non-Public plan
131/// REQUIRES the carrier on the Exchange — absent or wrong-provider is
132/// denied BEFORE the pipeline runs; the transport renders the denial in
133/// its own idiom via `reply_tx`. Returns `true` when the dispatch was
134/// denied (caller must `continue`).
135///
136/// The denial reply is a reply to a dispatched send, so it carries the same
137/// abandoned-receiver hazard as the pipeline reply sites: when the producer
138/// timed out and dropped the receiver, the denial would vanish silently.
139/// It therefore goes through [`send_reply_or_b_prime`] (rc-e2r9 review,
140/// Important 1 disposition: covered, not out-of-contract — there is no
141/// probe path here where the receiver is *expected* to be gone; the
142/// fire-and-forget case is the `None` branch below, which keeps its plain
143/// `warn!`). A `None` channel is a no-op for the helper.
144fn strict_dispatch_denies(
145 dispatch_plan: &Option<camel_api::security_policy::RouteSecurityPlan>,
146 exchange: &camel_api::Exchange,
147 reply_tx: &mut Option<tokio::sync::oneshot::Sender<Result<camel_api::Exchange, CamelError>>>,
148 metrics: &Option<Arc<dyn MetricsCollector>>,
149 route_id: &str,
150) -> bool {
151 if let Some(plan) = dispatch_plan.as_ref()
152 && let Err(denial) = camel_auth::enforce_dispatch(plan, exchange)
153 {
154 if let Some(tx) = reply_tx.take() {
155 send_reply_or_b_prime(Some(tx), Err(denial), metrics, route_id, "dispatch:denied");
156 } else {
157 // log-policy: handler-owned
158 warn!(
159 route_id = %route_id,
160 error = %denial,
161 "dispatch denied: no kernel carrier on Exchange"
162 );
163 }
164 return true;
165 }
166 false
167}
168
169#[cfg(test)]
170mod bind_key_tests {
171 use super::bind_key_from_uri;
172
173 #[test]
174 fn https_and_wss_listeners_gate() {
175 assert_eq!(
176 bind_key_from_uri("https://0.0.0.0:8443/api").map(|b| b.key),
177 Some("0.0.0.0:8443".to_string())
178 );
179 assert_eq!(
180 bind_key_from_uri("wss://0.0.0.0:9000").map(|b| b.key),
181 Some("0.0.0.0:9000".to_string())
182 );
183 }
184
185 #[test]
186 fn non_listener_schemes_skip() {
187 assert!(bind_key_from_uri("timer:tick?period=1s").is_none());
188 assert!(bind_key_from_uri("mcp:server/tool/x").is_none());
189 }
190
191 #[test]
192 fn bracketed_ipv6_hostname_check_uses_bare_host() {
193 let b = bind_key_from_uri("ws://[::1]:8080/path").expect("parses"); // allow-unwrap
194 assert!(b.loopback, "[::1] is loopback");
195 }
196
197 #[test]
198 fn localhost_authority_with_port_is_loopback() {
199 // Regression: rsplit(':') once compared the PORT segment ("8080"),
200 // never matching "localhost"; the host must exclude the port.
201 let b = bind_key_from_uri("http://localhost:8080/api").expect("parses"); // allow-unwrap
202 assert!(b.loopback, "localhost is loopback");
203 let b = bind_key_from_uri("http://myhost.example:8080").expect("parses"); // allow-unwrap
204 assert!(!b.loopback, "other hostnames stay non-loopback");
205 }
206}
207
208/// Best-effort, reverse-order shutdown of already-started `StepLifecycle`
209/// handles when `start_route` must abort. Used both mid-start-loop (the
210/// `[0..idx)` already-started prefix) and for any post-start failure path
211/// (e.g. `create_route_consumer`, the aggregate spawn branch, the consumer
212/// startup handshake) so the ADR-0022 SPI holds: if `start_route` returns
213/// `Err`, no started handle is left running.
214///
215/// Mirrors `StepLifecycle::shutdown`'s best-effort contract — each error is
216/// logged and swallowed so one failing shutdown cannot block rollback of the
217/// remaining handles.
218async fn rollback_started(route_id: &str, handles: &[Arc<dyn StepLifecycle>]) {
219 for handle in handles.iter().rev() {
220 if let Err(e) = handle.shutdown(StepShutdownReason::RouteStop).await {
221 warn!(
222 route_id = %route_id,
223 step = handle.name(),
224 error = %e,
225 "best-effort step shutdown during start rollback failed"
226 );
227 }
228 }
229}
230
231#[async_trait::async_trait]
232impl camel_api::RouteController for DefaultRouteController {
233 async fn start_route(&mut self, route_id: &str) -> Result<(), CamelError> {
234 // Check if route exists and can be started.
235 {
236 let managed = self
237 .routes
238 .get_mut(route_id)
239 .ok_or_else(|| CamelError::RouteError(format!("Route '{}' not found", route_id)))?;
240
241 let consumer_running = handle_is_running(&managed.consumer_handle);
242 let pipeline_running = handle_is_running(&managed.pipeline_handle);
243 if consumer_running && pipeline_running {
244 return Ok(());
245 }
246 if !consumer_running && pipeline_running {
247 return Err(CamelError::RouteError(format!(
248 "Route '{}' is suspended; use resume_route() to resume, or stop_route() then start_route() for full restart",
249 route_id
250 )));
251 }
252 if consumer_running && !pipeline_running {
253 return Err(CamelError::RouteError(format!(
254 "Route '{}' has inconsistent execution state; stop_route() then retry start_route()",
255 route_id
256 )));
257 }
258 }
259
260 info!(route_id = %route_id, "Starting route");
261
262 // Get the resolved route info
263 let (from_uri, pipeline, concurrency, dispatch_plan) = {
264 let managed = self
265 .routes
266 .get(route_id)
267 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
268 (
269 managed.from_uri.clone(),
270 Arc::clone(&managed.pipeline),
271 managed.concurrency.clone(),
272 managed.compiled.security_plan.clone(),
273 )
274 };
275
276 // ADR-0061 per-bind exposure gate: refuse to start Public routes on
277 // non-loopback binds without operator acknowledgement. Runs before
278 // any lifecycle step starts, so nothing needs rolling back. All
279 // sibling plans on the same bind are aggregated so the error/warn
280 // names every Public route on the bind.
281 if let Some(bind) = bind_key_from_uri(&from_uri) {
282 let owned = self.plans_for_bind(&bind.key);
283 let siblings: Vec<(&str, &RouteSecurityPlan)> =
284 owned.iter().map(|(id, plan)| (id.as_str(), plan)).collect();
285 enforce_bind_exposure_gate(
286 &bind.key,
287 bind.loopback,
288 &siblings,
289 self.bind_acks.acknowledged(&bind.key),
290 )?;
291 }
292
293 // ADR-0022: await each stateful step's `start()` before spawning the
294 // pipeline or consumer. On the Nth failure, roll back the already-
295 // started steps in reverse order (best-effort) and return the original
296 // start error WITHOUT spawning anything. Handles come from the compiled
297 // pipeline assembly, already collected in route order at compile time.
298 let lifecycle_handles: Vec<Arc<dyn StepLifecycle>> = pipeline.load().lifecycle.clone();
299 for (idx, handle) in lifecycle_handles.iter().enumerate() {
300 if let Err(start_err) = handle.start().await {
301 warn!(
302 route_id = %route_id,
303 step = handle.name(),
304 "step start failed; rolling back already-started steps"
305 );
306 // Only [0..idx) have started; the Nth handle itself never did.
307 rollback_started(route_id, &lifecycle_handles[0..idx]).await;
308 return Err(start_err);
309 }
310 }
311
312 // Clone crash notifier for consumer task
313 let crash_notifier = self.crash_notifier.clone();
314 let runtime_for_consumer = self.runtime.clone();
315
316 let consumer_component_ctx = Arc::new(ControllerComponentContext::new(
317 Arc::clone(&self.registry),
318 Arc::clone(&self.languages),
319 self.tracer_metrics
320 .clone()
321 .unwrap_or_else(|| Arc::new(NoOpMetrics)),
322 Arc::clone(&self.platform_service),
323 self.health_registry(),
324 Some(route_id.to_string()),
325 self.tracer_gating.levers.components_enabled(),
326 ));
327 let consumer_rt: Arc<dyn camel_component_api::RuntimeObservability> =
328 Arc::clone(&consumer_component_ctx) as Arc<_>;
329 let (mut consumer, consumer_concurrency) = match consumer_management::create_route_consumer(
330 consumer_rt,
331 &self.registry,
332 &from_uri,
333 consumer_component_ctx.as_ref(),
334 ) {
335 Ok(v) => v,
336 // ADR-0022 SPI: every started handle must be rolled back
337 // before start_route returns Err, so no stateful step is left
338 // running. This is the first post-start fallible step.
339 Err(e) => {
340 rollback_started(route_id, &lifecycle_handles).await;
341 return Err(e);
342 }
343 };
344
345 // Resolve effective concurrency: route override > consumer default
346 let effective_concurrency = concurrency.unwrap_or(consumer_concurrency);
347
348 // Wire security context before spawning consumer. The
349 // `security_authenticator` marker stays in the guard as the
350 // route's security classification; the authenticator itself no
351 // longer rides the context (kernel plan + providers do). DSL
352 // compile sets the marker only alongside the policy path, so the
353 // marker term is redundant for DSL routes — it bites programmatic
354 // ones (marker without sp_config classifies non-Public but injects
355 // no context; strict dispatch fails closed downstream).
356 let managed = self
357 .routes
358 .get_mut(route_id)
359 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
360 deliver_security_context(consumer.as_mut(), &managed.compiled);
361
362 // Create channel for consumer to send exchanges
363 let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(256);
364 // Create child tokens for independent lifecycle control
365 let consumer_cancel = managed.consumer_cancel_token.child_token();
366 let pipeline_cancel = managed.pipeline_cancel_token.child_token();
367 let drain_in_flight = Arc::clone(&managed.drain_in_flight);
368 // Clone sender for storage (to reuse on resume)
369 let tx_for_storage = tx.clone();
370 let consumer_ctx = ConsumerContext::new(tx, consumer_cancel.clone(), route_id.to_string());
371
372 // direct-inline-dispatch Task 2.2: publish the inline dispatcher
373 // capability for every non-Concurrent topology. Sequential and the
374 // `#[non_exhaustive]` wildcard arm (the spawn match below) are
375 // Sequential-equivalent; Concurrent models keep the capability
376 // `None` (channel path). Published before the consumer spawns,
377 // i.e. before any `mark_ready`, per the set-once contract.
378 //
379 // rc-2sba publication guard: an aggregate-split route's
380 // `managed.pipeline` is an identity shell (`compose_pipeline(vec![])`
381 // — the real work lives in the split pre/agg/post pipelines driven
382 // by the aggregate engine) and must never be exposed to inline
383 // execution. The capability is skipped entirely, so producers take
384 // the existing capability-unavailable channel path.
385 if !matches!(effective_concurrency, ConcurrencyModel::Concurrent { .. })
386 && managed.aggregate_split.is_none()
387 {
388 let dispatcher = RouteInlineDispatcher::new(
389 route_id.to_string(),
390 Arc::clone(&pipeline),
391 pipeline_cancel.clone(),
392 Arc::clone(&drain_in_flight),
393 Arc::clone(&self.cohort),
394 );
395 consumer_ctx.set_inline_dispatcher(Arc::new(dispatcher));
396 }
397
398 // --- Aggregator v2: check for aggregate route with timeout ---
399 let split_clone = managed.aggregate_split.clone();
400 if let Some(split) = split_clone {
401 let result = self
402 .start_aggregate_route(
403 route_id,
404 split,
405 consumer,
406 consumer_ctx,
407 rx,
408 crash_notifier,
409 runtime_for_consumer,
410 tx_for_storage,
411 pipeline_cancel,
412 drain_in_flight,
413 )
414 .await;
415 // ADR-0022 SPI: roll back already-started handles if the aggregate
416 // spawn/startup path returns Err.
417 if result.is_err() {
418 // rc-kh7c: cancel consumer's cancel token to stop child tasks
419 // spawned by consumer.start() that observe ctx.cancelled().
420 if let Some(managed) = self.routes.get_mut(route_id) {
421 managed.consumer_cancel_token.cancel();
422 }
423 rollback_started(route_id, &lifecycle_handles).await;
424 }
425 return result;
426 }
427 // --- End aggregator v2 branch ---
428
429 // Clone for the startup-failure cleanup path (rc-kh7c): pipeline_cancel
430 // is moved into the spawn closure below; this clone stays in scope so
431 // the error handler can cancel it to force immediate pipeline exit.
432 let pipeline_cancel_for_cleanup = pipeline_cancel.clone();
433
434 // rc-e2r9: capture metrics for b′ emission at reply-drop sites.
435 let metrics_for_reply_drop = self.tracer_metrics.clone();
436
437 // rc-jxkj cohort gate: the drain loop parks each dequeued envelope
438 // until the startup cohort opens the gate. Subscribed once here; the
439 // spawned task owns the receiver (`wait_for` needs &mut), mirroring
440 // the pipeline_cancel capture.
441 let mut cohort_rx = self.cohort.subscribe();
442
443 // Spawn pipeline task with its own cancellation token
444 let pipeline_handle = match effective_concurrency {
445 ConcurrencyModel::Concurrent { max } => {
446 // Owned for the spawned 'static task (route_id is a borrow).
447 // Review minor 2: `Arc<str>` so the per-envelope dispatch
448 // tasks only bump a refcount — the String allocation happens
449 // once per pipeline task, not once per envelope.
450 let route_id: Arc<str> = Arc::from(route_id);
451 let sem = max.map(|n| Arc::new(tokio::sync::Semaphore::new(n)));
452 // rc-e2r9: metrics for b′ emission at reply-drop sites.
453 let metrics_for_reply_drop = metrics_for_reply_drop.clone();
454 tokio::spawn(async move {
455 loop {
456 // B2 (ADR-0044): acquire permit BEFORE dequeue.
457 // Cancel-aware: route stop is not blocked waiting for a permit.
458 let permit = match &sem {
459 Some(s) => {
460 let acquired = tokio::select! {
461 p = Arc::clone(s).acquire_owned() => p.expect("semaphore closed"), // allow-unwrap
462 _ = pipeline_cancel.cancelled() => return,
463 };
464 Some(acquired)
465 }
466 None => None,
467 };
468
469 let envelope = tokio::select! {
470 envelope = rx.recv() => match envelope {
471 Some(e) => e,
472 None => return,
473 },
474 _ = pipeline_cancel.cancelled() => return,
475 };
476 let ExchangeEnvelope {
477 exchange,
478 mut reply_tx,
479 } = envelope;
480 // rc-jxkj cohort gate: park dispatch until the startup
481 // cohort completes. Level-triggered — after the first
482 // open, later envelopes pass without parking.
483 // rc-z5qz: `biased` with the gate polled FIRST —
484 // with the cohort open and the pipeline token
485 // cancelled, an unbiased select picks randomly and
486 // may drop a deliverable envelope. Gate-open wins
487 // deterministically; a closed gate still drops.
488 tokio::select! {
489 biased;
490 _ = cohort_rx.wait_for(|open| *open) => {}
491 _ = pipeline_cancel.cancelled() => {
492 // Drop the envelope; reply_tx (if any)
493 // resolves to ChannelClosed for the
494 // send_and_wait waiter.
495 return;
496 }
497 }
498 // ADR-0061 Task 2.9 strict-mode dispatch check (the
499 // flip deferred from Task 2.2): every transport now
500 // mints the typed carrier at its request boundary
501 // (grpc 2.1, mcp 2.6, ws 2.8, http 2.9), so a
502 // non-Public plan REQUIRES the carrier on the
503 // Exchange — absent or wrong-provider is denied
504 // BEFORE the pipeline runs; the transport renders
505 // the denial in its own idiom via reply_tx.
506 if strict_dispatch_denies(
507 &dispatch_plan,
508 &exchange,
509 &mut reply_tx,
510 &metrics_for_reply_drop,
511 &route_id,
512 ) {
513 continue;
514 }
515 let pipe_ref = Arc::clone(&pipeline);
516 let cancel = pipeline_cancel.clone();
517 let drain_clone = Arc::clone(&drain_in_flight);
518 // rc-e2r9: capture for b′ emission at reply-drop.
519 let inner_metrics = metrics_for_reply_drop.clone();
520 let inner_route_id = Arc::clone(&route_id);
521 tokio::spawn(async move {
522 // Permit owned by this task — released on completion (RAII).
523 let _permit = permit;
524 let _drain_guard = DrainGuard::new(drain_clone);
525
526 // Load current pipeline from ArcSwap
527 let mut pipe = pipe_ref.load().processor.clone_inner();
528
529 // Wait for service ready with circuit breaker backoff
530 if let Err(e) = ready_with_backoff(&mut pipe, &cancel).await {
531 // rc-e2r9 review, Important 2: the real error is
532 // cloned by the helper BEFORE the send — the old
533 // code moved it into the send and reported
534 // ChannelClosed, which defeated ConsumerStopping
535 // suppression at this site.
536 send_reply_or_b_prime(
537 reply_tx,
538 Err(e),
539 &inner_metrics,
540 &inner_route_id,
541 "concurrent:ready",
542 );
543 return;
544 }
545
546 // B1: scope CANCEL_TOKEN so run_steps can check
547 // cancellation between steps.
548 let result = CANCEL_TOKEN
549 .scope(cancel, async move { pipe.call(exchange).await })
550 .await;
551 if let Some(tx) = reply_tx {
552 // Helper clones the error before the send, so a
553 // dropped receiver emits b′ with the REAL error.
554 send_reply_or_b_prime(
555 Some(tx),
556 result,
557 &inner_metrics,
558 &inner_route_id,
559 "concurrent:pipeline",
560 );
561 } else if let Err(ref e) = result {
562 // log-policy: system-broken
563 error!("Pipeline error: {e}");
564 }
565 });
566 }
567 })
568 }
569 // Forward-compat: an unknown future variant is treated as
570 // Sequential — the safe, simplest pipeline topology. A consumer
571 // that needs Concurrent semantics for a future variant must
572 // override the route's `?concurrent=` setting explicitly so the
573 // operator (not the wildcard) chooses the topology.
574 _ => {
575 // Owned for the spawned 'static task (route_id is a borrow).
576 let route_id = route_id.to_string();
577 // rc-e2r9: metrics for b′ emission at reply-drop sites.
578 let metrics_for_reply_drop = metrics_for_reply_drop.clone();
579 tokio::spawn(async move {
580 loop {
581 // Use select! to exit promptly on cancellation even when idle
582 let envelope = tokio::select! {
583 envelope = rx.recv() => match envelope {
584 Some(e) => e,
585 None => return, // Channel closed
586 },
587 _ = pipeline_cancel.cancelled() => {
588 // Cancellation requested - exit gracefully
589 return;
590 }
591 };
592 let ExchangeEnvelope {
593 exchange,
594 mut reply_tx,
595 } = envelope;
596 // rc-jxkj cohort gate: park dispatch until the startup
597 // cohort completes. Level-triggered — after the first
598 // open, later envelopes pass without parking.
599 // rc-z5qz: `biased` with the gate polled FIRST —
600 // with the cohort open and the pipeline token
601 // cancelled, an unbiased select picks randomly and
602 // may drop a deliverable envelope. Gate-open wins
603 // deterministically; a closed gate still drops.
604 tokio::select! {
605 biased;
606 _ = cohort_rx.wait_for(|open| *open) => {}
607 _ = pipeline_cancel.cancelled() => {
608 // Drop the envelope; reply_tx (if any)
609 // resolves to ChannelClosed for the
610 // send_and_wait waiter.
611 return;
612 }
613 }
614
615 // ADR-0061 Task 2.9 strict-mode dispatch check — see
616 // the Concurrent branch above for the full contract.
617 if strict_dispatch_denies(
618 &dispatch_plan,
619 &exchange,
620 &mut reply_tx,
621 &metrics_for_reply_drop,
622 &route_id,
623 ) {
624 continue;
625 }
626
627 // Load current pipeline from ArcSwap (picks up hot-reloaded pipelines)
628 let mut pipeline = pipeline.load().processor.clone_inner();
629
630 if let Err(e) = ready_with_backoff(&mut pipeline, &pipeline_cancel).await {
631 // rc-e2r9 review, Important 2: the real error is
632 // cloned by the helper BEFORE the send — the old
633 // code moved it into the send and reported
634 // ChannelClosed, which defeated ConsumerStopping
635 // suppression at this site.
636 send_reply_or_b_prime(
637 reply_tx,
638 Err(e),
639 &metrics_for_reply_drop,
640 &route_id,
641 "sequential:ready",
642 );
643 return;
644 }
645
646 // B1: scope CANCEL_TOKEN so run_steps can check cancellation
647 // between steps. Per-start task-local — child token expires
648 // when this pipeline task exits; the next start re-scopes a
649 // fresh one (avoids the lifecycle bug where a compiled-in
650 // child token stays cancelled after stop→restart).
651 let cancel = pipeline_cancel.clone();
652 let _drain_guard = DrainGuard::new(Arc::clone(&drain_in_flight));
653 let result = CANCEL_TOKEN
654 .scope(cancel, async move { pipeline.call(exchange).await })
655 .await;
656 if let Some(tx) = reply_tx {
657 // Helper clones the error before the send, so a
658 // dropped receiver emits b′ with the REAL error.
659 send_reply_or_b_prime(
660 Some(tx),
661 result,
662 &metrics_for_reply_drop,
663 &route_id,
664 "sequential:pipeline",
665 );
666 } else if let Err(ref e) = result {
667 // log-policy: system-broken
668 error!("Pipeline error: {e}");
669 }
670 }
671 })
672 }
673 };
674 #[cfg(test)]
675 emit_start_route_event("pipeline_spawned", route_id);
676
677 // Start consumer after pipeline task is spawned to minimize the chance of
678 // fire-and-forget events being produced before the pipeline loop is active.
679 let (consumer_handle, startup_rx, watcher_inputs, outer_inputs) =
680 consumer_management::spawn_consumer_task(
681 route_id.to_string(),
682 consumer,
683 consumer_ctx,
684 crash_notifier,
685 runtime_for_consumer,
686 false,
687 );
688 #[cfg(test)]
689 emit_start_route_event("consumer_spawned", route_id);
690
691 // rc-w1u9: await consumer startup handshake. For Explicit consumers
692 // (HTTP, WebSocket) it propagates bind failures as proper startup
693 // errors. For Immediate consumers the receiver is pre-resolved
694 // (StartupReceiver::immediate) so this returns instantly — the
695 // controller never yields during the Immediate handshake (rc-slvd).
696 let startup_result =
697 consumer_management::await_consumer_startup(startup_rx, "startup").await;
698 match startup_result {
699 Ok(()) => {}
700 Err(e) => {
701 // rc-kh7c: abort the orphaned consumer task and cancel the
702 // pipeline so neither runs detached after start_route returns
703 // Err. Dropping a JoinHandle detaches the task (Tokio
704 // contract); abort() forces termination. The pipeline task
705 // would eventually self-clean via rx-drop, but explicit
706 // cancellation makes it immediate.
707 consumer_handle.abort();
708 pipeline_cancel_for_cleanup.cancel();
709 // Cancel the consumer's cancel token so child tasks spawned
710 // by consumer.start() that observe ctx.cancelled() also stop.
711 consumer_cancel.cancel();
712 rollback_started(route_id, &lifecycle_handles).await;
713 return Err(e);
714 }
715 }
716
717 // Detached failure watcher for Immediate consumers (rc-slvd).
718 // The route owns the JoinHandle; the watcher owns the AbortHandle,
719 // oneshot, and command_id — ownership split prevents any coupling.
720 if let Some(inputs) = watcher_inputs {
721 consumer_management::spawn_failure_watcher(inputs);
722 }
723
724 // Detached outer-task watcher for Explicit consumers (rc-a7rh):
725 // spawned only after the handshake resolved Ok — rollback
726 // terminations (abort-then-cancel above) happen before this point
727 // and are never watched.
728 if let Some(outer) = outer_inputs {
729 consumer_management::spawn_outer_task_watcher(outer);
730 }
731
732 // Store handles and update status
733 let managed = self
734 .routes
735 .get_mut(route_id)
736 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
737 managed.consumer_handle = Some(consumer_handle);
738 managed.pipeline_handle = Some(pipeline_handle);
739 managed.channel_sender = Some(tx_for_storage);
740
741 info!(route_id = %route_id, "Route started");
742 self.health_registry().mark_route_started(route_id);
743 Ok(())
744 }
745
746 async fn stop_route(&mut self, route_id: &str) -> Result<(), CamelError> {
747 self.stop_route_internal(route_id).await?;
748 self.health_registry().mark_route_stopped(route_id);
749 Ok(())
750 }
751
752 async fn restart_route(&mut self, route_id: &str) -> Result<(), CamelError> {
753 self.stop_route(route_id).await?;
754 tokio::time::sleep(Duration::from_millis(100)).await;
755 self.start_route(route_id).await
756 }
757
758 async fn suspend_route(&mut self, route_id: &str) -> Result<(), CamelError> {
759 // Check route exists and state.
760 let managed = self
761 .routes
762 .get_mut(route_id)
763 .ok_or_else(|| CamelError::RouteError(format!("Route '{}' not found", route_id)))?;
764
765 let consumer_running = handle_is_running(&managed.consumer_handle);
766 let pipeline_running = handle_is_running(&managed.pipeline_handle);
767
768 // Can only suspend from active started state.
769 if !consumer_running || !pipeline_running {
770 return Err(CamelError::RouteError(format!(
771 "Cannot suspend route '{}' with execution lifecycle {}",
772 route_id,
773 inferred_lifecycle_label(managed)
774 )));
775 }
776
777 info!(route_id = %route_id, "Suspending route (consumer only, keeping pipeline)");
778
779 // Cancel consumer token only (keep pipeline running)
780 let managed = self
781 .routes
782 .get_mut(route_id)
783 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
784 managed.consumer_cancel_token.cancel();
785
786 // Take and join consumer handle
787 let managed = self
788 .routes
789 .get_mut(route_id)
790 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
791 let consumer_handle = managed.consumer_handle.take();
792
793 // Wait for consumer task to complete with timeout
794 let timeout_result = tokio::time::timeout(DEFAULT_SHUTDOWN_TIMEOUT, async {
795 if let Some(handle) = consumer_handle {
796 let _ = handle.await;
797 }
798 })
799 .await;
800
801 if timeout_result.is_err() {
802 warn!(route_id = %route_id, "Consumer shutdown timed out during suspend");
803 }
804
805 // Get the managed route again (can't hold across await)
806 let managed = self
807 .routes
808 .get_mut(route_id)
809 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
810
811 // Create fresh cancellation token for consumer (for resume)
812 managed.consumer_cancel_token = CancellationToken::new();
813
814 info!(route_id = %route_id, "Route suspended (pipeline still running)");
815 self.health_registry().mark_route_stopped(route_id);
816 Ok(())
817 }
818
819 async fn resume_route(&mut self, route_id: &str) -> Result<(), CamelError> {
820 // Check route exists and is Suspended-equivalent execution state.
821 let managed = self
822 .routes
823 .get(route_id)
824 .ok_or_else(|| CamelError::RouteError(format!("Route '{}' not found", route_id)))?;
825
826 let consumer_running = handle_is_running(&managed.consumer_handle);
827 let pipeline_running = handle_is_running(&managed.pipeline_handle);
828 if consumer_running || !pipeline_running {
829 return Err(CamelError::RouteError(format!(
830 "Cannot resume route '{}' with execution lifecycle {} (expected Suspended)",
831 route_id,
832 inferred_lifecycle_label(managed)
833 )));
834 }
835
836 // Get the stored channel sender (must exist for a suspended route)
837 let sender = managed.channel_sender.clone().ok_or_else(|| {
838 CamelError::RouteError("Suspended route has no channel sender".into())
839 })?;
840
841 // Get from_uri and the concurrency override for creating the new
842 // consumer (the override feeds the inline-dispatcher gate below,
843 // mirroring the start path's effective-model resolution).
844 let from_uri = managed.from_uri.clone();
845 let concurrency_override = managed.concurrency.clone();
846
847 // ADR-0061 per-bind exposure gate on resume too (see start path).
848 if let Some(bind) = bind_key_from_uri(&from_uri) {
849 let owned = self.plans_for_bind(&bind.key);
850 let siblings: Vec<(&str, &RouteSecurityPlan)> =
851 owned.iter().map(|(id, plan)| (id.as_str(), plan)).collect();
852 enforce_bind_exposure_gate(
853 &bind.key,
854 bind.loopback,
855 &siblings,
856 self.bind_acks.acknowledged(&bind.key),
857 )?;
858 }
859
860 info!(route_id = %route_id, "Resuming route (spawning consumer only)");
861
862 let consumer_component_ctx = Arc::new(ControllerComponentContext::new(
863 Arc::clone(&self.registry),
864 Arc::clone(&self.languages),
865 self.tracer_metrics
866 .clone()
867 .unwrap_or_else(|| Arc::new(NoOpMetrics)),
868 Arc::clone(&self.platform_service),
869 self.health_registry(),
870 Some(route_id.to_string()),
871 self.tracer_gating.levers.components_enabled(),
872 ));
873 let consumer_rt: Arc<dyn camel_component_api::RuntimeObservability> =
874 Arc::clone(&consumer_component_ctx) as Arc<_>;
875 let (mut consumer, consumer_concurrency) = consumer_management::create_route_consumer(
876 consumer_rt,
877 &self.registry,
878 &from_uri,
879 consumer_component_ctx.as_ref(),
880 )?;
881
882 // Wire security context before spawning consumer (authenticator
883 // marker guard: see start path above).
884 let managed = self
885 .routes
886 .get(route_id)
887 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
888 deliver_security_context(consumer.as_mut(), &managed.compiled);
889
890 // Get the managed route for mutation
891 let managed = self
892 .routes
893 .get_mut(route_id)
894 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
895
896 // Create child token for consumer lifecycle
897 let consumer_cancel = managed.consumer_cancel_token.child_token();
898
899 let crash_notifier = self.crash_notifier.clone();
900 let runtime_for_consumer = self.runtime.clone();
901
902 // Create ConsumerContext with the stored sender
903 let consumer_ctx =
904 ConsumerContext::new(sender, consumer_cancel.clone(), route_id.to_string());
905
906 // direct-inline-dispatch Task 3.3 (bd rc-y4vk): mirror the
907 // start_route publication on the resume path. Without this the
908 // fresh resume ConsumerContext carries no capability and the
909 // resumed consumer's registry entry silently falls back to the
910 // channel path. Same gate as start (non-Concurrent only, wildcard
911 // = Sequential-equivalent), same handle captures (pipeline swap
912 // source, pipeline_cancel child scope, shared drain counter), and
913 // published before the resumed consumer spawns — a fresh ctx means
914 // a fresh OnceLock, so the set-once keep-first contract cannot
915 // interfere with the pre-suspend publication.
916 //
917 // rc-2sba publication guard (mirrors start): an aggregate-split
918 // route's `managed.pipeline` is an identity shell
919 // (`compose_pipeline(vec![])`) and must never be exposed to inline
920 // execution — the split pre/agg/post pipelines stay driven by the
921 // aggregate engine over the channel path, so no capability is
922 // published here either.
923 if !matches!(
924 concurrency_override.unwrap_or(consumer_concurrency),
925 ConcurrencyModel::Concurrent { .. }
926 ) && managed.aggregate_split.is_none()
927 {
928 let (pipeline, pipeline_cancel, drain_in_flight) = {
929 let managed = self
930 .routes
931 .get(route_id)
932 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
933 (
934 Arc::clone(&managed.pipeline),
935 managed.pipeline_cancel_token.child_token(),
936 Arc::clone(&managed.drain_in_flight),
937 )
938 };
939 let dispatcher = RouteInlineDispatcher::new(
940 route_id.to_string(),
941 pipeline,
942 pipeline_cancel,
943 drain_in_flight,
944 Arc::clone(&self.cohort),
945 );
946 consumer_ctx.set_inline_dispatcher(Arc::new(dispatcher));
947 }
948
949 // Spawn consumer task
950 let (consumer_handle, startup_rx, watcher_inputs, outer_inputs) =
951 consumer_management::spawn_consumer_task(
952 route_id.to_string(),
953 consumer,
954 consumer_ctx,
955 crash_notifier,
956 runtime_for_consumer,
957 true,
958 );
959
960 // rc-w1u9: await consumer startup handshake on resume too — bind
961 // failures during resume must surface as resume errors.
962 // For Immediate consumers the receiver is pre-resolved (rc-slvd).
963 let resume_result = consumer_management::await_consumer_startup(startup_rx, "resume").await;
964 if let Err(e) = resume_result {
965 // rc-kh7c cleanup parity with the start path: the consumer task
966 // must not run detached after a failed resume, and child tasks
967 // spawned by consumer.start() that observe ctx.cancelled() must
968 // stop too.
969 consumer_handle.abort();
970 consumer_cancel.cancel();
971 return Err(e);
972 }
973
974 // Detached failure watcher for Immediate consumers (rc-slvd).
975 if let Some(inputs) = watcher_inputs {
976 consumer_management::spawn_failure_watcher(inputs);
977 }
978
979 // Detached outer-task watcher for Explicit consumers (rc-a7rh):
980 // spawned only after the resume handshake resolved Ok — rollback
981 // terminations (abort-then-cancel above) happen before this point
982 // and are never watched.
983 if let Some(outer) = outer_inputs {
984 consumer_management::spawn_outer_task_watcher(outer);
985 }
986
987 // Store consumer handle and update status
988 let managed = self
989 .routes
990 .get_mut(route_id)
991 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
992 managed.consumer_handle = Some(consumer_handle);
993
994 info!(route_id = %route_id, "Route resumed");
995 self.health_registry().mark_route_started(route_id);
996 Ok(())
997 }
998
999 async fn start_all_routes(&mut self) -> Result<(), CamelError> {
1000 // Only start routes where auto_startup() == true
1001 // Sort by startup_order() ascending before starting
1002 let route_ids: Vec<String> = {
1003 let pairs = self.routes.auto_startup_sorted();
1004 pairs.into_iter().map(|(id, _)| id).collect()
1005 };
1006
1007 info!("Starting {} auto-startup routes", route_ids.len());
1008
1009 // Collect errors but continue starting remaining routes
1010 let mut errors: Vec<String> = Vec::new();
1011 for route_id in route_ids {
1012 if let Err(e) = self.start_route(&route_id).await {
1013 errors.push(format!("Route '{}': {}", route_id, e));
1014 }
1015 }
1016
1017 if !errors.is_empty() {
1018 return Err(CamelError::RouteError(format!(
1019 "Failed to start routes: {}",
1020 errors.join(", ")
1021 )));
1022 }
1023
1024 info!("All auto-startup routes started");
1025 Ok(())
1026 }
1027
1028 async fn stop_all_routes(&mut self) -> Result<(), CamelError> {
1029 // Sort by startup_order descending (reverse order)
1030 let route_ids: Vec<String> = {
1031 let pairs = self.routes.shutdown_sorted();
1032 pairs.into_iter().map(|(id, _)| id).collect()
1033 };
1034
1035 info!("Stopping {} routes", route_ids.len());
1036
1037 for route_id in route_ids {
1038 let _ = self.stop_route(&route_id).await;
1039 }
1040
1041 info!("All routes stopped");
1042 Ok(())
1043 }
1044}
1045
1046// ── rc-e2r9: b′ signal emission on reply-drop ──
1047// The shared `send_reply_or_b_prime` helper lives in
1048// `super::route_helpers` (single copy — the duplicated private helpers in
1049// this file and `route_controller.rs` drifted once already; see rc-e2r9
1050// review, Important 3).
1051
1052#[cfg(test)]
1053#[path = "route_controller_trait_tests.rs"]
1054mod bind_exposure_gate;