crate_plugin_kit/
cache.rs1use 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
14pub const CACHE_VERSION: u32 = 1;
16
17#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct Index {
20 #[serde(rename = "cacheVersion", default = "default_cache_version")]
22 pub cache_version: u32,
23
24 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct IndexEntry {
45 pub version: String,
47
48 #[serde(default, skip_serializing_if = "Option::is_none")]
50 pub abi: Option<u32>,
51
52 pub root: PathBuf,
54
55 #[serde(default)]
57 pub source: InstallSource,
58
59 #[serde(rename = "installedAt", default)]
61 pub installed_at: u64,
62}
63
64#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "kebab-case")]
67pub enum InstallSource {
68 Prebuilt,
70 #[default]
72 BuildHost,
73}
74
75pub 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 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 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 pub fn insert(&mut self, crate_name: &str, entry: IndexEntry) {
114 self.plugins.insert(crate_name.to_string(), entry);
115 }
116
117 pub fn remove(&mut self, crate_name: &str) -> Option<IndexEntry> {
119 self.plugins.remove(crate_name)
120 }
121
122 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 #[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 #[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 #[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 #[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}