churn/crates/churn-server/src/db.rs

80 lines
1.7 KiB
Rust
Raw Normal View History

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use async_trait::async_trait;
use churn_domain::ServerEnrollReq;
use tokio::sync::Mutex;
#[derive(Clone)]
pub struct Db(Arc<dyn DbTrait + Send + Sync + 'static>);
impl Db {
pub fn new_sled(path: &Path) -> Self {
Self(Arc::new(DefaultDb::new(path)))
}
}
impl std::ops::Deref for Db {
type Target = Arc<dyn DbTrait + Send + Sync + 'static>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Default for Db {
fn default() -> Self {
Self(Arc::new(DefaultDb::default()))
}
}
struct DefaultDb {
db: sled::Db,
}
impl Default for DefaultDb {
fn default() -> Self {
Self::new(&PathBuf::from("churn-server.sled"))
}
}
impl DefaultDb {
pub fn new(path: &Path) -> Self {
Self {
db: sled::open(path).expect("to be able open a sled path"),
}
}
}
#[async_trait]
pub trait DbTrait {
async fn insert(&self, namespace: &str, key: &str, value: &str) -> anyhow::Result<()>;
async fn get_all(&self, namespace: &str) -> anyhow::Result<Vec<String>>;
}
#[async_trait]
impl DbTrait for DefaultDb {
async fn insert(&self, namespace: &str, key: &str, value: &str) -> anyhow::Result<()> {
let tree = self.db.open_tree(namespace)?;
tree.insert(key, value)?;
tree.flush_async().await?;
Ok(())
}
async fn get_all(&self, namespace: &str) -> anyhow::Result<Vec<String>> {
let tree = self.db.open_tree(namespace)?;
Ok(tree
.iter()
.flatten()
.map(|(_, val)| val)
.flat_map(|v| v.iter().map(|v| v.to_string()).collect::<Vec<String>>())
.collect::<Vec<_>>())
}
}