armdb 0.9.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
435
436
437
438
439
440
use crate::Key;
use crate::error::{DbError, DbResult};

#[cfg(feature = "typed-tree")]
use crate::projection::ProjectionSink;

use std::mem::size_of;

/// Trait for receiving write notifications from tree/map operations.
///
/// Used for maintaining secondary indexes, audit logs, or any side-effect
/// that must observe every mutation synchronously.
///
/// # Zero-overhead default
///
/// The default implementation [`NoHook`] has `NEEDS_OLD_VALUE = false`,
/// `NEEDS_WRITE = false`, and an empty `on_write`. The compiler eliminates
/// all hook-related branches and calls when `H = NoHook`.
///
/// # Associated constants
///
/// - `NEEDS_OLD_VALUE`: when `false`, skips disk I/O for the old value in
///   VarTree/VarMap — `old` is `None` in `on_write`.
/// - `NEEDS_INIT`: when `true`, `on_init` is called for every live entry
///   during collection open.
/// - `NEEDS_WRITE`: when `false`, `on_write` may be skipped entirely by
///   the collection or its adapter. Set to `false` on `NoHook`.
pub trait WriteHook<K: Key>: Send + Sync {
    const NEEDS_OLD_VALUE: bool = true;
    const NEEDS_INIT: bool = false;
    const NEEDS_WRITE: bool = true;
    const EXPIRES: bool = false;
    const TTL_REVISION: u32 = 0;

    fn deadline(&self, _key: &K, _value: &[u8]) -> Option<u64> {
        None
    }

    /// True when `value` bytes cannot be decoded for TTL stage-2 (Var families).
    /// Distinguishes decode errors from a `None` policy deadline.
    fn ttl_decode_failed(&self, _value: &[u8]) -> bool {
        false
    }

    /// Called after a successful write operation.
    ///
    /// - `key` — the affected key
    /// - `old` — previous value (`Some` on update/delete when `NEEDS_OLD_VALUE`, else `None`)
    /// - `new` — new value (`Some` on put/insert/update, `None` on delete)
    ///
    /// # Reentrancy
    ///
    /// The shard lock is NOT held during this call — implementations may
    /// safely read from or write to the same collection, including the
    /// same shard.
    ///
    /// Inside `atomic()`, `on_write` is buffered per mutation and replayed after the shard
    /// lock is released, in application order; on a closure `Err`, hooks still fire for
    /// the operations that were applied.
    fn on_write(&self, key: &K, old: Option<&[u8]>, new: Option<&[u8]>);

    /// Called once per live entry during collection open.
    /// Fires after recovery and migration are complete, with the final value.
    ///
    /// # Reentrancy
    ///
    /// Like `on_write`, the shard lock is NOT held during this call —
    /// implementations may safely read from or write to the same collection,
    /// including the same shard.
    fn on_init(&self, _key: &K, _value: &[u8]) {}

    #[cfg(feature = "typed-tree")]
    const PROJECTS: bool = false;

    #[cfg(feature = "typed-tree")]
    fn project(
        &self,
        _key: &K,
        _old: Option<&[u8]>,
        _new: Option<&[u8]>,
        _sink: &mut ProjectionSink<'_>,
    ) -> DbResult<()> {
        Ok(())
    }

    #[cfg(feature = "typed-tree")]
    fn projection_targets(&self) -> Option<&crate::projection::IndexTargets> {
        None
    }

    #[cfg(feature = "typed-tree")]
    fn projection_limits(&self) -> (usize, usize) {
        (
            crate::projection::DEFAULT_MAX_PROJECTED_ROWS,
            crate::projection::DEFAULT_MAX_PROJECTED_BYTES,
        )
    }
}

/// Default no-op hook. All branches are eliminated at compile time.
pub struct NoHook;

impl<K: Key> WriteHook<K> for NoHook {
    const NEEDS_OLD_VALUE: bool = false;
    const NEEDS_INIT: bool = false;
    const NEEDS_WRITE: bool = false;

