Skip to main content

memstead_base/storage/
filesystem.rs

1//! Filesystem-backed [`MemBackend`](crate::backend::MemBackend) — the
2//! gix-free companion to `memstead_git_branch::storage::git_tree::GitTreeBackend`.
3//! Used by filesystem mems, where entities live as plain files under a
4//! workspace root and there is no commit history.
5//!
6//! ## Buffer + commit
7//!
8//! Mutations buffer in memory until [`FilesystemBackend::commit`].
9//! Per-path final-state collapse mirrors the git-tree adapter: a chain
10//! of write/delete ops on the same path collapses to a single terminal
11//! state by commit time. Move resolves at call-time into a
12//! `Delete(from)` + `Upsert(to, bytes)` pair — bytes come from the
13//! pending buffer when present, otherwise from the live file on disk.
14//!
15//! ## Atomicity
16//!
17//! Per-file writes are atomic via write-to-temp + rename. Multi-op
18//! commits are *not* transactional: a failure partway through leaves
19//! earlier ops landed and later ops untouched. Single-writer is
20//! assumed; concurrent writers against the same mem are out of scope.
21//!
22//! ## CommitId
23//!
24//! There is no commit history. [`Self::commit`] returns a synthetic
25//! opaque id (UNIX-nanos + counter, hex) to satisfy the trait surface.
26//! Callers that pass this through `_hash` envelopes get a unique
27//! per-commit token but no CAS guarantee — there is no parent state to
28//! compare against.
29
30use 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
44/// Per-path final state for the buffered op log. Move operations
45/// resolve at call time into a `Delete(from)` + `Upsert(to, bytes)`
46/// pair, mirroring the git-tree adapter so commit-time replay only
47/// ever sees these two terminal states.
48enum PendingState {
49    Upsert(Vec<u8>),
50    Delete,
51}
52
53/// In-flight mutation buffer. Cleared on a successful commit.
54struct 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
70/// Filesystem-backed [`MemBackend`]. Mutations buffer in memory until
71/// [`Self::commit`]; commit replays them against the directory at
72/// `root` with per-file write-to-temp + rename atomicity.
73pub struct FilesystemBackend {
74    root: PathBuf,
75    pending: Mutex<Pending>,
76}
77
78impl FilesystemBackend {
79    /// Build a writer rooted at `root`. The directory must already
80    /// exist; sub-directories are created lazily as commits run.
81    pub fn new(root: PathBuf) -> Self {
82        Self {
83            root,
84            pending: Mutex::new(Pending::new()),
85        }
86    }
87
88    /// Read the current bytes at `rel_key` from the buffered op log if
89    /// present, otherwise from disk. Used by `move_entity` to resolve
90    /// the source content.
91    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
111/// Normalise a mem-relative path to a forward-slash key. Rejects
112/// empty paths, absolute paths, and any path that escapes the mem
113/// root via `..`. Mirrors `git_tree::normalise_rel_path` so the two
114/// adapters reject the same inputs.
115///
116/// `pub(crate)` so the in-memory backend reuses the exact same
117/// rejection rules — a third hand-rolled copy would be free to drift.
118pub(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    /// Folder-mem drift cursor: the changelog's last-line `ts` — the
163    /// same RFC3339-millisecond dialect `folder_changes_since` accepts
164    /// as its cursor, so drift heads feed straight into delta reads.
165    /// Every mutation appends a changelog line (in this process or a
166    /// sibling's), advancing the cursor; the drift check then treats
167    /// the advance exactly like a git-branch tip move. Absent
168    /// changelog (a mem never mutated through the engine) keeps the
169    /// historical no-drift-signal `None`. Appends go through
170    /// `append_change_monotonic`, so the cursor strictly advances even
171    /// for same-millisecond commits; only a read-append race between
172    /// separate processes can momentarily share a cursor value —
173    /// detection then rides the next append.
174    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    /// Inside the mem's own `.memstead/`, in a self-ignoring `locks/`
205    /// subtree, so every process that mounts this folder, from any
206    /// workspace, contends on the same file.
207    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    /// Metadata-class existence probe: pending buffer first (same
231    /// precedence as `read_entity`), then one `symlink_metadata` call —
232    /// no file open, no byte read.
233    /// The mem root directory exists. A folder mount whose path is
234    /// gone (a moved checkout, a mem never materialised) lists zero
235    /// entities exactly like an empty one; this is how boot tells the
236    /// two apart.
237    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        // Drop the in-memory op buffer without replaying it. The
317        // atomic batch path calls this to roll back staged writes when
318        // a later item refuses the whole batch.
319        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        // Folder backend reads `<root>/.memstead/config.json`.
349        // Missing file → Ok(None); other IO errors propagate as
350        // BackendError.
351        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        // Folder backend writes `<root>/.memstead/config.json` to disk.
365        // Creates the `.memstead/` directory if missing. Existing config
366        // is overwritten — caller's responsibility to gate against
367        // overwrites if that's the contract (the unified
368        // `mem_management::create_mem` Step 4 already does the
369        // refusal-to-overwrite check upstream).
370        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    /// Compare-and-set under an exclusive lock file, which is what makes the
377    /// check and the write one step. `create_new` on the
378    /// lock is the atomic primitive: exactly one process wins it, so no other
379    /// engine can slip a write between this one's compare and its write.
380    ///
381    /// A stale lock (a process killed mid-write) is broken after a short wait
382    /// rather than blocking forever: a config write that hangs is its own
383    /// outage, and the compare inside still refuses to overwrite content it
384    /// did not observe. A hand edit made in that window is still detected,
385    /// because the compare reads the file, not the lock.
386    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                    // 50 x 10ms. Past that the holder is presumed dead: a
410                    // config write is milliseconds of work, so half a second
411                    // of contention is not a busy writer.
412                    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        // Release on every exit path, including the mismatch return.
430        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        // Read via the entity path so a staged (pending) sidecar write is
455        // visible before its commit, symmetric with the other backends.
456        self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
457    }
458
459    fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
460        // Stage into the same op buffer entity writes use so the sidecar
461        // rides the entity mutation's commit. `list_entities`
462        // (`walk_for_md`) skips `.memstead/`, so it never lists as an
463        // entity.
464        <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        // Monotonic variant: the last-line `ts` is this backend's
484        // drift cursor (`current_head()`), so same-millisecond commits
485        // must still advance it — see `append_change_monotonic`.
486        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
563/// Walk `dir` for `.md` files, accumulating mem-relative paths in
564/// `out`. Skips the mem's `.memstead/` umbrella so the engine never
565/// confuses changelog / config / schema files with entity-bearing
566/// markdown, and `README.md` — repository documentation beside the
567/// entity files, never an entity (mirrors the entity-source walker's
568/// skip; entities are slug-named after their titles, so no legitimate
569/// entity file carries this name).
570fn 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
597/// Write `bytes` to `target` atomically: write to a sibling temp file
598/// then rename. Creates parent directories as needed. The temp file
599/// shares the target's parent so the rename is same-fs (atomic on
600/// POSIX). On rename failure, the temp file is best-effort removed.
601fn 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
616/// Build a sibling temp path of the form `.<name>.tmp.<suffix>` next
617/// to `target`. The leading dot keeps the temp file out of the way of
618/// directory listings; the suffix combines UNIX-nanos with a process-
619/// scoped counter so concurrent writes never collide.
620fn 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
642/// `pub(crate)` so the in-memory backend mints the same synthetic
643/// write-id shape (UNIX-nanos + counter, hex) the folder backend
644/// produces — both are history-free backends and must hand callers an
645/// identically-shaped opaque identity. It is NOT a change cursor:
646/// the change feed's cursor is an RFC3339 timestamp, and passing this
647/// token as `since` refuses with `INVALID_CURSOR` (it would otherwise
648/// sort below every timestamp and replay the whole history).
649pub(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;