fasm_storage/store.rs
1//! The [`KvStore`] trait: an async byte-to-byte map scoped by directory.
2
3use core::error::Error;
4use core::future::Future;
5use core::ops::Bound;
6
7use crate::error::RetryableStorageError;
8use crate::maybe_send::{MaybeSend, MaybeSync};
9use crate::stream::KvStream;
10
11/// Async ordered key-value store, scoped by directory.
12///
13/// This trait abstracts over the in-memory BTreeMap, redb, FoundationDB, and
14/// browser IndexedDB backends. Store types and method futures use [`MaybeSend`]
15/// (and store types also use [`MaybeSync`]): these mean `Send`/`Sync` on native
16/// targets but impose no thread-safety requirement in a browser, where storage
17/// handles may hold `JsValue`s. The browser exception deliberately targets only
18/// `wasm32-unknown-unknown`, rather than `target_family = "wasm"`, because targets
19/// such as `wasm32-wasip1-threads` have real threads. Every operation is async so
20/// that network-backed and transactional engines fit without a blocking shim.
21///
22/// # Directories and keys
23///
24/// Every operation names a **directory** and a **key**. A directory is a
25/// sequence of segments (`&[&[u8]]`; the empty slice is the root directory);
26/// a key is an arbitrary byte sequence. The pair is the store's real key:
27/// the same key bytes in different directories are distinct entries, and a
28/// scan of one directory never yields another's keys.
29///
30/// **Directory segments are UTF-8** (the trait-level contract): every
31/// operation validates its directory with [`validate_dir`](crate::validate_dir) and rejects a
32/// non-UTF-8 segment with [`KeyError::DirSegmentNotUtf8`](crate::KeyError)
33/// before touching the engine. Keys have no such restriction.
34///
35/// Directories are created **lazily by the first write**: a `set` into a
36/// never-written directory allocates it (and any missing ancestor). Reads on
37/// a missing directory are empty, not an error — `get` answers `None`,
38/// `range` an empty stream. Existence is a query, [`KvDirNav::dir_exists`](crate::nav::KvDirNav::dir_exists)
39/// (crate root) — a directory with zero keys still exists.
40///
41/// # Ordering
42///
43/// Keys are **arbitrary byte sequences** ordered **lexicographically by byte
44/// value**, exactly as [`Ord for [u8]`](slice) defines it, within their
45/// directory. Shorter keys sort before longer keys that extend them, so
46/// `[1] < [1, 0] < [1, 0, 0] < [2]`. This is what makes a resolved
47/// directory prefix a usable namespacing scheme and is not negotiable per
48/// backend: a store whose engine orders differently must translate.
49///
50/// The empty key is a legal key and sorts first.
51///
52/// # Range scans
53///
54/// [`range`](KvStore::range) scans **one exact directory** between two key
55/// bounds and returns a continuation-based [`KvStream`] of
56/// [`KvPair`](crate::KvPair) whose `key` is the within-directory key — the
57/// directory is implicit in the scan. This enables backends to fetch
58/// incrementally, but does not require it: a backend may prefetch pages or
59/// materialize a snapshot. [`KvStream::take`] limits continuation polling,
60/// not necessarily backend fetches.
61///
62/// Bounds are over the within-directory key. A range whose keyed `start`
63/// sorts after its keyed `end` is empty. Equal keyed bounds are empty when
64/// either bound is excluded; two included equal bounds select that one key.
65///
66/// Scans across directories (subtree scans, multi-directory scans) are not
67/// expressible in one call; the directory dimension is exact-match only.
68///
69/// # Atomicity
70///
71/// Transactional backends **buffer writes until commit**. Reads issued through
72/// a handle must observe that handle's own buffered writes (read-your-writes),
73/// but nothing becomes visible to other handles, and nothing is durable, until
74/// the atomic commit is applied. `Ok(())` confirms that outcome; a
75/// non-retryable commit error may leave it unknown.
76///
77/// This matters because the state machines built on top perform multi-key
78/// updates — a swap row plus its registry summary, an index insertion plus the
79/// row it points at — whose exactly-once guarantees depend on all-or-nothing
80/// application. A partially applied session can double-credit, duplicate a
81/// withdrawal, or strand a reservation forever.
82/// The in-memory backend (the `fasm-storage-btreemap` crate) provides the same
83/// buffering, read-your-writes, and drop-rollback contract with no durability:
84/// a crash loses the base map, so it is test/simulation-only — the
85/// transaction contract itself does not differ.
86///
87/// # Errors
88///
89/// The associated error type must be a real [`Error`] and must answer
90/// [`RetryableStorageError::is_retryable`], because the layer above needs to
91/// distinguish "the transaction conflicted, rerun the transition" from "this
92/// data is corrupt, fail closed".
93///
94/// # Why `Sync`
95///
96/// Every method future is explicitly [`MaybeSend`]: it is `Send` on native
97/// targets, so a generic caller can move (for example) `store.get(..)` across a
98/// task boundary when `S: KvStore + Sync`. In a browser the marker does not
99/// require `Send`, allowing both the store and its futures to remain
100/// thread-local. [`MaybeSync`] supplies the native `Sync` requirement needed by
101/// futures that capture `&Self`.
102pub trait KvStore: MaybeSend + MaybeSync {
103 /// The error type for this store.
104 type Error: Error + RetryableStorageError + MaybeSend + MaybeSync + 'static;
105
106 /// Get a value by directory and key.
107 ///
108 /// Returns `Ok(Some(value))` if the key is present in the directory,
109 /// `Ok(None)` if it is not or the directory does not exist.
110 fn get(
111 &self,
112 dir: &[&[u8]],
113 key: &[u8],
114 ) -> impl Future<Output = Result<Option<Vec<u8>>, Self::Error>> + MaybeSend;
115
116 /// Set a key-value pair in a directory, overwriting any existing value
117 /// for the key. The directory (and any missing ancestor) is allocated
118 /// if needed.
119 fn set(
120 &mut self,
121 dir: &[&[u8]],
122 key: &[u8],
123 value: &[u8],
124 ) -> impl Future<Output = Result<(), Self::Error>> + MaybeSend;
125
126 /// Delete a key from a directory.
127 ///
128 /// Deleting an absent key or a key in a missing directory is a no-op,
129 /// not an error.
130 fn delete(
131 &mut self,
132 dir: &[&[u8]],
133 key: &[u8],
134 ) -> impl Future<Output = Result<(), Self::Error>> + MaybeSend;
135
136 /// Check whether a key exists in a directory.
137 ///
138 /// The default implementation goes through [`get`](KvStore::get) and
139 /// therefore pays for transferring the value. Backends with a cheaper
140 /// existence probe should override it.
141 fn exists(
142 &self,
143 dir: &[&[u8]],
144 key: &[u8],
145 ) -> impl Future<Output = Result<bool, Self::Error>> + MaybeSend {
146 async move { Ok(self.get(dir, key).await?.is_some()) }
147 }
148
149 /// Scan the keys of one directory between two key bounds, in
150 /// lexicographic order.
151 ///
152 /// Results are exposed through the returned continuation-based
153 /// [`KvStream`]; each pair's key is the within-directory key.
154 ///
155 /// # Arguments
156 ///
157 /// * `dir` — the exact directory to scan (validated UTF-8 segments).
158 /// * `start` — start bound over the within-directory key
159 /// (included / excluded / unbounded)
160 /// * `end` — end bound (included / excluded / unbounded)
161 /// * `reverse` — if `true`, produce the same set of pairs in descending
162 /// key order. `reverse` changes the iteration direction only; it never
163 /// reinterprets which bound is which.
164 ///
165 /// # Examples
166 ///
167 /// ```
168 /// use std::ops::Bound;
169 ///
170 /// use fasm_storage::KvStore;
171 ///
172 /// async fn demo<S: KvStore>(store: &S) -> Result<(), S::Error> {
173 /// // In directory `["pool"]`, all keys from "a" (inclusive) to
174 /// // "z" (exclusive).
175 /// let _ = store
176 /// .range(&[b"pool"], Bound::Included(b"a"), Bound::Excluded(b"z"), false)
177 /// .collect()
178 /// .await?;
179 ///
180 /// // In the root directory, all keys starting from "start".
181 /// let _ = store.range(&[], Bound::Included(b"start"), Bound::Unbounded, false);
182 ///
183 /// // The whole root directory, newest key first.
184 /// let _ = store.range(&[], Bound::Unbounded, Bound::Unbounded, true);
185 /// Ok(())
186 /// }
187 /// # fn main() {}
188 /// ```
189 fn range<'a>(
190 &'a self,
191 dir: &[&[u8]],
192 start: Bound<&'a [u8]>,
193 end: Bound<&'a [u8]>,
194 reverse: bool,
195 ) -> KvStream<'a, Self::Error>;
196
197 /// Delete every key in a range within one directory.
198 ///
199 /// Semantically identical to scanning the range and deleting each key,
200 /// but backends with a native range delete should use it. Clearing a
201 /// range that matches nothing is a no-op, not an error — including a
202 /// missing directory. The same empty-bound rules as
203 /// [`range`](KvStore::range) apply, including inverted keyed bounds.
204 ///
205 /// Clearing a directory's whole range (`Unbounded` to `Unbounded`)
206 /// removes all of its keys but **not** the directory itself:
207 /// [`KvDirNav::dir_exists`](crate::nav::KvDirNav::dir_exists) (crate root) still answers `true` after.
208 fn clear_range(
209 &mut self,
210 dir: &[&[u8]],
211 start: Bound<&[u8]>,
212 end: Bound<&[u8]>,
213 ) -> impl Future<Output = Result<(), Self::Error>> + MaybeSend;
214}