use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use self::io::{FolderIo, RealIo};
use super::CommitId;
use super::path_lock;
use crate::backend::BackendError;
use crate::backend::CompletedCommit;
use crate::backend::MemBackend;
use crate::filesystem::changelog::{
self, ChangeEntry, MutationKind, changelog_path, parse_rfc3339_utc,
};
use crate::provenance::{Provenance, ProvenanceKind};
use crate::vcs::{Actor, CommitContext, parse_client_id};
enum PendingState {
Upsert(Vec<u8>),
Delete,
}
struct Pending {
ops: HashMap<String, PendingState>,
records: Vec<Provenance>,
}
impl Pending {
fn new() -> Self {
Self {
ops: HashMap::new(),
records: Vec::new(),
}
}
fn clear(&mut self) {
self.ops.clear();
self.records.clear();
}
}
pub(crate) const COMMIT_RECORD_REL: &str = ".memstead/commit.json";
const COMMIT_PENDING_HEAD: &str = "commit-pending";
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "op", rename_all = "lowercase")]
enum RecordOp {
Upsert {
path: String,
tmp: String,
},
Delete {
path: String,
},
}
impl RecordOp {
fn path(&self) -> &str {
match self {
RecordOp::Upsert { path, .. } | RecordOp::Delete { path } => path,
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct CommitRecord {
v: u32,
ops: Vec<RecordOp>,
ledger: Vec<String>,
}
#[derive(Default)]
struct Attempt {
temps: Vec<PathBuf>,
created_dirs: Vec<PathBuf>,
}
pub struct FilesystemBackend {
root: PathBuf,
pending: Mutex<Pending>,
io: Box<dyn FolderIo>,
removal_sync_owed: Mutex<Option<Vec<String>>>,
meta_named: std::sync::atomic::AtomicBool,
}
impl FilesystemBackend {
pub fn new(root: PathBuf) -> Self {
Self {
root,
pending: Mutex::new(Pending::new()),
io: Box::new(RealIo),
removal_sync_owed: Mutex::new(None),
meta_named: std::sync::atomic::AtomicBool::new(false),
}
}
#[cfg(test)]
pub(crate) fn with_io(root: PathBuf, io: impl FolderIo + 'static) -> Self {
Self {
root,
pending: Mutex::new(Pending::new()),
io: Box::new(io),
removal_sync_owed: Mutex::new(None),
meta_named: std::sync::atomic::AtomicBool::new(false),
}
}
fn meta_dir(&self) -> PathBuf {
self.root.join(crate::mem::MEM_META_DIR)
}
fn lock_file(&self) -> PathBuf {
let root = std::fs::canonicalize(&self.root).unwrap_or_else(|_| self.root.clone());
root.join(".memstead").join("locks").join("write.lock")
}
fn config_lock_file(&self) -> PathBuf {
let root = std::fs::canonicalize(&self.root).unwrap_or_else(|_| self.root.clone());
root.join(".memstead").join("locks").join("config.lock")
}
fn record_path(&self) -> PathBuf {
self.root.join(COMMIT_RECORD_REL)
}
fn ensure_dir(&self, dir: &Path, attempt: &mut Attempt) -> std::io::Result<()> {
let mut missing: Vec<PathBuf> = Vec::new();
let mut cursor = Some(dir);
while let Some(d) = cursor {
if d.as_os_str().is_empty() || self.io.exists(d)? {
break;
}
missing.push(d.to_path_buf());
cursor = d.parent();
}
for d in missing.into_iter().rev() {
self.io.create_dir(&d)?;
attempt.created_dirs.push(d);
}
Ok(())
}
fn render_ledger(&self, records: &[Provenance]) -> std::io::Result<Vec<String>> {
if records.is_empty() {
return Ok(Vec::new());
}
let mut last = self
.io
.read_tail(&changelog_path(&self.root), 4096)?
.and_then(|tail| changelog::last_ts_in_tail(&tail));
let mut lines = Vec::with_capacity(records.len());
for record in records {
let ts = changelog::monotonic_ts(last, record.timestamp);
let line = changelog::render_change_line(&change_entry(record), ts)
.map_err(|e| std::io::Error::other(e.to_string()))?;
lines.push(line.trim_end_matches('\n').to_string());
last = Some(ts);
}
Ok(lines)
}
fn prepare_commit(
&self,
ops: &[(String, PendingState)],
records: &[Provenance],
attempt: &mut Attempt,
) -> std::io::Result<CommitRecord> {
refuse_symlinked_meta(&self.root).map_err(|e| std::io::Error::other(e.to_string()))?;
self.ensure_dir(&self.meta_dir(), attempt)?;
let mut record_ops = Vec::with_capacity(ops.len());
for (key, state) in ops {
if let Some(link) = symlink_on_path(&self.root, key)? {
return Err(std::io::Error::other(format!(
"{key} passes through the symbolic link {}; a mem writes only inside its own directory",
link.display()
)));
}
match state {
PendingState::Upsert(bytes) => {
let target = self.root.join(key);
if let Some(parent) = target.parent() {
self.ensure_dir(parent, attempt)?;
}
let tmp = make_tmp_path(&target);
attempt.temps.push(tmp.clone());
self.io.write(&tmp, bytes)?;
self.io.sync_file(&tmp)?;
record_ops.push(RecordOp::Upsert {
path: key.clone(),
tmp: sibling_key(key, &tmp),
});
}
PendingState::Delete => record_ops.push(RecordOp::Delete { path: key.clone() }),
}
}
let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
for path in attempt.temps.iter().chain(attempt.created_dirs.iter()) {
let mut dir = path.parent();
while let Some(d) = dir {
if !d.starts_with(&self.root) {
break;
}
dirs.insert(d.to_path_buf());
if d == self.root {
break;
}
dir = d.parent();
}
}
let name_meta = !self.meta_named.load(Ordering::SeqCst);
if name_meta {
dirs.insert(self.root.clone());
}
for dir in &dirs {
self.io.sync_dir(dir)?;
}
if name_meta {
self.meta_named.store(true, Ordering::SeqCst);
}
let record = CommitRecord {
v: 1,
ops: record_ops,
ledger: self.render_ledger(records)?,
};
let bytes =
serde_json::to_vec(&record).map_err(|e| std::io::Error::other(e.to_string()))?;
let record_path = self.record_path();
let record_tmp = make_tmp_path(&record_path);
attempt.temps.push(record_tmp.clone());
self.io.write(&record_tmp, &bytes)?;
self.io.sync_file(&record_tmp)?;
self.io.rename(&record_tmp, &record_path)?;
Ok(record)
}
fn abandon(&self, attempt: &Attempt) {
for tmp in &attempt.temps {
let _ = self.io.remove_file(tmp);
}
for dir in attempt.created_dirs.iter().rev() {
let _ = self.io.remove_dir(dir);
}
}
fn apply_record(&self, record: &CommitRecord) -> std::io::Result<()> {
self.io.sync_dir(&self.meta_dir())?;
let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
for op in &record.ops {
let target = self.root.join(op.path());
match op {
RecordOp::Upsert { path, tmp } => {
let tmp = self.root.join(tmp);
if self.io.exists(&tmp)? {
self.io.rename(&tmp, &target)?;
} else if !self.io.exists(&target)? {
return Err(std::io::Error::other(format!(
"commit record names {path}, and neither its staged content \
nor the file is on disk"
)));
}
}
RecordOp::Delete { .. } => match self.io.remove_file(&target) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
},
}
if let Some(parent) = target.parent() {
dirs.insert(parent.to_path_buf());
}
}
for dir in &dirs {
self.io.sync_dir(dir)?;
}
if !record.ledger.is_empty() {
let log = changelog_path(&self.root);
let span: u64 = record.ledger.iter().map(|l| l.len() as u64 + 1).sum();
let tail = self.io.read_tail(&log, span + 8192)?.unwrap_or_default();
let tail_text = String::from_utf8_lossy(&tail);
let present: HashSet<&str> = tail_text.lines().collect();
let mut out = String::new();
if !tail.is_empty() && !tail.ends_with(b"\n") {
out.push('\n');
}
let mut missing = false;
for line in &record.ledger {
if !present.contains(line.as_str()) {
out.push_str(line);
out.push('\n');
missing = true;
}
}
if missing {
self.io.append(&log, out.as_bytes())?;
}
self.io.sync_file(&log)?;
}
match self.io.remove_file(&self.record_path()) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
*self.owed() = Some(record.ops.iter().map(|op| op.path().to_string()).collect());
self.sync_record_removal().map(|_| ())
}
fn owed(&self) -> std::sync::MutexGuard<'_, Option<Vec<String>>> {
self.removal_sync_owed
.lock()
.unwrap_or_else(|e| e.into_inner())
}
fn sync_record_removal(&self) -> std::io::Result<Option<Vec<String>>> {
let mut owed = self.owed();
if owed.is_some() {
self.io.sync_dir(&self.meta_dir())?;
}
Ok(owed.take())
}
fn sweep_leftovers(&self) -> std::io::Result<()> {
let locks = self.meta_dir().join("locks");
let mut stack = vec![self.root.clone()];
while let Some(dir) = stack.pop() {
for entry in self.io.list_dir(&dir)? {
let path = dir.join(&entry.name);
if entry.is_dir {
if path != locks {
stack.push(path);
}
} else if is_temp_name(&entry.name) {
match self.io.remove_file(&path) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
}
}
}
Ok(())
}
fn ensure_whole(&self) -> Result<(), BackendError> {
if self.owed().is_some() {
return Err(BackendError::CommitNotApplied {
detail: "the removal of the last commit's record is not synced yet; \
loading the mem makes it good"
.to_string(),
});
}
let record = self.record_path();
if !self.io.exists(&record).map_err(BackendError::Io)? {
return Ok(());
}
let lock = self.lock_file();
if path_lock::holds_another(&lock) {
return Err(BackendError::CommitNotApplied {
detail: "the mem holds a commit that is in progress or was cut off, and this \
operation holds another mem's write lock, so it does not wait for it; \
loading the mem completes it"
.to_string(),
});
}
if path_lock::acquire(&lock).is_ok() {
path_lock::release(&lock);
}
if !self.io.exists(&record).map_err(BackendError::Io)? {
return Ok(());
}
Err(BackendError::CommitNotApplied {
detail: "the mem holds a commit that was cut off; loading the mem completes it"
.to_string(),
})
}
fn has_leftovers(&self) -> bool {
let locks = self.meta_dir().join("locks");
let mut stack = vec![self.root.clone()];
while let Some(dir) = stack.pop() {
let Ok(entries) = self.io.list_dir(&dir) else {
continue;
};
for entry in entries {
let path = dir.join(&entry.name);
if entry.is_dir {
if path != locks {
stack.push(path);
}
} else if is_temp_name(&entry.name) {
return true;
}
}
}
false
}
fn complete_decided_commit(&self) -> Result<Option<CompletedCommit>, BackendError> {
let record_path = self.record_path();
let Some(bytes) = self.io.read(&record_path).map_err(BackendError::Io)? else {
return Ok(None);
};
let unreadable = |why: String| {
BackendError::Other(format!(
"commit record {} cannot be read ({why}); the mem holds a decided commit \
that cannot be completed",
record_path.display()
))
};
let record: CommitRecord =
serde_json::from_slice(&bytes).map_err(|e| unreadable(e.to_string()))?;
if record.v != 1 {
return Err(unreadable(format!("unknown record version {}", record.v)));
}
for op in &record.ops {
normalise_rel_path(Path::new(op.path())).map_err(|e| unreadable(e.to_string()))?;
if let RecordOp::Upsert { tmp, .. } = op {
normalise_rel_path(Path::new(tmp)).map_err(|e| unreadable(e.to_string()))?;
}
}
self.apply_record(&record)
.map_err(|e| BackendError::CommitNotApplied {
detail: e.to_string(),
})?;
let _ = self.sweep_leftovers();
Ok(Some(CompletedCommit {
files: record.ops.iter().map(|op| op.path().to_string()).collect(),
}))
}
fn commit_staged_set(
&self,
ops: HashMap<String, PendingState>,
records: &[Provenance],
) -> Result<CommitId, BackendError> {
if self.owed().is_some() {
return Err(BackendError::Other(
"an earlier commit of this mem is applied but not yet durable; \
the mem must be loaded, which finishes it, before it is written again"
.to_string(),
));
}
match self.io.exists(&self.record_path()) {
Ok(false) => {}
Ok(true) => {
return Err(BackendError::Other(
"an earlier commit of this mem is decided and not yet applied; \
the mem must be loaded, which completes it, before it is written again"
.to_string(),
));
}
Err(e) => return Err(BackendError::Io(e)),
}
let mut ops: Vec<(String, PendingState)> = ops.into_iter().collect();
ops.sort_by(|a, b| a.0.cmp(&b.0));
let mut attempt = Attempt::default();
let record = match self.prepare_commit(&ops, records, &mut attempt) {
Ok(record) => record,
Err(e) => {
self.abandon(&attempt);
return Err(BackendError::Io(e));
}
};
let not_applied = |e: std::io::Error| BackendError::CommitNotApplied {
detail: e.to_string(),
};
self.apply_record(&record).map_err(not_applied)?;
Ok(make_commit_id())
}
fn read_source(
&self,
pending: &Pending,
rel_key: &str,
) -> Result<Option<Vec<u8>>, BackendError> {
if let Some(PendingState::Upsert(bytes)) = pending.ops.get(rel_key) {
return Ok(Some(bytes.clone()));
}
if let Some(PendingState::Delete) = pending.ops.get(rel_key) {
return Ok(None);
}
let full = self.root.join(rel_key);
match std::fs::read(&full) {
Ok(bytes) => Ok(Some(bytes)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(BackendError::Io(e)),
}
}
}
pub(crate) fn refuse_cut_off_commit(root: &Path) -> Result<(), BackendError> {
FilesystemBackend::new(root.to_path_buf()).ensure_whole()
}
pub fn normalise_rel_path(rel_path: &Path) -> Result<String, BackendError> {
if rel_path.as_os_str().is_empty() {
return Err(BackendError::Path("mem-relative path is empty".to_string()));
}
let mut parts: Vec<String> = Vec::new();
for component in rel_path.components() {
use std::path::Component;
match component {
Component::Normal(s) => match s.to_str() {
Some(p) if !p.is_empty() => parts.push(p.to_string()),
_ => {
return Err(BackendError::Path(format!(
"non-utf-8 or empty path component in {}",
rel_path.display()
)));
}
},
Component::CurDir => continue,
Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
return Err(BackendError::Path(format!(
"path traversal or absolute component in {}",
rel_path.display()
)));
}
}
}
if parts.is_empty() {
return Err(BackendError::Path(
"mem-relative path is empty after normalisation".to_string(),
));
}
Ok(parts.join("/"))
}
impl crate::backend::MemBackend for FilesystemBackend {
fn list_entities(&self) -> Result<Vec<PathBuf>, BackendError> {
self.ensure_whole()?;
let mut out = Vec::new();
if !self.root.exists() {
return Ok(out);
}
walk_for_md(&self.root, &self.root, &mut out)?;
Ok(out)
}
fn current_head(&self) -> Result<Option<String>, BackendError> {
if std::fs::symlink_metadata(self.record_path()).is_ok() || self.owed().is_some() {
return Ok(Some(COMMIT_PENDING_HEAD.to_string()));
}
let log_path = crate::filesystem::changelog::changelog_path(&self.root);
let raw = match std::fs::read_to_string(&log_path) {
Ok(s) => s,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => {
return Err(BackendError::Other(format!(
"reading folder changelog {}: {e}",
log_path.display()
)));
}
};
let last_ts = raw
.lines()
.rev()
.filter_map(|line| {
let trimmed = line.trim();
if trimmed.is_empty() {
return None;
}
serde_json::from_str::<serde_json::Value>(trimmed)
.ok()?
.get("ts")?
.as_str()
.map(str::to_string)
})
.next();
Ok(last_ts)
}
fn write_lock_path(&self) -> Option<PathBuf> {
Some(self.lock_file())
}
fn read_entity(&self, rel_path: &Path) -> Result<Option<Vec<u8>>, BackendError> {
let key = normalise_rel_path(rel_path)?;
let pending = self.pending.lock().map_err(|_| {
BackendError::Other("filesystem writer pending state poisoned".to_string())
})?;
if let Some(state) = pending.ops.get(&key) {
return Ok(match state {
PendingState::Upsert(bytes) => Some(bytes.clone()),
PendingState::Delete => None,
});
}
drop(pending);
self.ensure_whole()?;
let full = self.root.join(&key);
match std::fs::read(&full) {
Ok(bytes) => Ok(Some(bytes)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(BackendError::Io(e)),
}
}
fn storage_present(&self) -> Result<bool, BackendError> {
Ok(self.root.is_dir())
}
fn entity_exists(&self, rel_path: &Path) -> Result<bool, BackendError> {
let key = normalise_rel_path(rel_path)?;
let pending = self.pending.lock().map_err(|_| {
BackendError::Other("filesystem writer pending state poisoned".to_string())
})?;
if let Some(state) = pending.ops.get(&key) {
return Ok(matches!(state, PendingState::Upsert(_)));
}
drop(pending);
self.ensure_whole()?;
match std::fs::symlink_metadata(self.root.join(&key)) {
Ok(md) => Ok(md.is_file()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(BackendError::Io(e)),
}
}
fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError> {
let key = normalise_rel_path(rel_path)?;
refuse_unwritable(&self.root, &key)?;
let mut pending = self.pending.lock().map_err(|_| {
BackendError::Path("filesystem writer pending state poisoned".to_string())
})?;
pending
.ops
.insert(key, PendingState::Upsert(content.to_vec()));
Ok(())
}
fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError> {
let key = normalise_rel_path(rel_path)?;
refuse_unwritable(&self.root, &key)?;
let mut pending = self.pending.lock().map_err(|_| {
BackendError::Path("filesystem writer pending state poisoned".to_string())
})?;
pending.ops.insert(key, PendingState::Delete);
Ok(())
}
fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError> {
let from_key = normalise_rel_path(from)?;
let to_key = normalise_rel_path(to)?;
refuse_unwritable(&self.root, &from_key)?;
refuse_unwritable(&self.root, &to_key)?;
let mut pending = self.pending.lock().map_err(|_| {
BackendError::Path("filesystem writer pending state poisoned".to_string())
})?;
match pending.ops.get(&to_key) {
Some(PendingState::Upsert(_)) => {
return Err(BackendError::Path(format!(
"move target {} already has a pending write",
to.display()
)));
}
Some(PendingState::Delete) => {}
None => {
if self.read_source(&pending, &to_key)?.is_some() {
return Err(BackendError::Path(format!(
"move target {} already exists",
to.display()
)));
}
}
}
let bytes = match pending.ops.remove(&from_key) {
Some(PendingState::Upsert(b)) => b,
Some(PendingState::Delete) => {
pending.ops.insert(from_key, PendingState::Delete);
return Err(BackendError::Path(format!(
"move source {} is already pending deletion",
from.display()
)));
}
None => match self.read_source(&pending, &from_key)? {
Some(b) => b,
None => {
return Err(BackendError::Path(format!(
"move source {} does not exist",
from.display()
)));
}
},
};
pending.ops.insert(from_key, PendingState::Delete);
pending.ops.insert(to_key, PendingState::Upsert(bytes));
Ok(())
}
fn discard_pending(&self) -> Result<(), BackendError> {
let mut pending = self.pending.lock().map_err(|_| {
BackendError::Other("filesystem writer pending state poisoned".to_string())
})?;
pending.clear();
Ok(())
}
fn commit(&self, _message: &str, _ctx: &CommitContext<'_>) -> Result<CommitId, BackendError> {
let mut pending = self.pending.lock().map_err(|_| {
BackendError::Path("filesystem writer pending state poisoned".to_string())
})?;
let staged = std::mem::replace(&mut *pending, Pending::new());
if staged.ops.is_empty() && staged.records.is_empty() {
return Ok(make_commit_id());
}
self.commit_staged_set(staged.ops, &staged.records)
}
fn complete_interrupted_commit(&self) -> Result<Option<CompletedCommit>, BackendError> {
if let Some(files) =
self.sync_record_removal()
.map_err(|e| BackendError::CommitNotApplied {
detail: e.to_string(),
})?
{
return Ok(Some(CompletedCommit { files }));
}
let lock = self.lock_file();
if self
.io
.exists(&self.record_path())
.map_err(BackendError::Io)?
{
if path_lock::holds_another(&lock) {
return match path_lock::try_acquire(&lock) {
Ok(true) => {
let result = self.complete_decided_commit();
path_lock::release(&lock);
result
}
_ => Err(BackendError::CommitNotApplied {
detail: "the mem holds a commit in progress and another writer holds \
its lock; loading the mem completes it once the lock is free"
.to_string(),
}),
};
}
let locked = path_lock::acquire(&lock).is_ok();
let result = self.complete_decided_commit();
if locked {
path_lock::release(&lock);
}
return result;
}
if self.has_leftovers() && matches!(path_lock::try_acquire(&lock), Ok(true)) {
let result = if self
.io
.exists(&self.record_path())
.map_err(BackendError::Io)?
{
self.complete_decided_commit()
} else {
let _ = self.sweep_leftovers();
Ok(None)
};
path_lock::release(&lock);
return result;
}
Ok(None)
}
fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
let config_path = self.root.join(crate::mem::MEM_META_DIR).join("config.json");
match std::fs::read(&config_path) {
Ok(bytes) => Ok(Some(bytes)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(BackendError::Io(e)),
}
}
fn write_mem_config(
&self,
bytes: &[u8],
_ctx: &crate::vcs::CommitContext<'_>,
) -> Result<(), BackendError> {
let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
refuse_symlinked_meta(&self.root)?;
let _lock = ConfigLock::take(self.config_lock_file())?;
replace_file(&memstead_dir.join("config.json"), bytes)
}
fn write_mem_config_cas(
&self,
expected: Option<&[u8]>,
bytes: &[u8],
_ctx: &crate::vcs::CommitContext<'_>,
) -> Result<bool, BackendError> {
let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
let config_path = memstead_dir.join("config.json");
refuse_symlinked_meta(&self.root)?;
let _lock = ConfigLock::take(self.config_lock_file())?;
let current = match std::fs::read(&config_path) {
Ok(b) => Some(b),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(BackendError::Io(e)),
};
if let Some(expected) = expected
&& current.as_deref() != Some(expected)
{
return Ok(false);
}
replace_file(&config_path, bytes).map(|_| true)
}
fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
}
fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
<Self as MemBackend>::write_entity(
self,
Path::new(crate::anchor::ANCHOR_SIDECAR_PATH),
bytes,
)
}
fn stage_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
let mut pending = self.pending.lock().map_err(|_| {
BackendError::Other("filesystem writer pending state poisoned".to_string())
})?;
pending.records.push(record.clone());
Ok(())
}
fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
self.commit_staged_set(HashMap::new(), std::slice::from_ref(record))
.map(|_| ())
}
fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError> {
self.ensure_whole()?;
let log_path = changelog_path(&self.root);
let raw = match std::fs::read_to_string(&log_path) {
Ok(s) => s,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(BackendError::Io(e)),
};
let mut out = Vec::new();
for line in raw.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let value: serde_json::Value = match serde_json::from_str(trimmed) {
Ok(v) => v,
Err(_) => continue,
};
let ts_str = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
if let Some(c) = cursor
&& ts_str <= c
{
continue;
}
let timestamp = parse_rfc3339_utc(ts_str).unwrap_or(std::time::UNIX_EPOCH);
let kind = value
.get("kind")
.and_then(|v| v.as_str())
.and_then(ProvenanceKind::parse)
.unwrap_or(ProvenanceKind::Update);
let entity = value
.get("entity")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let actor = value
.get("actor")
.and_then(|v| v.as_str())
.and_then(Actor::from_trailer)
.unwrap_or(Actor::Unknown);
let client = value
.get("client")
.and_then(|v| v.as_str())
.and_then(parse_client_id);
let note = value
.get("note")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let logical_operation_id = value
.get("logical_op")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let mut record = Provenance::new(timestamp, kind, entity, actor, client, note);
if let Some(id) = logical_operation_id {
record = record.with_logical_operation_id(id);
}
if let Some(from) = value.get("renamed_from").and_then(|v| v.as_str()) {
record = record.with_renamed_from(from.to_string());
}
if let Some(role) = value
.get("role")
.and_then(|v| v.as_str())
.and_then(crate::vcs::Role::from_wire)
{
record = record.with_role(role);
}
record = record.with_identity(
value
.get("identity")
.and_then(|v| v.as_str())
.map(|s| s.to_string()),
);
out.push(record);
}
Ok(out)
}
}
fn walk_for_md(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), BackendError> {
let entries = match std::fs::read_dir(dir) {
Ok(e) => e,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(BackendError::Io(e)),
};
for entry in entries {
let entry = entry.map_err(BackendError::Io)?;
let path = entry.path();
let file_type = entry.file_type().map_err(BackendError::Io)?;
if file_type.is_dir() {
let name = entry.file_name();
if name == crate::mem::MEM_META_DIR {
continue;
}
if crate::mem::is_nested_mem_root(&path) {
continue;
}
walk_for_md(root, &path, out)?;
} else if file_type.is_file()
&& crate::filesystem::changelog::is_entity_file(&path)
&& let Ok(rel) = path.strip_prefix(root)
{
out.push(rel.to_path_buf());
}
}
Ok(())
}
fn change_entry(record: &Provenance) -> ChangeEntry<'_> {
let kind: MutationKind = record.kind.into();
ChangeEntry {
kind,
entity: record.entity.as_deref(),
actor: record.actor,
client: record.client.as_ref(),
note: record.note.as_deref(),
logical_operation_id: record.logical_operation_id.as_deref(),
role: record.role,
identity: record.identity.as_deref(),
renamed_from: record.renamed_from.as_deref(),
}
}
fn sibling_key(key: &str, tmp: &Path) -> String {
let name = tmp
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
match key.rsplit_once('/') {
Some((dir, _)) => format!("{dir}/{name}"),
None => name,
}
}
fn is_temp_name(name: &str) -> bool {
let Some(rest) = name.strip_prefix('.') else {
return false;
};
let Some((target, suffix)) = rest.rsplit_once(".tmp.") else {
return false;
};
let Some((nanos, counter)) = suffix.split_once('-') else {
return false;
};
let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit());
!target.is_empty() && hex(nanos) && hex(counter)
}
fn make_tmp_path(target: &Path) -> PathBuf {
let name = target
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| "_".to_string());
let suffix = unique_suffix();
let tmp_name = format!(".{name}.tmp.{suffix}");
target.with_file_name(tmp_name)
}
static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
static COMMIT_COUNTER: AtomicU64 = AtomicU64::new(0);
fn unique_suffix() -> String {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let counter = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
format!("{nanos:x}-{counter:x}")
}
pub(crate) fn make_commit_id() -> CommitId {
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let counter = COMMIT_COUNTER.fetch_add(1, Ordering::Relaxed);
format!("{nanos:032x}{counter:016x}")
}
#[cfg(test)]
mod commit_point_tests;
#[cfg(test)]
pub(crate) mod fault_io;
#[cfg(test)]
mod folder_drift_tests;
pub(crate) mod io;
#[cfg(test)]
mod tests;
fn replace_file(path: &Path, bytes: &[u8]) -> Result<(), BackendError> {
use std::io::Write as _;
let dir = path
.parent()
.ok_or_else(|| BackendError::Path(format!("{} has no parent", path.display())))?;
let name = path
.file_name()
.ok_or_else(|| BackendError::Path(format!("{} has no file name", path.display())))?;
let mut tmp_name = name.to_os_string();
tmp_name.push(format!(".tmp-{}", lock_token()));
let tmp = dir.join(tmp_name);
let written = (|| -> std::io::Result<()> {
let mut f = std::fs::File::create(&tmp)?;
f.write_all(bytes)?;
f.sync_all()?;
std::fs::rename(&tmp, path)?;
RealIo.sync_dir(dir)
})();
if written.is_err() {
let _ = std::fs::remove_file(&tmp);
}
written.map_err(BackendError::Io)
}
fn lock_token() -> String {
use std::sync::atomic::{AtomicU64, Ordering};
static SEQ: AtomicU64 = AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
format!(
"{}-{}-{}",
std::process::id(),
nanos,
SEQ.fetch_add(1, Ordering::Relaxed)
)
}
fn symlink_on_path(root: &Path, key: &str) -> std::io::Result<Option<PathBuf>> {
let mut at = root.to_path_buf();
for part in Path::new(key).components() {
at.push(part);
match std::fs::symlink_metadata(&at) {
Ok(md) if md.file_type().is_symlink() => return Ok(Some(at)),
Ok(md) if !md.is_dir() => return Ok(None),
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
}
}
Ok(None)
}
fn refuse_symlinked(root: &Path, key: &str) -> Result<(), BackendError> {
match symlink_on_path(root, key).map_err(BackendError::Io)? {
Some(link) => Err(BackendError::Path(format!(
"{key} passes through the symbolic link {}; a mem writes only inside its own directory",
link.display()
))),
None => Ok(()),
}
}
struct ConfigLock(PathBuf);
impl ConfigLock {
fn take(path: PathBuf) -> Result<Self, BackendError> {
path_lock::acquire(&path).map_err(BackendError::Io)?;
Ok(Self(path))
}
}
impl Drop for ConfigLock {
fn drop(&mut self) {
path_lock::release(&self.0);
}
}
const WRITABLE_META_PATHS: &[&str] = &[
crate::anchor::ANCHOR_SIDECAR_PATH,
crate::derivation::DERIVATION_SIDECAR_PATH,
crate::ops::proposal::PROPOSAL_RECORD_PATH,
];
fn refuse_unwritable(root: &Path, key: &str) -> Result<(), BackendError> {
let meta = format!("{}/", crate::mem::MEM_META_DIR);
if key.starts_with(&meta) && !WRITABLE_META_PATHS.contains(&key) {
return Err(BackendError::Path(format!(
"{key} is the backend's own file; only {} are written through entity paths",
WRITABLE_META_PATHS.join(", ")
)));
}
refuse_symlinked(root, key)
}
fn refuse_symlinked_meta(root: &Path) -> Result<(), BackendError> {
refuse_symlinked(root, crate::mem::MEM_META_DIR)
}