Skip to main content

icydb_core/db/
registry.rs

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