adk_kernel/stores/
watermark_sql.rs1use crate::error::{KernelError, Result};
9
10pub(crate) const WATERMARK_REGISTRY_TABLE: &str = "_adk_kernel_cron_watermark_migrations";
12
13#[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#[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#[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
56pub(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
64pub(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
72macro_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#[cfg(feature = "sqlite")]
145#[derive(Debug, Clone)]
146pub struct SqliteCronWatermarkStore {
147 pool: sqlx::SqlitePool,
148}
149
150#[cfg(feature = "sqlite")]
151impl SqliteCronWatermarkStore {
152 pub fn new(pool: sqlx::SqlitePool) -> Self {
154 Self { pool }
155 }
156
157 pub fn pool(&self) -> &sqlx::SqlitePool {
159 &self.pool
160 }
161
162 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#[cfg(feature = "postgres")]
203#[derive(Debug, Clone)]
204pub struct PostgresCronWatermarkStore {
205 pool: sqlx::PgPool,
206}
207
208#[cfg(feature = "postgres")]
209impl PostgresCronWatermarkStore {
210 pub fn new(pool: sqlx::PgPool) -> Self {
212 Self { pool }
213 }
214
215 pub fn pool(&self) -> &sqlx::PgPool {
217 &self.pool
218 }
219
220 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 pub async fn migrate(&self) -> Result<()> {
242 migrate_locked(self.pool.clone()).await
243 }
244}
245
246#[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);