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, InFlightClaim, 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(
317 ControllerComponentContext::new(
318 Arc::clone(&self.registry),
319 Arc::clone(&self.languages),
320 self.tracer_metrics
321 .clone()
322 .unwrap_or_else(|| Arc::new(NoOpMetrics)),
323 Arc::clone(&self.platform_service),
324 self.health_registry(),
325 Some(route_id.to_string()),
326 self.tracer_gating.levers.component_metrics_levers(),
327 )
328 .with_in_flight(Arc::clone(&self.in_flight_total)),
329 );
330 let consumer_rt: Arc<dyn camel_component_api::RuntimeObservability> =
331 Arc::clone(&consumer_component_ctx) as Arc<_>;
332 let (mut consumer, consumer_concurrency) = match consumer_management::create_route_consumer(
333 consumer_rt,
334 &self.registry,
335 &from_uri,
336 consumer_component_ctx.as_ref(),
337 ) {
338 Ok(v) => v,
339 // ADR-0022 SPI: every started handle must be rolled back
340 // before start_route returns Err, so no stateful step is left
341 // running. This is the first post-start fallible step.
342 Err(e) => {
343 rollback_started(route_id, &lifecycle_handles).await;
344 return Err(e);
345 }
346 };
347
348 // Resolve effective concurrency: route override > consumer default
349 let effective_concurrency = concurrency.unwrap_or(consumer_concurrency);
350
351 // Wire security context before spawning consumer. The
352 // `security_authenticator` marker stays in the guard as the
353 // route's security classification; the authenticator itself no
354 // longer rides the context (kernel plan + providers do). DSL
355 // compile sets the marker only alongside the policy path, so the
356 // marker term is redundant for DSL routes — it bites programmatic
357 // ones (marker without sp_config classifies non-Public but injects
358 // no context; strict dispatch fails closed downstream).
359 let managed = self
360 .routes
361 .get_mut(route_id)
362 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
363 deliver_security_context(consumer.as_mut(), &managed.compiled);
364
365 // Create channel for consumer to send exchanges
366 let (tx, mut rx) = mpsc::channel::<ExchangeEnvelope>(256);
367 // Create child tokens for independent lifecycle control
368 let consumer_cancel = managed.consumer_cancel_token.child_token();
369 let pipeline_cancel = managed.pipeline_cancel_token.child_token();
370 let drain_in_flight = Arc::clone(&managed.drain_in_flight);
371 // Clone sender for storage (to reuse on resume)
372 let tx_for_storage = tx.clone();
373 // drainclaim: the consumer context mints one claim per envelope
374 // sent through `send`/`send_and_wait` — counted from acceptance.
375 // Business-error-model Task 2.2: the route's mapping snapshot is
376 // installed on the same registration seam so the consumer's reply
377 // finalizer maps business errors per route.
378 let http_error_mapping = managed.compiled.http_error_mapping.clone();
379 let consumer_ctx = ConsumerContext::new(tx, consumer_cancel.clone(), route_id.to_string())
380 .with_in_flight_counter(Arc::clone(&self.in_flight_total))
381 .with_http_error_mapping(http_error_mapping);
382
383 // direct-inline-dispatch Task 2.2: publish the inline dispatcher
384 // capability for every non-Concurrent topology. Sequential and the
385 // `#[non_exhaustive]` wildcard arm (the spawn match below) are
386 // Sequential-equivalent; Concurrent models keep the capability
387 // `None` (channel path). Published before the consumer spawns,
388 // i.e. before any `mark_ready`, per the set-once contract.
389 //
390 // rc-2sba publication guard: an aggregate-split route's
391 // `managed.pipeline` is an identity shell (`compose_pipeline(vec![])`
392 // — the real work lives in the split pre/agg/post pipelines driven
393 // by the aggregate engine) and must never be exposed to inline
394 // execution. The capability is skipped entirely, so producers take
395 // the existing capability-unavailable channel path.
396 if !matches!(effective_concurrency, ConcurrencyModel::Concurrent { .. })
397 && managed.aggregate_split.is_none()
398 {
399 let dispatcher = RouteInlineDispatcher::new(
400 route_id.to_string(),
401 Arc::clone(&pipeline),
402 pipeline_cancel.clone(),
403 Arc::clone(&drain_in_flight),
404 Arc::clone(&self.cohort),
405 Some(Arc::clone(&self.in_flight_total)),
406 );
407 consumer_ctx.set_inline_dispatcher(Arc::new(dispatcher));
408 }
409
410 // --- Aggregator v2: check for aggregate route with timeout ---
411 let split_clone = managed.aggregate_split.clone();
412 if let Some(split) = split_clone {
413 let result = self
414 .start_aggregate_route(
415 route_id,
416 split,
417 consumer,
418 consumer_ctx,
419 rx,
420 crash_notifier,
421 runtime_for_consumer,
422 tx_for_storage,
423 pipeline_cancel,
424 drain_in_flight,
425 )
426 .await;
427 // ADR-0022 SPI: roll back already-started handles if the aggregate
428 // spawn/startup path returns Err.
429 if result.is_err() {
430 // rc-kh7c: cancel consumer's cancel token to stop child tasks
431 // spawned by consumer.start() that observe ctx.cancelled().
432 if let Some(managed) = self.routes.get_mut(route_id) {
433 managed.consumer_cancel_token.cancel();
434 }
435 rollback_started(route_id, &lifecycle_handles).await;
436 }
437 return result;
438 }
439 // --- End aggregator v2 branch ---
440
441 // Clone for the startup-failure cleanup path (rc-kh7c): pipeline_cancel
442 // is moved into the spawn closure below; this clone stays in scope so
443 // the error handler can cancel it to force immediate pipeline exit.
444 let pipeline_cancel_for_cleanup = pipeline_cancel.clone();
445
446 // rc-e2r9: capture metrics for b′ emission at reply-drop sites.
447 let metrics_for_reply_drop = self.tracer_metrics.clone();
448
449 // rc-jxkj cohort gate: the drain loop parks each dequeued envelope
450 // until the startup cohort opens the gate. Subscribed once here; the
451 // spawned task owns the receiver (`wait_for` needs &mut), mirroring
452 // the pipeline_cancel capture.
453 let mut cohort_rx = self.cohort.subscribe();
454
455 // Spawn pipeline task with its own cancellation token
456 let pipeline_handle = match effective_concurrency {
457 ConcurrencyModel::Concurrent { max } => {
458 // Owned for the spawned 'static task (route_id is a borrow).
459 // Review minor 2: `Arc<str>` so the per-envelope dispatch
460 // tasks only bump a refcount — the String allocation happens
461 // once per pipeline task, not once per envelope.
462 let route_id: Arc<str> = Arc::from(route_id);
463 let sem = max.map(|n| Arc::new(tokio::sync::Semaphore::new(n)));
464 // rc-e2r9: metrics for b′ emission at reply-drop sites.
465 let metrics_for_reply_drop = metrics_for_reply_drop.clone();
466 tokio::spawn(async move {
467 loop {
468 // B2 (ADR-0044): acquire permit BEFORE dequeue.
469 // Cancel-aware: route stop is not blocked waiting for a permit.
470 let permit = match &sem {
471 Some(s) => {
472 let acquired = tokio::select! {
473 p = Arc::clone(s).acquire_owned() => p.expect("semaphore closed"), // allow-unwrap
474 _ = pipeline_cancel.cancelled() => return,
475 };
476 Some(acquired)
477 }
478 None => None,
479 };
480
481 let envelope = tokio::select! {
482 envelope = rx.recv() => match envelope {
483 Some(e) => e,
484 None => return,
485 },
486 _ = pipeline_cancel.cancelled() => return,
487 };
488 let ExchangeEnvelope {
489 exchange,
490 mut reply_tx,
491 in_flight_claim,
492 } = envelope;
493 // drainclaim: `in_flight_claim` is moved into the
494 // per-envelope task below and held across the
495 // pipeline future; any earlier exit of THIS scope
496 // (denied dispatch, cohort-gate cancel) drops it —
497 // drop = release.
498 // rc-jxkj cohort gate: park dispatch until the startup
499 // cohort completes. Level-triggered — after the first
500 // open, later envelopes pass without parking.
501 // rc-z5qz: `biased` with the gate polled FIRST —
502 // with the cohort open and the pipeline token
503 // cancelled, an unbiased select picks randomly and
504 // may drop a deliverable envelope. Gate-open wins
505 // deterministically; a closed gate still drops.
506 tokio::select! {
507 biased;
508 _ = cohort_rx.wait_for(|open| *open) => {}
509 _ = pipeline_cancel.cancelled() => {
510 // Drop the envelope; reply_tx (if any)
511 // resolves to ChannelClosed for the
512 // send_and_wait waiter.
513 return;
514 }
515 }
516 // ADR-0061 Task 2.9 strict-mode dispatch check (the
517 // flip deferred from Task 2.2): every transport now
518 // mints the typed carrier at its request boundary
519 // (grpc 2.1, mcp 2.6, ws 2.8, http 2.9), so a
520 // non-Public plan REQUIRES the carrier on the
521 // Exchange — absent or wrong-provider is denied
522 // BEFORE the pipeline runs; the transport renders
523 // the denial in its own idiom via reply_tx.
524 if strict_dispatch_denies(
525 &dispatch_plan,
526 &exchange,
527 &mut reply_tx,
528 &metrics_for_reply_drop,
529 &route_id,
530 ) {
531 continue;
532 }
533 let pipe_ref = Arc::clone(&pipeline);
534 let cancel = pipeline_cancel.clone();
535 let drain_clone = Arc::clone(&drain_in_flight);
536 // rc-e2r9: capture for b′ emission at reply-drop.
537 let inner_metrics = metrics_for_reply_drop.clone();
538 let inner_route_id = Arc::clone(&route_id);
539 tokio::spawn(async move {
540 // Permit owned by this task — released on completion (RAII).
541 let _permit = permit;
542 let _drain_guard = DrainGuard::new(drain_clone);
543 // drainclaim: the claim lives as long as this
544 // task — completion, abort, panic, or the
545 // readiness early-return below all drop it.
546 let _in_flight_claim = in_flight_claim;
547 // claimfamily (rc-hllkk): split a sibling claim
548 // onto the exchange so residency inside
549 // pipeline-embedded stash sites (resequencer
550 // buffers, aggregator buckets) stays counted
551 // after this task completes. The sibling is
552 // taken back from an in-band Ok result below —
553 // exchanges that complete inside the pipeline
554 // release at task end (drainclaim semantics);
555 // stash emissions escape with theirs.
556 let mut exchange = exchange;
557 exchange.in_flight_claim =
558 _in_flight_claim.as_ref().map(InFlightClaim::split);
559
560 // Load current pipeline from ArcSwap
561 let mut pipe = pipe_ref.load().processor.clone_inner();
562
563 // Wait for service ready with circuit breaker backoff
564 if let Err(e) = ready_with_backoff(&mut pipe, &cancel).await {
565 // rc-e2r9 review, Important 2: the real error is
566 // cloned by the helper BEFORE the send — the old
567 // code moved it into the send and reported
568 // ChannelClosed, which defeated ConsumerStopping
569 // suppression at this site.
570 send_reply_or_b_prime(
571 reply_tx,
572 Err(e),
573 &inner_metrics,
574 &inner_route_id,
575 "concurrent:ready",
576 );
577 return;
578 }
579
580 // B1: scope CANCEL_TOKEN so run_steps can check
581 // cancellation between steps.
582 let mut result = CANCEL_TOKEN
583 .scope(cancel, async move { pipe.call(exchange).await })
584 .await;
585 // claimfamily: reclaim the sibling from an
586 // in-band result (input completed inside this
587 // pipeline) so release stays at task end. A
588 // stash emission already escaped with its claim;
589 // a transformed result carries None (its input's
590 // sibling dropped on consume).
591 if let Ok(ref mut ex) = result {
592 ex.in_flight_claim = None;
593 }
594 if let Some(tx) = reply_tx {
595 // Helper clones the error before the send, so a
596 // dropped receiver emits b′ with the REAL error.
597 send_reply_or_b_prime(
598 Some(tx),
599 result,
600 &inner_metrics,
601 &inner_route_id,
602 "concurrent:pipeline",
603 );
604 } else if let Err(ref e) = result {
605 // log-policy: system-broken
606 error!("Pipeline error: {e}");
607 }
608 });
609 }
610 })
611 }
612 // Forward-compat: an unknown future variant is treated as
613 // Sequential — the safe, simplest pipeline topology. A consumer
614 // that needs Concurrent semantics for a future variant must
615 // override the route's `?concurrent=` setting explicitly so the
616 // operator (not the wildcard) chooses the topology.
617 _ => {
618 // Owned for the spawned 'static task (route_id is a borrow).
619 let route_id = route_id.to_string();
620 // rc-e2r9: metrics for b′ emission at reply-drop sites.
621 let metrics_for_reply_drop = metrics_for_reply_drop.clone();
622 tokio::spawn(async move {
623 // Read once per consumer task: no per-exchange env lookup (seam is test-only).
624 let pipeline_marker = std::env::var_os("CAMEL_JOB_PIPELINE_MARKER").is_some();
625 loop {
626 // Use select! to exit promptly on cancellation even when idle
627 let envelope = tokio::select! {
628 envelope = rx.recv() => match envelope {
629 Some(e) => e,
630 None => return, // Channel closed
631 },
632 _ = pipeline_cancel.cancelled() => {
633 // Cancellation requested - exit gracefully
634 return;
635 }
636 };
637 let ExchangeEnvelope {
638 exchange,
639 mut reply_tx,
640 in_flight_claim,
641 } = envelope;
642 // drainclaim: hold the claim for the whole iteration
643 // — the readiness early-return below and every
644 // `continue`/`return` exit drop it via scope exit.
645 let _in_flight_claim = in_flight_claim;
646 // rc-jxkj cohort gate: park dispatch until the startup
647 // cohort completes. Level-triggered — after the first
648 // open, later envelopes pass without parking.
649 // rc-z5qz: `biased` with the gate polled FIRST —
650 // with the cohort open and the pipeline token
651 // cancelled, an unbiased select picks randomly and
652 // may drop a deliverable envelope. Gate-open wins
653 // deterministically; a closed gate still drops.
654 tokio::select! {
655 biased;
656 _ = cohort_rx.wait_for(|open| *open) => {}
657 _ = pipeline_cancel.cancelled() => {
658 // Drop the envelope; reply_tx (if any)
659 // resolves to ChannelClosed for the
660 // send_and_wait waiter.
661 return;
662 }
663 }
664
665 // ADR-0061 Task 2.9 strict-mode dispatch check — see
666 // the Concurrent branch above for the full contract.
667 if strict_dispatch_denies(
668 &dispatch_plan,
669 &exchange,
670 &mut reply_tx,
671 &metrics_for_reply_drop,
672 &route_id,
673 ) {
674 continue;
675 }
676
677 // Load current pipeline from ArcSwap (picks up hot-reloaded pipelines)
678 let mut pipeline = pipeline.load().processor.clone_inner();
679
680 if let Err(e) = ready_with_backoff(&mut pipeline, &pipeline_cancel).await {
681 // rc-e2r9 review, Important 2: the real error is
682 // cloned by the helper BEFORE the send — the old
683 // code moved it into the send and reported
684 // ChannelClosed, which defeated ConsumerStopping
685 // suppression at this site.
686 send_reply_or_b_prime(
687 reply_tx,
688 Err(e),
689 &metrics_for_reply_drop,
690 &route_id,
691 "sequential:ready",
692 );
693 return;
694 }
695
696 // B1: scope CANCEL_TOKEN so run_steps can check cancellation
697 // between steps. Per-start task-local — child token expires
698 // when this pipeline task exits; the next start re-scopes a
699 // fresh one (avoids the lifecycle bug where a compiled-in
700 // child token stays cancelled after stop→restart).
701 let cancel = pipeline_cancel.clone();
702 let _drain_guard = DrainGuard::new(Arc::clone(&drain_in_flight));
703 // claimfamily (rc-hllkk): split a sibling claim onto
704 // the exchange so residency inside pipeline-embedded
705 // stash sites (resequencer buffers, aggregator
706 // buckets) stays counted after this iteration
707 // completes. Taken back from an in-band Ok result
708 // below — exchanges that complete inside the
709 // pipeline release at iteration end (drainclaim
710 // semantics); stash emissions escape with theirs.
711 let mut exchange = exchange;
712 exchange.in_flight_claim =
713 _in_flight_claim.as_ref().map(InFlightClaim::split);
714 // Test seam (default off, mirrors `CAMEL_JOB_SIGNAL_MARKER` /
715 // `CAMEL_JOB_SHUTDOWN_MARKER`): proves route pipeline entry with the
716 // drain claim held, so job-signal tests can synchronize INT on an
717 // observed teardown-holding exchange instead of a timing guess.
718 if pipeline_marker {
719 eprintln!("camel job: pipeline entered");
720 }
721 let mut result = CANCEL_TOKEN
722 .scope(cancel, async move { pipeline.call(exchange).await })
723 .await;
724 // claimfamily: reclaim the sibling from an in-band
725 // result (input completed inside this pipeline) so
726 // release stays at iteration end. A stash emission
727 // already escaped with its claim; a transformed
728 // result carries None (its input's sibling dropped
729 // on consume).
730 if let Ok(ref mut ex) = result {
731 ex.in_flight_claim = None;
732 }
733 if let Some(tx) = reply_tx {
734 // Helper clones the error before the send, so a
735 // dropped receiver emits b′ with the REAL error.
736 send_reply_or_b_prime(
737 Some(tx),
738 result,
739 &metrics_for_reply_drop,
740 &route_id,
741 "sequential:pipeline",
742 );
743 } else if let Err(ref e) = result {
744 // log-policy: system-broken
745 error!("Pipeline error: {e}");
746 }
747 }
748 })
749 }
750 };
751 #[cfg(test)]
752 emit_start_route_event("pipeline_spawned", route_id);
753
754 // Start consumer after pipeline task is spawned to minimize the chance of
755 // fire-and-forget events being produced before the pipeline loop is active.
756 let (consumer_handle, startup_rx, watcher_inputs, outer_inputs, stop_budget_tx) =
757 consumer_management::spawn_consumer_task(
758 route_id.to_string(),
759 consumer,
760 consumer_ctx,
761 crash_notifier,
762 runtime_for_consumer,
763 false,
764 );
765 #[cfg(test)]
766 emit_start_route_event("consumer_spawned", route_id);
767
768 // rc-w1u9: await consumer startup handshake. For Explicit consumers
769 // (HTTP, WebSocket) it propagates bind failures as proper startup
770 // errors. For Immediate consumers the receiver is pre-resolved
771 // (StartupReceiver::immediate) so this returns instantly — the
772 // controller never yields during the Immediate handshake (rc-slvd).
773 let startup_result =
774 consumer_management::await_consumer_startup(startup_rx, "startup").await;
775 match startup_result {
776 Ok(()) => {}
777 Err(e) => {
778 // rc-kh7c: abort the orphaned consumer task and cancel the
779 // pipeline so neither runs detached after start_route returns
780 // Err. Dropping a JoinHandle detaches the task (Tokio
781 // contract); abort() forces termination. The pipeline task
782 // would eventually self-clean via rx-drop, but explicit
783 // cancellation makes it immediate.
784 consumer_handle.abort();
785 pipeline_cancel_for_cleanup.cancel();
786 // Cancel the consumer's cancel token so child tasks spawned
787 // by consumer.start() that observe ctx.cancelled() also stop.
788 consumer_cancel.cancel();
789 rollback_started(route_id, &lifecycle_handles).await;
790 return Err(e);
791 }
792 }
793
794 // Detached failure watcher for Immediate consumers (rc-slvd).
795 // The route owns the JoinHandle; the watcher owns the AbortHandle,
796 // oneshot, and command_id — ownership split prevents any coupling.
797 if let Some(inputs) = watcher_inputs {
798 consumer_management::spawn_failure_watcher(inputs);
799 }
800
801 // Detached outer-task watcher for Explicit consumers (rc-a7rh):
802 // spawned only after the handshake resolved Ok — rollback
803 // terminations (abort-then-cancel above) happen before this point
804 // and are never watched.
805 if let Some(outer) = outer_inputs {
806 consumer_management::spawn_outer_task_watcher(outer);
807 }
808
809 // Store handles and update status
810 let managed = self
811 .routes
812 .get_mut(route_id)
813 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
814 managed.consumer_handle = Some(consumer_handle);
815 managed.pipeline_handle = Some(pipeline_handle);
816 managed.channel_sender = Some(tx_for_storage);
817 managed.stop_budget = Some(stop_budget_tx);
818
819 info!(route_id = %route_id, "Route started");
820 self.health_registry().mark_route_started(route_id);
821 Ok(())
822 }
823
824 async fn stop_route(&mut self, route_id: &str) -> Result<(), CamelError> {
825 self.stop_route_internal(route_id).await?;
826 self.health_registry().mark_route_stopped(route_id);
827 Ok(())
828 }
829
830 async fn stop_route_with_budget(
831 &mut self,
832 route_id: &str,
833 budget: std::time::Duration,
834 ) -> Result<(), CamelError> {
835 self.stop_route_with_budget_internal(route_id, budget)
836 .await?;
837 self.health_registry().mark_route_stopped(route_id);
838 Ok(())
839 }
840
841 async fn restart_route(&mut self, route_id: &str) -> Result<(), CamelError> {
842 self.stop_route(route_id).await?;
843 tokio::time::sleep(Duration::from_millis(100)).await;
844 self.start_route(route_id).await
845 }
846
847 async fn suspend_route(&mut self, route_id: &str) -> Result<(), CamelError> {
848 // Check route exists and state.
849 let managed = self
850 .routes
851 .get_mut(route_id)
852 .ok_or_else(|| CamelError::RouteError(format!("Route '{}' not found", route_id)))?;
853
854 let consumer_running = handle_is_running(&managed.consumer_handle);
855 let pipeline_running = handle_is_running(&managed.pipeline_handle);
856
857 // Can only suspend from active started state.
858 if !consumer_running || !pipeline_running {
859 return Err(CamelError::RouteError(format!(
860 "Cannot suspend route '{}' with execution lifecycle {}",
861 route_id,
862 inferred_lifecycle_label(managed)
863 )));
864 }
865
866 info!(route_id = %route_id, "Suspending route (consumer only, keeping pipeline)");
867
868 // Cancel consumer token only (keep pipeline running)
869 let managed = self
870 .routes
871 .get_mut(route_id)
872 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
873 managed.consumer_cancel_token.cancel();
874
875 // Take and join consumer handle
876 let managed = self
877 .routes
878 .get_mut(route_id)
879 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
880 let consumer_handle = managed.consumer_handle.take();
881
882 // Wait for consumer task to complete with timeout
883 let timeout_result = tokio::time::timeout(DEFAULT_SHUTDOWN_TIMEOUT, async {
884 if let Some(handle) = consumer_handle {
885 let _ = handle.await;
886 }
887 })
888 .await;
889
890 if timeout_result.is_err() {
891 warn!(route_id = %route_id, "Consumer shutdown timed out during suspend");
892 }
893
894 // Get the managed route again (can't hold across await)
895 let managed = self
896 .routes
897 .get_mut(route_id)
898 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
899
900 // Create fresh cancellation token for consumer (for resume)
901 managed.consumer_cancel_token = CancellationToken::new();
902
903 info!(route_id = %route_id, "Route suspended (pipeline still running)");
904 self.health_registry().mark_route_stopped(route_id);
905 Ok(())
906 }
907
908 async fn resume_route(&mut self, route_id: &str) -> Result<(), CamelError> {
909 // Check route exists and is Suspended-equivalent execution state.
910 let managed = self
911 .routes
912 .get(route_id)
913 .ok_or_else(|| CamelError::RouteError(format!("Route '{}' not found", route_id)))?;
914
915 let consumer_running = handle_is_running(&managed.consumer_handle);
916 let pipeline_running = handle_is_running(&managed.pipeline_handle);
917 if consumer_running || !pipeline_running {
918 return Err(CamelError::RouteError(format!(
919 "Cannot resume route '{}' with execution lifecycle {} (expected Suspended)",
920 route_id,
921 inferred_lifecycle_label(managed)
922 )));
923 }
924
925 // Get the stored channel sender (must exist for a suspended route)
926 let sender = managed.channel_sender.clone().ok_or_else(|| {
927 CamelError::RouteError("Suspended route has no channel sender".into())
928 })?;
929
930 // Get from_uri and the concurrency override for creating the new
931 // consumer (the override feeds the inline-dispatcher gate below,
932 // mirroring the start path's effective-model resolution).
933 let from_uri = managed.from_uri.clone();
934 let concurrency_override = managed.concurrency.clone();
935
936 // ADR-0061 per-bind exposure gate on resume too (see start path).
937 if let Some(bind) = bind_key_from_uri(&from_uri) {
938 let owned = self.plans_for_bind(&bind.key);
939 let siblings: Vec<(&str, &RouteSecurityPlan)> =
940 owned.iter().map(|(id, plan)| (id.as_str(), plan)).collect();
941 enforce_bind_exposure_gate(
942 &bind.key,
943 bind.loopback,
944 &siblings,
945 self.bind_acks.acknowledged(&bind.key),
946 )?;
947 }
948
949 info!(route_id = %route_id, "Resuming route (spawning consumer only)");
950
951 let consumer_component_ctx = Arc::new(
952 ControllerComponentContext::new(
953 Arc::clone(&self.registry),
954 Arc::clone(&self.languages),
955 self.tracer_metrics
956 .clone()
957 .unwrap_or_else(|| Arc::new(NoOpMetrics)),
958 Arc::clone(&self.platform_service),
959 self.health_registry(),
960 Some(route_id.to_string()),
961 self.tracer_gating.levers.component_metrics_levers(),
962 )
963 .with_in_flight(Arc::clone(&self.in_flight_total)),
964 );
965 let consumer_rt: Arc<dyn camel_component_api::RuntimeObservability> =
966 Arc::clone(&consumer_component_ctx) as Arc<_>;
967 let (mut consumer, consumer_concurrency) = consumer_management::create_route_consumer(
968 consumer_rt,
969 &self.registry,
970 &from_uri,
971 consumer_component_ctx.as_ref(),
972 )?;
973
974 // Wire security context before spawning consumer (authenticator
975 // marker guard: see start path above).
976 let managed = self
977 .routes
978 .get(route_id)
979 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
980 deliver_security_context(consumer.as_mut(), &managed.compiled);
981
982 // Get the managed route for mutation
983 let managed = self
984 .routes
985 .get_mut(route_id)
986 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
987
988 // Create child token for consumer lifecycle
989 let consumer_cancel = managed.consumer_cancel_token.child_token();
990
991 let crash_notifier = self.crash_notifier.clone();
992 let runtime_for_consumer = self.runtime.clone();
993
994 // Create ConsumerContext with the stored sender. drainclaim: same
995 // counter installation as the start path — resumed routes count.
996 // Business-error-model Task 2.2: the mapping snapshot rides the
997 // resume registration too, so a suspend/resume cycle preserves it.
998 let http_error_mapping = managed.compiled.http_error_mapping.clone();
999 let consumer_ctx =
1000 ConsumerContext::new(sender, consumer_cancel.clone(), route_id.to_string())
1001 .with_in_flight_counter(Arc::clone(&self.in_flight_total))
1002 .with_http_error_mapping(http_error_mapping);
1003
1004 // direct-inline-dispatch Task 3.3 (bd rc-y4vk): mirror the
1005 // start_route publication on the resume path. Without this the
1006 // fresh resume ConsumerContext carries no capability and the
1007 // resumed consumer's registry entry silently falls back to the
1008 // channel path. Same gate as start (non-Concurrent only, wildcard
1009 // = Sequential-equivalent), same handle captures (pipeline swap
1010 // source, pipeline_cancel child scope, shared drain counter), and
1011 // published before the resumed consumer spawns — a fresh ctx means
1012 // a fresh OnceLock, so the set-once keep-first contract cannot
1013 // interfere with the pre-suspend publication.
1014 //
1015 // rc-2sba publication guard (mirrors start): an aggregate-split
1016 // route's `managed.pipeline` is an identity shell
1017 // (`compose_pipeline(vec![])`) and must never be exposed to inline
1018 // execution — the split pre/agg/post pipelines stay driven by the
1019 // aggregate engine over the channel path, so no capability is
1020 // published here either.
1021 if !matches!(
1022 concurrency_override.unwrap_or(consumer_concurrency),
1023 ConcurrencyModel::Concurrent { .. }
1024 ) && managed.aggregate_split.is_none()
1025 {
1026 let (pipeline, pipeline_cancel, drain_in_flight) = {
1027 let managed = self
1028 .routes
1029 .get(route_id)
1030 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
1031 (
1032 Arc::clone(&managed.pipeline),
1033 managed.pipeline_cancel_token.child_token(),
1034 Arc::clone(&managed.drain_in_flight),
1035 )
1036 };
1037 let dispatcher = RouteInlineDispatcher::new(
1038 route_id.to_string(),
1039 pipeline,
1040 pipeline_cancel,
1041 drain_in_flight,
1042 Arc::clone(&self.cohort),
1043 Some(Arc::clone(&self.in_flight_total)),
1044 );
1045 consumer_ctx.set_inline_dispatcher(Arc::new(dispatcher));
1046 }
1047
1048 // Spawn consumer task
1049 let (consumer_handle, startup_rx, watcher_inputs, outer_inputs, stop_budget_tx) =
1050 consumer_management::spawn_consumer_task(
1051 route_id.to_string(),
1052 consumer,
1053 consumer_ctx,
1054 crash_notifier,
1055 runtime_for_consumer,
1056 true,
1057 );
1058
1059 // rc-w1u9: await consumer startup handshake on resume too — bind
1060 // failures during resume must surface as resume errors.
1061 // For Immediate consumers the receiver is pre-resolved (rc-slvd).
1062 let resume_result = consumer_management::await_consumer_startup(startup_rx, "resume").await;
1063 if let Err(e) = resume_result {
1064 // rc-kh7c cleanup parity with the start path: the consumer task
1065 // must not run detached after a failed resume, and child tasks
1066 // spawned by consumer.start() that observe ctx.cancelled() must
1067 // stop too.
1068 consumer_handle.abort();
1069 consumer_cancel.cancel();
1070 return Err(e);
1071 }
1072
1073 // Detached failure watcher for Immediate consumers (rc-slvd).
1074 if let Some(inputs) = watcher_inputs {
1075 consumer_management::spawn_failure_watcher(inputs);
1076 }
1077
1078 // Detached outer-task watcher for Explicit consumers (rc-a7rh):
1079 // spawned only after the resume handshake resolved Ok — rollback
1080 // terminations (abort-then-cancel above) happen before this point
1081 // and are never watched.
1082 if let Some(outer) = outer_inputs {
1083 consumer_management::spawn_outer_task_watcher(outer);
1084 }
1085
1086 // Store consumer handle and update status
1087 let managed = self
1088 .routes
1089 .get_mut(route_id)
1090 .expect("invariant: route must exist after prior existence check"); // allow-unwrap
1091 managed.consumer_handle = Some(consumer_handle);
1092 managed.stop_budget = Some(stop_budget_tx);
1093
1094 info!(route_id = %route_id, "Route resumed");
1095 self.health_registry().mark_route_started(route_id);
1096 Ok(())
1097 }
1098
1099 async fn start_all_routes(&mut self) -> Result<(), CamelError> {
1100 // Only start routes where auto_startup() == true
1101 // Sort by startup_order() ascending before starting
1102 let route_ids: Vec<String> = {
1103 let pairs = self.routes.auto_startup_sorted();
1104 pairs.into_iter().map(|(id, _)| id).collect()
1105 };
1106
1107 info!("Starting {} auto-startup routes", route_ids.len());
1108
1109 // Collect errors but continue starting remaining routes
1110 let mut errors: Vec<String> = Vec::new();
1111 for route_id in route_ids {
1112 if let Err(e) = self.start_route(&route_id).await {
1113 errors.push(format!("Route '{}': {}", route_id, e));
1114 }
1115 }
1116
1117 if !errors.is_empty() {
1118 return Err(CamelError::RouteError(format!(
1119 "Failed to start routes: {}",
1120 errors.join(", ")
1121 )));
1122 }
1123
1124 info!("All auto-startup routes started");
1125 Ok(())
1126 }
1127
1128 async fn stop_all_routes(&mut self) -> Result<(), CamelError> {
1129 // Sort by startup_order descending (reverse order)
1130 let route_ids: Vec<String> = {
1131 let pairs = self.routes.shutdown_sorted();
1132 pairs.into_iter().map(|(id, _)| id).collect()
1133 };
1134
1135 info!("Stopping {} routes", route_ids.len());
1136
1137 for route_id in route_ids {
1138 let _ = self.stop_route(&route_id).await;
1139 }
1140
1141 info!("All routes stopped");
1142 Ok(())
1143 }
1144}
1145
1146// ── rc-e2r9: b′ signal emission on reply-drop ──
1147// The shared `send_reply_or_b_prime` helper lives in
1148// `super::route_helpers` (single copy — the duplicated private helpers in
1149// this file and `route_controller.rs` drifted once already; see rc-e2r9
1150// review, Important 3).
1151
1152#[cfg(test)]
1153#[path = "route_controller_trait_tests.rs"]
1154mod bind_exposure_gate;