fs-transaction 0.2.1

Multi-file filesystem transactions that survive a crash: staged change sets, all-or-nothing apply, write-ahead recovery
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
//! An in-memory [`Storage`] backend.
//!
//! Available on every target this crate compiles for — including
//! `wasm32-unknown-unknown`, where it needs no browser API at all. Useful for
//! tests and sandboxes, and for clients (a WASM frontend with no direct disk
//! access) that load a workspace into memory up front and persist it
//! out-of-band (export/import, a network round-trip, OPFS as a bulk blob).

use std::collections::{HashMap, HashSet};
use std::io::{self, Error, ErrorKind};
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, RwLock};

use super::{DirEntry, FileType, Metadata, ReadStorage};

use super::{Capabilities, Storage};

/// An in-memory, clone-shared [`Storage`] backend.
///
/// Content lives behind `Arc<RwLock<_>>`, so cloning an `InMemoryFs` is cheap
/// and every clone sees the same files — the same relationship an `Arc<StdFs>`
/// has to the one real filesystem it names, but without needing the `Arc`
/// wrapper, since it's built into the type. `std::sync::RwLock` (not a
/// runtime's async lock) is deliberate: every method here runs to completion
/// without ever awaiting *inside* the critical section, so there is nothing
/// for an async lock to buy, and a plain `std::sync` primitive is the one
/// that's guaranteed to exist — and to compile — on `wasm32-unknown-unknown`,
/// which has no threads and no async-runtime assumption to lean on.
///
/// Text and binary content are stored separately (a write picks one store
/// based on whether the bytes are valid UTF-8) so that a round-trip through
/// [`export_entries`](Self::export_entries) — text only — stays plain
/// strings, the shape a JS/WASM caller wants. Directories are tracked
/// explicitly (in a `HashSet`) rather than inferred from file paths, so an
/// empty directory `create_dir_all` created still shows up in
/// [`read_dir`](ReadStorage::read_dir).
///
/// Symlinks may be added with [`add_symlink`](Self::add_symlink): reading or
/// getting [`metadata`](ReadStorage::metadata) of the link resolves to the
/// target's content, matching [`ReadStorage::metadata`]'s documented
/// "follows symlinks" contract. Resolution is a single hop, not a followed
/// chain — a symlink to a symlink is not resolved further — which is all the
/// coherence a test double needs; a real filesystem's chain-following and
/// cycle detection isn't reproduced here.
#[derive(Debug, Clone, Default)]
pub struct InMemoryFs {
    /// Text files, stored as path -> content.
    files: Arc<RwLock<HashMap<PathBuf, String>>>,
    /// Binary (non-UTF-8) files, stored as path -> bytes.
    binary_files: Arc<RwLock<HashMap<PathBuf, Vec<u8>>>>,
    /// Directories known to exist — implicitly populated by every write's
    /// parent chain, and by an explicit `create_dir_all`.
    directories: Arc<RwLock<HashSet<PathBuf>>>,
    /// Symlinks: link path -> target path. Reading the link path resolves to
    /// the target's content; the parent's `read_dir` reports the link itself
    /// as [`FileType::SYMLINK`].
    symlinks: Arc<RwLock<HashMap<PathBuf, PathBuf>>>,
}

impl InMemoryFs {
    /// An empty in-memory filesystem.
    pub fn new() -> Self {
        Self::default()
    }

    /// A filesystem pre-populated with text files (and the directories that
    /// contain them).
    pub fn with_files(entries: Vec<(PathBuf, String)>) -> Self {
        let fs = Self::new();
        {
            let mut files = fs.files.write().unwrap();
            let mut dirs = fs.directories.write().unwrap();
            for (path, content) in entries {
                insert_ancestor_dirs(&mut dirs, &path);
                files.insert(path, content);
            }
        }
        fs
    }

    /// Load files from `(path_string, content)` pairs — convenience for a
    /// caller (JS/WASM interop) that only has strings, not `PathBuf`s.
    pub fn load_from_entries(entries: Vec<(String, String)>) -> Self {
        Self::with_files(
            entries
                .into_iter()
                .map(|(path, content)| (PathBuf::from(path), content))
                .collect(),
        )
    }

    /// Every text file, as `(path_string, content)` pairs — the counterpart to
    /// [`load_from_entries`](Self::load_from_entries), for persisting a
    /// session's edits back out.
    pub fn export_entries(&self) -> Vec<(String, String)> {
        self.files
            .read()
            .unwrap()
            .iter()
            .map(|(path, content)| (path.to_string_lossy().into_owned(), content.clone()))
            .collect()
    }

    /// Every binary file, as `(path_string, content_bytes)` pairs.
    pub fn export_binary_entries(&self) -> Vec<(String, Vec<u8>)> {
        self.binary_files
            .read()
            .unwrap()
            .iter()
            .map(|(path, content)| (path.to_string_lossy().into_owned(), content.clone()))
            .collect()
    }

