Skip to main content

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.backend_factory)(&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 an operation on the
207    /// mem `subject` as a whole (its deletion): `subject` itself may be
208    /// unreadable or out of service, which is often why it is being
209    /// removed, and that does not refuse the operation. Every other
210    /// mem must be readable as for any verb that reads the workspace.
211    pub fn lock_workspace_for_mem_operation(
212        &mut self,
213        subject: &str,
214    ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
215        self.lock_workspace_for_mems_operation(&[subject])
216    }
217
218    /// [`Self::lock_workspace_for_mem_operation`] for an operation on
219    /// several mems as wholes (`pull --all` reconciles every one): each
220    /// subject may be unreadable or out of service; every other mem must
221    /// be readable.
222    pub fn lock_workspace_for_mems_operation(
223        &mut self,
224        subjects: &[&str],
225    ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
226        let mut warnings = self.roster_before_locking();
227        let (guard, reloaded) = self.lock_whole_workspace_except(true, subjects)?;
228        warnings.extend(reloaded);
229        Ok((guard, warnings))
230    }
231
232    fn lock_whole_workspace(
233        &mut self,
234        writes: bool,
235    ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
236        self.lock_whole_workspace_except(writes, &[])
237    }
238
239    fn lock_whole_workspace_except(
240        &mut self,
241        writes: bool,
242        tolerated: &[&str],
243    ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
244        // Every mount that has a write lock, the ones this engine mounts
245        // read-only included: another process may mount the same
246        // storage writable, and a guard that reads it needs its writer
247        // to wait like any other.
248        let (guard, mut warnings) = self.lock_on_a_settled_roster(writes, |engine| {
249            engine
250                .mounts
251                .iter()
252                .filter(|m| {
253                    m.mount.capability == crate::workspace::MountCapability::Write
254                        || m.backend.write_lock_path().is_some()
255                })
256                .map(|m| m.mount.mem.clone())
257                .collect()
258        })?;
259        warnings.extend(self.reload_if_stale_content_only(None));
260        if let Some((stale, failure)) = self
261            .mounts
262            .iter()
263            .filter(|m| !tolerated.contains(&m.mount.mem.as_str()))
264            .find_map(|m| m.reload_failure.as_ref().map(|f| (m, f)))
265        {
266            return Err(failure.refusal(&stale.mount.mem));
267        }
268        // A mem that is out of service is in no view at all: one whose
269        // deferred load just failed under this lock, or one that never
270        // attached. Its referrers are as unread as a stale mem's.
271        if let Some(out) = self
272            .quarantined
273            .iter()
274            .find(|q| !tolerated.contains(&q.mount.mem.as_str()))
275        {
276            return Err(EngineError::StaleView {
277                mem: out.mount.mem.clone(),
278                cause: super::StaleCause::OutOfService,
279                detail: format!("{}: {}", out.reason_code, out.reason_message),
280            });
281        }
282        Ok((guard, warnings))
283    }
284
285    /// Take the locks `choose` names, and hold them over a roster that
286    /// did not change while this process waited for them. The process
287    /// that held a lock may have changed the roster before it let go (a
288    /// mem rename takes the mem away under the lock a writer into it
289    /// is waiting on; a mem created meanwhile is one more writable
290    /// mount). So the roster is reconciled once more under the locks;
291    /// when that changes the mounts, the locks are given back and
292    /// chosen again. Nothing is planned before this returns.
293    fn lock_on_a_settled_roster(
294        &mut self,
295        writes: bool,
296        choose: impl Fn(&Self) -> Vec<String>,
297    ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
298        let nested = COVERED.with(|c| !c.borrow().is_empty());
299        if nested || !writes {
300            return Ok((
301                self.lock_mems_for_write_if(writes, &choose(self))?,
302                Vec::new(),
303            ));
304        }
305        let mut warnings = Vec::new();
306        // A roster that keeps changing is not waited out for ever, and
307        // no lock set is kept over a roster that changed under it: the
308        // call is refused, and sent again it starts from the roster as
309        // it is then.
310        for _ in 0..3 {
311            let guard = self.lock_mems_for_write(&choose(self))?;
312            // What counts is whether the mounts changed, not whether
313            // the reconcile had something to say: a mem that keeps
314            // failing to attach is reported every time and changes
315            // nothing.
316            let mounted = |engine: &Self| -> Vec<String> {
317                engine.mounts.iter().map(|m| m.mount.mem.clone()).collect()
318            };
319            let before = mounted(self);
320            let reported = self.roster_warnings();
321            if mounted(self) == before {
322                warnings.extend(reported);
323                return Ok((guard, warnings));
324            }
325            drop(guard);
326            warnings.extend(reported);
327        }
328        Err(EngineError::Backend(BackendError::Other(
329            "the workspace's mount roster changed each time this operation had taken its write \
330             locks; nothing was written, send the call again"
331                .to_string(),
332        )))
333    }
334
335    /// The lock and the view of a verb that names the mems it writes.
336    /// `locked` are the mems whose lock it takes, `written` the ones
337    /// it writes (reloaded, and loaded when deferred); every other
338    /// loaded mem is reloaded too ([`Self::level_for_write`]).
339    ///
340    /// When `reads_workspace` says so, the verb is one that learns its
341    /// write set or its guard's read set by reading the workspace after
342    /// all, and gets [`Self::lock_workspace_for_write_if`] instead:
343    /// a call that names an entity by a bare slug (which mem carries
344    /// the slug is a fact about every mem), and a call that adds an
345    /// edge on an acyclic relationship (the cycle guard walks edges in
346    /// every mem, and two writers that each hold one mem's lock could
347    /// each add the edge that closes the other's cycle). The question
348    /// is asked after the roster is reconciled and before any lock is
349    /// taken.
350    ///
351    /// A mutation running inside another one keeps the outer one's
352    /// locks: taking further locks there would take them out of order.
353    pub(in crate::engine) fn lock_for_verb<S: AsRef<str>>(
354        &mut self,
355        writes: bool,
356        locked: &[S],
357        written: &[S],
358        reads_workspace: impl Fn(&Self) -> bool,
359    ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
360        let nested = COVERED.with(|c| !c.borrow().is_empty());
361        let mut warnings = self.roster_before_locking();
362        if !nested && reads_workspace(self) {
363            let (guard, reloaded) = self.lock_whole_workspace(writes)?;
364            warnings.extend(reloaded);
365            return Ok((guard, warnings));
366        }
367        let names: Vec<String> = locked.iter().map(|m| m.as_ref().to_string()).collect();
368        let (guard, settled) = self.lock_on_a_settled_roster(writes, |_| names.clone())?;
369        warnings.extend(settled);
370        warnings.extend(self.level_for_write(written));
371        // The question again, on the view taken under the locks: what
372        // it reads (a schema's relationships) may have changed since
373        // it was asked. A yes now gives the locks back and takes every
374        // mount, before anything is planned.
375        if writes && !nested && reads_workspace(self) {
376            drop(guard);
377            let (guard, reloaded) = self.lock_whole_workspace(writes)?;
378            warnings.extend(reloaded);
379            return Ok((guard, warnings));
380        }
381        Ok((guard, warnings))
382    }
383
384    /// [`Self::lock_for_verb`] for a verb whose references depend on
385    /// what is in storage: an update that appends to a section or
386    /// patches one adds whatever link the resulting body holds, and
387    /// that body is the stored text with the call's text worked in.
388    /// `refer` names the mems the verb's result refers to, from the
389    /// engine's view. It is asked before the locks are taken and again
390    /// under them, on the reloaded view; when the second answer names
391    /// a mem the first did not, the locks are given back and taken
392    /// again with it. Nothing is planned before the two agree.
393    pub(in crate::engine) fn lock_for_verb_referring(
394        &mut self,
395        writes: bool,
396        written: &[String],
397        refer: impl Fn(&Self) -> Vec<String>,
398        reads_workspace: impl Fn(&Self) -> bool,
399    ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
400        let mut warnings = Vec::new();
401        let mut referred = refer(self);
402        for _ in 0..3 {
403            let mut locked = referred.clone();
404            locked.extend(written.iter().cloned());
405            let (guard, more) =
406                self.lock_for_verb(writes, &locked, written, |engine| reads_workspace(engine))?;
407            warnings.extend(more);
408            let under_lock = refer(self);
409            if !writes || under_lock.iter().all(|mem| referred.contains(mem)) {
410                return Ok((guard, warnings));
411            }
412            drop(guard);
413            for mem in under_lock {
414                if !referred.contains(&mem) {
415                    referred.push(mem);
416                }
417            }
418        }
419        Err(EngineError::Backend(BackendError::Other(
420            "what this write refers to changed each time it had taken its write locks; nothing \
421             was written, send the call again"
422                .to_string(),
423        )))
424    }
425
426    /// Whether an edge of `rel_type` out of `mem` is guarded against
427    /// cycles: the relationship is acyclic, or it is in an acyclic set.
428    ///
429    /// The name is judged in the form the verb will write it in: a
430    /// caller may send `depends_on`, and the lock is decided before the
431    /// verb normalises its arguments. A name that does not normalise is
432    /// refused by the verb, and no edge comes of it.
433    pub(in crate::engine) fn rel_type_is_acyclic(&self, mem: &str, rel_type: &str) -> bool {
434        let Ok(rel_type) = crate::entity::id::validate_rel_type(rel_type) else {
435            return false;
436        };
437        self.schemas.get(mem).is_some_and(|s| {
438            s.relationship_acyclic(&rel_type) || s.acyclic_set_containing(&rel_type).is_some()
439        })
440    }
441
442    /// The lock of a verb that names its mems: the roster is reconciled
443    /// first, so a mem attached to the workspace since this engine
444    /// started is mounted, and therefore locked, before the first write
445    /// into it. Returns what the reconcile reported; the caller takes
446    /// its view under the lock ([`Self::level_for_write`]) and looks
447    /// its mounts up after this call (a reconcile moves them).
448    pub fn lock_for_write<S: AsRef<str>>(
449        &mut self,
450        writes: bool,
451        mems: &[S],
452    ) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
453        let mut warnings = self.roster_before_locking();
454        let names: Vec<String> = mems.iter().map(|m| m.as_ref().to_string()).collect();
455        let (guard, settled) = self.lock_on_a_settled_roster(writes, |_| names.clone())?;
456        warnings.extend(settled);
457        Ok((guard, warnings))
458    }
459
460    /// The view a verb plans from, taken under its locks: the mems it
461    /// writes are reloaded (a deferred one is loaded: a write into a
462    /// mem needs the mem), and so is every other mem that is loaded.
463    /// The mems the write refers to are among its locks
464    /// ([`referred_mems`]), so what it checks of a relation target
465    /// (that it exists, what type it has) is read from a view taken
466    /// under the target's mem's lock and stays true until the commit. A
467    /// check that reads further than the mems a call names, the cycle
468    /// guard, does not run under this view: its verb takes the whole
469    /// workspace ([`Self::lock_for_verb`]). A deferred mem that is not
470    /// written stays unloaded; a target in it is checked against its
471    /// storage, under its lock.
472    pub(in crate::engine) fn level_for_write<S: AsRef<str>>(
473        &mut self,
474        written: &[S],
475    ) -> Vec<crate::ops::WarningHint> {
476        let mut mems: Vec<String> = written.iter().map(|m| m.as_ref().to_string()).collect();
477        for m in &self.mounts {
478            if !m.deferred && !mems.contains(&m.mount.mem) {
479                mems.push(m.mount.mem.clone());
480            }
481        }
482        let mut warnings = Vec::new();
483        for mem in &mems {
484            warnings.extend(self.reload_if_stale_content_only(Some(mem)));
485        }
486        warnings
487    }
488
489    /// The mount a write into `mem` goes to. Looked up after
490    /// [`Self::lock_for_write`], whose roster reconcile can move the
491    /// mounts.
492    pub(in crate::engine) fn writable_mount_index(&self, mem: &str) -> Result<usize, EngineError> {
493        let idx = self
494            .mounts
495            .iter()
496            .position(|m| m.mount.mem == mem)
497            .ok_or_else(|| self.unknown_mem_error(mem))?;
498        if self.mounts[idx].mount.capability != crate::workspace::MountCapability::Write {
499            return Err(EngineError::ReadOnlyMount(mem.to_string()));
500        }
501        Ok(idx)
502    }
503
504    /// Reconcile the roster ahead of a lock. A mutation that runs
505    /// inside another one (a batch over the single-item path) holds its
506    /// locks already and has begun planning: the membership it planned
507    /// against stays as it is until the outer mutation is done.
508    fn roster_before_locking(&mut self) -> Vec<crate::ops::WarningHint> {
509        if COVERED.with(|c| c.borrow().is_empty()) {
510            self.roster_warnings()
511        } else {
512            Vec::new()
513        }
514    }
515
516    /// [`Self::lock_mems_for_write`] when `writes` is true; an empty
517    /// guard otherwise. A rehearsal (`dry_run`) commits nothing, so it
518    /// takes no lock and leaves the workspace byte-identical, lock files
519    /// included.
520    pub fn lock_mems_for_write_if<S: AsRef<str>>(
521        &mut self,
522        writes: bool,
523        mems: &[S],
524    ) -> Result<MemWriteGuard, EngineError> {
525        if writes {
526            self.lock_mems_for_write(mems)
527        } else {
528            Ok(MemWriteGuard::empty())
529        }
530    }
531
532    /// Take the cross-process write lock of every named mem, in sorted
533    /// order (so two multi-mem writers can never deadlock), and hold it
534    /// until the returned guard drops. Call it before the
535    /// reload-before-operation probe of a mutation and keep the guard
536    /// alive past the commit. Mems that are not mounted are skipped:
537    /// the mutation's own lookup reports an unknown mem with its usual
538    /// error. A backend with no shared state takes no OS lock and is
539    /// still covered for the staged-write discard.
540    ///
541    /// What an earlier mutation left staged on a mem when its discard
542    /// failed is discarded here, once the mem's lock is held and before
543    /// the guard covers its backend: a backend whose discard keeps
544    /// failing can be replaced by a fresh one only while no mutation
545    /// holds it, and a write sent again right after the failed one
546    /// would otherwise hold it already and be refused as stale.
547    pub fn lock_mems_for_write<S: AsRef<str>>(
548        &mut self,
549        mems: &[S],
550    ) -> Result<MemWriteGuard, EngineError> {
551        let mut locks: Vec<(String, Option<PathBuf>, usize, Option<String>)> = mems
552            .iter()
553            .filter_map(|name| {
554                let m = self.mounts.iter().find(|m| m.mount.mem == name.as_ref())?;
555                // Named for the refusal below when it is mounted
556                // read-only.
557                let read_only = (m.mount.capability != crate::workspace::MountCapability::Write)
558                    .then(|| m.mount.mem.clone());
559                Some((
560                    m.mount.mem.clone(),
561                    m.backend.write_lock_path(),
562                    backend_key(&m.backend),
563                    read_only,
564                ))
565            })
566            .collect();
567        // Sorted by lock path so two multi-mem writers take their locks
568        // in one order; pathless backends take no lock and sort first.
569        locks.sort_by(|a, b| a.1.cmp(&b.1));
570        locks.dedup_by(|a, b| a.2 == b.2);
571        let mut guard = MemWriteGuard::empty();
572        for (mem, path, _, read_only) in locks {
573            if let Some(path) = &path {
574                match (path_lock::acquire(path), read_only) {
575                    (Ok(()), _) => {}
576                    // A mem mounted read-only may sit where this
577                    // process cannot open its lock file. The operation
578                    // asked for the lock because it reads the mem and
579                    // needs it to hold still, and another process may
580                    // write it; without the lock that cannot be had,
581                    // so the operation is refused and names the mem.
582                    (Err(e), Some(mem)) => {
583                        return Err(EngineError::StaleView {
584                            mem,
585                            cause: super::StaleCause::LockUnavailable,
586                            detail: format!(
587                                "the mem's write lock cannot be taken here ({e}), so its content \
588                                 cannot be held still for an operation that reads it"
589                            ),
590                        });
591                    }
592                    (Err(e), None) => return Err(EngineError::Backend(BackendError::Io(e))),
593                }
594            }
595            // A failure stays recorded on the mount, and the reload
596            // under this lock refuses the write naming the mem.
597            let _ = self.discard_strays(&mem);
598            let Some(m) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
599                if let Some(path) = &path {
600                    path_lock::release(path);
601                }
602                continue;
603            };
604            guard.cover(Held {
605                path,
606                backend: Arc::clone(&m.backend),
607                strays: Arc::clone(&m.strays),
608            });
609        }
610        Ok(guard)
611    }
612}
613
614/// The mems a create or an update refers to besides the one it writes:
615/// the mems of its declared relation targets and of the wiki-links in
616/// the text the call brings. The write takes their locks with its own.
617/// A delete, a rename or a retype of a target holds the target's mem,
618/// so a reference cannot be written while one is under way, whenever
619/// the writing mem was attached; the write waits, reloads, and is
620/// computed against the target as that verb left it.
621pub(in crate::engine) fn referred_mems<'a>(
622    own: &str,
623    targets: impl IntoIterator<Item = &'a crate::entity::EntityId>,
624    texts: impl IntoIterator<Item = &'a str>,
625) -> Vec<String> {
626    let mut mems: Vec<String> = targets.into_iter().map(|t| t.mem().to_string()).collect();
627    for text in texts {
628        // Cheap gate: a text without a wiki-link names no mem.
629        if text.contains("[[") {
630            mems.extend(
631                crate::entity::parser::extract_inline_links_lenient(text, own)
632                    .iter()
633                    .map(|t| t.mem().to_string()),
634            );
635        }
636    }
637    mems.retain(|m| !m.is_empty() && m != own);
638    mems.sort();
639    mems.dedup();
640    mems
641}