Skip to main content

fasm_storage/
scoped.rs

1//! [`ScopedKvStore`]: a directory-pinned view over any [`KvStore`].
2
3use core::fmt;
4use core::future::Future;
5use core::ops::Bound;
6
7use crate::commit::Commit;
8use crate::nav::KvDirNav;
9use crate::store::KvStore;
10use crate::stream::KvStream;
11
12/// A directory-pinned view of another [`KvStore`].
13///
14/// The store is pinned to a directory, and every operation's directory
15/// argument is a **relative path from the pin**: the empty path names the
16/// pinned directory itself, and a non-empty path names a subdirectory of it.
17/// The inner store sees the joined absolute path; the caller never types the
18/// pinned part again. Bounds pass through unchanged — they are always over
19/// the within-directory key, so a scan yields keys of the directory the call
20/// names.
21///
22/// The pinned directory (and any relative subdirectory) is created lazily
23/// like any other (the first write allocates it); reads on a never-written
24/// directory are empty.
25///
26/// This type is scope plumbing, **not a capability boundary**.
27/// [`Self::inner`], [`Self::inner_mut`], and [`Self::into_inner`] deliberately
28/// expose the wrapped store, through which code may access any directory.
29/// Callers that need structural isolation must not hand out those escape
30/// hatches. Higher layers own that restriction; the scoped handles held by
31/// state-machine crates are the actual capability boundary.
32///
33/// # Commit
34///
35/// [`Commit`] forwards straight through, unwrapped: pinning a directory
36/// cannot fail at commit time, so there is no scoped error to introduce and
37/// the caller keeps the backend's own commit error type.
38#[derive(Clone, PartialEq, Eq)]
39pub struct ScopedKvStore<KV> {
40    inner: KV,
41    dir: Vec<Vec<u8>>,
42}
43
44impl<KV> fmt::Debug for ScopedKvStore<KV> {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        f.debug_struct("ScopedKvStore")
47            .field("dir_segments", &self.dir.len())
48            .finish()
49    }
50}
51
52impl<KV> ScopedKvStore<KV> {
53    /// Wrap `inner`, pinning every operation under the directory `dir`:
54    /// a caller path `p` is issued to the inner store as `dir ++ p`.
55    ///
56    /// An empty directory pins the root and yields a transparent
57    /// pass-through view.
58    pub fn new(inner: KV, dir: impl Into<Vec<Vec<u8>>>) -> Self {
59        Self {
60            inner,
61            dir: dir.into(),
62        }
63    }
64
65    /// The pinned directory, as owned segments.
66    pub fn dir(&self) -> &[Vec<u8>] {
67        &self.dir
68    }
69
70    /// Borrow the wrapped store, which still sees any directory.
71    pub fn inner(&self) -> &KV {
72        &self.inner
73    }
74
75    /// Mutably borrow the wrapped store, which still sees any directory.
76    pub fn inner_mut(&mut self) -> &mut KV {
77        &mut self.inner
78    }
79
80    /// Unwrap, returning the underlying store.
81    pub fn into_inner(self) -> KV {
82        self.inner
83    }
84
85    /// Build a further-nested scope by appending one segment to this
86    /// directory.
87    ///
88    /// Consumes `self`, since the outer view and the nested view would
89    /// otherwise both claim ownership of the same backend.
90    pub fn nested(self, seg: impl Into<Vec<u8>>) -> Self {
91        let seg = seg.into();
92        Self {
93            inner: self.inner,
94            dir: {
95                let mut dir = self.dir;
96                dir.push(seg);
97                dir
98            },
99        }
100    }
101}
102
103/// Join a pinned directory with a caller-supplied relative path, as a
104/// per-op borrow slice.
105///
106/// A free function so the pin borrow is a `self.dir` *field* borrow, kept
107/// disjoint from the `self.inner` borrow the same statement takes for the
108/// forwarded call.
109fn join_dir<'a>(pin: &'a [Vec<u8>], rel: &'a [&'a [u8]]) -> Vec<&'a [u8]> {
110    pin.iter()
111        .map(|s| s.as_slice())
112        .chain(rel.iter().copied())
113        .collect()
114}
115
116impl<KV: KvStore> KvStore for ScopedKvStore<KV> {
117    type Error = KV::Error;
118
119    async fn get(&self, dir: &[&[u8]], key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
120        self.inner.get(&join_dir(&self.dir, dir), key).await
121    }
122
123    async fn set(&mut self, dir: &[&[u8]], key: &[u8], value: &[u8]) -> Result<(), Self::Error> {
124        let d = join_dir(&self.dir, dir);
125        self.inner.set(&d, key, value).await
126    }
127
128    async fn delete(&mut self, dir: &[&[u8]], key: &[u8]) -> Result<(), Self::Error> {
129        let d = join_dir(&self.dir, dir);
130        self.inner.delete(&d, key).await
131    }
132
133    async fn exists(&self, dir: &[&[u8]], key: &[u8]) -> Result<bool, Self::Error> {
134        self.inner.exists(&join_dir(&self.dir, dir), key).await
135    }
136
137    fn range<'a>(
138        &'a self,
139        dir: &[&[u8]],
140        start: Bound<&'a [u8]>,
141        end: Bound<&'a [u8]>,
142        reverse: bool,
143    ) -> KvStream<'a, Self::Error> {
144        let d = join_dir(&self.dir, dir);
145        self.inner.range(&d, start, end, reverse)
146    }
147
148    async fn clear_range(
149        &mut self,
150        dir: &[&[u8]],
151        start: Bound<&[u8]>,
152        end: Bound<&[u8]>,
153    ) -> Result<(), Self::Error> {
154        let d = join_dir(&self.dir, dir);
155        self.inner.clear_range(&d, start, end).await
156    }
157}
158
159impl<KV: KvDirNav> KvDirNav for ScopedKvStore<KV> {
160    async fn list_dirs(&self, dir: &[&[u8]]) -> Result<Vec<Vec<u8>>, Self::Error> {
161        KvDirNav::list_dirs(&self.inner, &join_dir(&self.dir, dir)).await
162    }
163
164    async fn dir_exists(&self, dir: &[&[u8]]) -> Result<bool, Self::Error> {
165        KvDirNav::dir_exists(&self.inner, &join_dir(&self.dir, dir)).await
166    }
167
168    async fn remove_dir(&mut self, dir: &[&[u8]]) -> Result<bool, Self::Error> {
169        KvDirNav::remove_dir(&mut self.inner, &join_dir(&self.dir, dir)).await
170    }
171}
172
173impl<KV: Commit> Commit for ScopedKvStore<KV> {
174    type Error = KV::Error;
175
176    fn commit(self) -> impl Future<Output = Result<(), Self::Error>> {
177        self.inner.commit()
178    }
179}