Skip to main content

agent_storage/memory/
in_memory_storage.rs

1//! Process-local implementation of execution persistence contracts.
2
3use super::State;
4use crate::{
5    ConversationMessageStore, RunEventStore, RunStore, StorageError, StoredMessage, StoredRun,
6    StoredRunEvent, TaskRunStore, UsageStore,
7};
8use agent_metering::{ModelPricing, UsageRecord};
9use async_trait::async_trait;
10use std::sync::Arc;
11use tokio::sync::RwLock;
12use uuid::Uuid;
13
14/// A cloneable in-memory store implementing all execution storage contracts.
15#[derive(Clone, Default)]
16pub struct InMemoryStorage {
17    state: Arc<RwLock<State>>,
18}
19
20#[async_trait]
21impl RunStore for InMemoryStorage {
22    async fn insert_run(&self, run: StoredRun) -> Result<(), StorageError> {
23        let mut state = self.state.write().await;
24        if state.runs.contains_key(&run.id) {
25            return Err(StorageError::AlreadyExists(format!("run {}", run.id)));
26        }
27        state.runs.insert(run.id, run);
28        Ok(())
29    }
30
31    async fn update_run(&self, run: StoredRun) -> Result<(), StorageError> {
32        let mut state = self.state.write().await;
33        if !state.runs.contains_key(&run.id) {
34            return Err(StorageError::NotFound(format!("run {}", run.id)));
35        }
36        state.runs.insert(run.id, run);
37        Ok(())
38    }
39
40    async fn get_run(&self, id: Uuid) -> Result<Option<StoredRun>, StorageError> {
41        Ok(self.state.read().await.runs.get(&id).cloned())
42    }
43
44    async fn list_runs(
45        &self,
46        conversation_id: Option<Uuid>,
47    ) -> Result<Vec<StoredRun>, StorageError> {
48        let state = self.state.read().await;
49        let mut runs: Vec<_> = state
50            .runs
51            .values()
52            .filter(|run| conversation_id.is_none_or(|id| run.conversation_id == Some(id)))
53            .cloned()
54            .collect();
55        runs.sort_by(|left, right| {
56            right
57                .created_at
58                .cmp(&left.created_at)
59                .then_with(|| right.id.cmp(&left.id))
60        });
61        Ok(runs)
62    }
63}
64
65#[async_trait]
66impl TaskRunStore for InMemoryStorage {
67    async fn associate_task_run(&self, task_id: Uuid, run_id: Uuid) -> Result<(), StorageError> {
68        let mut state = self.state.write().await;
69        if !state.runs.contains_key(&run_id) {
70            return Err(StorageError::NotFound(format!("run {run_id}")));
71        }
72        if let Some(existing) = state.task_runs.get(&run_id) {
73            return if *existing == task_id {
74                Ok(())
75            } else {
76                Err(StorageError::InvalidAssociation(format!(
77                    "run {run_id} is already associated with task {existing}"
78                )))
79            };
80        }
81        state.task_runs.insert(run_id, task_id);
82        Ok(())
83    }
84
85    async fn list_task_runs(&self, task_id: Uuid) -> Result<Vec<StoredRun>, StorageError> {
86        let state = self.state.read().await;
87        let mut runs = state
88            .task_runs
89            .iter()
90            .filter(|(_, associated_task)| **associated_task == task_id)
91            .filter_map(|(run_id, _)| state.runs.get(run_id).cloned())
92            .collect::<Vec<_>>();
93        runs.sort_by(|left, right| {
94            right
95                .created_at
96                .cmp(&left.created_at)
97                .then_with(|| right.id.cmp(&left.id))
98        });
99        Ok(runs)
100    }
101}
102
103#[async_trait]
104impl RunEventStore for InMemoryStorage {
105    async fn append_event(&self, event: StoredRunEvent) -> Result<(), StorageError> {
106        let mut state = self.state.write().await;
107        if !state.runs.contains_key(&event.run_id) {
108            return Err(StorageError::NotFound(format!("run {}", event.run_id)));
109        }
110
111        let events = state.events.entry(event.run_id).or_default();
112        let expected = events.len() as u64;
113        if event.sequence < expected {
114            return Err(StorageError::DuplicateSequence {
115                stream: format!("run {}", event.run_id),
116                sequence: event.sequence,
117            });
118        }
119        if event.sequence > expected {
120            return Err(StorageError::OutOfOrderSequence {
121                stream: format!("run {}", event.run_id),
122                expected,
123                actual: event.sequence,
124            });
125        }
126        events.push(event);
127        Ok(())
128    }
129
130    async fn list_events(
131        &self,
132        run_id: Uuid,
133        after_sequence: Option<u64>,
134    ) -> Result<Vec<StoredRunEvent>, StorageError> {
135        let state = self.state.read().await;
136        if !state.runs.contains_key(&run_id) {
137            return Err(StorageError::NotFound(format!("run {run_id}")));
138        }
139        Ok(state
140            .events
141            .get(&run_id)
142            .into_iter()
143            .flatten()
144            .filter(|event| after_sequence.is_none_or(|cursor| event.sequence > cursor))
145            .cloned()
146            .collect())
147    }
148}
149
150#[async_trait]
151impl ConversationMessageStore for InMemoryStorage {
152    async fn append_message(&self, message: StoredMessage) -> Result<(), StorageError> {
153        let mut state = self.state.write().await;
154        if let Some(run_id) = message.run_id {
155            let Some(run) = state.runs.get(&run_id) else {
156                return Err(StorageError::NotFound(format!("run {run_id}")));
157            };
158            if run.conversation_id != Some(message.conversation_id) {
159                return Err(StorageError::InvalidAssociation(format!(
160                    "run {run_id} does not belong to conversation {}",
161                    message.conversation_id
162                )));
163            }
164        }
165
166        let messages = state.messages.entry(message.conversation_id).or_default();
167        let expected = messages.len() as u64;
168        if message.sequence < expected {
169            return Err(StorageError::DuplicateSequence {
170                stream: format!("conversation {}", message.conversation_id),
171                sequence: message.sequence,
172            });
173        }
174        if message.sequence > expected {
175            return Err(StorageError::OutOfOrderSequence {
176                stream: format!("conversation {}", message.conversation_id),
177                expected,
178                actual: message.sequence,
179            });
180        }
181        messages.push(message);
182        Ok(())
183    }
184
185    async fn list_messages(
186        &self,
187        conversation_id: Uuid,
188    ) -> Result<Vec<StoredMessage>, StorageError> {
189        Ok(self
190            .state
191            .read()
192            .await
193            .messages
194            .get(&conversation_id)
195            .cloned()
196            .unwrap_or_default())
197    }
198}
199
200#[async_trait]
201impl UsageStore for InMemoryStorage {
202    async fn append_usage(&self, record: UsageRecord) -> Result<(), StorageError> {
203        let mut state = self.state.write().await;
204        if !state.runs.contains_key(&record.run_id) {
205            return Err(StorageError::NotFound(format!("run {}", record.run_id)));
206        }
207        if let Some(existing) = state.usage.get(&record.invocation_id) {
208            return if existing == &record {
209                Ok(())
210            } else {
211                Err(StorageError::AlreadyExists(format!(
212                    "usage invocation {}",
213                    record.invocation_id
214                )))
215            };
216        }
217        state.usage.insert(record.invocation_id, record);
218        Ok(())
219    }
220
221    async fn list_usage(&self, run_id: Option<Uuid>) -> Result<Vec<UsageRecord>, StorageError> {
222        let state = self.state.read().await;
223        let mut records = state
224            .usage
225            .values()
226            .filter(|record| run_id.is_none_or(|id| record.run_id == id))
227            .cloned()
228            .collect::<Vec<_>>();
229        records.sort_by(|left, right| {
230            left.occurred_at
231                .cmp(&right.occurred_at)
232                .then_with(|| left.invocation_id.cmp(&right.invocation_id))
233        });
234        Ok(records)
235    }
236
237    async fn insert_pricing(&self, pricing: ModelPricing) -> Result<(), StorageError> {
238        pricing
239            .validate()
240            .map_err(|error| StorageError::Backend(error.to_string()))?;
241        let mut state = self.state.write().await;
242        let key = (
243            pricing.provider.clone(),
244            pricing.model.clone(),
245            pricing.version.clone(),
246        );
247        if state.pricing.contains_key(&key)
248            || state
249                .pricing
250                .values()
251                .any(|existing| existing.overlaps(&pricing))
252        {
253            return Err(StorageError::AlreadyExists(format!(
254                "pricing version or effective period already exists for {}:{}",
255                key.0, key.1
256            )));
257        }
258        state.pricing.insert(key, pricing);
259        Ok(())
260    }
261
262    async fn get_pricing(
263        &self,
264        provider: &str,
265        model: &str,
266        version: &str,
267    ) -> Result<Option<ModelPricing>, StorageError> {
268        Ok(self
269            .state
270            .read()
271            .await
272            .pricing
273            .get(&(provider.to_owned(), model.to_owned(), version.to_owned()))
274            .cloned())
275    }
276
277    async fn list_pricing(
278        &self,
279        provider: &str,
280        model: &str,
281    ) -> Result<Vec<ModelPricing>, StorageError> {
282        let state = self.state.read().await;
283        let mut prices = state
284            .pricing
285            .values()
286            .filter(|price| price.provider == provider && price.model == model)
287            .cloned()
288            .collect::<Vec<_>>();
289        prices.sort_by(|left, right| {
290            left.effective_from
291                .cmp(&right.effective_from)
292                .then_with(|| left.version.cmp(&right.version))
293        });
294        Ok(prices)
295    }
296
297    async fn list_all_pricing(&self) -> Result<Vec<ModelPricing>, StorageError> {
298        let state = self.state.read().await;
299        let mut prices = state.pricing.values().cloned().collect::<Vec<_>>();
300        prices.sort_by(|left, right| {
301            left.provider
302                .cmp(&right.provider)
303                .then_with(|| left.model.cmp(&right.model))
304                .then_with(|| left.effective_from.cmp(&right.effective_from))
305                .then_with(|| left.version.cmp(&right.version))
306        });
307        Ok(prices)
308    }
309}