Skip to main content

schedr_agent/
watch.rs

1//! Change detection for DAG roots: polling, the settle time, and the content hash.
2//!
3//! The agent scans each root on every poll. A changed scan isn't hashed at once: the root must
4//! stay unchanged for the settle time, so half-written files are never parsed. Only a new
5//! content hash is reported; a scan that changed with the same contents (e.g. files touched)
6//! isn't (see archive/PROJECT.md, Code versions and change detection). The first scan after start
7//! settles too.
8
9use std::path::{Path, PathBuf};
10use std::time::{Duration, Instant};
11
12use crate::scan::{Captured, ScanError, Snapshot, capture, remove_capture, scan};
13
14#[cfg(test)]
15mod tests;
16
17/// What a [`ChangeDetector`] decided about a scan.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Observation {
20    /// The same as the last settled scan.
21    Unchanged,
22    /// Changed, and not yet unchanged for the settle time: look again after this long.
23    Settling(Duration),
24    /// Unchanged for the settle time: hash it.
25    Settled(Snapshot),
26}
27
28/// Decides when a changed root has settled.
29#[derive(Debug, Clone)]
30pub struct ChangeDetector {
31    settle: Duration,
32    settled: Option<Snapshot>,
33    pending: Option<(Snapshot, Instant)>,
34}
35
36impl ChangeDetector {
37    /// A detector with the given settle time and no scan seen yet.
38    #[must_use]
39    pub const fn new(settle: Duration) -> Self {
40        Self {
41            settle,
42            settled: None,
43            pending: None,
44        }
45    }
46
47    /// Takes a scan made at `now`.
48    pub fn observe(&mut self, now: Instant, snapshot: Snapshot) -> Observation {
49        if self.settled.as_ref() == Some(&snapshot) {
50            self.pending = None;
51            return Observation::Unchanged;
52        }
53        let since = match &self.pending {
54            Some((pending, since)) if *pending == snapshot => *since,
55            _ => now,
56        };
57        let waited = now.saturating_duration_since(since);
58        if waited >= self.settle {
59            self.pending = None;
60            Observation::Settled(snapshot)
61        } else {
62            self.pending = Some((snapshot, since));
63            Observation::Settling(self.settle.saturating_sub(waited))
64        }
65    }
66
67    /// Records a settled scan as the current one (after it was hashed).
68    pub fn accept(&mut self, snapshot: Snapshot) {
69        self.settled = Some(snapshot);
70    }
71}
72
73/// The result of polling a root.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum Poll {
76    /// Nothing new to report.
77    Unchanged,
78    /// The root is changing: poll again after this long.
79    Settling(Duration),
80    /// The root has a new content hash.
81    Changed {
82        /// The new content hash.
83        hash: String,
84        /// The scan it was computed from (its `.py` files are the ones to parse).
85        snapshot: Snapshot,
86    },
87}
88
89/// Watches one root: scans it, waits for it to settle and copies and hashes it.
90#[derive(Debug, Clone)]
91pub struct RootWatcher {
92    dir: PathBuf,
93    store: PathBuf,
94    settle: Duration,
95    detector: ChangeDetector,
96    code: Option<Captured>,
97    snapshot: Option<Snapshot>,
98}
99
100impl RootWatcher {
101    /// A watcher for the root at `dir`, its code copied into `store` (decision 102), with no
102    /// hash yet.
103    #[must_use]
104    pub fn new(dir: impl Into<PathBuf>, store: impl Into<PathBuf>, settle: Duration) -> Self {
105        Self {
106            dir: dir.into(),
107            store: store.into(),
108            settle,
109            detector: ChangeDetector::new(settle),
110            code: None,
111            snapshot: None,
112        }
113    }
114
115    /// The root's directory as configured.
116    #[must_use]
117    pub fn dir(&self) -> &Path {
118        &self.dir
119    }
120
121    /// Where its code is copied.
122    #[must_use]
123    pub fn store(&self) -> &Path {
124        &self.store
125    }
126
127    /// The last reported content hash.
128    #[must_use]
129    pub fn hash(&self) -> Option<&str> {
130        self.code.as_ref().map(|code| code.hash.as_str())
131    }
132
133    /// The copy of the code the last reported hash is of: what parse jobs and tasks import.
134    #[must_use]
135    pub fn code_dir(&self) -> Option<&Path> {
136        self.code.as_ref().map(|code| code.dir.as_path())
137    }
138
139    /// The scan the last reported hash was computed from (its `.py` files are what a parse
140    /// job for that hash imports).
141    #[must_use]
142    pub const fn snapshot(&self) -> Option<&Snapshot> {
143        self.snapshot.as_ref()
144    }
145
146    /// Scans the root at `now`; when it has settled, copies and hashes it and checks that it
147    /// didn't change meanwhile.
148    ///
149    /// # Errors
150    ///
151    /// [`ScanError`] if the root can't be scanned, a file can't be read or the copy can't be
152    /// written; the next poll tries again.
153    pub fn poll(&mut self, now: Instant) -> Result<Poll, ScanError> {
154        let snapshot = match self.detector.observe(now, scan(&self.dir)?) {
155            Observation::Unchanged => return Ok(Poll::Unchanged),
156            Observation::Settling(wait) => return Ok(Poll::Settling(wait)),
157            Observation::Settled(snapshot) => snapshot,
158        };
159        let captured = capture(&snapshot, &self.store)?;
160        // Changed while copied (or gone): a copy made for it is of no use, never reported.
161        let drop_fresh = || {
162            if captured.fresh
163                && let Err(error) = remove_capture(&captured.dir)
164            {
165                tracing::warn!(dir = %captured.dir.display(), %error, "can't remove a copy of DAG code");
166            }
167        };
168        let after = match scan(&self.dir) {
169            Ok(after) => after,
170            Err(error) => {
171                drop_fresh();
172                return Err(error);
173            }
174        };
175        if after != snapshot {
176            drop_fresh();
177            self.detector.observe(now, after);
178            return Ok(Poll::Settling(self.settle));
179        }
180        self.detector.accept(snapshot.clone());
181        if self.hash() == Some(captured.hash.as_str()) {
182            return Ok(Poll::Unchanged);
183        }
184        let hash = captured.hash.clone();
185        self.code = Some(captured);
186        self.snapshot = Some(snapshot.clone());
187        Ok(Poll::Changed { hash, snapshot })
188    }
189}