Skip to main content

link_cli/storage/
lock.rs

1//! Advisory file locking for multi-process access to a links database.
2//!
3//! Uses the standard library's [`std::fs::File`] advisory locks (`flock`
4//! on Unix, `LockFileEx` on Windows). Locks are taken on a dedicated
5//! sidecar `*.lock` file rather than on the database itself, so that the
6//! lock survives operations that rewrite or remap the database file.
7//!
8//! Advisory locks are held per *open file description*, which means two
9//! [`FileLock`] values inside a single process contend exactly the same
10//! way two separate processes do.
11
12use std::fs::{File, OpenOptions, TryLockError};
13use std::path::{Path, PathBuf};
14
15use crate::error::LinkError;
16
17/// Requested sharing mode for a [`FileLock`].
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum LockMode {
20    /// Multiple readers may hold the lock at the same time.
21    Shared,
22    /// Only one holder at a time; excludes all shared holders.
23    Exclusive,
24}
25
26/// Conventional sidecar lock filename for a links database.
27pub fn lock_file_path<P: AsRef<Path>>(database_filename: P) -> PathBuf {
28    let path = database_filename.as_ref();
29    let mut name = path
30        .file_name()
31        .map(|n| n.to_os_string())
32        .unwrap_or_default();
33    name.push(".lock");
34    match path.parent() {
35        Some(parent) if !parent.as_os_str().is_empty() => parent.join(name),
36        _ => PathBuf::from(name),
37    }
38}
39
40/// `<pid>.<random>`: a token no other process, nor another call in this
41/// one, is likely to share. Names temporary files and lock owners.
42pub fn unique_token() -> String {
43    use std::hash::{BuildHasher, Hasher};
44    use std::sync::atomic::{AtomicU64, Ordering};
45    static NEXT: AtomicU64 = AtomicU64::new(0);
46    #[cfg(not(target_arch = "wasm32"))]
47    let pid = std::process::id();
48    #[cfg(target_arch = "wasm32")]
49    let pid = 0u32;
50    // Each `RandomState` has fresh keys, seeded from the operating system.
51    let mut random = std::collections::hash_map::RandomState::new().build_hasher();
52    random.write_u64(NEXT.fetch_add(1, Ordering::Relaxed));
53    format!("{pid}.{:016x}", random.finish())
54}
55
56/// RAII guard around an advisory lock on a sidecar lock file.
57///
58/// The lock is released when the guard is dropped (and, as a backstop,
59/// by the operating system when the process exits — so a crashed writer
60/// never leaves a database permanently locked).
61#[derive(Debug)]
62pub struct FileLock {
63    file: File,
64    path: PathBuf,
65    mode: LockMode,
66}
67
68impl FileLock {
69    /// Acquires the lock, blocking until it becomes available.
70    pub fn acquire<P: AsRef<Path>>(lock_path: P, mode: LockMode) -> Result<Self, LinkError> {
71        let (file, path) = Self::open(lock_path)?;
72        let result = match mode {
73            LockMode::Shared => file.lock_shared(),
74            LockMode::Exclusive => file.lock(),
75        };
76        result.map_err(|error| {
77            LinkError::Lock(format!("failed to lock {}: {error}", path.display()))
78        })?;
79        Ok(Self { file, path, mode })
80    }
81
82    /// Tries to acquire the lock, returning `Ok(None)` when another
83    /// holder currently owns a conflicting lock.
84    pub fn try_acquire<P: AsRef<Path>>(
85        lock_path: P,
86        mode: LockMode,
87    ) -> Result<Option<Self>, LinkError> {
88        let (file, path) = Self::open(lock_path)?;
89        let result = match mode {
90            LockMode::Shared => file.try_lock_shared(),
91            LockMode::Exclusive => file.try_lock(),
92        };
93        match result {
94            Ok(()) => Ok(Some(Self { file, path, mode })),
95            Err(TryLockError::WouldBlock) => Ok(None),
96            Err(TryLockError::Error(error)) => Err(LinkError::Lock(format!(
97                "failed to lock {}: {error}",
98                path.display()
99            ))),
100        }
101    }
102
103    /// The sidecar lock file this guard holds.
104    pub fn path(&self) -> &Path {
105        &self.path
106    }
107
108    /// The sharing mode this guard was acquired with.
109    pub fn mode(&self) -> LockMode {
110        self.mode
111    }
112
113    fn open<P: AsRef<Path>>(lock_path: P) -> Result<(File, PathBuf), LinkError> {
114        let path = lock_path.as_ref().to_path_buf();
115        if let Some(parent) = path.parent() {
116            if !parent.as_os_str().is_empty() && !parent.exists() {
117                std::fs::create_dir_all(parent)?;
118            }
119        }
120        let file = OpenOptions::new()
121            .create(true)
122            .truncate(false)
123            .read(true)
124            .write(true)
125            .open(&path)?;
126        Ok((file, path))
127    }
128}
129
130impl Drop for FileLock {
131    fn drop(&mut self) {
132        let _ = self.file.unlock();
133    }
134}