Skip to main content

agent_effects_memory/
lib.rs

1//! In-memory store for [`agent-effects`](https://crates.io/crates/agent-effects).
2//!
3//! For tests, examples and development. Nothing survives the process.
4
5use std::collections::{BTreeMap, HashMap};
6use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
7use std::time::{Duration, SystemTime};
8
9use agent_effects_store::{
10    EffectEvent, EffectId, EffectKey, EffectRecord, EffectStore, InsertOutcome, LateObservation,
11    Lease, ListQuery, NewEffect, PruneQuery, StoreError, TransitionRequest, WorkerId,
12};
13
14/// An in-process store for tests, examples and development.
15///
16/// Nothing survives the process. Clones share the same data, so a test can
17/// drop a runtime and build a new one over the same store to simulate a
18/// restart.
19#[derive(Clone, Debug, Default)]
20pub struct MemoryStore {
21    inner: Arc<Mutex<Inner>>,
22}
23
24#[derive(Debug, Default)]
25struct Inner {
26    records: BTreeMap<EffectId, EffectRecord>,
27    by_key: HashMap<EffectKey, EffectId>,
28    events: HashMap<EffectId, Vec<EffectEvent>>,
29    late: BTreeMap<EffectId, LateObservation>,
30}
31
32impl MemoryStore {
33    /// An empty store.
34    pub fn new() -> Self {
35        Self::default()
36    }
37
38    /// The number of records.
39    pub fn len(&self) -> usize {
40        self.lock().records.len()
41    }
42
43    /// Whether the store has no records.
44    pub fn is_empty(&self) -> bool {
45        self.len() == 0
46    }
47
48    fn lock(&self) -> MutexGuard<'_, Inner> {
49        // Every mutation completes before the guard drops, so a panic while
50        // holding it cannot leave a half-applied change behind.
51        self.inner.lock().unwrap_or_else(PoisonError::into_inner)
52    }
53
54    fn with_record<T>(
55        &self,
56        id: EffectId,
57        f: impl FnOnce(&mut EffectRecord) -> Result<T, StoreError>,
58    ) -> Result<T, StoreError> {
59        let mut inner = self.lock();
60        let record = inner.records.get_mut(&id).ok_or(StoreError::NotFound(id))?;
61        // Work on a copy so a failed check cannot leave a partial change.
62        let mut updated = record.clone();
63        let result = f(&mut updated)?;
64        *record = updated;
65        Ok(result)
66    }
67}
68
69// Every operation completes under one lock without awaiting; the methods are
70// `async` only to satisfy the trait.
71#[allow(unknown_lints, clippy::unused_async_trait_impl)]
72impl EffectStore for MemoryStore {
73    async fn append_late_observation(
74        &self,
75        observation: LateObservation,
76    ) -> Result<(), StoreError> {
77        let mut inner = self.lock();
78        if !inner.records.contains_key(&observation.effect_id) {
79            return Err(StoreError::NotFound(observation.effect_id));
80        }
81        inner.late.entry(observation.id).or_insert(observation);
82        Ok(())
83    }
84
85    async fn late_observations(
86        &self,
87        id: EffectId,
88        after: Option<EffectId>,
89        limit: usize,
90    ) -> Result<Vec<LateObservation>, StoreError> {
91        let inner = self.lock();
92        if !inner.records.contains_key(&id) {
93            return Err(StoreError::NotFound(id));
94        }
95        Ok(inner
96            .late
97            .values()
98            .filter(|observation| {
99                observation.effect_id == id && after.is_none_or(|after| observation.id > after)
100            })
101            .take(limit)
102            .cloned()
103            .collect())
104    }
105    async fn insert_or_get(&self, new: NewEffect) -> Result<InsertOutcome, StoreError> {
106        let mut inner = self.lock();
107        if let Some(id) = inner.by_key.get(&new.key) {
108            return Ok(InsertOutcome {
109                record: inner.records[id].clone(),
110                inserted: false,
111            });
112        }
113        let record = EffectRecord::new(new);
114        inner.by_key.insert(record.key.clone(), record.id);
115        inner.records.insert(record.id, record.clone());
116        Ok(InsertOutcome {
117            record,
118            inserted: true,
119        })
120    }
121
122    async fn get(&self, id: EffectId) -> Result<Option<EffectRecord>, StoreError> {
123        Ok(self.lock().records.get(&id).cloned())
124    }
125
126    async fn get_by_key(&self, key: &EffectKey) -> Result<Option<EffectRecord>, StoreError> {
127        let inner = self.lock();
128        Ok(inner.by_key.get(key).map(|id| inner.records[id].clone()))
129    }
130
131    async fn acquire_lease(
132        &self,
133        id: EffectId,
134        owner: &WorkerId,
135        now: SystemTime,
136        ttl: Duration,
137    ) -> Result<Lease, StoreError> {
138        self.with_record(id, |record| record.acquire_lease(owner, now, ttl))
139    }
140
141    async fn renew_lease(
142        &self,
143        lease: &Lease,
144        now: SystemTime,
145        ttl: Duration,
146    ) -> Result<Lease, StoreError> {
147        self.with_record(lease.effect_id, |record| {
148            record.renew_lease(lease, now, ttl)
149        })
150    }
151
152    async fn release_lease(&self, lease: &Lease) -> Result<(), StoreError> {
153        self.with_record(lease.effect_id, |record| {
154            record.release_lease(lease);
155            Ok(())
156        })
157    }
158
159    async fn transition(&self, request: TransitionRequest) -> Result<EffectRecord, StoreError> {
160        let mut inner = self.lock();
161        let id = request.id;
162        let record = inner.records.get_mut(&id).ok_or(StoreError::NotFound(id))?;
163        let mut updated = record.clone();
164        let event = updated.apply(request)?;
165        *record = updated.clone();
166        inner.events.entry(id).or_default().push(event);
167        Ok(updated)
168    }
169
170    async fn list(&self, query: ListQuery) -> Result<Vec<EffectRecord>, StoreError> {
171        Ok(self
172            .lock()
173            .records
174            .values()
175            .filter(|record| query.matches(record))
176            .take(query.limit)
177            .cloned()
178            .collect())
179    }
180
181    async fn events(&self, id: EffectId) -> Result<Vec<EffectEvent>, StoreError> {
182        let inner = self.lock();
183        if !inner.records.contains_key(&id) {
184            return Err(StoreError::NotFound(id));
185        }
186        Ok(inner.events.get(&id).cloned().unwrap_or_default())
187    }
188
189    async fn prune(&self, query: PruneQuery) -> Result<u64, StoreError> {
190        let mut inner = self.lock();
191        let doomed: Vec<EffectId> = inner
192            .records
193            .values()
194            .filter(|record| query.matches(record))
195            .take(query.limit)
196            .map(|record| record.id)
197            .collect();
198        for id in &doomed {
199            if let Some(record) = inner.records.remove(id) {
200                inner.by_key.remove(&record.key);
201            }
202            inner.events.remove(id);
203            inner
204                .late
205                .retain(|_, observation| observation.effect_id != *id);
206        }
207        Ok(doomed.len() as u64)
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::MemoryStore;
214
215    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
216    async fn passes_the_conformance_suite() {
217        agent_effects_store::testkit::conformance(|| async { MemoryStore::new() }).await;
218    }
219}