Skip to main content

surjection_core/store/
lock.rs

1//! The cross-process lock `<SURJECTION_HOME>/state/surjection.lock` (SPEC 4.1),
2//! held together with Loadout 1.0.x's `state/loadout.lock`.
3//!
4//! Any process mutating the store, the ledger or client files holds it. A
5//! second process waits up to [`LOCK_TIMEOUT`], then fails with `locked`
6//! (CLI exit code 6). The lock is an OS advisory lock on an open handle, so
7//! it is released when the holder exits or crashes; the file itself is
8//! never read, written or deleted.
9
10use 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
18/// Lock file name inside `state/`.
19pub const LOCK_FILE: &str = "surjection.lock";
20/// How long a second process waits for the lock.
21pub const LOCK_TIMEOUT: Duration = Duration::from_secs(10);
22
23const POLL_INTERVAL: Duration = Duration::from_millis(50);
24
25/// The lock file Loadout 1.0.x takes. Held as well, so a 1.0.x process
26/// still running against this data folder (through the link `surject
27/// migrate loadout` leaves) and this build never change it at once.
28pub const LEGACY_LOCK_FILE: &str = "loadout.lock";
29
30/// The held lock; released on drop.
31#[derive(Debug)]
32pub struct StoreLock {
33    files: Vec<File>,
34}
35
36impl StoreLock {
37    /// Takes the lock in `state_dir` ([`LOCK_FILE`], then
38    /// [`LEGACY_LOCK_FILE`], always in that order), waiting up to `timeout`
39    /// for another holder to release it. Creates `state_dir` if needed.
40    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        // Closing the handle releases the lock too; unlocking first makes the
89        // release immediate on every OS.
90        for file in self.files.iter().rev() {
91            let _ = file.unlock();
92        }
93    }
94}