Skip to main content

brep_plm/
dirlock.rs

1//! One process per data directory.
2//!
3//! The store holds the whole metadata in memory and writes each change to
4//! `plm.sqlite` from there ([`crate::db`]). A second process opening the same
5//! directory would load its own copy, and the two would overwrite each other's
6//! changes row by row: SQLite keeps the FILE consistent, not two servers' ideas
7//! of it. So [`Db::open`](crate::db::Db::open) takes an exclusive lock on
8//! `<data>/plm.lock` first, and holds it for as long as the store is open.
9//!
10//! The lock is the operating system's advisory file lock on an open handle, so
11//! it is released when the process exits however it exits — a crash leaves no
12//! stale lock to clear by hand. The file itself stays, holding the pid of the
13//! last process that took it, which is what the refusal names.
14
15use std::fs::{File, OpenOptions, TryLockError};
16use std::io::{self, Read, Seek, SeekFrom, Write};
17use std::path::{Path, PathBuf};
18
19/// The lock file in a data directory.
20pub const LOCK_FILE: &str = "plm.lock";
21
22/// An exclusive hold on a data directory, released on drop.
23#[derive(Debug)]
24pub struct DirLock {
25    path: PathBuf,
26    // Held for its lock; never read after it is taken.
27    _file: File,
28}
29
30impl DirLock {
31    /// Take the directory `root`, or say which process has it.
32    pub fn acquire(root: &Path) -> io::Result<DirLock> {
33        std::fs::create_dir_all(root)?;
34        let path = root.join(LOCK_FILE);
35        let mut file = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path)?;
36        match file.try_lock() {
37            Ok(()) => {}
38            Err(TryLockError::WouldBlock) => {
39                let mut text = String::new();
40                let _ = file.read_to_string(&mut text);
41                let holder = match text.trim() {
42                    "" => "another process".to_string(),
43                    pid => format!("another brep-plm process (pid {pid})"),
44                };
45                return Err(io::Error::new(
46                    io::ErrorKind::ResourceBusy,
47                    format!(
48                        "{} is in use by {holder} — stop that server first, or give this one a different --data",
49                        root.display()
50                    ),
51                ));
52            }
53            Err(TryLockError::Error(error)) => return Err(error),
54        }
55        file.set_len(0)?;
56        file.seek(SeekFrom::Start(0))?;
57        writeln!(file, "{}", std::process::id())?;
58        file.flush()?;
59        Ok(DirLock { path, _file: file })
60    }
61
62    pub fn path(&self) -> &Path {
63        &self.path
64    }
65}
66
67impl Drop for DirLock {
68    /// Release the lock on the open file description itself, not only this
69    /// handle's reference to it. The file is opened close-on-exec (std's
70    /// default), but a child another thread forks while the lock is held keeps
71    /// a copy of the descriptor until its `exec`, and an advisory lock lives as
72    /// long as any copy does: dropping the handle alone left the directory
73    /// "in use" for that window (a flake in the test below, 2026-10-22).
74    fn drop(&mut self) {
75        let _ = self._file.unlock();
76    }
77}
78