    #[inline(always)]
    fn on_write(&self, _key: &K, _old: Option<&[u8]>, _new: Option<&[u8]>) {}

    #[inline(always)]
    fn on_init(&self, _key: &K, _value: &[u8]) {}

    #[cfg(feature = "typed-tree")]
    const PROJECTS: bool = false;

    #[cfg(feature = "typed-tree")]
    fn project(
        &self,
        _key: &K,
        _old: Option<&[u8]>,
        _new: Option<&[u8]>,
        _sink: &mut ProjectionSink<'_>,
    ) -> DbResult<()> {
        Ok(())
    }
}

/// Typed write hook for [`TypedTree`](crate::TypedTree).
///
/// Receives `&T` directly instead of raw bytes — no encode/decode needed.
/// Called after the in-memory commit. The hook arguments carry the
/// mutation's (old, new) pair; a reentrant `get()` from the hook
/// observes the committed value (or a later concurrent write).
///
/// Inside `atomic()`, `on_write` is buffered per mutation and replayed after the shard
/// lock is released, in application order; on a closure `Err`, hooks still fire for
/// the operations that were applied.
///
/// **Exception — `LsmTree`** (feature `fjall`): inside `LsmTree::atomic` hooks fire
/// *synchronously, under the held stripe lock*, not buffered-and-replayed. A hook
/// that re-enters the same collection there will deadlock. Tracked in
/// libfunc/armour#119.
#[cfg(feature = "typed-tree")]
pub trait TypedWriteHook<K: Key, T>: Send + Sync {
    /// Unused for TypedTree/TypedMap/ZeroTree/ZeroMap — old value is always
    /// provided (it lives in memory). Kept for trait uniformity with `WriteHook`.
    const NEEDS_OLD_VALUE: bool = true;
    const NEEDS_INIT: bool = false;
    const NEEDS_WRITE: bool = true;
    const EXPIRES: bool = false;
    const TTL_REVISION: u32 = 0;

    fn deadline(&self, _key: &K, _value: &T) -> Option<u64> {
        None
    }

    fn on_write(&self, key: &K, old: Option<&T>, new: Option<&T>);

    /// See [`WriteHook::on_init`] for reentrancy guarantees.
    fn on_init(&self, _key: &K, _value: &T) {}

    const PROJECTS: bool = false;

    fn project(&self, _key: &K, _value: &T, _sink: &mut ProjectionSink<'_>) -> DbResult<()> {
        Ok(())
    }

    fn projection_targets(&self) -> Option<&crate::projection::IndexTargets> {
        None
    }

    fn projection_limits(&self) -> (usize, usize) {
        (
            crate::projection::DEFAULT_MAX_PROJECTED_ROWS,
            crate::projection::DEFAULT_MAX_PROJECTED_BYTES,
        )
    }
}

#[cfg(feature = "typed-tree")]
impl<K: Key, T> TypedWriteHook<K, T> for NoHook {
    const NEEDS_OLD_VALUE: bool = false;
    const NEEDS_INIT: bool = false;
    const NEEDS_WRITE: bool = false;

    #[inline(always)]
    fn on_write(&self, _key: &K, _old: Option<&T>, _new: Option<&T>) {}

    #[inline(always)]
    fn on_init(&self, _key: &K, _value: &T) {}

    const PROJECTS: bool = false;

    fn project(&self, _key: &K, _value: &T, _sink: &mut ProjectionSink<'_>) -> DbResult<()> {
        Ok(())
    }
}

/// Adapter: wraps a [`TypedWriteHook<K, T>`] and implements [`WriteHook<K>`]
/// by converting raw bytes to `&T` via zerocopy. Used by ZeroTree/ZeroMap
/// so their users get typed hook callbacks.
#[cfg(feature = "typed-tree")]
pub struct ZeroHookAdapter<K, T, H> {
    pub(crate) inner: H,
    pub(crate) _marker: std::marker::PhantomData<fn() -> (K, T)>,
}

#[cfg(feature = "typed-tree")]
impl<K, T, H> ZeroHookAdapter<K, T, H> {
    pub fn new(inner: H) -> Self {
        Self {
            inner,
            _marker: std::marker::PhantomData,
        }
    }
}

