Skip to main content

ridx_format/workspace/
cache_resolver.rs

1/*
2 * rust-intelligence — Ultra-fast, zero-memory code intelligence for Rust
3 * Copyright (c) 2026 Alexander Panasenko
4 *
5 * Contact: alex@prod.codes
6 * Author: https://prod.codes/about/
7 * Project: https://github.com/alex09x/rust-intelligence
8 * SPDX-License-Identifier: MIT OR Apache-2.0
9 */
10
11//! Resilient cache lookup for external dependency index shards.
12//!
13//! When a workspace manifest references a dependency object path or unit key from an older
14//! compiler driver run that no longer exists on disk, `CacheObjectResolver` discovers candidate
15//! shards in `cache_dir/objects/` strictly matching the crate's name, version, and 64-bit generation digest.
16
17use crate::reader::IndexReader;
18use crate::workspace::manifest::DependencyShardInfo;
19use std::collections::HashMap;
20use std::fs;
21use std::path::PathBuf;
22
23#[derive(Debug, Clone)]
24#[allow(dead_code)]
25struct CachedObjectInfo {
26    version: String,
27    generation: String,
28    unit_key: String,
29    path: PathBuf,
30}
31
32/// Resolves dependency index shard files from primary paths or the global cache directory.
33pub struct CacheObjectResolver {
34    cache_dir: PathBuf,
35    cache_map: Option<HashMap<String, Vec<CachedObjectInfo>>>,
36}
37
38impl CacheObjectResolver {
39    /// Creates a new resolver backed by the specified global cache directory.
40    pub fn new(cache_dir: PathBuf) -> Self {
41        Self { cache_dir, cache_map: None }
42    }
43
44    /// Resolves an existing `.ridx` shard file for the given dependency shard.
45    ///
46    /// Resolution order:
47    /// 1. Exact `dep.object_path` if it exists on disk.
48    /// 2. `cache_object_path(cache_dir, dep.unit_key)` if it exists on disk.
49    /// 3. Resilient fallback: scans `cache_dir/objects/*/*.ridx` for shards matching `dep.name`,
50    ///    strictly requiring exact version and generation match.
51    pub fn resolve(&mut self, dep: &DependencyShardInfo) -> Option<PathBuf> {
52        let obj_path = PathBuf::from(&dep.object_path);
53        if obj_path.is_file() {
54            return Some(obj_path);
55        }
56
57        let fallback = crate::format::cache_object_path(&self.cache_dir, &dep.unit_key);
58        if fallback.is_file() {
59            return Some(fallback);
60        }
61
62        self.resolve_resilient(dep)
63    }
64
65    fn resolve_resilient(&mut self, dep: &DependencyShardInfo) -> Option<PathBuf> {
66        let expected_gen = match dep.generation.as_deref() {
67            Some(g) if !g.is_empty() => g,
68            _ => return None,
69        };
70
71        if self.cache_map.is_none() {
72            self.populate_cache_map();
73        }
74
75        let map = self.cache_map.as_ref()?;
76        let candidates = map.get(&dep.name)?;
77
78        // Invariant & Design Decision:
79        // When exact object_path and unit_key fail to resolve (e.g. following a rebuild of
80        // ridx-driver or toolchain bump where driver hash shifts across unit_keys), resolve_resilient
81        // discovers candidate shards matching exact crate name, semantic version, and generation digest.
82        //
83        // While unit_key additionally hashes active Cargo features, compilation target, and driver
84        // version, `generation` is a 64-bit content digest over source file contents.
85        // In LSP and code navigation workflows, reusing a source-identical shard of the same version
86        // across targets or features is an accepted compromise to preserve cross-crate intelligence
87        // and avoid full dependency re-indexing when the driver or toolchain updates;
88        // steps 1 and 2 are tried first.
89        candidates.iter().find(|c| c.version == dep.version && c.generation == expected_gen).map(|c| c.path.clone())
90    }
91
92    fn populate_cache_map(&mut self) {
93        let mut map: HashMap<String, Vec<CachedObjectInfo>> = HashMap::new();
94        let objects_dir = self.cache_dir.join("objects");
95
96        if let Ok(entries) = fs::read_dir(&objects_dir) {
97            for entry in entries.flatten() {
98                let sub = entry.path();
99                if sub.is_dir() {
100                    if let Ok(files) = fs::read_dir(&sub) {
101                        for f in files.flatten() {
102                            let p = f.path();
103                            if p.extension().and_then(|s| s.to_str()) == Some("ridx") {
104                                if let Ok(reader) = IndexReader::open(&p) {
105                                    let name = reader.crate_name().to_string();
106                                    if !name.is_empty() {
107                                        map.entry(name).or_default().push(CachedObjectInfo {
108                                            version: reader.crate_version().to_string(),
109                                            generation: reader.generation().to_string(),
110                                            unit_key: reader.unit_key().to_string(),
111                                            path: p,
112                                        });
113                                    }
114                                }
115                            }
116                        }
117                    }
118                }
119            }
120        }
121
122        self.cache_map = Some(map);
123    }
124}