adk_kernel/stores/
partition_memory.rs1use 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#[derive(Debug, Default)]
30pub struct InMemoryPartitionStore {
31 partitions: RwLock<BTreeMap<PartitionId, Partition>>,
32 crossings: RwLock<Vec<CrossingRecord>>,
33 grants: RwLock<BTreeSet<(String, String)>>,
35}
36
37impl InMemoryPartitionStore {
38 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}