68 lines · 2.1 KB · RustRaw
//! Cross-process exclusion between a local media snapshot and mutations.//! Readers keep working. A mutation retries instead of waiting while holding//! a database transaction; this avoids a media-lock/database-lock deadlock.use std::fs::{File, OpenOptions};use std::io;use std::path::Path;pub const LOCK_FILE: &str = ".cotton-backup.lock";fn open(root: &Path) -> io::Result<File> { let path = root.join(LOCK_FILE); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } let mut options = OpenOptions::new(); options.read(true).write(true).create(true).truncate(false); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } if std::fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file()) { return Err(io::Error::other("media backup lock must be a regular file")); } options.open(path)}pub fn mutating(root: &Path) -> io::Result<File> { let file = open(root)?; file.try_lock_shared().map_err(|e| { io::Error::new( io::ErrorKind::WouldBlock, format!("media backup in progress; retry the write: {e}"), ) })?; Ok(file)}pub fn snapshot(root: &Path) -> io::Result<File> { let file = open(root)?; file.try_lock().map_err(|e| { io::Error::new( io::ErrorKind::WouldBlock, format!("media is being changed; retry the backup: {e}"), ) })?; Ok(file)}#[cfg(test)]mod tests { use super::*; /// RULE: A snapshot excludes every writer, but concurrent writers and ordinary readers remain possible. #[test] fn snapshot_and_mutations_exclude_each_other() { let dir = tempfile::tempdir().unwrap(); let root = dir.path().join("media"); let one = mutating(&root).unwrap(); let two = mutating(&root).unwrap(); assert!(snapshot(&root).is_err()); drop((one, two)); let backup = snapshot(&root).unwrap(); assert!(mutating(&root).is_err()); assert!(snapshot(&root).is_err()); drop(backup); assert!(mutating(&root).is_ok()); }}