Skip to main content

muta_protocol/traits/
storage.rs

1use async_trait::async_trait;
2use derive_more::Display;
3
4use crate::codec::ProtocolCodec;
5use crate::types::epoch::{Epoch, Proof};
6use crate::types::receipt::Receipt;
7use crate::types::{Hash, SignedTransaction};
8use crate::ProtocolResult;
9
10#[derive(Debug, Copy, Clone, Display)]
11pub enum StorageCategory {
12    Epoch,
13    Receipt,
14    SignedTransaction,
15}
16
17pub trait StorageSchema {
18    type Key: ProtocolCodec + Send;
19    type Value: ProtocolCodec + Send;
20
21    fn category() -> StorageCategory;
22}
23
24#[async_trait]
25pub trait Storage: Send + Sync {
26    async fn insert_transactions(&self, signed_txs: Vec<SignedTransaction>) -> ProtocolResult<()>;
27
28    async fn insert_epoch(&self, epoch: Epoch) -> ProtocolResult<()>;
29
30    async fn insert_receipts(&self, receipts: Vec<Receipt>) -> ProtocolResult<()>;
31
32    async fn update_latest_proof(&self, proof: Proof) -> ProtocolResult<()>;
33
34    async fn get_transaction_by_hash(&self, tx_hash: Hash) -> ProtocolResult<SignedTransaction>;
35
36    async fn get_transactions(&self, hashes: Vec<Hash>) -> ProtocolResult<Vec<SignedTransaction>>;
37
38    async fn get_latest_epoch(&self) -> ProtocolResult<Epoch>;
39
40    async fn get_epoch_by_epoch_id(&self, epoch_id: u64) -> ProtocolResult<Epoch>;
41
42    async fn get_epoch_by_hash(&self, epoch_hash: Hash) -> ProtocolResult<Epoch>;
43
44    async fn get_receipt(&self, hash: Hash) -> ProtocolResult<Receipt>;
45
46    async fn get_receipts(&self, hash: Vec<Hash>) -> ProtocolResult<Vec<Receipt>>;
47
48    async fn get_latest_proof(&self) -> ProtocolResult<Proof>;
49}
50
51pub enum StorageBatchModify<S: StorageSchema> {
52    Remove,
53    Insert(<S as StorageSchema>::Value),
54}
55
56#[async_trait]
57pub trait StorageAdapter: Send + Sync {
58    async fn insert<S: StorageSchema>(
59        &self,
60        key: <S as StorageSchema>::Key,
61        val: <S as StorageSchema>::Value,
62    ) -> ProtocolResult<()>;
63
64    async fn get<S: StorageSchema>(
65        &self,
66        key: <S as StorageSchema>::Key,
67    ) -> ProtocolResult<Option<<S as StorageSchema>::Value>>;
68
69    async fn get_batch<S: StorageSchema>(
70        &self,
71        keys: Vec<<S as StorageSchema>::Key>,
72    ) -> ProtocolResult<Vec<Option<<S as StorageSchema>::Value>>> {
73        let mut vec = Vec::new();
74
75        for key in keys {
76            vec.push(self.get::<S>(key).await?);
77        }
78
79        Ok(vec)
80    }
81
82    async fn remove<S: StorageSchema>(&self, key: <S as StorageSchema>::Key) -> ProtocolResult<()>;
83
84    async fn contains<S: StorageSchema>(
85        &self,
86        key: <S as StorageSchema>::Key,
87    ) -> ProtocolResult<bool>;
88
89    async fn batch_modify<S: StorageSchema>(
90        &self,
91        keys: Vec<<S as StorageSchema>::Key>,
92        vals: Vec<StorageBatchModify<S>>,
93    ) -> ProtocolResult<()>;
94}