kotoba_db_core/
engine.rs

1use anyhow::Result;
2use super::types::{Block, Cid};
3
4/// A trait for pluggable storage engines.
5/// This defines the basic key-value interface that the database core uses.
6#[async_trait::async_trait]
7pub trait StorageEngine: Send + Sync {
8    /// Puts a key-value pair into the store.
9    async fn put(&mut self, key: &[u8], value: &[u8]) -> Result<()>;
10
11    /// Gets a value from the store by its key.
12    async fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>;
13
14    /// Deletes a key-value pair from the store.
15    async fn delete(&mut self, key: &[u8]) -> Result<()>;
16
17    /// Scans a range of keys with a given prefix.
18    async fn scan(&self, prefix: &[u8]) -> Result<Vec<(Vec<u8>, Vec<u8>)>>;
19}
20
21impl dyn StorageEngine {
22    /// Stores a content-addressed block in the database.
23    /// Returns the CID of the stored block.
24    pub async fn put_block(&mut self, block: &Block) -> Result<Cid> {
25        let cid = block.cid()?;
26        let bytes = block.to_bytes()?;
27        self.put(&cid, &bytes).await?;
28        Ok(cid)
29    }
30
31    /// Retrieves a content-addressed block from the database by its CID.
32    pub async fn get_block(&self, cid: &Cid) -> Result<Option<Block>> {
33        match self.get(cid).await? {
34            Some(bytes) => {
35                let block = Block::from_bytes(&bytes)?;
36                Ok(Some(block))
37            }
38            None => Ok(None),
39        }
40    }
41}