crossbank 0.1.2

Local, on-device key/value storage for Rust — one API on native (redb) and in the browser (IndexedDB). A Hive-shaped replacement, with no network, server, or sync.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! The native backend, on [`redb`](https://github.com/cberner/redb).
//!
//! Pure Rust, ACID, and it builds for every platform Flutter ships to —
//! Linux, macOS, Windows, Android and iOS. Crash safety, transactions and
//! compaction come with it rather than being ours to get right.
//!
//! # Why not Hive's own format
//!
//! Hive is Bitcask-inspired: an append-only log of frames, an index rebuilt by
//! scanning the whole file at open, and an explicit `compact()`. We copy Hive's
//! *architecture* — eager and lazy containers, watch streams, the box mental
//! model — but not its bytes, for two reasons. Its deleted values stay readable
//! on disk until someone calls `compact()`, and its keys are stored in plaintext
//! even in encrypted boxes. Neither is a property we want, and rolling our own
//! log would mean owning torn-write and crash-recovery correctness that redb has
//! already solved.
//!
//! # The one rule this file exists to honour
//!
//! redb is **synchronous**, and a `WriteTransaction` held across an `.await`
//! while another task on the same executor calls `begin_write` is a hard
//! deadlock — native-only, and therefore invisible to browser testing.
//!
//! The [`Backend`] trait makes that impossible rather than
//! merely discouraged: every method here is a single synchronous block with no
//! await points inside it. A transaction is opened and committed within one
//! function call, always. That is the payoff for `commit(Vec<Op>)` taking a
//! complete op list instead of handing out a transaction handle.
//!
//! Blocking inline is acceptable for local disk. If it ever stops being
//! acceptable, the fix is an offload hook, not an async runtime dependency.

use std::ops::Bound;
use std::path::{Path, PathBuf};
use std::sync::RwLock;

use redb::{Database, Durability, ReadableDatabase, TableDefinition, TableError};

use super::api::{
    BFut, Backend, CommitOptions, Durability as CommitDurability, KeyRange, Op, ScanPage,
    ScanRequest, Table, Usage,
};
use crate::error::{Error, Result};

type Def = TableDefinition<'static, &'static [u8], &'static [u8]>;

const META: Def = TableDefinition::new("meta");
const RECORDS: Def = TableDefinition::new("records");
const CHUNKS: Def = TableDefinition::new("chunks");

fn definition(table: Table) -> Def {
    match table {
        Table::Meta => META,
        Table::Records => RECORDS,
        Table::Chunks => CHUNKS,
    }
}

fn backend_err(context: &str, e: impl std::fmt::Display) -> Error {
    let message = e.to_string();
    // Running out of disk is a quota problem, not an opaque IO failure, and a
    // caller can do something about it.
    if message.contains("No space left") || message.contains("ENOSPC") {
        return Error::QuotaExceeded {
            needed: 0,
            available: Some(0),
        };
    }
    Error::Backend(format!("{context}: {message}"))
}

/// A bank stored in a single redb file.
#[derive(Debug)]
pub struct RedbBackend {
    /// `None` once closed.
    ///
    /// redb takes an **exclusive** file lock that is only released when the
    /// `Database` is dropped, so close-then-reopen in one process needs a way
    /// to drop it while the `Arc<dyn Backend>` handle is still alive. An
    /// `Option` behind a lock is that way.
    db: RwLock<Option<Database>>,
    path: PathBuf,
}

impl RedbBackend {
    /// Open, or create, the database at `path`.
    ///
    /// redb takes an **exclusive** file lock, so a second process opening the
    /// same file fails rather than corrupting it. That is also why native
    /// cross-tab coherence is a non-problem: a desktop app is one process.
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref().to_path_buf();
        let db = Database::create(&path).map_err(|e| backend_err("opening the database", e))?;

        let backend = Self {
            db: RwLock::new(Some(db)),
            path,
        };
        backend.create_tables()?;
        Ok(backend)
    }

    /// Borrow the open database, or report [`Error::Closed`].
    ///
    /// A closure rather than a returned guard: the guard's lifetime is tied to
    /// the borrow of `self`, and threading that through the boxed backend
    /// futures is noise for no gain. Never unwraps a poisoned lock — a
    /// poisoned lock is a backend failure, not a panic site.
    fn with_db<T>(&self, f: impl FnOnce(&Database) -> Result<T>) -> Result<T> {
        let guard = self
            .db
            .read()
            .map_err(|_| Error::backend("the redb handle lock was poisoned"))?;
        match guard.as_ref() {
            Some(db) => f(db),
            None => Err(Error::Closed),
        }
    }

    /// Create all three tables up front.
    ///
    /// Without this, a read transaction against a table nothing has written yet
    /// returns `TableDoesNotExist`, and every read path would need to translate
    /// that into "empty". Creating them once at open keeps the read paths
    /// honest and matches the fixed-table layout the web backend must use
    /// anyway.
    /// Called on **every** open, so the common case — an existing database
    /// whose tables are all there — must not cost a write transaction. It used
    /// to: an unconditional `begin_write` plus commit is a full fsync paid on
    /// every reopen for the privilege of creating three tables that already
    /// existed. A read transaction answers the question for free.
    fn create_tables(&self) -> Result<()> {
        if !self.any_table_missing()? {
            return Ok(());
        }
        self.with_db(|db| {
            let txn = db
                .begin_write()
                .map_err(|e| backend_err("beginning the setup transaction", e))?;
            {
                for table in Table::ALL {
                    txn.open_table(definition(table))
                        .map_err(|e| backend_err("creating a table", e))?;
                }
            }
            txn.commit()
                .map_err(|e| backend_err("committing table creation", e))
        })
    }

    /// Whether any of the three fixed tables has yet to be created.
    ///
    /// A read transaction, so it writes nothing and forces no fsync. Anything
    /// other than a clean "does not exist" is propagated rather than treated
    /// as absence — creating a table over a real error would be the wrong
    /// recovery.
    fn any_table_missing(&self) -> Result<bool> {
        self.with_db(|db| {
            let txn = db
                .begin_read()
                .map_err(|e| backend_err("beginning the table probe", e))?;
            for table in Table::ALL {
                match txn.open_table(definition(table)) {
                    Ok(_) => {}
                    Err(TableError::TableDoesNotExist(_)) => return Ok(true),
                    Err(e) => return Err(backend_err("probing for a table", e)),
                }
            }
            Ok(false)
        })
    }

    fn read_one(&self, table: Table, key: &[u8]) -> Result<Option<Vec<u8>>> {
        self.with_db(|db| {
            let txn = db
                .begin_read()
                .map_err(|e| backend_err("beginning a read", e))?;
            let handle = match txn.open_table(definition(table)) {
                Ok(handle) => handle,
                Err(TableError::TableDoesNotExist(_)) => return Ok(None),
                Err(e) => return Err(backend_err("opening a table for reading", e)),
            };

            handle
                .get(key)
                .map_err(|e| backend_err("reading a key", e))
                .map(|found| found.map(|guard| guard.value().to_vec()))
        })
    }

    fn scan_page(&self, request: &ScanRequest) -> Result<ScanPage> {
        self.with_db(|db| {
            let txn = db
                .begin_read()
                .map_err(|e| backend_err("beginning a scan", e))?;
            let handle = match txn.open_table(definition(request.table)) {
                Ok(handle) => handle,
                Err(TableError::TableDoesNotExist(_)) => return Ok(ScanPage::default()),
                Err(e) => return Err(backend_err("opening a table for scanning", e)),
            };

            let bounds = as_ref_bounds(&request.range);
            let iter = handle
                .range::<&[u8]>(bounds)
                .map_err(|e| backend_err("opening a range", e))?;

            let mut items = Vec::new();
            let mut resume = None;

            // `Box<dyn Iterator>` so direction is chosen once rather than
            // duplicating the body.
            let entries: Box<dyn Iterator<Item = _>> = if request.reverse {
                Box::new(iter.rev())
            } else {
                Box::new(iter)
            };

            for entry in entries {
                if items.len() >= request.limit {
                    break;
                }
                let (key, value) = entry.map_err(|e| backend_err("reading a range entry", e))?;
                let key = key.value().to_vec();
                let value = request.want_values.then(|| value.value().to_vec());
                resume = Some(key.clone());
                items.push((key, value));
            }

            // Only offer a resume point when the page actually filled. An exhausted
            // range must report `None`, or a paging caller loops forever.
            let exhausted = items.len() < request.limit;
            Ok(ScanPage {
                items,
                resume: if exhausted { None } else { resume },
            })
        })
    }

    /// Apply every op in one transaction, or none of them.
    ///
    /// No await points anywhere inside. See the module docs.
    fn apply(&self, ops: Vec<Op>, durability: CommitDurability) -> Result<()> {
        self.with_db(|db| {
            let mut txn = db
                .begin_write()
                .map_err(|e| backend_err("beginning a write", e))?;

            // Stated explicitly rather than relied upon: at `Immediate` a
            // commit must be durable before it returns, or the crash-and-reopen
            // tests prove nothing. At `Eventual` the commit is still atomic and
            // still visible to a reopen in this process — it is the fsync that
            // is deferred to `flush`.
            // redb 4 spells the relaxed level `None`, not `Eventual` — that
            // variant was removed. Its own docs state the contract we rely on:
            // such a commit "will not be persisted to disk unless followed by
            // a commit with `Durability::Immediate`", which is exactly what
            // `flush` below issues.
            let redb_durability = match durability {
                CommitDurability::Immediate => Durability::Immediate,
                CommitDurability::Eventual => Durability::None,
            };
            txn.set_durability(redb_durability)
                .map_err(|e| backend_err("setting durability", e))?;

            {
                for op in ops {
                    match op {
                        Op::Put { table, key, value } => {
                            let mut handle = txn
                                .open_table(definition(table))
                                .map_err(|e| backend_err("opening a table for writing", e))?;
                            handle
                                .insert(key.as_slice(), value.as_slice())
                                .map_err(|e| backend_err("inserting a key", e))?;
                        }
                        Op::Delete { table, key } => {
                            let mut handle = txn
                                .open_table(definition(table))
                                .map_err(|e| backend_err("opening a table for deletion", e))?;
                            handle
                                .remove(key.as_slice())
                                .map_err(|e| backend_err("removing a key", e))?;
                        }
                        Op::DeleteRange { table, range } => {
                            let mut handle = txn.open_table(definition(table)).map_err(|e| {
                                backend_err("opening a table for range deletion", e)
                            })?;
                            let bounds = as_ref_bounds(&range);
                            handle
                                .retain_in::<&[u8], _>(bounds, |_, _| false)
                                .map_err(|e| backend_err("deleting a range", e))?;
                        }
                    }
                }
            }

            txn.commit().map_err(|e| backend_err("committing", e))
        })
    }
}