    /// Load binary files from `(path_string, content_bytes)` pairs.
    pub fn load_binary_entries(&self, entries: Vec<(String, Vec<u8>)>) {
        let mut binary_files = self.binary_files.write().unwrap();
        let mut dirs = self.directories.write().unwrap();
        for (path_str, content) in entries {
            let path = PathBuf::from(path_str);
            insert_ancestor_dirs(&mut dirs, &path);
            binary_files.insert(path, content);
        }
    }

    /// Every text-file path currently stored.
    pub fn list_all_files(&self) -> Vec<PathBuf> {
        self.files.read().unwrap().keys().cloned().collect()
    }

    /// Remove every file, directory, and symlink — resetting the filesystem to
    /// empty without needing a fresh `InMemoryFs` (and its own, separately
    /// shared, clones).
    pub fn clear(&self) {
        self.files.write().unwrap().clear();
        self.binary_files.write().unwrap().clear();
        self.directories.write().unwrap().clear();
        self.symlinks.write().unwrap().clear();
    }

    /// Add a symlink from `link` to `target`. Reading `link` (or its
    /// [`metadata`](ReadStorage::metadata)) resolves to `target`'s content;
    /// `link`'s entry in its parent's [`read_dir`](ReadStorage::read_dir) reports
    /// [`FileType::SYMLINK`] — the un-followed type a caller needs in order to
    /// recognize and skip it, since `metadata` itself only ever reports the
    /// followed, resolved type.
    pub fn add_symlink(&self, link: &Path, target: &Path) {
        let link = normalize_path(link);
        let target = normalize_path(target);
        insert_ancestor_dirs(&mut self.directories.write().unwrap(), &link);
        self.symlinks.write().unwrap().insert(link, target);
    }

    /// The single-hop resolution [`ReadStorage::read`], [`ReadStorage::read_to_string`],
    /// and [`ReadStorage::metadata`] all use: a symlinked path resolves to its
    /// target; anything else resolves to itself.
    fn resolve(&self, normalized: &Path) -> PathBuf {
        self.symlinks
            .read()
            .unwrap()
            .get(normalized)
            .cloned()
            .unwrap_or_else(|| normalized.to_path_buf())
    }
}

/// Strip `.` and resolve `..` lexically — the backend has no real parent
/// directories to walk, so this is the closest available analog of
/// `std::fs`'s implicit path resolution, and it's what keeps
/// `"dir/file.md"` and `"dir/sub/../file.md"` naming the same entry.
fn normalize_path(path: &Path) -> PathBuf {
    let mut components: Vec<Component> = Vec::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if !matches!(components.last(), None | Some(Component::RootDir)) {
                    components.pop();
                }
            }
            c => components.push(c),
        }
    }
    components.iter().collect()
}

/// Register every non-empty ancestor of `path` as an existing directory —
/// the implicit parent-creation a real `write` to a nested path performs via
/// `create_dir_all`.
fn insert_ancestor_dirs(dirs: &mut HashSet<PathBuf>, path: &Path) {
    let mut current = path;
    while let Some(parent) = current.parent() {
        if parent.as_os_str().is_empty() {
            break;
        }
        dirs.insert(parent.to_path_buf());
        current = parent;
    }
}

fn not_found(path: &Path) -> Error {
    Error::new(
        ErrorKind::NotFound,
        format!("not found: {}", path.display()),
    )
}

