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