Skip to main content

hyprstream_core/services/
kata_9p_backend.rs

1//! `ModelBackend` — the capnp-RPC [`Backend`] for the Kata 9P translator.
2//!
3//! This is the production counterpart to the in-memory test backend. It turns
4//! each 9P filesystem operation into a capnp RPC against the model service's
5//! `fs` scope (`nine.capnp` envelope), via the generated `ModelClient`. The
6//! flow is the mirror of [`RemoteModelMount`], which goes VFS → RPC:
7//!
8//! ```text
9//!   Kata guest (virtio-9P) ──► Translator ──► ModelBackend ──► ModelClient.fs()
10//!        9P2000.L wire            fid table      capnp RPC (nine.capnp)
11//! ```
12//!
13//! The model service resolves the synthetic `/srv/model/<ref>/...` tree from
14//! its `FsHandler`/`SyntheticTree`, exactly as it does for the in-process VFS.
15//!
16//! ## Fid numbering
17//!
18//! The translator allocates 9P fids on its side; we forward them unchanged as
19//! the model service's remote fids (same one-to-one scheme `RemoteModelMount`
20//! uses). The first walk component establishes the model reference; later
21//! single-name walks traverse the path within that model's synthetic tree.
22
23use std::sync::atomic::AtomicU32;
24
25use async_trait::async_trait;
26use dashmap::DashMap;
27use hyprstream_9p::backend::{Backend, OpenResult, StatResult, WalkResult};
28use hyprstream_9p::msg::Qid;
29
30use hyprstream_rpc_std::model_client::{ModelClient, ModelFsClient};
31use hyprstream_rpc_std::model_client::{
32    NpClunk, NpOpen, NpRead, NpStatReq, NpWalk, NpWrite, ROpen, RStat, RWalk,
33};
34
35/// Per-fid state cached on the backend side after a walk.
36#[derive(Clone, Debug)]
37struct ModelFidState {
38    /// Model reference this fid belongs to (e.g. "qwen3:main").
39    model_ref: String,
40}
41
42/// `Backend` impl that proxies 9P operations to the model service.
43///
44/// Holds a single-threaded tokio runtime to drive the async client, mirroring
45/// `RemoteModelMount`. If the model service is unreachable, calls return
46/// `anyhow::Error` and the translator surfaces an `Rlerror`.
47pub struct ModelBackend {
48    client: ModelClient,
49    rt: tokio::runtime::Runtime,
50    /// 9P fid → model_ref (resolved on walk).
51    fids: DashMap<u32, ModelFidState>,
52    /// Monotonic counter for locally-synthesized qid path values, used when
53    /// the backend must fabricate a qid (e.g. root attach). Normally the qid
54    /// arrives in the RPC response and this is unused.
55    #[allow(dead_code)]
56    next_path_id: AtomicU32,
57}
58
59impl ModelBackend {
60    /// Wrap a `ModelClient`. The client must already be configured to talk to
61    /// the model service (signing key, server verifying key, subject).
62    #[allow(clippy::expect_used)] // runtime creation is infallible in practice
63    pub fn new(client: ModelClient) -> Self {
64        let rt = tokio::runtime::Builder::new_current_thread()
65            .enable_all()
66            .build()
67            .expect("failed to create tokio runtime for ModelBackend");
68        Self {
69            client,
70            rt,
71            fids: DashMap::new(),
72            next_path_id: AtomicU32::new(1),
73        }
74    }
75
76    /// Build the scoped fs client for a model reference.
77    fn fs_client(&self, model_ref: &str) -> ModelFsClient {
78        self.client.fs(model_ref)
79    }
80}
81
82fn qid_from_rpc(q: &hyprstream_rpc_std::model_client::Qid) -> Qid {
83    Qid {
84        qtype: q.qtype,
85        version: q.version,
86        path: q.path,
87    }
88}
89
90#[async_trait]
91impl Backend for ModelBackend {
92    async fn walk(
93        &self,
94        fid: u32,
95        newfid: u32,
96        components: &[String],
97    ) -> anyhow::Result<WalkResult> {
98        if components.len() > 1 {
99            anyhow::bail!("ModelBackend only supports single-name walks; refusing an ambiguous multi-name binding");
100        }
101        // Resolve model_ref: prefer a previously-walked parent fid, else take
102        // the first walk component as the model_ref.
103        let (model_ref, wnames): (String, Vec<String>) = if components.is_empty() {
104            // Clone / attach — inherit model_ref from the source fid.
105            let mr = self
106                .fids
107                .get(&fid)
108                .map(|s| s.model_ref.clone())
109                .ok_or_else(|| anyhow::anyhow!("walk: source fid {fid} has no model_ref"))?;
110            (mr, Vec::new())
111        } else if let Some(state) = self.fids.get(&fid) {
112            // Once the model reference is established, subsequent one-name
113            // walks stay in that model's fs scope.
114            (state.model_ref.clone(), components.to_vec())
115        } else {
116            // The first component establishes the model reference.
117            let model_ref = components[0].clone();
118            let rest = components[1..].to_vec();
119            (model_ref, rest)
120        };
121
122        // Forward the walk to the model service's fs scope.
123        let fs = self.fs_client(&model_ref);
124        let req = NpWalk {
125            fid,
126            newfid,
127            wnames,
128        };
129        let RWalk { qid, .. } = self.rt.block_on(fs.walk(&req))?;
130        self.fids.insert(newfid, ModelFidState { model_ref });
131
132        Ok(WalkResult {
133            qids: vec![qid_from_rpc(&qid)],
134            reached: components.to_vec(),
135        })
136    }
137
138    async fn open(&self, fid: u32, flags: u32) -> anyhow::Result<OpenResult> {
139        let state = self
140            .fids
141            .get(&fid)
142            .ok_or_else(|| anyhow::anyhow!("open: fid {fid} not walked"))?
143            .clone();
144        let fs = self.fs_client(&state.model_ref);
145        // 9P2000.L lopen flags are Linux O_* bits; the model service's NpOpen
146        // expects a 9P mode byte (OREAD=0, OWRITE=1, ORDWR=2). Truncate the
147        // translation to the low bits for read/write intent.
148        let mode = lopen_flags_to_mode(flags);
149        let req = NpOpen { fid, mode };
150        let ROpen { qid, iounit } = self.rt.block_on(fs.open(&req))?;
151        Ok(OpenResult {
152            qid: qid_from_rpc(&qid),
153            iounit,
154        })
155    }
156
157    async fn read(&self, fid: u32, offset: u64, count: u32) -> anyhow::Result<Vec<u8>> {
158        let state = self
159            .fids
160            .get(&fid)
161            .ok_or_else(|| anyhow::anyhow!("read: fid {fid} not walked"))?
162            .clone();
163        let fs = self.fs_client(&state.model_ref);
164        let req = NpRead { fid, offset, count };
165        let result = self.rt.block_on(fs.read(&req))?;
166        Ok(result.data)
167    }
168
169    async fn write(&self, fid: u32, offset: u64, data: &[u8]) -> anyhow::Result<u32> {
170        let state = self
171            .fids
172            .get(&fid)
173            .ok_or_else(|| anyhow::anyhow!("write: fid {fid} not walked"))?
174            .clone();
175        let fs = self.fs_client(&state.model_ref);
176        let req = NpWrite {
177            fid,
178            offset,
179            data: data.to_vec(),
180        };
181        let result = self.rt.block_on(fs.write(&req))?;
182        Ok(result.count)
183    }
184
185    async fn stat(&self, fid: u32) -> anyhow::Result<StatResult> {
186        let state = self
187            .fids
188            .get(&fid)
189            .ok_or_else(|| anyhow::anyhow!("stat: fid {fid} not walked"))?
190            .clone();
191        let fs = self.fs_client(&state.model_ref);
192        let req = NpStatReq { fid };
193        let RStat { stat } = self.rt.block_on(fs.stat(&req))?;
194        Ok(StatResult {
195            qid: qid_from_rpc(&stat.qid),
196            mode: stat.mode,
197            size: stat.length,
198            mtime_sec: stat.mtime as u64,
199        })
200    }
201
202    async fn readdir(&self, fid: u32, offset: u64, count: u32) -> anyhow::Result<Vec<u8>> {
203        // The model service encodes directory listings in read() responses
204        // (see RemoteModelMount::readdir): stat-encoded entries served via
205        // NpRead on a directory fid. Reuse that path.
206        self.read(fid, offset, count).await
207    }
208
209    async fn clunk(&self, fid: u32) -> anyhow::Result<()> {
210        // Best-effort remote clunk; drop local state regardless.
211        if let Some((_, state)) = self.fids.remove(&fid) {
212            let fs = self.fs_client(&state.model_ref);
213            let req = NpClunk { fid };
214            let _ = self.rt.block_on(fs.clunk(&req));
215        }
216        Ok(())
217    }
218}
219
220/// Map 9P2000.L Tlopen flags (Linux O_* bits) to a 9P open mode byte.
221///
222/// Only read/write intent is preserved; flags like O_TRUNC / O_APPEND are
223/// advisory here since the model service's synthetic tree is mostly read-only.
224fn lopen_flags_to_mode(flags: u32) -> u8 {
225    const O_WRONLY: u32 = 0o1;
226    const O_RDWR: u32 = 0o2;
227    let acc = flags & 0o3;
228    match acc {
229        O_WRONLY => 1, // OWRITE
230        O_RDWR => 2,   // ORDWR
231        _ => 0,        // OREAD
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    #[test]
240    fn lopen_flags_mapping() {
241        assert_eq!(lopen_flags_to_mode(0), 0); // OREAD
242        assert_eq!(lopen_flags_to_mode(0o1), 1); // OWRITE
243        assert_eq!(lopen_flags_to_mode(0o2), 2); // ORDWR
244        assert_eq!(lopen_flags_to_mode(0o100), 0); // O_CREAT + OREAD → OREAD
245        assert_eq!(lopen_flags_to_mode(0o101), 1); // O_CREAT + OWRITE → OWRITE
246    }
247}