impl ReadStorage for InMemoryFs {
    async fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
        let normalized = normalize_path(path);
        let resolved = self.resolve(&normalized);
        if let Some(data) = self.binary_files.read().unwrap().get(&resolved) {
            return Ok(data.clone());
        }
        if let Some(text) = self.files.read().unwrap().get(&resolved) {
            return Ok(text.as_bytes().to_vec());
        }
        Err(not_found(path))
    }

    async fn read_to_string(&self, path: &Path) -> io::Result<String> {
        // Built on `read` rather than duplicating its lookup: this is the one
        // point of divergence from the crossfs reference, and it's a
        // correctness fix, not just a dedup — reusing `read` means a binary
        // file correctly reports `InvalidData` (mirroring
        // `std::fs::read_to_string`) instead of a misleading `NotFound`.
        let bytes = self.read(path).await?;
        String::from_utf8(bytes).map_err(|e| Error::new(ErrorKind::InvalidData, e))
    }

    async fn read_dir(&self, path: &Path) -> io::Result<Vec<DirEntry>> {
        let normalized = normalize_path(path);
        if !normalized.as_os_str().is_empty()
            && !self.directories.read().unwrap().contains(&normalized)
        {
            return Err(not_found(path));
        }

        let mut result = Vec::new();
        for entry in self.files.read().unwrap().keys() {
            if entry.parent() == Some(normalized.as_path()) {
                result.push(DirEntry::new(entry.clone(), FileType::FILE));
            }
        }
        for entry in self.binary_files.read().unwrap().keys() {
            if entry.parent() == Some(normalized.as_path()) {
                result.push(DirEntry::new(entry.clone(), FileType::FILE));
            }
        }
        // Listed by un-followed type — a caller that wants to skip symlinks
        // (rather than transparently read through them) needs exactly this,
        // since `metadata` itself only ever reports the resolved type.
        for entry in self.symlinks.read().unwrap().keys() {
            if entry.parent() == Some(normalized.as_path()) {
                result.push(DirEntry::new(entry.clone(), FileType::SYMLINK));
            }
        }
        for entry in self.directories.read().unwrap().iter() {
            if entry.parent() == Some(normalized.as_path()) && entry != &normalized {
                result.push(DirEntry::new(entry.clone(), FileType::DIR));
            }
        }
        Ok(result)
    }

    async fn metadata(&self, path: &Path) -> io::Result<Metadata> {
        let normalized = normalize_path(path);
        let resolved = self.resolve(&normalized);

        if let Some(data) = self.binary_files.read().unwrap().get(&resolved) {
            return Ok(Metadata::new(FileType::FILE, data.len() as u64, None));
        }
        if let Some(text) = self.files.read().unwrap().get(&resolved) {
            return Ok(Metadata::new(FileType::FILE, text.len() as u64, None));
        }
        if self.directories.read().unwrap().contains(&resolved) {
            return Ok(Metadata::new(FileType::DIR, 0, None));
        }
        Err(not_found(path))
    }

    // No modification-time tracking: unlike a real filesystem there is no
    // clock backing these bytes, and a fabricated timestamp (e.g. "now" on
    // every write) would claim a precision this backend cannot honor across
    // a clone or an export/import round-trip. `Metadata::modified` reports
    // `Unsupported` accordingly — an honest "this backend doesn't know",
    // exactly as it would for a real backend that genuinely lacks the field.

    // `executable` is deliberately left at the trait's default — the decline.
    // There is no bit behind these bytes, and answering `false` would claim
    // one; `None` is the honest "no such thing here".

    async fn read_link(&self, path: &Path) -> io::Result<Option<PathBuf>> {
        // This backend *does* model links, so `Ok(None)` — reserved for the
        // backend-wide decline — is never its answer: a path holding a link
        // yields the target, and anything else is an error, exactly as
        // `readlink` behaves.
        let normalized = normalize_path(path);
        if let Some(target) = self.symlinks.read().unwrap().get(&normalized) {
            return Ok(Some(target.clone()));
        }
        let occupied = self.files.read().unwrap().contains_key(&normalized)
            || self.binary_files.read().unwrap().contains_key(&normalized)
            || self.directories.read().unwrap().contains(&normalized);
        if occupied {
            return Err(Error::new(
                ErrorKind::InvalidInput,
                format!("not a symbolic link: {}", path.display()),
            ));
        }
        Err(not_found(path))
    }
}

impl Storage for InMemoryFs {
    async fn write(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
        let normalized = normalize_path(path);
        // Through the link where the path holds one, single hop — `std::fs::write`
        // opens the path and therefore follows, and this backend's reads
        // already resolve; a write that instead stored bytes *under the link's
        // own name* would leave them permanently shadowed, readable by nobody,
        // with the write reporting success. The double must not invent that.
        let resolved = self.resolve(&normalized);
        insert_ancestor_dirs(&mut self.directories.write().unwrap(), &resolved);

        // Store as text when the bytes are valid UTF-8, so `read_to_string`
        // and `export_entries` see a plain string — matching the diaryx
        // behavior this mirrors, where `write`/`read_to_string` round-tripped
        // through a text store. Non-UTF-8 content still round-trips through
        // `read`, just via the binary store instead.
        match std::str::from_utf8(contents) {
            Ok(s) => {
                self.files
                    .write()
                    .unwrap()
                    .insert(resolved.clone(), s.to_string());
                self.binary_files.write().unwrap().remove(&resolved);
            }
            Err(_) => {
                self.binary_files
                    .write()
                    .unwrap()
                    .insert(resolved.clone(), contents.to_vec());
                self.files.write().unwrap().remove(&resolved);
            }
        }
        Ok(())
    }

    async fn create_new(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
        let normalized = normalize_path(path);
        // Anything already answering to the name occupies it — a file of either
        // store, a symlink, or a directory, exactly the set `std::fs`'s
        // `O_CREAT|O_EXCL` refuses. The checks and the insert are not under one
        // lock, but nothing interleaves them on the targets this backend
        // exists for: wasm has no threads, and a multithreaded test that
        // races two `create_new` calls is testing the double, not the code
        // under test.
        let occupied = self.files.read().unwrap().contains_key(&normalized)
            || self.binary_files.read().unwrap().contains_key(&normalized)
            || self.symlinks.read().unwrap().contains_key(&normalized)
            || self.directories.read().unwrap().contains(&normalized);
        if occupied {
            return Err(Error::new(
                ErrorKind::AlreadyExists,
                format!("already exists: {}", path.display()),
            ));
        }
        self.write(path, contents).await
    }

    async fn create_dir_all(&self, path: &Path) -> io::Result<()> {
        let normalized = normalize_path(path);
        let mut dirs = self.directories.write().unwrap();
        if !normalized.as_os_str().is_empty() {
            dirs.insert(normalized.clone());
        }
        insert_ancestor_dirs(&mut dirs, &normalized);
        Ok(())
    }

