Skip to main content

crate_plugin_kit/
cache.rs

1//! 安装记录缓存 `<plugins>/.plugins.json`。
2//!
3//! 这个文件是**加速与展示用**,不是事实来源 —— 事实来源永远是每个插件目录里的
4//! manifest。缓存丢了、坏了,`list()` 会从磁盘重建。
5
6use std::collections::BTreeMap;
7use std::path::{Path, PathBuf};
8use std::time::{SystemTime, UNIX_EPOCH};
9
10use serde::{Deserialize, Serialize};
11
12use crate::error::KitResult;
13
14/// 当前缓存 schema 版本。
15pub const CACHE_VERSION: u32 = 1;
16
17/// `.plugins.json` 的内容。
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct Index {
20    /// schema 版本。
21    #[serde(rename = "cacheVersion", default = "default_cache_version")]
22    pub cache_version: u32,
23
24    /// crate 名 → 安装记录。
25    #[serde(default)]
26    pub plugins: BTreeMap<String, IndexEntry>,
27}
28
29fn default_cache_version() -> u32 {
30    CACHE_VERSION
31}
32
33impl Default for Index {
34    fn default() -> Self {
35        Self {
36            cache_version: CACHE_VERSION,
37            plugins: BTreeMap::new(),
38        }
39    }
40}
41
42/// 一条安装记录。
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct IndexEntry {
45    /// 安装的版本。
46    pub version: String,
47
48    /// manifest 里声明的 ABI 版本(宿主自用)。
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub abi: Option<u32>,
51
52    /// 安装目录的绝对路径。
53    pub root: PathBuf,
54
55    /// 安装来源。
56    #[serde(default)]
57    pub source: InstallSource,
58
59    /// 安装时刻(Unix 秒)。用整数而不是 RFC3339 字符串,省掉一个日期库依赖。
60    #[serde(rename = "installedAt", default)]
61    pub installed_at: u64,
62}
63
64/// 插件是怎么装进来的。
65#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "kebab-case")]
67pub enum InstallSource {
68    /// 从 GitHub Releases 下载的预编译产物。
69    Prebuilt,
70    /// 本地 `cargo build` 编译出来的(默认路径)。
71    #[default]
72    BuildHost,
73}
74
75/// 当前 Unix 秒。取不到系统时间时返回 0(宁可时间戳不准,也不要让安装失败)。
76pub fn now_unix() -> u64 {
77    SystemTime::now()
78        .duration_since(UNIX_EPOCH)
79        .map(|d| d.as_secs())
80        .unwrap_or(0)
81}
82
83impl Index {
84    /// 读缓存。文件不存在或解析失败都返回空索引 —— 缓存不是事实来源。
85    pub fn load(path: &Path) -> Self {
86        let Ok(text) = std::fs::read_to_string(path) else {
87            return Self::default();
88        };
89        match serde_json::from_str::<Self>(&text) {
90            Ok(mut idx) => {
91                idx.cache_version = CACHE_VERSION;
92                idx
93            }
94            Err(_) => Self::default(),
95        }
96    }
97
98    /// 写缓存(原子替换:先写临时文件再 rename)。
99    pub fn save(&self, path: &Path) -> KitResult<()> {
100        if let Some(parent) = path.parent() {
101            std::fs::create_dir_all(parent)?;
102        }
103        let text = serde_json::to_string_pretty(self)
104            .map_err(|e| crate::error::KitError::Registry(format!("序列化索引失败:{e}")))?;
105
106        let tmp = path.with_extension("json.tmp");
107        std::fs::write(&tmp, text)?;
108        std::fs::rename(&tmp, path)?;
109        Ok(())
110    }
111
112    /// 记一条。
113    pub fn insert(&mut self, crate_name: &str, entry: IndexEntry) {
114        self.plugins.insert(crate_name.to_string(), entry);
115    }
116
117    /// 删一条。
118    pub fn remove(&mut self, crate_name: &str) -> Option<IndexEntry> {
119        self.plugins.remove(crate_name)
120    }
121
122    /// 取一条。
123    pub fn get(&self, crate_name: &str) -> Option<&IndexEntry> {
124        self.plugins.get(crate_name)
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    fn entry(version: &str) -> IndexEntry {
133        IndexEntry {
134            version: version.to_string(),
135            abi: Some(1),
136            root: PathBuf::from("some").join("plugin"),
137            source: InstallSource::BuildHost,
138            installed_at: 1_767_225_600,
139        }
140    }
141
142    #[test]
143    fn insert_get_remove_round_trip() {
144        let mut idx = Index::default();
145        assert!(idx.get("a").is_none());
146
147        idx.insert("a", entry("0.1.0"));
148        assert_eq!(idx.get("a").unwrap().version, "0.1.0");
149
150        let removed = idx.remove("a");
151        assert_eq!(removed.unwrap().version, "0.1.0");
152        assert!(idx.get("a").is_none());
153        assert!(idx.remove("a").is_none());
154    }
155
156    #[test]
157    fn save_then_load_round_trips() {
158        let dir = tempfile::tempdir().unwrap();
159        let path = dir.path().join("nested").join(".plugins.json");
160
161        let mut idx = Index::default();
162        idx.insert("myapp-plugin-foo", entry("0.2.0"));
163        idx.save(&path).expect("应当能落盘");
164
165        let back = Index::load(&path);
166        assert_eq!(back.cache_version, CACHE_VERSION);
167        let got = back.get("myapp-plugin-foo").unwrap();
168        assert_eq!(got.version, "0.2.0");
169        assert_eq!(got.abi, Some(1));
170        assert_eq!(got.source, InstallSource::BuildHost);
171        assert_eq!(got.installed_at, 1_767_225_600);
172    }
173
174    /// 缓存不是事实来源:文件不存在时给一个空索引,而不是报错。
175    #[test]
176    fn a_missing_file_yields_an_empty_index() {
177        let dir = tempfile::tempdir().unwrap();
178        let idx = Index::load(&dir.path().join("nope.json"));
179        assert!(idx.plugins.is_empty());
180        assert_eq!(idx.cache_version, CACHE_VERSION);
181    }
182
183    /// 同上:文件坏了也只当空的,不把整个 `list()` 拖垮。
184    #[test]
185    fn a_corrupt_file_yields_an_empty_index() {
186        let dir = tempfile::tempdir().unwrap();
187        let path = dir.path().join(".plugins.json");
188        std::fs::write(&path, "{ this is not json").unwrap();
189
190        let idx = Index::load(&path);
191        assert!(idx.plugins.is_empty());
192    }
193
194    /// 旧缓存里 `source` 字段可能缺失 —— 要能读回并落到默认值。
195    #[test]
196    fn missing_optional_fields_fall_back() {
197        let dir = tempfile::tempdir().unwrap();
198        let path = dir.path().join(".plugins.json");
199        std::fs::write(&path, r#"{"plugins":{"a":{"version":"0.1.0","root":"r"}}}"#).unwrap();
200
201        let idx = Index::load(&path);
202        let got = idx.get("a").unwrap();
203        assert_eq!(got.source, InstallSource::BuildHost);
204        assert_eq!(got.abi, None);
205        assert_eq!(got.installed_at, 0);
206    }
207
208    /// 保存是"先写临时文件再 rename",所以不该留下 `.tmp` 残骸。
209    #[test]
210    fn save_leaves_no_temp_file_behind() {
211        let dir = tempfile::tempdir().unwrap();
212        let path = dir.path().join(".plugins.json");
213
214        let mut idx = Index::default();
215        idx.insert("a", entry("0.1.0"));
216        idx.save(&path).unwrap();
217
218        let leftovers: Vec<_> = std::fs::read_dir(dir.path())
219            .unwrap()
220            .filter_map(|e| e.ok())
221            .map(|e| e.file_name().to_string_lossy().into_owned())
222            .filter(|n| n.ends_with(".tmp"))
223            .collect();
224        assert!(leftovers.is_empty(), "留下了临时文件:{leftovers:?}");
225    }
226
227    #[test]
228    fn now_unix_is_after_the_epoch() {
229        assert!(now_unix() > 1_600_000_000);
230    }
231}