armdb 0.15.0

sharded bitcask key-value storage optimized for NVMe
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
//! The one place where the segmented family touches the file system.
//!
//! Durable publication depends on the *order* of fsync and rename calls, and
//! on what the process does when one of them fails. Neither can be observed
//! through real files, so every such call goes through [`SegFs`]; tests
//! substitute [`TraceFs`] to record the order and to inject a failure.

use std::fs::{File, OpenOptions};
use std::io::{self, Write};
use std::path::Path;
use std::sync::Arc;

pub(crate) trait SegFs: Send + Sync + 'static {
    /// Create or truncate a file for writing.
    fn create(&self, path: &Path) -> io::Result<File>;
    /// Create a temporary file only if its name is unoccupied.
    fn create_new(&self, path: &Path) -> io::Result<File>;
    /// Write bytes to an open output. Routed here for deterministic fault tests.
    fn write_all(&self, out: &mut dyn Write, path: &Path, bytes: &[u8]) -> io::Result<()>;
    /// Make the contents of `file` durable. `path` is for tracing only.
    fn sync_file(&self, file: &File, path: &Path) -> io::Result<()>;
    fn rename(&self, from: &Path, to: &Path) -> io::Result<()>;
    /// Make the entries of `dir` durable: a preceding create, rename or
    /// unlink inside it survives a power loss only after this.
    fn sync_dir(&self, dir: &Path) -> io::Result<()>;
    fn create_dir_all(&self, dir: &Path) -> io::Result<()>;
    /// Succeeds when `path` does not exist.
    fn remove_file(&self, path: &Path) -> io::Result<()>;
    /// Succeeds when `dir` does not exist.
    fn remove_dir_all(&self, dir: &Path) -> io::Result<()>;
}

pub(crate) struct RealFs;

pub(crate) fn real() -> Arc<dyn SegFs> {
    Arc::new(RealFs)
}

fn absent_is_ok(result: io::Result<()>) -> io::Result<()> {
    match result {
        Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
        other => other,
    }
}

impl SegFs for RealFs {
    fn create(&self, path: &Path) -> io::Result<File> {
        File::create(path)
    }

    fn create_new(&self, path: &Path) -> io::Result<File> {
        OpenOptions::new().write(true).create_new(true).open(path)
    }

    fn write_all(&self, out: &mut dyn Write, _path: &Path, bytes: &[u8]) -> io::Result<()> {
        out.write_all(bytes)
    }

