surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
//! The cross-process lock `<SURJECTION_HOME>/state/surjection.lock` (SPEC 4.1),
//! held together with Loadout 1.0.x's `state/loadout.lock`.
//!
//! Any process mutating the store, the ledger or client files holds it. A
//! second process waits up to [`LOCK_TIMEOUT`], then fails with `locked`
//! (CLI exit code 6). The lock is an OS advisory lock on an open handle, so
//! it is released when the holder exits or crashes; the file itself is
//! never read, written or deleted.

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;

/// Lock file name inside `state/`.
pub const LOCK_FILE: &str = "surjection.lock";
/// How long a second process waits for the lock.
pub const LOCK_TIMEOUT: Duration = Duration::from_secs(10);

const POLL_INTERVAL: Duration = Duration::from_millis(50);

/// The lock file Loadout 1.0.x takes. Held as well, so a 1.0.x process
/// still running against this data folder (through the link `surject
/// migrate loadout` leaves) and this build never change it at once.
pub const LEGACY_LOCK_FILE: &str = "loadout.lock";

/// The held lock; released on drop.
#[derive(Debug)]
pub struct StoreLock {
    files: Vec<File>,
}

impl StoreLock {
    /// Takes the lock in `state_dir` ([`LOCK_FILE`], then
    /// [`LEGACY_LOCK_FILE`], always in that order), waiting up to `timeout`
    /// for another holder to release it. Creates `state_dir` if needed.
    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) {
        // Closing the handle releases the lock too; unlocking first makes the
        // release immediate on every OS.
        for file in self.files.iter().rev() {
            let _ = file.unlock();
        }
    }
}