// SAFETY: The adapter delegates to H which is Send+Sync (via TypedWriteHook bound).
// PhantomData<fn() -> (K, T)> is always Send+Sync.
#[cfg(feature = "typed-tree")]
unsafe impl<K, T, H: Send> Send for ZeroHookAdapter<K, T, H> {}
#[cfg(feature = "typed-tree")]
unsafe impl<K, T, H: Sync> Sync for ZeroHookAdapter<K, T, H> {}

#[cfg(feature = "typed-tree")]
impl<K: Key, T: Copy + zerocopy::FromBytes, H: TypedWriteHook<K, T>> WriteHook<K>
    for ZeroHookAdapter<K, T, H>
{
    const NEEDS_OLD_VALUE: bool = H::NEEDS_OLD_VALUE;
    const NEEDS_INIT: bool = H::NEEDS_INIT;
    const NEEDS_WRITE: bool = H::NEEDS_WRITE;
    const EXPIRES: bool = H::EXPIRES;
    const TTL_REVISION: u32 = H::TTL_REVISION;
    const PROJECTS: bool = H::PROJECTS;

    fn deadline(&self, key: &K, value: &[u8]) -> Option<u64> {
        debug_assert_eq!(value.len(), size_of::<T>());
        let val: T = zerocopy::FromBytes::read_from_bytes(value).ok()?;
        self.inner.deadline(key, &val)
    }

    #[inline]
    fn on_write(&self, key: &K, old: Option<&[u8]>, new: Option<&[u8]>) {
        if !H::NEEDS_WRITE {
            return;
        }
        let read = |b: &[u8]| -> T {
            debug_assert_eq!(b.len(), size_of::<T>());
            zerocopy::FromBytes::read_from_bytes(b).expect("slice len == size_of::<T>()")
        };
        let old_val = old.map(read);
        let new_val = new.map(read);
        self.inner.on_write(key, old_val.as_ref(), new_val.as_ref());
    }

    #[inline]
    fn on_init(&self, key: &K, value: &[u8]) {
        debug_assert_eq!(value.len(), size_of::<T>());
        let val: T =
            zerocopy::FromBytes::read_from_bytes(value).expect("slice len == size_of::<T>()");
        self.inner.on_init(key, &val);
    }

    fn project(
        &self,
        key: &K,
        _old: Option<&[u8]>,
        new: Option<&[u8]>,
        sink: &mut ProjectionSink<'_>,
    ) -> DbResult<()> {
        if !H::PROJECTS {
            return Ok(());
        }
        if let Some(b) = new {
            debug_assert_eq!(b.len(), size_of::<T>());
            let val: T = zerocopy::FromBytes::read_from_bytes(b).map_err(|_| {
                DbError::FormatMismatch("zero hook adapter project decode failed".into())
            })?;
            self.inner.project(key, &val, sink)?;
        }
        Ok(())
    }

    fn projection_targets(&self) -> Option<&crate::projection::IndexTargets> {
        self.inner.projection_targets()
    }

    fn projection_limits(&self) -> (usize, usize) {
        self.inner.projection_limits()
    }
}

/// Adapter: wraps a [`TypedWriteHook<K, T>`] and implements [`WriteHook<K>`]
/// by decoding raw bytes to `T` via a [`Codec`](crate::codec::Codec).
/// Used by `VarTypedTree` / `VarTypedMap` so their users get typed hook callbacks.
///
/// Decode errors are logged at `warn` level. `on_write` passes `None` for the
/// failed side; `on_init` skips the entry entirely.
///
/// When `H::NEEDS_WRITE` is `false` (e.g. `NoHook`), `on_write` is a no-op —
/// no decode is performed.
#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
pub struct VarTypedHookAdapter<K, T, C, H> {
    pub(crate) inner: H,
    pub(crate) codec: C,
    pub(crate) _marker: std::marker::PhantomData<fn() -> (K, T)>,
}

