Skip to main content

surjection_core/skills/
hash_cache.rs

1//! Content summaries of skill folders, cached by their file listing (#3,
2//! #9: the app scans unmanaged folders on focus and watcher events).
3//!
4//! The key is the folder's path and, for every file below it (nested
5//! `.git` left out, as [`read_folder`] leaves it out), its relative path,
6//! size and modification time. The listing costs metadata only; a folder
7//! whose listing is unchanged is not read again. A folder holding a link
8//! is never cached (what it points to can change without the listing
9//! changing). The listing is taken before the content is read, so a change
10//! during the read shows as a new listing next time.
11//!
12//! An edit that keeps a file's size and modification time is not seen.
13//! The cache is for listings only: adopt reads every folder again and
14//! compares it with the store copy under the store lock before replacing
15//! anything.
16
17use std::collections::HashMap;
18use std::path::{Path, PathBuf};
19use std::sync::Mutex;
20use std::time::SystemTime;
21
22use crate::error::CoreError;
23use crate::fs::Fs;
24use crate::skills::{
25    SKILL_FILE, SkillFiles, confine, content_hash, files_size, frontmatter, read_folder,
26};
27
28/// What a scan needs of a folder's content.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Summary {
31    /// [`content_hash`] of the files.
32    pub hash: String,
33    /// `description` from its `SKILL.md`.
34    pub description: Option<String>,
35    pub bytes: u64,
36    pub has_skill_file: bool,
37}
38
39impl Summary {
40    pub fn of(files: &SkillFiles) -> Self {
41        let description = files.get(SKILL_FILE).and_then(|text| {
42            frontmatter::parse(&String::from_utf8_lossy(text))
43                .ok()
44                .flatten()
45                .and_then(|fm| fm.description().map(str::to_owned))
46        });
47        Self {
48            hash: content_hash(files),
49            description,
50            bytes: files_size(files),
51            has_skill_file: files.contains_key(SKILL_FILE),
52        }
53    }
54}
55
56/// One file of a listing: relative path, size, modification time.
57type ListedFile = (String, u64, Option<SystemTime>);
58
59/// Summaries of folders by path, valid while their listing is unchanged.
60/// Machine-local and in memory: the app keeps one for its process.
61#[derive(Debug, Default)]
62pub struct FolderHashCache {
63    entries: Mutex<HashMap<PathBuf, (Vec<ListedFile>, Summary)>>,
64}
65
66impl FolderHashCache {
67    pub fn new() -> Self {
68        Self::default()
69    }
70
71    /// The summary of the folder `dir`: from the cache when its listing is
72    /// the one cached, else read ([`read_folder`], with its errors) and
73    /// cached.
74    pub fn summary(&self, fs: &dyn Fs, dir: &Path) -> Result<Summary, CoreError> {
75        let listed = listing(fs, dir);
76        if let Some(listed) = &listed
77            && let Some((known, summary)) = self.lock().get(dir)
78            && known == listed
79        {
80            return Ok(summary.clone());
81        }
82        let summary = Summary::of(&read_folder(fs, dir)?);
83        let mut entries = self.lock();
84        match listed {
85            Some(listed) => {
86                entries.insert(dir.to_path_buf(), (listed, summary.clone()));
87            }
88            None => {
89                entries.remove(dir);
90            }
91        }
92        Ok(summary)
93    }
94
95    /// Number of folders cached.
96    pub fn len(&self) -> usize {
97        self.lock().len()
98    }
99
100    pub fn is_empty(&self) -> bool {
101        self.len() == 0
102    }
103
104    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<PathBuf, (Vec<ListedFile>, Summary)>> {
105        self.entries
106            .lock()
107            .unwrap_or_else(std::sync::PoisonError::into_inner)
108    }
109}
110
111/// The files below `dir`, sorted; `None` when the folder cannot be listed
112/// or holds a link (then it is read every time).
113fn listing(fs: &dyn Fs, dir: &Path) -> Option<Vec<ListedFile>> {
114    fn walk(dir: &Path, prefix: &str, out: &mut Vec<ListedFile>) -> Option<()> {
115        for item in std::fs::read_dir(dir).ok()? {
116            let item = item.ok()?;
117            let name = item.file_name().to_string_lossy().into_owned();
118            if name == ".git" {
119                continue;
120            }
121            let relative = if prefix.is_empty() {
122                name
123            } else {
124                format!("{prefix}/{name}")
125            };
126            // The entry's own metadata (a link is not followed); on
127            // Windows it comes with the listing, without another call.
128            let meta = item.metadata().ok()?;
129            if meta.file_type().is_symlink() {
130                return None;
131            }
132            if meta.is_dir() {
133                walk(&item.path(), &relative, out)?;
134            } else {
135                out.push((relative, meta.len(), meta.modified().ok()));
136            }
137        }
138        Some(())
139    }
140    confine(fs, dir).ok()?;
141    if std::fs::symlink_metadata(dir)
142        .ok()?
143        .file_type()
144        .is_symlink()
145    {
146        return None;
147    }
148    let mut out = Vec::new();
149    walk(dir, "", &mut out)?;
150    out.sort();
151    Some(out)
152}