diff --git a/crates/suite-account/src/lock.rs b/crates/suite-account/src/lock.rs index 6a95e6bd2a..74906014b6 100644 --- a/crates/suite-account/src/lock.rs +++ b/crates/suite-account/src/lock.rs @@ -17,15 +17,51 @@ use std::fs::{self, File, OpenOptions}; use std::io; use std::path::{Path, PathBuf}; -use std::time::{Duration, Instant}; +use std::time::{Duration, Instant, SystemTime}; use crate::error::Error; -/// How long to wait for another process holding the lock before giving up. Long enough that a -/// normal read-change-write of a few-hundred-byte file never times out under load; short enough -/// that a process holding the lock across a crash does not wedge every other app indefinitely. +/// How long one hold of the lock by another process may last before a waiter gives up. Long enough +/// that a normal read-change-write of a few-hundred-byte file never times out under load; short +/// enough that a process stuck holding the lock does not wedge every other app indefinitely. The +/// wait starts again whenever another hold begins, so a waiter behind a long run of short holds +/// (another app signing in many accounts) keeps waiting. const LOCK_TIMEOUT: Duration = Duration::from_secs(5); const POLL_INTERVAL: Duration = Duration::from_millis(20); +/// Every hold sets the lock file's length to the next value in `1..=HOLDS`, which also moves its +/// modification time, so a waiter can see that the lock changed hands between two polls. The length +/// repeats every `HOLDS` holds; the modification time tells apart two holds that left the same length. +const HOLDS: u64 = 64; + +/// What a waiter reads from the lock file: its length and, when the file system reports one, its +/// modification time. +type HoldMark = (u64, Option); + +/// A waiter's view of the holds it has waited through. +struct Wait { + since: Instant, + hold: Option, +} + +impl Wait { + fn new(now: Instant, hold: Option) -> Self { + Wait { since: now, hold } + } + + /// Whether to give up, seeing `hold` (the lock file's mark, when it could be read) at `now`. + fn expired(&mut self, now: Instant, hold: Option) -> bool { + if hold.is_some() && hold != self.hold { + self.hold = hold; + self.since = now; + return false; + } + now.saturating_duration_since(self.since) > LOCK_TIMEOUT + } +} + +fn hold_mark(lock: &File) -> Option { + lock.metadata().ok().map(|m| (m.len(), m.modified().ok())) +} fn lock_path(path: &Path) -> PathBuf { let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts.json"); @@ -51,12 +87,12 @@ pub(crate) fn with_lock(path: &Path, f: impl FnOnce() -> Result) -> let lock = open_lock_file(path).map_err(|e| Error::Io(format!("couldn't open the lock beside {} ({e})", path.display())))?; #[cfg(windows)] let _prepared = crate::accounts::prepare(path); - let start = Instant::now(); + let mut wait = Wait::new(Instant::now(), hold_mark(&lock)); loop { match lock.try_lock() { Ok(()) => break, Err(fs::TryLockError::WouldBlock) => { - if start.elapsed() > LOCK_TIMEOUT { + if wait.expired(Instant::now(), hold_mark(&lock)) { return Err(Error::Io(format!("timed out waiting for the accounts lock on {}", path.display()))); } std::thread::sleep(POLL_INTERVAL); @@ -66,6 +102,10 @@ pub(crate) fn with_lock(path: &Path, f: impl FnOnce() -> Result) -> } } } + // A failure here only costs waiters the restart of their timeout for this hold. + if let Some((n, _)) = hold_mark(&lock) { + let _ = lock.set_len(n % HOLDS + 1); + } let result = f(); let _ = lock.unlock(); result @@ -88,6 +128,67 @@ mod tests { assert!(with_lock(&path, || Ok(true)).unwrap(), "the lock is free again once `with_lock` returns"); } + #[test] + fn a_waiter_behind_many_short_holds_keeps_waiting() { + let t0 = Instant::now(); + let step = Duration::from_secs(1); + let mut wait = Wait::new(t0, Some((1, None))); + // Sixty seconds of holds that each last one second: far past `LOCK_TIMEOUT` in all. + for i in 1..=60u32 { + let hold = Some((u64::from(i) % HOLDS + 1, None)); + assert!(!wait.expired(t0 + step * i, hold), "gave up after {i} s behind holds that kept changing"); + } + } + + #[test] + fn a_waiter_that_misses_a_whole_cycle_of_lengths_keeps_waiting() { + let t0 = Instant::now(); + let first = SystemTime::UNIX_EPOCH + Duration::from_secs(1_000); + let mut wait = Wait::new(t0, Some((1, Some(first)))); + // `HOLDS` holds of 80 ms each went by between two polls and the last one left the length at + // 1 again; only the modification time shows that the lock changed hands. + let later = first + Duration::from_millis(80) * 64; + assert!(!wait.expired(t0 + Duration::from_millis(5_070), Some((1, Some(later))))); + } + + #[test] + fn the_mark_tells_apart_two_holds_that_leave_the_same_length() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("accounts.json"); + with_lock(&path, || Ok(())).unwrap(); + let lock = open_lock_file(&path).unwrap(); + let before = hold_mark(&lock).unwrap(); + let Some(modified) = before.1 else { return }; + lock.set_modified(modified + Duration::from_secs(1)).unwrap(); + let after = hold_mark(&lock).unwrap(); + assert_eq!(before.0, after.0); + assert_ne!(before, after, "a new hold that leaves the same length must still change the mark"); + } + + #[test] + fn a_waiter_gives_up_on_one_hold_that_lasts_past_the_timeout() { + let t0 = Instant::now(); + let mut wait = Wait::new(t0, Some((3, None))); + assert!(!wait.expired(t0 + LOCK_TIMEOUT, Some((3, None)))); + assert!(wait.expired(t0 + LOCK_TIMEOUT + Duration::from_millis(1), Some((3, None)))); + // Without a readable length the timeout counts from the start of the wait. + let mut blind = Wait::new(t0, None); + assert!(!blind.expired(t0 + LOCK_TIMEOUT, None)); + assert!(blind.expired(t0 + LOCK_TIMEOUT + Duration::from_millis(1), None)); + } + + #[test] + fn each_hold_marks_the_lock_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("accounts.json"); + let mut seen = Vec::new(); + for _ in 0..3 { + with_lock(&path, || Ok(())).unwrap(); + seen.push(fs::metadata(lock_path(&path)).unwrap().len()); + } + assert_eq!(seen, [1, 2, 3]); + } + #[test] fn an_error_from_the_closure_still_releases_the_lock() { let dir = tempfile::tempdir().unwrap();