Skip to main content

camel_core/lifecycle/application/
runtime_bus.rs

1use std::sync::Arc;
2
3use async_trait::async_trait;
4use tokio::sync::OnceCell;
5
6use camel_api::{
7    CamelError, MetricsCollector, RuntimeCommand, RuntimeCommandBus, RuntimeCommandResult,
8    RuntimeQuery, RuntimeQueryBus, RuntimeQueryResult,
9};
10
11use crate::lifecycle::application::commands::{
12    CommandDeps, execute_command, handle_register_internal,
13};
14use crate::lifecycle::application::ports::RouteRegistrationPort;
15use crate::lifecycle::application::ports::{
16    CommandDedupPort, EventPublisherPort, InFlightCountResult, ProjectionStorePort,
17    RouteRepositoryPort, RuntimeExecutionPort, RuntimeUnitOfWorkPort,
18};
19use crate::lifecycle::application::queries::{QueryDeps, execute_query};
20use crate::lifecycle::application::route_definition::RouteDefinition;
21use crate::lifecycle::domain::DomainError;
22use camel_component_api::HealthCheckRegistry as HealthCheckRegistryTrait;
23
24impl From<InFlightCountResult> for RuntimeQueryResult {
25    fn from(r: InFlightCountResult) -> Self {
26        match r {
27            InFlightCountResult::InFlightCount { route_id, count } => {
28                RuntimeQueryResult::InFlightCount { route_id, count }
29            }
30            InFlightCountResult::RouteNotFound { route_id } => {
31                RuntimeQueryResult::RouteNotFound { route_id }
32            }
33        }
34    }
35}
36
37pub struct RuntimeBus {
38    repo: Arc<dyn RouteRepositoryPort>,
39    projections: Arc<dyn ProjectionStorePort>,
40    events: Arc<dyn EventPublisherPort>,
41    dedup: Arc<dyn CommandDedupPort>,
42    uow: Option<Arc<dyn RuntimeUnitOfWorkPort>>,
43    execution: Option<Arc<dyn RuntimeExecutionPort>>,
44    health_registry: Option<Arc<dyn HealthCheckRegistryTrait>>,
45    metrics: Option<Arc<dyn MetricsCollector>>,
46    /// Transaction-manager registry handed to canonical route lowering.
47    ///
48    /// Bundle boot registers one manager per catalog datasource (sqltrans-exec
49    /// step 9). Tests and embedded callers that register nothing keep the
50    /// canonical `transacted` block failing closed at load with
51    /// `ManagerMissing`.
52    transaction_registry: Arc<crate::TransactionManagerRegistry>,
53    /// Boot's single datasource catalog, installed by the bundle cascade.
54    ///
55    /// Canonical lowering resolves a block datasource's URL through this
56    /// catalog so the dialect stage can run. Before boot installs it, the
57    /// lowering seam keeps the always-absent URL resolver and fails closed
58    /// with `DialectUnprovable` naming the datasource.
59    datasource_catalog: OnceCell<Arc<dyn camel_api::datasource::DatasourceCatalog>>,
60    journal_recovered_once: OnceCell<u64>,
61}
62
63impl RuntimeBus {
64    pub fn new(
65        repo: Arc<dyn RouteRepositoryPort>,
66        projections: Arc<dyn ProjectionStorePort>,
67        events: Arc<dyn EventPublisherPort>,
68        dedup: Arc<dyn CommandDedupPort>,
69    ) -> Self {
70        Self {
71            repo,
72            projections,
73            events,
74            dedup,
75            uow: None,
76            execution: None,
77            health_registry: None,
78            metrics: None,
79            transaction_registry: Arc::new(crate::TransactionManagerRegistry::new()),
80            datasource_catalog: OnceCell::new(),
81            journal_recovered_once: OnceCell::new(),
82        }
83    }
84
85    pub fn with_uow(mut self, uow: Arc<dyn RuntimeUnitOfWorkPort>) -> Self {
86        self.uow = Some(uow);
87        self
88    }
89
90    pub fn with_execution(mut self, execution: Arc<dyn RuntimeExecutionPort>) -> Self {
91        self.execution = Some(execution);
92        self
93    }
94
95    pub fn with_health_registry(
96        mut self,
97        health_registry: Arc<crate::health_registry::HealthCheckRegistry>,
98    ) -> Self {
99        self.health_registry = Some(health_registry);
100        self
101    }
102
103    /// Thread a metrics handle so infrastructure commands (ReloadTlsCerts,
104    /// ReloadTemplates) can record counters (rc-d3pj). When None (default),
105    /// no counters are recorded.
106    pub fn with_metrics(mut self, metrics: Arc<dyn MetricsCollector>) -> Self {
107        self.metrics = Some(metrics);
108        self
109    }
110
111    /// Register the [`camel_api::TransactionManager`] for `datasource`.
112    ///
113    /// Duplicate-rejecting: the existing manager is preserved and
114    /// [`crate::RegistryError::AlreadyRegistered`] is returned. Bundle boot
115    /// calls this once per catalog datasource; a datasource without a manager
116    /// still fails load validation closed with `ManagerMissing`.
117    pub fn register_transaction_manager(
118        &self,
119        datasource: impl Into<String>,
120        manager: Arc<dyn camel_api::TransactionManager>,
121    ) -> Result<(), crate::RegistryError> {
122        self.transaction_registry.register(datasource, manager)
123    }
124
125    /// Read-only handle to the transaction-manager registry the canonical
126    /// route lowering resolves against.
127    pub(crate) fn transaction_registry(&self) -> Arc<crate::TransactionManagerRegistry> {
128        Arc::clone(&self.transaction_registry)
129    }
130
131    /// Install the boot's datasource catalog for URL resolution.
132    ///
133    /// The bundle cascade installs its single catalog after creating it, so a
134    /// canonical `transacted` block can resolve its datasource URL by load
135    /// time. Installing twice is rejected: one boot owns one catalog.
136    pub(crate) fn install_datasource_catalog(
137        &self,
138        catalog: Arc<dyn camel_api::datasource::DatasourceCatalog>,
139    ) -> Result<(), CamelError> {
140        self.datasource_catalog.set(catalog).map_err(|_| {
141            CamelError::Config("datasource catalog already installed on this runtime".into())
142        })
143    }
144
145    pub fn repo(&self) -> &Arc<dyn RouteRepositoryPort> {
146        &self.repo
147    }
148
149    /// H8 boot reconciliation: fail any route still in a transient state
150    /// (`Starting` / `Stopping`) from a previous run. Called from
151    /// `CamelContext::start()` before `auto_startup_route_ids()`.
152    pub async fn reconcile_transient_states(&self) -> Result<(), CamelError> {
153        self.ensure_journal_recovered().await?;
154        let deps = self.deps();
155        crate::lifecycle::application::commands::reconcile_transient_states(&deps).await
156    }
157
158    pub(crate) async fn register_aggregate_only(&self, route_id: String) -> Result<(), CamelError> {
159        self.ensure_journal_recovered().await?;
160        let deps = self.deps();
161        if deps.repo.load(&route_id).await?.is_some() {
162            return Err(CamelError::RouteError(format!(
163                "route '{route_id}' already registered"
164            )));
165        }
166        let (aggregate, events) =
167            crate::lifecycle::domain::RouteRuntimeAggregate::register(route_id.clone());
168        if let Some(uow) = &deps.uow {
169            uow.persist_upsert(
170                aggregate.clone(),
171                None,
172                crate::lifecycle::application::commands::project_from_aggregate(&aggregate),
173                &events,
174            )
175            .await?;
176        } else {
177            deps.repo.save(aggregate.clone()).await?;
178            if let Some(primary_error) =
179                crate::lifecycle::application::commands::upsert_projection_with_reconciliation(
180                    &*deps.projections,
181                    crate::lifecycle::application::commands::project_from_aggregate(&aggregate),
182                )
183                .await?
184            {
185                deps.events.publish(&events).await?;
186                return Err(CamelError::RouteError(format!(
187                    "post-effect reconciliation recovered after runtime persistence error: {primary_error}"
188                )));
189            }
190            deps.events.publish(&events).await?;
191        }
192        Ok(())
193    }
194
195    fn deps(&self) -> CommandDeps {
196        CommandDeps {
197            repo: Arc::clone(&self.repo),
198            projections: Arc::clone(&self.projections),
199            events: Arc::clone(&self.events),
200            uow: self.uow.clone(),
201            execution: self.execution.clone(),
202            health_registry: self.health_registry.clone(),
203            transaction_registry: Arc::clone(&self.transaction_registry),
204            datasource_catalog: self.datasource_catalog.get().cloned(),
205        }
206    }
207
208    fn query_deps(&self) -> QueryDeps {
209        QueryDeps {
210            projections: Arc::clone(&self.projections),
211        }
212    }
213
214    async fn ensure_journal_recovered(&self) -> Result<(), CamelError> {
215        let Some(uow) = &self.uow else {
216            return Ok(());
217        };
218
219        self.journal_recovered_once
220            .get_or_try_init(|| async {
221                uow.recover_from_journal().await?;
222                let nonce = uow.recovered_boot_nonce().await?;
223                Ok::<u64, CamelError>(nonce)
224            })
225            .await?;
226        Ok(())
227    }
228
229    /// Journal-derived boot nonce from the recovered durable dedup store.
230    /// Yields `0` before journal recovery ran or when no unit-of-work is
231    /// installed (no durable journal support).
232    pub(crate) fn boot_nonce(&self) -> u64 {
233        self.journal_recovered_once.get().copied().unwrap_or(0)
234    }
235}
236
237#[async_trait]
238impl RuntimeCommandBus for RuntimeBus {
239    async fn execute(&self, cmd: RuntimeCommand) -> Result<RuntimeCommandResult, CamelError> {
240        // ── TLS cert reload intercept ──────────────────────────────────────
241        // Infrastructure command — bypasses journal recovery + dedup.
242        // Reloads are idempotent and NOT journaled.
243        if let RuntimeCommand::ReloadTlsCerts {
244            scheme, host, port, ..
245        } = &cmd
246        {
247            let registry = camel_component_api::tls_source::TlsReloadRegistry::global();
248            match registry.find(scheme, host, *port) {
249                Some(handler) => {
250                    handler.reload().await?;
251                    // rc-d3pj: record reload counter once per successful reload.
252                    if let Some(metrics) = &self.metrics {
253                        // allow-open-label rc-ycts (scheme/host: TLS listener config values)
254                        metrics.record_counter(
255                            "tls_reloads_total",
256                            1.0,
257                            &[("scheme", scheme), ("host", host)],
258                        );
259                    }
260                    return Ok(RuntimeCommandResult::TlsCertsReloaded {
261                        scheme: scheme.clone(),
262                        host: host.clone(),
263                        port: *port,
264                    });
265                }
266                None => {
267                    return Err(CamelError::Config(format!(
268                        "no TLS server found for {scheme}://{host}:{port}"
269                    )));
270                }
271            }
272        }
273        // ── End TLS reload intercept ────────────────────────────────────────
274
275        // ── Template reload intercept ──────────────────────────────────────
276        // Infrastructure command — bypasses journal recovery + dedup (mirrors
277        // ReloadTlsCerts above). Reloads are idempotent and NOT journaled;
278        // RouteStatus is not mutated and ADR-0018 is not invoked. Dispatches to
279        // the registry in camel-component-api (NOT camel-template — that would
280        // invert the dependency).
281        if let RuntimeCommand::ReloadTemplates { route_id, .. } = &cmd {
282            let route_id = route_id.clone();
283            camel_component_api::template_reload::TemplateReloadRegistry::global()
284                .reload_route(&route_id)
285                .await?;
286            // rc-d3pj: record reload counter once per successful reload.
287            if let Some(metrics) = &self.metrics {
288                // allow-open-label rc-xl5k (route label: user-defined route id)
289                metrics.record_counter(
290                    "template_reloads_total",
291                    1.0,
292                    &[("route_id", route_id.as_str())],
293                );
294            }
295            return Ok(RuntimeCommandResult::TemplatesReloaded { route_id });
296        }
297        // ── End template reload intercept ──────────────────────────────────
298
299        self.ensure_journal_recovered().await?;
300        let command_id = cmd.command_id().to_string();
301        if !self.dedup.first_seen(&command_id).await? {
302            return Ok(RuntimeCommandResult::Duplicate { command_id });
303        }
304        let deps = self.deps();
305        match execute_command(&deps, cmd).await {
306            Ok(result) => Ok(result),
307            Err(err) => {
308                let _ = self.dedup.forget_seen(&command_id).await;
309                Err(err)
310            }
311        }
312    }
313}
314
315#[async_trait]
316impl RuntimeQueryBus for RuntimeBus {
317    async fn ask(&self, query: RuntimeQuery) -> Result<RuntimeQueryResult, CamelError> {
318        self.ensure_journal_recovered().await?;
319
320        match query {
321            RuntimeQuery::InFlightCount { route_id } => {
322                if let Some(execution) = &self.execution {
323                    execution
324                        .in_flight_count(&route_id)
325                        .await
326                        .map(|r| r.into())
327                        .map_err(Into::into)
328                } else {
329                    Ok(RuntimeQueryResult::RouteNotFound { route_id })
330                }
331            }
332            other => {
333                let deps = self.query_deps();
334                execute_query(&deps, other).await
335            }
336        }
337    }
338}
339
340#[async_trait]
341impl RouteRegistrationPort for RuntimeBus {
342    async fn register_route(&self, def: RouteDefinition) -> Result<(), DomainError> {
343        self.ensure_journal_recovered()
344            .await
345            .map_err(|e| DomainError::InvalidState(e.to_string()))?;
346        let deps = self.deps();
347        handle_register_internal(&deps, def)
348            .await
349            .map(|_| ())
350            .map_err(|e| match e {
351                CamelError::RouteError(msg) => DomainError::InvalidState(msg),
352                other => DomainError::InvalidState(other.to_string()),
353            })
354    }
355}
356
357#[cfg(test)]
358mod tests {
359    use crate::lifecycle::domain::DomainError;
360
361    use super::*;
362    use std::collections::{HashMap, HashSet};
363    use std::sync::Mutex;
364
365    use crate::lifecycle::application::ports::RouteRegistrationPort as InternalRuntimeCommandBus;
366    use crate::lifecycle::application::ports::RouteStatusProjection;
367    use crate::lifecycle::application::route_definition::RouteDefinition;
368    use crate::lifecycle::domain::{RouteRuntimeAggregate, RuntimeEvent};
369
370    #[derive(Clone, Default)]
371    struct InMemoryTestRepo {
372        routes: Arc<Mutex<HashMap<String, RouteRuntimeAggregate>>>,
373    }
374
375    #[async_trait]
376    impl RouteRepositoryPort for InMemoryTestRepo {
377        async fn load(&self, route_id: &str) -> Result<Option<RouteRuntimeAggregate>, DomainError> {
378            Ok(self
379                .routes
380                .lock()
381                .expect("lock test routes")
382                .get(route_id)
383                .cloned())
384        }
385
386        async fn save(&self, aggregate: RouteRuntimeAggregate) -> Result<(), DomainError> {
387            self.routes
388                .lock()
389                .expect("lock test routes")
390                .insert(aggregate.route_id().to_string(), aggregate);
391            Ok(())
392        }
393
394        async fn save_if_version(
395            &self,
396            aggregate: RouteRuntimeAggregate,
397            expected_version: u64,
398        ) -> Result<(), DomainError> {
399            let route_id = aggregate.route_id().to_string();
400            let mut routes = self.routes.lock().expect("lock test routes");
401            let current = routes.get(&route_id).ok_or_else(|| {
402                DomainError::InvalidState(format!(
403                    "optimistic lock conflict for route '{route_id}': route not found"
404                ))
405            })?;
406
407            if current.version() != expected_version {
408                return Err(DomainError::InvalidState(format!(
409                    "optimistic lock conflict for route '{route_id}': expected version {expected_version}, actual {}",
410                    current.version()
411                )));
412            }
413
414            routes.insert(route_id, aggregate);
415            Ok(())
416        }
417
418        async fn delete(&self, route_id: &str) -> Result<(), DomainError> {
419            self.routes
420                .lock()
421                .expect("lock test routes")
422                .remove(route_id);
423            Ok(())
424        }
425    }
426
427    #[derive(Clone, Default)]
428    struct InMemoryTestProjectionStore {
429        statuses: Arc<Mutex<HashMap<String, RouteStatusProjection>>>,
430    }
431
432    #[async_trait]
433    impl ProjectionStorePort for InMemoryTestProjectionStore {
434        async fn upsert_status(&self, status: RouteStatusProjection) -> Result<(), DomainError> {
435            self.statuses
436                .lock()
437                .expect("lock test statuses")
438                .insert(status.route_id.clone(), status);
439            Ok(())
440        }
441
442        async fn get_status(
443            &self,
444            route_id: &str,
445        ) -> Result<Option<RouteStatusProjection>, DomainError> {
446            Ok(self
447                .statuses
448                .lock()
449                .expect("lock test statuses")
450                .get(route_id)
451                .cloned())
452        }
453
454        async fn list_statuses(&self) -> Result<Vec<RouteStatusProjection>, DomainError> {
455            Ok(self
456                .statuses
457                .lock()
458                .expect("lock test statuses")
459                .values()
460                .cloned()
461                .collect())
462        }
463
464        async fn remove_status(&self, route_id: &str) -> Result<(), DomainError> {
465            self.statuses
466                .lock()
467                .expect("lock test statuses")
468                .remove(route_id);
469            Ok(())
470        }
471    }
472
473    #[derive(Clone, Default)]
474    struct InMemoryTestEventPublisher;
475
476    #[async_trait]
477    impl EventPublisherPort for InMemoryTestEventPublisher {
478        async fn publish(&self, _events: &[RuntimeEvent]) -> Result<(), DomainError> {
479            Ok(())
480        }
481    }
482
483    #[derive(Clone, Default)]
484    struct InMemoryTestDedup {
485        seen: Arc<Mutex<HashSet<String>>>,
486    }
487
488    #[derive(Clone, Default)]
489    struct InspectableDedup {
490        seen: Arc<Mutex<HashSet<String>>>,
491        forget_calls: Arc<Mutex<u32>>,
492    }
493
494    #[async_trait]
495    impl CommandDedupPort for InMemoryTestDedup {
496        async fn first_seen(&self, command_id: &str) -> Result<bool, DomainError> {
497            let mut seen = self.seen.lock().expect("lock dedup set");
498            Ok(seen.insert(command_id.to_string()))
499        }
500
501        async fn forget_seen(&self, command_id: &str) -> Result<(), DomainError> {
502            self.seen.lock().expect("lock dedup set").remove(command_id);
503            Ok(())
504        }
505    }
506
507    #[async_trait]
508    impl CommandDedupPort for InspectableDedup {
509        async fn first_seen(&self, command_id: &str) -> Result<bool, DomainError> {
510            let mut seen = self.seen.lock().expect("lock dedup set");
511            Ok(seen.insert(command_id.to_string()))
512        }
513
514        async fn forget_seen(&self, command_id: &str) -> Result<(), DomainError> {
515            self.seen.lock().expect("lock dedup set").remove(command_id);
516            let mut calls = self.forget_calls.lock().expect("forget calls");
517            *calls += 1;
518            Ok(())
519        }
520    }
521
522    fn build_test_runtime_bus() -> RuntimeBus {
523        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
524        let projections: Arc<dyn ProjectionStorePort> =
525            Arc::new(InMemoryTestProjectionStore::default());
526        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
527        let dedup: Arc<dyn CommandDedupPort> = Arc::new(InMemoryTestDedup::default());
528        RuntimeBus::new(repo, projections, events, dedup)
529    }
530
531    #[derive(Default)]
532    struct CountingUow {
533        recover_calls: Arc<Mutex<u32>>,
534    }
535
536    #[derive(Default)]
537    struct FailingRecoverUow;
538
539    #[async_trait]
540    impl RuntimeUnitOfWorkPort for CountingUow {
541        async fn persist_upsert(
542            &self,
543            _aggregate: RouteRuntimeAggregate,
544            _expected_version: Option<u64>,
545            _projection: RouteStatusProjection,
546            _events: &[RuntimeEvent],
547        ) -> Result<(), DomainError> {
548            Ok(())
549        }
550
551        async fn persist_delete(
552            &self,
553            _route_id: &str,
554            _events: &[RuntimeEvent],
555        ) -> Result<(), DomainError> {
556            Ok(())
557        }
558
559        async fn recover_from_journal(&self) -> Result<(), DomainError> {
560            let mut calls = self.recover_calls.lock().expect("recover_calls");
561            *calls += 1;
562            Ok(())
563        }
564    }
565
566    #[async_trait]
567    impl RuntimeUnitOfWorkPort for FailingRecoverUow {
568        async fn persist_upsert(
569            &self,
570            _aggregate: RouteRuntimeAggregate,
571            _expected_version: Option<u64>,
572            _projection: RouteStatusProjection,
573            _events: &[RuntimeEvent],
574        ) -> Result<(), DomainError> {
575            Ok(())
576        }
577
578        async fn persist_delete(
579            &self,
580            _route_id: &str,
581            _events: &[RuntimeEvent],
582        ) -> Result<(), DomainError> {
583            Ok(())
584        }
585
586        async fn recover_from_journal(&self) -> Result<(), DomainError> {
587            Err(DomainError::InvalidState("recover failed".into()))
588        }
589    }
590
591    #[derive(Default)]
592    struct InFlightExecutionPort;
593
594    #[async_trait]
595    impl RuntimeExecutionPort for InFlightExecutionPort {
596        async fn register_route(&self, _definition: RouteDefinition) -> Result<(), DomainError> {
597            Ok(())
598        }
599        async fn start_route(&self, _route_id: &str) -> Result<(), DomainError> {
600            Ok(())
601        }
602        async fn stop_route(
603            &self,
604            _route_id: &str,
605            _stop_budget: Option<std::time::Duration>,
606        ) -> Result<(), DomainError> {
607            Ok(())
608        }
609        async fn suspend_route(&self, _route_id: &str) -> Result<(), DomainError> {
610            Ok(())
611        }
612        async fn resume_route(&self, _route_id: &str) -> Result<(), DomainError> {
613            Ok(())
614        }
615        async fn reload_route(&self, _route_id: &str) -> Result<(), DomainError> {
616            Ok(())
617        }
618        async fn remove_route(&self, _route_id: &str) -> Result<(), DomainError> {
619            Ok(())
620        }
621        async fn in_flight_count(
622            &self,
623            route_id: &str,
624        ) -> Result<InFlightCountResult, DomainError> {
625            if route_id == "known" {
626                Ok(InFlightCountResult::InFlightCount {
627                    route_id: route_id.to_string(),
628                    count: 3,
629                })
630            } else {
631                Ok(InFlightCountResult::RouteNotFound {
632                    route_id: route_id.to_string(),
633                })
634            }
635        }
636    }
637
638    #[tokio::test]
639    async fn runtime_bus_implements_internal_command_bus() {
640        let bus = build_test_runtime_bus();
641        let def = RouteDefinition::new("timer:test", vec![]).with_route_id("internal-route");
642        let result = InternalRuntimeCommandBus::register_route(&bus, def).await;
643        assert!(
644            result.is_ok(),
645            "internal bus registration failed: {:?}",
646            result
647        );
648
649        let status = bus
650            .ask(RuntimeQuery::GetRouteStatus {
651                route_id: "internal-route".to_string(),
652            })
653            .await
654            .unwrap();
655        match status {
656            RuntimeQueryResult::RouteStatus { status, .. } => {
657                assert_eq!(status, "Registered");
658            }
659            _ => panic!("unexpected query result"),
660        }
661    }
662
663    #[tokio::test]
664    async fn execute_returns_duplicate_for_replayed_command_id() {
665        use camel_api::runtime::{CanonicalRouteSpec, CanonicalStepSpec, RuntimeCommand};
666
667        let bus = build_test_runtime_bus();
668
669        let mut spec = CanonicalRouteSpec::new("dup-route", "timer:tick");
670        spec.steps = vec![CanonicalStepSpec::Stop];
671
672        let cmd = RuntimeCommand::RegisterRoute {
673            spec: spec.clone(),
674            command_id: "dup-cmd".into(),
675            causation_id: None,
676        };
677        let first = bus.execute(cmd).await.unwrap();
678        assert!(matches!(
679            first,
680            RuntimeCommandResult::RouteRegistered { route_id } if route_id == "dup-route"
681        ));
682
683        let second = bus
684            .execute(RuntimeCommand::RegisterRoute {
685                spec,
686                command_id: "dup-cmd".into(),
687                causation_id: None,
688            })
689            .await
690            .unwrap();
691        assert!(matches!(
692            second,
693            RuntimeCommandResult::Duplicate { command_id } if command_id == "dup-cmd"
694        ));
695    }
696
697    #[tokio::test]
698    async fn ask_in_flight_count_without_execution_returns_route_not_found() {
699        let bus = build_test_runtime_bus();
700        let res = bus
701            .ask(RuntimeQuery::InFlightCount {
702                route_id: "missing".into(),
703            })
704            .await
705            .unwrap();
706        assert!(matches!(
707            res,
708            RuntimeQueryResult::RouteNotFound { route_id } if route_id == "missing"
709        ));
710    }
711
712    #[tokio::test]
713    async fn ask_in_flight_count_with_execution_delegates_to_adapter() {
714        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
715        let projections: Arc<dyn ProjectionStorePort> =
716            Arc::new(InMemoryTestProjectionStore::default());
717        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
718        let dedup: Arc<dyn CommandDedupPort> = Arc::new(InMemoryTestDedup::default());
719        let execution: Arc<dyn RuntimeExecutionPort> = Arc::new(InFlightExecutionPort);
720        let bus = RuntimeBus::new(repo, projections, events, dedup).with_execution(execution);
721
722        let known = bus
723            .ask(RuntimeQuery::InFlightCount {
724                route_id: "known".into(),
725            })
726            .await
727            .unwrap();
728        assert!(matches!(
729            known,
730            RuntimeQueryResult::InFlightCount { route_id, count }
731            if route_id == "known" && count == 3
732        ));
733    }
734
735    #[tokio::test]
736    async fn journal_recovery_runs_once_even_with_multiple_commands() {
737        use camel_api::runtime::{CanonicalRouteSpec, CanonicalStepSpec, RuntimeCommand};
738
739        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
740        let projections: Arc<dyn ProjectionStorePort> =
741            Arc::new(InMemoryTestProjectionStore::default());
742        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
743        let dedup: Arc<dyn CommandDedupPort> = Arc::new(InMemoryTestDedup::default());
744        let uow = Arc::new(CountingUow::default());
745        let bus = RuntimeBus::new(repo, projections, events, dedup).with_uow(uow.clone());
746
747        let mut spec_a = CanonicalRouteSpec::new("a", "timer:a");
748        spec_a.steps = vec![CanonicalStepSpec::Stop];
749        let mut spec_b = CanonicalRouteSpec::new("b", "timer:b");
750        spec_b.steps = vec![CanonicalStepSpec::Stop];
751
752        bus.execute(RuntimeCommand::RegisterRoute {
753            spec: spec_a,
754            command_id: "c-a".into(),
755            causation_id: None,
756        })
757        .await
758        .unwrap();
759
760        bus.execute(RuntimeCommand::RegisterRoute {
761            spec: spec_b,
762            command_id: "c-b".into(),
763            causation_id: None,
764        })
765        .await
766        .unwrap();
767
768        let calls = *uow.recover_calls.lock().expect("recover calls");
769        assert_eq!(calls, 1, "journal recovery should run once");
770    }
771
772    #[tokio::test]
773    async fn execute_on_command_error_forgets_dedup_marker() {
774        use camel_api::runtime::{CanonicalRouteSpec, RuntimeCommand};
775
776        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
777        let projections: Arc<dyn ProjectionStorePort> =
778            Arc::new(InMemoryTestProjectionStore::default());
779        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
780        let dedup = Arc::new(InspectableDedup::default());
781        let dedup_port: Arc<dyn CommandDedupPort> = dedup.clone();
782
783        let bus = RuntimeBus::new(repo, projections, events, dedup_port);
784
785        // Invalid canonical contract: empty route_id -> execute_command should fail.
786        let cmd = RuntimeCommand::RegisterRoute {
787            spec: CanonicalRouteSpec::new("", "timer:tick"),
788            command_id: "err-cmd".into(),
789            causation_id: None,
790        };
791
792        let err = bus.execute(cmd).await.expect_err("must fail");
793        assert!(err.to_string().contains("route_id cannot be empty"));
794
795        assert_eq!(*dedup.forget_calls.lock().expect("forget calls"), 1);
796        assert!(!dedup.seen.lock().expect("seen").contains("err-cmd"));
797    }
798
799    #[tokio::test]
800    async fn execute_propagates_recover_error_from_uow() {
801        use camel_api::runtime::{CanonicalRouteSpec, CanonicalStepSpec, RuntimeCommand};
802
803        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
804        let projections: Arc<dyn ProjectionStorePort> =
805            Arc::new(InMemoryTestProjectionStore::default());
806        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
807        let dedup: Arc<dyn CommandDedupPort> = Arc::new(InMemoryTestDedup::default());
808        let uow: Arc<dyn RuntimeUnitOfWorkPort> = Arc::new(FailingRecoverUow);
809
810        let bus = RuntimeBus::new(repo, projections, events, dedup).with_uow(uow);
811
812        let mut spec = CanonicalRouteSpec::new("x", "timer:x");
813        spec.steps = vec![CanonicalStepSpec::Stop];
814        let err = bus
815            .execute(RuntimeCommand::RegisterRoute {
816                spec,
817                command_id: "recover-err".into(),
818                causation_id: None,
819            })
820            .await
821            .expect_err("recover should fail");
822
823        assert!(err.to_string().contains("recover failed"));
824    }
825
826    #[tokio::test]
827    async fn ask_in_flight_count_with_execution_handles_unknown_route() {
828        let repo: Arc<dyn RouteRepositoryPort> = Arc::new(InMemoryTestRepo::default());
829        let projections: Arc<dyn ProjectionStorePort> =
830            Arc::new(InMemoryTestProjectionStore::default());
831        let events: Arc<dyn EventPublisherPort> = Arc::new(InMemoryTestEventPublisher);
832        let dedup: Arc<dyn CommandDedupPort> = Arc::new(InMemoryTestDedup::default());
833        let execution: Arc<dyn RuntimeExecutionPort> = Arc::new(InFlightExecutionPort);
834        let bus = RuntimeBus::new(repo, projections, events, dedup).with_execution(execution);
835
836        let unknown = bus
837            .ask(RuntimeQuery::InFlightCount {
838                route_id: "unknown".into(),
839            })
840            .await
841            .unwrap();
842        assert!(matches!(
843            unknown,
844            RuntimeQueryResult::RouteNotFound { route_id } if route_id == "unknown"
845        ));
846    }
847
848    #[tokio::test]
849    async fn watcher_duplicate_failroute_is_noop() {
850        // rc-slvd: bus-level dedup pin — the failure watcher retries with
851        // the SAME command_id; the second execute must return the dedup
852        // outcome and cause exactly ONE lifecycle transition to Failed.
853        // REAL bus (a fake would make dedup vacuously green).
854        use crate::lifecycle::domain::RouteRuntimeState;
855        use camel_api::RuntimeCommand;
856
857        let bus = build_test_runtime_bus();
858        let def = RouteDefinition::new("timer:test", vec![]).with_route_id("dup-fail-route");
859        InternalRuntimeCommandBus::register_route(&bus, def)
860            .await
861            .expect("register route");
862
863        let cmd = RuntimeCommand::FailRoute {
864            route_id: "dup-fail-route".into(),
865            error: "watcher".into(),
866            command_id: "fail-once".into(),
867            causation_id: None,
868        };
869        let first = bus.execute(cmd.clone()).await.unwrap();
870        assert!(
871            matches!(
872                &first,
873                RuntimeCommandResult::RouteStateChanged { status, .. } if status == "Failed"
874            ),
875            "first FailRoute must transition to Failed, got {first:?}"
876        );
877
878        let second = bus.execute(cmd).await.unwrap();
879        assert!(
880            matches!(
881                &second,
882                RuntimeCommandResult::Duplicate { command_id } if command_id == "fail-once"
883            ),
884            "duplicate command_id must return the dedup no-op, got {second:?}"
885        );
886
887        // Exactly ONE transition: aggregate Failed at version 1 (0 was the
888        // register), and the status query agrees.
889        let aggregate = bus
890            .repo()
891            .load("dup-fail-route")
892            .await
893            .unwrap()
894            .expect("route exists");
895        assert!(matches!(aggregate.state(), RouteRuntimeState::Failed(_)));
896        assert_eq!(
897            aggregate.version(),
898            1,
899            "the duplicate must not apply a second transition"
900        );
901
902        let status = bus
903            .ask(RuntimeQuery::GetRouteStatus {
904                route_id: "dup-fail-route".into(),
905            })
906            .await
907            .unwrap();
908        match status {
909            RuntimeQueryResult::RouteStatus { status, .. } => assert_eq!(status, "Failed"),
910            other => panic!("unexpected query result: {other:?}"),
911        }
912    }
913
914    #[test]
915    fn runtime_bus_registers_and_resolves_manager() {
916        use crate::resolve_transaction_manager;
917        use crate::test_support::FakeTransactionManager;
918
919        let bus = build_test_runtime_bus();
920        let manager: Arc<dyn camel_api::TransactionManager> =
921            Arc::new(FakeTransactionManager::new("pg"));
922
923        bus.register_transaction_manager("pg", Arc::clone(&manager))
924            .expect("a fresh bus must accept the first registration");
925
926        let registry = bus.transaction_registry();
927        let resolved =
928            resolve_transaction_manager(&registry, "pg").expect("registered manager must resolve");
929        assert!(
930            Arc::ptr_eq(&manager, &resolved),
931            "resolution must hand back the SAME Arc that was registered"
932        );
933
934        // Duplicate registration is rejected and preserves the original.
935        let duplicate: Arc<dyn camel_api::TransactionManager> =
936            Arc::new(FakeTransactionManager::new("pg"));
937        let err = bus
938            .register_transaction_manager("pg", duplicate)
939            .expect_err("duplicate registration must be rejected");
940        assert!(
941            matches!(&err, crate::RegistryError::AlreadyRegistered(name) if name == "pg"),
942            "expected AlreadyRegistered('pg'), got {err:?}"
943        );
944        let still = resolve_transaction_manager(&registry, "pg").expect("original must survive");
945        assert!(
946            Arc::ptr_eq(&manager, &still),
947            "a rejected duplicate must not replace the registered manager"
948        );
949    }
950
951    #[test]
952    fn unregistered_datasource_still_fails_closed() {
953        use crate::resolve_transaction_manager;
954
955        let bus = build_test_runtime_bus();
956        let registry = bus.transaction_registry();
957        assert!(
958            registry.is_empty(),
959            "a fresh bus must start with no transaction managers"
960        );
961
962        let err = resolve_transaction_manager(&registry, "audit")
963            .err()
964            .expect("an empty registry must not resolve a manager");
965        assert!(
966            matches!(
967                &err,
968                camel_api::TransactionError::ManagerMissing { datasource } if datasource == "audit"
969            ),
970            "expected ManagerMissing('audit'), got {err:?}"
971        );
972    }
973}