wasmcloud_host/
store.rs

1//! Module with structs for use in managing and accessing data used by various wasmCloud entities
2use std::collections::HashMap;
3
4use bytes::Bytes;
5use tokio::sync::RwLock;
6use tracing::instrument;
7
8#[async_trait::async_trait]
9/// A trait for managing a store of data, such as a config store or a data store.
10pub trait StoreManager: Send + Sync {
11    /// Retrieves a value from the config store by key.
12    async fn get(&self, key: &str) -> anyhow::Result<Option<Bytes>>;
13
14    /// Inserts or updates a key-value pair in the config store.
15    async fn put(&self, key: &str, value: Bytes) -> anyhow::Result<()>;
16
17    /// Deletes a key from the config store.
18    async fn del(&self, key: &str) -> anyhow::Result<()>;
19}
20
21/// A struct that implements the StoreManager trait, storing data in an in-memory HashMap.
22#[derive(Default)]
23pub struct DefaultStore {
24    store: RwLock<HashMap<String, Bytes>>,
25}
26
27#[async_trait::async_trait]
28impl StoreManager for DefaultStore {
29    #[instrument(skip(self))]
30    async fn get(&self, key: &str) -> anyhow::Result<Option<Bytes>> {
31        Ok(self.store.read().await.get(key).cloned())
32    }
33
34    #[instrument(skip(self, value))]
35    async fn put(&self, key: &str, value: Bytes) -> anyhow::Result<()> {
36        self.store.write().await.insert(key.to_string(), value);
37        Ok(())
38    }
39
40    #[instrument(skip(self))]
41    async fn del(&self, key: &str) -> anyhow::Result<()> {
42        self.store.write().await.remove(key);
43        Ok(())
44    }
45}