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 read_entity(&self, rel_path: &Path) -> Result<Option<Vec<u8>>, BackendError> {
205 let key = normalise_rel_path(rel_path)?;
206 let pending = self.pending.lock().map_err(|_| {
207 BackendError::Other("filesystem writer pending state poisoned".to_string())
208 })?;
209 if let Some(state) = pending.ops.get(&key) {
210 return Ok(match state {
211 PendingState::Upsert(bytes) => Some(bytes.clone()),
212 PendingState::Delete => None,
213 });
214 }
215 let full = self.root.join(&key);
216 match std::fs::read(&full) {
217 Ok(bytes) => Ok(Some(bytes)),
218 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
219 Err(e) => Err(BackendError::Io(e)),
220 }
221 }
222
223 fn storage_present(&self) -> Result<bool, BackendError> {
231 Ok(self.root.is_dir())
232 }
233
234 fn entity_exists(&self, rel_path: &Path) -> Result<bool, BackendError> {
235 let key = normalise_rel_path(rel_path)?;
236 let pending = self.pending.lock().map_err(|_| {
237 BackendError::Other("filesystem writer pending state poisoned".to_string())
238 })?;
239 if let Some(state) = pending.ops.get(&key) {
240 return Ok(matches!(state, PendingState::Upsert(_)));
241 }
242 drop(pending);
243 match std::fs::symlink_metadata(self.root.join(&key)) {
244 Ok(md) => Ok(md.is_file()),
245 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
246 Err(e) => Err(BackendError::Io(e)),
247 }
248 }
249
250 fn write_entity(&self, rel_path: &Path, content: &[u8]) -> Result<(), BackendError> {
251 let key = normalise_rel_path(rel_path)?;
252 let mut pending = self.pending.lock().map_err(|_| {
253 BackendError::Path("filesystem writer pending state poisoned".to_string())
254 })?;
255 pending
256 .ops
257 .insert(key, PendingState::Upsert(content.to_vec()));
258 Ok(())
259 }
260
261 fn delete_entity(&self, rel_path: &Path) -> Result<(), BackendError> {
262 let key = normalise_rel_path(rel_path)?;
263 let mut pending = self.pending.lock().map_err(|_| {
264 BackendError::Path("filesystem writer pending state poisoned".to_string())
265 })?;
266 pending.ops.insert(key, PendingState::Delete);
267 Ok(())
268 }
269
270 fn move_entity(&self, from: &Path, to: &Path) -> Result<(), BackendError> {
271 let from_key = normalise_rel_path(from)?;
272 let to_key = normalise_rel_path(to)?;
273 let mut pending = self.pending.lock().map_err(|_| {
274 BackendError::Path("filesystem writer pending state poisoned".to_string())
275 })?;
276
277 let bytes = match pending.ops.remove(&from_key) {
278 Some(PendingState::Upsert(b)) => b,
279 Some(PendingState::Delete) => {
280 pending.ops.insert(from_key, PendingState::Delete);
281 return Err(BackendError::Path(format!(
282 "move source {} is already pending deletion",
283 from.display()
284 )));
285 }
286 None => match self.read_source(&pending, &from_key)? {
287 Some(b) => b,
288 None => {
289 return Err(BackendError::Path(format!(
290 "move source {} does not exist",
291 from.display()
292 )));
293 }
294 },
295 };
296
297 if matches!(pending.ops.get(&to_key), Some(PendingState::Upsert(_))) {
298 return Err(BackendError::Path(format!(
299 "move target {} already has a pending write",
300 to.display()
301 )));
302 }
303 pending.ops.insert(from_key, PendingState::Delete);
304 pending.ops.insert(to_key, PendingState::Upsert(bytes));
305 Ok(())
306 }
307
308 fn discard_pending(&self) -> Result<(), BackendError> {
309 let mut pending = self.pending.lock().map_err(|_| {
313 BackendError::Other("filesystem writer pending state poisoned".to_string())
314 })?;
315 pending.clear();
316 Ok(())
317 }
318
319 fn commit(&self, _message: &str, _ctx: &CommitContext<'_>) -> Result<CommitId, BackendError> {
320 let mut pending = self.pending.lock().map_err(|_| {
321 BackendError::Path("filesystem writer pending state poisoned".to_string())
322 })?;
323
324 for (key, state) in pending.ops.iter() {
325 let target = self.root.join(key);
326 match state {
327 PendingState::Upsert(bytes) => atomic_write(&target, bytes)?,
328 PendingState::Delete => match std::fs::remove_file(&target) {
329 Ok(()) => {}
330 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
331 Err(e) => return Err(BackendError::Io(e)),
332 },
333 }
334 }
335
336 pending.clear();
337 Ok(make_commit_id())
338 }
339
340 fn read_mem_config(&self) -> Result<Option<Vec<u8>>, BackendError> {
341 let config_path = self.root.join(crate::mem::MEM_META_DIR).join("config.json");
345 match std::fs::read(&config_path) {
346 Ok(bytes) => Ok(Some(bytes)),
347 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
348 Err(e) => Err(BackendError::Io(e)),
349 }
350 }
351
352 fn write_mem_config(
353 &self,
354 bytes: &[u8],
355 _ctx: &crate::vcs::CommitContext<'_>,
356 ) -> Result<(), BackendError> {
357 let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
364 std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
365 let config_path = memstead_dir.join("config.json");
366 std::fs::write(&config_path, bytes).map_err(BackendError::Io)
367 }
368
369 fn write_mem_config_cas(
380 &self,
381 expected: Option<&[u8]>,
382 bytes: &[u8],
383 _ctx: &crate::vcs::CommitContext<'_>,
384 ) -> Result<bool, BackendError> {
385 let memstead_dir = self.root.join(crate::mem::MEM_META_DIR);
386 std::fs::create_dir_all(&memstead_dir).map_err(BackendError::Io)?;
387 let config_path = memstead_dir.join("config.json");
388 let lock_path = memstead_dir.join("config.json.lock");
389
390 let mut held = None;
391 for attempt in 0..50 {
392 match std::fs::OpenOptions::new()
393 .write(true)
394 .create_new(true)
395 .open(&lock_path)
396 {
397 Ok(f) => {
398 held = Some(f);
399 break;
400 }
401 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
402 if attempt == 49 {
406 let _ = std::fs::remove_file(&lock_path);
407 }
408 std::thread::sleep(std::time::Duration::from_millis(10));
409 }
410 Err(e) => return Err(BackendError::Io(e)),
411 }
412 }
413 let _lock = match held {
414 Some(f) => f,
415 None => std::fs::OpenOptions::new()
416 .write(true)
417 .create(true)
418 .truncate(true)
419 .open(&lock_path)
420 .map_err(BackendError::Io)?,
421 };
422 let release = || {
424 let _ = std::fs::remove_file(&lock_path);
425 };
426
427 let current = match std::fs::read(&config_path) {
428 Ok(b) => Some(b),
429 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
430 Err(e) => {
431 release();
432 return Err(BackendError::Io(e));
433 }
434 };
435 if let Some(expected) = expected
436 && current.as_deref() != Some(expected)
437 {
438 release();
439 return Ok(false);
440 }
441 let result = std::fs::write(&config_path, bytes).map_err(BackendError::Io);
442 release();
443 result.map(|_| true)
444 }
445
446 fn read_anchors_sidecar(&self) -> Result<Option<Vec<u8>>, BackendError> {
447 self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
450 }
451
452 fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
453 <Self as MemBackend>::write_entity(
458 self,
459 Path::new(crate::anchor::ANCHOR_SIDECAR_PATH),
460 bytes,
461 )
462 }
463
464 fn append_provenance(&self, record: &Provenance) -> Result<(), BackendError> {
465 let kind: MutationKind = record.kind.into();
466 let entry = ChangeEntry {
467 kind,
468 entity: record.entity.as_deref(),
469 actor: record.actor,
470 client: record.client.as_ref(),
471 note: record.note.as_deref(),
472 logical_operation_id: record.logical_operation_id.as_deref(),
473 role: record.role,
474 identity: record.identity.as_deref(),
475 };
476 changelog::append_change_monotonic(&self.root, &entry, record.timestamp)
480 .map_err(|e| BackendError::Other(format!("changelog append: {e}")))
481 }
482
483 fn read_provenance(&self, cursor: Option<&str>) -> Result<Vec<Provenance>, BackendError> {
484 let log_path = changelog_path(&self.root);
485 let raw = match std::fs::read_to_string(&log_path) {
486 Ok(s) => s,
487 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
488 Err(e) => return Err(BackendError::Io(e)),
489 };
490 let mut out = Vec::new();
491 for line in raw.lines() {
492 let trimmed = line.trim();
493 if trimmed.is_empty() {
494 continue;
495 }
496 let value: serde_json::Value = match serde_json::from_str(trimmed) {
497 Ok(v) => v,
498 Err(_) => continue,
499 };
500 let ts_str = value.get("ts").and_then(|v| v.as_str()).unwrap_or("");
501 if let Some(c) = cursor
502 && ts_str <= c
503 {
504 continue;
505 }
506 let timestamp = parse_rfc3339_utc(ts_str).unwrap_or(std::time::UNIX_EPOCH);
507 let kind = value
508 .get("kind")
509 .and_then(|v| v.as_str())
510 .and_then(ProvenanceKind::parse)
511 .unwrap_or(ProvenanceKind::Update);
512 let entity = value
513 .get("entity")
514 .and_then(|v| v.as_str())
515 .map(|s| s.to_string());
516 let actor = value
517 .get("actor")
518 .and_then(|v| v.as_str())
519 .and_then(Actor::from_trailer)
520 .unwrap_or(Actor::Unknown);
521 let client = value
522 .get("client")
523 .and_then(|v| v.as_str())
524 .and_then(parse_client_id);
525 let note = value
526 .get("note")
527 .and_then(|v| v.as_str())
528 .map(|s| s.to_string());
529 let logical_operation_id = value
530 .get("logical_op")
531 .and_then(|v| v.as_str())
532 .map(|s| s.to_string());
533 let mut record = Provenance::new(timestamp, kind, entity, actor, client, note);
534 if let Some(id) = logical_operation_id {
535 record = record.with_logical_operation_id(id);
536 }
537 if let Some(role) = value
538 .get("role")
539 .and_then(|v| v.as_str())
540 .and_then(crate::vcs::Role::from_wire)
541 {
542 record = record.with_role(role);
543 }
544 record = record.with_identity(
545 value
546 .get("identity")
547 .and_then(|v| v.as_str())
548 .map(|s| s.to_string()),
549 );
550 out.push(record);
551 }
552 Ok(out)
553 }
554}
555
556fn walk_for_md(root: &Path, dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), BackendError> {
564 let entries = match std::fs::read_dir(dir) {
565 Ok(e) => e,
566 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
567 Err(e) => return Err(BackendError::Io(e)),
568 };
569 for entry in entries {
570 let entry = entry.map_err(BackendError::Io)?;
571 let path = entry.path();
572 let file_type = entry.file_type().map_err(BackendError::Io)?;
573 if file_type.is_dir() {
574 let name = entry.file_name();
575 if name == crate::mem::MEM_META_DIR {
576 continue;
577 }
578 walk_for_md(root, &path, out)?;
579 } else if file_type.is_file()
580 && path.extension().and_then(|s| s.to_str()) == Some("md")
581 && entry.file_name() != "README.md"
582 && let Ok(rel) = path.strip_prefix(root)
583 {
584 out.push(rel.to_path_buf());
585 }
586 }
587 Ok(())
588}
589
590fn atomic_write(target: &Path, bytes: &[u8]) -> Result<(), BackendError> {
595 if let Some(parent) = target.parent()
596 && !parent.as_os_str().is_empty()
597 {
598 std::fs::create_dir_all(parent).map_err(BackendError::Io)?;
599 }
600 let tmp = make_tmp_path(target);
601 std::fs::write(&tmp, bytes).map_err(BackendError::Io)?;
602 if let Err(e) = std::fs::rename(&tmp, target) {
603 let _ = std::fs::remove_file(&tmp);
604 return Err(BackendError::Io(e));
605 }
606 Ok(())
607}
608
609fn make_tmp_path(target: &Path) -> PathBuf {
614 let name = target
615 .file_name()
616 .map(|n| n.to_string_lossy().to_string())
617 .unwrap_or_else(|| "_".to_string());
618 let suffix = unique_suffix();
619 let tmp_name = format!(".{name}.tmp.{suffix}");
620 target.with_file_name(tmp_name)
621}
622
623static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
624static COMMIT_COUNTER: AtomicU64 = AtomicU64::new(0);
625
626fn unique_suffix() -> String {
627 let nanos = std::time::SystemTime::now()
628 .duration_since(std::time::UNIX_EPOCH)
629 .map(|d| d.as_nanos())
630 .unwrap_or(0);
631 let counter = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
632 format!("{nanos:x}-{counter:x}")
633}
634
635pub(crate) fn make_commit_id() -> CommitId {
643 let nanos = std::time::SystemTime::now()
644 .duration_since(std::time::UNIX_EPOCH)
645 .map(|d| d.as_nanos())
646 .unwrap_or(0);
647 let counter = COMMIT_COUNTER.fetch_add(1, Ordering::Relaxed);
648 format!("{nanos:032x}{counter:016x}")
649}
650
651#[cfg(test)]
652mod folder_drift_tests;
653#[cfg(test)]
654mod tests;