Skip to main content

crate_plugin_kit/
cache.rs

1//! Install record cache `<plugins>/.plugins.json`.
2//!
3//! This file is for speed and display only, never a source of truth — the source
4//! of truth is always the manifest in each plugin dir. If the cache is lost or
5//! corrupt, `list()` rebuilds from disk.
6
7use std::collections::BTreeMap;
8use std::path::{Path, PathBuf};
9use std::time::{SystemTime, UNIX_EPOCH};
10
11use serde::{Deserialize, Serialize};
12
13use crate::error::KitResult;
14
15/// Current cache schema version.
16pub const CACHE_VERSION: u32 = 1;
17
18/// Contents of `.plugins.json`.
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct Index {
21    /// Schema version.
22    #[serde(rename = "cacheVersion", default = "default_cache_version")]
23    pub cache_version: u32,
24
25    /// Crate name → install record.
26    #[serde(default)]
27    pub plugins: BTreeMap<String, IndexEntry>,
28}
29
30fn default_cache_version() -> u32 {
31    CACHE_VERSION
32}
33
34impl Default for Index {
35    fn default() -> Self {
36        Self {
37            cache_version: CACHE_VERSION,
38            plugins: BTreeMap::new(),
39        }
40    }
41}
42
43/// One install record.
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct IndexEntry {
46    /// Installed version.
47    pub version: String,
48
49    /// ABI version declared by the manifest (for the host's own use).
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub abi: Option<u32>,
52
53    /// Absolute path of the install dir.
54    pub root: PathBuf,
55
56    /// How it was installed.
57    #[serde(default)]
58    pub source: InstallSource,
59
60    /// Install time (Unix seconds). An integer instead of an RFC3339 string, which
61    /// saves a date library dependency.
62    #[serde(rename = "installedAt", default)]
63    pub installed_at: u64,
64}
65
66/// How a plugin got installed.
67#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "kebab-case")]
69pub enum InstallSource {
70    /// Prebuilt artifact downloaded from GitHub Releases.
71    Prebuilt,
72    /// Compiled locally by `cargo build` (the default path).
73    #[default]
74    BuildHost,
75    /// Compiled from a checkout on this machine.
76    ///
77    /// The path is kept because it is what `update` rebuilds from: a plugin that was
78    /// installed from a directory has no registry to look up, and rebuilding the same
79    /// directory is what updating it means.
80    Local {
81        /// The directory that was installed from.
82        path: PathBuf,
83    },
84}
85
86/// Current Unix seconds. Returns 0 when the system time is unavailable — a wrong
87/// timestamp beats a failed install.
88pub fn now_unix() -> u64 {
89    SystemTime::now()
90        .duration_since(UNIX_EPOCH)
91        .map(|d| d.as_secs())
92        .unwrap_or(0)
93}
94
95impl Index {
96    /// Reads the cache. A missing or unparsable file yields an empty index — the
97    /// cache is not a source of truth.
98    pub fn load(path: &Path) -> Self {
99        let Ok(text) = std::fs::read_to_string(path) else {
100            return Self::default();
101        };
102        match serde_json::from_str::<Self>(&text) {
103            Ok(mut idx) => {
104                idx.cache_version = CACHE_VERSION;
105                idx
106            }
107            Err(_) => Self::default(),
108        }
109    }
110
111    /// Writes the cache (atomic replace: write a temp file, then rename).
112    pub fn save(&self, path: &Path) -> KitResult<()> {
113        if let Some(parent) = path.parent() {
114            std::fs::create_dir_all(parent)?;
115        }
116        let text = serde_json::to_string_pretty(self).map_err(|e| {
117            crate::error::KitError::Registry(format!("failed to serialize index: {e}"))
118        })?;
119
120        let tmp = path.with_extension("json.tmp");
121        std::fs::write(&tmp, text)?;
122        std::fs::rename(&tmp, path)?;
123        Ok(())
124    }
125
126    /// Records one entry.
127    pub fn insert(&mut self, crate_name: &str, entry: IndexEntry) {
128        self.plugins.insert(crate_name.to_string(), entry);
129    }
130
131    /// Removes one entry.
132    pub fn remove(&mut self, crate_name: &str) -> Option<IndexEntry> {
133        self.plugins.remove(crate_name)
134    }
135
136    /// Looks up one entry.
137    pub fn get(&self, crate_name: &str) -> Option<&IndexEntry> {
138        self.plugins.get(crate_name)
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    fn entry(version: &str) -> IndexEntry {
147        IndexEntry {
148            version: version.to_string(),
149            abi: Some(1),
150            root: PathBuf::from("some").join("plugin"),
151            source: InstallSource::BuildHost,
152            installed_at: 1_767_225_600,
153        }
154    }
155
156    #[test]
157    fn insert_get_remove_round_trip() {
158        let mut idx = Index::default();
159        assert!(idx.get("a").is_none());
160
161        idx.insert("a", entry("0.1.0"));
162        assert_eq!(idx.get("a").unwrap().version, "0.1.0");
163
164        let removed = idx.remove("a");
165        assert_eq!(removed.unwrap().version, "0.1.0");
166        assert!(idx.get("a").is_none());
167        assert!(idx.remove("a").is_none());
168    }
169
170    #[test]
171    fn save_then_load_round_trips() {
172        let dir = tempfile::tempdir().unwrap();
173        let path = dir.path().join("nested").join(".plugins.json");
174
175        let mut idx = Index::default();
176        idx.insert("myapp-plugin-foo", entry("0.2.0"));
177        idx.save(&path).expect("should be able to write to disk");
178
179        let back = Index::load(&path);
180        assert_eq!(back.cache_version, CACHE_VERSION);
181        let got = back.get("myapp-plugin-foo").unwrap();
182        assert_eq!(got.version, "0.2.0");
183        assert_eq!(got.abi, Some(1));
184        assert_eq!(got.source, InstallSource::BuildHost);
185        assert_eq!(got.installed_at, 1_767_225_600);
186    }
187
188    /// The cache is not a source of truth: a missing file yields an empty index
189    /// rather than an error.
190    #[test]
191    fn a_missing_file_yields_an_empty_index() {
192        let dir = tempfile::tempdir().unwrap();
193        let idx = Index::load(&dir.path().join("nope.json"));
194        assert!(idx.plugins.is_empty());
195        assert_eq!(idx.cache_version, CACHE_VERSION);
196    }
197
198    /// Same as above: a corrupt file is also treated as empty, so it cannot drag
199    /// down the whole `list()`.
200    #[test]
201    fn a_corrupt_file_yields_an_empty_index() {
202        let dir = tempfile::tempdir().unwrap();
203        let path = dir.path().join(".plugins.json");
204        std::fs::write(&path, "{ this is not json").unwrap();
205
206        let idx = Index::load(&path);
207        assert!(idx.plugins.is_empty());
208    }
209
210    /// Older caches may lack the `source` field — it must read back and fall back
211    /// to the default.
212    #[test]
213    fn missing_optional_fields_fall_back() {
214        let dir = tempfile::tempdir().unwrap();
215        let path = dir.path().join(".plugins.json");
216        std::fs::write(&path, r#"{"plugins":{"a":{"version":"0.1.0","root":"r"}}}"#).unwrap();
217
218        let idx = Index::load(&path);
219        let got = idx.get("a").unwrap();
220        assert_eq!(got.source, InstallSource::BuildHost);
221        assert_eq!(got.abi, None);
222        assert_eq!(got.installed_at, 0);
223    }
224
225    /// Saving writes a temp file and then renames, so no `.tmp` leftovers should
226    /// remain.
227    #[test]
228    fn save_leaves_no_temp_file_behind() {
229        let dir = tempfile::tempdir().unwrap();
230        let path = dir.path().join(".plugins.json");
231
232        let mut idx = Index::default();
233        idx.insert("a", entry("0.1.0"));
234        idx.save(&path).unwrap();
235
236        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
237            .unwrap()
238            .filter_map(|e| e.ok())
239            .map(|e| e.file_name().to_string_lossy().into_owned())
240            .filter(|n| n.ends_with(".tmp"))
241            .collect();
242        assert!(
243            leftovers.is_empty(),
244            "left a temp file behind: {leftovers:?}"
245        );
246    }
247
248    #[test]
249    fn now_unix_is_after_the_epoch() {
250        assert!(now_unix() > 1_600_000_000);
251    }
252}