memstead_base/engine/write_lock.rs
1//! Cross-process write serialisation per mem.
2//!
3//! Every mutation runs reload-before-operation, compares the caller's
4//! `expected_hash`, then commits. Those three steps must be one atomic
5//! unit across processes: if a sibling process commits between this
6//! process's reload and its commit, the compare runs against a snapshot
7//! that is already behind, and a stale write lands over the sibling's
8//! (a lost update reported as success). The guard below holds an
9//! exclusive OS file lock on the mem's [`MemBackend::write_lock_path`]
10//! for the whole unit, so a second writer blocks until the first has
11//! committed and then reloads, sees the new content, and gets its honest
12//! `HASH_MISMATCH`.
13//!
14//! The lock is reentrant per thread: a mutation that calls another
15//! mutation entry point (a batch over single-item paths, a merge over
16//! creates) takes the same lock again without blocking on itself. Two
17//! threads, or two engines on two threads, still exclude each other,
18//! because each takes its own open file description and OS file locks
19//! conflict between those even inside one process.
20//!
21//! [`MemBackend::write_lock_path`]: crate::backend::MemBackend::write_lock_path
22
23use std::cell::RefCell;
24use std::collections::HashMap;
25use std::fs::{File, OpenOptions};
26use std::path::PathBuf;
27
28use crate::backend::BackendError;
29
30use super::{Engine, EngineError};
31
32thread_local! {
33 /// Locks this thread holds, by lock-file path, with a nesting count.
34 static HELD: RefCell<HashMap<PathBuf, (File, usize)>> = RefCell::new(HashMap::new());
35}
36
37/// Held for the duration of one mutation; dropping it releases every
38/// lock it took (the OS lock goes when the last nested holder drops).
39#[must_use = "the write lock is released as soon as the guard drops"]
40pub struct MemWriteGuard {
41 paths: Vec<PathBuf>,
42}
43
44impl Drop for MemWriteGuard {
45 fn drop(&mut self) {
46 HELD.with(|held| {
47 let mut held = held.borrow_mut();
48 for path in self.paths.iter().rev() {
49 let release = match held.get_mut(path) {
50 Some((_, count)) => {
51 *count -= 1;
52 *count == 0
53 }
54 None => false,
55 };
56 if release && let Some((file, _)) = held.remove(path) {
57 // Closing the descriptor releases the lock too; the
58 // explicit unlock just makes the release immediate.
59 let _ = file.unlock();
60 }
61 }
62 });
63 }
64}
65
66fn acquire(path: &PathBuf) -> Result<(), BackendError> {
67 let already = HELD.with(|held| {
68 if let Some((_, count)) = held.borrow_mut().get_mut(path) {
69 *count += 1;
70 true
71 } else {
72 false
73 }
74 });
75 if already {
76 return Ok(());
77 }
78 if let Some(dir) = path.parent() {
79 std::fs::create_dir_all(dir)?;
80 // Self-ignoring, like the findings and friction stores: a lock
81 // file inside a tracked folder mem never shows up as git noise.
82 let gitignore = dir.join(".gitignore");
83 if !gitignore.exists() {
84 let _ = std::fs::write(&gitignore, "*\n");
85 }
86 }
87 let file = OpenOptions::new()
88 .read(true)
89 .write(true)
90 .create(true)
91 .truncate(false)
92 .open(path)?;
93 file.lock()?;
94 HELD.with(|held| held.borrow_mut().insert(path.clone(), (file, 1)));
95 Ok(())
96}
97
98impl Engine {
99 /// [`Self::lock_mems_for_write`] when `writes` is true; an empty
100 /// guard otherwise. A rehearsal (`dry_run`) commits nothing, so it
101 /// takes no lock and leaves the workspace byte-identical, lock files
102 /// included.
103 pub fn lock_mems_for_write_if<S: AsRef<str>>(
104 &self,
105 writes: bool,
106 mems: &[S],
107 ) -> Result<MemWriteGuard, EngineError> {
108 if writes {
109 self.lock_mems_for_write(mems)
110 } else {
111 Ok(MemWriteGuard { paths: Vec::new() })
112 }
113 }
114
115 /// Take the cross-process write lock of every named mem, in sorted
116 /// order (so two multi-mem writers can never deadlock), and hold it
117 /// until the returned guard drops. Call it before the
118 /// reload-before-operation probe of a mutation and keep the guard
119 /// alive past the commit. Mems that are not mounted, or whose
120 /// backend has no shared state, are skipped: the mutation's own
121 /// lookup reports an unknown mem with its usual error.
122 pub fn lock_mems_for_write<S: AsRef<str>>(
123 &self,
124 mems: &[S],
125 ) -> Result<MemWriteGuard, EngineError> {
126 let mut paths: Vec<PathBuf> = mems
127 .iter()
128 .filter_map(|name| {
129 self.mounts
130 .iter()
131 .find(|m| m.mount.mem == name.as_ref())
132 .and_then(|m| m.backend.write_lock_path())
133 })
134 .collect();
135 paths.sort();
136 paths.dedup();
137 let mut guard = MemWriteGuard {
138 paths: Vec::with_capacity(paths.len()),
139 };
140 for path in paths {
141 acquire(&path).map_err(EngineError::Backend)?;
142 guard.paths.push(path);
143 }
144 Ok(guard)
145 }
146}