Skip to main content

camel_core/
registry.rs

1//! Generic `NamedRegistry<T>` — a fallible (duplicate-detecting) named object registry.
2//!
3//! Unlike the auth crate's `NamedRegistry` (DashMap-based, infallible `register()`),
4//! this registry uses `Mutex<HashMap>` so that `register()` can reject duplicates
5//! with `Err(RegistryError::AlreadyRegistered)`.
6
7use std::collections::HashMap;
8use std::sync::{Arc, Mutex};
9
10/// Error returned by `NamedRegistry::register`.
11#[derive(Debug, thiserror::Error)]
12pub enum RegistryError {
13    /// A value with this name is already registered.
14    #[error("already registered: {0}")]
15    AlreadyRegistered(String),
16}
17
18/// A named registry with duplicate detection.
19///
20/// # Fallible registration
21///
22/// Unlike the auth crate's DashMap-based `NamedRegistry` (which silently
23/// overwrites), this registry's `register()` returns
24/// `Err(RegistryError::AlreadyRegistered)` if the name is taken.
25///
26/// Returns `Arc<T>` from `get()` so the caller shares ownership of the
27/// registered value.
28///
29/// # Thread safety
30///
31/// Uses `Mutex<HashMap<String, Arc<T>>>` internally. All methods are safe
32/// to call from multiple threads.
33pub struct NamedRegistry<T: ?Sized + Send + Sync + 'static> {
34    map: Mutex<HashMap<String, Arc<T>>>,
35}
36
37impl<T: ?Sized + Send + Sync + 'static> NamedRegistry<T> {
38    /// Create an empty registry.
39    pub fn new() -> Self {
40        Self {
41            map: Mutex::new(HashMap::new()),
42        }
43    }
44
45    /// Register `value` under `name`.
46    ///
47    /// Returns `Err(RegistryError::AlreadyRegistered)` if `name` is already
48    /// taken. The existing value is preserved.
49    ///
50    /// D-M5 fix: the previous implementation did `map.insert(name, value)`
51    /// and then returned `Err` if `insert` reported the key existed. That
52    /// silently overwrote the existing value. Callers who checked the
53    /// `Err` and queried `get` would receive the *new* (rejected) value,
54    /// not the original. The fix is check-then-insert under the held
55    /// lock: if the key is present, return `Err` and do not touch the
56    /// map; otherwise insert.
57    pub fn register(&self, name: impl Into<String>, value: Arc<T>) -> Result<(), RegistryError> {
58        let name = name.into();
59        let mut map = self
60            .map
61            .lock()
62            .expect("registry mutex poisoned: another thread panicked while holding this lock"); // allow-unwrap
63        if map.contains_key(&name) {
64            return Err(RegistryError::AlreadyRegistered(name));
65        }
66        map.insert(name, value);
67        Ok(())
68    }
69
70    /// Register or replace `value` under `name`.
71    ///
72    /// Returns the previous value if `name` was already registered, or `None`
73    /// if this is the first registration under this name.
74    pub fn register_or_replace(&self, name: impl Into<String>, value: Arc<T>) -> Option<Arc<T>> {
75        let name = name.into();
76        let mut map = self
77            .map
78            .lock()
79            .expect("registry mutex poisoned: another thread panicked while holding this lock"); // allow-unwrap
80        map.insert(name, value)
81    }
82
83    /// Retrieve a registered value by name.
84    pub fn get(&self, name: &str) -> Option<Arc<T>> {
85        self.map
86            .lock()
87            .expect("registry mutex poisoned: another thread panicked while holding this lock") // allow-unwrap
88            .get(name)
89            .cloned()
90    }
91
92    /// Number of registered values.
93    pub fn len(&self) -> usize {
94        self.map
95            .lock()
96            .expect("registry mutex poisoned: another thread panicked while holding this lock") // allow-unwrap
97            .len()
98    }
99
100    /// Whether the registry holds no values.
101    pub fn is_empty(&self) -> bool {
102        self.len() == 0
103    }
104}
105
106impl<T: ?Sized + Send + Sync + 'static> Default for NamedRegistry<T> {
107    fn default() -> Self {
108        Self::new()
109    }
110}
111
112/// Convenience alias for the idempotent repository registry.
113pub(crate) type IdempotentRegistry = NamedRegistry<dyn camel_api::IdempotentRepository>;
114
115/// Shareable handle to the idempotent repository registry.
116///
117/// `Arc<IdempotentRegistry>` is shared between `CamelContext` (which owns the
118/// user-facing `register_idempotent_repository` API) and `DefaultRouteController`
119/// (which needs read access during step compilation to resolve
120/// `idempotent_consumer` repository names). The registry has internal Mutex
121/// protection so concurrent reads/writes from both sides are safe.
122pub(crate) type SharedIdempotentRegistry = Arc<IdempotentRegistry>;
123
124/// Convenience alias for the claim check repository registry.
125pub(crate) type ClaimCheckRegistry = NamedRegistry<dyn camel_api::ClaimCheckRepository>;
126
127/// Shareable handle to the claim check repository registry.
128///
129/// Mirrors `SharedIdempotentRegistry` — shared between `CamelContext` and
130/// `DefaultRouteController` for step-compile-time repository resolution.
131pub(crate) type SharedClaimCheckRegistry = Arc<ClaimCheckRegistry>;
132
133/// Convenience alias for the cache repository registry.
134pub(crate) type CacheRegistry = NamedRegistry<dyn camel_api::CacheRepository>;
135
136/// Shareable handle to the cache repository registry.
137///
138/// Shared between `CamelContext` (which owns the user-facing
139/// `register_cache_repository` / `replace_cache_repository` API) and
140/// any consumer that needs read access during step compilation.
141pub(crate) type SharedCacheRegistry = Arc<CacheRegistry>;
142
143/// Registry of [`camel_api::TransactionManager`] ports, keyed by datasource name.
144///
145/// Bundle boot registers one manager per catalog datasource (sqltrans-exec
146/// step 9); absent catalog (tests, embedded callers) resolves empty and load
147/// validation fails closed with `ManagerMissing`.
148pub type TransactionManagerRegistry = NamedRegistry<dyn camel_api::TransactionManager>;
149
150/// Resolve the [`camel_api::TransactionManager`] registered for `datasource`.
151///
152/// Fails closed with [`camel_api::TransactionError::ManagerMissing`] naming the
153/// datasource when no manager is registered. There is no fallback to another
154/// datasource and no `None` return: a missing manager is always an error.
155pub fn resolve_transaction_manager(
156    registry: &TransactionManagerRegistry,
157    datasource: &str,
158) -> Result<Arc<dyn camel_api::TransactionManager>, camel_api::TransactionError> {
159    registry
160        .get(datasource)
161        .ok_or_else(|| camel_api::TransactionError::ManagerMissing {
162            datasource: datasource.to_owned(),
163        })
164}
165
166/// Shared test-only doubles.
167///
168/// `FakeTransactionManager` is used by both the registry and `RuntimeBus`
169/// suites. Opening a session is deliberately unimplemented in slice 1: the
170/// dark slice exercises registry resolution only, never session lifecycle.
171#[cfg(test)]
172pub(crate) mod test_support {
173    /// Minimal `TransactionManager` test double shared by the registry and
174    /// `RuntimeBus` suites. Opening a session is deliberately unimplemented:
175    /// the dark slice exercises registry resolution only, never session
176    /// lifecycle.
177    pub(crate) struct FakeTransactionManager {
178        datasource: String,
179    }
180
181    impl FakeTransactionManager {
182        pub(crate) fn new(datasource: impl Into<String>) -> Self {
183            Self {
184                datasource: datasource.into(),
185            }
186        }
187    }
188
189    impl camel_api::TransactionManager for FakeTransactionManager {
190        fn datasource(&self) -> &str {
191            &self.datasource
192        }
193
194        fn open_session(&self) -> camel_api::transaction::OpenSessionFuture<'_> {
195            panic!("the registry slice must never open a transaction session")
196        }
197
198        fn acquire_deadline(&self) -> std::time::Duration {
199            std::time::Duration::from_secs(5)
200        }
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn register_then_get() {
210        let registry: NamedRegistry<str> = NamedRegistry::new();
211        registry.register("hello", Arc::from("world")).unwrap();
212        let got = registry.get("hello");
213        assert!(got.is_some());
214        assert_eq!(*got.unwrap(), *"world");
215    }
216
217    #[test]
218    fn get_missing_returns_none() {
219        let registry: NamedRegistry<str> = NamedRegistry::new();
220        assert!(registry.get("nonexistent").is_none());
221    }
222
223    #[test]
224    fn duplicate_register_fails() {
225        let registry: NamedRegistry<str> = NamedRegistry::new();
226        registry.register("key1", Arc::from("first")).unwrap();
227        let err = registry.register("key1", Arc::from("second")).unwrap_err();
228        assert!(
229            matches!(&err, RegistryError::AlreadyRegistered(name) if name == "key1"),
230            "expected AlreadyRegistered('key1'), got {err:?}"
231        );
232        // D-M5 fix: check-then-insert. The existing value is preserved on
233        // Err. The pre-fix code did `map.insert` (overwriting) then
234        // returned Err, leaving the new value in place. Callers trusting
235        // the error kept the wrong repository silently.
236        let val = registry.get("key1").unwrap();
237        assert_eq!(*val, *"first");
238    }
239
240    #[test]
241    fn register_or_replace_inserts_and_returns_previous() {
242        let registry: NamedRegistry<str> = NamedRegistry::new();
243        // First insert — no previous value
244        assert!(
245            registry
246                .register_or_replace("key1", Arc::from("first"))
247                .is_none()
248        );
249        assert_eq!(*registry.get("key1").unwrap(), *"first");
250        // Replace — previous value returned, new value stored
251        let prev = registry.register_or_replace("key1", Arc::from("second"));
252        assert!(prev.is_some());
253        assert_eq!(*prev.unwrap(), *"first");
254        assert_eq!(*registry.get("key1").unwrap(), *"second");
255        // Replace again
256        let prev = registry.register_or_replace("key1", Arc::from("third"));
257        assert!(prev.is_some());
258        assert_eq!(*prev.unwrap(), *"second");
259        assert_eq!(*registry.get("key1").unwrap(), *"third");
260    }
261
262    use super::test_support::FakeTransactionManager;
263
264    #[test]
265    fn registry_missing_manager_fails_closed() {
266        let registry = TransactionManagerRegistry::new();
267        let err = resolve_transaction_manager(&registry, "pg")
268            .err()
269            .expect("an empty registry must not resolve a manager");
270        assert!(
271            matches!(
272                &err,
273                camel_api::TransactionError::ManagerMissing { datasource } if datasource == "pg"
274            ),
275            "expected ManagerMissing('pg'), got {err:?}"
276        );
277    }
278
279    #[test]
280    fn registry_round_trip_with_fake_manager() {
281        let registry = TransactionManagerRegistry::new();
282        let manager: Arc<dyn camel_api::TransactionManager> =
283            Arc::new(FakeTransactionManager::new("pg"));
284        registry.register("pg", manager).expect("register manager");
285
286        let resolved =
287            resolve_transaction_manager(&registry, "pg").expect("registered manager must resolve");
288        assert_eq!(resolved.datasource(), "pg");
289    }
290}