Skip to main content

adk_kernel/stores/
partition_memory.rs

1//! The in-memory [`PartitionStore`] (spec 3.2 §7.8, §13 Q8).
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use async_trait::async_trait;
6use tokio::sync::RwLock;
7
8use crate::error::Result;
9use crate::partition::{CrossingFilter, CrossingRecord, Partition, PartitionId, PartitionStore};
10
11/// A [`PartitionStore`] in process memory, for tests and a kernel with no durable store
12/// (spec 3.2 §7.8). Its records end with the process.
13///
14/// # Example
15///
16/// ```rust
17/// use adk_kernel::{InMemoryPartitionStore, Partition, PartitionStore};
18///
19/// # #[tokio::main(flavor = "current_thread")]
20/// # async fn main() -> adk_kernel::Result<()> {
21/// let store = InMemoryPartitionStore::new();
22/// store.put(Partition::new("work", "work")).await?;
23/// store.put(Partition::new("home", "home")).await?;
24/// let ids: Vec<_> = store.list().await?.into_iter().map(|p| p.id.to_string()).collect();
25/// assert_eq!(ids, ["home", "work"]);
26/// # Ok(())
27/// # }
28/// ```
29#[derive(Debug, Default)]
30pub struct InMemoryPartitionStore {
31    partitions: RwLock<BTreeMap<PartitionId, Partition>>,
32    crossings: RwLock<Vec<CrossingRecord>>,
33    /// (run, fingerprint digest) of each live grant.
34    grants: RwLock<BTreeSet<(String, String)>>,
35}
36
37impl InMemoryPartitionStore {
38    /// An empty store.
39    pub fn new() -> Self {
40        Self::default()
41    }
42}
43
44#[async_trait]
45impl PartitionStore for InMemoryPartitionStore {
46    async fn put(&self, partition: Partition) -> Result<()> {
47        self.partitions.write().await.insert(partition.id.clone(), partition);
48        Ok(())
49    }
50
51    async fn get(&self, id: &PartitionId) -> Result<Option<Partition>> {
52        Ok(self.partitions.read().await.get(id).cloned())
53    }
54
55    async fn list(&self) -> Result<Vec<Partition>> {
56        Ok(self.partitions.read().await.values().cloned().collect())
57    }
58
59    async fn delete(&self, id: &PartitionId) -> Result<bool> {
60        Ok(self.partitions.write().await.remove(id).is_some())
61    }
62
63    async fn record_crossing(&self, record: CrossingRecord) -> Result<()> {
64        self.crossings.write().await.push(record);
65        Ok(())
66    }
67
68    async fn crossings(&self, filter: &CrossingFilter) -> Result<Vec<CrossingRecord>> {
69        let mut records: Vec<CrossingRecord> = self
70            .crossings
71            .read()
72            .await
73            .iter()
74            .filter(|record| filter.matches(record))
75            .cloned()
76            .collect();
77        records.sort_by(|a, b| a.at.cmp(&b.at).then_with(|| a.id.cmp(&b.id)));
78        records.truncate(filter.limit.unwrap_or(usize::MAX));
79        Ok(records)
80    }
81
82    async fn grant(&self, run: &str, fingerprint: &str) -> Result<()> {
83        self.grants.write().await.insert((run.to_string(), fingerprint.to_string()));
84        Ok(())
85    }
86
87    async fn grants(&self, run: &str) -> Result<Vec<String>> {
88        Ok(self
89            .grants
90            .read()
91            .await
92            .iter()
93            .filter(|(granted, _)| granted == run)
94            .map(|(_, fingerprint)| fingerprint.clone())
95            .collect())
96    }
97
98    async fn release_run(&self, run: &str) -> Result<u64> {
99        let mut grants = self.grants.write().await;
100        let before = grants.len();
101        grants.retain(|(granted, _)| granted != run);
102        Ok((before - grants.len()) as u64)
103    }
104}