camel-core 0.70.0

Core engine for rust-camel
Documentation
//! Generic `NamedRegistry<T>` — a fallible (duplicate-detecting) named object registry.
//!
//! Unlike the auth crate's `NamedRegistry` (DashMap-based, infallible `register()`),
//! this registry uses `Mutex<HashMap>` so that `register()` can reject duplicates
//! with `Err(RegistryError::AlreadyRegistered)`.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

/// Error returned by `NamedRegistry::register`.
#[derive(Debug, thiserror::Error)]
pub enum RegistryError {
    /// A value with this name is already registered.
    #[error("already registered: {0}")]
    AlreadyRegistered(String),
}

/// A named registry with duplicate detection.
///
/// # Fallible registration
///
/// Unlike the auth crate's DashMap-based `NamedRegistry` (which silently
/// overwrites), this registry's `register()` returns
/// `Err(RegistryError::AlreadyRegistered)` if the name is taken.
///
/// Returns `Arc<T>` from `get()` so the caller shares ownership of the
/// registered value.
///
/// # Thread safety
///
/// Uses `Mutex<HashMap<String, Arc<T>>>` internally. All methods are safe
/// to call from multiple threads.
pub struct NamedRegistry<T: ?Sized + Send + Sync + 'static> {
    map: Mutex<HashMap<String, Arc<T>>>,
}

impl<T: ?Sized + Send + Sync + 'static> NamedRegistry<T> {
    /// Create an empty registry.
    pub fn new() -> Self {
        Self {
            map: Mutex::new(HashMap::new()),
        }
    }

    /// Register `value` under `name`.
    ///
    /// Returns `Err(RegistryError::AlreadyRegistered)` if `name` is already
    /// taken. The existing value is preserved.
    ///
    /// D-M5 fix: the previous implementation did `map.insert(name, value)`
    /// and then returned `Err` if `insert` reported the key existed. That
    /// silently overwrote the existing value. Callers who checked the
    /// `Err` and queried `get` would receive the *new* (rejected) value,
    /// not the original. The fix is check-then-insert under the held
    /// lock: if the key is present, return `Err` and do not touch the
    /// map; otherwise insert.
    pub fn register(&self, name: impl Into<String>, value: Arc<T>) -> Result<(), RegistryError> {
        let name = name.into();
        let mut map = self
            .map
            .lock()
            .expect("registry mutex poisoned: another thread panicked while holding this lock"); // allow-unwrap
        if map.contains_key(&name) {
            return Err(RegistryError::AlreadyRegistered(name));
        }
        map.insert(name, value);
        Ok(())
    }

    /// Register or replace `value` under `name`.
    ///
    /// Returns the previous value if `name` was already registered, or `None`
    /// if this is the first registration under this name.
    pub fn register_or_replace(&self, name: impl Into<String>, value: Arc<T>) -> Option<Arc<T>> {
        let name = name.into();
        let mut map = self
            .map
            .lock()
            .expect("registry mutex poisoned: another thread panicked while holding this lock"); // allow-unwrap
        map.insert(name, value)
    }

    /// Retrieve a registered value by name.
    pub fn get(&self, name: &str) -> Option<Arc<T>> {
        self.map
            .lock()
            .expect("registry mutex poisoned: another thread panicked while holding this lock") // allow-unwrap
            .get(name)
            .cloned()
    }

    /// Number of registered values.
    pub fn len(&self) -> usize {
        self.map
            .lock()
            .expect("registry mutex poisoned: another thread panicked while holding this lock") // allow-unwrap
            .len()
    }

    /// Whether the registry holds no values.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<T: ?Sized + Send + Sync + 'static> Default for NamedRegistry<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Convenience alias for the idempotent repository registry.
pub(crate) type IdempotentRegistry = NamedRegistry<dyn camel_api::IdempotentRepository>;

/// Shareable handle to the idempotent repository registry.
///
/// `Arc<IdempotentRegistry>` is shared between `CamelContext` (which owns the
/// user-facing `register_idempotent_repository` API) and `DefaultRouteController`
/// (which needs read access during step compilation to resolve
/// `idempotent_consumer` repository names). The registry has internal Mutex
/// protection so concurrent reads/writes from both sides are safe.
pub(crate) type SharedIdempotentRegistry = Arc<IdempotentRegistry>;

/// Convenience alias for the claim check repository registry.
pub(crate) type ClaimCheckRegistry = NamedRegistry<dyn camel_api::ClaimCheckRepository>;

/// Shareable handle to the claim check repository registry.
///
/// Mirrors `SharedIdempotentRegistry` — shared between `CamelContext` and
/// `DefaultRouteController` for step-compile-time repository resolution.
pub(crate) type SharedClaimCheckRegistry = Arc<ClaimCheckRegistry>;

/// Convenience alias for the cache repository registry.
pub(crate) type CacheRegistry = NamedRegistry<dyn camel_api::CacheRepository>;

/// Shareable handle to the cache repository registry.
///
/// Shared between `CamelContext` (which owns the user-facing
/// `register_cache_repository` / `replace_cache_repository` API) and
/// any consumer that needs read access during step compilation.
pub(crate) type SharedCacheRegistry = Arc<CacheRegistry>;

