use std::io::{ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub const DEFAULT_LOCK_STALE_AFTER: Duration = Duration::from_secs(30);
pub const DEFAULT_LOCK_WAIT_ATTEMPTS: u32 = 5_000;
pub const DEFAULT_LOCK_WAIT_INTERVAL: Duration = Duration::from_millis(1);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LockDecision {
Takeover { age: Duration },
Wait { age: Option<Duration> },
}
pub fn decide_lock(
age: Option<Duration>,
stale_after: Duration,
takeover_used: bool,
) -> LockDecision {
match age {
Some(age) if age >= stale_after && !takeover_used => LockDecision::Takeover { age },
_ => LockDecision::Wait { age },
}
}
pub fn lock_age(mtime: SystemTime, now: SystemTime) -> Option<Duration> {
let base = mtime.min(now);
now.duration_since(base).ok()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LockPolicy {
pub stale_after: Duration,
pub wait_attempts: u32,
pub wait_interval: Duration,
}
impl Default for LockPolicy {
fn default() -> Self {
Self {
stale_after: DEFAULT_LOCK_STALE_AFTER,
wait_attempts: DEFAULT_LOCK_WAIT_ATTEMPTS,
wait_interval: DEFAULT_LOCK_WAIT_INTERVAL,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LockError {
Contended(String),
Io(String),
}
impl LockError {
pub fn message(&self) -> &str {
match self {
Self::Contended(message) | Self::Io(message) => message,
}
}
}
impl std::fmt::Display for LockError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.message())
}
}
impl std::error::Error for LockError {}
#[derive(Debug)]
pub struct FileLock {
path: PathBuf,
token: String,
}
impl FileLock {
pub fn acquire(path: impl Into<PathBuf>) -> Result<Self, LockError> {
Self::acquire_with(path, LockPolicy::default())
}
pub fn acquire_with(path: impl Into<PathBuf>, policy: LockPolicy) -> Result<Self, LockError> {
let path = path.into();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|error| {
LockError::Io(format!("创建锁目录 {} 失败: {error}", parent.display()))
})?;
}
let mut last_age: Option<Duration> = None;
let mut takeover_used = false;
for _attempt in 0..policy.wait_attempts.max(1) {
match create_lock_file(&path) {
LockCreate::Created(token) => return Ok(Self { path, token }),
LockCreate::Busy => {
match decide_lock(age_of(&path), policy.stale_after, takeover_used) {
LockDecision::Takeover { age } => {
last_age = Some(age);
takeover_used = true;
match age_of(&path) {
Some(age) if age >= policy.stale_after => {
let _ = std::fs::remove_file(&path);
}
_ => {}
}
}
LockDecision::Wait { age } => {
last_age = age;
if policy.wait_interval > Duration::ZERO {
std::thread::sleep(policy.wait_interval);
}
}
}
}
LockCreate::Failed(error) => {
return Err(LockError::Io(format!(
"创建锁文件 {} 失败: {error}",
path.display()
)))
}
}
}
Err(LockError::Contended(lock_contention_message(
&path, last_age, &policy,
)))
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for FileLock {
fn drop(&mut self) {
let still_ours = std::fs::read_to_string(&self.path)
.map(|text| text.trim() == self.token.trim())
.unwrap_or(false);
if still_ours {
let _ = std::fs::remove_file(&self.path);
}
}
}
pub fn lock_contention_message(path: &Path, age: Option<Duration>, policy: &LockPolicy) -> String {
let holder = std::fs::read_to_string(path)
.ok()
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty());
let holder_note = match holder.as_deref() {
Some(value) => format!("holder={value}"),
None => "无持有者登记".to_string(),
};
match age {
Some(age) if age >= policy.stale_after => format!(
"锁文件 {} 由 {holder_note} 持有已超过 {} 秒却仍未接管成功(可能有进程在同一时刻\
抢下又崩溃);请确认没有进程正在写入,再删除该文件",
path.display(),
age.as_secs()
),
Some(age) => format!(
"锁文件 {} 由 {holder_note} 在 {} 毫秒前创建,尚未达到 {} 秒的孤儿判定,\
已等待 {} 次;请让并发写者完成后重试",
path.display(),
age.as_millis(),
policy.stale_after.as_secs(),
policy.wait_attempts
),
None => format!(
"锁文件 {} 正在被创建或删除,无法读出年龄,已等待 {} 次;请稍后重试",
path.display(),
policy.wait_attempts
),
}
}
enum LockCreate {
Created(String),
Busy,
Failed(String),
}
fn lock_token() -> String {
static LOCK_TOKEN_SERIAL: AtomicU64 = AtomicU64::new(0);
let serial = LOCK_TOKEN_SERIAL.fetch_add(1, Ordering::Relaxed);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|elapsed| elapsed.as_nanos())
.unwrap_or(0);
format!("{}-{}-{}", std::process::id(), serial, nanos)
}
fn create_lock_file(path: &Path) -> LockCreate {
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
let token = lock_token();
match options.open(path) {
Ok(mut file) => {
let _ = file.write_all(token.as_bytes());
LockCreate::Created(token)
}
Err(error)
if matches!(
error.kind(),
ErrorKind::AlreadyExists | ErrorKind::PermissionDenied
) =>
{
LockCreate::Busy
}
Err(error) => LockCreate::Failed(error.to_string()),
}
}
fn age_of(path: &Path) -> Option<Duration> {
let mtime = std::fs::metadata(path)
.and_then(|meta| meta.modified())
.ok()?;
lock_age(mtime, SystemTime::now())
}
#[cfg(test)]
mod tests {
use super::*;
fn temp_dir(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"qx-file-lock-{name}-{}-{}",
std::process::id(),
SystemTime::UNIX_EPOCH
.elapsed()
.unwrap_or_default()
.as_nanos()
));
std::fs::create_dir_all(&dir).expect("create temp dir");
dir
}
fn touch_with_age(path: &Path, age: Duration) {
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.expect("create lock")
.set_modified(SystemTime::now() - age)
.expect("backdate lock");
}
#[test]
fn decision_is_pure_and_bounded() {
let stale = Duration::from_secs(30);
assert_eq!(
decide_lock(Some(stale), stale, false),
LockDecision::Takeover { age: stale }
);
assert_eq!(
decide_lock(Some(stale - Duration::from_millis(1)), stale, false),
LockDecision::Wait {
age: Some(stale - Duration::from_millis(1))
}
);
assert_eq!(
decide_lock(None, stale, false),
LockDecision::Wait { age: None },
"读不到年龄必须等,不能抢"
);
}
#[test]
fn second_stale_sighting_in_one_competition_waits_instead_of_deleting() {
let stale = Duration::from_secs(3600);
assert_eq!(
decide_lock(Some(stale), Duration::from_secs(30), true),
LockDecision::Wait { age: Some(stale) },
"已经接管过一次就不得再删别人的锁"
);
assert_eq!(
decide_lock(Some(stale), Duration::from_secs(30), false),
LockDecision::Takeover { age: stale },
"第一次见到孤儿锁必须给出接管,否则崩溃一次即永久阻断"
);
}
#[test]
fn clock_skew_never_yields_negative_age() {
let now = SystemTime::now();
assert_eq!(
lock_age(now + Duration::from_secs(5), now),
Some(Duration::ZERO)
);
assert_eq!(lock_age(now, now), Some(Duration::ZERO));
}
#[test]
fn acquire_creates_then_removes_on_drop() {
let dir = temp_dir("drop");
let path = dir.join("x.lock");
let held = FileLock::acquire(&path).expect("acquire");
assert!(path.exists());
assert!(
std::fs::read_to_string(&path)
.unwrap()
.starts_with(&format!("{}-", std::process::id())),
"锁文件要登记本进程的所有权令牌"
);
assert_eq!(held.path(), path.as_path());
drop(held);
assert!(!path.exists(), "Drop 必须删除锁文件");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn orphan_lock_is_taken_over() {
let dir = temp_dir("takeover");
let path = dir.join("orphan.lock");
touch_with_age(&path, Duration::from_secs(3600));
let policy = LockPolicy {
stale_after: Duration::from_millis(500),
wait_attempts: 4,
wait_interval: Duration::ZERO,
};
let held = FileLock::acquire_with(&path, policy).expect("stale lock must be taken over");
assert!(
std::fs::read_to_string(&path)
.unwrap()
.starts_with(&format!("{}-", std::process::id())),
"接管后锁必须登记新持有者"
);
drop(held);
assert!(!path.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn fresh_lock_fails_boundedly_and_names_the_holder() {
let dir = temp_dir("fresh");
let path = dir.join("fresh.lock");
std::fs::write(&path, "999999").expect("seed lock");
let policy = LockPolicy {
stale_after: Duration::from_secs(30),
wait_attempts: 3,
wait_interval: Duration::from_millis(10),
};
let started = std::time::Instant::now();
let error =
FileLock::acquire_with(&path, policy).expect_err("fresh lock must not be stolen");
let elapsed = started.elapsed();
assert!(
matches!(error, LockError::Contended(_)),
"新鲜锁失败必须报成竞争: {error:?}"
);
let message = error.message();
assert!(message.contains(&path.display().to_string()), "{message}");
assert!(message.contains("holder=999999"), "{message}");
assert!(message.contains("尚未达到"), "{message}");
assert!(path.exists(), "等待预算用尽不得删掉别人的锁");
assert!(
elapsed >= Duration::from_millis(10) && elapsed < Duration::from_secs(2),
"等待必须真的等过预算、又必须在预算用尽时收场,实际 {elapsed:?}: {message}"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_holder_that_releases_inside_the_budget_lets_the_waiter_in() {
let dir = temp_dir("release");
let path = dir.join("brief.lock");
let held = FileLock::acquire(&path).expect("acquire");
let releaser = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(20));
drop(held);
});
let waiter = FileLock::acquire_with(
&path,
LockPolicy {
stale_after: Duration::from_secs(30),
wait_attempts: 2_000,
wait_interval: Duration::from_millis(2),
},
);
releaser.join().expect("releaser panicked");
let waiter = waiter.expect("占用方在预算内释放时,等待必须拿到锁而不是把写失败上抛");
assert!(
std::fs::read_to_string(&path)
.expect("waiter must own the file")
.starts_with(&format!("{}-", std::process::id())),
"等到的那把锁要登记自己为持有者"
);
drop(waiter);
assert!(!path.exists(), "等待得到的锁同样由 Drop 收回");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn default_policy_waits_for_a_live_holder_past_the_historical_budget() {
let dir = temp_dir("default-budget");
let path = dir.join("brief.lock");
let held = FileLock::acquire(&path).expect("acquire initial lock");
let releaser = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(150));
drop(held);
});
let started = std::time::Instant::now();
let waiter = FileLock::acquire(&path);
let elapsed = started.elapsed();
releaser.join().expect("releaser panicked");
let waiter = waiter.expect("default policy must wait for a live critical section");
assert!(
elapsed >= Duration::from_millis(100) && elapsed < Duration::from_secs(5),
"the live lock should be observed until release and remain within the default budget: {elapsed:?}"
);
drop(waiter);
assert!(!path.exists(), "the waiter must release the acquired lock");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn drop_does_not_delete_a_lock_somebody_else_holds_now() {
let dir = temp_dir("foreign-drop");
let path = dir.join("theft.lock");
let held = FileLock::acquire(&path).expect("acquire");
let forged = "999999-0-1700000000000000000";
std::fs::write(&path, forged).expect("simulate takeover");
drop(held);
assert!(
path.exists(),
"锁已经换了持有者,旧持有者的 Drop 不得把它删掉"
);
assert_eq!(std::fs::read_to_string(&path).unwrap(), forged);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn takeover_happens_at_most_once_per_competition() {
let dir = temp_dir("single-takeover");
let path = dir.join("once.lock");
touch_with_age(&path, Duration::from_secs(3600));
let policy = LockPolicy {
stale_after: Duration::from_millis(500),
wait_attempts: 8,
wait_interval: Duration::ZERO,
};
let held = FileLock::acquire_with(&path, policy).expect("first takeover acquires");
let error = FileLock::acquire_with(&path, policy).expect_err("second must not steal");
assert!(matches!(error, LockError::Contended(_)), "{error:?}");
assert!(error.message().contains("尚未达到"), "{error}");
assert!(path.exists(), "被抢掉的活锁必须还在");
drop(held);
assert!(!path.exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn contention_message_covers_all_three_observations() {
let dir = temp_dir("message");
let path = dir.join("missing.lock");
let policy = LockPolicy::default();
let none = lock_contention_message(&path, None, &policy);
assert!(none.contains("无法读出年龄"), "{none}");
let young = lock_contention_message(&path, Some(Duration::from_secs(1)), &policy);
assert!(young.contains("无持有者登记"), "{young}");
assert!(!young.contains("由 ,"), "文案不得出现悬空介词: {young}");
let old = lock_contention_message(&path, Some(Duration::from_secs(99)), &policy);
assert!(old.contains("请确认没有进程正在写入"), "{old}");
let _ = std::fs::remove_dir_all(&dir);
}
}