use std::collections::BTreeMap;
use std::time::Duration;
use async_trait::async_trait;
use chrono::{DateTime, SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
use crate::run_store::NewRun;
use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
pub const SCHEDULE_NOT_FOUND_CODE: &str = "schedule.not_found";
pub const INVALID_SCHEDULE_CODE: &str = "schedule.invalid";
pub const DEFAULT_MISFIRE_GRACE: Duration = Duration::from_secs(60);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum ScheduleSpec {
Cron {
expr: String,
timezone: String,
},
At(DateTime<Utc>),
Every(Duration),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum MissedFirePolicy {
Skip,
FireOnce,
CatchUp(u32),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Jitter {
pub percent: u8,
pub max: Duration,
pub seed: u64,
}
impl Default for Jitter {
fn default() -> Self {
Self::new(Self::DEFAULT_PERCENT, Self::DEFAULT_MAX)
}
}
impl Jitter {
pub const DEFAULT_PERCENT: u8 = 15;
pub const DEFAULT_MAX: Duration = Duration::from_secs(9 * 60);
pub const MAX_PERCENT: u8 = 50;
pub fn new(percent: u8, max: Duration) -> Self {
Self { percent: percent.min(Self::MAX_PERCENT), max, seed: 0 }
}
#[must_use]
pub fn salted(mut self, salt: &str) -> Self {
self.seed = fnv1a(self.seed ^ FNV_OFFSET, salt.as_bytes());
self
}
pub fn window(&self, at: DateTime<Utc>, next: Option<DateTime<Utc>>) -> Duration {
let Some(gap) = next.and_then(|next| (next - at).to_std().ok()) else {
return Duration::ZERO;
};
let share = gap.as_nanos() * u128::from(self.percent.min(Self::MAX_PERCENT)) / 100;
Duration::from_nanos(u64::try_from(share).unwrap_or(u64::MAX)).min(self.max)
}
pub fn offset(&self, key: &str, at: DateTime<Utc>, next: Option<DateTime<Utc>>) -> Duration {
let window = self.window(at, next).as_nanos();
let share = u128::from(mix(fnv1a(self.seed ^ FNV_OFFSET, key.as_bytes())));
let nanos = (window * share) >> 64;
Duration::from_millis(u64::try_from(nanos / 1_000_000).unwrap_or(u64::MAX))
}
pub fn offset_in(&self, spec: &ScheduleSpec, key: &str, at: DateTime<Utc>) -> Duration {
self.offset(key, at, spec.next_after(at).ok().flatten())
}
}
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
fn fnv1a(mut state: u64, bytes: &[u8]) -> u64 {
for byte in bytes {
state ^= u64::from(*byte);
state = state.wrapping_mul(0x0100_0000_01b3);
}
state
}
fn mix(mut hash: u64) -> u64 {
hash ^= hash >> 33;
hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
hash ^= hash >> 33;
hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
hash ^ (hash >> 33)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Schedule {
pub id: String,
pub spec: ScheduleSpec,
pub run: NewRun,
pub missed: MissedFirePolicy,
pub paused: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub next_fire_at: Option<DateTime<Utc>>,
pub revision: u64,
}
impl Schedule {
pub fn new(
id: impl Into<String>,
spec: ScheduleSpec,
run: NewRun,
missed: MissedFirePolicy,
) -> Self {
Self { id: id.into(), spec, run, missed, paused: false, next_fire_at: None, revision: 0 }
}
pub fn with_next_fire_at(mut self, at: DateTime<Utc>) -> Self {
self.next_fire_at = Some(at);
self
}
pub fn with_paused(mut self, paused: bool) -> Self {
self.paused = paused;
self
}
pub fn run_for(&self, fire_time: DateTime<Utc>) -> NewRun {
let mut run = self.run.clone().with_service_subject();
run.idempotency_key = Some(firing_idempotency_key(&self.id, fire_time));
run
}
pub fn run_now(&self, request_id: &str) -> NewRun {
let mut run = self.run.clone().with_service_subject();
run.idempotency_key = Some(manual_idempotency_key(&self.id, request_id));
run
}
pub fn validate(&self) -> Result<()> {
if self.id.is_empty() {
return Err(invalid_schedule_error("id must not be empty"));
}
if matches!(self.spec, ScheduleSpec::Every(interval) if interval.is_zero()) {
return Err(invalid_schedule_error("an Every interval must be greater than zero"));
}
if self.missed == MissedFirePolicy::CatchUp(0) {
return Err(invalid_schedule_error("CatchUp must fire at least one occurrence"));
}
self.run.validate()
}
fn same_definition(&self, other: &Self) -> bool {
self.spec == other.spec
&& self.run == other.run
&& self.missed == other.missed
&& self.paused == other.paused
&& self.next_fire_at == other.next_fire_at
}
}
pub fn firing_idempotency_key(schedule_id: &str, fire_time: DateTime<Utc>) -> String {
format!("schedule:{schedule_id}:{}", fire_time.to_rfc3339_opts(SecondsFormat::AutoSi, true))
}
pub fn manual_idempotency_key(schedule_id: &str, request_id: &str) -> String {
format!("schedule:{schedule_id}:manual:{request_id}")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FirePlan {
pub fire_times: Vec<DateTime<Utc>>,
pub next_fire_at: Option<DateTime<Utc>>,
}
pub fn plan_fires(
spec: &ScheduleSpec,
missed: MissedFirePolicy,
due_at: DateTime<Utc>,
now: DateTime<Utc>,
grace: Duration,
) -> Result<FirePlan> {
if due_at > now {
return Ok(FirePlan { fire_times: Vec::new(), next_fire_at: Some(due_at) });
}
let wanted = match missed {
MissedFirePolicy::Skip | MissedFirePolicy::FireOnce => 1,
MissedFirePolicy::CatchUp(0) => {
return Err(invalid_schedule_error("CatchUp must fire at least one occurrence"));
}
MissedFirePolicy::CatchUp(count) => count as usize,
};
let mut plan = match spec {
ScheduleSpec::At(_) => FirePlan { fire_times: vec![due_at], next_fire_at: None },
ScheduleSpec::Every(interval) => {
let step = chrono::Duration::from_std(*interval)
.ok()
.filter(|step| *step > chrono::Duration::zero())
.ok_or_else(|| invalid_schedule_error("an Every interval must be positive"))?;
let step_nanos = step.num_nanoseconds().unwrap_or(i64::MAX).max(1);
let elapsed = (now - due_at).num_nanoseconds().unwrap_or(i64::MAX);
let latest = elapsed / step_nanos;
let first = (latest - wanted as i64 + 1).max(0);
let at = |k: i64| {
due_at
.checked_add_signed(chrono::Duration::nanoseconds(k.saturating_mul(step_nanos)))
};
FirePlan {
fire_times: (first..=latest).filter_map(at).collect(),
next_fire_at: at(latest + 1),
}
}
ScheduleSpec::Cron { expr, timezone } => {
cron::latest_and_next(expr, timezone, due_at, now, wanted)?
}
};
if missed == MissedFirePolicy::Skip {
let late = plan
.fire_times
.last()
.is_some_and(|last| (now - *last).to_std().unwrap_or_default() > grace);
if late {
plan.fire_times.clear();
}
}
Ok(plan)
}
impl ScheduleSpec {
pub fn next_after(&self, after: DateTime<Utc>) -> Result<Option<DateTime<Utc>>> {
match self {
Self::At(at) => Ok((*at > after).then_some(*at)),
Self::Every(interval) => chrono::Duration::from_std(*interval)
.ok()
.filter(|step| *step > chrono::Duration::zero())
.map(|step| after.checked_add_signed(step))
.ok_or_else(|| invalid_schedule_error("an Every interval must be positive")),
Self::Cron { expr, timezone } => {
Ok(cron::latest_and_next(expr, timezone, after, after, 0)?.next_fire_at)
}
}
}
}
#[cfg(feature = "cron")]
mod cron {
use std::str::FromStr;
use chrono::{DateTime, LocalResult, TimeZone, Utc};
use chrono_tz::Tz;
use super::invalid_schedule_error;
use crate::Result;
fn parse(expr: &str, timezone: &str) -> Result<(::cron::Schedule, Tz)> {
let fields: Vec<&str> = expr.split_whitespace().collect();
let expanded = match fields.as_slice() {
[minute, hour, day, month, weekday] => {
let weekday = unix_weekdays(weekday).map_err(|reason| {
invalid_schedule_error(&format!(
"cron expression '{expr}' does not parse: the day of the week \
'{weekday}' {reason}"
))
})?;
format!("0 {minute} {hour} {day} {month} {weekday}")
}
_ => expr.to_string(),
};
let schedule = ::cron::Schedule::from_str(&expanded).map_err(|error| {
invalid_schedule_error(&format!("cron expression '{expr}' does not parse: {error}"))
})?;
let tz = timezone.parse::<Tz>().map_err(|_| {
invalid_schedule_error(&format!(
"time zone '{timezone}' is not an IANA name such as 'UTC' or 'Europe/Berlin'"
))
})?;
Ok((schedule, tz))
}
fn unix_weekdays(field: &str) -> std::result::Result<String, String> {
const NAMES: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
if field == "*" || field == "?" {
return Ok(field.to_string());
}
let day = |text: &str| -> std::result::Result<usize, String> {
if let Ok(number) = text.parse::<usize>() {
return match number {
0..=7 => Ok(number),
_ => Err(format!("names day {number}; days are 0 to 7, 0 and 7 Sunday")),
};
}
match text.to_ascii_lowercase().as_str() {
"sun" | "sunday" => Ok(0),
"mon" | "monday" => Ok(1),
"tue" | "tues" | "tuesday" => Ok(2),
"wed" | "wednesday" => Ok(3),
"thu" | "thurs" | "thursday" => Ok(4),
"fri" | "friday" => Ok(5),
"sat" | "saturday" => Ok(6),
_ => Err(format!("holds '{text}', which is neither a day number nor a day name")),
}
};
let mut selected = [false; 7];
for part in field.split(',') {
let (base, step) = match part.split_once('/') {
Some((base, step)) => match step.parse::<usize>() {
Ok(step) if step > 0 => (base, Some(step)),
_ => return Err(format!("has the step '{step}'; a step is 1 or more")),
},
None => (part, None),
};
let (start, end) = match (base, base.split_once('-')) {
("*" | "?", _) => (0, 7),
(_, Some((start, end))) => (day(start)?, day(end)?),
(_, None) => {
let start = day(base)?;
(start, if step.is_some() { 7 } else { start })
}
};
if start > end {
return Err(format!("has the range '{base}', which runs backwards"));
}
for value in (start..=end).step_by(step.unwrap_or(1)) {
selected[value % 7] = true;
}
}
let names: Vec<&str> =
NAMES.iter().zip(selected).filter_map(|(name, on)| on.then_some(*name)).collect();
Ok(names.join(","))
}
fn is_repeat(at: &DateTime<Tz>) -> bool {
matches!(at.timezone().from_local_datetime(&at.naive_local()), LocalResult::Ambiguous(first, _) if first != *at)
}
pub(super) fn latest_and_next(
expr: &str,
timezone: &str,
due_at: DateTime<Utc>,
now: DateTime<Utc>,
wanted: usize,
) -> Result<super::FirePlan> {
let (schedule, tz) = parse(expr, timezone)?;
let next = schedule
.after(&now.with_timezone(&tz))
.find(|at| !is_repeat(at))
.map(|at| at.with_timezone(&Utc));
let mut latest = Vec::with_capacity(wanted);
let start = (now + chrono::Duration::seconds(1)).with_timezone(&tz);
for at in schedule.after(&start).rev() {
if latest.len() >= wanted {
break;
}
let at = at.with_timezone(&Utc);
if at <= due_at {
break;
}
if at <= now && !is_repeat(&at.with_timezone(&tz)) {
latest.push(at);
}
}
if latest.len() < wanted {
latest.push(due_at);
}
latest.reverse();
Ok(super::FirePlan { fire_times: latest, next_fire_at: next })
}
}
#[cfg(not(feature = "cron"))]
mod cron {
use chrono::{DateTime, Utc};
use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
pub(super) fn latest_and_next(
_expr: &str,
_timezone: &str,
_due_at: DateTime<Utc>,
_now: DateTime<Utc>,
_wanted: usize,
) -> Result<super::FirePlan> {
Err(AdkError::new(
ErrorComponent::Agent,
ErrorCategory::Unsupported,
"schedule.cron_unavailable",
"cron schedules need the `cron` feature of adk-core; enable it in Cargo.toml",
))
}
}
#[async_trait]
pub trait ScheduleStore: Send + Sync {
async fn upsert(&self, schedule: Schedule) -> Result<Schedule>;
async fn get(&self, id: &str) -> Result<Option<Schedule>>;
async fn list(&self) -> Result<Vec<Schedule>>;
async fn delete(&self, id: &str) -> Result<()>;
async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule>;
async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>>;
async fn advance(
&self,
id: &str,
expected_revision: u64,
next_fire_at: Option<DateTime<Utc>>,
) -> Result<bool>;
}
pub fn schedule_not_found_error(id: &str) -> AdkError {
AdkError::not_found(
ErrorComponent::Agent,
SCHEDULE_NOT_FOUND_CODE,
format!("schedule store has no schedule '{id}'; upsert it first"),
)
}
pub fn invalid_schedule_error(reason: &str) -> AdkError {
AdkError::new(
ErrorComponent::Agent,
ErrorCategory::InvalidInput,
INVALID_SCHEDULE_CODE,
format!("invalid schedule: {reason}"),
)
}
#[derive(Debug, Default)]
pub struct InMemoryScheduleStore {
schedules: Mutex<BTreeMap<String, Schedule>>,
}
impl InMemoryScheduleStore {
pub fn new() -> Self {
Self::default()
}
}
#[async_trait]
impl ScheduleStore for InMemoryScheduleStore {
async fn upsert(&self, mut schedule: Schedule) -> Result<Schedule> {
schedule.validate()?;
let mut schedules = self.schedules.lock().await;
if let Some(existing) = schedules.get(&schedule.id) {
if existing.same_definition(&schedule) {
return Ok(existing.clone());
}
schedule.revision = existing.revision + 1;
} else {
schedule.revision = 1;
}
schedules.insert(schedule.id.clone(), schedule.clone());
Ok(schedule)
}
async fn get(&self, id: &str) -> Result<Option<Schedule>> {
Ok(self.schedules.lock().await.get(id).cloned())
}
async fn list(&self) -> Result<Vec<Schedule>> {
Ok(self.schedules.lock().await.values().cloned().collect())
}
async fn delete(&self, id: &str) -> Result<()> {
self.schedules
.lock()
.await
.remove(id)
.map(|_| ())
.ok_or_else(|| schedule_not_found_error(id))
}
async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule> {
let mut schedules = self.schedules.lock().await;
let schedule = schedules.get_mut(id).ok_or_else(|| schedule_not_found_error(id))?;
if schedule.paused != paused {
schedule.paused = paused;
schedule.revision += 1;
}
Ok(schedule.clone())
}
async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>> {
let schedules = self.schedules.lock().await;
let mut due: Vec<_> = schedules
.values()
.filter(|schedule| {
!schedule.paused && schedule.next_fire_at.is_some_and(|at| at <= now)
})
.cloned()
.collect();
due.sort_by(|a, b| (a.next_fire_at, &a.id).cmp(&(b.next_fire_at, &b.id)));
due.truncate(limit);
Ok(due)
}
async fn advance(
&self,
id: &str,
expected_revision: u64,
next_fire_at: Option<DateTime<Utc>>,
) -> Result<bool> {
let mut schedules = self.schedules.lock().await;
let schedule = schedules.get_mut(id).ok_or_else(|| schedule_not_found_error(id))?;
if schedule.revision != expected_revision {
return Ok(false);
}
schedule.next_fire_at = next_fire_at;
schedule.revision += 1;
Ok(true)
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
fn at(day: u32, hour: u32, minute: u32) -> DateTime<Utc> {
Utc.with_ymd_and_hms(2026, 10, day, hour, minute, 0).single().unwrap()
}
#[test]
fn every_policies() {
let spec = ScheduleSpec::Every(Duration::from_secs(600));
let due = at(15, 9, 0);
let now = at(15, 9, 35);
let grace = DEFAULT_MISFIRE_GRACE;
let plan = |missed| plan_fires(&spec, missed, due, now, grace).unwrap();
let next = Some(at(15, 9, 40));
assert_eq!(
plan(MissedFirePolicy::FireOnce),
FirePlan { fire_times: vec![at(15, 9, 30)], next_fire_at: next }
);
assert_eq!(
plan(MissedFirePolicy::Skip),
FirePlan { fire_times: vec![], next_fire_at: next }
);
assert_eq!(
plan(MissedFirePolicy::CatchUp(10)),
FirePlan {
fire_times: vec![at(15, 9, 0), at(15, 9, 10), at(15, 9, 20), at(15, 9, 30)],
next_fire_at: next
}
);
let on_time = plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 9, 0), grace).unwrap();
assert_eq!(on_time, FirePlan { fire_times: vec![due], next_fire_at: Some(at(15, 9, 10)) });
let early = plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 8, 0), grace).unwrap();
assert_eq!(early, FirePlan { fire_times: vec![], next_fire_at: Some(due) });
}
#[test]
fn at_fires_once() {
let due = at(15, 9, 0);
let plan = plan_fires(
&ScheduleSpec::At(due),
MissedFirePolicy::FireOnce,
due,
at(15, 12, 0),
DEFAULT_MISFIRE_GRACE,
)
.unwrap();
assert_eq!(plan, FirePlan { fire_times: vec![due], next_fire_at: None });
assert_eq!(ScheduleSpec::At(due).next_after(at(15, 8, 0)).unwrap(), Some(due));
assert_eq!(ScheduleSpec::At(due).next_after(due).unwrap(), None);
}
#[test]
fn invalid_specs_are_refused() {
let zero = ScheduleSpec::Every(Duration::ZERO);
assert_eq!(zero.next_after(at(15, 0, 0)).unwrap_err().code, INVALID_SCHEDULE_CODE);
let error = plan_fires(
&ScheduleSpec::At(at(15, 0, 0)),
MissedFirePolicy::CatchUp(0),
at(15, 0, 0),
at(15, 0, 0),
DEFAULT_MISFIRE_GRACE,
)
.unwrap_err();
assert_eq!(error.code, INVALID_SCHEDULE_CODE);
}
#[test]
fn firing_keys_are_canonical() {
let fractional = at(15, 9, 0) + chrono::Duration::milliseconds(250);
assert_eq!(
firing_idempotency_key("a:b/ü", fractional),
"schedule:a:b/ü:2026-10-15T09:00:00.250Z"
);
}
#[cfg(feature = "cron")]
mod cron_specs {
use super::*;
fn cron(expr: &str, timezone: &str) -> ScheduleSpec {
ScheduleSpec::Cron { expr: expr.into(), timezone: timezone.into() }
}
#[test]
fn five_and_six_field_expressions() {
let five = cron("*/15 * * * *", "UTC");
let six = cron("0 */15 * * * *", "UTC");
assert_eq!(five.next_after(at(15, 9, 1)).unwrap(), Some(at(15, 9, 15)));
assert_eq!(six.next_after(at(15, 9, 1)).unwrap(), Some(at(15, 9, 15)));
}
fn fires(spec: &ScheduleSpec, from: DateTime<Utc>, count: usize) -> Vec<DateTime<Utc>> {
let mut cursor = from;
let mut all = Vec::with_capacity(count);
while all.len() < count {
cursor = spec.next_after(cursor).unwrap().unwrap();
all.push(cursor);
}
all
}
#[test]
fn five_fields_count_weekdays_as_unix_cron_does() {
let weekdays = cron("0 9 * * 1-5", "UTC");
assert_eq!(
fires(&weekdays, at(18, 12, 0), 6),
vec![
at(19, 9, 0),
at(20, 9, 0),
at(21, 9, 0),
at(22, 9, 0),
at(23, 9, 0),
at(26, 9, 0)
],
"Monday to Friday, never Saturday or Sunday"
);
assert_eq!(weekdays.next_after(at(24, 10, 0)).unwrap(), Some(at(26, 9, 0)));
assert_eq!(fires(&cron("0 9 * * Mon-Fri", "UTC"), at(18, 12, 0), 6), {
fires(&weekdays, at(18, 12, 0), 6)
});
}
#[test]
fn zero_and_seven_are_sunday_and_six_is_saturday() {
for sunday in ["0", "7", "Sun", "0,7"] {
let spec = cron(&format!("0 9 * * {sunday}"), "UTC");
assert_eq!(
fires(&spec, at(23, 10, 0), 2),
vec![at(25, 9, 0), Utc.with_ymd_and_hms(2026, 11, 1, 9, 0, 0).unwrap()],
"{sunday}"
);
}
let saturday = cron("0 9 * * 6", "UTC");
assert_eq!(fires(&saturday, at(23, 10, 0), 2), vec![at(24, 9, 0), at(31, 9, 0)]);
let weekend = cron("30 7 * * 6,0", "UTC");
assert_eq!(
fires(&weekend, at(23, 10, 0), 3),
vec![at(24, 7, 30), at(25, 7, 30), at(31, 7, 30)]
);
let friday_to_sunday = cron("0 9 * * 5-7", "UTC");
assert_eq!(
fires(&friday_to_sunday, at(22, 10, 0), 4),
vec![at(23, 9, 0), at(24, 9, 0), at(25, 9, 0), at(30, 9, 0)]
);
}
#[test]
fn five_field_weekday_steps() {
let odd = cron("0 9 * * 1-5/2", "UTC");
assert_eq!(
fires(&odd, at(25, 10, 0), 3),
vec![at(26, 9, 0), at(28, 9, 0), at(30, 9, 0)]
);
let every_third = cron("0 9 * * */3", "UTC");
assert_eq!(
fires(&every_third, at(24, 10, 0), 3),
vec![at(25, 9, 0), at(28, 9, 0), at(31, 9, 0)]
);
}
#[test]
fn six_and_seven_fields_keep_the_crates_numbering() {
let six = cron("0 0 9 * * 1-5", "UTC");
assert_eq!(
fires(&six, at(23, 10, 0), 5),
vec![at(25, 9, 0), at(26, 9, 0), at(27, 9, 0), at(28, 9, 0), at(29, 9, 0)]
);
let seven = cron("0 0 9 * * 7 2026", "UTC");
assert_eq!(seven.next_after(at(23, 10, 0)).unwrap(), Some(at(24, 9, 0)));
}
#[test]
fn bad_five_field_weekdays_are_refused() {
for field in ["8", "5-1", "5L", "*/0", "MON#2", "1,", "Fri-Sun"] {
let error =
cron(&format!("0 9 * * {field}"), "UTC").next_after(at(15, 0, 0)).unwrap_err();
assert_eq!(error.code, INVALID_SCHEDULE_CODE, "{field}");
assert!(error.message.contains("day of the week"), "{field}: {}", error.message);
}
}
#[test]
fn catch_up_and_fire_once() {
let spec = cron("0 * * * *", "UTC");
let due = at(15, 9, 0);
let now = at(15, 12, 30);
let catch_up =
plan_fires(&spec, MissedFirePolicy::CatchUp(3), due, now, DEFAULT_MISFIRE_GRACE)
.unwrap();
assert_eq!(
catch_up,
FirePlan {
fire_times: vec![at(15, 10, 0), at(15, 11, 0), at(15, 12, 0)],
next_fire_at: Some(at(15, 13, 0))
}
);
let all =
plan_fires(&spec, MissedFirePolicy::CatchUp(100), due, now, DEFAULT_MISFIRE_GRACE)
.unwrap();
assert_eq!(
all.fire_times,
vec![at(15, 9, 0), at(15, 10, 0), at(15, 11, 0), at(15, 12, 0)]
);
let once =
plan_fires(&spec, MissedFirePolicy::FireOnce, due, now, DEFAULT_MISFIRE_GRACE)
.unwrap();
assert_eq!(once.fire_times, vec![at(15, 12, 0)]);
let skip =
plan_fires(&spec, MissedFirePolicy::Skip, due, now, DEFAULT_MISFIRE_GRACE).unwrap();
assert!(skip.fire_times.is_empty());
let on_time =
plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 9, 0), DEFAULT_MISFIRE_GRACE)
.unwrap();
assert_eq!(on_time.fire_times, vec![due]);
}
#[test]
fn time_zones_and_daylight_saving() {
let spec = cron("0 9 * * *", "Europe/Berlin");
assert_eq!(spec.next_after(at(24, 0, 0)).unwrap(), Some(at(24, 7, 0)));
assert_eq!(spec.next_after(at(25, 0, 0)).unwrap(), Some(at(25, 8, 0)));
let repeated = cron("0 30 2 * * *", "Europe/Berlin");
let first = Utc.with_ymd_and_hms(2026, 10, 25, 0, 30, 0).unwrap();
assert_eq!(repeated.next_after(at(25, 0, 0)).unwrap(), Some(first));
assert_eq!(
repeated.next_after(first).unwrap(),
Some(Utc.with_ymd_and_hms(2026, 10, 26, 1, 30, 0).unwrap())
);
let plan = plan_fires(
&repeated,
MissedFirePolicy::CatchUp(5),
first,
at(25, 12, 0),
DEFAULT_MISFIRE_GRACE,
)
.unwrap();
assert_eq!(plan.fire_times, vec![first]);
}
#[test]
fn bad_expressions_and_zones_are_refused() {
assert_eq!(
cron("not cron", "UTC").next_after(at(15, 0, 0)).unwrap_err().code,
INVALID_SCHEDULE_CODE
);
assert_eq!(
cron("* * * * *", "Mars/Olympus").next_after(at(15, 0, 0)).unwrap_err().code,
INVALID_SCHEDULE_CODE
);
}
}
mod jitter {
use proptest::prelude::*;
use super::*;
#[test]
fn a_fire_lands_before_the_next_occurrence() {
let jitter = Jitter::new(90, Duration::from_secs(3600));
assert_eq!(jitter.percent, Jitter::MAX_PERCENT, "clamped to half the gap");
let at = at(15, 9, 0);
let next = Some(at + chrono::Duration::minutes(10));
assert_eq!(jitter.window(at, next), Duration::from_secs(300));
for key in ["a", "b", "nightly", "report-17"] {
assert!(jitter.offset(key, at, next) < Duration::from_secs(300));
}
assert_eq!(jitter.window(at, None), Duration::ZERO);
assert_eq!(
Jitter::new(0, Duration::from_secs(60)).offset("a", at, next),
Duration::ZERO
);
}
#[test]
fn the_default_caps_a_daily_schedule_at_nine_minutes() {
let daily = ScheduleSpec::Cron { expr: "0 9 * * *".into(), timezone: "UTC".into() };
let at = at(15, 9, 0);
let jitter = Jitter::default();
assert_eq!(jitter.window(at, daily.next_after(at).unwrap()), Jitter::DEFAULT_MAX);
let every_minute = ScheduleSpec::Every(Duration::from_secs(60));
assert_eq!(
jitter.window(at, every_minute.next_after(at).unwrap()),
Duration::from_secs(9),
"15 percent of a minute"
);
}
#[test]
fn schedules_and_salts_spread_apart() {
let jitter = Jitter::new(50, Duration::from_secs(3600));
let at = at(15, 9, 0);
let next = Some(at + chrono::Duration::hours(2));
let offsets: std::collections::BTreeSet<Duration> =
(0..64).map(|n| jitter.offset(&format!("job-{n}"), at, next)).collect();
assert!(offsets.len() > 60, "64 schedules take {} distinct offsets", offsets.len());
let salted = jitter.salted("tenant-a");
assert_ne!(salted.offset("job-1", at, next), jitter.offset("job-1", at, next));
assert_eq!(salted, jitter.salted("tenant-a"), "a salt is deterministic");
}
#[test]
fn run_now_keeps_the_concurrency_key_and_leaves_the_schedule() {
let run = NewRun::new("default", "ops", "system", "probe", serde_json::json!({}))
.with_concurrency_key("cron:probe", crate::OnConflict::Reject);
let schedule = Schedule::new(
"probe",
ScheduleSpec::Every(Duration::from_secs(60)),
run,
MissedFirePolicy::Skip,
)
.with_next_fire_at(at(15, 9, 0));
let manual = schedule.run_now("r1");
assert_eq!(manual.idempotency_key.as_deref(), Some("schedule:probe:manual:r1"));
assert_eq!(manual.concurrency_key.as_deref(), Some("cron:probe"));
assert_ne!(manual.idempotency_key, schedule.run_for(at(15, 9, 0)).idempotency_key);
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn offsets_stay_inside_the_window(
key in "[a-z0-9:-]{1,24}",
percent in 0u8..=255,
max_ms in 0u64..=86_400_000,
gap_ms in 1i64..=7 * 86_400_000,
seed in any::<u64>(),
) {
let mut jitter = Jitter::new(percent, Duration::from_millis(max_ms));
jitter.seed = seed;
let at = at(15, 9, 0);
let next = at + chrono::Duration::milliseconds(gap_ms);
let window = jitter.window(at, Some(next));
let offset = jitter.offset(&key, at, Some(next));
prop_assert!(window <= Duration::from_millis(max_ms));
prop_assert!(window.as_nanos() * 2 <= u128::from(gap_ms.unsigned_abs()) * 1_000_000);
prop_assert!(offset <= window);
prop_assert!(window.is_zero() || offset < window);
prop_assert!(at + chrono::Duration::from_std(offset).unwrap() < next);
prop_assert_eq!(offset, jitter.offset(&key, at, Some(next)));
}
}
}
}