hyperlane-plugin-scheduler 23.3.0

A background async interval and 5-field cron job scheduler plugin for the Hyperlane framework with lock-free overlap protection, Tokio panic isolation, atomic per-job metrics, and graceful shutdown.
Documentation
use super::*;

/// Formats [`SchedulerError`] for diagnostics.
impl Display for SchedulerError {
    /// Writes a human-readable scheduler error message.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let msg: &str = match self {
            Self::InvalidCron => ERR_INVALID_CRON,
            Self::ZeroInterval => ERR_ZERO_INTERVAL,
        };
        f.write_str(msg)
    }
}

/// Marks [`SchedulerError`] as a standard error type.
impl Error for SchedulerError {}

/// Parsing and O(1) matching methods for [`CronMask`].
impl CronMask {
    /// Parses a 5-field cron expression (`min hour dom month dow`) or `@hourly`/`@daily`/`@weekly`/`@monthly`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Cron expression string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, SchedulerError>` - Compiled bitmask schedule or error.
    pub fn parse(expr: &str) -> Result<Self, SchedulerError> {
        let trimmed: &str = expr.trim();
        let expanded: &str = match trimmed {
            CRON_ALIAS_HOURLY => EXPR_HOURLY,
            CRON_ALIAS_DAILY => EXPR_DAILY,
            CRON_ALIAS_WEEKLY => EXPR_WEEKLY,
            CRON_ALIAS_MONTHLY => EXPR_MONTHLY,
            other => other,
        };
        let fields: Vec<&str> = expanded.split_ascii_whitespace().collect();
        if fields.len() != 5 {
            return Err(SchedulerError::InvalidCron);
        }
        let minutes: u64 = parse_cron_field(fields[0], 0, 59, false)?;
        let hours: u32 = parse_cron_field(fields[1], 0, 23, false)? as u32;
        let days: u32 = parse_cron_field(fields[2], 1, 31, false)? as u32;
        let months: u16 = parse_cron_field(fields[3], 1, 12, false)? as u16;
        let weekdays: u8 = parse_cron_field(fields[4], 0, 6, true)? as u8;
        Ok(Self {
            minutes,
            hours,
            days,
            months,
            weekdays,
        })
    }

    /// Tests in O(1) whether a UTC Unix timestamp `unix_secs` matches this cron schedule.
    ///
    /// # Arguments
    ///
    /// - `i64` - Unix timestamp in seconds.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when minute, hour, day-of-month, month, and weekday all match.
    #[inline]
    pub fn matches_unix_secs(&self, unix_secs: i64) -> bool {
        let Self {
            minutes,
            hours,
            days,
            months,
            weekdays,
        } = self;
        let epoch_days: i64 = unix_secs.div_euclid(86_400);
        let sod: u32 = unix_secs.rem_euclid(86_400) as u32;
        let hour: u32 = sod / 3600;
        let minute: u32 = (sod % 3600) / 60;
        let (_, month, day): (i32, u8, u8) = civil_from_days(epoch_days);
        let dow: u8 = (epoch_days + 4).rem_euclid(7) as u8;
        ((*minutes & (1u64 << minute)) != 0)
            && ((*hours & (1u32 << hour)) != 0)
            && ((*days & (1u32 << u32::from(day))) != 0)
            && ((*months & (1u16 << u32::from(month))) != 0)
            && ((*weekdays & (1u8 << u32::from(dow))) != 0)
    }

    /// Finds the next matching UTC minute strictly after `unix_secs` (scanning up to 1 year).
    ///
    /// # Arguments
    ///
    /// - `i64` - Reference Unix timestamp in seconds.
    ///
    /// # Returns
    ///
    /// - `Option<i64>` - Next matching UTC Unix timestamp aligned to `:00` seconds.
    pub fn next_unix_secs_after(&self, unix_secs: i64) -> Option<i64> {
        let mut candidate: i64 = (unix_secs.div_euclid(60) + 1) * 60;
        let max_steps: usize = 527_040;
        for _ in 0..max_steps {
            if self.matches_unix_secs(candidate) {
                return Some(candidate);
            }
            candidate += 60;
        }
        None
    }
}

/// Snapshot queries for [`JobMetrics`].
impl JobMetrics {
    /// Captures a point-in-time [`JobMetricsSnapshot`].
    ///
    /// # Returns
    ///
    /// - `JobMetricsSnapshot` - Atomic counter snapshot.
    pub fn snapshot(&self) -> JobMetricsSnapshot {
        let Self {
            runs,
            successes,
            failures,
            panics,
            skipped,
        } = self;
        JobMetricsSnapshot {
            runs: runs.load(Ordering::Relaxed),
            successes: successes.load(Ordering::Relaxed),
            failures: failures.load(Ordering::Relaxed),
            panics: panics.load(Ordering::Relaxed),
            skipped: skipped.load(Ordering::Relaxed),
        }
    }
}

/// Implements [`JobHandler`] for [`FnJobHandler`].
impl<F, Fut> JobHandler for FnJobHandler<F, Fut>
where
    F: Fn() -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<(), String>> + Send + 'static,
{
    /// Calls the wrapped async closure and boxes its future.
    ///
    /// # Returns
    ///
    /// - `Pin<Box<dyn Future<Output = Result<(), String>> + Send>>` - Execution future.
    fn run(&self) -> Pin<Box<dyn Future<Output = Result<(), String>> + Send>> {
        let Self { func, .. } = self;
        Box::pin(func())
    }
}

