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, InFlightGauge, Lifecycle, MetricsCollector,
13 MetricsHandle, PlatformIdentity, PlatformService, ReadinessGate, RouteTemplateSpec,
14 RuntimeCommandBus, 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
34pub 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 shutdown_token_slot: Arc<std::sync::Mutex<CancellationToken>>,
57 metrics: Arc<MetricsHandle>,
62 metrics_levers: MetricsLeversConfig,
68 platform_service: Arc<dyn PlatformService>,
70 languages: SharedLanguageRegistry,
71 shutdown_timeout: std::time::Duration,
72 drain_timeout: std::time::Duration,
76 services: Vec<Box<dyn Lifecycle>>,
77 health_registry: Arc<HealthCheckRegistry>,
78 component_configs: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
79 function_invoker: Option<Arc<dyn FunctionInvoker>>,
80 template_registry: Arc<TemplateRegistry>,
81 idempotent_repositories: crate::registry::SharedIdempotentRegistry,
82 claim_check_repositories: crate::registry::SharedClaimCheckRegistry,
83 cache_repositories: crate::registry::SharedCacheRegistry,
84 startup_checks: Vec<Box<dyn ConfigCheck>>,
88 build_version: &'static str,
92 build_git_sha: &'static str,
93 build_started_at: std::time::Instant,
95 in_flight_total: Arc<InFlightGauge>,
101}
102
103pub(crate) struct FromParts {
106 pub(crate) registry: Arc<std::sync::Mutex<Registry>>,
107 pub(crate) route_controller: RouteControllerHandle,
108 pub(crate) _actor_join: tokio::task::JoinHandle<()>,
109 pub(crate) supervision_join: Option<tokio::task::JoinHandle<()>>,
110 pub(crate) runtime: Arc<RuntimeBus>,
111 pub(crate) cancel_token: CancellationToken,
112 pub(crate) shutdown_token_slot: Arc<std::sync::Mutex<CancellationToken>>,
113 pub(crate) metrics: Arc<MetricsHandle>,
114 pub(crate) platform_service: Arc<dyn PlatformService>,
115 pub(crate) languages: SharedLanguageRegistry,
116 pub(crate) shutdown_timeout: std::time::Duration,
117 pub(crate) drain_timeout: std::time::Duration,
118 pub(crate) services: Vec<Box<dyn Lifecycle>>,
119 pub(crate) health_registry: Arc<HealthCheckRegistry>,
120 pub(crate) component_configs: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
121 pub(crate) function_invoker: Option<Arc<dyn FunctionInvoker>>,
122 pub(crate) template_registry: Arc<TemplateRegistry>,
123 pub(crate) idempotent_repositories: crate::registry::SharedIdempotentRegistry,
124 pub(crate) claim_check_repositories: crate::registry::SharedClaimCheckRegistry,
125 pub(crate) cache_repositories: crate::registry::SharedCacheRegistry,
126 pub(crate) startup_checks: Vec<Box<dyn ConfigCheck>>,
127 pub(crate) build_version: &'static str,
128 pub(crate) build_git_sha: &'static str,
129 pub(crate) build_started_at: std::time::Instant,
130 pub(crate) in_flight_total: Arc<InFlightGauge>,
131}
132
133impl CamelContext {
134 pub(crate) fn from_parts(parts: FromParts) -> Self {
135 Self {
136 registry: parts.registry,
137 route_controller: parts.route_controller,
138 actor_join: Some(parts._actor_join),
139 supervision_join: parts.supervision_join,
140 runtime: parts.runtime,
141 cancel_token: parts.cancel_token,
142 shutdown_token_slot: parts.shutdown_token_slot,
143 metrics: parts.metrics,
144 metrics_levers: MetricsLeversConfig::default(),
145 platform_service: parts.platform_service,
146 languages: parts.languages,
147 shutdown_timeout: parts.shutdown_timeout,
148 drain_timeout: parts.drain_timeout,
149 services: parts.services,
150 health_registry: parts.health_registry,
151 component_configs: parts.component_configs,
152 function_invoker: parts.function_invoker,
153 template_registry: parts.template_registry,
154 idempotent_repositories: parts.idempotent_repositories,
155 claim_check_repositories: parts.claim_check_repositories,
156 cache_repositories: parts.cache_repositories,
157 startup_checks: parts.startup_checks,
158 build_version: parts.build_version,
159 build_git_sha: parts.build_git_sha,
160 build_started_at: parts.build_started_at,
161 in_flight_total: parts.in_flight_total,
162 }
163 }
164}
165
166#[derive(Clone)]
170pub struct RuntimeExecutionHandle {
171 pub(crate) controller: RouteControllerHandle,
172 pub(crate) runtime: Arc<RuntimeBus>,
173 pub(crate) function_invoker: Option<Arc<dyn FunctionInvoker>>,
174 #[cfg(test)]
178 #[allow(clippy::type_complexity)]
179 pub(crate) test_lifecycle_inject: Arc<std::sync::Mutex<Option<Vec<Arc<dyn StepLifecycle>>>>>,
180}
181
182impl RuntimeExecutionHandle {
183 pub(crate) async fn add_route_definition(
184 &self,
185 definition: RouteDefinition,
186 ) -> Result<(), CamelError> {
187 use crate::lifecycle::application::ports::RouteRegistrationPort;
188 self.runtime
189 .register_route(definition)
190 .await
191 .map_err(Into::into)
192 }
193
194 #[allow(dead_code)]
197 pub(crate) async fn compile_route_definition(
198 &self,
199 definition: RouteDefinition,
200 ) -> Result<camel_api::BoxProcessor, CamelError> {
201 self.controller.compile_route_definition(definition).await
202 }
203
204 #[allow(dead_code)] pub(crate) async fn compile_route_definition_with_generation(
206 &self,
207 definition: RouteDefinition,
208 generation: u64,
209 ) -> Result<camel_api::BoxProcessor, CamelError> {
210 self.controller
211 .compile_route_definition_with_generation(definition, generation)
212 .await
213 }
214
215 pub(crate) async fn compile_route_definition_pipeline(
216 &self,
217 definition: RouteDefinition,
218 generation: u64,
219 ) -> Result<crate::lifecycle::domain::CompiledPipeline, CamelError> {
220 self.controller
221 .compile_route_definition_pipeline(definition, generation)
222 .await
223 }
224
225 pub(crate) async fn compile_route_definition_dry_pipeline(
228 &self,
229 definition: RouteDefinition,
230 ) -> Result<crate::lifecycle::domain::CompiledPipeline, CamelError> {
231 self.controller
232 .compile_route_definition_dry_pipeline(definition)
233 .await
234 }
235
236 pub(crate) async fn prepare_route_definition_with_generation(
237 &self,
238 definition: RouteDefinition,
239 generation: u64,
240 ) -> Result<crate::lifecycle::domain::route_compilation::PreparedRoute, CamelError> {
241 self.controller
242 .prepare_route_definition_with_generation(definition, generation)
243 .await
244 }
245
246 pub(crate) async fn insert_prepared_route(
247 &self,
248 prepared: crate::lifecycle::domain::route_compilation::PreparedRoute,
249 ) -> Result<(), CamelError> {
250 self.controller.insert_prepared_route(prepared).await
251 }
252
253 pub(crate) async fn discard_prepared_staging(&self, route_id: &str) -> Result<(), CamelError> {
254 self.controller.discard_prepared_staging(route_id).await
255 }
256
257 pub(crate) async fn remove_route_preserving_functions(
258 &self,
259 route_id: String,
260 ) -> Result<(), CamelError> {
261 self.controller
262 .remove_route_preserving_functions(route_id)
263 .await
264 }
265
266 pub(crate) async fn register_route_aggregate(
267 &self,
268 route_id: String,
269 ) -> Result<(), CamelError> {
270 self.runtime.register_aggregate_only(route_id).await
271 }
272
273 pub(crate) async fn swap_route_pipeline(
274 &self,
275 route_id: &str,
276 pipeline: camel_api::BoxProcessor,
277 ) -> Result<(), CamelError> {
278 self.controller.swap_pipeline(route_id, pipeline).await
279 }
280
281 pub(crate) async fn stop_route_reload(&self, route_id: &str) -> Result<(), CamelError> {
283 self.controller.stop_route_reload(route_id).await
284 }
285
286 pub(crate) async fn start_route_reload(&self, route_id: &str) -> Result<(), CamelError> {
288 self.controller.start_route_reload(route_id).await
289 }
290
291 pub(crate) async fn swap_route_pipeline_raw(
294 &self,
295 route_id: &str,
296 pipeline: camel_api::BoxProcessor,
297 lifecycle: Vec<Arc<dyn camel_api::StepLifecycle>>,
298 ) -> Result<(), CamelError> {
299 self.controller
300 .swap_pipeline_raw(route_id, pipeline, lifecycle)
301 .await
302 }
303
304 pub(crate) async fn execute_runtime_command(
305 &self,
306 cmd: camel_api::RuntimeCommand,
307 ) -> Result<camel_api::RuntimeCommandResult, CamelError> {
308 self.runtime.execute(cmd).await
309 }
310
311 pub(crate) async fn runtime_route_status(
312 &self,
313 route_id: &str,
314 ) -> Result<Option<String>, CamelError> {
315 match self
316 .runtime
317 .ask(camel_api::RuntimeQuery::GetRouteStatus {
318 route_id: route_id.to_string(),
319 })
320 .await
321 {
322 Ok(camel_api::RuntimeQueryResult::RouteStatus { status, .. }) => Ok(Some(status)),
323 Ok(_) => Err(CamelError::RouteError(
324 "unexpected runtime query response for route status".to_string(),
325 )),
326 Err(CamelError::RouteError(msg)) if msg.contains("not found") => Ok(None),
327 Err(err) => Err(err),
328 }
329 }
330
331 pub(crate) async fn runtime_route_ids(&self) -> Result<Vec<String>, CamelError> {
332 match self.runtime.ask(camel_api::RuntimeQuery::ListRoutes).await {
333 Ok(camel_api::RuntimeQueryResult::Routes { route_ids }) => Ok(route_ids),
334 Ok(_) => Err(CamelError::RouteError(
335 "unexpected runtime query response for route listing".to_string(),
336 )),
337 Err(err) => Err(err),
338 }
339 }
340
341 pub(crate) async fn route_source_hash(&self, route_id: &str) -> Option<u64> {
342 self.controller.route_source_hash(route_id).await
343 }
344
345 pub(crate) async fn in_flight_count(&self, route_id: &str) -> Result<u64, CamelError> {
346 if !self.controller.route_exists(route_id).await? {
347 return Err(CamelError::RouteError(format!(
348 "Route '{}' not found",
349 route_id
350 )));
351 }
352 Ok(self
353 .controller
354 .in_flight_count(route_id)
355 .await?
356 .unwrap_or(0))
357 }
358
359 pub(crate) async fn route_has_lifecycle(&self, route_id: &str) -> bool {
361 self.controller
362 .route_has_lifecycle(route_id)
363 .await
364 .unwrap_or(false)
365 }
366
367 pub(crate) fn function_invoker(&self) -> Option<Arc<dyn FunctionInvoker>> {
368 self.function_invoker.clone()
369 }
370
371 #[cfg(test)]
372 pub(crate) async fn force_start_route_for_test(
373 &self,
374 route_id: &str,
375 ) -> Result<(), CamelError> {
376 self.controller.start_route(route_id).await
377 }
378
379 pub async fn controller_route_count_for_test(&self) -> usize {
380 self.controller.route_count().await.unwrap_or(0)
381 }
382}
383
384#[async_trait::async_trait]
385impl crate::hot_reload::ports::ReloadExecutorPort for RuntimeExecutionHandle {
386 async fn add_route_definition(&self, definition: RouteDefinition) -> Result<(), CamelError> {
387 RuntimeExecutionHandle::add_route_definition(self, definition).await
388 }
389
390 async fn compile_route_definition_pipeline(
391 &self,
392 definition: RouteDefinition,
393 generation: u64,
394 ) -> Result<crate::lifecycle::domain::CompiledPipeline, CamelError> {
395 RuntimeExecutionHandle::compile_route_definition_pipeline(self, definition, generation)
396 .await
397 }
398
399 async fn compile_route_definition_dry_pipeline(
400 &self,
401 definition: RouteDefinition,
402 ) -> Result<crate::lifecycle::domain::CompiledPipeline, CamelError> {
403 RuntimeExecutionHandle::compile_route_definition_dry_pipeline(self, definition).await
404 }
405
406 async fn prepare_route_definition_with_generation(
407 &self,
408 definition: RouteDefinition,
409 generation: u64,
410 ) -> Result<crate::lifecycle::domain::route_compilation::PreparedRoute, CamelError> {
411 RuntimeExecutionHandle::prepare_route_definition_with_generation(
412 self, definition, generation,
413 )
414 .await
415 }
416
417 async fn insert_prepared_route(
418 &self,
419 prepared: crate::lifecycle::domain::route_compilation::PreparedRoute,
420 ) -> Result<(), CamelError> {
421 RuntimeExecutionHandle::insert_prepared_route(self, prepared).await
422 }
423
424 async fn discard_prepared_staging(&self, route_id: &str) -> Result<(), CamelError> {
425 RuntimeExecutionHandle::discard_prepared_staging(self, route_id).await
426 }
427
428 async fn remove_route_preserving_functions(&self, route_id: String) -> Result<(), CamelError> {
429 RuntimeExecutionHandle::remove_route_preserving_functions(self, route_id).await
430 }
431
432 async fn register_route_aggregate(&self, route_id: String) -> Result<(), CamelError> {
433 RuntimeExecutionHandle::register_route_aggregate(self, route_id).await
434 }
435
436 async fn swap_route_pipeline(
437 &self,
438 route_id: &str,
439 pipeline: camel_api::BoxProcessor,
440 ) -> Result<(), CamelError> {
441 RuntimeExecutionHandle::swap_route_pipeline(self, route_id, pipeline).await
442 }
443
444 async fn stop_route_reload(&self, route_id: &str) -> Result<(), CamelError> {
445 RuntimeExecutionHandle::stop_route_reload(self, route_id).await
446 }
447
448 async fn start_route_reload(&self, route_id: &str) -> Result<(), CamelError> {
449 RuntimeExecutionHandle::start_route_reload(self, route_id).await
450 }
451
452 async fn swap_route_pipeline_raw(
453 &self,
454 route_id: &str,
455 pipeline: camel_api::BoxProcessor,
456 lifecycle: Vec<std::sync::Arc<dyn camel_api::StepLifecycle>>,
457 ) -> Result<(), CamelError> {
458 RuntimeExecutionHandle::swap_route_pipeline_raw(self, route_id, pipeline, lifecycle).await
459 }
460
461 async fn execute_runtime_command(
462 &self,
463 cmd: camel_api::RuntimeCommand,
464 ) -> Result<camel_api::RuntimeCommandResult, CamelError> {
465 RuntimeExecutionHandle::execute_runtime_command(self, cmd).await
466 }
467
468 async fn runtime_route_status(&self, route_id: &str) -> Result<Option<String>, CamelError> {
469 RuntimeExecutionHandle::runtime_route_status(self, route_id).await
470 }
471
472 async fn in_flight_count(&self, route_id: &str) -> Result<u64, CamelError> {
473 RuntimeExecutionHandle::in_flight_count(self, route_id).await
474 }
475
476 async fn route_has_lifecycle(&self, route_id: &str) -> bool {
477 RuntimeExecutionHandle::route_has_lifecycle(self, route_id).await
478 }
479
480 #[cfg(test)]
481 fn take_test_lifecycle_inject(
482 &self,
483 ) -> Option<Vec<std::sync::Arc<dyn camel_api::StepLifecycle>>> {
484 self.test_lifecycle_inject.lock().unwrap().take()
485 }
486}
487
488impl CamelContext {
489 pub fn builder() -> CamelContextBuilder {
490 CamelContextBuilder::new()
491 }
492
493 pub async fn set_error_handler(&mut self, config: ErrorHandlerConfig) {
495 let _ = self.route_controller.set_error_handler(config).await;
496 }
497
498 pub async fn set_bind_exposure_acks(
502 &mut self,
503 acks: crate::lifecycle::adapters::route_controller_trait::BindExposureAcks,
504 ) {
505 let _ = self.route_controller.set_bind_exposure_acks(acks).await;
506 }
507
508 pub async fn set_tracing(&mut self, enabled: bool) {
510 let config = TracerConfig {
511 enabled,
512 ..Default::default()
513 };
514 self.metrics_levers = config.metrics_levers.clone();
517 let _ = self.route_controller.set_tracer_config(config).await;
518 }
519
520 pub async fn set_tracer_config(&mut self, config: TracerConfig) {
522 self.metrics_levers = config.metrics_levers.clone();
525 let _ = self.route_controller.set_tracer_config(config).await;
526 }
527
528 pub async fn with_tracing(mut self) -> Self {
530 self.set_tracing(true).await;
531 self
532 }
533
534 pub async fn with_tracer_config(mut self, config: TracerConfig) -> Self {
538 self.set_tracer_config(config).await;
539 self
540 }
541
542 pub fn with_lifecycle<L: Lifecycle + 'static>(mut self, service: L) -> Self {
551 self.add_lifecycle(service);
552 self
553 }
554
555 pub fn add_lifecycle<L: Lifecycle + 'static>(&mut self, service: L) {
560 if let Some(collector) = service.as_metrics_collector() {
561 self.metrics.register(collector);
565 self.metrics
570 .record_build_info(self.build_version, self.build_git_sha);
571 self.metrics
572 .record_uptime(self.build_started_at.elapsed().as_secs_f64());
573 }
574 if let Some(invoker) = service.as_function_invoker() {
575 self.function_invoker = Some(invoker.clone());
576 if let Err(e) = self.route_controller.try_set_function_invoker(invoker) {
577 tracing::debug!("Failed to propagate function invoker to route controller: {e}");
578 }
579 }
580
581 self.services.push(Box::new(service));
582 }
583
584 pub fn register_component<C: Component + 'static>(&mut self, component: C) {
590 self.register_component_dyn(Arc::new(component));
591 }
592
593 pub async fn set_intercept_rules(&self, rules: InterceptRules) -> Result<(), CamelError> {
600 self.route_controller.set_intercept_rules(rules).await
601 }
602
603 pub fn add_startup_check(&mut self, check: Box<dyn ConfigCheck>) {
612 self.startup_checks.push(check);
613 }
614
615 pub fn register_language(
622 &mut self,
623 name: impl Into<String>,
624 lang: Box<dyn Language>,
625 ) -> Result<(), LanguageRegistryError> {
626 let name = name.into();
627 let mut languages = self
628 .languages
629 .lock()
630 .expect("mutex poisoned: another thread panicked while holding this lock"); if languages.contains_key(&name) {
632 return Err(LanguageRegistryError::AlreadyRegistered { name });
633 }
634 languages.insert(name, Arc::from(lang));
635 Ok(())
636 }
637
638 pub fn resolve_language(&self, name: &str) -> Option<Arc<dyn Language>> {
640 let languages = self
641 .languages
642 .lock()
643 .expect("mutex poisoned: another thread panicked while holding this lock"); languages.get(name).cloned()
645 }
646
647 pub async fn add_route_definition(
651 &self,
652 definition: RouteDefinition,
653 ) -> Result<(), CamelError> {
654 use crate::lifecycle::application::ports::RouteRegistrationPort;
655 debug!(
656 from = definition.from_uri(),
657 route_id = %definition.route_id(),
658 "Adding route definition"
659 );
660 self.runtime
661 .register_route(definition)
662 .await
663 .map_err(Into::into)
664 }
665
666 pub fn registry(&self) -> std::sync::MutexGuard<'_, Registry> {
668 self.registry
669 .lock()
670 .expect("mutex poisoned: another thread panicked while holding this lock") }
672
673 pub fn registry_arc(&self) -> Arc<std::sync::Mutex<Registry>> {
675 Arc::clone(&self.registry)
676 }
677
678 pub fn runtime_execution_handle(&self) -> RuntimeExecutionHandle {
680 RuntimeExecutionHandle {
681 controller: self.route_controller.clone(),
682 runtime: Arc::clone(&self.runtime),
683 function_invoker: self.function_invoker.clone(),
684 #[cfg(test)]
685 test_lifecycle_inject: Arc::new(std::sync::Mutex::new(None)),
686 }
687 }
688
689 pub fn metrics(&self) -> Arc<dyn MetricsCollector> {
691 Arc::clone(&self.metrics) as Arc<dyn MetricsCollector>
692 }
693
694 pub fn total_in_flight(&self) -> u64 {
704 self.in_flight_total.total()
705 }
706
707 pub fn in_flight_gauge(&self) -> Arc<InFlightGauge> {
711 Arc::clone(&self.in_flight_total)
712 }
713
714 pub fn platform_service(&self) -> Arc<dyn PlatformService> {
716 Arc::clone(&self.platform_service)
717 }
718
719 pub fn readiness_gate(&self) -> Arc<dyn ReadinessGate> {
721 self.platform_service.readiness_gate()
722 }
723
724 pub fn platform_identity(&self) -> PlatformIdentity {
726 self.platform_service.identity()
727 }
728
729 pub fn leadership(&self) -> Arc<dyn camel_api::LeadershipService> {
731 self.platform_service.leadership()
732 }
733
734 pub fn runtime(&self) -> Arc<dyn camel_api::RuntimeHandle> {
736 self.runtime.clone()
737 }
738
739 pub fn transaction_registry(&self) -> Arc<crate::TransactionManagerRegistry> {
747 self.runtime.transaction_registry()
748 }
749
750 pub fn register_transaction_manager(
756 &self,
757 datasource: impl Into<String>,
758 manager: Arc<dyn camel_api::TransactionManager>,
759 ) -> Result<(), crate::RegistryError> {
760 self.runtime
761 .register_transaction_manager(datasource, manager)
762 }
763
764 pub fn install_datasource_catalog(
770 &self,
771 catalog: Arc<dyn camel_api::datasource::DatasourceCatalog>,
772 ) -> Result<(), CamelError> {
773 self.runtime.install_datasource_catalog(catalog)
774 }
775
776 pub fn producer_context(&self) -> camel_api::ProducerContext {
778 camel_api::ProducerContext::new().with_runtime(self.runtime())
779 }
780
781 pub async fn runtime_route_status(&self, route_id: &str) -> Result<Option<String>, CamelError> {
783 match self
784 .runtime()
785 .ask(camel_api::RuntimeQuery::GetRouteStatus {
786 route_id: route_id.to_string(),
787 })
788 .await
789 {
790 Ok(camel_api::RuntimeQueryResult::RouteStatus { status, .. }) => Ok(Some(status)),
791 Ok(_) => Err(CamelError::RouteError(
792 "unexpected runtime query response for route status".to_string(),
793 )),
794 Err(CamelError::RouteError(msg)) if msg.contains("not found") => Ok(None),
795 Err(err) => Err(err),
796 }
797 }
798
799 pub async fn start(&mut self) -> Result<(), CamelError> {
807 crate::lifecycle::application::context_lifecycle::start_context(
808 &mut self.services,
809 &mut self.startup_checks,
810 &self.runtime,
811 &self.route_controller,
812 &mut self.cancel_token,
813 &self.shutdown_token_slot,
814 )
815 .await?;
816 self.route_controller.mark_started().await
820 }
821
822 pub async fn stop(&mut self) -> Result<(), CamelError> {
824 self.stop_timeout(self.shutdown_timeout).await
825 }
826
827 pub async fn stop_timeout(&mut self, _timeout: std::time::Duration) -> Result<(), CamelError> {
837 crate::lifecycle::application::context_lifecycle::stop_context(
838 &self.cancel_token,
839 &mut self.supervision_join,
840 &self.runtime,
841 &self.route_controller,
842 &mut self.services,
843 self.drain_timeout,
844 )
845 .await
846 }
847
848 pub fn shutdown_timeout(&self) -> std::time::Duration {
850 self.shutdown_timeout
851 }
852
853 pub fn set_shutdown_timeout(&mut self, timeout: std::time::Duration) {
855 self.shutdown_timeout = timeout;
856 }
857
858 pub fn drain_timeout(&self) -> std::time::Duration {
862 self.drain_timeout
863 }
864
865 pub fn set_drain_timeout(&mut self, timeout: std::time::Duration) {
868 self.drain_timeout = timeout;
869 }
870
871 #[cfg(test)]
874 pub(crate) fn take_actor_join(&mut self) -> Option<tokio::task::JoinHandle<()>> {
875 self.actor_join.take()
876 }
877
878 pub async fn abort(&mut self) {
886 crate::lifecycle::application::context_lifecycle::abort_context(
887 &self.cancel_token,
888 &mut self.supervision_join,
889 &self.runtime,
890 &self.route_controller as &dyn crate::lifecycle::application::ports::RouteOrderingPort,
891 &self.route_controller
892 as &dyn crate::lifecycle::application::ports::RouteDestructiveTeardownPort,
893 &mut self.services,
894 self.health_registry.cancel_token(),
895 &mut self.actor_join,
896 )
897 .await
898 }
899
900 pub async fn health_check(&self) -> HealthReport {
902 use camel_api::HealthSource;
903 self.health_report().await
904 }
905
906 pub fn health_registry(&self) -> Arc<HealthCheckRegistry> {
907 Arc::clone(&self.health_registry)
908 }
909
910 pub fn set_component_config<T: 'static + Send + Sync>(&mut self, config: T) {
912 self.component_configs
913 .insert(TypeId::of::<T>(), Box::new(config));
914 }
915
916 pub fn get_component_config<T: 'static + Send + Sync>(&self) -> Option<&T> {
918 self.component_configs
919 .get(&TypeId::of::<T>())
920 .and_then(|b| b.downcast_ref::<T>())
921 }
922
923 pub fn component_metadata(&self, scheme: &str) -> Option<ComponentMetadata> {
927 self.registry.lock().ok()?.get_metadata(scheme)
928 }
929
930 pub fn all_component_metadata(&self) -> Vec<ComponentMetadata> {
932 self.registry
933 .lock()
934 .expect("mutex poisoned: another thread panicked while holding this lock") .all_metadata()
936 }
937
938 pub fn metadata_catalog(
945 &self,
946 ) -> crate::component_metadata_catalog::RuntimeComponentMetadataCatalog {
947 crate::component_metadata_catalog::RuntimeComponentMetadataCatalog::new(Arc::clone(
948 &self.registry,
949 ))
950 }
951
952 pub fn add_route_template(&self, spec: RouteTemplateSpec) -> Result<(), CamelError> {
958 self.template_registry.register(spec)
959 }
960
961 pub fn get_route_template(&self, id: &str) -> Option<RouteTemplateSpec> {
963 self.template_registry.get(id)
964 }
965
966 pub fn template_ids(&self) -> Vec<String> {
968 self.template_registry.template_ids()
969 }
970
971 pub fn record_template_instance(&self, record: TemplateInstanceRecord) {
973 self.template_registry.record_instance(record)
974 }
975
976 pub fn template_instances(&self, template_id: &str) -> Vec<TemplateInstanceRecord> {
978 self.template_registry.instances(template_id)
979 }
980
981 pub fn register_idempotent_repository(
988 &mut self,
989 name: impl Into<String>,
990 repo: Arc<dyn camel_api::IdempotentRepository>,
991 ) -> Result<(), RegistryError> {
992 self.idempotent_repositories.register(name, repo)
993 }
994
995 pub fn idempotent_repository(
997 &self,
998 name: &str,
999 ) -> Option<Arc<dyn camel_api::IdempotentRepository>> {
1000 self.idempotent_repositories.get(name)
1001 }
1002
1003 pub fn register_claim_check_repository(
1010 &mut self,
1011 name: impl Into<String>,
1012 repo: Arc<dyn camel_api::ClaimCheckRepository>,
1013 ) -> Result<(), RegistryError> {
1014 self.claim_check_repositories.register(name, repo)
1015 }
1016
1017 pub fn claim_check_repository(
1019 &self,
1020 name: &str,
1021 ) -> Option<Arc<dyn camel_api::ClaimCheckRepository>> {
1022 self.claim_check_repositories.get(name)
1023 }
1024
1025 pub fn register_cache_repository(
1032 &mut self,
1033 name: impl Into<String>,
1034 repo: Arc<dyn camel_api::CacheRepository>,
1035 ) -> Result<(), RegistryError> {
1036 self.cache_repositories.register(name, repo)
1037 }
1038
1039 pub fn replace_cache_repository(
1043 &mut self,
1044 name: impl Into<String>,
1045 repo: Arc<dyn camel_api::CacheRepository>,
1046 ) -> Option<Arc<dyn camel_api::CacheRepository>> {
1047 self.cache_repositories.register_or_replace(name, repo)
1048 }
1049
1050 pub fn cache_repository(&self, name: &str) -> Option<Arc<dyn camel_api::CacheRepository>> {
1052 self.cache_repositories.get(name)
1053 }
1054
1055 pub fn shutdown_token(&self) -> CancellationToken {
1060 self.cancel_token.clone()
1061 }
1062
1063 pub fn shutdown_token_slot(&self) -> Arc<std::sync::Mutex<CancellationToken>> {
1074 Arc::clone(&self.shutdown_token_slot)
1075 }
1076}
1077
1078impl Drop for CamelContext {
1091 fn drop(&mut self) {
1092 if let Some(handle) = self.actor_join.take() {
1093 handle.abort();
1094 }
1095 if let Some(handle) = self.supervision_join.take() {
1096 handle.abort();
1097 }
1098 }
1099}
1100
1101impl ComponentRegistrar for CamelContext {
1102 fn register_component_dyn(&mut self, component: Arc<dyn Component>) {
1103 let scheme = component.scheme().to_string();
1104 self.registry
1105 .lock()
1106 .expect("mutex poisoned: another thread panicked while holding this lock") .register(component);
1108 trace!(scheme, "Registered component");
1109 }
1110}
1111
1112impl ComponentContext for CamelContext {
1113 fn resolve_component(&self, scheme: &str) -> Option<Arc<dyn Component>> {
1114 self.registry.lock().ok()?.get(scheme)
1115 }
1116
1117 fn resolve_language(&self, name: &str) -> Option<Arc<dyn Language>> {
1118 self.languages.lock().ok()?.get(name).cloned()
1119 }
1120
1121 fn metrics(&self) -> Arc<dyn MetricsCollector> {
1122 Arc::clone(&self.metrics) as Arc<dyn MetricsCollector>
1123 }
1124
1125 fn component_metric_levers(&self) -> camel_api::ComponentMetricsLevers {
1131 self.metrics_levers.component_metrics_levers()
1132 }
1133
1134 fn health(&self) -> Arc<dyn camel_component_api::HealthCheckRegistry> {
1135 Arc::clone(&self.health_registry) as Arc<dyn camel_component_api::HealthCheckRegistry>
1138 }
1139
1140 fn platform_service(&self) -> Arc<dyn PlatformService> {
1141 Arc::clone(&self.platform_service)
1142 }
1143
1144 fn register_route_health_check(
1145 &self,
1146 route_id: &str,
1147 check: Arc<dyn camel_api::AsyncHealthCheck>,
1148 ) {
1149 self.health_registry.register_for_route(route_id, check);
1150 }
1151
1152 fn unregister_route_health_check(&self, route_id: &str) {
1153 self.health_registry.unregister_for_route(route_id);
1154 }
1155
1156 fn in_flight_counter(&self) -> Option<Arc<InFlightGauge>> {
1160 Some(Arc::clone(&self.in_flight_total))
1161 }
1162
1163 fn shutdown_token(&self) -> Option<CancellationToken> {
1167 Some(CamelContext::shutdown_token(self))
1168 }
1169}
1170
1171#[async_trait::async_trait]
1172impl camel_api::HealthSource for CamelContext {
1173 async fn liveness(&self) -> camel_api::HealthStatus {
1174 let has_failed = self
1175 .services
1176 .iter()
1177 .any(|s| s.status() == camel_api::ServiceStatus::Failed);
1178 if has_failed {
1179 camel_api::HealthStatus::Unhealthy
1180 } else {
1181 camel_api::HealthStatus::Healthy
1182 }
1183 }
1184
1185 async fn readiness(&self) -> camel_api::HealthStatus {
1186 let has_failed = self
1187 .services
1188 .iter()
1189 .any(|s| s.status() == camel_api::ServiceStatus::Failed);
1190 if has_failed {
1191 return camel_api::HealthStatus::Unhealthy;
1192 }
1193 let has_stopped = self
1194 .services
1195 .iter()
1196 .any(|s| s.status() == camel_api::ServiceStatus::Stopped);
1197 if has_stopped {
1198 return camel_api::HealthStatus::Degraded;
1199 }
1200 self.health_registry.check_all().await.status
1201 }
1202
1203 async fn health_report(&self) -> camel_api::HealthReport {
1204 let mut report = self.health_registry.check_all().await;
1205 let mut worst = report.status;
1206 for service in &self.services {
1207 let svc_status = service.status();
1208 let health = match svc_status {
1209 camel_api::ServiceStatus::Started => camel_api::HealthStatus::Healthy,
1210 camel_api::ServiceStatus::Stopped => camel_api::HealthStatus::Degraded,
1211 camel_api::ServiceStatus::Failed => camel_api::HealthStatus::Unhealthy,
1212 _ => camel_api::HealthStatus::Unhealthy,
1215 };
1216 if matches!(worst, camel_api::HealthStatus::Healthy)
1217 && matches!(
1218 health,
1219 camel_api::HealthStatus::Degraded | camel_api::HealthStatus::Unhealthy
1220 )
1221 {
1222 worst = health;
1223 }
1224 if matches!(worst, camel_api::HealthStatus::Degraded)
1225 && matches!(health, camel_api::HealthStatus::Unhealthy)
1226 {
1227 worst = health;
1228 }
1229 report.services.push(camel_api::ServiceHealth {
1230 name: service.name().to_string(),
1231 status: svc_status,
1232 message: None,
1233 });
1234 }
1235 report.status = worst;
1236 report
1237 }
1238
1239 async fn startup(&self) -> camel_api::HealthStatus {
1240 camel_api::HealthStatus::Healthy
1241 }
1242}
1243
1244#[cfg(test)]
1245#[path = "context_tests.rs"]
1246mod context_tests;