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 ([`crate::storage::path_lock`]): a
15//! mutation that calls another mutation entry point (a batch over
16//! single-item paths, a merge over creates) takes the same lock again
17//! without blocking on itself. Two threads, or two engines on two
18//! threads, still exclude each other.
19//!
20//! The guard is also the one exit every mutation shares for its staged
21//! writes. A mutation stages bytes into the backend and commits them
22//! later; an error between the two (a refused sidecar write, a failed
23//! commit, a `?` in any verb) used to leave the staged bytes in the
24//! backend, where the next read served them as content that never
25//! landed. When the outermost guard of a thread drops, it discards
26//! whatever is still staged on the mems it locked. After a commit
27//! nothing is staged and the discard is a no-op, so a call site has no
28//! failure path to remember: holding the lock is the cleanup.
29//!
30//! [`MemBackend::write_lock_path`]: crate::backend::MemBackend::write_lock_path
31
32use std::cell::RefCell;
33use std::collections::HashMap;
34use std::path::PathBuf;
35use std::sync::Arc;
36
37use crate::backend::{BackendError, MemBackend};
38use crate::storage::path_lock;
39
40use super::{Engine, EngineError};
41
42/// Held for the duration of one mutation; dropping it discards the
43/// writes still staged on the mems it covers and releases every lock
44/// it took (both when the last nested holder drops).
45#[must_use = "the write lock is released as soon as the guard drops"]
46pub struct MemWriteGuard {
47 /// Each covered mem's backend with its lock-file path. A backend
48 /// with no shared on-disk state has no path and takes no OS lock,
49 /// but its staged writes are discarded like any other's.
50 held: Vec<Held>,
51}
52
53/// One mem a guard covers.
54struct Held {
55 path: Option<PathBuf>,
56 backend: Arc<dyn MemBackend>,
57 /// The mount's record of a discard that failed
58 /// ([`super::MountedBackend::strays`]). The guard cannot reach the
59 /// engine when it drops, so it shares this flag with the mount.
60 strays: Arc<std::sync::atomic::AtomicBool>,
61}
62
63thread_local! {
64 /// How many guards of this thread cover a backend, by its address.
65 /// Only the outermost one discards: an inner guard dropping must
66 /// not empty a staged set the outer mutation is still building.
67 static COVERED: RefCell<HashMap<usize, usize>> = RefCell::new(HashMap::new());
68}
69
70fn backend_key(backend: &Arc<dyn MemBackend>) -> usize {
71 Arc::as_ptr(backend) as *const () as usize
72}
73
74impl MemWriteGuard {
75 fn empty() -> Self {
76 Self { held: Vec::new() }
77 }
78
79 fn cover(&mut self, held: Held) {
80 COVERED.with(|c| {
81 *c.borrow_mut()
82 .entry(backend_key(&held.backend))
83 .or_insert(0) += 1
84 });
85 self.held.push(held);
86 }
87}
88
89impl Drop for MemWriteGuard {
90 fn drop(&mut self) {
91 for Held {
92 path,
93 backend,
94 strays,
95 } in self.held.iter().rev()
96 {
97 let outermost = COVERED.with(|c| {
98 let mut covered = c.borrow_mut();
99 let key = backend_key(backend);
100 match covered.get_mut(&key) {
101 Some(count) if *count > 1 => {
102 *count -= 1;
103 false
104 }
105 _ => {
106 covered.remove(&key);
107 true
108 }
109 }
110 });
111 // Discard before the lock goes, so no other writer can
112 // stage between the two. A discard that fails leaves the
113 // staged writes where a read or the next commit would pick
114 // them up, so the backend is remembered and the engine
115 // discards again before its next operation.
116 if outermost {
117 strays.store(
118 backend.discard_pending().is_err(),
119 std::sync::atomic::Ordering::SeqCst,
120 );
121 }
122 if let Some(path) = path {
123 path_lock::release(path);
124 }
125 }
126 }
127}
128
129impl Engine {
130 /// Discard what a failed mutation left staged on `mem`'s backend,
131 /// if an earlier discard failed. Run before every operation, ahead
132 /// of anything that reads the backend: a staged write is served in
133 /// place of the committed bytes, and the next commit would land it.
134 ///
135 /// When the discard fails again, the backend is replaced by a fresh
136 /// one over the same storage: what is staged lives in the backend
137 /// value and nowhere on disk, so a new value has none of it. Only a
138 /// mount whose storage is on disk is replaced (an in-memory mem is
139 /// its backend), and not while a mutation of this thread holds the
140 /// backend. An error means the staged writes are still there.
141 pub(super) fn discard_strays(&mut self, mem: &str) -> Result<(), BackendError> {
142 use std::sync::atomic::Ordering;
143 let Some(idx) = self.mounts.iter().position(|m| m.mount.mem == mem) else {
144 return Ok(());
145 };
146 let state = &self.mounts[idx];
147 if !state.strays.load(Ordering::SeqCst) {
148 return Ok(());
149 }
150 let failure = match state.backend.discard_pending() {
151 Ok(()) => {
152 state.strays.store(false, Ordering::SeqCst);
153 return Ok(());
154 }
155 Err(e) => e,
156 };
157 let on_disk = matches!(
158 state.mount.storage,
159 crate::workspace::MountStorage::Folder { .. }
160 | crate::workspace::MountStorage::GitBranch { .. }
161 );
162 let held_by_a_mutation = COVERED.with(|c| {
163 c.borrow()
164 .get(&backend_key(&state.backend))
165 .is_some_and(|count| *count > 0)
166 });
167 if on_disk
168 && !held_by_a_mutation
169 && let Ok(fresh) = self.instantiate_backend(&state.mount)
170 {
171 self.mounts[idx].backend = Arc::from(fresh);
172 self.mounts[idx].strays = Default::default();
173 return Ok(());
174 }
175 Err(failure)
176 }
177
178 /// The lock and the view for a verb that learns what it writes, or
179 /// what its guard reads, only by reading the workspace (a delete's
180 /// and a retype's referrer check, a rename's referrers). Such a verb
181 /// cannot name its mems up front, and a view of a mem taken before
182 /// that mem's lock is held can miss what a sibling wrote into it. So
183 /// it takes every writable mount's lock, in the one sorted order the
184 /// lock defines, after the roster is reconciled (a mem attached
185 /// since is locked too), and only then reloads every mem and loads
186 /// the ones whose loading was deferred. No lock is taken after
187 /// planning began, so there is nothing to restart.
188 ///
189 /// A mem that cannot be reloaded refuses the verb with
190 /// `MEM_VIEW_STALE`: its view is from before the lock, and a guard
191 /// that reads every mem would be evaluated on it. So does a mem
192 /// that is out of service (quarantined), which is in no view.
193 ///
194 /// `writes` false (a rehearsal) takes no lock and still brings the
195 /// view up to date.
196 pub fn lock_workspace_for_write_if(
197 &mut self,
198 writes: bool,
199 ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
200 let mut warnings = self.roster_before_locking();
201 let (guard, reloaded) = self.lock_whole_workspace(writes)?;
202 warnings.extend(reloaded);
203 Ok((guard, warnings))
204 }
205
206 /// [`Self::lock_workspace_for_write_if`] for a verb that names the
207 /// entity it writes (a delete, a rename, a retype). When the id
208 /// names a mem that is mounted read-only the write is refused here,
209 /// before any lock is taken, so the refusal lays nothing where that
210 /// mem lives. A bare slug names no mem and is resolved under the
211 /// locks as before.
212 pub(in crate::engine) fn lock_workspace_for_entity_write(
213 &mut self,
214 writes: bool,
215 id: &crate::EntityId,
216 ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
217 let mut warnings = self.roster_before_locking();
218 if writes {
219 let mem = id.mem();
220 if self.mounts.iter().any(|m| {
221 m.mount.mem == mem && m.mount.capability != crate::workspace::MountCapability::Write
222 }) {
223 return Err(EngineError::ReadOnlyMount(mem.to_string()));
224 }
225 }
226 let (guard, reloaded) = self.lock_whole_workspace(writes)?;
227 warnings.extend(reloaded);
228 Ok((guard, warnings))
229 }
230
231 /// [`Self::lock_workspace_for_write_if`] for an operation on the
232 /// mem `subject` as a whole (its deletion): `subject` itself may be
233 /// unreadable or out of service, which is often why it is being
234 /// removed, and that does not refuse the operation. Every other
235 /// mem must be readable as for any verb that reads the workspace.
236 pub fn lock_workspace_for_mem_operation(
237 &mut self,
238 subject: &str,
239 ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
240 self.lock_workspace_for_mems_operation(&[subject])
241 }
242
243 /// [`Self::lock_workspace_for_mem_operation`] for an operation on
244 /// several mems as wholes (`pull --all` reconciles every one): each
245 /// subject may be unreadable or out of service; every other mem must
246 /// be readable.
247 pub fn lock_workspace_for_mems_operation(
248 &mut self,
249 subjects: &[&str],
250 ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
251 let mut warnings = self.roster_before_locking();
252 let (guard, reloaded) = self.lock_whole_workspace_except(true, subjects, None)?;
253 warnings.extend(reloaded);
254 Ok((guard, warnings))
255 }
256
257 /// [`Self::lock_workspace_for_mem_operation`] for taking a
258 /// read-only mount of `subject` off the roster: every other mem's
259 /// lock is held and every mem is read under it, and the subject's
260 /// own lock is not taken. Nothing is written to the subject's
261 /// storage, which this workspace only ever read and may not be able
262 /// to write to, so no lock file is laid where it lives.
263 pub fn lock_workspace_beside_read_mount(
264 &mut self,
265 subject: &str,
266 ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
267 let mut warnings = self.roster_before_locking();
268 let (guard, reloaded) =
269 self.lock_whole_workspace_except(true, &[subject], Some(subject))?;
270 warnings.extend(reloaded);
271 Ok((guard, warnings))
272 }
273
274 /// Whether `mem` is a read-only mount of a branch or a folder: the
275 /// mounts `memstead mem unregister` takes off the roster without
276 /// touching their storage.
277 pub fn is_removable_read_mount(&self, mem: &str) -> bool {
278 self.mounts.iter().any(|m| {
279 m.mount.mem == mem
280 && m.mount.capability == crate::workspace::MountCapability::ReadOnly
281 && matches!(
282 m.mount.storage,
283 crate::workspace::MountStorage::GitBranch { .. }
284 | crate::workspace::MountStorage::Folder { .. }
285 )
286 })
287 }
288
289 /// The roster as it stands, reconciled ahead of a decision that is
290 /// taken before any lock (which lock form a verb needs).
291 pub fn settle_roster_before_locking(&mut self) -> Vec<crate::ops::WarningHint> {
292 self.roster_before_locking()
293 }
294
295 fn lock_whole_workspace(
296 &mut self,
297 writes: bool,
298 ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
299 self.lock_whole_workspace_except(writes, &[], None)
300 }
301
302 /// `tolerated` are mems that may be unreadable without refusing the
303 /// operation; `unlocked` is one whose own lock is not taken.
304 fn lock_whole_workspace_except(
305 &mut self,
306 writes: bool,
307 tolerated: &[&str],
308 unlocked: Option<&str>,
309 ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
310 // Every mount that has a write lock, the ones this engine mounts
311 // read-only included: another process may mount the same
312 // storage writable, and a guard that reads it needs its writer
313 // to wait like any other.
314 let (guard, mut warnings) = self.lock_on_a_settled_roster(writes, |engine| {
315 engine
316 .mounts
317 .iter()
318 .filter(|m| {
319 m.mount.capability == crate::workspace::MountCapability::Write
320 || m.backend.write_lock_path().is_some()
321 })
322 .filter(|m| Some(m.mount.mem.as_str()) != unlocked)
323 .map(|m| m.mount.mem.clone())
324 .collect()
325 })?;
326 warnings.extend(self.reload_if_stale_content_only(None));
327 if let Some((stale, failure)) = self
328 .mounts
329 .iter()
330 .filter(|m| !tolerated.contains(&m.mount.mem.as_str()))
331 .find_map(|m| m.reload_failure.as_ref().map(|f| (m, f)))
332 {
333 return Err(failure.refusal(&stale.mount.mem));
334 }
335 // A mem that is out of service is in no view at all: one whose
336 // deferred load just failed under this lock, or one that never
337 // attached. Its referrers are as unread as a stale mem's.
338 if let Some(out) = self
339 .quarantined
340 .iter()
341 .find(|q| !tolerated.contains(&q.mount.mem.as_str()))
342 {
343 return Err(EngineError::StaleView {
344 mem: out.mount.mem.clone(),
345 cause: super::StaleCause::OutOfService,
346 detail: format!("{}: {}", out.reason_code, out.reason_message),
347 });
348 }
349 Ok((guard, warnings))
350 }
351
352 /// Take the locks `choose` names, and hold them over a roster that
353 /// did not change while this process waited for them. The process
354 /// that held a lock may have changed the roster before it let go (a
355 /// mem rename takes the mem away under the lock a writer into it
356 /// is waiting on; a mem created meanwhile is one more writable
357 /// mount). So the roster is reconciled once more under the locks;
358 /// when that changes the mounts, the locks are given back and
359 /// chosen again. Nothing is planned before this returns.
360 fn lock_on_a_settled_roster(
361 &mut self,
362 writes: bool,
363 choose: impl Fn(&Self) -> Vec<String>,
364 ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
365 let nested = COVERED.with(|c| !c.borrow().is_empty());
366 if nested || !writes {
367 return Ok((
368 self.lock_mems_for_write_if(writes, &choose(self))?,
369 Vec::new(),
370 ));
371 }
372 let mut warnings = Vec::new();
373 // A roster that keeps changing is not waited out for ever, and
374 // no lock set is kept over a roster that changed under it: the
375 // call is refused, and sent again it starts from the roster as
376 // it is then.
377 for _ in 0..3 {
378 let guard = self.lock_mems_for_write(&choose(self))?;
379 // What counts is whether the mounts changed, not whether
380 // the reconcile had something to say: a mem that keeps
381 // failing to attach is reported every time and changes
382 // nothing.
383 let mounted = |engine: &Self| -> Vec<String> {
384 engine.mounts.iter().map(|m| m.mount.mem.clone()).collect()
385 };
386 let before = mounted(self);
387 let reported = self.roster_warnings();
388 if mounted(self) == before {
389 warnings.extend(reported);
390 return Ok((guard, warnings));
391 }
392 drop(guard);
393 warnings.extend(reported);
394 }
395 Err(EngineError::Backend(BackendError::Other(
396 "the workspace's mount roster changed each time this operation had taken its write \
397 locks; nothing was written, send the call again"
398 .to_string(),
399 )))
400 }
401
402 /// The lock and the view of a verb that names the mems it writes.
403 /// `locked` are the mems whose lock it takes, `written` the ones
404 /// it writes (reloaded, and loaded when deferred); every other
405 /// loaded mem is reloaded too ([`Self::level_for_write`]).
406 ///
407 /// When `reads_workspace` says so, the verb is one that learns its
408 /// write set or its guard's read set by reading the workspace after
409 /// all, and gets [`Self::lock_workspace_for_write_if`] instead:
410 /// a call that names an entity by a bare slug (which mem carries
411 /// the slug is a fact about every mem), and a call that adds an
412 /// edge on an acyclic relationship (the cycle guard walks edges in
413 /// every mem, and two writers that each hold one mem's lock could
414 /// each add the edge that closes the other's cycle). The question
415 /// is asked after the roster is reconciled and before any lock is
416 /// taken.
417 ///
418 /// A mutation running inside another one keeps the outer one's
419 /// locks: taking further locks there would take them out of order.
420 pub(in crate::engine) fn lock_for_verb<S: AsRef<str>>(
421 &mut self,
422 writes: bool,
423 locked: &[S],
424 written: &[S],
425 reads_workspace: impl Fn(&Self) -> bool,
426 ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
427 let nested = COVERED.with(|c| !c.borrow().is_empty());
428 let mut warnings = self.roster_before_locking();
429 // A write into a mem mounted read-only is refused before any
430 // lock is taken: the refusal lays nothing where the mem lives,
431 // its lock file included.
432 if writes {
433 for mem in written {
434 if self.mounts.iter().any(|m| {
435 m.mount.mem == mem.as_ref()
436 && m.mount.capability != crate::workspace::MountCapability::Write
437 }) {
438 return Err(EngineError::ReadOnlyMount(mem.as_ref().to_string()));
439 }
440 }
441 }
442 if !nested && reads_workspace(self) {
443 let (guard, reloaded) = self.lock_whole_workspace(writes)?;
444 warnings.extend(reloaded);
445 return Ok((guard, warnings));
446 }
447 let names: Vec<String> = locked.iter().map(|m| m.as_ref().to_string()).collect();
448 let (guard, settled) = self.lock_on_a_settled_roster(writes, |_| names.clone())?;
449 warnings.extend(settled);
450 warnings.extend(self.level_for_write(written));
451 // The question again, on the view taken under the locks: what
452 // it reads (a schema's relationships) may have changed since
453 // it was asked. A yes now gives the locks back and takes every
454 // mount, before anything is planned.
455 if writes && !nested && reads_workspace(self) {
456 drop(guard);
457 let (guard, reloaded) = self.lock_whole_workspace(writes)?;
458 warnings.extend(reloaded);
459 return Ok((guard, warnings));
460 }
461 Ok((guard, warnings))
462 }
463
464 /// [`Self::lock_for_verb`] for a verb whose references depend on
465 /// what is in storage: an update that appends to a section or
466 /// patches one adds whatever link the resulting body holds, and
467 /// that body is the stored text with the call's text worked in.
468 /// `refer` names the mems the verb's result refers to, from the
469 /// engine's view. It is asked before the locks are taken and again
470 /// under them, on the reloaded view; when the second answer names
471 /// a mem the first did not, the locks are given back and taken
472 /// again with it. Nothing is planned before the two agree.
473 pub(in crate::engine) fn lock_for_verb_referring(
474 &mut self,
475 writes: bool,
476 written: &[String],
477 refer: impl Fn(&Self) -> Vec<String>,
478 reads_workspace: impl Fn(&Self) -> bool,
479 ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
480 let mut warnings = Vec::new();
481 let mut referred = refer(self);
482 for _ in 0..3 {
483 let mut locked = referred.clone();
484 locked.extend(written.iter().cloned());
485 let (guard, more) =
486 self.lock_for_verb(writes, &locked, written, |engine| reads_workspace(engine))?;
487 warnings.extend(more);
488 let under_lock = refer(self);
489 if !writes || under_lock.iter().all(|mem| referred.contains(mem)) {
490 return Ok((guard, warnings));
491 }
492 drop(guard);
493 for mem in under_lock {
494 if !referred.contains(&mem) {
495 referred.push(mem);
496 }
497 }
498 }
499 Err(EngineError::Backend(BackendError::Other(
500 "what this write refers to changed each time it had taken its write locks; nothing \
501 was written, send the call again"
502 .to_string(),
503 )))
504 }
505
506 /// Whether an edge of `rel_type` out of `mem` is guarded against
507 /// cycles: the relationship is acyclic, or it is in an acyclic set.
508 ///
509 /// The name is judged in the form the verb will write it in: a
510 /// caller may send `depends_on`, and the lock is decided before the
511 /// verb normalises its arguments. A name that does not normalise is
512 /// refused by the verb, and no edge comes of it.
513 pub(in crate::engine) fn rel_type_is_acyclic(&self, mem: &str, rel_type: &str) -> bool {
514 let Ok(rel_type) = crate::entity::id::validate_rel_type(rel_type) else {
515 return false;
516 };
517 self.schemas.get(mem).is_some_and(|s| {
518 s.relationship_acyclic(&rel_type) || s.acyclic_set_containing(&rel_type).is_some()
519 })
520 }
521
522 /// The lock of a verb that names its mems: the roster is reconciled
523 /// first, so a mem attached to the workspace since this engine
524 /// started is mounted, and therefore locked, before the first write
525 /// into it. Returns what the reconcile reported; the caller takes
526 /// its view under the lock ([`Self::level_for_write`]) and looks
527 /// its mounts up after this call (a reconcile moves them).
528 pub fn lock_for_write<S: AsRef<str>>(
529 &mut self,
530 writes: bool,
531 mems: &[S],
532 ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
533 let mut warnings = self.roster_before_locking();
534 let names: Vec<String> = mems.iter().map(|m| m.as_ref().to_string()).collect();
535 let (guard, settled) = self.lock_on_a_settled_roster(writes, |_| names.clone())?;
536 warnings.extend(settled);
537 Ok((guard, warnings))
538 }
539
540 /// The view a verb plans from, taken under its locks: the mems it
541 /// writes are reloaded (a deferred one is loaded: a write into a
542 /// mem needs the mem), and so is every other mem that is loaded.
543 /// The mems the write refers to are among its locks
544 /// ([`referred_mems`]), so what it checks of a relation target
545 /// (that it exists, what type it has) is read from a view taken
546 /// under the target's mem's lock and stays true until the commit. A
547 /// check that reads further than the mems a call names, the cycle
548 /// guard, does not run under this view: its verb takes the whole
549 /// workspace ([`Self::lock_for_verb`]). A deferred mem that is not
550 /// written stays unloaded; a target in it is checked against its
551 /// storage, under its lock.
552 pub(in crate::engine) fn level_for_write<S: AsRef<str>>(
553 &mut self,
554 written: &[S],
555 ) -> Vec<crate::ops::WarningHint> {
556 let mut mems: Vec<String> = written.iter().map(|m| m.as_ref().to_string()).collect();
557 for m in &self.mounts {
558 if !m.deferred && !mems.contains(&m.mount.mem) {
559 mems.push(m.mount.mem.clone());
560 }
561 }
562 let mut warnings = Vec::new();
563 for mem in &mems {
564 warnings.extend(self.reload_if_stale_content_only(Some(mem)));
565 }
566 warnings
567 }
568
569 /// The mount a write into `mem` goes to. Looked up after
570 /// [`Self::lock_for_write`], whose roster reconcile can move the
571 /// mounts.
572 pub(in crate::engine) fn writable_mount_index(&self, mem: &str) -> Result<usize, EngineError> {
573 let idx = self
574 .mounts
575 .iter()
576 .position(|m| m.mount.mem == mem)
577 .ok_or_else(|| self.unknown_mem_error(mem))?;
578 if self.mounts[idx].mount.capability != crate::workspace::MountCapability::Write {
579 return Err(EngineError::ReadOnlyMount(mem.to_string()));
580 }
581 Ok(idx)
582 }
583
584 /// Reconcile the roster ahead of a lock. A mutation that runs
585 /// inside another one (a batch over the single-item path) holds its
586 /// locks already and has begun planning: the membership it planned
587 /// against stays as it is until the outer mutation is done.
588 fn roster_before_locking(&mut self) -> Vec<crate::ops::WarningHint> {
589 if COVERED.with(|c| c.borrow().is_empty()) {
590 self.roster_warnings()
591 } else {
592 Vec::new()
593 }
594 }
595
596 /// [`Self::lock_mems_for_write`] when `writes` is true; an empty
597 /// guard otherwise. A rehearsal (`dry_run`) commits nothing, so it
598 /// takes no lock and leaves the workspace byte-identical, lock files
599 /// included.
600 pub fn lock_mems_for_write_if<S: AsRef<str>>(
601 &mut self,
602 writes: bool,
603 mems: &[S],
604 ) -> Result<MemWriteGuard, EngineError> {
605 if writes {
606 self.lock_mems_for_write(mems)
607 } else {
608 Ok(MemWriteGuard::empty())
609 }
610 }
611
612 /// Take the cross-process write lock of every named mem, in sorted
613 /// order (so two multi-mem writers can never deadlock), and hold it
614 /// until the returned guard drops. Call it before the
615 /// reload-before-operation probe of a mutation and keep the guard
616 /// alive past the commit. Mems that are not mounted are skipped:
617 /// the mutation's own lookup reports an unknown mem with its usual
618 /// error. A backend with no shared state takes no OS lock and is
619 /// still covered for the staged-write discard.
620 ///
621 /// What an earlier mutation left staged on a mem when its discard
622 /// failed is discarded here, once the mem's lock is held and before
623 /// the guard covers its backend: a backend whose discard keeps
624 /// failing can be replaced by a fresh one only while no mutation
625 /// holds it, and a write sent again right after the failed one
626 /// would otherwise hold it already and be refused as stale.
627 pub fn lock_mems_for_write<S: AsRef<str>>(
628 &mut self,
629 mems: &[S],
630 ) -> Result<MemWriteGuard, EngineError> {
631 let mut locks: Vec<(String, Option<PathBuf>, usize, Option<String>)> = mems
632 .iter()
633 .filter_map(|name| {
634 let m = self.mounts.iter().find(|m| m.mount.mem == name.as_ref())?;
635 // Named for the refusal below when it is mounted
636 // read-only.
637 let read_only = (m.mount.capability != crate::workspace::MountCapability::Write)
638 .then(|| m.mount.mem.clone());
639 Some((
640 m.mount.mem.clone(),
641 m.backend.write_lock_path(),
642 backend_key(&m.backend),
643 read_only,
644 ))
645 })
646 .collect();
647 // Sorted by lock path so two multi-mem writers take their locks
648 // in one order; pathless backends take no lock and sort first.
649 locks.sort_by(|a, b| a.1.cmp(&b.1));
650 locks.dedup_by(|a, b| a.2 == b.2);
651 let mut guard = MemWriteGuard::empty();
652 // How long a write waits for one mem's lock. A holder that never
653 // lets go would otherwise park every later writer of that mem
654 // without bound; past the limit the write refuses, and the
655 // guard gives back whatever it had taken on its way here.
656 let limit = self.settings().mutations.write_lock_timeout();
657 for (mem, path, _, read_only) in locks {
658 if let Some(path) = &path {
659 let started = std::time::Instant::now();
660 match (path_lock::acquire_within(path, limit), read_only) {
661 (Ok(true), _) => {}
662 (Ok(false), _) => {
663 return Err(EngineError::WriteLockTimeout {
664 mem,
665 waited_ms: started.elapsed().as_millis() as u64,
666 });
667 }
668 // A mem mounted read-only may sit where this
669 // process cannot open its lock file. The operation
670 // asked for the lock because it reads the mem and
671 // needs it to hold still, and another process may
672 // write it; without the lock that cannot be had,
673 // so the operation is refused and names the mem.
674 (Err(e), Some(mem)) => {
675 return Err(EngineError::StaleView {
676 mem,
677 cause: super::StaleCause::LockUnavailable,
678 detail: format!(
679 "the mem's write lock cannot be taken here ({e}), so its content \
680 cannot be held still for an operation that reads it"
681 ),
682 });
683 }
684 (Err(e), None) => return Err(EngineError::Backend(BackendError::Io(e))),
685 }
686 }
687 // A failure stays recorded on the mount, and the reload
688 // under this lock refuses the write naming the mem.
689 let _ = self.discard_strays(&mem);
690 let Some(m) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
691 if let Some(path) = &path {
692 path_lock::release(path);
693 }
694 continue;
695 };
696 guard.cover(Held {
697 path,
698 backend: Arc::clone(&m.backend),
699 strays: Arc::clone(&m.strays),
700 });
701 }
702 Ok(guard)
703 }
704}
705
706/// The mems a create or an update refers to besides the one it writes:
707/// the mems of its declared relation targets and of the wiki-links in
708/// the text the call brings. The write takes their locks with its own.
709/// A delete, a rename or a retype of a target holds the target's mem,
710/// so a reference cannot be written while one is under way, whenever
711/// the writing mem was attached; the write waits, reloads, and is
712/// computed against the target as that verb left it.
713pub(in crate::engine) fn referred_mems<'a>(
714 own: &str,
715 targets: impl IntoIterator<Item = &'a crate::entity::EntityId>,
716 texts: impl IntoIterator<Item = &'a str>,
717) -> Vec<String> {
718 let mut mems: Vec<String> = targets.into_iter().map(|t| t.mem().to_string()).collect();
719 for text in texts {
720 // Cheap gate: a text without a wiki-link names no mem.
721 if text.contains("[[") {
722 mems.extend(
723 crate::entity::parser::extract_inline_links_lenient(text, own)
724 .iter()
725 .map(|t| t.mem().to_string()),
726 );
727 }
728 }
729 mems.retain(|m| !m.is_empty() && m != own);
730 mems.sort();
731 mems.dedup();
732 mems
733}