1use 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
46const 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
92fn 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 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 pub fn from_pool(pool: $pool) -> Self {
142 Self { pool }
143 }
144
145 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 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 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 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 PostgresScheduleStore, sqlx::PgPool,
371 begin = "BEGIN",
372 lock = " FOR UPDATE",
373 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}