use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use crate::backend::{BackendError, MemBackend};
use crate::storage::path_lock;
use super::{Engine, EngineError};
#[must_use = "the write lock is released as soon as the guard drops"]
pub struct MemWriteGuard {
held: Vec<Held>,
}
struct Held {
path: Option<PathBuf>,
backend: Arc<dyn MemBackend>,
strays: Arc<std::sync::atomic::AtomicBool>,
}
thread_local! {
static COVERED: RefCell<HashMap<usize, usize>> = RefCell::new(HashMap::new());
}
fn backend_key(backend: &Arc<dyn MemBackend>) -> usize {
Arc::as_ptr(backend) as *const () as usize
}
impl MemWriteGuard {
fn empty() -> Self {
Self { held: Vec::new() }
}
fn cover(&mut self, held: Held) {
COVERED.with(|c| {
*c.borrow_mut()
.entry(backend_key(&held.backend))
.or_insert(0) += 1
});
self.held.push(held);
}
}
impl Drop for MemWriteGuard {
fn drop(&mut self) {
for Held {
path,
backend,
strays,
} in self.held.iter().rev()
{
let outermost = COVERED.with(|c| {
let mut covered = c.borrow_mut();
let key = backend_key(backend);
match covered.get_mut(&key) {
Some(count) if *count > 1 => {
*count -= 1;
false
}
_ => {
covered.remove(&key);
true
}
}
});
if outermost {
strays.store(
backend.discard_pending().is_err(),
std::sync::atomic::Ordering::SeqCst,
);
}
if let Some(path) = path {
path_lock::release(path);
}
}
}
}
impl Engine {
pub(super) fn discard_strays(&mut self, mem: &str) -> Result<(), BackendError> {
use std::sync::atomic::Ordering;
let Some(idx) = self.mounts.iter().position(|m| m.mount.mem == mem) else {
return Ok(());
};
let state = &self.mounts[idx];
if !state.strays.load(Ordering::SeqCst) {
return Ok(());
}
let failure = match state.backend.discard_pending() {
Ok(()) => {
state.strays.store(false, Ordering::SeqCst);
return Ok(());
}
Err(e) => e,
};
let on_disk = matches!(
state.mount.storage,
crate::workspace::MountStorage::Folder { .. }
| crate::workspace::MountStorage::GitBranch { .. }
);
let held_by_a_mutation = COVERED.with(|c| {
c.borrow()
.get(&backend_key(&state.backend))
.is_some_and(|count| *count > 0)
});
if on_disk
&& !held_by_a_mutation
&& let Ok(fresh) = (self.backend_factory)(&state.mount)
{
self.mounts[idx].backend = Arc::from(fresh);
self.mounts[idx].strays = Default::default();
return Ok(());
}
Err(failure)
}
pub fn lock_workspace_for_write_if(
&mut self,
writes: bool,
) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
let mut warnings = self.roster_before_locking();
let (guard, reloaded) = self.lock_whole_workspace(writes)?;
warnings.extend(reloaded);
Ok((guard, warnings))
}
pub fn lock_workspace_for_mem_operation(
&mut self,
subject: &str,
) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
self.lock_workspace_for_mems_operation(&[subject])
}
pub fn lock_workspace_for_mems_operation(
&mut self,
subjects: &[&str],
) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
let mut warnings = self.roster_before_locking();
let (guard, reloaded) = self.lock_whole_workspace_except(true, subjects)?;
warnings.extend(reloaded);
Ok((guard, warnings))
}
fn lock_whole_workspace(
&mut self,
writes: bool,
) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
self.lock_whole_workspace_except(writes, &[])
}
fn lock_whole_workspace_except(
&mut self,
writes: bool,
tolerated: &[&str],
) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
let (guard, mut warnings) = self.lock_on_a_settled_roster(writes, |engine| {
engine
.mounts
.iter()
.filter(|m| {
m.mount.capability == crate::workspace::MountCapability::Write
|| m.backend.write_lock_path().is_some()
})
.map(|m| m.mount.mem.clone())
.collect()
})?;
warnings.extend(self.reload_if_stale_content_only(None));
if let Some((stale, failure)) = self
.mounts
.iter()
.filter(|m| !tolerated.contains(&m.mount.mem.as_str()))
.find_map(|m| m.reload_failure.as_ref().map(|f| (m, f)))
{
return Err(failure.refusal(&stale.mount.mem));
}
if let Some(out) = self
.quarantined
.iter()
.find(|q| !tolerated.contains(&q.mount.mem.as_str()))
{
return Err(EngineError::StaleView {
mem: out.mount.mem.clone(),
cause: super::StaleCause::OutOfService,
detail: format!("{}: {}", out.reason_code, out.reason_message),
});
}
Ok((guard, warnings))
}
fn lock_on_a_settled_roster(
&mut self,
writes: bool,
choose: impl Fn(&Self) -> Vec<String>,
) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
let nested = COVERED.with(|c| !c.borrow().is_empty());
if nested || !writes {
return Ok((
self.lock_mems_for_write_if(writes, &choose(self))?,
Vec::new(),
));
}
let mut warnings = Vec::new();
for _ in 0..3 {
let guard = self.lock_mems_for_write(&choose(self))?;
let mounted = |engine: &Self| -> Vec<String> {
engine.mounts.iter().map(|m| m.mount.mem.clone()).collect()
};
let before = mounted(self);
let reported = self.roster_warnings();
if mounted(self) == before {
warnings.extend(reported);
return Ok((guard, warnings));
}
drop(guard);
warnings.extend(reported);
}
Err(EngineError::Backend(BackendError::Other(
"the workspace's mount roster changed each time this operation had taken its write \
locks; nothing was written, send the call again"
.to_string(),
)))
}
pub(in crate::engine) fn lock_for_verb<S: AsRef<str>>(
&mut self,
writes: bool,
locked: &[S],
written: &[S],
reads_workspace: impl Fn(&Self) -> bool,
) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
let nested = COVERED.with(|c| !c.borrow().is_empty());
let mut warnings = self.roster_before_locking();
if !nested && reads_workspace(self) {
let (guard, reloaded) = self.lock_whole_workspace(writes)?;
warnings.extend(reloaded);
return Ok((guard, warnings));
}
let names: Vec<String> = locked.iter().map(|m| m.as_ref().to_string()).collect();
let (guard, settled) = self.lock_on_a_settled_roster(writes, |_| names.clone())?;
warnings.extend(settled);
warnings.extend(self.level_for_write(written));
if writes && !nested && reads_workspace(self) {
drop(guard);
let (guard, reloaded) = self.lock_whole_workspace(writes)?;
warnings.extend(reloaded);
return Ok((guard, warnings));
}
Ok((guard, warnings))
}
pub(in crate::engine) fn lock_for_verb_referring(
&mut self,
writes: bool,
written: &[String],
refer: impl Fn(&Self) -> Vec<String>,
reads_workspace: impl Fn(&Self) -> bool,
) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
let mut warnings = Vec::new();
let mut referred = refer(self);
for _ in 0..3 {
let mut locked = referred.clone();
locked.extend(written.iter().cloned());
let (guard, more) =
self.lock_for_verb(writes, &locked, written, |engine| reads_workspace(engine))?;
warnings.extend(more);
let under_lock = refer(self);
if !writes || under_lock.iter().all(|mem| referred.contains(mem)) {
return Ok((guard, warnings));
}
drop(guard);
for mem in under_lock {
if !referred.contains(&mem) {
referred.push(mem);
}
}
}
Err(EngineError::Backend(BackendError::Other(
"what this write refers to changed each time it had taken its write locks; nothing \
was written, send the call again"
.to_string(),
)))
}
pub(in crate::engine) fn rel_type_is_acyclic(&self, mem: &str, rel_type: &str) -> bool {
let Ok(rel_type) = crate::entity::id::validate_rel_type(rel_type) else {
return false;
};
self.schemas.get(mem).is_some_and(|s| {
s.relationship_acyclic(&rel_type) || s.acyclic_set_containing(&rel_type).is_some()
})
}
pub fn lock_for_write<S: AsRef<str>>(
&mut self,
writes: bool,
mems: &[S],
) -> Result<(MemWriteGuard, Vec<crate::ops::WarningHint>), EngineError> {
let mut warnings = self.roster_before_locking();
let names: Vec<String> = mems.iter().map(|m| m.as_ref().to_string()).collect();
let (guard, settled) = self.lock_on_a_settled_roster(writes, |_| names.clone())?;
warnings.extend(settled);
Ok((guard, warnings))
}
pub(in crate::engine) fn level_for_write<S: AsRef<str>>(
&mut self,
written: &[S],
) -> Vec<crate::ops::WarningHint> {
let mut mems: Vec<String> = written.iter().map(|m| m.as_ref().to_string()).collect();
for m in &self.mounts {
if !m.deferred && !mems.contains(&m.mount.mem) {
mems.push(m.mount.mem.clone());
}
}
let mut warnings = Vec::new();
for mem in &mems {
warnings.extend(self.reload_if_stale_content_only(Some(mem)));
}
warnings
}
pub(in crate::engine) fn writable_mount_index(&self, mem: &str) -> Result<usize, EngineError> {
let idx = self
.mounts
.iter()
.position(|m| m.mount.mem == mem)
.ok_or_else(|| self.unknown_mem_error(mem))?;
if self.mounts[idx].mount.capability != crate::workspace::MountCapability::Write {
return Err(EngineError::ReadOnlyMount(mem.to_string()));
}
Ok(idx)
}
fn roster_before_locking(&mut self) -> Vec<crate::ops::WarningHint> {
if COVERED.with(|c| c.borrow().is_empty()) {
self.roster_warnings()
} else {
Vec::new()
}
}
pub fn lock_mems_for_write_if<S: AsRef<str>>(
&mut self,
writes: bool,
mems: &[S],
) -> Result<MemWriteGuard, EngineError> {
if writes {
self.lock_mems_for_write(mems)
} else {
Ok(MemWriteGuard::empty())
}
}
pub fn lock_mems_for_write<S: AsRef<str>>(
&mut self,
mems: &[S],
) -> Result<MemWriteGuard, EngineError> {
let mut locks: Vec<(String, Option<PathBuf>, usize, Option<String>)> = mems
.iter()
.filter_map(|name| {
let m = self.mounts.iter().find(|m| m.mount.mem == name.as_ref())?;
let read_only = (m.mount.capability != crate::workspace::MountCapability::Write)
.then(|| m.mount.mem.clone());
Some((
m.mount.mem.clone(),
m.backend.write_lock_path(),
backend_key(&m.backend),
read_only,
))
})
.collect();
locks.sort_by(|a, b| a.1.cmp(&b.1));
locks.dedup_by(|a, b| a.2 == b.2);
let mut guard = MemWriteGuard::empty();
for (mem, path, _, read_only) in locks {
if let Some(path) = &path {
match (path_lock::acquire(path), read_only) {
(Ok(()), _) => {}
(Err(e), Some(mem)) => {
return Err(EngineError::StaleView {
mem,
cause: super::StaleCause::LockUnavailable,
detail: format!(
"the mem's write lock cannot be taken here ({e}), so its content \
cannot be held still for an operation that reads it"
),
});
}
(Err(e), None) => return Err(EngineError::Backend(BackendError::Io(e))),
}
}
let _ = self.discard_strays(&mem);
let Some(m) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
if let Some(path) = &path {
path_lock::release(path);
}
continue;
};
guard.cover(Held {
path,
backend: Arc::clone(&m.backend),
strays: Arc::clone(&m.strays),
});
}
Ok(guard)
}
}
pub(in crate::engine) fn referred_mems<'a>(
own: &str,
targets: impl IntoIterator<Item = &'a crate::entity::EntityId>,
texts: impl IntoIterator<Item = &'a str>,
) -> Vec<String> {
let mut mems: Vec<String> = targets.into_iter().map(|t| t.mem().to_string()).collect();
for text in texts {
if text.contains("[[") {
mems.extend(
crate::entity::parser::extract_inline_links_lenient(text, own)
.iter()
.map(|t| t.mem().to_string()),
);
}
}
mems.retain(|m| !m.is_empty() && m != own);
mems.sort();
mems.dedup();
mems
}