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::{
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    /// Return whether the bound index store is currently valid for probe-free
100    /// covering authority.
101    #[must_use]
102    pub(in crate::db) fn index_is_valid(&self) -> bool {
103        self.with_index(IndexStore::is_valid)
104    }
105
106    /// Mark the bound index store as Building.
107    pub(in crate::db) fn mark_index_building(&self) {
108        self.with_index_mut(IndexStore::mark_building);
109    }
110
111    /// Mark the bound index store as Valid.
112    pub(in crate::db) fn mark_index_valid(&self) {
113        self.with_index_mut(IndexStore::mark_valid);
114    }
115
116    /// Return whether this store pair currently carries a synchronized
117    /// secondary covering-authority witness.
118    #[must_use]
119    pub(in crate::db) fn secondary_covering_authoritative(&self) -> bool {
120        self.with_data(DataStore::secondary_covering_authoritative)
121            && self.with_index(IndexStore::secondary_covering_authoritative)
122    }
123
124    /// Mark this row/index store pair as synchronized for witness-backed
125    /// secondary covering after successful commit or recovery.
126    pub(in crate::db) fn mark_secondary_covering_authoritative(&self) {
127        self.with_data_mut(DataStore::mark_secondary_covering_authoritative);
128        self.with_index_mut(IndexStore::mark_secondary_covering_authoritative);
129    }
130
131    /// Return whether this store pair currently carries one explicit
132    /// storage-owned secondary existence witness contract.
133    #[must_use]
134    pub(in crate::db) fn secondary_existence_witness_authoritative(&self) -> bool {
135        self.with_data(DataStore::secondary_existence_witness_authoritative)
136            && self.with_index(IndexStore::secondary_existence_witness_authoritative)
137    }
138
139    /// Mark this row/index store pair as synchronized for one explicit
140    /// storage-owned secondary existence witness contract.
141    pub(in crate::db) fn mark_secondary_existence_witness_authoritative(&self) {
142        self.with_data_mut(DataStore::mark_secondary_existence_witness_authoritative);
143        self.with_index_mut(IndexStore::mark_secondary_existence_witness_authoritative);
144    }
145
146    /// Return the raw row-store accessor.
147    #[must_use]
148    pub const fn data_store(&self) -> &'static LocalKey<RefCell<DataStore>> {
149        self.data
150    }
151
152    /// Return the raw index-store accessor.
153    #[must_use]
154    pub const fn index_store(&self) -> &'static LocalKey<RefCell<IndexStore>> {
155        self.index
156    }
157}
158
159///
160/// StoreRegistry
161/// Thread-local registry for both row and index stores.
162///
163
164#[derive(Default)]
165pub struct StoreRegistry {
166    stores: Vec<(&'static str, StoreHandle)>,
167}
168
169impl StoreRegistry {
170    /// Create an empty store registry.
171    #[must_use]
172    pub fn new() -> Self {
173        Self::default()
174    }
175
176    /// Iterate registered stores.
177    ///
178    /// Iteration order follows registration order. Semantic result ordering
179    /// must still not depend on this iteration order; callers that need
180    /// deterministic ordering must sort by store path.
181    pub fn iter(&self) -> impl Iterator<Item = (&'static str, StoreHandle)> {
182        self.stores.iter().copied()
183    }
184
185    /// Register a `Store` path to its row/index store pair.
186    pub fn register_store(
187        &mut self,
188        name: &'static str,
189        data: &'static LocalKey<RefCell<DataStore>>,
190        index: &'static LocalKey<RefCell<IndexStore>>,
191    ) -> Result<(), InternalError> {
192        if self
193            .stores
194            .iter()
195            .any(|(existing_name, _)| *existing_name == name)
196        {
197            return Err(StoreRegistryError::StoreAlreadyRegistered(name.to_string()).into());
198        }
199
200        // Keep one canonical logical store name per physical row/index store pair.
201        if let Some(existing_name) =
202            self.stores
203                .iter()
204                .find_map(|(existing_name, existing_handle)| {
205                    (std::ptr::eq(existing_handle.data_store(), data)
206                        && std::ptr::eq(existing_handle.index_store(), index))
207                    .then_some(*existing_name)
208                })
209        {
210            return Err(StoreRegistryError::StoreHandlePairAlreadyRegistered {
211                name: name.to_string(),
212                existing_name: existing_name.to_string(),
213            }
214            .into());
215        }
216
217        self.stores.push((name, StoreHandle::new(data, index)));
218
219        Ok(())
220    }
221
222    /// Look up a store handle by path.
223    pub fn try_get_store(&self, path: &str) -> Result<StoreHandle, InternalError> {
224        self.stores
225            .iter()
226            .find_map(|(existing_path, handle)| (*existing_path == path).then_some(*handle))
227            .ok_or_else(|| StoreRegistryError::StoreNotFound(path.to_string()).into())
228    }
229}
230
231///
232/// TESTS
233///
234
235#[cfg(test)]
236mod tests {
237    use crate::{
238        db::{data::DataStore, index::IndexStore, registry::StoreRegistry},
239        error::{ErrorClass, ErrorOrigin},
240        testing::test_memory,
241    };
242    use std::{cell::RefCell, ptr};
243
244    const STORE_PATH: &str = "store_registry_tests::Store";
245    const ALIAS_STORE_PATH: &str = "store_registry_tests::StoreAlias";
246
247    thread_local! {
248        static TEST_DATA_STORE: RefCell<DataStore> = RefCell::new(DataStore::init(test_memory(151)));
249        static TEST_INDEX_STORE: RefCell<IndexStore> =
250            RefCell::new(IndexStore::init(test_memory(152)));
251    }
252
253    fn test_registry() -> StoreRegistry {
254        let mut registry = StoreRegistry::new();
255        registry
256            .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
257            .expect("test store registration should succeed");
258        registry
259    }
260
261    #[test]
262    fn register_store_binds_data_and_index_handles() {
263        let registry = test_registry();
264        let handle = registry
265            .try_get_store(STORE_PATH)
266            .expect("registered store path should resolve");
267
268        assert!(
269            ptr::eq(handle.data_store(), &TEST_DATA_STORE),
270            "store handle should expose the registered data store accessor"
271        );
272        assert!(
273            ptr::eq(handle.index_store(), &TEST_INDEX_STORE),
274            "store handle should expose the registered index store accessor"
275        );
276
277        let data_rows = handle.with_data(|store| store.len());
278        let index_rows = handle.with_index(IndexStore::len);
279        assert_eq!(data_rows, 0, "fresh test data store should be empty");
280        assert_eq!(index_rows, 0, "fresh test index store should be empty");
281    }
282
283    #[test]
284    fn missing_store_path_rejected_before_access() {
285        let registry = StoreRegistry::new();
286        let err = registry
287            .try_get_store("store_registry_tests::Missing")
288            .expect_err("missing path should fail lookup");
289
290        assert_eq!(err.class, ErrorClass::Internal);
291        assert_eq!(err.origin, ErrorOrigin::Store);
292        assert!(
293            err.message
294                .contains("store 'store_registry_tests::Missing' not found"),
295            "missing store lookup should include the missing path"
296        );
297    }
298
299    #[test]
300    fn duplicate_store_registration_is_rejected() {
301        let mut registry = StoreRegistry::new();
302        registry
303            .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
304            .expect("initial store registration should succeed");
305
306        let err = registry
307            .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
308            .expect_err("duplicate registration should fail");
309        assert_eq!(err.class, ErrorClass::InvariantViolation);
310        assert_eq!(err.origin, ErrorOrigin::Store);
311        assert!(
312            err.message
313                .contains("store 'store_registry_tests::Store' already registered"),
314            "duplicate registration should include the conflicting path"
315        );
316    }
317
318    #[test]
319    fn alias_store_registration_reusing_same_store_pair_is_rejected() {
320        let mut registry = StoreRegistry::new();
321        registry
322            .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
323            .expect("initial store registration should succeed");
324
325        let err = registry
326            .register_store(ALIAS_STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
327            .expect_err("alias registration reusing the same store pair should fail");
328        assert_eq!(err.class, ErrorClass::InvariantViolation);
329        assert_eq!(err.origin, ErrorOrigin::Store);
330        assert!(
331            err.message.contains(
332                "store 'store_registry_tests::StoreAlias' reuses the same row/index store pair"
333            ),
334            "alias registration should include conflicting alias path"
335        );
336        assert!(
337            err.message
338                .contains("registered as 'store_registry_tests::Store'"),
339            "alias registration should include original path"
340        );
341    }
342}