armdb 0.15.1

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
use std::path::Path;
use std::time::Duration;

use armour_core::Typ;

use crate::{Config, DbResult, FixedConfig};

/// Child-process crash injection for the format-migration durable state machine.
///
/// This is deliberately exposed only by `test-faults`: production builds have
/// neither the atomics nor the exit seam.
#[cfg(any(test, feature = "test-faults"))]
pub mod failpoints {
    use std::path::{Path, PathBuf};
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicU8, Ordering};

    pub const NONE: u8 = 0;
    pub const AFTER_FORMAT_VERSION: u8 = 1;
    pub const BEFORE_SOURCE_RENAME: u8 = 2;
    pub const AFTER_SOURCE_RENAME: u8 = 3;
    pub const BEFORE_TARGET_RENAME: u8 = 4;
    pub const AFTER_TARGET_RENAME: u8 = 5;
    pub const BEFORE_OLD_REMOVE: u8 = 6;
    pub const AFTER_OLD_REMOVE: u8 = 7;
    pub const BEFORE_INFO_COMMIT: u8 = 8;
    pub const AFTER_INFO_COMMIT: u8 = 9;
    pub const BEFORE_MARKER_REMOVE: u8 = 10;
    pub const DURING_STAGE_FINALIZE: u8 = 11;
    /// Exit after rewriting the first page and tag, before completing a reseal.
    pub const DURING_STAGE_RESEAL: u8 = 12;

    /// Ordinary-error cleanup injection modes. Unlike the numbered durable
    /// boundary stages these return an I/O error instead of terminating the
    /// process, so tests can verify that cleanup failures reach the caller.
    pub const CLEANUP_NONE: u8 = 0;
    pub const CLEANUP_REMOVE_ERROR: u8 = 1;
    pub const CLEANUP_SYNC_ERROR: u8 = 2;

    pub static STAGE: AtomicU8 = AtomicU8::new(NONE);
    pub static CLEANUP_ERROR: AtomicU8 = AtomicU8::new(CLEANUP_NONE);
    static READ_DIR_ENTRY_ERROR: Mutex<Option<PathBuf>> = Mutex::new(None);

    /// Inject one individual `read_dir` entry error for the named directory.
    pub fn fail_next_read_dir_entry(path: impl Into<PathBuf>) {
        *READ_DIR_ENTRY_ERROR
            .lock()
            .expect("read-dir failpoint poisoned") = Some(path.into());
    }

    pub(crate) fn take_read_dir_entry_error(path: &Path) -> bool {
        let mut configured = READ_DIR_ENTRY_ERROR
            .lock()
            .expect("read-dir failpoint poisoned");
        if configured.as_deref() == Some(path) {
            configured.take();
            true
        } else {
            false
        }
    }

    pub fn hit(stage: u8) {
        if STAGE.load(Ordering::SeqCst) == stage {
            // A hard exit models process loss after the preceding durable
            // action without exercising destructors that could clean it up.
            std::process::exit(9);
        }
    }
}

/// Physical storage parameters required to rewrite a collection before it is
/// opened and its values are decoded.
#[derive(Clone, Copy)]
pub(crate) enum StorageDescriptor<'a> {
    Bitcask {
        config: &'a Config,
        key_len: usize,
        claims: bool,
    },
    Fixed {
        config: &'a FixedConfig,
        key_len: usize,
        value_len: u16,
        claims: bool,
    },
    #[allow(dead_code)]
    Lsm,
    /// A segmented collection. It has no shard layout of its own and takes
    /// no physical format migration.
    #[cfg(feature = "segmented")]
    Segmented,
}

