JFLib

datastore#

an embedded journal database: JSON collections, transactions, snapshots, crash recovery, secondary indexes, encryption at rest -- crate root lib/datastore/lib.rs

datastore -- an embedded, crash-safe store for one server process: collections of JSON
records (id -> value) kept in memory, made durable by a write-ahead log and snapshots, plus
append-only journals for logs that grow without bound (audit, session logs)

  Store::open(dir) / open_with(dir, Options) -> Result<Store, StoreError>
  get(coll, id) / list(coll) / count(coll) / ids(coll)          (clones of the values)
  write(|tx| { tx.put(coll, id, v); tx.delete(coll, id); }) -> Result<seq>
  update(coll, id, |v| ...)                                     read-modify-write in one txn
  compact()                                                     snapshot now
  add_index(coll, name, Index::field("owner").unique()) / find / find_one / range
                                secondary indexes in memory (index.rs), unique ones refuse a
                                transaction that breaks them (StoreError::Conflict)
  Store::open_encrypted(dir, opts, &key) / rekey(Some(&key) | None)   encryption at rest
                                (seal.rs): snapshots and log sealed, rekey encrypts, changes
                                the key or decrypts
  Journal::open(dir, durable) / open_encrypted(dir, durable, &key) / append(name, yyyymm,
       &value) / tail(name, n) / read_month(name, yyyymm) / rekey

Files in `dir`: LOCK, snap-<seq>.bcs, wal-<first seq>.log; journal/<name>/<yyyymm>.jl.
  snapshot: "BCS1" seq:u64 | colls:u32 | per collection name, records:u32 | per record id,
            JSON | BLAKE3 of everything before (32 bytes); encrypted: "BCE1" (seal.rs)
  WAL frame: "BCW1" len:u32 seq:u64 payload BLAKE3(len ‖ seq ‖ payload)[..16]; the payload is
            a JSON array of ["put", coll, id, value] / ["del", coll, id]; encrypted: "BCW2"
            and the payload sealed (seal.rs)
A transaction is one frame, written and fsynced before it becomes visible.  Opening loads the
newest valid snapshot and replays the frames after it.  A torn frame at the very end (a crash
during a write) is cut off; a damaged frame with intact data behind it stops the open with
StoreError::Corrupt unless Options::repair is set (then the log is cut there).  An encrypted
store always has a snapshot (one at seq 0 when it is new): its key id names the key.  A store
opened with the wrong key, or one of the other kind, is StoreError::Key, never repaired.

datastore crate root#

  • fn record_limits() -> Limits the limits of one stored record

  • enum StoreError

    • Locked -- another process holds the store
    • Io(String) -- reading or writing a file failed
    • Corrupt(String) -- a damaged log frame with intact data behind it (open with repair to cut the log there)
    • TooLarge -- a record or transaction over the size limits
    • Conflict(String) -- a transaction or a new index that would give two records the key of a unique index
    • Key(String) -- the store is encrypted and no key was given, it is not and one was, or it is sealed with another key
    • NoIndex(String) -- no index of this name on the collection (Store::add_index)
  • type StoreResult<T> = Result<T, StoreError>

  • struct Options

    • snapshot_bytes: u64 -- write a snapshot (and start a new log) when the log grows beyond this
    • repair: bool -- cut a damaged log at the damage instead of refusing to open
    • durable: bool -- fsync every transaction (off only for tests and bulk imports)
  • struct Recovery what open() found

    • snapshot_seq: u64
    • frames_replayed: u64
    • truncated_bytes: u64 -- bytes cut from the end of the log (a torn last write)
    • repaired: Option<String> -- the damage that was cut away with Options::repair
  • struct Tx the changes of one transaction

impl Tx

  • fn put(&mut self, coll: &str, id: &str, v: Value)

  • fn delete(&mut self, coll: &str, id: &str)

  • fn is_empty(&self) -> bool

  • type Data = BTreeMap<String, BTreeMap<String, Value>> the records of every collection: collection -> id -> value

  • struct Store the store (share it between threads by reference or Arc)

