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    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    /// Metadata-class existence probe: pending buffer first (same
224    /// precedence as `read_entity`), then one `symlink_metadata` call —
225    /// no file open, no byte read.
226    /// The mem root directory exists. A folder mount whose path is
227    /// gone (a moved checkout, a mem never materialised) lists zero
228    /// entities exactly like an empty one; this is how boot tells the
229    /// two apart.
230    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        // Drop the in-memory op buffer without replaying it. The
310        // atomic batch path calls this to roll back staged writes when
311        // a later item refuses the whole batch.
312        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        // Folder backend reads `<root>/.memstead/config.json`.
342        // Missing file → Ok(None); other IO errors propagate as
343        // BackendError.
344        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        // Folder backend writes `<root>/.memstead/config.json` to disk.
358        // Creates the `.memstead/` directory if missing. Existing config
359        // is overwritten — caller's responsibility to gate against
360        // overwrites if that's the contract (the unified
361        // `mem_management::create_mem` Step 4 already does the
362        // refusal-to-overwrite check upstream).
363        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    /// Compare-and-set under an exclusive lock file, which is what makes the
370    /// check and the write one step. `create_new` on the
371    /// lock is the atomic primitive: exactly one process wins it, so no other
372    /// engine can slip a write between this one's compare and its write.
373    ///
374    /// A stale lock (a process killed mid-write) is broken after a short wait
375    /// rather than blocking forever: a config write that hangs is its own
376    /// outage, and the compare inside still refuses to overwrite content it
377    /// did not observe. A hand edit made in that window is still detected,
378    /// because the compare reads the file, not the lock.
379    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                    // 50 x 10ms. Past that the holder is presumed dead: a
403                    // config write is milliseconds of work, so half a second
404                    // of contention is not a busy writer.
405                    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        // Release on every exit path, including the mismatch return.
423        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        // Read via the entity path so a staged (pending) sidecar write is
448        // visible before its commit, symmetric with the other backends.
449        self.read_entity(Path::new(crate::anchor::ANCHOR_SIDECAR_PATH))
450    }
451
452    fn write_anchors_sidecar(&self, bytes: &[u8]) -> Result<(), BackendError> {
453        // Stage into the same op buffer entity writes use so the sidecar
454        // rides the entity mutation's commit. `list_entities`
455        // (`walk_for_md`) skips `.memstead/`, so it never lists as an
456        // entity.
457        <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        // Monotonic variant: the last-line `ts` is this backend's
477        // drift cursor (`current_head()`), so same-millisecond commits
478        // must still advance it — see `append_change_monotonic`.
479        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
556/// Walk `dir` for `.md` files, accumulating mem-relative paths in
557/// `out`. Skips the mem's `.memstead/` umbrella so the engine never
558/// confuses changelog / config / schema files with entity-bearing
559/// markdown, and `README.md` — repository documentation beside the
560/// entity files, never an entity (mirrors the entity-source walker's
561/// skip; entities are slug-named after their titles, so no legitimate
562/// entity file carries this name).
563fn 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
590/// Write `bytes` to `target` atomically: write to a sibling temp file
591/// then rename. Creates parent directories as needed. The temp file
592/// shares the target's parent so the rename is same-fs (atomic on
593/// POSIX). On rename failure, the temp file is best-effort removed.
594fn 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
609/// Build a sibling temp path of the form `.<name>.tmp.<suffix>` next
610/// to `target`. The leading dot keeps the temp file out of the way of
611/// directory listings; the suffix combines UNIX-nanos with a process-
612/// scoped counter so concurrent writes never collide.
613fn 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
635/// `pub(crate)` so the in-memory backend mints the same synthetic
636/// write-id shape (UNIX-nanos + counter, hex) the folder backend
637/// produces — both are history-free backends and must hand callers an
638/// identically-shaped opaque identity. It is NOT a change cursor:
639/// the change feed's cursor is an RFC3339 timestamp, and passing this
640/// token as `since` refuses with `INVALID_CURSOR` (it would otherwise
641/// sort below every timestamp and replay the whole history).
642pub(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;