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, Copy, 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}
76
77/// Current Unix seconds. Returns 0 when the system time is unavailable — a wrong
78/// timestamp beats a failed install.
79pub fn now_unix() -> u64 {
80    SystemTime::now()
81        .duration_since(UNIX_EPOCH)
82        .map(|d| d.as_secs())
83        .unwrap_or(0)
84}
85
86impl Index {
87    /// Reads the cache. A missing or unparsable file yields an empty index — the
88    /// cache is not a source of truth.
89    pub fn load(path: &Path) -> Self {
90        let Ok(text) = std::fs::read_to_string(path) else {
91            return Self::default();
92        };
93        match serde_json::from_str::<Self>(&text) {
94            Ok(mut idx) => {
95                idx.cache_version = CACHE_VERSION;
96                idx
97            }
98            Err(_) => Self::default(),
99        }
100    }
101
102    /// Writes the cache (atomic replace: write a temp file, then rename).
103    pub fn save(&self, path: &Path) -> KitResult<()> {
104        if let Some(parent) = path.parent() {
105            std::fs::create_dir_all(parent)?;
106        }
107        let text = serde_json::to_string_pretty(self).map_err(|e| {
108            crate::error::KitError::Registry(format!("failed to serialize index: {e}"))
109        })?;
110
111        let tmp = path.with_extension("json.tmp");
112        std::fs::write(&tmp, text)?;
113        std::fs::rename(&tmp, path)?;
114        Ok(())
115    }
116
117    /// Records one entry.
118    pub fn insert(&mut self, crate_name: &str, entry: IndexEntry) {
119        self.plugins.insert(crate_name.to_string(), entry);
120    }
121
122    /// Removes one entry.
123    pub fn remove(&mut self, crate_name: &str) -> Option<IndexEntry> {
124        self.plugins.remove(crate_name)
125    }
126
127    /// Looks up one entry.
128    pub fn get(&self, crate_name: &str) -> Option<&IndexEntry> {
129        self.plugins.get(crate_name)
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    fn entry(version: &str) -> IndexEntry {
138        IndexEntry {
139            version: version.to_string(),
140            abi: Some(1),
141            root: PathBuf::from("some").join("plugin"),
142            source: InstallSource::BuildHost,
143            installed_at: 1_767_225_600,
144        }
145    }
146
147    #[test]
148    fn insert_get_remove_round_trip() {
149        let mut idx = Index::default();
150        assert!(idx.get("a").is_none());
151
152        idx.insert("a", entry("0.1.0"));
153        assert_eq!(idx.get("a").unwrap().version, "0.1.0");
154
155        let removed = idx.remove("a");
156        assert_eq!(removed.unwrap().version, "0.1.0");
157        assert!(idx.get("a").is_none());
158        assert!(idx.remove("a").is_none());
159    }
160
161    #[test]
162    fn save_then_load_round_trips() {
163        let dir = tempfile::tempdir().unwrap();
164        let path = dir.path().join("nested").join(".plugins.json");
165
166        let mut idx = Index::default();
167        idx.insert("myapp-plugin-foo", entry("0.2.0"));
168        idx.save(&path).expect("should be able to write to disk");
169
170        let back = Index::load(&path);
171        assert_eq!(back.cache_version, CACHE_VERSION);
172        let got = back.get("myapp-plugin-foo").unwrap();
173        assert_eq!(got.version, "0.2.0");
174        assert_eq!(got.abi, Some(1));
175        assert_eq!(got.source, InstallSource::BuildHost);
176        assert_eq!(got.installed_at, 1_767_225_600);
177    }
178
179    /// The cache is not a source of truth: a missing file yields an empty index
180    /// rather than an error.
181    #[test]
182    fn a_missing_file_yields_an_empty_index() {
183        let dir = tempfile::tempdir().unwrap();
184        let idx = Index::load(&dir.path().join("nope.json"));
185        assert!(idx.plugins.is_empty());
186        assert_eq!(idx.cache_version, CACHE_VERSION);
187    }
188
189    /// Same as above: a corrupt file is also treated as empty, so it cannot drag
190    /// down the whole `list()`.
191    #[test]
192    fn a_corrupt_file_yields_an_empty_index() {
193        let dir = tempfile::tempdir().unwrap();
194        let path = dir.path().join(".plugins.json");
195        std::fs::write(&path, "{ this is not json").unwrap();
196
197        let idx = Index::load(&path);
198        assert!(idx.plugins.is_empty());
199    }
200
201    /// Older caches may lack the `source` field — it must read back and fall back
202    /// to the default.
203    #[test]
204    fn missing_optional_fields_fall_back() {
205        let dir = tempfile::tempdir().unwrap();
206        let path = dir.path().join(".plugins.json");
207        std::fs::write(&path, r#"{"plugins":{"a":{"version":"0.1.0","root":"r"}}}"#).unwrap();
208
209        let idx = Index::load(&path);
210        let got = idx.get("a").unwrap();
211        assert_eq!(got.source, InstallSource::BuildHost);
212        assert_eq!(got.abi, None);
213        assert_eq!(got.installed_at, 0);
214    }
215
216    /// Saving writes a temp file and then renames, so no `.tmp` leftovers should
217    /// remain.
218    #[test]
219    fn save_leaves_no_temp_file_behind() {
220        let dir = tempfile::tempdir().unwrap();
221        let path = dir.path().join(".plugins.json");
222
223        let mut idx = Index::default();
224        idx.insert("a", entry("0.1.0"));
225        idx.save(&path).unwrap();
226
227        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
228            .unwrap()
229            .filter_map(|e| e.ok())
230            .map(|e| e.file_name().to_string_lossy().into_owned())
231            .filter(|n| n.ends_with(".tmp"))
232            .collect();
233        assert!(
234            leftovers.is_empty(),
235            "left a temp file behind: {leftovers:?}"
236        );
237    }
238
239    #[test]
240    fn now_unix_is_after_the_epoch() {
241        assert!(now_unix() > 1_600_000_000);
242    }
243}