diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 19c1a37409..0e863fa03d 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -900,10 +900,10 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { } /// The grants the grants file at `store` holds; none when it is missing or cannot be read. A grant -/// that is not well formed is left out. It is read under [`lock_store`]'s lock when that can be -/// taken, so it is read between two changes. +/// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read +/// between two changes, and none are read when the lock cannot be taken. fn read_store(store: &Path) -> Vec { - let _lock = lock_store(store).ok(); + let Ok(_lock) = lock_store(store) else { return Vec::new() }; load_store(store, false).unwrap_or_default() } @@ -983,9 +983,20 @@ fn write_store(store: &Path, grants: Vec) -> std::io::Result< }) } +/// How many times [`lock_store`] tries to take the grants file's lock, [`LOCK_PAUSE`] apart, before +/// it gives up. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const LOCK_TRIES: u32 = 20; + +/// The wait between two tries of [`lock_store`]. +#[cfg(not(target_arch = "wasm32"))] +const LOCK_PAUSE: std::time::Duration = std::time::Duration::from_millis(50); + /// The lock file beside the grants file at `store` (`Script Grants.lock`), locked until it is -/// dropped and waiting while another process holds it, so that processes that read and change the -/// grants file take turns. A change is not made when the lock cannot be taken. +/// dropped, so that processes that read and change the grants file take turns. While another +/// process or handle holds it, the lock is tried [`LOCK_TRIES`] times, [`LOCK_PAUSE`] apart, and +/// then the result is `Err` with [`std::io::ErrorKind::TimedOut`]. A change is not made when the +/// lock cannot be taken. #[cfg(not(target_arch = "wasm32"))] fn lock_store(store: &Path) -> std::io::Result { let lock = store.with_extension("lock"); @@ -993,13 +1004,40 @@ fn lock_store(store: &Path) -> std::io::Result { .parent() .map_or(Ok(()), std::fs::create_dir_all) .and_then(|()| std::fs::File::options().create(true).truncate(false).read(true).write(true).open(&lock)); - let file = opened.and_then(|f| f.lock().map(|()| f)); + let file = opened.and_then(take_lock); if let Err(e) = &file { log::warn!("can't lock {}: {e}", lock.display()); } file } +/// `file`, locked within [`lock_store`]'s tries. +#[cfg(not(target_arch = "wasm32"))] +fn take_lock(file: std::fs::File) -> std::io::Result { + let mut tries = 1; + loop { + match file.try_lock() { + Ok(()) => return Ok(file), + Err(std::fs::TryLockError::Error(e)) => return Err(e), + Err(std::fs::TryLockError::WouldBlock) if tries >= LOCK_TRIES => { + return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "another process holds the lock")); + } + Err(std::fs::TryLockError::WouldBlock) => tries += 1, + } + #[cfg(test)] + if WHILE_GRANTS_LOCKED.with_borrow_mut(|w| w.as_mut().map(|waiting| waiting()).is_some()) { + continue; + } + std::thread::sleep(LOCK_PAUSE); + } +} + +#[cfg(test)] +thread_local! { + /// Tests: runs on this thread in place of each wait of [`lock_store`] for a lock that is held. + pub(crate) static WHILE_GRANTS_LOCKED: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] fn lock_store(_: &Path) -> std::io::Result { diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 1943a11bab..7b5db047ef 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -613,6 +613,42 @@ fn a_grants_change_without_its_lock_changes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// Reading and changing the grants file wait for a lock another handle holds only for a bounded +/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock +/// released while it waits is taken. +#[test] +fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { + use crate::script::files::{LOCK_TRIES, WHILE_GRANTS_LOCKED, revoke_grants, stored_grants}; + let base = folder("grants-lock-held"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + let text = json!({"version": 1, "grants": [grant]}).to_string(); + write(&base.join("settings/Script Grants.json"), text.as_bytes()); + let held = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(base.join("settings/Script Grants.lock")).unwrap(); + held.lock().unwrap(); + let waits = std::rc::Rc::new(std::cell::Cell::new(0)); + let counted = waits.clone(); + WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); + assert_eq!(stored_grants(&data), Vec::::new(), "grants are not read without the lock"); + assert_eq!(waits.get(), LOCK_TRIES - 1); + waits.set(0); + let refused = revoke_grants(&data, None, None); + assert_eq!(refused.map_err(|e| e.kind()), Err(std::io::ErrorKind::TimedOut)); + assert_eq!(waits.get(), LOCK_TRIES - 1, "it waits between tries and gives up after the last"); + assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), text); + let mut released = Some(held); + let counted = waits.clone(); + waits.set(0); + WHILE_GRANTS_LOCKED.set(Some(Box::new(move || { + counted.set(counted.get() + 1); + drop(released.take()); + }))); + assert_eq!(revoke_grants(&data, None, None).unwrap(), 1, "a lock released while it waits is taken"); + assert_eq!(waits.get(), 1); + WHILE_GRANTS_LOCKED.set(None); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() {