use std::collections::VecDeque;
use std::fmt;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use super::cron::{Cron, CronParseError, WallClock, delay_until};
use super::datetime::{UtcDateTime, ZonedDateTime};
use crate::capability::{HCons, HList, HNil};
use crate::concurrency::Concurrency;
use crate::failure::{Cause, Exit, Never};
use crate::kernel::{Effect, sleep, succeed, suspend, sync};
use crate::layer::Layer;
use crate::par::all;
use crate::scope::Scope;
const DEFAULT_HISTORY: usize = 100;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum OverlapPolicy {
#[default]
Skip,
Allow,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MissedRunPolicy {
#[default]
Skip,
CatchUp {
max: usize,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CronSkip {
Overlap,
Missed,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CronOutcome {
Succeeded,
Failed(String),
Skipped(CronSkip),
}
#[derive(Clone, Debug)]
pub struct CronRun {
pub job: Arc<str>,
pub scheduled: ZonedDateTime,
pub started: Option<UtcDateTime>,
pub finished: Option<UtcDateTime>,
pub outcome: CronOutcome,
}
impl CronRun {
pub fn is_success(&self) -> bool {
self.outcome == CronOutcome::Succeeded
}
pub fn duration(&self) -> Option<Duration> {
Some(self.started?.distance_duration(&self.finished?))
}
fn skipped(job: &Arc<str>, scheduled: ZonedDateTime, why: CronSkip) -> Self {
Self {
job: Arc::clone(job),
scheduled,
started: None,
finished: None,
outcome: CronOutcome::Skipped(why),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CronError {
Parse(CronParseError),
DuplicateJob(String),
}
impl fmt::Display for CronError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Parse(e) => e.fmt(f),
Self::DuplicateJob(name) => write!(f, "cron job {name:?} is already registered"),
}
}
}
impl std::error::Error for CronError {}
impl From<CronParseError> for CronError {
fn from(e: CronParseError) -> Self {
Self::Parse(e)
}
}
type Task<R> = Arc<dyn Fn(ZonedDateTime) -> Effect<(), String, R> + Send + Sync>;
type Hook<R> = Arc<dyn Fn(&CronRun) -> Effect<(), Never, R> + Send + Sync>;
pub struct CronJob<R = HNil> {
name: Arc<str>,
cron: Cron,
task: Task<R>,
overlap: OverlapPolicy,
missed: MissedRunPolicy,
on_success: Vec<Hook<R>>,
on_failure: Vec<Hook<R>>,
history_limit: usize,
}
impl<R> Clone for CronJob<R> {
fn clone(&self) -> Self {
Self {
name: Arc::clone(&self.name),
cron: self.cron.clone(),
task: Arc::clone(&self.task),
overlap: self.overlap,
missed: self.missed,
on_success: self.on_success.clone(),
on_failure: self.on_failure.clone(),
history_limit: self.history_limit,
}
}
}
impl<R> fmt::Debug for CronJob<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CronJob")
.field("name", &&*self.name)
.field("cron", &self.cron)
.field("overlap", &self.overlap)
.field("missed", &self.missed)
.finish_non_exhaustive()
}
}
impl<R: Send + Sync + 'static> CronJob<R> {
pub fn new<A, E, F>(name: impl Into<Arc<str>>, cron: Cron, make: F) -> Self
where
A: Send + 'static,
E: fmt::Display + Send + 'static,
F: Fn() -> Effect<A, E, R> + Send + Sync + 'static,
{
Self::new_at(name, cron, move |_| make())
}
pub fn new_at<A, E, F>(name: impl Into<Arc<str>>, cron: Cron, make: F) -> Self
where
A: Send + 'static,
E: fmt::Display + Send + 'static,
F: Fn(ZonedDateTime) -> Effect<A, E, R> + Send + Sync + 'static,
{
Self {
name: name.into(),
cron,
task: Arc::new(move |fire| make(fire).map(|_| ()).map_err(|e| e.to_string())),
overlap: OverlapPolicy::default(),
missed: MissedRunPolicy::default(),
on_success: Vec::new(),
on_failure: Vec::new(),
history_limit: DEFAULT_HISTORY,
}
}
pub fn overlap(mut self, policy: OverlapPolicy) -> Self {
self.overlap = policy;
self
}
pub fn missed_runs(mut self, policy: MissedRunPolicy) -> Self {
self.missed = policy;
self
}
pub fn on_success(
mut self,
hook: impl Fn(&CronRun) -> Effect<(), Never, R> + Send + Sync + 'static,
) -> Self {
self.on_success.push(Arc::new(hook));
self
}
pub fn on_failure(
mut self,
hook: impl Fn(&CronRun) -> Effect<(), Never, R> + Send + Sync + 'static,
) -> Self {
self.on_failure.push(Arc::new(hook));
self
}
pub fn history_limit(mut self, limit: usize) -> Self {
self.history_limit = limit;
self
}
pub fn name(&self) -> &str {
&self.name
}
pub fn cron(&self) -> &Cron {
&self.cron
}
}
struct JobState {
name: Arc<str>,
limit: usize,
history: Mutex<VecDeque<CronRun>>,
running: AtomicUsize,
}
impl JobState {
fn record(&self, run: CronRun) {
if self.limit == 0 {
return;
}
let mut h = self.history.lock().unwrap_or_else(PoisonError::into_inner);
if h.len() >= self.limit {
h.pop_front();
}
h.push_back(run);
}
}
struct Entry<R> {
job: CronJob<R>,
state: Arc<JobState>,
}
pub struct CronRegistry<R = HNil> {
entries: Vec<Arc<Entry<R>>>,
}
impl<R> Clone for CronRegistry<R> {
fn clone(&self) -> Self {
Self {
entries: self.entries.clone(),
}
}
}
impl<R> Default for CronRegistry<R> {
fn default() -> Self {
Self {
entries: Vec::new(),
}
}
}
impl<R> fmt::Debug for CronRegistry<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list()
.entries(self.entries.iter().map(|e| &e.job))
.finish()
}
}
impl<R: Send + Sync + 'static> CronRegistry<R> {
pub fn new() -> Self {
Self::default()
}
pub fn with(mut self, job: CronJob<R>) -> Result<Self, CronError> {
if self.entries.iter().any(|e| e.job.name == job.name) {
return Err(CronError::DuplicateJob(job.name.to_string()));
}
let state = Arc::new(JobState {
name: Arc::clone(&job.name),
limit: job.history_limit,
history: Mutex::new(VecDeque::new()),
running: AtomicUsize::new(0),
});
self.entries.push(Arc::new(Entry { job, state }));
Ok(self)
}
pub fn schedule<A, E, F>(
self,
name: impl Into<Arc<str>>,
expression: &str,
make: F,
) -> Result<Self, CronError>
where
A: Send + 'static,
E: fmt::Display + Send + 'static,
F: Fn() -> Effect<A, E, R> + Send + Sync + 'static,
{
let cron = Cron::parse(expression)?;
self.with(CronJob::new(name, cron, make))
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn scheduler(&self) -> CronScheduler {
CronScheduler {
jobs: self.entries.iter().map(|e| Arc::clone(&e.state)).collect(),
}
}
pub fn run(&self, clock: WallClock) -> Effect<(), Never, R> {
let loops: Vec<_> = self
.entries
.iter()
.map(|e| start_loop(Arc::clone(e), clock.clone()))
.collect();
all(loops, Concurrency::Unbounded).map(|_| ())
}
pub fn layer(&self, clock: WallClock) -> Layer<HCons<CronScheduler, HNil>, Never, R>
where
R: HList,
{
let registry = self.clone();
Layer::scoped(move |scope: Scope| {
let started = registry
.entries
.iter()
.fold(succeed::<(), Never, R>(()), |acc, e| {
let fiber = scope.fork_in(start_loop(Arc::clone(e), clock.clone()));
acc.then(fiber.map(|_| ()))
});
let scheduler = registry.scheduler();
started.map(move |()| HCons::new(scheduler, HNil))
})
}
}
#[derive(Clone)]
pub struct CronScheduler {
jobs: Arc<[Arc<JobState>]>,
}
impl fmt::Debug for CronScheduler {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CronScheduler")
.field("jobs", &self.job_names())
.finish()
}
}
impl CronScheduler {
pub fn job_names(&self) -> Vec<Arc<str>> {
self.jobs.iter().map(|j| Arc::clone(&j.name)).collect()
}
pub fn history(&self, job: &str) -> Option<Vec<CronRun>> {
let state = self.state(job)?;
let h = state.history.lock().unwrap_or_else(PoisonError::into_inner);
Some(h.iter().cloned().collect())
}
pub fn last_run(&self, job: &str) -> Option<CronRun> {
let state = self.state(job)?;
let h = state.history.lock().unwrap_or_else(PoisonError::into_inner);
h.back().cloned()
}
pub fn running(&self, job: &str) -> Option<usize> {
Some(self.state(job)?.running.load(Ordering::SeqCst))
}
fn state(&self, job: &str) -> Option<&Arc<JobState>> {
self.jobs.iter().find(|j| &*j.name == job)
}
}
fn start_loop<R: Send + Sync + 'static>(
entry: Arc<Entry<R>>,
clock: WallClock,
) -> Effect<(), Never, R> {
clock.now().flat_map(move |now| job_loop(entry, clock, now))
}
fn job_loop<R: Send + Sync + 'static>(
entry: Arc<Entry<R>>,
clock: WallClock,
last: UtcDateTime,
) -> Effect<(), Never, R> {
clock.now().flat_map(move |now| {
let keep = match entry.job.missed {
MissedRunPolicy::Skip => 1,
MissedRunPolicy::CatchUp { max } => max.saturating_add(1),
};
let mut due: VecDeque<ZonedDateTime> = VecDeque::new();
let mut cursor = last;
let upcoming = loop {
match entry.job.cron.next_after(cursor) {
Some(fire) if fire.0.timestamp() <= now.0 => {
cursor = UtcDateTime(fire.0.timestamp());
due.push_back(fire);
if due.len() > keep
&& let Some(old) = due.pop_front()
{
let skip = CronRun::skipped(&entry.job.name, old, CronSkip::Missed);
entry.state.record(skip);
}
}
other => break other,
}
};
if due.is_empty() {
return match upcoming {
None => succeed(()),
Some(next) => sleep(delay_until(now, &next)).then(job_loop(entry, clock, last)),
};
}
let next_last = cursor;
dispatch(&entry, &clock, due.into()).then(job_loop(entry, clock, next_last))
})
}
fn dispatch<R: Send + Sync + 'static>(
entry: &Arc<Entry<R>>,
clock: &WallClock,
fires: Vec<ZonedDateTime>,
) -> Effect<(), Never, R> {
let state = &entry.state;
if entry.job.overlap == OverlapPolicy::Skip && state.running.load(Ordering::SeqCst) > 0 {
for fire in fires {
state.record(CronRun::skipped(&entry.job.name, fire, CronSkip::Overlap));
}
return succeed(());
}
state.running.fetch_add(1, Ordering::SeqCst);
let batch = fires.into_iter().fold(succeed(()), |acc, fire| {
acc.then(run_once(Arc::clone(entry), clock.clone(), fire))
});
let done = Arc::clone(state);
batch
.ensuring(sync(move || {
done.running.fetch_sub(1, Ordering::SeqCst);
}))
.fork()
.map(|_| ())
}
fn run_once<R: Send + Sync + 'static>(
entry: Arc<Entry<R>>,
clock: WallClock,
fire: ZonedDateTime,
) -> Effect<(), Never, R> {
let task = Arc::clone(&entry.job.task);
let end = clock.clone();
let at = fire.clone();
clock.now().flat_map(move |started| {
suspend(move || task(at))
.exit::<Never>()
.flat_map(move |exit| {
end.now().flat_map(move |finished| {
let outcome = match exit {
Exit::Success(()) => CronOutcome::Succeeded,
Exit::Failure(cause) => CronOutcome::Failed(render(&cause)),
};
let run = CronRun {
job: Arc::clone(&entry.job.name),
scheduled: fire,
started: Some(started),
finished: Some(finished),
outcome,
};
entry.state.record(run.clone());
let hooks = if run.is_success() {
&entry.job.on_success
} else {
&entry.job.on_failure
};
hooks.iter().fold(succeed(()), |acc, hook| {
let (hook, run) = (Arc::clone(hook), run.clone());
acc.then(suspend(move || hook(&run)).exit::<Never>().map(|_| ()))
})
})
})
})
}
fn render(cause: &Cause<String>) -> String {
match cause {
Cause::Fail(e) => e.clone(),
Cause::Die(d) => format!("defect: {d}"),
Cause::Interrupt(_) => "interrupted".to_string(),
Cause::Both(a, b) | Cause::Then(a, b) => format!("{}; {}", render(a), render(b)),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Executor, TestExecutor};
#[test]
fn cron_job_new_at_receives_each_fire_time() {
let seen = Arc::new(Mutex::new(Vec::new()));
let s = Arc::clone(&seen);
let job = CronJob::new_at("tick", Cron::parse("*/15 * * * *").unwrap(), move |fire| {
let s = Arc::clone(&s);
sync::<(), &str, _>(move || s.lock().unwrap().push(fire.inner().timestamp().to_string()))
});
let registry = CronRegistry::new().with(job).unwrap();
let exec = TestExecutor::new();
let start = UtcDateTime::from_epoch_millis(1_767_225_600_000).unwrap(); let fiber = registry
.run(WallClock::anchored(exec.now(), start))
.fork_root(Arc::new(exec.clone()));
exec.advance(Duration::from_secs(1800));
assert_eq!(
*seen.lock().unwrap(),
["2026-01-01T00:15:00Z", "2026-01-01T00:30:00Z"]
);
fiber.interrupt_now();
}
}