Skip to main content

alef_component_runtime/
maintenance.rs

1//! Cache inspection and cleanup: listing, removal and pruning of installed objects, plus
2//! removal of crash leftovers (`.install-*` staging dirs, orphaned temp files, stale `.used` and
3//! `.verified` files).
4//!
5//! Removal holds the object's `<digest>.lock`, the same lock an install holds, so an object is
6//! never deleted while another thread or process is installing it. Lock files themselves are
7//! never deleted (see [`ArtifactCache::digest_lock_file`]); they are empty, one per digest.
8
9use crate::ArtifactCache;
10use crate::ComponentError;
11use std::collections::HashSet;
12use std::fs::{self, File, OpenOptions, TryLockError};
13use std::path::{Path, PathBuf};
14use std::time::{Duration, SystemTime};
15
16/// Staging directories and temp files younger than this may belong to a live install in
17/// another process and are left alone.
18pub(crate) const STALE_AFTER: Duration = Duration::from_secs(60 * 60);
19const SECONDS_PER_DAY: u64 = 24 * 60 * 60;
20
21/// One installed object in the cache.
22#[derive(Clone, Debug, PartialEq, Eq)]
23#[non_exhaustive]
24pub struct CachedObject {
25    /// The archive digest naming the object directory.
26    pub sha256: String,
27    pub path: PathBuf,
28    /// Total size of the files under `path`.
29    pub size_bytes: u64,
30    /// When the object was last loaded through a cache (falls back to install time).
31    pub last_used: Option<SystemTime>,
32    /// The component id in this manager's lock that references the object, when any.
33    pub component: Option<String>,
34}
35
36/// Which objects [`ComponentManager::prune`](crate::ComponentManager::prune) keeps. An object
37/// is kept when it satisfies any enabled criterion; with none enabled everything is removed.
38///
39/// Several host versions can share one cache, so the usual policy combines both criteria:
40/// keep what this lock needs plus whatever any host used recently.
41#[derive(Clone, Debug, Default, PartialEq, Eq)]
42pub struct Retain {
43    referenced_by_lock: bool,
44    used_within: Option<Duration>,
45}
46
47impl Retain {
48    /// Keep nothing (until criteria are added).
49    #[must_use]
50    pub fn new() -> Self {
51        Self::default()
52    }
53
54    /// Keep objects referenced by the manager's lock (every target in it).
55    #[must_use]
56    pub fn referenced_by_lock(mut self) -> Self {
57        self.referenced_by_lock = true;
58        self
59    }
60
61    /// Keep objects loaded within the last `days` days.
62    #[must_use]
63    pub fn used_within_days(self, days: u64) -> Self {
64        self.used_within(Duration::from_secs(days.saturating_mul(SECONDS_PER_DAY)))
65    }
66
67    /// Keep objects loaded within the last `window`.
68    #[must_use]
69    pub fn used_within(mut self, window: Duration) -> Self {
70        self.used_within = Some(window);
71        self
72    }
73
74    fn keeps(&self, referenced: bool, last_used: Option<SystemTime>, now: SystemTime) -> bool {
75        if self.referenced_by_lock && referenced {
76            return true;
77        }
78        match (self.used_within, last_used) {
79            (Some(window), Some(used)) => !now.duration_since(used).is_ok_and(|age| age > window),
80            _ => false,
81        }
82    }
83}
84
85/// A path a cleanup could not remove, and why.
86#[derive(Clone, Debug, PartialEq, Eq)]
87pub struct SkippedRemoval {
88    pub path: PathBuf,
89    pub reason: String,
90}
91
92/// What a removal or prune did.
93#[derive(Clone, Debug, Default, PartialEq, Eq)]
94pub struct RemovalReport {
95    pub removed: Vec<PathBuf>,
96    /// Objects left in place: loaded in this process, or (Windows) held open by a loaded
97    /// library so the OS refused the delete.
98    pub skipped: Vec<SkippedRemoval>,
99    pub freed_bytes: u64,
100}
101
102impl ArtifactCache {
103    pub(crate) fn objects_dir(&self) -> PathBuf {
104        self.root.join("sha256")
105    }
106
107    fn used_path(&self, sha256: &str) -> PathBuf {
108        self.objects_dir().join(format!("{sha256}.used"))
109    }
110
111    /// Record that `sha256` was just loaded. Best effort.
112    pub(crate) fn touch_used(&self, sha256: &str) {
113        let Ok(file) = OpenOptions::new()
114            .write(true)
115            .create(true)
116            .truncate(false)
117            .open(self.used_path(sha256))
118        else {
119            return;
120        };
121        let _ = file.set_modified(SystemTime::now());
122    }
123
124    /// Every installed object, sorted by digest. A missing cache directory lists as empty.
125    pub fn list_objects(&self) -> Result<Vec<CachedObject>, ComponentError> {
126        let objects = self.objects_dir();
127        let reader = match fs::read_dir(&objects) {
128            Ok(reader) => reader,
129            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
130            Err(error) => return Err(error.into()),
131        };
132        let mut listed = Vec::new();
133        for item in reader {
134            let item = item?;
135            let Some(name) = item.file_name().to_str().map(str::to_owned) else {
136                continue;
137            };
138            if !is_digest_name(&name) || !item.file_type()?.is_dir() {
139                continue;
140            }
141            let path = item.path();
142            let installed = fs::metadata(&path).and_then(|meta| meta.modified()).ok();
143            let used = fs::metadata(self.used_path(&name))
144                .and_then(|meta| meta.modified())
145                .ok();
146            listed.push(CachedObject {
147                size_bytes: dir_size(&path),
148                last_used: used.or(installed),
149                sha256: name,
150                path,
151                component: None,
152            });
153        }
154        listed.sort_by(|a, b| a.sha256.cmp(&b.sha256));
155        Ok(listed)
156    }
157
158    /// Remove one object and its sidecar files. `Ok` with an empty report when absent. Waits for
159    /// an install of the same object in another thread or process to finish first.
160    pub fn remove_object(&self, sha256: &str) -> Result<RemovalReport, ComponentError> {
161        let sha256 = crate::cache::canonical_digest(sha256)?;
162        if !self.objects_dir().is_dir() {
163            return Ok(RemovalReport::default());
164        }
165        let lock = self.digest_lock_file(&sha256)?;
166        lock.lock()?;
167        self.remove_object_locked(&sha256, &lock)
168    }
169
170    /// Like [`Self::remove_object`], but skips (and reports) an object whose install is in
171    /// progress instead of waiting for it.
172    fn try_remove_object(&self, sha256: &str, path: PathBuf) -> Result<RemovalReport, ComponentError> {
173        let lock = self.digest_lock_file(sha256)?;
174        match lock.try_lock() {
175            Ok(()) => self.remove_object_locked(sha256, &lock),
176            Err(TryLockError::WouldBlock) => Ok(RemovalReport {
177                skipped: vec![SkippedRemoval {
178                    path,
179                    reason: "being installed by another thread or process".to_owned(),
180                }],
181                ..RemovalReport::default()
182            }),
183            Err(TryLockError::Error(error)) => Err(error.into()),
184        }
185    }
186
187    /// The removal itself; `_lock` is this object's digest lock, held by the caller.
188    fn remove_object_locked(&self, sha256: &str, _lock: &File) -> Result<RemovalReport, ComponentError> {
189        let mut report = RemovalReport::default();
190        let path = self.objects_dir().join(sha256);
191        if path.exists() {
192            let size = dir_size(&path);
193            match fs::remove_dir_all(&path) {
194                Ok(()) => {
195                    report.removed.push(path);
196                    report.freed_bytes = size;
197                }
198                Err(error) if is_sharing_violation(&error) => {
199                    report.skipped.push(SkippedRemoval {
200                        path,
201                        reason: format!("in use by a loaded library: {error}"),
202                    });
203                    return Ok(report);
204                }
205                Err(error) => return Err(error.into()),
206            }
207        }
208        for suffix in ["used", "verified"] {
209            let _ = fs::remove_file(self.objects_dir().join(format!("{sha256}.{suffix}")));
210        }
211        Ok(report)
212    }
213
214    /// Remove every object `retain` does not keep, except those in `protected` (digests
215    /// that are loaded in this process), then sweep crash leftovers.
216    pub(crate) fn prune_objects(
217        &self,
218        retain: &Retain,
219        locked: &HashSet<String>,
220        protected: &HashSet<String>,
221        now: SystemTime,
222    ) -> Result<RemovalReport, ComponentError> {
223        let mut report = RemovalReport::default();
224        for object in self.list_objects()? {
225            if retain.keeps(locked.contains(&object.sha256), object.last_used, now) {
226                continue;
227            }
228            if protected.contains(&object.sha256) {
229                report.skipped.push(SkippedRemoval {
230                    path: object.path,
231                    reason: "loaded in this process".to_owned(),
232                });
233                continue;
234            }
235            let removed = self.try_remove_object(&object.sha256, object.path)?;
236            report.removed.extend(removed.removed);
237            report.skipped.extend(removed.skipped);
238            report.freed_bytes += removed.freed_bytes;
239        }
240        let swept = self.clean_leftovers(STALE_AFTER, now)?;
241        report.removed.extend(swept.removed);
242        report.freed_bytes += swept.freed_bytes;
243        Ok(report)
244    }
245
246    /// Delete `.install-*` staging dirs and `.tmp*` files older than `min_age`, and `.used` /
247    /// `.verified` sidecars whose object is gone and whose digest is not being installed.
248    /// `.lock` files are kept (see [`ArtifactCache::digest_lock_file`]).
249    pub(crate) fn clean_leftovers(&self, min_age: Duration, now: SystemTime) -> Result<RemovalReport, ComponentError> {
250        let mut report = RemovalReport::default();
251        let objects = self.objects_dir();
252        let reader = match fs::read_dir(&objects) {
253            Ok(reader) => reader,
254            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(report),
255            Err(error) => return Err(error.into()),
256        };
257        for item in reader {
258            let item = item?;
259            let Some(name) = item.file_name().to_str().map(str::to_owned) else {
260                continue;
261            };
262            let path = item.path();
263            let is_dir = item.file_type()?.is_dir();
264            let old_enough = || {
265                fs::metadata(&path)
266                    .and_then(|meta| meta.modified())
267                    .ok()
268                    .and_then(|modified| now.duration_since(modified).ok())
269                    .is_some_and(|age| age >= min_age)
270            };
271            let staging = (name.starts_with(".install-") && is_dir) || (name.starts_with(".tmp") && !is_dir);
272            let stale = if staging {
273                old_enough()
274            } else if let Some(digest) = sidecar_digest(&name) {
275                !is_dir && !objects.join(digest).is_dir() && self.digest_is_idle(digest)
276            } else {
277                false
278            };
279            if !stale {
280                continue;
281            }
282            let size = if is_dir {
283                dir_size(&path)
284            } else {
285                item.metadata().map_or(0, |meta| meta.len())
286            };
287            let result = if is_dir {
288                fs::remove_dir_all(&path)
289            } else {
290                fs::remove_file(&path)
291            };
292            match result {
293                Ok(()) => {
294                    report.removed.push(path);
295                    report.freed_bytes += size;
296                }
297                Err(error) if is_sharing_violation(&error) => report.skipped.push(SkippedRemoval {
298                    path,
299                    reason: error.to_string(),
300                }),
301                Err(error) => return Err(error.into()),
302            }
303        }
304        Ok(report)
305    }
306
307    /// Whether no install of `digest` is in progress. A digest without a lock file has never been
308    /// installed by a runtime that takes one, so nothing can hold it.
309    fn digest_is_idle(&self, digest: &str) -> bool {
310        match OpenOptions::new()
311            .read(true)
312            .write(true)
313            .open(self.objects_dir().join(format!("{digest}.lock")))
314        {
315            Ok(file) => file.try_lock().is_ok(),
316            Err(error) => error.kind() == std::io::ErrorKind::NotFound,
317        }
318    }
319}
320
321fn is_digest_name(name: &str) -> bool {
322    name.len() == 64 && name.bytes().all(|byte| byte.is_ascii_hexdigit())
323}
324
325/// The digest a removable `<digest>.used|verified` sidecar name refers to.
326fn sidecar_digest(name: &str) -> Option<&str> {
327    let (digest, suffix) = name.split_once('.')?;
328    (is_digest_name(digest) && matches!(suffix, "used" | "verified")).then_some(digest)
329}
330
331fn dir_size(path: &Path) -> u64 {
332    let Ok(reader) = fs::read_dir(path) else {
333        return 0;
334    };
335    reader
336        .flatten()
337        .map(|item| match item.file_type() {
338            Ok(kind) if kind.is_dir() => dir_size(&item.path()),
339            Ok(_) => item.metadata().map_or(0, |meta| meta.len()),
340            Err(_) => 0,
341        })
342        .sum()
343}
344
345/// Windows refuses to delete a loaded DLL (access denied or sharing/lock violation).
346fn is_sharing_violation(error: &std::io::Error) -> bool {
347    const ERROR_ACCESS_DENIED: i32 = 5;
348    const ERROR_SHARING_VIOLATION: i32 = 32;
349    const ERROR_LOCK_VIOLATION: i32 = 33;
350    cfg!(windows)
351        && (error.kind() == std::io::ErrorKind::PermissionDenied
352            || matches!(
353                error.raw_os_error(),
354                Some(ERROR_ACCESS_DENIED | ERROR_SHARING_VIOLATION | ERROR_LOCK_VIOLATION)
355            ))
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361    use crate::TrustPolicy;
362
363    fn cache(dir: &Path) -> ArtifactCache {
364        ArtifactCache::new(dir, TrustPolicy::DigestOnly)
365    }
366
367    fn digest(byte: u8) -> String {
368        hex::encode([byte; 32])
369    }
370
371    fn make_object(cache: &ArtifactCache, byte: u8) -> PathBuf {
372        let path = cache.objects_dir().join(digest(byte));
373        fs::create_dir_all(&path).unwrap();
374        fs::write(path.join("lib.bin"), b"12345").unwrap();
375        path
376    }
377
378    fn age(path: &Path, days: u64) {
379        let past = SystemTime::now() - Duration::from_secs(days * SECONDS_PER_DAY);
380        OpenOptions::new()
381            .write(true)
382            .open(path)
383            .unwrap()
384            .set_modified(past)
385            .unwrap();
386    }
387
388    #[test]
389    fn lists_objects_with_size_and_ignores_sidecars() {
390        let dir = tempfile::tempdir().unwrap();
391        let cache = cache(dir.path());
392        make_object(&cache, 1);
393        fs::write(cache.objects_dir().join(format!("{}.lock", digest(1))), b"").unwrap();
394        fs::create_dir_all(cache.objects_dir().join(".install-abc")).unwrap();
395
396        let listed = cache.list_objects().unwrap();
397
398        assert_eq!(listed.len(), 1);
399        assert_eq!(listed[0].sha256, digest(1));
400        assert_eq!(listed[0].size_bytes, 5);
401        assert!(listed[0].last_used.is_some());
402    }
403
404    #[test]
405    fn listing_a_missing_cache_is_empty() {
406        let dir = tempfile::tempdir().unwrap();
407        assert!(cache(&dir.path().join("nope")).list_objects().unwrap().is_empty());
408    }
409
410    #[test]
411    fn remove_object_deletes_directory_and_sidecars() {
412        let dir = tempfile::tempdir().unwrap();
413        let cache = cache(dir.path());
414        let path = make_object(&cache, 1);
415        cache.touch_used(&digest(1));
416        fs::write(cache.objects_dir().join(format!("{}.lock", digest(1))), b"").unwrap();
417
418        let report = cache.remove_object(&digest(1)).unwrap();
419
420        assert_eq!(report.removed, vec![path.clone()]);
421        assert_eq!(report.freed_bytes, 5);
422        assert!(!path.exists());
423        assert!(!cache.used_path(&digest(1)).exists());
424        assert!(
425            cache.objects_dir().join(format!("{}.lock", digest(1))).exists(),
426            "lock files are never unlinked"
427        );
428        assert!(cache.remove_object(&digest(1)).unwrap().removed.is_empty());
429    }
430
431    fn hold_lock(cache: &ArtifactCache, byte: u8) -> File {
432        let lock = cache.digest_lock_file(&digest(byte)).unwrap();
433        lock.lock().unwrap();
434        lock
435    }
436
437    /// Regression: prune deleted an object while another process was installing it.
438    #[test]
439    fn prune_skips_an_object_whose_install_holds_the_digest_lock() {
440        let dir = tempfile::tempdir().unwrap();
441        let cache = cache(dir.path());
442        let installing = make_object(&cache, 1);
443        let held = hold_lock(&cache, 1);
444
445        let report = cache
446            .prune_objects(&Retain::new(), &HashSet::new(), &HashSet::new(), SystemTime::now())
447            .unwrap();
448        assert!(installing.exists());
449        assert_eq!(report.skipped.len(), 1, "{report:?}");
450        assert_eq!(report.skipped[0].path, installing);
451
452        drop(held);
453        let report = cache
454            .prune_objects(&Retain::new(), &HashSet::new(), &HashSet::new(), SystemTime::now())
455            .unwrap();
456        assert_eq!(report.removed, vec![installing.clone()]);
457        assert!(!installing.exists());
458    }
459
460    /// Regression: removal did not take the digest lock, so it could delete an object an install
461    /// on another thread was still writing.
462    #[test]
463    fn remove_object_waits_for_the_install_holding_the_digest_lock() {
464        use std::sync::Arc;
465        use std::sync::atomic::{AtomicBool, Ordering};
466
467        let dir = tempfile::tempdir().unwrap();
468        let cache = cache(dir.path());
469        let object = make_object(&cache, 1);
470        let held = hold_lock(&cache, 1);
471        let released = Arc::new(AtomicBool::new(false));
472
473        let remover = {
474            let cache = cache.clone();
475            let released = Arc::clone(&released);
476            std::thread::spawn(move || {
477                let report = cache.remove_object(&digest(1)).unwrap();
478                (released.load(Ordering::SeqCst), report)
479            })
480        };
481        std::thread::sleep(Duration::from_millis(100));
482        assert!(object.exists(), "removal must wait for the install's lock");
483        released.store(true, Ordering::SeqCst);
484        drop(held);
485
486        let (after_release, report) = remover.join().unwrap();
487        assert!(after_release, "the object was removed before the lock was released");
488        assert_eq!(report.removed, vec![object.clone()]);
489        assert!(!object.exists());
490    }
491
492    #[test]
493    fn prune_keeps_locked_or_recently_used_and_removes_the_rest() {
494        let dir = tempfile::tempdir().unwrap();
495        let cache = cache(dir.path());
496        let locked = make_object(&cache, 1);
497        let recent = make_object(&cache, 2);
498        let old = make_object(&cache, 3);
499        for byte in [1, 2, 3] {
500            cache.touch_used(&digest(byte));
501        }
502        age(&cache.used_path(&digest(1)), 90);
503        age(&cache.used_path(&digest(3)), 90);
504        let referenced = HashSet::from([digest(1)]);
505        let retain = Retain::new().referenced_by_lock().used_within_days(30);
506
507        let report = cache
508            .prune_objects(&retain, &referenced, &HashSet::new(), SystemTime::now())
509            .unwrap();
510
511        assert!(locked.exists() && recent.exists());
512        assert!(!old.exists());
513        assert_eq!(report.removed, vec![old]);
514    }
515
516    #[test]
517    fn prune_with_no_criteria_removes_everything_but_skips_protected() {
518        let dir = tempfile::tempdir().unwrap();
519        let cache = cache(dir.path());
520        let loaded = make_object(&cache, 1);
521        let other = make_object(&cache, 2);
522
523        let report = cache
524            .prune_objects(
525                &Retain::new(),
526                &HashSet::new(),
527                &HashSet::from([digest(1)]),
528                SystemTime::now(),
529            )
530            .unwrap();
531
532        assert!(loaded.exists());
533        assert!(!other.exists());
534        assert_eq!(report.skipped.len(), 1);
535        assert_eq!(report.skipped[0].path, loaded);
536    }
537
538    #[test]
539    fn clean_leftovers_removes_stale_staging_and_orphaned_sidecars_only() {
540        let dir = tempfile::tempdir().unwrap();
541        let cache = cache(dir.path());
542        let objects = cache.objects_dir();
543        let kept = make_object(&cache, 1);
544        fs::write(objects.join(format!("{}.lock", digest(1))), b"").unwrap();
545        let staging = objects.join(".install-crashed");
546        fs::create_dir_all(&staging).unwrap();
547        fs::write(staging.join("partial"), b"xx").unwrap();
548        let orphan_lock = objects.join(format!("{}.lock", digest(9)));
549        fs::write(&orphan_lock, b"").unwrap();
550        let orphan_stamp = objects.join(format!("{}.verified", digest(9)));
551        fs::write(&orphan_stamp, b"{}").unwrap();
552
553        let fresh = cache
554            .clean_leftovers(Duration::from_secs(3600), SystemTime::now())
555            .unwrap();
556        assert!(staging.exists(), "a young staging dir may belong to a live install");
557        assert!(!orphan_stamp.exists());
558        assert!(orphan_lock.exists(), "lock files are never unlinked");
559        assert_eq!(fresh.removed, vec![orphan_stamp.clone()]);
560
561        let later = cache.clean_leftovers(Duration::ZERO, SystemTime::now()).unwrap();
562        assert!(!staging.exists());
563        assert_eq!(later.removed, vec![staging]);
564        assert_eq!(later.freed_bytes, 2);
565        assert!(kept.exists());
566        assert!(objects.join(format!("{}.lock", digest(1))).exists());
567    }
568
569    #[test]
570    fn sidecars_of_a_digest_being_installed_are_kept() {
571        let dir = tempfile::tempdir().unwrap();
572        let cache = cache(dir.path());
573        fs::create_dir_all(cache.objects_dir()).unwrap();
574        let held = hold_lock(&cache, 9);
575        let stamp = cache.objects_dir().join(format!("{}.verified", digest(9)));
576        fs::write(&stamp, b"{}").unwrap();
577
578        cache.clean_leftovers(Duration::ZERO, SystemTime::now()).unwrap();
579        assert!(
580            stamp.exists(),
581            "the install holding the lock may be about to rename its object in"
582        );
583
584        drop(held);
585        cache.clean_leftovers(Duration::ZERO, SystemTime::now()).unwrap();
586        assert!(!stamp.exists());
587        assert!(cache.objects_dir().join(format!("{}.lock", digest(9))).exists());
588    }
589}