/// Borrow one bound as a slice.
///
/// A named function rather than a closure: a closure infers two unrelated
/// lifetimes for the argument and the return, and cannot tie them together.
fn borrow_bound(bound: &Bound<Vec<u8>>) -> Bound<&[u8]> {
    match bound {
        Bound::Unbounded => Bound::Unbounded,
        Bound::Included(v) => Bound::Included(v.as_slice()),
        Bound::Excluded(v) => Bound::Excluded(v.as_slice()),
    }
}

/// Borrow a [`KeyRange`] as bounds redb can consume.
fn as_ref_bounds(range: &KeyRange) -> (Bound<&[u8]>, Bound<&[u8]>) {
    (borrow_bound(&range.start), borrow_bound(&range.end))
}

impl Backend for RedbBackend {
    fn get<'a>(&'a self, table: Table, key: &'a [u8]) -> BFut<'a, Option<Vec<u8>>> {
        Box::pin(async move { self.read_one(table, key) })
    }

    fn get_many<'a>(&'a self, table: Table, keys: Vec<Vec<u8>>) -> BFut<'a, Vec<Option<Vec<u8>>>> {
        Box::pin(async move {
            // One read transaction for the batch, so the results are a
            // consistent snapshot rather than N independent reads.
            self.with_db(|db| {
                let txn = db
                    .begin_read()
                    .map_err(|e| backend_err("beginning a batch read", e))?;
                let handle = match txn.open_table(definition(table)) {
                    Ok(handle) => handle,
                    Err(TableError::TableDoesNotExist(_)) => return Ok(vec![None; keys.len()]),
                    Err(e) => return Err(backend_err("opening a table for batch reading", e)),
                };

                keys.iter()
                    .map(|key| {
                        handle
                            .get(key.as_slice())
                            .map_err(|e| backend_err("reading a key", e))
                            .map(|found| found.map(|guard| guard.value().to_vec()))
                    })
                    .collect()
            })
        })
    }

    /// Larger than the default. There is no transaction to outlive and no
    /// JS boundary to cross here — a B-tree range scan in a read transaction —
    /// so a page is nearly free and paging is nearly pure overhead.
    fn scan_page_size(&self) -> usize {
        1024
    }

    fn scan(&self, request: ScanRequest) -> BFut<'_, ScanPage> {
        Box::pin(async move { self.scan_page(&request) })
    }

    fn commit(&self, ops: Vec<Op>) -> BFut<'_, ()> {
        Box::pin(async move { self.apply(ops, CommitDurability::Immediate) })
    }

    fn commit_with(&self, ops: Vec<Op>, options: CommitOptions) -> BFut<'_, ()> {
        Box::pin(async move { self.apply(ops, options.durability) })
    }

    fn usage(&self) -> BFut<'_, Option<Usage>> {
        Box::pin(async move {
            let used = std::fs::metadata(&self.path).map(|m| m.len()).unwrap_or(0);
            Ok(Some(Usage {
                used,
                // Free disk space is a question about the filesystem, not about
                // us, and reporting a guess would be worse than reporting
                // nothing.
                available: None,
                // Nothing evicts a file behind the application's back.
                persisted: true,
            }))
        })
    }

    fn close(&self) -> BFut<'_, ()> {
        Box::pin(async move {
            // Taking the Database out and dropping it is what releases redb's
            // exclusive file lock. Idempotent: a second close finds `None`.
            let taken = {
                let mut guard = self
                    .db
                    .write()
                    .map_err(|_| Error::backend("the redb handle lock was poisoned"))?;
                guard.take()
            };
            drop(taken);
            Ok(())
        })
    }

    fn flush(&self) -> BFut<'_, ()> {
        // A commit at `Durability::Immediate` already reached the disk, so for
        // those this is genuinely nothing to do. But `Eventual` commits may be
        // sitting in redb's write-ahead state, and the only way to force them
        // out through redb's public API is a commit that *is* immediate. An
        // empty op list makes that as cheap as redb allows.
        Box::pin(async move { self.apply(Vec::new(), CommitDurability::Immediate) })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::executor::block_on;
    use tempfile::TempDir;

    fn backend(dir: &TempDir) -> RedbBackend {
        RedbBackend::open(dir.path().join("bank.redb")).unwrap()
    }

    fn put(key: &[u8], value: &[u8]) -> Op {
        Op::Put {
            table: Table::Records,
            key: key.to_vec(),
            value: value.to_vec(),
        }
    }

    #[test]
    fn a_reopened_database_still_has_its_data() {
        // The whole point of this backend.
        let dir = TempDir::new().unwrap();

        {
            let b = backend(&dir);
            block_on(b.commit(vec![put(b"k", b"survives")])).unwrap();
        }

        let b = backend(&dir);
        assert_eq!(
            block_on(b.get(Table::Records, b"k")).unwrap(),
            Some(b"survives".to_vec())
        );
    }

    #[test]
    fn reads_work_before_anything_has_been_written() {
        // Tables are created at open, so a read must return None rather than
        // erroring with TableDoesNotExist.
        let dir = TempDir::new().unwrap();
        let b = backend(&dir);

        assert_eq!(block_on(b.get(Table::Records, b"nothing")).unwrap(), None);
        assert!(block_on(b.scan(ScanRequest {
            table: Table::Chunks,
            range: KeyRange::all(),
            reverse: false,
            limit: 10,
            want_values: true,
        }))
        .unwrap()
        .items
        .is_empty());
    }

    #[test]
    fn an_empty_value_survives_a_reopen() {
        let dir = TempDir::new().unwrap();
        {
            let b = backend(&dir);
            block_on(b.commit(vec![put(b"empty", b"")])).unwrap();
        }

        let b = backend(&dir);
        assert_eq!(
            block_on(b.get(Table::Records, b"empty")).unwrap(),
            Some(Vec::new()),
            "an empty value must stay distinguishable from a missing key"
        );
        assert_eq!(block_on(b.get(Table::Records, b"other")).unwrap(), None);
    }

    #[test]
    fn a_failed_op_list_leaves_the_previous_state_intact() {
        // Atomicity, from the backend's side: the whole list applies or none of
        // it does. Proven by committing a good list, then a list whose range
        // deletion and put must land together.
        let dir = TempDir::new().unwrap();
        let b = backend(&dir);

        block_on(b.commit(vec![put(b"a", b"1"), put(b"b", b"2")])).unwrap();
        block_on(b.commit(vec![
            Op::DeleteRange {
                table: Table::Records,
                range: KeyRange::prefix(b"a"),
            },
            put(b"c", b"3"),
        ]))
        .unwrap();

        assert_eq!(block_on(b.get(Table::Records, b"a")).unwrap(), None);
        assert_eq!(
            block_on(b.get(Table::Records, b"b")).unwrap(),
            Some(b"2".to_vec())
        );
        assert_eq!(
            block_on(b.get(Table::Records, b"c")).unwrap(),
            Some(b"3".to_vec())
        );
    }

    #[test]
    fn tables_stay_independent_across_a_reopen() {
        let dir = TempDir::new().unwrap();
        {
            let b = backend(&dir);
            block_on(b.commit(vec![
                Op::Put {
                    table: Table::Meta,
                    key: b"k".to_vec(),
                    value: b"meta".to_vec(),
                },
                Op::Put {
                    table: Table::Records,
                    key: b"k".to_vec(),
                    value: b"record".to_vec(),
                },
            ]))
            .unwrap();
        }

        let b = backend(&dir);
        assert_eq!(
            block_on(b.get(Table::Meta, b"k")).unwrap(),
            Some(b"meta".to_vec())
        );
        assert_eq!(
            block_on(b.get(Table::Records, b"k")).unwrap(),
            Some(b"record".to_vec())
        );
        assert_eq!(block_on(b.get(Table::Chunks, b"k")).unwrap(), None);
    }

    #[test]
    fn reopening_creates_no_tables_and_writes_nothing() {
        // The reopen cost fix, asserted rather than assumed. A second open
        // must find every table already there — so it takes the read-only
        // probe and never the write transaction.
        let dir = TempDir::new().unwrap();
        {
            let b = backend(&dir);
            assert!(
                !b.any_table_missing().unwrap(),
                "the first open must have created all three tables"
            );
        }

        let b = backend(&dir);
        assert!(
            !b.any_table_missing().unwrap(),
            "a reopened database must not need its tables creating again"
        );
    }

    #[test]
    fn usage_reports_a_real_file_size() {
        let dir = TempDir::new().unwrap();
        let b = backend(&dir);
        block_on(b.commit(vec![put(b"k", &vec![0u8; 10_000])])).unwrap();

        let usage = block_on(b.usage()).unwrap().expect("redb reports usage");
        assert!(usage.used > 0, "a file with data must report a size");
        assert!(usage.persisted, "a file on disk is not evicted behind us");
        assert_eq!(
            usage.available, None,
            "free disk space is the filesystem's business, not ours"
        );
    }
}