adk_agent/ambient/cron_trigger.rs
1use std::str::FromStr;
2use std::sync::Arc;
3
4use adk_core::{AdkError, Result};
5use async_trait::async_trait;
6use chrono::{DateTime, Utc};
7use cron::Schedule;
8use futures::stream::BoxStream;
9use tokio::time::sleep;
10
11use super::event_source::{EventSource, TriggerEvent};
12use super::watermark::TickWatermark;
13
14/// Ticks a catch-up pass will replay before the remainder of the gap is discarded.
15const DEFAULT_MAX_CATCH_UP: usize = 64;
16
17/// What a [`CronTrigger`] does about ticks that came due while it was not watching.
18///
19/// A schedule can fall behind for three reasons: the process was not running, the host
20/// suspended, or the consumer took longer than the interval to accept the previous event. In
21/// every case the trigger resumes at the next future tick, so without a policy the elapsed ticks
22/// are dropped with no record that anything was skipped.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum MissedTickPolicy {
25 /// Discard elapsed ticks and wait for the next scheduled one.
26 ///
27 /// The default, and the behaviour of every release before this policy existed.
28 #[default]
29 Skip,
30 /// Emit one event covering the whole elapsed span, then resume.
31 ///
32 /// Suits sweeps where only the current state matters — a health check does not need to run
33 /// once per missed minute, it needs to run once, now.
34 CoalesceOne,
35 /// Emit one event per elapsed tick, oldest first, then resume.
36 ///
37 /// Suits schedules where each occurrence has its own work. Bounded by
38 /// [`CronTrigger::with_max_catch_up`].
39 All,
40}
41
42/// Emits trigger events on a cron schedule.
43///
44/// Uses the `cron` crate for expression parsing and next-tick calculation, which expects a
45/// six-field expression (seconds first).
46///
47/// # Missed ticks
48///
49/// By default the trigger resumes at the next future tick and elapsed ticks are discarded. Pair
50/// [`MissedTickPolicy`] with a [`TickWatermark`] to replay them; the watermark is what makes a
51/// gap visible across a process restart.
52///
53/// # Delivery contract
54///
55/// The watermark advances when the trigger *emits* a tick, not when the consumer finishes acting
56/// on it. A crash between emission and completion therefore drops that run rather than repeating
57/// it — at-most-once, not at-least-once. This keeps a consumer that stops polling from replaying
58/// the same gap on every restart. Consumers whose work must survive a mid-run crash should record
59/// their own completion state. When a configured watermark cannot be persisted, the stream stops
60/// before emitting the affected tick rather than violating this contract.
61///
62/// # Example
63///
64/// ```rust,ignore
65/// use std::sync::Arc;
66/// use adk_agent::ambient::{CronTrigger, FileTickWatermark, MissedTickPolicy};
67///
68/// // Fire every minute, and on restart run one catch-up sweep if ticks were missed.
69/// let trigger = CronTrigger::new("0 * * * * *")?
70/// .with_missed_tick_policy(MissedTickPolicy::CoalesceOne)
71/// .with_watermark(Arc::new(FileTickWatermark::new("/var/lib/my-agent/sweep.tick")));
72/// ```
73pub struct CronTrigger {
74 expression: String,
75 schedule: Schedule,
76 name: String,
77 missed_tick_policy: MissedTickPolicy,
78 watermark: Option<Arc<dyn TickWatermark>>,
79 max_catch_up: usize,
80}
81
82impl CronTrigger {
83 /// Create a new cron trigger from a cron expression.
84 ///
85 /// Returns an error if the expression is invalid.
86 ///
87 /// # Errors
88 ///
89 /// Returns `AdkError::Agent` with the parse error if the expression is invalid.
90 pub fn new(expression: &str) -> Result<Self> {
91 let schedule = Schedule::from_str(expression)
92 .map_err(|e| AdkError::agent(format!("invalid cron expression: {e}")))?;
93
94 Ok(Self {
95 expression: expression.to_string(),
96 schedule,
97 name: format!("cron:{expression}"),
98 missed_tick_policy: MissedTickPolicy::default(),
99 watermark: None,
100 max_catch_up: DEFAULT_MAX_CATCH_UP,
101 })
102 }
103
104 /// Sets what happens to ticks that came due while the trigger was not watching.
105 ///
106 /// Defaults to [`MissedTickPolicy::Skip`]. Without a [`TickWatermark`] this only covers gaps
107 /// within a single subscription, because nothing records where the schedule left off.
108 pub fn with_missed_tick_policy(mut self, policy: MissedTickPolicy) -> Self {
109 self.missed_tick_policy = policy;
110 self
111 }
112
113 /// Stores the most recent tick, so a restarted process can see which runs it missed.
114 ///
115 /// Has no effect under [`MissedTickPolicy::Skip`].
116 pub fn with_watermark(mut self, watermark: Arc<dyn TickWatermark>) -> Self {
117 self.watermark = Some(watermark);
118 self
119 }
120
121 /// Caps how many ticks one catch-up pass replays. Defaults to 64.
122 ///
123 /// A long outage on a frequent schedule can leave thousands of ticks outstanding; replaying
124 /// them all would flood the handler at subscribe time. Once the cap is reached the rest of
125 /// the gap is discarded, the durable cursor advances past it, and the trigger resumes at the
126 /// next future tick, logging how many ticks were dropped. A cap of zero is treated as one.
127 pub fn with_max_catch_up(mut self, max_catch_up: usize) -> Self {
128 self.max_catch_up = max_catch_up.max(1);
129 self
130 }
131
132 /// The configured missed-tick policy.
133 pub fn missed_tick_policy(&self) -> MissedTickPolicy {
134 self.missed_tick_policy
135 }
136}
137
138/// Ticks in `(cursor, now]`, capped so a long outage cannot enumerate an unbounded span.
139///
140/// Returns the ticks found and whether the cap truncated them.
141fn elapsed_ticks(
142 schedule: &Schedule,
143 cursor: DateTime<Utc>,
144 now: DateTime<Utc>,
145 cap: usize,
146) -> (Vec<DateTime<Utc>>, bool) {
147 let mut ticks = Vec::new();
148 let mut truncated = false;
149
150 for tick in schedule.after(&cursor).take_while(|tick| *tick <= now) {
151 if ticks.len() == cap {
152 truncated = true;
153 break;
154 }
155 ticks.push(tick);
156 }
157
158 (ticks, truncated)
159}
160
161#[async_trait]
162impl EventSource for CronTrigger {
163 fn name(&self) -> &str {
164 &self.name
165 }
166
167 async fn subscribe(&self) -> Result<BoxStream<'static, TriggerEvent>> {
168 let schedule = self.schedule.clone();
169 let source_name = self.name.clone();
170 let expression = self.expression.clone();
171 let policy = self.missed_tick_policy;
172 let watermark = self.watermark.clone();
173 let cap = self.max_catch_up;
174
175 // Where the schedule left off. A persisted watermark makes ticks missed while the process
176 // was down visible; without one, only drift inside this subscription is observable.
177 let restored = match (&watermark, policy) {
178 (Some(store), policy) if policy != MissedTickPolicy::Skip => store.read().await?,
179 _ => None,
180 };
181
182 let stream = async_stream::stream! {
183 let mut cursor = restored.unwrap_or_else(Utc::now);
184
185 loop {
186 // Account for everything already due before waiting on the next tick. Under
187 // `Skip` the span is abandoned deliberately; under the other policies it is
188 // replayed. Either way it is never silently unaccounted.
189 if policy != MissedTickPolicy::Skip {
190 let now = Utc::now();
191 let (missed, truncated) = elapsed_ticks(&schedule, cursor, now, cap);
192
193 if !missed.is_empty() {
194 let missed_count = missed.len();
195
196 if truncated {
197 tracing::warn!(
198 source = %source_name,
199 replayed = missed_count,
200 "catch-up cap reached; discarding the remainder of the missed span"
201 );
202 }
203
204 match policy {
205 MissedTickPolicy::Skip => unreachable!("guarded above"),
206 MissedTickPolicy::CoalesceOne => {
207 let scheduled_for = missed[missed_count - 1];
208 tracing::info!(
209 source = %source_name,
210 missed = missed_count,
211 "replaying missed ticks as one coalesced event"
212 );
213 // Persisted before the yield: `yield` suspends until the consumer
214 // polls again, so writing afterwards would leave the watermark a
215 // tick behind for as long as a consumer holds an event — and
216 // permanently behind if it drops the stream, replaying the same
217 // gap on every restart.
218 let accounted_through =
219 if truncated { now } else { scheduled_for };
220 if let Some(ref store) = watermark
221 && let Err(error) = store.write(accounted_through).await
222 {
223 tracing::error!(%error, "failed to persist tick watermark; stopping cron stream before emission");
224 return;
225 }
226 yield TriggerEvent {
227 source: source_name.clone(),
228 payload: serde_json::json!({
229 "expression": expression,
230 "tick": Utc::now().to_rfc3339(),
231 "scheduled_for": scheduled_for.to_rfc3339(),
232 "catch_up": true,
233 "missed_count": missed_count,
234 "missed_count_truncated": truncated,
235 }),
236 // A schedule has no caller.
237 principal: None,
238 };
239 }
240 MissedTickPolicy::All => {
241 for (index, scheduled_for) in missed.iter().enumerate() {
242 let accounted_through = if truncated && index + 1 == missed_count {
243 now
244 } else {
245 *scheduled_for
246 };
247 if let Some(ref store) = watermark
248 && let Err(error) = store.write(accounted_through).await
249 {
250 tracing::error!(%error, "failed to persist tick watermark; stopping cron stream before emission");
251 return;
252 }
253 yield TriggerEvent {
254 source: source_name.clone(),
255 payload: serde_json::json!({
256 "expression": expression,
257 "tick": Utc::now().to_rfc3339(),
258 "scheduled_for": scheduled_for.to_rfc3339(),
259 "catch_up": true,
260 }),
261 principal: None,
262 };
263 }
264 }
265 }
266 }
267
268 // Truncating abandons the rest of the gap, so resume from now rather than
269 // re-enumerating it on the next pass.
270 cursor = if truncated { now } else { missed.last().copied().unwrap_or(cursor) };
271 } else {
272 cursor = Utc::now();
273 }
274
275 let Some(next_tick) = schedule.after(&cursor).next() else {
276 // No more upcoming ticks — schedule is exhausted
277 break;
278 };
279
280 let duration = (next_tick - Utc::now()).to_std().unwrap_or_default();
281 sleep(duration).await;
282
283 cursor = next_tick;
284
285 if policy != MissedTickPolicy::Skip
286 && let Some(ref store) = watermark
287 && let Err(error) = store.write(next_tick).await
288 {
289 tracing::error!(%error, "failed to persist tick watermark; stopping cron stream before emission");
290 return;
291 }
292
293 yield TriggerEvent {
294 source: source_name.clone(),
295 payload: serde_json::json!({
296 "expression": expression,
297 "tick": Utc::now().to_rfc3339(),
298 "scheduled_for": next_tick.to_rfc3339(),
299 "catch_up": false,
300 }),
301 // A schedule has no caller.
302 principal: None,
303 };
304 }
305 };
306
307 Ok(Box::pin(stream))
308 }
309}
310
311impl std::fmt::Debug for CronTrigger {
312 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313 f.debug_struct("CronTrigger")
314 .field("expression", &self.expression)
315 .field("missed_tick_policy", &self.missed_tick_policy)
316 .field("watermark", &self.watermark.is_some())
317 .field("max_catch_up", &self.max_catch_up)
318 .finish()
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325 use chrono::TimeZone;
326
327 fn every_minute() -> Schedule {
328 Schedule::from_str("0 * * * * *").expect("valid expression")
329 }
330
331 #[test]
332 fn policy_defaults_to_skip() {
333 let trigger = CronTrigger::new("0 * * * * *").expect("valid expression");
334
335 assert_eq!(trigger.missed_tick_policy(), MissedTickPolicy::Skip);
336 }
337
338 #[test]
339 fn invalid_expressions_are_rejected() {
340 assert!(CronTrigger::new("not a cron expression").is_err());
341 }
342
343 #[test]
344 fn max_catch_up_of_zero_is_treated_as_one() {
345 let trigger =
346 CronTrigger::new("0 * * * * *").expect("valid expression").with_max_catch_up(0);
347
348 assert_eq!(trigger.max_catch_up, 1);
349 }
350
351 #[test]
352 fn elapsed_ticks_finds_every_tick_in_the_gap() {
353 let cursor = Utc.with_ymd_and_hms(2026, 8, 22, 10, 0, 0).unwrap();
354 let now = Utc.with_ymd_and_hms(2026, 8, 22, 10, 5, 0).unwrap();
355
356 let (ticks, truncated) = elapsed_ticks(&every_minute(), cursor, now, 64);
357
358 assert_eq!(ticks.len(), 5, "10:01 through 10:05 inclusive");
359 assert!(!truncated);
360 assert_eq!(ticks[0], Utc.with_ymd_and_hms(2026, 8, 22, 10, 1, 0).unwrap());
361 assert_eq!(ticks[4], now);
362 }
363
364 #[test]
365 fn elapsed_ticks_is_empty_when_no_tick_has_come_due() {
366 let cursor = Utc.with_ymd_and_hms(2026, 8, 22, 10, 0, 0).unwrap();
367 let now = Utc.with_ymd_and_hms(2026, 8, 22, 10, 0, 30).unwrap();
368
369 let (ticks, truncated) = elapsed_ticks(&every_minute(), cursor, now, 64);
370
371 assert!(ticks.is_empty());
372 assert!(!truncated);
373 }
374
375 #[test]
376 fn elapsed_ticks_reports_truncation_at_the_cap() {
377 let cursor = Utc.with_ymd_and_hms(2026, 8, 22, 10, 0, 0).unwrap();
378 let now = Utc.with_ymd_and_hms(2026, 8, 22, 20, 0, 0).unwrap();
379
380 let (ticks, truncated) = elapsed_ticks(&every_minute(), cursor, now, 10);
381
382 assert_eq!(ticks.len(), 10, "capped rather than replaying ten hours");
383 assert!(truncated);
384 }
385
386 #[test]
387 fn elapsed_ticks_excludes_the_cursor_itself() {
388 let cursor = Utc.with_ymd_and_hms(2026, 8, 22, 10, 0, 0).unwrap();
389 let now = Utc.with_ymd_and_hms(2026, 8, 22, 10, 1, 0).unwrap();
390
391 let (ticks, _) = elapsed_ticks(&every_minute(), cursor, now, 64);
392
393 assert_eq!(ticks, vec![now], "the cursor tick already fired");
394 }
395}