Skip to main content

hyprstream_vfs/
fsmount.rs

1//! `FsMount` — the writable / overlay filesystem supertrait.
2//!
3//! The base [`Mount`] trait (see `mount.rs`) is deliberately 9P-shaped and
4//! read/write-only: it can `walk`/`open`/`read`/`write`/`readdir`/`stat`/`clunk`
5//! a fid, and the only mutating semantics it carries are the open-mode bits
6//! `OTRUNC` (truncate-on-open) and `ORCLOSE` (remove-on-clunk). That surface is
7//! exactly right for synthetic, control, and stream mounts (`SyntheticTree`,
8//! `EnvMount`, ctl files, `/stream`, …) and we keep it untouched.
9//!
10//! A *full* filesystem — a sandbox rootfs, a writable overlay, a passthrough of
11//! a host directory — needs the rest of the POSIX namespace-mutation surface:
12//! create files, unlink/rmdir, mkdir, rename, change attributes, symlinks and
13//! hard links, plus the overlay-specific whiteout / opaque-dir primitives that
14//! make copy-on-write layering observable. Rather than bloat `Mount` (and force
15//! every existing read/write mount to grow `NotSupported` stubs), `FsMount` is a
16//! **supertrait** that *extends* `Mount`. This is the hyprstream-owned overlay
17//! interface: consumers code against `FsMount`, the v1 backend wraps
18//! `fuse_backend_rs::OverlayFs` (see `overlay.rs`), and a future native
19//! copy-on-write engine (backlog #370) can implement the very same trait with
20//! zero consumer churn.
21//!
22//! ## Why a supertrait, not a `Mount` change
23//!
24//! - **Blast radius.** `SyntheticTree`, `EnvMount`, and friends stay on `Mount`
25//!   verbatim. Only full-filesystem mounts (rootfs, overlay) opt in to
26//!   `FsMount`. No existing impl needs to change.
27//! - **Liskov.** Every `FsMount` *is* a `Mount`, so an `Arc<dyn FsMount>` can be
28//!   coerced to the `Arc<dyn Mount>` a [`Namespace`](crate::Namespace) stores.
29//!   The richer ops are reached by code that holds the concrete `FsMount`.
30//! - **Capability typing.** "Is this mount writable as a real filesystem?" is
31//!   answered by the type (`dyn FsMount`) rather than by probing for runtime
32//!   `NotSupported` errors.
33//!
34//! ## Op semantics
35//!
36//! All ops are **path-addressed** (relative to the mount root, like
37//! [`Mount::walk`]) and take the verified [`Subject`] of the caller for
38//! per-tenant policy enforcement and fid isolation — the uniform
39//! Subject-per-call boundary (#353/#319/#328) extended over the rootfs. Paths
40//! are component slices, never raw strings, so a backend never has to re-parse
41//! `/`-joined input. Mutating ops are **fail-closed**: a backend that cannot
42//! satisfy an op safely must return an error, never silently succeed.
43
44use async_trait::async_trait;
45use hyprstream_rpc::Subject;
46
47use crate::mount::{Mount, MountError, Stat};
48
49// ─────────────────────────────────────────────────────────────────────────────
50// Attribute change descriptor
51// ─────────────────────────────────────────────────────────────────────────────
52
53/// Attribute changes for [`FsMount::setattr`].
54///
55/// Each `Option` is "leave unchanged" when `None`. This mirrors the
56/// `SetattrValid` bitmask used by FUSE/9P2000.L: only the populated fields are
57/// applied, atomically where the backend supports it. Maps to chmod (`mode`),
58/// chown (`uid`/`gid`), truncate (`size`), and utimes (`atime`/`mtime`).
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
60pub struct SetAttr {
61    /// New permission bits (chmod). Lower 12 bits are the POSIX mode.
62    pub mode: Option<u32>,
63    /// New owner uid (chown).
64    pub uid: Option<u32>,
65    /// New owner gid (chown).
66    pub gid: Option<u32>,
67    /// New file length (truncate / extend).
68    pub size: Option<u64>,
69    /// New access time, seconds since the Unix epoch.
70    pub atime: Option<u64>,
71    /// New modification time, seconds since the Unix epoch.
72    pub mtime: Option<u64>,
73}
74
75impl SetAttr {
76    /// True when no field is set — the op would be a no-op.
77    pub fn is_empty(&self) -> bool {
78        self.mode.is_none()
79            && self.uid.is_none()
80            && self.gid.is_none()
81            && self.size.is_none()
82            && self.atime.is_none()
83            && self.mtime.is_none()
84    }
85}
86
87// ─────────────────────────────────────────────────────────────────────────────
88// FsMount supertrait
89// ─────────────────────────────────────────────────────────────────────────────
90
91/// A full, writable filesystem mount — the hyprstream overlay interface.
92///
93/// Extends [`Mount`] (walk/open/read/write/readdir/stat/clunk) with the
94/// namespace-mutation surface a writable or overlay filesystem needs:
95/// `create`, `unlink`/`rmdir`/`mkdir`, `rename`, `setattr`, `symlink`/`readlink`,
96/// `link`, and the overlay whiteout / opaque-dir hooks.
97///
98/// The v1 backend ([`crate::overlay`]) wraps `fuse_backend_rs::OverlayFs`, which
99/// implements copy-up and whiteouts internally — so an `FsMount` impl that
100/// delegates to it does **not** hand-roll copy-on-write. A future native CoW
101/// engine (backlog #370) implements this same trait directly.
102#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
103#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
104pub trait FsMount: Mount {
105    /// Create (and leave on disk) a regular file at `path` with `mode`.
106    ///
107    /// Fails with [`MountError::AlreadyExists`] if the final component exists.
108    /// On an overlay this triggers copy-up of the parent directory as needed and
109    /// places the new file in the writable upper layer.
110    async fn create(&self, path: &[&str], mode: u32, caller: &Subject) -> Result<(), MountError>;
111
112    /// Remove a non-directory entry (file, symlink, fifo, …) at `path`.
113    ///
114    /// On an overlay, removing an entry that exists only in a lower (read-only)
115    /// layer is realised as a **whiteout** in the upper layer — the lower entry
116    /// is masked, never mutated.
117    async fn unlink(&self, path: &[&str], caller: &Subject) -> Result<(), MountError>;
118
119    /// Create a directory at `path` with `mode`.
120    async fn mkdir(&self, path: &[&str], mode: u32, caller: &Subject) -> Result<(), MountError>;
121
122    /// Remove an empty directory at `path`.
123    ///
124    /// Fails with [`MountError::NotDirectory`] if `path` is not a directory and
125    /// (per POSIX) an error if it is non-empty. Overlay whiteout rules apply as
126    /// for [`unlink`](Self::unlink).
127    async fn rmdir(&self, path: &[&str], caller: &Subject) -> Result<(), MountError>;
128
129    /// Rename `from` to `to`, atomically replacing `to` if it exists.
130    ///
131    /// `from` and `to` are both rooted at the mount root and may live in
132    /// different directories. Across overlay layers this implies copy-up of the
133    /// source plus a whiteout at the old location, all handled by the backend.
134    async fn rename(&self, from: &[&str], to: &[&str], caller: &Subject) -> Result<(), MountError>;
135
136    /// Change file attributes (chmod / chown / truncate / utimes).
137    ///
138    /// Only the populated fields of [`SetAttr`] are applied. A `size` change on
139    /// a lower-layer file forces copy-up.
140    async fn setattr(
141        &self,
142        path: &[&str],
143        attr: &SetAttr,
144        caller: &Subject,
145    ) -> Result<(), MountError>;
146
147    /// Create a symbolic link at `path` whose target is `target`.
148    ///
149    /// `target` is stored verbatim (it may be absolute or relative and is *not*
150    /// resolved by this call).
151    async fn symlink(
152        &self,
153        path: &[&str],
154        target: &str,
155        caller: &Subject,
156    ) -> Result<(), MountError>;
157
158    /// Read the target of the symbolic link at `path`.
159    async fn readlink(&self, path: &[&str], caller: &Subject) -> Result<String, MountError>;
160
161    /// Create a hard link at `new_path` referring to the same inode as
162    /// `existing`.
163    async fn link(
164        &self,
165        existing: &[&str],
166        new_path: &[&str],
167        caller: &Subject,
168    ) -> Result<(), MountError>;
169
170    // ── Overlay / copy-on-write hooks ───────────────────────────────────────
171    //
172    // Default implementations let non-overlay full filesystems (e.g. a plain
173    // passthrough) ignore overlay semantics. The OverlayFs-backed v1 backend
174    // applies real whiteouts/opaque-dirs internally; these hooks expose that
175    // state to callers (e.g. FS-A's down-adapter) and let a native CoW engine
176    // implement them explicitly.
177
178    /// Report whether `path` resolves to a whiteout — an upper-layer marker that
179    /// masks an entry present in a lower layer. Default: `false` (no overlay).
180    async fn is_whiteout(&self, _path: &[&str], _caller: &Subject) -> Result<bool, MountError> {
181        Ok(false)
182    }
183
184    /// Report whether the directory at `path` is *opaque* — i.e. it hides the
185    /// contents of the same directory in all lower layers. Default: `false`.
186    async fn is_opaque(&self, _path: &[&str], _caller: &Subject) -> Result<bool, MountError> {
187        Ok(false)
188    }
189
190    /// Mark the directory at `path` opaque, hiding lower-layer contents.
191    ///
192    /// Default: [`MountError::NotSupported`] — a backend with no layering cannot
193    /// honour opacity and must say so rather than silently no-op (fail-closed).
194    async fn set_opaque(&self, _path: &[&str], _caller: &Subject) -> Result<(), MountError> {
195        Err(MountError::NotSupported(
196            "set_opaque: backend is not an overlay".into(),
197        ))
198    }
199
200    /// Stat a `path` directly (without holding a fid), returning its metadata.
201    ///
202    /// Convenience over `walk` + `stat` + `clunk` for the mutating ops above,
203    /// which routinely need to probe existence/type. Backends should implement
204    /// it in terms of their own fid machinery.
205    async fn stat_path(&self, path: &[&str], caller: &Subject) -> Result<Stat, MountError>;
206}