impl Store

  • fn open(dir: &str) -> StoreResult<Store>
  • fn open_with(dir: &str, opts: Options) -> StoreResult<Store>
  • fn open_encrypted(dir: &str, opts: Options, key: &[u8; 32]) -> StoreResult<Store> open an encrypted store (a new one in an empty or missing folder) with its 32-byte key, for example one kept in the system's secret store (plat::secret::secret_get). A store in the clear, or one sealed with another key, is StoreError::Key
  • fn encrypted(&self) -> bool whether the store is encrypted
  • fn recovery(&self) -> &Recovery what open() found and repaired
  • fn seq(&self) -> u64 the sequence number of the last transaction
  • fn get(&self, coll: &str, id: &str) -> Option<Value>
  • fn contains(&self, coll: &str, id: &str) -> bool
  • fn list(&self, coll: &str) -> Vec<(String, Value)> every record of a collection, ordered by id
  • fn filter(&self, coll: &str, mut f: impl FnMut(&str, &Value) -> bool) -> Vec<(String, Value)> the records for which f holds
  • fn ids(&self, coll: &str) -> Vec<String>
  • fn count(&self, coll: &str) -> usize
  • fn write<E: From<StoreError>>(&self, f: impl FnOnce(&Data, &mut Tx) -> Result<(), E>) -> Result<u64, E> run a transaction: the changes f records become durable and visible together (f sees the current data; nothing is written when it returns Err or records nothing)
  • fn put(&self, coll: &str, id: &str, v: Value) -> StoreResult<u64> put one record
  • fn delete(&self, coll: &str, id: &str) -> StoreResult<u64> delete one record
  • fn update(&self, coll: &str, id: &str, f: impl FnOnce(&mut Value)) -> StoreResult<Option<Value>> change one record in place (None: it does not exist)
  • fn compact(&self) -> StoreResult<()> write a snapshot now and start a new log
  • fn rekey(&self, key: Option<&[u8; 32]>) -> StoreResult<()> encrypt the store with key, change its key, or (None) keep it in the clear again: a snapshot under the new key and a new log, then every other snapshot and log goes (they are under the old key). Removed, not wiped: on an SSD nothing promises the old blocks are gone. A crash in between leaves the new snapshot, which the new key opens. Err(Io) after the switch names files under the old key that could not be removed
  • fn add_index(&self, coll: &str, name: &str, def: Index) -> StoreResult<()> index the records of a collection (built now from what is there, kept up to date by every commit; replaces an index of the same name). A unique index over records that share a key is refused (Conflict), and from then on every transaction that would make two share one. Indexes are not stored: add them after each open
  • fn drop_index(&self, coll: &str, name: &str) -> bool remove an index -> whether there was one
  • fn index_names(&self, coll: &str) -> Vec<String> the names of a collection's indexes
  • fn find(&self, coll: &str, index: &str, key: &Key) -> StoreResult<Vec<(String, Value)>> the records that have key in the index, ordered by id
  • fn find_one(&self, coll: &str, index: &str, key: &Key) -> StoreResult<Option<(String, Value)>> the first record that has key (the one of a unique index)
  • fn range(&self, coll: &str, index: &str, keys: impl RangeBounds<Key>, order: Order, limit: usize) -> StoreResult<Vec<(String, Value)>> the records whose keys lie in keys, by key and then id (Desc: the other way round), at most limit (usize::MAX: all); a record with several keys in the range comes once for each
  • fn count_key(&self, coll: &str, index: &str, key: &Key) -> StoreResult<usize> how many records have key in the index

datastore/index.rs#

Source: lib/datastore/index.rs

