Skip to main content

egui_pop_tokens/
cache.rs

1//! A cache of compiled files: what is read from a file at run time and
2//! costly to compile (a YAML token file, say) is compiled once and kept,
3//! never next to its source.
4//!
5//! The store is not specific to tokens. An entry is the compiled form of
6//! one source file, made by one compiler; it is keyed by the source's
7//! path, a hash of its contents and the compiler's version:
8//!
9//! - a **hit** (same path, same contents, same compiler version) gives
10//!   the compiled bytes back;
11//! - a **miss** or a **stale** entry (the source changed, or the compiler
12//!   is another version) gives nothing: the caller compiles the source
13//!   and puts the result, which replaces the stale entry.
14//!
15//! Nothing here is fatal (ADR 0003): an entry that cannot be read is a
16//! miss, and one that cannot be written is an error the caller reports
17//! while going on with what it compiled.
18//!
19//! The entries live under `<dir>/<compiler>/`, one file per source path.
20//! The directory is the platform's cache directory under the
21//! application's id ([`Cache::for_app`], [`platform_dir`]):
22//!
23//! | | Cache |
24//! |---|---|
25//! | Linux and BSD | `$XDG_CACHE_HOME/<app>/egui-pop` (`~/.cache/<app>/egui-pop`) |
26//! | macOS | `~/Library/Caches/<app>/egui-pop` |
27//! | Windows | `%LOCALAPPDATA%\<app>\cache\egui-pop` |
28//!
29//! egui-pop does not know the application's id, so the cache is off
30//! until the application gives one: [`set_default`] at start-up for every
31//! file read at run time ([`KitData::load`](crate::kit::KitData::load),
32//! [`Themes::add_path`](crate::Themes::add_path)), or a [`Cache`] passed
33//! where a reader takes one. [`Cache::at`] puts it elsewhere (a test's
34//! temporary directory), [`Cache::off`] turns it off.
35//!
36//! ```
37//! use egui_pop_tokens::cache::{Cache, Compiler};
38//!
39//! let dir = std::env::temp_dir().join(format!("egui-pop-cache-doc-{}", std::process::id()));
40//! let cache = Cache::at(&dir);
41//! let upper = Compiler { name: "upper", version: "1" };
42//! let source = dir.join("notes.txt");
43//! assert_eq!(cache.get(&upper, &source, b"hello"), None);
44//! cache.put(&upper, &source, b"hello", b"HELLO").unwrap();
45//! assert_eq!(cache.get(&upper, &source, b"hello").as_deref(), Some(&b"HELLO"[..]));
46//! // The source changed: stale.
47//! assert_eq!(cache.get(&upper, &source, b"hello!"), None);
48//! # std::fs::remove_dir_all(&dir).ok();
49//! ```
50
51use std::fmt;
52use std::path::{Path, PathBuf};
53use std::sync::RwLock;
54
55/// What made an entry: its name (a folder under the cache, so letters,
56/// digits, `-`, `_` and `.`) and its version. An entry made by another
57/// version is stale. A compiler raises its version whenever what it
58/// writes changes.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub struct Compiler<'a> {
61    pub name: &'a str,
62    pub version: &'a str,
63}
64
65/// Where compiled files are kept, or nowhere (off).
66#[derive(Clone, Debug, Default, PartialEq, Eq)]
67pub struct Cache {
68    dir: Option<PathBuf>,
69}
70
71/// An entry that could not be written: the source was compiled all the
72/// same, and is compiled again next time.
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub struct CacheError {
75    /// The entry's file.
76    pub entry: PathBuf,
77    pub message: String,
78}
79
80impl fmt::Display for CacheError {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        write!(
83            f,
84            "cannot write the cache entry `{}`: {}",
85            self.entry.display(),
86            self.message
87        )
88    }
89}
90
91impl std::error::Error for CacheError {}
92
93/// The first line of an entry: the store's format, then the compiler and
94/// the source it was made from.
95const MAGIC: &str = "egui-pop-cache/1";
96
97impl Cache {
98    /// No cache: nothing is read or written.
99    pub const fn off() -> Cache {
100        Cache { dir: None }
101    }
102
103    /// A cache in a directory of one's choosing (created when an entry is
104    /// first written).
105    pub fn at(dir: impl Into<PathBuf>) -> Cache {
106        Cache {
107            dir: Some(dir.into()),
108        }
109    }
110
111    /// The cache of an application, in the platform's cache directory
112    /// under its id ([`platform_dir`]); off when the platform gives none.
113    pub fn for_app(app_id: &str) -> Cache {
114        Cache {
115            dir: platform_dir(app_id),
116        }
117    }
118
119    /// The cache's directory; none when it is off.
120    pub fn dir(&self) -> Option<&Path> {
121        self.dir.as_deref()
122    }
123
124    /// Whether entries are read and written.
125    pub fn is_on(&self) -> bool {
126        self.dir.is_some()
127    }
128
129    /// The file holding a compiler's entry for a source (none when the
130    /// cache is off). A relative source path is taken from the current
131    /// directory.
132    pub fn entry_path(&self, compiler: &Compiler<'_>, source: &Path) -> Option<PathBuf> {
133        let dir = self.dir.as_ref()?;
134        let source = std::path::absolute(source).unwrap_or_else(|_| source.to_path_buf());
135        let key = hash(source.as_os_str().as_encoded_bytes());
136        Some(
137            dir.join(folder_name(compiler.name))
138                .join(format!("{key:032x}")),
139        )
140    }
141
142    /// The compiled form of a source, if the cache holds one made from
143    /// these contents by this version of the compiler. Anything else (no
144    /// entry, an unreadable one, a stale one) is none.
145    pub fn get(&self, compiler: &Compiler<'_>, source: &Path, contents: &[u8]) -> Option<Vec<u8>> {
146        let path = self.entry_path(compiler, source)?;
147        let mut bytes = std::fs::read(path).ok()?;
148        let end = bytes.iter().position(|b| *b == b'\n')?;
149        if bytes[..end] != *header(compiler, contents).as_bytes() {
150            return None;
151        }
152        bytes.drain(..=end);
153        Some(bytes)
154    }
155
156    /// Keeps the compiled form of a source, replacing what the cache held
157    /// for it. Written to a temporary file then renamed, so a reader never
158    /// sees half an entry. Off, it does nothing.
159    pub fn put(
160        &self,
161        compiler: &Compiler<'_>,
162        source: &Path,
163        contents: &[u8],
164        compiled: &[u8],
165    ) -> Result<(), CacheError> {
166        let Some(path) = self.entry_path(compiler, source) else {
167            return Ok(());
168        };
169        let failed = |e: std::io::Error| CacheError {
170            entry: path.clone(),
171            message: e.to_string(),
172        };
173        if let Some(parent) = path.parent() {
174            std::fs::create_dir_all(parent).map_err(failed)?;
175        }
176        let mut bytes = header(compiler, contents).into_bytes();
177        bytes.push(b'\n');
178        bytes.extend_from_slice(compiled);
179        let tmp = path.with_extension(format!("tmp{}", std::process::id()));
180        std::fs::write(&tmp, &bytes).map_err(failed)?;
181        std::fs::rename(&tmp, &path).map_err(|e| {
182            std::fs::remove_file(&tmp).ok();
183            failed(e)
184        })
185    }
186}
187
188fn header(compiler: &Compiler<'_>, contents: &[u8]) -> String {
189    format!(
190        "{MAGIC} {} {} {:032x} {}",
191        folder_name(compiler.name),
192        compiler.version.replace(char::is_whitespace, "_"),
193        hash(contents),
194        contents.len()
195    )
196}
197
198/// A compiler's name as a folder: anything but letters, digits, `-`, `_`
199/// and `.` becomes `_`.
200fn folder_name(name: &str) -> String {
201    let clean: String = name
202        .chars()
203        .map(|c| {
204            if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.') {
205                c
206            } else {
207                '_'
208            }
209        })
210        .collect();
211    match clean.trim_matches('.') {
212        "" => "_".into(),
213        _ => clean,
214    }
215}
216
217/// FNV-1a, 128 bits: stable across builds and platforms, so an entry
218/// written by one build is found by the next (a cache, not a defence:
219/// whoever can write the source can write the cache).
220fn hash(bytes: &[u8]) -> u128 {
221    const OFFSET: u128 = 0x6c62_272e_07bb_0142_62b8_2175_6295_c58d;
222    const PRIME: u128 = 0x0000_0000_0100_0000_0000_0000_0000_013b;
223    bytes
224        .iter()
225        .fold(OFFSET, |h, b| (h ^ u128::from(*b)).wrapping_mul(PRIME))
226}
227
228/// The cache directory for an application, read from the environment
229/// `env` gives (see the module); none when the variables it needs are
230/// missing.
231///
232/// ```
233/// let dir = egui_pop_tokens::cache::platform_dir_with("demo", |name| match name {
234///     "XDG_CACHE_HOME" => Some("/cache".into()),
235///     _ => None,
236/// });
237/// if cfg!(all(unix, not(target_os = "macos"))) {
238///     assert_eq!(dir, Some("/cache/demo/egui-pop".into()));
239/// }
240/// ```
241pub fn platform_dir_with(app_id: &str, env: impl Fn(&str) -> Option<String>) -> Option<PathBuf> {
242    let absolute = |v: Option<String>| v.map(PathBuf::from).filter(|p| p.is_absolute());
243    let base = if cfg!(windows) {
244        absolute(env("LOCALAPPDATA"))?.join(app_id).join("cache")
245    } else if cfg!(target_os = "macos") {
246        absolute(env("HOME"))?.join("Library/Caches").join(app_id)
247    } else {
248        match absolute(env("XDG_CACHE_HOME")) {
249            Some(p) => p,
250            None => absolute(env("HOME"))?.join(".cache"),
251        }
252        .join(app_id)
253    };
254    Some(base.join("egui-pop"))
255}
256
257/// The cache directory for an application (see the module).
258pub fn platform_dir(app_id: &str) -> Option<PathBuf> {
259    platform_dir_with(app_id, |name| std::env::var(name).ok())
260}
261
262static DEFAULT: RwLock<Option<Cache>> = RwLock::new(None);
263
264/// Sets the cache the readers taking none use, for the whole process
265/// (an application calls it once at start-up, with
266/// [`Cache::for_app`]).
267pub fn set_default(cache: Cache) {
268    *DEFAULT.write().unwrap_or_else(|e| e.into_inner()) = Some(cache);
269}
270
271/// The cache the readers taking none use: what [`set_default`] set, off
272/// before.
273pub fn default() -> Cache {
274    DEFAULT
275        .read()
276        .unwrap_or_else(|e| e.into_inner())
277        .clone()
278        .unwrap_or_default()
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    const C1: Compiler<'static> = Compiler {
286        name: "test",
287        version: "1",
288    };
289
290    fn temp(name: &str) -> PathBuf {
291        let dir =
292            std::env::temp_dir().join(format!("egui-pop-cache-{name}-{}", std::process::id()));
293        std::fs::remove_dir_all(&dir).ok();
294        dir
295    }
296
297    #[test]
298    fn a_hit_needs_the_same_path_contents_and_version() {
299        let dir = temp("key");
300        let cache = Cache::at(&dir);
301        let a = dir.join("a.yaml");
302        cache.put(&C1, &a, b"x", b"compiled").unwrap();
303        assert_eq!(cache.get(&C1, &a, b"x").as_deref(), Some(&b"compiled"[..]));
304        assert_eq!(cache.get(&C1, &a, b"y"), None, "changed contents");
305        assert_eq!(
306            cache.get(&C1, &dir.join("b.yaml"), b"x"),
307            None,
308            "other path"
309        );
310        let c2 = Compiler { version: "2", ..C1 };
311        assert_eq!(cache.get(&c2, &a, b"x"), None, "other version");
312        // A new entry replaces the stale one: one file per source.
313        cache.put(&c2, &a, b"x", b"two").unwrap();
314        assert_eq!(cache.get(&c2, &a, b"x").as_deref(), Some(&b"two"[..]));
315        assert_eq!(cache.get(&C1, &a, b"x"), None);
316        assert_eq!(std::fs::read_dir(dir.join("test")).unwrap().count(), 1);
317        std::fs::remove_dir_all(&dir).ok();
318    }
319
320    #[test]
321    fn off_reads_and_writes_nothing() {
322        let cache = Cache::off();
323        assert!(!cache.is_on());
324        assert_eq!(cache.put(&C1, Path::new("/a"), b"x", b"y"), Ok(()));
325        assert_eq!(cache.get(&C1, Path::new("/a"), b"x"), None);
326    }
327
328    #[test]
329    fn an_unwritable_cache_says_so() {
330        let dir = temp("unwritable");
331        std::fs::create_dir_all(&dir).unwrap();
332        let file = dir.join("file");
333        std::fs::write(&file, "").unwrap();
334        // Under a file: no folder can be made there.
335        let cache = Cache::at(file.join("cache"));
336        let err = cache.put(&C1, &dir.join("a"), b"x", b"y").unwrap_err();
337        assert!(err.to_string().contains("cannot write"), "{err}");
338        assert_eq!(cache.get(&C1, &dir.join("a"), b"x"), None);
339        std::fs::remove_dir_all(&dir).ok();
340    }
341
342    #[test]
343    fn a_damaged_entry_is_a_miss() {
344        let dir = temp("damaged");
345        let cache = Cache::at(&dir);
346        let a = dir.join("a");
347        cache.put(&C1, &a, b"x", b"y").unwrap();
348        std::fs::write(cache.entry_path(&C1, &a).unwrap(), "garbage").unwrap();
349        assert_eq!(cache.get(&C1, &a, b"x"), None);
350        std::fs::remove_dir_all(&dir).ok();
351    }
352
353    #[test]
354    fn compiler_names_are_folder_names() {
355        assert_eq!(folder_name("tokens"), "tokens");
356        assert_eq!(folder_name("../x y"), ".._x_y");
357        assert_eq!(folder_name(".."), "_");
358    }
359
360    #[test]
361    fn the_platform_dir_is_under_the_app_id() {
362        let dir = platform_dir_with("org.example.App", |name| match name {
363            "HOME" => Some("/home/u".into()),
364            "LOCALAPPDATA" => Some("C:\\Users\\u\\AppData\\Local".into()),
365            _ => None,
366        });
367        let dir = dir.expect("a home is enough");
368        assert!(dir.ends_with("egui-pop"));
369        assert!(dir.to_string_lossy().contains("org.example.App"));
370        assert_eq!(platform_dir_with("a", |_| None), None);
371        assert_eq!(
372            platform_dir_with("a", |_| Some("relative".into())),
373            None,
374            "a relative directory is not trusted"
375        );
376    }
377}