millipede_core/storage/
kvs.rs1use super::StorageResult;
4use serde::{Serialize, de::DeserializeOwned};
5
6#[derive(Debug, Clone)]
8pub struct KvEntry {
9 pub key: String,
11 pub value: bytes::Bytes,
13 pub content_type: String,
15}
16
17#[derive(Debug, Clone, Default)]
19#[non_exhaustive]
20#[must_use = "list options do nothing unless passed to KeyValueStore::list_keys"]
21pub struct ListKeysOptions {
22 pub limit: Option<usize>,
24 pub exclusive_start_key: Option<String>,
26}
27
28#[derive(Debug, Clone)]
30pub struct KeyInfo {
31 pub key: String,
33 pub size: u64,
35}
36
37#[derive(Debug, Clone)]
39pub struct KeyList {
40 pub keys: Vec<KeyInfo>,
42 pub is_truncated: bool,
44 pub next_exclusive_start_key: Option<String>,
46}
47
48#[async_trait::async_trait]
50pub trait KeyValueStore: Send + Sync {
51 async fn get_bytes(&self, key: &str) -> StorageResult<Option<KvEntry>>;
53 async fn set_bytes(
55 &self,
56 key: &str,
57 bytes: bytes::Bytes,
58 content_type: &str,
59 ) -> StorageResult<()>;
60 async fn delete(&self, key: &str) -> StorageResult<()>;
62 async fn list_keys(&self, opts: ListKeysOptions) -> StorageResult<KeyList>;
64}
65
66#[async_trait::async_trait]
68pub trait KeyValueStoreExt: KeyValueStore {
69 async fn get<T: DeserializeOwned + 'static>(&self, key: &str) -> StorageResult<Option<T>> {
71 match self.get_bytes(key).await? {
72 Some(entry) => Ok(Some(serde_json::from_slice(&entry.value)?)),
73 None => Ok(None),
74 }
75 }
76
77 async fn set<T: Serialize + Send + Sync>(&self, key: &str, value: &T) -> StorageResult<()> {
79 self.set_bytes(key, serde_json::to_vec(value)?.into(), "application/json")
80 .await
81 }
82}
83
84impl<K: KeyValueStore + ?Sized> KeyValueStoreExt for K {}