use std::path::PathBuf;
use crate::error::SorterError;
#[derive(Debug, Default)]
pub(crate) struct AsyncCleanupGuard {
dir: Option<PathBuf>,
}
impl AsyncCleanupGuard {
pub(crate) fn disarmed() -> Self {
Self { dir: None }
}
pub(crate) fn arm(&mut self, dir: PathBuf) {
self.dir.get_or_insert(dir);
}
pub(crate) async fn cleanup(&mut self) -> Result<(), SorterError> {
let Some(dir) = self.dir.take() else {
return Ok(());
};
async_fs_io::remove_dir_all(&dir).await.map_err(Into::into)
}
}
impl Drop for AsyncCleanupGuard {
fn drop(&mut self) {
let Some(dir) = self.dir.take() else {
return;
};
let Ok(handle) = tokio::runtime::Handle::try_current() else {
tracing::error!(
dir = %dir.display(),
"sort scratch cleanup was dropped outside a Tokio runtime"
);
return;
};
handle.spawn(async move {
if let Err(err) = async_fs_io::remove_dir_all(&dir).await {
tracing::error!(dir = %dir.display(), error = %err, "sort scratch cleanup failed");
}
});
}
}