//! One recorder per machine. //! //! A second copy brings its own OBS along, and the two fight over the game's capture hook and //! over the process audio. The result is two files for one game: one with the picture and the //! other with the microphone. Both the app and the tray can start a daemon, so the daemon claims //! a lock file on startup and leaves when somebody else holds it. use std::path::{Path, PathBuf}; use crate::error::Result; /// The lock, held for as long as the daemon runs. #[derive(Debug)] pub struct InstanceLock { path: PathBuf, file: std::fs::File, } impl InstanceLock { /// Take the lock, or report that another daemon already holds it. pub fn claim(path: &Path) -> Result> { if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } let file = match lock_file(path) { Ok(file) => file, Err(e) if is_held(&e) => return Ok(None), Err(e) => return Err(e.into()), }; Ok(Some(Self { path: path.to_path_buf(), file, })) } /// The file the lock lives in, for log lines. pub fn path(&self) -> &Path { &self.path } } impl Drop for InstanceLock { fn drop(&mut self) { // Closing the handle releases the lock; the file itself is harmless to leave behind. let _ = &self.file; #[cfg(unix)] let _ = std::fs::remove_file(&self.path); } } #[cfg(windows)] fn lock_file(path: &Path) -> std::io::Result { use std::os::windows::fs::OpenOptionsExt; // A share mode of 0 means the next open fails while this handle is alive. std::fs::OpenOptions::new() .create(true) .truncate(false) .write(true) .share_mode(0) .open(path) } #[cfg(windows)] fn is_held(error: &std::io::Error) -> bool { // ERROR_SHARING_VIOLATION: the other daemon holds this file open. error.raw_os_error() == Some(32) } #[cfg(unix)] fn lock_file(path: &Path) -> std::io::Result { use std::os::unix::io::AsRawFd; let file = std::fs::OpenOptions::new() .create(true) .truncate(false) .write(true) .open(path)?; let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; if result == 0 { Ok(file) } else { Err(std::io::Error::last_os_error()) } } #[cfg(unix)] fn is_held(error: &std::io::Error) -> bool { error.raw_os_error() == Some(libc::EWOULDBLOCK) } #[cfg(test)] mod tests { use super::*; #[test] fn the_second_claim_is_refused_while_the_first_holds_the_file() { let dir = std::env::temp_dir().join(format!("instance-lock-{}", std::process::id())); let path = dir.join("record-daemon.lock"); let first = InstanceLock::claim(&path).expect("first claim"); assert!(first.is_some(), "the first claim takes the lock"); let second = InstanceLock::claim(&path).expect("second claim runs"); assert!(second.is_none(), "the second claim finds the file held"); drop(first); let third = InstanceLock::claim(&path).expect("third claim runs"); assert!(third.is_some(), "the lock is free once the holder exits"); drop(third); let _ = std::fs::remove_dir_all(&dir); } }