/// Registry of [`camel_api::TransactionManager`] ports, keyed by datasource name.
///
/// Bundle boot registers one manager per catalog datasource (sqltrans-exec
/// step 9); absent catalog (tests, embedded callers) resolves empty and load
/// validation fails closed with `ManagerMissing`.
pub type TransactionManagerRegistry = NamedRegistry<dyn camel_api::TransactionManager>;

/// Resolve the [`camel_api::TransactionManager`] registered for `datasource`.
///
/// Fails closed with [`camel_api::TransactionError::ManagerMissing`] naming the
/// datasource when no manager is registered. There is no fallback to another
/// datasource and no `None` return: a missing manager is always an error.
pub fn resolve_transaction_manager(
    registry: &TransactionManagerRegistry,
    datasource: &str,
) -> Result<Arc<dyn camel_api::TransactionManager>, camel_api::TransactionError> {
    registry
        .get(datasource)
        .ok_or_else(|| camel_api::TransactionError::ManagerMissing {
            datasource: datasource.to_owned(),
        })
}

/// Shared test-only doubles.
///
/// `FakeTransactionManager` is used by both the registry and `RuntimeBus`
/// suites. Opening a session is deliberately unimplemented in slice 1: the
/// dark slice exercises registry resolution only, never session lifecycle.
#[cfg(test)]
pub(crate) mod test_support {
    /// Minimal `TransactionManager` test double shared by the registry and
    /// `RuntimeBus` suites. Opening a session is deliberately unimplemented:
    /// the dark slice exercises registry resolution only, never session
    /// lifecycle.
    pub(crate) struct FakeTransactionManager {
        datasource: String,
    }

    impl FakeTransactionManager {
        pub(crate) fn new(datasource: impl Into<String>) -> Self {
            Self {
                datasource: datasource.into(),
            }
        }
    }

    impl camel_api::TransactionManager for FakeTransactionManager {
        fn datasource(&self) -> &str {
            &self.datasource
        }

        fn open_session(&self) -> camel_api::transaction::OpenSessionFuture<'_> {
            panic!("the registry slice must never open a transaction session")
        }

        fn acquire_deadline(&self) -> std::time::Duration {
            std::time::Duration::from_secs(5)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn register_then_get() {
        let registry: NamedRegistry<str> = NamedRegistry::new();
        registry.register("hello", Arc::from("world")).unwrap();
        let got = registry.get("hello");
        assert!(got.is_some());
        assert_eq!(*got.unwrap(), *"world");
    }

    #[test]
    fn get_missing_returns_none() {
        let registry: NamedRegistry<str> = NamedRegistry::new();
        assert!(registry.get("nonexistent").is_none());
    }

    #[test]
    fn duplicate_register_fails() {
        let registry: NamedRegistry<str> = NamedRegistry::new();
        registry.register("key1", Arc::from("first")).unwrap();
        let err = registry.register("key1", Arc::from("second")).unwrap_err();
        assert!(
            matches!(&err, RegistryError::AlreadyRegistered(name) if name == "key1"),
            "expected AlreadyRegistered('key1'), got {err:?}"
        );
        // D-M5 fix: check-then-insert. The existing value is preserved on
        // Err. The pre-fix code did `map.insert` (overwriting) then
        // returned Err, leaving the new value in place. Callers trusting
        // the error kept the wrong repository silently.
        let val = registry.get("key1").unwrap();
        assert_eq!(*val, *"first");
    }

    #[test]
    fn register_or_replace_inserts_and_returns_previous() {
        let registry: NamedRegistry<str> = NamedRegistry::new();
        // First insert — no previous value
        assert!(
            registry
                .register_or_replace("key1", Arc::from("first"))
                .is_none()
        );
        assert_eq!(*registry.get("key1").unwrap(), *"first");
        // Replace — previous value returned, new value stored
        let prev = registry.register_or_replace("key1", Arc::from("second"));
        assert!(prev.is_some());
        assert_eq!(*prev.unwrap(), *"first");
        assert_eq!(*registry.get("key1").unwrap(), *"second");
        // Replace again
        let prev = registry.register_or_replace("key1", Arc::from("third"));
        assert!(prev.is_some());
        assert_eq!(*prev.unwrap(), *"second");
        assert_eq!(*registry.get("key1").unwrap(), *"third");
    }

    use super::test_support::FakeTransactionManager;

    #[test]
    fn registry_missing_manager_fails_closed() {
        let registry = TransactionManagerRegistry::new();
        let err = resolve_transaction_manager(&registry, "pg")
            .err()
            .expect("an empty registry must not resolve a manager");
        assert!(
            matches!(
                &err,
                camel_api::TransactionError::ManagerMissing { datasource } if datasource == "pg"
            ),
            "expected ManagerMissing('pg'), got {err:?}"
        );
    }

    #[test]
    fn registry_round_trip_with_fake_manager() {
        let registry = TransactionManagerRegistry::new();
        let manager: Arc<dyn camel_api::TransactionManager> =
            Arc::new(FakeTransactionManager::new("pg"));
        registry.register("pg", manager).expect("register manager");

        let resolved =
            resolve_transaction_manager(&registry, "pg").expect("registered manager must resolve");
        assert_eq!(resolved.datasource(), "pg");
    }
}