Skip to main content

fasm_storage/
lib.rs

1//! Ordered async byte-oriented key-value storage.
2//!
3//! This is the lowest storage layer for FASM state machines: an ordered map
4//! from byte keys to byte values, plus the two things a state machine needs on
5//! top of one — continuation-based range scans and an atomic commit boundary.
6//! It knows nothing about swaps, rows, or serialization; those live in the
7//! crates above it.
8//!
9//! ## The layering
10//!
11//! ```text
12//! state machine               typed rows, indexes, transitions
13//!         ▼
14//! high-level state traits     Result<Option<T>> getters over a key schema
15//!         ▼
16//! KvStore + Commit            ← this crate: ordered async bytes
17//!         ▼
18//! BTreeMapStore · redb tx · FoundationDB tx · IndexedDB session (browser wasm32-unknown-unknown)
19//! ```
20//!
21//! ## What this crate provides
22//!
23//! - [`KvStore`] — the backend trait: async `get`/`set`/`delete`/`exists`, a
24//!   continuation-based [`range`](KvStore::range) scan, and `clear_range`. Keys
25//!   are ordered lexicographically by byte value, always.
26//! - [`KvStream`] — the consuming continuation a scan returns, which enables
27//!   incremental backends without requiring a particular fetching strategy.
28//! - [`Commit`] — a *separate*, consuming trait marking the atomic boundary. One
29//!   state-transition invocation is one session is one commit.
30//! - [`RetryableStorageError`] — the contract every storage error answers, so
31//!   the layer above can tell "rerun the transition" from "fail closed".
32//! - [`MaybeSend`] and [`MaybeSync`] — target-aware portability markers that
33//!   preserve native thread-safety while permitting browser storage handles.
34//! - [`ScopedKvStore`] — a directory-pinned view over any backend: the caller
35//!   names keys only, every op lands in one directory; its inner-store escape
36//!   hatches are deliberate, not a capability boundary.
37//! - the keyspace helpers [`next_prefix`], [`prefix_range`], [`is_empty_range`],
38//!   [`bound_to_owned`], [`bound_as_slice`] — the pure bound arithmetic every
39//!   backend and key schema shares.
40//! - the directory-native key support: [`Key`] (the owned `(dir, key)` form),
41//!   [`validate_dir`] + [`KeyError`] (the trait-level UTF-8 directory
42//!   contract), [`KvDirNav`] (directory navigation — `list_dirs` /
43//!   `dir_exists` / `remove_dir`), the [`flatdir`] module (the flat
44//!   directory layout — a verbatim port of FoundationDB's `DirectoryLayer`:
45//!   tuple encoding, row layouts, HCA, directory ops) and the
46//!   [`flatengine`] module (the synchronous [`FlatEngine`] over [`RawKv`] and
47//!   asynchronous [`AsyncFlatEngine`] over [`AsyncRawKv`] that the flat
48//!   backends share).
49//! - `kv_store_tests!` (feature `test-utils`) — the conformance suite every
50//!   backend must pass, so key schemas can be written once against one set of
51//!   ordering and bound answers.
52//!
53//! ## Backends
54//!
55//! The trait and the plumbing live here; the concrete backends live in sibling
56//! crates: `fasm-storage-btreemap` (in-memory, tests and simulations only),
57//! `fasm-storage-redb`, `fasm-storage-fdb`, and `fasm-storage-indexeddb`
58//! (browser, `wasm32-unknown-unknown`). The IndexedDB backend pins each
59//! session or reader to the database revision on open, serves reads and
60//! bounded range scans directly from IndexedDB against that revision fence
61//! through [`AsyncFlatEngine`], buffers session writes and range deletes
62//! locally, and applies them in one revision-fenced readwrite commit using
63//! `?Send` browser futures. The conformance suite runs in the browser through
64//! its `test_attr` arm. The target-aware portability markers preserve the
65//! native backends' thread-safety contract while allowing browser storage
66//! handles and futures.
67//!
68//! ## Example
69//!
70//! The shape below is what every backend — and therefore every state machine
71//! on top — must provide. It is written generically over the backend so this
72//! documentation does not depend on any particular one; the concrete in-memory
73//! usage lives in `fasm-storage-btreemap`.
74//!
75//! ```
76//! use std::ops::Bound;
77//!
78//! use fasm_storage::{Commit, KvStore, ScopedKvStore};
79//!
80//! /// One invocation of a state transition is one session is one commit.
81//! /// `swap` is pinned to one directory; the relative directory argument
82//! /// is empty, so every operation addresses the pinned directory itself.
83//! async fn transition<S>(mut swap: ScopedKvStore<S>) -> Result<(), <S as Commit>::Error>
84//! where
85//!     S: KvStore + Commit,
86//! {
87//!     // Multi-key writes under a single session.
88//!     let _ = swap.set(&[], b"status", b"funded").await;
89//!     let _ = swap.range(&[], Bound::Unbounded, Bound::Unbounded, false).collect().await;
90//!
91//!     // Finalize the session atomically.
92//!     swap.commit().await?;
93//!     Ok(())
94//! }
95//! # fn main() {}
96//! ```
97
98mod commit;
99mod error;
100pub mod flatdir;
101pub mod flatengine;
102mod key;
103mod keyspace;
104mod maybe_send;
105mod nav;
106pub mod rawkv;
107mod scoped;
108mod store;
109mod stream;
110
111#[cfg(any(feature = "test-utils", test))]
112mod conformance;
113
114#[cfg(test)]
115mod tests;
116
117pub use commit::Commit;
118pub use error::RetryableStorageError;
119pub use flatengine::{AsyncFlatEngine, DataBounds, FlatEngine, FlatError};
120pub use key::{Key, KeyError, validate_dir};
121pub use keyspace::{bound_as_slice, bound_to_owned, is_empty_range, next_prefix, prefix_range};
122pub use maybe_send::{MaybeSend, MaybeSync};
123pub use nav::KvDirNav;
124pub use rawkv::{AsyncRawKv, RawKv};
125pub use scoped::ScopedKvStore;
126pub use store::KvStore;
127pub use stream::{KvPair, KvStream};
128
129/// Re-exports for [`kv_store_tests!`]. Not part of the public API.
130///
131/// The macro expands at the call site, where nothing it needs is guaranteed to
132/// be in scope; every path it emits goes through here so that invoking crates
133/// need no imports of their own.
134#[cfg(any(feature = "test-utils", test))]
135#[doc(hidden)]
136pub mod __private {
137    pub use core::ops::Bound;
138}