use crate::error::Result;
use crate::queue::JobId;
use crate::types::Cursor;
use async_trait::async_trait;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use std::time::{Duration, SystemTime};
pub const MAX_NAME_BYTES: usize = 256;
pub const MAX_AT_HORIZON_DAYS: i64 = 36525;
pub const MAX_CATCH_UP: u32 = 100;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MisfirePolicy {
Skip,
#[default]
RunOnce,
CatchUp(u32),
}
impl MisfirePolicy {
pub(crate) fn validate(self) -> Result<Self> {
match self {
Self::CatchUp(0) => Err(crate::error::ForgeError::invalid(
"catch-up count must be greater than zero",
)),
Self::CatchUp(count) if count > MAX_CATCH_UP => Err(crate::error::ForgeError::limit(
format!("catch-up count is {count}; max is {MAX_CATCH_UP}"),
)),
value => Ok(value),
}
}
pub fn name(self) -> &'static str {
match self {
Self::Skip => "skip",
Self::RunOnce => "run_once",
Self::CatchUp(_) => "catch_up",
}
}
pub fn max_catch_up(self) -> u32 {
match self {
Self::CatchUp(count) => count,
Self::Skip | Self::RunOnce => 0,
}
}
}
pub(crate) fn plan_cron_occurrences(
cron: &cron::Cron,
first_due: DateTime<Utc>,
now: DateTime<Utc>,
policy: MisfirePolicy,
) -> (Vec<DateTime<Utc>>, Option<DateTime<Utc>>) {
let next = cron.next_after(now);
if first_due > now || policy == MisfirePolicy::Skip {
return (Vec::new(), next);
}
let Some(latest) = cron.prev_or_at(now).filter(|latest| *latest >= first_due) else {
return (Vec::new(), next);
};
let count = match policy {
MisfirePolicy::Skip => 0,
MisfirePolicy::RunOnce => 1,
MisfirePolicy::CatchUp(count) => count,
};
let mut occurrences = Vec::with_capacity(count as usize);
let mut current = latest;
for _ in 0..count {
if current < first_due {
break;
}
occurrences.push(current);
let Some(previous_probe) = current.checked_sub_signed(chrono::Duration::minutes(1)) else {
break;
};
let Some(previous) = cron.prev_or_at(previous_probe) else {
break;
};
current = previous;
}
occurrences.reverse();
(occurrences, next)
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScheduleKind {
Cron(String),
At,
}
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct ScheduleOpts {
pub max_attempts: Option<u32>,
pub misfire_policy: MisfirePolicy,
}
impl ScheduleOpts {
pub fn new() -> Self {
Self::default()
}
pub fn with_max_attempts(mut self, max_attempts: u32) -> Self {
self.max_attempts = Some(max_attempts);
self
}
pub fn with_misfire_policy(mut self, policy: MisfirePolicy) -> Self {
self.misfire_policy = policy;
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct ScheduleInfo {
pub name: String,
pub kind: ScheduleKind,
pub queue: String,
pub next_run: SystemTime,
pub last_run: Option<SystemTime>,
pub paused: bool,
pub misfire_policy: MisfirePolicy,
}
impl ScheduleInfo {
pub fn new(
name: String,
kind: ScheduleKind,
queue: String,
next_run: SystemTime,
last_run: Option<SystemTime>,
paused: bool,
misfire_policy: MisfirePolicy,
) -> Self {
Self {
name,
kind,
queue,
next_run,
last_run,
paused,
misfire_policy,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct SchedulerDiagnostics {
pub lag: Option<Duration>,
pub last_successful_tick: Option<SystemTime>,
pub due_count: u64,
pub enqueue_failures: u64,
}
#[async_trait]
pub trait Schedule: Send + Sync {
async fn cron(
&self,
name: &str,
expr: &str,
queue: &str,
payload: Bytes,
opts: ScheduleOpts,
) -> Result<()>;
async fn at(
&self,
when: SystemTime,
queue: &str,
payload: Bytes,
opts: ScheduleOpts,
) -> Result<JobId>;
async fn cancel(&self, name: &str) -> Result<bool>;
async fn inspect(&self, name: &str) -> Result<Option<ScheduleInfo>>;
async fn pause(&self, name: &str) -> Result<bool>;
async fn resume(&self, name: &str) -> Result<bool>;
async fn diagnostics(&self) -> Result<SchedulerDiagnostics>;
async fn cancel_at(&self, job_id: JobId) -> Result<bool> {
self.cancel(&format!("at:{job_id}")).await
}
async fn list(
&self,
cursor: Option<Cursor>,
limit: u32,
) -> Result<(Vec<ScheduleInfo>, Option<Cursor>)>;
async fn process_due(&self) -> Result<u64>;
}
pub(crate) mod cron;
mod memory;
mod postgres;
pub(crate) use memory::MemSchedule;
pub(crate) use postgres::PgSchedule;