Skip to main content

storage_kit/ns/
namespace.rs

1//! [`Namespace`]: one tree for the app, a table of mounts underneath.
2//!
3//! To a caller there is a single file structure rooted at `/`. Under it is a mount table; each mount is a [`Backend`]
4//! at a namespace path. This is the Plan 9 composition (a namespace built from mounts) with the BeOS Storage Kit's
5//! shape (entries, directories, node monitoring).
6//!
7//! - **Longest prefix wins.** With mounts at `/data` and `/data/x`, `/data/x/f` is `/data/x`'s `f`; `/data/y` is
8//!   `/data`'s `y`. Mounts may nest. A path matched by no mount, and that no mount sits below, is `NotFound`.
9//! - **Mount points match case-folded** (by [`case_fold_key`], component by component). A mount at
10//!   `/Config` answers to `/config` and `/CONFIG`, so spelling a path differently can never route around a mount (on a
11//!   case-insensitive volume the host would otherwise answer to the other spelling and skip the mount's grant). Two
12//!   mount points that fold equal are one mount point, and are refused as `AlreadyExists`.
13//! - **A `ReadOnly` mount may not nest under a `ReadWrite` one** (`InvalidInput(ReadOnlyUnderReadWrite)`, at `build()`).
14//!   The writable parent could rename the directory that holds the nested mount point and then write through the new
15//!   name, which no nested mount covers. Mount read-only trees outside any writable mount (under a path that is only a
16//!   synthesised ancestor); a `ReadWrite` mount under a `ReadOnly` one is fine.
17//! - **Mount ancestors are synthesised.** With mounts at `/config` and `/data/x`, listing `/` gives `config` and `data`,
18//!   and `/data` lists `x`. Such a directory exists only as a name: it cannot be written (`PermissionDenied`) or watched
19//!   (`Unsupported(WatchOnMountAncestor)`).
20//! - **A real entry wins over a mount point for what it *is*.** If the mount covering `/a` has a *file* `b` and another
21//!   mount sits at `/a/b/c`, `walk(/a)` lists `b` as a file, `stat(/a/b)` says file and `read(/a/b)` returns its bytes: the
22//!   backend's entry decides the kind, the same for every verb. The nested mount is the thing that is refused: any verb
23//!   through `/a/b/c` answers `NotADirectory` (naming `/a/b`) while that file is in the way, because a mount point cannot
24//!   hang off a file. If the entry is a directory (or nothing is there, which is the synthetic case) the mount works and
25//!   the listing shows the name once. Costs one `stat` of the mount point's parent per call through a mount nested more
26//!   than one level below another.
27//! - **`Access::ReadOnly` is enforced here**, whatever the backend says, with `PermissionDenied`; a backend that is not
28//!   [`Caps::writable`] is refused as `Unsupported(Feature::Write)` even under `ReadWrite`.
29//! - **A rename across two mounts is `CrossMount`.** The caller copies, then removes; the Kit does not dress that up as
30//!   atomic. A rename whose destination is in *no* mount is `NotFound`.
31//! - **Errors and events carry namespace paths**, never a mount-relative one and never a host one.
32//! - **`walk` is sorted by name in UTF-8 byte order**, and is not paged yet (a directory is returned whole). Paging is
33//!   deferred until a read-only content-addressed mount has exercised the trait; adding it will be additive.
34//!
35//! - **A grant is per mount, not per host directory.** `Access::ReadOnly` makes every write *through that mount* a
36//!   `PermissionDenied`; it does not make the directory behind it read-only. Mount `D` read-write at `/rw` and `D/locked`
37//!   read-only at `/ro`, and a write through `/rw` changes what `/ro` reads. The Kit cannot see that: it holds no host
38//!   paths. The embedder chooses the host directories, so the embedder must keep them disjoint (or accept the overlap).
39//!   The one overlap it does catch is the **same** directory mounted twice, whatever the grants: `build()` refuses two
40//!   mounts whose backends report the same [`Backend::root_identity`] (`InvalidInput(DuplicateRoot)`). A directory
41//!   mounted together with an **ancestor or descendant** of itself is **not** detected, and neither is a backend that
42//!   reports no identity (`Memory` reports none).
43//!
44//! What the Namespace does **not** do is decide *which* host directories may be mounted, or who may mount what. That is
45//! policy, and policy (and the resolver that turns a role like "this app's config directory" into a real directory) is the
46//! embedder's. The Kit confines to the roots it is handed.
47//!
48//! A mount table is fixed at `build()`. Mount points are not protected from being renamed away inside a *writable*
49//! parent mount (that is why a `ReadOnly` mount cannot sit there): the namespace is a table of names, not a filesystem
50//! that tracks its own mount points.
51
52use std::fmt;
53use std::sync::Arc;
54
55use super::backend::{Access, Backend, Caps, Entry, Kind, Stat, Version, WriteOp};
56use super::error::{Feature, InputReason, NsError, NsErrorKind, NsResult};
57use super::path::{case_fold_key, NsPath};
58use super::watch::{Watch, WatchOpts};
59
60#[derive(Clone)]
61struct Mount {
62    point: NsPath,
63    /// `point`'s components as case-fold keys: what a request path is matched against.
64    key: Vec<String>,
65    backend: Arc<dyn Backend>,
66    access: Access,
67}
68
69/// Builds a [`Namespace`]. Obtain with [`Namespace::builder`].
70#[derive(Default)]
71pub struct NamespaceBuilder {
72    mounts: Vec<Mount>,
73}
74
75impl NamespaceBuilder {
76    /// Add a mount of `backend` at `point` with the given grant.
77    #[must_use]
78    pub fn mount(mut self, point: NsPath, backend: Arc<dyn Backend>, access: Access) -> Self {
79        self.mounts.push(Mount {
80            key: point.fold_components(),
81            point,
82            backend,
83            access,
84        });
85        self
86    }
87
88    /// Finish. Refused: two mounts at the same (case-folded) path (`AlreadyExists`), two mounts over the same host
89    /// directory (`InvalidInput(DuplicateRoot)`, from [`Backend::root_identity`]; the error names the later mount point),
90    /// and a `ReadOnly` mount nested under a `ReadWrite` one (`InvalidInput(ReadOnlyUnderReadWrite)`).
91    ///
92    /// Overlap of one host directory inside another (an ancestor and a descendant) is **not** detected; see the
93    /// [module docs](self).
94    pub fn build(self) -> NsResult<Namespace> {
95        for (i, m) in self.mounts.iter().enumerate() {
96            for other in &self.mounts[..i] {
97                if other.key == m.key {
98                    return Err(NsError::at(NsErrorKind::AlreadyExists, &m.point));
99                }
100            }
101        }
102        for (i, m) in self.mounts.iter().enumerate() {
103            let Some(id) = m.backend.root_identity() else {
104                continue;
105            };
106            if self.mounts[..i]
107                .iter()
108                .any(|other| other.backend.root_identity() == Some(id))
109            {
110                return Err(NsError::at(
111                    NsErrorKind::InvalidInput(InputReason::DuplicateRoot),
112                    &m.point,
113                ));
114            }
115        }
116        for m in &self.mounts {
117            if m.access != Access::ReadOnly {
118                continue;
119            }
120            let under_writable = self.mounts.iter().any(|a| {
121                a.access == Access::ReadWrite
122                    && a.key.len() < m.key.len()
123                    && m.key.starts_with(&a.key)
124            });
125            if under_writable {
126                return Err(NsError::at(
127                    NsErrorKind::InvalidInput(InputReason::ReadOnlyUnderReadWrite),
128                    &m.point,
129                ));
130            }
131        }
132        Ok(Namespace {
133            mounts: self.mounts,
134        })
135    }
136}
137
138/// A mount table and the five verbs over it: `walk`, `read`, `stat` (the `manifest` verb), `write` and `watch`.
139///
140/// Cheap to clone (the backends are shared).
141///
142/// **Grants are per mount, not per host directory.** A `ReadOnly` mount refuses writes made through it; it does not stop a
143/// `ReadWrite` mount (or another process) that reaches the same host files by another route. The embedder chooses the
144/// host directories and must keep them disjoint. `build()` refuses only the *same* directory mounted twice; an ancestor
145/// and a descendant mounted together are not detected, because the Kit holds no host paths. See the
146/// [module docs](self).
147#[derive(Clone)]
148pub struct Namespace {
149    mounts: Vec<Mount>,
150}
151
152impl fmt::Debug for Namespace {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        let mut list = f.debug_list();
155        for m in &self.mounts {
156            list.entry(&format_args!("{} ({:?})", m.point, m.access));
157        }
158        list.finish()
159    }
160}
161
162enum Resolved<'a> {
163    /// Covered by a mount; `rel` is the path inside it.
164    Mount {
165        mount: &'a Mount,
166        index: usize,
167        rel: NsPath,
168    },
169    /// Not covered by any mount, but at least one mount sits below it. Contains these child names.
170    Ancestor { children: Vec<String> },
171    /// Nothing here.
172    Nothing,
173}
174
175impl Namespace {
176    /// Start a mount table.
177    pub fn builder() -> NamespaceBuilder {
178        NamespaceBuilder::default()
179    }
180
181    /// The mount points, with their grants and the capabilities their backends declare.
182    pub fn mounts(&self) -> impl Iterator<Item = (&NsPath, Access, Caps)> + '_ {
183        self.mounts
184            .iter()
185            .map(|m| (&m.point, m.access, m.backend.caps()))
186    }
187
188    /// Names of the next component of every mount strictly below `path`, one per fold key, sorted.
189    fn child_mount_names(&self, path: &NsPath) -> Vec<String> {
190        let key = path.fold_components();
191        let depth = key.len();
192        let mut names: Vec<(String, String)> = self
193            .mounts
194            .iter()
195            .filter(|m| m.key.len() > depth && m.key.starts_with(&key))
196            .filter_map(|m| {
197                m.point
198                    .components()
199                    .nth(depth)
200                    .map(|c| (m.key[depth].clone(), c.to_string()))
201            })
202            .collect();
203        names.sort();
204        names.dedup_by(|a, b| a.0 == b.0);
205        names.into_iter().map(|(_, name)| name).collect()
206    }
207
208    fn resolve(&self, path: &NsPath) -> Resolved<'_> {
209        let key = path.fold_components();
210        let best = self
211            .mounts
212            .iter()
213            .enumerate()
214            .filter(|(_, m)| key.starts_with(&m.key))
215            .max_by_key(|(_, m)| m.key.len());
216        if let Some((index, mount)) = best {
217            let rel = path.tail_after(mount.key.len());
218            return Resolved::Mount { mount, index, rel };
219        }
220        let children = self.child_mount_names(path);
221        if children.is_empty() {
222            Resolved::Nothing
223        } else {
224            Resolved::Ancestor { children }
225        }
226    }
227
228    /// A mount point cannot hang off a file. If this mount is nested below another and the entry its point hangs from is
229    /// a file in that other mount, refuse (`NotADirectory`, naming the file). A directory, or nothing (the synthetic
230    /// case), is fine.
231    fn guard_nested(&self, index: usize) -> NsResult<()> {
232        let m = &self.mounts[index];
233        let Some(outer) = self
234            .mounts
235            .iter()
236            .filter(|o| o.key.len() < m.key.len() && m.key.starts_with(&o.key))
237            .max_by_key(|o| o.key.len())
238        else {
239            return Ok(());
240        };
241        if m.key.len() - outer.key.len() < 2 {
242            return Ok(()); // the mount point's parent is the outer mount's own root, which is a directory
243        }
244        let Some(parent) = m.point.parent() else {
245            return Ok(());
246        };
247        let rel = parent.tail_after(outer.key.len());
248        match outer.backend.stat(&rel) {
249            Ok(st) if st.kind == Kind::File => {
250                Err(NsError::at(NsErrorKind::NotADirectory, &parent))
251            }
252            Err(e) if e.kind() == NsErrorKind::NotADirectory => {
253                Err(NsError::at(NsErrorKind::NotADirectory, &parent))
254            }
255            _ => Ok(()),
256        }
257    }
258
259    /// List a directory. See the [module docs](self) for how mount ancestors and shadowing are handled.
260    pub fn walk(&self, path: &NsPath) -> NsResult<Vec<Entry>> {
261        match self.resolve(path) {
262            Resolved::Mount { mount, index, rel } => {
263                self.guard_nested(index)?;
264                let synthetic = self.child_mount_names(path);
265                let mut entries = match mount.backend.walk(&rel) {
266                    Ok(e) => e,
267                    // The directory is not in this backend but mounts sit below it: it exists as a mount ancestor.
268                    Err(e) if e.kind() == NsErrorKind::NotFound && !synthetic.is_empty() => {
269                        Vec::new()
270                    }
271                    Err(e) => return Err(e.rebased(&mount.point).or_at(path)),
272                };
273                for name in synthetic {
274                    // The backend's own entry (whatever its kind) wins; a mount name that folds equal to one is the same
275                    // entry, listed once.
276                    let key = case_fold_key(&name);
277                    if !entries.iter().any(|e| case_fold_key(&e.name) == key) {
278                        entries.push(Entry::new(name, Kind::Dir));
279                    }
280                }
281                entries.sort_by(|a, b| a.name.cmp(&b.name));
282                Ok(entries)
283            }
284            Resolved::Ancestor { children } => Ok(children
285                .into_iter()
286                .map(|name| Entry::new(name, Kind::Dir))
287                .collect()),
288            Resolved::Nothing => Err(NsError::at(NsErrorKind::NotFound, path)),
289        }
290    }
291
292    /// Read a whole file, at most `max` bytes (`TooLarge` otherwise; nothing is truncated).
293    pub fn read(&self, path: &NsPath, max: u64) -> NsResult<(Vec<u8>, Version)> {
294        match self.resolve(path) {
295            Resolved::Mount { mount, index, rel } => {
296                self.guard_nested(index)?;
297                mount
298                    .backend
299                    .read(&rel, max)
300                    .map_err(|e| e.rebased(&mount.point).or_at(path))
301            }
302            Resolved::Ancestor { .. } => Err(NsError::at(NsErrorKind::IsADirectory, path)),
303            Resolved::Nothing => Err(NsError::at(NsErrorKind::NotFound, path)),
304        }
305    }
306
307    /// The `manifest` verb: kind, size, version and, where the backend has them, owner, mode and link count.
308    pub fn stat(&self, path: &NsPath) -> NsResult<Stat> {
309        match self.resolve(path) {
310            Resolved::Mount { mount, index, rel } => {
311                self.guard_nested(index)?;
312                match mount.backend.stat(&rel) {
313                    Ok(s) => Ok(s),
314                    Err(e)
315                        if e.kind() == NsErrorKind::NotFound
316                            && !self.child_mount_names(path).is_empty() =>
317                    {
318                        Ok(synthetic_stat())
319                    }
320                    Err(e) => Err(e.rebased(&mount.point).or_at(path)),
321                }
322            }
323            Resolved::Ancestor { .. } => Ok(synthetic_stat()),
324            Resolved::Nothing => Err(NsError::at(NsErrorKind::NotFound, path)),
325        }
326    }
327
328    /// Apply a [`WriteOp`]. The grant is checked first (`ReadOnly` is `PermissionDenied`), then the backend's
329    /// capability. `if_version` is exact or best effort according to the backend's [`Caps::exact_if_version`].
330    ///
331    /// A `RenameWithinMount` whose destination is under a different mount is `CrossMount`.
332    pub fn write(
333        &self,
334        path: &NsPath,
335        op: WriteOp,
336        data: &[u8],
337        if_version: Option<&Version>,
338    ) -> NsResult<Version> {
339        let (mount, index, rel) = match self.resolve(path) {
340            Resolved::Mount { mount, index, rel } => (mount, index, rel),
341            Resolved::Ancestor { .. } => {
342                return Err(NsError::at(NsErrorKind::PermissionDenied, path))
343            }
344            Resolved::Nothing => return Err(NsError::at(NsErrorKind::NotFound, path)),
345        };
346        if mount.access == Access::ReadOnly {
347            return Err(NsError::at(NsErrorKind::PermissionDenied, path));
348        }
349        self.guard_nested(index)?;
350        if !mount.backend.caps().writable {
351            return Err(NsError::at(NsErrorKind::Unsupported(Feature::Write), path));
352        }
353        let op = match op {
354            WriteOp::RenameWithinMount { to } => match self.resolve(&to) {
355                Resolved::Mount {
356                    index: to_index,
357                    rel: to_rel,
358                    ..
359                } if to_index == index => WriteOp::RenameWithinMount { to: to_rel },
360                // A different mount: copy, then remove.
361                Resolved::Mount { .. } => return Err(NsError::at(NsErrorKind::CrossMount, path)),
362                // No mount at all (nothing there, or only a synthesised ancestor): there is no destination.
363                Resolved::Ancestor { .. } | Resolved::Nothing => {
364                    return Err(NsError::at(NsErrorKind::NotFound, &to));
365                }
366            },
367            other => other,
368        };
369        mount
370            .backend
371            .write(&rel, op, data, if_version)
372            .map_err(|e| e.rebased(&mount.point).or_at(path))
373    }
374
375    /// Watch a directory. Batches carry namespace paths. The watch sees changes inside the mount that covers `path`; a
376    /// recursive watch does not descend into mounts nested below it. A directory that exists only as a mount ancestor
377    /// cannot be watched (`Unsupported`): watch the mounts.
378    pub fn watch(&self, path: &NsPath, opts: WatchOpts) -> NsResult<Watch> {
379        match self.resolve(path) {
380            Resolved::Mount { mount, index, rel } => {
381                self.guard_nested(index)?;
382                let point = mount.point.clone();
383                let watch = mount
384                    .backend
385                    .watch(&rel, opts)
386                    .map_err(|e| e.rebased(&mount.point).or_at(path))?;
387                Ok(watch.map_paths(move |p| p.rebase(&point).ok()))
388            }
389            Resolved::Ancestor { .. } => Err(NsError::at(
390                NsErrorKind::Unsupported(Feature::WatchOnMountAncestor),
391                path,
392            )),
393            Resolved::Nothing => Err(NsError::at(NsErrorKind::NotFound, path)),
394        }
395    }
396}
397
398/// What `stat` says about a directory that exists only as a name in the mount table.
399fn synthetic_stat() -> Stat {
400    Stat {
401        kind: Kind::Dir,
402        size: 0,
403        version: Version::from_bytes(b"ns:mount-ancestor"),
404        owner: None,
405        mode: None,
406        links: None,
407        modified: None,
408    }
409}