1use std::collections::BTreeMap;
60use std::time::Duration;
61
62use async_trait::async_trait;
63use chrono::{DateTime, SecondsFormat, Utc};
64use serde::{Deserialize, Serialize};
65use tokio::sync::Mutex;
66
67use crate::run_store::NewRun;
68use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
69
70pub const SCHEDULE_NOT_FOUND_CODE: &str = "schedule.not_found";
72pub const INVALID_SCHEDULE_CODE: &str = "schedule.invalid";
74
75pub const DEFAULT_MISFIRE_GRACE: Duration = Duration::from_secs(60);
77
78#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90#[non_exhaustive]
91pub enum ScheduleSpec {
92 Cron {
94 expr: String,
98 timezone: String,
100 },
101 At(DateTime<Utc>),
103 Every(Duration),
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
109#[serde(rename_all = "camelCase")]
110#[non_exhaustive]
111pub enum MissedFirePolicy {
112 Skip,
114 FireOnce,
116 CatchUp(u32),
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
160#[non_exhaustive]
161pub struct Jitter {
162 pub percent: u8,
164 pub max: Duration,
166 pub seed: u64,
169}
170
171impl Default for Jitter {
172 fn default() -> Self {
174 Self::new(Self::DEFAULT_PERCENT, Self::DEFAULT_MAX)
175 }
176}
177
178impl Jitter {
179 pub const DEFAULT_PERCENT: u8 = 15;
181 pub const DEFAULT_MAX: Duration = Duration::from_secs(9 * 60);
183 pub const MAX_PERCENT: u8 = 50;
185
186 pub fn new(percent: u8, max: Duration) -> Self {
189 Self { percent: percent.min(Self::MAX_PERCENT), max, seed: 0 }
190 }
191
192 #[must_use]
203 pub fn salted(mut self, salt: &str) -> Self {
204 self.seed = fnv1a(self.seed ^ FNV_OFFSET, salt.as_bytes());
205 self
206 }
207
208 pub fn window(&self, at: DateTime<Utc>, next: Option<DateTime<Utc>>) -> Duration {
211 let Some(gap) = next.and_then(|next| (next - at).to_std().ok()) else {
212 return Duration::ZERO;
213 };
214 let share = gap.as_nanos() * u128::from(self.percent.min(Self::MAX_PERCENT)) / 100;
215 Duration::from_nanos(u64::try_from(share).unwrap_or(u64::MAX)).min(self.max)
216 }
217
218 pub fn offset(&self, key: &str, at: DateTime<Utc>, next: Option<DateTime<Utc>>) -> Duration {
222 let window = self.window(at, next).as_nanos();
223 let share = u128::from(mix(fnv1a(self.seed ^ FNV_OFFSET, key.as_bytes())));
224 let nanos = (window * share) >> 64;
226 Duration::from_millis(u64::try_from(nanos / 1_000_000).unwrap_or(u64::MAX))
227 }
228
229 pub fn offset_in(&self, spec: &ScheduleSpec, key: &str, at: DateTime<Utc>) -> Duration {
232 self.offset(key, at, spec.next_after(at).ok().flatten())
233 }
234}
235
236const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
237
238fn fnv1a(mut state: u64, bytes: &[u8]) -> u64 {
241 for byte in bytes {
242 state ^= u64::from(*byte);
243 state = state.wrapping_mul(0x0100_0000_01b3);
244 }
245 state
246}
247
248fn mix(mut hash: u64) -> u64 {
251 hash ^= hash >> 33;
252 hash = hash.wrapping_mul(0xff51_afd7_ed55_8ccd);
253 hash ^= hash >> 33;
254 hash = hash.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
255 hash ^ (hash >> 33)
256}
257
258#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
283#[serde(rename_all = "camelCase")]
284pub struct Schedule {
285 pub id: String,
287 pub spec: ScheduleSpec,
289 pub run: NewRun,
291 pub missed: MissedFirePolicy,
293 pub paused: bool,
295 #[serde(default, skip_serializing_if = "Option::is_none")]
297 pub next_fire_at: Option<DateTime<Utc>>,
298 pub revision: u64,
300}
301
302impl Schedule {
303 pub fn new(
305 id: impl Into<String>,
306 spec: ScheduleSpec,
307 run: NewRun,
308 missed: MissedFirePolicy,
309 ) -> Self {
310 Self { id: id.into(), spec, run, missed, paused: false, next_fire_at: None, revision: 0 }
311 }
312
313 pub fn with_next_fire_at(mut self, at: DateTime<Utc>) -> Self {
315 self.next_fire_at = Some(at);
316 self
317 }
318
319 pub fn with_paused(mut self, paused: bool) -> Self {
321 self.paused = paused;
322 self
323 }
324
325 pub fn run_for(&self, fire_time: DateTime<Utc>) -> NewRun {
329 let mut run = self.run.clone().with_service_subject();
330 run.idempotency_key = Some(firing_idempotency_key(&self.id, fire_time));
331 run
332 }
333
334 pub fn run_now(&self, request_id: &str) -> NewRun {
356 let mut run = self.run.clone().with_service_subject();
357 run.idempotency_key = Some(manual_idempotency_key(&self.id, request_id));
358 run
359 }
360
361 pub fn validate(&self) -> Result<()> {
369 if self.id.is_empty() {
370 return Err(invalid_schedule_error("id must not be empty"));
371 }
372 if matches!(self.spec, ScheduleSpec::Every(interval) if interval.is_zero()) {
373 return Err(invalid_schedule_error("an Every interval must be greater than zero"));
374 }
375 if self.missed == MissedFirePolicy::CatchUp(0) {
376 return Err(invalid_schedule_error("CatchUp must fire at least one occurrence"));
377 }
378 self.run.validate()
379 }
380
381 fn same_definition(&self, other: &Self) -> bool {
382 self.spec == other.spec
383 && self.run == other.run
384 && self.missed == other.missed
385 && self.paused == other.paused
386 && self.next_fire_at == other.next_fire_at
387 }
388}
389
390pub fn firing_idempotency_key(schedule_id: &str, fire_time: DateTime<Utc>) -> String {
402 format!("schedule:{schedule_id}:{}", fire_time.to_rfc3339_opts(SecondsFormat::AutoSi, true))
403}
404
405pub fn manual_idempotency_key(schedule_id: &str, request_id: &str) -> String {
415 format!("schedule:{schedule_id}:manual:{request_id}")
416}
417
418#[derive(Debug, Clone, PartialEq, Eq)]
420pub struct FirePlan {
421 pub fire_times: Vec<DateTime<Utc>>,
423 pub next_fire_at: Option<DateTime<Utc>>,
425}
426
427pub fn plan_fires(
456 spec: &ScheduleSpec,
457 missed: MissedFirePolicy,
458 due_at: DateTime<Utc>,
459 now: DateTime<Utc>,
460 grace: Duration,
461) -> Result<FirePlan> {
462 if due_at > now {
463 return Ok(FirePlan { fire_times: Vec::new(), next_fire_at: Some(due_at) });
464 }
465 let wanted = match missed {
466 MissedFirePolicy::Skip | MissedFirePolicy::FireOnce => 1,
467 MissedFirePolicy::CatchUp(0) => {
468 return Err(invalid_schedule_error("CatchUp must fire at least one occurrence"));
469 }
470 MissedFirePolicy::CatchUp(count) => count as usize,
471 };
472 let mut plan = match spec {
473 ScheduleSpec::At(_) => FirePlan { fire_times: vec![due_at], next_fire_at: None },
474 ScheduleSpec::Every(interval) => {
475 let step = chrono::Duration::from_std(*interval)
476 .ok()
477 .filter(|step| *step > chrono::Duration::zero())
478 .ok_or_else(|| invalid_schedule_error("an Every interval must be positive"))?;
479 let step_nanos = step.num_nanoseconds().unwrap_or(i64::MAX).max(1);
480 let elapsed = (now - due_at).num_nanoseconds().unwrap_or(i64::MAX);
481 let latest = elapsed / step_nanos;
482 let first = (latest - wanted as i64 + 1).max(0);
483 let at = |k: i64| {
484 due_at
485 .checked_add_signed(chrono::Duration::nanoseconds(k.saturating_mul(step_nanos)))
486 };
487 FirePlan {
488 fire_times: (first..=latest).filter_map(at).collect(),
489 next_fire_at: at(latest + 1),
490 }
491 }
492 ScheduleSpec::Cron { expr, timezone } => {
493 cron::latest_and_next(expr, timezone, due_at, now, wanted)?
494 }
495 };
496 if missed == MissedFirePolicy::Skip {
497 let late = plan
498 .fire_times
499 .last()
500 .is_some_and(|last| (now - *last).to_std().unwrap_or_default() > grace);
501 if late {
502 plan.fire_times.clear();
503 }
504 }
505 Ok(plan)
506}
507
508impl ScheduleSpec {
509 pub fn next_after(&self, after: DateTime<Utc>) -> Result<Option<DateTime<Utc>>> {
532 match self {
533 Self::At(at) => Ok((*at > after).then_some(*at)),
534 Self::Every(interval) => chrono::Duration::from_std(*interval)
535 .ok()
536 .filter(|step| *step > chrono::Duration::zero())
537 .map(|step| after.checked_add_signed(step))
538 .ok_or_else(|| invalid_schedule_error("an Every interval must be positive")),
539 Self::Cron { expr, timezone } => {
540 Ok(cron::latest_and_next(expr, timezone, after, after, 0)?.next_fire_at)
541 }
542 }
543 }
544}
545
546#[cfg(feature = "cron")]
547mod cron {
548 use std::str::FromStr;
549
550 use chrono::{DateTime, LocalResult, TimeZone, Utc};
551 use chrono_tz::Tz;
552
553 use super::invalid_schedule_error;
554 use crate::Result;
555
556 fn parse(expr: &str, timezone: &str) -> Result<(::cron::Schedule, Tz)> {
557 let fields: Vec<&str> = expr.split_whitespace().collect();
558 let expanded = match fields.as_slice() {
559 [minute, hour, day, month, weekday] => {
561 let weekday = unix_weekdays(weekday).map_err(|reason| {
562 invalid_schedule_error(&format!(
563 "cron expression '{expr}' does not parse: the day of the week \
564 '{weekday}' {reason}"
565 ))
566 })?;
567 format!("0 {minute} {hour} {day} {month} {weekday}")
568 }
569 _ => expr.to_string(),
570 };
571 let schedule = ::cron::Schedule::from_str(&expanded).map_err(|error| {
572 invalid_schedule_error(&format!("cron expression '{expr}' does not parse: {error}"))
573 })?;
574 let tz = timezone.parse::<Tz>().map_err(|_| {
575 invalid_schedule_error(&format!(
576 "time zone '{timezone}' is not an IANA name such as 'UTC' or 'Europe/Berlin'"
577 ))
578 })?;
579 Ok((schedule, tz))
580 }
581
582 fn unix_weekdays(field: &str) -> std::result::Result<String, String> {
586 const NAMES: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
587 if field == "*" || field == "?" {
588 return Ok(field.to_string());
589 }
590 let day = |text: &str| -> std::result::Result<usize, String> {
591 if let Ok(number) = text.parse::<usize>() {
592 return match number {
593 0..=7 => Ok(number),
594 _ => Err(format!("names day {number}; days are 0 to 7, 0 and 7 Sunday")),
595 };
596 }
597 match text.to_ascii_lowercase().as_str() {
598 "sun" | "sunday" => Ok(0),
599 "mon" | "monday" => Ok(1),
600 "tue" | "tues" | "tuesday" => Ok(2),
601 "wed" | "wednesday" => Ok(3),
602 "thu" | "thurs" | "thursday" => Ok(4),
603 "fri" | "friday" => Ok(5),
604 "sat" | "saturday" => Ok(6),
605 _ => Err(format!("holds '{text}', which is neither a day number nor a day name")),
606 }
607 };
608 let mut selected = [false; 7];
609 for part in field.split(',') {
610 let (base, step) = match part.split_once('/') {
611 Some((base, step)) => match step.parse::<usize>() {
612 Ok(step) if step > 0 => (base, Some(step)),
613 _ => return Err(format!("has the step '{step}'; a step is 1 or more")),
614 },
615 None => (part, None),
616 };
617 let (start, end) = match (base, base.split_once('-')) {
619 ("*" | "?", _) => (0, 7),
620 (_, Some((start, end))) => (day(start)?, day(end)?),
621 (_, None) => {
622 let start = day(base)?;
623 (start, if step.is_some() { 7 } else { start })
624 }
625 };
626 if start > end {
627 return Err(format!("has the range '{base}', which runs backwards"));
628 }
629 for value in (start..=end).step_by(step.unwrap_or(1)) {
630 selected[value % 7] = true;
631 }
632 }
633 let names: Vec<&str> =
634 NAMES.iter().zip(selected).filter_map(|(name, on)| on.then_some(*name)).collect();
635 Ok(names.join(","))
636 }
637
638 fn is_repeat(at: &DateTime<Tz>) -> bool {
641 matches!(at.timezone().from_local_datetime(&at.naive_local()), LocalResult::Ambiguous(first, _) if first != *at)
642 }
643
644 pub(super) fn latest_and_next(
647 expr: &str,
648 timezone: &str,
649 due_at: DateTime<Utc>,
650 now: DateTime<Utc>,
651 wanted: usize,
652 ) -> Result<super::FirePlan> {
653 let (schedule, tz) = parse(expr, timezone)?;
654 let next = schedule
655 .after(&now.with_timezone(&tz))
656 .find(|at| !is_repeat(at))
657 .map(|at| at.with_timezone(&Utc));
658 let mut latest = Vec::with_capacity(wanted);
659 let start = (now + chrono::Duration::seconds(1)).with_timezone(&tz);
661 for at in schedule.after(&start).rev() {
662 if latest.len() >= wanted {
663 break;
664 }
665 let at = at.with_timezone(&Utc);
666 if at <= due_at {
667 break;
668 }
669 if at <= now && !is_repeat(&at.with_timezone(&tz)) {
670 latest.push(at);
671 }
672 }
673 if latest.len() < wanted {
674 latest.push(due_at);
675 }
676 latest.reverse();
677 Ok(super::FirePlan { fire_times: latest, next_fire_at: next })
678 }
679}
680
681#[cfg(not(feature = "cron"))]
682mod cron {
683 use chrono::{DateTime, Utc};
684
685 use crate::{AdkError, ErrorCategory, ErrorComponent, Result};
686
687 pub(super) fn latest_and_next(
688 _expr: &str,
689 _timezone: &str,
690 _due_at: DateTime<Utc>,
691 _now: DateTime<Utc>,
692 _wanted: usize,
693 ) -> Result<super::FirePlan> {
694 Err(AdkError::new(
695 ErrorComponent::Agent,
696 ErrorCategory::Unsupported,
697 "schedule.cron_unavailable",
698 "cron schedules need the `cron` feature of adk-core; enable it in Cargo.toml",
699 ))
700 }
701}
702
703#[async_trait]
707pub trait ScheduleStore: Send + Sync {
708 async fn upsert(&self, schedule: Schedule) -> Result<Schedule>;
719
720 async fn get(&self, id: &str) -> Result<Option<Schedule>>;
722
723 async fn list(&self) -> Result<Vec<Schedule>>;
725
726 async fn delete(&self, id: &str) -> Result<()>;
732
733 async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule>;
739
740 async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>>;
743
744 async fn advance(
751 &self,
752 id: &str,
753 expected_revision: u64,
754 next_fire_at: Option<DateTime<Utc>>,
755 ) -> Result<bool>;
756}
757
758pub fn schedule_not_found_error(id: &str) -> AdkError {
766 AdkError::not_found(
767 ErrorComponent::Agent,
768 SCHEDULE_NOT_FOUND_CODE,
769 format!("schedule store has no schedule '{id}'; upsert it first"),
770 )
771}
772
773pub fn invalid_schedule_error(reason: &str) -> AdkError {
782 AdkError::new(
783 ErrorComponent::Agent,
784 ErrorCategory::InvalidInput,
785 INVALID_SCHEDULE_CODE,
786 format!("invalid schedule: {reason}"),
787 )
788}
789
790#[derive(Debug, Default)]
820pub struct InMemoryScheduleStore {
821 schedules: Mutex<BTreeMap<String, Schedule>>,
822}
823
824impl InMemoryScheduleStore {
825 pub fn new() -> Self {
827 Self::default()
828 }
829}
830
831#[async_trait]
832impl ScheduleStore for InMemoryScheduleStore {
833 async fn upsert(&self, mut schedule: Schedule) -> Result<Schedule> {
834 schedule.validate()?;
835 let mut schedules = self.schedules.lock().await;
836 if let Some(existing) = schedules.get(&schedule.id) {
837 if existing.same_definition(&schedule) {
838 return Ok(existing.clone());
839 }
840 schedule.revision = existing.revision + 1;
841 } else {
842 schedule.revision = 1;
843 }
844 schedules.insert(schedule.id.clone(), schedule.clone());
845 Ok(schedule)
846 }
847
848 async fn get(&self, id: &str) -> Result<Option<Schedule>> {
849 Ok(self.schedules.lock().await.get(id).cloned())
850 }
851
852 async fn list(&self) -> Result<Vec<Schedule>> {
853 Ok(self.schedules.lock().await.values().cloned().collect())
854 }
855
856 async fn delete(&self, id: &str) -> Result<()> {
857 self.schedules
858 .lock()
859 .await
860 .remove(id)
861 .map(|_| ())
862 .ok_or_else(|| schedule_not_found_error(id))
863 }
864
865 async fn set_paused(&self, id: &str, paused: bool) -> Result<Schedule> {
866 let mut schedules = self.schedules.lock().await;
867 let schedule = schedules.get_mut(id).ok_or_else(|| schedule_not_found_error(id))?;
868 if schedule.paused != paused {
869 schedule.paused = paused;
870 schedule.revision += 1;
871 }
872 Ok(schedule.clone())
873 }
874
875 async fn due(&self, now: DateTime<Utc>, limit: usize) -> Result<Vec<Schedule>> {
876 let schedules = self.schedules.lock().await;
877 let mut due: Vec<_> = schedules
878 .values()
879 .filter(|schedule| {
880 !schedule.paused && schedule.next_fire_at.is_some_and(|at| at <= now)
881 })
882 .cloned()
883 .collect();
884 due.sort_by(|a, b| (a.next_fire_at, &a.id).cmp(&(b.next_fire_at, &b.id)));
885 due.truncate(limit);
886 Ok(due)
887 }
888
889 async fn advance(
890 &self,
891 id: &str,
892 expected_revision: u64,
893 next_fire_at: Option<DateTime<Utc>>,
894 ) -> Result<bool> {
895 let mut schedules = self.schedules.lock().await;
896 let schedule = schedules.get_mut(id).ok_or_else(|| schedule_not_found_error(id))?;
897 if schedule.revision != expected_revision {
898 return Ok(false);
899 }
900 schedule.next_fire_at = next_fire_at;
901 schedule.revision += 1;
902 Ok(true)
903 }
904}
905
906#[cfg(test)]
907mod tests {
908 use super::*;
909 use chrono::TimeZone;
910
911 fn at(day: u32, hour: u32, minute: u32) -> DateTime<Utc> {
912 Utc.with_ymd_and_hms(2026, 10, day, hour, minute, 0).single().unwrap()
913 }
914
915 #[test]
916 fn every_policies() {
917 let spec = ScheduleSpec::Every(Duration::from_secs(600));
918 let due = at(15, 9, 0);
919 let now = at(15, 9, 35);
920 let grace = DEFAULT_MISFIRE_GRACE;
921 let plan = |missed| plan_fires(&spec, missed, due, now, grace).unwrap();
922 let next = Some(at(15, 9, 40));
923 assert_eq!(
924 plan(MissedFirePolicy::FireOnce),
925 FirePlan { fire_times: vec![at(15, 9, 30)], next_fire_at: next }
926 );
927 assert_eq!(
928 plan(MissedFirePolicy::Skip),
929 FirePlan { fire_times: vec![], next_fire_at: next }
930 );
931 assert_eq!(
932 plan(MissedFirePolicy::CatchUp(10)),
933 FirePlan {
934 fire_times: vec![at(15, 9, 0), at(15, 9, 10), at(15, 9, 20), at(15, 9, 30)],
935 next_fire_at: next
936 }
937 );
938 let on_time = plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 9, 0), grace).unwrap();
939 assert_eq!(on_time, FirePlan { fire_times: vec![due], next_fire_at: Some(at(15, 9, 10)) });
940 let early = plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 8, 0), grace).unwrap();
941 assert_eq!(early, FirePlan { fire_times: vec![], next_fire_at: Some(due) });
942 }
943
944 #[test]
945 fn at_fires_once() {
946 let due = at(15, 9, 0);
947 let plan = plan_fires(
948 &ScheduleSpec::At(due),
949 MissedFirePolicy::FireOnce,
950 due,
951 at(15, 12, 0),
952 DEFAULT_MISFIRE_GRACE,
953 )
954 .unwrap();
955 assert_eq!(plan, FirePlan { fire_times: vec![due], next_fire_at: None });
956 assert_eq!(ScheduleSpec::At(due).next_after(at(15, 8, 0)).unwrap(), Some(due));
957 assert_eq!(ScheduleSpec::At(due).next_after(due).unwrap(), None);
958 }
959
960 #[test]
961 fn invalid_specs_are_refused() {
962 let zero = ScheduleSpec::Every(Duration::ZERO);
963 assert_eq!(zero.next_after(at(15, 0, 0)).unwrap_err().code, INVALID_SCHEDULE_CODE);
964 let error = plan_fires(
965 &ScheduleSpec::At(at(15, 0, 0)),
966 MissedFirePolicy::CatchUp(0),
967 at(15, 0, 0),
968 at(15, 0, 0),
969 DEFAULT_MISFIRE_GRACE,
970 )
971 .unwrap_err();
972 assert_eq!(error.code, INVALID_SCHEDULE_CODE);
973 }
974
975 #[test]
976 fn firing_keys_are_canonical() {
977 let fractional = at(15, 9, 0) + chrono::Duration::milliseconds(250);
978 assert_eq!(
979 firing_idempotency_key("a:b/ü", fractional),
980 "schedule:a:b/ü:2026-10-15T09:00:00.250Z"
981 );
982 }
983
984 #[cfg(feature = "cron")]
985 mod cron_specs {
986 use super::*;
987
988 fn cron(expr: &str, timezone: &str) -> ScheduleSpec {
989 ScheduleSpec::Cron { expr: expr.into(), timezone: timezone.into() }
990 }
991
992 #[test]
993 fn five_and_six_field_expressions() {
994 let five = cron("*/15 * * * *", "UTC");
995 let six = cron("0 */15 * * * *", "UTC");
996 assert_eq!(five.next_after(at(15, 9, 1)).unwrap(), Some(at(15, 9, 15)));
997 assert_eq!(six.next_after(at(15, 9, 1)).unwrap(), Some(at(15, 9, 15)));
998 }
999
1000 fn fires(spec: &ScheduleSpec, from: DateTime<Utc>, count: usize) -> Vec<DateTime<Utc>> {
1002 let mut cursor = from;
1003 let mut all = Vec::with_capacity(count);
1004 while all.len() < count {
1005 cursor = spec.next_after(cursor).unwrap().unwrap();
1006 all.push(cursor);
1007 }
1008 all
1009 }
1010
1011 #[test]
1013 fn five_fields_count_weekdays_as_unix_cron_does() {
1014 let weekdays = cron("0 9 * * 1-5", "UTC");
1015 assert_eq!(
1016 fires(&weekdays, at(18, 12, 0), 6),
1017 vec![
1018 at(19, 9, 0),
1019 at(20, 9, 0),
1020 at(21, 9, 0),
1021 at(22, 9, 0),
1022 at(23, 9, 0),
1023 at(26, 9, 0)
1024 ],
1025 "Monday to Friday, never Saturday or Sunday"
1026 );
1027 assert_eq!(weekdays.next_after(at(24, 10, 0)).unwrap(), Some(at(26, 9, 0)));
1028 assert_eq!(fires(&cron("0 9 * * Mon-Fri", "UTC"), at(18, 12, 0), 6), {
1029 fires(&weekdays, at(18, 12, 0), 6)
1030 });
1031 }
1032
1033 #[test]
1034 fn zero_and_seven_are_sunday_and_six_is_saturday() {
1035 for sunday in ["0", "7", "Sun", "0,7"] {
1036 let spec = cron(&format!("0 9 * * {sunday}"), "UTC");
1037 assert_eq!(
1038 fires(&spec, at(23, 10, 0), 2),
1039 vec![at(25, 9, 0), Utc.with_ymd_and_hms(2026, 11, 1, 9, 0, 0).unwrap()],
1040 "{sunday}"
1041 );
1042 }
1043 let saturday = cron("0 9 * * 6", "UTC");
1044 assert_eq!(fires(&saturday, at(23, 10, 0), 2), vec![at(24, 9, 0), at(31, 9, 0)]);
1045 let weekend = cron("30 7 * * 6,0", "UTC");
1046 assert_eq!(
1047 fires(&weekend, at(23, 10, 0), 3),
1048 vec![at(24, 7, 30), at(25, 7, 30), at(31, 7, 30)]
1049 );
1050 let friday_to_sunday = cron("0 9 * * 5-7", "UTC");
1052 assert_eq!(
1053 fires(&friday_to_sunday, at(22, 10, 0), 4),
1054 vec![at(23, 9, 0), at(24, 9, 0), at(25, 9, 0), at(30, 9, 0)]
1055 );
1056 }
1057
1058 #[test]
1059 fn five_field_weekday_steps() {
1060 let odd = cron("0 9 * * 1-5/2", "UTC");
1062 assert_eq!(
1063 fires(&odd, at(25, 10, 0), 3),
1064 vec![at(26, 9, 0), at(28, 9, 0), at(30, 9, 0)]
1065 );
1066 let every_third = cron("0 9 * * */3", "UTC");
1068 assert_eq!(
1069 fires(&every_third, at(24, 10, 0), 3),
1070 vec![at(25, 9, 0), at(28, 9, 0), at(31, 9, 0)]
1071 );
1072 }
1073
1074 #[test]
1075 fn six_and_seven_fields_keep_the_crates_numbering() {
1076 let six = cron("0 0 9 * * 1-5", "UTC");
1078 assert_eq!(
1079 fires(&six, at(23, 10, 0), 5),
1080 vec![at(25, 9, 0), at(26, 9, 0), at(27, 9, 0), at(28, 9, 0), at(29, 9, 0)]
1081 );
1082 let seven = cron("0 0 9 * * 7 2026", "UTC");
1083 assert_eq!(seven.next_after(at(23, 10, 0)).unwrap(), Some(at(24, 9, 0)));
1084 }
1085
1086 #[test]
1087 fn bad_five_field_weekdays_are_refused() {
1088 for field in ["8", "5-1", "5L", "*/0", "MON#2", "1,", "Fri-Sun"] {
1089 let error =
1090 cron(&format!("0 9 * * {field}"), "UTC").next_after(at(15, 0, 0)).unwrap_err();
1091 assert_eq!(error.code, INVALID_SCHEDULE_CODE, "{field}");
1092 assert!(error.message.contains("day of the week"), "{field}: {}", error.message);
1093 }
1094 }
1095
1096 #[test]
1097 fn catch_up_and_fire_once() {
1098 let spec = cron("0 * * * *", "UTC");
1099 let due = at(15, 9, 0);
1100 let now = at(15, 12, 30);
1101 let catch_up =
1102 plan_fires(&spec, MissedFirePolicy::CatchUp(3), due, now, DEFAULT_MISFIRE_GRACE)
1103 .unwrap();
1104 assert_eq!(
1105 catch_up,
1106 FirePlan {
1107 fire_times: vec![at(15, 10, 0), at(15, 11, 0), at(15, 12, 0)],
1108 next_fire_at: Some(at(15, 13, 0))
1109 }
1110 );
1111 let all =
1112 plan_fires(&spec, MissedFirePolicy::CatchUp(100), due, now, DEFAULT_MISFIRE_GRACE)
1113 .unwrap();
1114 assert_eq!(
1115 all.fire_times,
1116 vec![at(15, 9, 0), at(15, 10, 0), at(15, 11, 0), at(15, 12, 0)]
1117 );
1118 let once =
1119 plan_fires(&spec, MissedFirePolicy::FireOnce, due, now, DEFAULT_MISFIRE_GRACE)
1120 .unwrap();
1121 assert_eq!(once.fire_times, vec![at(15, 12, 0)]);
1122 let skip =
1123 plan_fires(&spec, MissedFirePolicy::Skip, due, now, DEFAULT_MISFIRE_GRACE).unwrap();
1124 assert!(skip.fire_times.is_empty());
1125 let on_time =
1126 plan_fires(&spec, MissedFirePolicy::Skip, due, at(15, 9, 0), DEFAULT_MISFIRE_GRACE)
1127 .unwrap();
1128 assert_eq!(on_time.fire_times, vec![due]);
1129 }
1130
1131 #[test]
1132 fn time_zones_and_daylight_saving() {
1133 let spec = cron("0 9 * * *", "Europe/Berlin");
1135 assert_eq!(spec.next_after(at(24, 0, 0)).unwrap(), Some(at(24, 7, 0)));
1136 assert_eq!(spec.next_after(at(25, 0, 0)).unwrap(), Some(at(25, 8, 0)));
1137
1138 let repeated = cron("0 30 2 * * *", "Europe/Berlin");
1140 let first = Utc.with_ymd_and_hms(2026, 10, 25, 0, 30, 0).unwrap();
1141 assert_eq!(repeated.next_after(at(25, 0, 0)).unwrap(), Some(first));
1142 assert_eq!(
1143 repeated.next_after(first).unwrap(),
1144 Some(Utc.with_ymd_and_hms(2026, 10, 26, 1, 30, 0).unwrap())
1145 );
1146 let plan = plan_fires(
1147 &repeated,
1148 MissedFirePolicy::CatchUp(5),
1149 first,
1150 at(25, 12, 0),
1151 DEFAULT_MISFIRE_GRACE,
1152 )
1153 .unwrap();
1154 assert_eq!(plan.fire_times, vec![first]);
1155 }
1156
1157 #[test]
1158 fn bad_expressions_and_zones_are_refused() {
1159 assert_eq!(
1160 cron("not cron", "UTC").next_after(at(15, 0, 0)).unwrap_err().code,
1161 INVALID_SCHEDULE_CODE
1162 );
1163 assert_eq!(
1164 cron("* * * * *", "Mars/Olympus").next_after(at(15, 0, 0)).unwrap_err().code,
1165 INVALID_SCHEDULE_CODE
1166 );
1167 }
1168 }
1169
1170 mod jitter {
1171 use proptest::prelude::*;
1172
1173 use super::*;
1174
1175 #[test]
1176 fn a_fire_lands_before_the_next_occurrence() {
1177 let jitter = Jitter::new(90, Duration::from_secs(3600));
1178 assert_eq!(jitter.percent, Jitter::MAX_PERCENT, "clamped to half the gap");
1179 let at = at(15, 9, 0);
1180 let next = Some(at + chrono::Duration::minutes(10));
1181 assert_eq!(jitter.window(at, next), Duration::from_secs(300));
1182 for key in ["a", "b", "nightly", "report-17"] {
1183 assert!(jitter.offset(key, at, next) < Duration::from_secs(300));
1184 }
1185 assert_eq!(jitter.window(at, None), Duration::ZERO);
1186 assert_eq!(
1187 Jitter::new(0, Duration::from_secs(60)).offset("a", at, next),
1188 Duration::ZERO
1189 );
1190 }
1191
1192 #[test]
1193 fn the_default_caps_a_daily_schedule_at_nine_minutes() {
1194 let daily = ScheduleSpec::Cron { expr: "0 9 * * *".into(), timezone: "UTC".into() };
1195 let at = at(15, 9, 0);
1196 let jitter = Jitter::default();
1197 assert_eq!(jitter.window(at, daily.next_after(at).unwrap()), Jitter::DEFAULT_MAX);
1198 let every_minute = ScheduleSpec::Every(Duration::from_secs(60));
1199 assert_eq!(
1200 jitter.window(at, every_minute.next_after(at).unwrap()),
1201 Duration::from_secs(9),
1202 "15 percent of a minute"
1203 );
1204 }
1205
1206 #[test]
1207 fn schedules_and_salts_spread_apart() {
1208 let jitter = Jitter::new(50, Duration::from_secs(3600));
1209 let at = at(15, 9, 0);
1210 let next = Some(at + chrono::Duration::hours(2));
1211 let offsets: std::collections::BTreeSet<Duration> =
1212 (0..64).map(|n| jitter.offset(&format!("job-{n}"), at, next)).collect();
1213 assert!(offsets.len() > 60, "64 schedules take {} distinct offsets", offsets.len());
1214 let salted = jitter.salted("tenant-a");
1215 assert_ne!(salted.offset("job-1", at, next), jitter.offset("job-1", at, next));
1216 assert_eq!(salted, jitter.salted("tenant-a"), "a salt is deterministic");
1217 }
1218
1219 #[test]
1220 fn run_now_keeps_the_concurrency_key_and_leaves_the_schedule() {
1221 let run = NewRun::new("default", "ops", "system", "probe", serde_json::json!({}))
1222 .with_concurrency_key("cron:probe", crate::OnConflict::Reject);
1223 let schedule = Schedule::new(
1224 "probe",
1225 ScheduleSpec::Every(Duration::from_secs(60)),
1226 run,
1227 MissedFirePolicy::Skip,
1228 )
1229 .with_next_fire_at(at(15, 9, 0));
1230 let manual = schedule.run_now("r1");
1231 assert_eq!(manual.idempotency_key.as_deref(), Some("schedule:probe:manual:r1"));
1232 assert_eq!(manual.concurrency_key.as_deref(), Some("cron:probe"));
1233 assert_ne!(manual.idempotency_key, schedule.run_for(at(15, 9, 0)).idempotency_key);
1234 }
1235
1236 proptest! {
1237 #![proptest_config(ProptestConfig::with_cases(256))]
1238
1239 #[test]
1242 fn offsets_stay_inside_the_window(
1243 key in "[a-z0-9:-]{1,24}",
1244 percent in 0u8..=255,
1245 max_ms in 0u64..=86_400_000,
1246 gap_ms in 1i64..=7 * 86_400_000,
1247 seed in any::<u64>(),
1248 ) {
1249 let mut jitter = Jitter::new(percent, Duration::from_millis(max_ms));
1250 jitter.seed = seed;
1251 let at = at(15, 9, 0);
1252 let next = at + chrono::Duration::milliseconds(gap_ms);
1253 let window = jitter.window(at, Some(next));
1254 let offset = jitter.offset(&key, at, Some(next));
1255 prop_assert!(window <= Duration::from_millis(max_ms));
1256 prop_assert!(window.as_nanos() * 2 <= u128::from(gap_ms.unsigned_abs()) * 1_000_000);
1257 prop_assert!(offset <= window);
1258 prop_assert!(window.is_zero() || offset < window);
1259 prop_assert!(at + chrono::Duration::from_std(offset).unwrap() < next);
1260 prop_assert_eq!(offset, jitter.offset(&key, at, Some(next)));
1261 }
1262 }
1263 }
1264}