Skip to main content

storage_kit/ns/
error.rs

1//! [`NsError`]: the one error type of the namespace layer.
2//!
3//! **No host path ever appears in an error.** Not in `Display`, not in `Debug`, not in a `source()` chain (there is
4//! none). An error carries a [`NsErrorKind`] and, where it helps, the *namespace* path. The underlying OS error is
5//! reduced to its `std::io::ErrorKind`: the OS error text, and some libraries' errors, can embed the host path, and a
6//! namespace's whole job is that an app never learns where its tree lives on disk.
7
8use std::fmt;
9use std::io;
10
11use super::path::{NsPath, PathReason};
12
13/// Why an argument (not the path) was refused. A closed set of typed reasons, so an error can be carried over a wire
14/// and rebuilt on the far side without free text.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16#[non_exhaustive]
17pub enum InputReason {
18    /// Data was given to an operation that takes none (`Remove`, `MakeDir`, `RenameWithinMount`).
19    UnexpectedData,
20    /// `if_version` was given to an operation that creates (`CreateExclusive`, `MakeDir`): there is nothing to compare.
21    VersionOnCreate,
22    /// The mount root has no parent: it cannot be removed, renamed, or be the destination of a rename.
23    MountRoot,
24    /// A directory cannot be moved into itself.
25    MoveIntoSelf,
26    /// A `ReadOnly` mount nested under a `ReadWrite` one: the parent mount could rename the directory the nested mount
27    /// is meant to protect, and write through the new name. Mount read-only trees outside any writable mount.
28    ReadOnlyUnderReadWrite,
29    /// Two mounts are over the same host directory (their backends report the same root identity). Access is enforced
30    /// per mount, so a write through one would change what the other reads, whatever grants they were given.
31    DuplicateRoot,
32}
33
34impl InputReason {
35    fn describe(self) -> &'static str {
36        match self {
37            InputReason::UnexpectedData => "this operation takes no data",
38            InputReason::VersionOnCreate => "if_version is meaningless for an operation that creates",
39            InputReason::MountRoot => "the mount root has no parent and cannot be the target of this operation",
40            InputReason::MoveIntoSelf => "a directory cannot be moved into itself",
41            InputReason::DuplicateRoot => {
42                "two mounts are over the same host directory (access is per mount, so a write through one changes what the other reads)"
43            }
44            InputReason::ReadOnlyUnderReadWrite => {
45                "a ReadOnly mount cannot be nested under a ReadWrite mount (the parent could move it and write through the new name)"
46            }
47        }
48    }
49}
50
51/// What a backend declared it cannot do. A closed set, like [`InputReason`].
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53#[non_exhaustive]
54pub enum Feature {
55    /// `write` at all (the backend is not [`Caps::writable`](super::Caps::writable)).
56    Write,
57    /// `WriteOp::Replace` (the backend is not [`Caps::atomic_replace`](super::Caps::atomic_replace)).
58    AtomicReplace,
59    /// `watch` (the backend's watch kind is `None`).
60    Watch,
61    /// `watch` on a directory that exists only as a mount ancestor: watch the mounts below it.
62    WatchOnMountAncestor,
63}
64
65impl Feature {
66    fn describe(self) -> &'static str {
67        match self {
68            Feature::Write => "write",
69            Feature::AtomicReplace => "atomic replace",
70            Feature::Watch => "watch",
71            Feature::WatchOnMountAncestor => "watch on a directory that is only a mount ancestor",
72        }
73    }
74}
75
76/// What went wrong, as a value a caller can `match` on.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
78#[non_exhaustive]
79pub enum NsErrorKind {
80    /// The path violates the portable name grammar; the reason says which rule.
81    InvalidPath(PathReason),
82    /// An argument (not the path) is wrong, e.g. data given to an operation that takes none, or `if_version` given to a
83    /// create. The text says which.
84    InvalidInput(InputReason),
85    /// Nothing is at the path.
86    NotFound,
87    /// Something is already at the path (or, for a rename, at the destination).
88    AlreadyExists,
89    /// A directory was needed and a file was found (or a path component is a file).
90    NotADirectory,
91    /// A file was needed and a directory was found.
92    IsADirectory,
93    /// A directory could not be removed because it still has entries.
94    NotEmpty,
95    /// The mount is read-only, the OS refused, or the path is not under a writable mount.
96    PermissionDenied,
97    /// The entry is not a regular file or a directory (a device, FIFO or socket). The namespace never opens one.
98    NotRegular,
99    /// The file has more than one hard link, so writing it could change another name's contents. Refused.
100    HardLinked,
101    /// A symbolic link or reparse point was met. The namespace never follows one; mount the target as its own root if
102    /// it is meant to be reachable.
103    Escapes,
104    /// The name differs only by case from an existing sibling. Refused on every backend: the grammar is portable.
105    CaseCollision,
106    /// A read was larger than the caller's `max`. Nothing is truncated.
107    TooLarge,
108    /// `if_version` did not match the current version: someone else changed the entry. Re-read and retry.
109    VersionMismatch,
110    /// The backend declared this capability false in its [`Caps`](super::Caps).
111    Unsupported(Feature),
112    /// A rename between two mounts. Do a copy then a remove; it cannot be atomic and the Kit does not pretend it is.
113    CrossMount,
114    /// Any other I/O failure, reduced to its kind. The detail is deliberately dropped (see the module docs).
115    Io(io::ErrorKind),
116}
117
118/// An error from a namespace operation. See the [module docs](self) for what it will and will not contain.
119#[derive(Clone, PartialEq, Eq)]
120pub struct NsError {
121    kind: NsErrorKind,
122    path: Option<NsPath>,
123}
124
125impl NsError {
126    /// An error with no path (e.g. one produced while parsing a path).
127    pub fn new(kind: NsErrorKind) -> Self {
128        NsError { kind, path: None }
129    }
130
131    /// An error about `path`, a namespace path.
132    pub fn at(kind: NsErrorKind, path: &NsPath) -> Self {
133        NsError {
134            kind,
135            path: Some(path.clone()),
136        }
137    }
138
139    /// What went wrong.
140    pub fn kind(&self) -> NsErrorKind {
141        self.kind
142    }
143
144    /// The namespace path this is about, if any.
145    pub fn path(&self) -> Option<&NsPath> {
146        self.path.as_ref()
147    }
148
149    /// Attach `path` unless the error already has one.
150    #[must_use]
151    pub fn or_at(mut self, path: &NsPath) -> Self {
152        if self.path.is_none() {
153            self.path = Some(path.clone());
154        }
155        self
156    }
157
158    /// Re-root a mount-relative error path under `mount`, so what leaves the `Namespace` is a namespace path.
159    #[must_use]
160    pub(crate) fn rebased(mut self, mount: &NsPath) -> Self {
161        self.path = self.path.and_then(|p| p.rebase(mount).ok());
162        self
163    }
164
165    /// Reduce a `std::io::Error` to its kind, dropping the message (which can carry a host path).
166    pub(crate) fn from_io(err: &io::Error, path: &NsPath) -> Self {
167        NsError::at(kind_from_io(err), path)
168    }
169
170    /// As [`NsError::from_io`] for a failure that is not about a namespace path (e.g. opening the root).
171    pub(crate) fn from_io_nopath(err: &io::Error) -> Self {
172        NsError::new(kind_from_io(err))
173    }
174}
175
176pub(crate) fn kind_from_io(err: &io::Error) -> NsErrorKind {
177    use io::ErrorKind as K;
178    match err.kind() {
179        K::NotFound => NsErrorKind::NotFound,
180        K::AlreadyExists => NsErrorKind::AlreadyExists,
181        K::PermissionDenied => NsErrorKind::PermissionDenied,
182        K::NotADirectory => NsErrorKind::NotADirectory,
183        K::IsADirectory => NsErrorKind::IsADirectory,
184        K::DirectoryNotEmpty => NsErrorKind::NotEmpty,
185        other => NsErrorKind::Io(other),
186    }
187}
188
189impl fmt::Display for NsErrorKind {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        match self {
192            NsErrorKind::InvalidPath(r) => write!(f, "invalid path: {}", r.describe()),
193            NsErrorKind::InvalidInput(why) => write!(f, "invalid argument: {}", why.describe()),
194            NsErrorKind::NotFound => f.write_str("not found"),
195            NsErrorKind::AlreadyExists => f.write_str("already exists"),
196            NsErrorKind::NotADirectory => f.write_str("not a directory"),
197            NsErrorKind::IsADirectory => f.write_str("is a directory"),
198            NsErrorKind::NotEmpty => f.write_str("directory not empty (remove its entries first)"),
199            NsErrorKind::PermissionDenied => f.write_str("permission denied (read-only mount or no grant)"),
200            NsErrorKind::NotRegular => {
201                f.write_str("not a regular file or directory (a device, FIFO or socket is never opened)")
202            }
203            NsErrorKind::HardLinked => {
204                f.write_str("file has more than one hard link (refused: a write could change another name)")
205            }
206            NsErrorKind::Escapes => f.write_str(
207                "a symbolic link or reparse point was met (never followed; mount its target as its own root instead)",
208            ),
209            NsErrorKind::CaseCollision => {
210                f.write_str("name differs only by case from an existing sibling (pick a distinct name)")
211            }
212            NsErrorKind::TooLarge => f.write_str("larger than the requested maximum (raise `max` or stream elsewhere)"),
213            NsErrorKind::VersionMismatch => {
214                f.write_str("version mismatch: the entry changed since it was read (re-read and retry)")
215            }
216            NsErrorKind::Unsupported(what) => write!(f, "unsupported by this backend: {}", what.describe()),
217            NsErrorKind::CrossMount => {
218                f.write_str("rename across mounts is not atomic and not done (copy, then remove)")
219            }
220            NsErrorKind::Io(k) => write!(f, "I/O error ({k})"),
221        }
222    }
223}
224
225impl fmt::Display for NsError {
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        match &self.path {
228            Some(p) => write!(f, "{}: {}", p, self.kind),
229            None => write!(f, "{}", self.kind),
230        }
231    }
232}
233
234impl fmt::Debug for NsError {
235    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236        f.debug_struct("NsError")
237            .field("kind", &self.kind)
238            .field("path", &self.path)
239            .finish()
240    }
241}
242
243impl std::error::Error for NsError {}
244
245/// Shorthand used across the layer.
246pub type NsResult<T> = Result<T, NsError>;