forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB38df8d4Cole Helbling1 year ago2269 commits

watcher.rs617 lines, 17.8 KiBHistoryRawDownload
1//! File modification watcher.
2
3use std::path::{Path, PathBuf};
4use std::sync::mpsc;
5use std::time::{Duration, SystemTime};
6use std::{io, thread};
7
8use niri_config::ConfigPath;
9use smithay::reexports::calloop::channel::SyncSender;
10
11use crate::niri::State;
12
13const POLLING_INTERVAL: Duration = Duration::from_millis(500);
14
15pub struct Watcher {
16 load_config: mpsc::Sender<()>,
17}
18
19struct 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)]
34enum CheckResult {
35 Missing,
36 Unchanged,
37 Changed,
38}
39
40impl Watcher {
41 pub fn new<T: Send + 'static>(
42 path: ConfigPath,
43 mut process: impl FnMut(&ConfigPath) -> T + Send + 'static,
44 changed: SyncSender<T>,
45 ) -> Self {
46 let (load_config, load_config_rx) = mpsc::channel();
47
48 thread::Builder::new()
49 .name(format!("Filesystem Watcher for {path:?}"))
50 .spawn(move || {
51 let mut inner = WatcherInner::new(path);
52
53 loop {
54 let mut should_load = match load_config_rx.recv_timeout(POLLING_INTERVAL) {
55 Ok(()) => true,
56 Err(mpsc::RecvTimeoutError::Disconnected) => break,
57 Err(mpsc::RecvTimeoutError::Timeout) => false,
58 };
59
60 match inner.check() {
61 CheckResult::Missing => continue,
62 CheckResult::Unchanged => (),
63 CheckResult::Changed => {
64 trace!("config file changed");
65 should_load = true;
66 }
67 }
68
69 if should_load {
70 let rv = process(&inner.path);
71
72 if let Err(err) = changed.send(rv) {
73 warn!("error sending change notification: {err:?}");
74 break;
75 }
76 }
77 }
78
79 debug!("exiting watcher thread for {:?}", inner.path);
80 })
81 .unwrap();
82
83 Self { load_config }
84 }
85
86 pub fn load_config(&self) {
87 let _ = self.load_config.send(());
88 }
89}
90
91fn 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
97fn 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
107impl 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
127pub fn setup(state: &mut State, config_path: &ConfigPath) {
128 // Parsing the config actually takes > 20 ms on my beefy machine, so let's do it on the
129 // watcher thread.
130 let process = |path: &ConfigPath| {
131 path.load().map_err(|err| {
132 warn!("{err:?}");
133 })
134 };
135
136 let (tx, rx) = calloop::channel::sync_channel(1);
137 state
138 .niri
139 .event_loop
140 .insert_source(rx, |event, _, state| match event {
141 calloop::channel::Event::Msg(config) => state.reload_config(config),
142 calloop::channel::Event::Closed => (),
143 })
144 .unwrap();
145
146 state.niri.config_file_watcher = Some(Watcher::new(config_path.clone(), process, tx));
147}
148
149#[cfg(test)]
150mod tests {
151 use std::error::Error;
152 use std::fs::{self, File, FileTimes};
153 use std::io::Write;
154
155 use xshell::{cmd, Shell, TempDir};
156
157 use super::*;
158
159 type Result<T = (), E = Box<dyn Error>> = std::result::Result<T, E>;
160
161 fn canon(config_path: &ConfigPath) -> &PathBuf {
162 match config_path {
163 ConfigPath::Explicit(path) => path,
164 ConfigPath::Regular {
165 user_path,
166 system_path,
167 } => {
168 if user_path.exists() {
169 user_path
170 } else {
171 system_path
172 }
173 }
174 }
175 }
176
177 enum TestPath<P> {
178 Explicit(P),
179 Regular { user_path: P, system_path: P },
180 }
181
182 impl<P: AsRef<Path>> TestPath<P> {
183 fn setup<Discard>(
184 self,
185 setup: impl FnOnce(&Shell) -> xshell::Result<Discard>,
186 ) -> TestSetup {
187 self.setup_any(|sh| {
188 _ = setup(sh)?;
189 Ok(())
190 })
191 }
192
193 fn without_setup(self) -> TestSetup {
194 self.setup_any(|_| Ok(())).assert_initial_not_exists()
195 }
196
197 fn setup_any(self, setup: impl FnOnce(&Shell) -> Result) -> TestSetup {
198 let sh = Shell::new().unwrap();
199 let temp_dir = sh.create_temp_dir().unwrap();
200 sh.change_dir(temp_dir.path());
201
202 let dir = sh.current_dir();
203 let config_path = match self {
204 TestPath::Explicit(path) => ConfigPath::Explicit(dir.join(path)),
205 TestPath::Regular {
206 user_path,
207 system_path,
208 } => ConfigPath::Regular {
209 user_path: dir.join(user_path),
210 system_path: dir.join(system_path),
211 },
212 };
213
214 setup(&sh).unwrap();
215
216 TestSetup {
217 sh,
218 config_path,
219 _temp_dir: temp_dir,
220 }
221 }
222 }
223
224 struct TestSetup {
225 sh: Shell,
226 config_path: ConfigPath,
227 _temp_dir: TempDir,
228 }
229
230 impl TestSetup {
231 fn assert_initial_not_exists(self) -> Self {
232 let canon = canon(&self.config_path);
233 assert!(!canon.exists(), "initial should not exist");
234 self
235 }
236
237 fn assert_initial(self, expected: &str) -> Self {
238 let canon = canon(&self.config_path);
239 assert!(canon.exists(), "initial should exist at {canon:?}");
240 let actual = fs::read_to_string(canon).unwrap();
241 assert_eq!(actual, expected, "initial file contents do not match");
242 self
243 }
244
245 fn run(self, body: impl FnOnce(&Shell, &mut TestUtil) -> Result) -> Result {
246 let TestSetup {
247 sh, config_path, ..
248 } = self;
249
250 let mut test = TestUtil {
251 watcher: WatcherInner::new(config_path),
252 };
253
254 // don't trigger before we start
255 test.assert_unchanged();
256 // pass_time() inside assert_unchanged() ensures that mtime
257 // isn't the same as the initial time
258
259 body(&sh, &mut test)?;
260
261 // nothing should trigger after the test runs
262 test.assert_unchanged();
263
264 Ok(())
265 }
266 }
267
268 struct TestUtil {
269 watcher: WatcherInner,
270 }
271
272 impl TestUtil {
273 // Ensures that mtime is different between writes in the tests.
274 fn pass_time(&self) {
275 thread::sleep(Duration::from_millis(50));
276 }
277
278 fn assert_unchanged(&mut self) {
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,
285 "watcher should not have noticed any changes"
286 );
287
288 self.pass_time();
289 }
290
291 fn assert_changed_to(&mut self, expected: &str) {
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");
302
303 self.pass_time();
304 }
305 }
306
307 #[test]
308 fn change_file() -> Result {
309 TestPath::Explicit("niri/config.kdl")
310 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
311 .assert_initial("a")
312 .run(|sh, test| {
313 sh.write_file("niri/config.kdl", "b")?;
314 test.assert_changed_to("b");
315
316 Ok(())
317 })
318 }
319
320 #[test]
321 fn overwrite_but_dont_change_file() -> Result {
322 TestPath::Explicit("niri/config.kdl")
323 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
324 .assert_initial("a")
325 .run(|sh, test| {
326 sh.write_file("niri/config.kdl", "a")?;
327 test.assert_changed_to("a");
328
329 Ok(())
330 })
331 }
332
333 #[test]
334 fn touch_file() -> Result {
335 TestPath::Explicit("niri/config.kdl")
336 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
337 .assert_initial("a")
338 .run(|sh, test| {
339 cmd!(sh, "touch niri/config.kdl").run()?;
340 test.assert_changed_to("a");
341
342 Ok(())
343 })
344 }
345
346 #[test]
347 fn create_file() -> Result {
348 TestPath::Explicit("niri/config.kdl")
349 .setup(|sh| sh.create_dir("niri"))
350 .assert_initial_not_exists()
351 .run(|sh, test| {
352 sh.write_file("niri/config.kdl", "a")?;
353 test.assert_changed_to("a");
354
355 Ok(())
356 })
357 }
358
359 #[test]
360 fn create_dir_and_file() -> Result {
361 TestPath::Explicit("niri/config.kdl")
362 .without_setup()
363 .run(|sh, test| {
364 sh.write_file("niri/config.kdl", "a")?;
365 test.assert_changed_to("a");
366
367 Ok(())
368 })
369 }
370
371 #[test]
372 fn change_linked_file() -> Result {
373 TestPath::Explicit("niri/config.kdl")
374 .setup(|sh| {
375 sh.write_file("niri/config2.kdl", "a")?;
376 cmd!(sh, "ln -sf config2.kdl niri/config.kdl").run()
377 })
378 .assert_initial("a")
379 .run(|sh, test| {
380 sh.write_file("niri/config2.kdl", "b")?;
381 test.assert_changed_to("b");
382
383 Ok(())
384 })
385 }
386
387 #[test]
388 fn change_file_in_linked_dir() -> Result {
389 TestPath::Explicit("niri/config.kdl")
390 .setup(|sh| {
391 sh.write_file("niri2/config.kdl", "a")?;
392 cmd!(sh, "ln -s niri2 niri").run()
393 })
394 .assert_initial("a")
395 .run(|sh, test| {
396 sh.write_file("niri2/config.kdl", "b")?;
397 test.assert_changed_to("b");
398
399 Ok(())
400 })
401 }
402
403 #[test]
404 fn remove_file() -> Result {
405 TestPath::Explicit("niri/config.kdl")
406 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
407 .assert_initial("a")
408 .run(|sh, test| {
409 sh.remove_path("niri/config.kdl")?;
410 test.assert_unchanged();
411
412 Ok(())
413 })
414 }
415
416 #[test]
417 fn remove_dir() -> Result {
418 TestPath::Explicit("niri/config.kdl")
419 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
420 .assert_initial("a")
421 .run(|sh, test| {
422 sh.remove_path("niri")?;
423 test.assert_unchanged();
424
425 Ok(())
426 })
427 }
428
429 #[test]
430 fn recreate_file() -> Result {
431 TestPath::Explicit("niri/config.kdl")
432 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
433 .assert_initial("a")
434 .run(|sh, test| {
435 sh.remove_path("niri/config.kdl")?;
436 sh.write_file("niri/config.kdl", "b")?;
437 test.assert_changed_to("b");
438
439 Ok(())
440 })
441 }
442
443 #[test]
444 fn recreate_dir() -> Result {
445 TestPath::Explicit("niri/config.kdl")
446 .setup(|sh| {
447 sh.write_file("niri/config.kdl", "a")?;
448 Ok(())
449 })
450 .assert_initial("a")
451 .run(|sh, test| {
452 sh.remove_path("niri")?;
453 sh.write_file("niri/config.kdl", "b")?;
454 test.assert_changed_to("b");
455
456 Ok(())
457 })
458 }
459
460 #[test]
461 fn swap_dir() -> Result {
462 TestPath::Explicit("niri/config.kdl")
463 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
464 .assert_initial("a")
465 .run(|sh, test| {
466 sh.write_file("niri2/config.kdl", "b")?;
467 sh.remove_path("niri")?;
468 cmd!(sh, "mv niri2 niri").run()?;
469 test.assert_changed_to("b");
470
471 Ok(())
472 })
473 }
474
475 #[test]
476 fn swap_dir_link() -> Result {
477 TestPath::Explicit("niri/config.kdl")
478 .setup(|sh| {
479 sh.write_file("niri2/config.kdl", "a")?;
480 cmd!(sh, "ln -s niri2 niri").run()
481 })
482 .assert_initial("a")
483 .run(|sh, test| {
484 sh.write_file("niri3/config.kdl", "b")?;
485 sh.remove_path("niri")?;
486 cmd!(sh, "ln -s niri3 niri").run()?;
487 test.assert_changed_to("b");
488
489 Ok(())
490 })
491 }
492
493 // Important: On systems like NixOS, mtime is not kept for config files.
494 // So, this is testing that the watcher handles that correctly.
495 fn create_epoch(path: impl AsRef<Path>, content: &str) -> Result {
496 let mut file = File::create(path)?;
497 file.write_all(content.as_bytes())?;
498 file.set_times(
499 FileTimes::new()
500 .set_accessed(SystemTime::UNIX_EPOCH)
501 .set_modified(SystemTime::UNIX_EPOCH),
502 )?;
503 file.sync_all()?;
504 Ok(())
505 }
506
507 #[test]
508 fn swap_just_link() -> Result {
509 TestPath::Explicit("niri/config.kdl")
510 .setup_any(|sh| {
511 let dir = sh.current_dir().join("niri");
512
513 sh.create_dir(&dir)?;
514
515 create_epoch(dir.join("config2.kdl"), "a")?;
516 create_epoch(dir.join("config3.kdl"), "b")?;
517
518 cmd!(sh, "ln -s config2.kdl niri/config.kdl").run()?;
519
520 Ok(())
521 })
522 .assert_initial("a")
523 .run(|sh, test| {
524 cmd!(sh, "ln -sf config3.kdl niri/config.kdl").run()?;
525 test.assert_changed_to("b");
526
527 Ok(())
528 })
529 }
530
531 #[test]
532 fn swap_many_regular() -> Result {
533 TestPath::Regular {
534 user_path: "user-niri/config.kdl",
535 system_path: "system-niri/config.kdl",
536 }
537 .setup(|sh| sh.write_file("system-niri/config.kdl", "system config"))
538 .assert_initial("system config")
539 .run(|sh, test| {
540 sh.write_file("user-niri/config.kdl", "user config")?;
541 test.assert_changed_to("user config");
542
543 cmd!(sh, "touch system-niri/config.kdl").run()?;
544 test.assert_unchanged();
545
546 sh.remove_path("system-niri")?;
547 test.assert_unchanged();
548
549 sh.write_file("system-niri/config.kdl", "new system config")?;
550 test.assert_unchanged();
551
552 sh.remove_path("user-niri")?;
553 test.assert_changed_to("new system config");
554
555 sh.write_file("system-niri/config.kdl", "updated system config")?;
556 test.assert_changed_to("updated system config");
557
558 sh.write_file("user-niri/config.kdl", "new user config")?;
559 test.assert_changed_to("new user config");
560
561 Ok(())
562 })
563 }
564
565 #[test]
566 fn swap_many_links_regular_like_nix() -> Result {
567 TestPath::Regular {
568 user_path: "user-niri/config.kdl",
569 system_path: "system-niri/config.kdl",
570 }
571 .setup_any(|sh| {
572 let store = sh.current_dir().join("store");
573
574 sh.create_dir(&store)?;
575
576 create_epoch(store.join("gen1"), "gen 1")?;
577 create_epoch(store.join("gen2"), "gen 2")?;
578 create_epoch(store.join("gen3"), "gen 3")?;
579
580 sh.create_dir("user-niri")?;
581 sh.create_dir("system-niri")?;
582
583 Ok(())
584 })
585 .assert_initial_not_exists()
586 .run(|sh, test| {
587 let store = sh.current_dir().join("store");
588 test.assert_unchanged();
589
590 cmd!(sh, "ln -s {store}/gen1 user-niri/config.kdl").run()?;
591 test.assert_changed_to("gen 1");
592
593 cmd!(sh, "ln -s {store}/gen2 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 2");
598
599 cmd!(sh, "ln -s {store}/gen3 user-niri/config.kdl").run()?;
600 test.assert_changed_to("gen 3");
601
602 cmd!(sh, "ln -sf {store}/gen1 system-niri/config.kdl").run()?;
603 test.assert_unchanged();
604
605 cmd!(sh, "unlink system-niri/config.kdl").run()?;
606 test.assert_unchanged();
607
608 cmd!(sh, "ln -s {store}/gen1 system-niri/config.kdl").run()?;
609 test.assert_unchanged();
610
611 cmd!(sh, "unlink user-niri/config.kdl").run()?;
612 test.assert_changed_to("gen 1");
613
614 Ok(())
615 })
616 }
617}