use std::ffi::OsString;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use super::{Guard, Outcome, Removal, Verified, paths_equal};
pub const TRASH_ENV: &str = "VOOM_TRASH_DIR";
const LEDGER: &str = ".ledger";
const LOCK: &str = ".lock";
const FORCED: &str = "f";
const PLAIN: &str = "p";
const NAME_KEPT: usize = 64;
static DETACH: AtomicBool = AtomicBool::new(false);
static DETACHED: AtomicU64 = AtomicU64::new(0);
static SEQUENCE: AtomicU64 = AtomicU64::new(0);
pub fn detach_removals(enabled: bool) {
DETACH.store(enabled, Ordering::Relaxed);
}
#[must_use]
pub fn detached_count() -> u64 {
DETACHED.load(Ordering::Relaxed)
}
#[must_use]
pub fn trash_location() -> Option<PathBuf> {
match std::env::var_os(TRASH_ENV) {
Some(dir) if !dir.is_empty() => Some(PathBuf::from(dir)),
_ => dirs::cache_dir().map(|cache| cache.join("voom").join("trash")),
}
}
#[derive(Debug)]
pub struct Trash {
dir: PathBuf,
#[cfg(unix)]
dev: u64,
}
impl Trash {
pub fn at(dir: &Path) -> std::io::Result<Self> {
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
builder.create(dir)?;
let metadata = std::fs::symlink_metadata(dir)?;
if !metadata.is_dir() {
return Err(std::io::Error::other(format!("{} is not a directory", dir.display())));
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
let user = unsafe { libc::geteuid() };
if metadata.uid() != user {
return Err(std::io::Error::other(format!(
"{} belongs to another user",
dir.display()
)));
}
}
Ok(Self {
dir: dir.canonicalize()?,
#[cfg(unix)]
dev: std::os::unix::fs::MetadataExt::dev(&metadata),
})
}
#[must_use]
pub fn dir(&self) -> &Path {
&self.dir
}
fn detach(&self, verified: &Verified, force: bool) -> Option<std::io::Result<()>> {
let source = verified.canonical();
if super::path_starts_with(&self.dir, source) || super::path_starts_with(source, &self.dir) {
return None;
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
match std::fs::symlink_metadata(source) {
Ok(metadata) if metadata.dev() == self.dev => {}
Ok(_) => return None,
Err(error) => return Some(Err(error)),
}
}
let target = self.dir.join(entry_name(source, force));
match std::fs::rename(source, &target) {
Ok(()) => {
DETACHED.fetch_add(1, Ordering::Relaxed);
Some(Ok(()))
}
#[cfg(unix)]
Err(error) if error.raw_os_error() == Some(libc::EXDEV) => None,
Err(error) => Some(Err(error)),
}
}
#[must_use]
pub fn pending(&self) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(&self.dir) else {
return Vec::new();
};
entries
.flatten()
.filter(|entry| !entry.file_name().to_string_lossy().starts_with('.'))
.map(|entry| entry.path())
.collect()
}
}
fn entry_name(source: &Path, force: bool) -> OsString {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |elapsed| elapsed.as_nanos());
let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
let name: String = source
.file_name()
.map(|name| name.to_string_lossy().chars().take(NAME_KEPT).collect())
.unwrap_or_default();
let mode = if force { FORCED } else { PLAIN };
OsString::from(format!("{nanos}-{}-{sequence}-{mode}-{name}", std::process::id()))
}
fn forced(entry: &Path) -> bool {
entry
.file_name()
.and_then(|name| name.to_str())
.and_then(|name| name.split('-').nth(3))
.is_some_and(|mode| mode == FORCED)
}
fn shared() -> Option<std::sync::Arc<Trash>> {
static TRASH: std::sync::Mutex<Option<(PathBuf, std::sync::Arc<Trash>)>> = std::sync::Mutex::new(None);
let location = trash_location()?;
let mut slot = TRASH.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some((opened, trash)) = slot.as_ref()
&& paths_equal(opened, &location)
{
return Some(std::sync::Arc::clone(trash));
}
let trash = std::sync::Arc::new(Trash::at(&location).ok()?);
*slot = Some((location, std::sync::Arc::clone(&trash)));
Some(trash)
}
pub(super) fn try_detach(verified: &Verified, removal: Removal) -> Option<Outcome> {
if !DETACH.load(Ordering::Relaxed) {
return None;
}
let trash = shared()?;
match trash.detach(verified, removal.force)? {
Ok(()) => Some(Outcome::Detached),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Some(Outcome::Refused(super::Refusal::Vanished)),
Err(_) => None,
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Reaped {
pub freed_entries: u64,
pub bytes: u64,
pub failed_entries: u64,
}
impl Reaped {
fn add(&mut self, other: Self) {
self.freed_entries += other.freed_entries;
self.bytes += other.bytes;
self.failed_entries += other.failed_entries;
}
}
pub fn reap(dir: &Path) -> std::io::Result<Reaped> {
let trash = Trash::at(dir)?;
let _lock = lock(trash.dir())?;
let guard = Guard::new(&[trash.dir().to_path_buf()], true).map_err(std::io::Error::other)?;
let mut tried = std::collections::HashSet::new();
let mut total = Reaped::default();
loop {
let batch: Vec<PathBuf> = trash
.pending()
.into_iter()
.filter(|entry| tried.insert(entry.clone()))
.collect();
if batch.is_empty() {
return Ok(total);
}
let reaped = super::install_removal(|| {
use rayon::prelude::*;
batch
.par_iter()
.map(|entry| reap_entry(&guard, trash.dir(), entry))
.reduce(Reaped::default, |mut left, right| {
left.add(right);
left
})
});
total.add(reaped);
}
}
fn reap_entry(guard: &Guard, dir: &Path, entry: &Path) -> Reaped {
let was_forced = forced(entry);
let removal = if was_forced { Removal::forced() } else { Removal::new() };
let (mut outcome, mut bytes) = guard.reclaim(entry, removal);
if !was_forced && !matches!(outcome, Outcome::Removed | Outcome::Refused(super::Refusal::Vanished)) {
let (retried, again) = guard.reclaim(entry, Removal::forced());
outcome = retried;
bytes += again;
}
let reaped = match outcome {
Outcome::Removed | Outcome::Refused(super::Refusal::Vanished) => Reaped {
freed_entries: 1,
bytes,
failed_entries: 0,
},
Outcome::PartiallyRemoved { freed, .. } => Reaped {
freed_entries: 0,
bytes: freed,
failed_entries: 1,
},
_ => Reaped {
failed_entries: 1,
..Reaped::default()
},
};
record(dir, reaped);
reaped
}
fn record(dir: &Path, reaped: Reaped) {
let line = format!(
"{}\t{}\t{}\n",
reaped.freed_entries, reaped.bytes, reaped.failed_entries
);
if let Ok(mut ledger) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(dir.join(LEDGER))
{
let _ = ledger.write_all(line.as_bytes());
}
}
#[must_use]
pub fn collect_ledger(dir: &Path) -> Reaped {
let ledger = dir.join(LEDGER);
let taken = dir.join(format!("{LEDGER}.{}", std::process::id()));
if std::fs::rename(&ledger, &taken).is_err() {
return Reaped::default();
}
let text = std::fs::read_to_string(&taken).unwrap_or_default();
let _ = std::fs::remove_file(&taken);
let mut total = Reaped::default();
for line in text.lines() {
let mut fields = line.split('\t').map(|field| field.parse::<u64>().unwrap_or(0));
total.add(Reaped {
freed_entries: fields.next().unwrap_or(0),
bytes: fields.next().unwrap_or(0),
failed_entries: fields.next().unwrap_or(0),
});
}
total
}
#[cfg(unix)]
fn lock(dir: &Path) -> std::io::Result<std::fs::File> {
use std::os::fd::AsRawFd;
let file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(dir.join(LOCK))?;
if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(file)
}
#[cfg(not(unix))]
fn lock(dir: &Path) -> std::io::Result<std::fs::File> {
std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(dir.join(LOCK))
}
pub fn spawn_reaper() -> std::io::Result<Option<u32>> {
if detached_count() == 0 {
return Ok(None);
}
let Some(location) = trash_location() else {
return Ok(None);
};
spawn_at(&location)
}
pub fn spawn_reaper_for_pending() -> std::io::Result<Option<u32>> {
let Some(location) = trash_location() else {
return Ok(None);
};
if Trash::at(&location)?.pending().is_empty() {
return Ok(None);
}
spawn_at(&location)
}
fn spawn_at(location: &Path) -> std::io::Result<Option<u32>> {
let mut command = std::process::Command::new(std::env::current_exe()?);
command
.args(["reap", "--background"])
.env(TRASH_ENV, location)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut command, 0);
Ok(Some(command.spawn()?.id()))
}
pub fn yield_to_foreground() {
#[cfg(unix)]
unsafe {
libc::setpriority(libc::PRIO_PROCESS, 0, 10);
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use crate::testing::tree;
#[expect(clippy::expect_used, reason = "a fixture that fails a rail is the failure report")]
fn verified(guard: &Guard, path: &Path) -> Verified {
guard.check(path).expect("the fixture passes every rail")
}
#[test]
fn should_move_an_artifact_into_the_trash_in_one_rename_and_free_it_on_reap() {
let root = tree(&[
"project/target/debug/a.o",
"project/target/debug/b.o",
"project/src/main.rs",
]);
let trash_dir = root.path().join("trash");
let trash = Trash::at(&trash_dir).unwrap();
let guard = Guard::new(&[root.path().join("project")], true).unwrap();
let artifact = root.path().join("project/target");
assert!(trash.detach(&verified(&guard, &artifact), false).unwrap().is_ok());
assert!(!artifact.exists(), "the artifact has left its tree");
assert!(root.path().join("project/src/main.rs").exists(), "the source stays");
assert_eq!(trash.pending().len(), 1);
let reaped = reap(&trash_dir).unwrap();
assert_eq!(reaped.freed_entries, 1);
assert_eq!(reaped.failed_entries, 0);
assert!(reaped.bytes > 0, "the reaper counts what it frees");
assert_eq!(trash.pending(), [] as [std::path::PathBuf; 0]);
assert_eq!(collect_ledger(&trash_dir), reaped, "the ledger agrees with the reap");
assert_eq!(
collect_ledger(&trash_dir),
Reaped::default(),
"and is cleared once collected"
);
}
#[test]
fn should_not_detach_an_artifact_the_trash_is_inside() {
let root = tree(&["cache/voom/keep"]);
let trash = Trash::at(&root.path().join("cache/voom/trash")).unwrap();
let guard = Guard::new(&[root.path().to_path_buf()], true).unwrap();
assert!(
trash
.detach(&verified(&guard, &root.path().join("cache")), false)
.is_none()
);
assert!(root.path().join("cache/voom/keep").exists());
}
#[test]
fn should_refuse_a_trash_that_is_a_symlink() {
let root = tree(&["elsewhere/precious"]);
std::os::unix::fs::symlink(root.path().join("elsewhere"), root.path().join("trash")).unwrap();
assert!(Trash::at(&root.path().join("trash")).is_err());
}
#[test]
fn should_keep_the_force_setting_for_the_reaper() {
let root = tree(&["project/target/locked/file"]);
let trash_dir = root.path().join("trash");
let trash = Trash::at(&trash_dir).unwrap();
let guard = Guard::new(&[root.path().join("project")], true).unwrap();
let artifact = root.path().join("project/target");
assert!(trash.detach(&verified(&guard, &artifact), true).unwrap().is_ok());
let entry = trash.pending().pop().unwrap();
assert!(forced(&entry));
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(entry.join("locked"), std::fs::Permissions::from_mode(0o500)).unwrap();
}
let reaped = reap(&trash_dir).unwrap();
assert_eq!(reaped.failed_entries, 0, "a forced entry is repaired and freed");
assert_eq!(trash.pending(), [] as [std::path::PathBuf; 0]);
}
#[test]
fn should_repair_an_entry_whose_directory_kept_a_read_only_bit() {
use std::os::unix::fs::PermissionsExt;
let root = tree(&["project/target/locked/file"]);
let trash_dir = root.path().join("trash");
let trash = Trash::at(&trash_dir).unwrap();
let guard = Guard::new(&[root.path().join("project")], true).unwrap();
assert!(
trash
.detach(&verified(&guard, &root.path().join("project/target")), false)
.unwrap()
.is_ok()
);
let entry = trash.pending().pop().unwrap();
std::fs::set_permissions(entry.join("locked"), std::fs::Permissions::from_mode(0o500)).unwrap();
let reaped = reap(&trash_dir).unwrap();
assert_eq!(
reaped.failed_entries, 0,
"the trash retries with repair, it does not give up"
);
assert_eq!(trash.pending(), [] as [std::path::PathBuf; 0], "the entry is gone");
}
}