Skip to main content

rust_meth_lib/probe/
cache.rs

1//!
2//! ## Probe caching
3//!
4//! Probes are cached in-process by `(type_name, effective_deps, probe_kind)`. A cache hit skips
5//! temp-dir creation and file writes entirely. The cache holds an [`Arc`] to each `CachedProbe`;
6//! when all references are dropped the directory is deleted automatically. Call
7//! [`cache_entries`] to inspect what is currently cached, and [`clear_probe_cache`] to evict
8//! everything immediately.
9//!
10//! When the [`Probe`] instance goes out of scope, its [`Drop`] implementation automatically deletes
11//! the entire temporary directory and its contents from the disk, unless the entry is still held
12//! by the cache.
13
14use std::collections::HashMap;
15use std::fs;
16use std::path::{Path, PathBuf};
17use std::sync::{Arc, Mutex, OnceLock};
18
19// -- Hashing --
20//
21// Simple FNV-1a hash
22
23pub(super) fn fnv1a(data: &str) -> u64 {
24    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
25    for byte in data.bytes() {
26        hash ^= u64::from(byte);
27        hash = hash.wrapping_mul(0x0100_0000_01b3);
28    }
29    hash
30}
31
32/// Computes the persistent cache key for a probe configuration.
33///
34/// Returns a 16-character hex string derived from `type_name`, `effective_deps`,
35/// `method_name`, the `rust-analyzer` version, and the `rust-meth-lib` version.
36/// Any change to these inputs produces a different key, so upgrades to either
37/// binary automatically invalidate stale cache entries.
38#[must_use]
39pub fn cache_key_hash(
40    type_name: &str,
41    effective_deps: Option<&str>,
42    method_name: Option<&str>,
43    ra_version: &str,
44) -> String {
45    let canonical = format!(
46        "type={}\ndeps={}\nmethod={}\nra={}\nlib={}",
47        type_name,
48        effective_deps.unwrap_or(""),
49        method_name.unwrap_or(""),
50        ra_version,
51        env!("CARGO_PKG_VERSION"),
52    );
53    format!("{:016x}", fnv1a(&canonical))
54}
55
56// ── Persistent cache ──────────────────────────────────────────────────────────
57
58/// Metadata stored alongside each persistent probe directory.
59#[derive(Debug, serde::Serialize, serde::Deserialize)]
60pub(super) struct ProbeMeta {
61    pub(super) type_name: String,
62    pub(super) effective_deps: Option<String>,
63    pub(super) method_name: Option<String>,
64    pub(super) ra_version: String,
65    pub(super) lib_version: String,
66    pub(super) dot_line: u32,
67    pub(super) dot_col: u32,
68}
69
70/// Returns the root directory of the persistent probe cache.
71///
72/// Respects `$XDG_CACHE_HOME` if set, otherwise falls back to `~/.cache`.
73/// The full path is `$XDG_CACHE_HOME/rust-meth/probes/`.
74#[must_use]
75pub fn persistent_cache_dir() -> PathBuf {
76    let base = std::env::var_os("XDG_CACHE_HOME").map_or_else(
77        || {
78            std::env::var_os("HOME")
79                .map_or_else(std::env::temp_dir, PathBuf::from)
80                .join(".cache")
81        },
82        PathBuf::from,
83    );
84    base.join("rust-meth").join("probes")
85}
86
87/// Public view of a single persistent cache entry.
88#[derive(Debug, Clone)]
89pub struct PersistentCacheEntry {
90    /// The Rust type that was probed.
91    pub type_name: String,
92    /// The effective TOML dependency string, if any.
93    pub deps: Option<String>,
94    /// `None` for completion probes; `Some(method_name)` for definition probes.
95    pub method_name: Option<String>,
96    /// The `rust-analyzer` version this entry was created with.
97    pub ra_version: String,
98    /// The `rust-meth-lib` version this entry was created with.
99    pub lib_version: String,
100    /// Absolute path to the cached probe directory on disk.
101    pub dir: PathBuf,
102}
103
104/// Returns all entries currently in the persistent probe cache.
105///
106/// Reads `meta.json` from each subdirectory of [`persistent_cache_dir`].
107/// Entries whose `meta.json` is missing or malformed are silently skipped.
108#[must_use]
109pub fn persistent_cache_entries() -> Vec<PersistentCacheEntry> {
110    let dir = persistent_cache_dir();
111    let Ok(read_dir) = fs::read_dir(&dir) else {
112        return Vec::new();
113    };
114    read_dir
115        .filter_map(|entry| {
116            let entry = entry.ok()?;
117            let probe_dir = entry.path();
118            let meta_path = probe_dir.join("meta.json");
119            let meta_bytes = fs::read(&meta_path).ok()?;
120            let meta: ProbeMeta = serde_json::from_slice(&meta_bytes).ok()?;
121            Some(PersistentCacheEntry {
122                type_name: meta.type_name,
123                deps: meta.effective_deps,
124                method_name: meta.method_name,
125                ra_version: meta.ra_version,
126                lib_version: meta.lib_version,
127                dir: probe_dir,
128            })
129        })
130        .collect()
131}
132
133/// Removes all entries from the persistent probe cache.
134///
135/// Deletes the entire [`persistent_cache_dir`] and its contents.
136///
137/// # Errors
138///
139/// Returns an error if the directory cannot be removed.
140pub fn clear_persistent_cache() -> std::io::Result<()> {
141    let dir = persistent_cache_dir();
142    if dir.exists() {
143        fs::remove_dir_all(&dir)?;
144    }
145    Ok(())
146}
147
148pub(super) fn load_persistent_probe(
149    type_name: &str,
150    effective_deps: Option<&str>,
151    method_name: Option<&str>,
152    ra_version: &str,
153) -> Option<(PathBuf, PathBuf, u32, u32)> {
154    let hash = cache_key_hash(type_name, effective_deps, method_name, ra_version);
155    let probe_dir = persistent_cache_dir().join(&hash);
156    if !probe_dir.exists() {
157        return None;
158    }
159    let meta_bytes = fs::read(probe_dir.join("meta.json")).ok()?;
160    let meta: ProbeMeta = serde_json::from_slice(&meta_bytes).ok()?;
161    let src_path = probe_dir.join("src").join("main.rs");
162    if !src_path.exists() || !probe_dir.join("Cargo.toml").exists() {
163        return None;
164    }
165    Some((probe_dir, src_path, meta.dot_line, meta.dot_col))
166}
167
168pub(super) fn save_persistent_probe(
169    probe_dir: &Path,
170    type_name: &str,
171    effective_deps: Option<&str>,
172    method_name: Option<&str>,
173    ra_version: &str,
174    dot_line: u32,
175    dot_col: u32,
176) {
177    let hash = cache_key_hash(type_name, effective_deps, method_name, ra_version);
178    let cache_dir = persistent_cache_dir().join(&hash);
179    let cache_src_dir = cache_dir.join("src");
180
181    let save = || -> std::io::Result<()> {
182        fs::create_dir_all(&cache_src_dir)?;
183        fs::copy(probe_dir.join("Cargo.toml"), cache_dir.join("Cargo.toml"))?;
184        fs::copy(
185            probe_dir.join("src").join("main.rs"),
186            cache_src_dir.join("main.rs"),
187        )?;
188        let meta = ProbeMeta {
189            type_name: type_name.to_string(),
190            effective_deps: effective_deps.map(str::to_owned),
191            method_name: method_name.map(str::to_owned),
192            ra_version: ra_version.to_string(),
193            lib_version: env!("CARGO_PKG_VERSION").to_string(),
194            dot_line,
195            dot_col,
196        };
197        fs::write(
198            cache_dir.join("meta.json"),
199            serde_json::to_vec_pretty(&meta)?,
200        )?;
201        Ok(())
202    };
203
204    if let Err(e) = save()
205        && std::env::var("RUST_METH_DEBUG").is_ok()
206    {
207        eprintln!("[debug] failed to save persistent probe: {e}");
208    }
209}
210
211/// Queries the `rust-analyzer` binary for its version string.
212#[must_use]
213pub fn ra_version(ra_path: &Path) -> String {
214    std::process::Command::new(ra_path)
215        .arg("--version")
216        .output()
217        .ok()
218        .and_then(|o| String::from_utf8(o.stdout).ok())
219        .map(|s| s.trim().to_string())
220        .filter(|s| !s.is_empty())
221        .unwrap_or_else(|| "unknown".to_string())
222}
223
224// -- In-process Cache types --
225
226// Identifies a unique probe configuration for cache lookup.
227#[derive(Debug, Clone, Hash, Eq, PartialEq)]
228pub(super) struct CacheKey {
229    pub(super) type_name: String,
230    /// Effective deps after `infer_dep`, so `serde_json::Value` with `deps=None`
231    /// and with `deps=Some(r#"serde_json = "*""#)` share the same cache entry.
232    pub(super) effective_deps: Option<String>,
233    /// `None` for completion probes, `Some(method_name)` for definition probes.
234    pub(super) method_name: Option<String>,
235}
236
237/// The heap-allocated probe data kept alive by the cache [`Arc`].
238///
239/// Deletes its directory when the last [`Arc`] is dropped (i.e. when both
240/// the cache entry and the [`Probe`] borrowing it are gone).
241#[derive(Debug)]
242pub(super) struct CachedProbe {
243    pub(super) dir: PathBuf,
244    pub(super) src_path: PathBuf,
245    pub(super) dot_line: u32,
246    pub(super) dot_col: u32,
247    pub(super) owned: bool,
248}
249
250impl Drop for CachedProbe {
251    fn drop(&mut self) {
252        if self.owned {
253            let _ = fs::remove_dir_all(&self.dir);
254        }
255    }
256}
257
258/// Public view of a single cache entry, returned by [`cache_entries`].
259#[derive(Debug, Clone)]
260pub struct CacheEntry {
261    /// The Rust type that was probed (e.g. `"Vec<u8>"`).
262    pub type_name: String,
263    /// The effective TOML dependency string, if any.
264    pub deps: Option<String>,
265    /// `None` for completion probes; `Some(method_name)` for definition probes.
266    pub method_name: Option<String>,
267    /// Absolute path to the cached probe directory on disk.
268    pub dir: PathBuf,
269}
270
271// -- Global cache --
272
273type Cache = Mutex<HashMap<CacheKey, Arc<CachedProbe>>>;
274
275pub(super) fn global_cache() -> &'static Cache {
276    static CACHE: OnceLock<Cache> = OnceLock::new();
277    CACHE.get_or_init(|| Mutex::new(HashMap::new()))
278}
279
280/// Returns a snapshot of all probe directories currently held in the cache.
281///
282/// ## Panics
283///
284/// A poisoned mutex means the thread panicked while holding the lock, leaving
285/// the cache in an unknown state.
286#[must_use]
287pub fn cache_entries() -> Vec<CacheEntry> {
288    let cache = global_cache().lock().expect("probe cache lock poisoned");
289    cache
290        .iter()
291        .map(|(key, probe)| CacheEntry {
292            type_name: key.type_name.clone(),
293            deps: key.effective_deps.clone(),
294            method_name: key.method_name.clone(),
295            dir: probe.dir.clone(),
296        })
297        .collect()
298}
299
300/// Evicts all entries from the probe cache.
301///
302/// Each entry's directory is deleted when its [`Arc`] reference count reaches
303/// zero immediately if no `Probe` is currently borrowing the entry, or
304/// when the last borrowing `Probe` is dropped otherwise.
305///
306/// ## Panics
307///
308/// A poisoned mutex means the thread panicked while holding the lock, leaving
309/// the cache in an unknown state.
310pub fn clear_probe_cache() {
311    let mut cache = global_cache().lock().expect("probe cache lock poisoned");
312    cache.clear();
313}
314#[cfg(test)]
315#[allow(clippy::unwrap_used)]
316mod tests {
317    use super::*;
318    use crate::probe::Probe;
319    use serial_test::serial;
320
321    #[test]
322    #[serial]
323    fn cache_hit_returns_same_directory() {
324        clear_probe_cache();
325        let p1 = Probe::new_with_deps("Vec<u8>", None).unwrap();
326        let p2 = Probe::new_with_deps("Vec<u8>", None).unwrap();
327        assert_eq!(p1.dir, p2.dir, "cache hit should reuse the same directory");
328    }
329
330    #[test]
331    #[serial]
332    fn cache_miss_different_type_names() {
333        clear_probe_cache();
334        let p1 = Probe::new_with_deps("Vec<u8>", None).unwrap();
335        let p2 = Probe::new_with_deps("String", None).unwrap();
336        assert_ne!(p1.dir, p2.dir);
337    }
338
339    #[test]
340    #[serial]
341    fn cache_miss_different_deps() {
342        clear_probe_cache();
343        let p1 = Probe::new_with_deps("serde_json::Value", Some(r#"serde_json = "1.0""#)).unwrap();
344        let p2 = Probe::new_with_deps("serde_json::Value", Some(r#"serde_json = "2.0""#)).unwrap();
345        assert_ne!(p1.dir, p2.dir);
346    }
347
348    #[test]
349    #[serial]
350    fn cache_entries_reflects_current_cache() {
351        clear_probe_cache();
352        let _p1 = Probe::new_with_deps("Vec<u8>", None).unwrap();
353        let _p2 = Probe::new_with_deps("String", None).unwrap();
354        let entries = cache_entries();
355        let names: Vec<&str> = entries.iter().map(|e| e.type_name.as_str()).collect();
356        assert!(names.contains(&"Vec<u8>"));
357        assert!(names.contains(&"String"));
358    }
359
360    #[test]
361    #[serial]
362    fn clear_probe_cache_evicts_all_entries() {
363        let _p = Probe::new_with_deps("Vec<u8>", None).unwrap();
364        clear_probe_cache();
365        assert!(cache_entries().is_empty());
366    }
367
368    #[test]
369    #[serial]
370    fn directory_persists_while_cache_holds_arc() {
371        clear_probe_cache();
372        let dir = {
373            let p = Probe::new_with_deps("Vec<u8>", None).unwrap();
374            p.dir.clone()
375        };
376        {
377            let _guard = global_cache().lock().expect("probe cache lock poisoned");
378            assert!(dir.exists(), "dir should persist while cache holds the Arc");
379        }
380        clear_probe_cache();
381        assert!(
382            !dir.exists(),
383            "dir should be deleted after cache is cleared"
384        );
385    }
386
387    // -- persistent cache --
388
389    #[test]
390    fn persistent_cache_dir_ends_with_rust_meth_probes() {
391        let dir = persistent_cache_dir();
392        assert!(dir.ends_with("rust-meth/probes"));
393    }
394
395    #[test]
396    fn cache_key_hash_differs_by_type() {
397        let h1 = cache_key_hash("Vec<u8>", None, None, "rust-analyzer 1.0");
398        let h2 = cache_key_hash("String", None, None, "rust-analyzer 1.0");
399        assert_ne!(h1, h2);
400    }
401
402    #[test]
403    fn cache_key_hash_differs_by_ra_version() {
404        let h1 = cache_key_hash("Vec<u8>", None, None, "rust-analyzer 1.0");
405        let h2 = cache_key_hash("Vec<u8>", None, None, "rust-analyzer 2.0");
406        assert_ne!(h1, h2);
407    }
408
409    #[test]
410    fn cache_key_hash_differs_by_deps() {
411        let h1 = cache_key_hash(
412            "serde_json::Value",
413            Some(r#"serde_json = "1.0""#),
414            None,
415            "ra",
416        );
417        let h2 = cache_key_hash(
418            "serde_json::Value",
419            Some(r#"serde_json = "2.0""#),
420            None,
421            "ra",
422        );
423        assert_ne!(h1, h2);
424    }
425
426    #[test]
427    fn meta_json_round_trips() {
428        let meta = ProbeMeta {
429            type_name: "Vec<u8>".to_string(),
430            effective_deps: None,
431            method_name: None,
432            ra_version: "rust-analyzer 1.80.0".to_string(),
433            lib_version: "0.4.0".to_string(),
434            dot_line: 11,
435            dot_col: 7,
436        };
437        let json = serde_json::to_vec_pretty(&meta).unwrap();
438        let back: ProbeMeta = serde_json::from_slice(&json).unwrap();
439        assert_eq!(back.type_name, "Vec<u8>");
440        assert_eq!(back.dot_line, 11);
441        assert_eq!(back.dot_col, 7);
442        assert_eq!(back.ra_version, "rust-analyzer 1.80.0");
443        assert!(back.effective_deps.is_none());
444    }
445}