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