Skip to main content

aurelin_framework/scheduling/
mod.rs

1//! Explicit, single-run scheduling of application callbacks.
2
3mod builder;
4pub mod commands;
5mod report;
6
7use std::{error::Error, future::Future, pin::Pin, sync::Arc};
8
9use chrono::{DateTime, Timelike, Utc};
10use chrono_tz::Tz;
11
12use crate::cache::Cache;
13
14pub use builder::{ConfigurationError, ScheduleBuilder, TaskBuilder};
15pub use report::{RunReport, TaskFailure, TaskOutcome, TaskResult};
16
17type BoxError = Box<dyn Error + Send + Sync + 'static>;
18type TaskFuture = Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send + 'static>>;
19type Callback = dyn Fn() -> TaskFuture + Send + Sync;
20
21struct Task {
22    name: String,
23    expression: cron::Schedule,
24    timezone: Tz,
25    callback: Arc<Callback>,
26    overlap_seconds: Option<i64>,
27    one_server: bool,
28}
29
30struct ScheduleInner {
31    tasks: Vec<Task>,
32    cache: Option<Cache>,
33}
34
35/// An immutable schedule. Clones share task definitions and cache handles.
36#[derive(Clone)]
37pub struct Schedule {
38    inner: Arc<ScheduleInner>,
39}
40
41impl Schedule {
42    /// Begin configuring a schedule.
43    pub fn builder() -> ScheduleBuilder {
44        ScheduleBuilder::default()
45    }
46
47    /// Evaluate one instant, awaiting due tasks in registration order.
48    ///
49    /// Tasks without single-server election can run on every invocation.
50    pub async fn run_due_at(&self, instant: DateTime<Utc>) -> RunReport {
51        let minute = instant.with_second(0).and_then(|time| time.with_nanosecond(0)).unwrap_or(instant);
52        let mut tasks = Vec::new();
53        for task in &self.inner.tasks {
54            if !task.expression.includes(minute.with_timezone(&task.timezone)) {
55                continue;
56            }
57            let outcome = self.run_task(task, minute).await;
58            tasks.push(TaskResult { name: task.name.clone(), outcome });
59        }
60        RunReport { tasks }
61    }
62
63    /// Evaluate one run using the current UTC clock.
64    pub async fn run(&self) -> RunReport {
65        self.run_due_at(Utc::now()).await
66    }
67
68    async fn run_task(&self, task: &Task, minute: DateTime<Utc>) -> TaskOutcome {
69        if task.one_server {
70            // The election survives callback completion so later runners lose as well.
71            if let Some(cache) = &self.inner.cache {
72                let key = format!("{}:occurrence:{}", lock_key(&task.name), minute.timestamp());
73                match cache.lock(&key, 3600).acquire().await {
74                    Ok(true) => {}
75                    Ok(false) => return TaskOutcome::SkippedElection,
76                    Err(error) => return TaskOutcome::Failed(TaskFailure::Election(error)),
77                }
78            }
79        }
80        let lock = match (task.overlap_seconds, &self.inner.cache) {
81            (Some(seconds), Some(cache)) => Some(cache.lock(&lock_key(&task.name), seconds)),
82            _ => None,
83        };
84        if let Some(lock) = &lock {
85            match lock.acquire().await {
86                Ok(true) => {}
87                Ok(false) => return TaskOutcome::SkippedOverlap,
88                Err(error) => return TaskOutcome::Failed(TaskFailure::Acquire(error)),
89            }
90        }
91        let result = (task.callback)().await;
92        let released = match lock {
93            Some(lock) => lock.release().await.map(Some),
94            None => Ok(None),
95        };
96        match (result, released) {
97            (Ok(()), Ok(_)) => TaskOutcome::Succeeded,
98            (Err(error), Ok(_)) => TaskOutcome::Failed(TaskFailure::Callback(error)),
99            (Ok(()), Err(error)) => TaskOutcome::Failed(TaskFailure::Release(error)),
100            (Err(callback), Err(release)) => TaskOutcome::Failed(TaskFailure::CallbackAndRelease { callback, release }),
101        }
102    }
103}
104
105/// Derive the stable cache-lock name for a scheduled task.
106pub fn lock_key(name: &str) -> String {
107    use sha2::{Digest, Sha256};
108    let digest = Sha256::digest(name.as_bytes());
109    format!("aurelin:schedule:{digest:x}")
110}