forge
Explore
Log in

Don't you dare go Hollow

watcher: Refactor tests to not use threads

Browse files at this commit

6d0505e684c9b93e03a8b4cc5a313c4dea365e54Ivan MolodetskikhParent: 8b4517a
Fixes flakiness, removes unnecessary waiting.
src/utils/watcher.rsmodified+96 -124
@@ -10,94 +10,73 @@ use smithay::reexports::calloop::channel::SyncSender;
1010
1111 use crate::niri::State;
1212
13+const POLLING_INTERVAL: Duration = Duration::from_millis(500);
14+
1315 pub struct Watcher {
1416 load_config: mpsc::Sender<()>,
1517 }
1618
19+struct WatcherInner {
20+ /// The paths we're watching.
21+ path: ConfigPath,
22+
23+ /// Last observed props of the watched file.
24+ ///
25+ /// Equality on this means the file did not change.
26+ ///
27+ /// We store the absolute path in addition to mtime to account for symlinked configs where the
28+ /// symlink target may change without mtime. This is common on nix where everything is a
29+ /// symlink to /nix/store, which keeps no mtime (= 1970-01-01).
30+ last_props: Option<(SystemTime, PathBuf)>,
31+}
32+
33+#[derive(Debug, PartialEq, Eq)]
34+enum CheckResult {
35+ Missing,
36+ Unchanged,
37+ Changed,
38+}
39+
1740 impl Watcher {
1841 pub fn new<T: Send + 'static>(
1942 path: ConfigPath,
20- process: impl FnMut(&ConfigPath) -> T + Send + 'static,
21- changed: SyncSender<T>,
22- ) -> Self {
23- let interval = Duration::from_millis(500);
24- Self::with_start_notification(path, process, changed, None, interval)
25- }
26-
27- pub fn with_start_notification<T: Send + 'static>(
28- config_path: ConfigPath,
2943 mut process: impl FnMut(&ConfigPath) -> T + Send + 'static,
3044 changed: SyncSender<T>,
31- started: Option<mpsc::SyncSender<()>>,
32- polling_interval: Duration,
3345 ) -> Self {
3446 let (load_config, load_config_rx) = mpsc::channel();
3547
3648 thread::Builder::new()
37- .name(format!("Filesystem Watcher for {config_path:?}"))
49+ .name(format!("Filesystem Watcher for {path:?}"))
3850 .spawn(move || {
39- // this "should" be as simple as storing the last seen mtime,
40- // and if the contents change without updating mtime, we ignore it.
41- //
42- // but that breaks if the config is a symlink, and its target
43- // changes but the new target and old target have identical mtimes.
44- // in which case we should *not* ignore it; this is an entirely different file.
45- //
46- // in practice, this edge case does not occur on systems other than nix.
47- // because, on nix, everything is a symlink to /nix/store
48- // and /nix/store keeps no mtime (= 1970-01-01)
49- // so, symlink targets change frequently when mtime doesn't.
50- //
51- // therefore, we must also store the canonical path, along with its mtime
52-
53- fn see_path(path: &Path) -> io::Result<(SystemTime, PathBuf)> {
54- let canon = path.canonicalize()?;
55- let mtime = canon.metadata()?.modified()?;
56- Ok((mtime, canon))
57- }
58-
59- fn see(config_path: &ConfigPath) -> io::Result<(SystemTime, PathBuf)> {
60- match config_path {
61- ConfigPath::Explicit(path) => see_path(path),
62- ConfigPath::Regular {
63- user_path,
64- system_path,
65- } => see_path(user_path).or_else(|_| see_path(system_path)),
66- }
67- }
68-
69- let mut last_props = see(&config_path).ok();
70-
71- if let Some(started) = started {
72- let _ = started.send(());
73- }
51+ let mut inner = WatcherInner::new(path);
7452
7553 loop {
76- let mut should_load = match load_config_rx.recv_timeout(polling_interval) {
54+ let mut should_load = match load_config_rx.recv_timeout(POLLING_INTERVAL) {
7755 Ok(()) => true,
7856 Err(mpsc::RecvTimeoutError::Disconnected) => break,
7957 Err(mpsc::RecvTimeoutError::Timeout) => false,
8058 };
8159
82- if let Ok(new_props) = see(&config_path) {
83- if last_props.as_ref() != Some(&new_props) {
84- last_props = Some(new_props);
60+ match inner.check() {
61+ CheckResult::Missing => continue,
62+ CheckResult::Unchanged => (),
63+ CheckResult::Changed => {
8564 trace!("config file changed");
8665 should_load = true;
8766 }
67+ }
8868
89- if should_load {
90- let rv = process(&config_path);
69+ if should_load {
70+ let rv = process(&inner.path);
9171
92- if let Err(err) = changed.send(rv) {
93- warn!("error sending change notification: {err:?}");
94- break;
95- }
72+ if let Err(err) = changed.send(rv) {
73+ warn!("error sending change notification: {err:?}");
74+ break;
9675 }
9776 }
9877 }
9978
100- debug!("exiting watcher thread for {config_path:?}");
79+ debug!("exiting watcher thread for {:?}", inner.path);
10180 })
10281 .unwrap();
10382
@@ -109,6 +88,42 @@ impl Watcher {
10988 }
11089 }
11190
91+fn see_path(path: &Path) -> io::Result<(SystemTime, PathBuf)> {
92+ let canon = path.canonicalize()?;
93+ let mtime = canon.metadata()?.modified()?;
94+ Ok((mtime, canon))
95+}
96+
97+fn see(config_path: &ConfigPath) -> io::Result<(SystemTime, PathBuf)> {
98+ match config_path {
99+ ConfigPath::Explicit(path) => see_path(path),
100+ ConfigPath::Regular {
101+ user_path,
102+ system_path,
103+ } => see_path(user_path).or_else(|_| see_path(system_path)),
104+ }
105+}
106+
107+impl WatcherInner {
108+ pub fn new(path: ConfigPath) -> Self {
109+ let last_props = see(&path).ok();
110+ Self { path, last_props }
111+ }
112+
113+ pub fn check(&mut self) -> CheckResult {
114+ if let Ok(new_props) = see(&self.path) {
115+ if self.last_props.as_ref() != Some(&new_props) {
116+ self.last_props = Some(new_props);
117+ CheckResult::Changed
118+ } else {
119+ CheckResult::Unchanged
120+ }
121+ } else {
122+ CheckResult::Missing
123+ }
124+ }
125+}
126+
112127 pub fn setup(state: &mut State, config_path: &ConfigPath) {
113128 // Parsing the config actually takes > 20 ms on my beefy machine, so let's do it on the
114129 // watcher thread.
@@ -137,8 +152,6 @@ mod tests {
137152 use std::fs::{self, File, FileTimes};
138153 use std::io::Write;
139154
140- use calloop::channel::{sync_channel, Event};
141- use calloop::EventLoop;
142155 use xshell::{cmd, Shell, TempDir};
143156
144157 use super::*;
@@ -234,29 +247,9 @@ mod tests {
234247 sh, config_path, ..
235248 } = self;
236249
237- let (tx, rx) = sync_channel(1);
238- let (started_tx, started_rx) = mpsc::sync_channel(1);
239-
240- let _watcher = Watcher::with_start_notification(
241- config_path,
242- |config_path| canon(config_path).clone(),
243- tx,
244- Some(started_tx),
245- Duration::from_millis(100),
246- );
247-
248- started_rx.recv()?;
249-
250- let event_loop = EventLoop::try_new()?;
251- event_loop
252- .handle()
253- .insert_source(rx, |event, (), latest_path| {
254- if let Event::Msg(path) = event {
255- *latest_path = Some(path);
256- }
257- })?;
258-
259- let mut test = TestUtil { event_loop };
250+ let mut test = TestUtil {
251+ watcher: WatcherInner::new(config_path),
252+ };
260253
261254 // don't trigger before we start
262255 test.assert_unchanged();
@@ -272,22 +265,23 @@ mod tests {
272265 }
273266 }
274267
275- struct TestUtil<'a> {
276- event_loop: EventLoop<'a, Option<PathBuf>>,
268+ struct TestUtil {
269+ watcher: WatcherInner,
277270 }
278271
279- impl<'a> TestUtil<'a> {
272+ impl TestUtil {
273+ // Ensures that mtime is different between writes in the tests.
280274 fn pass_time(&self) {
281275 thread::sleep(Duration::from_millis(50));
282276 }
283277
284278 fn assert_unchanged(&mut self) {
285- let mut new_path = None;
286- self.event_loop
287- .dispatch(Duration::from_millis(150), &mut new_path)
288- .unwrap();
289- assert_eq!(
290- new_path, None,
279+ let res = self.watcher.check();
280+
281+ // This may be Missing or Unchanged, both are fine.
282+ assert_ne!(
283+ res,
284+ CheckResult::Changed,
291285 "watcher should not have noticed any changes"
292286 );
293287
@@ -295,29 +289,22 @@ mod tests {
295289 }
296290
297291 fn assert_changed_to(&mut self, expected: &str) {
298- let mut new_path = None;
299- self.event_loop
300- .dispatch(Duration::from_millis(150), &mut new_path)
301- .unwrap();
302- let Some(new_path) = new_path else {
303- panic!("watcher should have noticed a change, but it didn't");
304- };
305- let actual = fs::read_to_string(&new_path).unwrap();
306- assert_eq!(actual, expected, "watcher gave the wrong file");
292+ let res = self.watcher.check();
293+ assert_eq!(
294+ res,
295+ CheckResult::Changed,
296+ "watcher should have noticed a change, but it didn't"
297+ );
298+
299+ let new_path = canon(&self.watcher.path);
300+ let actual = fs::read_to_string(new_path).unwrap();
301+ assert_eq!(actual, expected, "wrong file contents");
307302
308303 self.pass_time();
309304 }
310305 }
311306
312- // All tests are currently ignored because they are flaky. Presumably, this is because the
313- // watcher thread sleeps can align with test thread runs in such a way that the watcher wakes
314- // up in the middle between operations and ends up reporting a change one more time than
315- // expected, leading to test failures on the final unchanged check.
316- //
317- // https://github.com/YaLTeR/niri/issues/2226
318-
319307 #[test]
320- #[ignore]
321308 fn change_file() -> Result {
322309 TestPath::Explicit("niri/config.kdl")
323310 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
@@ -331,7 +318,6 @@ mod tests {
331318 }
332319
333320 #[test]
334- #[ignore]
335321 fn overwrite_but_dont_change_file() -> Result {
336322 TestPath::Explicit("niri/config.kdl")
337323 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
@@ -345,7 +331,6 @@ mod tests {
345331 }
346332
347333 #[test]
348- #[ignore]
349334 fn touch_file() -> Result {
350335 TestPath::Explicit("niri/config.kdl")
351336 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
@@ -359,7 +344,6 @@ mod tests {
359344 }
360345
361346 #[test]
362- #[ignore]
363347 fn create_file() -> Result {
364348 TestPath::Explicit("niri/config.kdl")
365349 .setup(|sh| sh.create_dir("niri"))
@@ -373,7 +357,6 @@ mod tests {
373357 }
374358
375359 #[test]
376- #[ignore]
377360 fn create_dir_and_file() -> Result {
378361 TestPath::Explicit("niri/config.kdl")
379362 .without_setup()
@@ -386,7 +369,6 @@ mod tests {
386369 }
387370
388371 #[test]
389- #[ignore]
390372 fn change_linked_file() -> Result {
391373 TestPath::Explicit("niri/config.kdl")
392374 .setup(|sh| {
@@ -403,7 +385,6 @@ mod tests {
403385 }
404386
405387 #[test]
406- #[ignore]
407388 fn change_file_in_linked_dir() -> Result {
408389 TestPath::Explicit("niri/config.kdl")
409390 .setup(|sh| {
@@ -420,7 +401,6 @@ mod tests {
420401 }
421402
422403 #[test]
423- #[ignore]
424404 fn remove_file() -> Result {
425405 TestPath::Explicit("niri/config.kdl")
426406 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
@@ -434,7 +414,6 @@ mod tests {
434414 }
435415
436416 #[test]
437- #[ignore]
438417 fn remove_dir() -> Result {
439418 TestPath::Explicit("niri/config.kdl")
440419 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
@@ -448,7 +427,6 @@ mod tests {
448427 }
449428
450429 #[test]
451- #[ignore]
452430 fn recreate_file() -> Result {
453431 TestPath::Explicit("niri/config.kdl")
454432 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
@@ -463,7 +441,6 @@ mod tests {
463441 }
464442
465443 #[test]
466- #[ignore]
467444 fn recreate_dir() -> Result {
468445 TestPath::Explicit("niri/config.kdl")
469446 .setup(|sh| {
@@ -481,7 +458,6 @@ mod tests {
481458 }
482459
483460 #[test]
484- #[ignore]
485461 fn swap_dir() -> Result {
486462 TestPath::Explicit("niri/config.kdl")
487463 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
@@ -497,7 +473,6 @@ mod tests {
497473 }
498474
499475 #[test]
500- #[ignore]
501476 fn swap_dir_link() -> Result {
502477 TestPath::Explicit("niri/config.kdl")
503478 .setup(|sh| {
@@ -530,7 +505,6 @@ mod tests {
530505 }
531506
532507 #[test]
533- #[ignore]
534508 fn swap_just_link() -> Result {
535509 TestPath::Explicit("niri/config.kdl")
536510 .setup_any(|sh| {
@@ -555,7 +529,6 @@ mod tests {
555529 }
556530
557531 #[test]
558- #[ignore]
559532 fn swap_many_regular() -> Result {
560533 TestPath::Regular {
561534 user_path: "user-niri/config.kdl",
@@ -590,7 +563,6 @@ mod tests {
590563 }
591564
592565 #[test]
593- #[ignore]
594566 fn swap_many_links_regular_like_nix() -> Result {
595567 TestPath::Regular {
596568 user_path: "user-niri/config.kdl",