use serde::{Deserialize, Serialize};
use crate::kernel::identity::{RunId, Seq};
use crate::kernel::KernelError;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Snapshot<S> {
pub run_id: RunId,
pub at_seq: Seq,
pub state: S,
}
pub trait SnapshotStore<S>: Send + Sync {
fn load_latest(&self, run_id: &RunId) -> Result<Option<Snapshot<S>>, KernelError>;
fn save(&self, snapshot: &Snapshot<S>) -> Result<(), KernelError>;
}
pub struct InMemorySnapshotStore<S> {
latest: std::sync::RwLock<std::collections::HashMap<RunId, Snapshot<S>>>,
}
impl<S: Clone + Send + Sync> InMemorySnapshotStore<S> {
pub fn new() -> Self {
Self {
latest: std::sync::RwLock::new(std::collections::HashMap::new()),
}
}
}
impl<S: Clone + Send + Sync> Default for InMemorySnapshotStore<S> {
fn default() -> Self {
Self::new()
}
}
impl<S: Clone + Send + Sync> SnapshotStore<S> for InMemorySnapshotStore<S> {
fn load_latest(&self, run_id: &RunId) -> Result<Option<Snapshot<S>>, KernelError> {
let guard = self
.latest
.read()
.map_err(|e| KernelError::SnapshotStore(e.to_string()))?;
Ok(guard.get(run_id).cloned())
}
fn save(&self, snapshot: &Snapshot<S>) -> Result<(), KernelError> {
let mut guard = self
.latest
.write()
.map_err(|e| KernelError::SnapshotStore(e.to_string()))?;
guard.insert(snapshot.run_id.clone(), snapshot.clone());
Ok(())
}
}