adk_kernel/stores/
ledger_memory.rs1use std::collections::BTreeMap;
4
5use async_trait::async_trait;
6use tokio::sync::RwLock;
7
8use crate::error::Result;
9use crate::partition::PartitionId;
10use crate::proc::{
11 LedgerEntry, LedgerQuery, LedgerStore, Observation, ObservationQuery, PassState,
12 order_observations,
13};
14
15#[derive(Debug, Default)]
34pub struct InMemoryLedgerStore {
35 rows: RwLock<Vec<LedgerEntry>>,
36 observations: RwLock<BTreeMap<String, Observation>>,
37 states: RwLock<BTreeMap<PartitionId, PassState>>,
38}
39
40impl InMemoryLedgerStore {
41 pub fn new() -> Self {
43 Self::default()
44 }
45}
46
47#[async_trait]
48impl LedgerStore for InMemoryLedgerStore {
49 async fn append(&self, mut entry: LedgerEntry) -> Result<LedgerEntry> {
50 let mut rows = self.rows.write().await;
51 entry.seq = rows.last().map_or(1, |last| last.seq + 1);
52 rows.push(entry.clone());
53 Ok(entry)
54 }
55
56 async fn list(&self, query: &LedgerQuery) -> Result<Vec<LedgerEntry>> {
57 Ok(self
58 .rows
59 .read()
60 .await
61 .iter()
62 .filter(|entry| query.matches(entry))
63 .take(query.limit.unwrap_or(usize::MAX))
64 .cloned()
65 .collect())
66 }
67
68 async fn put_observation(&self, observation: Observation) -> Result<()> {
69 self.observations.write().await.insert(observation.id.clone(), observation);
70 Ok(())
71 }
72
73 async fn observations(&self, query: &ObservationQuery) -> Result<Vec<Observation>> {
74 let mut observations: Vec<Observation> = self
75 .observations
76 .read()
77 .await
78 .values()
79 .filter(|observation| query.matches(observation))
80 .cloned()
81 .collect();
82 order_observations(&mut observations);
83 observations.truncate(query.limit.unwrap_or(usize::MAX));
84 Ok(observations)
85 }
86
87 async fn pass_state(&self, partition: &PartitionId) -> Result<Option<PassState>> {
88 Ok(self.states.read().await.get(partition).cloned())
89 }
90
91 async fn pass_states(&self) -> Result<Vec<PassState>> {
92 Ok(self.states.read().await.values().cloned().collect())
93 }
94
95 async fn put_pass_state(&self, state: PassState) -> Result<()> {
96 self.states.write().await.insert(state.partition.clone(), state);
97 Ok(())
98 }
99}