Skip to main content

camel_core/
context.rs

1use std::any::{Any, TypeId};
2use std::collections::HashMap;
3use std::sync::Arc;
4use std::sync::atomic::{AtomicU64, Ordering};
5use tokio_util::sync::CancellationToken;
6use tracing::{info, warn};
7
8use camel_api::error_handler::ErrorHandlerConfig;
9use camel_api::{
10    CamelError, HealthReport, HealthStatus, Lifecycle, MetricsCollector, NoOpMetrics,
11    RuntimeCommandBus, RuntimeQueryBus, ServiceHealth, ServiceStatus, SupervisionConfig,
12};
13use camel_component_api::{Component, ComponentContext, ComponentRegistrar};
14use camel_language_api::Language;
15use camel_language_api::LanguageError;
16
17use crate::lifecycle::adapters::RuntimeExecutionAdapter;
18use crate::lifecycle::adapters::controller_actor::{
19    RouteControllerHandle, spawn_controller_actor, spawn_supervision_task,
20};
21use crate::lifecycle::adapters::route_controller::{
22    DefaultRouteController, SharedLanguageRegistry,
23};
24use crate::lifecycle::application::route_definition::RouteDefinition;
25use crate::lifecycle::application::runtime_bus::RuntimeBus;
26use crate::shared::components::domain::Registry;
27use crate::shared::observability::domain::TracerConfig;
28
29static CONTEXT_COMMAND_SEQ: AtomicU64 = AtomicU64::new(0);
30
31pub struct CamelContextBuilder {
32    registry: Option<Arc<std::sync::Mutex<Registry>>>,
33    languages: Option<SharedLanguageRegistry>,
34    metrics: Option<Arc<dyn MetricsCollector>>,
35    supervision_config: Option<SupervisionConfig>,
36    runtime_store: Option<crate::lifecycle::adapters::InMemoryRuntimeStore>,
37    shutdown_timeout: std::time::Duration,
38}
39
40/// The CamelContext is the runtime engine that manages components, routes, and their lifecycle.
41///
42/// # Lifecycle
43///
44/// A `CamelContext` is single-use: call [`start()`](Self::start) once to launch routes,
45/// then [`stop()`](Self::stop) or [`abort()`](Self::abort) to shut down. Restarting a
46/// stopped context is not supported — create a new instance instead.
47pub struct CamelContext {
48    registry: Arc<std::sync::Mutex<Registry>>,
49    route_controller: RouteControllerHandle,
50    _actor_join: tokio::task::JoinHandle<()>,
51    supervision_join: Option<tokio::task::JoinHandle<()>>,
52    runtime: Arc<RuntimeBus>,
53    cancel_token: CancellationToken,
54    metrics: Arc<dyn MetricsCollector>,
55    languages: SharedLanguageRegistry,
56    shutdown_timeout: std::time::Duration,
57    services: Vec<Box<dyn Lifecycle>>,
58    component_configs: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
59}
60
61/// Opaque handle for runtime side-effect execution operations.
62///
63/// This intentionally does not expose direct lifecycle mutation APIs to callers.
64#[derive(Clone)]
65pub struct RuntimeExecutionHandle {
66    controller: RouteControllerHandle,
67    runtime: Arc<RuntimeBus>,
68}
69
70impl RuntimeExecutionHandle {
71    pub(crate) async fn add_route_definition(
72        &self,
73        definition: RouteDefinition,
74    ) -> Result<(), CamelError> {
75        use crate::lifecycle::ports::RouteRegistrationPort;
76        self.runtime.register_route(definition).await
77    }
78
79    pub(crate) async fn compile_route_definition(
80        &self,
81        definition: RouteDefinition,
82    ) -> Result<camel_api::BoxProcessor, CamelError> {
83        self.controller.compile_route_definition(definition).await
84    }
85
86    pub(crate) async fn swap_route_pipeline(
87        &self,
88        route_id: &str,
89        pipeline: camel_api::BoxProcessor,
90    ) -> Result<(), CamelError> {
91        self.controller.swap_pipeline(route_id, pipeline).await
92    }
93
94    pub(crate) async fn execute_runtime_command(
95        &self,
96        cmd: camel_api::RuntimeCommand,
97    ) -> Result<camel_api::RuntimeCommandResult, CamelError> {
98        self.runtime.execute(cmd).await
99    }
100
101    pub(crate) async fn runtime_route_status(
102        &self,
103        route_id: &str,
104    ) -> Result<Option<String>, CamelError> {
105        match self
106            .runtime
107            .ask(camel_api::RuntimeQuery::GetRouteStatus {
108                route_id: route_id.to_string(),
109            })
110            .await
111        {
112            Ok(camel_api::RuntimeQueryResult::RouteStatus { status, .. }) => Ok(Some(status)),
113            Ok(_) => Err(CamelError::RouteError(
114                "unexpected runtime query response for route status".to_string(),
115            )),
116            Err(CamelError::RouteError(msg)) if msg.contains("not found") => Ok(None),
117            Err(err) => Err(err),
118        }
119    }
120
121    pub(crate) async fn runtime_route_ids(&self) -> Result<Vec<String>, CamelError> {
122        match self.runtime.ask(camel_api::RuntimeQuery::ListRoutes).await {
123            Ok(camel_api::RuntimeQueryResult::Routes { route_ids }) => Ok(route_ids),
124            Ok(_) => Err(CamelError::RouteError(
125                "unexpected runtime query response for route listing".to_string(),
126            )),
127            Err(err) => Err(err),
128        }
129    }
130
131    pub(crate) async fn route_source_hash(&self, route_id: &str) -> Option<u64> {
132        self.controller.route_source_hash(route_id).await
133    }
134
135    pub(crate) async fn in_flight_count(&self, route_id: &str) -> Result<u64, CamelError> {
136        if !self.controller.route_exists(route_id).await? {
137            return Err(CamelError::RouteError(format!(
138                "Route '{}' not found",
139                route_id
140            )));
141        }
142        Ok(self
143            .controller
144            .in_flight_count(route_id)
145            .await?
146            .unwrap_or(0))
147    }
148
149    #[cfg(test)]
150    pub(crate) async fn force_start_route_for_test(
151        &self,
152        route_id: &str,
153    ) -> Result<(), CamelError> {
154        self.controller.start_route(route_id).await
155    }
156
157    #[cfg(test)]
158    pub(crate) async fn controller_route_count_for_test(&self) -> usize {
159        self.controller.route_count().await.unwrap_or(0)
160    }
161}
162
163impl CamelContext {
164    fn built_in_languages() -> SharedLanguageRegistry {
165        let mut languages: HashMap<String, Arc<dyn Language>> = HashMap::new();
166        languages.insert(
167            "simple".to_string(),
168            Arc::new(camel_language_simple::SimpleLanguage),
169        );
170        #[cfg(feature = "lang-js")]
171        {
172            let js_lang = camel_language_js::JsLanguage::new();
173            languages.insert("js".to_string(), Arc::new(js_lang.clone()));
174            languages.insert("javascript".to_string(), Arc::new(js_lang));
175        }
176        #[cfg(feature = "lang-rhai")]
177        {
178            let rhai_lang = camel_language_rhai::RhaiLanguage::new();
179            languages.insert("rhai".to_string(), Arc::new(rhai_lang));
180        }
181        #[cfg(feature = "lang-jsonpath")]
182        {
183            languages.insert(
184                "jsonpath".to_string(),
185                Arc::new(camel_language_jsonpath::JsonPathLanguage),
186            );
187        }
188        #[cfg(feature = "lang-xpath")]
189        {
190            languages.insert(
191                "xpath".to_string(),
192                Arc::new(camel_language_xpath::XPathLanguage),
193            );
194        }
195        Arc::new(std::sync::Mutex::new(languages))
196    }
197
198    fn build_runtime(
199        controller: RouteControllerHandle,
200        store: crate::lifecycle::adapters::InMemoryRuntimeStore,
201    ) -> Arc<RuntimeBus> {
202        let execution = Arc::new(RuntimeExecutionAdapter::new(controller));
203        Arc::new(
204            RuntimeBus::new(
205                Arc::new(store.clone()),
206                Arc::new(store.clone()),
207                Arc::new(store.clone()),
208                Arc::new(store.clone()),
209            )
210            .with_uow(Arc::new(store))
211            .with_execution(execution),
212        )
213    }
214
215    pub fn builder() -> CamelContextBuilder {
216        CamelContextBuilder::new()
217    }
218
219    /// Set a global error handler applied to all routes without a per-route handler.
220    pub async fn set_error_handler(&mut self, config: ErrorHandlerConfig) {
221        let _ = self.route_controller.set_error_handler(config).await;
222    }
223
224    /// Enable or disable tracing globally.
225    pub async fn set_tracing(&mut self, enabled: bool) {
226        let _ = self
227            .route_controller
228            .set_tracer_config(TracerConfig {
229                enabled,
230                ..Default::default()
231            })
232            .await;
233    }
234
235    /// Configure tracing with full config.
236    pub async fn set_tracer_config(&mut self, config: TracerConfig) {
237        // Inject metrics collector if not already set
238        let config = if config.metrics_collector.is_none() {
239            TracerConfig {
240                metrics_collector: Some(Arc::clone(&self.metrics)),
241                ..config
242            }
243        } else {
244            config
245        };
246
247        let _ = self.route_controller.set_tracer_config(config).await;
248    }
249
250    /// Builder-style: enable tracing with default config.
251    pub async fn with_tracing(mut self) -> Self {
252        self.set_tracing(true).await;
253        self
254    }
255
256    /// Builder-style: configure tracing with custom config.
257    /// Note: tracing subscriber initialization (stdout/file output) is handled
258    /// separately via init_tracing_subscriber (called in camel-config bridge).
259    pub async fn with_tracer_config(mut self, config: TracerConfig) -> Self {
260        self.set_tracer_config(config).await;
261        self
262    }
263
264    /// Register a lifecycle service (Apache Camel: addService pattern)
265    pub fn with_lifecycle<L: Lifecycle + 'static>(mut self, service: L) -> Self {
266        // Auto-register MetricsCollector if available
267        if let Some(collector) = service.as_metrics_collector() {
268            self.metrics = collector;
269        }
270
271        self.services.push(Box::new(service));
272        self
273    }
274
275    /// Register a component with this context.
276    pub fn register_component<C: Component + 'static>(&mut self, component: C) {
277        info!(scheme = component.scheme(), "Registering component");
278        self.registry
279            .lock()
280            .expect("mutex poisoned: another thread panicked while holding this lock")
281            .register(Arc::new(component));
282    }
283
284    /// Register a language with this context, keyed by name.
285    ///
286    /// Returns `Err(LanguageError::AlreadyRegistered)` if a language with the
287    /// same name is already registered. Use [`resolve_language`](Self::resolve_language)
288    /// to check before registering, or choose a distinct name.
289    pub fn register_language(
290        &mut self,
291        name: impl Into<String>,
292        lang: Box<dyn Language>,
293    ) -> Result<(), LanguageError> {
294        let name = name.into();
295        let mut languages = self
296            .languages
297            .lock()
298            .expect("mutex poisoned: another thread panicked while holding this lock");
299        if languages.contains_key(&name) {
300            return Err(LanguageError::AlreadyRegistered(name));
301        }
302        languages.insert(name, Arc::from(lang));
303        Ok(())
304    }
305
306    /// Resolve a language by name. Returns `None` if not registered.
307    pub fn resolve_language(&self, name: &str) -> Option<Arc<dyn Language>> {
308        let languages = self
309            .languages
310            .lock()
311            .expect("mutex poisoned: another thread panicked while holding this lock");
312        languages.get(name).cloned()
313    }
314
315    /// Add a route definition to this context.
316    ///
317    /// The route must have an ID. Steps are resolved immediately using registered components.
318    pub async fn add_route_definition(
319        &self,
320        definition: RouteDefinition,
321    ) -> Result<(), CamelError> {
322        use crate::lifecycle::ports::RouteRegistrationPort;
323        info!(
324            from = definition.from_uri(),
325            route_id = %definition.route_id(),
326            "Adding route definition"
327        );
328        self.runtime.register_route(definition).await
329    }
330
331    fn next_context_command_id(op: &str, route_id: &str) -> String {
332        let seq = CONTEXT_COMMAND_SEQ.fetch_add(1, Ordering::Relaxed);
333        format!("context:{op}:{route_id}:{seq}")
334    }
335
336    /// Access the component registry.
337    pub fn registry(&self) -> std::sync::MutexGuard<'_, Registry> {
338        self.registry
339            .lock()
340            .expect("mutex poisoned: another thread panicked while holding this lock")
341    }
342
343    /// Get runtime execution handle for file-watcher integrations.
344    pub fn runtime_execution_handle(&self) -> RuntimeExecutionHandle {
345        RuntimeExecutionHandle {
346            controller: self.route_controller.clone(),
347            runtime: Arc::clone(&self.runtime),
348        }
349    }
350
351    /// Get the metrics collector.
352    pub fn metrics(&self) -> Arc<dyn MetricsCollector> {
353        Arc::clone(&self.metrics)
354    }
355
356    /// Get runtime command/query bus handle.
357    pub fn runtime(&self) -> Arc<dyn camel_api::RuntimeHandle> {
358        self.runtime.clone()
359    }
360
361    /// Build a producer context wired to this runtime.
362    pub fn producer_context(&self) -> camel_api::ProducerContext {
363        camel_api::ProducerContext::new().with_runtime(self.runtime())
364    }
365
366    /// Query route status via runtime read-model.
367    pub async fn runtime_route_status(&self, route_id: &str) -> Result<Option<String>, CamelError> {
368        match self
369            .runtime()
370            .ask(camel_api::RuntimeQuery::GetRouteStatus {
371                route_id: route_id.to_string(),
372            })
373            .await
374        {
375            Ok(camel_api::RuntimeQueryResult::RouteStatus { status, .. }) => Ok(Some(status)),
376            Ok(_) => Err(CamelError::RouteError(
377                "unexpected runtime query response for route status".to_string(),
378            )),
379            Err(CamelError::RouteError(msg)) if msg.contains("not found") => Ok(None),
380            Err(err) => Err(err),
381        }
382    }
383
384    /// Start all routes. Each route's consumer will begin producing exchanges.
385    ///
386    /// Only routes with `auto_startup == true` will be started, in order of their
387    /// `startup_order` (lower values start first).
388    pub async fn start(&mut self) -> Result<(), CamelError> {
389        info!("Starting CamelContext");
390
391        // Start lifecycle services first
392        for (i, service) in self.services.iter_mut().enumerate() {
393            info!("Starting service: {}", service.name());
394            if let Err(e) = service.start().await {
395                // Rollback: stop already started services in reverse order
396                warn!(
397                    "Service {} failed to start, rolling back {} services",
398                    service.name(),
399                    i
400                );
401                for j in (0..i).rev() {
402                    if let Err(rollback_err) = self.services[j].stop().await {
403                        warn!(
404                            "Failed to stop service {} during rollback: {}",
405                            self.services[j].name(),
406                            rollback_err
407                        );
408                    }
409                }
410                return Err(e);
411            }
412        }
413
414        // Then start routes via runtime command bus (aggregate-first),
415        // preserving route controller startup ordering metadata.
416        let route_ids = self.route_controller.auto_startup_route_ids().await?;
417        for route_id in route_ids {
418            self.runtime
419                .execute(camel_api::RuntimeCommand::StartRoute {
420                    route_id: route_id.clone(),
421                    command_id: Self::next_context_command_id("start", &route_id),
422                    causation_id: None,
423                })
424                .await?;
425        }
426
427        info!("CamelContext started");
428        Ok(())
429    }
430
431    /// Graceful shutdown with default 30-second timeout.
432    pub async fn stop(&mut self) -> Result<(), CamelError> {
433        self.stop_timeout(self.shutdown_timeout).await
434    }
435
436    /// Graceful shutdown with custom timeout.
437    ///
438    /// Note: The timeout parameter is currently not used directly; the RouteController
439    /// manages its own shutdown timeout. This may change in a future version.
440    pub async fn stop_timeout(&mut self, _timeout: std::time::Duration) -> Result<(), CamelError> {
441        info!("Stopping CamelContext");
442
443        // Signal cancellation (for any legacy code that might use it)
444        self.cancel_token.cancel();
445        if let Some(join) = self.supervision_join.take() {
446            join.abort();
447        }
448
449        // Stop all routes via runtime command bus (aggregate-first),
450        // preserving route controller shutdown ordering metadata.
451        let route_ids = self.route_controller.shutdown_route_ids().await?;
452        for route_id in route_ids {
453            if let Err(err) = self
454                .runtime
455                .execute(camel_api::RuntimeCommand::StopRoute {
456                    route_id: route_id.clone(),
457                    command_id: Self::next_context_command_id("stop", &route_id),
458                    causation_id: None,
459                })
460                .await
461            {
462                warn!(route_id = %route_id, error = %err, "Runtime stop command failed during context shutdown");
463            }
464        }
465
466        // Then stop lifecycle services in reverse insertion order (LIFO)
467        // Continue stopping all services even if some fail
468        let mut first_error = None;
469        for service in self.services.iter_mut().rev() {
470            info!("Stopping service: {}", service.name());
471            if let Err(e) = service.stop().await {
472                warn!("Service {} failed to stop: {}", service.name(), e);
473                if first_error.is_none() {
474                    first_error = Some(e);
475                }
476            }
477        }
478
479        info!("CamelContext stopped");
480
481        if let Some(e) = first_error {
482            Err(e)
483        } else {
484            Ok(())
485        }
486    }
487
488    /// Get the graceful shutdown timeout used by [`stop()`](Self::stop).
489    pub fn shutdown_timeout(&self) -> std::time::Duration {
490        self.shutdown_timeout
491    }
492
493    /// Set the graceful shutdown timeout used by [`stop()`](Self::stop).
494    pub fn set_shutdown_timeout(&mut self, timeout: std::time::Duration) {
495        self.shutdown_timeout = timeout;
496    }
497
498    /// Immediate abort — kills all tasks without draining.
499    pub async fn abort(&mut self) {
500        self.cancel_token.cancel();
501        if let Some(join) = self.supervision_join.take() {
502            join.abort();
503        }
504        let route_ids = self
505            .route_controller
506            .shutdown_route_ids()
507            .await
508            .unwrap_or_default();
509        for route_id in route_ids {
510            let _ = self
511                .runtime
512                .execute(camel_api::RuntimeCommand::StopRoute {
513                    route_id: route_id.clone(),
514                    command_id: Self::next_context_command_id("abort-stop", &route_id),
515                    causation_id: None,
516                })
517                .await;
518        }
519    }
520
521    /// Check health status of all registered services.
522    pub fn health_check(&self) -> HealthReport {
523        let services: Vec<ServiceHealth> = self
524            .services
525            .iter()
526            .map(|s| ServiceHealth {
527                name: s.name().to_string(),
528                status: s.status(),
529            })
530            .collect();
531
532        let status = if services.iter().all(|s| s.status == ServiceStatus::Started) {
533            HealthStatus::Healthy
534        } else {
535            HealthStatus::Unhealthy
536        };
537
538        HealthReport {
539            status,
540            services,
541            ..Default::default()
542        }
543    }
544
545    /// Store a component config. Overwrites any previously stored config of the same type.
546    pub fn set_component_config<T: 'static + Send + Sync>(&mut self, config: T) {
547        self.component_configs
548            .insert(TypeId::of::<T>(), Box::new(config));
549    }
550
551    /// Retrieve a stored component config by type. Returns None if not stored.
552    pub fn get_component_config<T: 'static + Send + Sync>(&self) -> Option<&T> {
553        self.component_configs
554            .get(&TypeId::of::<T>())
555            .and_then(|b| b.downcast_ref::<T>())
556    }
557}
558
559impl ComponentRegistrar for CamelContext {
560    fn register_component_dyn(&mut self, component: Arc<dyn Component>) {
561        self.registry
562            .lock()
563            .expect("mutex poisoned: another thread panicked while holding this lock")
564            .register(component);
565    }
566}
567
568impl ComponentContext for CamelContext {
569    fn resolve_component(&self, scheme: &str) -> Option<Arc<dyn Component>> {
570        self.registry.lock().ok()?.get(scheme)
571    }
572
573    fn resolve_language(&self, name: &str) -> Option<Arc<dyn Language>> {
574        self.languages.lock().ok()?.get(name).cloned()
575    }
576
577    fn metrics(&self) -> Arc<dyn MetricsCollector> {
578        Arc::clone(&self.metrics)
579    }
580}
581
582impl CamelContextBuilder {
583    pub fn new() -> Self {
584        Self {
585            registry: None,
586            languages: None,
587            metrics: None,
588            supervision_config: None,
589            runtime_store: None,
590            shutdown_timeout: std::time::Duration::from_secs(30),
591        }
592    }
593
594    pub fn registry(mut self, registry: Arc<std::sync::Mutex<Registry>>) -> Self {
595        self.registry = Some(registry);
596        self
597    }
598
599    pub fn languages(mut self, languages: SharedLanguageRegistry) -> Self {
600        self.languages = Some(languages);
601        self
602    }
603
604    pub fn metrics(mut self, metrics: Arc<dyn MetricsCollector>) -> Self {
605        self.metrics = Some(metrics);
606        self
607    }
608
609    pub fn supervision(mut self, config: SupervisionConfig) -> Self {
610        self.supervision_config = Some(config);
611        self
612    }
613
614    pub fn runtime_store(
615        mut self,
616        store: crate::lifecycle::adapters::InMemoryRuntimeStore,
617    ) -> Self {
618        self.runtime_store = Some(store);
619        self
620    }
621
622    pub fn shutdown_timeout(mut self, timeout: std::time::Duration) -> Self {
623        self.shutdown_timeout = timeout;
624        self
625    }
626
627    pub async fn build(self) -> Result<CamelContext, CamelError> {
628        let registry = self
629            .registry
630            .unwrap_or_else(|| Arc::new(std::sync::Mutex::new(Registry::new())));
631        let languages = self
632            .languages
633            .unwrap_or_else(CamelContext::built_in_languages);
634        let metrics = self.metrics.unwrap_or_else(|| Arc::new(NoOpMetrics));
635
636        let (controller, actor_join, supervision_join) =
637            if let Some(config) = self.supervision_config {
638                let (crash_tx, crash_rx) = tokio::sync::mpsc::channel(64);
639                let mut controller_impl = DefaultRouteController::with_languages(
640                    Arc::clone(&registry),
641                    Arc::clone(&languages),
642                );
643                controller_impl.set_crash_notifier(crash_tx);
644                let (controller, actor_join) = spawn_controller_actor(controller_impl);
645                let supervision_join = spawn_supervision_task(
646                    controller.clone(),
647                    config,
648                    Some(Arc::clone(&metrics)),
649                    crash_rx,
650                );
651                (controller, actor_join, Some(supervision_join))
652            } else {
653                let controller_impl = DefaultRouteController::with_languages(
654                    Arc::clone(&registry),
655                    Arc::clone(&languages),
656                );
657                let (controller, actor_join) = spawn_controller_actor(controller_impl);
658                (controller, actor_join, None)
659            };
660
661        let store = self.runtime_store.unwrap_or_default();
662        let runtime = CamelContext::build_runtime(controller.clone(), store);
663        let runtime_handle: Arc<dyn camel_api::RuntimeHandle> = runtime.clone();
664        controller
665            .try_set_runtime_handle(runtime_handle)
666            .expect("controller actor mailbox should accept initial runtime handle");
667
668        Ok(CamelContext {
669            registry,
670            route_controller: controller,
671            _actor_join: actor_join,
672            supervision_join,
673            runtime,
674            cancel_token: CancellationToken::new(),
675            metrics,
676            languages,
677            shutdown_timeout: self.shutdown_timeout,
678            services: Vec::new(),
679            component_configs: HashMap::new(),
680        })
681    }
682}
683
684impl Default for CamelContextBuilder {
685    fn default() -> Self {
686        Self::new()
687    }
688}
689
690#[cfg(test)]
691#[path = "context_tests.rs"]
692mod context_tests;