Skip to main content

adk_agent/ambient/
watermark.rs

1//! Durable tick watermarks for [`CronTrigger`](super::CronTrigger).
2//!
3//! A watermark records the most recent tick a schedule emitted. Without one a
4//! [`CronTrigger`](super::CronTrigger) has no memory across process restarts: on resubscribe it
5//! waits for the next future tick, and every tick that came due while the process was down is
6//! lost with no record that it was skipped. Supplying a watermark is what lets
7//! [`MissedTickPolicy`](crate::ambient::MissedTickPolicy) see that gap and act on it.
8
9use std::io::Write;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12use std::time::Duration;
13
14use adk_core::{AdkError, Result};
15use async_trait::async_trait;
16use chrono::{DateTime, Utc};
17
18/// Records the point through which a schedule has been accounted for, so a restarted process can
19/// tell which scheduled runs it missed.
20///
21/// # Example
22///
23/// ```rust,ignore
24/// use std::sync::Arc;
25/// use adk_agent::ambient::{CronTrigger, FileTickWatermark, MissedTickPolicy};
26///
27/// let watermark = Arc::new(FileTickWatermark::new("/var/lib/my-agent/sweep.tick"));
28/// let trigger = CronTrigger::new("0 */5 * * * *")?
29///     .with_missed_tick_policy(MissedTickPolicy::CoalesceOne)
30///     .with_watermark(watermark);
31/// ```
32#[async_trait]
33pub trait TickWatermark: Send + Sync {
34    /// Reads the most recent accounted-through cursor, or `None` when the schedule has never run.
35    async fn read(&self) -> Result<Option<DateTime<Utc>>>;
36
37    /// Records `cursor` as the point through which the schedule has been accounted for.
38    ///
39    /// The cursor is normally a scheduled tick. It can be a wall-clock instant when a bounded
40    /// catch-up intentionally discards the remainder of an older gap.
41    async fn write(&self, cursor: DateTime<Utc>) -> Result<()>;
42}
43
44/// A [`TickWatermark`] backed by a single file holding one RFC 3339 timestamp.
45///
46/// Writes go to a unique sibling temporary file, are synchronized, and atomically replace the
47/// destination, so a reader never observes a partial timestamp. Missing parent directories are
48/// created on first write. Writes through one watermark and its clones run one at a time, and
49/// the last one wins. On Windows, replacing the file while another process replaces it fails
50/// for a moment, so a write retries for up to [`FileTickWatermark::PUBLISH_RETRY`] before it
51/// reports the conflict.
52///
53/// # Example
54///
55/// ```rust,ignore
56/// use adk_agent::ambient::FileTickWatermark;
57///
58/// let watermark = FileTickWatermark::new("/var/lib/my-agent/sweep.tick");
59/// ```
60#[derive(Debug, Clone)]
61pub struct FileTickWatermark {
62    path: PathBuf,
63    // On Windows a replace of the file fails while another replace of it is in flight, so the
64    // writes through this watermark and its clones take turns.
65    writing: Arc<tokio::sync::Mutex<()>>,
66}
67
68impl FileTickWatermark {
69    /// How long a write keeps retrying on Windows while another process replaces the same file.
70    pub const PUBLISH_RETRY: Duration = Duration::from_secs(1);
71
72    /// Creates a watermark stored at `path`.
73    pub fn new(path: impl Into<PathBuf>) -> Self {
74        Self { path: path.into(), writing: Arc::new(tokio::sync::Mutex::new(())) }
75    }
76
77    /// The file backing this watermark.
78    pub fn path(&self) -> &Path {
79        &self.path
80    }
81}
82
83#[async_trait]
84impl TickWatermark for FileTickWatermark {
85    async fn read(&self) -> Result<Option<DateTime<Utc>>> {
86        let path = self.path.clone();
87
88        // tokio's `fs` feature is not enabled for this crate, and a watermark is a few bytes
89        // read at most once per subscribe, so the blocking pool is the cheaper dependency.
90        let raw = tokio::task::spawn_blocking(move || match std::fs::read_to_string(&path) {
91            Ok(contents) => Ok(Some(contents)),
92            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
93            Err(err) => Err(AdkError::agent(format!(
94                "failed to read tick watermark at {}: {err}",
95                path.display()
96            ))),
97        })
98        .await
99        .map_err(|err| AdkError::agent(format!("tick watermark read task failed: {err}")))??;
100
101        let Some(raw) = raw else {
102            return Ok(None);
103        };
104
105        let trimmed = raw.trim();
106        if trimmed.is_empty() {
107            return Ok(None);
108        }
109
110        let parsed = DateTime::parse_from_rfc3339(trimmed).map_err(|err| {
111            AdkError::agent(format!(
112                "tick watermark at {} is not an RFC 3339 timestamp: {err}",
113                self.path.display()
114            ))
115        })?;
116
117        Ok(Some(parsed.with_timezone(&Utc)))
118    }
119
120    async fn write(&self, tick: DateTime<Utc>) -> Result<()> {
121        let path = self.path.clone();
122        let encoded = tick.to_rfc3339();
123        let _turn = self.writing.lock().await;
124
125        tokio::task::spawn_blocking(move || {
126            if let Some(parent) = path.parent()
127                && !parent.as_os_str().is_empty()
128            {
129                std::fs::create_dir_all(parent).map_err(|err| {
130                    AdkError::agent(format!(
131                        "failed to create tick watermark directory {}: {err}",
132                        parent.display()
133                    ))
134                })?;
135            }
136
137            let parent = path
138                .parent()
139                .filter(|parent| !parent.as_os_str().is_empty())
140                .unwrap_or_else(|| Path::new("."));
141            let mut temporary = tempfile::NamedTempFile::new_in(parent).map_err(|err| {
142                AdkError::agent(format!(
143                    "failed to create a temporary tick watermark beside {}: {err}",
144                    path.display()
145                ))
146            })?;
147            temporary.write_all(encoded.as_bytes()).map_err(|err| {
148                AdkError::agent(format!(
149                    "failed to write tick watermark for {}: {err}",
150                    path.display()
151                ))
152            })?;
153            temporary.as_file().sync_all().map_err(|err| {
154                AdkError::agent(format!(
155                    "failed to synchronize tick watermark for {}: {err}",
156                    path.display()
157                ))
158            })?;
159            publish(temporary, &path)?;
160
161            #[cfg(unix)]
162            std::fs::File::open(parent).and_then(|directory| directory.sync_all()).map_err(
163                |err| {
164                    AdkError::agent(format!(
165                        "failed to synchronize tick watermark directory {}: {err}",
166                        parent.display()
167                    ))
168                },
169            )?;
170
171            Ok(())
172        })
173        .await
174        .map_err(|err| AdkError::agent(format!("tick watermark write task failed: {err}")))?
175    }
176}
177
178/// Replaces `path` with `temporary`. On Windows the replace fails with `PermissionDenied`, or
179/// a sharing violation, while another process replaces or holds the file, so it is retried
180/// with a doubling pause for up to [`FileTickWatermark::PUBLISH_RETRY`].
181fn publish(mut temporary: tempfile::NamedTempFile, path: &Path) -> Result<()> {
182    let started = std::time::Instant::now();
183    let mut pause = Duration::from_millis(10);
184    loop {
185        let error = match temporary.persist(path) {
186            Ok(_) => return Ok(()),
187            Err(error) => error,
188        };
189        // ERROR_SHARING_VIOLATION: another process has the file open without sharing it.
190        let held = cfg!(windows)
191            && (error.error.kind() == std::io::ErrorKind::PermissionDenied
192                || error.error.raw_os_error() == Some(32));
193        if held && started.elapsed() + pause <= FileTickWatermark::PUBLISH_RETRY {
194            std::thread::sleep(pause);
195            pause = (pause * 2).min(Duration::from_millis(200));
196            temporary = error.file;
197            continue;
198        }
199        let remedy = if held {
200            format!(
201                "; another process kept it for {:?}: give each schedule its own watermark file",
202                FileTickWatermark::PUBLISH_RETRY
203            )
204        } else {
205            String::new()
206        };
207        return Err(AdkError::agent(format!(
208            "failed to publish tick watermark to {}: {}{remedy}",
209            path.display(),
210            error.error
211        )));
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use chrono::TimeZone;
219    use std::sync::Arc;
220
221    #[tokio::test]
222    async fn read_returns_none_when_the_file_is_absent() {
223        let dir = tempfile::tempdir().expect("tempdir");
224        let watermark = FileTickWatermark::new(dir.path().join("missing.tick"));
225
226        assert_eq!(watermark.read().await.expect("read"), None);
227    }
228
229    #[tokio::test]
230    async fn write_then_read_round_trips_the_tick() {
231        let dir = tempfile::tempdir().expect("tempdir");
232        let watermark = FileTickWatermark::new(dir.path().join("sweep.tick"));
233        let tick = Utc.with_ymd_and_hms(2026, 8, 22, 13, 45, 0).unwrap();
234
235        watermark.write(tick).await.expect("write");
236
237        assert_eq!(watermark.read().await.expect("read"), Some(tick));
238    }
239
240    #[tokio::test]
241    async fn write_creates_missing_parent_directories() {
242        let dir = tempfile::tempdir().expect("tempdir");
243        let watermark = FileTickWatermark::new(dir.path().join("nested/deeper/sweep.tick"));
244        let tick = Utc.with_ymd_and_hms(2026, 1, 2, 3, 4, 5).unwrap();
245
246        watermark.write(tick).await.expect("write");
247
248        assert_eq!(watermark.read().await.expect("read"), Some(tick));
249    }
250
251    #[tokio::test]
252    async fn write_overwrites_a_previous_tick() {
253        let dir = tempfile::tempdir().expect("tempdir");
254        let watermark = FileTickWatermark::new(dir.path().join("sweep.tick"));
255        let first = Utc.with_ymd_and_hms(2026, 8, 22, 10, 0, 0).unwrap();
256        let second = Utc.with_ymd_and_hms(2026, 8, 22, 11, 0, 0).unwrap();
257
258        watermark.write(first).await.expect("first write");
259        watermark.write(second).await.expect("second write");
260
261        assert_eq!(watermark.read().await.expect("read"), Some(second));
262    }
263
264    #[tokio::test]
265    async fn concurrent_writes_use_independent_temporary_files() {
266        let dir = tempfile::tempdir().expect("tempdir");
267        let watermark = Arc::new(FileTickWatermark::new(dir.path().join("sweep.tick")));
268        let first = Utc.with_ymd_and_hms(2026, 8, 22, 10, 0, 0).unwrap();
269        let second = Utc.with_ymd_and_hms(2026, 8, 22, 11, 0, 0).unwrap();
270
271        let (first_result, second_result) =
272            tokio::join!(watermark.write(first), watermark.write(second));
273        first_result.expect("first write");
274        second_result.expect("second write");
275
276        let stored = watermark.read().await.expect("read").expect("stored");
277        assert!(stored == first || stored == second);
278    }
279
280    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
281    async fn many_concurrent_writes_through_clones_all_land() {
282        let dir = tempfile::tempdir().expect("tempdir");
283        let watermark = FileTickWatermark::new(dir.path().join("sweep.tick"));
284        let ticks: Vec<_> =
285            (0..16).map(|hour| Utc.with_ymd_and_hms(2026, 8, 22, hour, 0, 0).unwrap()).collect();
286
287        let writes = ticks.iter().map(|tick| {
288            let watermark = watermark.clone();
289            let tick = *tick;
290            tokio::spawn(async move { watermark.write(tick).await })
291        });
292        for write in futures::future::join_all(writes).await {
293            write.expect("write task").expect("write");
294        }
295
296        let stored = watermark.read().await.expect("read").expect("stored");
297        assert!(ticks.contains(&stored), "{stored}");
298    }
299
300    /// Another process holding the file without sharing it: the write waits it out.
301    #[cfg(windows)]
302    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
303    async fn a_write_waits_out_another_process_holding_the_file() {
304        use std::os::windows::fs::OpenOptionsExt as _;
305
306        let dir = tempfile::tempdir().expect("tempdir");
307        let path = dir.path().join("sweep.tick");
308        std::fs::write(&path, "2026-08-22T10:00:00+00:00").expect("seed");
309        let tick = Utc.with_ymd_and_hms(2026, 8, 22, 11, 0, 0).unwrap();
310
311        let held = std::fs::OpenOptions::new().read(true).share_mode(0).open(&path).expect("hold");
312        let release = std::thread::spawn(move || {
313            std::thread::sleep(Duration::from_millis(200));
314            drop(held);
315        });
316        FileTickWatermark::new(&path).write(tick).await.expect("write after the release");
317        release.join().unwrap();
318        assert_eq!(FileTickWatermark::new(&path).read().await.expect("read"), Some(tick));
319
320        // Held past the retry, the write fails and says why.
321        let _held = std::fs::OpenOptions::new().read(true).share_mode(0).open(&path).expect("hold");
322        let started = std::time::Instant::now();
323        let error = FileTickWatermark::new(&path).write(tick).await.unwrap_err();
324        assert!(started.elapsed() < FileTickWatermark::PUBLISH_RETRY * 3, "the retry is bounded");
325        assert!(error.to_string().contains("its own watermark file"), "{error}");
326    }
327
328    #[tokio::test]
329    async fn read_treats_an_empty_file_as_no_watermark() {
330        let dir = tempfile::tempdir().expect("tempdir");
331        let path = dir.path().join("empty.tick");
332        std::fs::write(&path, "   \n").expect("seed");
333        let watermark = FileTickWatermark::new(path);
334
335        assert_eq!(watermark.read().await.expect("read"), None);
336    }
337
338    #[tokio::test]
339    async fn read_rejects_a_corrupt_watermark() {
340        let dir = tempfile::tempdir().expect("tempdir");
341        let path = dir.path().join("corrupt.tick");
342        std::fs::write(&path, "not-a-timestamp").expect("seed");
343        let watermark = FileTickWatermark::new(path);
344
345        assert!(watermark.read().await.is_err());
346    }
347}