/// Job registration and startup methods for [`Scheduler`].
impl Scheduler {
    /// Registers a fixed-interval async closure job.
    ///
    /// # Arguments
    ///
    /// - `N` - Job name.
    /// - `Duration` - Positive tick interval.
    /// - `bool` - Skip overlapping ticks when still running.
    /// - `bool` - Execute once immediately on startup.
    /// - `F` - Async job closure.
    ///
    /// # Returns
    ///
    /// - `Result<&mut Self, SchedulerError>` - Mutable scheduler reference or [`SchedulerError::ZeroInterval`].
    pub fn add_interval_job<N, F, Fut>(
        &mut self,
        name: N,
        interval: Duration,
        skip_if_running: bool,
        run_immediately: bool,
        func: F,
    ) -> Result<&mut Self, SchedulerError>
    where
        N: Into<String>,
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), String>> + Send + 'static,
    {
        if interval.is_zero() {
            return Err(SchedulerError::ZeroInterval);
        }
        let Self { jobs } = self;
        jobs.push(Arc::new(RegisteredJob {
            name: name.into(),
            schedule: JobSchedule::Interval(interval),
            skip_if_running,
            run_immediately,
            in_flight: AtomicBool::new(false),
            metrics: Arc::new(JobMetrics::default()),
            handler: Arc::new(FnJobHandler {
                func,
                _marker: PhantomData,
            }),
        }));
        Ok(self)
    }

    /// Registers a 5-field UTC cron async closure job.
    ///
    /// # Arguments
    ///
    /// - `N` - Job name.
    /// - `&str` - 5-field cron expression or `@hourly`/`@daily`/`@weekly`/`@monthly`.
    /// - `bool` - Skip overlapping ticks when still running.
    /// - `F` - Async job closure.
    ///
    /// # Returns
    ///
    /// - `Result<&mut Self, SchedulerError>` - Mutable scheduler reference or [`SchedulerError::InvalidCron`].
    pub fn add_cron_job<N, F, Fut>(
        &mut self,
        name: N,
        cron_expr: &str,
        skip_if_running: bool,
        func: F,
    ) -> Result<&mut Self, SchedulerError>
    where
        N: Into<String>,
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), String>> + Send + 'static,
    {
        let mask: CronMask = CronMask::parse(cron_expr)?;
        let Self { jobs } = self;
        jobs.push(Arc::new(RegisteredJob {
            name: name.into(),
            schedule: JobSchedule::Cron(mask),
            skip_if_running,
            run_immediately: false,
            in_flight: AtomicBool::new(false),
            metrics: Arc::new(JobMetrics::default()),
            handler: Arc::new(FnJobHandler {
                func,
                _marker: PhantomData,
            }),
        }));
        Ok(self)
    }

    /// Spawns background Tokio tasks for all registered jobs and returns a [`SchedulerHandle`].
    ///
    /// # Returns
    ///
    /// - `SchedulerHandle` - Running scheduler handle with metrics and graceful shutdown.
    pub fn start(self) -> SchedulerHandle {
        let Self { jobs } = self;
        let (stop_tx, stop_rx): (Sender<bool>, Receiver<bool>) = watch::channel(false);
        let mut tasks: Vec<JoinHandle<()>> = Vec::with_capacity(jobs.len());
        let mut metrics: Vec<(String, Arc<JobMetrics>)> = Vec::with_capacity(jobs.len());
        for job in jobs {
            metrics.push((job.name.clone(), Arc::clone(&job.metrics)));
            let mut rx: Receiver<bool> = stop_rx.clone();
            let handle: JoinHandle<()> = spawn(async move {
                if job.run_immediately {
                    execute_job_once(Arc::clone(&job)).await;
                }
                match job.schedule {
                    JobSchedule::Interval(period) => {
                        let mut next_tick: Instant = Instant::now() + period;
                        loop {
                            select! {
                                _ = sleep_until(next_tick) => {
                                    execute_job_once(Arc::clone(&job)).await;
                                    next_tick = Instant::now() + period;
                                }
                                changed = rx.changed() => {
                                    if changed.is_err() || *rx.borrow() {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    JobSchedule::Cron(mask) => loop {
                        let now_secs: i64 = current_unix_secs();
                        let Some(target_secs) = mask.next_unix_secs_after(now_secs) else {
                            break;
                        };
                        let wait_secs: u64 = (target_secs - now_secs).max(1) as u64;
                        select! {
                            _ = sleep(Duration::from_secs(wait_secs)) => {
                                execute_job_once(Arc::clone(&job)).await;
                            }
                            changed = rx.changed() => {
                                if changed.is_err() || *rx.borrow() {
                                    break;
                                }
                            }
                        }
                    },
                }
            });
            tasks.push(handle);
        }
        SchedulerHandle {
            stop_tx,
            tasks,
            metrics,
        }
    }
}

/// Metrics inspection and graceful shutdown for [`SchedulerHandle`].
impl SchedulerHandle {
    /// Returns a snapshot of metrics for the job matching `name`, if registered.
    ///
    /// # Arguments
    ///
    /// - `&str` - Registered job name.
    ///
    /// # Returns
    ///
    /// - `Option<JobMetricsSnapshot>` - Atomic counter snapshot.
    pub fn job_metrics(&self, name: &str) -> Option<JobMetricsSnapshot> {
        let Self { metrics, .. } = self;
        metrics
            .iter()
            .find(|(n, _): &&(String, Arc<JobMetrics>)| n.as_str() == name)
            .map(|(_, m): &(String, Arc<JobMetrics>)| m.snapshot())
    }

    /// Signals all scheduled loops to exit and awaits completion of in-flight executions.
    pub async fn shutdown(self) {
        let Self { stop_tx, tasks, .. } = self;
        let _: Result<(), watch::error::SendError<bool>> = stop_tx.send(true);
        for task in tasks {
            let _: Result<(), JoinError> = task.await;
        }
    }
}