1use crate::ArtifactCache;
6use crate::ComponentError;
7use fs2::FileExt as _;
8use std::collections::HashSet;
9use std::fs::{self, OpenOptions};
10use std::path::{Path, PathBuf};
11use std::time::{Duration, SystemTime};
12
13pub(crate) const STALE_AFTER: Duration = Duration::from_secs(60 * 60);
16const SECONDS_PER_DAY: u64 = 24 * 60 * 60;
17
18#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct CachedObject {
22 pub sha256: String,
24 pub path: PathBuf,
25 pub size_bytes: u64,
27 pub last_used: Option<SystemTime>,
29 pub component: Option<String>,
31}
32
33#[derive(Clone, Debug, Default, PartialEq, Eq)]
39pub struct Retain {
40 referenced_by_lock: bool,
41 used_within: Option<Duration>,
42}
43
44impl Retain {
45 #[must_use]
47 pub fn new() -> Self {
48 Self::default()
49 }
50
51 #[must_use]
53 pub fn referenced_by_lock(mut self) -> Self {
54 self.referenced_by_lock = true;
55 self
56 }
57
58 #[must_use]
60 pub fn used_within_days(self, days: u64) -> Self {
61 self.used_within(Duration::from_secs(days.saturating_mul(SECONDS_PER_DAY)))
62 }
63
64 #[must_use]
66 pub fn used_within(mut self, window: Duration) -> Self {
67 self.used_within = Some(window);
68 self
69 }
70
71 fn keeps(&self, referenced: bool, last_used: Option<SystemTime>, now: SystemTime) -> bool {
72 if self.referenced_by_lock && referenced {
73 return true;
74 }
75 match (self.used_within, last_used) {
76 (Some(window), Some(used)) => !now.duration_since(used).is_ok_and(|age| age > window),
77 _ => false,
78 }
79 }
80}
81
82#[derive(Clone, Debug, PartialEq, Eq)]
84pub struct SkippedRemoval {
85 pub path: PathBuf,
86 pub reason: String,
87}
88
89#[derive(Clone, Debug, Default, PartialEq, Eq)]
91pub struct RemovalReport {
92 pub removed: Vec<PathBuf>,
93 pub skipped: Vec<SkippedRemoval>,
96 pub freed_bytes: u64,
97}
98
99impl ArtifactCache {
100 pub(crate) fn objects_dir(&self) -> PathBuf {
101 self.root.join("sha256")
102 }
103
104 fn used_path(&self, sha256: &str) -> PathBuf {
105 self.objects_dir().join(format!("{sha256}.used"))
106 }
107
108 pub(crate) fn touch_used(&self, sha256: &str) {
110 let Ok(file) = OpenOptions::new()
111 .write(true)
112 .create(true)
113 .truncate(false)
114 .open(self.used_path(sha256))
115 else {
116 return;
117 };
118 let _ = file.set_modified(SystemTime::now());
119 }
120
121 pub fn list_objects(&self) -> Result<Vec<CachedObject>, ComponentError> {
123 let objects = self.objects_dir();
124 let reader = match fs::read_dir(&objects) {
125 Ok(reader) => reader,
126 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
127 Err(error) => return Err(error.into()),
128 };
129 let mut listed = Vec::new();
130 for item in reader {
131 let item = item?;
132 let Some(name) = item.file_name().to_str().map(str::to_owned) else {
133 continue;
134 };
135 if !is_digest_name(&name) || !item.file_type()?.is_dir() {
136 continue;
137 }
138 let path = item.path();
139 let installed = fs::metadata(&path).and_then(|meta| meta.modified()).ok();
140 let used = fs::metadata(self.used_path(&name))
141 .and_then(|meta| meta.modified())
142 .ok();
143 listed.push(CachedObject {
144 size_bytes: dir_size(&path),
145 last_used: used.or(installed),
146 sha256: name,
147 path,
148 component: None,
149 });
150 }
151 listed.sort_by(|a, b| a.sha256.cmp(&b.sha256));
152 Ok(listed)
153 }
154
155 pub fn remove_object(&self, sha256: &str) -> Result<RemovalReport, ComponentError> {
157 crate::cache::decode_digest(sha256)?;
158 let mut report = RemovalReport::default();
159 let path = self.objects_dir().join(sha256);
160 if path.exists() {
161 let size = dir_size(&path);
162 match fs::remove_dir_all(&path) {
163 Ok(()) => {
164 report.removed.push(path);
165 report.freed_bytes = size;
166 }
167 Err(error) if is_sharing_violation(&error) => {
168 report.skipped.push(SkippedRemoval {
169 path,
170 reason: format!("in use by a loaded library: {error}"),
171 });
172 return Ok(report);
173 }
174 Err(error) => return Err(error.into()),
175 }
176 }
177 for suffix in ["used", "verified"] {
178 let _ = fs::remove_file(self.objects_dir().join(format!("{sha256}.{suffix}")));
179 }
180 self.remove_lock_if_idle(sha256);
181 Ok(report)
182 }
183
184 pub(crate) fn prune_objects(
187 &self,
188 retain: &Retain,
189 locked: &HashSet<String>,
190 protected: &HashSet<String>,
191 now: SystemTime,
192 ) -> Result<RemovalReport, ComponentError> {
193 let mut report = RemovalReport::default();
194 for object in self.list_objects()? {
195 if retain.keeps(locked.contains(&object.sha256), object.last_used, now) {
196 continue;
197 }
198 if protected.contains(&object.sha256) {
199 report.skipped.push(SkippedRemoval {
200 path: object.path,
201 reason: "loaded in this process".to_owned(),
202 });
203 continue;
204 }
205 let removed = self.remove_object(&object.sha256)?;
206 report.removed.extend(removed.removed);
207 report.skipped.extend(removed.skipped);
208 report.freed_bytes += removed.freed_bytes;
209 }
210 let swept = self.clean_leftovers(STALE_AFTER, now)?;
211 report.removed.extend(swept.removed);
212 report.freed_bytes += swept.freed_bytes;
213 Ok(report)
214 }
215
216 pub(crate) fn clean_leftovers(&self, min_age: Duration, now: SystemTime) -> Result<RemovalReport, ComponentError> {
220 let mut report = RemovalReport::default();
221 let objects = self.objects_dir();
222 let reader = match fs::read_dir(&objects) {
223 Ok(reader) => reader,
224 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(report),
225 Err(error) => return Err(error.into()),
226 };
227 for item in reader {
228 let item = item?;
229 let Some(name) = item.file_name().to_str().map(str::to_owned) else {
230 continue;
231 };
232 let path = item.path();
233 let is_dir = item.file_type()?.is_dir();
234 let old_enough = || {
235 fs::metadata(&path)
236 .and_then(|meta| meta.modified())
237 .ok()
238 .and_then(|modified| now.duration_since(modified).ok())
239 .is_some_and(|age| age >= min_age)
240 };
241 let staging = (name.starts_with(".install-") && is_dir) || (name.starts_with(".tmp") && !is_dir);
242 let stale = if staging {
243 old_enough()
244 } else if let Some(digest) = sidecar_digest(&name) {
245 !is_dir && !objects.join(digest).is_dir() && self.sidecar_is_unclaimed(&path, &name)
246 } else {
247 false
248 };
249 if !stale {
250 continue;
251 }
252 let size = if is_dir {
253 dir_size(&path)
254 } else {
255 item.metadata().map_or(0, |meta| meta.len())
256 };
257 let result = if is_dir {
258 fs::remove_dir_all(&path)
259 } else {
260 fs::remove_file(&path)
261 };
262 match result {
263 Ok(()) => {
264 report.removed.push(path);
265 report.freed_bytes += size;
266 }
267 Err(error) if is_sharing_violation(&error) => report.skipped.push(SkippedRemoval {
268 path,
269 reason: error.to_string(),
270 }),
271 Err(error) => return Err(error.into()),
272 }
273 }
274 Ok(report)
275 }
276
277 fn sidecar_is_unclaimed(&self, path: &Path, name: &str) -> bool {
279 if !name.ends_with(".lock") {
280 return true;
281 }
282 OpenOptions::new()
283 .read(true)
284 .write(true)
285 .open(path)
286 .is_ok_and(|file| file.try_lock_exclusive().is_ok())
287 }
288
289 fn remove_lock_if_idle(&self, sha256: &str) {
290 let path = self.objects_dir().join(format!("{sha256}.lock"));
291 if self.sidecar_is_unclaimed(&path, &format!("{sha256}.lock")) {
292 let _ = fs::remove_file(path);
293 }
294 }
295}
296
297fn is_digest_name(name: &str) -> bool {
298 name.len() == 64 && name.bytes().all(|byte| byte.is_ascii_hexdigit())
299}
300
301fn sidecar_digest(name: &str) -> Option<&str> {
303 let (digest, suffix) = name.split_once('.')?;
304 (is_digest_name(digest) && matches!(suffix, "lock" | "used" | "verified")).then_some(digest)
305}
306
307fn dir_size(path: &Path) -> u64 {
308 let Ok(reader) = fs::read_dir(path) else {
309 return 0;
310 };
311 reader
312 .flatten()
313 .map(|item| match item.file_type() {
314 Ok(kind) if kind.is_dir() => dir_size(&item.path()),
315 Ok(_) => item.metadata().map_or(0, |meta| meta.len()),
316 Err(_) => 0,
317 })
318 .sum()
319}
320
321fn is_sharing_violation(error: &std::io::Error) -> bool {
323 const ERROR_ACCESS_DENIED: i32 = 5;
324 const ERROR_SHARING_VIOLATION: i32 = 32;
325 const ERROR_LOCK_VIOLATION: i32 = 33;
326 cfg!(windows)
327 && (error.kind() == std::io::ErrorKind::PermissionDenied
328 || matches!(
329 error.raw_os_error(),
330 Some(ERROR_ACCESS_DENIED | ERROR_SHARING_VIOLATION | ERROR_LOCK_VIOLATION)
331 ))
332}
333
334#[cfg(test)]
335mod tests {
336 use super::*;
337 use crate::TrustPolicy;
338
339 fn cache(dir: &Path) -> ArtifactCache {
340 ArtifactCache::new(dir, TrustPolicy::DigestOnly)
341 }
342
343 fn digest(byte: u8) -> String {
344 hex::encode([byte; 32])
345 }
346
347 fn make_object(cache: &ArtifactCache, byte: u8) -> PathBuf {
348 let path = cache.objects_dir().join(digest(byte));
349 fs::create_dir_all(&path).unwrap();
350 fs::write(path.join("lib.bin"), b"12345").unwrap();
351 path
352 }
353
354 fn age(path: &Path, days: u64) {
355 let past = SystemTime::now() - Duration::from_secs(days * SECONDS_PER_DAY);
356 OpenOptions::new()
357 .write(true)
358 .open(path)
359 .unwrap()
360 .set_modified(past)
361 .unwrap();
362 }
363
364 #[test]
365 fn lists_objects_with_size_and_ignores_sidecars() {
366 let dir = tempfile::tempdir().unwrap();
367 let cache = cache(dir.path());
368 make_object(&cache, 1);
369 fs::write(cache.objects_dir().join(format!("{}.lock", digest(1))), b"").unwrap();
370 fs::create_dir_all(cache.objects_dir().join(".install-abc")).unwrap();
371
372 let listed = cache.list_objects().unwrap();
373
374 assert_eq!(listed.len(), 1);
375 assert_eq!(listed[0].sha256, digest(1));
376 assert_eq!(listed[0].size_bytes, 5);
377 assert!(listed[0].last_used.is_some());
378 }
379
380 #[test]
381 fn listing_a_missing_cache_is_empty() {
382 let dir = tempfile::tempdir().unwrap();
383 assert!(cache(&dir.path().join("nope")).list_objects().unwrap().is_empty());
384 }
385
386 #[test]
387 fn remove_object_deletes_directory_and_sidecars() {
388 let dir = tempfile::tempdir().unwrap();
389 let cache = cache(dir.path());
390 let path = make_object(&cache, 1);
391 cache.touch_used(&digest(1));
392 fs::write(cache.objects_dir().join(format!("{}.lock", digest(1))), b"").unwrap();
393
394 let report = cache.remove_object(&digest(1)).unwrap();
395
396 assert_eq!(report.removed, vec![path.clone()]);
397 assert_eq!(report.freed_bytes, 5);
398 assert!(!path.exists());
399 assert!(!cache.used_path(&digest(1)).exists());
400 assert!(!cache.objects_dir().join(format!("{}.lock", digest(1))).exists());
401 assert!(cache.remove_object(&digest(1)).unwrap().removed.is_empty());
402 }
403
404 #[test]
405 fn prune_keeps_locked_or_recently_used_and_removes_the_rest() {
406 let dir = tempfile::tempdir().unwrap();
407 let cache = cache(dir.path());
408 let locked = make_object(&cache, 1);
409 let recent = make_object(&cache, 2);
410 let old = make_object(&cache, 3);
411 for byte in [1, 2, 3] {
412 cache.touch_used(&digest(byte));
413 }
414 age(&cache.used_path(&digest(1)), 90);
415 age(&cache.used_path(&digest(3)), 90);
416 let referenced = HashSet::from([digest(1)]);
417 let retain = Retain::new().referenced_by_lock().used_within_days(30);
418
419 let report = cache
420 .prune_objects(&retain, &referenced, &HashSet::new(), SystemTime::now())
421 .unwrap();
422
423 assert!(locked.exists() && recent.exists());
424 assert!(!old.exists());
425 assert_eq!(report.removed, vec![old]);
426 }
427
428 #[test]
429 fn prune_with_no_criteria_removes_everything_but_skips_protected() {
430 let dir = tempfile::tempdir().unwrap();
431 let cache = cache(dir.path());
432 let loaded = make_object(&cache, 1);
433 let other = make_object(&cache, 2);
434
435 let report = cache
436 .prune_objects(
437 &Retain::new(),
438 &HashSet::new(),
439 &HashSet::from([digest(1)]),
440 SystemTime::now(),
441 )
442 .unwrap();
443
444 assert!(loaded.exists());
445 assert!(!other.exists());
446 assert_eq!(report.skipped.len(), 1);
447 assert_eq!(report.skipped[0].path, loaded);
448 }
449
450 #[test]
451 fn clean_leftovers_removes_stale_staging_and_orphaned_sidecars_only() {
452 let dir = tempfile::tempdir().unwrap();
453 let cache = cache(dir.path());
454 let objects = cache.objects_dir();
455 let kept = make_object(&cache, 1);
456 fs::write(objects.join(format!("{}.lock", digest(1))), b"").unwrap();
457 let staging = objects.join(".install-crashed");
458 fs::create_dir_all(&staging).unwrap();
459 fs::write(staging.join("partial"), b"xx").unwrap();
460 let orphan_lock = objects.join(format!("{}.lock", digest(9)));
461 fs::write(&orphan_lock, b"").unwrap();
462 let orphan_stamp = objects.join(format!("{}.verified", digest(9)));
463 fs::write(&orphan_stamp, b"{}").unwrap();
464
465 let fresh = cache
466 .clean_leftovers(Duration::from_secs(3600), SystemTime::now())
467 .unwrap();
468 assert!(staging.exists(), "a young staging dir may belong to a live install");
469 assert!(!orphan_lock.exists() && !orphan_stamp.exists());
470 assert_eq!(fresh.removed.len(), 2);
471
472 let later = cache.clean_leftovers(Duration::ZERO, SystemTime::now()).unwrap();
473 assert!(!staging.exists());
474 assert_eq!(later.removed, vec![staging]);
475 assert_eq!(later.freed_bytes, 2);
476 assert!(kept.exists());
477 assert!(objects.join(format!("{}.lock", digest(1))).exists());
478 }
479
480 #[test]
481 fn held_lock_file_is_not_treated_as_stale() {
482 let dir = tempfile::tempdir().unwrap();
483 let cache = cache(dir.path());
484 fs::create_dir_all(cache.objects_dir()).unwrap();
485 let lock_path = cache.objects_dir().join(format!("{}.lock", digest(9)));
486 let held = OpenOptions::new()
487 .read(true)
488 .write(true)
489 .create(true)
490 .truncate(false)
491 .open(&lock_path)
492 .unwrap();
493 held.lock_exclusive().unwrap();
494
495 cache.clean_leftovers(Duration::ZERO, SystemTime::now()).unwrap();
496
497 assert!(lock_path.exists());
498 }
499}