Skip to main content

adk_session/
schedule.rs

1//! SQL-backed [`ScheduleStore`](adk_core::ScheduleStore) implementations.
2//!
3//! One row per schedule in `adk_schedules`; the spec, run template, and missed-fire
4//! policy are JSON text, and `next_fire_at_us` is indexed with `paused` for
5//! [`due`](adk_core::ScheduleStore::due).
6//!
7//! | Operation | Statement | Why it is safe under concurrency |
8//! |-----------|-----------|----------------------------------|
9//! | `advance` | `UPDATE ... SET revision = revision + 1 WHERE id = $id AND revision = $expected` | Compare-and-swap on the revision inside the write |
10//! | `upsert` | Read, compare, then insert or update in one transaction (`BEGIN IMMEDIATE` on SQLite, `SELECT ... FOR UPDATE` on PostgreSQL) | An identical definition leaves the revision alone, so replicas registering at startup do not break an advance in flight |
11//! | `set_paused` | `UPDATE ... WHERE id = $id AND paused <> $paused` | Moves the revision only on a change |
12//! | `due` | `WHERE NOT paused AND next_fire_at_us <= $now ORDER BY next_fire_at_us, id LIMIT $n` | Served by the `(paused, next_fire_at_us)` index |
13
14use adk_core::schedule::schedule_not_found_error;
15use adk_core::{Result, Schedule, ScheduleStore};
16use chrono::{DateTime, Utc};
17
18use crate::durable_sql::{from_json, from_micros, micros, storage_error, to_json, to_u64};
19
20const CODE: &str = "session.schedule_store.storage";
21
22const REGISTRY_TABLE: &str = "_adk_schedule_migrations";
23
24const MIGRATIONS: &[(i64, &str, &str)] = &[(
25    1,
26    "create schedule table",
27    "\
28CREATE TABLE IF NOT EXISTS adk_schedules (\
29    id TEXT PRIMARY KEY, \
30    spec TEXT NOT NULL, \
31    run TEXT NOT NULL, \
32    missed TEXT NOT NULL, \
33    paused BOOLEAN NOT NULL, \
34    next_fire_at_us BIGINT, \
35    revision BIGINT NOT NULL\
36);\
37CREATE INDEX IF NOT EXISTS adk_schedules_due ON adk_schedules (paused, next_fire_at_us);",
38)];
39
40macro_rules! schedule_columns {
41    () => {
42        "id, spec, run, missed, paused, next_fire_at_us, revision"
43    };
44}
45
46// Parameters appear in ascending order in every statement, so SQLite, which numbers
47// `$N` parameters by first appearance, binds them as PostgreSQL does.
48const INSERT: &str = "\
49INSERT INTO adk_schedules (id, spec, run, missed, paused, next_fire_at_us, revision) \
50VALUES ($1, $2, $3, $4, $5, $6, 1) \
51ON CONFLICT (id) DO NOTHING";
52
53const UPDATE: &str = "\
54UPDATE adk_schedules \
55SET spec = $1, run = $2, missed = $3, paused = $4, next_fire_at_us = $5, revision = revision + 1 \
56WHERE id = $6 \
57RETURNING revision";
58
59const GET: &str = concat!("SELECT ", schedule_columns!(), " FROM adk_schedules WHERE id = $1");
60
61const SET_PAUSED: &str = concat!(
62    "UPDATE adk_schedules SET paused = $1, revision = revision + 1 ",
63    "WHERE id = $2 AND paused <> $1"
64);
65
66const ADVANCE: &str = "\
67UPDATE adk_schedules SET next_fire_at_us = $1, revision = revision + 1 \
68WHERE id = $2 AND revision = $3";
69
70const EXISTS: &str = "SELECT 1 FROM adk_schedules WHERE id = $1";
71
72const DELETE: &str = "DELETE FROM adk_schedules WHERE id = $1";
73
74type ScheduleRow = (String, String, String, String, bool, Option<i64>, i64);
75
76fn decode(
77    (id, spec, run, missed, paused, next_fire_at_us, revision): ScheduleRow,
78) -> Result<Schedule> {
79    let mut schedule = Schedule::new(
80        id,
81        from_json(CODE, "spec", &spec)?,
82        from_json(CODE, "run", &run)?,
83        from_json(CODE, "missed", &missed)?,
84    )
85    .with_paused(paused);
86    schedule.next_fire_at =
87        next_fire_at_us.map(|us| from_micros(CODE, "next_fire_at_us", us)).transpose()?;
88    schedule.revision = to_u64(CODE, "revision", revision)?;
89    Ok(schedule)
90}
91
92/// Whether two schedules have the same definition, ignoring the revision.
93fn same_definition(a: &Schedule, b: &Schedule) -> bool {
94    a.spec == b.spec
95        && a.run == b.run
96        && a.missed == b.missed
97        && a.paused == b.paused
98        && a.next_fire_at == b.next_fire_at
99}
100
101fn stored_next_fire_at(at: Option<DateTime<Utc>>) -> (Option<DateTime<Utc>>, Option<i64>) {
102    at.map(micros).map_or((None, None), |(at, us)| (Some(at), Some(us)))
103}
104
105fn failed(e: sqlx::Error) -> adk_core::AdkError {
106    storage_error(CODE, format!("schedule store query failed: {e}"))
107}
108
109macro_rules! sql_schedule_store {
110    (
111        $(#[$doc:meta])*
112        $name:ident, $pool:ty,
113        begin = $begin:literal,
114        lock = $lock:literal,
115        collate = $collate:literal,
116        $migrate:expr
117    ) => {
118        $(#[$doc])*
119        #[derive(Debug, Clone)]
120        pub struct $name {
121            pool: $pool,
122        }
123
124        impl $name {
125            /// Connects to `database_url` and creates a connection pool.
126            ///
127            /// Call [`migrate`](Self::migrate) before first use.
128            ///
129            /// # Errors
130            ///
131            /// Returns `session.schedule_store.storage` when the database cannot be
132            /// reached.
133            pub async fn new(database_url: &str) -> Result<Self> {
134                let pool = <$pool>::connect(database_url).await.map_err(|e| {
135                    storage_error(CODE, format!("schedule store connection failed: {e}"))
136                })?;
137                Ok(Self::from_pool(pool))
138            }
139
140            /// Uses an existing pool, such as the one the session service holds.
141            pub fn from_pool(pool: $pool) -> Self {
142                Self { pool }
143            }
144
145            /// Creates or upgrades the schedule table.
146            ///
147            /// # Errors
148            ///
149            /// Returns an error when a migration statement fails.
150            pub async fn migrate(&self) -> Result<()> {
151                let migrate = $migrate;
152                migrate(&self.pool).await
153            }
154        }
155
156        #[async_trait::async_trait]
157        impl ScheduleStore for $name {
158            async fn upsert(&self, mut schedule: Schedule) -> Result<Schedule> {
159                schedule.validate()?;
160                let (next_fire_at, next_fire_at_us) = stored_next_fire_at(schedule.next_fire_at);
161                schedule.next_fire_at = next_fire_at;
162                let spec = to_json(CODE, &schedule.spec)?;
163                let run = to_json(CODE, &schedule.run)?;
164                let missed = to_json(CODE, &schedule.missed)?;
165                // A concurrent first insert of the same id makes ours conflict; the retry
166                // then reads the committed row.
167                for _ in 0..3 {
168                    let mut tx = self.pool.begin_with($begin).await.map_err(failed)?;
169                    let existing: Option<ScheduleRow> =
170                        sqlx::query_as(concat!("SELECT ", schedule_columns!(),
171                            " FROM adk_schedules WHERE id = $1", $lock))
172                            .bind(&schedule.id)
173                            .fetch_optional(&mut *tx)
174                            .await
175                            .map_err(failed)?;
176                    match existing.map(decode).transpose()? {
177                        Some(existing) if same_definition(&existing, &schedule) => {
178                            tx.rollback().await.map_err(failed)?;
179                            return Ok(existing);
180                        }
181                        Some(_) => {
182                            let revision: i64 = sqlx::query_scalar(UPDATE)
183                                .bind(&spec)
184                                .bind(&run)
185                                .bind(&missed)
186                                .bind(schedule.paused)
187                                .bind(next_fire_at_us)
188                                .bind(&schedule.id)
189                                .fetch_one(&mut *tx)
190                                .await
191                                .map_err(failed)?;
192                            tx.commit().await.map_err(failed)?;
193                            schedule.revision = to_u64(CODE, "revision", revision)?;
194                            return Ok(schedule);
195                        }
196                        None => {
197                            let inserted = sqlx::query(INSERT)
198                                .bind(&schedule.id)
199                                .bind(&spec)
200                                .bind(&run)
201                                .bind(&missed)
202                                .bind(schedule.paused)
203                                .bind(next_fire_at_us)
204                                .execute(&mut *tx)
205                                .await
206                                .map_err(failed)?;
207                            if inserted.rows_affected() == 1 {
208                                tx.commit().await.map_err(failed)?;
209                                schedule.revision = 1;
210                                return Ok(schedule);
211                            }
212                            tx.rollback().await.map_err(failed)?;
213                        }
214                    }
215                }
216                Err(storage_error(
217                    CODE,
218                    format!(
219                        "schedule '{}' was inserted and deleted concurrently three times; retry \
220                         the upsert",
221                        schedule.id
222                    ),
223                ))
224            }
225
226            async fn get(&self, id: &str) -> Result<Option<Schedule>> {
227                let row: Option<ScheduleRow> =
228                    sqlx::query_as(GET).bind(id).fetch_optional(&self.pool).await.map_err(failed)?;
229                row.map(decode).transpose()
230            }
231
232            async fn list(&self) -> Result<Vec<Schedule>> {
233                let rows: Vec<ScheduleRow> = sqlx::query_as(concat!(
234                    "SELECT ", schedule_columns!(), " FROM adk_schedules ORDER BY id", $collate
235                ))
236                .fetch_all(&self.pool)
237                .await
238                .map_err(failed)?;
239                rows.into_iter().map(decode).collect()
240            }
241
242            async fn delete(&self, id: &str) -> Result<()> {
243                let deleted = sqlx::query(DELETE).bind(id).execute(&self.pool).await.map_err(failed)?;
244                if deleted.rows_affected() == 0 {
245                    return Err(schedule_not_found_error(id));
246                }
247                Ok(())
248            }
249
250            async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule> {
251                sqlx::query(SET_PAUSED)
252                    .bind(paused)
253                    .bind(id)
254                    .execute(&self.pool)
255                    .await
256                    .map_err(failed)?;
257                self.get(id).await?.ok_or_else(|| schedule_not_found_error(id))
258            }
259
260            async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>> {
261                let rows: Vec<ScheduleRow> = sqlx::query_as(concat!(
262                    "SELECT ", schedule_columns!(), " FROM adk_schedules ",
263                    "WHERE paused = FALSE AND next_fire_at_us IS NOT NULL AND next_fire_at_us <= $1 ",
264                    "ORDER BY next_fire_at_us, id", $collate, " LIMIT $2"
265                ))
266                .bind(micros(now).1)
267                .bind(i64::try_from(limit).unwrap_or(i64::MAX))
268                .fetch_all(&self.pool)
269                .await
270                .map_err(failed)?;
271                rows.into_iter().map(decode).collect()
272            }
273
274            async fn advance(
275                &self,
276                id: &str,
277                expected_revision: u64,
278                next_fire_at: Option<DateTime<Utc>>,
279            ) -> Result<bool> {
280                let advanced = match i64::try_from(expected_revision) {
281                    Ok(expected) => sqlx::query(ADVANCE)
282                        .bind(stored_next_fire_at(next_fire_at).1)
283                        .bind(id)
284                        .bind(expected)
285                        .execute(&self.pool)
286                        .await
287                        .map_err(failed)?
288                        .rows_affected(),
289                    // A revision past BIGINT was never assigned.
290                    Err(_) => 0,
291                };
292                if advanced == 1 {
293                    return Ok(true);
294                }
295                let exists: Option<i32> = sqlx::query_scalar(EXISTS)
296                    .bind(id)
297                    .fetch_optional(&self.pool)
298                    .await
299                    .map_err(failed)?;
300                match exists {
301                    Some(_) => Ok(false),
302                    None => Err(schedule_not_found_error(id)),
303                }
304            }
305        }
306    };
307}
308
309#[cfg(feature = "sqlite")]
310sql_schedule_store! {
311    /// SQLite-backed [`ScheduleStore`].
312    ///
313    /// # Example
314    ///
315    /// ```rust,no_run
316    /// use std::time::Duration;
317    /// use adk_core::{MissedFirePolicy, NewRun, Schedule, ScheduleSpec, ScheduleStore};
318    /// use adk_session::SqliteScheduleStore;
319    ///
320    /// # async fn example() -> adk_core::Result<()> {
321    /// let store = SqliteScheduleStore::new("sqlite://runtime.db?mode=rwc").await?;
322    /// store.migrate().await?;
323    /// let spec = ScheduleSpec::Every(Duration::from_secs(3600));
324    /// let first = spec.next_after(chrono::Utc::now())?.expect("an interval always fires");
325    /// let run = NewRun::new("default", "reports", "system", "report_agent", serde_json::json!({}));
326    /// let schedule = Schedule::new("hourly-report", spec, run, MissedFirePolicy::FireOnce)
327    ///     .with_next_fire_at(first);
328    /// store.upsert(schedule).await?;
329    /// # Ok(())
330    /// # }
331    /// ```
332    SqliteScheduleStore, sqlx::SqlitePool,
333    begin = "BEGIN IMMEDIATE",
334    lock = "",
335    collate = "",
336    |pool: &sqlx::SqlitePool| {
337        let pool = pool.clone();
338        async move {
339            crate::migration::sqlite_runner::run_sql_migrations(
340                &pool,
341                REGISTRY_TABLE,
342                MIGRATIONS,
343                || async { Ok(false) },
344            )
345            .await
346        }
347    }
348}
349
350#[cfg(feature = "postgres")]
351sql_schedule_store! {
352    /// PostgreSQL-backed [`ScheduleStore`]. [`migrate`](Self::migrate) takes an advisory
353    /// lock, so concurrent processes can call it at startup.
354    ///
355    /// # Example
356    ///
357    /// ```rust,no_run
358    /// use adk_core::ScheduleStore;
359    /// use adk_session::PostgresScheduleStore;
360    ///
361    /// # async fn example() -> adk_core::Result<()> {
362    /// let store = PostgresScheduleStore::new("postgres://localhost/app").await?;
363    /// store.migrate().await?;
364    /// for schedule in store.due(chrono::Utc::now(), 100).await? {
365    ///     println!("{} is due", schedule.id);
366    /// }
367    /// # Ok(())
368    /// # }
369    /// ```
370    PostgresScheduleStore, sqlx::PgPool,
371    begin = "BEGIN",
372    lock = " FOR UPDATE",
373    // Byte order, as schedule ids compare in Rust.
374    collate = " COLLATE \"C\"",
375    |pool: &sqlx::PgPool| {
376        let pool = pool.clone();
377        async move {
378            crate::migration::run_pg_migrations_locked(&pool, REGISTRY_TABLE, MIGRATIONS).await
379        }
380    }
381}