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 layout engine over a [`RawKv`] view that
47//!   the flat backends share).
48//! - `kv_store_tests!` (feature `test-utils`) — the conformance suite every
49//!   backend must pass, so key schemas can be written once against one set of
50//!   ordering and bound answers.
51//!
52//! ## Backends
53//!
54//! The trait and the plumbing live here; the concrete backends live in sibling
55//! crates: `fasm-storage-btreemap` (in-memory, tests and simulations only),
56//! `fasm-storage-redb`, `fasm-storage-fdb`, and `fasm-storage-indexeddb`
57//! (browser, `wasm32-unknown-unknown`). The IndexedDB backend captures a full
58//! snapshot per session or reader, reuses `FlatEngine`, and applies each write
59//! buffer in one revision-fenced readwrite commit using `?Send` browser futures.
60//! The conformance suite runs in the browser through its `test_attr`
61//! arm. The target-aware portability markers preserve the native backends'
62//! thread-safety contract while allowing browser storage handles and futures.
63//!
64//! ## Example
65//!
66//! The shape below is what every backend — and therefore every state machine
67//! on top — must provide. It is written generically over the backend so this
68//! documentation does not depend on any particular one; the concrete in-memory
69//! usage lives in `fasm-storage-btreemap`.
70//!
71//! ```
72//! use std::ops::Bound;
73//!
74//! use fasm_storage::{Commit, KvStore, ScopedKvStore};
75//!
76//! /// One invocation of a state transition is one session is one commit.
77//! /// `swap` is pinned to one directory; the relative directory argument
78//! /// is empty, so every operation addresses the pinned directory itself.
79//! async fn transition<S>(mut swap: ScopedKvStore<S>) -> Result<(), <S as Commit>::Error>
80//! where
81//!     S: KvStore + Commit,
82//! {
83//!     // Multi-key writes under a single session.
84//!     let _ = swap.set(&[], b"status", b"funded").await;
85//!     let _ = swap.range(&[], Bound::Unbounded, Bound::Unbounded, false).collect().await;
86//!
87//!     // Finalize the session atomically.
88//!     swap.commit().await?;
89//!     Ok(())
90//! }
91//! # fn main() {}
92//! ```
93
94mod commit;
95mod error;
96pub mod flatdir;
97pub mod flatengine;
98mod key;
99mod keyspace;
100mod maybe_send;
101mod nav;
102pub mod rawkv;
103mod scoped;
104mod store;
105mod stream;
106
107#[cfg(any(feature = "test-utils", test))]
108mod conformance;
109
110#[cfg(test)]
111mod tests;
112
113pub use commit::Commit;
114pub use error::RetryableStorageError;
115pub use flatengine::{DataBounds, FlatEngine, FlatError};
116pub use key::{Key, KeyError, validate_dir};
117pub use keyspace::{bound_as_slice, bound_to_owned, is_empty_range, next_prefix, prefix_range};
118pub use maybe_send::{MaybeSend, MaybeSync};
119pub use nav::KvDirNav;
120pub use rawkv::RawKv;
121pub use scoped::ScopedKvStore;
122pub use store::KvStore;
123pub use stream::{KvPair, KvStream};
124
125/// Re-exports for [`kv_store_tests!`]. Not part of the public API.
126///
127/// The macro expands at the call site, where nothing it needs is guaranteed to
128/// be in scope; every path it emits goes through here so that invoking crates
129/// need no imports of their own.
130#[cfg(any(feature = "test-utils", test))]
131#[doc(hidden)]
132pub mod __private {
133    pub use core::ops::Bound;
134}