use super::StorageResult;
use serde::{Serialize, de::DeserializeOwned};
#[derive(Debug, Clone)]
pub struct KvEntry {
pub key: String,
pub value: bytes::Bytes,
pub content_type: String,
}
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
#[must_use = "list options do nothing unless passed to KeyValueStore::list_keys"]
pub struct ListKeysOptions {
pub limit: Option<usize>,
pub exclusive_start_key: Option<String>,
}
#[derive(Debug, Clone)]
pub struct KeyInfo {
pub key: String,
pub size: u64,
}
#[derive(Debug, Clone)]
pub struct KeyList {
pub keys: Vec<KeyInfo>,
pub is_truncated: bool,
pub next_exclusive_start_key: Option<String>,
}
#[async_trait::async_trait]
pub trait KeyValueStore: Send + Sync {
async fn get_bytes(&self, key: &str) -> StorageResult<Option<KvEntry>>;
async fn set_bytes(
&self,
key: &str,
bytes: bytes::Bytes,
content_type: &str,
) -> StorageResult<()>;
async fn delete(&self, key: &str) -> StorageResult<()>;
async fn list_keys(&self, opts: ListKeysOptions) -> StorageResult<KeyList>;
}
#[async_trait::async_trait]
pub trait KeyValueStoreExt: KeyValueStore {
async fn get<T: DeserializeOwned + 'static>(&self, key: &str) -> StorageResult<Option<T>> {
match self.get_bytes(key).await? {
Some(entry) => Ok(Some(serde_json::from_slice(&entry.value)?)),
None => Ok(None),
}
}
async fn set<T: Serialize + Send + Sync>(&self, key: &str, value: &T) -> StorageResult<()> {
self.set_bytes(key, serde_json::to_vec(value)?.into(), "application/json")
.await
}
}
impl<K: KeyValueStore + ?Sized> KeyValueStoreExt for K {}