impl StorageDescriptor<'_> {
    pub(crate) fn validate(&self) -> DbResult<()> {
        match self {
            Self::Bitcask { config, .. } => config.validate(),
            Self::Fixed { config, .. } => config.validate(),
            Self::Lsm => Ok(()),
            #[cfg(feature = "segmented")]
            Self::Segmented => Ok(()),
        }
    }

    pub(crate) fn policy(&self) -> FormatMigrationPolicy {
        match self {
            Self::Bitcask { config, .. } => config.format_migration,
            Self::Fixed { config, .. } => config.format_migration,
            Self::Lsm => FormatMigrationPolicy::Auto,
            #[cfg(feature = "segmented")]
            Self::Segmented => FormatMigrationPolicy::Auto,
        }
    }

    /// Validate immutable on-disk backend parameters before a format pass can
    /// create markers, dirty metadata, or rewrite any shard.
    pub(crate) fn validate_persisted(&self, collection_dir: &Path) -> DbResult<()> {
        let meta_path = collection_dir.join("db.meta");
        if !meta_path.exists() || matches!(self, Self::Lsm) {
            return Ok(());
        }
        let meta = crate::meta::DbMeta::decode(&std::fs::read(meta_path)?)?;
        match self {
            Self::Bitcask { config, .. } => {
                if meta.backend != crate::meta::Backend::Bitcask {
                    return Err(crate::DbError::FormatMismatch(format!(
                        "db.meta: expected Bitcask backend, found {:?}",
                        meta.backend
                    )));
                }
                if meta.shard_count as usize != config.shard_count {
                    return Err(crate::DbError::FormatMismatch(format!(
                        "shard_count mismatch: db has {}, config has {}",
                        meta.shard_count, config.shard_count
                    )));
                }
                if meta.shard_prefix_bits as usize != config.shard_prefix_bits {
                    return Err(crate::DbError::FormatMismatch(format!(
                        "shard_prefix_bits mismatch: db has {}, config has {}",
                        meta.shard_prefix_bits, config.shard_prefix_bits
                    )));
                }
                let was_encrypted = meta.flags & crate::meta::FLAG_ENCRYPTED != 0;
                #[cfg(feature = "encryption")]
                if was_encrypted != config.encryption_key.is_some() {
                    return Err(crate::DbError::Config(if was_encrypted {
                        "database is encrypted but no encryption_key provided"
                    } else {
                        "database is not encrypted but encryption_key was provided"
                    }));
                }
                #[cfg(feature = "encryption")]
                if let Some(key) = config.encryption_key.as_ref() {
                    crate::enc_check::preflight_collection(
                        collection_dir,
                        meta.flags,
                        key,
                        config.encryption_context.as_ref(),
                    )?;
                }
                #[cfg(not(feature = "encryption"))]
                if was_encrypted {
                    return Err(crate::DbError::FormatMismatch(
                        "database is encrypted but binary lacks the encryption feature".into(),
                    ));
                }
            }
            Self::Fixed { config, .. } => {
                if meta.backend != crate::meta::Backend::FixedStore {
                    return Err(crate::DbError::FormatMismatch(format!(
                        "db.meta: expected FixedStore backend, found {:?}",
                        meta.backend
                    )));
                }
                if meta.shard_count as usize != config.shard_count {
                    return Err(crate::DbError::FormatMismatch(format!(
                        "db.meta: shard_count mismatch: stored {}, config {}",
                        meta.shard_count, config.shard_count
                    )));
                }
                if meta.shard_prefix_bits as usize != config.shard_prefix_bits {
                    return Err(crate::DbError::FormatMismatch(format!(
                        "db.meta: shard_prefix_bits mismatch: stored {}, config {}",
                        meta.shard_prefix_bits, config.shard_prefix_bits
                    )));
                }
            }
            Self::Lsm => {}
            #[cfg(feature = "segmented")]
            Self::Segmented => {
                if meta.backend != crate::meta::Backend::Segmented {
                    return Err(crate::DbError::FormatMismatch(format!(
                        "db.meta: expected Segmented backend, found {:?}",
                        meta.backend
                    )));
                }
            }
        }
        Ok(())
    }

    pub(crate) fn claims(&self) -> bool {
        match self {
            Self::Bitcask { claims, .. } | Self::Fixed { claims, .. } => *claims,
            Self::Lsm => false,
            #[cfg(feature = "segmented")]
            Self::Segmented => false,
        }
    }

    pub(crate) fn shard_count(&self) -> Option<usize> {
        match self {
            Self::Bitcask { config, .. } => Some(config.shard_count),
            Self::Fixed { config, .. } => Some(config.shard_count),
            Self::Lsm => None,
            #[cfg(feature = "segmented")]
            Self::Segmented => None,
        }
    }
}

#[cfg(feature = "armour")]
#[allow(dead_code)] // Consumed by the subsequent opener/rewrite tasks.
#[doc(hidden)]
pub mod plan;

#[cfg(feature = "armour")]
pub mod unchanged;

#[cfg(feature = "armour")]
#[allow(dead_code)] // Consumed by the subsequent opener/rewrite tasks.
pub(crate) mod marker;

#[cfg(feature = "armour")]
pub(crate) mod bitcask;

#[cfg(feature = "armour")]
pub(crate) mod fixed;

/// Policy controlling whether an opener runs a pending value-format migration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(
    any(feature = "armour", feature = "postcard-codec"),
    derive(serde::Deserialize)
)]
pub enum FormatMigrationPolicy {
    /// Run declared format migrations automatically while opening the collection.
    #[default]
    Auto,
    /// Refuse an open that requires a format rewrite.
    Refuse,
}

/// Decision returned by one value-format migration step.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormatAction {
    Write,
    Keep,
    Drop,
}

