1use chrono::{DateTime, Utc};
2use larust_core::AppError;
3use larust_orm::Backend;
4use sqlx::AnyPool;
5use std::future::Future;
6use std::pin::Pin;
7use std::str::FromStr;
8use std::time::Duration;
9
10type BoxedTask =
11 Box<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), AppError>> + Send>> + Send + Sync>;
12
13struct Entry {
14 cron: cron::Schedule,
15 task: BoxedTask,
16 name: Option<String>,
17 on_one_server: bool,
19}
20
21#[must_use]
27pub struct Schedule {
28 entries: Vec<Entry>,
29}
30
31impl Default for Schedule {
32 fn default() -> Self {
33 Self::new()
34 }
35}
36
37impl Schedule {
38 pub fn new() -> Self {
39 Self {
40 entries: Vec::new(),
41 }
42 }
43
44 pub fn cron<F, Fut>(mut self, expr: &str, task: F) -> Self
57 where
58 F: Fn() -> Fut + Send + Sync + 'static,
59 Fut: Future<Output = Result<(), AppError>> + Send + 'static,
60 {
61 let parsed = cron::Schedule::from_str(expr).unwrap_or_else(|error| {
62 panic!(
63 "invalid cron expression {expr:?}: {error} -- Schedule::cron uses the `cron` \
64 crate's 7-field dialect (sec min hour day-of-month month day-of-week year), \
65 not the classic 5-field Unix cron format"
66 )
67 });
68 self.entries.push(Entry {
69 cron: parsed,
70 task: Box::new(move || Box::pin(task())),
71 name: None,
72 on_one_server: false,
73 });
74 self
75 }
76
77 pub fn name(mut self, name: impl Into<String>) -> Self {
89 self.entries
90 .last_mut()
91 .expect("Schedule::name called before registering any task")
92 .name = Some(name.into());
93 self
94 }
95
96 pub fn on_one_server(mut self) -> Self {
131 let entry = self
132 .entries
133 .last_mut()
134 .expect("Schedule::on_one_server called before registering any task");
135 assert!(
136 entry.name.is_some(),
137 "Schedule::on_one_server requires .name(...) first -- a task closure has no \
138 identity of its own to derive a cross-process lock key from"
139 );
140 entry.on_one_server = true;
141 self
142 }
143
144 pub fn every_minute<F, Fut>(self, task: F) -> Self
146 where
147 F: Fn() -> Fut + Send + Sync + 'static,
148 Fut: Future<Output = Result<(), AppError>> + Send + 'static,
149 {
150 self.cron("0 * * * * * *", task)
151 }
152
153 pub fn hourly<F, Fut>(self, task: F) -> Self
155 where
156 F: Fn() -> Fut + Send + Sync + 'static,
157 Fut: Future<Output = Result<(), AppError>> + Send + 'static,
158 {
159 self.cron("0 0 * * * * *", task)
160 }
161
162 pub fn daily<F, Fut>(self, task: F) -> Self
164 where
165 F: Fn() -> Fut + Send + Sync + 'static,
166 Fut: Future<Output = Result<(), AppError>> + Send + 'static,
167 {
168 self.cron("0 0 0 * * * *", task)
169 }
170
171 pub fn daily_at<F, Fut>(self, time: &str, task: F) -> Self
175 where
176 F: Fn() -> Fut + Send + Sync + 'static,
177 Fut: Future<Output = Result<(), AppError>> + Send + 'static,
178 {
179 let (hour, minute) = parse_hh_mm(time);
180 self.cron(&format!("0 {minute} {hour} * * * *"), task)
181 }
182
183 pub fn weekly<F, Fut>(self, task: F) -> Self
185 where
186 F: Fn() -> Fut + Send + Sync + 'static,
187 Fut: Future<Output = Result<(), AppError>> + Send + 'static,
188 {
189 self.cron("0 0 0 * * Sun *", task)
190 }
191
192 pub fn monthly<F, Fut>(self, task: F) -> Self
194 where
195 F: Fn() -> Fut + Send + Sync + 'static,
196 Fut: Future<Output = Result<(), AppError>> + Send + 'static,
197 {
198 self.cron("0 0 0 1 * * *", task)
199 }
200}
201
202fn parse_hh_mm(time: &str) -> (u32, u32) {
203 let (hour_str, minute_str) = time.split_once(':').unwrap_or_else(|| {
204 panic!("invalid time {time:?} for Schedule::daily_at -- expected \"HH:MM\"")
205 });
206 let hour: u32 = hour_str.parse().unwrap_or_else(|_| {
207 panic!("invalid hour in {time:?} for Schedule::daily_at -- expected \"HH:MM\"")
208 });
209 let minute: u32 = minute_str.parse().unwrap_or_else(|_| {
210 panic!("invalid minute in {time:?} for Schedule::daily_at -- expected \"HH:MM\"")
211 });
212 assert!(
213 hour < 24,
214 "hour out of range in {time:?} for Schedule::daily_at -- expected 00-23"
215 );
216 assert!(
217 minute < 60,
218 "minute out of range in {time:?} for Schedule::daily_at -- expected 00-59"
219 );
220 (hour, minute)
221}
222
223const LOCK_RETENTION_SECS: i64 = 7 * 24 * 60 * 60;
231
232async fn ensure_lock_table(pool: &AnyPool) -> Result<(), AppError> {
243 let create_table = match larust_orm::backend() {
244 Backend::Sqlite => {
245 "CREATE TABLE IF NOT EXISTS scheduler_locks (\
246 task_name TEXT NOT NULL, \
247 scheduled_for_unix INTEGER NOT NULL, \
248 PRIMARY KEY (task_name, scheduled_for_unix)\
249 )"
250 }
251 Backend::MySql => {
256 "CREATE TABLE IF NOT EXISTS scheduler_locks (\
257 task_name VARCHAR(255) NOT NULL, \
258 scheduled_for_unix BIGINT NOT NULL, \
259 PRIMARY KEY (task_name, scheduled_for_unix)\
260 )"
261 }
262 Backend::Postgres => {
263 "CREATE TABLE IF NOT EXISTS scheduler_locks (\
264 task_name TEXT NOT NULL, \
265 scheduled_for_unix BIGINT NOT NULL, \
266 PRIMARY KEY (task_name, scheduled_for_unix)\
267 )"
268 }
269 };
270 sqlx::query(create_table)
271 .execute(pool)
272 .await
273 .map_err(|source| AppError::Internal(Box::new(source)))?;
274 Ok(())
275}
276
277async fn claim(task_name: &str, at: DateTime<Utc>) -> Result<bool, AppError> {
283 let pool = larust_orm::pool()?;
284 ensure_lock_table(pool).await?;
285
286 let backend = larust_orm::backend();
287 let scheduled_for = at.timestamp();
288
289 let prune_sql = format!(
290 "DELETE FROM scheduler_locks WHERE task_name = {} AND scheduled_for_unix < {}",
291 larust_orm::placeholder(backend, 1),
292 larust_orm::placeholder(backend, 2),
293 );
294 sqlx::query(&prune_sql)
295 .bind(task_name)
296 .bind(scheduled_for - LOCK_RETENTION_SECS)
297 .execute(pool)
298 .await
299 .map_err(|source| AppError::Internal(Box::new(source)))?;
300
301 let claim_sql = format!(
302 "INSERT INTO scheduler_locks (task_name, scheduled_for_unix) VALUES ({}, {})",
303 larust_orm::placeholder(backend, 1),
304 larust_orm::placeholder(backend, 2),
305 );
306 match sqlx::query(&claim_sql)
307 .bind(task_name)
308 .bind(scheduled_for)
309 .execute(pool)
310 .await
311 {
312 Ok(_) => Ok(true),
313 Err(sqlx::Error::Database(database)) if database.is_unique_violation() => Ok(false),
317 Err(source) => Err(AppError::Internal(Box::new(source))),
318 }
319}
320
321async fn run_due(schedule: &Schedule, at: DateTime<Utc>) {
337 for entry in &schedule.entries {
338 if !entry.cron.includes(at) {
339 continue;
340 }
341
342 if entry.on_one_server {
343 let name = entry.name.as_deref().unwrap();
346 match claim(name, at).await {
347 Ok(true) => {}
348 Ok(false) => {
349 tracing::info!(
350 task = name,
351 "scheduled task already claimed by another process this occurrence, \
352 skipping"
353 );
354 continue;
355 }
356 Err(error) => {
357 tracing::error!(
358 task = name,
359 %error,
360 "failed to claim scheduled task lock, skipping this occurrence"
361 );
362 continue;
363 }
364 }
365 }
366
367 match (entry.task)().await {
368 Ok(()) => {
369 tracing::info!(cron = entry.cron.source(), name = ?entry.name, "scheduled task ran");
370 }
371 Err(error) => {
372 tracing::error!(
373 cron = entry.cron.source(),
374 name = ?entry.name,
375 %error,
376 "scheduled task failed"
377 );
378 }
379 }
380 }
381}
382
383const TICK_INTERVAL: Duration = Duration::from_secs(1);
384
385pub async fn work(schedule: Schedule) -> Result<(), AppError> {
414 let mut interval = tokio::time::interval(TICK_INTERVAL);
415 interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
416 tracing::info!("scheduler worker started");
417 loop {
418 interval.tick().await;
419 run_due(&schedule, Utc::now()).await;
420 }
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426 use chrono::TimeZone;
427 use std::sync::atomic::{AtomicUsize, Ordering};
428 use std::sync::Arc;
429
430 fn assert_send_sync<T: Send + Sync>() {}
431
432 #[test]
433 fn schedule_is_send_and_sync() {
434 assert_send_sync::<Schedule>();
435 }
436
437 #[test]
438 fn every_minute_produces_the_expected_cron_source() {
439 let schedule = Schedule::new().every_minute(|| async { Ok(()) });
440 assert_eq!(schedule.entries[0].cron.source(), "0 * * * * * *");
441 }
442
443 #[test]
444 fn hourly_produces_the_expected_cron_source() {
445 let schedule = Schedule::new().hourly(|| async { Ok(()) });
446 assert_eq!(schedule.entries[0].cron.source(), "0 0 * * * * *");
447 }
448
449 #[test]
450 fn daily_produces_the_expected_cron_source() {
451 let schedule = Schedule::new().daily(|| async { Ok(()) });
452 assert_eq!(schedule.entries[0].cron.source(), "0 0 0 * * * *");
453 }
454
455 #[test]
456 fn weekly_produces_the_expected_cron_source() {
457 let schedule = Schedule::new().weekly(|| async { Ok(()) });
458 assert_eq!(schedule.entries[0].cron.source(), "0 0 0 * * Sun *");
459 }
460
461 #[test]
462 fn monthly_produces_the_expected_cron_source() {
463 let schedule = Schedule::new().monthly(|| async { Ok(()) });
464 assert_eq!(schedule.entries[0].cron.source(), "0 0 0 1 * * *");
465 }
466
467 #[test]
468 fn daily_at_parses_hh_mm_into_the_expected_cron_source() {
469 let schedule = Schedule::new().daily_at("13:07", || async { Ok(()) });
470 assert_eq!(schedule.entries[0].cron.source(), "0 7 13 * * * *");
471 }
472
473 #[test]
474 #[should_panic(expected = "invalid time")]
475 fn daily_at_panics_on_a_malformed_time() {
476 let _ = Schedule::new().daily_at("not-a-time", || async { Ok(()) });
477 }
478
479 #[test]
480 #[should_panic(expected = "hour out of range")]
481 fn daily_at_panics_on_an_out_of_range_hour() {
482 let _ = Schedule::new().daily_at("24:00", || async { Ok(()) });
483 }
484
485 #[test]
486 #[should_panic(expected = "invalid cron expression")]
487 fn cron_panics_on_an_invalid_expression() {
488 let _ = Schedule::new().cron("not a cron expression", || async { Ok(()) });
489 }
490
491 #[tokio::test]
492 async fn run_due_fires_a_task_exactly_at_a_matching_instant_not_a_neighboring_one() {
493 let matching_calls = Arc::new(AtomicUsize::new(0));
494 let calls = Arc::clone(&matching_calls);
495 let schedule = Schedule::new().cron("0 30 9 * * * *", move || {
496 let calls = Arc::clone(&calls);
497 async move {
498 calls.fetch_add(1, Ordering::SeqCst);
499 Ok(())
500 }
501 });
502
503 let matching = Utc.with_ymd_and_hms(2026, 8, 15, 9, 30, 0).unwrap();
504 let not_matching = Utc.with_ymd_and_hms(2026, 8, 15, 9, 31, 0).unwrap();
505
506 run_due(&schedule, not_matching).await;
507 assert_eq!(matching_calls.load(Ordering::SeqCst), 0);
508
509 run_due(&schedule, matching).await;
510 assert_eq!(matching_calls.load(Ordering::SeqCst), 1);
511 }
512
513 #[tokio::test]
514 async fn a_failing_task_does_not_block_a_same_tick_sibling() {
515 let good_calls = Arc::new(AtomicUsize::new(0));
516 let calls = Arc::clone(&good_calls);
517
518 let schedule = Schedule::new()
519 .cron("0 0 12 * * * *", || async {
520 Err(AppError::Internal(Box::new(std::io::Error::other(
521 "deliberate test failure",
522 ))))
523 })
524 .cron("0 0 12 * * * *", move || {
525 let calls = Arc::clone(&calls);
526 async move {
527 calls.fetch_add(1, Ordering::SeqCst);
528 Ok(())
529 }
530 });
531
532 let at = Utc.with_ymd_and_hms(2026, 8, 15, 12, 0, 0).unwrap();
533 run_due(&schedule, at).await;
534
535 assert_eq!(
536 good_calls.load(Ordering::SeqCst),
537 1,
538 "the second task should still have run despite the first failing"
539 );
540 }
541
542 #[test]
543 #[should_panic(expected = "requires .name(...) first")]
544 fn on_one_server_panics_without_a_name_first() {
545 let _ = Schedule::new().daily(|| async { Ok(()) }).on_one_server();
546 }
547
548 #[test]
549 #[should_panic(expected = "called before registering any task")]
550 fn name_panics_before_any_task_is_registered() {
551 let _ = Schedule::new().name("too-early");
552 }
553
554 #[test]
555 fn name_and_on_one_server_apply_to_the_most_recently_registered_task() {
556 let schedule = Schedule::new()
557 .daily(|| async { Ok(()) })
558 .hourly(|| async { Ok(()) })
559 .name("hourly-task")
560 .on_one_server();
561
562 assert_eq!(schedule.entries[0].name, None);
563 assert!(!schedule.entries[0].on_one_server);
564 assert_eq!(schedule.entries[1].name.as_deref(), Some("hourly-task"));
565 assert!(schedule.entries[1].on_one_server);
566 }
567
568 #[tokio::test]
576 async fn on_one_server_claims_exactly_once_per_task_and_occurrence() {
577 let dir = tempfile::tempdir().unwrap().keep();
578 let database_url = format!("sqlite://{}/test.sqlite", dir.display());
579 larust_orm::connect(&database_url).await.unwrap();
580
581 let at = Utc.with_ymd_and_hms(2026, 8, 15, 9, 30, 0).unwrap();
582 let later = Utc.with_ymd_and_hms(2026, 8, 15, 10, 30, 0).unwrap();
583
584 assert!(claim("report-task", at).await.unwrap());
586 assert!(!claim("report-task", at).await.unwrap());
591 assert!(claim("other-task", at).await.unwrap());
594 assert!(claim("report-task", later).await.unwrap());
597
598 let already_claimed_calls = Arc::new(AtomicUsize::new(0));
602 let calls = Arc::clone(&already_claimed_calls);
603 let unclaimed_calls = Arc::new(AtomicUsize::new(0));
604 let calls2 = Arc::clone(&unclaimed_calls);
605
606 let schedule = Schedule::new()
607 .cron("0 0 11 * * * *", move || {
608 let calls = Arc::clone(&calls);
609 async move {
610 calls.fetch_add(1, Ordering::SeqCst);
611 Ok(())
612 }
613 })
614 .name("report-task")
615 .on_one_server()
616 .cron("0 0 11 * * * *", move || {
617 let calls = Arc::clone(&calls2);
618 async move {
619 calls.fetch_add(1, Ordering::SeqCst);
620 Ok(())
621 }
622 })
623 .name("fresh-task")
624 .on_one_server();
625
626 let eleven = Utc.with_ymd_and_hms(2026, 8, 15, 11, 0, 0).unwrap();
627 claim("report-task", eleven).await.unwrap(); run_due(&schedule, eleven).await;
629
630 assert_eq!(
631 already_claimed_calls.load(Ordering::SeqCst),
632 0,
633 "a task whose occurrence was already claimed elsewhere must not run"
634 );
635 assert_eq!(
636 unclaimed_calls.load(Ordering::SeqCst),
637 1,
638 "a task whose occurrence was not yet claimed must run exactly once"
639 );
640 }
641}