Skip to main content

icydb_core/db/
registry.rs

1use crate::{
2    db::{data::DataStore, index::IndexStore},
3    error::{ErrorClass, ErrorOrigin, InternalError},
4};
5use std::{cell::RefCell, collections::HashMap, thread::LocalKey};
6use thiserror::Error as ThisError;
7
8///
9/// StoreRegistryError
10///
11
12#[derive(Debug, ThisError)]
13#[expect(clippy::enum_variant_names)]
14pub enum StoreRegistryError {
15    #[error("store '{0}' not found")]
16    StoreNotFound(String),
17
18    #[error("store '{0}' already registered")]
19    StoreAlreadyRegistered(String),
20
21    #[error(
22        "store '{name}' reuses the same row/index store pair already registered as '{existing_name}'"
23    )]
24    StoreHandlePairAlreadyRegistered { name: String, existing_name: String },
25}
26
27impl StoreRegistryError {
28    pub(crate) const fn class(&self) -> ErrorClass {
29        match self {
30            Self::StoreNotFound(_) => ErrorClass::Internal,
31            Self::StoreAlreadyRegistered(_) | Self::StoreHandlePairAlreadyRegistered { .. } => {
32                ErrorClass::InvariantViolation
33            }
34        }
35    }
36}
37
38impl From<StoreRegistryError> for InternalError {
39    fn from(err: StoreRegistryError) -> Self {
40        Self::classified(err.class(), ErrorOrigin::Store, err.to_string())
41    }
42}
43
44///
45/// StoreHandle
46///
47/// Bound pair of row and index stores for one schema `Store` path.
48///
49
50#[derive(Clone, Copy, Debug)]
51pub struct StoreHandle {
52    data: &'static LocalKey<RefCell<DataStore>>,
53    index: &'static LocalKey<RefCell<IndexStore>>,
54}
55
56impl StoreHandle {
57    /// Build a store handle from thread-local row/index stores.
58    #[must_use]
59    pub const fn new(
60        data: &'static LocalKey<RefCell<DataStore>>,
61        index: &'static LocalKey<RefCell<IndexStore>>,
62    ) -> Self {
63        Self { data, index }
64    }
65
66    /// Borrow the row store immutably.
67    pub fn with_data<R>(&self, f: impl FnOnce(&DataStore) -> R) -> R {
68        self.data.with_borrow(f)
69    }
70
71    /// Borrow the row store mutably.
72    pub fn with_data_mut<R>(&self, f: impl FnOnce(&mut DataStore) -> R) -> R {
73        self.data.with_borrow_mut(f)
74    }
75
76    /// Borrow the index store immutably.
77    pub fn with_index<R>(&self, f: impl FnOnce(&IndexStore) -> R) -> R {
78        self.index.with_borrow(f)
79    }
80
81    /// Borrow the index store mutably.
82    pub fn with_index_mut<R>(&self, f: impl FnOnce(&mut IndexStore) -> R) -> R {
83        self.index.with_borrow_mut(f)
84    }
85
86    /// Return the raw row-store accessor.
87    #[must_use]
88    pub const fn data_store(&self) -> &'static LocalKey<RefCell<DataStore>> {
89        self.data
90    }
91
92    /// Return the raw index-store accessor.
93    #[must_use]
94    pub const fn index_store(&self) -> &'static LocalKey<RefCell<IndexStore>> {
95        self.index
96    }
97}
98
99///
100/// StoreRegistry
101///
102/// Thread-local registry for both row and index stores.
103///
104
105#[derive(Default)]
106pub struct StoreRegistry {
107    stores: HashMap<&'static str, StoreHandle>,
108}
109
110impl StoreRegistry {
111    /// Create an empty store registry.
112    #[must_use]
113    pub fn new() -> Self {
114        Self::default()
115    }
116
117    /// Iterate registered stores.
118    pub fn iter(&self) -> impl Iterator<Item = (&'static str, StoreHandle)> {
119        self.stores.iter().map(|(k, v)| (*k, *v))
120    }
121
122    /// Register a `Store` path to its row/index store pair.
123    pub fn register_store(
124        &mut self,
125        name: &'static str,
126        data: &'static LocalKey<RefCell<DataStore>>,
127        index: &'static LocalKey<RefCell<IndexStore>>,
128    ) -> Result<(), InternalError> {
129        if self.stores.contains_key(name) {
130            return Err(StoreRegistryError::StoreAlreadyRegistered(name.to_string()).into());
131        }
132
133        // Keep one canonical logical store name per physical row/index store pair.
134        if let Some(existing_name) =
135            self.stores
136                .iter()
137                .find_map(|(existing_name, existing_handle)| {
138                    (std::ptr::eq(existing_handle.data_store(), data)
139                        && std::ptr::eq(existing_handle.index_store(), index))
140                    .then_some(*existing_name)
141                })
142        {
143            return Err(StoreRegistryError::StoreHandlePairAlreadyRegistered {
144                name: name.to_string(),
145                existing_name: existing_name.to_string(),
146            }
147            .into());
148        }
149
150        self.stores.insert(name, StoreHandle::new(data, index));
151        Ok(())
152    }
153
154    /// Look up a store handle by path.
155    pub fn try_get_store(&self, path: &str) -> Result<StoreHandle, InternalError> {
156        self.stores
157            .get(path)
158            .copied()
159            .ok_or_else(|| StoreRegistryError::StoreNotFound(path.to_string()).into())
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use crate::{
166        db::{data::DataStore, index::IndexStore, registry::StoreRegistry},
167        error::{ErrorClass, ErrorOrigin},
168        test_support::test_memory,
169    };
170    use std::{cell::RefCell, ptr};
171
172    const STORE_PATH: &str = "store_registry_tests::Store";
173    const ALIAS_STORE_PATH: &str = "store_registry_tests::StoreAlias";
174
175    thread_local! {
176        static TEST_DATA_STORE: RefCell<DataStore> = RefCell::new(DataStore::init(test_memory(151)));
177        static TEST_INDEX_STORE: RefCell<IndexStore> =
178            RefCell::new(IndexStore::init(test_memory(152)));
179    }
180
181    fn test_registry() -> StoreRegistry {
182        let mut registry = StoreRegistry::new();
183        registry
184            .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
185            .expect("test store registration should succeed");
186        registry
187    }
188
189    #[test]
190    fn register_store_binds_data_and_index_handles() {
191        let registry = test_registry();
192        let handle = registry
193            .try_get_store(STORE_PATH)
194            .expect("registered store path should resolve");
195
196        assert!(
197            ptr::eq(handle.data_store(), &TEST_DATA_STORE),
198            "store handle should expose the registered data store accessor"
199        );
200        assert!(
201            ptr::eq(handle.index_store(), &TEST_INDEX_STORE),
202            "store handle should expose the registered index store accessor"
203        );
204
205        let data_rows = handle.with_data(|store| store.len());
206        let index_rows = handle.with_index(IndexStore::len);
207        assert_eq!(data_rows, 0, "fresh test data store should be empty");
208        assert_eq!(index_rows, 0, "fresh test index store should be empty");
209    }
210
211    #[test]
212    fn missing_store_path_rejected_before_access() {
213        let registry = StoreRegistry::new();
214        let err = registry
215            .try_get_store("store_registry_tests::Missing")
216            .expect_err("missing path should fail lookup");
217
218        assert_eq!(err.class, ErrorClass::Internal);
219        assert_eq!(err.origin, ErrorOrigin::Store);
220        assert!(
221            err.message
222                .contains("store 'store_registry_tests::Missing' not found"),
223            "missing store lookup should include the missing path"
224        );
225    }
226
227    #[test]
228    fn duplicate_store_registration_is_rejected() {
229        let mut registry = StoreRegistry::new();
230        registry
231            .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
232            .expect("initial store registration should succeed");
233
234        let err = registry
235            .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
236            .expect_err("duplicate registration should fail");
237        assert_eq!(err.class, ErrorClass::InvariantViolation);
238        assert_eq!(err.origin, ErrorOrigin::Store);
239        assert!(
240            err.message
241                .contains("store 'store_registry_tests::Store' already registered"),
242            "duplicate registration should include the conflicting path"
243        );
244    }
245
246    #[test]
247    fn alias_store_registration_reusing_same_store_pair_is_rejected() {
248        let mut registry = StoreRegistry::new();
249        registry
250            .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
251            .expect("initial store registration should succeed");
252
253        let err = registry
254            .register_store(ALIAS_STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
255            .expect_err("alias registration reusing the same store pair should fail");
256        assert_eq!(err.class, ErrorClass::InvariantViolation);
257        assert_eq!(err.origin, ErrorOrigin::Store);
258        assert!(
259            err.message.contains(
260                "store 'store_registry_tests::StoreAlias' reuses the same row/index store pair"
261            ),
262            "alias registration should include conflicting alias path"
263        );
264        assert!(
265            err.message
266                .contains("registered as 'store_registry_tests::Store'"),
267            "alias registration should include original path"
268        );
269    }
270}