Skip to main content

foxtive_supervisor/persistence/
memory.rs

1use super::{PersistedTaskState, TaskStateStore};
2use std::collections::HashMap;
3use tokio::sync::Mutex;
4
5/// A default in-memory implementation of TaskStateStore (for reference/testing)
6pub struct InMemoryStateStore {
7    states: Mutex<HashMap<String, PersistedTaskState>>,
8}
9
10impl InMemoryStateStore {
11    pub fn new() -> Self {
12        Self {
13            states: Mutex::new(HashMap::new()),
14        }
15    }
16}
17
18impl Default for InMemoryStateStore {
19    fn default() -> Self {
20        Self::new()
21    }
22}
23
24#[async_trait::async_trait]
25impl TaskStateStore for InMemoryStateStore {
26    async fn save_state(&self, state: PersistedTaskState) -> anyhow::Result<()> {
27        let mut states = self.states.lock().await;
28        states.insert(state.task_id.clone(), state);
29        Ok(())
30    }
31
32    async fn load_state(&self, task_id: &str) -> anyhow::Result<Option<PersistedTaskState>> {
33        let states = self.states.lock().await;
34        Ok(states.get(task_id).cloned())
35    }
36
37    async fn load_all_states(&self) -> anyhow::Result<Vec<PersistedTaskState>> {
38        let states = self.states.lock().await;
39        Ok(states.values().cloned().collect())
40    }
41
42    async fn delete_state(&self, task_id: &str) -> anyhow::Result<()> {
43        let mut states = self.states.lock().await;
44        states.remove(task_id);
45        Ok(())
46    }
47}