Files
leaguerecorder/record-daemon/src/instance.rs
T
vhaudiquet 9f5f1f669d record-daemon: keep one recorder running per machine
One test recording produced two half-files: the game in one, the
microphone in the other. Two daemons were alive at once, each with its
own OBS, and only one of them won the game's capture hook and its audio.
Any launch path can start a daemon (the app when it cannot reach the
pipe, the tray, a manual run) and the pipe server accepts a second
instance without complaint, so nothing stopped the second copy.

The daemon now claims a lock file in its configuration directory before
booting OBS. On Windows the file is opened with a share mode of zero, so
a second open fails with a sharing violation; on Unix an exclusive
flock does the same. The loser logs which process holds the lock and
exits, leaving the running recorder alone. Closing the handle releases
the lock, so a crash does not leave the machine without a recorder.
2026-11-16 22:20:51 +01:00

111 lines
3.3 KiB
Rust

//! 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<Option<Self>> {
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<std::fs::File> {
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<std::fs::File> {
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);
}
}