commonware_storage/
store.rs

1//! Traits for interacting with a storage system.
2
3use std::future::Future;
4
5/// A read-only key-value store.
6pub trait Store {
7    type Key;
8    type Value;
9    type Error;
10
11    /// Get the value of a key.
12    fn get(
13        &self,
14        key: &Self::Key,
15    ) -> impl Future<Output = Result<Option<Self::Value>, Self::Error>>;
16}
17
18/// A mutable key-value store.
19pub trait StoreMut: Store {
20    /// Update the value of a key.
21    fn update(
22        &mut self,
23        key: Self::Key,
24        value: Self::Value,
25    ) -> impl Future<Output = Result<(), Self::Error>>;
26
27    /// Updates the value associated with the given key in the store, inserting a default value if
28    /// the key does not already exist.
29    fn upsert(
30        &mut self,
31        key: Self::Key,
32        update: impl FnOnce(&mut Self::Value),
33    ) -> impl Future<Output = Result<(), Self::Error>>
34    where
35        Self::Value: Default,
36    {
37        async {
38            let mut value = self.get(&key).await?.unwrap_or_default();
39            update(&mut value);
40
41            self.update(key, value).await
42        }
43    }
44
45    /// Creates a new key-value pair in the db.
46    /// Returns true if the key was created, false if it already existed.
47    fn create(
48        &mut self,
49        key: Self::Key,
50        value: Self::Value,
51    ) -> impl Future<Output = Result<bool, Self::Error>> {
52        async {
53            if self.get(&key).await?.is_some() {
54                return Ok(false);
55            }
56
57            self.update(key, value).await?;
58            Ok(true)
59        }
60    }
61}
62
63/// A mutable key-value store that supports deleting values.
64pub trait StoreDeletable: StoreMut {
65    /// Delete the value of a key.
66    ///
67    /// Returns `true` if the key existed and was deleted, `false` if it did not exist.
68    fn delete(&mut self, key: Self::Key) -> impl Future<Output = Result<bool, Self::Error>>;
69}
70
71/// A mutable key-value store that can be persisted.
72pub trait StorePersistable: StoreMut {
73    /// Commit the store to disk, ensuring all changes are durably persisted.
74    fn commit(&mut self) -> impl Future<Output = Result<(), Self::Error>>;
75
76    /// Destroy the store, removing all persisted data.
77    fn destroy(self) -> impl Future<Output = Result<(), Self::Error>>;
78}