1use 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
73enum PendingState {
78 Upsert(Vec<u8>),
79 Delete,
80}
81
82struct 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
104pub(crate) const COMMIT_RECORD_REL: &str = ".memstead/commit.json";
107
108const COMMIT_PENDING_HEAD: &str = "commit-pending";
112
113#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
116#[serde(tag = "op", rename_all = "lowercase")]
117enum RecordOp {
118 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#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
139struct CommitRecord {
140 v: u32,
141 ops: Vec<RecordOp>,
143 ledger: Vec<String>,
145}
146
147#[derive(Default)]
150struct Attempt {
151 temps: Vec<PathBuf>,
153 created_dirs: Vec<PathBuf>,
155}
156
157pub struct FilesystemBackend {
160 root: PathBuf,
161 pending: Mutex<Pending>,
162 io: Box<dyn FolderIo>,
163 removal_sync_owed: Mutex<Option<Vec<String>>>,
170 meta_named: std::sync::atomic::AtomicBool,
173}
174
175impl FilesystemBackend {
176 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 #[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 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 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 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 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 fn prepare_commit(
270 &self,
271 ops: &[(String, PendingState)],
272 records: &[Provenance],
273 attempt: &mut Attempt,
274 ) -> std::io::Result<CommitRecord> {
275 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 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 let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
312 for path in attempt.temps.iter().chain(attempt.created_dirs.iter()) {
313 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 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 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 fn apply_record(&self, record: &CommitRecord) -> std::io::Result<()> {
379 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 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 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 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 *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 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 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 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 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 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 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 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 fn commit_staged_set(
623 &self,
624 ops: HashMap<String, PendingState>,
625 records: &[Provenance],
626 ) -> Result<CommitId, BackendError> {
627 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 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 let mut ops: Vec<(String, PendingState)> = ops.into_iter().collect();
654 ops.sort_by(|a, b| a.0.cmp(&b.0));
655
656 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 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 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
701pub(crate) fn refuse_cut_off_commit(root: &Path) -> Result<(), BackendError> {
707 FilesystemBackend::new(root.to_path_buf()).ensure_whole()
708}
709
710pub 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 fn current_head(&self) -> Result<Option<String>, BackendError> {
774 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 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 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 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 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 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 fn complete_interrupted_commit(&self) -> Result<Option<CompletedCommit>, BackendError> {
984 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 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 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 if self.has_leftovers() && matches!(path_lock::try_acquire(&lock), Ok(true)) {
1034 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 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 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 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 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 self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
1123 }
1124
1125 fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
1126 <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 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
1233fn 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 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
1270fn 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
1286fn 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
1299fn 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
1315fn 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
1341pub(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
1367fn 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
1394fn 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
1410fn 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 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
1429fn 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
1440struct 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
1456const 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
1465fn 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
1478fn refuse_symlinked_meta(root: &Path) -> Result<(), BackendError> {
1481 refuse_symlinked(root, crate::mem::MEM_META_DIR)
1482}