refactor: apply zero-unwrap policy and optimize locks in store.rs and handlers

This commit is contained in:
Riz Ashraf committed 2026-09-21 11:34:21 +01:00
1 parent 9f24e66d88
commit 8afbf97b11
33 files changed
+3127 -3207

No files matched your search

+25 -24
View File
@@ -14,52 +14,53 @@ impl<T: DeserializeOwned + Default + Serialize + Clone + Send + Sync + 'static>
let initial_data = Self::load_from_db(key, &db);
let cache = Arc::new(RwLock::new(initial_data));
let (tx, mut rx) = tokio::sync::mpsc::channel::<()>(1);
let db_clone = db.clone();
let key_clone = key.to_string();
let cache_clone = cache.clone();
tokio::spawn(async move {
while rx.recv().await.is_some() {
// Drain any other pending notifications so we batch writes
while let Ok(_) = rx.try_recv() {}
while rx.try_recv().is_ok() {}
let db_inner = db_clone.clone();
let key_inner = key_clone.clone();
let json_data = {
let lock = cache_clone.read().unwrap();
serde_json::to_vec(&*lock).unwrap()
let lock = cache_clone.read().unwrap_or_else(|e| e.into_inner());
serde_json::to_vec(&*lock).unwrap_or_default()
};
let _ = tokio::task::spawn_blocking(move || {
let write_txn = db_inner.begin_write().unwrap();
{
let mut table = write_txn.open_table(STORE_TABLE).unwrap();
table.insert(key_inner.as_str(), json_data.as_slice()).unwrap();
if let Ok(write_txn) = db_inner.begin_write() {
if let Ok(mut table) = write_txn.open_table(STORE_TABLE) {
let _ = table.insert(key_inner.as_str(), json_data.as_slice());
}
let _ = write_txn.commit();
}
write_txn.commit().unwrap();
}).await;
})
.await;
}
});
Self {
cache,
tx,
}
Self { cache, tx }
}
fn load_from_db(key: &str, db: &Database) -> T {
let read_txn = db.begin_read().unwrap();
let Ok(read_txn) = db.begin_read() else {
return T::default();
};
if let Ok(table) = read_txn.open_table(STORE_TABLE)
&& let Ok(Some(value)) = table.get(key)
&& let Ok(parsed) = serde_json::from_slice::<T>(value.value()) {
return parsed;
}
&& let Ok(parsed) = serde_json::from_slice::<T>(value.value())
{
return parsed;
}
T::default()
}
pub fn read(&self) -> T {
let lock = self.cache.read().unwrap();
let lock = self.cache.read().unwrap_or_else(|e| e.into_inner());
lock.clone()
}
@@ -67,13 +68,13 @@ impl<T: DeserializeOwned + Default + Serialize + Clone + Send + Sync + 'static>
where
F: FnOnce(&T) -> R,
{
let lock = self.cache.read().unwrap();
let lock = self.cache.read().unwrap_or_else(|e| e.into_inner());
f(&lock)
}
pub fn modify<F: FnOnce(&mut T)>(&self, f: F) {
{
let mut lock = self.cache.write().unwrap();
let mut lock = self.cache.write().unwrap_or_else(|e| e.into_inner());
f(&mut lock);
}
let _ = self.tx.try_send(());