Skip to main content

vcon_server/
fs.rs

1//! The filesystem calls Store makes for object files, behind an interface
2//! so tests can simulate a crash. The catalog is SQLite, which does its own
3//! I/O and is durable once a commit returns.
4
5use std::ffi::OsString;
6use std::fs::{DirBuilder, File, OpenOptions};
7use std::io::{self, Write};
8use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
9use std::path::Path;
10
11/// The mode of every file the server makes: the service account's alone,
12/// whatever the umask of the process. The umask can only take bits away,
13/// and these have none for group or others to lose.
14pub const FILE_MODE: u32 = 0o600;
15
16/// The mode of every directory the server makes, as `FILE_MODE`.
17pub const DIR_MODE: u32 = 0o700;
18
19/// The filesystem calls Store makes.
20pub trait Fs: Send + Sync {
21    /// Creates a file that must not exist yet and writes `data` to it,
22    /// without syncing.
23    ///
24    /// # Errors
25    ///
26    /// `AlreadyExists` if the path is taken, `NotFound` if its directory
27    /// does not exist, or any other I/O error.
28    fn write_new(&self, path: &Path, data: &[u8]) -> io::Result<()>;
29    /// Makes a file's data durable.
30    ///
31    /// # Errors
32    ///
33    /// `NotFound` if there is no such file, or any other I/O error.
34    fn sync_file(&self, path: &Path) -> io::Result<()>;
35    /// Renames a file, replacing any file at `to`.
36    ///
37    /// # Errors
38    ///
39    /// The I/O error that stopped the rename.
40    fn rename(&self, from: &Path, to: &Path) -> io::Result<()>;
41    /// Renames a file only if nothing has the name `to`, in one step: of
42    /// two callers renaming onto one name, one is refused.
43    ///
44    /// # Errors
45    ///
46    /// `AlreadyExists` if `to` is taken, or the I/O error that stopped the
47    /// rename.
48    fn rename_new(&self, from: &Path, to: &Path) -> io::Result<()>;
49    /// Makes a directory's entries durable: files created, renamed or
50    /// removed in it.
51    ///
52    /// # Errors
53    ///
54    /// `NotFound` if there is no such directory, or any other I/O error.
55    fn sync_dir(&self, dir: &Path) -> io::Result<()>;
56    /// Reads a whole file.
57    ///
58    /// # Errors
59    ///
60    /// `NotFound` if there is no such file, or any other I/O error.
61    fn read(&self, path: &Path) -> io::Result<Vec<u8>>;
62    /// Removes a file.
63    ///
64    /// # Errors
65    ///
66    /// `NotFound` if there is no such file, an error if the path is a
67    /// directory, or any other I/O error.
68    fn remove(&self, path: &Path) -> io::Result<()>;
69    /// The names in a directory, sorted.
70    ///
71    /// # Errors
72    ///
73    /// `NotFound` if there is no such directory, or any other I/O error.
74    fn list(&self, dir: &Path) -> io::Result<Vec<OsString>>;
75    /// Creates a directory and its parents, without syncing. A new
76    /// directory survives a crash once the directory holding it is synced.
77    ///
78    /// # Errors
79    ///
80    /// An error if a file stands in the path, or any other I/O error.
81    fn create_dir_all(&self, dir: &Path) -> io::Result<()>;
82    /// Removes a directory and everything in it, without syncing. The
83    /// removal survives a crash once the directory that held it is synced.
84    ///
85    /// # Errors
86    ///
87    /// `NotFound` if there is no such directory, an error if the path is a
88    /// file, or any other I/O error.
89    fn remove_dir_all(&self, dir: &Path) -> io::Result<()>;
90    /// Opens an existing file, to make its data durable later through the
91    /// handle, as often as needed. Linux reports a failed writeback to each
92    /// file open at the time, once: a file opened after the failure does not
93    /// see it, so a file that must see every failure is opened once, before
94    /// the writes, and kept open.
95    ///
96    /// # Errors
97    ///
98    /// `NotFound` if there is no such file, or any other I/O error.
99    fn open_for_sync(&self, path: &Path) -> io::Result<Box<dyn SyncHandle>>;
100}
101
102/// A file kept open so its data can be made durable again and again.
103pub trait SyncHandle: Send + Sync {
104    /// Makes the file's data durable (fdatasync).
105    ///
106    /// # Errors
107    ///
108    /// The I/O error the sync reported, a failed writeback among them.
109    fn sync_data(&self) -> io::Result<()>;
110}
111
112impl SyncHandle for File {
113    fn sync_data(&self) -> io::Result<()> {
114        File::sync_data(self)
115    }
116}
117
118/// The operating system's filesystem. No test can see whether a sync
119/// reached the disk without cutting power, so Store's crash tests use the
120/// crash filesystem's model of syncing instead.
121#[derive(Debug, Clone, Copy, Default)]
122pub struct OsFs;
123
124impl Fs for OsFs {
125    fn write_new(&self, path: &Path, data: &[u8]) -> io::Result<()> {
126        OpenOptions::new()
127            .write(true)
128            .create_new(true)
129            .mode(FILE_MODE)
130            .open(path)?
131            .write_all(data)
132    }
133
134    fn sync_file(&self, path: &Path) -> io::Result<()> {
135        File::open(path)?.sync_all()
136    }
137
138    fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
139        std::fs::rename(from, to)
140    }
141
142    fn rename_new(&self, from: &Path, to: &Path) -> io::Result<()> {
143        use std::os::unix::ffi::OsStrExt;
144        let c = |p: &Path| {
145            std::ffi::CString::new(p.as_os_str().as_bytes())
146                .map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))
147        };
148        let (from, to) = (c(from)?, c(to)?);
149        // SAFETY: both paths are NUL-terminated strings that live across the
150        // call, and renameat2 reads only them and its flags.
151        let done = unsafe {
152            libc::renameat2(
153                libc::AT_FDCWD,
154                from.as_ptr(),
155                libc::AT_FDCWD,
156                to.as_ptr(),
157                libc::RENAME_NOREPLACE,
158            )
159        };
160        if done != 0 {
161            return Err(io::Error::last_os_error());
162        }
163        Ok(())
164    }
165
166    fn sync_dir(&self, dir: &Path) -> io::Result<()> {
167        File::open(dir)?.sync_all()
168    }
169
170    fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
171        std::fs::read(path)
172    }
173
174    fn remove(&self, path: &Path) -> io::Result<()> {
175        std::fs::remove_file(path)
176    }
177
178    fn list(&self, dir: &Path) -> io::Result<Vec<OsString>> {
179        let mut names = std::fs::read_dir(dir)?
180            .map(|entry| entry.map(|e| e.file_name()))
181            .collect::<io::Result<Vec<_>>>()?;
182        names.sort();
183        Ok(names)
184    }
185
186    fn create_dir_all(&self, dir: &Path) -> io::Result<()> {
187        DirBuilder::new().recursive(true).mode(DIR_MODE).create(dir)
188    }
189
190    fn remove_dir_all(&self, dir: &Path) -> io::Result<()> {
191        std::fs::remove_dir_all(dir)
192    }
193
194    fn open_for_sync(&self, path: &Path) -> io::Result<Box<dyn SyncHandle>> {
195        Ok(Box::new(File::open(path)?))
196    }
197}
198
199#[cfg(test)]
200pub(crate) use crash::{CrashFs, Op};
201
202#[cfg(test)]
203mod crash {
204    use std::collections::BTreeMap;
205    use std::ffi::OsString;
206    use std::io;
207    use std::path::{Path, PathBuf};
208    use std::sync::{Arc, Condvar, Mutex};
209    use std::time::{Duration, Instant};
210
211    use super::{Fs, SyncHandle};
212
213    /// One call, as the crash filesystem logs it.
214    #[derive(Debug, Clone, PartialEq, Eq)]
215    pub(crate) enum Op {
216        Write(PathBuf),
217        SyncFile(PathBuf),
218        /// A sync through a handle of a file on disk.
219        SyncData(PathBuf),
220        Rename(PathBuf, PathBuf),
221        SyncDir(PathBuf),
222        Remove(PathBuf),
223        CreateDir(PathBuf),
224        RemoveDir(PathBuf),
225    }
226
227    /// An in-memory filesystem that keeps what was synced apart from what
228    /// was not, so a simulated crash can drop the latter. A file's data
229    /// survives a crash once the file is synced; an entry in a directory, a
230    /// file or a directory made, renamed or removed there, once that
231    /// directory is synced. A directory lost in a crash takes everything
232    /// in it.
233    ///
234    /// The model is rooted at a directory that exists on disk and is
235    /// durable. A directory made in the model is made on disk too, because
236    /// SQLite opens its catalogs there; a crash drops it only from the model.
237    /// A directory is removed only from the model, since a crash may bring
238    /// it back and SQLite's files in it must then still be there.
239    ///
240    /// A file opened for sync is a file on disk (SQLite's WAL): its syncs
241    /// are real, logged as `SyncData`, counted, and can be held or made to
242    /// fail, so a test can order a commit's sync against everything else.
243    pub(crate) struct CrashFs {
244        shared: Arc<Shared>,
245    }
246
247    struct Shared {
248        state: Mutex<State>,
249        /// Wakes held syncs when they are let go, and a test waiting for a
250        /// sync to be held.
251        turn: Condvar,
252    }
253
254    struct State {
255        root: PathBuf,
256        dirs: BTreeMap<PathBuf, Dir>,
257        files: Vec<File>,
258        log: Vec<Op>,
259        /// From this many changes on, every change fails.
260        fail_from: Option<usize>,
261        /// While set, a sync through a handle waits.
262        hold_syncs: bool,
263        /// The syncs waiting now.
264        held: usize,
265        /// While set, a sync through a handle fails.
266        fail_syncs: bool,
267        /// The syncs done through handles, per file.
268        syncs: BTreeMap<PathBuf, usize>,
269    }
270
271    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
272    enum Entry {
273        /// An index into `State::files`.
274        File(usize),
275        Dir,
276    }
277
278    /// A directory's entries, as they are and as a crash would leave them.
279    #[derive(Default)]
280    struct Dir {
281        now: BTreeMap<OsString, Entry>,
282        synced: BTreeMap<OsString, Entry>,
283    }
284
285    struct File {
286        now: Vec<u8>,
287        synced: Vec<u8>,
288    }
289
290    fn not_found() -> io::Error {
291        io::Error::from(io::ErrorKind::NotFound)
292    }
293
294    /// A path's directory and name.
295    fn split(path: &Path) -> io::Result<(PathBuf, OsString)> {
296        match (path.parent(), path.file_name()) {
297            (Some(dir), Some(name)) => Ok((dir.to_owned(), name.to_owned())),
298            _ => Err(io::Error::from(io::ErrorKind::InvalidInput)),
299        }
300    }
301
302    impl Shared {
303        fn state(&self) -> std::sync::MutexGuard<'_, State> {
304            self.state
305                .lock()
306                .expect("no test panicked holding the lock")
307        }
308    }
309
310    impl State {
311        /// Fails once the fail point is reached, as a dead process would.
312        fn alive(&self) -> io::Result<()> {
313            match self.fail_from {
314                Some(n) if self.log.len() >= n => Err(io::Error::other("the process has died")),
315                _ => Ok(()),
316            }
317        }
318
319        /// Whether `dir` is the root or is reached from it through
320        /// entries as they are now.
321        fn exists(&self, dir: &Path) -> bool {
322            if dir == self.root {
323                return true;
324            }
325            let Ok((parent, name)) = split(dir) else {
326                return false;
327            };
328            self.exists(&parent)
329                && self
330                    .dirs
331                    .get(&parent)
332                    .is_some_and(|p| p.now.get(&name) == Some(&Entry::Dir))
333        }
334
335        fn dir(&mut self, dir: &Path) -> io::Result<&mut Dir> {
336            if !self.exists(dir) {
337                return Err(not_found());
338            }
339            self.dirs.get_mut(dir).ok_or_else(not_found)
340        }
341
342        fn file(&mut self, path: &Path) -> io::Result<usize> {
343            let (dir, name) = split(path)?;
344            match self.dir(&dir)?.now.get(&name) {
345                Some(Entry::File(index)) => Ok(*index),
346                _ => Err(not_found()),
347            }
348        }
349    }
350
351    impl CrashFs {
352        /// A model rooted at `root`, an existing directory.
353        pub(crate) fn new(root: &Path) -> CrashFs {
354            CrashFs {
355                shared: Arc::new(Shared {
356                    state: Mutex::new(State {
357                        root: root.to_owned(),
358                        dirs: BTreeMap::from([(root.to_owned(), Dir::default())]),
359                        files: Vec::new(),
360                        log: Vec::new(),
361                        fail_from: None,
362                        hold_syncs: false,
363                        held: 0,
364                        fail_syncs: false,
365                        syncs: BTreeMap::new(),
366                    }),
367                    turn: Condvar::new(),
368                }),
369            }
370        }
371
372        fn state(&self) -> std::sync::MutexGuard<'_, State> {
373            self.shared.state()
374        }
375
376        /// From now on, a sync through a handle waits until `release_syncs`.
377        pub(crate) fn hold_syncs(&self) {
378            self.state().hold_syncs = true;
379        }
380
381        /// Lets every held sync go on, and later ones run at once.
382        pub(crate) fn release_syncs(&self) {
383            self.state().hold_syncs = false;
384            self.shared.turn.notify_all();
385        }
386
387        /// From now on, a sync through a handle fails, as a failed
388        /// writeback would make it.
389        pub(crate) fn fail_syncs(&self) {
390            self.state().fail_syncs = true;
391            self.shared.turn.notify_all();
392        }
393
394        /// Syncs through handles succeed again.
395        pub(crate) fn heal_syncs(&self) {
396            self.state().fail_syncs = false;
397        }
398
399        /// The syncs done through handles of `path` so far.
400        pub(crate) fn syncs(&self, path: &Path) -> usize {
401            self.state().syncs.get(path).copied().unwrap_or(0)
402        }
403
404        /// Waits until `n` syncs are held; panics after 20 s, so a test
405        /// that never holds one fails instead of hanging.
406        pub(crate) fn await_held(&self, n: usize) {
407            let deadline = Instant::now() + Duration::from_secs(20);
408            let mut state = self.state();
409            while state.held < n {
410                let left = deadline.saturating_duration_since(Instant::now());
411                assert!(!left.is_zero(), "{n} syncs held within 20 s");
412                state = self
413                    .shared
414                    .turn
415                    .wait_timeout(state, left)
416                    .expect("no test panicked holding the lock")
417                    .0;
418            }
419        }
420
421        /// Loses everything not yet synced.
422        pub(crate) fn crash(&self) {
423            let mut state = self.state();
424            state.fail_from = None;
425            for dir in state.dirs.values_mut() {
426                dir.now = dir.synced.clone();
427            }
428            for file in &mut state.files {
429                file.now = file.synced.clone();
430            }
431        }
432
433        /// From the `n`th change on (counting from 0 over the whole log),
434        /// every change fails and changes nothing, as for a process that
435        /// has died. `crash` clears it.
436        pub(crate) fn fail_from(&self, n: usize) {
437            self.state().fail_from = Some(n);
438        }
439
440        /// Ends the fail point without a crash: later changes work again
441        /// and nothing is lost, as after an I/O error the process lived
442        /// through. A test uses it to see what a live process does next
443        /// (a poisoned catalog stays poisoned).
444        pub(crate) fn revive(&self) {
445            self.state().fail_from = None;
446        }
447
448        /// Every change so far, in order.
449        pub(crate) fn log(&self) -> Vec<Op> {
450            self.state().log.clone()
451        }
452    }
453
454    impl Fs for CrashFs {
455        fn write_new(&self, path: &Path, data: &[u8]) -> io::Result<()> {
456            let (dir, name) = split(path)?;
457            let mut state = self.state();
458            state.alive()?;
459            let index = state.files.len();
460            let entries = &mut state.dir(&dir)?.now;
461            if entries.contains_key(&name) {
462                return Err(io::Error::from(io::ErrorKind::AlreadyExists));
463            }
464            entries.insert(name, Entry::File(index));
465            state.files.push(File {
466                now: data.to_vec(),
467                synced: Vec::new(),
468            });
469            state.log.push(Op::Write(path.to_owned()));
470            Ok(())
471        }
472
473        fn sync_file(&self, path: &Path) -> io::Result<()> {
474            let mut state = self.state();
475            state.alive()?;
476            let index = state.file(path)?;
477            let file = &mut state.files[index];
478            file.synced = file.now.clone();
479            state.log.push(Op::SyncFile(path.to_owned()));
480            Ok(())
481        }
482
483        fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
484            let ((from_dir, from_name), (to_dir, to_name)) = (split(from)?, split(to)?);
485            let mut state = self.state();
486            state.alive()?;
487            let index = state.file(from)?;
488            state.dir(&to_dir)?;
489            state.dir(&from_dir)?.now.remove(&from_name);
490            state.dir(&to_dir)?.now.insert(to_name, Entry::File(index));
491            state.log.push(Op::Rename(from.to_owned(), to.to_owned()));
492            Ok(())
493        }
494
495        fn rename_new(&self, from: &Path, to: &Path) -> io::Result<()> {
496            let (to_dir, to_name) = split(to)?;
497            {
498                let mut state = self.state();
499                state.alive()?;
500                if state.dir(&to_dir)?.now.contains_key(&to_name) {
501                    return Err(io::Error::from(io::ErrorKind::AlreadyExists));
502                }
503            }
504            self.rename(from, to)
505        }
506
507        fn sync_dir(&self, dir: &Path) -> io::Result<()> {
508            let mut state = self.state();
509            state.alive()?;
510            let entries = state.dir(dir)?;
511            entries.synced = entries.now.clone();
512            state.log.push(Op::SyncDir(dir.to_owned()));
513            Ok(())
514        }
515
516        fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
517            let mut state = self.state();
518            let index = state.file(path)?;
519            Ok(state.files[index].now.clone())
520        }
521
522        fn remove(&self, path: &Path) -> io::Result<()> {
523            let (dir, name) = split(path)?;
524            let mut state = self.state();
525            state.alive()?;
526            state.file(path)?;
527            state.dir(&dir)?.now.remove(&name);
528            state.log.push(Op::Remove(path.to_owned()));
529            Ok(())
530        }
531
532        fn list(&self, dir: &Path) -> io::Result<Vec<OsString>> {
533            Ok(self.state().dir(dir)?.now.keys().cloned().collect())
534        }
535
536        fn create_dir_all(&self, dir: &Path) -> io::Result<()> {
537            let mut state = self.state();
538            state.alive()?;
539            let below = dir
540                .strip_prefix(&state.root)
541                .map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?
542                .to_owned();
543            // Find what is missing before touching the disk, so a refusal
544            // makes nothing there either.
545            let mut path = state.root.clone();
546            let mut missing = Vec::new();
547            for part in &below {
548                let next = path.join(part);
549                let parent = std::mem::replace(&mut path, next);
550                if !missing.is_empty() {
551                    missing.push(path.clone());
552                    continue;
553                }
554                match state.dir(&parent)?.now.get(part) {
555                    Some(Entry::Dir) => {}
556                    Some(Entry::File(_)) => {
557                        return Err(io::Error::from(io::ErrorKind::AlreadyExists));
558                    }
559                    None => missing.push(path.clone()),
560                }
561            }
562            if missing.is_empty() {
563                return Ok(());
564            }
565            std::fs::create_dir_all(dir)?;
566            for path in missing {
567                let (parent, name) = split(&path)?;
568                state.dir(&parent)?.now.insert(name, Entry::Dir);
569                state.dirs.insert(path, Dir::default());
570            }
571            state.log.push(Op::CreateDir(dir.to_owned()));
572            Ok(())
573        }
574
575        fn remove_dir_all(&self, dir: &Path) -> io::Result<()> {
576            let (parent, name) = split(dir)?;
577            let mut state = self.state();
578            state.alive()?;
579            if !state.exists(dir) {
580                return Err(not_found());
581            }
582            state.dir(&parent)?.now.remove(&name);
583            state.log.push(Op::RemoveDir(dir.to_owned()));
584            Ok(())
585        }
586
587        fn open_for_sync(&self, path: &Path) -> io::Result<Box<dyn SyncHandle>> {
588            Ok(Box::new(CrashSync {
589                path: path.to_owned(),
590                file: std::fs::File::open(path)?,
591                shared: self.shared.clone(),
592            }))
593        }
594    }
595
596    /// A handle of a file on disk whose syncs the crash filesystem holds,
597    /// fails, logs and counts.
598    struct CrashSync {
599        path: PathBuf,
600        file: std::fs::File,
601        shared: Arc<Shared>,
602    }
603
604    impl SyncHandle for CrashSync {
605        fn sync_data(&self) -> io::Result<()> {
606            let mut state = self.shared.state();
607            state.alive()?;
608            state.held += 1;
609            self.shared.turn.notify_all();
610            // A test that never lets a held sync go fails here, after 60 s,
611            // instead of hanging.
612            let deadline = Instant::now() + Duration::from_secs(60);
613            while state.hold_syncs && !state.fail_syncs {
614                let left = deadline.saturating_duration_since(Instant::now());
615                if left.is_zero() {
616                    state.held -= 1;
617                    return Err(io::Error::other("a held sync was not let go within 60 s"));
618                }
619                state = self
620                    .shared
621                    .turn
622                    .wait_timeout(state, left)
623                    .expect("no test panicked holding the lock")
624                    .0;
625            }
626            state.held -= 1;
627            if state.fail_syncs {
628                return Err(io::Error::other("the writeback failed"));
629            }
630            self.file.sync_data()?;
631            state.log.push(Op::SyncData(self.path.clone()));
632            *state.syncs.entry(self.path.clone()).or_default() += 1;
633            Ok(())
634        }
635    }
636}
637
638#[cfg(test)]
639mod tests {
640    use std::io::ErrorKind::{AlreadyExists, NotFound};
641    use std::path::PathBuf;
642
643    use super::*;
644
645    /// What every implementation must do, crash or no crash.
646    fn behaves_like_a_filesystem(fs: &dyn Fs, root: &Path) {
647        let dir = root.join("objects");
648        let (a, b) = (dir.join("a"), dir.join("b"));
649        assert_eq!(
650            fs.write_new(&a, b"x").map_err(|e| e.kind()),
651            Err(NotFound),
652            "no dir yet"
653        );
654        fs.create_dir_all(&dir).expect("create the dir");
655        fs.create_dir_all(&dir).expect("create it again");
656        fs.write_new(&a, b"one").expect("write");
657        assert_eq!(
658            fs.write_new(&a, b"two").map_err(|e| e.kind()),
659            Err(AlreadyExists),
660            "write_new never replaces a file"
661        );
662        assert!(fs.create_dir_all(&a).is_err(), "a file has the name");
663        assert!(
664            fs.create_dir_all(&a.join("d")).is_err(),
665            "a file stands in the way"
666        );
667        assert!(!a.join("d").exists(), "and nothing is made on disk");
668        assert_eq!(
669            fs.read(&a).expect("read"),
670            b"one",
671            "the refused write left the first one"
672        );
673        fs.sync_file(&a).expect("sync the file");
674        fs.sync_dir(&dir).expect("sync the dir");
675        fs.rename(&a, &b).expect("rename");
676        assert_eq!(
677            fs.read(&a).map_err(|e| e.kind()),
678            Err(NotFound),
679            "rename moves the file away"
680        );
681        assert_eq!(
682            fs.read(&b).expect("read"),
683            b"one",
684            "the file is under its new name"
685        );
686        fs.rename(&b, &b).expect("rename onto itself");
687        assert_eq!(
688            fs.read(&b).expect("read"),
689            b"one",
690            "renaming onto itself changes nothing"
691        );
692        fs.write_new(&a, b"three").expect("write again");
693        fs.rename(&a, &b).expect("rename over");
694        assert_eq!(
695            fs.read(&b).expect("read"),
696            b"three",
697            "rename replaces the target"
698        );
699        fs.write_new(&a, b"four").expect("write");
700        fs.create_dir_all(&dir.join("c"))
701            .expect("a directory inside");
702        assert_eq!(
703            fs.list(&dir).expect("list"),
704            ["a", "b", "c"].map(OsString::from),
705            "files and directories, sorted"
706        );
707        assert_eq!(
708            fs.write_new(&dir.join("c"), b"x").map_err(|e| e.kind()),
709            Err(AlreadyExists),
710            "a directory's name is taken"
711        );
712        assert!(
713            fs.remove(&dir.join("c")).is_err(),
714            "remove takes only a file"
715        );
716        assert!(
717            fs.remove_dir_all(&a).is_err(),
718            "remove_dir_all takes only a directory"
719        );
720        fs.create_dir_all(&dir.join("c/d"))
721            .expect("a directory inside c");
722        fs.write_new(&dir.join("c/f"), b"x")
723            .expect("a file inside c");
724        fs.remove_dir_all(&dir.join("c"))
725            .expect("remove c and all in it");
726        assert_eq!(
727            fs.list(&dir.join("c")).map_err(|e| e.kind()),
728            Err(NotFound),
729            "remove_dir_all removed c itself"
730        );
731        assert_eq!(
732            fs.remove_dir_all(&dir.join("c")).map_err(|e| e.kind()),
733            Err(NotFound),
734            "a directory that is gone cannot be removed again"
735        );
736        fs.create_dir_all(&dir.join("c")).expect("c again");
737        fs.remove(&a).expect("remove");
738        fs.remove(&b).expect("remove");
739        assert_eq!(
740            fs.list(&dir).expect("list"),
741            [OsString::from("c")],
742            "the removed files are gone and c is left"
743        );
744        assert_eq!(
745            fs.remove(&b).map_err(|e| e.kind()),
746            Err(NotFound),
747            "b was removed"
748        );
749        assert_eq!(
750            fs.sync_file(&b).map_err(|e| e.kind()),
751            Err(NotFound),
752            "b was removed"
753        );
754        assert_eq!(
755            fs.sync_dir(&root.join("none")).map_err(|e| e.kind()),
756            Err(NotFound),
757            "no directory has that name"
758        );
759        assert_eq!(
760            fs.list(&root.join("none")).map_err(|e| e.kind()),
761            Err(NotFound),
762            "no directory has that name"
763        );
764        let (x, y, z) = (dir.join("x"), dir.join("y"), dir.join("z"));
765        fs.write_new(&x, b"five").expect("write x");
766        fs.write_new(&y, b"six").expect("write y");
767        assert_eq!(
768            fs.rename_new(&x, &y).map_err(|e| e.kind()),
769            Err(AlreadyExists),
770            "rename_new never replaces a file"
771        );
772        assert_eq!(fs.read(&x).expect("read x"), b"five", "x is left");
773        assert_eq!(fs.read(&y).expect("read y"), b"six", "y is left");
774        fs.rename_new(&x, &z).expect("rename onto a free name");
775        assert_eq!(fs.read(&z).expect("read z"), b"five", "under its new name");
776        assert_eq!(
777            fs.read(&x).map_err(|e| e.kind()),
778            Err(NotFound),
779            "rename_new moves the file away"
780        );
781    }
782
783    #[test]
784    fn the_os_filesystem_behaves_like_a_filesystem() {
785        let root = tempfile::tempdir().expect("temp dir");
786        behaves_like_a_filesystem(&OsFs, root.path());
787    }
788
789    #[test]
790    fn the_crash_filesystem_behaves_like_a_filesystem() {
791        let root = tempfile::tempdir().expect("temp dir");
792        behaves_like_a_filesystem(&CrashFs::new(root.path()), root.path());
793    }
794
795    /// A crash filesystem rooted at a temporary directory.
796    struct Model {
797        root: tempfile::TempDir,
798        fs: CrashFs,
799    }
800
801    impl Model {
802        fn new() -> Model {
803            let root = tempfile::tempdir().expect("temp dir");
804            let fs = CrashFs::new(root.path());
805            Model { root, fs }
806        }
807
808        fn root(&self) -> &Path {
809            self.root.path()
810        }
811
812        /// The directory the file tests use, made and synced.
813        fn dir(&self) -> PathBuf {
814            self.root().join("objects")
815        }
816
817        fn f(&self) -> PathBuf {
818            self.dir().join("f")
819        }
820    }
821
822    /// A model with a durable `dir()`, after `steps` on its file `f()`.
823    fn after(steps: impl FnOnce(&CrashFs, &Path)) -> Model {
824        let m = Model::new();
825        m.fs.create_dir_all(&m.dir()).expect("create the dir");
826        m.fs.sync_dir(m.root()).expect("sync the root");
827        steps(&m.fs, &m.f());
828        m
829    }
830
831    fn synced(fs: &CrashFs, f: &Path) {
832        fs.write_new(f, b"data").expect("write");
833        fs.sync_file(f).expect("sync the file");
834        fs.sync_dir(f.parent().expect("a dir"))
835            .expect("sync the dir");
836    }
837
838    #[test]
839    fn a_crash_drops_a_file_whose_entry_was_not_synced() {
840        for sync_data in [false, true] {
841            let m = after(|fs, f| {
842                fs.write_new(f, b"data").expect("write");
843                if sync_data {
844                    fs.sync_file(f).expect("sync the file");
845                }
846            });
847            m.fs.crash();
848            assert_eq!(
849                m.fs.read(&m.f()).map_err(|e| e.kind()),
850                Err(NotFound),
851                "the entry was never synced, so the crash loses the file (data synced: {sync_data})"
852            );
853        }
854    }
855
856    #[test]
857    fn a_crash_empties_a_file_whose_data_was_not_synced() {
858        let m = after(|fs, f| {
859            fs.write_new(f, b"data").expect("write");
860            fs.sync_dir(f.parent().expect("a dir"))
861                .expect("sync the dir");
862        });
863        m.fs.crash();
864        assert_eq!(
865            m.fs.read(&m.f()).expect("the entry survives"),
866            b"",
867            "the entry was synced but the data was not, so the file comes back empty"
868        );
869    }
870
871    #[test]
872    fn a_crash_keeps_a_file_synced_in_both_ways() {
873        let m = after(synced);
874        m.fs.crash();
875        assert_eq!(
876            m.fs.read(&m.f()).expect("survives"),
877            b"data",
878            "data and entry were both synced, so the crash keeps the file whole"
879        );
880    }
881
882    #[test]
883    fn a_rename_or_remove_survives_a_crash_only_once_the_dir_is_synced() {
884        for sync in [false, true] {
885            let renamed = after(|fs, f| {
886                synced(fs, f);
887                fs.rename(f, &f.with_file_name("g")).expect("rename");
888                if sync {
889                    fs.sync_dir(f.parent().expect("a dir"))
890                        .expect("sync the dir");
891                }
892            });
893            renamed.fs.crash();
894            let names = if sync { ["g"] } else { ["f"] };
895            assert_eq!(
896                renamed.fs.list(&renamed.dir()).expect("list"),
897                names.map(OsString::from),
898                "rename, sync {sync}"
899            );
900            assert_eq!(
901                renamed
902                    .fs
903                    .read(&renamed.dir().join(names[0]))
904                    .expect("read"),
905                b"data",
906                "whichever name survives, the synced data is under it"
907            );
908
909            let removed = after(|fs, f| {
910                synced(fs, f);
911                fs.remove(f).expect("remove");
912                if sync {
913                    fs.sync_dir(f.parent().expect("a dir"))
914                        .expect("sync the dir");
915                }
916            });
917            removed.fs.crash();
918            let left = removed.fs.list(&removed.dir()).expect("list").len();
919            assert_eq!(left, usize::from(!sync), "remove, sync {sync}");
920        }
921    }
922
923    #[test]
924    fn a_new_directory_survives_a_crash_only_once_its_parent_is_synced() {
925        let m = Model::new();
926        let (a, b) = (m.root().join("a"), m.root().join("a/b"));
927        m.fs.create_dir_all(&b).expect("create a/b");
928        m.fs.crash();
929        assert_eq!(
930            m.fs.list(m.root()).expect("list"),
931            Vec::<OsString>::new(),
932            "nothing was synced, so the crash loses a"
933        );
934        assert_eq!(
935            m.fs.list(&a).map_err(|e| e.kind()),
936            Err(NotFound),
937            "a is gone after the crash"
938        );
939
940        m.fs.create_dir_all(&b).expect("create a/b");
941        m.fs.sync_dir(&a).expect("sync a, not the root");
942        m.fs.crash();
943        assert_eq!(
944            m.fs.list(&b).map_err(|e| e.kind()),
945            Err(NotFound),
946            "b is lost with a"
947        );
948
949        m.fs.create_dir_all(&b).expect("create a/b");
950        m.fs.sync_dir(m.root()).expect("sync the root");
951        m.fs.crash();
952        assert_eq!(
953            m.fs.list(m.root()).expect("list"),
954            [OsString::from("a")],
955            "the root was synced, so its entry for a survives"
956        );
957        assert_eq!(
958            m.fs.list(&a).expect("a survives"),
959            Vec::<OsString>::new(),
960            "b's entry in a was never synced"
961        );
962
963        m.fs.create_dir_all(&b).expect("create b");
964        m.fs.sync_dir(&a).expect("sync a");
965        m.fs.crash();
966        assert_eq!(
967            m.fs.list(&b).expect("b survives"),
968            Vec::<OsString>::new(),
969            "a was synced, so its entry for b survives, and b is empty"
970        );
971    }
972
973    #[test]
974    fn a_lost_directory_takes_its_synced_files_with_it() {
975        let m = Model::new();
976        let a = m.root().join("a");
977        m.fs.create_dir_all(&a).expect("create a");
978        synced(&m.fs, &a.join("f"));
979        m.fs.crash();
980        assert_eq!(
981            m.fs.list(m.root()).expect("list"),
982            Vec::<OsString>::new(),
983            "the root was never synced, so a is lost with its synced file"
984        );
985        m.fs.create_dir_all(&a).expect("create a again");
986        assert_eq!(
987            m.fs.list(&a).expect("list"),
988            Vec::<OsString>::new(),
989            "a new directory starts empty"
990        );
991    }
992
993    #[test]
994    fn a_directory_removal_survives_a_crash_only_once_its_parent_is_synced() {
995        for sync in [false, true] {
996            let m = Model::new();
997            let a = m.root().join("a");
998            m.fs.create_dir_all(&a).expect("create a");
999            synced(&m.fs, &a.join("f"));
1000            m.fs.sync_dir(m.root()).expect("sync the root");
1001            m.fs.remove_dir_all(&a).expect("remove a");
1002            if sync {
1003                m.fs.sync_dir(m.root()).expect("sync the root");
1004            }
1005            m.fs.crash();
1006            if sync {
1007                assert_eq!(
1008                    m.fs.list(&a).map_err(|e| e.kind()),
1009                    Err(NotFound),
1010                    "the root was synced after the removal, so it holds"
1011                );
1012            } else {
1013                assert_eq!(
1014                    m.fs.read(&a.join("f")).expect("back"),
1015                    b"data",
1016                    "the removal was never synced, so a comes back with its file"
1017                );
1018            }
1019        }
1020    }
1021
1022    /// A crash may bring a removed directory back, and SQLite's files in
1023    /// it must then still be there, so removal touches only the model.
1024    #[test]
1025    fn a_directory_is_removed_only_from_the_model() {
1026        let m = Model::new();
1027        let a = m.root().join("a");
1028        m.fs.create_dir_all(&a).expect("create a");
1029        m.fs.remove_dir_all(&a).expect("remove a");
1030        assert!(
1031            a.is_dir(),
1032            "the directory stays on disk, for a crash that brings it back"
1033        );
1034    }
1035
1036    /// SQLite opens its files on disk, so a directory made in the model is
1037    /// made on disk too.
1038    #[test]
1039    fn a_directory_is_also_made_on_disk() {
1040        let m = Model::new();
1041        let b = m.root().join("a/b");
1042        m.fs.create_dir_all(&b).expect("create a/b");
1043        assert!(
1044            b.is_dir(),
1045            "the directory is on disk, where SQLite will open its files"
1046        );
1047    }
1048
1049    #[test]
1050    fn nothing_outside_the_root_can_be_made() {
1051        let m = Model::new();
1052        let outside = m.root().with_file_name("elsewhere-5c1e");
1053        assert!(
1054            m.fs.create_dir_all(&outside).is_err(),
1055            "the model refuses a path outside its root"
1056        );
1057        assert!(!outside.exists(), "and makes nothing there on disk");
1058    }
1059
1060    #[test]
1061    fn every_call_that_changes_state_is_logged_in_order() {
1062        let m = Model::new();
1063        let (dir, f, g) = (m.dir(), m.f(), m.dir().join("g"));
1064        m.fs.create_dir_all(&dir).expect("create the dir");
1065        m.fs.create_dir_all(&dir).expect("already there: no change");
1066        synced(&m.fs, &f);
1067        m.fs.rename(&f, &g).expect("rename");
1068        m.fs.remove(&g).expect("remove");
1069        m.fs.remove_dir_all(&dir).expect("remove the dir");
1070        assert_eq!(
1071            m.fs.log(),
1072            [
1073                Op::CreateDir(dir.clone()),
1074                Op::Write(f.clone()),
1075                Op::SyncFile(f.clone()),
1076                Op::SyncDir(dir.clone()),
1077                Op::Rename(f, g.clone()),
1078                Op::Remove(g),
1079                Op::RemoveDir(dir),
1080            ],
1081            "one entry per change, in order; the create that changed nothing is not logged"
1082        );
1083    }
1084
1085    #[test]
1086    fn from_the_fail_point_on_no_change_happens_until_a_crash() {
1087        let m = after(|fs, f| fs.write_new(f, b"data").expect("write"));
1088        let ops = m.fs.log().len();
1089        m.fs.fail_from(ops);
1090        let (f, g) = (m.f(), m.dir().join("g"));
1091        assert!(m.fs.sync_file(&f).is_err(), "sync");
1092        assert!(m.fs.write_new(&g, b"x").is_err(), "write");
1093        assert!(m.fs.rename(&f, &g).is_err(), "rename");
1094        assert!(m.fs.sync_dir(&m.dir()).is_err(), "sync dir");
1095        assert!(m.fs.remove(&f).is_err(), "remove");
1096        assert!(
1097            m.fs.create_dir_all(&m.dir().join("d")).is_err(),
1098            "create dir"
1099        );
1100        assert!(m.fs.remove_dir_all(&m.dir()).is_err(), "remove dir");
1101        assert!(!m.dir().join("d").exists(), "not made on disk either");
1102        assert_eq!(m.fs.log().len(), ops, "nothing changed");
1103        assert_eq!(
1104            m.fs.read(&f).expect("reads still work"),
1105            b"data",
1106            "the fail point stops changes, not reads"
1107        );
1108        m.fs.crash();
1109        m.fs.write_new(&g, b"x")
1110            .expect("works again after the crash");
1111    }
1112
1113    /// A file on disk, beside the model, as SQLite's WAL is.
1114    fn on_disk(root: &Path) -> PathBuf {
1115        let wal = root.join("catalog.sqlite-wal");
1116        std::fs::write(&wal, b"frames").expect("write the file on disk");
1117        wal
1118    }
1119
1120    #[test]
1121    fn the_os_filesystem_opens_an_existing_file_for_sync_and_syncs_it_again_and_again() {
1122        let root = tempfile::tempdir().expect("temp dir");
1123        let wal = on_disk(root.path());
1124        let handle = OsFs.open_for_sync(&wal).expect("opens");
1125        handle.sync_data().expect("the first sync");
1126        std::fs::OpenOptions::new()
1127            .append(true)
1128            .open(&wal)
1129            .and_then(|mut f| f.write_all(b"more"))
1130            .expect("another writer appends");
1131        handle.sync_data().expect("the same handle syncs again");
1132    }
1133
1134    #[test]
1135    fn the_os_filesystem_refuses_to_open_a_missing_file_for_sync() {
1136        let root = tempfile::tempdir().expect("temp dir");
1137        let missing = root.path().join("catalog.sqlite-wal");
1138        assert_eq!(
1139            OsFs.open_for_sync(&missing).err().map(|e| e.kind()),
1140            Some(NotFound),
1141            "no file, no handle: the WAL must exist before it is opened for sync"
1142        );
1143        assert!(!missing.exists(), "opening for sync never creates the file");
1144    }
1145
1146    #[test]
1147    fn the_crash_filesystem_refuses_to_open_a_missing_file_for_sync() {
1148        let m = Model::new();
1149        assert_eq!(
1150            m.fs.open_for_sync(&m.root().join("absent-wal"))
1151                .err()
1152                .map(|e| e.kind()),
1153            Some(NotFound),
1154            "a handle is of a file on disk"
1155        );
1156    }
1157
1158    #[test]
1159    fn a_sync_through_a_crash_handle_is_logged_in_order_and_counted() {
1160        let m = Model::new();
1161        let wal = on_disk(m.root());
1162        let handle = m.fs.open_for_sync(&wal).expect("opens");
1163        assert_eq!(m.fs.syncs(&wal), 0, "opening is not a sync");
1164        m.fs.create_dir_all(&m.dir()).expect("create the dir");
1165        handle.sync_data().expect("sync");
1166        m.fs.sync_dir(&m.dir()).expect("sync the dir");
1167        handle.sync_data().expect("sync again");
1168        assert_eq!(
1169            m.fs.log(),
1170            [
1171                Op::CreateDir(m.dir()),
1172                Op::SyncData(wal.clone()),
1173                Op::SyncDir(m.dir()),
1174                Op::SyncData(wal.clone()),
1175            ],
1176            "each sync is logged where it happened"
1177        );
1178        assert_eq!(m.fs.syncs(&wal), 2, "and counted per file");
1179    }
1180
1181    #[test]
1182    fn a_failing_crash_handle_fails_every_sync_and_logs_none() {
1183        let m = Model::new();
1184        let wal = on_disk(m.root());
1185        let handle = m.fs.open_for_sync(&wal).expect("opens");
1186        m.fs.fail_syncs();
1187        assert!(handle.sync_data().is_err(), "the first sync fails");
1188        assert!(handle.sync_data().is_err(), "and every later one");
1189        assert_eq!(m.fs.syncs(&wal), 0, "a failed sync is not counted");
1190        assert!(m.fs.log().is_empty(), "nor logged");
1191    }
1192
1193    #[test]
1194    fn a_crash_handle_cannot_sync_once_the_process_has_died() {
1195        let m = Model::new();
1196        let wal = on_disk(m.root());
1197        let handle = m.fs.open_for_sync(&wal).expect("opens");
1198        m.fs.fail_from(0);
1199        assert!(handle.sync_data().is_err(), "a dead process syncs nothing");
1200        assert_eq!(m.fs.syncs(&wal), 0, "nothing counted");
1201    }
1202
1203    #[test]
1204    fn a_held_sync_waits_until_it_is_let_go_and_other_calls_go_on() {
1205        let m = Model::new();
1206        let wal = on_disk(m.root());
1207        let handle = m.fs.open_for_sync(&wal).expect("opens");
1208        m.fs.hold_syncs();
1209        std::thread::scope(|s| {
1210            let syncing = s.spawn(|| handle.sync_data());
1211            m.fs.await_held(1);
1212            assert!(!syncing.is_finished(), "the sync waits while held");
1213            assert_eq!(m.fs.syncs(&wal), 0, "and has not happened");
1214            m.fs.create_dir_all(&m.dir())
1215                .expect("other calls are not held");
1216            m.fs.release_syncs();
1217            syncing
1218                .join()
1219                .expect("the sync thread ends")
1220                .expect("and syncs once let go");
1221        });
1222        assert_eq!(m.fs.syncs(&wal), 1, "one sync, after the release");
1223        assert_eq!(
1224            m.fs.log(),
1225            [Op::CreateDir(m.dir()), Op::SyncData(wal)],
1226            "the held sync is logged after what ran while it waited"
1227        );
1228    }
1229
1230    #[test]
1231    fn a_held_sync_fails_when_syncs_are_made_to_fail_while_it_waits() {
1232        let m = Model::new();
1233        let wal = on_disk(m.root());
1234        let handle = m.fs.open_for_sync(&wal).expect("opens");
1235        m.fs.hold_syncs();
1236        std::thread::scope(|s| {
1237            let syncing = s.spawn(|| handle.sync_data());
1238            m.fs.await_held(1);
1239            m.fs.fail_syncs();
1240            assert!(
1241                syncing.join().expect("the sync thread ends").is_err(),
1242                "a sync held when syncs start to fail fails, without a release"
1243            );
1244        });
1245        assert_eq!(m.fs.syncs(&wal), 0, "not counted");
1246    }
1247
1248    #[test]
1249    fn a_revived_crash_filesystem_changes_again_and_loses_nothing() {
1250        let m = after(|fs, f| fs.write_new(f, b"data").expect("write"));
1251        m.fs.fail_from(m.fs.log().len());
1252        let g = m.dir().join("g");
1253        assert!(m.fs.write_new(&g, b"x").is_err(), "the fail point holds");
1254        m.fs.revive();
1255        m.fs.write_new(&g, b"x")
1256            .expect("a revived filesystem changes again");
1257        assert_eq!(
1258            m.fs.read(&m.f()).expect("still there"),
1259            b"data",
1260            "revive is not a crash: the unsynced write is kept"
1261        );
1262    }
1263
1264    #[test]
1265    fn a_revived_crash_handle_syncs_again() {
1266        let m = Model::new();
1267        let wal = on_disk(m.root());
1268        let handle = m.fs.open_for_sync(&wal).expect("opens");
1269        m.fs.fail_from(0);
1270        assert!(handle.sync_data().is_err(), "the fail point holds");
1271        m.fs.revive();
1272        handle.sync_data().expect("a revived handle syncs");
1273        assert_eq!(m.fs.syncs(&wal), 1, "counted once");
1274    }
1275}