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                Arc::new(camel_core::RegistryComponentContext::new(
209                    component_registry.clone(),
210                )),
211                bean_cfg.config.clone(),
212            )
213            .await
214            .unwrap_or_else(|e| {
215                eprintln!("Failed to load WASM bean '{}': {}", bean_name, e);
216                std::process::exit(1);
217            });
218            tracing::info!(
219                bean = %bean_name,
220                plugin = %bean_cfg.plugin,
221                methods = ?wasm_bean.methods(),
222                "WASM bean loaded"
223            );
224            bean_reg
225                .lock()
226                .expect("beans registry lock") // allow-unwrap
227                .register(bean_name, wasm_bean)
228                .unwrap_or_else(|e| {
229                    eprintln!("Bean registration failed for '{}': {}", bean_name, e);
230                    std::process::exit(1);
231                });
232        }
233    }
234
235    // 3. Determine route patterns
236    let patterns: Vec<String> = if let Some(p) = routes_override {
237        vec![p]
238    } else if !camel_config.routes.is_empty() {
239        camel_config.routes.clone()
240    } else {
241        vec!["routes/*.yaml".to_string()]
242    };
243
244    tracing::info!("camel-cli: loading routes from patterns: {:?}", patterns);
245
246    let security_compile_context =
247        crate::build_security_compile_context_from_config(&camel_config, ctx.registry_arc())
248            .await?;
249
250    // Define register_bundle! macro — looks up config key in ComponentsConfig::raw,
251    // falling back to an empty table so bundles always register with their serde defaults.
252    // Uses UFCS to invoke ComponentBundle methods without requiring trait in scope
253    macro_rules! register_bundle {
254        ($ctx:expr, $cfg:expr, $Bundle:ty) => {
255            let raw = $cfg
256                .components
257                .raw
258                .get(<$Bundle as camel_component_api::ComponentBundle>::config_key())
259                .cloned()
260                .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
261            match <$Bundle as camel_component_api::ComponentBundle>::from_toml(raw) {
262                Ok(bundle) => <$Bundle as camel_component_api::ComponentBundle>::register_all(
263                    bundle, &mut $ctx,
264                ),
265                Err(e) => {
266                    return Err(camel_api::CamelError::Config(format!(
267                        "Failed to load {} config: {}",
268                        <$Bundle as camel_component_api::ComponentBundle>::config_key(),
269                        e
270                    )));
271                }
272            }
273        };
274    }
275
276    // Register built-in components (no config needed)
277    ctx.register_component(camel_component_timer::TimerComponent::new());
278    ctx.register_component(camel_component_cron::CronComponent::new());
279    ctx.register_component(camel_component_log::LogComponent::new());
280    ctx.register_component(camel_component_direct::DirectComponent::new());
281    ctx.register_component(camel_component_seda::SedaComponent::new());
282    ctx.register_component(camel_component_mock::MockComponent::new());
283    ctx.register_component(camel_component_controlbus::ControlBusComponent::new());
284    let validator_component = camel_component_validator::ValidatorComponent::new();
285    let validator_backend = validator_component.xsd_bridge_backend();
286    ctx.register_component(validator_component);
287
288    let xslt_component = camel_xslt::XsltComponent::default();
289    let xslt_runtime = xslt_component.bridge_runtime();
290    ctx.register_component(xslt_component);
291
292    let xj_component = camel_xj::XjComponent::default();
293    let xj_runtime = xj_component.bridge_runtime();
294    ctx.register_component(xj_component);
295
296    ctx = ctx.with_lifecycle(BridgeCleanup {
297        xslt: xslt_runtime,
298        xj: xj_runtime,
299        validator: validator_backend,
300    });
301
302    // Register HTTP, WS, File, Container (always-on in camel-cli, no feature flag)
303    register_bundle!(ctx, camel_config, camel_component_http::HttpBundle);
304    #[cfg(feature = "http-static")]
305    register_bundle!(ctx, camel_config, camel_component_http::HttpStaticBundle);
306    register_bundle!(ctx, camel_config, camel_component_ws::WsBundle);
307    register_bundle!(ctx, camel_config, camel_component_file::FileBundle);
308    register_bundle!(
309        ctx,
310        camel_config,
311        camel_component_container::ContainerBundle
312    );
313    // External template renderer (ADR-0047 Stage 2): always-on built-in.
314    register_bundle!(ctx, camel_config, camel_template::TemplateBundle);
315
316    // Register optional/feature-gated bundles
317    let jms_pool = {
318        let raw = camel_config
319            .components
320            .raw
321            .get("jms")
322            .cloned()
323            .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
324        match <camel_component_jms::JmsBundle as camel_component_api::ComponentBundle>::from_toml(
325            raw,
326        ) {
327            Ok(bundle) => {
328                let pool = bundle.pool();
329                <camel_component_jms::JmsBundle as camel_component_api::ComponentBundle>::register_all(bundle, &mut ctx);
330                pool
331            }
332            Err(e) => {
333                return Err(camel_api::CamelError::Config(format!(
334                    "Failed to load jms config: {e}"
335                )));
336            }
337        }
338    };
339
340    let cxf_pool = {
341        let raw = camel_config
342            .components
343            .raw
344            .get("cxf")
345            .cloned()
346            .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
347        match <camel_component_cxf::CxfBundle as camel_component_api::ComponentBundle>::from_toml(
348            raw,
349        ) {
350            Ok(bundle) => {
351                let pool = bundle.pool();
352                <camel_component_cxf::CxfBundle as camel_component_api::ComponentBundle>::register_all(bundle, &mut ctx);
353                pool
354            }
355            Err(e) => {
356                return Err(camel_api::CamelError::Config(format!(
357                    "Failed to load cxf config: {e}"
358                )));
359            }
360        }
361    };
362
363    #[cfg(feature = "kafka")]
364    register_bundle!(ctx, camel_config, camel_component_kafka::KafkaBundle);
365    #[cfg(feature = "mqtt")]
366    register_bundle!(ctx, camel_config, camel_component_mqtt::MqttBundle);
367    register_bundle!(ctx, camel_config, camel_master::MasterBundle);
368    register_bundle!(
369        ctx,
370        camel_config,
371        camel_component_opensearch::OpenSearchBundle
372    );
373    register_bundle!(ctx, camel_config, camel_component_redis::RedisBundle);
374    {
375        let sql_raw = camel_config
376            .components
377            .raw
378            .get(<camel_component_sql::SqlBundle as camel_component_api::ComponentBundle>::config_key())
379            .cloned()
380            .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
381        match <camel_component_sql::SqlBundle as camel_component_api::ComponentBundle>::from_toml(
382            sql_raw,
383        ) {
384            Ok(bundle) => {
385                let bundle = bundle.with_catalog(Arc::clone(&datasource_catalog));
386                <camel_component_sql::SqlBundle as camel_component_api::ComponentBundle>::register_all(bundle, &mut ctx);
387            }
388            Err(e) => {
389                // log-policy: system-broken
390                tracing::error!("failed to initialize SQL bundle: {}", e);
391            }
392        }
393    }
394    #[cfg(feature = "surrealdb")]
395    {
396        let surrealdb_raw = camel_config
397            .components
398            .raw
399            .get(<camel_component_surrealdb::SurrealDbBundle as camel_component_api::ComponentBundle>::config_key())
400            .cloned()
401            .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));
402        match <camel_component_surrealdb::SurrealDbBundle as camel_component_api::ComponentBundle>::from_toml(
403            surrealdb_raw,
404        ) {
405            Ok(bundle) => {
406                let bundle = bundle.with_catalog(Arc::clone(&datasource_catalog));
407                <camel_component_surrealdb::SurrealDbBundle as camel_component_api::ComponentBundle>::register_all(
408                    bundle, &mut ctx,
409                );
410            }
411            Err(e) => {
412                // log-policy: system-broken
413                tracing::error!("failed to initialize SurrealDB bundle: {}", e);
414            }
415        }
416    }
417    #[cfg(feature = "grpc")]
418    register_bundle!(ctx, camel_config, camel_component_grpc::GrpcBundle);
419
420    #[cfg(feature = "llm")]
421    register_bundle!(ctx, camel_config, camel_component_llm::LlmBundle);
422
423    #[cfg(feature = "wasm")]
424    {
425        let base_dir = std::path::Path::new(&config_path)
426            .parent()
427            .unwrap_or(std::path::Path::new("."))
428            .to_path_buf();
429        let wasm_bundle = camel_component_wasm::WasmBundle::new(
430            Arc::new(camel_core::RegistryComponentContext::new(
431                ctx.registry_arc(),
432            )),
433            base_dir,
434        );
435        <camel_component_wasm::WasmBundle as camel_component_api::ComponentBundle>::register_all(
436            wasm_bundle,
437            &mut ctx,
438        );
439    }
440
441    // Languages are registered in `configure_context_with_beans` (camel-config)
442    // via `camel_core::languages_from_config(&config.languages)`, which applies
443    // Camel.toml [languages.*.limits] and registers js/javascript/rhai/
444    // jsonpath/xpath under feature gates. A direct `CamelContext::builder().build()`
445    // caller gets `LanguagesConfig::default()` (rust-camel runtime defaults).
446
447    // 5. Discover and load initial routes
448    match camel_dsl::discover_routes_with_threshold_and_security(
449        &patterns,
450        camel_config.stream_caching.threshold,
451        security_compile_context.clone(),
452    ) {
453        Ok(defs) => {
454            // Conditionally register ExecBundle: only when a discovered route
455            // references `exec:` or the operator declared `[components.exec]`.
456            #[cfg(feature = "exec")]
457            {
458                let exec_used = camel_core::startup_validation::route_definitions_reference_scheme(
459                    &defs, "exec",
460                );
461                let exec_configured = camel_config.components.raw.contains_key("exec");
462                if exec_used || exec_configured {
463                    register_bundle!(ctx, camel_config, camel_component_exec::ExecBundle);
464                }
465            }
466
467            // ADR-0033: register fail-closed ConfigChecks derived from the
468            // discovered routes (e.g. SqlDynamicQueryCheck for every `sql:`
469            // endpoint). The checks run synchronously at the head of
470            // `CamelContext::start()` before any route consumer is started.
471            for check in
472                camel_core::startup_validation::scan_route_definitions_for_sql_checks(&defs)
473            {
474                ctx.add_startup_check(check);
475            }
476            // Benchmark instrumentation: when BENCH_LATENCY_FILE is set,
477            // wrap every top-level `To` step with timing processors.
478            let defs = crate::commands::bench_instrument::maybe_instrument_routes(defs);
479            for def in defs {
480                let id = def.route_id().to_string();
481                if let Err(e) = ctx.add_route_definition(def).await {
482                    // log-policy: system-broken
483                    tracing::error!("Failed to add route '{}': {}", id, e);
484                }
485            }
486        }
487        Err(e) => {
488            // log-policy: system-broken
489            tracing::error!("Failed to discover routes: {}", e);
490            std::process::exit(1);
491        }
492    }
493
494    // 6. Start context
495    if let Err(e) = ctx.start().await {
496        // log-policy: system-broken
497        tracing::error!("Failed to start CamelContext: {}", e);
498        std::process::exit(1);
499    }
500
501    tracing::info!("camel-cli: context started");
502
503    // 7. Resolve whether to enable the file watcher:
504    //    CLI flag takes precedence; falls back to Camel.toml `watch` field (default: false).
505    let watch_enabled = cli_watch.unwrap_or(camel_config.watch);
506
507    // 8. Optionally start file watcher in background
508    let watcher_shutdown = CancellationToken::new();
509    if watch_enabled {
510        let ctrl = ctx.runtime_execution_handle();
511        let watch_patterns = patterns.clone();
512        let watch_security_compile_context = security_compile_context.clone();
513        let drain_timeout = std::time::Duration::from_millis(camel_config.drain_timeout_ms);
514        let debounce = std::time::Duration::from_millis(camel_config.watch_debounce_ms);
515        let watcher_token = watcher_shutdown.clone();
516        tokio::spawn(async move {
517            let watch_dirs = camel_core::reload_watcher::resolve_watch_dirs(&watch_patterns);
518            let result = camel_core::reload_watcher::watch_and_reload(
519                watch_dirs,
520                ctrl,
521                move || {
522                    camel_dsl::discover_routes_with_threshold_and_security(
523                        &watch_patterns,
524                        camel_config.stream_caching.threshold,
525                        watch_security_compile_context.clone(),
526                    )
527                    .map_err(|e| camel_api::CamelError::RouteError(e.to_string()))
528                },
529                Some(watcher_token),
530                drain_timeout,
531                debounce,
532            )
533            .await;
534            if let Err(e) = result {
535                // log-policy: system-broken
536                tracing::error!("File watcher failed: {}", e);
537            }
538        });
539        tracing::info!(
540            "camel-cli: hot-reload watching {:?}. Press Ctrl+C to stop.",
541            patterns
542        );
543    } else {
544        tracing::info!("camel-cli: running (hot-reload disabled). Press Ctrl+C to stop.");
545    }
546
547    tokio::select! {
548        _ = tokio::signal::ctrl_c() => tracing::info!("Received Ctrl+C"),
549        _ = async {
550            #[cfg(unix)]
551            {
552                tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
553                    .expect("Failed to install SIGTERM handler") // allow-unwrap
554                    .recv()
555                    .await
556            }
557            #[cfg(not(unix))]
558            {
559                std::future::pending::<()>().await
560            }
561        } => tracing::info!("Received SIGTERM"),
562    }
563
564    // Second Ctrl+C = force exit
565    let force_exit = tokio::spawn(async {
566        tokio::signal::ctrl_c().await.ok();
567        tracing::warn!("Second Ctrl+C — forcing exit");
568        std::process::exit(1);
569    });
570
571    tracing::info!("camel-cli: shutting down...");
572    watcher_shutdown.cancel();
573
574    // Signal pools to stop restarting BEFORE context shutdown
575    jms_pool.begin_shutdown();
576    cxf_pool.begin_shutdown();
577
578    // Stop context (routes + lifecycle services)
579    ctx.stop().await.unwrap_or_else(|e| {
580        // log-policy: system-broken
581        tracing::error!("Error during shutdown: {}", e);
582    });
583
584    // Tear down bridge pools with timeouts
585    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(30);
586
587    match tokio::time::timeout(SHUTDOWN_TIMEOUT, jms_pool.shutdown()).await {
588        Ok(Ok(())) => {}
589        Ok(Err(e)) => {
590            // log-policy: system-broken
591            tracing::error!("JMS pool shutdown failed: {}", e);
592        }
593        Err(_) => tracing::warn!("JMS pool shutdown timed out after 30s"),
594    }
595
596    match tokio::time::timeout(SHUTDOWN_TIMEOUT, cxf_pool.shutdown()).await {
597        Ok(Ok(())) => {}
598        Ok(Err(e)) => {
599            // log-policy: system-broken
600            tracing::error!("CXF pool shutdown failed: {}", e);
601        }
602        Err(_) => tracing::warn!("CXF pool shutdown timed out after 30s"),
603    }
604
605    force_exit.abort();
606
607    tracing::info!("camel-cli: stopped");
608    Ok(())
609}
610
611// ---------------------------------------------------------------------------
612// Tests
613// ---------------------------------------------------------------------------
614
615#[cfg(test)]
616mod tests {
617    /// The run function must emit exactly one startup warning about the CWD trust model.
618    #[test]
619    fn startup_warning_emitted() {
620        let source = include_str!("run.rs");
621        // Build the search string from two parts so the concatenated form
622        // never appears literally in test code — only in the warn! call.
623        let a = "camel run trusts the current working directory";
624        let b = " and will execute route";
625        let msg = format!("{a}{b}");
626        let count = source.matches(&msg).count();
627        assert_eq!(
628            count, 1,
629            "expected exactly one tracing::warn! with the trust-model message in run.rs; found {count}"
630        );
631    }
632
633    /// The run command's clap help must document the trust model.
634    #[test]
635    fn clap_help_documents_trust_model() {
636        let source = include_str!("../main.rs");
637        let has_trust_doc = source
638            .contains("Trust model: `camel run` executes route scripts, WASM modules, and beans")
639            || source
640                .contains("Trust model: camel run executes route scripts, WASM modules, and beans");
641        assert!(
642            has_trust_doc,
643            "expected trust model documentation in the Run subcommand help in main.rs"
644        );
645    }
646}