Skip to main content

hyprstream_core/services/
remote_mount.rs

1//! Remote model mount — bridges the VFS `Mount` trait to the generated `ModelClient` RPC.
2//!
3//! `RemoteModelMount` wraps a `ModelClient` and translates synchronous `Mount`
4//! trait calls into async RPC requests over ZMQ. This allows the TUI shell's
5//! VFS namespace to serve `/srv/model` by proxying 9P operations to the model
6//! service, which in turn delegates to its local `FsHandler` / `SyntheticTree`.
7//!
8//! ## Shared bridge
9//!
10//! The sync→async plumbing (embedded tokio runtime, fid allocator, fid map,
11//! `anyhow → MountError` mapping, the opaque fid key, and the packed 9P stat
12//! parser) is shared with `RemoteRegistryMount` via [`NinePBridge`] in
13//! [`crate::services::ninep_bridge`]. Only the model-specific pieces live
14//! here: the `ModelClient`/`ModelFsClient` types, the 1-level scope
15//! extraction (first path component = model ref), and the `stat` (not
16//! `np_stat`) RPC method name.
17//!
18//! ## Fid management
19//!
20//! The mount allocates local fid numbers and tracks them via the bridge's
21//! `DashMap`. Each local fid maps to a `RemoteFidState` that stores the
22//! remote fid number returned by walk, plus metadata (open mode, qtype) for
23//! stat/readdir synthesis.
24//!
25//! ## Timeout / graceful degradation
26//!
27//! A dedicated single-threaded tokio runtime drives the async client. If the
28//! model service is unreachable, `block_on` will hang until the ZMQ socket
29//! timeout fires (set on the underlying socket). Callers see
30//! `MountError::Io("service unreachable: ...")`.
31
32use async_trait::async_trait;
33use hyprstream_rpc::Subject;
34use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Stat};
35
36use crate::services::ninep_bridge::{fid_key, map_err, parse_dir_stats, NinePBridge, RemoteFidKey};
37use crate::services::types::QTDIR;
38use hyprstream_rpc_std::model_client::{ModelClient, ModelFsClient};
39
40// ─────────────────────────────────────────────────────────────────────────────
41// Remote fid state
42// ─────────────────────────────────────────────────────────────────────────────
43
44/// Per-fid state held locally.
45#[derive(Clone, Debug)]
46struct RemoteFidState {
47    /// Fid number on the remote side.
48    remote_fid: u32,
49    /// Model reference this fid belongs to (e.g., "qwen3:main").
50    model_ref: String,
51    /// Qtype from the walk response (QTDIR or QTFILE).
52    qtype: u8,
53    /// Whether open() has been called.
54    opened: bool,
55}
56
57// ─────────────────────────────────────────────────────────────────────────────
58// RemoteModelMount
59// ─────────────────────────────────────────────────────────────────────────────
60
61/// A `Mount` implementation that proxies 9P operations to the model service
62/// via the generated `ModelClient` RPC.
63pub struct RemoteModelMount {
64    client: ModelClient,
65    bridge: NinePBridge<RemoteFidState>,
66}
67
68impl RemoteModelMount {
69    /// Create a new remote mount wrapping the given model client.
70    pub fn new(client: ModelClient) -> Self {
71        Self {
72            client,
73            bridge: NinePBridge::new("RemoteModelMount"),
74        }
75    }
76
77    /// Get the scoped fs client for a model reference.
78    fn fs_client(&self, model_ref: &str) -> ModelFsClient {
79        self.client.fs(model_ref)
80    }
81}
82
83#[async_trait]
84impl Mount for RemoteModelMount {
85    async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
86        // First component is the model_ref (e.g., "qwen3:main"), rest is path within model tree.
87        if components.is_empty() {
88            return Err(MountError::InvalidArgument("empty path".into()));
89        }
90
91        let model_ref = components[0];
92        let wnames: Vec<String> = components[1..]
93            .iter()
94            .map(std::string::ToString::to_string)
95            .collect();
96
97        let local_fid = self.bridge.alloc_fid();
98        let remote_newfid = local_fid; // Use same numbering for simplicity.
99
100        let fs = self.fs_client(model_ref);
101        let walk_req = hyprstream_rpc_std::model_client::NpWalk {
102            fid: 0, // root
103            newfid: remote_newfid,
104            wnames,
105        };
106
107        let result = self
108            .bridge
109            .rt()
110            .block_on(fs.walk(&walk_req))
111            .map_err(map_err)?;
112
113        // Determine qtype from the walk response qid.
114        let qtype = result.qid.qtype;
115
116        let state = RemoteFidState {
117            remote_fid: remote_newfid,
118            model_ref: model_ref.to_owned(),
119            qtype,
120            opened: false,
121        };
122        self.bridge.insert(local_fid, state);
123
124        Ok(Fid::new(RemoteFidKey(local_fid)))
125    }
126
127    async fn open(&self, fid: &mut Fid, mode: u8, _caller: &Subject) -> Result<(), MountError> {
128        let local_id = fid_key(fid)?.0;
129
130        let mut state = self.bridge.get_mut(local_id)?;
131
132        let fs = self.fs_client(&state.model_ref);
133        let open_req = hyprstream_rpc_std::model_client::NpOpen {
134            fid: state.remote_fid,
135            mode,
136        };
137
138        let _result = self
139            .bridge
140            .rt()
141            .block_on(fs.open(&open_req))
142            .map_err(map_err)?;
143        state.opened = true;
144
145        Ok(())
146    }
147
148    async fn read(
149        &self,
150        fid: &Fid,
151        offset: u64,
152        count: u32,
153        _caller: &Subject,
154    ) -> Result<Vec<u8>, MountError> {
155        let local_id = fid_key(fid)?.0;
156
157        let state = self.bridge.get(local_id)?;
158
159        let fs = self.fs_client(&state.model_ref);
160        let read_req = hyprstream_rpc_std::model_client::NpRead {
161            fid: state.remote_fid,
162            offset,
163            count,
164        };
165
166        let result = self
167            .bridge
168            .rt()
169            .block_on(fs.read(&read_req))
170            .map_err(map_err)?;
171        Ok(result.data)
172    }
173
174    async fn write(
175        &self,
176        fid: &Fid,
177        offset: u64,
178        data: &[u8],
179        _caller: &Subject,
180    ) -> Result<u32, MountError> {
181        let local_id = fid_key(fid)?.0;
182
183        let state = self.bridge.get(local_id)?;
184
185        let fs = self.fs_client(&state.model_ref);
186        let write_req = hyprstream_rpc_std::model_client::NpWrite {
187            fid: state.remote_fid,
188            offset,
189            data: data.to_vec(),
190        };
191
192        let result = self
193            .bridge
194            .rt()
195            .block_on(fs.write(&write_req))
196            .map_err(map_err)?;
197        Ok(result.count)
198    }
199
200    async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
201        // 9P doesn't have a dedicated readdir — we read the directory fid and parse
202        // the stat entries from the raw bytes. However, the model service's SyntheticTree
203        // encodes directory listings in its read() response as newline-separated entries.
204        //
205        // For now, do a read at offset 0 and parse the response.
206        // The model service returns stat-encoded directory entries.
207        let local_id = fid_key(fid)?.0;
208
209        let state = self.bridge.get(local_id)?;
210
211        if state.qtype != QTDIR {
212            return Err(MountError::NotDirectory(format!(
213                "fid {} is not a directory",
214                local_id
215            )));
216        }
217
218        // Read directory data from remote.
219        let fs = self.fs_client(&state.model_ref);
220        let read_req = hyprstream_rpc_std::model_client::NpRead {
221            fid: state.remote_fid,
222            offset: 0,
223            count: 65536, // Large enough for most directory listings.
224        };
225
226        let result = self
227            .bridge
228            .rt()
229            .block_on(fs.read(&read_req))
230            .map_err(map_err)?;
231
232        // Parse stat entries from the raw 9P directory read data.
233        // Directory reads return packed NpStat entries. Each entry is preceded
234        // by a 2-byte little-endian size. We extract name + qtype from each.
235        Ok(parse_dir_stats(&result.data))
236    }
237
238    async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
239        let local_id = fid_key(fid)?.0;
240
241        let state = self.bridge.get(local_id)?;
242
243        let fs = self.fs_client(&state.model_ref);
244        let stat_req = hyprstream_rpc_std::model_client::NpStatReq {
245            fid: state.remote_fid,
246        };
247
248        let result = self
249            .bridge
250            .rt()
251            .block_on(fs.stat(&stat_req))
252            .map_err(map_err)?;
253
254        // Convert the RPC RStat → VFS Stat.
255        let np_stat = &result.stat;
256
257        Ok(Stat {
258            qtype: np_stat.qid.qtype,
259            // Thread the wire qid version/path through instead of discarding
260            // them. `nine.capnp` already carries these; we were flattening the
261            // qid to qtype only. See the qid-soundness invariant on
262            // `hyprstream_vfs::Stat` — these are advisory identity hints, not
263            // yet a strong identity (content-CID qid lands in #387).
264            version: np_stat.qid.version,
265            path: np_stat.qid.path,
266            size: np_stat.length,
267            name: np_stat.name.clone(),
268            mtime: np_stat.mtime as u64,
269        })
270    }
271
272    async fn clunk(&self, fid: Fid, _caller: &Subject) {
273        let local_id = match fid_key(&fid) {
274            Ok(k) => k.0,
275            Err(_) => return,
276        };
277
278        if let Some(state) = self.bridge.remove(local_id) {
279            let fs = self.fs_client(&state.model_ref);
280            let clunk_req = hyprstream_rpc_std::model_client::NpClunk {
281                fid: state.remote_fid,
282            };
283
284            // Best-effort clunk — ignore errors.
285            let _ = self.bridge.rt().block_on(fs.clunk(&clunk_req));
286        }
287    }
288}