Skip to main content

adk_kernel/
watermark.rs

1//! Cron watermarks: where each cron wake source left off, so the ticks it missed while no
2//! kernel watched replay once, per the schedule's catch-up policy (spec 3.2 §7.4, §7.13).
3//!
4//! | Item | What it is |
5//! |---|---|
6//! | [`CronWatermarkStore`] | The cursor of each cron source by name, which only moves forward |
7//! | [`SourceWatermark`] | One source's cursor as an `adk_agent::ambient::TickWatermark` |
8//!
9//! The store runs on in-memory, SQLite, PostgreSQL and Redis ([`InMemoryCronWatermarkStore`],
10//! `SqliteCronWatermarkStore`, `PostgresCronWatermarkStore`, `RedisCronWatermarkStore`), and
11//! on MongoDB, Firestore and Neo4j (`MongoCronWatermarkStore`,
12//! `FirestoreCronWatermarkStore`, `Neo4jCronWatermarkStore`), with the conformance suite
13//! `cron_watermark_store_conformance_tests!` (feature `conformance`).
14//! A tenant kernel (`managed::TenantKernel`, feature `managed`) keeps its watermarks in the
15//! tenant's own store, so a tick missed while no replica of the tenant ran is seen by the next
16//! replica that starts.
17//!
18//! [`InMemoryCronWatermarkStore`]: crate::stores::InMemoryCronWatermarkStore
19
20use std::sync::Arc;
21
22use adk_agent::ambient::TickWatermark;
23use async_trait::async_trait;
24use chrono::{DateTime, Utc};
25
26use crate::error::Result;
27
28/// Where each cron wake source left off (spec 3.2 §7.4, §7.13): the instant through which
29/// its ticks are accounted for, by source name.
30///
31/// A cursor only moves forward: [`advance`](Self::advance) keeps the later of the stored
32/// cursor and the one given, so replicas that watch one schedule and write in any order
33/// never move it back, and a tick already accounted for is never planned again.
34///
35/// # Example
36///
37/// ```rust
38/// use adk_kernel::CronWatermarkStore;
39/// use adk_kernel::stores::InMemoryCronWatermarkStore;
40/// use chrono::{TimeZone, Utc};
41///
42/// # #[tokio::main(flavor = "current_thread")]
43/// # async fn main() -> adk_kernel::Result<()> {
44/// let store = InMemoryCronWatermarkStore::new();
45/// let nine = Utc.with_ymd_and_hms(2026, 10, 24, 9, 0, 0).unwrap();
46/// let eight = Utc.with_ymd_and_hms(2026, 10, 24, 8, 0, 0).unwrap();
47/// assert_eq!(store.advance("nightly", nine).await?, nine);
48/// // An earlier cursor, from a replica behind this one, leaves it where it is.
49/// assert_eq!(store.advance("nightly", eight).await?, nine);
50/// assert_eq!(store.read("nightly").await?, Some(nine));
51/// # Ok(())
52/// # }
53/// ```
54#[async_trait]
55pub trait CronWatermarkStore: Send + Sync {
56    /// The cursor of `source`, or `None` when it never ran.
57    ///
58    /// # Errors
59    ///
60    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
61    async fn read(&self, source: &str) -> Result<Option<DateTime<Utc>>>;
62
63    /// Moves the cursor of `source` to `cursor` unless it is already later, and returns the
64    /// cursor as stored. Cursors keep microseconds.
65    ///
66    /// # Errors
67    ///
68    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
69    async fn advance(&self, source: &str, cursor: DateTime<Utc>) -> Result<DateTime<Utc>>;
70
71    /// Deletes the cursor of `source`; `false` when there was none.
72    ///
73    /// # Errors
74    ///
75    /// Returns [`KernelError::Store`](crate::KernelError::Store) when the backend fails.
76    async fn delete(&self, source: &str) -> Result<bool>;
77}
78
79/// The cursor of one cron source in a [`CronWatermarkStore`], as the
80/// `adk_agent::ambient::TickWatermark` a [`CronWakeSource`](crate::CronWakeSource) or a
81/// `CronTrigger` keeps (spec 3.2 §7.4).
82///
83/// # Example
84///
85/// ```rust
86/// use std::sync::Arc;
87/// use adk_agent::ambient::TickWatermark;
88/// use adk_kernel::SourceWatermark;
89/// use adk_kernel::stores::InMemoryCronWatermarkStore;
90///
91/// # #[tokio::main(flavor = "current_thread")]
92/// # async fn main() -> adk_core::Result<()> {
93/// let watermark = SourceWatermark::new(Arc::new(InMemoryCronWatermarkStore::new()), "nightly");
94/// assert_eq!(watermark.read().await?, None);
95/// # Ok(())
96/// # }
97/// ```
98#[derive(Clone)]
99pub struct SourceWatermark {
100    store: Arc<dyn CronWatermarkStore>,
101    source: String,
102}
103
104impl std::fmt::Debug for SourceWatermark {
105    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106        f.debug_struct("SourceWatermark").field("source", &self.source).finish_non_exhaustive()
107    }
108}
109
110impl SourceWatermark {
111    /// The cursor of `source` in `store`.
112    pub fn new(store: Arc<dyn CronWatermarkStore>, source: impl Into<String>) -> Self {
113        Self { store, source: source.into() }
114    }
115
116    /// The source whose cursor this is.
117    pub fn source(&self) -> &str {
118        &self.source
119    }
120}
121
122#[async_trait]
123impl TickWatermark for SourceWatermark {
124    async fn read(&self) -> adk_core::Result<Option<DateTime<Utc>>> {
125        Ok(self.store.read(&self.source).await?)
126    }
127
128    async fn write(&self, cursor: DateTime<Utc>) -> adk_core::Result<()> {
129        self.store.advance(&self.source, cursor).await?;
130        Ok(())
131    }
132}