Skip to main content

adk_kernel/stores/
watermark_memory.rs

1//! The in-memory [`CronWatermarkStore`] (spec 3.2 §7.4, §13 Q8).
2
3use std::collections::BTreeMap;
4
5use async_trait::async_trait;
6use chrono::{DateTime, Utc};
7use tokio::sync::RwLock;
8
9use crate::error::Result;
10use crate::watermark::CronWatermarkStore;
11
12/// A [`CronWatermarkStore`] in process memory, for tests and a kernel with no durable store
13/// (spec 3.2 §7.4). Its cursors end with the process, so a restarted kernel over it sees no
14/// tick it missed.
15///
16/// # Example
17///
18/// ```rust
19/// use adk_kernel::CronWatermarkStore;
20/// use adk_kernel::stores::InMemoryCronWatermarkStore;
21///
22/// # #[tokio::main(flavor = "current_thread")]
23/// # async fn main() -> adk_kernel::Result<()> {
24/// let store = InMemoryCronWatermarkStore::new();
25/// let now = chrono::Utc::now();
26/// store.advance("nightly", now).await?;
27/// assert!(store.read("nightly").await?.is_some());
28/// assert!(store.delete("nightly").await?);
29/// # Ok(())
30/// # }
31/// ```
32#[derive(Debug, Default)]
33pub struct InMemoryCronWatermarkStore {
34    cursors: RwLock<BTreeMap<String, DateTime<Utc>>>,
35}
36
37impl InMemoryCronWatermarkStore {
38    /// An empty store.
39    pub fn new() -> Self {
40        Self::default()
41    }
42}
43
44/// `cursor` truncated to the microseconds every backend keeps.
45pub(crate) fn micros(cursor: DateTime<Utc>) -> DateTime<Utc> {
46    DateTime::from_timestamp_micros(cursor.timestamp_micros()).unwrap_or(cursor)
47}
48
49#[async_trait]
50impl CronWatermarkStore for InMemoryCronWatermarkStore {
51    async fn read(&self, source: &str) -> Result<Option<DateTime<Utc>>> {
52        Ok(self.cursors.read().await.get(source).copied())
53    }
54
55    async fn advance(&self, source: &str, cursor: DateTime<Utc>) -> Result<DateTime<Utc>> {
56        let cursor = micros(cursor);
57        let mut cursors = self.cursors.write().await;
58        let stored = cursors.entry(source.to_string()).or_insert(cursor);
59        if *stored < cursor {
60            *stored = cursor;
61        }
62        Ok(*stored)
63    }
64
65    async fn delete(&self, source: &str) -> Result<bool> {
66        Ok(self.cursors.write().await.remove(source).is_some())
67    }
68}