crate_plugin_kit/
cache.rs1use 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
15pub const CACHE_VERSION: u32 = 1;
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct Index {
21 #[serde(rename = "cacheVersion", default = "default_cache_version")]
23 pub cache_version: u32,
24
25 #[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#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct IndexEntry {
46 pub version: String,
48
49 #[serde(default, skip_serializing_if = "Option::is_none")]
51 pub abi: Option<u32>,
52
53 pub root: PathBuf,
55
56 #[serde(default)]
58 pub source: InstallSource,
59
60 #[serde(rename = "installedAt", default)]
63 pub installed_at: u64,
64}
65
66#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "kebab-case")]
69pub enum InstallSource {
70 Prebuilt,
72 #[default]
74 BuildHost,
75 Local {
81 path: PathBuf,
83 },
84}
85
86pub 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 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 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 pub fn insert(&mut self, crate_name: &str, entry: IndexEntry) {
128 self.plugins.insert(crate_name.to_string(), entry);
129 }
130
131 pub fn remove(&mut self, crate_name: &str) -> Option<IndexEntry> {
133 self.plugins.remove(crate_name)
134 }
135
136 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 #[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 #[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 #[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 #[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}