use crate::backend::BackendError;
use crate::entity::EntityId;
use crate::ops::WarningHint;
use crate::provenance::{Provenance, ProvenanceKind};
use crate::vcs::{Actor, ClientId, CommitContext};
use crate::engine::{Engine, EngineError};
pub(in crate::engine) struct Landed {
pub(in crate::engine) write_id: String,
pub(in crate::engine) warnings: Vec<WarningHint>,
}
impl Engine {
pub(in crate::engine) fn provenance_record(
&self,
kind: ProvenanceKind,
entity: &EntityId,
actor: Actor,
client: Option<&ClientId>,
note: Option<&str>,
) -> Provenance {
Provenance::new(
std::time::SystemTime::now(),
kind,
Some(entity.to_string()),
actor,
client.cloned(),
note.map(String::from),
)
.with_role(self.current_role)
.with_identity(self.current_identity.clone())
}
pub(in crate::engine) fn commit_staged(
&self,
mount_idx: usize,
subject: &str,
ctx: &CommitContext<'_>,
records: &[Provenance],
) -> Result<Landed, EngineError> {
self.commit_staged_pinned(mount_idx, subject, ctx, records, None)
}
pub(in crate::engine) fn commit_staged_pinned(
&self,
mount_idx: usize,
subject: &str,
ctx: &CommitContext<'_>,
records: &[Provenance],
expected_parent: Option<&str>,
) -> Result<Landed, EngineError> {
let state = &self.mounts[mount_idx];
let backend = state.backend.as_ref();
if let Some(failure) = &state.reload_failure {
let _ = backend.discard_pending();
return Err(failure.refusal(&state.mount.mem));
}
let staged = records
.iter()
.try_for_each(|record| backend.stage_provenance(record));
let committed = staged
.and_then(|()| backend.commit_with_expected_parent(subject, ctx, expected_parent));
self.settle(mount_idx, committed, records)
}
pub(in crate::engine) fn append_record(
&self,
mount_idx: usize,
record: &Provenance,
) -> Result<Landed, EngineError> {
let state = &self.mounts[mount_idx];
if let Some(failure) = &state.reload_failure {
return Err(failure.refusal(&state.mount.mem));
}
let appended = state
.backend
.append_provenance(record)
.map(|()| String::new());
self.settle(mount_idx, appended, std::slice::from_ref(record))
}
pub(in crate::engine) fn commit_or_complete(
&self,
mount_idx: usize,
committed: Result<Landed, EngineError>,
) -> Result<Landed, EngineError> {
let (mem, detail) = match committed {
Err(EngineError::CommitNotApplied { mem, detail }) => (mem, detail),
other => return other,
};
match self.mounts[mount_idx].backend.complete_interrupted_commit() {
Ok(_) => Ok(Landed {
write_id: crate::storage::filesystem::make_commit_id(),
warnings: vec![WarningHint::WriteFollowUpFailed {
mem,
step: "commit_apply".to_string(),
detail,
}],
}),
Err(again) => Err(EngineError::CommitNotApplied {
mem,
detail: format!("{detail}; and once more: {again}"),
}),
}
}
fn lost_race_refusal(
&self,
mount_idx: usize,
records: &[Provenance],
tip: String,
) -> EngineError {
let Some(id) = records.iter().find_map(|r| r.entity.clone()) else {
return EngineError::HashMismatch {
id: String::new(),
current: tip,
is_stub: false,
};
};
let entity_id = EntityId(id.clone());
let path = self
.store
.get(&entity_id)
.map(|e| e.file_path.clone())
.unwrap_or_else(|| crate::entity::id::id_to_file_path(&entity_id));
match self.mounts[mount_idx]
.backend
.read_entity(std::path::Path::new(&path))
{
Ok(Some(bytes)) => EngineError::HashMismatch {
id,
current: crate::entity::parser::compute_hash(&String::from_utf8_lossy(&bytes)),
is_stub: false,
},
Ok(None) => EngineError::NotFound {
id,
suggestions: Vec::new(),
},
Err(e) => EngineError::Backend(e),
}
}
fn settle(
&self,
mount_idx: usize,
committed: Result<String, BackendError>,
records: &[Provenance],
) -> Result<Landed, EngineError> {
let state = &self.mounts[mount_idx];
let backend = state.backend.as_ref();
match committed {
Err(BackendError::HashMismatch { current: tip }) => {
let _ = backend.discard_pending();
Err(self.lost_race_refusal(mount_idx, records, tip))
}
Ok(write_id) => Ok(Landed {
write_id,
warnings: Vec::new(),
}),
Err(BackendError::FollowUpFailed {
commit,
step,
detail,
}) => Ok(Landed {
write_id: commit,
warnings: vec![WarningHint::WriteFollowUpFailed {
mem: state.mount.mem.clone(),
step: step.to_string(),
detail,
}],
}),
Err(BackendError::CommitNotApplied { detail }) => {
match backend.complete_interrupted_commit() {
Ok(_) => Ok(Landed {
write_id: crate::storage::filesystem::make_commit_id(),
warnings: vec![WarningHint::WriteFollowUpFailed {
mem: state.mount.mem.clone(),
step: "commit_apply".to_string(),
detail,
}],
}),
Err(again) => Err(EngineError::CommitNotApplied {
mem: state.mount.mem.clone(),
detail: format!("{detail}; completing it at once failed as well: {again}"),
}),
}
}
Err(e) => {
let _ = backend.discard_pending();
Err(e.into())
}
}
}
pub(in crate::engine) fn after_commit<T>(
&mut self,
mount_idx: usize,
name: &'static str,
warnings: &mut Vec<WarningHint>,
step: impl FnOnce(&mut Self) -> Result<T, EngineError>,
) -> Option<T> {
self.after_commits(&[mount_idx], name, warnings, step)
}
pub(in crate::engine) fn after_commits<T>(
&mut self,
mounts: &[usize],
name: &'static str,
warnings: &mut Vec<WarningHint>,
step: impl FnOnce(&mut Self) -> Result<T, EngineError>,
) -> Option<T> {
#[cfg(test)]
let step = |engine: &mut Self| {
if test_fault::take() {
return Err(EngineError::ParseAfterWrite(
"injected follow-up failure".to_string(),
));
}
step(engine)
};
match step(self) {
Ok(value) => Some(value),
Err(e) => {
let mems: Vec<String> = mounts
.iter()
.map(|&m| self.mounts[m].mount.mem.clone())
.collect();
for mem in mems {
let mut detail = e.to_string();
if let Err(reload) = self.reload_one_mem(&mem) {
self.note_reload_failure(&mem, &reload);
detail.push_str(&format!(
"; reloading the mem from storage failed as well: {reload}"
));
}
warnings.push(WarningHint::WriteFollowUpFailed {
mem,
step: name.to_string(),
detail,
});
}
None
}
}
}
pub(in crate::engine) fn batch_commit_failed(
&mut self,
mounts: &[usize],
items: &[(usize, EntityId)],
committed: Vec<(usize, String)>,
failed_mount: usize,
cause: EngineError,
) -> EngineError {
use crate::engine::error::{PartialItem, PartialMem};
let in_storage = with_a_decided_commit(committed, failed_mount, &cause);
if in_storage.is_empty() || mounts.len() < 2 {
return cause;
}
self.level_committed_mounts(&in_storage);
let name = |mount_idx: usize| self.mounts[mount_idx].mount.mem.clone();
let mems = mounts
.iter()
.map(|&mount_idx| {
let landed = in_storage.iter().any(|(idx, _)| *idx == mount_idx);
let mut ids: Vec<&EntityId> = items
.iter()
.filter(|(idx, _)| *idx == mount_idx)
.map(|(_, id)| id)
.collect();
ids.dedup();
PartialMem {
mem: name(mount_idx),
landed,
error: (mount_idx == failed_mount).then(|| cause.to_string()),
items: ids
.into_iter()
.map(|id| PartialItem {
id: id.to_string(),
landed,
current_hash: self.hash_now(id),
})
.collect(),
}
})
.collect();
EngineError::RenamePartialFailure {
committed_mems: in_storage.iter().map(|(idx, _)| name(*idx)).collect(),
failed_mem: name(failed_mount),
failure_cause: failure_cause_of(&cause).to_string(),
mems,
}
}
pub(in crate::engine) fn hash_now(&self, id: &EntityId) -> Option<String> {
let stale = self
.mounts
.iter()
.any(|m| m.mount.mem == id.mem() && m.reload_failure.is_some());
if stale {
return None;
}
self.store
.get(id)
.filter(|e| !e.stub)
.map(|e| e.content_hash.clone())
}
pub(in crate::engine) fn level_committed_mounts(
&mut self,
commits: &[(usize, String)],
) -> Vec<WarningHint> {
let mut behind = Vec::new();
for (mount_idx, write_id) in commits {
if !write_id.is_empty() {
self.record_self_write(*mount_idx, write_id);
}
let mem = self.mounts[*mount_idx].mount.mem.clone();
let reloaded = self
.reload_one_mem(&mem)
.or_else(|_| self.reload_one_mem(&mem));
if let Err(e) = reloaded {
self.note_reload_failure(&mem, &e);
tracing::warn!(
mem = %mem,
error = %e,
"reload after a partly failed operation did not complete; \
the next operation retries"
);
behind.push(WarningHint::WriteFollowUpFailed {
mem,
step: "reload".to_string(),
detail: e.to_string(),
});
}
}
behind
}
}
pub(in crate::engine) fn with_a_decided_commit(
mut committed: Vec<(usize, String)>,
failed_mount: usize,
cause: &EngineError,
) -> Vec<(usize, String)> {
if matches!(cause, EngineError::CommitNotApplied { .. }) {
committed.push((failed_mount, String::new()));
}
committed
}
pub(in crate::engine) fn failure_cause_of(cause: &EngineError) -> &'static str {
match cause {
EngineError::Backend(BackendError::ParentMismatch { .. })
| EngineError::HashMismatch { .. }
| EngineError::NotFound { .. } => "drift",
_ => "storage",
}
}
#[cfg(test)]
pub(in crate::engine) mod test_fault {
use std::cell::Cell;
thread_local! {
static ARMED: Cell<bool> = const { Cell::new(false) };
}
pub(in crate::engine) fn arm() {
ARMED.with(|a| a.set(true));
}
pub(super) fn take() -> bool {
ARMED.with(|a| a.replace(false))
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod decided_commit_tests;