    async fn remove_file(&self, path: &Path) -> io::Result<()> {
        let normalized = normalize_path(path);
        if self.files.write().unwrap().remove(&normalized).is_some() {
            return Ok(());
        }
        if self
            .binary_files
            .write()
            .unwrap()
            .remove(&normalized)
            .is_some()
        {
            return Ok(());
        }
        if self.symlinks.write().unwrap().remove(&normalized).is_some() {
            return Ok(());
        }
        Err(not_found(path))
    }

    async fn remove_dir_all(&self, path: &Path) -> io::Result<()> {
        let normalized = normalize_path(path);
        self.files
            .write()
            .unwrap()
            .retain(|p, _| !p.starts_with(&normalized));
        self.binary_files
            .write()
            .unwrap()
            .retain(|p, _| !p.starts_with(&normalized));
        self.symlinks
            .write()
            .unwrap()
            .retain(|p, _| !p.starts_with(&normalized));
        self.directories
            .write()
            .unwrap()
            .retain(|p| p != &normalized && !p.starts_with(&normalized));
        Ok(())
    }

    async fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
        let from_norm = normalize_path(from);
        let to_norm = normalize_path(to);
        if from_norm == to_norm {
            return Ok(());
        }

        let is_dir = self.directories.read().unwrap().contains(&from_norm);
        if is_dir {
            self.rename_dir(&from_norm, &to_norm, to)
        } else {
            self.rename_file(&from_norm, &to_norm, from, to).await
        }
    }

    async fn set_link(&self, path: &Path, target: &Path) -> io::Result<()> {
        // Replaces whatever is at the path, per the trait's contract: a plain
        // file gives way to the link, and an existing link is repointed. The
        // target is recorded as given, never resolved or required to exist —
        // a dangling link is an honest link.
        let normalized = normalize_path(path);
        insert_ancestor_dirs(&mut self.directories.write().unwrap(), &normalized);
        self.files.write().unwrap().remove(&normalized);
        self.binary_files.write().unwrap().remove(&normalized);
        self.symlinks
            .write()
            .unwrap()
            .insert(normalized, normalize_path(target));
        Ok(())
    }

    fn capabilities(&self) -> Capabilities {
        Capabilities::IN_MEMORY
    }

    async fn replace(&self, path: &Path, contents: &[u8]) -> io::Result<()> {
        // The default protocol stages through a temp sibling and a `rename`
        // because *that* is what makes a plain `write` atomic on a real
        // filesystem. Here, a single `write` already is the atomic step — it
        // takes the map's write lock for its entire duration, so no observer
        // ever sees a splice — so replaying the temp-then-rename dance would
        // only litter the map with a `.fstx-tmp` entry no caller asked for.
        // This is exactly the "backend whose atomic replacement is native"
        // case the default documents overriding — and overriding *here*, not
        // `write_atomic`, is what lets every protocol built on `replace`
        // (`write_atomic`'s composed default included) pick the override up.
        //
        // One faithful difference from `write`: the rename that realizes the
        // default protocol replaces the *entry* at the path, so a link there
        // gives way to the file rather than forwarding to its target — the
        // same replacement `set_link` performs in the other direction.
        self.symlinks.write().unwrap().remove(&normalize_path(path));
        self.write(path, contents).await
    }
}

impl InMemoryFs {
    fn rename_dir(&self, from_norm: &Path, to_norm: &Path, to: &Path) -> io::Result<()> {
        {
            // A *directory* rename keeps the refusal a file rename gave up:
            // renaming onto a non-directory is an error on every platform,
            // and onto a directory `std::fs::rename` is platform-divergent
            // (unix replaces only an empty one, Windows refuses outright) —
            // so the portable double refuses the lot, and nothing in this
            // crate renames a directory onto an occupied name.
            let files = self.files.read().unwrap();
            let bin = self.binary_files.read().unwrap();
            let dirs = self.directories.read().unwrap();
            let links = self.symlinks.read().unwrap();
            if files.contains_key(to_norm)
                || bin.contains_key(to_norm)
                || dirs.contains(to_norm)
                || links.contains_key(to_norm)
            {
                return Err(Error::new(
                    ErrorKind::AlreadyExists,
                    format!("destination already exists: {}", to.display()),
                ));
            }
        }

        let files_to_move: Vec<(PathBuf, String)> = self
            .files
            .read()
            .unwrap()
            .iter()
            .filter(|(p, _)| p.starts_with(from_norm))
            .map(|(p, c)| (p.clone(), c.clone()))
            .collect();
        let binaries_to_move: Vec<(PathBuf, Vec<u8>)> = self
            .binary_files
            .read()
            .unwrap()
            .iter()
            .filter(|(p, _)| p.starts_with(from_norm))
            .map(|(p, c)| (p.clone(), c.clone()))
            .collect();

        {
            let mut files = self.files.write().unwrap();
            for (old_path, content) in files_to_move {
                files.remove(&old_path);
                let relative = old_path.strip_prefix(from_norm).unwrap();
                files.insert(to_norm.join(relative), content);
            }
        }
        {
            let mut binary = self.binary_files.write().unwrap();
            for (old_path, content) in binaries_to_move {
                binary.remove(&old_path);
                let relative = old_path.strip_prefix(from_norm).unwrap();
                binary.insert(to_norm.join(relative), content);
            }
        }
        {
            let mut dirs = self.directories.write().unwrap();
            let old_dirs: Vec<PathBuf> = dirs
                .iter()
                .filter(|d| d.starts_with(from_norm))
                .cloned()
                .collect();
            for old_dir in old_dirs {
                dirs.remove(&old_dir);
                let relative = old_dir.strip_prefix(from_norm).unwrap();
                dirs.insert(to_norm.join(relative));
            }
            insert_ancestor_dirs(&mut dirs, to_norm);
        }

        Ok(())
    }

