Skip to main content

adk_server/background/
scheduler.rs

1//! The durable scheduler: enqueues each schedule's fire times exactly once, from any
2//! number of replicas.
3//!
4//! Every replica runs the same loop over [`ScheduleStore::due`]:
5//!
6//! 1. [`plan_fires`] picks the fire times the schedule's [`MissedFirePolicy`] keeps.
7//! 2. Each fire time is enqueued with [`Schedule::run_for`], whose idempotency key is
8//!    `schedule:{id}:{fire time}`, so replicas that plan the same fire time create one run.
9//! 3. [`ScheduleStore::advance`] moves the schedule on by compare-and-swap on its
10//!    revision; a replica that loses the race drops its plan, and its enqueues were
11//!    no-ops.
12//!
13//! A replica that crashes between enqueue and advance leaves the schedule due; the next
14//! tick re-plans the same fire times, which enqueue nothing new. While the governance
15//! kill switch refuses work, nothing fires and nothing advances; once it is lifted the
16//! missed-fire policy decides which of the fire times that fell due during the freeze run.
17//!
18//! # Jitter
19//!
20//! With [`DurableScheduler::with_jitter`], each run is still enqueued at its fire time and
21//! keyed by it, but its `not_before` is the fire time plus the schedule's
22//! [`Jitter`] offset, so no worker claims it earlier. Planning, the idempotency key and the
23//! advance are unchanged, and the offset is under half the gap to the next fire time. A run
24//! waiting out its offset is a queued run like any other: a worker under a frozen kill
25//! switch claims nothing, and the run starts once the freeze lifts.
26//!
27//! [`MissedFirePolicy`]: adk_core::schedule::MissedFirePolicy
28
29use std::sync::Arc;
30use std::time::Duration;
31
32use adk_core::schedule::{DEFAULT_MISFIRE_GRACE, Jitter, Schedule, plan_fires};
33use adk_core::{Clock, DurableRunStore, Enqueued, GovernanceControl, ScheduleStore, SystemClock};
34
35/// What one scheduler tick did.
36#[derive(Debug, Clone, Default, PartialEq, Eq)]
37#[non_exhaustive]
38pub struct SchedulerTick {
39    /// Runs this tick created.
40    pub enqueued: usize,
41    /// Fire times whose run already existed (another replica enqueued it).
42    pub existing: usize,
43    /// Fire times refused by a schedule's concurrency key (`Skip` policy).
44    pub rejected: usize,
45    /// Schedules this tick advanced.
46    pub advanced: usize,
47    /// Schedules another replica advanced first.
48    pub lost_race: usize,
49    /// Whether the governance control refused the tick.
50    pub frozen: bool,
51}
52
53/// Enqueues due schedules into a [`DurableRunStore`]; run one per replica.
54///
55/// # Example
56///
57/// ```rust
58/// use std::sync::Arc;
59/// use std::time::Duration;
60/// use adk_core::{InMemoryRunStore, InMemoryScheduleStore, NewRun};
61/// use adk_core::schedule::{MissedFirePolicy, Schedule, ScheduleSpec, ScheduleStore};
62/// use adk_server::background::DurableScheduler;
63///
64/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
65/// let schedules = Arc::new(InMemoryScheduleStore::new());
66/// let runs = Arc::new(InMemoryRunStore::new());
67/// let now = chrono::Utc::now();
68/// schedules.upsert(
69///     Schedule::new(
70///         "probe",
71///         ScheduleSpec::Every(Duration::from_secs(60)),
72///         NewRun::new("default", "ops", "system", "probe", serde_json::json!({})),
73///         MissedFirePolicy::Skip,
74///     )
75///     .with_next_fire_at(now),
76/// ).await?;
77///
78/// let scheduler = DurableScheduler::new(schedules, runs);
79/// assert_eq!(scheduler.tick().await?.enqueued, 1);
80/// assert_eq!(scheduler.tick().await?.enqueued, 0, "advanced past the fire time");
81/// # Ok::<(), adk_core::AdkError>(())
82/// # }).unwrap();
83/// ```
84#[derive(Clone)]
85pub struct DurableScheduler {
86    schedules: Arc<dyn ScheduleStore>,
87    runs: Arc<dyn DurableRunStore>,
88    governance: Option<GovernanceControl>,
89    tick_interval: Duration,
90    batch: usize,
91    grace: Duration,
92    clock: Arc<dyn Clock>,
93    jitter: Option<Jitter>,
94}
95
96impl std::fmt::Debug for DurableScheduler {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        f.debug_struct("DurableScheduler")
99            .field("tick_interval", &self.tick_interval)
100            .field("batch", &self.batch)
101            .field("grace", &self.grace)
102            .field("jitter", &self.jitter)
103            .finish_non_exhaustive()
104    }
105}
106
107impl DurableScheduler {
108    /// A scheduler that ticks every second, handles up to 100 due schedules per tick,
109    /// and uses [`DEFAULT_MISFIRE_GRACE`].
110    pub fn new(schedules: Arc<dyn ScheduleStore>, runs: Arc<dyn DurableRunStore>) -> Self {
111        Self {
112            schedules,
113            runs,
114            governance: None,
115            tick_interval: Duration::from_secs(1),
116            batch: 100,
117            grace: DEFAULT_MISFIRE_GRACE,
118            clock: Arc::new(SystemClock),
119            jitter: None,
120        }
121    }
122
123    /// Fires nothing while `control` refuses work.
124    #[must_use]
125    pub fn with_governance(mut self, control: GovernanceControl) -> Self {
126        self.governance = Some(control);
127        self
128    }
129
130    /// Sets how often [`spawn`](Self::spawn) ticks.
131    #[must_use]
132    pub fn with_tick_interval(mut self, interval: Duration) -> Self {
133        self.tick_interval = interval;
134        self
135    }
136
137    /// Sets how many due schedules one tick handles.
138    #[must_use]
139    pub fn with_batch(mut self, batch: usize) -> Self {
140        self.batch = batch.max(1);
141        self
142    }
143
144    /// Sets how late an occurrence may fire under `MissedFirePolicy::Skip`.
145    #[must_use]
146    pub fn with_grace(mut self, grace: Duration) -> Self {
147        self.grace = grace;
148        self
149    }
150
151    /// Sets the clock that decides what is due.
152    #[must_use]
153    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
154        self.clock = clock;
155        self
156    }
157
158    /// Delays each fired run by its schedule's [`Jitter`] offset, keyed by the schedule id:
159    /// the run is enqueued at its fire time with `not_before` set that much later (see
160    /// [Jitter](self#jitter)). Off by default.
161    ///
162    /// # Example
163    ///
164    /// ```rust
165    /// use std::sync::Arc;
166    /// use std::time::Duration;
167    /// use adk_core::{InMemoryRunStore, InMemoryScheduleStore};
168    /// use adk_core::schedule::Jitter;
169    /// use adk_server::background::DurableScheduler;
170    ///
171    /// let scheduler = DurableScheduler::new(Arc::new(InMemoryScheduleStore::new()), Arc::new(InMemoryRunStore::new()))
172    ///     .with_jitter(Jitter::new(15, Duration::from_secs(9 * 60)));
173    /// assert_eq!(scheduler.jitter(), Some(Jitter::default()));
174    /// ```
175    #[must_use]
176    pub fn with_jitter(mut self, jitter: Jitter) -> Self {
177        self.jitter = Some(jitter);
178        self
179    }
180
181    /// The jitter fired runs are delayed by, if any.
182    pub fn jitter(&self) -> Option<Jitter> {
183        self.jitter
184    }
185
186    /// Enqueues the fire times of every due schedule and advances each one.
187    ///
188    /// # Errors
189    ///
190    /// Returns the schedule store's error from [`ScheduleStore::due`]. A failure on one
191    /// schedule is logged and leaves it due for the next tick.
192    pub async fn tick(&self) -> adk_core::Result<SchedulerTick> {
193        let mut tick = SchedulerTick::default();
194        if let Some(control) = &self.governance
195            && let Err(error) = control.check()
196        {
197            tracing::debug!(error = %error, "governance refuses work; no schedule fires");
198            tick.frozen = true;
199            return Ok(tick);
200        }
201        let now = self.clock.now();
202        for schedule in self.schedules.due(now, self.batch).await? {
203            if let Err(error) = self.fire(&schedule, now, &mut tick).await {
204                tracing::warn!(schedule.id = %schedule.id, error = %error, "could not fire schedule");
205            }
206        }
207        Ok(tick)
208    }
209
210    async fn fire(
211        &self,
212        schedule: &Schedule,
213        now: chrono::DateTime<chrono::Utc>,
214        tick: &mut SchedulerTick,
215    ) -> adk_core::Result<()> {
216        let Some(due_at) = schedule.next_fire_at else { return Ok(()) };
217        let plan = match plan_fires(&schedule.spec, schedule.missed, due_at, now, self.grace) {
218            Ok(plan) => plan,
219            Err(error) => {
220                // An unplannable schedule would be due on every tick; pause it instead.
221                tracing::error!(schedule.id = %schedule.id, error = %error, "schedule cannot be planned; pausing it");
222                self.schedules.set_paused(&schedule.id, true).await?;
223                return Ok(());
224            }
225        };
226        // Re-checked per schedule: a freeze that lands mid-tick stops the remaining firings.
227        if let Some(control) = &self.governance
228            && control.check().is_err()
229        {
230            tick.frozen = true;
231            return Ok(());
232        }
233        for fire_time in &plan.fire_times {
234            let mut run = schedule.run_for(*fire_time);
235            if let Some(jitter) = &self.jitter {
236                let offset = jitter.offset_in(&schedule.spec, &schedule.id, *fire_time);
237                if let Some(at) = chrono::Duration::from_std(offset)
238                    .ok()
239                    .filter(|offset| !offset.is_zero())
240                    .and_then(|offset| fire_time.checked_add_signed(offset))
241                {
242                    run.not_before = Some(at);
243                }
244            }
245            match self.runs.enqueue(run).await? {
246                Enqueued::Created(run) => {
247                    tick.enqueued += 1;
248                    tracing::info!(schedule.id = %schedule.id, run.id = %run.run_id, fire_time = %fire_time, "schedule fired");
249                }
250                Enqueued::Existing(_) => tick.existing += 1,
251                Enqueued::Rejected { blocking_run_id } => {
252                    tick.rejected += 1;
253                    tracing::info!(
254                        schedule.id = %schedule.id,
255                        fire_time = %fire_time,
256                        blocking.run_id = %blocking_run_id,
257                        "previous run still active; occurrence skipped"
258                    );
259                }
260            }
261        }
262        if self.schedules.advance(&schedule.id, schedule.revision, plan.next_fire_at).await? {
263            tick.advanced += 1;
264        } else {
265            tick.lost_race += 1;
266        }
267        Ok(())
268    }
269
270    /// Spawns the tick loop and returns its handle; abort the handle to stop it.
271    pub fn spawn(self) -> tokio::task::JoinHandle<()> {
272        tokio::spawn(async move {
273            let mut interval = tokio::time::interval(self.tick_interval);
274            interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
275            loop {
276                interval.tick().await;
277                if let Err(error) = self.tick().await {
278                    tracing::warn!(error = %error, "scheduler tick failed");
279                }
280            }
281        })
282    }
283}