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}: 소유자 외 권한 비트가 남아 있다 (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(), "픽스처가 락 파일을 미리 만들면 안 된다");
let guard = acquire(&path, LOCK_DEADLINE).expect("must acquire");
assert!(path.exists(), "락 파일이 생성돼야 한다");
drop(guard);
assert!(
path.exists(),
"락 해제 후에도 파일은 남아야 한다 (고정 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)),
"두 번째는 타임아웃해야 한다"
);
assert!(
elapsed >= Duration::from_millis(300),
"deadline 이전에 포기했다: {elapsed:?}"
);
assert!(
elapsed < Duration::from_secs(5),
"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 이 락을 풀지 않았다");
}
#[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, "해제 경로에서 락 파일이 바뀌었다");
let second = acquire(&path, LOCK_DEADLINE).expect("second");
assert_eq!(inode_of(&path), ino, "재획득이 락 파일을 새로 만들었다");
drop(second);
assert_eq!(inode_of(&path), ino, "두 번째 해제에서 락 파일이 바뀌었다");
}
#[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)),
"타임아웃해야 한다"
);
assert!(path.exists(), "타임아웃이 락 파일을 지웠다");
assert_eq!(inode_of(&path), ino, "타임아웃이 락 파일을 갈아치웠다");
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(), "패닉이 잡혀야 한다");
let second = acquire(&path, Duration::from_millis(500));
assert!(second.is_ok(), "언와인딩 중 Drop 이 락을 풀지 않았다");
assert!(path.exists(), "언와인딩 경로에서 락 파일이 사라졌다");
}
#[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(),
"비어 있는 락은 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, "deadline 0 인데 재시도했다");
assert!(
started.elapsed() < Duration::from_millis(500),
"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, "실제 입출력 오류에서 재시도했다");
assert!(
started.elapsed() < Duration::from_secs(1),
"실제 오류인데 deadline 까지 기다렸다: {:?}",
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(), "경합은 재시도해야 한다: {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,
"백오프가 자라지 않아 500ms 동안 {}회나 깨어났다",
attempts.get()
);
assert!(
attempts.get() >= 3,
"재시도가 거의 없었다: {}",
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("풀린 락은 잡혀야 한다");
let elapsed = started.elapsed();
assert!(
elapsed < Duration::from_millis(1_500),
"락이 풀렸는데도 오래 잤다: {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("풀린 락은 잡혀야 한다");
let elapsed = started.elapsed();
assert!(
elapsed >= Duration::from_millis(1_400),
"형제가 쥐고 있는 동안 잡혔다: {elapsed:?}"
);
assert!(
elapsed < Duration::from_millis(2_500),
"백오프 상한이 없어 해제 후에도 오래 잤다: {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 가 락 파일 내용을 잘랐다"
);
drop(guard);
assert_eq!(
std::fs::read(&path).expect("read"),
b"KEEP_ME",
"해제가 락 파일 내용을 잘랐다"
);
}
#[test]
fn the_retry_interval_grows_from_the_initial_toward_the_cap() {
assert!(
LOCK_RETRY_INITIAL < LOCK_RETRY_MAX,
"초기 간격이 상한보다 크다"
);
assert!(LOCK_RETRY_MAX <= LOCK_DEADLINE, "상한이 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),
"열 수 없는 경로인데 deadline 까지 기다렸다: {:?}",
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);
}