use std::fs::{File, TryLockError};
use std::path::Path;
use std::thread;
use std::time::{Duration, Instant};
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
pub const LOCK_FILE: &str = "surjection.lock";
pub const LOCK_TIMEOUT: Duration = Duration::from_secs(10);
const POLL_INTERVAL: Duration = Duration::from_millis(50);
pub const LEGACY_LOCK_FILE: &str = "loadout.lock";
#[derive(Debug)]
pub struct StoreLock {
files: Vec<File>,
}
impl StoreLock {
pub fn acquire(fs: &dyn Fs, state_dir: &Path, timeout: Duration) -> Result<Self, CoreError> {
fs.create_dir_all(state_dir).map_err(|err| {
CoreError::new(ErrorCode::IoError, format!("cannot open lock file: {err}"))
.with_path(state_dir)
})?;
let deadline = Instant::now() + timeout;
let mut files = Vec::with_capacity(2);
for name in [LOCK_FILE, LEGACY_LOCK_FILE] {
files.push(lock_one(fs, &state_dir.join(name), deadline, timeout)?);
}
Ok(Self { files })
}
}
fn lock_one(
fs: &dyn Fs,
path: &Path,
deadline: Instant,
timeout: Duration,
) -> Result<File, CoreError> {
let io_error = |err: std::io::Error| {
CoreError::new(ErrorCode::IoError, format!("cannot open lock file: {err}")).with_path(path)
};
let file = fs.open_lock_file(path).map_err(io_error)?;
loop {
match file.try_lock() {
Ok(()) => return Ok(file),
Err(TryLockError::WouldBlock) => {}
Err(TryLockError::Error(err)) => return Err(io_error(err)),
}
let now = Instant::now();
if now >= deadline {
return Err(CoreError::new(
ErrorCode::Locked,
format!(
"another Surjection (or Loadout 1.0.x) process is changing the store; gave up \
after {} ms",
timeout.as_millis()
),
)
.with_path(path));
}
thread::sleep(POLL_INTERVAL.min(deadline - now));
}
}
impl Drop for StoreLock {
fn drop(&mut self) {
for file in self.files.iter().rev() {
let _ = file.unlock();
}
}
}