storage_kit/ns/backend.rs
1//! The [`Backend`] trait and the plain-data types that cross it.
2//!
3//! This is the contract a mount implements. It is **synchronous, path-addressed and stateless**: there is no file handle
4//! anywhere in it, because a handle cannot cross a remote boundary and a stateless call can be replayed, logged and
5//! served. (An async adapter is a later layer over this, not a change to it.)
6//!
7//! It is also deliberately *not* the engine's `backend` module: that one is a block transport under the
8//! content-addressed store. This one is a file tree. The two share no types.
9//!
10//! Every path a `Backend` receives is **relative to its mount** (the mount root is `/`). A backend never sees, and never
11//! returns, the namespace path it is mounted at; the [`Namespace`](super::Namespace) adds and strips that prefix.
12
13use std::fmt;
14use std::time::SystemTime;
15
16use super::error::NsResult;
17use super::path::NsPath;
18use super::watch::{Watch, WatchOpts};
19
20/// An opaque token for "the state this entry was in when you looked".
21///
22/// Returned by every `read`, `stat` and `write`; handed back as `if_version` to say "only if nothing changed".
23///
24/// - **An opaque equality token.** Compare for equality, nothing else: the bytes mean different things per backend and
25/// are not stable across versions of this crate. Do not order, parse or persist one across an upgrade.
26/// - **Valid only against its own mount.** A version taken from one mount means nothing to another: `Memory` makes
27/// every instance's versions distinct, and a `HostDir` version carries the file's device and inode. Offered to the
28/// wrong mount it is a `VersionMismatch`, never a match.
29/// - **A file's version** changes whenever its content is replaced (`HostDir` derives it from mtime in nanoseconds,
30/// size, inode and device; `Memory` from a counter).
31/// - **A directory's version** changes **at least whenever its set of entries changes** (an entry added, removed or
32/// renamed in it). It may change more often (a backend is free to bump it for other reasons), so use it as "something
33/// may have changed, re-list", never as "exactly these entries changed". It does *not* promise to change when an
34/// entry's content changes.
35#[derive(Clone, PartialEq, Eq, Hash)]
36pub struct Version(Box<[u8]>);
37
38impl Version {
39 /// Wrap backend-defined bytes. For backend authors.
40 pub fn from_bytes(bytes: &[u8]) -> Self {
41 Version(bytes.into())
42 }
43
44 /// The raw token, for logging or for carrying over a wire. Not for interpretation.
45 pub fn as_bytes(&self) -> &[u8] {
46 &self.0
47 }
48}
49
50impl fmt::Debug for Version {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 f.write_str("Version(")?;
53 for b in self.0.iter() {
54 write!(f, "{b:02x}")?;
55 }
56 f.write_str(")")
57 }
58}
59
60/// What an entry is. The namespace has exactly two kinds; everything else on a host disk is refused or hidden.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
62pub enum Kind {
63 /// A regular file.
64 File,
65 /// A directory.
66 Dir,
67}
68
69/// One name in a directory listing.
70#[derive(Debug, Clone, PartialEq, Eq)]
71#[non_exhaustive]
72pub struct Entry {
73 /// The component name (inside the portable grammar; never a path).
74 pub name: String,
75 /// File or directory.
76 pub kind: Kind,
77}
78
79impl Entry {
80 /// An entry. For backend authors.
81 pub fn new(name: impl Into<String>, kind: Kind) -> Self {
82 Entry {
83 name: name.into(),
84 kind,
85 }
86 }
87}
88
89/// The `manifest` verb: what is known about one entry.
90///
91/// `owner`, `mode` and `links` are `Some` only where the backend has them (see [`Caps::owner_mode`]); the caller's
92/// policy decides what to do with them. The Kit reports, it does not judge: whether "owned by you and not writable by
93/// group or others" is acceptable is the embedder's rule.
94#[derive(Debug, Clone, PartialEq, Eq)]
95#[non_exhaustive]
96pub struct Stat {
97 /// File or directory.
98 pub kind: Kind,
99 /// Size in bytes for a file; always 0 for a directory (a directory's size is not portable).
100 pub size: u64,
101 /// The current version of the entry.
102 pub version: Version,
103 /// Owning user id, where the backend has one (Unix `HostDir`).
104 pub owner: Option<u32>,
105 /// Permission bits (`0o7777` mask), where the backend has them.
106 pub mode: Option<u32>,
107 /// Hard-link count, where the backend can tell.
108 pub links: Option<u64>,
109 /// Last modification time, where known.
110 pub modified: Option<SystemTime>,
111}
112
113/// An argument of the namespace verb `write`: **not new verbs**. The set is closed per release (`non_exhaustive`).
114///
115/// `append` and `at_offset` are **reserved and not implemented**: partial writes need a position model that survives a
116/// remote hop and a `Cas` commit, and that is not settled. Do not simulate them with read-modify-write.
117///
118/// Except where noted, every op takes its data from the `data` argument of [`Backend::write`] (empty for ops that take
119/// none; non-empty data on those is `InvalidInput`).
120#[derive(Debug, Clone, PartialEq, Eq)]
121#[non_exhaustive]
122pub enum WriteOp {
123 /// Create a file with `data`; fail with `AlreadyExists` if the name is taken. Not atomic as to *content*: a
124 /// concurrent reader can see a partial file. Use `Replace` if readers must never see one.
125 CreateExclusive,
126 /// Make the file's content exactly `data`, creating it if absent. **Atomic** where [`Caps::atomic_replace`]: a
127 /// temporary file in the same directory, `fsync` of the file, `rename` over the target, `fsync` of the directory, so
128 /// a reader sees the old content or the new content and a crash leaves one of them. Always yields a new file
129 /// (mode `0600` on Unix), so it also resets permission bits. Refused on a directory (`IsADirectory`).
130 Replace,
131 /// Remove a file or an **empty** directory. Returns the version the entry had.
132 Remove,
133 /// Rename within this mount. The destination must not exist (`AlreadyExists`) and its name must not case-collide
134 /// with a sibling. Across mounts the namespace returns `CrossMount`.
135 RenameWithinMount {
136 /// The destination, relative to the same mount as the source.
137 to: NsPath,
138 },
139 /// Create one directory (not its parents: that would be `NotFound`). Mode `0700` on Unix.
140 MakeDir,
141}
142
143/// What a watch is built from. Typed, so a caller can branch on it without parsing a string.
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
145#[non_exhaustive]
146pub enum WatchKind {
147 /// Events come from the platform or are delivered synchronously (immediate).
148 Native,
149 /// The backend re-scans on an interval. Changes are reported on the poll that sees them, never sooner.
150 Polling,
151 /// The only signal is that the whole root changed (a content-addressed mount's root hash).
152 RootChanged,
153 /// Not supported; `watch` returns `Unsupported`.
154 None,
155}
156
157/// What a mount can and cannot do, and where it is weaker than it looks. A typed struct, not strings.
158///
159/// A capability that is `false` (or [`WatchKind::None`]) means the operation returns
160/// [`NsErrorKind::Unsupported`](super::NsErrorKind::Unsupported), and the conformance suite checks that it does.
161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
162#[non_exhaustive]
163pub struct Caps {
164 /// `write` is available at all.
165 pub writable: bool,
166 /// `WriteOp::Replace` is atomic (temp file plus rename, or a commit).
167 pub atomic_replace: bool,
168 /// `if_version` is **exact** (compare-and-swap). `false` means best effort: check, then act, with a window between.
169 /// Either way a stale version is detected when the change happened before the check.
170 pub exact_if_version: bool,
171 /// How `watch` is implemented.
172 pub watch: WatchKind,
173 /// `Stat::owner` and `Stat::mode` are populated.
174 pub owner_mode: bool,
175 /// Two names differing only by case can address two entries on this backend. Informational: the portable grammar
176 /// refuses to *create* a case-colliding sibling on every backend regardless.
177 pub case_sensitive: bool,
178 /// Confinement is as strict as the Kit claims everywhere: no symlink or reparse point followed, no hard-link alias
179 /// written, identity checks on handles. `false` means a known weaker platform (Windows `HostDir`), so the embedder
180 /// must not rely on the strong guarantee; the docs of the backend list what is missing.
181 pub strict_confinement: bool,
182}
183
184impl Caps {
185 /// Every capability off. A starting point for a backend author: set what you provide.
186 pub const fn none() -> Self {
187 Caps {
188 writable: false,
189 atomic_replace: false,
190 exact_if_version: false,
191 watch: WatchKind::None,
192 owner_mode: false,
193 case_sensitive: false,
194 strict_confinement: false,
195 }
196 }
197}
198
199/// A mount's grant, enforced by the [`Namespace`](super::Namespace) on top of the backend's own [`Caps::writable`].
200///
201/// **The grant belongs to the mount, not to the data behind it.** `ReadOnly` means "nothing written *through this mount*
202/// changes anything"; it does not make the host directory read-only. If the embedder also mounts the same directory, or
203/// one inside it, read-write somewhere else, or another process writes it, what this mount reads changes. The Kit
204/// enforces the grant per mount and the embedder chooses the host directories, so choose them to be disjoint. The one
205/// overlap the Kit can see, the *same* directory mounted twice, is refused at `build()`
206/// (`InvalidInput(DuplicateRoot)`); a directory mounted together with one of its ancestors or descendants is not
207/// detected, because the Kit holds no host paths by design (see [`Backend::root_identity`]).
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
209#[non_exhaustive]
210pub enum Access {
211 /// Reads and watches only; every write is `PermissionDenied`.
212 ReadOnly,
213 /// Reads, watches and writes.
214 ReadWrite,
215}
216
217/// A mount: a file tree behind one root, addressed by path.
218///
219/// Implementations must enforce the portable name grammar (it comes for free from [`NsPath`], and any name read back
220/// from the backing store goes through [`validate_name`](super::validate_name)), must refuse to create a name that
221/// case-folds to an existing sibling (`CaseCollision`), and must return `Unsupported` for anything their [`Caps`] say
222/// they cannot do. The [`conformance`](super::conformance) suite checks all of it.
223///
224/// **This trait is not frozen** (see the [module docs](super)). New methods arrive with a default body, so an existing
225/// implementation keeps compiling and behaves as if the new capability were absent; [`Backend::root_identity`] was added
226/// that way. A method without a default would be a breaking change and a minor bump while pre-1.0.
227pub trait Backend: Send + Sync {
228 /// What this mount can do. Cheap; may be called often.
229 fn caps(&self) -> Caps;
230
231 /// Which host directory this mount is rooted at, as `(device, inode)` (Windows: volume serial number and file
232 /// index), or `None` if the backend is not over a host directory or cannot tell. **Default `None`.**
233 ///
234 /// [`NamespaceBuilder::build`](super::NamespaceBuilder::build) uses it for one check: two mounts that report the
235 /// same identity are refused (`InvalidInput(DuplicateRoot)`), because access is enforced per mount and two mounts of
236 /// one directory would let a write through one change what the other, perhaps read-only, mount reads.
237 ///
238 /// What this does **not** detect: a directory mounted together with an ancestor or a descendant of it (it needs
239 /// host paths, which the Kit does not keep), two mounts of a backend that returns `None`, or an identity that
240 /// differs because the same directory was reached through two different hard-linked or bind-mounted views. Only a
241 /// backend over a real host directory should return `Some`; its value must not change for the life of the backend.
242 fn root_identity(&self) -> Option<(u64, u64)> {
243 None
244 }
245
246 /// List a directory, **sorted by name in UTF-8 byte order** (so `B` sorts before `a`, and `z` before `é`), the whole
247 /// directory at once. Only entries that are addressable are listed: names outside the grammar, temporary files, and
248 /// anything that is neither a regular file nor a directory are omitted.
249 ///
250 /// The order is part of the contract (a caller may merge two listings, or page through one by name). Paging of `walk`
251 /// itself (a cursor, a page size) is **deferred** until a read-only content-addressed mount has exercised the trait;
252 /// it will be added as a separate, additive call.
253 fn walk(&self, path: &NsPath) -> NsResult<Vec<Entry>>;
254
255 /// Read a whole file. If it is larger than `max` bytes the result is `TooLarge` and nothing is returned; the
256 /// backend reads at most `max + 1` bytes to find that out.
257 fn read(&self, path: &NsPath, max: u64) -> NsResult<(Vec<u8>, Version)>;
258
259 /// The `manifest` verb. Works on files and directories (and on `/`).
260 fn stat(&self, path: &NsPath) -> NsResult<Stat>;
261
262 /// Apply one [`WriteOp`]. `if_version`: if `Some`, the target must exist (`NotFound` otherwise) and its current
263 /// version must equal it (`VersionMismatch` otherwise); it is meaningless for `CreateExclusive` and `MakeDir`
264 /// (`InvalidInput`). Exact where [`Caps::exact_if_version`], otherwise check-then-act.
265 ///
266 /// Returns the version of the entry after the op (for `Remove`, the version it had).
267 fn write(
268 &self,
269 path: &NsPath,
270 op: WriteOp,
271 data: &[u8],
272 if_version: Option<&Version>,
273 ) -> NsResult<Version>;
274
275 /// Watch a **directory**. A file is `NotADirectory`. See [`Watch`].
276 fn watch(&self, path: &NsPath, opts: WatchOpts) -> NsResult<Watch>;
277}