use super::*;
use std::cell::Cell;
use std::fs::TryLockError;
use std::os::unix::fs::PermissionsExt as _;
use std::time::{Duration, Instant};
struct TempLock {
dir: std::path::PathBuf,
file: std::path::PathBuf,
}
impl std::ops::Deref for TempLock {
type Target = std::path::Path;
fn deref(&self) -> &std::path::Path {
&self.file
}
}
impl AsRef<std::path::Path> for TempLock {
fn as_ref(&self) -> &std::path::Path {
&self.file
}
}
impl Drop for TempLock {
fn drop(&mut self) {
let _ = std::fs::set_permissions(&self.dir, std::fs::Permissions::from_mode(0o700));
let _ = std::fs::remove_dir_all(&self.dir);
}
}
fn temp_lock_path(tag: &str) -> TempLock {
let dir = std::env::temp_dir().join(format!(
"fleetwire-lock-{tag}-{}-{:?}",
std::process::id(),
std::thread::current().id()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
let file = dir.join("tokens.lock");
TempLock { dir, file }
}
fn mode_of(path: &std::path::Path) -> u32 {
std::fs::metadata(path)
.expect("must exist")
.permissions()
.mode()
& 0o777
}
fn inode_of(path: &std::path::Path) -> u64 {
use std::os::unix::fs::MetadataExt as _;
std::fs::metadata(path).expect("must exist").ino()
}
#[track_caller]
fn assert_owner_only(path: &std::path::Path, what: &str) {
let mode = mode_of(path);
assert_eq!(
mode & 0o077,
0,
"{what}: permission bits for others than the owner remain (mode {mode:o})"
);
}
#[test]
fn acquire_succeeds_on_a_fresh_path_and_creates_the_lock_file() {
let path = temp_lock_path("fresh");
assert!(
!path.exists(),
"the fixture must not create the lock file in advance"
);
let guard = acquire(&path, LOCK_DEADLINE).expect("must acquire");
assert!(path.exists(), "the lock file must be created");
drop(guard);
assert!(
path.exists(),
"the file must remain even after the lock is released (fixed inode)"
);
}
#[test]
fn a_second_holder_times_out_while_the_first_holds_it() {
let path = temp_lock_path("contended");
let first = acquire(&path, LOCK_DEADLINE).expect("first must acquire");
let started = Instant::now();
let second = acquire(&path, Duration::from_millis(300));
let elapsed = started.elapsed();
assert!(
matches!(second, Err(LockError::Timeout)),
"the second must time out"
);
assert!(
elapsed >= Duration::from_millis(300),
"gave up before the deadline: {elapsed:?}"
);
assert!(
elapsed < Duration::from_secs(5),
"greatly exceeded the deadline: {elapsed:?}"
);
drop(first);
}
#[test]
fn the_lock_is_reacquirable_after_the_guard_drops() {
let path = temp_lock_path("reacquire");
drop(acquire(&path, LOCK_DEADLINE).expect("first"));
let second = acquire(&path, Duration::from_millis(500));
assert!(second.is_ok(), "Drop did not release the lock");
}
#[test]
fn the_lock_file_keeps_its_inode_across_acquire_release_cycles() {
let path = temp_lock_path("inode");
let first = acquire(&path, LOCK_DEADLINE).expect("first");
let ino = inode_of(&path);
drop(first);
assert_eq!(
inode_of(&path),
ino,
"the lock file changed on the release path"
);
let second = acquire(&path, LOCK_DEADLINE).expect("second");
assert_eq!(
inode_of(&path),
ino,
"reacquiring created the lock file anew"
);
drop(second);
assert_eq!(
inode_of(&path),
ino,
"the lock file changed on the second release"
);
}
#[test]
fn a_timed_out_acquire_leaves_the_lock_file_in_place() {
let path = temp_lock_path("timeout-keeps");
let first = acquire(&path, LOCK_DEADLINE).expect("first");
let ino = inode_of(&path);
let second = acquire(&path, Duration::from_millis(50));
assert!(matches!(second, Err(LockError::Timeout)), "must time out");
assert!(path.exists(), "the timeout deleted the lock file");
assert_eq!(inode_of(&path), ino, "the timeout replaced the lock file");
drop(first);
}
#[test]
fn the_lock_is_released_when_the_guard_drops_during_a_panic() {
let path = temp_lock_path("panic-unwind");
let guard = acquire(&path, LOCK_DEADLINE).expect("first");
let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
let _held = guard;
panic!("intentional panic: lock must still be released while unwinding");
}));
assert!(caught.is_err(), "the panic must be caught");
let second = acquire(&path, Duration::from_millis(500));
assert!(
second.is_ok(),
"Drop did not release the lock during unwinding"
);
assert!(
path.exists(),
"the lock file disappeared on the unwinding path"
);
}
#[test]
fn a_zero_deadline_still_attempts_the_lock_once() {
let path = temp_lock_path("zero-free");
let guard = acquire(&path, Duration::ZERO);
assert!(
guard.is_ok(),
"a free lock must be acquired even with deadline 0: {:?}",
guard.err()
);
}
#[test]
fn a_zero_deadline_makes_exactly_one_attempt_before_timing_out() {
let attempts = Cell::new(0_u32);
let started = Instant::now();
let outcome = retry_until_locked(Duration::ZERO, || {
attempts.set(attempts.get() + 1);
Err(TryLockError::WouldBlock)
});
assert!(matches!(outcome, Err(LockError::Timeout)), "{outcome:?}");
assert_eq!(attempts.get(), 1, "retried despite deadline 0");
assert!(
started.elapsed() < Duration::from_millis(500),
"slept despite deadline 0: {:?}",
started.elapsed()
);
}
#[test]
fn a_real_lock_error_aborts_immediately_instead_of_retrying() {
let attempts = Cell::new(0_u32);
let started = Instant::now();
let outcome = retry_until_locked(Duration::from_secs(10), || {
attempts.set(attempts.get() + 1);
Err(TryLockError::Error(std::io::Error::other(
"simulated disk failure",
)))
});
assert!(matches!(outcome, Err(LockError::Io(_))), "{outcome:?}");
assert_eq!(attempts.get(), 1, "retried on a real I/O error");
assert!(
started.elapsed() < Duration::from_secs(1),
"waited until the deadline despite a real error: {:?}",
started.elapsed()
);
}
#[test]
fn contention_is_retried_rather_than_treated_as_failure() {
let attempts = Cell::new(0_u32);
let outcome = retry_until_locked(Duration::from_secs(10), || {
attempts.set(attempts.get() + 1);
if attempts.get() < 4 {
Err(TryLockError::WouldBlock)
} else {
Ok(())
}
});
assert!(outcome.is_ok(), "contention must be retried: {outcome:?}");
assert_eq!(attempts.get(), 4);
}
#[test]
fn the_retry_interval_backs_off_instead_of_spinning_at_the_initial_value() {
let attempts = Cell::new(0_u32);
let outcome = retry_until_locked(Duration::from_millis(500), || {
attempts.set(attempts.get() + 1);
Err(TryLockError::WouldBlock)
});
assert!(matches!(outcome, Err(LockError::Timeout)), "{outcome:?}");
assert!(
attempts.get() <= 25,
"the backoff did not grow, so it woke as many as {} times in 500ms",
attempts.get()
);
assert!(
attempts.get() >= 3,
"there were almost no retries: {}",
attempts.get()
);
}
#[test]
fn a_freed_lock_is_picked_up_long_before_the_deadline() {
let path = temp_lock_path("prompt");
let first = acquire(&path, LOCK_DEADLINE).expect("first");
let releaser = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(30));
drop(first);
});
let started = Instant::now();
acquire(&path, Duration::from_secs(5)).expect("a released lock should be acquired");
let elapsed = started.elapsed();
assert!(
elapsed < Duration::from_millis(1_500),
"slept for a long time although the lock was released: {elapsed:?}"
);
releaser.join().expect("releaser");
}
#[test]
fn a_lock_held_for_a_while_is_still_picked_up_promptly_after_release() {
let path = temp_lock_path("cap");
let first = acquire(&path, LOCK_DEADLINE).expect("first");
let releaser = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(1_400));
drop(first);
});
let started = Instant::now();
acquire(&path, LOCK_DEADLINE).expect("a released lock should be acquired");
let elapsed = started.elapsed();
assert!(
elapsed >= Duration::from_millis(1_400),
"acquired while the sibling was still holding it: {elapsed:?}"
);
assert!(
elapsed < Duration::from_millis(2_500),
"no backoff cap, so it slept long even after the release: {elapsed:?}"
);
releaser.join().expect("releaser");
}
#[test]
fn acquiring_does_not_modify_the_lock_file_contents() {
let path = temp_lock_path("no-truncate");
std::fs::write(&path, b"KEEP_ME").expect("seed the lock file");
let guard = acquire(&path, LOCK_DEADLINE).expect("must acquire");
assert_eq!(
std::fs::read(&path).expect("read"),
b"KEEP_ME",
"acquire truncated the lock file contents"
);
drop(guard);
assert_eq!(
std::fs::read(&path).expect("read"),
b"KEEP_ME",
"the release truncated the lock file contents"
);
}
#[test]
fn the_retry_interval_grows_from_the_initial_toward_the_cap() {
assert!(
LOCK_RETRY_INITIAL < LOCK_RETRY_MAX,
"the initial interval is larger than the cap"
);
assert!(
LOCK_RETRY_MAX <= LOCK_DEADLINE,
"the cap is larger than the deadline"
);
}
#[test]
fn an_unopenable_lock_path_is_reported_as_io_without_waiting() {
let path = temp_lock_path("eisdir");
std::fs::create_dir(&path).expect("occupy the lock path with a dir");
let started = Instant::now();
let outcome = acquire(&path, LOCK_DEADLINE);
assert!(matches!(outcome, Err(LockError::Io(_))), "{outcome:?}");
assert!(
started.elapsed() < Duration::from_secs(1),
"waited until the deadline although the path cannot be opened: {:?}",
started.elapsed()
);
}
#[test]
fn acquire_creates_a_missing_lock_directory_owner_only() {
let temp = temp_lock_path("mkdir-mode");
let root = temp.parent().expect("parent").to_path_buf();
let deep = root.join("nested").join("deep");
let guard = acquire(&deep.join("tokens.lock"), LOCK_DEADLINE).expect("must acquire");
assert_owner_only(&root.join("nested"), "lock dir (ancestor)");
assert_owner_only(&deep, "lock dir");
drop(guard);
}
#[test]
fn the_lock_file_is_created_owner_only() {
let path = temp_lock_path("filemode");
let guard = acquire(&path, LOCK_DEADLINE).expect("must acquire");
assert_owner_only(&path, "lock file");
drop(guard);
}