Medlar/crates/core/src/disk.rs
2026-11-25 14:03:30 -06:00

353 lines
13 KiB
Rust

//! The file on disk while it downloads: `name.medlar`, renamed when it is whole.
//!
//! Everything here blocks, except `write_at`.
use crate::http::name;
use rustix::fs::{CWD, FallocateFlags, RenameFlags, fallocate, fstatvfs, renameat_with};
use rustix::io::Errno;
use std::collections::HashSet;
use std::fs::{File, OpenOptions, TryLockError};
use std::io;
use std::os::unix::fs::{FileExt, MetadataExt};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard};
pub const ENDING: &str = ".medlar";
#[derive(Debug)]
pub enum Error {
/// Not enough free space, seen before writing.
NoSpace { need: u64, free: u64 },
/// Another process is writing this file.
Busy,
Io(io::Error),
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Error {
Error::Io(e)
}
}
impl From<Errno> for Error {
fn from(e: Errno) -> Error {
Error::Io(e.into())
}
}
pub type Result<T> = std::result::Result<T, Error>;
/// Held by whoever looks for a free name, until the file is there: two downloads must not settle on the same one.
pub(crate) fn names() -> MutexGuard<'static, ()> {
static NAMES: Mutex<()> = Mutex::new(());
NAMES.lock().unwrap_or_else(|e| e.into_inner())
}
/// Locked against a second Medlar while it is open.
#[derive(Debug)]
pub struct PartialFile {
file: Arc<File>,
path: PathBuf,
}
impl PartialFile {
/// Starts a file in `folder`, under `name` or a numbered variant of it that is free and not in `used`. Returns the name it
/// took. `used` are the names of other downloads there, whose files may be empty or missing for now.
/// Hold `names` until the name is recorded.
pub fn create(folder: &Path, name: &str, used: &HashSet<String>) -> Result<(PartialFile, String)> {
std::fs::create_dir_all(folder)?;
for name in variants(name) {
if used.contains(&name) || exists(&folder.join(&name))? {
continue;
}
let path = partial_path(folder, &name);
let file = match OpenOptions::new().read(true).write(true).create_new(true).open(&path) {
Ok(file) => file,
// Empty and not locked: left by a kill right after it was made. Nothing is lost by taking it.
Err(e) if e.kind() == io::ErrorKind::AlreadyExists && is_empty_file(&path) => open(&path)?,
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e.into()),
};
match lock(&file) {
Ok(()) if file.metadata()?.len() == 0 => return Ok((PartialFile { file: Arc::new(file), path }, name)),
Ok(()) | Err(Error::Busy) => continue,
Err(e) => return Err(e),
}
}
unreachable!("variants never end")
}
/// The file of a download that was started before. None when it is gone.
pub fn reopen(folder: &Path, name: &str) -> Result<Option<PartialFile>> {
PartialFile::hold(partial_path(folder, name))
}
/// The same for a partial file anywhere.
pub(crate) fn hold(path: PathBuf) -> Result<Option<PartialFile>> {
let file = match open(&path) {
Ok(file) => file,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e.into()),
};
lock(&file)?;
Ok(Some(PartialFile { file: Arc::new(file), path }))
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn size(&self) -> Result<u64> {
Ok(self.file.metadata()?.len())
}
/// Takes the space for `size` bytes, or fails before anything is written. Filesystems that can't reserve get a sparse file.
pub fn reserve(&self, size: u64) -> Result<()> {
let meta = self.file.metadata()?;
let need = size.saturating_sub(meta.blocks() * 512);
let fs = fstatvfs(&self.file)?;
// Some network filesystems don't say.
if fs.f_blocks > 0 {
let free = fs.f_bavail.saturating_mul(fs.f_frsize);
if need > free {
return Err(Error::NoSpace { need, free });
}
}
if size > meta.len() {
match fallocate(&self.file, FallocateFlags::empty(), 0, size) {
Ok(()) => {}
Err(Errno::NOSPC) => return Err(Errno::NOSPC.into()),
Err(_) => self.file.set_len(size)?,
}
}
Ok(())
}
/// Throws the contents away.
pub fn clear(&self) -> Result<()> {
Ok(self.file.set_len(0)?)
}
/// Writes all of `buf[..n]` at `at`, off the async threads, and gives the buffer back.
pub async fn write_at(&self, buf: Vec<u8>, n: usize, at: u64) -> Result<Vec<u8>> {
let file = self.file.clone();
blocking(move || {
file.write_all_at(&buf[..n], at)?;
Ok(buf)
})
.await
}
pub async fn read_at(&self, n: usize, at: u64) -> Result<Vec<u8>> {
let file = self.file.clone();
blocking(move || {
let mut buf = vec![0; n];
file.read_exact_at(&mut buf, at)?;
Ok(buf)
})
.await
}
/// Returns when everything written so far would survive a power cut.
pub fn sync(&self) -> Result<()> {
Ok(self.file.sync_data()?)
}
/// Cuts the file to `size`, syncs it and renames it to `name`, or to a numbered variant when that name is taken by now.
/// `chosen` is called with each name before it is tried, so that a crash can't lose track of the file.
pub fn finish<E: From<Error>>(
mut self,
name: &str,
size: u64,
mut chosen: impl FnMut(&str) -> std::result::Result<(), E>,
) -> std::result::Result<PathBuf, E> {
let io = |e: io::Error| E::from(Error::Io(e));
self.file.set_len(size).map_err(io)?;
self.file.sync_all().map_err(io)?;
let folder = self.path.parent().unwrap_or(Path::new("/")).to_path_buf();
let _names = names();
for variant in variants(name) {
let to = folder.join(&variant);
let from = partial_path(&folder, &variant);
if exists(&to).map_err(io)? || (from != self.path && exists(&from).map_err(io)?) {
continue;
}
// Under both names for a moment, so that it can be found whichever name a crash leaves us with.
let old = (from != self.path).then(|| std::mem::replace(&mut self.path, from));
if let Some(old) = &old
&& std::fs::hard_link(old, &self.path).is_err()
{
rename_new(old, &self.path).map_err(io)?;
}
chosen(&variant)?;
if let Some(old) = &old {
let _ = std::fs::remove_file(old);
}
match rename_new(&self.path, &to) {
Ok(()) => {
// Not every filesystem can sync a folder; the file itself is safe already.
let _ = File::open(&folder).and_then(|d| d.sync_all());
return Ok(to);
}
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(io(e)),
}
}
unreachable!("variants never end")
}
}
/// Bytes left for a folder that may not be there yet. None when its drive doesn't say. May wait for a slow drive.
pub fn free(folder: &Path) -> Option<u64> {
let there = folder.ancestors().find(|f| f.is_dir())?;
let stat = rustix::fs::statvfs(there).ok()?;
Some(stat.f_bavail.saturating_mul(stat.f_frsize))
}
pub fn partial_path(folder: &Path, name: &str) -> PathBuf {
folder.join(format!("{name}{ENDING}"))
}
/// Runs blocking file work off the async threads.
pub(crate) async fn blocking<T: Send + 'static, E: Send + 'static>(
work: impl FnOnce() -> std::result::Result<T, E> + Send + 'static,
) -> std::result::Result<T, E> {
match tokio::task::spawn_blocking(work).await {
Ok(result) => result,
Err(e) => std::panic::resume_unwind(e.into_panic()),
}
}
/// `a.zip`, `a (1).zip`, `a (2).zip` …
pub(crate) fn variants(name: &str) -> impl Iterator<Item = String> {
let (stem, ext) = name::split(name);
// Keep `.tar.gz` together.
let (stem, ext) = match stem.strip_suffix(".tar") {
Some(s) if ext.is_some() && !s.is_empty() => (s, &name[s.len()..]),
_ => (stem, &name[stem.len()..]),
};
let (stem, ext) = (stem.to_string(), ext.to_string());
(0u64..).map(move |n| if n == 0 { format!("{stem}{ext}") } else { format!("{stem} ({n}){ext}") })
}
/// Also true for a link that points nowhere.
pub(crate) fn exists(path: &Path) -> io::Result<bool> {
match path.symlink_metadata() {
Ok(_) => Ok(true),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(e),
}
}
fn is_empty_file(path: &Path) -> bool {
path.symlink_metadata().is_ok_and(|m| m.is_file() && m.len() == 0)
}
fn open(path: &Path) -> io::Result<File> {
OpenOptions::new().read(true).write(true).open(path)
}
fn lock(file: &File) -> Result<()> {
match file.try_lock() {
Err(TryLockError::WouldBlock) => Err(Error::Busy),
// Some network filesystems have no locks.
Ok(()) | Err(TryLockError::Error(_)) => Ok(()),
}
}
/// Renames without ever replacing a file.
pub(crate) fn rename_new(from: &Path, to: &Path) -> io::Result<()> {
match renameat_with(CWD, from, CWD, to, RenameFlags::NOREPLACE) {
Err(Errno::INVAL | Errno::NOSYS | Errno::NOTSUP) => rename_over_placeholder(from, to),
other => Ok(other?),
}
}
/// For filesystems without NOREPLACE: take the name with an empty file, then replace that.
fn rename_over_placeholder(from: &Path, to: &Path) -> io::Result<()> {
OpenOptions::new().write(true).create_new(true).open(to)?;
std::fs::rename(from, to)
}
#[cfg(test)]
mod tests {
use super::*;
use std::convert::Infallible;
#[derive(Debug)]
struct Fail;
impl From<Error> for Fail {
fn from(_: Error) -> Fail {
Fail
}
}
impl From<Infallible> for Fail {
fn from(_: Infallible) -> Fail {
Fail
}
}
fn finish(f: PartialFile, name: &str, size: u64) -> PathBuf {
f.finish(name, size, |_| Ok::<(), Fail>(())).unwrap()
}
#[test]
fn nothing_is_overwritten() {
let dir = tempfile::tempdir().unwrap();
let d = dir.path();
std::fs::write(d.join("a.tar.gz"), "mine").unwrap();
std::fs::write(d.join("a (1).tar.gz.medlar"), "half").unwrap();
std::os::unix::fs::symlink("/nowhere", d.join("a (2).tar.gz")).unwrap();
let (f, name) = PartialFile::create(d, "a.tar.gz", &HashSet::new()).unwrap();
assert_eq!(name, "a (3).tar.gz");
f.reserve(10).unwrap();
// Someone takes the name while it downloads.
std::fs::write(d.join(&name), "other").unwrap();
assert_eq!(finish(f, &name, 10), d.join("a (3) (1).tar.gz"));
assert_eq!(std::fs::read(d.join("a.tar.gz")).unwrap(), b"mine");
assert_eq!(std::fs::read(d.join("a (3).tar.gz")).unwrap(), b"other");
assert!(!partial_path(d, &name).exists());
std::fs::write(d.join("x"), "x").unwrap();
for rename in [rename_new, rename_over_placeholder] {
assert_eq!(rename(&d.join("x"), &d.join("a.tar.gz")).unwrap_err().kind(), io::ErrorKind::AlreadyExists);
}
rename_over_placeholder(&d.join("x"), &d.join("y")).unwrap();
assert_eq!(std::fs::read(d.join("y")).unwrap(), b"x");
}
#[test]
fn one_writer_and_empty_leftovers() {
let dir = tempfile::tempdir().unwrap();
let (first, name) = PartialFile::create(dir.path(), "f.bin", &HashSet::new()).unwrap();
let (_second, other) = PartialFile::create(dir.path(), "f.bin", &HashSet::new()).unwrap();
assert_eq!((name.as_str(), other.as_str()), ("f.bin", "f (1).bin"));
assert!(matches!(PartialFile::reopen(dir.path(), "f.bin"), Err(Error::Busy)));
drop(first);
assert!(PartialFile::reopen(dir.path(), "f.bin").unwrap().is_some());
assert_eq!(PartialFile::create(dir.path(), "f.bin", &HashSet::new()).unwrap().1, "f.bin");
// Empty, but another download's.
assert_eq!(PartialFile::create(dir.path(), "f.bin", &HashSet::from(["f.bin".into()])).unwrap().1, "f (2).bin");
assert!(PartialFile::reopen(dir.path(), "gone").unwrap().is_none());
}
#[test]
fn space_is_checked_before_writing() {
let dir = tempfile::tempdir().unwrap();
let (f, _) = PartialFile::create(dir.path(), "f", &HashSet::new()).unwrap();
assert!(matches!(f.reserve(1 << 50), Err(Error::NoSpace { need, free }) if need > free));
assert_eq!(f.size().unwrap(), 0);
f.reserve(100_000).unwrap();
assert_eq!(f.size().unwrap(), 100_000);
}
#[tokio::test]
async fn a_full_disk_is_an_error() {
let file = Arc::new(open(Path::new("/dev/full")).unwrap());
let f = PartialFile { file, path: "/dev/full".into() };
match f.write_at(vec![0; 10], 10, 0).await {
Err(Error::Io(e)) => assert_eq!(e.kind(), io::ErrorKind::StorageFull),
other => panic!("{other:?}"),
}
}
}