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, Lease, ListQuery,
11    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}
30
31impl MemoryStore {
32    /// An empty store.
33    pub fn new() -> Self {
34        Self::default()
35    }
36
37    /// The number of records.
38    pub fn len(&self) -> usize {
39        self.lock().records.len()
40    }
41
42    /// Whether the store has no records.
43    pub fn is_empty(&self) -> bool {
44        self.len() == 0
45    }
46
47    fn lock(&self) -> MutexGuard<'_, Inner> {
48        // Every mutation completes before the guard drops, so a panic while
49        // holding it cannot leave a half-applied change behind.
50        self.inner.lock().unwrap_or_else(PoisonError::into_inner)
51    }
52
53    fn with_record<T>(
54        &self,
55        id: EffectId,
56        f: impl FnOnce(&mut EffectRecord) -> Result<T, StoreError>,
57    ) -> Result<T, StoreError> {
58        let mut inner = self.lock();
59        let record = inner.records.get_mut(&id).ok_or(StoreError::NotFound(id))?;
60        // Work on a copy so a failed check cannot leave a partial change.
61        let mut updated = record.clone();
62        let result = f(&mut updated)?;
63        *record = updated;
64        Ok(result)
65    }
66}
67
68// Every operation completes under one lock without awaiting; the methods are
69// `async` only to satisfy the trait.
70#[allow(unknown_lints, clippy::unused_async_trait_impl)]
71impl EffectStore for MemoryStore {
72    async fn insert_or_get(&self, new: NewEffect) -> Result<InsertOutcome, StoreError> {
73        let mut inner = self.lock();
74        if let Some(id) = inner.by_key.get(&new.key) {
75            return Ok(InsertOutcome {
76                record: inner.records[id].clone(),
77                inserted: false,
78            });
79        }
80        let record = EffectRecord::new(new);
81        inner.by_key.insert(record.key.clone(), record.id);
82        inner.records.insert(record.id, record.clone());
83        Ok(InsertOutcome {
84            record,
85            inserted: true,
86        })
87    }
88
89    async fn get(&self, id: EffectId) -> Result<Option<EffectRecord>, StoreError> {
90        Ok(self.lock().records.get(&id).cloned())
91    }
92
93    async fn get_by_key(&self, key: &EffectKey) -> Result<Option<EffectRecord>, StoreError> {
94        let inner = self.lock();
95        Ok(inner.by_key.get(key).map(|id| inner.records[id].clone()))
96    }
97
98    async fn acquire_lease(
99        &self,
100        id: EffectId,
101        owner: &WorkerId,
102        now: SystemTime,
103        ttl: Duration,
104    ) -> Result<Lease, StoreError> {
105        self.with_record(id, |record| record.acquire_lease(owner, now, ttl))
106    }
107
108    async fn renew_lease(
109        &self,
110        lease: &Lease,
111        now: SystemTime,
112        ttl: Duration,
113    ) -> Result<Lease, StoreError> {
114        self.with_record(lease.effect_id, |record| {
115            record.renew_lease(lease, now, ttl)
116        })
117    }
118
119    async fn release_lease(&self, lease: &Lease) -> Result<(), StoreError> {
120        self.with_record(lease.effect_id, |record| {
121            record.release_lease(lease);
122            Ok(())
123        })
124    }
125
126    async fn transition(&self, request: TransitionRequest) -> Result<EffectRecord, StoreError> {
127        let mut inner = self.lock();
128        let id = request.id;
129        let record = inner.records.get_mut(&id).ok_or(StoreError::NotFound(id))?;
130        let mut updated = record.clone();
131        let event = updated.apply(request)?;
132        *record = updated.clone();
133        inner.events.entry(id).or_default().push(event);
134        Ok(updated)
135    }
136
137    async fn list(&self, query: ListQuery) -> Result<Vec<EffectRecord>, StoreError> {
138        Ok(self
139            .lock()
140            .records
141            .values()
142            .filter(|record| query.matches(record))
143            .take(query.limit)
144            .cloned()
145            .collect())
146    }
147
148    async fn events(&self, id: EffectId) -> Result<Vec<EffectEvent>, StoreError> {
149        let inner = self.lock();
150        if !inner.records.contains_key(&id) {
151            return Err(StoreError::NotFound(id));
152        }
153        Ok(inner.events.get(&id).cloned().unwrap_or_default())
154    }
155
156    async fn prune(&self, query: PruneQuery) -> Result<u64, StoreError> {
157        let mut inner = self.lock();
158        let doomed: Vec<EffectId> = inner
159            .records
160            .values()
161            .filter(|record| query.matches(record))
162            .take(query.limit)
163            .map(|record| record.id)
164            .collect();
165        for id in &doomed {
166            if let Some(record) = inner.records.remove(id) {
167                inner.by_key.remove(&record.key);
168            }
169            inner.events.remove(id);
170        }
171        Ok(doomed.len() as u64)
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::MemoryStore;
178
179    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
180    async fn passes_the_conformance_suite() {
181        agent_effects_store::testkit::conformance(|| async { MemoryStore::new() }).await;
182    }
183}