hyprstream_core/services/ninep_bridge.rs
1//! Shared sync→async bridge for 9P-style `Mount` implementations that proxy
2//! to a Cap'n Proto RPC service (`nine.capnp` envelope).
3//!
4//! Both `RemoteModelMount` (1-level scope: first path component = model ref)
5//! and `RemoteRegistryMount` (2-level scope: repo → worktree, with async UUID
6//! resolution) translate synchronous VFS `Mount` trait calls into async RPC
7//! requests by embedding a dedicated single-threaded tokio runtime and
8//! `block_on`-ing each op. The runtime, the local-fid allocator, the
9//! `DashMap<u32, S>` that tracks remote fid state, the `anyhow → MountError`
10//! mapping, the opaque `RemoteFidKey` newtype stored in `Fid`, and the packed
11//! 9P stat parser used for directory reads are identical across the two
12//! mounts — only the RPC client type, the scope extraction, and which RPC
13//! method names / directory byte format differ.
14//!
15//! This module factors out the shared pieces:
16//!
17//! - [`NinePBridge`]`<S>` — owns the runtime + fid map + fid allocator. Each
18//! mount holds one of these and supplies its own fid-state type `S`.
19//! - [`map_err`] — `anyhow::Error → MountError` classification.
20//! - [`RemoteFidKey`] — the opaque newtype stored inside `hyprstream_vfs::Fid`.
21//! - [`parse_dir_stats`] — decode packed 9P stat entries from a directory
22//! `read()` response (the format the model service's `SyntheticTree` emits).
23//!
24//! What stays mount-specific:
25//!
26//! - the top-level `Mount` impl (walk's scope extraction differs: 1-level vs
27//! 2-level with async `get_by_name` resolution),
28//! - the request-struct construction (each generated client module has its
29//! own `NpWalk`/`NpOpen`/... types),
30//! - the stat RPC method name (`stat` on `ModelFsClient`, `np_stat` on
31//! `WorktreeClient`),
32//! - the directory-entry byte format (packed 9P stats for the model service
33//! vs `name_len+name+is_dir+size` for the registry worktree service).
34
35use std::sync::atomic::{AtomicU32, Ordering};
36
37use dashmap::DashMap;
38use hyprstream_vfs::{DirEntry, Fid, MountError, Stat};
39
40use crate::services::types::QTDIR;
41
42// ─────────────────────────────────────────────────────────────────────────────
43// Opaque fid key
44// ─────────────────────────────────────────────────────────────────────────────
45
46/// Newtype stored inside the opaque `hyprstream_vfs::Fid`.
47///
48/// Wraps the locally-allocated fid number so that subsequent `open`/`read`/
49/// `write`/`readdir`/`stat`/`clunk` calls can look the remote fid state back
50/// up in the bridge's `DashMap`.
51#[derive(Clone, Debug)]
52pub struct RemoteFidKey(pub u32);
53
54// ─────────────────────────────────────────────────────────────────────────────
55// Bridge: runtime + fid map + allocator
56// ─────────────────────────────────────────────────────────────────────────────
57
58/// Shared sync→async bridge plumbing for a 9P `Mount` proxying to a Cap'n
59/// Proto RPC service.
60///
61/// Owns:
62/// - a dedicated single-threaded tokio runtime (`rt`) used to `block_on` each
63/// async RPC op from the sync `Mount` trait,
64/// - a `DashMap<u32, S>` mapping locally-allocated fid numbers to per-fid
65/// state `S` (the mount chooses what to store — typically the remote fid
66/// number, the scoped RPC client, the walk-response qtype, and an
67/// `opened` flag),
68/// - a monotonic fid allocator (`next_fid`).
69///
70/// Each op in a `Mount` impl follows the same shape:
71///
72/// ```ignore
73/// let local_id = fid_key(fid)?.0;
74/// let state = bridge.get(local_id)?; // or get_mut for open
75/// // ...build request, bridge.rt().block_on(client.op(&req)).map_err(map_err)?...
76/// ```
77///
78/// `fid_key` and `map_err` are module-level free functions (not methods on
79/// the generic `NinePBridge<S>`) so call sites don't need to spell out the
80/// fid-state type parameter `S`.
81pub struct NinePBridge<S> {
82 rt: tokio::runtime::Runtime,
83 fids: DashMap<u32, S>,
84 next_fid: AtomicU32,
85}
86
87impl<S> NinePBridge<S> {
88 /// Construct a new bridge with a fresh single-threaded runtime and an
89 /// empty fid map starting at fid 1 (fid 0 is reserved for the 9P root).
90 #[allow(clippy::expect_used)] // Runtime creation is infallible in practice
91 pub fn new(label: &str) -> Self {
92 let rt = tokio::runtime::Builder::new_current_thread()
93 .enable_all()
94 .build()
95 .unwrap_or_else(|e| panic!("failed to create tokio runtime for {label}: {e}"));
96 Self {
97 rt,
98 fids: DashMap::new(),
99 next_fid: AtomicU32::new(1),
100 }
101 }
102
103 /// Allocate a new local fid number (monotonic, starts at 1).
104 pub fn alloc_fid(&self) -> u32 {
105 self.next_fid.fetch_add(1, Ordering::Relaxed)
106 }
107
108 /// Borrow the embedded runtime — used to `block_on` async RPC ops from
109 /// the sync `Mount` trait.
110 pub fn rt(&self) -> &tokio::runtime::Runtime {
111 &self.rt
112 }
113
114 /// Insert fid state for a locally-allocated fid (called from `walk`).
115 pub fn insert(&self, local_fid: u32, state: S) {
116 self.fids.insert(local_fid, state);
117 }
118
119 /// Look up a shared reference to fid state.
120 ///
121 /// Convenience over `fids.get` that yields a `MountError::NotFound` for
122 /// a stale/unknown local fid.
123 pub fn get(&self, local_fid: u32) -> Result<dashmap::mapref::one::Ref<'_, u32, S>, MountError> {
124 self.fids
125 .get(&local_fid)
126 .ok_or_else(|| MountError::NotFound(format!("fid {} not found", local_fid)))
127 }
128
129 /// Look up a mutable reference to fid state (used by `open`, which flips
130 /// the `opened` flag).
131 pub fn get_mut(
132 &self,
133 local_fid: u32,
134 ) -> Result<dashmap::mapref::one::RefMut<'_, u32, S>, MountError> {
135 self.fids
136 .get_mut(&local_fid)
137 .ok_or_else(|| MountError::NotFound(format!("fid {} not found", local_fid)))
138 }
139
140 /// Remove fid state (called from `clunk`). Returns the state so the
141 /// caller can issue the best-effort remote clunk with the remote fid.
142 pub fn remove(&self, local_fid: u32) -> Option<S> {
143 self.fids.remove(&local_fid).map(|(_, s)| s)
144 }
145}
146
147/// Downcast the opaque `Fid` to its `RemoteFidKey`, returning
148/// `MountError::InvalidArgument` on a type mismatch. All `Mount` ops start
149/// with this. Free-standing so callers don't need to name the bridge's
150/// fid-state type parameter.
151pub fn fid_key(fid: &Fid) -> Result<&RemoteFidKey, MountError> {
152 fid.downcast_ref::<RemoteFidKey>()
153 .ok_or_else(|| MountError::InvalidArgument("bad fid type".into()))
154}
155
156/// Classify an `anyhow::Error` (as surfaced by the generated RPC clients)
157/// into a `MountError` by string-matching the common 9P / filesystem error
158/// phrases. Identical for every backing service. Free-standing so callers
159/// don't need to name the bridge's fid-state type parameter.
160pub fn map_err(e: anyhow::Error) -> MountError {
161 let msg = e.to_string();
162 if msg.contains("not found") || msg.contains("No such") {
163 MountError::NotFound(msg)
164 } else if msg.contains("permission denied") {
165 MountError::PermissionDenied(msg)
166 } else if msg.contains("not a directory") {
167 MountError::NotDirectory(msg)
168 } else if msg.contains("is a directory") {
169 MountError::IsDirectory(msg)
170 } else {
171 MountError::Io(msg)
172 }
173}
174
175// ─────────────────────────────────────────────────────────────────────────────
176// Directory stat parsing (packed 9P stats)
177// ─────────────────────────────────────────────────────────────────────────────
178
179/// Parse packed 9P stat entries from a directory `read()` response.
180///
181/// Each stat entry is: `[2-byte LE size][stat bytes]`. We extract qid
182/// (type/version/path), length, mtime, and name for `DirEntry`.
183///
184/// This is the format the model service's `SyntheticTree` emits for directory
185/// reads. The registry worktree service uses a different per-entry format
186/// (`name_len+name+is_dir+size`) and parses it locally — see
187/// `parse_worktree_dir_entries` in `remote_registry_mount.rs`.
188pub fn parse_dir_stats(data: &[u8]) -> Vec<DirEntry> {
189 let mut entries = Vec::new();
190 let mut offset = 0;
191
192 while offset + 2 <= data.len() {
193 let entry_size = u16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
194 offset += 2;
195
196 if offset + entry_size > data.len() {
197 break;
198 }
199
200 let entry_data = &data[offset..offset + entry_size];
201 offset += entry_size;
202
203 // 9P stat layout. The outer 2-byte size has already been consumed; the
204 // inner bytes are:
205 // type(2) dev(4) qid.type(1) qid.vers(4) qid.path(8)
206 // mode(4) atime(4) mtime(4) length(8) = 39 bytes
207 // then name_len(2) name ...
208 //
209 // Offsets:
210 // qid.type @ 6 (1 byte)
211 // qid.vers @ 7..11 (u32 LE)
212 // qid.path @ 11..19 (u64 LE)
213 // mode @ 19..23
214 // atime @ 23..27
215 // mtime @ 27..31 (u32 LE)
216 // length @ 31..39 (u64 LE)
217 // name_len @ 39..41 (u16 LE)
218 if entry_data.len() < 41 {
219 continue;
220 }
221
222 let qtype = entry_data[6];
223 let qvers = u32::from_le_bytes(entry_data[7..11].try_into().unwrap_or([0; 4]));
224 let qpath = u64::from_le_bytes(entry_data[11..19].try_into().unwrap_or([0; 8]));
225 let mtime = u32::from_le_bytes(entry_data[27..31].try_into().unwrap_or([0; 4])) as u64;
226 let length = u64::from_le_bytes(entry_data[31..39].try_into().unwrap_or([0; 8]));
227
228 let name_len = u16::from_le_bytes([entry_data[39], entry_data[40]]) as usize;
229 if entry_data.len() < 41 + name_len {
230 continue;
231 }
232 let name = String::from_utf8_lossy(&entry_data[41..41 + name_len]).to_string();
233
234 entries.push(DirEntry {
235 name: name.clone(),
236 is_dir: qtype == QTDIR,
237 size: length,
238 stat: Some(Stat {
239 qtype,
240 version: qvers,
241 path: qpath,
242 size: length,
243 name,
244 mtime,
245 }),
246 });
247 }
248
249 entries
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 #[test]
257 fn parse_empty_dir_stats() {
258 assert!(parse_dir_stats(&[]).is_empty());
259 }
260
261 #[test]
262 fn parse_truncated_dir_stats() {
263 // Size says 100 bytes but only 5 available — should not panic.
264 let data = [100, 0, 0, 0, 0];
265 assert!(parse_dir_stats(&data).is_empty());
266 }
267
268 /// Build one packed 9P stat entry (inner layout, no outer 2-byte size) and
269 /// verify qid type/version/path, length, mtime, and name are all decoded.
270 #[test]
271 fn parse_dir_stats_decodes_qid_and_fields() {
272 let qtype: u8 = 0x80; // QTDIR
273 let qvers: u32 = 0x0A0B_0C0D;
274 let qpath: u64 = 0x0102_0304_0506_0708;
275 let mtime: u32 = 0x1122_3344;
276 let length: u64 = 0x99AA_BBCC_DDDE_EEF0;
277 let name = b"model-dir";
278
279 // Inner stat: type(2) dev(4) qid.type(1) qid.vers(4) qid.path(8)
280 // mode(4) atime(4) mtime(4) length(8) name_len(2) name
281 let mut inner = Vec::new();
282 inner.extend_from_slice(&0u16.to_le_bytes()); // type
283 inner.extend_from_slice(&0u32.to_le_bytes()); // dev
284 inner.push(qtype);
285 inner.extend_from_slice(&qvers.to_le_bytes());
286 inner.extend_from_slice(&qpath.to_le_bytes());
287 inner.extend_from_slice(&0u32.to_le_bytes()); // mode
288 inner.extend_from_slice(&0u32.to_le_bytes()); // atime
289 inner.extend_from_slice(&mtime.to_le_bytes());
290 inner.extend_from_slice(&length.to_le_bytes());
291 inner.extend_from_slice(&(name.len() as u16).to_le_bytes());
292 inner.extend_from_slice(name);
293
294 // Prepend the 2-byte LE entry size.
295 let mut data = (inner.len() as u16).to_le_bytes().to_vec();
296 data.extend_from_slice(&inner);
297
298 let entries = parse_dir_stats(&data);
299 assert_eq!(entries.len(), 1);
300 let e = &entries[0];
301 assert_eq!(e.name, "model-dir");
302 assert!(e.is_dir);
303 assert_eq!(e.size, length);
304 let stat = match e.stat.as_ref() {
305 Some(s) => s,
306 None => panic!("stat must be present on parsed dir entry"),
307 };
308 assert_eq!(stat.qtype, qtype);
309 assert_eq!(
310 stat.version, qvers,
311 "qid version must be decoded, not flattened"
312 );
313 assert_eq!(stat.path, qpath, "qid path must be decoded, not flattened");
314 assert_eq!(stat.size, length);
315 assert_eq!(stat.mtime, mtime as u64);
316 }
317
318 /// `map_err` classifies the common 9P/filesystem error phrases.
319 #[test]
320 fn map_err_classifies_common_phrases() {
321 use hyprstream_vfs::MountError;
322
323 let classify = |msg: &str| map_err(anyhow::anyhow!("{}", msg));
324
325 assert!(matches!(
326 classify("not found here"),
327 MountError::NotFound(_)
328 ));
329 assert!(matches!(classify("No such file"), MountError::NotFound(_)));
330 assert!(matches!(
331 classify("permission denied"),
332 MountError::PermissionDenied(_)
333 ));
334 assert!(matches!(
335 classify("not a directory"),
336 MountError::NotDirectory(_)
337 ));
338 assert!(matches!(
339 classify("is a directory"),
340 MountError::IsDirectory(_)
341 ));
342 assert!(matches!(classify("disk on fire"), MountError::Io(_)));
343 }
344
345 /// `NinePBridge` allocates fids monotonically from 1 and tracks state.
346 #[test]
347 fn bridge_allocates_and_tracks_fids() {
348 let bridge = NinePBridge::<&'static str>::new("test");
349 assert_eq!(bridge.alloc_fid(), 1);
350 assert_eq!(bridge.alloc_fid(), 2);
351
352 bridge.insert(1, "root");
353 assert_eq!(bridge.get(1).map(|r| *r).unwrap_or("MISSING"), "root");
354 assert!(bridge.get(99).is_err());
355
356 {
357 if let Ok(mut r) = bridge.get_mut(1) {
358 *r = "changed";
359 } else {
360 panic!("fid 1 must be present for mutation");
361 }
362 }
363 assert_eq!(bridge.get(1).map(|r| *r).unwrap_or("MISSING"), "changed");
364
365 assert_eq!(bridge.remove(1), Some("changed"));
366 assert_eq!(bridge.remove(1), None);
367 }
368}