use crate::db_operations::DbOperations;
use crate::schema::SchemaError;
use serde::{de::DeserializeOwned, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Clone)]
pub struct DbOperationsSync {
inner: Arc<DbOperations>,
}
impl DbOperationsSync {
pub fn new(db_ops: DbOperations) -> Self {
Self {
inner: Arc::new(db_ops),
}
}
pub fn from_sled(db: sled::Db) -> Result<Self, crate::storage::StorageError> {
let db_ops = match tokio::runtime::Handle::try_current() {
Ok(handle) => {
handle.block_on(DbOperations::from_sled(db))?
}
Err(_) => {
let runtime =
tokio::runtime::Runtime::new().expect("Failed to create Tokio runtime");
runtime.block_on(DbOperations::from_sled(db))?
}
};
Ok(Self {
inner: Arc::new(db_ops),
})
}
pub fn inner(&self) -> &Arc<DbOperations> {
&self.inner
}
fn block_on<F: std::future::Future>(&self, future: F) -> F::Output {
match tokio::runtime::Handle::try_current() {
Ok(handle) => {
handle.block_on(future)
}
Err(_) => {
let runtime =
tokio::runtime::Runtime::new().expect("Failed to create Tokio runtime");
runtime.block_on(future)
}
}
}
pub fn store_item<T: Serialize + Send + Sync>(
&self,
key: &str,
item: &T,
) -> Result<(), SchemaError> {
self.block_on(self.inner.store_item(key, item))
}
pub fn get_item<T: DeserializeOwned + Send + Sync>(
&self,
key: &str,
) -> Result<Option<T>, SchemaError> {
self.block_on(self.inner.get_item(key))
}
pub fn delete_item(&self, key: &str) -> Result<bool, SchemaError> {
self.block_on(self.inner.delete_item(key))
}
pub fn list_items_with_prefix(&self, prefix: &str) -> Result<Vec<String>, SchemaError> {
self.block_on(self.inner.list_items_with_prefix(prefix))
}
pub fn store_in_namespace<T: Serialize + Send + Sync>(
&self,
namespace: &str,
key: &str,
item: &T,
) -> Result<(), SchemaError> {
self.block_on(self.inner.store_in_namespace(namespace, key, item))
}
pub fn get_from_namespace<T: DeserializeOwned + Send + Sync>(
&self,
namespace: &str,
key: &str,
) -> Result<Option<T>, SchemaError> {
self.block_on(self.inner.get_from_namespace(namespace, key))
}
pub fn list_keys_in_namespace(&self, namespace: &str) -> Result<Vec<String>, SchemaError> {
self.block_on(self.inner.list_keys_in_namespace(namespace))
}
pub fn delete_from_namespace(&self, namespace: &str, key: &str) -> Result<bool, SchemaError> {
self.block_on(self.inner.delete_from_namespace(namespace, key))
}
pub fn batch_store_items<T: Serialize + Send + Sync + Clone>(
&self,
items: &[(String, T)],
) -> Result<(), SchemaError> {
self.block_on(self.inner.batch_store_items(items))
}
pub fn get_stats(&self) -> Result<HashMap<String, u64>, SchemaError> {
self.block_on(self.inner.get_stats())
}
}