Skip to main content

mortise_core/app/
live.rs

1//! An app that is kept fresh: read on a worker thread, and read again when its files change.
2
3use std::collections::BTreeMap;
4use std::path::{Component, Path, PathBuf};
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::mpsc::{Receiver, Sender, channel};
7use std::sync::{Arc, Mutex};
8use std::time::Duration;
9
10use notify::{RecommendedWatcher, RecursiveMode};
11use notify_debouncer_full::{DebounceEventResult, Debouncer, RecommendedCache, new_debouncer};
12
13use crate::app::{AppSnapshot, ReadError, ReadOptions, read_app_cached};
14use crate::modules::module::{Progress, ReadCache};
15
16/// How long file changes are collected before the app is read again.
17const QUIET: Duration = Duration::from_millis(300);
18
19/// What a [`LiveApp`] holds at this moment.
20#[derive(Debug, Clone)]
21pub enum LiveState {
22    /// The first read has not ended.
23    Reading,
24    /// The last read. It stays until a later read ends.
25    Ready(Arc<AppSnapshot>),
26    /// The last read failed.
27    Failed(Arc<ReadError>),
28}
29
30enum Command {
31    /// Read everything again now, also the files that did not change.
32    Refresh,
33    /// Files changed: read again, but only the files that changed.
34    Changed,
35    /// Watch the files of the app, or stop watching.
36    Watch(bool),
37    /// Read with other options from now on, and read again.
38    Options(ReadOptions),
39    Stop,
40}
41
42/// An app folder with a worker thread that reads it.
43///
44/// The interface never changes a snapshot: it asks for the current one with
45/// [`LiveApp::state`] and is told through `on_change` that a newer one is there.
46pub struct LiveApp {
47    state: Arc<Mutex<LiveState>>,
48    watching: Arc<AtomicBool>,
49    commands: Sender<Command>,
50    progress: Arc<Progress>,
51}
52
53impl LiveApp {
54    /// Starts reading the app in `root`. `codes` are the codes its modules already
55    /// have. `on_change` is called from the worker thread after every read.
56    pub fn open(
57        root: PathBuf,
58        codes: BTreeMap<String, String>,
59        options: ReadOptions,
60        on_change: impl Fn() + Send + 'static,
61    ) -> Self {
62        let state = Arc::new(Mutex::new(LiveState::Reading));
63        let watching = Arc::new(AtomicBool::new(false));
64        let (commands, inbox) = channel();
65        let cache = ReadCache::default();
66        let progress = cache.progress();
67        let worker = Worker {
68            root,
69            codes,
70            options,
71            cache,
72            state: Arc::clone(&state),
73            inbox,
74            // The watcher reports into the same inbox.
75            outbox: commands.clone(),
76            on_change: Box::new(on_change),
77            watcher: None,
78            watched: Plan::default(),
79            watching: Arc::clone(&watching),
80        };
81        std::thread::Builder::new()
82            .name("mortise-app-reader".to_owned())
83            .spawn(move || worker.run())
84            .expect("a thread can be started");
85        Self {
86            state,
87            watching,
88            commands,
89            progress,
90        }
91    }
92
93    /// How far the read that is going on is: the PHP files read, and how many there are.
94    pub fn progress(&self) -> (usize, usize) {
95        self.progress.get()
96    }
97
98    /// True once the watcher that [`LiveApp::watch`] asked for is in place.
99    pub fn is_watching(&self) -> bool {
100        self.watching.load(Ordering::Relaxed)
101    }
102
103    /// The current state. Cheap: a snapshot is shared, not copied.
104    pub fn state(&self) -> LiveState {
105        self.state
106            .lock()
107            .expect("the state is never poisoned")
108            .clone()
109    }
110
111    /// Reads the app again, now, also the files that did not change.
112    pub fn refresh(&self) {
113        let _ = self.commands.send(Command::Refresh);
114    }
115
116    /// Changes what the user set for the app, and reads it again.
117    pub fn set_options(&self, options: ReadOptions) {
118        let _ = self.commands.send(Command::Options(options));
119    }
120
121    /// Starts or stops reading the app again when its files change.
122    pub fn watch(&self, on: bool) {
123        let _ = self.commands.send(Command::Watch(on));
124    }
125}
126
127impl Drop for LiveApp {
128    fn drop(&mut self) {
129        let _ = self.commands.send(Command::Stop);
130    }
131}
132
133/// A folder to watch, and whether the folders inside it are watched too.
134type Watched = (PathBuf, RecursiveMode);
135
136/// What the watcher is set to watch.
137#[derive(Debug, Default, PartialEq)]
138struct Plan {
139    /// The folders that are watched. Each one is there.
140    folders: Vec<Watched>,
141    /// The wanted folders that are not there yet, each with the folder above it that
142    /// is watched in its place.
143    missing: Vec<(PathBuf, PathBuf)>,
144    /// The statuses file the config names.
145    statuses: PathBuf,
146}
147
148struct Worker {
149    root: PathBuf,
150    codes: BTreeMap<String, String>,
151    options: ReadOptions,
152    cache: ReadCache,
153    state: Arc<Mutex<LiveState>>,
154    inbox: Receiver<Command>,
155    outbox: Sender<Command>,
156    on_change: Box<dyn Fn() + Send>,
157    watcher: Option<Debouncer<RecommendedWatcher, RecommendedCache>>,
158    /// What the watcher watches. Empty while it is off.
159    watched: Plan,
160    watching: Arc<AtomicBool>,
161}
162
163impl Worker {
164    fn run(mut self) {
165        self.read();
166        while let Ok(command) = self.inbox.recv() {
167            match command {
168                Command::Refresh => {
169                    self.cache.clear();
170                    self.read();
171                }
172                Command::Changed => self.read(),
173                Command::Options(options) => {
174                    self.options = options;
175                    self.read();
176                }
177                Command::Watch(true) => self.start_watching(),
178                Command::Watch(false) => {
179                    self.watcher = None;
180                    self.watched = Plan::default();
181                    self.watching.store(false, Ordering::Relaxed);
182                }
183                Command::Stop => break,
184            }
185        }
186    }
187
188    fn read(&mut self) {
189        let state = match read_app_cached(&self.root, &self.codes, &self.options, &mut self.cache) {
190            Ok(app) => {
191                // A code is kept once given, also for a module that is gone for a while.
192                self.codes.extend(app.codes());
193                LiveState::Ready(Arc::new(app))
194            }
195            Err(error) => LiveState::Failed(Arc::new(error)),
196        };
197        *self.state.lock().expect("the state is never poisoned") = state;
198        // The modules folder, the statuses file or the coverage report can move when a
199        // config changes, and a wanted folder can appear.
200        if self.watcher.is_some() && self.plan() != self.watched {
201            self.start_watching();
202        }
203        (self.on_change)();
204    }
205
206    /// The statuses file the config names, or the default one before the first read.
207    fn statuses_file(&self) -> PathBuf {
208        match &*self.state.lock().expect("the state is never poisoned") {
209            LiveState::Ready(app) => app.layout.statuses_file.clone(),
210            _ => self.root.join("modules_statuses.json"),
211        }
212    }
213
214    /// What should be watched: the app folder and its config folder for the few files
215    /// Mortise reads there, the whole modules folder, the folders of the statuses file
216    /// and of the coverage report, and git's folder for a new commit or another branch.
217    fn wanted(&self) -> Vec<Watched> {
218        let (modules_dir, report) = match &*self.state.lock().expect("the state is never poisoned")
219        {
220            LiveState::Ready(app) => (
221                app.layout.modules_dir.clone(),
222                app.coverage_report
223                    .as_ref()
224                    .map(|report| report.path.clone()),
225            ),
226            _ => (self.root.join("Modules"), None),
227        };
228        let mut wanted = vec![
229            (self.root.clone(), RecursiveMode::NonRecursive),
230            (self.root.join("config"), RecursiveMode::NonRecursive),
231            (self.root.join(".git"), RecursiveMode::NonRecursive),
232            // A tool that uses libgit2 changes only the refs and this log on a commit.
233            // When `.git` is a file, as in a worktree, this folder is not there and
234            // is not watched.
235            (
236                self.root.join(".git").join("logs"),
237                RecursiveMode::NonRecursive,
238            ),
239            (modules_dir, RecursiveMode::Recursive),
240        ];
241        let statuses = self.statuses_file();
242        if let Some(folder) = statuses.parent() {
243            let covered = wanted.iter().any(|(watched, mode)| {
244                watched == folder
245                    || (*mode == RecursiveMode::Recursive && folder.starts_with(watched))
246            });
247            if !covered {
248                wanted.push((folder.to_owned(), RecursiveMode::NonRecursive));
249            }
250        }
251        if let Some(folder) = report.as_deref().and_then(Path::parent) {
252            wanted.push((folder.to_owned(), RecursiveMode::NonRecursive));
253        }
254        wanted
255    }
256
257    /// What to watch now. A wanted folder that is not there is watched through the
258    /// nearest folder above it, so that its creation is seen.
259    fn plan(&self) -> Plan {
260        let mut plan = Plan {
261            statuses: self.statuses_file(),
262            ..Plan::default()
263        };
264        for (folder, mode) in self.wanted() {
265            let watched = if folder.is_dir() {
266                (folder, mode)
267            } else if folder.exists() {
268                // Not a folder, such as `.git` in a worktree.
269                continue;
270            } else {
271                // When the nearest path above is a file, the folder cannot appear.
272                let Some(above) = folder
273                    .ancestors()
274                    .find(|path| path.exists())
275                    .filter(|path| path.is_dir())
276                else {
277                    continue;
278                };
279                plan.missing.push((folder.clone(), above.to_owned()));
280                (above.to_owned(), RecursiveMode::NonRecursive)
281            };
282            // A folder wanted twice, such as a modules folder set to `config`, is
283            // watched once, with its subfolders when either wants them.
284            match plan
285                .folders
286                .iter_mut()
287                .find(|(folder, _)| *folder == watched.0)
288            {
289                Some((_, mode)) if watched.1 == RecursiveMode::Recursive => *mode = watched.1,
290                Some(_) => {}
291                None => plan.folders.push(watched),
292            }
293        }
294        plan
295    }
296
297    fn start_watching(&mut self) {
298        self.watcher = None;
299        let mut plan = self.plan();
300
301        let outbox = self.outbox.clone();
302        let root = self.root.clone();
303        // The statuses file counts wherever it is, also in `storage`. On macOS the
304        // watcher reports paths without symbolic links, so that form counts too.
305        let real_statuses = plan
306            .statuses
307            .parent()
308            .and_then(real)
309            .zip(plan.statuses.file_name())
310            .map(|(folder, name)| folder.join(name));
311        let statuses: Vec<PathBuf> = std::iter::once(plan.statuses.clone())
312            .chain(real_statuses)
313            .collect();
314        // A missing folder counts when it, or a folder on the way to it, appears.
315        let missing: Vec<(PathBuf, PathBuf)> = plan
316            .missing
317            .iter()
318            .cloned()
319            .chain(
320                plan.missing
321                    .iter()
322                    .filter_map(|(folder, above)| Some((real(folder)?, real(above)?))),
323            )
324            .collect();
325        let appears = move |path: &Path| {
326            missing
327                .iter()
328                .any(|(folder, above)| folder.starts_with(path) && path != above)
329        };
330        let handler = move |result: DebounceEventResult| {
331            let relevant = result.is_ok_and(|events| {
332                events.iter().any(|event| {
333                    event.paths.iter().any(|path| {
334                        statuses.contains(path) || is_relevant(&root, path) || appears(path)
335                    })
336                })
337            });
338            if relevant {
339                let _ = outbox.send(Command::Changed);
340            }
341        };
342        let Ok(mut watcher) = new_debouncer(QUIET, None, handler) else {
343            return;
344        };
345        // Only the folders that are watched are kept, so that a read after a failure
346        // tries again.
347        plan.folders
348            .retain(|(folder, mode)| watcher.watch(folder, *mode).is_ok());
349        self.watched = plan;
350        self.watcher = Some(watcher);
351        self.watching.store(true, Ordering::Relaxed);
352    }
353}
354
355/// A path as the watcher reports it: without symbolic links, which macOS resolves.
356/// The part that is not there yet is kept as it is.
357fn real(path: &Path) -> Option<PathBuf> {
358    let there = path.ancestors().find(|path| path.exists())?;
359    let rest = path.strip_prefix(there).ok()?;
360    Some(std::fs::canonicalize(there).ok()?.join(rest))
361}
362
363/// False for what Mortise never reads and what changes in bulk: installed packages,
364/// logs and caches, and git's own files except the few that change with a commit or
365/// a checkout. Only the part of the path inside the app counts.
366fn is_relevant(root: &Path, path: &Path) -> bool {
367    let inside = path.strip_prefix(root).unwrap_or(path);
368    let mut parts = inside.components().filter_map(|part| match part {
369        Component::Normal(name) => name.to_str(),
370        _ => None,
371    });
372    if inside.starts_with(".git") {
373        // The index is rewritten by every `git status` of every editor: not that.
374        let git: Vec<&str> = parts.skip(1).collect();
375        return matches!(
376            git.as_slice(),
377            ["HEAD" | "COMMIT_EDITMSG" | "ORIG_HEAD" | "packed-refs"] | ["logs", "HEAD"]
378        );
379    }
380    // A coverage report is a file Mortise reads, wherever it is written.
381    if inside
382        .extension()
383        .is_some_and(|extension| extension == "xml")
384    {
385        return true;
386    }
387    !parts.any(|name| matches!(name, "vendor" | "node_modules" | ".git" | "storage"))
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393
394    #[test]
395    fn installed_packages_logs_and_most_git_files_are_not_relevant() {
396        let root = Path::new("/home/storage/shop-api");
397        let relevant = |path: &str| is_relevant(root, &root.join(path));
398        assert!(relevant("modules_statuses.json"));
399        assert!(relevant("Modules/Blog/app/Models/Post.php"));
400        assert!(relevant("build/coverage/clover.xml"));
401        assert!(relevant("storage/coverage/clover.xml"));
402        assert!(!relevant("vendor/composer/installed.json"));
403        assert!(!relevant("Modules/Blog/node_modules/x/index.js"));
404        assert!(!relevant("storage/logs/laravel.log"));
405
406        assert!(relevant(".git/HEAD"));
407        assert!(relevant(".git/COMMIT_EDITMSG"));
408        assert!(relevant(".git/logs/HEAD"));
409        assert!(!relevant(".git/logs/refs/heads/main"));
410        assert!(!relevant(".git/index"));
411        assert!(!relevant(".git/index.lock"));
412        assert!(!relevant(".git/objects/ab/cdef"));
413    }
414}