vcon-server 0.4.17

Stores vCons encrypted at rest, on local disk or in an S3 bucket (as objects or Parquet files), and returns them to authorized readers.
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
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
//! The filesystem calls Store makes for object files, behind an interface
//! so tests can simulate a crash. The catalog is SQLite, which does its own
//! I/O and is durable once a commit returns.

use std::ffi::OsString;
use std::fs::{DirBuilder, File, OpenOptions};
use std::io::{self, Write};
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
use std::path::Path;

/// The mode of every file the server makes: the service account's alone,
/// whatever the umask of the process. The umask can only take bits away,
/// and these have none for group or others to lose.
pub const FILE_MODE: u32 = 0o600;

/// The mode of every directory the server makes, as `FILE_MODE`.
pub const DIR_MODE: u32 = 0o700;

/// The filesystem calls Store makes.
pub trait Fs: Send + Sync {
    /// Creates a file that must not exist yet and writes `data` to it,
    /// without syncing.
    ///
    /// # Errors
    ///
    /// `AlreadyExists` if the path is taken, `NotFound` if its directory
    /// does not exist, or any other I/O error.
    fn write_new(&self, path: &Path, data: &[u8]) -> io::Result<()>;
    /// Makes a file's data durable.
    ///
    /// # Errors
    ///
    /// `NotFound` if there is no such file, or any other I/O error.
    fn sync_file(&self, path: &Path) -> io::Result<()>;
    /// Renames a file, replacing any file at `to`.
    ///
    /// # Errors
    ///
    /// The I/O error that stopped the rename.
    fn rename(&self, from: &Path, to: &Path) -> io::Result<()>;
    /// Renames a file only if nothing has the name `to`, in one step: of
    /// two callers renaming onto one name, one is refused.
    ///
    /// # Errors
    ///
    /// `AlreadyExists` if `to` is taken, or the I/O error that stopped the
    /// rename.
    fn rename_new(&self, from: &Path, to: &Path) -> io::Result<()>;
    /// Makes a directory's entries durable: files created, renamed or
    /// removed in it.
    ///
    /// # Errors
    ///
    /// `NotFound` if there is no such directory, or any other I/O error.
    fn sync_dir(&self, dir: &Path) -> io::Result<()>;
    /// Reads a whole file.
    ///
    /// # Errors
    ///
    /// `NotFound` if there is no such file, or any other I/O error.
    fn read(&self, path: &Path) -> io::Result<Vec<u8>>;
    /// Removes a file.
    ///
    /// # Errors
    ///
    /// `NotFound` if there is no such file, an error if the path is a
    /// directory, or any other I/O error.
    fn remove(&self, path: &Path) -> io::Result<()>;
    /// The names in a directory, sorted.
    ///
    /// # Errors
    ///
    /// `NotFound` if there is no such directory, or any other I/O error.
    fn list(&self, dir: &Path) -> io::Result<Vec<OsString>>;
    /// Creates a directory and its parents, without syncing. A new
    /// directory survives a crash once the directory holding it is synced.
    ///
    /// # Errors
    ///
    /// An error if a file stands in the path, or any other I/O error.
    fn create_dir_all(&self, dir: &Path) -> io::Result<()>;
    /// Removes a directory and everything in it, without syncing. The
    /// removal survives a crash once the directory that held it is synced.
    ///
    /// # Errors
    ///
    /// `NotFound` if there is no such directory, an error if the path is a
    /// file, or any other I/O error.
    fn remove_dir_all(&self, dir: &Path) -> io::Result<()>;
    /// Opens an existing file, to make its data durable later through the
    /// handle, as often as needed. Linux reports a failed writeback to each
    /// file open at the time, once: a file opened after the failure does not
    /// see it, so a file that must see every failure is opened once, before
    /// the writes, and kept open.
    ///
    /// # Errors
    ///
    /// `NotFound` if there is no such file, or any other I/O error.
    fn open_for_sync(&self, path: &Path) -> io::Result<Box<dyn SyncHandle>>;
}

/// A file kept open so its data can be made durable again and again.
pub trait SyncHandle: Send + Sync {
    /// Makes the file's data durable (fdatasync).
    ///
    /// # Errors
    ///
    /// The I/O error the sync reported, a failed writeback among them.
    fn sync_data(&self) -> io::Result<()>;
}

impl SyncHandle for File {
    fn sync_data(&self) -> io::Result<()> {
        File::sync_data(self)
    }
}

/// The operating system's filesystem. No test can see whether a sync
/// reached the disk without cutting power, so Store's crash tests use the
/// crash filesystem's model of syncing instead.
#[derive(Debug, Clone, Copy, Default)]
pub struct OsFs;

impl Fs for OsFs {
    fn write_new(&self, path: &Path, data: &[u8]) -> io::Result<()> {
        OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(FILE_MODE)
            .open(path)?
            .write_all(data)
    }

    fn sync_file(&self, path: &Path) -> io::Result<()> {
        File::open(path)?.sync_all()
    }

    fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
        std::fs::rename(from, to)
    }

    fn rename_new(&self, from: &Path, to: &Path) -> io::Result<()> {
        use std::os::unix::ffi::OsStrExt;
        let c = |p: &Path| {
            std::ffi::CString::new(p.as_os_str().as_bytes())
                .map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))
        };
        let (from, to) = (c(from)?, c(to)?);
        // SAFETY: both paths are NUL-terminated strings that live across the
        // call, and renameat2 reads only them and its flags.
        let done = unsafe {
            libc::renameat2(
                libc::AT_FDCWD,
                from.as_ptr(),
                libc::AT_FDCWD,
                to.as_ptr(),
                libc::RENAME_NOREPLACE,
            )
        };
        if done != 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(())
    }

    fn sync_dir(&self, dir: &Path) -> io::Result<()> {
        File::open(dir)?.sync_all()
    }

    fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
        std::fs::read(path)
    }

    fn remove(&self, path: &Path) -> io::Result<()> {
        std::fs::remove_file(path)
    }

    fn list(&self, dir: &Path) -> io::Result<Vec<OsString>> {
        let mut names = std::fs::read_dir(dir)?
            .map(|entry| entry.map(|e| e.file_name()))
            .collect::<io::Result<Vec<_>>>()?;
        names.sort();
        Ok(names)
    }

    fn create_dir_all(&self, dir: &Path) -> io::Result<()> {
        DirBuilder::new().recursive(true).mode(DIR_MODE).create(dir)
    }

    fn remove_dir_all(&self, dir: &Path) -> io::Result<()> {
        std::fs::remove_dir_all(dir)
    }

    fn open_for_sync(&self, path: &Path) -> io::Result<Box<dyn SyncHandle>> {
        Ok(Box::new(File::open(path)?))
    }
}

#[cfg(test)]
pub(crate) use crash::{CrashFs, Op};

#[cfg(test)]
mod crash {
    use std::collections::BTreeMap;
    use std::ffi::OsString;
    use std::io;
    use std::path::{Path, PathBuf};
    use std::sync::{Arc, Condvar, Mutex};
    use std::time::{Duration, Instant};

    use super::{Fs, SyncHandle};

