Skip to main content

adk_kernel/stores/
watermark_sql.rs

1//! The SQLite and PostgreSQL [`CronWatermarkStore`](crate::CronWatermarkStore)s (spec 3.2
2//! §7.4, §13 Q8).
3//!
4//! One row per cron source in `adk_kernel_cron_watermarks`: the source's name and its cursor
5//! in microseconds since the Unix epoch. An advance is one upsert that keeps the later
6//! cursor, so replicas writing in any order never move a cursor back.
7
8use crate::error::{KernelError, Result};
9
10/// The migration registry of the cron watermark store, distinct from every other store's.
11pub(crate) const WATERMARK_REGISTRY_TABLE: &str = "_adk_kernel_cron_watermark_migrations";
12
13/// The SQLite schema.
14#[cfg(feature = "sqlite")]
15const SQLITE_MIGRATIONS: &[(i64, &str, &str)] = &[(
16    1,
17    "create the kernel cron watermark table",
18    "\
19CREATE TABLE IF NOT EXISTS adk_kernel_cron_watermarks (\
20    source TEXT PRIMARY KEY, \
21    cursor_us BIGINT NOT NULL\
22);",
23)];
24
25/// The PostgreSQL schema.
26#[cfg(feature = "postgres")]
27const POSTGRES_MIGRATIONS: &[(i64, &str, &str)] = &[(
28    1,
29    "create the kernel cron watermark table",
30    "\
31CREATE TABLE IF NOT EXISTS adk_kernel_cron_watermarks (\
32    source TEXT COLLATE \"C\" PRIMARY KEY, \
33    cursor_us BIGINT NOT NULL\
34);",
35)];
36
37pub(crate) const READ: &str = "SELECT cursor_us FROM adk_kernel_cron_watermarks WHERE source = $1";
38
39/// SQLite's two-argument `MAX` is its scalar maximum.
40#[cfg(feature = "sqlite")]
41pub(crate) const SQLITE_ADVANCE: &str = "\
42INSERT INTO adk_kernel_cron_watermarks (source, cursor_us) VALUES ($1, $2) \
43ON CONFLICT (source) DO UPDATE SET \
44cursor_us = MAX(adk_kernel_cron_watermarks.cursor_us, excluded.cursor_us) \
45RETURNING cursor_us";
46
47#[cfg(feature = "postgres")]
48pub(crate) const POSTGRES_ADVANCE: &str = "\
49INSERT INTO adk_kernel_cron_watermarks (source, cursor_us) VALUES ($1, $2) \
50ON CONFLICT (source) DO UPDATE SET \
51cursor_us = GREATEST(adk_kernel_cron_watermarks.cursor_us, excluded.cursor_us) \
52RETURNING cursor_us";
53
54pub(crate) const DELETE: &str = "DELETE FROM adk_kernel_cron_watermarks WHERE source = $1";
55
56/// The instant `micros` microseconds after the Unix epoch.
57pub(crate) fn instant(backend: &'static str, micros: i64) -> Result<chrono::DateTime<chrono::Utc>> {
58    chrono::DateTime::from_timestamp_micros(micros).ok_or_else(|| KernelError::Store {
59        backend,
60        reason: format!("a stored cron watermark is out of range: {micros}"),
61    })
62}
63
64/// Maps a database error.
65pub(crate) fn db_error(backend: &'static str, action: &str, error: &sqlx::Error) -> KernelError {
66    KernelError::Store {
67        backend,
68        reason: format!("could not {action} the cron watermarks: {error}"),
69    }
70}
71
72/// Implements [`CronWatermarkStore`](crate::CronWatermarkStore) for a store with a `pool`
73/// field, advancing with `$advance`.
74macro_rules! sql_watermark_store {
75    ($store:ty, $backend:literal, $advance:expr) => {
76        #[async_trait::async_trait]
77        impl $crate::watermark::CronWatermarkStore for $store {
78            async fn read(
79                &self,
80                source: &str,
81            ) -> $crate::error::Result<Option<chrono::DateTime<chrono::Utc>>> {
82                let row: Option<(i64,)> = sqlx::query_as($crate::stores::watermark_sql::READ)
83                    .bind(source)
84                    .fetch_optional(&self.pool)
85                    .await
86                    .map_err(|e| $crate::stores::watermark_sql::db_error($backend, "read", &e))?;
87                row.map(|(micros,)| $crate::stores::watermark_sql::instant($backend, micros))
88                    .transpose()
89            }
90
91            async fn advance(
92                &self,
93                source: &str,
94                cursor: chrono::DateTime<chrono::Utc>,
95            ) -> $crate::error::Result<chrono::DateTime<chrono::Utc>> {
96                let (micros,): (i64,) = sqlx::query_as($advance)
97                    .bind(source)
98                    .bind(cursor.timestamp_micros())
99                    .fetch_one(&self.pool)
100                    .await
101                    .map_err(|e| {
102                        $crate::stores::watermark_sql::db_error($backend, "advance", &e)
103                    })?;
104                $crate::stores::watermark_sql::instant($backend, micros)
105            }
106
107            async fn delete(&self, source: &str) -> $crate::error::Result<bool> {
108                let done = sqlx::query($crate::stores::watermark_sql::DELETE)
109                    .bind(source)
110                    .execute(&self.pool)
111                    .await
112                    .map_err(|e| {
113                        $crate::stores::watermark_sql::db_error($backend, "delete from", &e)
114                    })?;
115                Ok(done.rows_affected() > 0)
116            }
117        }
118    };
119}
120
121/// A [`CronWatermarkStore`](crate::CronWatermarkStore) in SQLite (spec 3.2 §7.4, feature
122/// `sqlite`).
123///
124/// Its table is `adk_kernel_cron_watermarks`, and [`migrate`](Self::migrate) records its
125/// steps in `_adk_kernel_cron_watermark_migrations`, distinct from every other store's, so
126/// it shares a pool such as `harness.db`'s. Call `migrate` once before use.
127///
128/// # Example
129///
130/// ```rust
131/// use adk_kernel::{CronWatermarkStore, SqliteCronWatermarkStore};
132///
133/// # #[tokio::main(flavor = "current_thread")]
134/// # async fn main() -> adk_kernel::Result<()> {
135/// let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
136/// let store = SqliteCronWatermarkStore::new(pool);
137/// store.migrate().await?;
138/// let now = chrono::Utc::now();
139/// store.advance("nightly", now).await?;
140/// assert_eq!(store.read("nightly").await?.map(|at| at.timestamp_micros()), Some(now.timestamp_micros()));
141/// # Ok(())
142/// # }
143/// ```
144#[cfg(feature = "sqlite")]
145#[derive(Debug, Clone)]
146pub struct SqliteCronWatermarkStore {
147    pool: sqlx::SqlitePool,
148}
149
150#[cfg(feature = "sqlite")]
151impl SqliteCronWatermarkStore {
152    /// A store over `pool`, such as the pool of `harness.db`.
153    pub fn new(pool: sqlx::SqlitePool) -> Self {
154        Self { pool }
155    }
156
157    /// The pool the store writes to.
158    pub fn pool(&self) -> &sqlx::SqlitePool {
159        &self.pool
160    }
161
162    /// Creates or upgrades the store's table.
163    ///
164    /// Idempotent: a step already recorded in `_adk_kernel_cron_watermark_migrations` is
165    /// not run again.
166    ///
167    /// # Errors
168    ///
169    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
170    /// migrated by a newer release.
171    pub async fn migrate(&self) -> Result<()> {
172        adk_session::migration::sqlite_runner::run_sql_migrations(
173            &self.pool,
174            WATERMARK_REGISTRY_TABLE,
175            SQLITE_MIGRATIONS,
176            || async { Ok(false) },
177        )
178        .await
179        .map_err(|error| KernelError::Store { backend: "sqlite", reason: error.message })
180    }
181}
182
183#[cfg(feature = "sqlite")]
184sql_watermark_store!(SqliteCronWatermarkStore, "sqlite", SQLITE_ADVANCE);
185
186/// A [`CronWatermarkStore`](crate::CronWatermarkStore) in PostgreSQL, shared by every
187/// replica (spec 3.2 §7.4, feature `postgres`).
188///
189/// Its table is `adk_kernel_cron_watermarks`; [`migrate`](Self::migrate) records its steps
190/// in `_adk_kernel_cron_watermark_migrations` under an advisory lock, so replicas starting
191/// together migrate one at a time.
192///
193/// # Example
194///
195/// ```rust,no_run
196/// # async fn example() -> adk_kernel::Result<()> {
197/// let store = adk_kernel::PostgresCronWatermarkStore::connect("postgres://localhost/app").await?;
198/// store.migrate().await?;
199/// # Ok(())
200/// # }
201/// ```
202#[cfg(feature = "postgres")]
203#[derive(Debug, Clone)]
204pub struct PostgresCronWatermarkStore {
205    pool: sqlx::PgPool,
206}
207
208#[cfg(feature = "postgres")]
209impl PostgresCronWatermarkStore {
210    /// A store over `pool`, such as the one the session service and the run store use.
211    pub fn new(pool: sqlx::PgPool) -> Self {
212        Self { pool }
213    }
214
215    /// The pool the store writes to.
216    pub fn pool(&self) -> &sqlx::PgPool {
217        &self.pool
218    }
219
220    /// Connects to `database_url` with a pool of its own.
221    ///
222    /// # Errors
223    ///
224    /// Returns [`KernelError::Store`] when the server cannot be reached.
225    pub async fn connect(database_url: &str) -> Result<Self> {
226        let pool =
227            sqlx::PgPool::connect(database_url).await.map_err(|error| KernelError::Store {
228                backend: "postgres",
229                reason: format!("could not connect: {error}"),
230            })?;
231        Ok(Self::new(pool))
232    }
233
234    /// Creates or upgrades the store's table, under a session-level advisory lock keyed by
235    /// the registry table, so replicas starting together migrate one at a time.
236    ///
237    /// # Errors
238    ///
239    /// Returns [`KernelError::Store`] when a statement fails, or when the database was
240    /// migrated by a newer release.
241    pub async fn migrate(&self) -> Result<()> {
242        migrate_locked(self.pool.clone()).await
243    }
244}
245
246/// Runs the migrations under the advisory lock. Boxed so the future is checked for `Send`
247/// here, with concrete lifetimes, rather than inside callers' `async_trait` methods.
248#[cfg(feature = "postgres")]
249fn migrate_locked(
250    pool: sqlx::PgPool,
251) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>> {
252    use sqlx::Connection as _;
253
254    let store_error = |action: &str, error: &dyn std::fmt::Display| KernelError::Store {
255        backend: "postgres",
256        reason: format!("could not {action}: {error}"),
257    };
258    Box::pin(async move {
259        let key = WATERMARK_REGISTRY_TABLE
260            .bytes()
261            .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
262                (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
263            })
264            .cast_signed();
265        let mut lock = sqlx::PgConnection::connect_with(&pool.connect_options())
266            .await
267            .map_err(|error| store_error("connect for the migration lock", &error))?;
268        sqlx::query("SELECT pg_advisory_lock($1)")
269            .bind(key)
270            .execute(&mut lock)
271            .await
272            .map_err(|error| store_error("take the migration lock", &error))?;
273        let result = adk_session::migration::pg_runner::run_sql_migrations(
274            &pool,
275            WATERMARK_REGISTRY_TABLE,
276            POSTGRES_MIGRATIONS,
277            || async { Ok(false) },
278        )
279        .await
280        .map_err(|error| KernelError::Store { backend: "postgres", reason: error.message });
281        let _ = lock.close().await;
282        result
283    })
284}
285
286#[cfg(feature = "postgres")]
287sql_watermark_store!(PostgresCronWatermarkStore, "postgres", POSTGRES_ADVANCE);