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() -> Limitsthe limits of one stored recordenum StoreErrorLocked-- another process holds the storeIo(String)-- reading or writing a file failedCorrupt(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 limitsConflict(String)-- a transaction or a new index that would give two records the key of a unique indexKey(String)-- the store is encrypted and no key was given, it is not and one was, or it is sealed with another keyNoIndex(String)-- no index of this name on the collection (Store::add_index)
type StoreResult<T> = Result<T, StoreError>struct Optionssnapshot_bytes: u64-- write a snapshot (and start a new log) when the log grows beyond thisrepair: bool-- cut a damaged log at the damage instead of refusing to opendurable: bool-- fsync every transaction (off only for tests and bulk imports)
struct Recoverywhat open() foundsnapshot_seq: u64frames_replayed: u64truncated_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 Txthe 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) -> booltype Data = BTreeMap<String, BTreeMap<String, Value>>the records of every collection: collection -> id -> valuestruct Storethe 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::Keyfn encrypted(&self) -> boolwhether the store is encryptedfn recovery(&self) -> &Recoverywhat open() found and repairedfn seq(&self) -> u64the sequence number of the last transactionfn get(&self, coll: &str, id: &str) -> Option<Value>fn contains(&self, coll: &str, id: &str) -> boolfn list(&self, coll: &str) -> Vec<(String, Value)>every record of a collection, ordered by idfn filter(&self, coll: &str, mut f: impl FnMut(&str, &Value) -> bool) -> Vec<(String, Value)>the records for whichfholdsfn ids(&self, coll: &str) -> Vec<String>fn count(&self, coll: &str) -> usizefn write<E: From<StoreError>>(&self, f: impl FnOnce(&Data, &mut Tx) -> Result<(), E>) -> Result<u64, E>run a transaction: the changesfrecords 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 recordfn delete(&self, coll: &str, id: &str) -> StoreResult<u64>delete one recordfn 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 logfn rekey(&self, key: Option<&[u8; 32]>) -> StoreResult<()>encrypt the store withkey, 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 removedfn 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 openfn drop_index(&self, coll: &str, name: &str) -> boolremove an index -> whether there was onefn index_names(&self, coll: &str) -> Vec<String>the names of a collection's indexesfn find(&self, coll: &str, index: &str, key: &Key) -> StoreResult<Vec<(String, Value)>>the records that havekeyin the index, ordered by idfn find_one(&self, coll: &str, index: &str, key: &Key) -> StoreResult<Option<(String, Value)>>the first record that haskey(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 inkeys, by key and then id (Desc: the other way round), at mostlimit(usize::MAX: all); a record with several keys in the range comes once for eachfn count_key(&self, coll: &str, index: &str, key: &Key) -> StoreResult<usize>how many records havekeyin 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 Keya key of an indexBool(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 Indexwhat an index takes from a record: Index::field or Index::by, maybe unique
impl Index
fn field(path: &str) -> Indexthe 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) -> Indexkeys 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 changesfn unique(mut self) -> Indexno two records may share a key (a record may have a key twice)fn is_unique(&self) -> boolenum Orderthe order of Store::rangeAsc-- by key, then idDesc-- 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 belowdir;durable: fsync each appendfn open_encrypted(dir: &str, durable: bool, key: &[u8; 32]) -> StoreResult<Journal>journals belowdirwhose 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) -> boolwhether the lines are sealedfn append(&self, name: &str, month: u32, v: &Value) -> StoreResult<()>append one entry to journalnamein monthyyyymm(e.g. 202610)fn months(&self, name: &str) -> Vec<u32>the months that have entries, oldest firstfn read_month(&self, name: &str, month: u32) -> Vec<Value>the entries of one month, oldest firstfn tail(&self, name: &str, n: usize) -> Vec<Value>the newestnentries (oldest first), across monthsfn prune_before(&self, name: &str, month: u32) -> usizeremove the months beforemonth(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 belowdirfor another key:from(None: in the clear) is the key they have,tothe 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 undertoalready stay. Lines that open under neither (damaged, a third key) stay as they are, unreadable as before. No Journal may be open ondirmeanwhile (an append could be lost)