From 8c831b1fc2288d260125155bb00eb7bc0ddfb898 Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Wed, 5 Aug 2026 10:08:23 +0800 Subject: [PATCH] fix: preserve lock files owned by another process --- crates/gpapi/src/utils/lock_file.rs | 49 +++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/crates/gpapi/src/utils/lock_file.rs b/crates/gpapi/src/utils/lock_file.rs index d723b41..260a36b 100644 --- a/crates/gpapi/src/utils/lock_file.rs +++ b/crates/gpapi/src/utils/lock_file.rs @@ -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"); + } }