#![cfg_attr(coverage_nightly, coverage(off))]
use super::*;
use parking_lot::RwLock;
use std::collections::BTreeMap;
#[async_trait::async_trait]
pub trait EventPersistence: Send + Sync {
async fn append_event(&self, event: &StateEvent) -> Result<(), EventStoreError>;
async fn append_batch(&self, events: &[StateEvent]) -> Result<(), EventStoreError>;
async fn load_all(&self) -> Result<Vec<StateEvent>, EventStoreError>;
async fn compact(&self, events: &BTreeMap<EventId, StateEvent>) -> Result<(), EventStoreError>;
}
#[derive(Default)]
pub struct InMemoryPersistence {
events: RwLock<Vec<StateEvent>>,
}
impl InMemoryPersistence {
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
pub fn new() -> Self {
Self::default()
}
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
pub fn len(&self) -> usize {
self.events.read().len()
}
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
pub fn is_empty(&self) -> bool {
self.events.read().is_empty()
}
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
pub fn clear(&self) {
self.events.write().clear();
}
}
#[async_trait::async_trait]
impl EventPersistence for InMemoryPersistence {
async fn append_event(&self, event: &StateEvent) -> Result<(), EventStoreError> {
self.events.write().push(event.clone());
Ok(())
}
async fn append_batch(&self, events: &[StateEvent]) -> Result<(), EventStoreError> {
self.events.write().extend(events.iter().cloned());
Ok(())
}
async fn load_all(&self) -> Result<Vec<StateEvent>, EventStoreError> {
Ok(self.events.read().clone())
}
async fn compact(&self, events: &BTreeMap<EventId, StateEvent>) -> Result<(), EventStoreError> {
let mut persisted = self.events.write();
persisted.clear();
persisted.extend(events.values().cloned());
Ok(())
}
}