forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB289ae36Ivan Molodetskikh2 years ago1428 commits

watcher.rs348 lines, 9.9 KiBHistoryRawDownload
1//! File modification watcher.
2
3use std::path::PathBuf;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::{mpsc, Arc};
6use std::thread;
7use std::time::Duration;
8
9use smithay::reexports::calloop::channel::SyncSender;
10
11pub struct Watcher {
12 should_stop: Arc<AtomicBool>,
13}
14
15impl Drop for Watcher {
16 fn drop(&mut self) {
17 self.should_stop.store(true, Ordering::SeqCst);
18 }
19}
20
21impl Watcher {
22 pub fn new(path: PathBuf, changed: SyncSender<()>) -> Self {
23 Self::with_start_notification(path, changed, None)
24 }
25
26 pub fn with_start_notification(
27 path: PathBuf,
28 changed: SyncSender<()>,
29 started: Option<mpsc::SyncSender<()>>,
30 ) -> Self {
31 let should_stop = Arc::new(AtomicBool::new(false));
32
33 {
34 let should_stop = should_stop.clone();
35 thread::Builder::new()
36 .name(format!("Filesystem Watcher for {}", path.to_string_lossy()))
37 .spawn(move || {
38 // this "should" be as simple as mtime, but it does not quite work in practice;
39 // it doesn't work if the config is a symlink, and its target changes but the
40 // new target and old target have identical mtimes.
41 //
42 // in practice, this does not occur on any systems other than nix.
43 // because, on nix practically everything is a symlink to /nix/store
44 // and due to reproducibility, /nix/store keeps no mtime (= 1970-01-01)
45 // so, symlink targets change frequently when mtime doesn't.
46 let mut last_props = path
47 .canonicalize()
48 .and_then(|canon| Ok((canon.metadata()?.modified()?, canon)))
49 .ok();
50
51 if let Some(started) = started {
52 let _ = started.send(());
53 }
54
55 loop {
56 thread::sleep(Duration::from_millis(500));
57
58 if should_stop.load(Ordering::SeqCst) {
59 break;
60 }
61
62 if let Ok(new_props) = path
63 .canonicalize()
64 .and_then(|canon| Ok((canon.metadata()?.modified()?, canon)))
65 {
66 if last_props.as_ref() != Some(&new_props) {
67 trace!("file changed: {}", path.to_string_lossy());
68
69 if let Err(err) = changed.send(()) {
70 warn!("error sending change notification: {err:?}");
71 break;
72 }
73
74 last_props = Some(new_props);
75 }
76 }
77 }
78
79 debug!("exiting watcher thread for {}", path.to_string_lossy());
80 })
81 .unwrap();
82 }
83
84 Self { should_stop }
85 }
86}
87
88#[cfg(test)]
89mod tests {
90 use std::error::Error;
91 use std::fs::File;
92 use std::io::Write;
93 use std::sync::atomic::AtomicU8;
94
95 use calloop::channel::sync_channel;
96 use calloop::EventLoop;
97 use smithay::reexports::rustix::fs::{futimens, Timestamps};
98 use smithay::reexports::rustix::time::Timespec;
99 use xshell::{cmd, Shell};
100
101 use super::*;
102
103 fn check(
104 setup: impl FnOnce(&Shell) -> Result<(), Box<dyn Error>>,
105 change: impl FnOnce(&Shell) -> Result<(), Box<dyn Error>>,
106 ) {
107 let sh = Shell::new().unwrap();
108 let temp_dir = sh.create_temp_dir().unwrap();
109 sh.change_dir(temp_dir.path());
110 // let dir = sh.create_dir("xshell").unwrap();
111 // sh.change_dir(dir);
112
113 let mut config_path = sh.current_dir();
114 config_path.push("niri");
115 config_path.push("config.kdl");
116
117 setup(&sh).unwrap();
118
119 let changed = AtomicU8::new(0);
120
121 let mut event_loop = EventLoop::try_new().unwrap();
122 let loop_handle = event_loop.handle();
123
124 let (tx, rx) = sync_channel(1);
125 let (started_tx, started_rx) = mpsc::sync_channel(1);
126 let _watcher = Watcher::with_start_notification(config_path.clone(), tx, Some(started_tx));
127 loop_handle
128 .insert_source(rx, |_, _, _| {
129 changed.fetch_add(1, Ordering::SeqCst);
130 })
131 .unwrap();
132 started_rx.recv().unwrap();
133
134 // HACK: if we don't sleep, files might have the same mtime.
135 thread::sleep(Duration::from_millis(100));
136
137 change(&sh).unwrap();
138
139 event_loop
140 .dispatch(Duration::from_millis(750), &mut ())
141 .unwrap();
142
143 assert_eq!(changed.load(Ordering::SeqCst), 1);
144
145 // Verify that the watcher didn't break.
146 sh.write_file(&config_path, "c").unwrap();
147
148 event_loop
149 .dispatch(Duration::from_millis(750), &mut ())
150 .unwrap();
151
152 assert_eq!(changed.load(Ordering::SeqCst), 2);
153 }
154
155 #[test]
156 fn change_file() {
157 check(
158 |sh| {
159 sh.write_file("niri/config.kdl", "a")?;
160 Ok(())
161 },
162 |sh| {
163 sh.write_file("niri/config.kdl", "b")?;
164 Ok(())
165 },
166 );
167 }
168
169 #[test]
170 fn create_file() {
171 check(
172 |sh| {
173 sh.create_dir("niri")?;
174 Ok(())
175 },
176 |sh| {
177 sh.write_file("niri/config.kdl", "a")?;
178 Ok(())
179 },
180 );
181 }
182
183 #[test]
184 fn create_dir_and_file() {
185 check(
186 |_sh| Ok(()),
187 |sh| {
188 sh.write_file("niri/config.kdl", "a")?;
189 Ok(())
190 },
191 );
192 }
193
194 #[test]
195 fn change_linked_file() {
196 check(
197 |sh| {
198 sh.write_file("niri/config2.kdl", "a")?;
199 cmd!(sh, "ln -s config2.kdl niri/config.kdl").run()?;
200 Ok(())
201 },
202 |sh| {
203 sh.write_file("niri/config2.kdl", "b")?;
204 Ok(())
205 },
206 );
207 }
208
209 #[test]
210 fn change_file_in_linked_dir() {
211 check(
212 |sh| {
213 sh.write_file("niri2/config.kdl", "a")?;
214 cmd!(sh, "ln -s niri2 niri").run()?;
215 Ok(())
216 },
217 |sh| {
218 sh.write_file("niri2/config.kdl", "b")?;
219 Ok(())
220 },
221 );
222 }
223
224 #[test]
225 fn recreate_file() {
226 check(
227 |sh| {
228 sh.write_file("niri/config.kdl", "a")?;
229 Ok(())
230 },
231 |sh| {
232 sh.remove_path("niri/config.kdl")?;
233 sh.write_file("niri/config.kdl", "b")?;
234 Ok(())
235 },
236 );
237 }
238
239 #[test]
240 fn recreate_dir() {
241 check(
242 |sh| {
243 sh.write_file("niri/config.kdl", "a")?;
244 Ok(())
245 },
246 |sh| {
247 sh.remove_path("niri")?;
248 sh.write_file("niri/config.kdl", "b")?;
249 Ok(())
250 },
251 );
252 }
253
254 #[test]
255 fn swap_dir() {
256 check(
257 |sh| {
258 sh.write_file("niri/config.kdl", "a")?;
259 Ok(())
260 },
261 |sh| {
262 sh.write_file("niri2/config.kdl", "b")?;
263 sh.remove_path("niri")?;
264 cmd!(sh, "mv niri2 niri").run()?;
265 Ok(())
266 },
267 );
268 }
269
270 #[test]
271 fn swap_just_link() {
272 // NixOS setup: link path changes, mtime stays constant.
273 check(
274 |sh| {
275 let mut dir = sh.current_dir();
276 dir.push("niri");
277 sh.create_dir(&dir)?;
278
279 let mut d2 = dir.clone();
280 d2.push("config2.kdl");
281 let mut c2 = File::create(d2).unwrap();
282 write!(c2, "a")?;
283 c2.flush()?;
284 futimens(
285 &c2,
286 &Timestamps {
287 last_access: Timespec {
288 tv_sec: 0,
289 tv_nsec: 0,
290 },
291 last_modification: Timespec {
292 tv_sec: 0,
293 tv_nsec: 0,
294 },
295 },
296 )?;
297 c2.sync_all()?;
298 drop(c2);
299
300 let mut d3 = dir.clone();
301 d3.push("config3.kdl");
302 let mut c3 = File::create(d3).unwrap();
303 write!(c3, "b")?;
304 c3.flush()?;
305 futimens(
306 &c3,
307 &Timestamps {
308 last_access: Timespec {
309 tv_sec: 0,
310 tv_nsec: 0,
311 },
312 last_modification: Timespec {
313 tv_sec: 0,
314 tv_nsec: 0,
315 },
316 },
317 )?;
318 c3.sync_all()?;
319 drop(c3);
320
321 cmd!(sh, "ln -s config2.kdl niri/config.kdl").run()?;
322 Ok(())
323 },
324 |sh| {
325 cmd!(sh, "unlink niri/config.kdl").run()?;
326 cmd!(sh, "ln -s config3.kdl niri/config.kdl").run()?;
327 Ok(())
328 },
329 );
330 }
331
332 #[test]
333 fn swap_dir_link() {
334 check(
335 |sh| {
336 sh.write_file("niri2/config.kdl", "a")?;
337 cmd!(sh, "ln -s niri2 niri").run()?;
338 Ok(())
339 },
340 |sh| {
341 sh.write_file("niri3/config.kdl", "b")?;
342 cmd!(sh, "unlink niri").run()?;
343 cmd!(sh, "ln -s niri3 niri").run()?;
344 Ok(())
345 },
346 );
347 }
348}