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 lock_wait: Mutex<Option<Option<std::time::Duration>>>,
179 lock_wait_spent: Mutex<Option<std::time::Instant>>,
184}
185
186#[derive(Clone, Copy)]
190struct LockWait {
191 limit: std::time::Duration,
192 told: bool,
193 looked_once: bool,
194}
195
196fn default_lock_wait() -> Option<std::time::Duration> {
199 Some(std::time::Duration::from_secs(
200 crate::workspace::MutationsSection::DEFAULT_WRITE_LOCK_TIMEOUT_SECS,
201 ))
202}
203
204impl FilesystemBackend {
205 pub fn new(root: PathBuf) -> Self {
208 Self {
209 root,
210 pending: Mutex::new(Pending::new()),
211 io: Box::new(RealIo),
212 removal_sync_owed: Mutex::new(None),
213 meta_named: std::sync::atomic::AtomicBool::new(false),
214 lock_wait: Mutex::new(None),
215 lock_wait_spent: Mutex::new(None),
216 }
217 }
218
219 #[cfg(test)]
222 pub(crate) fn with_io(root: PathBuf, io: impl FolderIo + 'static) -> Self {
223 Self {
224 root,
225 pending: Mutex::new(Pending::new()),
226 io: Box::new(io),
227 removal_sync_owed: Mutex::new(None),
228 meta_named: std::sync::atomic::AtomicBool::new(false),
229 lock_wait: Mutex::new(None),
230 lock_wait_spent: Mutex::new(None),
231 }
232 }
233
234 fn meta_dir(&self) -> PathBuf {
235 self.root.join(crate::mem::MEM_META_DIR)
236 }
237
238 fn lock_file(&self) -> PathBuf {
242 let root = std::fs::canonicalize(&self.root).unwrap_or_else(|_| self.root.clone());
243 root.join(".memstead").join("locks").join("write.lock")
244 }
245
246 fn config_lock_file(&self) -> PathBuf {
248 let root = std::fs::canonicalize(&self.root).unwrap_or_else(|_| self.root.clone());
249 root.join(".memstead").join("locks").join("config.lock")
250 }
251
252 fn record_path(&self) -> PathBuf {
253 self.root.join(COMMIT_RECORD_REL)
254 }
255
256 fn lock_wait_limit(&self) -> (Option<std::time::Duration>, bool) {
260 match self.lock_wait.lock().map(|told| *told) {
261 Ok(Some(limit)) => (limit, true),
262 _ => (default_lock_wait(), false),
263 }
264 }
265
266 fn wait_for_write_lock(&self, lock: &Path) -> std::io::Result<Option<LockWait>> {
277 let (limit, told) = self.lock_wait_limit();
278 let spent_recently = limit.is_some_and(|limit| {
279 self.lock_wait_spent
280 .lock()
281 .ok()
282 .and_then(|at| *at)
283 .is_some_and(|at| at.elapsed() < limit)
284 });
285 let wait = if spent_recently {
286 Some(std::time::Duration::ZERO)
287 } else {
288 limit
289 };
290 if path_lock::acquire_within(lock, wait)? {
291 return Ok(None);
292 }
293 if !spent_recently && let Ok(mut spent) = self.lock_wait_spent.lock() {
294 *spent = Some(std::time::Instant::now());
295 }
296 Ok(Some(LockWait {
297 limit: limit.unwrap_or_default(),
298 told,
299 looked_once: spent_recently,
300 }))
301 }
302
303 fn lock_wait_passed(&self, wait: LockWait) -> BackendError {
308 let whose = if wait.told {
309 "`write_lock_timeout_secs` in the workspace's `[mutations]` table sets that wait, \
310 `0` waits without bound"
311 } else {
312 "the default wait of a reader that has no workspace to ask; \
313 `write_lock_timeout_secs` does not reach it"
314 };
315 let waited = if wait.looked_once {
318 format!(
319 "another process holds its write lock; a wait of {} s for that lock ran out a \
320 moment ago and is not repeated yet",
321 wait.limit.as_secs_f64()
322 )
323 } else {
324 format!(
325 "another process held its write lock for the whole wait of {} s",
326 wait.limit.as_secs_f64()
327 )
328 };
329 BackendError::CommitNotApplied {
330 detail: format!(
331 "the mem holds a commit that is decided and not applied, and {waited} \
332 ({whose}); nothing of the mem was read; loading the mem completes the commit \
333 once the lock is free"
334 ),
335 }
336 }
337
338 fn ensure_dir(&self, dir: &Path, attempt: &mut Attempt) -> std::io::Result<()> {
341 let mut missing: Vec<PathBuf> = Vec::new();
342 let mut cursor = Some(dir);
343 while let Some(d) = cursor {
344 if d.as_os_str().is_empty() || self.io.exists(d)? {
345 break;
346 }
347 missing.push(d.to_path_buf());
348 cursor = d.parent();
349 }
350 for d in missing.into_iter().rev() {
351 self.io.create_dir(&d)?;
352 attempt.created_dirs.push(d);
353 }
354 Ok(())
355 }
356
357 fn render_ledger(&self, records: &[Provenance]) -> std::io::Result<Vec<String>> {
362 if records.is_empty() {
363 return Ok(Vec::new());
364 }
365 let mut last = self
366 .io
367 .read_tail(&changelog_path(&self.root), 4096)?
368 .and_then(|tail| changelog::last_ts_in_tail(&tail));
369 let mut lines = Vec::with_capacity(records.len());
370 for record in records {
371 let ts = changelog::monotonic_ts(last, record.timestamp);
372 let line = changelog::render_change_line(&change_entry(record), ts)
373 .map_err(|e| std::io::Error::other(e.to_string()))?;
374 lines.push(line.trim_end_matches('\n').to_string());
375 last = Some(ts);
376 }
377 Ok(lines)
378 }
379
380 fn prepare_commit(
385 &self,
386 ops: &[(String, PendingState)],
387 records: &[Provenance],
388 attempt: &mut Attempt,
389 ) -> std::io::Result<CommitRecord> {
390 refuse_symlinked_meta(&self.root).map_err(|e| std::io::Error::other(e.to_string()))?;
393 self.ensure_dir(&self.meta_dir(), attempt)?;
394
395 let mut record_ops = Vec::with_capacity(ops.len());
396 for (key, state) in ops {
397 if let Some(link) = symlink_on_path(&self.root, key)? {
399 return Err(std::io::Error::other(format!(
400 "{key} passes through the symbolic link {}; a mem writes only inside its own directory",
401 link.display()
402 )));
403 }
404 match state {
405 PendingState::Upsert(bytes) => {
406 let target = self.root.join(key);
407 if let Some(parent) = target.parent() {
408 self.ensure_dir(parent, attempt)?;
409 }
410 let tmp = make_tmp_path(&target);
411 attempt.temps.push(tmp.clone());
412 self.io.write(&tmp, bytes)?;
413 self.io.sync_file(&tmp)?;
414 record_ops.push(RecordOp::Upsert {
415 path: key.clone(),
416 tmp: sibling_key(key, &tmp),
417 });
418 }
419 PendingState::Delete => record_ops.push(RecordOp::Delete { path: key.clone() }),
420 }
421 }
422
423 let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
427 for path in attempt.temps.iter().chain(attempt.created_dirs.iter()) {
428 let mut dir = path.parent();
433 while let Some(d) = dir {
434 if !d.starts_with(&self.root) {
435 break;
436 }
437 dirs.insert(d.to_path_buf());
438 if d == self.root {
439 break;
440 }
441 dir = d.parent();
442 }
443 }
444 let name_meta = !self.meta_named.load(Ordering::SeqCst);
450 if name_meta {
451 dirs.insert(self.root.clone());
452 }
453 for dir in &dirs {
454 self.io.sync_dir(dir)?;
455 }
456 if name_meta {
457 self.meta_named.store(true, Ordering::SeqCst);
458 }
459
460 let record = CommitRecord {
461 v: 1,
462 ops: record_ops,
463 ledger: self.render_ledger(records)?,
464 };
465 let bytes =
466 serde_json::to_vec(&record).map_err(|e| std::io::Error::other(e.to_string()))?;
467 let record_path = self.record_path();
468 let record_tmp = make_tmp_path(&record_path);
469 attempt.temps.push(record_tmp.clone());
470 self.io.write(&record_tmp, &bytes)?;
471 self.io.sync_file(&record_tmp)?;
472 self.io.rename(&record_tmp, &record_path)?;
473 Ok(record)
474 }
475
476 fn abandon(&self, attempt: &Attempt) {
480 for tmp in &attempt.temps {
481 let _ = self.io.remove_file(tmp);
482 }
483 for dir in attempt.created_dirs.iter().rev() {
484 let _ = self.io.remove_dir(dir);
485 }
486 }
487
488 fn apply_record(&self, record: &CommitRecord) -> std::io::Result<()> {
494 self.io.sync_dir(&self.meta_dir())?;
500
501 let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
502 for op in &record.ops {
503 let target = self.root.join(op.path());
504 match op {
505 RecordOp::Upsert { path, tmp } => {
506 let tmp = self.root.join(tmp);
507 if self.io.exists(&tmp)? {
508 self.io.rename(&tmp, &target)?;
509 } else if !self.io.exists(&target)? {
510 return Err(std::io::Error::other(format!(
511 "commit record names {path}, and neither its staged content \
512 nor the file is on disk"
513 )));
514 }
515 }
516 RecordOp::Delete { .. } => match self.io.remove_file(&target) {
517 Ok(()) => {}
518 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
519 Err(e) => return Err(e),
520 },
521 }
522 if let Some(parent) = target.parent() {
527 dirs.insert(parent.to_path_buf());
528 }
529 }
530 for dir in &dirs {
531 self.io.sync_dir(dir)?;
532 }
533
534 if !record.ledger.is_empty() {
535 let log = changelog_path(&self.root);
536 let span: u64 = record.ledger.iter().map(|l| l.len() as u64 + 1).sum();
540 let tail = self.io.read_tail(&log, span + 8192)?.unwrap_or_default();
541 let tail_text = String::from_utf8_lossy(&tail);
542 let present: HashSet<&str> = tail_text.lines().collect();
543 let mut out = String::new();
544 if !tail.is_empty() && !tail.ends_with(b"\n") {
548 out.push('\n');
549 }
550 let mut missing = false;
551 for line in &record.ledger {
552 if !present.contains(line.as_str()) {
553 out.push_str(line);
554 out.push('\n');
555 missing = true;
556 }
557 }
558 if missing {
559 self.io.append(&log, out.as_bytes())?;
560 }
561 self.io.sync_file(&log)?;
562 }
563
564 match self.io.remove_file(&self.record_path()) {
565 Ok(()) => {}
566 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
567 Err(e) => return Err(e),
568 }
569 *self.owed() = Some(record.ops.iter().map(|op| op.path().to_string()).collect());
575 self.sync_record_removal().map(|_| ())
576 }
577
578 fn owed(&self) -> std::sync::MutexGuard<'_, Option<Vec<String>>> {
579 self.removal_sync_owed
580 .lock()
581 .unwrap_or_else(|e| e.into_inner())
582 }
583
584 fn sync_record_removal(&self) -> std::io::Result<Option<Vec<String>>> {
589 let mut owed = self.owed();
590 if owed.is_some() {
591 self.io.sync_dir(&self.meta_dir())?;
592 }
593 Ok(owed.take())
594 }
595
596 fn sweep_leftovers(&self) -> std::io::Result<()> {
600 let locks = self.meta_dir().join("locks");
601 let mut stack = vec![self.root.clone()];
602 while let Some(dir) = stack.pop() {
603 for entry in self.io.list_dir(&dir)? {
604 let path = dir.join(&entry.name);
605 if entry.is_dir {
606 if path != locks {
607 stack.push(path);
608 }
609 } else if is_temp_name(&entry.name) {
610 match self.io.remove_file(&path) {
611 Ok(()) => {}
612 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
613 Err(e) => return Err(e),
614 }
615 }
616 }
617 }
618 Ok(())
619 }
620
621 fn ensure_whole(&self) -> Result<(), BackendError> {
635 if self.owed().is_some() {
636 return Err(BackendError::CommitNotApplied {
637 detail: "the removal of the last commit's record is not synced yet; \
638 loading the mem makes it good"
639 .to_string(),
640 });
641 }
642 let record = self.record_path();
643 if !self.io.exists(&record).map_err(BackendError::Io)? {
644 return Ok(());
645 }
646 let lock = self.lock_file();
647 if path_lock::holds_another(&lock) {
652 return Err(BackendError::CommitNotApplied {
653 detail: "the mem holds a commit that is in progress or was cut off, and this \
654 operation holds another mem's write lock, so it does not wait for it; \
655 loading the mem completes it"
656 .to_string(),
657 });
658 }
659 match self.wait_for_write_lock(&lock) {
664 Ok(None) => path_lock::release(&lock),
665 Ok(Some(wait)) => {
666 if self.io.exists(&record).map_err(BackendError::Io)? {
667 return Err(self.lock_wait_passed(wait));
668 }
669 }
670 Err(_) => {}
671 }
672 if !self.io.exists(&record).map_err(BackendError::Io)? {
673 return Ok(());
674 }
675 Err(BackendError::CommitNotApplied {
676 detail: "the mem holds a commit that was cut off; loading the mem completes it"
677 .to_string(),
678 })
679 }
680
681 fn has_leftovers(&self) -> bool {
685 let locks = self.meta_dir().join("locks");
686 let mut stack = vec![self.root.clone()];
687 while let Some(dir) = stack.pop() {
688 let Ok(entries) = self.io.list_dir(&dir) else {
689 continue;
690 };
691 for entry in entries {
692 let path = dir.join(&entry.name);
693 if entry.is_dir {
694 if path != locks {
695 stack.push(path);
696 }
697 } else if is_temp_name(&entry.name) {
698 return true;
699 }
700 }
701 }
702 false
703 }
704
705 fn complete_decided_commit(&self) -> Result<Option<CompletedCommit>, BackendError> {
709 let record_path = self.record_path();
710 let Some(bytes) = self.io.read(&record_path).map_err(BackendError::Io)? else {
711 return Ok(None);
712 };
713 let unreadable = |why: String| {
714 BackendError::Other(format!(
715 "commit record {} cannot be read ({why}); the mem holds a decided commit \
716 that cannot be completed",
717 record_path.display()
718 ))
719 };
720 let record: CommitRecord =
721 serde_json::from_slice(&bytes).map_err(|e| unreadable(e.to_string()))?;
722 if record.v != 1 {
723 return Err(unreadable(format!("unknown record version {}", record.v)));
724 }
725 for op in &record.ops {
728 normalise_rel_path(Path::new(op.path())).map_err(|e| unreadable(e.to_string()))?;
729 if let RecordOp::Upsert { tmp, .. } = op {
730 normalise_rel_path(Path::new(tmp)).map_err(|e| unreadable(e.to_string()))?;
731 }
732 }
733 self.apply_record(&record)
734 .map_err(|e| BackendError::CommitNotApplied {
735 detail: e.to_string(),
736 })?;
737 let _ = self.sweep_leftovers();
738 Ok(Some(CompletedCommit {
739 files: record.ops.iter().map(|op| op.path().to_string()).collect(),
740 }))
741 }
742
743 fn commit_staged_set(
748 &self,
749 ops: HashMap<String, PendingState>,
750 records: &[Provenance],
751 ) -> Result<CommitId, BackendError> {
752 if self.owed().is_some() {
755 return Err(BackendError::Other(
756 "an earlier commit of this mem is applied but not yet durable; \
757 the mem must be loaded, which finishes it, before it is written again"
758 .to_string(),
759 ));
760 }
761
762 match self.io.exists(&self.record_path()) {
765 Ok(false) => {}
766 Ok(true) => {
767 return Err(BackendError::Other(
768 "an earlier commit of this mem is decided and not yet applied; \
769 the mem must be loaded, which completes it, before it is written again"
770 .to_string(),
771 ));
772 }
773 Err(e) => return Err(BackendError::Io(e)),
774 }
775
776 let mut ops: Vec<(String, PendingState)> = ops.into_iter().collect();
779 ops.sort_by(|a, b| a.0.cmp(&b.0));
780
781 let mut attempt = Attempt::default();
785 let record = match self.prepare_commit(&ops, records, &mut attempt) {
786 Ok(record) => record,
787 Err(e) => {
788 self.abandon(&attempt);
789 return Err(BackendError::Io(e));
790 }
791 };
792
793 let not_applied = |e: std::io::Error| BackendError::CommitNotApplied {
797 detail: e.to_string(),
798 };
799 self.apply_record(&record).map_err(not_applied)?;
800 Ok(make_commit_id())
801 }
802
803 fn read_source(
807 &self,
808 pending: &Pending,
809 rel_key: &str,
810 ) -> Result<Option<Vec<u8>>, BackendError> {
811 if let Some(PendingState::Upsert(bytes)) = pending.ops.get(rel_key) {
812 return Ok(Some(bytes.clone()));
813 }
814 if let Some(PendingState::Delete) = pending.ops.get(rel_key) {
815 return Ok(None);
816 }
817 let full = self.root.join(rel_key);
818 match std::fs::read(&full) {
819 Ok(bytes) => Ok(Some(bytes)),
820 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
821 Err(e) => Err(BackendError::Io(e)),
822 }
823 }
824}
825
826pub(crate) fn refuse_cut_off_commit(root: &Path) -> Result<(), BackendError> {
832 FilesystemBackend::new(root.to_path_buf()).ensure_whole()
833}
834
835pub(crate) fn refuse_cut_off_commit_within(
839 root: &Path,
840 limit: Option<std::time::Duration>,
841) -> Result<(), BackendError> {
842 let backend = FilesystemBackend::new(root.to_path_buf());
843 backend.set_lock_wait(limit);
844 backend.ensure_whole()
845}
846
847pub fn normalise_rel_path(rel_path: &Path) -> Result<String, BackendError> {
853 if rel_path.as_os_str().is_empty() {
854 return Err(BackendError::Path("mem-relative path is empty".to_string()));
855 }
856 let mut parts: Vec<String> = Vec::new();
857 for component in rel_path.components() {
858 use std::path::Component;
859 match component {
860 Component::Normal(s) => match s.to_str() {
861 Some(p) if !p.is_empty() => parts.push(p.to_string()),
862 _ => {
863 return Err(BackendError::Path(format!(
864 "non-utf-8 or empty path component in {}",
865 rel_path.display()
866 )));
867 }
868 },
869 Component::CurDir => continue,
870 Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
871 return Err(BackendError::Path(format!(
872 "path traversal or absolute component in {}",
873 rel_path.display()
874 )));
875 }
876 }
877 }
878 if parts.is_empty() {
879 return Err(BackendError::Path(
880 "mem-relative path is empty after normalisation".to_string(),
881 ));
882 }
883 Ok(parts.join("/"))
884}
885
886impl crate::backend::MemBackend for FilesystemBackend {
887 fn list_entities(&self) -> Result<Vec<PathBuf>, BackendError> {
888 self.ensure_whole()?;
889 let mut out = Vec::new();
890 if !self.root.exists() {
891 return Ok(out);
892 }
893 walk_for_md(&self.root, &self.root, &mut out)?;
894 Ok(out)
895 }
896
897 fn current_head(&self) -> Result<Option<String>, BackendError> {
911 if std::fs::symlink_metadata(self.record_path()).is_ok() || self.owed().is_some() {
919 return Ok(Some(COMMIT_PENDING_HEAD.to_string()));
920 }
921 let log_path = crate::filesystem::changelog::changelog_path(&self.root);
922 let raw = match std::fs::read_to_string(&log_path) {
923 Ok(s) => s,
924 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
925 Err(e) => {
926 return Err(BackendError::Other(format!(
927 "reading folder changelog {}: {e}",
928 log_path.display()
929 )));
930 }
931 };
932 let last_ts = raw
933 .lines()
934 .rev()
935 .filter_map(|line| {
936 let trimmed = line.trim();
937 if trimmed.is_empty() {
938 return None;
939 }
940 serde_json::from_str::<serde_json::Value>(trimmed)
941 .ok()?
942 .get("ts")?
943 .as_str()
944 .map(str::to_string)
945 })
946 .next();
947 Ok(last_ts)
948 }
949
950 fn write_lock_path(&self) -> Option<PathBuf> {
959 Some(self.lock_file())
960 }
961
962 fn read_entity(&self, rel_path: &Path) -> Result<Option<Vec<u8>>, BackendError> {
963 let key = normalise_rel_path(rel_path)?;
964 let pending = self.pending.lock().map_err(|_| {
965 BackendError::Other("filesystem writer pending state poisoned".to_string())
966 })?;
967 if let Some(state) = pending.ops.get(&key) {
968 return Ok(match state {
969 PendingState::Upsert(bytes) => Some(bytes.clone()),
970 PendingState::Delete => None,
971 });
972 }
973 drop(pending);
974 self.ensure_whole()?;
975 let full = self.root.join(&key);
976 match std::fs::read(&full) {
977 Ok(bytes) => Ok(Some(bytes)),
978 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
979 Err(e) => Err(BackendError::Io(e)),
980 }
981 }
982
983 fn storage_present(&self) -> Result<bool, BackendError> {
991 Ok(self.root.is_dir())
992 }
993
994 fn entity_exists(&self, rel_path: &Path) -> Result<bool, BackendError> {
995 let key = normalise_rel_path(rel_path)?;
996 let pending = self.pending.lock().map_err(|_| {
997 BackendError::Other("filesystem writer pending state poisoned".to_string())
998 })?;
999 if let Some(state) = pending.ops.get(&key) {
1000 return Ok(matches!(state, PendingState::Upsert(_)));
1001 }
1002 drop(pending);
1003 self.ensure_whole()?;
1004 match std::fs::symlink_metadata(self.root.join(&key)) {
1005 Ok(md) => Ok(md.is_file()),
1006 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1007 Err(e) => Err(BackendError::Io(e)),
1008 }
1009 }
1010
1011 fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError> {
1012 let key = normalise_rel_path(rel_path)?;
1013 refuse_unwritable(&self.root, &key)?;
1014 let mut pending = self.pending.lock().map_err(|_| {
1015 BackendError::Path("filesystem writer pending state poisoned".to_string())
1016 })?;
1017 pending
1018 .ops
1019 .insert(key, PendingState::Upsert(content.to_vec()));
1020 Ok(())
1021 }
1022
1023 fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError> {
1024 let key = normalise_rel_path(rel_path)?;
1025 refuse_unwritable(&self.root, &key)?;
1026 let mut pending = self.pending.lock().map_err(|_| {
1027 BackendError::Path("filesystem writer pending state poisoned".to_string())
1028 })?;
1029 pending.ops.insert(key, PendingState::Delete);
1030 Ok(())
1031 }
1032
1033 fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError> {
1034 let from_key = normalise_rel_path(from)?;
1035 let to_key = normalise_rel_path(to)?;
1036 refuse_unwritable(&self.root, &from_key)?;
1037 refuse_unwritable(&self.root, &to_key)?;
1038 let mut pending = self.pending.lock().map_err(|_| {
1039 BackendError::Path("filesystem writer pending state poisoned".to_string())
1040 })?;
1041
1042 match pending.ops.get(&to_key) {
1045 Some(PendingState::Upsert(_)) => {
1046 return Err(BackendError::Path(format!(
1047 "move target {} already has a pending write",
1048 to.display()
1049 )));
1050 }
1051 Some(PendingState::Delete) => {}
1052 None => {
1053 if self.read_source(&pending, &to_key)?.is_some() {
1054 return Err(BackendError::Path(format!(
1055 "move target {} already exists",
1056 to.display()
1057 )));
1058 }
1059 }
1060 }
1061
1062 let bytes = match pending.ops.remove(&from_key) {
1063 Some(PendingState::Upsert(b)) => b,
1064 Some(PendingState::Delete) => {
1065 pending.ops.insert(from_key, PendingState::Delete);
1066 return Err(BackendError::Path(format!(
1067 "move source {} is already pending deletion",
1068 from.display()
1069 )));
1070 }
1071 None => match self.read_source(&pending, &from_key)? {
1072 Some(b) => b,
1073 None => {
1074 return Err(BackendError::Path(format!(
1075 "move source {} does not exist",
1076 from.display()
1077 )));
1078 }
1079 },
1080 };
1081
1082 pending.ops.insert(from_key, PendingState::Delete);
1083 pending.ops.insert(to_key, PendingState::Upsert(bytes));
1084 Ok(())
1085 }
1086
1087 fn discard_pending(&self) -> Result<(), BackendError> {
1088 let mut pending = self.pending.lock().map_err(|_| {
1091 BackendError::Other("filesystem writer pending state poisoned".to_string())
1092 })?;
1093 pending.clear();
1094 Ok(())
1095 }
1096
1097 fn commit(&self, _message: &str, _ctx: &CommitContext<'_>) -> Result<CommitId, BackendError> {
1098 let mut pending = self.pending.lock().map_err(|_| {
1099 BackendError::Path("filesystem writer pending state poisoned".to_string())
1100 })?;
1101 let staged = std::mem::replace(&mut *pending, Pending::new());
1105 if staged.ops.is_empty() && staged.records.is_empty() {
1106 return Ok(make_commit_id());
1107 }
1108
1109 self.commit_staged_set(staged.ops, &staged.records)
1110 }
1111
1112 fn set_lock_wait(&self, limit: Option<std::time::Duration>) {
1113 if let Ok(mut wait) = self.lock_wait.lock() {
1114 *wait = Some(limit);
1115 }
1116 }
1117
1118 fn lock_wait(&self) -> Option<Option<std::time::Duration>> {
1119 Some(self.lock_wait_limit().0)
1120 }
1121
1122 fn complete_interrupted_commit(&self) -> Result<Option<CompletedCommit>, BackendError> {
1132 if let Some(files) =
1136 self.sync_record_removal()
1137 .map_err(|e| BackendError::CommitNotApplied {
1138 detail: e.to_string(),
1139 })?
1140 {
1141 return Ok(Some(CompletedCommit { files }));
1142 }
1143 let lock = self.lock_file();
1144 if self
1145 .io
1146 .exists(&self.record_path())
1147 .map_err(BackendError::Io)?
1148 {
1149 if path_lock::holds_another(&lock) {
1156 return match path_lock::try_acquire(&lock) {
1157 Ok(true) => {
1158 let result = self.complete_decided_commit();
1159 path_lock::release(&lock);
1160 result
1161 }
1162 _ => Err(BackendError::CommitNotApplied {
1163 detail: "the mem holds a commit in progress and another writer holds \
1164 its lock; loading the mem completes it once the lock is free"
1165 .to_string(),
1166 }),
1167 };
1168 }
1169 let locked = match self.wait_for_write_lock(&lock) {
1176 Ok(None) => true,
1177 Ok(Some(wait)) => {
1178 if !self
1181 .io
1182 .exists(&self.record_path())
1183 .map_err(BackendError::Io)?
1184 {
1185 return Ok(None);
1186 }
1187 return Err(self.lock_wait_passed(wait));
1188 }
1189 Err(_) => false,
1190 };
1191 let result = self.complete_decided_commit();
1192 if locked {
1193 path_lock::release(&lock);
1194 }
1195 return result;
1196 }
1197 if self.has_leftovers() && matches!(path_lock::try_acquire(&lock), Ok(true)) {
1200 let result = if self
1205 .io
1206 .exists(&self.record_path())
1207 .map_err(BackendError::Io)?
1208 {
1209 self.complete_decided_commit()
1210 } else {
1211 let _ = self.sweep_leftovers();
1212 Ok(None)
1213 };
1214 path_lock::release(&lock);
1215 return result;
1216 }
1217 Ok(None)
1218 }
1219
1220 fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
1221 let config_path = self.root.join(crate::mem::MEM_META_DIR).join("config.json");
1225 match std::fs::read(&config_path) {
1226 Ok(bytes) => Ok(Some(bytes)),
1227 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
1228 Err(e) => Err(BackendError::Io(e)),
1229 }
1230 }
1231
1232 fn write_mem_config(
1233 &self,
1234 bytes: &[u8],
1235 _ctx: &crate::vcs::CommitContext<'_>,
1236 ) -> Result<(), BackendError> {
1237 let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
1244 std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
1245 refuse_symlinked_meta(&self.root)?;
1246 let _lock = ConfigLock::take(self.config_lock_file())?;
1247 replace_file(&memstead_dir.join("config.json"), bytes)
1248 }
1249
1250 fn write_mem_config_cas(
1257 &self,
1258 expected: Option<&[u8]>,
1259 bytes: &[u8],
1260 _ctx: &crate::vcs::CommitContext<'_>,
1261 ) -> Result<bool, BackendError> {
1262 let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
1263 std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
1264 let config_path = memstead_dir.join("config.json");
1265 refuse_symlinked_meta(&self.root)?;
1270 let _lock = ConfigLock::take(self.config_lock_file())?;
1271
1272 let current = match std::fs::read(&config_path) {
1273 Ok(b) => Some(b),
1274 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
1275 Err(e) => return Err(BackendError::Io(e)),
1276 };
1277 if let Some(expected) = expected
1278 && current.as_deref() != Some(expected)
1279 {
1280 return Ok(false);
1281 }
1282 replace_file(&config_path, bytes).map(|_| true)
1283 }
1284
1285 fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
1286 self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
1289 }
1290
1291 fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
1292 <Self as MemBackend>::write_entity(
1297 self,
1298 Path::new(crate::anchor::ANCHOR_SIDECAR_PATH),
1299 bytes,
1300 )
1301 }
1302
1303 fn stage_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
1304 let mut pending = self.pending.lock().map_err(|_| {
1305 BackendError::Other("filesystem writer pending state poisoned".to_string())
1306 })?;
1307 pending.records.push(record.clone());
1308 Ok(())
1309 }
1310
1311 fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
1312 self.commit_staged_set(HashMap::new(), std::slice::from_ref(record))
1319 .map(|_| ())
1320 }
1321
1322 fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError> {
1323 self.ensure_whole()?;
1324 let log_path = changelog_path(&self.root);
1325 let raw = match std::fs::read_to_string(&log_path) {
1326 Ok(s) => s,
1327 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
1328 Err(e) => return Err(BackendError::Io(e)),
1329 };
1330 let mut out = Vec::new();
1331 for line in raw.lines() {
1332 let trimmed = line.trim();
1333 if trimmed.is_empty() {
1334 continue;
1335 }
1336 let value: serde_json::Value = match serde_json::from_str(trimmed) {
1337 Ok(v) => v,
1338 Err(_) => continue,
1339 };
1340 let ts_str = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
1341 if let Some(c) = cursor
1342 && ts_str <= c
1343 {
1344 continue;
1345 }
1346 let timestamp = parse_rfc3339_utc(ts_str).unwrap_or(std::time::UNIX_EPOCH);
1347 let kind = value
1348 .get("kind")
1349 .and_then(|v| v.as_str())
1350 .and_then(ProvenanceKind::parse)
1351 .unwrap_or(ProvenanceKind::Update);
1352 let entity = value
1353 .get("entity")
1354 .and_then(|v| v.as_str())
1355 .map(|s| s.to_string());
1356 let actor = value
1357 .get("actor")
1358 .and_then(|v| v.as_str())
1359 .and_then(Actor::from_trailer)
1360 .unwrap_or(Actor::Unknown);
1361 let client = value
1362 .get("client")
1363 .and_then(|v| v.as_str())
1364 .and_then(parse_client_id);
1365 let note = value
1366 .get("note")
1367 .and_then(|v| v.as_str())
1368 .map(|s| s.to_string());
1369 let logical_operation_id = value
1370 .get("logical_op")
1371 .and_then(|v| v.as_str())
1372 .map(|s| s.to_string());
1373 let mut record = Provenance::new(timestamp, kind, entity, actor, client, note);
1374 if let Some(id) = logical_operation_id {
1375 record = record.with_logical_operation_id(id);
1376 }
1377 if let Some(from) = value.get("renamed_from").and_then(|v| v.as_str()) {
1378 record = record.with_renamed_from(from.to_string());
1379 }
1380 if let Some(role) = value
1381 .get("role")
1382 .and_then(|v| v.as_str())
1383 .and_then(crate::vcs::Role::from_wire)
1384 {
1385 record = record.with_role(role);
1386 }
1387 record = record.with_identity(
1388 value
1389 .get("identity")
1390 .and_then(|v| v.as_str())
1391 .map(|s| s.to_string()),
1392 );
1393 out.push(record);
1394 }
1395 Ok(out)
1396 }
1397}
1398
1399fn walk_for_md(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), BackendError> {
1407 let entries = match std::fs::read_dir(dir) {
1408 Ok(e) => e,
1409 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
1410 Err(e) => return Err(BackendError::Io(e)),
1411 };
1412 for entry in entries {
1413 let entry = entry.map_err(BackendError::Io)?;
1414 let path = entry.path();
1415 let file_type = entry.file_type().map_err(BackendError::Io)?;
1416 if file_type.is_dir() {
1417 let name = entry.file_name();
1418 if name == crate::mem::MEM_META_DIR {
1419 continue;
1420 }
1421 if crate::mem::is_nested_mem_root(&path) {
1423 continue;
1424 }
1425 walk_for_md(root, &path, out)?;
1426 } else if file_type.is_file()
1427 && crate::filesystem::changelog::is_entity_file(&path)
1428 && let Ok(rel) = path.strip_prefix(root)
1429 {
1430 out.push(rel.to_path_buf());
1431 }
1432 }
1433 Ok(())
1434}
1435
1436fn change_entry(record: &Provenance) -> ChangeEntry<'_> {
1438 let kind: MutationKind = record.kind.into();
1439 ChangeEntry {
1440 kind,
1441 entity: record.entity.as_deref(),
1442 actor: record.actor,
1443 client: record.client.as_ref(),
1444 note: record.note.as_deref(),
1445 logical_operation_id: record.logical_operation_id.as_deref(),
1446 role: record.role,
1447 identity: record.identity.as_deref(),
1448 renamed_from: record.renamed_from.as_deref(),
1449 }
1450}
1451
1452fn sibling_key(key: &str, tmp: &Path) -> String {
1455 let name = tmp
1456 .file_name()
1457 .map(|n| n.to_string_lossy().into_owned())
1458 .unwrap_or_default();
1459 match key.rsplit_once('/') {
1460 Some((dir, _)) => format!("{dir}/{name}"),
1461 None => name,
1462 }
1463}
1464
1465fn is_temp_name(name: &str) -> bool {
1468 let Some(rest) = name.strip_prefix('.') else {
1469 return false;
1470 };
1471 let Some((target, suffix)) = rest.rsplit_once(".tmp.") else {
1472 return false;
1473 };
1474 let Some((nanos, counter)) = suffix.split_once('-') else {
1475 return false;
1476 };
1477 let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit());
1478 !target.is_empty() && hex(nanos) && hex(counter)
1479}
1480
1481fn make_tmp_path(target: &Path) -> PathBuf {
1486 let name = target
1487 .file_name()
1488 .map(|n| n.to_string_lossy().to_string())
1489 .unwrap_or_else(|| "_".to_string());
1490 let suffix = unique_suffix();
1491 let tmp_name = format!(".{name}.tmp.{suffix}");
1492 target.with_file_name(tmp_name)
1493}
1494
1495static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
1496static COMMIT_COUNTER: AtomicU64 = AtomicU64::new(0);
1497
1498fn unique_suffix() -> String {
1499 let nanos = std::time::SystemTime::now()
1500 .duration_since(std::time::UNIX_EPOCH)
1501 .map(|d| d.as_nanos())
1502 .unwrap_or(0);
1503 let counter = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
1504 format!("{nanos:x}-{counter:x}")
1505}
1506
1507pub(crate) fn make_commit_id() -> CommitId {
1515 let nanos = std::time::SystemTime::now()
1516 .duration_since(std::time::UNIX_EPOCH)
1517 .map(|d| d.as_nanos())
1518 .unwrap_or(0);
1519 let counter = COMMIT_COUNTER.fetch_add(1, Ordering::Relaxed);
1520 format!("{nanos:032x}{counter:016x}")
1521}
1522
1523#[cfg(test)]
1524mod commit_point_tests;
1525#[cfg(test)]
1526pub(crate) mod fault_io;
1527#[cfg(test)]
1528mod folder_drift_tests;
1529pub(crate) mod io;
1530#[cfg(test)]
1531mod tests;
1532
1533fn replace_file(path: &Path, bytes: &[u8]) -> Result<(), BackendError> {
1537 use std::io::Write as _;
1538 let dir = path
1539 .parent()
1540 .ok_or_else(|| BackendError::Path(format!("{} has no parent", path.display())))?;
1541 let name = path
1542 .file_name()
1543 .ok_or_else(|| BackendError::Path(format!("{} has no file name", path.display())))?;
1544 let mut tmp_name = name.to_os_string();
1545 tmp_name.push(format!(".tmp-{}", lock_token()));
1546 let tmp = dir.join(tmp_name);
1547 let written = (|| -> std::io::Result<()> {
1548 let mut f = std::fs::File::create(&tmp)?;
1549 f.write_all(bytes)?;
1550 f.sync_all()?;
1551 std::fs::rename(&tmp, path)?;
1552 RealIo.sync_dir(dir)
1553 })();
1554 if written.is_err() {
1555 let _ = std::fs::remove_file(&tmp);
1556 }
1557 written.map_err(BackendError::Io)
1558}
1559
1560fn lock_token() -> String {
1562 use std::sync::atomic::{AtomicU64, Ordering};
1563 static SEQ: AtomicU64 = AtomicU64::new(0);
1564 let nanos = std::time::SystemTime::now()
1565 .duration_since(std::time::UNIX_EPOCH)
1566 .map(|d| d.as_nanos())
1567 .unwrap_or(0);
1568 format!(
1569 "{}-{}-{}",
1570 std::process::id(),
1571 nanos,
1572 SEQ.fetch_add(1, Ordering::Relaxed)
1573 )
1574}
1575
1576fn symlink_on_path(root: &Path, key: &str) -> std::io::Result<Option<PathBuf>> {
1580 let mut at = root.to_path_buf();
1581 for part in Path::new(key).components() {
1582 at.push(part);
1583 match std::fs::symlink_metadata(&at) {
1584 Ok(md) if md.file_type().is_symlink() => return Ok(Some(at)),
1585 Ok(md) if !md.is_dir() => return Ok(None),
1587 Ok(_) => {}
1588 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1589 Err(e) => return Err(e),
1590 }
1591 }
1592 Ok(None)
1593}
1594
1595fn refuse_symlinked(root: &Path, key: &str) -> Result<(), BackendError> {
1597 match symlink_on_path(root, key).map_err(BackendError::Io)? {
1598 Some(link) => Err(BackendError::Path(format!(
1599 "{key} passes through the symbolic link {}; a mem writes only inside its own directory",
1600 link.display()
1601 ))),
1602 None => Ok(()),
1603 }
1604}
1605
1606struct ConfigLock(PathBuf);
1608
1609impl ConfigLock {
1610 fn take(path: PathBuf) -> Result<Self, BackendError> {
1611 path_lock::acquire(&path).map_err(BackendError::Io)?;
1612 Ok(Self(path))
1613 }
1614}
1615
1616impl Drop for ConfigLock {
1617 fn drop(&mut self) {
1618 path_lock::release(&self.0);
1619 }
1620}
1621
1622const WRITABLE_META_PATHS: &[&str] = &[
1626 crate::anchor::ANCHOR_SIDECAR_PATH,
1627 crate::derivation::DERIVATION_SIDECAR_PATH,
1628 crate::ops::proposal::PROPOSAL_RECORD_PATH,
1629];
1630
1631fn refuse_unwritable(root: &Path, key: &str) -> Result<(), BackendError> {
1634 let meta = format!("{}/", crate::mem::MEM_META_DIR);
1635 if key.starts_with(&meta) && !WRITABLE_META_PATHS.contains(&key) {
1636 return Err(BackendError::Path(format!(
1637 "{key} is the backend's own file; only {} are written through entity paths",
1638 WRITABLE_META_PATHS.join(", ")
1639 )));
1640 }
1641 refuse_symlinked(root, key)
1642}
1643
1644fn refuse_symlinked_meta(root: &Path) -> Result<(), BackendError> {
1647 refuse_symlinked(root, crate::mem::MEM_META_DIR)
1648}