icydb_core/db/
registry.rs1use 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#[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#[derive(Clone, Copy, Debug)]
58pub struct StoreHandle {
59 data: &'static LocalKey<RefCell<DataStore>>,
60 index: &'static LocalKey<RefCell<IndexStore>>,
61}
62
63impl StoreHandle {
64 #[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 pub fn with_data<R>(&self, f: impl FnOnce(&DataStore) -> R) -> R {
75 self.data.with_borrow(f)
76 }
77
78 pub fn with_data_mut<R>(&self, f: impl FnOnce(&mut DataStore) -> R) -> R {
80 self.data.with_borrow_mut(f)
81 }
82
83 pub fn with_index<R>(&self, f: impl FnOnce(&IndexStore) -> R) -> R {
85 self.index.with_borrow(f)
86 }
87
88 pub fn with_index_mut<R>(&self, f: impl FnOnce(&mut IndexStore) -> R) -> R {
90 self.index.with_borrow_mut(f)
91 }
92
93 #[must_use]
95 pub(in crate::db) fn index_state(&self) -> IndexState {
96 self.with_index(IndexStore::state)
97 }
98
99 #[must_use]
102 pub(in crate::db) fn index_is_valid(&self) -> bool {
103 self.with_index(IndexStore::is_valid)
104 }
105
106 pub(in crate::db) fn mark_index_building(&self) {
108 self.with_index_mut(IndexStore::mark_building);
109 }
110
111 pub(in crate::db) fn mark_index_valid(&self) {
113 self.with_index_mut(IndexStore::mark_valid);
114 }
115
116 #[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 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 #[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 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 #[must_use]
148 pub const fn data_store(&self) -> &'static LocalKey<RefCell<DataStore>> {
149 self.data
150 }
151
152 #[must_use]
154 pub const fn index_store(&self) -> &'static LocalKey<RefCell<IndexStore>> {
155 self.index
156 }
157}
158
159#[derive(Default)]
165pub struct StoreRegistry {
166 stores: Vec<(&'static str, StoreHandle)>,
167}
168
169impl StoreRegistry {
170 #[must_use]
172 pub fn new() -> Self {
173 Self::default()
174 }
175
176 pub fn iter(&self) -> impl Iterator<Item = (&'static str, StoreHandle)> {
182 self.stores.iter().copied()
183 }
184
185 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 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 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#[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}