diff --git a/crates/cloud-local/README.md b/crates/cloud-local/README.md index a5006c2ca3..a2e7cf0ca8 100644 --- a/crates/cloud-local/README.md +++ b/crates/cloud-local/README.md @@ -37,3 +37,16 @@ write never truncates its target in place. It writes a new sibling file and rena over the target, so the target's directory entry is replaced rather than its bytes being overwritten. A rename only ever changes one name; it does not reach through to any other name, inside the root or out, that happens to point at the same inode. + +## Concurrent saves + +A `Job::Write` checks the file's etag again just before the rename, and holds one lock for this +process from that check until the rename is done. Within one process, two saves made from the +same etag cannot both succeed: the second gets `Fault::Conflict`. A second process writing the +same folder does not take that lock, so its save can still land between the check and the rename. +A deployment that needs the guarantee across processes needs a backend whose provider offers a +conditional write. + +The etag is the file's length and modification time. On a filesystem whose timestamps are coarser +than the time between two saves, two saves of the same length can leave the same etag, and the +second save is then not refused. diff --git a/crates/cloud-local/src/lib.rs b/crates/cloud-local/src/lib.rs index 715a870842..a34d82b826 100644 --- a/crates/cloud-local/src/lib.rs +++ b/crates/cloud-local/src/lib.rs @@ -62,6 +62,7 @@ use std::ffi::OsStr; use std::fs; use std::io::{Read as _, Write as _}; use std::path::{Component, Path, PathBuf}; +use std::sync::Mutex; use std::sync::atomic::{AtomicU64, Ordering}; use cap_std::fs::{Dir, OpenOptions}; @@ -322,27 +323,41 @@ fn read(root: &Path, entry: &Entry) -> Result<(Entry, Vec), Fault> { /// so a hard link sharing the target's inode keeps its own, unmodified copy: /// the rename replaces `entry.id`'s directory entry, and never reaches /// through to any other name pointing at the same inode. +/// +/// The etag is checked once before any bytes are written, and again under +/// [`WRITE_LOCK`] just before the rename. Two saves made from the same etag +/// at once otherwise both pass the check before either renames, both report +/// success, and the later rename replaces the first save without a +/// [`Fault::Conflict`]. fn write(root: &Path, entry: &Entry, bytes: &[u8]) -> Result { let rel = relative(&entry.id)?; let dir = open_root(root)?; - match dir.symlink_metadata(&rel) { - Ok(meta) if meta.is_symlink() => return Err(Fault::Refused("that path is a link, not a plain file".to_owned())), - Ok(meta) => { - if Some(etag_of(&meta)) != entry.etag { - return Err(Fault::Conflict); - } - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(io_fault(&error)), - } + check_unchanged(&dir, &rel, entry)?; if let Some(parent) = rel.parent() { dir.create_dir_all(parent).map_err(|error| io_fault(&error))?; } - write_replacing(&dir, &rel, bytes)?; - let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?; + let meta = write_replacing(&dir, &rel, bytes, || check_unchanged(&dir, &rel, entry))?; Ok(Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() }) } +/// Refuses a link at `rel`, and a file whose etag is no longer `entry.etag`. +/// A file that does not exist passes. +fn check_unchanged(dir: &Dir, rel: &Path, entry: &Entry) -> Result<(), Fault> { + match dir.symlink_metadata(rel) { + Ok(meta) if meta.is_symlink() => Err(Fault::Refused("that path is a link, not a plain file".to_owned())), + Ok(meta) if Some(etag_of(&meta)) != entry.etag => Err(Fault::Conflict), + Ok(_) => Ok(()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(io_fault(&error)), + } +} + +/// Held by [`write_replacing`] from its last check until the rename is done +/// and the new file's metadata is read, so no other save in this process can +/// change the file in between. The temporary file is written and synced +/// before the lock is taken, so a slow save does not hold up the others. +static WRITE_LOCK: Mutex<()> = Mutex::new(()); + /// The next in a run of sibling temporary names, unique within this process. /// Not meant to resist a second process picking the same name; the create /// this writes with is exclusive (`create_new`), so a collision there is @@ -355,7 +370,11 @@ static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); /// be a hard link to a file outside `root`, the outside copy would be /// corrupted along with it. A rename only ever replaces `rel`'s own /// directory entry. -fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8]) -> Result<(), Fault> { +/// +/// `check` runs under [`WRITE_LOCK`] right before the rename; when it fails, +/// the temporary file is removed and `rel` is left as it was. Returns the +/// metadata of the file just published. +fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8], check: impl FnOnce() -> Result<(), Fault>) -> Result { let name = rel.file_name().ok_or_else(|| Fault::Refused("that path names no file".to_owned()))?; let mut temp_name = OsStr::new(".").to_os_string(); temp_name.push(name); @@ -375,11 +394,21 @@ fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8]) -> Result<(), Fault> { let _ = dir.remove_file(&temp_rel); return Err(fault); } - if let Err(error) = dir.rename(&temp_rel, dir, rel) { + #[cfg(test)] + tests::before_lock(); + let published = { + let _serialized = WRITE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + check().and_then(|()| { + #[cfg(test)] + tests::after_check(); + dir.rename(&temp_rel, dir, rel).map_err(|error| io_fault(&error))?; + dir.metadata(rel).map_err(|error| io_fault(&error)) + }) + }; + if published.is_err() { let _ = dir.remove_file(&temp_rel); - return Err(io_fault(&error)); } - Ok(()) + published } fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result { @@ -435,6 +464,85 @@ fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result; + static AFTER_CHECK: Mutex> = Mutex::new(None); + + pub(super) fn after_check() { + let hook = AFTER_CHECK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + if let Some(hook) = hook { + hook(); + } + } + + /// Run once by the next [`write_replacing`] to finish its temporary file, + /// before it takes [`WRITE_LOCK`], then cleared. + static BEFORE_LOCK: Mutex> = Mutex::new(None); + + pub(super) fn before_lock() { + let hook = BEFORE_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take(); + if let Some(hook) = hook { + hook(); + } + } + + fn entry_for(id: &str) -> Entry { + Entry { + room: format!("local:{id}"), + name: id.trim_start_matches('/').to_owned(), + kind: EntryKind::File, + size: None, + modified: None, + mime: None, + etag: None, + writable: true, + shared_by: None, + path: id.to_owned(), + id: id.to_owned(), + } + } + + #[test] + fn two_saves_from_one_etag_cannot_both_pass_the_check() { + let root = tempfile::tempdir().unwrap(); + std::fs::write(root.path().join("Note.txt"), b"original").unwrap(); + let (read_entry, _) = read(root.path(), &entry_for("/Note.txt")).unwrap(); + + let (checked_tx, checked_rx) = mpsc::channel::<()>(); + let (go_tx, go_rx) = mpsc::channel::<()>(); + *AFTER_CHECK.lock().unwrap() = Some(Box::new(move || { + checked_tx.send(()).unwrap(); + go_rx.recv().unwrap(); + })); + + let first = { + let (root, entry) = (root.path().to_owned(), read_entry.clone()); + std::thread::spawn(move || write(&root, &entry, b"first save")) + }; + checked_rx.recv().unwrap(); + // The first save has passed its check and not yet renamed. A second + // save must not be able to reach its own check in between. + assert!(WRITE_LOCK.try_lock().is_err(), "the check and the rename must run under one lock"); + // The second save passes its early check and writes its temporary + // file before the first one renames, so only the recheck under the + // lock can refuse it. + let (ready_tx, ready_rx) = mpsc::channel::<()>(); + *BEFORE_LOCK.lock().unwrap() = Some(Box::new(move || ready_tx.send(()).unwrap())); + let second = { + let (root, entry) = (root.path().to_owned(), read_entry.clone()); + std::thread::spawn(move || write(&root, &entry, b"second save")) + }; + ready_rx.recv().unwrap(); + go_tx.send(()).unwrap(); + + assert!(first.join().unwrap().is_ok()); + assert!(matches!(second.join().unwrap(), Err(Fault::Conflict)), "the second save started from a stale etag"); + assert_eq!(std::fs::read(root.path().join("Note.txt")).unwrap(), b"first save"); + let left: Vec<_> = std::fs::read_dir(root.path()).unwrap().map(|item| item.unwrap().file_name()).collect(); + assert_eq!(left, ["Note.txt"], "the refused save's temporary file is removed"); + } #[test] fn a_parent_segment_cannot_walk_out_of_root() {