forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB055a94dIvan Molodetskikh1 year ago2247 commits

watcher.rs602 lines, 18.4 KiBHistoryRawDownload
1//! File modification watcher.
2
3use std::path::{Path, PathBuf};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{mpsc, Arc};
6use std::time::{Duration, SystemTime};
7use std::{io, thread};
8
9use niri_config::ConfigPath;
10use smithay::reexports::calloop::channel::SyncSender;
11
12pub struct Watcher {
13 should_stop: Arc<AtomicBool>,
14}
15
16impl Drop for Watcher {
17 fn drop(&mut self) {
18 self.should_stop.store(true, Ordering::SeqCst);
19 }
20}
21
22impl Watcher {
23 pub fn new<T: Send + 'static>(
24 path: ConfigPath,
25 process: impl FnMut(&ConfigPath) -> T + Send + 'static,
26 changed: SyncSender<T>,
27 ) -> Self {
28 let interval = Duration::from_millis(500);
29 Self::with_start_notification(path, process, changed, None, interval)
30 }
31
32 pub fn with_start_notification<T: Send + 'static>(
33 config_path: ConfigPath,
34 mut process: impl FnMut(&ConfigPath) -> T + Send + 'static,
35 changed: SyncSender<T>,
36 started: Option<mpsc::SyncSender<()>>,
37 polling_interval: Duration,
38 ) -> Self {
39 let should_stop = Arc::new(AtomicBool::new(false));
40
41 {
42 let should_stop = should_stop.clone();
43 thread::Builder::new()
44 .name(format!("Filesystem Watcher for {config_path:?}"))
45 .spawn(move || {
46 // this "should" be as simple as storing the last seen mtime,
47 // and if the contents change without updating mtime, we ignore it.
48 //
49 // but that breaks if the config is a symlink, and its target
50 // changes but the new target and old target have identical mtimes.
51 // in which case we should *not* ignore it; this is an entirely different file.
52 //
53 // in practice, this edge case does not occur on systems other than nix.
54 // because, on nix, everything is a symlink to /nix/store
55 // and /nix/store keeps no mtime (= 1970-01-01)
56 // so, symlink targets change frequently when mtime doesn't.
57 //
58 // therefore, we must also store the canonical path, along with its mtime
59
60 fn see_path(path: &Path) -> io::Result<(SystemTime, PathBuf)> {
61 let canon = path.canonicalize()?;
62 let mtime = canon.metadata()?.modified()?;
63 Ok((mtime, canon))
64 }
65
66 fn see(config_path: &ConfigPath) -> io::Result<(SystemTime, PathBuf)> {
67 match config_path {
68 ConfigPath::Explicit(path) => see_path(path),
69 ConfigPath::Regular {
70 user_path,
71 system_path,
72 } => see_path(user_path).or_else(|_| see_path(system_path)),
73 }
74 }
75
76 let mut last_props = see(&config_path).ok();
77
78 if let Some(started) = started {
79 let _ = started.send(());
80 }
81
82 loop {
83 thread::sleep(polling_interval);
84
85 if should_stop.load(Ordering::SeqCst) {
86 break;
87 }
88
89 if let Ok(new_props) = see(&config_path) {
90 if last_props.as_ref() != Some(&new_props) {
91 trace!("config file changed");
92
93 let rv = process(&config_path);
94
95 if let Err(err) = changed.send(rv) {
96 warn!("error sending change notification: {err:?}");
97 break;
98 }
99
100 last_props = Some(new_props);
101 }
102 }
103 }
104
105 debug!("exiting watcher thread for {config_path:?}");
106 })
107 .unwrap();
108 }
109
110 Self { should_stop }
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use std::error::Error;
117 use std::fs::{self, File, FileTimes};
118 use std::io::Write;
119
120 use calloop::channel::{sync_channel, Event};
121 use calloop::EventLoop;
122 use xshell::{cmd, Shell, TempDir};
123
124 use super::*;
125
126 type Result<T = (), E = Box<dyn Error>> = std::result::Result<T, E>;
127
128 fn canon(config_path: &ConfigPath) -> &PathBuf {
129 match config_path {
130 ConfigPath::Explicit(path) => path,
131 ConfigPath::Regular {
132 user_path,
133 system_path,
134 } => {
135 if user_path.exists() {
136 user_path
137 } else {
138 system_path
139 }
140 }
141 }
142 }
143
144 enum TestPath<P> {
145 Explicit(P),
146 Regular { user_path: P, system_path: P },
147 }
148
149 impl<P: AsRef<Path>> TestPath<P> {
150 fn setup<Discard>(
151 self,
152 setup: impl FnOnce(&Shell) -> xshell::Result<Discard>,
153 ) -> TestSetup {
154 self.setup_any(|sh| {
155 _ = setup(sh)?;
156 Ok(())
157 })
158 }
159
160 fn without_setup(self) -> TestSetup {
161 self.setup_any(|_| Ok(())).assert_initial_not_exists()
162 }
163
164 fn setup_any(self, setup: impl FnOnce(&Shell) -> Result) -> TestSetup {
165 let sh = Shell::new().unwrap();
166 let temp_dir = sh.create_temp_dir().unwrap();
167 sh.change_dir(temp_dir.path());
168
169 let dir = sh.current_dir();
170 let config_path = match self {
171 TestPath::Explicit(path) => ConfigPath::Explicit(dir.join(path)),
172 TestPath::Regular {
173 user_path,
174 system_path,
175 } => ConfigPath::Regular {
176 user_path: dir.join(user_path),
177 system_path: dir.join(system_path),
178 },
179 };
180
181 setup(&sh).unwrap();
182
183 TestSetup {
184 sh,
185 config_path,
186 _temp_dir: temp_dir,
187 }
188 }
189 }
190
191 struct TestSetup {
192 sh: Shell,
193 config_path: ConfigPath,
194 _temp_dir: TempDir,
195 }
196
197 impl TestSetup {
198 fn assert_initial_not_exists(self) -> Self {
199 let canon = canon(&self.config_path);
200 assert!(!canon.exists(), "initial should not exist");
201 self
202 }
203
204 fn assert_initial(self, expected: &str) -> Self {
205 let canon = canon(&self.config_path);
206 assert!(canon.exists(), "initial should exist at {canon:?}");
207 let actual = fs::read_to_string(canon).unwrap();
208 assert_eq!(actual, expected, "initial file contents do not match");
209 self
210 }
211
212 fn run(self, body: impl FnOnce(&Shell, &mut TestUtil) -> Result) -> Result {
213 let TestSetup {
214 sh, config_path, ..
215 } = self;
216
217 let (tx, rx) = sync_channel(1);
218 let (started_tx, started_rx) = mpsc::sync_channel(1);
219
220 let _watcher = Watcher::with_start_notification(
221 config_path,
222 |config_path| canon(config_path).clone(),
223 tx,
224 Some(started_tx),
225 Duration::from_millis(100),
226 );
227
228 started_rx.recv()?;
229
230 let event_loop = EventLoop::try_new()?;
231 event_loop
232 .handle()
233 .insert_source(rx, |event, (), latest_path| {
234 if let Event::Msg(path) = event {
235 *latest_path = Some(path);
236 }
237 })?;
238
239 let mut test = TestUtil { event_loop };
240
241 // don't trigger before we start
242 test.assert_unchanged();
243 // pass_time() inside assert_unchanged() ensures that mtime
244 // isn't the same as the initial time
245
246 body(&sh, &mut test)?;
247
248 // nothing should trigger after the test runs
249 test.assert_unchanged();
250
251 Ok(())
252 }
253 }
254
255 struct TestUtil<'a> {
256 event_loop: EventLoop<'a, Option<PathBuf>>,
257 }
258
259 impl<'a> TestUtil<'a> {
260 fn pass_time(&self) {
261 thread::sleep(Duration::from_millis(50));
262 }
263
264 fn assert_unchanged(&mut self) {
265 let mut new_path = None;
266 self.event_loop
267 .dispatch(Duration::from_millis(150), &mut new_path)
268 .unwrap();
269 assert_eq!(
270 new_path, None,
271 "watcher should not have noticed any changes"
272 );
273
274 self.pass_time();
275 }
276
277 fn assert_changed_to(&mut self, expected: &str) {
278 let mut new_path = None;
279 self.event_loop
280 .dispatch(Duration::from_millis(150), &mut new_path)
281 .unwrap();
282 let Some(new_path) = new_path else {
283 panic!("watcher should have noticed a change, but it didn't");
284 };
285 let actual = fs::read_to_string(&new_path).unwrap();
286 assert_eq!(actual, expected, "watcher gave the wrong file");
287
288 self.pass_time();
289 }
290 }
291
292 #[test]
293 fn change_file() -> Result {
294 TestPath::Explicit("niri/config.kdl")
295 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
296 .assert_initial("a")
297 .run(|sh, test| {
298 sh.write_file("niri/config.kdl", "b")?;
299 test.assert_changed_to("b");
300
301 Ok(())
302 })
303 }
304
305 #[test]
306 fn overwrite_but_dont_change_file() -> Result {
307 TestPath::Explicit("niri/config.kdl")
308 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
309 .assert_initial("a")
310 .run(|sh, test| {
311 sh.write_file("niri/config.kdl", "a")?;
312 test.assert_changed_to("a");
313
314 Ok(())
315 })
316 }
317
318 #[test]
319 fn touch_file() -> Result {
320 TestPath::Explicit("niri/config.kdl")
321 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
322 .assert_initial("a")
323 .run(|sh, test| {
324 cmd!(sh, "touch niri/config.kdl").run()?;
325 test.assert_changed_to("a");
326
327 Ok(())
328 })
329 }
330
331 #[test]
332 fn create_file() -> Result {
333 TestPath::Explicit("niri/config.kdl")
334 .setup(|sh| sh.create_dir("niri"))
335 .assert_initial_not_exists()
336 .run(|sh, test| {
337 sh.write_file("niri/config.kdl", "a")?;
338 test.assert_changed_to("a");
339
340 Ok(())
341 })
342 }
343
344 #[test]
345 fn create_dir_and_file() -> Result {
346 TestPath::Explicit("niri/config.kdl")
347 .without_setup()
348 .run(|sh, test| {
349 sh.write_file("niri/config.kdl", "a")?;
350 test.assert_changed_to("a");
351
352 Ok(())
353 })
354 }
355
356 #[test]
357 fn change_linked_file() -> Result {
358 TestPath::Explicit("niri/config.kdl")
359 .setup(|sh| {
360 sh.write_file("niri/config2.kdl", "a")?;
361 cmd!(sh, "ln -sf config2.kdl niri/config.kdl").run()
362 })
363 .assert_initial("a")
364 .run(|sh, test| {
365 sh.write_file("niri/config2.kdl", "b")?;
366 test.assert_changed_to("b");
367
368 Ok(())
369 })
370 }
371
372 #[test]
373 fn change_file_in_linked_dir() -> Result {
374 TestPath::Explicit("niri/config.kdl")
375 .setup(|sh| {
376 sh.write_file("niri2/config.kdl", "a")?;
377 cmd!(sh, "ln -s niri2 niri").run()
378 })
379 .assert_initial("a")
380 .run(|sh, test| {
381 sh.write_file("niri2/config.kdl", "b")?;
382 test.assert_changed_to("b");
383
384 Ok(())
385 })
386 }
387
388 #[test]
389 fn remove_file() -> Result {
390 TestPath::Explicit("niri/config.kdl")
391 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
392 .assert_initial("a")
393 .run(|sh, test| {
394 sh.remove_path("niri/config.kdl")?;
395 test.assert_unchanged();
396
397 Ok(())
398 })
399 }
400
401 #[test]
402 fn remove_dir() -> Result {
403 TestPath::Explicit("niri/config.kdl")
404 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
405 .assert_initial("a")
406 .run(|sh, test| {
407 sh.remove_path("niri")?;
408 test.assert_unchanged();
409
410 Ok(())
411 })
412 }
413
414 #[test]
415 fn recreate_file() -> Result {
416 TestPath::Explicit("niri/config.kdl")
417 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
418 .assert_initial("a")
419 .run(|sh, test| {
420 sh.remove_path("niri/config.kdl")?;
421 sh.write_file("niri/config.kdl", "b")?;
422 test.assert_changed_to("b");
423
424 Ok(())
425 })
426 }
427
428 #[test]
429 fn recreate_dir() -> Result {
430 TestPath::Explicit("niri/config.kdl")
431 .setup(|sh| {
432 sh.write_file("niri/config.kdl", "a")?;
433 Ok(())
434 })
435 .assert_initial("a")
436 .run(|sh, test| {
437 sh.remove_path("niri")?;
438 sh.write_file("niri/config.kdl", "b")?;
439 test.assert_changed_to("b");
440
441 Ok(())
442 })
443 }
444
445 #[test]
446 fn swap_dir() -> Result {
447 TestPath::Explicit("niri/config.kdl")
448 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
449 .assert_initial("a")
450 .run(|sh, test| {
451 sh.write_file("niri2/config.kdl", "b")?;
452 sh.remove_path("niri")?;
453 cmd!(sh, "mv niri2 niri").run()?;
454 test.assert_changed_to("b");
455
456 Ok(())
457 })
458 }
459
460 #[test]
461 fn swap_dir_link() -> Result {
462 TestPath::Explicit("niri/config.kdl")
463 .setup(|sh| {
464 sh.write_file("niri2/config.kdl", "a")?;
465 cmd!(sh, "ln -s niri2 niri").run()
466 })
467 .assert_initial("a")
468 .run(|sh, test| {
469 sh.write_file("niri3/config.kdl", "b")?;
470 sh.remove_path("niri")?;
471 cmd!(sh, "ln -s niri3 niri").run()?;
472 test.assert_changed_to("b");
473
474 Ok(())
475 })
476 }
477
478 // Important: On systems like NixOS, mtime is not kept for config files.
479 // So, this is testing that the watcher handles that correctly.
480 fn create_epoch(path: impl AsRef<Path>, content: &str) -> Result {
481 let mut file = File::create(path)?;
482 file.write_all(content.as_bytes())?;
483 file.set_times(
484 FileTimes::new()
485 .set_accessed(SystemTime::UNIX_EPOCH)
486 .set_modified(SystemTime::UNIX_EPOCH),
487 )?;
488 file.sync_all()?;
489 Ok(())
490 }
491
492 #[test]
493 fn swap_just_link() -> Result {
494 TestPath::Explicit("niri/config.kdl")
495 .setup_any(|sh| {
496 let dir = sh.current_dir().join("niri");
497
498 sh.create_dir(&dir)?;
499
500 create_epoch(dir.join("config2.kdl"), "a")?;
501 create_epoch(dir.join("config3.kdl"), "b")?;
502
503 cmd!(sh, "ln -s config2.kdl niri/config.kdl").run()?;
504
505 Ok(())
506 })
507 .assert_initial("a")
508 .run(|sh, test| {
509 cmd!(sh, "ln -sf config3.kdl niri/config.kdl").run()?;
510 test.assert_changed_to("b");
511
512 Ok(())
513 })
514 }
515
516 #[test]
517 fn swap_many_regular() -> Result {
518 TestPath::Regular {
519 user_path: "user-niri/config.kdl",
520 system_path: "system-niri/config.kdl",
521 }
522 .setup(|sh| sh.write_file("system-niri/config.kdl", "system config"))
523 .assert_initial("system config")
524 .run(|sh, test| {
525 sh.write_file("user-niri/config.kdl", "user config")?;
526 test.assert_changed_to("user config");
527
528 cmd!(sh, "touch system-niri/config.kdl").run()?;
529 test.assert_unchanged();
530
531 sh.remove_path("system-niri")?;
532 test.assert_unchanged();
533
534 sh.write_file("system-niri/config.kdl", "new system config")?;
535 test.assert_unchanged();
536
537 sh.remove_path("user-niri")?;
538 test.assert_changed_to("new system config");
539
540 sh.write_file("system-niri/config.kdl", "updated system config")?;
541 test.assert_changed_to("updated system config");
542
543 sh.write_file("user-niri/config.kdl", "new user config")?;
544 test.assert_changed_to("new user config");
545
546 Ok(())
547 })
548 }
549
550 #[test]
551 fn swap_many_links_regular_like_nix() -> Result {
552 TestPath::Regular {
553 user_path: "user-niri/config.kdl",
554 system_path: "system-niri/config.kdl",
555 }
556 .setup_any(|sh| {
557 let store = sh.current_dir().join("store");
558
559 sh.create_dir(&store)?;
560
561 create_epoch(store.join("gen1"), "gen 1")?;
562 create_epoch(store.join("gen2"), "gen 2")?;
563 create_epoch(store.join("gen3"), "gen 3")?;
564
565 sh.create_dir("user-niri")?;
566 sh.create_dir("system-niri")?;
567
568 Ok(())
569 })
570 .assert_initial_not_exists()
571 .run(|sh, test| {
572 let store = sh.current_dir().join("store");
573 test.assert_unchanged();
574
575 cmd!(sh, "ln -s {store}/gen1 user-niri/config.kdl").run()?;
576 test.assert_changed_to("gen 1");
577
578 cmd!(sh, "ln -s {store}/gen2 system-niri/config.kdl").run()?;
579 test.assert_unchanged();
580
581 cmd!(sh, "unlink user-niri/config.kdl").run()?;
582 test.assert_changed_to("gen 2");
583
584 cmd!(sh, "ln -s {store}/gen3 user-niri/config.kdl").run()?;
585 test.assert_changed_to("gen 3");
586
587 cmd!(sh, "ln -sf {store}/gen1 system-niri/config.kdl").run()?;
588 test.assert_unchanged();
589
590 cmd!(sh, "unlink system-niri/config.kdl").run()?;
591 test.assert_unchanged();
592
593 cmd!(sh, "ln -s {store}/gen1 system-niri/config.kdl").run()?;
594 test.assert_unchanged();
595
596 cmd!(sh, "unlink user-niri/config.kdl").run()?;
597 test.assert_changed_to("gen 1");
598
599 Ok(())
600 })
601 }
602}