    async fn rename_file(
        &self,
        from_norm: &Path,
        to_norm: &Path,
        from: &Path,
        to: &Path,
    ) -> io::Result<()> {
        {
            let files = self.files.read().unwrap();
            let bin = self.binary_files.read().unwrap();
            let links = self.symlinks.read().unwrap();
            if !files.contains_key(from_norm)
                && !bin.contains_key(from_norm)
                && !links.contains_key(from_norm)
            {
                return Err(not_found(from));
            }
            // A directory is the one occupant a file's rename never replaces —
            // `std::fs::rename` refuses that on every platform. Any other
            // occupant gives way below, which is the mirror's whole point:
            // the default `write_atomic` publishes by renaming a staged
            // sibling *over* the target, and a rename that refused an
            // occupied destination would fail the commonest replace there is.
            if self.directories.read().unwrap().contains(to_norm) {
                return Err(Error::new(
                    ErrorKind::AlreadyExists,
                    format!("destination is a directory: {}", to.display()),
                ));
            }
        }

        if let Some(parent) = to_norm.parent() {
            self.create_dir_all(parent).await?;
        }

        // The non-directory occupant, if any, is replaced — file, binary, or
        // link alike, exactly the entry-level replacement `rename(2)` performs.
        self.files.write().unwrap().remove(to_norm);
        self.binary_files.write().unwrap().remove(to_norm);
        self.symlinks.write().unwrap().remove(to_norm);

        // A link moves as a link — the entry relocates, the target string
        // rides along unresolved, exactly as `rename(2)` treats one.
        let moved_link = self.symlinks.write().unwrap().remove(from_norm);
        if let Some(target) = moved_link {
            self.symlinks
                .write()
                .unwrap()
                .insert(to_norm.to_path_buf(), target);
            return Ok(());
        }

        // Each removal is its own statement, not an `if let`'s scrutinee: an
        // `if let SCRUTINEE { BODY }` extends the scrutinee's temporaries
        // across the whole body, so writing `if let Some(c) =
        // self.files.write().unwrap().remove(..) { self.files.write()... }`
        // would keep the first write guard alive while the body took a second
        // one on the same lock — a same-thread self-deadlock on
        // `std::sync::RwLock`, not a panic. Binding the removal to a plain
        // `let` first drops that guard before the body ever runs.
        let removed_text = self.files.write().unwrap().remove(from_norm);
        if let Some(content) = removed_text {
            self.files
                .write()
                .unwrap()
                .insert(to_norm.to_path_buf(), content);
            return Ok(());
        }
        let removed_binary = self.binary_files.write().unwrap().remove(from_norm);
        if let Some(content) = removed_binary {
            self.binary_files
                .write()
                .unwrap()
                .insert(to_norm.to_path_buf(), content);
            return Ok(());
        }
        Err(not_found(from))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::exec::block_on;

    #[test]
    fn read_write_roundtrip() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("test.md"), b"Hello, World!")).unwrap();
        assert_eq!(
            block_on(fs.read_to_string(Path::new("test.md"))).unwrap(),
            "Hello, World!"
        );
        assert!(block_on(fs.try_exists(Path::new("test.md"))).unwrap());
        block_on(fs.remove_file(Path::new("test.md"))).unwrap();
        assert!(!block_on(fs.try_exists(Path::new("test.md"))).unwrap());
    }

    #[test]
    fn binary_content_round_trips_through_read_but_not_read_to_string() {
        let fs = InMemoryFs::new();
        let invalid_utf8 = vec![0xff, 0xfe, 0xfd];
        block_on(fs.write(Path::new("bin.dat"), &invalid_utf8)).unwrap();
        assert_eq!(
            block_on(fs.read(Path::new("bin.dat"))).unwrap(),
            invalid_utf8
        );
        let err = block_on(fs.read_to_string(Path::new("bin.dat"))).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn create_dir_all_creates_parents_implicitly_via_write() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("a/b/c/file.md"), b"Content")).unwrap();
        assert!(block_on(fs.metadata(Path::new("a"))).unwrap().is_dir());
        assert!(block_on(fs.metadata(Path::new("a/b"))).unwrap().is_dir());
        assert!(block_on(fs.metadata(Path::new("a/b/c"))).unwrap().is_dir());
        assert!(block_on(fs.try_exists(Path::new("a/b/c/file.md"))).unwrap());
    }

    #[test]
    fn read_dir_returns_immediate_children_only() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("dir/file1.md"), b"1")).unwrap();
        block_on(fs.write(Path::new("dir/file2.md"), b"2")).unwrap();
        block_on(fs.write(Path::new("dir/subdir/file3.md"), b"3")).unwrap();

        let entries = block_on(fs.read_dir(Path::new("dir"))).unwrap();
        let paths: Vec<PathBuf> = entries.iter().map(|e| e.path().to_path_buf()).collect();
        assert!(paths.contains(&PathBuf::from("dir/file1.md")));
        assert!(paths.contains(&PathBuf::from("dir/file2.md")));
        assert!(paths.contains(&PathBuf::from("dir/subdir")));
        assert!(!paths.contains(&PathBuf::from("dir/subdir/file3.md")));
    }

    #[test]
    fn read_dir_of_an_untracked_directory_is_not_found() {
        // Fidelity to `std::fs::read_dir`'s contract: a path that was never
        // written to or `create_dir_all`'d is an error, not an empty listing.
        let fs = InMemoryFs::new();
        let err = block_on(fs.read_dir(Path::new("never/created"))).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::NotFound);
    }

    #[test]
    fn read_dir_of_the_root_never_errors() {
        // The root is never explicitly inserted into `directories` (it has no
        // non-empty parent to register it), so it needs its own carve-out
        // against the untracked-directory check above.
        let fs = InMemoryFs::new();
        assert!(block_on(fs.read_dir(Path::new(""))).unwrap().is_empty());
    }

    #[test]
    fn export_then_import_roundtrip() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("file1.md"), b"Content 1")).unwrap();
        block_on(fs.write(Path::new("dir/file2.md"), b"Content 2")).unwrap();

        let entries = fs.export_entries();
        let fs2 = InMemoryFs::load_from_entries(entries);

        assert_eq!(
            block_on(fs2.read_to_string(Path::new("file1.md"))).unwrap(),
            "Content 1"
        );
        assert_eq!(
            block_on(fs2.read_to_string(Path::new("dir/file2.md"))).unwrap(),
            "Content 2"
        );
    }

    #[test]
    fn path_normalization() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("dir/file.md"), b"Content")).unwrap();
        assert!(block_on(fs.try_exists(Path::new("dir/file.md"))).unwrap());
        assert!(block_on(fs.try_exists(Path::new("dir/./file.md"))).unwrap());
        assert!(block_on(fs.try_exists(Path::new("dir/subdir/../file.md"))).unwrap());
    }

    #[test]
    fn rename_moves_a_single_file() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("old.md"), b"content")).unwrap();
        block_on(fs.rename(Path::new("old.md"), Path::new("new.md"))).unwrap();
        assert!(!block_on(fs.try_exists(Path::new("old.md"))).unwrap());
        assert_eq!(
            block_on(fs.read_to_string(Path::new("new.md"))).unwrap(),
            "content"
        );
    }

    #[test]
    fn rename_moves_a_directory_and_its_contents() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("dir/a.md"), b"a")).unwrap();
        block_on(fs.write(Path::new("dir/sub/b.md"), b"b")).unwrap();

        block_on(fs.rename(Path::new("dir"), Path::new("moved"))).unwrap();

        assert!(!block_on(fs.try_exists(Path::new("dir/a.md"))).unwrap());
        assert_eq!(
            block_on(fs.read_to_string(Path::new("moved/a.md"))).unwrap(),
            "a"
        );
        assert_eq!(
            block_on(fs.read_to_string(Path::new("moved/sub/b.md"))).unwrap(),
            "b"
        );
        assert!(
            block_on(fs.metadata(Path::new("moved/sub")))
                .unwrap()
                .is_dir()
        );
    }

    #[test]
    fn rename_replaces_an_occupied_file_destination() {
        // The port doc is the contract: `rename` mirrors `std::fs::rename`,
        // which replaces an existing destination file on every platform —
        // and the default `write_atomic` publishes by renaming a staged
        // sibling over the target, so a double that refused would fail the
        // commonest replace there is.
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("a.md"), b"a")).unwrap();
        block_on(fs.write(Path::new("b.md"), b"b")).unwrap();
        block_on(fs.rename(Path::new("a.md"), Path::new("b.md"))).unwrap();
        assert!(!block_on(fs.try_exists(Path::new("a.md"))).unwrap());
        assert_eq!(block_on(fs.read_to_string(Path::new("b.md"))).unwrap(), "a");
    }

    #[test]
    fn rename_refuses_a_directory_destination() {
        // The one occupant a file's rename never replaces, on any platform.
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("a.md"), b"a")).unwrap();
        block_on(fs.create_dir_all(Path::new("dir"))).unwrap();
        let err = block_on(fs.rename(Path::new("a.md"), Path::new("dir"))).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
        assert_eq!(block_on(fs.read_to_string(Path::new("a.md"))).unwrap(), "a");
    }

    #[test]
    fn a_directory_rename_still_refuses_any_occupied_destination() {
        // Directory-onto-directory is platform-divergent in std, so the
        // portable double keeps the refusal for directories — and nothing in
        // this crate renames a directory onto an occupied name.
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("dir/a.md"), b"a")).unwrap();
        block_on(fs.write(Path::new("other/b.md"), b"b")).unwrap();
        block_on(fs.write(Path::new("file.md"), b"f")).unwrap();
        for taken in ["other", "file.md"] {
            let err = block_on(fs.rename(Path::new("dir"), Path::new(taken))).unwrap_err();
            assert_eq!(err.kind(), io::ErrorKind::AlreadyExists, "{taken}");
        }
    }

    // ---- symlinks: coherence with `ReadStorage::metadata`'s "follows symlinks"
    // contract, and with `read_dir`'s un-followed listing — the two shapes
    // diaryx_core's validator actually exercises (skip a symlink named
    // directly, and skip one discovered by scanning a directory). ----

    #[test]
    fn metadata_and_read_follow_a_symlink_to_its_target() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("real.md"), b"hello")).unwrap();
        fs.add_symlink(Path::new("link.md"), Path::new("real.md"));

        let m = block_on(fs.metadata(Path::new("link.md"))).unwrap();
        assert!(m.is_file());
        assert!(!m.is_dir());

        assert_eq!(
            block_on(fs.read_to_string(Path::new("link.md"))).unwrap(),
            "hello"
        );
    }

    #[test]
    fn read_dir_reports_a_symlink_by_its_own_unfollowed_type() {
        // This is what a directory scan (diaryx_core's orphan-file pass) uses
        // to recognize and skip a symlink without ever resolving it.
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("real.md"), b"hello")).unwrap();
        fs.add_symlink(Path::new("link.md"), Path::new("real.md"));

        let entries = block_on(fs.read_dir(Path::new(""))).unwrap();
        let link_entry = entries
            .iter()
            .find(|e| e.path() == Path::new("link.md"))
            .expect("symlink should appear in its parent's listing");
        assert!(link_entry.file_type().is_symlink());

        let real_entry = entries
            .iter()
            .find(|e| e.path() == Path::new("real.md"))
            .expect("the real file should also be listed");
        assert!(!real_entry.file_type().is_symlink());
    }

    #[test]
    fn a_symlink_to_a_missing_target_is_not_found_by_metadata() {
        let fs = InMemoryFs::new();
        fs.add_symlink(Path::new("dangling.md"), Path::new("nowhere.md"));
        let err = block_on(fs.metadata(Path::new("dangling.md"))).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::NotFound);
    }

    #[test]
    fn write_follows_a_link_to_its_target() {
        // `std::fs::write` opens and therefore follows; a double that stored
        // the bytes under the link's own name would shadow them forever
        // behind `resolve`, with the write reporting success.
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("real.md"), b"old")).unwrap();
        fs.add_symlink(Path::new("link.md"), Path::new("real.md"));

        block_on(fs.write(Path::new("link.md"), b"new")).unwrap();

        assert_eq!(
            block_on(fs.read_to_string(Path::new("real.md"))).unwrap(),
            "new",
            "the bytes must land in the target"
        );
        assert_eq!(
            block_on(fs.read_to_string(Path::new("link.md"))).unwrap(),
            "new"
        );
        assert_eq!(
            block_on(fs.read_link(Path::new("link.md"))).unwrap(),
            Some(PathBuf::from("real.md")),
            "the link itself must still stand"
        );
    }

    #[test]
    fn write_atomic_replaces_a_link_rather_than_writing_through_it() {
        // The default protocol's rename replaces the entry at the path; the
        // native override must keep that half of the contract too.
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("real.md"), b"target bytes")).unwrap();
        fs.add_symlink(Path::new("link.md"), Path::new("real.md"));

        block_on(fs.write_atomic(Path::new("link.md"), b"a file now")).unwrap();

        assert_eq!(
            block_on(fs.read_link(Path::new("link.md")))
                .unwrap_err()
                .kind(),
            io::ErrorKind::InvalidInput,
            "the link must be gone, replaced by a regular file"
        );
        assert_eq!(
            block_on(fs.read_to_string(Path::new("link.md"))).unwrap(),
            "a file now"
        );
        assert_eq!(
            block_on(fs.read_to_string(Path::new("real.md"))).unwrap(),
            "target bytes",
            "nothing may be written through the link"
        );
    }

    #[test]
    fn rename_moves_a_link_as_a_link_and_replaces_one_at_the_destination() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("real.md"), b"content")).unwrap();
        fs.add_symlink(Path::new("link.md"), Path::new("real.md"));

        block_on(fs.rename(Path::new("link.md"), Path::new("moved.md"))).unwrap();
        assert_eq!(
            block_on(fs.read_link(Path::new("moved.md"))).unwrap(),
            Some(PathBuf::from("real.md"))
        );
        assert!(!block_on(fs.try_exists(Path::new("link.md"))).unwrap());

        // A link at the destination is replaced like any non-directory
        // occupant — `rename(2)` removes the entry, never follows it.
        block_on(fs.write(Path::new("other.md"), b"other")).unwrap();
        block_on(fs.rename(Path::new("other.md"), Path::new("moved.md"))).unwrap();
        assert_eq!(
            block_on(fs.read_link(Path::new("moved.md")))
                .unwrap_err()
                .kind(),
            ErrorKind::InvalidInput,
            "the link must be gone, replaced by the renamed file"
        );
        assert_eq!(
            block_on(fs.read_to_string(Path::new("moved.md"))).unwrap(),
            "other"
        );
        assert_eq!(
            block_on(fs.read_to_string(Path::new("real.md"))).unwrap(),
            "content",
            "nothing may be renamed through the link"
        );
    }

    #[test]
    fn removing_a_symlink_leaves_its_target_untouched() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("real.md"), b"hello")).unwrap();
        fs.add_symlink(Path::new("link.md"), Path::new("real.md"));

        block_on(fs.remove_file(Path::new("link.md"))).unwrap();

        assert!(!block_on(fs.try_exists(Path::new("link.md"))).unwrap());
        assert_eq!(
            block_on(fs.read_to_string(Path::new("real.md"))).unwrap(),
            "hello"
        );
    }

    // ---- exclusive create ----

    #[test]
    fn create_new_writes_a_fresh_file_and_refuses_a_second() {
        let fs = InMemoryFs::new();
        block_on(fs.create_new(Path::new("once.md"), b"first")).unwrap();
        assert_eq!(
            block_on(fs.read_to_string(Path::new("once.md"))).unwrap(),
            "first"
        );
        let err = block_on(fs.create_new(Path::new("once.md"), b"second")).unwrap_err();
        assert_eq!(err.kind(), ErrorKind::AlreadyExists);
        assert_eq!(
            block_on(fs.read_to_string(Path::new("once.md"))).unwrap(),
            "first",
            "the loser must have changed nothing"
        );
    }

    #[test]
    fn create_new_counts_every_kind_of_occupant() {
        // A directory, a symlink, and a binary file all answer to their names;
        // `create_new` must refuse each exactly as `O_CREAT|O_EXCL` would.
        let fs = InMemoryFs::new();
        block_on(fs.create_dir_all(Path::new("dir"))).unwrap();
        block_on(fs.write(Path::new("bin.dat"), &[0xff, 0xfe])).unwrap();
        block_on(fs.write(Path::new("real.md"), b"hello")).unwrap();
        fs.add_symlink(Path::new("link.md"), Path::new("real.md"));

        for taken in ["dir", "bin.dat", "link.md"] {
            let err = block_on(fs.create_new(Path::new(taken), b"x")).unwrap_err();
            assert_eq!(err.kind(), ErrorKind::AlreadyExists, "{taken}");
        }
    }

    #[test]
    fn in_memory_declares_exclusive_create() {
        assert!(InMemoryFs::new().capabilities().exclusive_create);
    }

    // ---- capabilities ----

    #[test]
    fn in_memory_declares_atomic_replace_but_no_durability_across_a_restart() {
        let fs = InMemoryFs::new();
        let caps = fs.capabilities();
        assert!(
            caps.atomic_replace,
            "a single locked write is already atomic"
        );
        assert_eq!(
            caps.sync_guarantee,
            super::super::SyncGuarantee::None,
            "nothing here survives the process exiting, so there is not even an \
             ordering worth promising against a crash"
        );
        assert!(
            !caps.native_transactions,
            "the lock covers one call, not a batch of several committed together"
        );
    }

    #[test]
    fn write_atomic_lands_the_new_contents_without_a_temp_sibling() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("doc.md"), b"old")).unwrap();
        block_on(fs.write_atomic(Path::new("doc.md"), b"new")).unwrap();

        assert_eq!(
            block_on(fs.read_to_string(Path::new("doc.md"))).unwrap(),
            "new"
        );
        // No `.doc.md.fstx-tmp` sibling should exist — `replace` was
        // overridden to skip the default's staging dance, and `write_atomic`
        // composes on the override.
        let entries = block_on(fs.read_dir(Path::new(""))).unwrap();
        assert_eq!(entries.len(), 1, "no stray temp-sibling entry: {entries:?}");
    }

    // ---- clone-shares-state ----

    #[test]
    fn clones_share_the_same_backing_store() {
        let fs = InMemoryFs::new();
        let clone = fs.clone();
        block_on(fs.write(Path::new("shared.md"), b"visible everywhere")).unwrap();
        assert_eq!(
            block_on(clone.read_to_string(Path::new("shared.md"))).unwrap(),
            "visible everywhere"
        );
    }

    #[test]
    fn clear_empties_every_store() {
        let fs = InMemoryFs::new();
        block_on(fs.write(Path::new("a.md"), b"a")).unwrap();
        fs.add_symlink(Path::new("link.md"), Path::new("a.md"));

        fs.clear();

        assert!(!block_on(fs.try_exists(Path::new("a.md"))).unwrap());
        assert!(block_on(fs.metadata(Path::new("link.md"))).is_err());
    }
}