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, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "kebab-case")]
69pub enum InstallSource {
70 Prebuilt,
72 #[default]
74 BuildHost,
75}
76
77pub 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 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 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 pub fn insert(&mut self, crate_name: &str, entry: IndexEntry) {
119 self.plugins.insert(crate_name.to_string(), entry);
120 }
121
122 pub fn remove(&mut self, crate_name: &str) -> Option<IndexEntry> {
124 self.plugins.remove(crate_name)
125 }
126
127 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 #[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 #[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 #[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 #[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}