icydb_core/db/
registry.rs1use 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#[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#[derive(Clone, Copy, Debug)]
55pub struct StoreHandle {
56 data: &'static LocalKey<RefCell<DataStore>>,
57 index: &'static LocalKey<RefCell<IndexStore>>,
58}
59
60impl StoreHandle {
61 #[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 pub fn with_data<R>(&self, f: impl FnOnce(&DataStore) -> R) -> R {
72 self.data.with_borrow(f)
73 }
74
75 pub fn with_data_mut<R>(&self, f: impl FnOnce(&mut DataStore) -> R) -> R {
77 self.data.with_borrow_mut(f)
78 }
79
80 pub fn with_index<R>(&self, f: impl FnOnce(&IndexStore) -> R) -> R {
82 self.index.with_borrow(f)
83 }
84
85 pub fn with_index_mut<R>(&self, f: impl FnOnce(&mut IndexStore) -> R) -> R {
87 self.index.with_borrow_mut(f)
88 }
89
90 #[must_use]
93 pub(in crate::db) fn secondary_covering_authoritative(&self) -> bool {
94 self.with_data(DataStore::secondary_covering_authoritative)
95 && self.with_index(IndexStore::secondary_covering_authoritative)
96 }
97
98 pub(in crate::db) fn mark_secondary_covering_authoritative(&self) {
101 self.with_data_mut(DataStore::mark_secondary_covering_authoritative);
102 self.with_index_mut(IndexStore::mark_secondary_covering_authoritative);
103 }
104
105 #[must_use]
107 pub const fn data_store(&self) -> &'static LocalKey<RefCell<DataStore>> {
108 self.data
109 }
110
111 #[must_use]
113 pub const fn index_store(&self) -> &'static LocalKey<RefCell<IndexStore>> {
114 self.index
115 }
116}
117
118#[derive(Default)]
124pub struct StoreRegistry {
125 stores: Vec<(&'static str, StoreHandle)>,
126}
127
128impl StoreRegistry {
129 #[must_use]
131 pub fn new() -> Self {
132 Self::default()
133 }
134
135 pub fn iter(&self) -> impl Iterator<Item = (&'static str, StoreHandle)> {
141 self.stores.iter().copied()
142 }
143
144 pub fn register_store(
146 &mut self,
147 name: &'static str,
148 data: &'static LocalKey<RefCell<DataStore>>,
149 index: &'static LocalKey<RefCell<IndexStore>>,
150 ) -> Result<(), InternalError> {
151 if self
152 .stores
153 .iter()
154 .any(|(existing_name, _)| *existing_name == name)
155 {
156 return Err(StoreRegistryError::StoreAlreadyRegistered(name.to_string()).into());
157 }
158
159 if let Some(existing_name) =
161 self.stores
162 .iter()
163 .find_map(|(existing_name, existing_handle)| {
164 (std::ptr::eq(existing_handle.data_store(), data)
165 && std::ptr::eq(existing_handle.index_store(), index))
166 .then_some(*existing_name)
167 })
168 {
169 return Err(StoreRegistryError::StoreHandlePairAlreadyRegistered {
170 name: name.to_string(),
171 existing_name: existing_name.to_string(),
172 }
173 .into());
174 }
175
176 self.stores.push((name, StoreHandle::new(data, index)));
177
178 Ok(())
179 }
180
181 pub fn try_get_store(&self, path: &str) -> Result<StoreHandle, InternalError> {
183 self.stores
184 .iter()
185 .find_map(|(existing_path, handle)| (*existing_path == path).then_some(*handle))
186 .ok_or_else(|| StoreRegistryError::StoreNotFound(path.to_string()).into())
187 }
188}
189
190#[cfg(test)]
195mod tests {
196 use crate::{
197 db::{data::DataStore, index::IndexStore, registry::StoreRegistry},
198 error::{ErrorClass, ErrorOrigin},
199 testing::test_memory,
200 };
201 use std::{cell::RefCell, ptr};
202
203 const STORE_PATH: &str = "store_registry_tests::Store";
204 const ALIAS_STORE_PATH: &str = "store_registry_tests::StoreAlias";
205
206 thread_local! {
207 static TEST_DATA_STORE: RefCell<DataStore> = RefCell::new(DataStore::init(test_memory(151)));
208 static TEST_INDEX_STORE: RefCell<IndexStore> =
209 RefCell::new(IndexStore::init(test_memory(152)));
210 }
211
212 fn test_registry() -> StoreRegistry {
213 let mut registry = StoreRegistry::new();
214 registry
215 .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
216 .expect("test store registration should succeed");
217 registry
218 }
219
220 #[test]
221 fn register_store_binds_data_and_index_handles() {
222 let registry = test_registry();
223 let handle = registry
224 .try_get_store(STORE_PATH)
225 .expect("registered store path should resolve");
226
227 assert!(
228 ptr::eq(handle.data_store(), &TEST_DATA_STORE),
229 "store handle should expose the registered data store accessor"
230 );
231 assert!(
232 ptr::eq(handle.index_store(), &TEST_INDEX_STORE),
233 "store handle should expose the registered index store accessor"
234 );
235
236 let data_rows = handle.with_data(|store| store.len());
237 let index_rows = handle.with_index(IndexStore::len);
238 assert_eq!(data_rows, 0, "fresh test data store should be empty");
239 assert_eq!(index_rows, 0, "fresh test index store should be empty");
240 }
241
242 #[test]
243 fn missing_store_path_rejected_before_access() {
244 let registry = StoreRegistry::new();
245 let err = registry
246 .try_get_store("store_registry_tests::Missing")
247 .expect_err("missing path should fail lookup");
248
249 assert_eq!(err.class, ErrorClass::Internal);
250 assert_eq!(err.origin, ErrorOrigin::Store);
251 assert!(
252 err.message
253 .contains("store 'store_registry_tests::Missing' not found"),
254 "missing store lookup should include the missing path"
255 );
256 }
257
258 #[test]
259 fn duplicate_store_registration_is_rejected() {
260 let mut registry = StoreRegistry::new();
261 registry
262 .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
263 .expect("initial store registration should succeed");
264
265 let err = registry
266 .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
267 .expect_err("duplicate registration should fail");
268 assert_eq!(err.class, ErrorClass::InvariantViolation);
269 assert_eq!(err.origin, ErrorOrigin::Store);
270 assert!(
271 err.message
272 .contains("store 'store_registry_tests::Store' already registered"),
273 "duplicate registration should include the conflicting path"
274 );
275 }
276
277 #[test]
278 fn alias_store_registration_reusing_same_store_pair_is_rejected() {
279 let mut registry = StoreRegistry::new();
280 registry
281 .register_store(STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
282 .expect("initial store registration should succeed");
283
284 let err = registry
285 .register_store(ALIAS_STORE_PATH, &TEST_DATA_STORE, &TEST_INDEX_STORE)
286 .expect_err("alias registration reusing the same store pair should fail");
287 assert_eq!(err.class, ErrorClass::InvariantViolation);
288 assert_eq!(err.origin, ErrorOrigin::Store);
289 assert!(
290 err.message.contains(
291 "store 'store_registry_tests::StoreAlias' reuses the same row/index store pair"
292 ),
293 "alias registration should include conflicting alias path"
294 );
295 assert!(
296 err.message
297 .contains("registered as 'store_registry_tests::Store'"),
298 "alias registration should include original path"
299 );
300 }
301}