Skip to main content

hyprstream_vfs/
mount.rs

1//! Mount trait — in-process 9P operations without network transport.
2
3use async_trait::async_trait;
4use hyprstream_rpc::Subject;
5
6// ─────────────────────────────────────────────────────────────────────────────
7// Open mode constants (9P2000)
8// ─────────────────────────────────────────────────────────────────────────────
9
10/// Open for reading
11pub const OREAD: u8 = 0;
12/// Open for writing
13pub const OWRITE: u8 = 1;
14/// Open for read+write
15pub const ORDWR: u8 = 2;
16/// Truncate on open (OR'd with above)
17pub const OTRUNC: u8 = 0x10;
18/// Remove on clunk (OR'd with above)
19pub const ORCLOSE: u8 = 0x40;
20
21/// Plan 9 `DMDIR` permission bit. OR'd into `perm` for `create` to make a directory.
22///
23/// Matches the kernel/lib9 value (`0x80000000`) and the registry service's
24/// `DMDIR` constant in `services/types.rs`.
25pub const DMDIR: u32 = 0x8000_0000;
26
27// ─────────────────────────────────────────────────────────────────────────────
28// Error type
29// ─────────────────────────────────────────────────────────────────────────────
30
31/// Mount-level error.
32#[derive(Debug)]
33pub enum MountError {
34    NotFound(String),
35    PermissionDenied(String),
36    NotDirectory(String),
37    IsDirectory(String),
38    InvalidArgument(String),
39    NotSupported(String),
40    AlreadyExists(String),
41    Io(String),
42}
43
44impl std::fmt::Display for MountError {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        match self {
47            Self::NotFound(s) => write!(f, "not found: {s}"),
48            Self::PermissionDenied(s) => write!(f, "permission denied: {s}"),
49            Self::NotDirectory(s) => write!(f, "not a directory: {s}"),
50            Self::IsDirectory(s) => write!(f, "is a directory: {s}"),
51            Self::InvalidArgument(s) => write!(f, "invalid argument: {s}"),
52            Self::NotSupported(s) => write!(f, "not supported: {s}"),
53            Self::AlreadyExists(s) => write!(f, "already exists: {s}"),
54            Self::Io(s) => write!(f, "I/O error: {s}"),
55        }
56    }
57}
58
59impl std::error::Error for MountError {}
60
61// ─────────────────────────────────────────────────────────────────────────────
62// Fid
63// ─────────────────────────────────────────────────────────────────────────────
64
65/// Opaque fid handle from a mount.
66pub struct Fid(Box<dyn std::any::Any + Send + Sync>);
67
68impl std::fmt::Debug for Fid {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        f.debug_tuple("Fid").finish_non_exhaustive()
71    }
72}
73
74impl Fid {
75    /// Create a new Fid wrapping an arbitrary Send+Sync value.
76    pub fn new<T: std::any::Any + Send + Sync>(val: T) -> Self {
77        Self(Box::new(val))
78    }
79
80    /// Downcast to a concrete type (immutable).
81    pub fn downcast_ref<T: std::any::Any>(&self) -> Option<&T> {
82        self.0.downcast_ref()
83    }
84
85    /// Downcast to a concrete type (mutable).
86    pub fn downcast_mut<T: std::any::Any>(&mut self) -> Option<&mut T> {
87        self.0.downcast_mut()
88    }
89
90    /// Downcast to a concrete type, consuming the fid. Returns the original fid
91    /// in the `Err` variant if the inner type differs, so the caller can fall
92    /// back (e.g. a no-op clunk). Used by `Mount::clunk` implementations that
93    /// need the owned typed state to release resources (e.g. the CAS staging
94    /// fid refcount, #814).
95    pub fn downcast_into<T: std::any::Any>(self) -> Result<T, Fid> {
96        match self.0.downcast::<T>() {
97            Ok(boxed) => Ok(*boxed),
98            Err(boxed) => Err(Fid(boxed)),
99        }
100    }
101}
102
103// ─────────────────────────────────────────────────────────────────────────────
104// DirEntry & Stat
105// ─────────────────────────────────────────────────────────────────────────────
106
107/// Directory entry.
108#[derive(Clone, Debug)]
109pub struct DirEntry {
110    pub name: String,
111    pub is_dir: bool,
112    pub size: u64,
113    pub stat: Option<Stat>,
114}
115
116/// File metadata.
117///
118/// # Qid soundness invariant — SECURITY
119///
120/// In 9P, a file's `qid` is its *identity*: two files are the same file if
121/// and only if their qids are equal. A qid is the triple `{qtype, version,
122/// path}`. Historically this struct carried only `qtype`, flattening the qid
123/// and destroying the identity signal — every file looked like the same file
124/// to any qid-keyed consumer.
125///
126/// `version` and `path` are now threaded end-to-end so the surface is sound,
127/// but the *values* are not yet a strong identity:
128///   - Synthetic mounts set `version = 1` constant and `path = fnv64(path)`,
129///     which is non-cryptographic and changes on rename.
130///   - Registry-backed mounts set `path = inode` (rename-stable but subject to
131///     inode reuse) and `version = ctime` (truncated).
132///
133/// **Convention:** `path == 0` means "unknown / not provided" (e.g. non-Unix
134/// registry fallback, or a mount that has no meaningful file identity). It is
135/// NOT a valid identity and must not be treated as one.
136///
137/// **No server authz, cache key, or dedup logic may key on `qid` (version or
138/// path) as a sound identity until #387 lands a content-CID-derived qid with
139/// an AFS-style data-version uniquifier.** Treat the qid fields here as an
140/// advisory identity *hint* only. Authz must continue to key on the verified
141/// `Subject` plus path resolution, never on qid.
142#[derive(Clone, Debug)]
143pub struct Stat {
144    pub qtype: u8,
145    /// Qid version (data-version). Advisory hint only — see type-level invariant.
146    pub version: u32,
147    /// Qid path (file identity). `0` means unknown. Advisory hint only — see type-level invariant.
148    pub path: u64,
149    pub size: u64,
150    pub name: String,
151    pub mtime: u64,
152}
153
154impl Stat {
155    /// Construct a `Stat` with `version = 0, path = 0` (qid unknown).
156    ///
157    /// Use this for mounts that have no meaningful file identity (e.g. purely
158    /// synthetic test mounts). The result carries qtype/size/name/mtime and
159    /// signals via `path == 0` that the qid is not a usable identity.
160    pub fn unknown_qid(qtype: u8, size: u64, name: String, mtime: u64) -> Self {
161        Self {
162            qtype,
163            version: 0,
164            path: 0,
165            size,
166            name,
167            mtime,
168        }
169    }
170}
171
172// ─────────────────────────────────────────────────────────────────────────────
173// Mount trait
174// ─────────────────────────────────────────────────────────────────────────────
175
176/// In-process mount backend. Implements 9P semantics without ZMQ/IPC.
177///
178/// Used for `/config/`, `/private/`, `/bin/`, `/env/`, and any other
179/// client-local namespace entries. Every method receives the verified
180/// `Subject` of the caller for per-tenant fid isolation and policy checks.
181#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
182#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
183#[cfg_attr(target_arch = "wasm32", allow(clippy::non_send_fields_in_send_ty))]
184pub trait Mount: Send + Sync {
185    /// Walk path components, returning an opaque fid.
186    async fn walk(&self, components: &[&str], caller: &Subject) -> Result<Fid, MountError>;
187
188    /// Open a walked fid for I/O. `mode`: OREAD=0, OWRITE=1, ORDWR=2.
189    async fn open(&self, fid: &mut Fid, mode: u8, caller: &Subject) -> Result<(), MountError>;
190
191    /// Create a new file or directory under a walked *directory* fid (9P `Tcreate`).
192    ///
193    /// On success, `fid` is replaced by an opened fid on the new file (the
194    /// directory fid is consumed, exactly as in 9P). `perm` carries the Unix
195    /// mode bits; OR in [`DMDIR`] to create a directory. `mode` is the open
196    /// mode for the newly created file (the new fid is opened writable).
197    ///
198    /// # Default
199    ///
200    /// Returns [`MountError::NotSupported`]. Read-only / synthetic mounts
201    /// (the common case) inherit this default and remain writable-mount-free.
202    /// Only the registry worktree mount (the writable upper layer of the union)
203    /// overrides it — see `RemoteRegistryMount::create`.
204    ///
205    /// # Copy-up
206    ///
207    /// The union namespace performs copy-up *before* reaching here: a write to
208    /// a path that exists only in a read-only lower layer is redirected to the
209    /// writable upper layer, which may `create` the file first. See
210    /// `Namespace::echo` / `Namespace::create`.
211    async fn create(
212        &self,
213        _fid: &mut Fid,
214        _name: &str,
215        _perm: u32,
216        _mode: u8,
217        _caller: &Subject,
218    ) -> Result<Stat, MountError> {
219        Err(MountError::NotSupported(
220            "create is not supported on this mount".into(),
221        ))
222    }
223
224    /// Read bytes from an open fid at offset.
225    async fn read(
226        &self,
227        fid: &Fid,
228        offset: u64,
229        count: u32,
230        caller: &Subject,
231    ) -> Result<Vec<u8>, MountError>;
232
233    /// Write bytes to an open fid at offset. Returns bytes written.
234    async fn write(
235        &self,
236        fid: &Fid,
237        offset: u64,
238        data: &[u8],
239        caller: &Subject,
240    ) -> Result<u32, MountError>;
241
242    /// Read directory entries from an open directory fid.
243    async fn readdir(&self, fid: &Fid, caller: &Subject) -> Result<Vec<DirEntry>, MountError>;
244
245    /// Get file metadata.
246    async fn stat(&self, fid: &Fid, caller: &Subject) -> Result<Stat, MountError>;
247
248    /// Release a fid.
249    async fn clunk(&self, fid: Fid, caller: &Subject);
250
251    /// Capability downcast: report whether this mount is also a writable
252    /// [`FsMount`](crate::FsMount), returning a borrow if so.
253    ///
254    /// The base [`Mount`] surface is read/write-on-existing-files only; full
255    /// namespace mutation (`create`/`unlink`/`mkdir`/`rename`/…) lives on the
256    /// `FsMount` supertrait. A [`Namespace`](crate::Namespace) stores every mount
257    /// as `Arc<dyn Mount>`, erasing the richer type, so a consumer that holds
258    /// only a `dyn Mount` (e.g. FS-A's `Namespace → FileSystem` down-adapter)
259    /// needs a way back to the `FsMount` vtable to route writes. This hook is the
260    /// idiomatic capability-typed answer to "is this mount writable as a real
261    /// filesystem?" — preferable to probing for `NotSupported` at runtime.
262    ///
263    /// Default: `None` (a plain `Mount` is not a full filesystem). `FsMount`
264    /// impls override this to return `Some(self)`; the blanket impl in
265    /// `fsmount.rs` is *not* possible (it would require `Self: Sized`), so each
266    /// `FsMount` opts in with a one-line override.
267    fn as_fsmount(&self) -> Option<&dyn crate::fsmount::FsMount> {
268        None
269    }
270}