ifc_lite_processing/result_cache/
config.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! [`ResultCacheConfig`], its mode, its test hooks and the default location.
6
7use std::path::PathBuf;
8
9/// What a [`ResultCache`](super::ResultCache) may do. Off unless a caller opts in.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum CacheMode {
12    /// Call [`process`](crate::process) directly; no hashing, no file access.
13    #[default]
14    Off,
15    /// Replay entries; never create, write or touch anything.
16    ReadOnly,
17    /// Replay entries; store new results; refresh last-use times; evict.
18    ReadWrite,
19}
20
21/// Where and how much. Defaults: off, the platform cache directory, 10 GiB
22/// per directory, 1 GiB per entry. The limits are policy choices, not
23/// measured optima.
24#[non_exhaustive]
25#[derive(Debug, Clone)]
26pub struct ResultCacheConfig {
27    pub mode: CacheMode,
28    /// `None`: [`default_directory`]. Entries go in a `result-v1` directory
29    /// beneath it.
30    pub directory: Option<PathBuf>,
31    pub max_bytes: u64,
32    pub max_entry_bytes: u64,
33    /// Free space a write must leave on the cache's filesystem (default 1 GiB).
34    pub min_free_bytes: u64,
35    /// Test hook: mixed into the engine identity to stand for a different
36    /// build or entry format. Empty in production.
37    #[doc(hidden)]
38    pub engine_salt: Vec<u8>,
39    /// Test hook: called with the batch number after each live batch, so a
40    /// test can act deterministically in the middle of a pass. `None` in
41    /// production; the cached pass then runs with no sink at all.
42    #[doc(hidden)]
43    pub pass_hook: Option<PassHook>,
44}
45
46/// See [`ResultCacheConfig::pass_hook`].
47#[doc(hidden)]
48#[derive(Clone)]
49pub struct PassHook(pub std::sync::Arc<dyn Fn(usize) + Send + Sync>);
50
51impl std::fmt::Debug for PassHook {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        f.write_str("PassHook")
54    }
55}
56
57/// Calls the [`PassHook`] after each batch; no other event.
58pub(super) struct HookSink<'a>(pub(super) &'a PassHook, pub(super) usize);
59
60impl crate::ProcessingSink for HookSink<'_> {
61    fn on_batch(&mut self, _meshes: &[crate::MeshData], _processed: usize, _total: usize) {
62        self.1 += 1;
63        (self.0 .0)(self.1);
64    }
65}
66
67impl Default for ResultCacheConfig {
68    fn default() -> Self {
69        Self {
70            mode: CacheMode::Off,
71            directory: None,
72            max_bytes: 10 << 30,
73            max_entry_bytes: 1 << 30,
74            min_free_bytes: 1 << 30,
75            engine_salt: Vec::new(),
76            pass_hook: None,
77        }
78    }
79}
80
81impl ResultCacheConfig {
82    pub fn mode(mut self, mode: CacheMode) -> Self {
83        self.mode = mode;
84        self
85    }
86    pub fn directory(mut self, directory: impl Into<PathBuf>) -> Self {
87        self.directory = Some(directory.into());
88        self
89    }
90    pub fn max_bytes(mut self, bytes: u64) -> Self {
91        self.max_bytes = bytes;
92        self
93    }
94    pub fn max_entry_bytes(mut self, bytes: u64) -> Self {
95        self.max_entry_bytes = bytes;
96        self
97    }
98    pub fn min_free_bytes(mut self, bytes: u64) -> Self {
99        self.min_free_bytes = bytes;
100        self
101    }
102    #[doc(hidden)]
103    pub fn engine_salt(mut self, salt: &[u8]) -> Self {
104        self.engine_salt = salt.to_vec();
105        self
106    }
107    #[doc(hidden)]
108    pub fn pass_hook(mut self, hook: impl Fn(usize) + Send + Sync + 'static) -> Self {
109        self.pass_hook = Some(PassHook(std::sync::Arc::new(hook)));
110        self
111    }
112}
113
114/// The per-user default root: `IFC_LITE_CACHE_DIR` if set, else
115/// `$XDG_CACHE_HOME/ifc-lite/native` or `~/.cache/ifc-lite/native` (Linux and
116/// other Unix), `~/Library/Caches/ifc-lite/native` (macOS),
117/// `%LOCALAPPDATA%\ifc-lite\native` (Windows).
118pub fn default_directory() -> Option<PathBuf> {
119    let env_dir = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()).map(PathBuf::from);
120    if let Some(dir) = env_dir("IFC_LITE_CACHE_DIR") {
121        return Some(dir);
122    }
123    let base = if cfg!(windows) {
124        env_dir("LOCALAPPDATA")
125    } else if cfg!(target_os = "macos") {
126        env_dir("HOME").map(|h| h.join("Library").join("Caches"))
127    } else {
128        env_dir("XDG_CACHE_HOME").filter(|p| p.is_absolute()).or_else(|| env_dir("HOME").map(|h| h.join(".cache")))
129    };
130    base.map(|b| b.join("ifc-lite").join("native"))
131}
132