forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB90ef202Ivan Molodetskikh1 year ago2349 commits

watcher.rs624 lines, 18.0 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::{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(
141 rx,
142 |event: calloop::channel::Event<Result<Config, ()>>, _, state| match event {
143 calloop::channel::Event::Msg(config) => {
144 let failed = config.is_err();
145 state.reload_config(config);
146 state.ipc_config_loaded(failed);
147 }
148 calloop::channel::Event::Closed => (),
149 },
150 )
151 .unwrap();
152
153 state.niri.config_file_watcher = Some(Watcher::new(config_path.clone(), process, tx));
154}
155
156#[cfg(test)]
157mod tests {
158 use std::error::Error;
159 use std::fs::{self, File, FileTimes};
160 use std::io::Write;
161
162 use xshell::{cmd, Shell, TempDir};
163
164 use super::*;
165
166 type Result<T = (), E = Box<dyn Error>> = std::result::Result<T, E>;
167
168 fn canon(config_path: &ConfigPath) -> &PathBuf {
169 match config_path {
170 ConfigPath::Explicit(path) => path,
171 ConfigPath::Regular {
172 user_path,
173 system_path,
174 } => {
175 if user_path.exists() {
176 user_path
177 } else {
178 system_path
179 }
180 }
181 }
182 }
183
184 enum TestPath<P> {
185 Explicit(P),
186 Regular { user_path: P, system_path: P },
187 }
188
189 impl<P: AsRef<Path>> TestPath<P> {
190 fn setup<Discard>(
191 self,
192 setup: impl FnOnce(&Shell) -> xshell::Result<Discard>,
193 ) -> TestSetup {
194 self.setup_any(|sh| {
195 _ = setup(sh)?;
196 Ok(())
197 })
198 }
199
200 fn without_setup(self) -> TestSetup {
201 self.setup_any(|_| Ok(())).assert_initial_not_exists()
202 }
203
204 fn setup_any(self, setup: impl FnOnce(&Shell) -> Result) -> TestSetup {
205 let sh = Shell::new().unwrap();
206 let temp_dir = sh.create_temp_dir().unwrap();
207 sh.change_dir(temp_dir.path());
208
209 let dir = sh.current_dir();
210 let config_path = match self {
211 TestPath::Explicit(path) => ConfigPath::Explicit(dir.join(path)),
212 TestPath::Regular {
213 user_path,
214 system_path,
215 } => ConfigPath::Regular {
216 user_path: dir.join(user_path),
217 system_path: dir.join(system_path),
218 },
219 };
220
221 setup(&sh).unwrap();
222
223 TestSetup {
224 sh,
225 config_path,
226 _temp_dir: temp_dir,
227 }
228 }
229 }
230
231 struct TestSetup {
232 sh: Shell,
233 config_path: ConfigPath,
234 _temp_dir: TempDir,
235 }
236
237 impl TestSetup {
238 fn assert_initial_not_exists(self) -> Self {
239 let canon = canon(&self.config_path);
240 assert!(!canon.exists(), "initial should not exist");
241 self
242 }
243
244 fn assert_initial(self, expected: &str) -> Self {
245 let canon = canon(&self.config_path);
246 assert!(canon.exists(), "initial should exist at {canon:?}");
247 let actual = fs::read_to_string(canon).unwrap();
248 assert_eq!(actual, expected, "initial file contents do not match");
249 self
250 }
251
252 fn run(self, body: impl FnOnce(&Shell, &mut TestUtil) -> Result) -> Result {
253 let TestSetup {
254 sh, config_path, ..
255 } = self;
256
257 let mut test = TestUtil {
258 watcher: WatcherInner::new(config_path),
259 };
260
261 // don't trigger before we start
262 test.assert_unchanged();
263 // pass_time() inside assert_unchanged() ensures that mtime
264 // isn't the same as the initial time
265
266 body(&sh, &mut test)?;
267
268 // nothing should trigger after the test runs
269 test.assert_unchanged();
270
271 Ok(())
272 }
273 }
274
275 struct TestUtil {
276 watcher: WatcherInner,
277 }
278
279 impl TestUtil {
280 // Ensures that mtime is different between writes in the tests.
281 fn pass_time(&self) {
282 thread::sleep(Duration::from_millis(50));
283 }
284
285 fn assert_unchanged(&mut self) {
286 let res = self.watcher.check();
287
288 // This may be Missing or Unchanged, both are fine.
289 assert_ne!(
290 res,
291 CheckResult::Changed,
292 "watcher should not have noticed any changes"
293 );
294
295 self.pass_time();
296 }
297
298 fn assert_changed_to(&mut self, expected: &str) {
299 let res = self.watcher.check();
300 assert_eq!(
301 res,
302 CheckResult::Changed,
303 "watcher should have noticed a change, but it didn't"
304 );
305
306 let new_path = canon(&self.watcher.path);
307 let actual = fs::read_to_string(new_path).unwrap();
308 assert_eq!(actual, expected, "wrong file contents");
309
310 self.pass_time();
311 }
312 }
313
314 #[test]
315 fn change_file() -> Result {
316 TestPath::Explicit("niri/config.kdl")
317 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
318 .assert_initial("a")
319 .run(|sh, test| {
320 sh.write_file("niri/config.kdl", "b")?;
321 test.assert_changed_to("b");
322
323 Ok(())
324 })
325 }
326
327 #[test]
328 fn overwrite_but_dont_change_file() -> Result {
329 TestPath::Explicit("niri/config.kdl")
330 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
331 .assert_initial("a")
332 .run(|sh, test| {
333 sh.write_file("niri/config.kdl", "a")?;
334 test.assert_changed_to("a");
335
336 Ok(())
337 })
338 }
339
340 #[test]
341 fn touch_file() -> Result {
342 TestPath::Explicit("niri/config.kdl")
343 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
344 .assert_initial("a")
345 .run(|sh, test| {
346 cmd!(sh, "touch niri/config.kdl").run()?;
347 test.assert_changed_to("a");
348
349 Ok(())
350 })
351 }
352
353 #[test]
354 fn create_file() -> Result {
355 TestPath::Explicit("niri/config.kdl")
356 .setup(|sh| sh.create_dir("niri"))
357 .assert_initial_not_exists()
358 .run(|sh, test| {
359 sh.write_file("niri/config.kdl", "a")?;
360 test.assert_changed_to("a");
361
362 Ok(())
363 })
364 }
365
366 #[test]
367 fn create_dir_and_file() -> Result {
368 TestPath::Explicit("niri/config.kdl")
369 .without_setup()
370 .run(|sh, test| {
371 sh.write_file("niri/config.kdl", "a")?;
372 test.assert_changed_to("a");
373
374 Ok(())
375 })
376 }
377
378 #[test]
379 fn change_linked_file() -> Result {
380 TestPath::Explicit("niri/config.kdl")
381 .setup(|sh| {
382 sh.write_file("niri/config2.kdl", "a")?;
383 cmd!(sh, "ln -sf config2.kdl niri/config.kdl").run()
384 })
385 .assert_initial("a")
386 .run(|sh, test| {
387 sh.write_file("niri/config2.kdl", "b")?;
388 test.assert_changed_to("b");
389
390 Ok(())
391 })
392 }
393
394 #[test]
395 fn change_file_in_linked_dir() -> Result {
396 TestPath::Explicit("niri/config.kdl")
397 .setup(|sh| {
398 sh.write_file("niri2/config.kdl", "a")?;
399 cmd!(sh, "ln -s niri2 niri").run()
400 })
401 .assert_initial("a")
402 .run(|sh, test| {
403 sh.write_file("niri2/config.kdl", "b")?;
404 test.assert_changed_to("b");
405
406 Ok(())
407 })
408 }
409
410 #[test]
411 fn remove_file() -> Result {
412 TestPath::Explicit("niri/config.kdl")
413 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
414 .assert_initial("a")
415 .run(|sh, test| {
416 sh.remove_path("niri/config.kdl")?;
417 test.assert_unchanged();
418
419 Ok(())
420 })
421 }
422
423 #[test]
424 fn remove_dir() -> Result {
425 TestPath::Explicit("niri/config.kdl")
426 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
427 .assert_initial("a")
428 .run(|sh, test| {
429 sh.remove_path("niri")?;
430 test.assert_unchanged();
431
432 Ok(())
433 })
434 }
435
436 #[test]
437 fn recreate_file() -> Result {
438 TestPath::Explicit("niri/config.kdl")
439 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
440 .assert_initial("a")
441 .run(|sh, test| {
442 sh.remove_path("niri/config.kdl")?;
443 sh.write_file("niri/config.kdl", "b")?;
444 test.assert_changed_to("b");
445
446 Ok(())
447 })
448 }
449
450 #[test]
451 fn recreate_dir() -> Result {
452 TestPath::Explicit("niri/config.kdl")
453 .setup(|sh| {
454 sh.write_file("niri/config.kdl", "a")?;
455 Ok(())
456 })
457 .assert_initial("a")
458 .run(|sh, test| {
459 sh.remove_path("niri")?;
460 sh.write_file("niri/config.kdl", "b")?;
461 test.assert_changed_to("b");
462
463 Ok(())
464 })
465 }
466
467 #[test]
468 fn swap_dir() -> Result {
469 TestPath::Explicit("niri/config.kdl")
470 .setup(|sh| sh.write_file("niri/config.kdl", "a"))
471 .assert_initial("a")
472 .run(|sh, test| {
473 sh.write_file("niri2/config.kdl", "b")?;
474 sh.remove_path("niri")?;
475 cmd!(sh, "mv niri2 niri").run()?;
476 test.assert_changed_to("b");
477
478 Ok(())
479 })
480 }
481
482 #[test]
483 fn swap_dir_link() -> Result {
484 TestPath::Explicit("niri/config.kdl")
485 .setup(|sh| {
486 sh.write_file("niri2/config.kdl", "a")?;
487 cmd!(sh, "ln -s niri2 niri").run()
488 })
489 .assert_initial("a")
490 .run(|sh, test| {
491 sh.write_file("niri3/config.kdl", "b")?;
492 sh.remove_path("niri")?;
493 cmd!(sh, "ln -s niri3 niri").run()?;
494 test.assert_changed_to("b");
495
496 Ok(())
497 })
498 }
499
500 // Important: On systems like NixOS, mtime is not kept for config files.
501 // So, this is testing that the watcher handles that correctly.
502 fn create_epoch(path: impl AsRef<Path>, content: &str) -> Result {
503 let mut file = File::create(path)?;
504 file.write_all(content.as_bytes())?;
505 file.set_times(
506 FileTimes::new()
507 .set_accessed(SystemTime::UNIX_EPOCH)
508 .set_modified(SystemTime::UNIX_EPOCH),
509 )?;
510 file.sync_all()?;
511 Ok(())
512 }
513
514 #[test]
515 fn swap_just_link() -> Result {
516 TestPath::Explicit("niri/config.kdl")
517 .setup_any(|sh| {
518 let dir = sh.current_dir().join("niri");
519
520 sh.create_dir(&dir)?;
521
522 create_epoch(dir.join("config2.kdl"), "a")?;
523 create_epoch(dir.join("config3.kdl"), "b")?;
524
525 cmd!(sh, "ln -s config2.kdl niri/config.kdl").run()?;
526
527 Ok(())
528 })
529 .assert_initial("a")
530 .run(|sh, test| {
531 cmd!(sh, "ln -sf config3.kdl niri/config.kdl").run()?;
532 test.assert_changed_to("b");
533
534 Ok(())
535 })
536 }
537
538 #[test]
539 fn swap_many_regular() -> Result {
540 TestPath::Regular {
541 user_path: "user-niri/config.kdl",
542 system_path: "system-niri/config.kdl",
543 }
544 .setup(|sh| sh.write_file("system-niri/config.kdl", "system config"))
545 .assert_initial("system config")
546 .run(|sh, test| {
547 sh.write_file("user-niri/config.kdl", "user config")?;
548 test.assert_changed_to("user config");
549
550 cmd!(sh, "touch system-niri/config.kdl").run()?;
551 test.assert_unchanged();
552
553 sh.remove_path("system-niri")?;
554 test.assert_unchanged();
555
556 sh.write_file("system-niri/config.kdl", "new system config")?;
557 test.assert_unchanged();
558
559 sh.remove_path("user-niri")?;
560 test.assert_changed_to("new system config");
561
562 sh.write_file("system-niri/config.kdl", "updated system config")?;
563 test.assert_changed_to("updated system config");
564
565 sh.write_file("user-niri/config.kdl", "new user config")?;
566 test.assert_changed_to("new user config");
567
568 Ok(())
569 })
570 }
571
572 #[test]
573 fn swap_many_links_regular_like_nix() -> Result {
574 TestPath::Regular {
575 user_path: "user-niri/config.kdl",
576 system_path: "system-niri/config.kdl",
577 }
578 .setup_any(|sh| {
579 let store = sh.current_dir().join("store");
580
581 sh.create_dir(&store)?;
582
583 create_epoch(store.join("gen1"), "gen 1")?;
584 create_epoch(store.join("gen2"), "gen 2")?;
585 create_epoch(store.join("gen3"), "gen 3")?;
586
587 sh.create_dir("user-niri")?;
588 sh.create_dir("system-niri")?;
589
590 Ok(())
591 })
592 .assert_initial_not_exists()
593 .run(|sh, test| {
594 let store = sh.current_dir().join("store");
595 test.assert_unchanged();
596
597 cmd!(sh, "ln -s {store}/gen1 user-niri/config.kdl").run()?;
598 test.assert_changed_to("gen 1");
599
600 cmd!(sh, "ln -s {store}/gen2 system-niri/config.kdl").run()?;
601 test.assert_unchanged();
602
603 cmd!(sh, "unlink user-niri/config.kdl").run()?;
604 test.assert_changed_to("gen 2");
605
606 cmd!(sh, "ln -s {store}/gen3 user-niri/config.kdl").run()?;
607 test.assert_changed_to("gen 3");
608
609 cmd!(sh, "ln -sf {store}/gen1 system-niri/config.kdl").run()?;
610 test.assert_unchanged();
611
612 cmd!(sh, "unlink system-niri/config.kdl").run()?;
613 test.assert_unchanged();
614
615 cmd!(sh, "ln -s {store}/gen1 system-niri/config.kdl").run()?;
616 test.assert_unchanged();
617
618 cmd!(sh, "unlink user-niri/config.kdl").run()?;
619 test.assert_changed_to("gen 1");
620
621 Ok(())
622 })
623 }
624}