index -- secondary indexes of a collection: keys of a record (a field, or a function of the
record) -> the ids that have them, kept in memory beside the data and updated by every
commit.  A unique index refuses a transaction that would give two records one key
(StoreError::Conflict) before anything is written.

  Key            Bool < Int < Str (by kind, then value); Key::of(&Value): strings, booleans
                 and integral numbers (i64 and u64), nothing else
  Index::field("owner.id") / Index::by(|id, v| keys) / .unique()
  Store::add_index / drop_index / find / find_one / range (lib.rs)

Indexes are not stored: an app adds them after every open, and they are built from the
records then (one pass).  An array at a field's path gives one key per element; missing
members, null, objects and fractions give none (the record is not in the index).
  • enum Key a key of an index
    • Bool(bool)
    • Int(i128) -- an integral number (every i64 and u64)
    • Str(String)

impl Key

  • fn of(v: &Value) -> Option<Key> a JSON value as a key: a string, a boolean or an integral number; None for the rest (null, arrays, objects, fractions and numbers beyond i64 and u64)

  • struct Index what an index takes from a record: Index::field or Index::by, maybe unique

impl Index

  • fn field(path: &str) -> Index the value at a path of members, '.' between them ("owner" or "owner.id"); an array there gives a key for each element that is one (Key::of)

  • fn by(f: impl Fn(&str, &Value) -> Vec<Key> + Send + Sync + 'static) -> Index keys computed from a record (its id and value): a member name with a '.', several fields together (as one Key::Str), a fraction scaled to an integer. The keys of a record are kept with it, so they are removed exactly when it changes

  • fn unique(mut self) -> Index no two records may share a key (a record may have a key twice)

  • fn is_unique(&self) -> bool

  • enum Order the order of Store::range

    • Asc -- by key, then id
    • Desc -- the other way round

datastore/journal.rs#

Source: lib/datastore/journal.rs

journal -- append-only logs of JSON lines, one file per name and month
(<dir>/<name>/<yyyymm>.jl): audit entries, session logs.  A line is complete or ignored (a
crash during an append leaves at most one partial last line, which readers skip).
Encrypted (open_encrypted): every line sealed on its own ("~" + base64url, seal.rs), bound
to its journal and month; lines that do not open -- plain ones too -- are skipped.
Journal::rekey rewrites the files for another key, or none.
  • struct Journal

impl Journal

  • fn open(dir: &str, durable: bool) -> StoreResult<Journal> journals below dir; durable: fsync each append
  • fn open_encrypted(dir: &str, durable: bool, key: &[u8; 32]) -> StoreResult<Journal> journals below dir whose lines are sealed with a 32-byte key (the key of a Store may be used: the journal derives keys of its own)
  • fn encrypted(&self) -> bool whether the lines are sealed
  • fn append(&self, name: &str, month: u32, v: &Value) -> StoreResult<()> append one entry to journal name in month yyyymm (e.g. 202610)
  • fn months(&self, name: &str) -> Vec<u32> the months that have entries, oldest first
  • fn read_month(&self, name: &str, month: u32) -> Vec<Value> the entries of one month, oldest first
  • fn tail(&self, name: &str, n: usize) -> Vec<Value> the newest n entries (oldest first), across months
  • fn prune_before(&self, name: &str, month: u32) -> usize remove the months before month (retention)
  • fn remove(&self, name: &str) remove a whole journal (e.g. the log of a deleted session)
  • fn rekey(dir: &str, from: Option<&[u8; 32]>, to: Option<&[u8; 32]>) -> StoreResult<usize> rewrite the journals below dir for another key: from (None: in the clear) is the key they have, to the one they get (None: in the clear) -> the files rewritten. Each file is replaced whole (written aside, synced, renamed). Interrupted, it is run again with the same keys: lines that are under to already stay. Lines that open under neither (damaged, a third key) stay as they are, unreadable as before. No Journal may be open on dir meanwhile (an append could be lost)

Source: docs/API.md in the JFLib repository.