Skip to main content

subspace_core/path/
cache.rs

1//! The `PATH` that worked last time, and where each tool was found.
2//!
3//! The file (`path-cache.json` beside the product's `state.json`) holds only
4//! a schema version, the save time, the source, the `PATH` folders and tool
5//! paths. It never holds network or proxy variables, other environment
6//! values or tokens. [`super::apply`] saves it when the `PATH` is known good:
7//! after a login-shell capture, or after a start from a terminal.
8//!
9//! The GUI, the service and the CLI can write at the same time. Each write
10//! goes to a temporary file that is renamed over the old one, so the file
11//! stays valid; one process can overwrite a tool path another just saved.
12//! That lost update is accepted: the next successful lookup saves it again.
13
14use std::collections::BTreeMap;
15use std::path::{Path, PathBuf};
16use std::sync::{Mutex, OnceLock};
17
18use chrono::{DateTime, Utc};
19use serde::{Deserialize, Serialize};
20
21use crate::log::{Level, Logger};
22
23/// The schema this build reads and writes. Another value is a foreign file.
24pub(super) const CACHE_VERSION: &str = "1";
25
26/// Where a saved `PATH` came from.
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(tag = "kind", rename_all = "snake_case")]
29pub enum CacheSource {
30    LoginShell {
31        shell: PathBuf,
32    },
33    Terminal,
34    /// Windows: the machine and user `Path` registry values.
35    Registry,
36}
37
38/// The cache file.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct PathCache {
41    pub version: String,
42    pub saved_at: DateTime<Utc>,
43    pub source: CacheSource,
44    /// The `PATH` folders, in order.
45    pub path: Vec<PathBuf>,
46    /// The last absolute path where each tool was found, as found: no
47    /// symbolic link is resolved.
48    #[serde(default)]
49    pub tools: BTreeMap<String, PathBuf>,
50}
51
52/// A saved `PATH` that [`super::apply`] used because the shell failed.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct CachedPath {
55    pub saved_at: DateTime<Utc>,
56    pub source: CacheSource,
57    pub version: String,
58    /// How many saved folders were appended.
59    pub added: usize,
60}
61
62/// A saved tool path that a lookup tried after `PATH` had no such tool.
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct CachedTool {
65    pub path: PathBuf,
66    /// When the cache file was saved; the tool was found then or later.
67    pub saved_at: DateTime<Utc>,
68    /// Whether the file still exists and is executable, so it was used.
69    pub usable: bool,
70}
71
72/// The cache in `file`, or `None` when it is missing, unreadable, not
73/// JSON, of another schema or of the wrong shape. Such a file is replaced
74/// at the next good save.
75/// A relative tool path in the file is dropped: it depends on a working
76/// directory that is not known.
77pub fn read_cache(file: &Path) -> Option<PathCache> {
78    let bytes = std::fs::read(file).ok()?;
79    let mut cache = serde_json::from_slice::<PathCache>(&bytes)
80        .ok()
81        .filter(|cache| cache.version == CACHE_VERSION)?;
82    cache.tools.retain(|_, path| path.is_absolute());
83    Some(cache)
84}
85
86/// Write `cache` to `file` through a private temporary file in the same
87/// folder and a rename.
88pub(super) fn write_cache(file: &Path, cache: &PathCache) -> std::io::Result<()> {
89    use std::io::Write as _;
90
91    let directory = file.parent().unwrap_or(Path::new("."));
92    std::fs::create_dir_all(directory)?;
93    let bytes = serde_json::to_vec_pretty(cache).map_err(std::io::Error::other)?;
94    let mut temporary = tempfile::NamedTempFile::new_in(directory)?;
95    crate::private_file::set_owner_only(temporary.path())?;
96    temporary.write_all(&bytes)?;
97    temporary.as_file().sync_all()?;
98    temporary.persist(file).map_err(|error| error.error)?;
99    Ok(())
100}
101
102/// The cache file of this process and the tool paths it holds.
103struct Active {
104    file: PathBuf,
105    tools: Mutex<BTreeMap<String, PathBuf>>,
106}
107
108static ACTIVE: OnceLock<Active> = OnceLock::new();
109
110/// Use `file` for tool lookups in this process from now on.
111pub(super) fn activate(file: PathBuf, cache: Option<&PathCache>) {
112    let tools = cache.map(|cache| cache.tools.clone()).unwrap_or_default();
113    let _ = ACTIVE.set(Active {
114        file,
115        tools: Mutex::new(tools),
116    });
117}
118
119/// Save `found` for `name` when it differs from the saved path. Only a file
120/// that [`super::apply`] saved gets tool paths; errors are ignored.
121pub(super) fn remember_tool(name: &str, found: &Path) {
122    let Some(active) = ACTIVE.get() else {
123        return;
124    };
125    let Ok(mut tools) = active.tools.lock() else {
126        return;
127    };
128    if tools.get(name).is_some_and(|saved| saved == found) {
129        return;
130    }
131    if remember_in(&active.file, name, found).is_ok() {
132        tools.insert(name.to_string(), found.to_path_buf());
133    }
134}
135
136/// Re-read `file`, set the tool path and write it back.
137pub(super) fn remember_in(file: &Path, name: &str, found: &Path) -> std::io::Result<()> {
138    let Some(mut cache) = read_cache(file) else {
139        return Err(std::io::Error::other("no path cache"));
140    };
141    cache.tools.insert(name.to_string(), found.to_path_buf());
142    write_cache(file, &cache)
143}
144
145/// The saved path of `name` in `cache`, with whether `usable` accepts it.
146pub(super) fn cached_tool_in(
147    cache: &PathCache,
148    name: &str,
149    usable: fn(&Path) -> bool,
150) -> Option<CachedTool> {
151    let path = cache.tools.get(name)?;
152    Some(CachedTool {
153        path: path.clone(),
154        saved_at: cache.saved_at,
155        usable: usable(path),
156    })
157}
158
159/// The saved path of `name` when it is still usable; a use is logged.
160pub(super) fn cached_tool(name: &str) -> Option<PathBuf> {
161    let active = ACTIVE.get()?;
162    let tool = read_cached_tool(&active.file, name)?;
163    record_tool_use(name, tool)
164}
165
166fn record_tool_use(name: &str, tool: CachedTool) -> Option<PathBuf> {
167    if !tool.usable {
168        return None;
169    }
170    let path = tool.path.display().to_string();
171    Logger::new("path").record(
172        Level::Info,
173        "cached tool path used",
174        &[("tool", name), ("path", &path)],
175    );
176    Some(tool.path)
177}
178
179/// Read the active cached tool without recording or logging its use.
180pub(super) fn cached_tool_readonly(name: &str) -> Option<PathBuf> {
181    let active = ACTIVE.get()?;
182    cached_tool_readonly_in(&active.file, name)
183}
184
185pub(super) fn cached_tool_readonly_in(file: &Path, name: &str) -> Option<PathBuf> {
186    let tool = read_cached_tool(file, name)?;
187    tool.usable.then_some(tool.path)
188}
189
190fn read_cached_tool(file: &Path, name: &str) -> Option<CachedTool> {
191    let cache = read_cache(file)?;
192    cached_tool_in(&cache, name, super::lookup::usable_cached)
193}
194
195#[cfg(test)]
196mod tests;