Skip to main content

camel_core/
context.rs

1use std::any::{Any, TypeId};
2use std::collections::HashMap;
3use std::sync::Arc;
4use tokio_util::sync::CancellationToken;
5use tracing::{debug, trace};
6
7#[cfg(test)]
8use camel_api::StepLifecycle;
9use camel_api::component_metadata::ComponentMetadata;
10use camel_api::error_handler::ErrorHandlerConfig;
11use camel_api::{
12    CamelError, FunctionInvoker, HealthReport, Lifecycle, MetricsCollector, MetricsHandle,
13    PlatformIdentity, PlatformService, ReadinessGate, RouteTemplateSpec, RuntimeCommandBus,
14    RuntimeQueryBus, TemplateInstanceRecord,
15};
16use camel_component_api::{Component, ComponentContext, ComponentRegistrar};
17use camel_language_api::Language;
18
19use crate::health_registry::HealthCheckRegistry;
20use crate::intercept::InterceptRules;
21use crate::language_registry::LanguageRegistryError;
22use crate::lifecycle::adapters::controller_actor::RouteControllerHandle;
23use crate::lifecycle::adapters::route_controller::SharedLanguageRegistry;
24use crate::lifecycle::application::route_definition::RouteDefinition;
25use crate::lifecycle::application::runtime_bus::RuntimeBus;
26use crate::registry::RegistryError;
27use crate::shared::components::domain::Registry;
28use crate::shared::observability::domain::{MetricsLeversConfig, TracerConfig};
29use crate::startup_validation::ConfigCheck;
30use crate::template::TemplateRegistry;
31
32pub use crate::context_builder::CamelContextBuilder;
33
34/// The CamelContext is the runtime engine that manages components, routes, and their lifecycle.
35///
36/// # Lifecycle
37///
38/// Call [`start()`](Self::start) to launch routes, then [`stop()`](Self::stop)
39/// or [`abort()`](Self::abort) to shut down. A stopped context can be restarted
40/// by calling `start()` again — the controller actor stays alive across stop/start
41/// cycles; only [`abort()`](Self::abort) is destructive.
42pub struct CamelContext {
43    registry: Arc<std::sync::Mutex<Registry>>,
44    route_controller: RouteControllerHandle,
45    actor_join: Option<tokio::task::JoinHandle<()>>,
46    supervision_join: Option<tokio::task::JoinHandle<()>>,
47    runtime: Arc<RuntimeBus>,
48    cancel_token: CancellationToken,
49    /// Shared late-bound metrics cell (rc-hrm1.3): the SAME handle instance
50    /// seeds the route controller's `tracer_metrics` and the RuntimeBus
51    /// collector, so a collector registered at any time — including after
52    /// routes are added — is observed by all subsequent emission calls.
53    metrics: Arc<MetricsHandle>,
54    /// Snapshot of the metric-family levers from the last
55    /// `set_tracer_config` call (default: components off). Read
56    /// synchronously by `ComponentContext::component_metrics_enabled`
57    /// — the controller actor holds its own copy for pipeline gating,
58    /// which is not reachable from a sync context method.
59    metrics_levers: MetricsLeversConfig,
60    // Platform ports
61    platform_service: Arc<dyn PlatformService>,
62    languages: SharedLanguageRegistry,
63    shutdown_timeout: std::time::Duration,
64    services: Vec<Box<dyn Lifecycle>>,
65    health_registry: Arc<HealthCheckRegistry>,
66    component_configs: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
67    function_invoker: Option<Arc<dyn FunctionInvoker>>,
68    template_registry: Arc<TemplateRegistry>,
69    idempotent_repositories: crate::registry::SharedIdempotentRegistry,
70    claim_check_repositories: crate::registry::SharedClaimCheckRegistry,
71    cache_repositories: crate::registry::SharedCacheRegistry,
72    /// Fail-closed startup validation registry (ADR-0033). Checks are drained
73    /// and executed synchronously at the head of [`start()`](Self::start) before
74    /// any route consumer is started.
75    startup_checks: Vec<Box<dyn ConfigCheck>>,
76    /// Build identity (dashboard-observability T3.2): re-published when a
77    /// metrics collector registers late, because the composite does not
78    /// replay past observations to new members.
79    build_version: &'static str,
80    build_git_sha: &'static str,
81    /// Anchor for `camel_uptime_seconds` (context build time).
82    build_started_at: std::time::Instant,
83}
84
85/// Parts bag used by [`CamelContextBuilder::build`] to construct a [`CamelContext`]
86/// without accessing private fields from a sibling module.
87pub(crate) struct FromParts {
88    pub(crate) registry: Arc<std::sync::Mutex<Registry>>,
89    pub(crate) route_controller: RouteControllerHandle,
90    pub(crate) _actor_join: tokio::task::JoinHandle<()>,
91    pub(crate) supervision_join: Option<tokio::task::JoinHandle<()>>,
92    pub(crate) runtime: Arc<RuntimeBus>,
93    pub(crate) cancel_token: CancellationToken,
94    pub(crate) metrics: Arc<MetricsHandle>,
95    pub(crate) platform_service: Arc<dyn PlatformService>,
96    pub(crate) languages: SharedLanguageRegistry,
97    pub(crate) shutdown_timeout: std::time::Duration,
98    pub(crate) services: Vec<Box<dyn Lifecycle>>,
99    pub(crate) health_registry: Arc<HealthCheckRegistry>,
100    pub(crate) component_configs: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
101    pub(crate) function_invoker: Option<Arc<dyn FunctionInvoker>>,
102    pub(crate) template_registry: Arc<TemplateRegistry>,
103    pub(crate) idempotent_repositories: crate::registry::SharedIdempotentRegistry,
104    pub(crate) claim_check_repositories: crate::registry::SharedClaimCheckRegistry,
105    pub(crate) cache_repositories: crate::registry::SharedCacheRegistry,
106    pub(crate) startup_checks: Vec<Box<dyn ConfigCheck>>,
107    pub(crate) build_version: &'static str,
108    pub(crate) build_git_sha: &'static str,
109    pub(crate) build_started_at: std::time::Instant,
110}
111
112impl CamelContext {
113    pub(crate) fn from_parts(parts: FromParts) -> Self {
114        Self {
115            registry: parts.registry,
116            route_controller: parts.route_controller,
117            actor_join: Some(parts._actor_join),
118            supervision_join: parts.supervision_join,
119            runtime: parts.runtime,
120            cancel_token: parts.cancel_token,
121            metrics: parts.metrics,
122            metrics_levers: MetricsLeversConfig::default(),
123            platform_service: parts.platform_service,
124            languages: parts.languages,
125            shutdown_timeout: parts.shutdown_timeout,
126            services: parts.services,
127            health_registry: parts.health_registry,
128            component_configs: parts.component_configs,
129            function_invoker: parts.function_invoker,
130            template_registry: parts.template_registry,
131            idempotent_repositories: parts.idempotent_repositories,
132            claim_check_repositories: parts.claim_check_repositories,
133            cache_repositories: parts.cache_repositories,
134            startup_checks: parts.startup_checks,
135            build_version: parts.build_version,
136            build_git_sha: parts.build_git_sha,
137            build_started_at: parts.build_started_at,
138        }
139    }
140}
141
142/// Opaque handle for runtime side-effect execution operations.
143///
144/// This intentionally does not expose direct lifecycle mutation APIs to callers.
145#[derive(Clone)]
146pub struct RuntimeExecutionHandle {
147    pub(crate) controller: RouteControllerHandle,
148    pub(crate) runtime: Arc<RuntimeBus>,
149    pub(crate) function_invoker: Option<Arc<dyn FunctionInvoker>>,
150    /// Lifecycle handles to inject into the compiled pipeline during
151    /// `apply_swap`.  Used in tests to simulate lifecycle-bearing routes
152    /// (e.g. resequencer).  Always `None` in production.
153    #[cfg(test)]
154    #[allow(clippy::type_complexity)]
155    pub(crate) test_lifecycle_inject: Arc<std::sync::Mutex<Option<Vec<Arc<dyn StepLifecycle>>>>>,
156}
157
158impl RuntimeExecutionHandle {
159    pub(crate) async fn add_route_definition(
160        &self,
161        definition: RouteDefinition,
162    ) -> Result<(), CamelError> {
163        use crate::lifecycle::application::ports::RouteRegistrationPort;
164        self.runtime
165            .register_route(definition)
166            .await
167            .map_err(Into::into)
168    }
169
170    /// Compile a route definition into a bare BoxProcessor (no lifecycle).
171    /// Kept for tests; hot-reload uses the lifecycle-preserving variant instead.
172    #[allow(dead_code)]
173    pub(crate) async fn compile_route_definition(
174        &self,
175        definition: RouteDefinition,
176    ) -> Result<camel_api::BoxProcessor, CamelError> {
177        self.controller.compile_route_definition(definition).await
178    }
179
180    #[allow(dead_code)] // kept for potential future hot-reload paths
181    pub(crate) async fn compile_route_definition_with_generation(
182        &self,
183        definition: RouteDefinition,
184        generation: u64,
185    ) -> Result<camel_api::BoxProcessor, CamelError> {
186        self.controller
187            .compile_route_definition_with_generation(definition, generation)
188            .await
189    }
190
191    pub(crate) async fn compile_route_definition_pipeline(
192        &self,
193        definition: RouteDefinition,
194        generation: u64,
195    ) -> Result<crate::lifecycle::domain::CompiledPipeline, CamelError> {
196        self.controller
197            .compile_route_definition_pipeline(definition, generation)
198            .await
199    }
200
201    /// Compile without function generation, returning full CompiledPipeline.
202    /// Oracle Fix 1: stateless hot-reload path preserves lifecycle handles.
203    pub(crate) async fn compile_route_definition_dry_pipeline(
204        &self,
205        definition: RouteDefinition,
206    ) -> Result<crate::lifecycle::domain::CompiledPipeline, CamelError> {
207        self.controller
208            .compile_route_definition_dry_pipeline(definition)
209            .await
210    }
211
212    pub(crate) async fn prepare_route_definition_with_generation(
213        &self,
214        definition: RouteDefinition,
215        generation: u64,
216    ) -> Result<crate::lifecycle::domain::route_compilation::PreparedRoute, CamelError> {
217        self.controller
218            .prepare_route_definition_with_generation(definition, generation)
219            .await
220    }
221
222    pub(crate) async fn insert_prepared_route(
223        &self,
224        prepared: crate::lifecycle::domain::route_compilation::PreparedRoute,
225    ) -> Result<(), CamelError> {
226        self.controller.insert_prepared_route(prepared).await
227    }
228
229    pub(crate) async fn discard_prepared_staging(&self, route_id: &str) -> Result<(), CamelError> {
230        self.controller.discard_prepared_staging(route_id).await
231    }
232
233    pub(crate) async fn remove_route_preserving_functions(
234        &self,
235        route_id: String,
236    ) -> Result<(), CamelError> {
237        self.controller
238            .remove_route_preserving_functions(route_id)
239            .await
240    }
241
242    pub(crate) async fn register_route_aggregate(
243        &self,
244        route_id: String,
245    ) -> Result<(), CamelError> {
246        self.runtime.register_aggregate_only(route_id).await
247    }
248
249    pub(crate) async fn swap_route_pipeline(
250        &self,
251        route_id: &str,
252        pipeline: camel_api::BoxProcessor,
253    ) -> Result<(), CamelError> {
254        self.controller.swap_pipeline(route_id, pipeline).await
255    }
256
257    /// Stop the route via the reload path (graceful lifecycle drain).
258    pub(crate) async fn stop_route_reload(&self, route_id: &str) -> Result<(), CamelError> {
259        self.controller.stop_route_reload(route_id).await
260    }
261
262    /// Start the route via the reload path (re-create consumer).
263    pub(crate) async fn start_route_reload(&self, route_id: &str) -> Result<(), CamelError> {
264        self.controller.start_route_reload(route_id).await
265    }
266
267    /// Raw pipeline swap — bypasses the lifecycle/aggregate rejection check.
268    /// Only safe after the route has been stopped (Restart path).
269    pub(crate) async fn swap_route_pipeline_raw(
270        &self,
271        route_id: &str,
272        pipeline: camel_api::BoxProcessor,
273        lifecycle: Vec<Arc<dyn camel_api::StepLifecycle>>,
274    ) -> Result<(), CamelError> {
275        self.controller
276            .swap_pipeline_raw(route_id, pipeline, lifecycle)
277            .await
278    }
279
280    pub(crate) async fn execute_runtime_command(
281        &self,
282        cmd: camel_api::RuntimeCommand,
283    ) -> Result<camel_api::RuntimeCommandResult, CamelError> {
284        self.runtime.execute(cmd).await
285    }
286
287    pub(crate) async fn runtime_route_status(
288        &self,
289        route_id: &str,
290    ) -> Result<Option<String>, CamelError> {
291        match self
292            .runtime
293            .ask(camel_api::RuntimeQuery::GetRouteStatus {
294                route_id: route_id.to_string(),
295            })
296            .await
297        {
298            Ok(camel_api::RuntimeQueryResult::RouteStatus { status, .. }) => Ok(Some(status)),
299            Ok(_) => Err(CamelError::RouteError(
300                "unexpected runtime query response for route status".to_string(),
301            )),
302            Err(CamelError::RouteError(msg)) if msg.contains("not found") => Ok(None),
303            Err(err) => Err(err),
304        }
305    }
306
307    pub(crate) async fn runtime_route_ids(&self) -> Result<Vec<String>, CamelError> {
308        match self.runtime.ask(camel_api::RuntimeQuery::ListRoutes).await {
309            Ok(camel_api::RuntimeQueryResult::Routes { route_ids }) => Ok(route_ids),
310            Ok(_) => Err(CamelError::RouteError(
311                "unexpected runtime query response for route listing".to_string(),
312            )),
313            Err(err) => Err(err),
314        }
315    }
316
317    pub(crate) async fn route_source_hash(&self, route_id: &str) -> Option<u64> {
318        self.controller.route_source_hash(route_id).await
319    }
320
321    pub(crate) async fn in_flight_count(&self, route_id: &str) -> Result<u64, CamelError> {
322        if !self.controller.route_exists(route_id).await? {
323            return Err(CamelError::RouteError(format!(
324                "Route '{}' not found",
325                route_id
326            )));
327        }
328        Ok(self
329            .controller
330            .in_flight_count(route_id)
331            .await?
332            .unwrap_or(0))
333    }
334
335    /// Check whether the running route has lifecycle-bearing steps.
336    pub(crate) async fn route_has_lifecycle(&self, route_id: &str) -> bool {
337        self.controller
338            .route_has_lifecycle(route_id)
339            .await
340            .unwrap_or(false)
341    }
342
343    pub(crate) fn function_invoker(&self) -> Option<Arc<dyn FunctionInvoker>> {
344        self.function_invoker.clone()
345    }
346
347    #[cfg(test)]
348    pub(crate) async fn force_start_route_for_test(
349        &self,
350        route_id: &str,
351    ) -> Result<(), CamelError> {
352        self.controller.start_route(route_id).await
353    }
354
355    pub async fn controller_route_count_for_test(&self) -> usize {
356        self.controller.route_count().await.unwrap_or(0)
357    }
358}
359
360#[async_trait::async_trait]
361impl crate::hot_reload::ports::ReloadExecutorPort for RuntimeExecutionHandle {
362    async fn add_route_definition(&self, definition: RouteDefinition) -> Result<(), CamelError> {
363        RuntimeExecutionHandle::add_route_definition(self, definition).await
364    }
365
366    async fn compile_route_definition_pipeline(
367        &self,
368        definition: RouteDefinition,
369        generation: u64,
370    ) -> Result<crate::lifecycle::domain::CompiledPipeline, CamelError> {
371        RuntimeExecutionHandle::compile_route_definition_pipeline(self, definition, generation)
372            .await
373    }
374
375    async fn compile_route_definition_dry_pipeline(
376        &self,
377        definition: RouteDefinition,
378    ) -> Result<crate::lifecycle::domain::CompiledPipeline, CamelError> {
379        RuntimeExecutionHandle::compile_route_definition_dry_pipeline(self, definition).await
380    }
381
382    async fn prepare_route_definition_with_generation(
383        &self,
384        definition: RouteDefinition,
385        generation: u64,
386    ) -> Result<crate::lifecycle::domain::route_compilation::PreparedRoute, CamelError> {
387        RuntimeExecutionHandle::prepare_route_definition_with_generation(
388            self, definition, generation,
389        )
390        .await
391    }
392
393    async fn insert_prepared_route(
394        &self,
395        prepared: crate::lifecycle::domain::route_compilation::PreparedRoute,
396    ) -> Result<(), CamelError> {
397        RuntimeExecutionHandle::insert_prepared_route(self, prepared).await
398    }
399
400    async fn discard_prepared_staging(&self, route_id: &str) -> Result<(), CamelError> {
401        RuntimeExecutionHandle::discard_prepared_staging(self, route_id).await
402    }
403
404    async fn remove_route_preserving_functions(&self, route_id: String) -> Result<(), CamelError> {
405        RuntimeExecutionHandle::remove_route_preserving_functions(self, route_id).await
406    }
407
408    async fn register_route_aggregate(&self, route_id: String) -> Result<(), CamelError> {
409        RuntimeExecutionHandle::register_route_aggregate(self, route_id).await
410    }
411
412    async fn swap_route_pipeline(
413        &self,
414        route_id: &str,
415        pipeline: camel_api::BoxProcessor,
416    ) -> Result<(), CamelError> {
417        RuntimeExecutionHandle::swap_route_pipeline(self, route_id, pipeline).await
418    }
419
420    async fn stop_route_reload(&self, route_id: &str) -> Result<(), CamelError> {
421        RuntimeExecutionHandle::stop_route_reload(self, route_id).await
422    }
423
424    async fn start_route_reload(&self, route_id: &str) -> Result<(), CamelError> {
425        RuntimeExecutionHandle::start_route_reload(self, route_id).await
426    }
427
428    async fn swap_route_pipeline_raw(
429        &self,
430        route_id: &str,
431        pipeline: camel_api::BoxProcessor,
432        lifecycle: Vec<std::sync::Arc<dyn camel_api::StepLifecycle>>,
433    ) -> Result<(), CamelError> {
434        RuntimeExecutionHandle::swap_route_pipeline_raw(self, route_id, pipeline, lifecycle).await
435    }
436
437    async fn execute_runtime_command(
438        &self,
439        cmd: camel_api::RuntimeCommand,
440    ) -> Result<camel_api::RuntimeCommandResult, CamelError> {
441        RuntimeExecutionHandle::execute_runtime_command(self, cmd).await
442    }
443
444    async fn runtime_route_status(&self, route_id: &str) -> Result<Option<String>, CamelError> {
445        RuntimeExecutionHandle::runtime_route_status(self, route_id).await
446    }
447
448    async fn in_flight_count(&self, route_id: &str) -> Result<u64, CamelError> {
449        RuntimeExecutionHandle::in_flight_count(self, route_id).await
450    }
451
452    async fn route_has_lifecycle(&self, route_id: &str) -> bool {
453        RuntimeExecutionHandle::route_has_lifecycle(self, route_id).await
454    }
455
456    #[cfg(test)]
457    fn take_test_lifecycle_inject(
458        &self,
459    ) -> Option<Vec<std::sync::Arc<dyn camel_api::StepLifecycle>>> {
460        self.test_lifecycle_inject.lock().unwrap().take()
461    }
462}
463
464impl CamelContext {
465    pub fn builder() -> CamelContextBuilder {
466        CamelContextBuilder::new()
467    }
468
469    /// Set a global error handler applied to all routes without a per-route handler.
470    pub async fn set_error_handler(&mut self, config: ErrorHandlerConfig) {
471        let _ = self.route_controller.set_error_handler(config).await;
472    }
473
474    /// Install per-bind public-exposure acknowledgements (ADR-0061).
475    /// Built by the CLI from `CamelConfig.binds`; the per-bind gate fails
476    /// closed on non-loopback binds until acknowledged.
477    pub async fn set_bind_exposure_acks(
478        &mut self,
479        acks: crate::lifecycle::adapters::route_controller_trait::BindExposureAcks,
480    ) {
481        let _ = self.route_controller.set_bind_exposure_acks(acks).await;
482    }
483
484    /// Enable or disable tracing globally.
485    pub async fn set_tracing(&mut self, enabled: bool) {
486        let config = TracerConfig {
487            enabled,
488            ..Default::default()
489        };
490        // Keep the lever snapshot in lockstep with what is forwarded
491        // (this path resets the levers to their defaults).
492        self.metrics_levers = config.metrics_levers.clone();
493        let _ = self.route_controller.set_tracer_config(config).await;
494    }
495
496    /// Configure tracing with full config.
497    pub async fn set_tracer_config(&mut self, config: TracerConfig) {
498        // Snapshot the levers for the sync `component_metrics_enabled`
499        // surface before the config moves into the controller actor.
500        self.metrics_levers = config.metrics_levers.clone();
501        let _ = self.route_controller.set_tracer_config(config).await;
502    }
503
504    /// Builder-style: enable tracing with default config.
505    pub async fn with_tracing(mut self) -> Self {
506        self.set_tracing(true).await;
507        self
508    }
509
510    /// Builder-style: configure tracing with custom config.
511    /// Note: tracing subscriber initialization (stdout/file output) is handled
512    /// separately via init_tracing_subscriber (called in camel-config bridge).
513    pub async fn with_tracer_config(mut self, config: TracerConfig) -> Self {
514        self.set_tracer_config(config).await;
515        self
516    }
517
518    /// Register a lifecycle service (Apache Camel: addService pattern)
519    ///
520    /// For services exposing `as_function_invoker()`, the invoker is propagated
521    /// to the route controller so that subsequent route definitions with function
522    /// steps work correctly.
523    ///
524    /// Prefer [`CamelContextBuilder::with_lifecycle`] when possible, which wires
525    /// the invoker at build time before any routes are added.
526    pub fn with_lifecycle<L: Lifecycle + 'static>(mut self, service: L) -> Self {
527        if let Some(collector) = service.as_metrics_collector() {
528            // Late-bound registration (compose, never replace): the shared
529            // handle fans the collector into every emission path seeded at
530            // build time — context slot, controller tracer path, RuntimeBus.
531            self.metrics.register(collector);
532            // The composite does not replay past observations to a newly
533            // registered collector, so re-publish the identity gauges: a
534            // collector wired post-build (e.g. configure_context's
535            // PrometheusService) still reports build info and uptime.
536            self.metrics
537                .record_build_info(self.build_version, self.build_git_sha);
538            self.metrics
539                .record_uptime(self.build_started_at.elapsed().as_secs_f64());
540        }
541        if let Some(invoker) = service.as_function_invoker() {
542            self.function_invoker = Some(invoker.clone());
543            if let Err(e) = self.route_controller.try_set_function_invoker(invoker) {
544                tracing::debug!("Failed to propagate function invoker to route controller: {e}");
545            }
546        }
547
548        self.services.push(Box::new(service));
549        self
550    }
551
552    /// Register a component with this context.
553    ///
554    /// Delegates to [`register_component_dyn`](Self::register_component_dyn)
555    /// so metadata harvesting happens regardless of which entry point
556    /// is used.
557    pub fn register_component<C: Component + 'static>(&mut self, component: C) {
558        self.register_component_dyn(Arc::new(component));
559    }
560
561    /// Install route send-point interception rules (pre-first-use only).
562    ///
563    /// Returns `CamelError::Config` once frozen: after the first route is
564    /// registered or the context is started, compiled pipelines have
565    /// captured the rule set and it cannot change. Builder-time rules via
566    /// [`CamelContextBuilder::with_intercept_rules`] bypass this gate.
567    pub async fn set_intercept_rules(&self, rules: InterceptRules) -> Result<(), CamelError> {
568        self.route_controller.set_intercept_rules(rules).await
569    }
570
571    /// Register a startup `ConfigCheck` to be evaluated at the head of
572    /// [`start()`](Self::start). Established by ADR-0033.
573    ///
574    /// Checks are drained and executed synchronously before any route consumer
575    /// is started. If any check returns `Err`, `start()` fails closed with
576    /// `CamelError::Config(_)` and no route is started. The check list is
577    /// consumed (moved) during `start()` so this method may be called multiple
578    /// times to register an arbitrary number of checks.
579    pub fn add_startup_check(&mut self, check: Box<dyn ConfigCheck>) {
580        self.startup_checks.push(check);
581    }
582
583    /// Register a language with this context, keyed by name.
584    ///
585    /// Returns `Err(LanguageRegistryError::AlreadyRegistered)` if a language
586    /// with the same name is already registered. Use
587    /// [`resolve_language`](Self::resolve_language) to check before
588    /// registering, or choose a distinct name.
589    pub fn register_language(
590        &mut self,
591        name: impl Into<String>,
592        lang: Box<dyn Language>,
593    ) -> Result<(), LanguageRegistryError> {
594        let name = name.into();
595        let mut languages = self
596            .languages
597            .lock()
598            .expect("mutex poisoned: another thread panicked while holding this lock"); // allow-unwrap
599        if languages.contains_key(&name) {
600            return Err(LanguageRegistryError::AlreadyRegistered { name });
601        }
602        languages.insert(name, Arc::from(lang));
603        Ok(())
604    }
605
606    /// Resolve a language by name. Returns `None` if not registered.
607    pub fn resolve_language(&self, name: &str) -> Option<Arc<dyn Language>> {
608        let languages = self
609            .languages
610            .lock()
611            .expect("mutex poisoned: another thread panicked while holding this lock"); // allow-unwrap
612        languages.get(name).cloned()
613    }
614
615    /// Add a route definition to this context.
616    ///
617    /// The route must have an ID. Steps are resolved immediately using registered components.
618    pub async fn add_route_definition(
619        &self,
620        definition: RouteDefinition,
621    ) -> Result<(), CamelError> {
622        use crate::lifecycle::application::ports::RouteRegistrationPort;
623        debug!(
624            from = definition.from_uri(),
625            route_id = %definition.route_id(),
626            "Adding route definition"
627        );
628        self.runtime
629            .register_route(definition)
630            .await
631            .map_err(Into::into)
632    }
633
634    /// Access the component registry.
635    pub fn registry(&self) -> std::sync::MutexGuard<'_, Registry> {
636        self.registry
637            .lock()
638            .expect("mutex poisoned: another thread panicked while holding this lock") // allow-unwrap
639    }
640
641    /// Access the shared component registry Arc.
642    pub fn registry_arc(&self) -> Arc<std::sync::Mutex<Registry>> {
643        Arc::clone(&self.registry)
644    }
645
646    /// Get runtime execution handle for file-watcher integrations.
647    pub fn runtime_execution_handle(&self) -> RuntimeExecutionHandle {
648        RuntimeExecutionHandle {
649            controller: self.route_controller.clone(),
650            runtime: Arc::clone(&self.runtime),
651            function_invoker: self.function_invoker.clone(),
652            #[cfg(test)]
653            test_lifecycle_inject: Arc::new(std::sync::Mutex::new(None)),
654        }
655    }
656
657    /// Get the metrics collector (the shared late-bound handle).
658    pub fn metrics(&self) -> Arc<dyn MetricsCollector> {
659        Arc::clone(&self.metrics) as Arc<dyn MetricsCollector>
660    }
661
662    /// Get the platform service.
663    pub fn platform_service(&self) -> Arc<dyn PlatformService> {
664        Arc::clone(&self.platform_service)
665    }
666
667    /// Get the readiness gate port.
668    pub fn readiness_gate(&self) -> Arc<dyn ReadinessGate> {
669        self.platform_service.readiness_gate()
670    }
671
672    /// Get the platform identity.
673    pub fn platform_identity(&self) -> PlatformIdentity {
674        self.platform_service.identity()
675    }
676
677    /// Get the leadership service port.
678    pub fn leadership(&self) -> Arc<dyn camel_api::LeadershipService> {
679        self.platform_service.leadership()
680    }
681
682    /// Get runtime command/query bus handle.
683    pub fn runtime(&self) -> Arc<dyn camel_api::RuntimeHandle> {
684        self.runtime.clone()
685    }
686
687    /// Build a producer context wired to this runtime.
688    pub fn producer_context(&self) -> camel_api::ProducerContext {
689        camel_api::ProducerContext::new().with_runtime(self.runtime())
690    }
691
692    /// Query route status via runtime read-model.
693    pub async fn runtime_route_status(&self, route_id: &str) -> Result<Option<String>, CamelError> {
694        match self
695            .runtime()
696            .ask(camel_api::RuntimeQuery::GetRouteStatus {
697                route_id: route_id.to_string(),
698            })
699            .await
700        {
701            Ok(camel_api::RuntimeQueryResult::RouteStatus { status, .. }) => Ok(Some(status)),
702            Ok(_) => Err(CamelError::RouteError(
703                "unexpected runtime query response for route status".to_string(),
704            )),
705            Err(CamelError::RouteError(msg)) if msg.contains("not found") => Ok(None),
706            Err(err) => Err(err),
707        }
708    }
709
710    /// Start all routes. Each route's consumer will begin producing exchanges.
711    ///
712    /// Only routes with `auto_startup == true` will be started, in order of their
713    /// `startup_order` (lower values start first).
714    ///
715    /// Algorithm lives in `lifecycle::application::context_lifecycle::start_context`
716    /// (Tier C C2). Public signature is unchanged.
717    pub async fn start(&mut self) -> Result<(), CamelError> {
718        crate::lifecycle::application::context_lifecycle::start_context(
719            &mut self.services,
720            &mut self.startup_checks,
721            &self.runtime,
722            &self.route_controller,
723            &mut self.cancel_token,
724        )
725        .await?;
726        // Trip the intercept-rules freeze so it applies even with zero
727        // routes. A failed `start_context` above returns early — a failed
728        // start does not freeze.
729        self.route_controller.mark_started().await
730    }
731
732    /// Graceful shutdown with default 30-second timeout.
733    pub async fn stop(&mut self) -> Result<(), CamelError> {
734        self.stop_timeout(self.shutdown_timeout).await
735    }
736
737    /// Graceful shutdown with custom timeout.
738    ///
739    /// Note: The timeout parameter is currently not propagated to the
740    /// RouteController's per-route shutdown timeout. The RouteController
741    /// uses a hardcoded 5-second default (`DEFAULT_SHUTDOWN_TIMEOUT`).
742    /// Full propagation is planned for a future version.
743    ///
744    /// Algorithm lives in `lifecycle::application::context_lifecycle::stop_context`
745    /// (Tier C C2). Public signature is unchanged.
746    pub async fn stop_timeout(&mut self, _timeout: std::time::Duration) -> Result<(), CamelError> {
747        crate::lifecycle::application::context_lifecycle::stop_context(
748            &self.cancel_token,
749            &mut self.supervision_join,
750            &self.runtime,
751            &self.route_controller,
752            &mut self.services,
753        )
754        .await
755    }
756
757    /// Get the graceful shutdown timeout used by [`stop()`](Self::stop).
758    pub fn shutdown_timeout(&self) -> std::time::Duration {
759        self.shutdown_timeout
760    }
761
762    /// Set the graceful shutdown timeout used by [`stop()`](Self::stop).
763    pub fn set_shutdown_timeout(&mut self, timeout: std::time::Duration) {
764        self.shutdown_timeout = timeout;
765    }
766
767    /// Test-only: take the actor join handle out of the context.
768    /// Used to verify the actor exits gracefully after stop().
769    #[cfg(test)]
770    pub(crate) fn take_actor_join(&mut self) -> Option<tokio::task::JoinHandle<()>> {
771        self.actor_join.take()
772    }
773
774    /// Immediate abort — kills all tasks without draining.
775    ///
776    /// Algorithm lives in `lifecycle::application::context_lifecycle::abort_context`
777    /// (Tier C C2). Public signature is unchanged. The use-case routes
778    /// through `RouteOrderingPort` + `RouteDestructiveTeardownPort`; the
779    /// same underlying `RouteControllerHandle` is passed twice as both
780    /// trait objects.
781    pub async fn abort(&mut self) {
782        crate::lifecycle::application::context_lifecycle::abort_context(
783            &self.cancel_token,
784            &mut self.supervision_join,
785            &self.runtime,
786            &self.route_controller as &dyn crate::lifecycle::application::ports::RouteOrderingPort,
787            &self.route_controller
788                as &dyn crate::lifecycle::application::ports::RouteDestructiveTeardownPort,
789            &mut self.services,
790            self.health_registry.cancel_token(),
791            &mut self.actor_join,
792        )
793        .await
794    }
795
796    /// Check health status of all registered services and lifecycle services.
797    pub async fn health_check(&self) -> HealthReport {
798        use camel_api::HealthSource;
799        self.health_report().await
800    }
801
802    pub fn health_registry(&self) -> Arc<HealthCheckRegistry> {
803        Arc::clone(&self.health_registry)
804    }
805
806    /// Store a component config. Overwrites any previously stored config of the same type.
807    pub fn set_component_config<T: 'static + Send + Sync>(&mut self, config: T) {
808        self.component_configs
809            .insert(TypeId::of::<T>(), Box::new(config));
810    }
811
812    /// Retrieve a stored component config by type. Returns None if not stored.
813    pub fn get_component_config<T: 'static + Send + Sync>(&self) -> Option<&T> {
814        self.component_configs
815            .get(&TypeId::of::<T>())
816            .and_then(|b| b.downcast_ref::<T>())
817    }
818
819    // --- Component Metadata ---
820
821    /// Get a component's harvested metadata by URI scheme.
822    pub fn component_metadata(&self, scheme: &str) -> Option<ComponentMetadata> {
823        self.registry.lock().ok()?.get_metadata(scheme)
824    }
825
826    /// Get metadata for every registered component.
827    pub fn all_component_metadata(&self) -> Vec<ComponentMetadata> {
828        self.registry
829            .lock()
830            .expect("mutex poisoned: another thread panicked while holding this lock") // allow-unwrap
831            .all_metadata()
832    }
833
834    /// Get a metadata catalog handle implementing
835    /// [`ComponentMetadataCatalog`](camel_api::component_metadata::ComponentMetadataCatalog).
836    ///
837    /// The returned handle shares the same `Arc<Mutex<Registry>>` as the
838    /// context, so registrations made through one are visible through the
839    /// other.
840    pub fn metadata_catalog(
841        &self,
842    ) -> crate::component_metadata_catalog::RuntimeComponentMetadataCatalog {
843        crate::component_metadata_catalog::RuntimeComponentMetadataCatalog::new(Arc::clone(
844            &self.registry,
845        ))
846    }
847
848    // --- Route Template Registry (data-only) ---
849
850    /// Register a route template specification.
851    ///
852    /// Returns `Err(CamelError)` if a template with the same ID is already registered.
853    pub fn add_route_template(&self, spec: RouteTemplateSpec) -> Result<(), CamelError> {
854        self.template_registry.register(spec)
855    }
856
857    /// Retrieve a route template specification by its ID.
858    pub fn get_route_template(&self, id: &str) -> Option<RouteTemplateSpec> {
859        self.template_registry.get(id)
860    }
861
862    /// Return all registered template IDs.
863    pub fn template_ids(&self) -> Vec<String> {
864        self.template_registry.template_ids()
865    }
866
867    /// Record a newly instantiated template instance.
868    pub fn record_template_instance(&self, record: TemplateInstanceRecord) {
869        self.template_registry.record_instance(record)
870    }
871
872    /// Return all instance records for a given template ID.
873    pub fn template_instances(&self, template_id: &str) -> Vec<TemplateInstanceRecord> {
874        self.template_registry.instances(template_id)
875    }
876
877    // --- Idempotent Repository Registry ---
878
879    /// Register an idempotent repository.
880    ///
881    /// Returns `Err(RegistryError::AlreadyRegistered)` if a repository with
882    /// the same name is already registered.
883    pub fn register_idempotent_repository(
884        &mut self,
885        name: impl Into<String>,
886        repo: Arc<dyn camel_api::IdempotentRepository>,
887    ) -> Result<(), RegistryError> {
888        self.idempotent_repositories.register(name, repo)
889    }
890
891    /// Retrieve an idempotent repository by name.
892    pub fn idempotent_repository(
893        &self,
894        name: &str,
895    ) -> Option<Arc<dyn camel_api::IdempotentRepository>> {
896        self.idempotent_repositories.get(name)
897    }
898
899    // --- Claim Check Repository Registry ---
900
901    /// Register a claim check repository.
902    ///
903    /// Returns `Err(RegistryError::AlreadyRegistered)` if a repository with
904    /// the same name is already registered.
905    pub fn register_claim_check_repository(
906        &mut self,
907        name: impl Into<String>,
908        repo: Arc<dyn camel_api::ClaimCheckRepository>,
909    ) -> Result<(), RegistryError> {
910        self.claim_check_repositories.register(name, repo)
911    }
912
913    /// Retrieve a claim check repository by name.
914    pub fn claim_check_repository(
915        &self,
916        name: &str,
917    ) -> Option<Arc<dyn camel_api::ClaimCheckRepository>> {
918        self.claim_check_repositories.get(name)
919    }
920
921    // --- Cache Repository Registry ---
922
923    /// Register a cache repository.
924    ///
925    /// Returns `Err(RegistryError::AlreadyRegistered)` if a repository with
926    /// the same name is already registered.
927    pub fn register_cache_repository(
928        &mut self,
929        name: impl Into<String>,
930        repo: Arc<dyn camel_api::CacheRepository>,
931    ) -> Result<(), RegistryError> {
932        self.cache_repositories.register(name, repo)
933    }
934
935    /// Replace an existing cache repository, returning the evicted value.
936    ///
937    /// Returns `None` if no repository was registered under `name`.
938    pub fn replace_cache_repository(
939        &mut self,
940        name: impl Into<String>,
941        repo: Arc<dyn camel_api::CacheRepository>,
942    ) -> Option<Arc<dyn camel_api::CacheRepository>> {
943        self.cache_repositories.register_or_replace(name, repo)
944    }
945
946    /// Retrieve a cache repository by name.
947    pub fn cache_repository(&self, name: &str) -> Option<Arc<dyn camel_api::CacheRepository>> {
948        self.cache_repositories.get(name)
949    }
950
951    /// Access the shutdown cancellation token.
952    ///
953    /// Repositories that need to bind background sweep tasks to context
954    /// shutdown (e.g. `RedbCacheRepository`) can `child_token()` from this.
955    pub fn shutdown_token(&self) -> CancellationToken {
956        self.cancel_token.clone()
957    }
958}
959
960impl ComponentRegistrar for CamelContext {
961    fn register_component_dyn(&mut self, component: Arc<dyn Component>) {
962        let scheme = component.scheme().to_string();
963        self.registry
964            .lock()
965            .expect("mutex poisoned: another thread panicked while holding this lock") // allow-unwrap
966            .register(component);
967        trace!(scheme, "Registered component");
968    }
969}
970
971impl ComponentContext for CamelContext {
972    fn resolve_component(&self, scheme: &str) -> Option<Arc<dyn Component>> {
973        self.registry.lock().ok()?.get(scheme)
974    }
975
976    fn resolve_language(&self, name: &str) -> Option<Arc<dyn Language>> {
977        self.languages.lock().ok()?.get(name).cloned()
978    }
979
980    fn metrics(&self) -> Arc<dyn MetricsCollector> {
981        Arc::clone(&self.metrics) as Arc<dyn MetricsCollector>
982    }
983
984    /// Snapshot of the `[observability.metrics].components` lever
985    /// (dashboard-observability Task 4.1): gates only the uniform
986    /// component-operations family offered through
987    /// `RuntimeObservability::component_metrics()`. Error-family
988    /// emission is never lever-gated, so it is not part of this flag.
989    fn component_metrics_enabled(&self) -> bool {
990        self.metrics_levers.components_enabled()
991    }
992
993    fn health(&self) -> Arc<dyn camel_component_api::HealthCheckRegistry> {
994        // The concrete HealthCheckRegistry struct implements the trait via
995        // the impl added in health_registry.rs.
996        Arc::clone(&self.health_registry) as Arc<dyn camel_component_api::HealthCheckRegistry>
997    }
998
999    fn platform_service(&self) -> Arc<dyn PlatformService> {
1000        Arc::clone(&self.platform_service)
1001    }
1002
1003    fn register_route_health_check(
1004        &self,
1005        route_id: &str,
1006        check: Arc<dyn camel_api::AsyncHealthCheck>,
1007    ) {
1008        self.health_registry.register_for_route(route_id, check);
1009    }
1010
1011    fn unregister_route_health_check(&self, route_id: &str) {
1012        self.health_registry.unregister_for_route(route_id);
1013    }
1014}
1015
1016#[async_trait::async_trait]
1017impl camel_api::HealthSource for CamelContext {
1018    async fn liveness(&self) -> camel_api::HealthStatus {
1019        let has_failed = self
1020            .services
1021            .iter()
1022            .any(|s| s.status() == camel_api::ServiceStatus::Failed);
1023        if has_failed {
1024            camel_api::HealthStatus::Unhealthy
1025        } else {
1026            camel_api::HealthStatus::Healthy
1027        }
1028    }
1029
1030    async fn readiness(&self) -> camel_api::HealthStatus {
1031        let has_failed = self
1032            .services
1033            .iter()
1034            .any(|s| s.status() == camel_api::ServiceStatus::Failed);
1035        if has_failed {
1036            return camel_api::HealthStatus::Unhealthy;
1037        }
1038        let has_stopped = self
1039            .services
1040            .iter()
1041            .any(|s| s.status() == camel_api::ServiceStatus::Stopped);
1042        if has_stopped {
1043            return camel_api::HealthStatus::Degraded;
1044        }
1045        self.health_registry.check_all().await.status
1046    }
1047
1048    async fn health_report(&self) -> camel_api::HealthReport {
1049        let mut report = self.health_registry.check_all().await;
1050        let mut worst = report.status;
1051        for service in &self.services {
1052            let svc_status = service.status();
1053            let health = match svc_status {
1054                camel_api::ServiceStatus::Started => camel_api::HealthStatus::Healthy,
1055                camel_api::ServiceStatus::Stopped => camel_api::HealthStatus::Degraded,
1056                camel_api::ServiceStatus::Failed => camel_api::HealthStatus::Unhealthy,
1057                // Forward-safe fail-closed: an unknown future ServiceStatus keeps
1058                // the pod NotReady (no traffic) rather than guessing Degraded.
1059                _ => camel_api::HealthStatus::Unhealthy,
1060            };
1061            if matches!(worst, camel_api::HealthStatus::Healthy)
1062                && matches!(
1063                    health,
1064                    camel_api::HealthStatus::Degraded | camel_api::HealthStatus::Unhealthy
1065                )
1066            {
1067                worst = health;
1068            }
1069            if matches!(worst, camel_api::HealthStatus::Degraded)
1070                && matches!(health, camel_api::HealthStatus::Unhealthy)
1071            {
1072                worst = health;
1073            }
1074            report.services.push(camel_api::ServiceHealth {
1075                name: service.name().to_string(),
1076                status: svc_status,
1077                message: None,
1078            });
1079        }
1080        report.status = worst;
1081        report
1082    }
1083
1084    async fn startup(&self) -> camel_api::HealthStatus {
1085        camel_api::HealthStatus::Healthy
1086    }
1087}
1088
1089#[cfg(test)]
1090#[path = "context_tests.rs"]
1091mod context_tests;