use crate::error::Result;
use redb::{Database, ReadableDatabase, TableDefinition};
use serde::{Serialize, de::DeserializeOwned};
use std::path::Path;
use std::sync::Arc;
use tokio::task;
const DEFAULT_TABLE: TableDefinition<&str, &[u8]> = TableDefinition::new("kv_store");
#[derive(Clone)]
pub struct KVStore {
db: Arc<Database>,
}
impl KVStore {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
let db = Database::create(path)?;
let write_txn = db.begin_write()?;
{
let _ = write_txn.open_table(DEFAULT_TABLE)?;
}
write_txn.commit()?;
Ok(Self { db: Arc::new(db) })
}
pub async fn set<V>(&self, key: impl AsRef<str>, value: V) -> Result<()>
where
V: Serialize + Send + 'static,
{
let key = key.as_ref().to_string();
let db = self.db.clone();
task::spawn_blocking(move || {
let encoded = postcard::to_allocvec(&value)?;
let write_txn = db.begin_write()?;
{
let mut table = write_txn.open_table(DEFAULT_TABLE)?;
table.insert(key.as_str(), encoded.as_slice())?;
}
write_txn.commit()?;
Ok(())
})
.await?
}
pub async fn get<V>(&self, key: impl AsRef<str>) -> Result<Option<V>>
where
V: DeserializeOwned + Send + 'static,
{
let key = key.as_ref().to_string();
let db = self.db.clone();
task::spawn_blocking(move || {
let read_txn = db.begin_read()?;
let table = read_txn.open_table(DEFAULT_TABLE)?;
let value_access = table.get(key.as_str())?;
match value_access {
Some(access) => {
let decoded: V = postcard::from_bytes(access.value())?;
Ok(Some(decoded))
}
None => Ok(None),
}
})
.await?
}
pub async fn delete(&self, key: impl AsRef<str>) -> Result<()> {
let key = key.as_ref().to_string();
let db = self.db.clone();
task::spawn_blocking(move || {
let write_txn = db.begin_write()?;
{
let mut table = write_txn.open_table(DEFAULT_TABLE)?;
table.remove(key.as_str())?;
}
write_txn.commit()?;
Ok(())
})
.await?
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct TestData {
value: String,
count: u32,
}
#[tokio::test]
async fn test_set_and_get() {
let store = KVStore::open("test_set_get.redb").unwrap();
let data = TestData {
value: "hello".to_string(),
count: 42,
};
store.set("test_key", data.clone()).await.unwrap();
let result: Option<TestData> = store.get("test_key").await.unwrap();
assert_eq!(result, Some(data));
std::fs::remove_file("test_set_get.redb").ok();
}
#[tokio::test]
async fn test_get_nonexistent() {
let store = KVStore::open("test_nonexistent.redb").unwrap();
let result: Option<TestData> = store.get("does_not_exist").await.unwrap();
assert_eq!(result, None);
std::fs::remove_file("test_nonexistent.redb").ok();
}
#[tokio::test]
async fn test_delete() {
let store = KVStore::open("test_delete.redb").unwrap();
let data = TestData {
value: "test".to_string(),
count: 1,
};
store.set("key", data).await.unwrap();
store.delete("key").await.unwrap();
let result: Option<TestData> = store.get("key").await.unwrap();
assert_eq!(result, None);
std::fs::remove_file("test_delete.redb").ok();
}
#[tokio::test]
async fn test_overwrite() {
let store = KVStore::open("test_overwrite.redb").unwrap();
let data1 = TestData {
value: "first".to_string(),
count: 1,
};
let data2 = TestData {
value: "second".to_string(),
count: 2,
};
store.set("key", data1).await.unwrap();
store.set("key", data2.clone()).await.unwrap();
let result: Option<TestData> = store.get("key").await.unwrap();
assert_eq!(result, Some(data2));
std::fs::remove_file("test_overwrite.redb").ok();
}
#[tokio::test]
async fn test_multiple_keys() {
let store = KVStore::open("test_multiple.redb").unwrap();
let data1 = TestData {
value: "first".to_string(),
count: 1,
};
let data2 = TestData {
value: "second".to_string(),
count: 2,
};
store.set("key1", data1.clone()).await.unwrap();
store.set("key2", data2.clone()).await.unwrap();
let result1: Option<TestData> = store.get("key1").await.unwrap();
let result2: Option<TestData> = store.get("key2").await.unwrap();
assert_eq!(result1, Some(data1));
assert_eq!(result2, Some(data2));
std::fs::remove_file("test_multiple.redb").ok();
}
}