Skip to main content

memstead_base/storage/
filesystem.rs

1//! Filesystem-backed [`MemBackend`](crate::backend::MemBackend) — the
2//! gix-free companion to `memstead_git_branch::storage::git_tree::GitTreeBackend`.
3//! Used by filesystem mems, where entities live as plain files under a
4//! workspace root and there is no commit history.
5//!
6//! ## Buffer + commit
7//!
8//! Mutations buffer in memory until [`FilesystemBackend::commit`].
9//! Per-path final-state collapse mirrors the git-tree adapter: a chain
10//! of write/delete ops on the same path collapses to a single terminal
11//! state by commit time. Move resolves at call-time into a
12//! `Delete(from)` + `Upsert(to, bytes)` pair — bytes come from the
13//! pending buffer when present, otherwise from the live file on disk.
14//!
15//! ## One commit point
16//!
17//! A commit is all of its files and its ledger lines, or none of them.
18//! It runs in two halves around one commit point:
19//!
20//! 1. **Before.** Every new file content is written to a temp file
21//!    beside its target and synced, the directories that name the
22//!    temps are synced, and the ledger lines of the staged provenance
23//!    records are rendered. Then a commit record naming every file
24//!    operation and every ledger line is written under `.memstead/`
25//!    (temp, sync, rename). The rename that puts the record in place
26//!    is the commit point; syncing `.memstead/` makes it durable.
27//! 2. **After.** The temps are renamed into place, the deletes are
28//!    applied, the touched directories are synced, the ledger lines
29//!    are appended and synced, the record is removed and `.memstead/`
30//!    is synced. Only then does the commit return success.
31//!
32//! A failure before the commit point removes what the attempt wrote
33//! and returns the IO error: storage is what it was. A failure after
34//! it returns [`BackendError::CommitNotApplied`]: the commit is decided,
35//! and [`MemBackend::complete_interrupted_commit`] finishes it from the
36//! record at the next load. The same call removes the temps of an
37//! attempt that died before its commit point. Nothing has to be undone
38//! in either case, because nothing is moved into place before every
39//! content is safely beside its target.
40//!
41//! All of it runs through the [`io::FolderIo`] seam, so tests record
42//! the order of the steps and fail or cut off any one of them.
43//!
44//! Writers are serialised by the engine's cross-process write lock
45//! ([`MemBackend::write_lock_path`]); the backend itself assumes one
46//! writer at a time.
47//!
48//! ## CommitId
49//!
50//! There is no commit history. [`Self::commit`] returns a synthetic
51//! opaque id (UNIX-nanos + counter, hex) to satisfy the trait surface.
52//! Callers that pass this through `_hash` envelopes get a unique
53//! per-commit token but no CAS guarantee — there is no parent state to
54//! compare against.
55
56use std::collections::{BTreeSet, HashMap, HashSet};
57use std::path::{Path, PathBuf};
58use std::sync::Mutex;
59use std::sync::atomic::{AtomicU64, Ordering};
60
61use self::io::{FolderIo, RealIo};
62use super::CommitId;
63use super::path_lock;
64use crate::backend::BackendError;
65use crate::backend::CompletedCommit;
66use crate::backend::MemBackend;
67use crate::filesystem::changelog::{
68    self, ChangeEntry, MutationKind, changelog_path, parse_rfc3339_utc,
69};
70use crate::provenance::{Provenance, ProvenanceKind};
71use crate::vcs::{Actor, CommitContext, parse_client_id};
72
73/// Per-path final state for the buffered op log. Move operations
74/// resolve at call time into a `Delete(from)` + `Upsert(to, bytes)`
75/// pair, mirroring the git-tree adapter so commit-time replay only
76/// ever sees these two terminal states.
77enum PendingState {
78    Upsert(Vec<u8>),
79    Delete,
80}
81
82/// In-flight mutation buffer: the staged file operations and the
83/// provenance records that belong to the same commit. Emptied by every
84/// exit of a commit, successful or not, and by a discard.
85struct Pending {
86    ops: HashMap<String, PendingState>,
87    records: Vec<Provenance>,
88}
89
90impl Pending {
91    fn new() -> Self {
92        Self {
93            ops: HashMap::new(),
94            records: Vec::new(),
95        }
96    }
97
98    fn clear(&mut self) {
99        self.ops.clear();
100        self.records.clear();
101    }
102}
103
104/// Mem-relative path of the commit record: present from a commit's
105/// commit point until the commit is fully applied, absent otherwise.
106pub(crate) const COMMIT_RECORD_REL: &str = ".memstead/commit.json";
107
108/// The drift cursor a mem reports while a commit record is on disk.
109/// No ledger timestamp ever equals it, so the engine's staleness probe
110/// sees a change and reloads, and the reload completes the commit.
111const COMMIT_PENDING_HEAD: &str = "commit-pending";
112
113/// One file operation of a commit, as its record names it. Paths are
114/// mem-relative with forward slashes.
115#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
116#[serde(tag = "op", rename_all = "lowercase")]
117enum RecordOp {
118    /// `tmp` holds the synced new content and is renamed onto `path`.
119    Upsert {
120        path: String,
121        tmp: String,
122    },
123    Delete {
124        path: String,
125    },
126}
127
128impl RecordOp {
129    fn path(&self) -> &str {
130        match self {
131            RecordOp::Upsert { path, .. } | RecordOp::Delete { path } => path,
132        }
133    }
134}
135
136/// The commit record: everything needed to finish a decided commit
137/// without the process that decided it.
138#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
139struct CommitRecord {
140    v: u32,
141    /// File operations, in path order.
142    ops: Vec<RecordOp>,
143    /// The commit's ledger lines, in order, without their newline.
144    ledger: Vec<String>,
145}
146
147/// What one commit attempt has put on disk before its commit point,
148/// so a failed attempt can take all of it away again.
149#[derive(Default)]
150struct Attempt {
151    /// Temp files written, the record's temp included.
152    temps: Vec<PathBuf>,
153    /// Directories created, outermost first.
154    created_dirs: Vec<PathBuf>,
155}
156
157/// Filesystem-backed [`MemBackend`]. Mutations buffer in memory until
158/// [`Self::commit`], which lands them as one commit (module docs).
159pub struct FilesystemBackend {
160    root: PathBuf,
161    pending: Mutex<Pending>,
162    io: Box<dyn FolderIo>,
163    /// Set while the record of an applied commit is removed and the
164    /// sync of that removal has not succeeded: the files of that
165    /// commit. The commit has not returned success, and must not until
166    /// the sync is made good: a removal that is not durable lets a
167    /// power loss bring the record back after later writes. Reads
168    /// refuse meanwhile, as they do while a record is on disk.
169    removal_sync_owed: Mutex<Option<Vec<String>>>,
170    /// This backend has synced the mem root since it was built, so the
171    /// name of `.memstead/` is durable.
172    meta_named: std::sync::atomic::AtomicBool,
173}
174
175impl FilesystemBackend {
176    /// Build a writer rooted at `root`. The directory must already
177    /// exist; sub-directories are created lazily as commits run.
178    pub fn new(root: PathBuf) -> Self {
179        Self {
180            root,
181            pending: Mutex::new(Pending::new()),
182            io: Box::new(RealIo),
183            removal_sync_owed: Mutex::new(None),
184            meta_named: std::sync::atomic::AtomicBool::new(false),
185        }
186    }
187
188    /// [`Self::new`] over a caller-supplied IO, for tests that trace
189    /// or fault the steps of a commit.
190    #[cfg(test)]
191    pub(crate) fn with_io(root: PathBuf, io: impl FolderIo + 'static) -> Self {
192        Self {
193            root,
194            pending: Mutex::new(Pending::new()),
195            io: Box::new(io),
196            removal_sync_owed: Mutex::new(None),
197            meta_named: std::sync::atomic::AtomicBool::new(false),
198        }
199    }
200
201    fn meta_dir(&self) -> PathBuf {
202        self.root.join(crate::mem::MEM_META_DIR)
203    }
204
205    /// The write lock's file, by its canonical path: the engine's lock
206    /// and this backend's own recovery take the same lock, and the lock
207    /// table is keyed by path.
208    fn lock_file(&self) -> PathBuf {
209        let root = std::fs::canonicalize(&self.root).unwrap_or_else(|_| self.root.clone());
210        root.join(".memstead").join("locks").join("write.lock")
211    }
212
213    /// The config lock's file, by its canonical path, beside the write lock.
214    fn config_lock_file(&self) -> PathBuf {
215        let root = std::fs::canonicalize(&self.root).unwrap_or_else(|_| self.root.clone());
216        root.join(".memstead").join("locks").join("config.lock")
217    }
218
219    fn record_path(&self) -> PathBuf {
220        self.root.join(COMMIT_RECORD_REL)
221    }
222
223    /// Create `dir` and every missing directory above it, noting each
224    /// one created so a failed attempt can remove it again.
225    fn ensure_dir(&self, dir: &Path, attempt: &mut Attempt) -> std::io::Result<()> {
226        let mut missing: Vec<PathBuf> = Vec::new();
227        let mut cursor = Some(dir);
228        while let Some(d) = cursor {
229            if d.as_os_str().is_empty() || self.io.exists(d)? {
230                break;
231            }
232            missing.push(d.to_path_buf());
233            cursor = d.parent();
234        }
235        for d in missing.into_iter().rev() {
236            self.io.create_dir(&d)?;
237            attempt.created_dirs.push(d);
238        }
239        Ok(())
240    }
241
242    /// Render the ledger lines of `records`, each with a timestamp
243    /// strictly after the ledger's last line and after the line before
244    /// it: the last line's `ts` is the drift cursor, and two lines that
245    /// shared one would hide the second from every reader.
246    fn render_ledger(&self, records: &[Provenance]) -> std::io::Result<Vec<String>> {
247        if records.is_empty() {
248            return Ok(Vec::new());
249        }
250        let mut last = self
251            .io
252            .read_tail(&changelog_path(&self.root), 4096)?
253            .and_then(|tail| changelog::last_ts_in_tail(&tail));
254        let mut lines = Vec::with_capacity(records.len());
255        for record in records {
256            let ts = changelog::monotonic_ts(last, record.timestamp);
257            let line = changelog::render_change_line(&change_entry(record), ts)
258                .map_err(|e| std::io::Error::other(e.to_string()))?;
259            lines.push(line.trim_end_matches('\n').to_string());
260            last = Some(ts);
261        }
262        Ok(lines)
263    }
264
265    /// Everything before the commit point: contents beside their
266    /// targets and synced, then the record in place. Returns the
267    /// record once its rename has happened; an error means the rename
268    /// has not, and `attempt` lists what to remove.
269    fn prepare_commit(
270        &self,
271        ops: &[(String, PendingState)],
272        records: &[Provenance],
273        attempt: &mut Attempt,
274    ) -> std::io::Result<CommitRecord> {
275        // The record and the ledger live under `.memstead/`; a link there
276        // would carry them outside the mem.
277        refuse_symlinked_meta(&self.root).map_err(|e| std::io::Error::other(e.to_string()))?;
278        self.ensure_dir(&self.meta_dir(), attempt)?;
279
280        let mut record_ops = Vec::with_capacity(ops.len());
281        for (key, state) in ops {
282            // Checked again at commit: a link can appear after staging.
283            if let Some(link) = symlink_on_path(&self.root, key)? {
284                return Err(std::io::Error::other(format!(
285                    "{key} passes through the symbolic link {}; a mem writes only inside its own directory",
286                    link.display()
287                )));
288            }
289            match state {
290                PendingState::Upsert(bytes) => {
291                    let target = self.root.join(key);
292                    if let Some(parent) = target.parent() {
293                        self.ensure_dir(parent, attempt)?;
294                    }
295                    let tmp = make_tmp_path(&target);
296                    attempt.temps.push(tmp.clone());
297                    self.io.write(&tmp, bytes)?;
298                    self.io.sync_file(&tmp)?;
299                    record_ops.push(RecordOp::Upsert {
300                        path: key.clone(),
301                        tmp: sibling_key(key, &tmp),
302                    });
303                }
304                PendingState::Delete => record_ops.push(RecordOp::Delete { path: key.clone() }),
305            }
306        }
307
308        // The names must be as durable as the contents: a record that
309        // survives a power loss while a temp's directory entry does not
310        // would name a content that is gone.
311        let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
312        for path in attempt.temps.iter().chain(attempt.created_dirs.iter()) {
313            // Every directory from the file's own up to the mem root,
314            // not only the ones this attempt created: a directory left
315            // behind by an earlier attempt that was cut off exists
316            // already and was never named durably.
317            let mut dir = path.parent();
318            while let Some(d) = dir {
319                if !d.starts_with(&self.root) {
320                    break;
321                }
322                dirs.insert(d.to_path_buf());
323                if d == self.root {
324                    break;
325                }
326                dir = d.parent();
327            }
328        }
329        // `.memstead/` itself must be named durably before a record is
330        // put in it. This backend cannot know who created the directory
331        // (the write lock makes it for its lock file, outside any
332        // commit), so the first commit of each backend syncs the mem
333        // root once, whatever it found.
334        let name_meta = !self.meta_named.load(Ordering::SeqCst);
335        if name_meta {
336            dirs.insert(self.root.clone());
337        }
338        for dir in &dirs {
339            self.io.sync_dir(dir)?;
340        }
341        if name_meta {
342            self.meta_named.store(true, Ordering::SeqCst);
343        }
344
345        let record = CommitRecord {
346            v: 1,
347            ops: record_ops,
348            ledger: self.render_ledger(records)?,
349        };
350        let bytes =
351            serde_json::to_vec(&record).map_err(|e| std::io::Error::other(e.to_string()))?;
352        let record_path = self.record_path();
353        let record_tmp = make_tmp_path(&record_path);
354        attempt.temps.push(record_tmp.clone());
355        self.io.write(&record_tmp, &bytes)?;
356        self.io.sync_file(&record_tmp)?;
357        self.io.rename(&record_tmp, &record_path)?;
358        Ok(record)
359    }
360
361    /// Take away what an attempt that never reached its commit point
362    /// put on disk. Best effort: a temp that stays is removed by the
363    /// next load, and an empty directory that stays changes nothing.
364    fn abandon(&self, attempt: &Attempt) {
365        for tmp in &attempt.temps {
366            let _ = self.io.remove_file(tmp);
367        }
368        for dir in attempt.created_dirs.iter().rev() {
369            let _ = self.io.remove_dir(dir);
370        }
371    }
372
373    /// Everything after the commit point, written so that running it
374    /// again from any cut-off point ends in the same state: a temp
375    /// still present is renamed, a temp already gone means its file is
376    /// in place, a ledger line already written is not written twice.
377    /// Shared by the commit itself and by the completion at load.
378    fn apply_record(&self, record: &CommitRecord) -> std::io::Result<()> {
379        // The record's own name first, on every run: it is what makes
380        // the commit point durable, and a completion cannot know
381        // whether the run it finishes got this far. Without it a power
382        // loss could bring back the record of an older commit, whose
383        // deletes would then be applied over this one's files.
384        self.io.sync_dir(&self.meta_dir())?;
385
386        let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
387        for op in &record.ops {
388            let target = self.root.join(op.path());
389            match op {
390                RecordOp::Upsert { path, tmp } => {
391                    let tmp = self.root.join(tmp);
392                    if self.io.exists(&tmp)? {
393                        self.io.rename(&tmp, &target)?;
394                    } else if !self.io.exists(&target)? {
395                        return Err(std::io::Error::other(format!(
396                            "commit record names {path}, and neither its staged content \
397                             nor the file is on disk"
398                        )));
399                    }
400                }
401                RecordOp::Delete { .. } => match self.io.remove_file(&target) {
402                    Ok(()) => {}
403                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
404                    Err(e) => return Err(e),
405                },
406            }
407            // Every operation's directory is synced on every run, also
408            // where this run found the move already made: an earlier
409            // run may have been cut off between the move and its sync,
410            // and this one cannot tell.
411            if let Some(parent) = target.parent() {
412                dirs.insert(parent.to_path_buf());
413            }
414        }
415        for dir in &dirs {
416            self.io.sync_dir(dir)?;
417        }
418
419        if !record.ledger.is_empty() {
420            let log = changelog_path(&self.root);
421            // The commit's lines, if any are there, are the last thing
422            // in the ledger, so a tail that can hold all of them is
423            // enough to see which are missing.
424            let span: u64 = record.ledger.iter().map(|l| l.len() as u64 + 1).sum();
425            let tail = self.io.read_tail(&log, span + 8192)?.unwrap_or_default();
426            let tail_text = String::from_utf8_lossy(&tail);
427            let present: HashSet<&str> = tail_text.lines().collect();
428            let mut out = String::new();
429            // A cut-off append leaves a line without its newline. Close
430            // it, so it stays one unparseable line (which every reader
431            // skips) and cannot swallow the line written after it.
432            if !tail.is_empty() && !tail.ends_with(b"\n") {
433                out.push('\n');
434            }
435            let mut missing = false;
436            for line in &record.ledger {
437                if !present.contains(line.as_str()) {
438                    out.push_str(line);
439                    out.push('\n');
440                    missing = true;
441                }
442            }
443            if missing {
444                self.io.append(&log, out.as_bytes())?;
445            }
446            self.io.sync_file(&log)?;
447        }
448
449        match self.io.remove_file(&self.record_path()) {
450            Ok(()) => {}
451            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
452            Err(e) => return Err(e),
453        }
454        // The removal is synced like everything else. A record that a
455        // power loss brought back would be applied again by the next
456        // load, and its deletes would then hit whatever was written to
457        // those paths since. The same sync names a ledger file this
458        // commit created, which lives in the same directory.
459        *self.owed() = Some(record.ops.iter().map(|op| op.path().to_string()).collect());
460        self.sync_record_removal().map(|_| ())
461    }
462
463    fn owed(&self) -> std::sync::MutexGuard<'_, Option<Vec<String>>> {
464        self.removal_sync_owed
465            .lock()
466            .unwrap_or_else(|e| e.into_inner())
467    }
468
469    /// Sync the removal of the commit record, if that sync is still
470    /// owed, and return the files of the commit it belonged to. The
471    /// record is gone by then, so nothing on disk says the sync is
472    /// missing; the backend remembers it until it succeeds.
473    fn sync_record_removal(&self) -> std::io::Result<Option<Vec<String>>> {
474        let mut owed = self.owed();
475        if owed.is_some() {
476            self.io.sync_dir(&self.meta_dir())?;
477        }
478        Ok(owed.take())
479    }
480
481    /// Remove the temp files of attempts that never reached their
482    /// commit point. Walks where entities and the sidecars live; the
483    /// lock directory is another process's business.
484    fn sweep_leftovers(&self) -> std::io::Result<()> {
485        let locks = self.meta_dir().join("locks");
486        let mut stack = vec![self.root.clone()];
487        while let Some(dir) = stack.pop() {
488            for entry in self.io.list_dir(&dir)? {
489                let path = dir.join(&entry.name);
490                if entry.is_dir {
491                    if path != locks {
492                        stack.push(path);
493                    }
494                } else if is_temp_name(&entry.name) {
495                    match self.io.remove_file(&path) {
496                        Ok(()) => {}
497                        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
498                        Err(e) => return Err(e),
499                    }
500                }
501            }
502        }
503        Ok(())
504    }
505
506    /// Refuse to read storage that holds part of a commit. Every read
507    /// of files a commit can move (entities, the sidecars, the ledger)
508    /// starts here. While a commit record is on disk the commit is
509    /// decided and possibly half applied: a live writer is given the
510    /// time to finish it (the read waits for the mem's write lock), and
511    /// a record that is still there afterwards belongs to a commit that
512    /// was cut off, so the read returns that condition instead of
513    /// bytes. Completing it is left to a load, the one place that
514    /// reports what it completed. This is what keeps a cut-off commit
515    /// from being served in part by a reader that goes to storage
516    /// directly (an anchor read, a publish) while the engine's own view
517    /// still shows the state before it. One existence check when no
518    /// record is on disk.
519    fn ensure_whole(&self) -> Result<(), BackendError> {
520        if self.owed().is_some() {
521            return Err(BackendError::CommitNotApplied {
522                detail: "the removal of the last commit's record is not synced yet; \
523                         loading the mem makes it good"
524                    .to_string(),
525            });
526        }
527        let record = self.record_path();
528        if !self.io.exists(&record).map_err(BackendError::Io)? {
529            return Ok(());
530        }
531        let lock = self.lock_file();
532        // A reader that holds another mem's write lock does not wait
533        // here: this lock is not one of the sorted set it took, and a
534        // writer of this mem may be waiting for one of those. It gets
535        // the condition at once and takes no lock.
536        if path_lock::holds_another(&lock) {
537            return Err(BackendError::CommitNotApplied {
538                detail: "the mem holds a commit that is in progress or was cut off, and this \
539                         operation holds another mem's write lock, so it does not wait for it; \
540                         loading the mem completes it"
541                    .to_string(),
542            });
543        }
544        if path_lock::acquire(&lock).is_ok() {
545            path_lock::release(&lock);
546        }
547        if !self.io.exists(&record).map_err(BackendError::Io)? {
548            return Ok(());
549        }
550        Err(BackendError::CommitNotApplied {
551            detail: "the mem holds a commit that was cut off; loading the mem completes it"
552                .to_string(),
553        })
554    }
555
556    /// Is a temp file of an abandoned attempt on disk? The read-only
557    /// half of [`Self::sweep_leftovers`], so a mem with nothing to
558    /// remove is never locked or written for the asking.
559    fn has_leftovers(&self) -> bool {
560        let locks = self.meta_dir().join("locks");
561        let mut stack = vec![self.root.clone()];
562        while let Some(dir) = stack.pop() {
563            let Ok(entries) = self.io.list_dir(&dir) else {
564                continue;
565            };
566            for entry in entries {
567                let path = dir.join(&entry.name);
568                if entry.is_dir {
569                    if path != locks {
570                        stack.push(path);
571                    }
572                } else if is_temp_name(&entry.name) {
573                    return true;
574                }
575            }
576        }
577        false
578    }
579
580    /// Finish the commit whose record is on disk. The caller holds the
581    /// mem's write lock. `Ok(None)` when a live writer finished it
582    /// while this call waited for the lock.
583    fn complete_decided_commit(&self) -> Result<Option<CompletedCommit>, BackendError> {
584        let record_path = self.record_path();
585        let Some(bytes) = self.io.read(&record_path).map_err(BackendError::Io)? else {
586            return Ok(None);
587        };
588        let unreadable = |why: String| {
589            BackendError::Other(format!(
590                "commit record {} cannot be read ({why}); the mem holds a decided commit \
591                 that cannot be completed",
592                record_path.display()
593            ))
594        };
595        let record: CommitRecord =
596            serde_json::from_slice(&bytes).map_err(|e| unreadable(e.to_string()))?;
597        if record.v != 1 {
598            return Err(unreadable(format!("unknown record version {}", record.v)));
599        }
600        // The record is input from disk: hold its paths to the same
601        // rules as a staged path before anything is moved or removed.
602        for op in &record.ops {
603            normalise_rel_path(Path::new(op.path())).map_err(|e| unreadable(e.to_string()))?;
604            if let RecordOp::Upsert { tmp, .. } = op {
605                normalise_rel_path(Path::new(tmp)).map_err(|e| unreadable(e.to_string()))?;
606            }
607        }
608        self.apply_record(&record)
609            .map_err(|e| BackendError::CommitNotApplied {
610                detail: e.to_string(),
611            })?;
612        let _ = self.sweep_leftovers();
613        Ok(Some(CompletedCommit {
614            files: record.ops.iter().map(|op| op.path().to_string()).collect(),
615        }))
616    }
617
618    /// Land one set of file operations and provenance records behind
619    /// one commit point. The body of [`MemBackend::commit`], and of the
620    /// standalone provenance append, which is a commit of ledger lines
621    /// and no file.
622    fn commit_staged_set(
623        &self,
624        ops: HashMap<String, PendingState>,
625        records: &[Provenance],
626    ) -> Result<CommitId, BackendError> {
627        // An earlier commit whose record removal is not synced yet is
628        // not finished either: a load makes it good and reports it.
629        if self.owed().is_some() {
630            return Err(BackendError::Other(
631                "an earlier commit of this mem is applied but not yet durable; \
632                 the mem must be loaded, which finishes it, before it is written again"
633                    .to_string(),
634            ));
635        }
636
637        // A record already on disk is an earlier commit, decided and
638        // not yet applied. Putting a new record over it would lose it.
639        match self.io.exists(&self.record_path()) {
640            Ok(false) => {}
641            Ok(true) => {
642                return Err(BackendError::Other(
643                    "an earlier commit of this mem is decided and not yet applied; \
644                     the mem must be loaded, which completes it, before it is written again"
645                        .to_string(),
646                ));
647            }
648            Err(e) => return Err(BackendError::Io(e)),
649        }
650
651        // Path order, so the commit's steps and its record read the
652        // same on every run.
653        let mut ops: Vec<(String, PendingState)> = ops.into_iter().collect();
654        ops.sort_by(|a, b| a.0.cmp(&b.0));
655
656        // Failure handling is spelled out here rather than left to a
657        // drop guard: a process that dies mid-commit runs none of it,
658        // and the recovery at load must cope with exactly that.
659        let mut attempt = Attempt::default();
660        let record = match self.prepare_commit(&ops, records, &mut attempt) {
661            Ok(record) => record,
662            Err(e) => {
663                self.abandon(&attempt);
664                return Err(BackendError::Io(e));
665            }
666        };
667
668        // The record is in place: the commit is decided. From here an
669        // error leaves a commit that the next load completes, never a
670        // failed write.
671        let not_applied = |e: std::io::Error| BackendError::CommitNotApplied {
672            detail: e.to_string(),
673        };
674        self.apply_record(&record).map_err(not_applied)?;
675        Ok(make_commit_id())
676    }
677
678    /// Read the current bytes at `rel_key` from the buffered op log if
679    /// present, otherwise from disk. Used by `move_entity` to resolve
680    /// the source content.
681    fn read_source(
682        &self,
683        pending: &Pending,
684        rel_key: &str,
685    ) -> Result<Option<Vec<u8>>, BackendError> {
686        if let Some(PendingState::Upsert(bytes)) = pending.ops.get(rel_key) {
687            return Ok(Some(bytes.clone()));
688        }
689        if let Some(PendingState::Delete) = pending.ops.get(rel_key) {
690            return Ok(None);
691        }
692        let full = self.root.join(rel_key);
693        match std::fs::read(&full) {
694            Ok(bytes) => Ok(Some(bytes)),
695            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
696            Err(e) => Err(BackendError::Io(e)),
697        }
698    }
699}
700
701/// Refuse to read the folder mem at `root` while it holds a commit that
702/// was cut off. For readers that walk a mem's directory without a
703/// backend in hand; the backend's own reads refuse through
704/// `FilesystemBackend::ensure_whole`. A directory with no commit record
705/// costs one existence check and is not touched.
706pub(crate) fn refuse_cut_off_commit(root: &Path) -> Result<(), BackendError> {
707    FilesystemBackend::new(root.to_path_buf()).ensure_whole()
708}
709
710/// Normalise a mem-relative path to a forward-slash key. Rejects
711/// empty paths, absolute paths, and any path that escapes the mem
712/// root via `..`. Every backend (folder, in-memory, git-branch) keys
713/// its entries through this one function, so they reject the same
714/// inputs.
715pub fn normalise_rel_path(rel_path: &Path) -> Result<String, BackendError> {
716    if rel_path.as_os_str().is_empty() {
717        return Err(BackendError::Path("mem-relative path is empty".to_string()));
718    }
719    let mut parts: Vec<String> = Vec::new();
720    for component in rel_path.components() {
721        use std::path::Component;
722        match component {
723            Component::Normal(s) => match s.to_str() {
724                Some(p) if !p.is_empty() => parts.push(p.to_string()),
725                _ => {
726                    return Err(BackendError::Path(format!(
727                        "non-utf-8 or empty path component in {}",
728                        rel_path.display()
729                    )));
730                }
731            },
732            Component::CurDir => continue,
733            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
734                return Err(BackendError::Path(format!(
735                    "path traversal or absolute component in {}",
736                    rel_path.display()
737                )));
738            }
739        }
740    }
741    if parts.is_empty() {
742        return Err(BackendError::Path(
743            "mem-relative path is empty after normalisation".to_string(),
744        ));
745    }
746    Ok(parts.join("/"))
747}
748
749impl crate::backend::MemBackend for FilesystemBackend {
750    fn list_entities(&self) -> Result<Vec<PathBuf>, BackendError> {
751        self.ensure_whole()?;
752        let mut out = Vec::new();
753        if !self.root.exists() {
754            return Ok(out);
755        }
756        walk_for_md(&self.root, &self.root, &mut out)?;
757        Ok(out)
758    }
759
760    /// Folder-mem drift cursor: the changelog's last-line `ts` (or the
761    /// commit-pending marker while a decided commit is unapplied) — the
762    /// same RFC3339-millisecond dialect `folder_changes_since` accepts
763    /// as its cursor, so drift heads feed straight into delta reads.
764    /// Every mutation appends a changelog line (in this process or a
765    /// sibling's), advancing the cursor; the drift check then treats
766    /// the advance exactly like a git-branch tip move. Absent
767    /// changelog (a mem never mutated through the engine) keeps the
768    /// historical no-drift-signal `None`. Appends go through
769    /// `append_change_monotonic`, so the cursor strictly advances even
770    /// for same-millisecond commits; only a read-append race between
771    /// separate processes can momentarily share a cursor value —
772    /// detection then rides the next append.
773    fn current_head(&self) -> Result<Option<String>, BackendError> {
774        // A commit record on disk is a decided commit not yet applied:
775        // report a cursor no ledger line carries, so the staleness
776        // probe reloads the mem and the reload completes the commit.
777        // The same while the sync of an applied commit's record removal
778        // is owed: a commit that carried no ledger line would otherwise
779        // leave the cursor where it was, and nothing would ever reload
780        // the mem and make the sync good.
781        if std::fs::symlink_metadata(self.record_path()).is_ok() || self.owed().is_some() {
782            return Ok(Some(COMMIT_PENDING_HEAD.to_string()));
783        }
784        let log_path = crate::filesystem::changelog::changelog_path(&self.root);
785        let raw = match std::fs::read_to_string(&log_path) {
786            Ok(s) => s,
787            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
788            Err(e) => {
789                return Err(BackendError::Other(format!(
790                    "reading folder changelog {}: {e}",
791                    log_path.display()
792                )));
793            }
794        };
795        let last_ts = raw
796            .lines()
797            .rev()
798            .filter_map(|line| {
799                let trimmed = line.trim();
800                if trimmed.is_empty() {
801                    return None;
802                }
803                serde_json::from_str::<serde_json::Value>(trimmed)
804                    .ok()?
805                    .get("ts")?
806                    .as_str()
807                    .map(str::to_string)
808            })
809            .next();
810        Ok(last_ts)
811    }
812
813    /// Inside the mem's own `.memstead/`, in a self-ignoring `locks/`
814    /// subtree, so every process that mounts this folder, from any
815    /// workspace, contends on the same file.
816    ///
817    /// The path is the canonical one. Two processes that spell the
818    /// folder differently (through a symlink, through `..`) must sort
819    /// their locks alike, or each takes the other's second lock first;
820    /// and within one process the lock table is keyed by this path.
821    fn write_lock_path(&self) -> Option<PathBuf> {
822        Some(self.lock_file())
823    }
824
825    fn read_entity(&self, rel_path: &Path) -> Result<Option<Vec<u8>>, BackendError> {
826        let key = normalise_rel_path(rel_path)?;
827        let pending = self.pending.lock().map_err(|_| {
828            BackendError::Other("filesystem writer pending state poisoned".to_string())
829        })?;
830        if let Some(state) = pending.ops.get(&key) {
831            return Ok(match state {
832                PendingState::Upsert(bytes) => Some(bytes.clone()),
833                PendingState::Delete => None,
834            });
835        }
836        drop(pending);
837        self.ensure_whole()?;
838        let full = self.root.join(&key);
839        match std::fs::read(&full) {
840            Ok(bytes) => Ok(Some(bytes)),
841            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
842            Err(e) => Err(BackendError::Io(e)),
843        }
844    }
845
846    /// Metadata-class existence probe: pending buffer first (same
847    /// precedence as `read_entity`), then one `symlink_metadata` call —
848    /// no file open, no byte read.
849    /// The mem root directory exists. A folder mount whose path is
850    /// gone (a moved checkout, a mem never materialised) lists zero
851    /// entities exactly like an empty one; this is how boot tells the
852    /// two apart.
853    fn storage_present(&self) -> Result<bool, BackendError> {
854        Ok(self.root.is_dir())
855    }
856
857    fn entity_exists(&self, rel_path: &Path) -> Result<bool, BackendError> {
858        let key = normalise_rel_path(rel_path)?;
859        let pending = self.pending.lock().map_err(|_| {
860            BackendError::Other("filesystem writer pending state poisoned".to_string())
861        })?;
862        if let Some(state) = pending.ops.get(&key) {
863            return Ok(matches!(state, PendingState::Upsert(_)));
864        }
865        drop(pending);
866        self.ensure_whole()?;
867        match std::fs::symlink_metadata(self.root.join(&key)) {
868            Ok(md) => Ok(md.is_file()),
869            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
870            Err(e) => Err(BackendError::Io(e)),
871        }
872    }
873
874    fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError> {
875        let key = normalise_rel_path(rel_path)?;
876        refuse_unwritable(&self.root, &key)?;
877        let mut pending = self.pending.lock().map_err(|_| {
878            BackendError::Path("filesystem writer pending state poisoned".to_string())
879        })?;
880        pending
881            .ops
882            .insert(key, PendingState::Upsert(content.to_vec()));
883        Ok(())
884    }
885
886    fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError> {
887        let key = normalise_rel_path(rel_path)?;
888        refuse_unwritable(&self.root, &key)?;
889        let mut pending = self.pending.lock().map_err(|_| {
890            BackendError::Path("filesystem writer pending state poisoned".to_string())
891        })?;
892        pending.ops.insert(key, PendingState::Delete);
893        Ok(())
894    }
895
896    fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError> {
897        let from_key = normalise_rel_path(from)?;
898        let to_key = normalise_rel_path(to)?;
899        refuse_unwritable(&self.root, &from_key)?;
900        refuse_unwritable(&self.root, &to_key)?;
901        let mut pending = self.pending.lock().map_err(|_| {
902            BackendError::Path("filesystem writer pending state poisoned".to_string())
903        })?;
904
905        // The target is checked before the source is touched, so a
906        // refused move leaves the staged state exactly as it was.
907        match pending.ops.get(&to_key) {
908            Some(PendingState::Upsert(_)) => {
909                return Err(BackendError::Path(format!(
910                    "move target {} already has a pending write",
911                    to.display()
912                )));
913            }
914            Some(PendingState::Delete) => {}
915            None => {
916                if self.read_source(&pending, &to_key)?.is_some() {
917                    return Err(BackendError::Path(format!(
918                        "move target {} already exists",
919                        to.display()
920                    )));
921                }
922            }
923        }
924
925        let bytes = match pending.ops.remove(&from_key) {
926            Some(PendingState::Upsert(b)) => b,
927            Some(PendingState::Delete) => {
928                pending.ops.insert(from_key, PendingState::Delete);
929                return Err(BackendError::Path(format!(
930                    "move source {} is already pending deletion",
931                    from.display()
932                )));
933            }
934            None => match self.read_source(&pending, &from_key)? {
935                Some(b) => b,
936                None => {
937                    return Err(BackendError::Path(format!(
938                        "move source {} does not exist",
939                        from.display()
940                    )));
941                }
942            },
943        };
944
945        pending.ops.insert(from_key, PendingState::Delete);
946        pending.ops.insert(to_key, PendingState::Upsert(bytes));
947        Ok(())
948    }
949
950    fn discard_pending(&self) -> Result<(), BackendError> {
951        // Drop the staged operations and their provenance records
952        // without replaying them: nothing staged has touched disk.
953        let mut pending = self.pending.lock().map_err(|_| {
954            BackendError::Other("filesystem writer pending state poisoned".to_string())
955        })?;
956        pending.clear();
957        Ok(())
958    }
959
960    fn commit(&self, _message: &str, _ctx: &CommitContext<'_>) -> Result<CommitId, BackendError> {
961        let mut pending = self.pending.lock().map_err(|_| {
962            BackendError::Path("filesystem writer pending state poisoned".to_string())
963        })?;
964        // Taken out before anything can fail: whatever this commit
965        // comes to, nothing stays staged behind it, so no later read
966        // can serve a write that never landed.
967        let staged = std::mem::replace(&mut *pending, Pending::new());
968        if staged.ops.is_empty() && staged.records.is_empty() {
969            return Ok(make_commit_id());
970        }
971
972        self.commit_staged_set(staged.ops, &staged.records)
973    }
974
975    /// Recovery writes, so it excludes a live writer first: the record
976    /// it applies and the temps it removes belong to a writer that is
977    /// gone only if no one holds the mem's write lock. A record on disk
978    /// waits for that lock (a live writer finishes its own commit and
979    /// the record is gone by then); leftover temps are removed only if
980    /// the lock is free at once, since they are invisible to readers
981    /// and a load must not wait on hygiene. A mem with nothing to
982    /// recover is not touched at all, lock file included.
983    fn complete_interrupted_commit(&self) -> Result<Option<CompletedCommit>, BackendError> {
984        // A commit of this backend that is applied except for the sync
985        // of its record's removal: make the sync good, and that commit
986        // is the one this call completed.
987        if let Some(files) =
988            self.sync_record_removal()
989                .map_err(|e| BackendError::CommitNotApplied {
990                    detail: e.to_string(),
991                })?
992        {
993            return Ok(Some(CompletedCommit { files }));
994        }
995        let lock = self.lock_file();
996        if self
997            .io
998            .exists(&self.record_path())
999            .map_err(BackendError::Io)?
1000        {
1001            // A load that runs under another mem's write lock (the
1002            // reload of a peer before a write) does not wait for this
1003            // one: the lock is outside the sorted set its operation
1004            // took, and a writer of this mem may be waiting for one of
1005            // those. It takes the lock if it is free and otherwise
1006            // leaves the commit to its writer, or to the next load.
1007            if path_lock::holds_another(&lock) {
1008                return match path_lock::try_acquire(&lock) {
1009                    Ok(true) => {
1010                        let result = self.complete_decided_commit();
1011                        path_lock::release(&lock);
1012                        result
1013                    }
1014                    _ => Err(BackendError::CommitNotApplied {
1015                        detail: "the mem holds a commit in progress and another writer holds \
1016                                 its lock; loading the mem completes it once the lock is free"
1017                            .to_string(),
1018                    }),
1019                };
1020            }
1021            // A lock that cannot be taken (a read-only location) is not
1022            // a reason to serve the mem half applied: the completion
1023            // below then fails with its own error.
1024            let locked = path_lock::acquire(&lock).is_ok();
1025            let result = self.complete_decided_commit();
1026            if locked {
1027                path_lock::release(&lock);
1028            }
1029            return result;
1030        }
1031        // Best effort from here: a temp that stays is removed by a
1032        // later load and changes nothing a reader sees.
1033        if self.has_leftovers() && matches!(path_lock::try_acquire(&lock), Ok(true)) {
1034            // Look again under the lock: a sibling writer may have
1035            // passed its commit point and died since the first look.
1036            // Its temps are then the contents of a decided commit, to
1037            // be moved into place and never swept.
1038            let result = if self
1039                .io
1040                .exists(&self.record_path())
1041                .map_err(BackendError::Io)?
1042            {
1043                self.complete_decided_commit()
1044            } else {
1045                let _ = self.sweep_leftovers();
1046                Ok(None)
1047            };
1048            path_lock::release(&lock);
1049            return result;
1050        }
1051        Ok(None)
1052    }
1053
1054    fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
1055        // Folder backend reads `<root>/.memstead/config.json`.
1056        // Missing file → Ok(None); other IO errors propagate as
1057        // BackendError.
1058        let config_path = self.root.join(crate::mem::MEM_META_DIR).join("config.json");
1059        match std::fs::read(&config_path) {
1060            Ok(bytes) => Ok(Some(bytes)),
1061            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1062            Err(e) => Err(BackendError::Io(e)),
1063        }
1064    }
1065
1066    fn write_mem_config(
1067        &self,
1068        bytes: &[u8],
1069        _ctx: &crate::vcs::CommitContext<'_>,
1070    ) -> Result<(), BackendError> {
1071        // Folder backend writes `<root>/.memstead/config.json` to disk.
1072        // Creates the `.memstead/` directory if missing. Existing config
1073        // is overwritten — caller's responsibility to gate against
1074        // overwrites if that's the contract (the unified
1075        // `mem_management::create_mem` Step 4 already does the
1076        // refusal-to-overwrite check upstream).
1077        let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
1078        std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
1079        refuse_symlinked_meta(&self.root)?;
1080        let _lock = ConfigLock::take(self.config_lock_file())?;
1081        replace_file(&memstead_dir.join("config.json"), bytes)
1082    }
1083
1084    /// Compare-and-set under the mem's config lock (an operating-system
1085    /// file lock, shared with [`Self::write_mem_config`]), which is what
1086    /// makes the check and the write one step. A hand edit is still
1087    /// detected, because the compare reads the file. The write replaces the
1088    /// file through a renamed temp, so a crash leaves the old config or the
1089    /// new one.
1090    fn write_mem_config_cas(
1091        &self,
1092        expected: Option<&[u8]>,
1093        bytes: &[u8],
1094        _ctx: &crate::vcs::CommitContext<'_>,
1095    ) -> Result<bool, BackendError> {
1096        let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
1097        std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
1098        let config_path = memstead_dir.join("config.json");
1099        // The config lock makes the compare and the write one step against
1100        // every other config writer of this mem, in any process. It is an
1101        // operating-system lock: a writer that dies releases it, so there is
1102        // no stale age to guess and no live holder is ever overtaken.
1103        refuse_symlinked_meta(&self.root)?;
1104        let _lock = ConfigLock::take(self.config_lock_file())?;
1105
1106        let current = match std::fs::read(&config_path) {
1107            Ok(b) => Some(b),
1108            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
1109            Err(e) => return Err(BackendError::Io(e)),
1110        };
1111        if let Some(expected) = expected
1112            && current.as_deref() != Some(expected)
1113        {
1114            return Ok(false);
1115        }
1116        replace_file(&config_path, bytes).map(|_| true)
1117    }
1118
1119    fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
1120        // Read via the entity path so a staged (pending) sidecar write is
1121        // visible before its commit, symmetric with the other backends.
1122        self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
1123    }
1124
1125    fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
1126        // Stage into the same op buffer entity writes use so the sidecar
1127        // rides the entity mutation's commit. `list_entities`
1128        // (`walk_for_md`) skips `.memstead/`, so it never lists as an
1129        // entity.
1130        <Self as MemBackend>::write_entity(
1131            self,
1132            Path::new(crate::anchor::ANCHOR_SIDECAR_PATH),
1133            bytes,
1134        )
1135    }
1136
1137    fn stage_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
1138        let mut pending = self.pending.lock().map_err(|_| {
1139            BackendError::Other("filesystem writer pending state poisoned".to_string())
1140        })?;
1141        pending.records.push(record.clone());
1142        Ok(())
1143    }
1144
1145    fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
1146        // A record on its own is a commit of one ledger line and no
1147        // file, behind the same commit point as any other: it is
1148        // durable when this returns, and a failure after the commit
1149        // point is the decided-and-not-applied condition, never a line
1150        // that is in the ledger while the caller is told it failed.
1151        // Writes staged for a later commit are not touched.
1152        self.commit_staged_set(HashMap::new(), std::slice::from_ref(record))
1153            .map(|_| ())
1154    }
1155
1156    fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError> {
1157        self.ensure_whole()?;
1158        let log_path = changelog_path(&self.root);
1159        let raw = match std::fs::read_to_string(&log_path) {
1160            Ok(s) => s,
1161            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1162            Err(e) => return Err(BackendError::Io(e)),
1163        };
1164        let mut out = Vec::new();
1165        for line in raw.lines() {
1166            let trimmed = line.trim();
1167            if trimmed.is_empty() {
1168                continue;
1169            }
1170            let value: serde_json::Value = match serde_json::from_str(trimmed) {
1171                Ok(v) => v,
1172                Err(_) => continue,
1173            };
1174            let ts_str = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
1175            if let Some(c) = cursor
1176                && ts_str <= c
1177            {
1178                continue;
1179            }
1180            let timestamp = parse_rfc3339_utc(ts_str).unwrap_or(std::time::UNIX_EPOCH);
1181            let kind = value
1182                .get("kind")
1183                .and_then(|v| v.as_str())
1184                .and_then(ProvenanceKind::parse)
1185                .unwrap_or(ProvenanceKind::Update);
1186            let entity = value
1187                .get("entity")
1188                .and_then(|v| v.as_str())
1189                .map(|s| s.to_string());
1190            let actor = value
1191                .get("actor")
1192                .and_then(|v| v.as_str())
1193                .and_then(Actor::from_trailer)
1194                .unwrap_or(Actor::Unknown);
1195            let client = value
1196                .get("client")
1197                .and_then(|v| v.as_str())
1198                .and_then(parse_client_id);
1199            let note = value
1200                .get("note")
1201                .and_then(|v| v.as_str())
1202                .map(|s| s.to_string());
1203            let logical_operation_id = value
1204                .get("logical_op")
1205                .and_then(|v| v.as_str())
1206                .map(|s| s.to_string());
1207            let mut record = Provenance::new(timestamp, kind, entity, actor, client, note);
1208            if let Some(id) = logical_operation_id {
1209                record = record.with_logical_operation_id(id);
1210            }
1211            if let Some(from) = value.get("renamed_from").and_then(|v| v.as_str()) {
1212                record = record.with_renamed_from(from.to_string());
1213            }
1214            if let Some(role) = value
1215                .get("role")
1216                .and_then(|v| v.as_str())
1217                .and_then(crate::vcs::Role::from_wire)
1218            {
1219                record = record.with_role(role);
1220            }
1221            record = record.with_identity(
1222                value
1223                    .get("identity")
1224                    .and_then(|v| v.as_str())
1225                    .map(|s| s.to_string()),
1226            );
1227            out.push(record);
1228        }
1229        Ok(out)
1230    }
1231}
1232
1233/// Walk `dir` for `.md` files, accumulating mem-relative paths in
1234/// `out`. Skips the mem's `.memstead/` umbrella so the engine never
1235/// confuses changelog / config / schema files with entity-bearing
1236/// markdown, and `README.md` — repository documentation beside the
1237/// entity files, never an entity (mirrors the entity-source walker's
1238/// skip; entities are slug-named after their titles, so no legitimate
1239/// entity file carries this name).
1240fn walk_for_md(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), BackendError> {
1241    let entries = match std::fs::read_dir(dir) {
1242        Ok(e) => e,
1243        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
1244        Err(e) => return Err(BackendError::Io(e)),
1245    };
1246    for entry in entries {
1247        let entry = entry.map_err(BackendError::Io)?;
1248        let path = entry.path();
1249        let file_type = entry.file_type().map_err(BackendError::Io)?;
1250        if file_type.is_dir() {
1251            let name = entry.file_name();
1252            if name == crate::mem::MEM_META_DIR {
1253                continue;
1254            }
1255            // A subdirectory with its own mem config is another mem.
1256            if crate::mem::is_nested_mem_root(&path) {
1257                continue;
1258            }
1259            walk_for_md(root, &path, out)?;
1260        } else if file_type.is_file()
1261            && crate::filesystem::changelog::is_entity_file(&path)
1262            && let Ok(rel) = path.strip_prefix(root)
1263        {
1264            out.push(rel.to_path_buf());
1265        }
1266    }
1267    Ok(())
1268}
1269
1270/// The ledger entry a provenance record writes.
1271fn change_entry(record: &Provenance) -> ChangeEntry<'_> {
1272    let kind: MutationKind = record.kind.into();
1273    ChangeEntry {
1274        kind,
1275        entity: record.entity.as_deref(),
1276        actor: record.actor,
1277        client: record.client.as_ref(),
1278        note: record.note.as_deref(),
1279        logical_operation_id: record.logical_operation_id.as_deref(),
1280        role: record.role,
1281        identity: record.identity.as_deref(),
1282        renamed_from: record.renamed_from.as_deref(),
1283    }
1284}
1285
1286/// The mem-relative key of `tmp`, the temp file beside the target at
1287/// `key`: same directory, the temp's file name.
1288fn sibling_key(key: &str, tmp: &Path) -> String {
1289    let name = tmp
1290        .file_name()
1291        .map(|n| n.to_string_lossy().into_owned())
1292        .unwrap_or_default();
1293    match key.rsplit_once('/') {
1294        Some((dir, _)) => format!("{dir}/{name}"),
1295        None => name,
1296    }
1297}
1298
1299/// Is `name` a temp file of this backend ([`make_tmp_path`]):
1300/// `.<target>.tmp.<hex>-<hex>`?
1301fn is_temp_name(name: &str) -> bool {
1302    let Some(rest) = name.strip_prefix('.') else {
1303        return false;
1304    };
1305    let Some((target, suffix)) = rest.rsplit_once(".tmp.") else {
1306        return false;
1307    };
1308    let Some((nanos, counter)) = suffix.split_once('-') else {
1309        return false;
1310    };
1311    let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit());
1312    !target.is_empty() && hex(nanos) && hex(counter)
1313}
1314
1315/// Build a sibling temp path of the form `.<name>.tmp.<suffix>` next
1316/// to `target`. The leading dot keeps the temp file out of the way of
1317/// directory listings; the suffix combines UNIX-nanos with a process-
1318/// scoped counter so concurrent writes never collide.
1319fn make_tmp_path(target: &Path) -> PathBuf {
1320    let name = target
1321        .file_name()
1322        .map(|n| n.to_string_lossy().to_string())
1323        .unwrap_or_else(|| "_".to_string());
1324    let suffix = unique_suffix();
1325    let tmp_name = format!(".{name}.tmp.{suffix}");
1326    target.with_file_name(tmp_name)
1327}
1328
1329static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
1330static COMMIT_COUNTER: AtomicU64 = AtomicU64::new(0);
1331
1332fn unique_suffix() -> String {
1333    let nanos = std::time::SystemTime::now()
1334        .duration_since(std::time::UNIX_EPOCH)
1335        .map(|d| d.as_nanos())
1336        .unwrap_or(0);
1337    let counter = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
1338    format!("{nanos:x}-{counter:x}")
1339}
1340
1341/// `pub(crate)` so the in-memory backend mints the same synthetic
1342/// write-id shape (UNIX-nanos + counter, hex) the folder backend
1343/// produces — both are history-free backends and must hand callers an
1344/// identically-shaped opaque identity. It is NOT a change cursor:
1345/// the change feed's cursor is an RFC3339 timestamp, and passing this
1346/// token as `since` refuses with `INVALID_CURSOR` (it would otherwise
1347/// sort below every timestamp and replay the whole history).
1348pub(crate) fn make_commit_id() -> CommitId {
1349    let nanos = std::time::SystemTime::now()
1350        .duration_since(std::time::UNIX_EPOCH)
1351        .map(|d| d.as_nanos())
1352        .unwrap_or(0);
1353    let counter = COMMIT_COUNTER.fetch_add(1, Ordering::Relaxed);
1354    format!("{nanos:032x}{counter:016x}")
1355}
1356
1357#[cfg(test)]
1358mod commit_point_tests;
1359#[cfg(test)]
1360pub(crate) mod fault_io;
1361#[cfg(test)]
1362mod folder_drift_tests;
1363pub(crate) mod io;
1364#[cfg(test)]
1365mod tests;
1366
1367/// Replace `path` with `bytes`: write a sibling temp file, sync it, rename
1368/// it over `path` and sync the directory. A crash leaves either the old
1369/// file or the new one, never a truncated one.
1370fn replace_file(path: &Path, bytes: &[u8]) -> Result<(), BackendError> {
1371    use std::io::Write as _;
1372    let dir = path
1373        .parent()
1374        .ok_or_else(|| BackendError::Path(format!("{} has no parent", path.display())))?;
1375    let name = path
1376        .file_name()
1377        .ok_or_else(|| BackendError::Path(format!("{} has no file name", path.display())))?;
1378    let mut tmp_name = name.to_os_string();
1379    tmp_name.push(format!(".tmp-{}", lock_token()));
1380    let tmp = dir.join(tmp_name);
1381    let written = (|| -> std::io::Result<()> {
1382        let mut f = std::fs::File::create(&tmp)?;
1383        f.write_all(bytes)?;
1384        f.sync_all()?;
1385        std::fs::rename(&tmp, path)?;
1386        RealIo.sync_dir(dir)
1387    })();
1388    if written.is_err() {
1389        let _ = std::fs::remove_file(&tmp);
1390    }
1391    written.map_err(BackendError::Io)
1392}
1393
1394/// A token unique to this process and call, naming a temp file.
1395fn lock_token() -> String {
1396    use std::sync::atomic::{AtomicU64, Ordering};
1397    static SEQ: AtomicU64 = AtomicU64::new(0);
1398    let nanos = std::time::SystemTime::now()
1399        .duration_since(std::time::UNIX_EPOCH)
1400        .map(|d| d.as_nanos())
1401        .unwrap_or(0);
1402    format!(
1403        "{}-{}-{}",
1404        std::process::id(),
1405        nanos,
1406        SEQ.fetch_add(1, Ordering::Relaxed)
1407    )
1408}
1409
1410/// The first component of `key` under `root` that is a symbolic link, if
1411/// any. A write or delete through one would land outside the mem, where no
1412/// listing, commit record or ledger of this mem sees it.
1413fn symlink_on_path(root: &Path, key: &str) -> std::io::Result<Option<PathBuf>> {
1414    let mut at = root.to_path_buf();
1415    for part in Path::new(key).components() {
1416        at.push(part);
1417        match std::fs::symlink_metadata(&at) {
1418            Ok(md) if md.file_type().is_symlink() => return Ok(Some(at)),
1419            // Nothing below a file can exist; the write fails on its own.
1420            Ok(md) if !md.is_dir() => return Ok(None),
1421            Ok(_) => {}
1422            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1423            Err(e) => return Err(e),
1424        }
1425    }
1426    Ok(None)
1427}
1428
1429/// Refuse `key` when it passes through a symbolic link inside the mem.
1430fn refuse_symlinked(root: &Path, key: &str) -> Result<(), BackendError> {
1431    match symlink_on_path(root, key).map_err(BackendError::Io)? {
1432        Some(link) => Err(BackendError::Path(format!(
1433            "{key} passes through the symbolic link {}; a mem writes only inside its own directory",
1434            link.display()
1435        ))),
1436        None => Ok(()),
1437    }
1438}
1439
1440/// The mem's config lock, held for the scope of one config write.
1441struct ConfigLock(PathBuf);
1442
1443impl ConfigLock {
1444    fn take(path: PathBuf) -> Result<Self, BackendError> {
1445        path_lock::acquire(&path).map_err(BackendError::Io)?;
1446        Ok(Self(path))
1447    }
1448}
1449
1450impl Drop for ConfigLock {
1451    fn drop(&mut self) {
1452        path_lock::release(&self.0);
1453    }
1454}
1455
1456/// The paths under `.memstead/` an entity-path write may reach: the
1457/// sidecars that ride a commit. Everything else there (the commit record,
1458/// the ledger, the config, the locks) is the backend's own.
1459const WRITABLE_META_PATHS: &[&str] = &[
1460    crate::anchor::ANCHOR_SIDECAR_PATH,
1461    crate::derivation::DERIVATION_SIDECAR_PATH,
1462    crate::ops::proposal::PROPOSAL_RECORD_PATH,
1463];
1464
1465/// Refuse an entity-path write to one of the backend's own files under
1466/// `.memstead/`, and any path through a symbolic link.
1467fn refuse_unwritable(root: &Path, key: &str) -> Result<(), BackendError> {
1468    let meta = format!("{}/", crate::mem::MEM_META_DIR);
1469    if key.starts_with(&meta) && !WRITABLE_META_PATHS.contains(&key) {
1470        return Err(BackendError::Path(format!(
1471            "{key} is the backend's own file; only {} are written through entity paths",
1472            WRITABLE_META_PATHS.join(", ")
1473        )));
1474    }
1475    refuse_symlinked(root, key)
1476}
1477
1478/// Refuse a `.memstead` directory that is a symbolic link: the config, the
1479/// commit record and the ledger would land outside the mem.
1480fn refuse_symlinked_meta(root: &Path) -> Result<(), BackendError> {
1481    refuse_symlinked(root, crate::mem::MEM_META_DIR)
1482}