Skip to main content

adk_kernel/stores/
memory.rs

1//! The in-memory [`ProcessStore`] (spec 3.2 §7.3, §13 Q8).
2
3use std::collections::BTreeMap;
4
5use async_trait::async_trait;
6use chrono::NaiveDate;
7use tokio::sync::RwLock;
8
9use super::{ProcessFilter, ProcessStore, SpendScope, UsageTotals};
10use crate::bus::SpendDelta;
11use crate::error::{KernelError, Result};
12use crate::partition::PartitionId;
13use crate::process::ProcessMeta;
14use crate::sched::QueueClass;
15use crate::wake::WakeSet;
16
17/// A [`ProcessStore`] in process memory, for tests and a kernel with no durable store
18/// (spec 3.2 §7.3). Its rows end with the process.
19///
20/// Rows are kept in `pid` order, so [`list`](ProcessStore::list) orders as the durable
21/// backends do.
22///
23/// # Example
24///
25/// ```rust
26/// use adk_kernel::{InMemoryProcessStore, ProcessFilter, ProcessKind, ProcessMeta, ProcessStore, QueueClass};
27///
28/// # #[tokio::main(flavor = "current_thread")]
29/// # async fn main() -> adk_kernel::Result<()> {
30/// let store = InMemoryProcessStore::new();
31/// store.put(ProcessMeta::new("run-2", QueueClass::Background, ProcessKind::Goal)).await?;
32/// store.put(ProcessMeta::new("run-1", QueueClass::Interactive, ProcessKind::Interactive)).await?;
33/// let pids: Vec<_> = store
34///     .list(&ProcessFilter::default())
35///     .await?
36///     .into_iter()
37///     .map(|meta| meta.pid)
38///     .collect();
39/// assert_eq!(pids, ["run-1", "run-2"]);
40/// # Ok(())
41/// # }
42/// ```
43#[derive(Debug, Default)]
44pub struct InMemoryProcessStore {
45    rows: RwLock<BTreeMap<String, ProcessMeta>>,
46    /// Usage per process, partition and UTC day.
47    spend: RwLock<BTreeMap<(String, PartitionId, NaiveDate), UsageTotals>>,
48}
49
50impl InMemoryProcessStore {
51    /// An empty store.
52    pub fn new() -> Self {
53        Self::default()
54    }
55}
56
57/// The class a durable backend reads back for `queue`, which it stores by name.
58fn stored_queue(queue: QueueClass) -> QueueClass {
59    match queue {
60        QueueClass::Named(name) => QueueClass::from_name(&name),
61        other => other,
62    }
63}
64
65#[async_trait]
66impl ProcessStore for InMemoryProcessStore {
67    async fn put(&self, mut meta: ProcessMeta) -> Result<()> {
68        meta.queue = stored_queue(meta.queue);
69        self.rows.write().await.insert(meta.pid.clone(), meta);
70        Ok(())
71    }
72
73    async fn get(&self, pid: &str) -> Result<Option<ProcessMeta>> {
74        Ok(self.rows.read().await.get(pid).cloned())
75    }
76
77    async fn list(&self, filter: &ProcessFilter) -> Result<Vec<ProcessMeta>> {
78        let filter =
79            ProcessFilter { queue: filter.queue.clone().map(stored_queue), ..filter.clone() };
80        Ok(self
81            .rows
82            .read()
83            .await
84            .values()
85            .filter(|meta| filter.matches(meta))
86            .take(filter.limit.unwrap_or(usize::MAX))
87            .cloned()
88            .collect())
89    }
90
91    async fn set_wake(&self, pid: &str, wake: Option<WakeSet>) -> Result<()> {
92        let mut rows = self.rows.write().await;
93        let row = rows.get_mut(pid).ok_or_else(|| KernelError::NotFound { pid: pid.into() })?;
94        row.wake = wake;
95        Ok(())
96    }
97
98    async fn set_queue(&self, pid: &str, queue: QueueClass) -> Result<()> {
99        let mut rows = self.rows.write().await;
100        let row = rows.get_mut(pid).ok_or_else(|| KernelError::NotFound { pid: pid.into() })?;
101        row.queue = stored_queue(queue);
102        Ok(())
103    }
104
105    async fn delete(&self, pid: &str) -> Result<bool> {
106        Ok(self.rows.write().await.remove(pid).is_some())
107    }
108
109    async fn set_suspend_requested(&self, pid: &str, requested: bool) -> Result<()> {
110        let mut rows = self.rows.write().await;
111        let row = rows.get_mut(pid).ok_or_else(|| KernelError::NotFound { pid: pid.into() })?;
112        row.suspend_requested = requested;
113        Ok(())
114    }
115
116    async fn add_spend(
117        &self,
118        pid: &str,
119        partition: &PartitionId,
120        day: NaiveDate,
121        delta: SpendDelta,
122    ) -> Result<()> {
123        let mut spend = self.spend.write().await;
124        spend.entry((pid.to_string(), partition.clone(), day)).or_default().add(&delta);
125        Ok(())
126    }
127
128    async fn spend(
129        &self,
130        scope: &SpendScope,
131        from: NaiveDate,
132        to_inclusive: NaiveDate,
133    ) -> Result<u64> {
134        Ok(self.usage(scope, from, to_inclusive).await?.micro_usd)
135    }
136
137    async fn usage(
138        &self,
139        scope: &SpendScope,
140        from: NaiveDate,
141        to_inclusive: NaiveDate,
142    ) -> Result<UsageTotals> {
143        let mut totals = UsageTotals::default();
144        for ((pid, partition, day), day_totals) in self.spend.read().await.iter() {
145            let in_scope = match scope {
146                SpendScope::Process(process) => process == pid,
147                SpendScope::Partition(scoped) => scoped == partition,
148            };
149            if in_scope && (from..=to_inclusive).contains(day) {
150                totals.merge(day_totals);
151            }
152        }
153        Ok(totals)
154    }
155}