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
3//! `.lock`, `.used` and `.verified` files).
4
5use 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
13/// Staging directories and temp files younger than this may belong to a live install in
14/// another process and are left alone.
15pub(crate) const STALE_AFTER: Duration = Duration::from_secs(60 * 60);
16const SECONDS_PER_DAY: u64 = 24 * 60 * 60;
17
18/// One installed object in the cache.
19#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct CachedObject {
22    /// The archive digest naming the object directory.
23    pub sha256: String,
24    pub path: PathBuf,
25    /// Total size of the files under `path`.
26    pub size_bytes: u64,
27    /// When the object was last loaded through a cache (falls back to install time).
28    pub last_used: Option<SystemTime>,
29    /// The component id in this manager's lock that references the object, when any.
30    pub component: Option<String>,
31}
32
33/// Which objects [`ComponentManager::prune`](crate::ComponentManager::prune) keeps. An object
34/// is kept when it satisfies any enabled criterion; with none enabled everything is removed.
35///
36/// Several host versions can share one cache, so the usual policy combines both criteria:
37/// keep what this lock needs plus whatever any host used recently.
38#[derive(Clone, Debug, Default, PartialEq, Eq)]
39pub struct Retain {
40    referenced_by_lock: bool,
41    used_within: Option<Duration>,
42}
43
44impl Retain {
45    /// Keep nothing (until criteria are added).
46    #[must_use]
47    pub fn new() -> Self {
48        Self::default()
49    }
50
51    /// Keep objects referenced by the manager's lock (every target in it).
52    #[must_use]
53    pub fn referenced_by_lock(mut self) -> Self {
54        self.referenced_by_lock = true;
55        self
56    }
57
58    /// Keep objects loaded within the last `days` days.
59    #[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    /// Keep objects loaded within the last `window`.
65    #[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/// A path a cleanup could not remove, and why.
83#[derive(Clone, Debug, PartialEq, Eq)]
84pub struct SkippedRemoval {
85    pub path: PathBuf,
86    pub reason: String,
87}
88
89/// What a removal or prune did.
90#[derive(Clone, Debug, Default, PartialEq, Eq)]
91pub struct RemovalReport {
92    pub removed: Vec<PathBuf>,
93    /// Objects left in place: loaded in this process, or (Windows) held open by a loaded
94    /// library so the OS refused the delete.
95    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    /// Record that `sha256` was just loaded. Best effort.
109    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    /// Every installed object, sorted by digest. A missing cache directory lists as empty.
122    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    /// Remove one object and its sidecar files. `Ok` with an empty report when absent.
156    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    /// Remove every object `retain` does not keep, except those in `protected` (digests
185    /// that are loaded in this process), then sweep crash leftovers.
186    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    /// Delete `.install-*` staging dirs and `.tmp*` files older than `min_age`, and
217    /// `.lock` / `.used` / `.verified` sidecars whose object is gone (a `.lock` only when no
218    /// process holds it).
219    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    /// A `.lock` file is only stale when no process holds it; other sidecars always are.
278    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
301/// The digest a `<digest>.lock|used|verified` sidecar name refers to.
302fn 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
321/// Windows refuses to delete a loaded DLL (access denied or sharing/lock violation).
322fn 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}