surjection_core/store/
lock.rs1use std::fs::{File, TryLockError};
11use std::path::Path;
12use std::thread;
13use std::time::{Duration, Instant};
14
15use crate::error::{CoreError, ErrorCode};
16use crate::fs::Fs;
17
18pub const LOCK_FILE: &str = "surjection.lock";
20pub const LOCK_TIMEOUT: Duration = Duration::from_secs(10);
22
23const POLL_INTERVAL: Duration = Duration::from_millis(50);
24
25pub const LEGACY_LOCK_FILE: &str = "loadout.lock";
29
30#[derive(Debug)]
32pub struct StoreLock {
33 files: Vec<File>,
34}
35
36impl StoreLock {
37 pub fn acquire(fs: &dyn Fs, state_dir: &Path, timeout: Duration) -> Result<Self, CoreError> {
41 fs.create_dir_all(state_dir).map_err(|err| {
42 CoreError::new(ErrorCode::IoError, format!("cannot open lock file: {err}"))
43 .with_path(state_dir)
44 })?;
45 let deadline = Instant::now() + timeout;
46 let mut files = Vec::with_capacity(2);
47 for name in [LOCK_FILE, LEGACY_LOCK_FILE] {
48 files.push(lock_one(fs, &state_dir.join(name), deadline, timeout)?);
49 }
50 Ok(Self { files })
51 }
52}
53
54fn lock_one(
55 fs: &dyn Fs,
56 path: &Path,
57 deadline: Instant,
58 timeout: Duration,
59) -> Result<File, CoreError> {
60 let io_error = |err: std::io::Error| {
61 CoreError::new(ErrorCode::IoError, format!("cannot open lock file: {err}")).with_path(path)
62 };
63 let file = fs.open_lock_file(path).map_err(io_error)?;
64 loop {
65 match file.try_lock() {
66 Ok(()) => return Ok(file),
67 Err(TryLockError::WouldBlock) => {}
68 Err(TryLockError::Error(err)) => return Err(io_error(err)),
69 }
70 let now = Instant::now();
71 if now >= deadline {
72 return Err(CoreError::new(
73 ErrorCode::Locked,
74 format!(
75 "another Surjection (or Loadout 1.0.x) process is changing the store; gave up \
76 after {} ms",
77 timeout.as_millis()
78 ),
79 )
80 .with_path(path));
81 }
82 thread::sleep(POLL_INTERVAL.min(deadline - now));
83 }
84}
85
86impl Drop for StoreLock {
87 fn drop(&mut self) {
88 for file in self.files.iter().rev() {
91 let _ = file.unlock();
92 }
93 }
94}