Skip to main content

icydb_core/db/
registry.rs

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