#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
impl<K, T, C, H> VarTypedHookAdapter<K, T, C, H> {
    pub fn new(inner: H, codec: C) -> Self {
        Self {
            inner,
            codec,
            _marker: std::marker::PhantomData,
        }
    }
}

#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
impl<K, T, C, H> VarTypedHookAdapter<K, T, C, H>
where
    K: Key,
    T: Send + Sync,
    H: TypedWriteHook<K, T>,
{
    pub(crate) fn typed_deadline(&self, key: &K, value: &T) -> Option<u64> {
        if H::EXPIRES {
            self.inner.deadline(key, value)
        } else {
            None
        }
    }
}

// SAFETY: delegates to H (Send+Sync via TypedWriteHook) and C (Send+Sync via Codec).
// PhantomData<fn() -> (K, T)> is always Send+Sync.
#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
unsafe impl<K, T, C: Send, H: Send> Send for VarTypedHookAdapter<K, T, C, H> {}
#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
unsafe impl<K, T, C: Sync, H: Sync> Sync for VarTypedHookAdapter<K, T, C, H> {}

#[cfg(all(feature = "typed-tree", feature = "var-collections"))]
impl<K, T, C, H> WriteHook<K> for VarTypedHookAdapter<K, T, C, H>
where
    K: Key,
    T: Send + Sync,
    C: crate::codec::Codec<T>,
    H: TypedWriteHook<K, T>,
{
    const NEEDS_OLD_VALUE: bool = H::NEEDS_OLD_VALUE;
    const NEEDS_INIT: bool = H::NEEDS_INIT;
    const NEEDS_WRITE: bool = H::NEEDS_WRITE;
    const EXPIRES: bool = H::EXPIRES;
    const TTL_REVISION: u32 = H::TTL_REVISION;
    const PROJECTS: bool = H::PROJECTS;

    fn deadline(&self, key: &K, value: &[u8]) -> Option<u64> {
        self.codec
            .decode_from(value)
            .ok()
            .and_then(|val| self.inner.deadline(key, &val))
    }

    fn ttl_decode_failed(&self, value: &[u8]) -> bool {
        self.codec.decode_from(value).is_err()
    }

    #[inline]
    fn on_write(&self, key: &K, old: Option<&[u8]>, new: Option<&[u8]>) {
        if !H::NEEDS_WRITE {
            return;
        }
        let old_t = old.and_then(|b| {
            self.codec
                .decode_from(b)
                .map_err(|_| {
                    tracing::warn!(
                        side = "old",
                        value_len = b.len(),
                        "var_typed hook adapter: on_write decode failed"
                    );
                })
                .ok()
        });
        let new_t = new.and_then(|b| {
            self.codec
                .decode_from(b)
                .map_err(|_| {
                    tracing::warn!(
                        side = "new",
                        value_len = b.len(),
                        "var_typed hook adapter: on_write decode failed"
                    );
                })
                .ok()
        });
        self.inner.on_write(key, old_t.as_ref(), new_t.as_ref());
    }

    #[inline]
    fn on_init(&self, key: &K, value: &[u8]) {
        match self.codec.decode_from(value) {
            Ok(val) => self.inner.on_init(key, &val),
            Err(_) => {
                tracing::warn!(
                    key_len = std::mem::size_of::<K>(),
                    value_len = value.len(),
                    "var_typed hook adapter: on_init decode failed, entry skipped"
                );
            }
        }
    }

    fn project(
        &self,
        key: &K,
        _old: Option<&[u8]>,
        new: Option<&[u8]>,
        sink: &mut ProjectionSink<'_>,
    ) -> DbResult<()> {
        if !H::PROJECTS {
            return Ok(());
        }
        if let Some(b) = new {
            let val = self.codec.decode_from(b)?;
            self.inner.project(key, &val, sink)?;
        }
        Ok(())
    }

    fn projection_targets(&self) -> Option<&crate::projection::IndexTargets> {
        self.inner.projection_targets()
    }

    fn projection_limits(&self) -> (usize, usize) {
        self.inner.projection_limits()
    }
}