Skip to main content

link_cli/store_lock/
mod.rs

1//! Store locking for `clink` invocations (issue #194).
2//!
3//! Every invocation loads the whole store, changes it in memory and saves it
4//! back. Two invocations that overlap would each save their own copy, and the
5//! later save would drop the writes of the earlier one. A [`StoreLock`] makes
6//! that read-modify-write exclusive: writers take it exclusively, readers
7//! share it, and a waiter gives up with a "store is locked" error naming the
8//! owner once `--lock-timeout` passes.
9//!
10//! | `--lock` | Lock                         | Released by                           |
11//! | -------- | ---------------------------- | ------------------------------------- |
12//! | `flock`  | `flock`/`LockFileEx` on `<db>.lock` | the operating system when the holder exits |
13//! | `pid`    | the directory `<db>.lock.d`  | the holder; a waiter breaks it when the owner process is gone |
14//! | `none`   | nothing                      | -                                     |
15//!
16//! An exclusive `flock` holder writes its owner record to `<db>.lock.owner`
17//! and removes it on release, so that waiters and `--lock-status` can name
18//! it. The record is a file of its own because on Windows the lock keeps
19//! every other process from reading `<db>.lock` itself.
20
21mod owner;
22mod pid_lock;
23
24use std::fs;
25use std::path::{Path, PathBuf};
26use std::time::{Duration, Instant};
27
28pub use owner::{Liveness, LockOwner};
29pub use pid_lock::lock_dir_path;
30
31use crate::diagnostics;
32use crate::error::LinkError;
33use crate::storage::lock::unique_token;
34use crate::storage::{lock_file_path, FileLock, LockMode};
35use pid_lock::{Attempt, PidLock};
36
37/// How long a waiter waits by default, in milliseconds.
38pub const DEFAULT_LOCK_TIMEOUT_MS: u64 = 30_000;
39
40/// The `--lock` mechanism.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum StoreLockKind {
43    Flock,
44    Pid,
45    None,
46}
47
48/// The parsed `--lock`, `--no-lock` and `--lock-timeout` options.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct StoreLockOptions {
51    pub kind: StoreLockKind,
52    /// How long to wait for a held lock; zero tries once.
53    pub timeout: Duration,
54    /// Report waiting, breaking and acquiring on stderr.
55    pub trace: bool,
56}
57
58impl Default for StoreLockOptions {
59    fn default() -> Self {
60        Self {
61            kind: StoreLockKind::Flock,
62            timeout: Duration::from_millis(DEFAULT_LOCK_TIMEOUT_MS),
63            trace: false,
64        }
65    }
66}
67
68impl StoreLockOptions {
69    /// Reads the raw values of `--lock` and `--lock-timeout`.
70    pub fn parse(kind: Option<&str>, timeout: Option<&str>) -> Result<Self, LinkError> {
71        let mut options = Self::default();
72        if let Some(value) = kind.map(str::trim).filter(|value| !value.is_empty()) {
73            options.kind = match value.to_ascii_lowercase().as_str() {
74                "flock" => StoreLockKind::Flock,
75                "pid" => StoreLockKind::Pid,
76                "none" => StoreLockKind::None,
77                _ => {
78                    return Err(LinkError::InvalidFormat(format!(
79                        "Invalid --lock value '{value}'. Use 'flock', 'pid' or 'none'."
80                    )))
81                }
82            };
83        }
84        if let Some(value) = timeout.map(str::trim) {
85            let milliseconds = value.parse::<u64>().map_err(|_| {
86                LinkError::InvalidFormat(format!(
87                    "Invalid --lock-timeout value '{value}'. Use a whole number of milliseconds."
88                ))
89            })?;
90            options.timeout = Duration::from_millis(milliseconds);
91        }
92        Ok(options)
93    }
94}
95
96/// The stores of one invocation without duplicates, in the order every
97/// process locks them: sorted by absolute path. Each keeps the spelling it
98/// was given, which is what messages show.
99pub fn lock_order<I, P>(stores: I) -> Vec<PathBuf>
100where
101    I: IntoIterator<Item = P>,
102    P: AsRef<Path>,
103{
104    let mut paths: Vec<(PathBuf, PathBuf)> = stores
105        .into_iter()
106        .map(|store| (normalize(store.as_ref()), store.as_ref().to_path_buf()))
107        .collect();
108    paths.sort_by(|left, right| left.0.cmp(&right.0));
109    paths.dedup_by(|later, earlier| later.0 == earlier.0);
110    paths.into_iter().map(|(_, store)| store).collect()
111}
112
113fn normalize(store: &Path) -> PathBuf {
114    let absolute = std::path::absolute(store).unwrap_or_else(|_| store.to_path_buf());
115    match (absolute.parent(), absolute.file_name()) {
116        (Some(parent), Some(name)) => parent
117            .canonicalize()
118            .map(|parent| parent.join(name))
119            .unwrap_or(absolute),
120        _ => absolute,
121    }
122}
123
124#[derive(Debug)]
125enum Guard {
126    Flock(FlockGuard),
127    Pid(PidLock),
128}
129
130/// Locks held for one invocation; dropping it releases them.
131#[derive(Debug)]
132pub struct StoreLock {
133    guards: Vec<Guard>,
134}
135
136impl StoreLock {
137    /// Locks every store in `stores` (see [`lock_order`]),
138    /// waiting up to `options.timeout` for each. `--lock pid` is always
139    /// exclusive.
140    pub fn acquire(
141        stores: &[PathBuf],
142        mode: LockMode,
143        options: &StoreLockOptions,
144    ) -> Result<Self, LinkError> {
145        // `None`: a timeout too long to reach, so wait for good.
146        let deadline = Instant::now().checked_add(options.timeout);
147        let mut guards = Vec::new();
148        for store in stores {
149            guards.push(match options.kind {
150                StoreLockKind::None => continue,
151                StoreLockKind::Flock => {
152                    Guard::Flock(acquire_flock(store, mode, deadline, options)?)
153                }
154                StoreLockKind::Pid => Guard::Pid(acquire_pid(store, deadline, options)?),
155            });
156        }
157        Ok(Self { guards })
158    }
159
160    /// The lock files and directories held.
161    pub fn paths(&self) -> Vec<&Path> {
162        self.guards
163            .iter()
164            .map(|guard| match guard {
165                Guard::Flock(guard) => guard.lock.path(),
166                Guard::Pid(lock) => lock.path(),
167            })
168            .collect()
169    }
170}
171
172/// Waits from 1 ms, doubling up to 50 ms, until `deadline`.
173struct Backoff {
174    delay: Duration,
175    deadline: Option<Instant>,
176}
177
178impl Backoff {
179    fn new(deadline: Option<Instant>) -> Self {
180        Self {
181            delay: Duration::from_millis(1),
182            deadline,
183        }
184    }
185
186    /// Sleeps before the next attempt; false once the deadline has passed.
187    fn wait(&mut self) -> bool {
188        let left = match self.deadline {
189            Some(deadline) => match deadline.checked_duration_since(Instant::now()) {
190                Some(left) if !left.is_zero() => left,
191                _ => return false,
192            },
193            None => self.delay,
194        };
195        std::thread::sleep(self.delay.min(left));
196        self.delay = (self.delay * 2).min(Duration::from_millis(50));
197        true
198    }
199}
200
201fn locked_error(path: &Path, kind: &str, holder: &str, options: &StoreLockOptions) -> LinkError {
202    LinkError::Lock(format!(
203        "store is locked: {} is held by {holder}; gave up waiting for the {kind} lock after {} ms (--lock-timeout)",
204        path.display(),
205        options.timeout.as_millis()
206    ))
207}
208
209/// `<db>.lock.owner`: the record of the exclusive `flock` holder.
210pub fn owner_file_path(store: &Path) -> PathBuf {
211    let mut name = lock_file_path(store).into_os_string();
212    name.push(".owner");
213    PathBuf::from(name)
214}
215
216/// Replaces the record at `path` at once, so that no reader sees half of it.
217/// Best effort: the record only serves diagnostics.
218fn write_record(path: &Path, record: &str) {
219    let mut staging = path.as_os_str().to_owned();
220    staging.push(format!(".{}.tmp", unique_token()));
221    let staging = PathBuf::from(staging);
222    if fs::write(&staging, record)
223        .and_then(|()| fs::rename(&staging, path))
224        .is_err()
225    {
226        let _ = fs::remove_file(&staging);
227    }
228}
229
230/// An exclusive or shared `flock` on `<db>.lock`. An exclusive holder keeps
231/// its owner record in `<db>.lock.owner` and removes it on release.
232#[derive(Debug)]
233struct FlockGuard {
234    lock: FileLock,
235    owner: PathBuf,
236}
237
238impl Drop for FlockGuard {
239    fn drop(&mut self) {
240        // Before the lock itself is released, with the fields.
241        if self.lock.mode() == LockMode::Exclusive {
242            let _ = fs::remove_file(&self.owner);
243        }
244    }
245}
246
247fn acquire_flock(
248    store: &Path,
249    mode: LockMode,
250    deadline: Option<Instant>,
251    options: &StoreLockOptions,
252) -> Result<FlockGuard, LinkError> {
253    let path = lock_file_path(store);
254    let kind = match mode {
255        LockMode::Shared => "shared flock",
256        LockMode::Exclusive => "exclusive flock",
257    };
258    let mut backoff = Backoff::new(deadline);
259    let mut reported = false;
260    loop {
261        if let Some(lock) = FileLock::try_acquire(&path, mode)? {
262            let owner = owner_file_path(store);
263            match mode {
264                LockMode::Exclusive => {
265                    write_record(&owner, &LockOwner::current(&unique_token()).to_record())
266                }
267                // No exclusive holder exists, so a record is a crashed one's.
268                LockMode::Shared => {
269                    let _ = fs::remove_file(&owner);
270                }
271            }
272            let guard = FlockGuard { lock, owner };
273            if options.trace {
274                diagnostics::stderr!("[TRACE] Acquired {kind} lock {}", path.display());
275            }
276            return Ok(guard);
277        }
278        if options.trace && !reported {
279            reported = true;
280            diagnostics::stderr!(
281                "[TRACE] Waiting for {kind} lock {}: held by {}",
282                path.display(),
283                flock_holder(store)
284            );
285        }
286        if !backoff.wait() {
287            return Err(locked_error(&path, kind, &flock_holder(store), options));
288        }
289    }
290}
291
292/// Who holds the `<db>.lock` of `store`: shared readers, or the writer its
293/// record names.
294fn flock_holder(store: &Path) -> String {
295    if let Ok(Some(_probe)) = FileLock::try_acquire(lock_file_path(store), LockMode::Shared) {
296        return "shared readers".into();
297    }
298    let text = fs::read_to_string(owner_file_path(store)).unwrap_or_default();
299    match LockOwner::parse(&text) {
300        Some(owner) => format!("an exclusive writer: {}", owner.describe()),
301        None => "an exclusive writer that left no owner record".into(),
302    }
303}
304
305fn acquire_pid(
306    store: &Path,
307    deadline: Option<Instant>,
308    options: &StoreLockOptions,
309) -> Result<PidLock, LinkError> {
310    let dir = lock_dir_path(store);
311    let mut backoff = Backoff::new(deadline);
312    let mut reported = false;
313    loop {
314        let holder = match pid_lock::try_acquire(&dir, options.trace)? {
315            Attempt::Acquired(lock) => {
316                if options.trace {
317                    diagnostics::stderr!("[TRACE] Acquired pid lock {}", dir.display());
318                }
319                return Ok(lock);
320            }
321            Attempt::Held(owner) => describe_pid_holder(&dir, owner.as_ref()),
322        };
323        if options.trace && !reported {
324            reported = true;
325            diagnostics::stderr!(
326                "[TRACE] Waiting for pid lock {}: held by {holder}",
327                dir.display()
328            );
329        }
330        if !backoff.wait() {
331            return Err(locked_error(&dir, "pid", &holder, options));
332        }
333    }
334}
335
336fn describe_pid_holder(dir: &Path, owner: Option<&LockOwner>) -> String {
337    match owner {
338        Some(owner) => owner.describe(),
339        None => format!(
340            "a directory without an owner record (removed once {} is 10 s old)",
341            dir.display()
342        ),
343    }
344}
345
346/// `--lock-status`: one line per store and lock kind, without taking or
347/// creating any lock that is not already there.
348pub fn lock_status(stores: &[PathBuf]) -> String {
349    let mut report = String::new();
350    for store in stores {
351        let path = lock_file_path(store);
352        let state = if !path.exists() {
353            "unlocked".to_string()
354        } else {
355            match FileLock::try_acquire(&path, LockMode::Exclusive) {
356                Ok(Some(_probe)) => "unlocked".to_string(),
357                Ok(None) => format!("locked by {}", flock_holder(store)),
358                Err(error) => format!("unknown ({error})"),
359            }
360        };
361        report.push_str(&format!("flock {}: {state}\n", path.display()));
362        let dir = lock_dir_path(store);
363        let state = if fs::symlink_metadata(&dir).is_err() {
364            "unlocked".to_string()
365        } else {
366            let owner = pid_lock::read_owner(&dir);
367            let mut state = format!("locked by {}", describe_pid_holder(&dir, owner.as_ref()));
368            if let Some(reason) = pid_lock::stale_reason(&dir, owner.as_ref()) {
369                state.push_str(&format!("; stale, the next writer breaks it: {reason}"));
370            }
371            state
372        };
373        report.push_str(&format!("pid {}: {state}\n", dir.display()));
374    }
375    report
376}