/// Byte-to-byte callback used by a format migration step.
pub type FormatStepFn = fn(key: &[u8], old: &[u8], out: &mut Vec<u8>) -> DbResult<FormatAction>;

/// What a format step does to stored rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FormatStepKind {
    /// Rows are rewritten through `step`.
    Rewrite,
    /// Stored bytes already decode as the next version; armdb proves it against
    /// the stored schema and advances only metadata.
    Unchanged,
}

/// One declared value-format transition.
#[derive(Clone, Copy)]
pub struct FormatMigration {
    pub from_version: u16,
    pub from_typ: Option<&'static Typ>,
    pub to_typ: Option<&'static Typ>,
    pub step: FormatStepFn,
    /// Whether rows need rewriting or only a proven metadata advance.
    pub kind: FormatStepKind,
}

impl FormatMigration {
    /// Declares that rows stored at `from_version` decode unchanged as the next
    /// version. armdb proves it against the schema stored in `db.info` (Rapira
    /// codecs only) and rewrites nothing.
    pub const fn unchanged(from_version: u16) -> Self {
        Self {
            from_version,
            from_typ: None,
            to_typ: None,
            step: keep_step,
            kind: FormatStepKind::Unchanged,
        }
    }

    pub const fn raw(from_version: u16, step: FormatStepFn) -> Self {
        Self {
            from_version,
            from_typ: None,
            to_typ: None,
            step,
            kind: FormatStepKind::Rewrite,
        }
    }

    pub const fn raw_checked(
        from_version: u16,
        from_typ: &'static Typ,
        to_typ: &'static Typ,
        step: FormatStepFn,
    ) -> Self {
        Self {
            from_version,
            from_typ: Some(from_typ),
            to_typ: Some(to_typ),
            step,
            kind: FormatStepKind::Rewrite,
        }
    }
}

fn keep_step(_key: &[u8], _old: &[u8], _out: &mut Vec<u8>) -> DbResult<FormatAction> {
    Ok(FormatAction::Keep)
}

/// Summary returned by an explicit format migration run.
#[derive(Debug, Clone)]
pub struct FormatMigrationReport {
    pub collection: &'static str,
    pub from: u16,
    pub to: u16,
    pub shards: usize,
    pub rows_migrated: u64,
    pub rows_dropped: u64,
    pub bytes_before: u64,
    pub bytes_after: u64,
    pub elapsed: Duration,
    pub warnings: Vec<String>,
}

impl FormatMigrationReport {
    pub(crate) fn empty(collection: &'static str, version: u16) -> Self {
        Self {
            collection,
            from: version,
            to: version,
            shards: 0,
            rows_migrated: 0,
            rows_dropped: 0,
            bytes_before: 0,
            bytes_after: 0,
            elapsed: Duration::ZERO,
            warnings: Vec::new(),
        }
    }
}

#[cfg(feature = "armour")]
pub(crate) fn refuse_if_required(
    policy: FormatMigrationPolicy,
    collection: &'static str,
    plan: &plan::MigrationPlan,
) -> DbResult<()> {
    if policy == FormatMigrationPolicy::Refuse {
        return Err(crate::DbError::FormatMigrationRequired {
            collection,
            from: plan.stored_version,
            to: plan.format_to_version,
        });
    }
    Ok(())
}

#[cfg(test)]
#[cfg(feature = "segmented")]
mod segmented_descriptor_tests {
    use super::*;
    use crate::error::DbError;
    use crate::meta::{Backend, DbMeta, META_VERSION};

    fn write_meta(dir: &Path, backend: Backend) {
        let meta = DbMeta {
            version: META_VERSION,
            backend,
            shard_count: 0,
            shard_prefix_bits: 0,
            flags: 0,
        };
        std::fs::write(dir.join("db.meta"), meta.encode()).unwrap();
    }

    #[test]
    fn a_segmented_descriptor_has_no_shards_and_no_claims() {
        let d = StorageDescriptor::Segmented;
        d.validate().unwrap();
        assert_eq!(d.shard_count(), None);
        assert!(!d.claims());
        assert!(matches!(d.policy(), FormatMigrationPolicy::Auto));
    }

    #[test]
    fn a_directory_of_another_backend_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        // Nothing there yet: a new collection.
        StorageDescriptor::Segmented
            .validate_persisted(dir.path())
            .unwrap();

        write_meta(dir.path(), Backend::Segmented);
        StorageDescriptor::Segmented
            .validate_persisted(dir.path())
            .unwrap();

        write_meta(dir.path(), Backend::Bitcask);
        assert!(matches!(
            StorageDescriptor::Segmented.validate_persisted(dir.path()),
            Err(DbError::FormatMismatch(m)) if m.contains("Segmented")
        ));
    }
}