    /// One call, as the crash filesystem logs it.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub(crate) enum Op {
        Write(PathBuf),
        SyncFile(PathBuf),
        /// A sync through a handle of a file on disk.
        SyncData(PathBuf),
        Rename(PathBuf, PathBuf),
        SyncDir(PathBuf),
        Remove(PathBuf),
        CreateDir(PathBuf),
        RemoveDir(PathBuf),
    }

    /// An in-memory filesystem that keeps what was synced apart from what
    /// was not, so a simulated crash can drop the latter. A file's data
    /// survives a crash once the file is synced; an entry in a directory, a
    /// file or a directory made, renamed or removed there, once that
    /// directory is synced. A directory lost in a crash takes everything
    /// in it.
    ///
    /// The model is rooted at a directory that exists on disk and is
    /// durable. A directory made in the model is made on disk too, because
    /// SQLite opens its catalogs there; a crash drops it only from the model.
    /// A directory is removed only from the model, since a crash may bring
    /// it back and SQLite's files in it must then still be there.
    ///
    /// A file opened for sync is a file on disk (SQLite's WAL): its syncs
    /// are real, logged as `SyncData`, counted, and can be held or made to
    /// fail, so a test can order a commit's sync against everything else.
    pub(crate) struct CrashFs {
        shared: Arc<Shared>,
    }

    struct Shared {
        state: Mutex<State>,
        /// Wakes held syncs when they are let go, and a test waiting for a
        /// sync to be held.
        turn: Condvar,
    }

    struct State {
        root: PathBuf,
        dirs: BTreeMap<PathBuf, Dir>,
        files: Vec<File>,
        log: Vec<Op>,
        /// From this many changes on, every change fails.
        fail_from: Option<usize>,
        /// While set, a sync through a handle waits.
        hold_syncs: bool,
        /// The syncs waiting now.
        held: usize,
        /// While set, a sync through a handle fails.
        fail_syncs: bool,
        /// The syncs done through handles, per file.
        syncs: BTreeMap<PathBuf, usize>,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Entry {
        /// An index into `State::files`.
        File(usize),
        Dir,
    }

    /// A directory's entries, as they are and as a crash would leave them.
    #[derive(Default)]
    struct Dir {
        now: BTreeMap<OsString, Entry>,
        synced: BTreeMap<OsString, Entry>,
    }

    struct File {
        now: Vec<u8>,
        synced: Vec<u8>,
    }

    fn not_found() -> io::Error {
        io::Error::from(io::ErrorKind::NotFound)
    }

    /// A path's directory and name.
    fn split(path: &Path) -> io::Result<(PathBuf, OsString)> {
        match (path.parent(), path.file_name()) {
            (Some(dir), Some(name)) => Ok((dir.to_owned(), name.to_owned())),
            _ => Err(io::Error::from(io::ErrorKind::InvalidInput)),
        }
    }

    impl Shared {
        fn state(&self) -> std::sync::MutexGuard<'_, State> {
            self.state
                .lock()
                .expect("no test panicked holding the lock")
        }
    }

    impl State {
        /// Fails once the fail point is reached, as a dead process would.
        fn alive(&self) -> io::Result<()> {
            match self.fail_from {
                Some(n) if self.log.len() >= n => Err(io::Error::other("the process has died")),
                _ => Ok(()),
            }
        }

        /// Whether `dir` is the root or is reached from it through
        /// entries as they are now.
        fn exists(&self, dir: &Path) -> bool {
            if dir == self.root {
                return true;
            }
            let Ok((parent, name)) = split(dir) else {
                return false;
            };
            self.exists(&parent)
                && self
                    .dirs
                    .get(&parent)
                    .is_some_and(|p| p.now.get(&name) == Some(&Entry::Dir))
        }

        fn dir(&mut self, dir: &Path) -> io::Result<&mut Dir> {
            if !self.exists(dir) {
                return Err(not_found());
            }
            self.dirs.get_mut(dir).ok_or_else(not_found)
        }

        fn file(&mut self, path: &Path) -> io::Result<usize> {
            let (dir, name) = split(path)?;
            match self.dir(&dir)?.now.get(&name) {
                Some(Entry::File(index)) => Ok(*index),
                _ => Err(not_found()),
            }
        }
    }

    impl CrashFs {
        /// A model rooted at `root`, an existing directory.
        pub(crate) fn new(root: &Path) -> CrashFs {
            CrashFs {
                shared: Arc::new(Shared {
                    state: Mutex::new(State {
                        root: root.to_owned(),
                        dirs: BTreeMap::from([(root.to_owned(), Dir::default())]),
                        files: Vec::new(),
                        log: Vec::new(),
                        fail_from: None,
                        hold_syncs: false,
                        held: 0,
                        fail_syncs: false,
                        syncs: BTreeMap::new(),
                    }),
                    turn: Condvar::new(),
                }),
            }
        }

        fn state(&self) -> std::sync::MutexGuard<'_, State> {
            self.shared.state()
        }

        /// From now on, a sync through a handle waits until `release_syncs`.
        pub(crate) fn hold_syncs(&self) {
            self.state().hold_syncs = true;
        }

        /// Lets every held sync go on, and later ones run at once.
        pub(crate) fn release_syncs(&self) {
            self.state().hold_syncs = false;
            self.shared.turn.notify_all();
        }

        /// From now on, a sync through a handle fails, as a failed
        /// writeback would make it.
        pub(crate) fn fail_syncs(&self) {
            self.state().fail_syncs = true;
            self.shared.turn.notify_all();
        }

        /// Syncs through handles succeed again.
        pub(crate) fn heal_syncs(&self) {
            self.state().fail_syncs = false;
        }

        /// The syncs done through handles of `path` so far.
        pub(crate) fn syncs(&self, path: &Path) -> usize {
            self.state().syncs.get(path).copied().unwrap_or(0)
        }

        /// Waits until `n` syncs are held; panics after 20 s, so a test
        /// that never holds one fails instead of hanging.
        pub(crate) fn await_held(&self, n: usize) {
            let deadline = Instant::now() + Duration::from_secs(20);
            let mut state = self.state();
            while state.held < n {
                let left = deadline.saturating_duration_since(Instant::now());
                assert!(!left.is_zero(), "{n} syncs held within 20 s");
                state = self
                    .shared
                    .turn
                    .wait_timeout(state, left)
                    .expect("no test panicked holding the lock")
                    .0;
            }
        }

        /// Loses everything not yet synced.
        pub(crate) fn crash(&self) {
            let mut state = self.state();
            state.fail_from = None;
            for dir in state.dirs.values_mut() {
                dir.now = dir.synced.clone();
            }
            for file in &mut state.files {
                file.now = file.synced.clone();
            }
        }

        /// From the `n`th change on (counting from 0 over the whole log),
        /// every change fails and changes nothing, as for a process that
        /// has died. `crash` clears it.
        pub(crate) fn fail_from(&self, n: usize) {
            self.state().fail_from = Some(n);
        }

        /// Ends the fail point without a crash: later changes work again
        /// and nothing is lost, as after an I/O error the process lived
        /// through. A test uses it to see what a live process does next
        /// (a poisoned catalog stays poisoned).
        pub(crate) fn revive(&self) {
            self.state().fail_from = None;
        }

        /// Every change so far, in order.
        pub(crate) fn log(&self) -> Vec<Op> {
            self.state().log.clone()
        }
    }

    impl Fs for CrashFs {
        fn write_new(&self, path: &Path, data: &[u8]) -> io::Result<()> {
            let (dir, name) = split(path)?;
            let mut state = self.state();
            state.alive()?;
            let index = state.files.len();
            let entries = &mut state.dir(&dir)?.now;
            if entries.contains_key(&name) {
                return Err(io::Error::from(io::ErrorKind::AlreadyExists));
            }
            entries.insert(name, Entry::File(index));
            state.files.push(File {
                now: data.to_vec(),
                synced: Vec::new(),
            });
            state.log.push(Op::Write(path.to_owned()));
            Ok(())
        }

        fn sync_file(&self, path: &Path) -> io::Result<()> {
            let mut state = self.state();
            state.alive()?;
            let index = state.file(path)?;
            let file = &mut state.files[index];
            file.synced = file.now.clone();
            state.log.push(Op::SyncFile(path.to_owned()));
            Ok(())
        }

        fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
            let ((from_dir, from_name), (to_dir, to_name)) = (split(from)?, split(to)?);
            let mut state = self.state();
            state.alive()?;
            let index = state.file(from)?;
            state.dir(&to_dir)?;
            state.dir(&from_dir)?.now.remove(&from_name);
            state.dir(&to_dir)?.now.insert(to_name, Entry::File(index));
            state.log.push(Op::Rename(from.to_owned(), to.to_owned()));
            Ok(())
        }

        fn rename_new(&self, from: &Path, to: &Path) -> io::Result<()> {
            let (to_dir, to_name) = split(to)?;
            {
                let mut state = self.state();
                state.alive()?;
                if state.dir(&to_dir)?.now.contains_key(&to_name) {
                    return Err(io::Error::from(io::ErrorKind::AlreadyExists));
                }
            }
            self.rename(from, to)
        }

        fn sync_dir(&self, dir: &Path) -> io::Result<()> {
            let mut state = self.state();
            state.alive()?;
            let entries = state.dir(dir)?;
            entries.synced = entries.now.clone();
            state.log.push(Op::SyncDir(dir.to_owned()));
            Ok(())
        }

        fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
            let mut state = self.state();
            let index = state.file(path)?;
            Ok(state.files[index].now.clone())
        }

        fn remove(&self, path: &Path) -> io::Result<()> {
            let (dir, name) = split(path)?;
            let mut state = self.state();
            state.alive()?;
            state.file(path)?;
            state.dir(&dir)?.now.remove(&name);
            state.log.push(Op::Remove(path.to_owned()));
            Ok(())
        }

        fn list(&self, dir: &Path) -> io::Result<Vec<OsString>> {
            Ok(self.state().dir(dir)?.now.keys().cloned().collect())
        }

        fn create_dir_all(&self, dir: &Path) -> io::Result<()> {
            let mut state = self.state();
            state.alive()?;
            let below = dir
                .strip_prefix(&state.root)
                .map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?
                .to_owned();
            // Find what is missing before touching the disk, so a refusal
            // makes nothing there either.
            let mut path = state.root.clone();
            let mut missing = Vec::new();
            for part in &below {
                let next = path.join(part);
                let parent = std::mem::replace(&mut path, next);
                if !missing.is_empty() {
                    missing.push(path.clone());
                    continue;
                }
                match state.dir(&parent)?.now.get(part) {
                    Some(Entry::Dir) => {}
                    Some(Entry::File(_)) => {
                        return Err(io::Error::from(io::ErrorKind::AlreadyExists));
                    }
                    None => missing.push(path.clone()),
                }
            }
            if missing.is_empty() {
                return Ok(());
            }
            std::fs::create_dir_all(dir)?;
            for path in missing {
                let (parent, name) = split(&path)?;
                state.dir(&parent)?.now.insert(name, Entry::Dir);
                state.dirs.insert(path, Dir::default());
            }
            state.log.push(Op::CreateDir(dir.to_owned()));
            Ok(())
        }

        fn remove_dir_all(&self, dir: &Path) -> io::Result<()> {
            let (parent, name) = split(dir)?;
            let mut state = self.state();
            state.alive()?;
            if !state.exists(dir) {
                return Err(not_found());
            }
            state.dir(&parent)?.now.remove(&name);
            state.log.push(Op::RemoveDir(dir.to_owned()));
            Ok(())
        }

        fn open_for_sync(&self, path: &Path) -> io::Result<Box<dyn SyncHandle>> {
            Ok(Box::new(CrashSync {
                path: path.to_owned(),
                file: std::fs::File::open(path)?,
                shared: self.shared.clone(),
            }))
        }
    }

    /// A handle of a file on disk whose syncs the crash filesystem holds,
    /// fails, logs and counts.
    struct CrashSync {
        path: PathBuf,
        file: std::fs::File,
        shared: Arc<Shared>,
    }

    impl SyncHandle for CrashSync {
        fn sync_data(&self) -> io::Result<()> {
            let mut state = self.shared.state();
            state.alive()?;
            state.held += 1;
            self.shared.turn.notify_all();
            // A test that never lets a held sync go fails here, after 60 s,
            // instead of hanging.
            let deadline = Instant::now() + Duration::from_secs(60);
            while state.hold_syncs && !state.fail_syncs {
                let left = deadline.saturating_duration_since(Instant::now());
                if left.is_zero() {
                    state.held -= 1;
                    return Err(io::Error::other("a held sync was not let go within 60 s"));
                }
                state = self
                    .shared
                    .turn
                    .wait_timeout(state, left)
                    .expect("no test panicked holding the lock")
                    .0;
            }
            state.held -= 1;
            if state.fail_syncs {
                return Err(io::Error::other("the writeback failed"));
            }
            self.file.sync_data()?;
            state.log.push(Op::SyncData(self.path.clone()));
            *state.syncs.entry(self.path.clone()).or_default() += 1;
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io::ErrorKind::{AlreadyExists, NotFound};
    use std::path::PathBuf;

    use super::*;

    /// What every implementation must do, crash or no crash.
    fn behaves_like_a_filesystem(fs: &dyn Fs, root: &Path) {
        let dir = root.join("objects");
        let (a, b) = (dir.join("a"), dir.join("b"));
        assert_eq!(
            fs.write_new(&a, b"x").map_err(|e| e.kind()),
            Err(NotFound),
            "no dir yet"
        );
        fs.create_dir_all(&dir).expect("create the dir");
        fs.create_dir_all(&dir).expect("create it again");
        fs.write_new(&a, b"one").expect("write");
        assert_eq!(
            fs.write_new(&a, b"two").map_err(|e| e.kind()),
            Err(AlreadyExists),
            "write_new never replaces a file"
        );
        assert!(fs.create_dir_all(&a).is_err(), "a file has the name");
        assert!(
            fs.create_dir_all(&a.join("d")).is_err(),
            "a file stands in the way"
        );
        assert!(!a.join("d").exists(), "and nothing is made on disk");
        assert_eq!(
            fs.read(&a).expect("read"),
            b"one",
            "the refused write left the first one"
        );
        fs.sync_file(&a).expect("sync the file");
        fs.sync_dir(&dir).expect("sync the dir");
        fs.rename(&a, &b).expect("rename");
        assert_eq!(
            fs.read(&a).map_err(|e| e.kind()),
            Err(NotFound),
            "rename moves the file away"
        );
        assert_eq!(
            fs.read(&b).expect("read"),
            b"one",
            "the file is under its new name"
        );
        fs.rename(&b, &b).expect("rename onto itself");
        assert_eq!(
            fs.read(&b).expect("read"),
            b"one",
            "renaming onto itself changes nothing"
        );
        fs.write_new(&a, b"three").expect("write again");
        fs.rename(&a, &b).expect("rename over");
        assert_eq!(
            fs.read(&b).expect("read"),
            b"three",
            "rename replaces the target"
        );
        fs.write_new(&a, b"four").expect("write");
        fs.create_dir_all(&dir.join("c"))
            .expect("a directory inside");
        assert_eq!(
            fs.list(&dir).expect("list"),
            ["a", "b", "c"].map(OsString::from),
            "files and directories, sorted"
        );
        assert_eq!(
            fs.write_new(&dir.join("c"), b"x").map_err(|e| e.kind()),
            Err(AlreadyExists),
            "a directory's name is taken"
        );
        assert!(
            fs.remove(&dir.join("c")).is_err(),
            "remove takes only a file"
        );
        assert!(
            fs.remove_dir_all(&a).is_err(),
            "remove_dir_all takes only a directory"
        );
        fs.create_dir_all(&dir.join("c/d"))
            .expect("a directory inside c");
        fs.write_new(&dir.join("c/f"), b"x")
            .expect("a file inside c");
        fs.remove_dir_all(&dir.join("c"))
            .expect("remove c and all in it");
        assert_eq!(
            fs.list(&dir.join("c")).map_err(|e| e.kind()),
            Err(NotFound),
            "remove_dir_all removed c itself"
        );
        assert_eq!(
            fs.remove_dir_all(&dir.join("c")).map_err(|e| e.kind()),
            Err(NotFound),
            "a directory that is gone cannot be removed again"
        );
        fs.create_dir_all(&dir.join("c")).expect("c again");
        fs.remove(&a).expect("remove");
        fs.remove(&b).expect("remove");
        assert_eq!(
            fs.list(&dir).expect("list"),
            [OsString::from("c")],
            "the removed files are gone and c is left"
        );
        assert_eq!(
            fs.remove(&b).map_err(|e| e.kind()),
            Err(NotFound),
            "b was removed"
        );
        assert_eq!(
            fs.sync_file(&b).map_err(|e| e.kind()),
            Err(NotFound),
            "b was removed"
        );
        assert_eq!(
            fs.sync_dir(&root.join("none")).map_err(|e| e.kind()),
            Err(NotFound),
            "no directory has that name"
        );
        assert_eq!(
            fs.list(&root.join("none")).map_err(|e| e.kind()),
            Err(NotFound),
            "no directory has that name"
        );
        let (x, y, z) = (dir.join("x"), dir.join("y"), dir.join("z"));
        fs.write_new(&x, b"five").expect("write x");
        fs.write_new(&y, b"six").expect("write y");
        assert_eq!(
            fs.rename_new(&x, &y).map_err(|e| e.kind()),
            Err(AlreadyExists),
            "rename_new never replaces a file"
        );
        assert_eq!(fs.read(&x).expect("read x"), b"five", "x is left");
        assert_eq!(fs.read(&y).expect("read y"), b"six", "y is left");
        fs.rename_new(&x, &z).expect("rename onto a free name");
        assert_eq!(fs.read(&z).expect("read z"), b"five", "under its new name");
        assert_eq!(
            fs.read(&x).map_err(|e| e.kind()),
            Err(NotFound),
            "rename_new moves the file away"
        );
    }

    #[test]
    fn the_os_filesystem_behaves_like_a_filesystem() {
        let root = tempfile::tempdir().expect("temp dir");
        behaves_like_a_filesystem(&OsFs, root.path());
    }

    #[test]
    fn the_crash_filesystem_behaves_like_a_filesystem() {
        let root = tempfile::tempdir().expect("temp dir");
        behaves_like_a_filesystem(&CrashFs::new(root.path()), root.path());
    }

    /// A crash filesystem rooted at a temporary directory.
    struct Model {
        root: tempfile::TempDir,
        fs: CrashFs,
    }

    impl Model {
        fn new() -> Model {
            let root = tempfile::tempdir().expect("temp dir");
            let fs = CrashFs::new(root.path());
            Model { root, fs }
        }

        fn root(&self) -> &Path {
            self.root.path()
        }

        /// The directory the file tests use, made and synced.
        fn dir(&self) -> PathBuf {
            self.root().join("objects")
        }

        fn f(&self) -> PathBuf {
            self.dir().join("f")
        }
    }

    /// A model with a durable `dir()`, after `steps` on its file `f()`.
    fn after(steps: impl FnOnce(&CrashFs, &Path)) -> Model {
        let m = Model::new();
        m.fs.create_dir_all(&m.dir()).expect("create the dir");
        m.fs.sync_dir(m.root()).expect("sync the root");
        steps(&m.fs, &m.f());
        m
    }

    fn synced(fs: &CrashFs, f: &Path) {
        fs.write_new(f, b"data").expect("write");
        fs.sync_file(f).expect("sync the file");
        fs.sync_dir(f.parent().expect("a dir"))
            .expect("sync the dir");
    }

    #[test]
    fn a_crash_drops_a_file_whose_entry_was_not_synced() {
        for sync_data in [false, true] {
            let m = after(|fs, f| {
                fs.write_new(f, b"data").expect("write");
                if sync_data {
                    fs.sync_file(f).expect("sync the file");
                }
            });
            m.fs.crash();
            assert_eq!(
                m.fs.read(&m.f()).map_err(|e| e.kind()),
                Err(NotFound),
                "the entry was never synced, so the crash loses the file (data synced: {sync_data})"
            );
        }
    }

    #[test]
    fn a_crash_empties_a_file_whose_data_was_not_synced() {
        let m = after(|fs, f| {
            fs.write_new(f, b"data").expect("write");
            fs.sync_dir(f.parent().expect("a dir"))
                .expect("sync the dir");
        });
        m.fs.crash();
        assert_eq!(
            m.fs.read(&m.f()).expect("the entry survives"),
            b"",
            "the entry was synced but the data was not, so the file comes back empty"
        );
    }

    #[test]
    fn a_crash_keeps_a_file_synced_in_both_ways() {
        let m = after(synced);
        m.fs.crash();
        assert_eq!(
            m.fs.read(&m.f()).expect("survives"),
            b"data",
            "data and entry were both synced, so the crash keeps the file whole"
        );
    }

    #[test]
    fn a_rename_or_remove_survives_a_crash_only_once_the_dir_is_synced() {
        for sync in [false, true] {
            let renamed = after(|fs, f| {
                synced(fs, f);
                fs.rename(f, &f.with_file_name("g")).expect("rename");
                if sync {
                    fs.sync_dir(f.parent().expect("a dir"))
                        .expect("sync the dir");
                }
            });
            renamed.fs.crash();
            let names = if sync { ["g"] } else { ["f"] };
            assert_eq!(
                renamed.fs.list(&renamed.dir()).expect("list"),
                names.map(OsString::from),
                "rename, sync {sync}"
            );
            assert_eq!(
                renamed
                    .fs
                    .read(&renamed.dir().join(names[0]))
                    .expect("read"),
                b"data",
                "whichever name survives, the synced data is under it"
            );

            let removed = after(|fs, f| {
                synced(fs, f);
                fs.remove(f).expect("remove");
                if sync {
                    fs.sync_dir(f.parent().expect("a dir"))
                        .expect("sync the dir");
                }
            });
            removed.fs.crash();
            let left = removed.fs.list(&removed.dir()).expect("list").len();
            assert_eq!(left, usize::from(!sync), "remove, sync {sync}");
        }
    }

    #[test]
    fn a_new_directory_survives_a_crash_only_once_its_parent_is_synced() {
        let m = Model::new();
        let (a, b) = (m.root().join("a"), m.root().join("a/b"));
        m.fs.create_dir_all(&b).expect("create a/b");
        m.fs.crash();
        assert_eq!(
            m.fs.list(m.root()).expect("list"),
            Vec::<OsString>::new(),
            "nothing was synced, so the crash loses a"
        );
        assert_eq!(
            m.fs.list(&a).map_err(|e| e.kind()),
            Err(NotFound),
            "a is gone after the crash"
        );

        m.fs.create_dir_all(&b).expect("create a/b");
        m.fs.sync_dir(&a).expect("sync a, not the root");
        m.fs.crash();
        assert_eq!(
            m.fs.list(&b).map_err(|e| e.kind()),
            Err(NotFound),
            "b is lost with a"
        );

        m.fs.create_dir_all(&b).expect("create a/b");
        m.fs.sync_dir(m.root()).expect("sync the root");
        m.fs.crash();
        assert_eq!(
            m.fs.list(m.root()).expect("list"),
            [OsString::from("a")],
            "the root was synced, so its entry for a survives"
        );
        assert_eq!(
            m.fs.list(&a).expect("a survives"),
            Vec::<OsString>::new(),
            "b's entry in a was never synced"
        );

        m.fs.create_dir_all(&b).expect("create b");
        m.fs.sync_dir(&a).expect("sync a");
        m.fs.crash();
        assert_eq!(
            m.fs.list(&b).expect("b survives"),
            Vec::<OsString>::new(),
            "a was synced, so its entry for b survives, and b is empty"
        );
    }

    #[test]
    fn a_lost_directory_takes_its_synced_files_with_it() {
        let m = Model::new();
        let a = m.root().join("a");
        m.fs.create_dir_all(&a).expect("create a");
        synced(&m.fs, &a.join("f"));
        m.fs.crash();
        assert_eq!(
            m.fs.list(m.root()).expect("list"),
            Vec::<OsString>::new(),
            "the root was never synced, so a is lost with its synced file"
        );
        m.fs.create_dir_all(&a).expect("create a again");
        assert_eq!(
            m.fs.list(&a).expect("list"),
            Vec::<OsString>::new(),
            "a new directory starts empty"
        );
    }

    #[test]
    fn a_directory_removal_survives_a_crash_only_once_its_parent_is_synced() {
        for sync in [false, true] {
            let m = Model::new();
            let a = m.root().join("a");
            m.fs.create_dir_all(&a).expect("create a");
            synced(&m.fs, &a.join("f"));
            m.fs.sync_dir(m.root()).expect("sync the root");
            m.fs.remove_dir_all(&a).expect("remove a");
            if sync {
                m.fs.sync_dir(m.root()).expect("sync the root");
            }
            m.fs.crash();
            if sync {
                assert_eq!(
                    m.fs.list(&a).map_err(|e| e.kind()),
                    Err(NotFound),
                    "the root was synced after the removal, so it holds"
                );
            } else {
                assert_eq!(
                    m.fs.read(&a.join("f")).expect("back"),
                    b"data",
                    "the removal was never synced, so a comes back with its file"
                );
            }
        }
    }

    /// A crash may bring a removed directory back, and SQLite's files in
    /// it must then still be there, so removal touches only the model.
    #[test]
    fn a_directory_is_removed_only_from_the_model() {
        let m = Model::new();
        let a = m.root().join("a");
        m.fs.create_dir_all(&a).expect("create a");
        m.fs.remove_dir_all(&a).expect("remove a");
        assert!(
            a.is_dir(),
            "the directory stays on disk, for a crash that brings it back"
        );
    }

    /// SQLite opens its files on disk, so a directory made in the model is
    /// made on disk too.
    #[test]
    fn a_directory_is_also_made_on_disk() {
        let m = Model::new();
        let b = m.root().join("a/b");
        m.fs.create_dir_all(&b).expect("create a/b");
        assert!(
            b.is_dir(),
            "the directory is on disk, where SQLite will open its files"
        );
    }

    #[test]
    fn nothing_outside_the_root_can_be_made() {
        let m = Model::new();
        let outside = m.root().with_file_name("elsewhere-5c1e");
        assert!(
            m.fs.create_dir_all(&outside).is_err(),
            "the model refuses a path outside its root"
        );
        assert!(!outside.exists(), "and makes nothing there on disk");
    }

    #[test]
    fn every_call_that_changes_state_is_logged_in_order() {
        let m = Model::new();
        let (dir, f, g) = (m.dir(), m.f(), m.dir().join("g"));
        m.fs.create_dir_all(&dir).expect("create the dir");
        m.fs.create_dir_all(&dir).expect("already there: no change");
        synced(&m.fs, &f);
        m.fs.rename(&f, &g).expect("rename");
        m.fs.remove(&g).expect("remove");
        m.fs.remove_dir_all(&dir).expect("remove the dir");
        assert_eq!(
            m.fs.log(),
            [
                Op::CreateDir(dir.clone()),
                Op::Write(f.clone()),
                Op::SyncFile(f.clone()),
                Op::SyncDir(dir.clone()),
                Op::Rename(f, g.clone()),
                Op::Remove(g),
                Op::RemoveDir(dir),
            ],
            "one entry per change, in order; the create that changed nothing is not logged"
        );
    }

    #[test]
    fn from_the_fail_point_on_no_change_happens_until_a_crash() {
        let m = after(|fs, f| fs.write_new(f, b"data").expect("write"));
        let ops = m.fs.log().len();
        m.fs.fail_from(ops);
        let (f, g) = (m.f(), m.dir().join("g"));
        assert!(m.fs.sync_file(&f).is_err(), "sync");
        assert!(m.fs.write_new(&g, b"x").is_err(), "write");
        assert!(m.fs.rename(&f, &g).is_err(), "rename");
        assert!(m.fs.sync_dir(&m.dir()).is_err(), "sync dir");
        assert!(m.fs.remove(&f).is_err(), "remove");
        assert!(
            m.fs.create_dir_all(&m.dir().join("d")).is_err(),
            "create dir"
        );
        assert!(m.fs.remove_dir_all(&m.dir()).is_err(), "remove dir");
        assert!(!m.dir().join("d").exists(), "not made on disk either");
        assert_eq!(m.fs.log().len(), ops, "nothing changed");
        assert_eq!(
            m.fs.read(&f).expect("reads still work"),
            b"data",
            "the fail point stops changes, not reads"
        );
        m.fs.crash();
        m.fs.write_new(&g, b"x")
            .expect("works again after the crash");
    }

    /// A file on disk, beside the model, as SQLite's WAL is.
    fn on_disk(root: &Path) -> PathBuf {
        let wal = root.join("catalog.sqlite-wal");
        std::fs::write(&wal, b"frames").expect("write the file on disk");
        wal
    }

    #[test]
    fn the_os_filesystem_opens_an_existing_file_for_sync_and_syncs_it_again_and_again() {
        let root = tempfile::tempdir().expect("temp dir");
        let wal = on_disk(root.path());
        let handle = OsFs.open_for_sync(&wal).expect("opens");
        handle.sync_data().expect("the first sync");
        std::fs::OpenOptions::new()
            .append(true)
            .open(&wal)
            .and_then(|mut f| f.write_all(b"more"))
            .expect("another writer appends");
        handle.sync_data().expect("the same handle syncs again");
    }

    #[test]
    fn the_os_filesystem_refuses_to_open_a_missing_file_for_sync() {
        let root = tempfile::tempdir().expect("temp dir");
        let missing = root.path().join("catalog.sqlite-wal");
        assert_eq!(
            OsFs.open_for_sync(&missing).err().map(|e| e.kind()),
            Some(NotFound),
            "no file, no handle: the WAL must exist before it is opened for sync"
        );
        assert!(!missing.exists(), "opening for sync never creates the file");
    }

    #[test]
    fn the_crash_filesystem_refuses_to_open_a_missing_file_for_sync() {
        let m = Model::new();
        assert_eq!(
            m.fs.open_for_sync(&m.root().join("absent-wal"))
                .err()
                .map(|e| e.kind()),
            Some(NotFound),
            "a handle is of a file on disk"
        );
    }

    #[test]
    fn a_sync_through_a_crash_handle_is_logged_in_order_and_counted() {
        let m = Model::new();
        let wal = on_disk(m.root());
        let handle = m.fs.open_for_sync(&wal).expect("opens");
        assert_eq!(m.fs.syncs(&wal), 0, "opening is not a sync");
        m.fs.create_dir_all(&m.dir()).expect("create the dir");
        handle.sync_data().expect("sync");
        m.fs.sync_dir(&m.dir()).expect("sync the dir");
        handle.sync_data().expect("sync again");
        assert_eq!(
            m.fs.log(),
            [
                Op::CreateDir(m.dir()),
                Op::SyncData(wal.clone()),
                Op::SyncDir(m.dir()),
                Op::SyncData(wal.clone()),
            ],
            "each sync is logged where it happened"
        );
        assert_eq!(m.fs.syncs(&wal), 2, "and counted per file");
    }

    #[test]
    fn a_failing_crash_handle_fails_every_sync_and_logs_none() {
        let m = Model::new();
        let wal = on_disk(m.root());
        let handle = m.fs.open_for_sync(&wal).expect("opens");
        m.fs.fail_syncs();
        assert!(handle.sync_data().is_err(), "the first sync fails");
        assert!(handle.sync_data().is_err(), "and every later one");
        assert_eq!(m.fs.syncs(&wal), 0, "a failed sync is not counted");
        assert!(m.fs.log().is_empty(), "nor logged");
    }

    #[test]
    fn a_crash_handle_cannot_sync_once_the_process_has_died() {
        let m = Model::new();
        let wal = on_disk(m.root());
        let handle = m.fs.open_for_sync(&wal).expect("opens");
        m.fs.fail_from(0);
        assert!(handle.sync_data().is_err(), "a dead process syncs nothing");
        assert_eq!(m.fs.syncs(&wal), 0, "nothing counted");
    }

    #[test]
    fn a_held_sync_waits_until_it_is_let_go_and_other_calls_go_on() {
        let m = Model::new();
        let wal = on_disk(m.root());
        let handle = m.fs.open_for_sync(&wal).expect("opens");
        m.fs.hold_syncs();
        std::thread::scope(|s| {
            let syncing = s.spawn(|| handle.sync_data());
            m.fs.await_held(1);
            assert!(!syncing.is_finished(), "the sync waits while held");
            assert_eq!(m.fs.syncs(&wal), 0, "and has not happened");
            m.fs.create_dir_all(&m.dir())
                .expect("other calls are not held");
            m.fs.release_syncs();
            syncing
                .join()
                .expect("the sync thread ends")
                .expect("and syncs once let go");
        });
        assert_eq!(m.fs.syncs(&wal), 1, "one sync, after the release");
        assert_eq!(
            m.fs.log(),
            [Op::CreateDir(m.dir()), Op::SyncData(wal)],
            "the held sync is logged after what ran while it waited"
        );
    }

    #[test]
    fn a_held_sync_fails_when_syncs_are_made_to_fail_while_it_waits() {
        let m = Model::new();
        let wal = on_disk(m.root());
        let handle = m.fs.open_for_sync(&wal).expect("opens");
        m.fs.hold_syncs();
        std::thread::scope(|s| {
            let syncing = s.spawn(|| handle.sync_data());
            m.fs.await_held(1);
            m.fs.fail_syncs();
            assert!(
                syncing.join().expect("the sync thread ends").is_err(),
                "a sync held when syncs start to fail fails, without a release"
            );
        });
        assert_eq!(m.fs.syncs(&wal), 0, "not counted");
    }

    #[test]
    fn a_revived_crash_filesystem_changes_again_and_loses_nothing() {
        let m = after(|fs, f| fs.write_new(f, b"data").expect("write"));
        m.fs.fail_from(m.fs.log().len());
        let g = m.dir().join("g");
        assert!(m.fs.write_new(&g, b"x").is_err(), "the fail point holds");
        m.fs.revive();
        m.fs.write_new(&g, b"x")
            .expect("a revived filesystem changes again");
        assert_eq!(
            m.fs.read(&m.f()).expect("still there"),
            b"data",
            "revive is not a crash: the unsynced write is kept"
        );
    }

    #[test]
    fn a_revived_crash_handle_syncs_again() {
        let m = Model::new();
        let wal = on_disk(m.root());
        let handle = m.fs.open_for_sync(&wal).expect("opens");
        m.fs.fail_from(0);
        assert!(handle.sync_data().is_err(), "the fail point holds");
        m.fs.revive();
        handle.sync_data().expect("a revived handle syncs");
        assert_eq!(m.fs.syncs(&wal), 1, "counted once");
    }
}