    fn sync_file(&self, file: &File, _path: &Path) -> io::Result<()> {
        file.sync_all()
    }

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

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

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

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

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

#[cfg(test)]
pub(crate) use trace::{FsOp, FsOpKind, TraceFs};

#[cfg(test)]
mod trace {
    use super::*;
    use std::path::PathBuf;
    use std::sync::Mutex;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) enum FsOpKind {
        Create,
        CreateNew,
        WriteAll,
        SyncFile,
        Rename,
        SyncDir,
        CreateDirAll,
        RemoveFile,
        RemoveDirAll,
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    pub(crate) enum FsOp {
        Create(PathBuf),
        CreateNew(PathBuf),
        WriteAll(PathBuf),
        SyncFile(PathBuf),
        Rename(PathBuf, PathBuf),
        SyncDir(PathBuf),
        CreateDirAll(PathBuf),
        RemoveFile(PathBuf),
        RemoveDirAll(PathBuf),
    }

    impl FsOp {
        pub(crate) fn kind(&self) -> FsOpKind {
            match self {
                Self::Create(_) => FsOpKind::Create,
                Self::CreateNew(_) => FsOpKind::CreateNew,
                Self::WriteAll(_) => FsOpKind::WriteAll,
                Self::SyncFile(_) => FsOpKind::SyncFile,
                Self::Rename(..) => FsOpKind::Rename,
                Self::SyncDir(_) => FsOpKind::SyncDir,
                Self::CreateDirAll(_) => FsOpKind::CreateDirAll,
                Self::RemoveFile(_) => FsOpKind::RemoveFile,
                Self::RemoveDirAll(_) => FsOpKind::RemoveDirAll,
            }
        }

        /// The path the operation acts on; for a rename, its destination.
        pub(crate) fn target(&self) -> &Path {
            match self {
                Self::Create(p)
                | Self::CreateNew(p)
                | Self::WriteAll(p)
                | Self::SyncFile(p)
                | Self::SyncDir(p)
                | Self::CreateDirAll(p)
                | Self::RemoveFile(p)
                | Self::RemoveDirAll(p) => p,
                Self::Rename(_, to) => to,
            }
        }

        /// Matches on the target's file name only, so a fragment cannot hit
        /// the test's temporary directory (`/tmp/.tmpXXXX`) by accident.
        fn matches(&self, kind: FsOpKind, name_contains: &str) -> bool {
            self.kind() == kind
                && self
                    .target()
                    .file_name()
                    .map_or(name_contains.is_empty(), |name| {
                        name.to_string_lossy().contains(name_contains)
                    })
        }
    }

    struct Fault {
        kind: FsOpKind,
        name_contains: String,
        skips_left: usize,
    }

    #[derive(Default)]
    struct TraceState {
        log: Vec<FsOp>,
        fault: Option<Fault>,
    }

    /// Real file system that records every non-injected call and can fail one.
    pub(crate) struct TraceFs {
        inner: RealFs,
        state: Mutex<TraceState>,
    }

    impl TraceFs {
        pub(crate) fn new() -> Arc<Self> {
            Arc::new(Self {
                inner: RealFs,
                state: Mutex::new(TraceState::default()),
            })
        }

        /// Fail the `nth` (zero-based) matching call. The fault fires once;
        /// the failed call performs nothing.
        pub(crate) fn fail_on(&self, kind: FsOpKind, name_contains: &str, nth: usize) {
            self.state.lock().unwrap().fault = Some(Fault {
                kind,
                name_contains: name_contains.to_owned(),
                skips_left: nth,
            });
        }

        pub(crate) fn ops(&self) -> Vec<FsOp> {
            self.state.lock().unwrap().log.clone()
        }

        pub(crate) fn clear(&self) {
            self.state.lock().unwrap().log.clear();
        }

        /// Index of the first recorded call that matches.
        pub(crate) fn position(&self, kind: FsOpKind, name_contains: &str) -> Option<usize> {
            self.state
                .lock()
                .unwrap()
                .log
                .iter()
                .position(|op| op.matches(kind, name_contains))
        }

        fn run<T>(
            &self,
            op: FsOp,
            operation: impl FnOnce(&RealFs) -> io::Result<T>,
        ) -> io::Result<T> {
            // Keep fault selection, trace order, and the forwarded call in one
            // critical section so the log reflects the order of filesystem calls.
            let mut state = self.state.lock().unwrap();
            let fires = match state.fault.as_mut() {
                Some(f) if op.matches(f.kind, &f.name_contains) => {
                    if f.skips_left == 0 {
                        true
                    } else {
                        f.skips_left -= 1;
                        false
                    }
                }
                _ => false,
            };
            if fires {
                state.fault = None;
                return Err(io::Error::other(format!("injected fault at {op:?}")));
            }
            state.log.push(op);
            operation(&self.inner)
        }
    }

    impl SegFs for TraceFs {
        fn create(&self, path: &Path) -> io::Result<File> {
            self.run(FsOp::Create(path.to_path_buf()), |fs| fs.create(path))
        }

        fn create_new(&self, path: &Path) -> io::Result<File> {
            self.run(FsOp::CreateNew(path.to_path_buf()), |fs| {
                fs.create_new(path)
            })
        }

        fn write_all(&self, out: &mut dyn Write, path: &Path, bytes: &[u8]) -> io::Result<()> {
            self.run(FsOp::WriteAll(path.to_path_buf()), |fs| {
                fs.write_all(out, path, bytes)
            })
        }

        fn sync_file(&self, file: &File, path: &Path) -> io::Result<()> {
            self.run(FsOp::SyncFile(path.to_path_buf()), |fs| {
                fs.sync_file(file, path)
            })
        }

        fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
            self.run(FsOp::Rename(from.to_path_buf(), to.to_path_buf()), |fs| {
                fs.rename(from, to)
            })
        }

        fn sync_dir(&self, dir: &Path) -> io::Result<()> {
            self.run(FsOp::SyncDir(dir.to_path_buf()), |fs| fs.sync_dir(dir))
        }

        fn create_dir_all(&self, dir: &Path) -> io::Result<()> {
            self.run(FsOp::CreateDirAll(dir.to_path_buf()), |fs| {
                fs.create_dir_all(dir)
            })
        }

        fn remove_file(&self, path: &Path) -> io::Result<()> {
            self.run(FsOp::RemoveFile(path.to_path_buf()), |fs| {
                fs.remove_file(path)
            })
        }

        fn remove_dir_all(&self, dir: &Path) -> io::Result<()> {
            self.run(FsOp::RemoveDirAll(dir.to_path_buf()), |fs| {
                fs.remove_dir_all(dir)
            })
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use std::sync::mpsc;
        use std::time::Duration;

        #[test]
        fn concurrent_calls_are_recorded_in_forwarded_operation_order() {
            let fs = TraceFs::new();
            let (first_started_tx, first_started_rx) = mpsc::channel();
            let (release_first_tx, release_first_rx) = mpsc::channel();
            let (second_attempted_tx, second_attempted_rx) = mpsc::channel();
            let (second_started_tx, second_started_rx) = mpsc::channel();

            let first_fs = fs.clone();
            let first = std::thread::spawn(move || {
                first_fs.run(FsOp::SyncDir("first".into()), |_| {
                    first_started_tx.send(()).unwrap();
                    release_first_rx.recv().unwrap();
                    Ok(())
                })
            });
            first_started_rx.recv().unwrap();

            let second_fs = fs.clone();
            let second = std::thread::spawn(move || {
                second_attempted_tx.send(()).unwrap();
                second_fs.run(FsOp::SyncDir("second".into()), |_| {
                    second_started_tx.send(()).unwrap();
                    Ok(())
                })
            });
            second_attempted_rx.recv().unwrap();

            let second_started_early = second_started_rx
                .recv_timeout(Duration::from_millis(100))
                .is_ok();
            release_first_tx.send(()).unwrap();
            first.join().unwrap().unwrap();
            second.join().unwrap().unwrap();
            assert!(
                !second_started_early,
                "the second operation ran before the first completed"
            );
            assert_eq!(
                fs.ops(),
                [
                    FsOp::SyncDir("first".into()),
                    FsOp::SyncDir("second".into())
                ]
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    #[test]
    fn real_fs_round_trips_a_file() {
        let dir = tempfile::tempdir().unwrap();
        let fs = RealFs;
        let tmp = dir.path().join("a.tmp");
        let dst = dir.path().join("a");
        let mut file = fs.create(&tmp).unwrap();
        file.write_all(b"payload").unwrap();
        fs.sync_file(&file, &tmp).unwrap();
        drop(file);
        fs.rename(&tmp, &dst).unwrap();
        fs.sync_dir(dir.path()).unwrap();
        assert_eq!(std::fs::read(&dst).unwrap(), b"payload");
        assert!(!tmp.exists());
    }

    #[test]
    fn removing_something_absent_is_not_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let fs = RealFs;
        fs.remove_file(&dir.path().join("nope")).unwrap();
        fs.remove_dir_all(&dir.path().join("nope-dir")).unwrap();
    }

    #[test]
    fn trace_fs_records_operations_in_order() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let tmp = dir.path().join("MANIFEST.tmp");
        let dst = dir.path().join("MANIFEST");
        let file = fs.create(&tmp).unwrap();
        fs.sync_file(&file, &tmp).unwrap();
        drop(file);
        fs.rename(&tmp, &dst).unwrap();
        fs.sync_dir(dir.path()).unwrap();

        let kinds: Vec<FsOpKind> = fs.ops().iter().map(FsOp::kind).collect();
        assert_eq!(
            kinds,
            [
                FsOpKind::Create,
                FsOpKind::SyncFile,
                FsOpKind::Rename,
                FsOpKind::SyncDir
            ]
        );
        let sync = fs.position(FsOpKind::SyncFile, "MANIFEST.tmp").unwrap();
        let rename = fs.position(FsOpKind::Rename, "MANIFEST").unwrap();
        assert!(sync < rename);
    }

    #[test]
    fn an_injected_fault_fires_once_and_does_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        let a = dir.path().join("a");
        let b = dir.path().join("b");
        std::fs::write(&a, b"x").unwrap();

        fs.fail_on(FsOpKind::Rename, "b", 0);
        let err = fs.rename(&a, &b).unwrap_err();
        assert!(err.to_string().contains("injected"));
        assert!(a.exists(), "a failed rename must not move the file");
        assert!(!b.exists());

        fs.rename(&a, &b).unwrap();
        assert!(b.exists());
    }

    #[test]
    fn a_fault_can_skip_the_first_matches() {
        let dir = tempfile::tempdir().unwrap();
        let fs = TraceFs::new();
        fs.fail_on(FsOpKind::SyncDir, "", 1);
        fs.sync_dir(dir.path()).unwrap();
        assert!(fs.sync_dir(dir.path()).is_err());
        fs.sync_dir(dir.path()).unwrap();
    }
}