fix: preserve lock files owned by another process

This commit is contained in:
Kevin Yue committed 2026-08-05 10:08:23 +08:00
1 parent 912bf3046d
commit 8c831b1fc2
1 file changed
+47 -2
+47 -2
View File
@@ -29,8 +29,15 @@ impl LockFile {
}
pub fn unlock(&self) -> anyhow::Result<()> {
std::fs::remove_file(&self.path)?;
Ok(())
match std::fs::read_to_string(&self.path) {
Ok(content) if LockInfo::parse(&content).is_ok_and(|info| info.pid == self.pid) => {
std::fs::remove_file(&self.path)?;
Ok(())
}
Ok(_) => Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(err.into()),
}
}
pub async fn check_health(&self) -> bool {
@@ -142,4 +149,42 @@ mod tests {
PathBuf::from("/var/run/gpservice-dev-123/gpservice.lock")
);
}
#[test]
fn unlock_removes_lock_owned_by_process() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("gpservice.lock");
let lock = LockFile::new(&path, 1234);
lock.lock("8080").unwrap();
lock.unlock().unwrap();
assert!(!path.exists());
}
#[test]
fn unlock_preserves_lock_owned_by_another_process() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("gpservice.lock");
let owner = LockFile::new(&path, 1234);
let other = LockFile::new(&path, 5678);
owner.lock("8080").unwrap();
other.unlock().unwrap();
assert_eq!(std::fs::read_to_string(path).unwrap(), "1234:8080");
}
#[test]
fn unlock_ignores_missing_or_malformed_lock() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("gpservice.lock");
let lock = LockFile::new(&path, 1234);
lock.unlock().unwrap();
std::fs::write(&path, "not-a-lock").unwrap();
lock.unlock().unwrap();
assert_eq!(std::fs::read_to_string(path).unwrap(), "not-a-lock");
}
}