1use std::collections::HashMap;
31use std::path::{Path, PathBuf};
32use std::sync::Mutex;
33use std::sync::atomic::{AtomicU64, Ordering};
34
35use super::CommitId;
36use crate::backend::BackendError;
37use crate::backend::MemBackend;
38use crate::filesystem::changelog::{
39 self, ChangeEntry, MutationKind, changelog_path, parse_rfc3339_utc,
40};
41use crate::provenance::{Provenance, ProvenanceKind};
42use crate::vcs::{Actor, CommitContext, parse_client_id};
43
44enum PendingState {
49 Upsert(Vec<u8>),
50 Delete,
51}
52
53struct Pending {
55 ops: HashMap<String, PendingState>,
56}
57
58impl Pending {
59 fn new() -> Self {
60 Self {
61 ops: HashMap::new(),
62 }
63 }
64
65 fn clear(&mut self) {
66 self.ops.clear();
67 }
68}
69
70pub struct FilesystemBackend {
74 root: PathBuf,
75 pending: Mutex<Pending>,
76}
77
78impl FilesystemBackend {
79 pub fn new(root: PathBuf) -> Self {
82 Self {
83 root,
84 pending: Mutex::new(Pending::new()),
85 }
86 }
87
88 fn read_source(
92 &self,
93 pending: &Pending,
94 rel_key: &str,
95 ) -> Result<Option<Vec<u8>>, BackendError> {
96 if let Some(PendingState::Upsert(bytes)) = pending.ops.get(rel_key) {
97 return Ok(Some(bytes.clone()));
98 }
99 if let Some(PendingState::Delete) = pending.ops.get(rel_key) {
100 return Ok(None);
101 }
102 let full = self.root.join(rel_key);
103 match std::fs::read(&full) {
104 Ok(bytes) => Ok(Some(bytes)),
105 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
106 Err(e) => Err(BackendError::Io(e)),
107 }
108 }
109}
110
111pub(crate) fn normalise_rel_path(rel_path: &Path) -> Result<String, BackendError> {
119 if rel_path.as_os_str().is_empty() {
120 return Err(BackendError::Path("mem-relative path is empty".to_string()));
121 }
122 let mut parts: Vec<String> = Vec::new();
123 for component in rel_path.components() {
124 use std::path::Component;
125 match component {
126 Component::Normal(s) => match s.to_str() {
127 Some(p) if !p.is_empty() => parts.push(p.to_string()),
128 _ => {
129 return Err(BackendError::Path(format!(
130 "non-utf-8 or empty path component in {}",
131 rel_path.display()
132 )));
133 }
134 },
135 Component::CurDir => continue,
136 Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
137 return Err(BackendError::Path(format!(
138 "path traversal or absolute component in {}",
139 rel_path.display()
140 )));
141 }
142 }
143 }
144 if parts.is_empty() {
145 return Err(BackendError::Path(
146 "mem-relative path is empty after normalisation".to_string(),
147 ));
148 }
149 Ok(parts.join("/"))
150}
151
152impl crate::backend::MemBackend for FilesystemBackend {
153 fn list_entities(&self) -> Result<Vec<PathBuf>, BackendError> {
154 let mut out = Vec::new();
155 if !self.root.exists() {
156 return Ok(out);
157 }
158 walk_for_md(&self.root, &self.root, &mut out)?;
159 Ok(out)
160 }
161
162 fn current_head(&self) -> Result<Option<String>, BackendError> {
175 let log_path = crate::filesystem::changelog::changelog_path(&self.root);
176 let raw = match std::fs::read_to_string(&log_path) {
177 Ok(s) => s,
178 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
179 Err(e) => {
180 return Err(BackendError::Other(format!(
181 "reading folder changelog {}: {e}",
182 log_path.display()
183 )));
184 }
185 };
186 let last_ts = raw
187 .lines()
188 .rev()
189 .filter_map(|line| {
190 let trimmed = line.trim();
191 if trimmed.is_empty() {
192 return None;
193 }
194 serde_json::from_str::<serde_json::Value>(trimmed)
195 .ok()?
196 .get("ts")?
197 .as_str()
198 .map(str::to_string)
199 })
200 .next();
201 Ok(last_ts)
202 }
203
204 fn write_lock_path(&self) -> Option<PathBuf> {
208 Some(self.root.join(".memstead").join("locks").join("write.lock"))
209 }
210
211 fn read_entity(&self, rel_path: &Path) -> Result<Option<Vec<u8>>, BackendError> {
212 let key = normalise_rel_path(rel_path)?;
213 let pending = self.pending.lock().map_err(|_| {
214 BackendError::Other("filesystem writer pending state poisoned".to_string())
215 })?;
216 if let Some(state) = pending.ops.get(&key) {
217 return Ok(match state {
218 PendingState::Upsert(bytes) => Some(bytes.clone()),
219 PendingState::Delete => None,
220 });
221 }
222 let full = self.root.join(&key);
223 match std::fs::read(&full) {
224 Ok(bytes) => Ok(Some(bytes)),
225 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
226 Err(e) => Err(BackendError::Io(e)),
227 }
228 }
229
230 fn storage_present(&self) -> Result<bool, BackendError> {
238 Ok(self.root.is_dir())
239 }
240
241 fn entity_exists(&self, rel_path: &Path) -> Result<bool, BackendError> {
242 let key = normalise_rel_path(rel_path)?;
243 let pending = self.pending.lock().map_err(|_| {
244 BackendError::Other("filesystem writer pending state poisoned".to_string())
245 })?;
246 if let Some(state) = pending.ops.get(&key) {
247 return Ok(matches!(state, PendingState::Upsert(_)));
248 }
249 drop(pending);
250 match std::fs::symlink_metadata(self.root.join(&key)) {
251 Ok(md) => Ok(md.is_file()),
252 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
253 Err(e) => Err(BackendError::Io(e)),
254 }
255 }
256
257 fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError> {
258 let key = normalise_rel_path(rel_path)?;
259 let mut pending = self.pending.lock().map_err(|_| {
260 BackendError::Path("filesystem writer pending state poisoned".to_string())
261 })?;
262 pending
263 .ops
264 .insert(key, PendingState::Upsert(content.to_vec()));
265 Ok(())
266 }
267
268 fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError> {
269 let key = normalise_rel_path(rel_path)?;
270 let mut pending = self.pending.lock().map_err(|_| {
271 BackendError::Path("filesystem writer pending state poisoned".to_string())
272 })?;
273 pending.ops.insert(key, PendingState::Delete);
274 Ok(())
275 }
276
277 fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError> {
278 let from_key = normalise_rel_path(from)?;
279 let to_key = normalise_rel_path(to)?;
280 let mut pending = self.pending.lock().map_err(|_| {
281 BackendError::Path("filesystem writer pending state poisoned".to_string())
282 })?;
283
284 let bytes = match pending.ops.remove(&from_key) {
285 Some(PendingState::Upsert(b)) => b,
286 Some(PendingState::Delete) => {
287 pending.ops.insert(from_key, PendingState::Delete);
288 return Err(BackendError::Path(format!(
289 "move source {} is already pending deletion",
290 from.display()
291 )));
292 }
293 None => match self.read_source(&pending, &from_key)? {
294 Some(b) => b,
295 None => {
296 return Err(BackendError::Path(format!(
297 "move source {} does not exist",
298 from.display()
299 )));
300 }
301 },
302 };
303
304 if matches!(pending.ops.get(&to_key), Some(PendingState::Upsert(_))) {
305 return Err(BackendError::Path(format!(
306 "move target {} already has a pending write",
307 to.display()
308 )));
309 }
310 pending.ops.insert(from_key, PendingState::Delete);
311 pending.ops.insert(to_key, PendingState::Upsert(bytes));
312 Ok(())
313 }
314
315 fn discard_pending(&self) -> Result<(), BackendError> {
316 let mut pending = self.pending.lock().map_err(|_| {
320 BackendError::Other("filesystem writer pending state poisoned".to_string())
321 })?;
322 pending.clear();
323 Ok(())
324 }
325
326 fn commit(&self, _message: &str, _ctx: &CommitContext<'_>) -> Result<CommitId, BackendError> {
327 let mut pending = self.pending.lock().map_err(|_| {
328 BackendError::Path("filesystem writer pending state poisoned".to_string())
329 })?;
330
331 for (key, state) in pending.ops.iter() {
332 let target = self.root.join(key);
333 match state {
334 PendingState::Upsert(bytes) => atomic_write(&target, bytes)?,
335 PendingState::Delete => match std::fs::remove_file(&target) {
336 Ok(()) => {}
337 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
338 Err(e) => return Err(BackendError::Io(e)),
339 },
340 }
341 }
342
343 pending.clear();
344 Ok(make_commit_id())
345 }
346
347 fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
348 let config_path = self.root.join(crate::mem::MEM_META_DIR).join("config.json");
352 match std::fs::read(&config_path) {
353 Ok(bytes) => Ok(Some(bytes)),
354 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
355 Err(e) => Err(BackendError::Io(e)),
356 }
357 }
358
359 fn write_mem_config(
360 &self,
361 bytes: &[u8],
362 _ctx: &crate::vcs::CommitContext<'_>,
363 ) -> Result<(), BackendError> {
364 let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
371 std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
372 let config_path = memstead_dir.join("config.json");
373 std::fs::write(&config_path, bytes).map_err(BackendError::Io)
374 }
375
376 fn write_mem_config_cas(
387 &self,
388 expected: Option<&[u8]>,
389 bytes: &[u8],
390 _ctx: &crate::vcs::CommitContext<'_>,
391 ) -> Result<bool, BackendError> {
392 let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
393 std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
394 let config_path = memstead_dir.join("config.json");
395 let lock_path = memstead_dir.join("config.json.lock");
396
397 let mut held = None;
398 for attempt in 0..50 {
399 match std::fs::OpenOptions::new()
400 .write(true)
401 .create_new(true)
402 .open(&lock_path)
403 {
404 Ok(f) => {
405 held = Some(f);
406 break;
407 }
408 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
409 if attempt == 49 {
413 let _ = std::fs::remove_file(&lock_path);
414 }
415 std::thread::sleep(std::time::Duration::from_millis(10));
416 }
417 Err(e) => return Err(BackendError::Io(e)),
418 }
419 }
420 let _lock = match held {
421 Some(f) => f,
422 None => std::fs::OpenOptions::new()
423 .write(true)
424 .create(true)
425 .truncate(true)
426 .open(&lock_path)
427 .map_err(BackendError::Io)?,
428 };
429 let release = || {
431 let _ = std::fs::remove_file(&lock_path);
432 };
433
434 let current = match std::fs::read(&config_path) {
435 Ok(b) => Some(b),
436 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
437 Err(e) => {
438 release();
439 return Err(BackendError::Io(e));
440 }
441 };
442 if let Some(expected) = expected
443 && current.as_deref() != Some(expected)
444 {
445 release();
446 return Ok(false);
447 }
448 let result = std::fs::write(&config_path, bytes).map_err(BackendError::Io);
449 release();
450 result.map(|_| true)
451 }
452
453 fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
454 self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
457 }
458
459 fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
460 <Self as MemBackend>::write_entity(
465 self,
466 Path::new(crate::anchor::ANCHOR_SIDECAR_PATH),
467 bytes,
468 )
469 }
470
471 fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
472 let kind: MutationKind = record.kind.into();
473 let entry = ChangeEntry {
474 kind,
475 entity: record.entity.as_deref(),
476 actor: record.actor,
477 client: record.client.as_ref(),
478 note: record.note.as_deref(),
479 logical_operation_id: record.logical_operation_id.as_deref(),
480 role: record.role,
481 identity: record.identity.as_deref(),
482 };
483 changelog::append_change_monotonic(&self.root, &entry, record.timestamp)
487 .map_err(|e| BackendError::Other(format!("changelog append: {e}")))
488 }
489
490 fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError> {
491 let log_path = changelog_path(&self.root);
492 let raw = match std::fs::read_to_string(&log_path) {
493 Ok(s) => s,
494 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
495 Err(e) => return Err(BackendError::Io(e)),
496 };
497 let mut out = Vec::new();
498 for line in raw.lines() {
499 let trimmed = line.trim();
500 if trimmed.is_empty() {
501 continue;
502 }
503 let value: serde_json::Value = match serde_json::from_str(trimmed) {
504 Ok(v) => v,
505 Err(_) => continue,
506 };
507 let ts_str = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
508 if let Some(c) = cursor
509 && ts_str <= c
510 {
511 continue;
512 }
513 let timestamp = parse_rfc3339_utc(ts_str).unwrap_or(std::time::UNIX_EPOCH);
514 let kind = value
515 .get("kind")
516 .and_then(|v| v.as_str())
517 .and_then(ProvenanceKind::parse)
518 .unwrap_or(ProvenanceKind::Update);
519 let entity = value
520 .get("entity")
521 .and_then(|v| v.as_str())
522 .map(|s| s.to_string());
523 let actor = value
524 .get("actor")
525 .and_then(|v| v.as_str())
526 .and_then(Actor::from_trailer)
527 .unwrap_or(Actor::Unknown);
528 let client = value
529 .get("client")
530 .and_then(|v| v.as_str())
531 .and_then(parse_client_id);
532 let note = value
533 .get("note")
534 .and_then(|v| v.as_str())
535 .map(|s| s.to_string());
536 let logical_operation_id = value
537 .get("logical_op")
538 .and_then(|v| v.as_str())
539 .map(|s| s.to_string());
540 let mut record = Provenance::new(timestamp, kind, entity, actor, client, note);
541 if let Some(id) = logical_operation_id {
542 record = record.with_logical_operation_id(id);
543 }
544 if let Some(role) = value
545 .get("role")
546 .and_then(|v| v.as_str())
547 .and_then(crate::vcs::Role::from_wire)
548 {
549 record = record.with_role(role);
550 }
551 record = record.with_identity(
552 value
553 .get("identity")
554 .and_then(|v| v.as_str())
555 .map(|s| s.to_string()),
556 );
557 out.push(record);
558 }
559 Ok(out)
560 }
561}
562
563fn walk_for_md(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), BackendError> {
571 let entries = match std::fs::read_dir(dir) {
572 Ok(e) => e,
573 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
574 Err(e) => return Err(BackendError::Io(e)),
575 };
576 for entry in entries {
577 let entry = entry.map_err(BackendError::Io)?;
578 let path = entry.path();
579 let file_type = entry.file_type().map_err(BackendError::Io)?;
580 if file_type.is_dir() {
581 let name = entry.file_name();
582 if name == crate::mem::MEM_META_DIR {
583 continue;
584 }
585 walk_for_md(root, &path, out)?;
586 } else if file_type.is_file()
587 && path.extension().and_then(|s| s.to_str()) == Some("md")
588 && entry.file_name() != "README.md"
589 && let Ok(rel) = path.strip_prefix(root)
590 {
591 out.push(rel.to_path_buf());
592 }
593 }
594 Ok(())
595}
596
597fn atomic_write(target: &Path, bytes: &[u8]) -> Result<(), BackendError> {
602 if let Some(parent) = target.parent()
603 && !parent.as_os_str().is_empty()
604 {
605 std::fs::create_dir_all(parent).map_err(BackendError::Io)?;
606 }
607 let tmp = make_tmp_path(target);
608 std::fs::write(&tmp, bytes).map_err(BackendError::Io)?;
609 if let Err(e) = std::fs::rename(&tmp, target) {
610 let _ = std::fs::remove_file(&tmp);
611 return Err(BackendError::Io(e));
612 }
613 Ok(())
614}
615
616fn make_tmp_path(target: &Path) -> PathBuf {
621 let name = target
622 .file_name()
623 .map(|n| n.to_string_lossy().to_string())
624 .unwrap_or_else(|| "_".to_string());
625 let suffix = unique_suffix();
626 let tmp_name = format!(".{name}.tmp.{suffix}");
627 target.with_file_name(tmp_name)
628}
629
630static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
631static COMMIT_COUNTER: AtomicU64 = AtomicU64::new(0);
632
633fn unique_suffix() -> String {
634 let nanos = std::time::SystemTime::now()
635 .duration_since(std::time::UNIX_EPOCH)
636 .map(|d| d.as_nanos())
637 .unwrap_or(0);
638 let counter = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
639 format!("{nanos:x}-{counter:x}")
640}
641
642pub(crate) fn make_commit_id() -> CommitId {
650 let nanos = std::time::SystemTime::now()
651 .duration_since(std::time::UNIX_EPOCH)
652 .map(|d| d.as_nanos())
653 .unwrap_or(0);
654 let counter = COMMIT_COUNTER.fetch_add(1, Ordering::Relaxed);
655 format!("{nanos:032x}{counter:016x}")
656}
657
658#[cfg(test)]
659mod folder_drift_tests;
660#[cfg(test)]
661mod tests;