Skip to main content

hyperlane_plugin_scheduler/
impl.rs

1use super::*;
2
3/// Formats [`SchedulerError`] for diagnostics.
4impl Display for SchedulerError {
5    /// Writes a human-readable scheduler error message.
6    ///
7    /// # Arguments
8    ///
9    /// - `&mut Formatter<'_>` - Output formatter.
10    ///
11    /// # Returns
12    ///
13    /// - `fmt::Result` - Formatting outcome.
14    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15        let msg: &str = match self {
16            Self::InvalidCron => ERR_INVALID_CRON,
17            Self::ZeroInterval => ERR_ZERO_INTERVAL,
18        };
19        f.write_str(msg)
20    }
21}
22
23/// Marks [`SchedulerError`] as a standard error type.
24impl Error for SchedulerError {}
25
26/// Parsing and O(1) matching methods for [`CronMask`].
27impl CronMask {
28    /// Parses a 5-field cron expression (`min hour dom month dow`) or `@hourly`/`@daily`/`@weekly`/`@monthly`.
29    ///
30    /// # Arguments
31    ///
32    /// - `&str` - Cron expression string.
33    ///
34    /// # Returns
35    ///
36    /// - `Result<Self, SchedulerError>` - Compiled bitmask schedule or error.
37    pub fn parse(expr: &str) -> Result<Self, SchedulerError> {
38        let trimmed: &str = expr.trim();
39        let expanded: &str = match trimmed {
40            CRON_ALIAS_HOURLY => EXPR_HOURLY,
41            CRON_ALIAS_DAILY => EXPR_DAILY,
42            CRON_ALIAS_WEEKLY => EXPR_WEEKLY,
43            CRON_ALIAS_MONTHLY => EXPR_MONTHLY,
44            other => other,
45        };
46        let fields: Vec<&str> = expanded.split_ascii_whitespace().collect();
47        if fields.len() != 5 {
48            return Err(SchedulerError::InvalidCron);
49        }
50        let minutes: u64 = parse_cron_field(fields[0], 0, 59, false)?;
51        let hours: u32 = parse_cron_field(fields[1], 0, 23, false)? as u32;
52        let days: u32 = parse_cron_field(fields[2], 1, 31, false)? as u32;
53        let months: u16 = parse_cron_field(fields[3], 1, 12, false)? as u16;
54        let weekdays: u8 = parse_cron_field(fields[4], 0, 6, true)? as u8;
55        Ok(Self {
56            minutes,
57            hours,
58            days,
59            months,
60            weekdays,
61        })
62    }
63
64    /// Tests in O(1) whether a UTC Unix timestamp `unix_secs` matches this cron schedule.
65    ///
66    /// # Arguments
67    ///
68    /// - `i64` - Unix timestamp in seconds.
69    ///
70    /// # Returns
71    ///
72    /// - `bool` - `true` when minute, hour, day-of-month, month, and weekday all match.
73    #[inline]
74    pub fn matches_unix_secs(&self, unix_secs: i64) -> bool {
75        let Self {
76            minutes,
77            hours,
78            days,
79            months,
80            weekdays,
81        } = self;
82        let epoch_days: i64 = unix_secs.div_euclid(86_400);
83        let sod: u32 = unix_secs.rem_euclid(86_400) as u32;
84        let hour: u32 = sod / 3600;
85        let minute: u32 = (sod % 3600) / 60;
86        let (_, month, day): (i32, u8, u8) = civil_from_days(epoch_days);
87        let dow: u8 = (epoch_days + 4).rem_euclid(7) as u8;
88        ((*minutes & (1u64 << minute)) != 0)
89            && ((*hours & (1u32 << hour)) != 0)
90            && ((*days & (1u32 << u32::from(day))) != 0)
91            && ((*months & (1u16 << u32::from(month))) != 0)
92            && ((*weekdays & (1u8 << u32::from(dow))) != 0)
93    }
94
95    /// Finds the next matching UTC minute strictly after `unix_secs` (scanning up to 1 year).
96    ///
97    /// # Arguments
98    ///
99    /// - `i64` - Reference Unix timestamp in seconds.
100    ///
101    /// # Returns
102    ///
103    /// - `Option<i64>` - Next matching UTC Unix timestamp aligned to `:00` seconds.
104    pub fn next_unix_secs_after(&self, unix_secs: i64) -> Option<i64> {
105        let mut candidate: i64 = (unix_secs.div_euclid(60) + 1) * 60;
106        let max_steps: usize = 527_040;
107        for _ in 0..max_steps {
108            if self.matches_unix_secs(candidate) {
109                return Some(candidate);
110            }
111            candidate += 60;
112        }
113        None
114    }
115}
116
117/// Snapshot queries for [`JobMetrics`].
118impl JobMetrics {
119    /// Captures a point-in-time [`JobMetricsSnapshot`].
120    ///
121    /// # Returns
122    ///
123    /// - `JobMetricsSnapshot` - Atomic counter snapshot.
124    pub fn snapshot(&self) -> JobMetricsSnapshot {
125        let Self {
126            runs,
127            successes,
128            failures,
129            panics,
130            skipped,
131        } = self;
132        JobMetricsSnapshot {
133            runs: runs.load(Ordering::Relaxed),
134            successes: successes.load(Ordering::Relaxed),
135            failures: failures.load(Ordering::Relaxed),
136            panics: panics.load(Ordering::Relaxed),
137            skipped: skipped.load(Ordering::Relaxed),
138        }
139    }
140}
141
142/// Implements [`JobHandler`] for [`FnJobHandler`].
143impl<F, Fut> JobHandler for FnJobHandler<F, Fut>
144where
145    F: Fn() -> Fut + Send + Sync + 'static,
146    Fut: Future<Output = Result<(), String>> + Send + 'static,
147{
148    /// Calls the wrapped async closure and boxes its future.
149    ///
150    /// # Returns
151    ///
152    /// - `Pin<Box<dyn Future<Output = Result<(), String>> + Send>>` - Execution future.
153    fn run(&self) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send>> {
154        let Self { func, .. } = self;
155        Box::pin(func())
156    }
157}
158
159/// Job registration and startup methods for [`Scheduler`].
160impl Scheduler {
161    /// Registers a fixed-interval async closure job.
162    ///
163    /// # Arguments
164    ///
165    /// - `N` - Job name.
166    /// - `Duration` - Positive tick interval.
167    /// - `bool` - Skip overlapping ticks when still running.
168    /// - `bool` - Execute once immediately on startup.
169    /// - `F` - Async job closure.
170    ///
171    /// # Returns
172    ///
173    /// - `Result<&mut Self, SchedulerError>` - Mutable scheduler reference or [`SchedulerError::ZeroInterval`].
174    pub fn add_interval_job<N, F, Fut>(
175        &mut self,
176        name: N,
177        interval: Duration,
178        skip_if_running: bool,
179        run_immediately: bool,
180        func: F,
181    ) -> Result<&mut Self, SchedulerError>
182    where
183        N: Into<String>,
184        F: Fn() -> Fut + Send + Sync + 'static,
185        Fut: Future<Output = Result<(), String>> + Send + 'static,
186    {
187        if interval.is_zero() {
188            return Err(SchedulerError::ZeroInterval);
189        }
190        let Self { jobs } = self;
191        jobs.push(Arc::new(RegisteredJob {
192            name: name.into(),
193            schedule: JobSchedule::Interval(interval),
194            skip_if_running,
195            run_immediately,
196            in_flight: AtomicBool::new(false),
197            metrics: Arc::new(JobMetrics::default()),
198            handler: Arc::new(FnJobHandler {
199                func,
200                _marker: PhantomData,
201            }),
202        }));
203        Ok(self)
204    }
205
206    /// Registers a 5-field UTC cron async closure job.
207    ///
208    /// # Arguments
209    ///
210    /// - `N` - Job name.
211    /// - `&str` - 5-field cron expression or `@hourly`/`@daily`/`@weekly`/`@monthly`.
212    /// - `bool` - Skip overlapping ticks when still running.
213    /// - `F` - Async job closure.
214    ///
215    /// # Returns
216    ///
217    /// - `Result<&mut Self, SchedulerError>` - Mutable scheduler reference or [`SchedulerError::InvalidCron`].
218    pub fn add_cron_job<N, F, Fut>(
219        &mut self,
220        name: N,
221        cron_expr: &str,
222        skip_if_running: bool,
223        func: F,
224    ) -> Result<&mut Self, SchedulerError>
225    where
226        N: Into<String>,
227        F: Fn() -> Fut + Send + Sync + 'static,
228        Fut: Future<Output = Result<(), String>> + Send + 'static,
229    {
230        let mask: CronMask = CronMask::parse(cron_expr)?;
231        let Self { jobs } = self;
232        jobs.push(Arc::new(RegisteredJob {
233            name: name.into(),
234            schedule: JobSchedule::Cron(mask),
235            skip_if_running,
236            run_immediately: false,
237            in_flight: AtomicBool::new(false),
238            metrics: Arc::new(JobMetrics::default()),
239            handler: Arc::new(FnJobHandler {
240                func,
241                _marker: PhantomData,
242            }),
243        }));
244        Ok(self)
245    }
246
247    /// Spawns background Tokio tasks for all registered jobs and returns a [`SchedulerHandle`].
248    ///
249    /// # Returns
250    ///
251    /// - `SchedulerHandle` - Running scheduler handle with metrics and graceful shutdown.
252    pub fn start(self) -> SchedulerHandle {
253        let Self { jobs } = self;
254        let (stop_tx, stop_rx): (Sender<bool>, Receiver<bool>) = watch::channel(false);
255        let mut tasks: Vec<JoinHandle<()>> = Vec::with_capacity(jobs.len());
256        let mut metrics: Vec<(String, Arc<JobMetrics>)> = Vec::with_capacity(jobs.len());
257        for job in jobs {
258            metrics.push((job.name.clone(), Arc::clone(&job.metrics)));
259            let mut rx: Receiver<bool> = stop_rx.clone();
260            let handle: JoinHandle<()> = spawn(async move {
261                if job.run_immediately {
262                    execute_job_once(Arc::clone(&job)).await;
263                }
264                match job.schedule {
265                    JobSchedule::Interval(period) => {
266                        let mut next_tick: Instant = Instant::now() + period;
267                        loop {
268                            select! {
269                                _ = sleep_until(next_tick) => {
270                                    execute_job_once(Arc::clone(&job)).await;
271                                    next_tick = Instant::now() + period;
272                                }
273                                changed = rx.changed() => {
274                                    if changed.is_err() || *rx.borrow() {
275                                        break;
276                                    }
277                                }
278                            }
279                        }
280                    }
281                    JobSchedule::Cron(mask) => loop {
282                        let now_secs: i64 = current_unix_secs();
283                        let Some(target_secs) = mask.next_unix_secs_after(now_secs) else {
284                            break;
285                        };
286                        let wait_secs: u64 = (target_secs - now_secs).max(1) as u64;
287                        select! {
288                            _ = sleep(Duration::from_secs(wait_secs)) => {
289                                execute_job_once(Arc::clone(&job)).await;
290                            }
291                            changed = rx.changed() => {
292                                if changed.is_err() || *rx.borrow() {
293                                    break;
294                                }
295                            }
296                        }
297                    },
298                }
299            });
300            tasks.push(handle);
301        }
302        SchedulerHandle {
303            stop_tx,
304            tasks,
305            metrics,
306        }
307    }
308}
309
310/// Metrics inspection and graceful shutdown for [`SchedulerHandle`].
311impl SchedulerHandle {
312    /// Returns a snapshot of metrics for the job matching `name`, if registered.
313    ///
314    /// # Arguments
315    ///
316    /// - `&str` - Registered job name.
317    ///
318    /// # Returns
319    ///
320    /// - `Option<JobMetricsSnapshot>` - Atomic counter snapshot.
321    pub fn job_metrics(&self, name: &str) -> Option<JobMetricsSnapshot> {
322        let Self { metrics, .. } = self;
323        metrics
324            .iter()
325            .find(|(n, _): &&(String, Arc<JobMetrics>)| n.as_str() == name)
326            .map(|(_, m): &(String, Arc<JobMetrics>)| m.snapshot())
327    }
328
329    /// Signals all scheduled loops to exit and awaits completion of in-flight executions.
330    pub async fn shutdown(self) {
331        let Self { stop_tx, tasks, .. } = self;
332        let _: Result<(), watch::error::SendError<bool>> = stop_tx.send(true);
333        for task in tasks {
334            let _: Result<(), JoinError> = task.await;
335        }
336    }
337}