Skip to main content

hyprstream_9p/
remote_mount.rs

1//! `Remote9pMount` — a native VFS [`Mount`] backed by a socket 9P client.
2//!
3//! This is the **client half** of the bidirectional 9P story (#708): where
4//! [`MountBackend`](crate::mount_backend::MountBackend) exports a local VFS
5//! [`Mount`] *as* a 9P server, `Remote9pMount` *imports* a remote 9P2000.L server
6//! and presents it back as a [`Mount`] the host can
7//! [`bind_mount`](hyprstream_vfs::Namespace) into its own namespace. Together
8//! they let hyprstream both serve its namespace to a guest and consume the
9//! guest's namespace — two independent 9P sessions over two sockets.
10//!
11//! It is the native, socket-transport analogue of the wasm-only
12//! [`WanixMount`](crate::wanix_mount::WanixMount): the same `P9Client`-backed
13//! `Mount` shape, but generic over a genuinely `Send + Sync`
14//! [`SocketTransport`] rather than the browser DMA transport, and with no
15//! `unsafe impl Send/Sync` (the wasm `WanixMount` needs one because its DMA
16//! transport is only sound single-threaded). See the crate docs for why the two
17//! are separate types rather than one renamed generic.
18//!
19//! ## Subject / fid semantics
20//!
21//! Every op threads the caller [`Subject`], exactly like every other VFS
22//! [`Mount`]. Each `walk` returns an opaque [`Fid`] wrapping the remote 9P fid
23//! number; `open`/`read`/`write`/`readdir`/`stat`/`clunk` forward to that fid.
24//! The wrapped [`P9Client`] is held behind a single async `Mutex` so each
25//! Mount op is one atomic T→R exchange on the connection — requests never
26//! interleave on the wire.
27
28use anyhow::Result;
29use async_trait::async_trait;
30use std::path::Path;
31use tokio::net::{TcpStream, UnixStream};
32use tokio::sync::Mutex;
33
34use hyprstream_rpc::Subject;
35use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Stat};
36
37use crate::client::{P9Client, P9Transport};
38use crate::socket_transport::SocketTransport;
39
40/// Fid state for a [`Remote9pMount`] — the remote 9P fid number.
41struct P9FidState {
42    fid: u32,
43}
44
45/// A VFS [`Mount`] that forwards every operation to a remote 9P2000.L server
46/// over a socket [`P9Transport`].
47///
48/// Build one with [`connect_uds`](Remote9pMount::connect_uds) /
49/// [`connect_tcp`](Remote9pMount::connect_tcp), or [`from_client`] with a
50/// pre-connected [`P9Client`] over any transport.
51///
52/// [`from_client`]: Remote9pMount::from_client
53pub struct Remote9pMount<T: P9Transport> {
54    client: Mutex<P9Client<T>>,
55}
56
57impl<T: P9Transport> Remote9pMount<T> {
58    /// Wrap an already-connected [`P9Client`] (version + attach handshake done).
59    pub fn from_client(client: P9Client<T>) -> Self {
60        Self {
61            client: Mutex::new(client),
62        }
63    }
64}
65
66impl Remote9pMount<SocketTransport<UnixStream>> {
67    /// Dial a remote 9P server on a Unix domain socket and attach its root.
68    ///
69    /// `uname`/`aname` are the 9P attach identity and export name (the server's
70    /// [`Translator`](crate::translator::Translator) ignores them and serves its
71    /// single Subject-scoped root, but they are sent for protocol conformance).
72    pub async fn connect_uds(path: impl AsRef<Path>, uname: &str, aname: &str) -> Result<Self> {
73        let transport = SocketTransport::connect_uds(path).await?;
74        let client = P9Client::connect(transport, uname, aname).await?;
75        Ok(Self::from_client(client))
76    }
77}
78
79impl Remote9pMount<SocketTransport<TcpStream>> {
80    /// Dial a remote 9P server over TCP and attach its root.
81    pub async fn connect_tcp(
82        addr: impl tokio::net::ToSocketAddrs,
83        uname: &str,
84        aname: &str,
85    ) -> Result<Self> {
86        let transport = SocketTransport::connect_tcp(addr).await?;
87        let client = P9Client::connect(transport, uname, aname).await?;
88        Ok(Self::from_client(client))
89    }
90}
91
92#[async_trait]
93impl<T> Mount for Remote9pMount<T>
94where
95    T: P9Transport + Send + Sync + 'static,
96{
97    async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
98        let client = self.client.lock().await;
99        let (fid, _qids) = client
100            .walk(components)
101            .await
102            .map_err(|e| MountError::NotFound(e.to_string()))?;
103        Ok(Fid::new(P9FidState { fid }))
104    }
105
106    async fn open(&self, fid: &mut Fid, mode: u8, _caller: &Subject) -> Result<(), MountError> {
107        let f = fid
108            .downcast_ref::<P9FidState>()
109            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?
110            .fid;
111        let client = self.client.lock().await;
112        client
113            .open(f, mode as u32)
114            .await
115            .map_err(|e| MountError::Io(e.to_string()))?;
116        Ok(())
117    }
118
119    async fn read(
120        &self,
121        fid: &Fid,
122        offset: u64,
123        count: u32,
124        _caller: &Subject,
125    ) -> Result<Vec<u8>, MountError> {
126        let f = fid
127            .downcast_ref::<P9FidState>()
128            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?
129            .fid;
130        let client = self.client.lock().await;
131        client
132            .read(f, offset, count)
133            .await
134            .map_err(|e| MountError::Io(e.to_string()))
135    }
136
137    async fn write(
138        &self,
139        fid: &Fid,
140        offset: u64,
141        data: &[u8],
142        _caller: &Subject,
143    ) -> Result<u32, MountError> {
144        let f = fid
145            .downcast_ref::<P9FidState>()
146            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?
147            .fid;
148        let client = self.client.lock().await;
149        client
150            .write(f, offset, data)
151            .await
152            .map_err(|e| MountError::Io(e.to_string()))
153    }
154
155    async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
156        let f = fid
157            .downcast_ref::<P9FidState>()
158            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?
159            .fid;
160        let client = self.client.lock().await;
161        let entries = client
162            .readdir(f, 0, 65536)
163            .await
164            .map_err(|e| MountError::Io(e.to_string()))?;
165        Ok(entries
166            .into_iter()
167            .map(|e| DirEntry {
168                name: e.name,
169                is_dir: e.qid.is_dir(),
170                size: 0,
171                stat: None,
172            })
173            .collect())
174    }
175
176    async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
177        let f = fid
178            .downcast_ref::<P9FidState>()
179            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?
180            .fid;
181        let client = self.client.lock().await;
182        let (qid, _mode, size, mtime) = client
183            .getattr(f)
184            .await
185            .map_err(|e| MountError::Io(e.to_string()))?;
186        Ok(Stat {
187            qtype: qid.qtype,
188            version: qid.version,
189            path: qid.path,
190            size,
191            name: String::new(), // name comes from walk, not stat
192            mtime,
193        })
194    }
195
196    async fn clunk(&self, fid: Fid, _caller: &Subject) {
197        if let Some(f) = fid.downcast_ref::<P9FidState>().map(|s| s.fid) {
198            let client = self.client.lock().await;
199            let _ = client.clunk(f).await;
200        }
201    }
202}