Skip to main content

camel_cli/commands/
run.rs

1//! `camel run` subcommand body.
2//!
3//! Owns the 7 ADR-0012 `error!` sites migrated in Phase C (see ADR-0012 +
4//! Phase C plan). Each site has a `// log-policy: …` annotation that
5//! classifies it per the ADR taxonomy.
6//!
7//! All sites in this file are category (c) or (d) — system-broken /
8//! bootstrap. The annotations are added in the Infra cluster task (Task 9),
9//! NOT in this split commit.
10
11use camel_api::datasource::DatasourceCatalog;
12#[cfg(feature = "wasm")]
13use camel_bean::BeanProcessor;
14use camel_core::datasource::RuntimeDatasourceCatalog;
15use std::sync::Arc;
16use std::time::Duration;
17use tokio_util::sync::CancellationToken;
18
19struct BridgeCleanup {
20    xslt: Arc<camel_xslt::XsltBridgeRuntime>,
21    xj: Arc<camel_xj::XjBridgeRuntime>,
22    validator: Option<Arc<camel_component_validator::xsd_bridge::XsdBridgeBackend>>,
23}
24
25#[async_trait::async_trait]
26impl camel_api::lifecycle::Lifecycle for BridgeCleanup {
27    fn name(&self) -> &str {
28        "bridge-cleanup"
29    }
30
31    async fn start(&mut self) -> Result<(), camel_api::CamelError> {
32        Ok(())
33    }
34
35    async fn stop(&mut self) -> Result<(), camel_api::CamelError> {
36        self.xslt.shutdown().await;
37        self.xj.shutdown().await;
38        if let Some(validator) = &self.validator {
39            validator.shutdown().await;
40        }
41        Ok(())
42    }
43}
44
45pub async fn run(
46    routes_override: Option<String>,
47    config_path: String,
48    cli_watch: Option<bool>,
49    otel: bool,
50    otel_endpoint: Option<String>,
51    service_name: Option<String>,
52    health_port: Option<u16>,
53) -> Result<(), camel_api::CamelError> {
54    // 1. Load config (fall back to empty config with serde defaults if Camel.toml not found)
55    let mut camel_config: camel_config::config::CamelConfig =
56        camel_config::config::CamelConfig::from_file(&config_path).unwrap_or_else(|_| {
57            // Build an empty config so serde defaults apply
58            config::Config::builder()
59                .build()
60                .and_then(|c| c.try_deserialize())
61                .unwrap_or_else(|e| {
62                    eprintln!("Failed to build default config: {e}");
63                    std::process::exit(1);
64                })
65        });
66
67    // 1b. Apply OTel CLI overrides (--otel-endpoint and --service-name imply --otel)
68    let otel_enabled = otel || otel_endpoint.is_some() || service_name.is_some();
69    if otel_enabled {
70        let otel_cfg =
71            camel_config
72                .observability
73                .otel
74                .get_or_insert(camel_config::OtelCamelConfig {
75                    enabled: true,
76                    endpoint: "http://localhost:4317".to_string(),
77                    service_name: "rust-camel".to_string(),
78                    ..Default::default()
79                });
80        otel_cfg.enabled = true;
81        if let Some(ep) = otel_endpoint {
82            otel_cfg.endpoint = ep;
83        }
84        if let Some(name) = service_name {
85            otel_cfg.service_name = name;
86        }
87    }
88
89    if let Some(port) = health_port {
90        let health_cfg = camel_config
91            .observability
92            .health
93            .get_or_insert(camel_config::config::HealthCamelConfig::default());
94        health_cfg.enabled = true;
95        health_cfg.port = port;
96    }
97
98    // 2. Build context with beans registry (also initialises tracing subscriber)
99    let beans_registry = {
100        let bean_reg = std::sync::Arc::new(std::sync::Mutex::new(camel_bean::BeanRegistry::new()));
101        if camel_config.beans.is_empty() {
102            None
103        } else {
104            Some(bean_reg)
105        }
106    };
107
108    let mut ctx = camel_config::config::CamelConfig::configure_context_with_beans(
109        &camel_config,
110        beans_registry.clone(),
111    )
112    .await
113    .unwrap_or_else(|e| {
114        eprintln!("Failed to configure CamelContext: {e}");
115        std::process::exit(1);
116    });
117
118    // R4-L4: CWD trust model — camel run executes route scripts/WASM/beans
119    // from the current working directory (dev-tool model, like cargo run).
120    tracing::warn!(
121        "camel run trusts the current working directory and will execute route \
122         scripts, WASM modules, and beans resolved from it; only run from a \
123         trusted directory"
124    );
125
126    match camel_function::FunctionRuntimeService::with_default_container_provider(
127        camel_function::FunctionConfig::default(),
128    ) {
129        Ok(svc) => ctx = ctx.with_lifecycle(svc),
130        Err(e) => tracing::warn!("Function runtime disabled: {e}"),
131    }
132
133    // 3a. Create datasource catalog from configured datasources, wiring health registry
134    let datasource_catalog: Arc<dyn DatasourceCatalog> = {
135        let catalog = RuntimeDatasourceCatalog::new(camel_config.datasources.clone())
136            .with_health_registry(ctx.health_registry());
137        Arc::new(catalog)
138    };
139
140    // Load WASM beans after context is created (needs component registry)
141    #[cfg(feature = "wasm")]
142    if let Some(ref bean_reg) = beans_registry {
143        let component_registry = ctx.registry_arc();
144        let plugins_dir_raw = camel_config
145            .components
146            .raw
147            .get("wasm")
148            .and_then(|v| v.get("plugins_dir"))
149            .and_then(|v| v.as_str())
150            .unwrap_or("plugins");
151        let config_dir = std::path::Path::new(&config_path)
152            .parent()
153            .map(|p| {
154                if p.as_os_str().is_empty() {
155                    std::path::Path::new(".")
156                } else {
157                    p
158                }
159            })
160            .unwrap_or(std::path::Path::new("."));
161        let camel_root = config_dir.canonicalize().unwrap_or_else(|e| {
162            eprintln!("Error: cannot resolve project root: {e}");
163            std::process::exit(1);
164        });
165        crate::commands::plugin::validate_plugins_dir(&camel_root, plugins_dir_raw).unwrap_or_else(
166            |e| {
167                eprintln!("Error: invalid plugins_dir: {e}");
168                std::process::exit(1);
169            },
170        );
171        let plugins_dir = camel_root.join(plugins_dir_raw);
172        for (bean_name, bean_cfg) in &camel_config.beans {
173            tracing::info!(bean = %bean_name, plugin = %bean_cfg.plugin, "registering WASM bean");
174
175            if !bean_cfg
176                .plugin
177                .chars()
178                .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
179            {
180                eprintln!(
181                    "Invalid bean plugin name '{}': must be alphanumeric with - or _",
182                    bean_cfg.plugin
183                );
184                std::process::exit(1);
185            }
186
187            let wasm_path = plugins_dir.join(format!("{}.wasm", bean_cfg.plugin));
188            let canonical_plugins = plugins_dir.canonicalize().unwrap_or_else(|_| {
189                eprintln!("Plugins directory not found: {}", plugins_dir.display());
190                std::process::exit(1);
191            });
192            let canonical_path = wasm_path.canonicalize().unwrap_or_else(|_| {
193                eprintln!("WASM bean plugin not found: {}", wasm_path.display());
194                std::process::exit(1);
195            });
196            if !canonical_path.starts_with(&canonical_plugins) {
197                eprintln!(
198                    "Bean plugin path escapes plugins directory: {}",
199                    bean_cfg.plugin
200                );
201                std::process::exit(1);
202            }
203            let wasm_config =
204                camel_component_wasm::config::WasmConfig::from_limits(&bean_cfg.limits);
205            let wasm_bean = camel_component_wasm::bean::WasmBean::new(
206                &wasm_path,
207                wasm_config,
208                component_registry.clone(),
209                bean_cfg.config.clone(),
210            )
211            .await
212            .unwrap_or_else(|e| {
213                eprintln!("Failed to load WASM bean '{}': {}", bean_name, e);
214                std::process::exit(1);
215            });
216            tracing::info!(
217                bean = %bean_name,
218                plugin = %bean_cfg.plugin,
219                methods = ?wasm_bean.methods(),
220                "WASM bean loaded"
221            );
222            bean_reg
223                .lock()
224                .expect("beans registry lock") // allow-unwrap
225                .register(bean_name, wasm_bean)
226                .unwrap_or_else(|e| {
227                    eprintln!("Bean registration failed for '{}': {}", bean_name, e);
228                    std::process::exit(1);
229                });
230        }
231    }
232
233    // 3. Determine route patterns
234    let patterns: Vec<String> = if let Some(p) = routes_override {
235        vec![p]
236    } else if !camel_config.routes.is_empty() {
237        camel_config.routes.clone()
238    } else {
239        vec!["routes/*.yaml".to_string()]
240    };
241
242    tracing::info!("camel-cli: loading routes from patterns: {:?}", patterns);
243
244    let security_compile_context =
245        crate::build_security_compile_context_from_config(&camel_config, ctx.registry_arc())
246            .await?;
247
248    // Define register_bundle! macro — looks up config key in ComponentsConfig::raw,
249    // falling back to an empty table so bundles always register with their serde defaults.
250    // Uses UFCS to invoke ComponentBundle methods without requiring trait in scope
251    macro_rules! register_bundle {
252        ($ctx:expr, $cfg:expr, $Bundle:ty) => {
253            let raw = $cfg
254                .components
255                .raw
256                .get(<$Bundle as camel_component_api::ComponentBundle>::config_key())
257                .cloned()
258                .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
259            match <$Bundle as camel_component_api::ComponentBundle>::from_toml(raw) {
260                Ok(bundle) => <$Bundle as camel_component_api::ComponentBundle>::register_all(
261                    bundle, &mut $ctx,
262                ),
263                Err(e) => {
264                    return Err(camel_api::CamelError::Config(format!(
265                        "Failed to load {} config: {}",
266                        <$Bundle as camel_component_api::ComponentBundle>::config_key(),
267                        e
268                    )));
269                }
270            }
271        };
272    }
273
274    // Register built-in components (no config needed)
275    ctx.register_component(camel_component_timer::TimerComponent::new());
276    ctx.register_component(camel_component_cron::CronComponent::new());
277    ctx.register_component(camel_component_log::LogComponent::new());
278    ctx.register_component(camel_component_direct::DirectComponent::new());
279    ctx.register_component(camel_component_seda::SedaComponent::new());
280    ctx.register_component(camel_component_mock::MockComponent::new());
281    ctx.register_component(camel_component_controlbus::ControlBusComponent::new());
282    let validator_component = camel_component_validator::ValidatorComponent::new();
283    let validator_backend = validator_component.xsd_bridge_backend();
284    ctx.register_component(validator_component);
285
286    let xslt_component = camel_xslt::XsltComponent::default();
287    let xslt_runtime = xslt_component.bridge_runtime();
288    ctx.register_component(xslt_component);
289
290    let xj_component = camel_xj::XjComponent::default();
291    let xj_runtime = xj_component.bridge_runtime();
292    ctx.register_component(xj_component);
293
294    ctx = ctx.with_lifecycle(BridgeCleanup {
295        xslt: xslt_runtime,
296        xj: xj_runtime,
297        validator: validator_backend,
298    });
299
300    // Register HTTP, WS, File, Container (always-on in camel-cli, no feature flag)
301    register_bundle!(ctx, camel_config, camel_component_http::HttpBundle);
302    #[cfg(feature = "http-static")]
303    register_bundle!(ctx, camel_config, camel_component_http::HttpStaticBundle);
304    register_bundle!(ctx, camel_config, camel_component_ws::WsBundle);
305    register_bundle!(ctx, camel_config, camel_component_file::FileBundle);
306    register_bundle!(
307        ctx,
308        camel_config,
309        camel_component_container::ContainerBundle
310    );
311    // External template renderer (ADR-0047 Stage 2): always-on built-in.
312    register_bundle!(ctx, camel_config, camel_template::TemplateBundle);
313
314    // Register optional/feature-gated bundles
315    let jms_pool = {
316        let raw = camel_config
317            .components
318            .raw
319            .get("jms")
320            .cloned()
321            .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
322        match <camel_component_jms::JmsBundle as camel_component_api::ComponentBundle>::from_toml(
323            raw,
324        ) {
325            Ok(bundle) => {
326                let pool = bundle.pool();
327                <camel_component_jms::JmsBundle as camel_component_api::ComponentBundle>::register_all(bundle, &mut ctx);
328                pool
329            }
330            Err(e) => {
331                return Err(camel_api::CamelError::Config(format!(
332                    "Failed to load jms config: {e}"
333                )));
334            }
335        }
336    };
337
338    let cxf_pool = {
339        let raw = camel_config
340            .components
341            .raw
342            .get("cxf")
343            .cloned()
344            .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
345        match <camel_component_cxf::CxfBundle as camel_component_api::ComponentBundle>::from_toml(
346            raw,
347        ) {
348            Ok(bundle) => {
349                let pool = bundle.pool();
350                <camel_component_cxf::CxfBundle as camel_component_api::ComponentBundle>::register_all(bundle, &mut ctx);
351                pool
352            }
353            Err(e) => {
354                return Err(camel_api::CamelError::Config(format!(
355                    "Failed to load cxf config: {e}"
356                )));
357            }
358        }
359    };
360
361    #[cfg(feature = "kafka")]
362    register_bundle!(ctx, camel_config, camel_component_kafka::KafkaBundle);
363    #[cfg(feature = "mqtt")]
364    register_bundle!(ctx, camel_config, camel_component_mqtt::MqttBundle);
365    register_bundle!(ctx, camel_config, camel_master::MasterBundle);
366    register_bundle!(
367        ctx,
368        camel_config,
369        camel_component_opensearch::OpenSearchBundle
370    );
371    register_bundle!(ctx, camel_config, camel_component_redis::RedisBundle);
372    {
373        let sql_raw = camel_config
374            .components
375            .raw
376            .get(<camel_component_sql::SqlBundle as camel_component_api::ComponentBundle>::config_key())
377            .cloned()
378            .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
379        match <camel_component_sql::SqlBundle as camel_component_api::ComponentBundle>::from_toml(
380            sql_raw,
381        ) {
382            Ok(bundle) => {
383                let bundle = bundle.with_catalog(Arc::clone(&datasource_catalog));
384                <camel_component_sql::SqlBundle as camel_component_api::ComponentBundle>::register_all(bundle, &mut ctx);
385            }
386            Err(e) => {
387                // log-policy: system-broken
388                tracing::error!("failed to initialize SQL bundle: {}", e);
389            }
390        }
391    }
392    #[cfg(feature = "surrealdb")]
393    {
394        let surrealdb_raw = camel_config
395            .components
396            .raw
397            .get(<camel_component_surrealdb::SurrealDbBundle as camel_component_api::ComponentBundle>::config_key())
398            .cloned()
399            .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
400        match <camel_component_surrealdb::SurrealDbBundle as camel_component_api::ComponentBundle>::from_toml(
401            surrealdb_raw,
402        ) {
403            Ok(bundle) => {
404                let bundle = bundle.with_catalog(Arc::clone(&datasource_catalog));
405                <camel_component_surrealdb::SurrealDbBundle as camel_component_api::ComponentBundle>::register_all(
406                    bundle, &mut ctx,
407                );
408            }
409            Err(e) => {
410                // log-policy: system-broken
411                tracing::error!("failed to initialize SurrealDB bundle: {}", e);
412            }
413        }
414    }
415    #[cfg(feature = "grpc")]
416    register_bundle!(ctx, camel_config, camel_component_grpc::GrpcBundle);
417
418    #[cfg(feature = "llm")]
419    register_bundle!(ctx, camel_config, camel_component_llm::LlmBundle);
420
421    #[cfg(feature = "wasm")]
422    {
423        let base_dir = std::path::Path::new(&config_path)
424            .parent()
425            .unwrap_or(std::path::Path::new("."))
426            .to_path_buf();
427        let wasm_bundle = camel_component_wasm::WasmBundle::new(ctx.registry_arc(), base_dir);
428        <camel_component_wasm::WasmBundle as camel_component_api::ComponentBundle>::register_all(
429            wasm_bundle,
430            &mut ctx,
431        );
432    }
433
434    // Languages are registered in `configure_context_with_beans` (camel-config)
435    // via `camel_core::languages_from_config(&config.languages)`, which applies
436    // Camel.toml [languages.*.limits] and registers js/javascript/rhai/
437    // jsonpath/xpath under feature gates. A direct `CamelContext::builder().build()`
438    // caller gets `LanguagesConfig::default()` (rust-camel runtime defaults).
439
440    // 5. Discover and load initial routes
441    match camel_dsl::discover_routes_with_threshold_and_security(
442        &patterns,
443        camel_config.stream_caching.threshold,
444        security_compile_context.clone(),
445    ) {
446        Ok(defs) => {
447            // Conditionally register ExecBundle: only when a discovered route
448            // references `exec:` or the operator declared `[components.exec]`.
449            #[cfg(feature = "exec")]
450            {
451                let exec_used = camel_core::startup_validation::route_definitions_reference_scheme(
452                    &defs, "exec",
453                );
454                let exec_configured = camel_config.components.raw.contains_key("exec");
455                if exec_used || exec_configured {
456                    register_bundle!(ctx, camel_config, camel_component_exec::ExecBundle);
457                }
458            }
459
460            // ADR-0033: register fail-closed ConfigChecks derived from the
461            // discovered routes (e.g. SqlDynamicQueryCheck for every `sql:`
462            // endpoint). The checks run synchronously at the head of
463            // `CamelContext::start()` before any route consumer is started.
464            for check in
465                camel_core::startup_validation::scan_route_definitions_for_sql_checks(&defs)
466            {
467                ctx.add_startup_check(check);
468            }
469            // Benchmark instrumentation: when BENCH_LATENCY_FILE is set,
470            // wrap every top-level `To` step with timing processors.
471            let defs = crate::commands::bench_instrument::maybe_instrument_routes(defs);
472            for def in defs {
473                let id = def.route_id().to_string();
474                if let Err(e) = ctx.add_route_definition(def).await {
475                    // log-policy: system-broken
476                    tracing::error!("Failed to add route '{}': {}", id, e);
477                }
478            }
479        }
480        Err(e) => {
481            // log-policy: system-broken
482            tracing::error!("Failed to discover routes: {}", e);
483            std::process::exit(1);
484        }
485    }
486
487    // 6. Start context
488    if let Err(e) = ctx.start().await {
489        // log-policy: system-broken
490        tracing::error!("Failed to start CamelContext: {}", e);
491        std::process::exit(1);
492    }
493
494    tracing::info!("camel-cli: context started");
495
496    // 7. Resolve whether to enable the file watcher:
497    //    CLI flag takes precedence; falls back to Camel.toml `watch` field (default: false).
498    let watch_enabled = cli_watch.unwrap_or(camel_config.watch);
499
500    // 8. Optionally start file watcher in background
501    let watcher_shutdown = CancellationToken::new();
502    if watch_enabled {
503        let ctrl = ctx.runtime_execution_handle();
504        let watch_patterns = patterns.clone();
505        let watch_security_compile_context = security_compile_context.clone();
506        let drain_timeout = std::time::Duration::from_millis(camel_config.drain_timeout_ms);
507        let debounce = std::time::Duration::from_millis(camel_config.watch_debounce_ms);
508        let watcher_token = watcher_shutdown.clone();
509        tokio::spawn(async move {
510            let watch_dirs = camel_core::reload_watcher::resolve_watch_dirs(&watch_patterns);
511            let result = camel_core::reload_watcher::watch_and_reload(
512                watch_dirs,
513                ctrl,
514                move || {
515                    camel_dsl::discover_routes_with_threshold_and_security(
516                        &watch_patterns,
517                        camel_config.stream_caching.threshold,
518                        watch_security_compile_context.clone(),
519                    )
520                    .map_err(|e| camel_api::CamelError::RouteError(e.to_string()))
521                },
522                Some(watcher_token),
523                drain_timeout,
524                debounce,
525            )
526            .await;
527            if let Err(e) = result {
528                // log-policy: system-broken
529                tracing::error!("File watcher failed: {}", e);
530            }
531        });
532        tracing::info!(
533            "camel-cli: hot-reload watching {:?}. Press Ctrl+C to stop.",
534            patterns
535        );
536    } else {
537        tracing::info!("camel-cli: running (hot-reload disabled). Press Ctrl+C to stop.");
538    }
539
540    tokio::select! {
541        _ = tokio::signal::ctrl_c() => tracing::info!("Received Ctrl+C"),
542        _ = async {
543            #[cfg(unix)]
544            {
545                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
546                    .expect("Failed to install SIGTERM handler") // allow-unwrap
547                    .recv()
548                    .await
549            }
550            #[cfg(not(unix))]
551            {
552                std::future::pending::<()>().await
553            }
554        } => tracing::info!("Received SIGTERM"),
555    }
556
557    // Second Ctrl+C = force exit
558    let force_exit = tokio::spawn(async {
559        tokio::signal::ctrl_c().await.ok();
560        tracing::warn!("Second Ctrl+C — forcing exit");
561        std::process::exit(1);
562    });
563
564    tracing::info!("camel-cli: shutting down...");
565    watcher_shutdown.cancel();
566
567    // Signal pools to stop restarting BEFORE context shutdown
568    jms_pool.begin_shutdown();
569    cxf_pool.begin_shutdown();
570
571    // Stop context (routes + lifecycle services)
572    ctx.stop().await.unwrap_or_else(|e| {
573        // log-policy: system-broken
574        tracing::error!("Error during shutdown: {}", e);
575    });
576
577    // Tear down bridge pools with timeouts
578    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
579
580    match tokio::time::timeout(SHUTDOWN_TIMEOUT, jms_pool.shutdown()).await {
581        Ok(Ok(())) => {}
582        Ok(Err(e)) => {
583            // log-policy: system-broken
584            tracing::error!("JMS pool shutdown failed: {}", e);
585        }
586        Err(_) => tracing::warn!("JMS pool shutdown timed out after 30s"),
587    }
588
589    match tokio::time::timeout(SHUTDOWN_TIMEOUT, cxf_pool.shutdown()).await {
590        Ok(Ok(())) => {}
591        Ok(Err(e)) => {
592            // log-policy: system-broken
593            tracing::error!("CXF pool shutdown failed: {}", e);
594        }
595        Err(_) => tracing::warn!("CXF pool shutdown timed out after 30s"),
596    }
597
598    force_exit.abort();
599
600    tracing::info!("camel-cli: stopped");
601    Ok(())
602}
603
604// ---------------------------------------------------------------------------
605// Tests
606// ---------------------------------------------------------------------------
607
608#[cfg(test)]
609mod tests {
610    /// The run function must emit exactly one startup warning about the CWD trust model.
611    #[test]
612    fn startup_warning_emitted() {
613        let source = include_str!("run.rs");
614        // Build the search string from two parts so the concatenated form
615        // never appears literally in test code — only in the warn! call.
616        let a = "camel run trusts the current working directory";
617        let b = " and will execute route";
618        let msg = format!("{a}{b}");
619        let count = source.matches(&msg).count();
620        assert_eq!(
621            count, 1,
622            "expected exactly one tracing::warn! with the trust-model message in run.rs; found {count}"
623        );
624    }
625
626    /// The run command's clap help must document the trust model.
627    #[test]
628    fn clap_help_documents_trust_model() {
629        let source = include_str!("../main.rs");
630        let has_trust_doc = source
631            .contains("Trust model: `camel run` executes route scripts, WASM modules, and beans")
632            || source
633                .contains("Trust model: camel run executes route scripts, WASM modules, and beans");
634        assert!(
635            has_trust_doc,
636            "expected trust model documentation in the Run subcommand help in main.rs"
637        );
638    }
639}