Skip to main content

adk_kernel/stores/
agenda_memory.rs

1//! The in-memory [`AgendaStore`] (spec 3.2 §7.5, §13 Q8).
2
3use std::collections::BTreeMap;
4
5use async_trait::async_trait;
6use tokio::sync::RwLock;
7
8use crate::agenda::{AgendaFilter, AgendaItem, AgendaStateKind, AgendaStore};
9use crate::error::Result;
10
11/// An [`AgendaStore`] in process memory, for tests and a kernel with no durable store
12/// (spec 3.2 §7.5). Its items end with the process.
13///
14/// # Example
15///
16/// ```rust
17/// use adk_core::principal::SubjectRef;
18/// use adk_kernel::{AgendaFilter, AgendaItem, AgendaOrigin, AgendaStore, InMemoryAgendaStore};
19///
20/// # #[tokio::main(flavor = "current_thread")]
21/// # async fn main() -> adk_kernel::Result<()> {
22/// let store = InMemoryAgendaStore::new();
23/// let now = chrono::Utc::now();
24/// store.put(AgendaItem::new("b", SubjectRef::human("alice"), "t", "r", AgendaOrigin::User, now)).await?;
25/// store.put(AgendaItem::new("a", SubjectRef::human("alice"), "t", "r", AgendaOrigin::User, now)).await?;
26/// let ids: Vec<_> = store.list(&AgendaFilter::default()).await?.into_iter().map(|item| item.id).collect();
27/// assert_eq!(ids, ["a", "b"]);
28/// # Ok(())
29/// # }
30/// ```
31#[derive(Debug, Default)]
32pub struct InMemoryAgendaStore {
33    items: RwLock<BTreeMap<String, AgendaItem>>,
34}
35
36impl InMemoryAgendaStore {
37    /// An empty store.
38    pub fn new() -> Self {
39        Self::default()
40    }
41}
42
43#[async_trait]
44impl AgendaStore for InMemoryAgendaStore {
45    async fn put(&self, item: AgendaItem) -> Result<()> {
46        self.items.write().await.insert(item.id.clone(), item);
47        Ok(())
48    }
49
50    async fn get(&self, id: &str) -> Result<Option<AgendaItem>> {
51        Ok(self.items.read().await.get(id).cloned())
52    }
53
54    async fn list(&self, filter: &AgendaFilter) -> Result<Vec<AgendaItem>> {
55        let items = self.items.read().await;
56        let mut matched: Vec<AgendaItem> =
57            items.values().filter(|item| filter.matches(item)).cloned().collect();
58        matched.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.id.cmp(&b.id)));
59        if let Some(limit) = filter.limit {
60            matched.truncate(limit);
61        }
62        Ok(matched)
63    }
64
65    async fn transition(&self, item: AgendaItem, from: AgendaStateKind) -> Result<bool> {
66        let mut items = self.items.write().await;
67        match items.get_mut(&item.id) {
68            Some(stored) if stored.state.kind() == from => {
69                *stored = item;
70                Ok(true)
71            }
72            Some(_) | None => Ok(false),
73        }
74    }
75
76    async fn delete(&self, id: &str) -> Result<bool> {
77        Ok(self.items.write().await.remove(id).is_some())
78    }
79}