Skip to main content

forgedb_storage_native/
dir_lock.rs

1//! Advisory single-writer lock for a ForgeDB data directory.
2//!
3//! Enforces the v1 single-writer-per-process contract at the OS advisory-lock
4//! level: the first process to call [`DirLock::acquire`] on a data directory
5//! holds an exclusive lock; any subsequent attempt — from a different process —
6//! returns `Err` with `ErrorKind::WouldBlock` so the caller can print a clear
7//! diagnostic and exit cleanly.
8//!
9//! The lock is **not** a lease, a registry, or a distributed coordinator — it
10//! only prevents two writers from accidentally opening the same directory.
11//! Concurrent-writer serialization is explicitly out of scope for v1.
12//!
13//! The lock file is `<root>/.forgedb.lock`.  It is created if absent and is
14//! never deleted on drop — the OS reclaims the advisory lock automatically when
15//! the file handle closes.
16
17use fs2::FileExt;
18use std::fs::{self, OpenOptions};
19use std::io;
20use std::path::Path;
21
22/// The single-writer lock filename under a data directory (`<root>/.forgedb.lock`).
23///
24/// **Cross-crate contract:** `forgedb-coordinator` advisory-locks this same file
25/// (by a duplicated constant, since it must not depend on `forgedb-storage*` —
26/// MVCC spec T3-8) so a coordinator and a standalone writer are mutually
27/// exclusive (T3-5). Renaming it here without updating
28/// `forgedb_coordinator::server::DIR_LOCK_FILENAME` breaks that exclusion; a
29/// parity test in each crate pins the string.
30pub const LOCK_FILENAME: &str = ".forgedb.lock";
31
32/// An advisory exclusive lock on a ForgeDB data directory.
33///
34/// Holds an open `File` to `<root>/.forgedb.lock` with an OS-level exclusive
35/// advisory lock (via [`fs2::FileExt::try_lock_exclusive`]).  The lock is
36/// released automatically when this value is dropped (the `File` closes, which
37/// the OS uses to release the advisory lock).
38///
39/// # Acquiring
40///
41/// ```no_run
42/// use forgedb_storage_native::DirLock;
43/// use std::path::Path;
44///
45/// let lock = DirLock::acquire(Path::new("./data"))?;
46/// // lock is held for the lifetime of the value
47/// drop(lock); // released here
48/// # Ok::<(), std::io::Error>(())
49/// ```
50///
51/// # Conflicts
52///
53/// If another process already holds the lock, [`acquire`](DirLock::acquire)
54/// returns `Err` with `kind() == io::ErrorKind::WouldBlock`.  The caller
55/// should print a human-readable message and exit:
56///
57/// ```no_run
58/// use forgedb_storage_native::DirLock;
59/// use std::path::Path;
60///
61/// match DirLock::acquire(Path::new("./data")) {
62///     Ok(lock) => { /* proceed */ }
63///     Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
64///         eprintln!("error: another ForgeDB writer already has this data directory open");
65///         std::process::exit(1);
66///     }
67///     Err(e) => return Err(e),
68/// }
69/// # Ok::<(), std::io::Error>(())
70/// ```
71pub struct DirLock {
72    // The File holds the advisory lock; closing it releases the lock.
73    // No explicit unlock is needed: fs2 releases on drop via the OS.
74    _file: std::fs::File,
75}
76
77impl std::fmt::Debug for DirLock {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        f.debug_struct("DirLock").finish_non_exhaustive()
80    }
81}
82
83impl DirLock {
84    /// Try to acquire an exclusive advisory lock on `<root>/.forgedb.lock`,
85    /// creating the file (and any missing parent directories) if needed.
86    ///
87    /// Returns `Ok(DirLock)` on success.  If another process already holds the
88    /// lock, returns `Err` with `kind() == io::ErrorKind::WouldBlock` so the
89    /// caller can print a clear "another writer already has this data dir open"
90    /// message and exit.
91    ///
92    /// # Errors
93    ///
94    /// - `WouldBlock` — another process already holds the exclusive lock.
95    /// - Any other `io::Error` from creating the directory or opening the file.
96    pub fn acquire(root: &Path) -> io::Result<DirLock> {
97        fs::create_dir_all(root)?;
98        let lock_path = root.join(LOCK_FILENAME);
99        let file = OpenOptions::new()
100            .read(true)
101            .write(true)
102            .create(true)
103            .truncate(false)
104            .open(&lock_path)?;
105
106        file.try_lock_exclusive().map_err(|e| {
107            // fs2 surfaces a lock-held conflict as a platform-specific OS error.
108            // Normalise it to WouldBlock so callers don't need to match on
109            // platform codes.
110            if e.kind() == io::ErrorKind::WouldBlock
111                || e.raw_os_error() == Some(libc_ewouldblock())
112            {
113                io::Error::new(
114                    io::ErrorKind::WouldBlock,
115                    "another ForgeDB writer already has this data directory open",
116                )
117            } else {
118                e
119            }
120        })?;
121
122        Ok(DirLock { _file: file })
123    }
124}
125
126/// The platform EWOULDBLOCK code, used to normalise fs2 lock-conflict errors.
127///
128/// On most POSIX systems EWOULDBLOCK == EAGAIN (11 on Linux, 35 on macOS).
129/// We only need this as a fallback for older fs2 versions that may not surface
130/// the error as `WouldBlock` directly.
131#[cfg(unix)]
132fn libc_ewouldblock() -> i32 {
133    // SAFETY: `EWOULDBLOCK` is a compile-time constant; no unsafe memory ops.
134    libc::EWOULDBLOCK
135}
136
137#[cfg(not(unix))]
138fn libc_ewouldblock() -> i32 {
139    // On non-Unix targets fs2 should already set the kind to WouldBlock.
140    // Return an impossible value so the fallback branch is never taken.
141    i32::MAX
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    /// G3 mirror (PM re-gate #84) — pins the lock filename so the coordinator's
149    /// duplicated `DIR_LOCK_FILENAME` constant cannot silently desync from the
150    /// file `DirLock` actually locks. The other half lives in
151    /// `forgedb_coordinator::server::tests::lock_filename_matches_storage_dirlock`.
152    #[test]
153    fn lock_filename_is_stable() {
154        assert_eq!(LOCK_FILENAME, ".forgedb.lock");
155    }
156}