fasm_storage/stream.rs
1//! The consuming key-value continuation returned by range scans.
2
3use core::fmt;
4use core::future::Future;
5use core::pin::Pin;
6
7use crate::maybe_send::MaybeSend;
8
9/// A key-value pair produced by a range scan.
10///
11/// Keys are always reported relative to the exact directory passed to
12/// [`KvStore::range`](crate::KvStore::range). A [`ScopedKvStore`] joins its
13/// pinned directory with the caller's relative directory, but the returned key
14/// remains the within-directory key.
15///
16/// [`ScopedKvStore`]: crate::ScopedKvStore
17#[derive(Clone, PartialEq, Eq)]
18pub struct KvPair {
19 /// The key bytes.
20 pub key: Vec<u8>,
21 /// The value bytes.
22 pub value: Vec<u8>,
23}
24
25impl fmt::Debug for KvPair {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 write!(
28 f,
29 "KvPair {{ key: <elided>, value: <{} bytes> }}",
30 self.value.len()
31 )
32 }
33}
34
35/// The boxed future type inside a [`KvStream`].
36// Trait objects may add only auto traits such as `Send`; the target-aware
37// `MaybeSend` marker therefore cannot be written directly on this `dyn` type.
38#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
39type KvStreamFuture<'a, E> =
40 Pin<Box<dyn Future<Output = Result<Option<(KvPair, KvStream<'a, E>)>, E>> + Send + 'a>>;
41
42/// The boxed future type inside a browser [`KvStream`].
43#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
44type KvStreamFuture<'a, E> =
45 Pin<Box<dyn Future<Output = Result<Option<(KvPair, KvStream<'a, E>)>, E>> + 'a>>;
46
47/// An async stream of key-value pairs.
48///
49/// This is a *consuming cons-list*: awaiting the stream yields either `None`
50/// (exhausted) or one [`KvPair`] together with the stream carrying the remainder.
51/// Consuming rather than borrowing means a backend can keep a live cursor, a
52/// page buffer, or a transaction read handle inside the future without any of
53/// it leaking into the caller's borrow graph.
54///
55/// The continuation shape enables lazy backends, but does not force a fetching
56/// strategy. A backend may prefetch pages or materialize the range up front;
57/// [`take`] stops polling continuations after its limit, but cannot undo such
58/// backend work. The in-memory backend, for example, materializes its
59/// snapshot up front.
60///
61/// # Cancellation
62///
63/// This stream and its async methods are consuming. Dropping a returned future,
64/// as can happen when it loses a `select` or timeout race, loses both the
65/// in-flight page and the continuation. To resume, reissue
66/// [`KvStore::range`](crate::KvStore::range) from the last processed key; the
67/// caller owns deduplication at that seam.
68///
69/// ```
70/// use std::ops::Bound;
71///
72/// use fasm_storage::KvStore;
73///
74/// async fn demo<S: KvStore>(store: &S) -> Result<(), S::Error> {
75/// let mut cursor = store.range(&[], Bound::Unbounded, Bound::Unbounded, false);
76/// while let Some((pair, rest)) = cursor.next().await? {
77/// println!("key has {} bytes", pair.key.len());
78/// cursor = rest;
79/// }
80/// Ok(())
81/// }
82/// # fn main() {}
83/// ```
84///
85/// [`take`]: KvStream::take
86#[must_use = "a KvStream does nothing unless awaited"]
87pub struct KvStream<'a, E> {
88 inner: KvStreamFuture<'a, E>,
89}
90
91impl<E> fmt::Debug for KvStream<'_, E> {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.write_str("KvStream(..)")
94 }
95}
96
97impl<'a, E> KvStream<'a, E> {
98 /// Create a new stream from a future producing the head pair and the tail.
99 ///
100 /// On native targets the future must be `Send` so scans can cross task
101 /// boundaries. Browser futures may retain thread-local Web API handles. It
102 /// is boxed in either case, so backends may return async blocks of any
103 /// shape.
104 pub fn new<F>(fut: F) -> Self
105 where
106 F: Future<Output = Result<Option<(KvPair, KvStream<'a, E>)>, E>> + MaybeSend + 'a,
107 {
108 Self {
109 inner: Box::pin(fut),
110 }
111 }
112
113 /// Create an empty stream (no items).
114 pub fn empty() -> Self
115 where
116 E: 'a,
117 {
118 Self {
119 inner: Box::pin(async { Ok(None) }),
120 }
121 }
122
123 /// Create a stream that fails on its first poll.
124 ///
125 /// Useful for backends whose `range` signature cannot return a `Result` but
126 /// which can fail while *setting up* the scan (acquiring a snapshot,
127 /// mapping bounds); the failure is deferred into the stream instead of
128 /// being swallowed.
129 pub fn failed(err: E) -> Self
130 where
131 E: MaybeSend + 'a,
132 {
133 Self {
134 inner: Box::pin(async move { Err(err) }),
135 }
136 }
137
138 /// Get the next item in the stream.
139 ///
140 /// Returns `Ok(Some((pair, next)))` if there is another item, or
141 /// `Ok(None)` if the stream is exhausted.
142 ///
143 /// This consumes the stream. Dropping the returned future loses the
144 /// in-flight page and continuation; resume by reissuing the range from the
145 /// last processed key and deduplicate at the seam.
146 pub async fn next(self) -> Result<Option<(KvPair, KvStream<'a, E>)>, E> {
147 self.inner.await
148 }
149
150 /// Collect all remaining items into a vector.
151 ///
152 /// **Warning**: this loads the entire remaining range into memory. Prefer
153 /// [`take`](Self::take) or [`for_each`](Self::for_each) for unbounded scans.
154 ///
155 /// This consumes the stream. Dropping the returned future loses the
156 /// in-flight page and continuation; resume by reissuing the range from the
157 /// last processed key and deduplicate at the seam.
158 pub async fn collect(self) -> Result<Vec<KvPair>, E> {
159 let mut results = Vec::new();
160 let mut current = self;
161
162 while let Some((pair, next)) = current.next().await? {
163 results.push(pair);
164 current = next;
165 }
166
167 Ok(results)
168 }
169
170 /// Collect up to `limit` items into a vector.
171 ///
172 /// Stops polling continuations as soon as `limit` items have been produced.
173 /// A backend may already have prefetched or materialized additional items.
174 ///
175 /// This consumes the stream. Dropping the returned future loses the
176 /// in-flight page and continuation; resume by reissuing the range from the
177 /// last processed key and deduplicate at the seam.
178 pub async fn take(self, limit: usize) -> Result<Vec<KvPair>, E> {
179 let mut results = Vec::with_capacity(limit.min(64));
180 let mut current = self;
181
182 for _ in 0..limit {
183 match current.next().await? {
184 Some((pair, next)) => {
185 results.push(pair);
186 current = next;
187 }
188 None => break,
189 }
190 }
191
192 Ok(results)
193 }
194
195 /// Apply a function to each item, stopping on the first *stream* error.
196 ///
197 /// The visitor is infallible and synchronous, so it can neither stop the
198 /// walk early nor report a failure of its own. A consumer that needs either
199 /// — a parse that can fail, a search that ends at the first match — should
200 /// drive [`next`](Self::next) directly rather than reaching for this.
201 ///
202 /// This consumes the stream. Dropping the returned future loses the
203 /// in-flight page and continuation; resume by reissuing the range from the
204 /// last processed key and deduplicate at the seam.
205 pub async fn for_each<F>(self, mut f: F) -> Result<(), E>
206 where
207 F: FnMut(KvPair),
208 {
209 let mut current = self;
210
211 while let Some((pair, next)) = current.next().await? {
212 f(pair);
213 current = next;
214 }
215
216 Ok(())
217 }
218}