Skip to main content

sokf_core/cache/
hint.rs

1//! This module holds the hint, the list of the paths that changed
2//! (CACHE-1_AC-23). It also builds the tree for a run with a hint. A caller
3//! that knows which paths changed passes them in, such as `--changed` or a
4//! language server's file watcher. The run then lists again only those
5//! paths, by the walk's rules, and uses the store's rows for every other
6//! file and directory. A hinted directory stands for every path under it.
7//! The next run without a hint finds any change that the hint leaves out.
8
9use std::{
10    collections::{BTreeMap, BTreeSet},
11    fs,
12    sync::Arc,
13};
14
15use super::{Cache, sync::kind_of};
16use crate::{
17    Config, RepoPath, RepoRoot, Result, Stat, Tree,
18    walk::{self, Keep, WalkedDir, WalkedFile, innermost},
19};
20
21impl Cache {
22    /// `set_hint` records the paths that a caller knows changed, so that the
23    /// next sync reads the file metadata of only those paths.
24    pub fn set_hint(&self, paths: Vec<RepoPath>) {
25        *self.hint.borrow_mut() = Some(paths);
26    }
27
28    /// `drop_hint` forgets the paths that a caller said changed, so that the
29    /// next sync walks the repository.
30    pub fn drop_hint(&self) {
31        *self.hint.borrow_mut() = None;
32        self.missed.set(false);
33    }
34
35    /// `note_missing` records that the run read a file that the walk lists
36    /// and found it removed. In a run with a hint on a filled store, the
37    /// hint left that removal out (CACHE-1_AC-53).
38    pub fn note_missing(&self) {
39        if self.hint.borrow().is_some() && !self.is_fresh() {
40            self.missed.set(true);
41        }
42    }
43
44    /// `missed` returns whether this run's hint left out a removed file
45    /// that the run read.
46    pub fn missed(&self) -> bool {
47        self.missed.get()
48    }
49
50    /// `hint` returns the paths that a caller said changed, or `None` when
51    /// the caller gave none.
52    pub fn hint(&self) -> Option<Vec<RepoPath>> {
53        self.hint.borrow().clone()
54    }
55
56    /// `tree_from_store` builds the tree that a run with a hint works on. It
57    /// starts from the store's files and directories. It drops what the
58    /// store recorded at or under each hinted path, and lists those paths
59    /// again as the walk lists them. It adds each directory above a hinted
60    /// path that the walk lists, up to its root. It removes each directory
61    /// above a hinted path that is no longer a directory. When no check has
62    /// filled the store, it walks the repository instead.
63    // sokf-implements: CACHE-1_AC-23
64    // sokf-implements: CACHE-1_AC-28
65    // sokf-implements: CACHE-1_AC-46
66    // sokf-implements: CACHE-1_AC-47
67    // sokf-implements: CACHE-1_AC-49
68    // sokf-implements: CACHE-1_AC-50
69    // sokf-implements: CLI-4_AC-21
70    pub fn tree_from_store(
71        &self,
72        root: &RepoRoot,
73        config: &Config,
74        changed: &[RepoPath],
75    ) -> Result<Tree> {
76        if self.is_fresh() {
77            return walk::collect(root, config);
78        }
79        let roots = config.roots.clone();
80        let hints = scopes(changed);
81        // A hint that holds a whole root lists as much as a walk does.
82        if covers_root(&hints, &roots) {
83            return walk::collect(root, config);
84        }
85        let mut files = self.stored_files();
86        drop_scopes(&mut files, &hints);
87        let mut dirs = self.stored_dirs();
88        let hint_keys = keys(&hints);
89        dirs.retain(|d, _| !in_scope(&hint_keys, d.as_str()));
90
91        let mut seen = BTreeSet::new();
92        let mut found_dirs = Vec::new();
93        let mut outside = BTreeSet::new();
94        for path in &hints {
95            if innermost(&roots, path).is_none() {
96                outside.insert(path.clone());
97                continue;
98            }
99            let listed =
100                walk::list_under_root(root, &roots, path, &mut seen, &mut files, &mut found_dirs)?;
101            let mut dir = path.parent();
102            while let Some(d) = dir {
103                let Some(owner) = innermost(&roots, &d) else {
104                    break;
105                };
106                if listed {
107                    dirs.entry(d.clone()).or_insert(owner);
108                } else if is_walked_dir(root, &roots[owner], &d) {
109                    break;
110                } else {
111                    dirs.remove(&d);
112                }
113                dir = d.parent();
114            }
115        }
116        if !outside.is_empty() {
117            // The walk outside the roots descends only into the directories
118            // above a hinted path and into the hinted paths themselves.
119            let above: BTreeSet<RepoPath> = outside
120                .iter()
121                .flat_map(|h| std::iter::successors(h.parent(), RepoPath::parent))
122                .collect();
123            let scope: Vec<String> = outside.iter().map(ToString::to_string).collect();
124            let keep: Keep =
125                Arc::new(move |p: &RepoPath| above.contains(p) || in_scope(&scope, p.as_str()));
126            let outside_keys = keys(&outside);
127            files.extend(
128                walk::walk_outside(root, config, Some(keep))?
129                    .into_iter()
130                    .filter(|f| in_scope(&outside_keys, f.path.as_str())),
131            );
132        }
133        for d in found_dirs {
134            dirs.insert(d.path, d.root);
135        }
136        let mut tree = Tree::new(
137            root.clone(),
138            roots,
139            files,
140            dirs.into_iter()
141                .map(|(path, root)| WalkedDir { path, root })
142                .collect(),
143        );
144        tree.registered_count = config.registered_count;
145        Ok(tree)
146    }
147
148    /// `stored_files` returns the files that the store recorded, with their
149    /// kinds, roots, and stats.
150    fn stored_files(&self) -> Vec<WalkedFile> {
151        let mut files = Vec::new();
152        if let Ok(mut stmt) = self
153            .conn()
154            .prepare("SELECT path, kind, root, len, mtime FROM files ORDER BY path")
155            && let Ok(mut rows) = stmt.query([])
156        {
157            while let Ok(Some(r)) = rows.next() {
158                let Some(path) = r
159                    .get_ref(0)
160                    .ok()
161                    .and_then(|v| v.as_str().ok())
162                    .and_then(RepoPath::parse)
163                else {
164                    continue;
165                };
166                let (Ok(kind), Ok(owner), Ok(len), Ok(mtime)) = (
167                    r.get::<_, u8>(1),
168                    r.get::<_, Option<usize>>(2),
169                    r.get::<_, u64>(3),
170                    r.get::<_, Option<i64>>(4),
171                ) else {
172                    continue;
173                };
174                files.push(WalkedFile {
175                    path,
176                    root: owner,
177                    kind: kind_of(kind),
178                    stat: Stat { len, mtime },
179                });
180            }
181        }
182        files
183    }
184
185    /// `stored_dirs` returns the directories that the store recorded, each
186    /// with the index of its root.
187    pub(super) fn stored_dirs(&self) -> BTreeMap<RepoPath, usize> {
188        self.conn()
189            .rows("SELECT path, root FROM dirs", [], |r| {
190                Ok((r.get::<_, String>(0)?, r.get::<_, usize>(1)?))
191            })
192            .into_iter()
193            .filter_map(|(path, owner)| Some((RepoPath::parse(&path)?, owner)))
194            .collect()
195    }
196}
197
198/// `scopes` returns the hinted paths in path order, each once, without a
199/// path that lies under another hinted path, because the other path's
200/// scope already covers it.
201pub(super) fn scopes(changed: &[RepoPath]) -> BTreeSet<RepoPath> {
202    let all: BTreeSet<&RepoPath> = changed.iter().collect();
203    all.iter()
204        .filter(|p| !std::iter::successors(p.parent(), RepoPath::parent).any(|a| all.contains(&a)))
205        .map(|p| (*p).clone())
206        .collect()
207}
208
209/// `covers_root` returns whether a knowledge root is one of `hints` or
210/// lies under one.
211pub(super) fn covers_root(hints: &BTreeSet<RepoPath>, roots: &[RepoPath]) -> bool {
212    let keys = keys(hints);
213    roots.iter().any(|r| in_scope(&keys, r.as_str()))
214}
215
216/// `in_scope` returns whether `path` is one of `hints`, which are sorted,
217/// or lies under one. It looks up `path` and each directory above it by
218/// binary search, without allocating.
219fn in_scope<S: AsRef<str>>(hints: &[S], path: &str) -> bool {
220    let mut p = path;
221    loop {
222        if hints.binary_search_by(|h| h.as_ref().cmp(p)).is_ok() {
223            return true;
224        }
225        match p.rfind('/') {
226            Some(0) if p.len() > 1 => p = "/",
227            Some(i) if i > 0 => p = &p[..i],
228            _ => return false,
229        }
230    }
231}
232
233/// `keys` returns the hinted paths as strings, in the order of `hints`.
234fn keys(hints: &BTreeSet<RepoPath>) -> Vec<&str> {
235    hints.iter().map(RepoPath::as_str).collect()
236}
237
238/// `drop_scopes` removes from `files`, which is sorted by path, each file
239/// at or under one of `hints`. It finds each hint's files by binary search,
240/// because a run with a hint holds the rows of every file in the store.
241fn drop_scopes(files: &mut Vec<WalkedFile>, hints: &BTreeSet<RepoPath>) {
242    let mut ranges: Vec<(usize, usize)> = Vec::new();
243    for h in hints {
244        if let Ok(i) = files.binary_search_by(|f| f.path.cmp(h)) {
245            ranges.push((i, i + 1));
246        }
247        let (low, high) = under(h);
248        let start = files.partition_point(|f| f.path.as_str() < low.as_str());
249        let end = files.partition_point(|f| f.path.as_str() < high.as_str());
250        if start < end {
251            ranges.push((start, end));
252        }
253    }
254    if ranges.is_empty() {
255        return;
256    }
257    ranges.sort_unstable();
258    let (mut index, mut next) = (0, 0);
259    files.retain(|_| {
260        while next < ranges.len() && ranges[next].1 <= index {
261            next += 1;
262        }
263        let dropped = next < ranges.len() && ranges[next].0 <= index;
264        index += 1;
265        !dropped
266    });
267}
268
269/// `under` returns the bounds of the paths that lie strictly under `path`
270/// in string order: each such path is at least the first bound and less
271/// than the second.
272pub(super) fn under(path: &RepoPath) -> (String, String) {
273    let low = if path.as_str() == "/" {
274        "/".to_string()
275    } else {
276        format!("{path}/")
277    };
278    // `0` is the character after `/`, so the second bound follows every
279    // path that begins with the first.
280    let high = format!("{}0", &low[..low.len() - 1]);
281    (low, high)
282}
283
284/// `is_walked_dir` returns whether the walk of the root `owner` reaches
285/// the directory `dir`: `dir` and each directory between it and `owner`
286/// are directories, not links.
287fn is_walked_dir(root: &RepoRoot, owner: &RepoPath, dir: &RepoPath) -> bool {
288    std::iter::successors(Some(dir.clone()), RepoPath::parent)
289        .take_while(|d| d != owner && d.starts_with(owner))
290        .all(|d| fs::symlink_metadata(d.to_fs(root)).is_ok_and(|m| m.is_dir()))
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    fn p(s: &str) -> RepoPath {
298        RepoPath::parse(s).unwrap()
299    }
300
301    #[test]
302    fn scopes_drop_a_path_under_another() {
303        let got = scopes(&[p("/a/b.md"), p("/a-b"), p("/a"), p("/a"), p("/c")]);
304        assert_eq!(got, [p("/a"), p("/a-b"), p("/c")].into());
305        assert!(in_scope(&keys(&got), "/a/b/c"));
306        assert!(!in_scope(&keys(&got), "/a-c"));
307        assert!(in_scope(&["/"], "/a/b"));
308        assert!(covers_root(&got, &[p("/a/k")]));
309        assert!(!covers_root(&got, &[p("/k")]));
310    }
311
312    #[test]
313    fn drop_scopes_removes_each_hinted_path_and_the_paths_under_it() {
314        let file = |s: &str| WalkedFile {
315            path: p(s),
316            root: None,
317            kind: crate::FileKind::Candidate,
318            stat: Stat::default(),
319        };
320        let mut files: Vec<WalkedFile> =
321            ["/a", "/a-b", "/a-b/c", "/a/b", "/a/c/d", "/a0", "/b", "/c"]
322                .into_iter()
323                .map(file)
324                .collect();
325        drop_scopes(&mut files, &[p("/a"), p("/c")].into());
326        let left: Vec<&str> = files.iter().map(|f| f.path.as_str()).collect();
327        assert_eq!(left, ["/a-b", "/a-b/c", "/a0", "/b"]);
328    }
329
330    #[test]
331    fn under_bounds_the_paths_below_a_directory() {
332        let (low, high) = under(&p("/a"));
333        for inside in ["/a/b", "/a/b/c", "/a/~"] {
334            assert!(low.as_str() <= inside && inside < high.as_str(), "{inside}");
335        }
336        for outside in ["/a", "/a-b", "/a0", "/ab", "/b"] {
337            assert!(
338                !(low.as_str() <= outside && outside < high.as_str()),
339                "{outside}"
340            );
341        }
342        assert_eq!(under(&p("/")), ("/".to_string(), "0".to_string()));
343    }
344}