Skip to main content

hyprstream_9p/
client.rs

1//! 9P2000.L client — sends T-messages, receives R-messages.
2//!
3//! Transport-agnostic: the caller provides `send` and `recv` functions.
4//! On wasm32, these would be backed by DMA ring buffers (SharedArrayBuffer).
5//! On native, these could be backed by pipes, TCP, or QUIC streams.
6
7use std::sync::atomic::{AtomicU16, AtomicU32, Ordering};
8
9use crate::msg::{self, Qid, Response};
10
11/// Transport trait for sending/receiving 9P messages.
12///
13/// Implementations provide the actual byte transport (DMA ring, socket, etc.).
14/// Messages are already length-prefixed by the 9P serializer.
15///
16/// The trait is `Send` on native targets — so a socket-backed transport can back
17/// a `Send + Sync` [`Mount`](hyprstream_vfs::Mount) — and `?Send` on wasm32,
18/// where the DMA transport is single-threaded. This mirrors the `Mount` trait's
19/// own `cfg_attr` split.
20#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
21#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
22pub trait P9Transport {
23    /// Send a complete 9P message (including length prefix).
24    async fn send(&self, data: &[u8]) -> anyhow::Result<()>;
25
26    /// Receive a complete 9P message (including length prefix).
27    async fn recv(&self) -> anyhow::Result<Vec<u8>>;
28}
29
30/// 9P2000.L client.
31///
32/// Manages fid allocation, tag sequencing, and protocol handshake.
33/// All operations are async — the transport determines the actual I/O.
34/// The client uses atomic fid/tag counters (rather than `Cell`) so that
35/// `P9Client<T>` is `Send + Sync` whenever the transport is. That lets a native,
36/// socket-backed client back a `Send + Sync` VFS `Mount` served on real OS
37/// threads; on single-threaded wasm the atomics are equally correct.
38pub struct P9Client<T: P9Transport> {
39    transport: T,
40    next_fid: AtomicU32,
41    next_tag: AtomicU16,
42    root_fid: u32,
43    #[allow(dead_code)]
44    msize: u32,
45}
46
47impl<T: P9Transport> P9Client<T> {
48    /// Create a new client and perform version + attach handshake.
49    pub async fn connect(transport: T, uname: &str, aname: &str) -> anyhow::Result<Self> {
50        let client = Self {
51            transport,
52            next_fid: AtomicU32::new(1), // 0 reserved for root
53            next_tag: AtomicU16::new(1), // 0 is NOTAG
54            root_fid: 0,
55            msize: 8192,
56        };
57
58        // Version negotiation
59        let tag = client.alloc_tag();
60        let msg = msg::tversion(tag, 65536, "9P2000.L");
61        client.transport.send(&msg).await?;
62        let resp = client.transport.recv().await?;
63        let (_, response) = msg::parse_response(&resp)?;
64        match response {
65            Response::Version { msize, version } => {
66                if version != "9P2000.L" {
67                    anyhow::bail!("server does not support 9P2000.L: {version}");
68                }
69                // Update msize to what server accepts
70                let _ = msize; // TODO: use negotiated msize
71            }
72            Response::Error { ecode } => anyhow::bail!("version failed: errno {ecode}"),
73            _ => anyhow::bail!("unexpected response to Tversion"),
74        }
75
76        // Attach to root
77        let tag = client.alloc_tag();
78        let msg = msg::tattach(tag, 0, u32::MAX, uname, aname);
79        client.transport.send(&msg).await?;
80        let resp = client.transport.recv().await?;
81        let (_, response) = msg::parse_response(&resp)?;
82        match response {
83            Response::Attach { qid: _ } => {}
84            Response::Error { ecode } => anyhow::bail!("attach failed: errno {ecode}"),
85            _ => anyhow::bail!("unexpected response to Tattach"),
86        }
87
88        Ok(client)
89    }
90
91    fn alloc_fid(&self) -> u32 {
92        // Returns the current value and post-increments; wraps like the prior
93        // `Cell` version (fid 0 is the root and only recurs after 2^32 walks).
94        self.next_fid.fetch_add(1, Ordering::Relaxed)
95    }
96
97    fn alloc_tag(&self) -> u16 {
98        // Post-increment; skip NOTAG (0) if we wrap onto it.
99        let tag = self.next_tag.fetch_add(1, Ordering::Relaxed);
100        if tag == 0 {
101            self.next_tag.fetch_add(1, Ordering::Relaxed)
102        } else {
103            tag
104        }
105    }
106
107    /// Send a T-message and receive the R-message, checking for errors.
108    async fn rpc(&self, msg: &[u8]) -> anyhow::Result<Response> {
109        self.transport.send(msg).await?;
110        let resp = self.transport.recv().await?;
111        let (_, response) = msg::parse_response(&resp)?;
112        if let Response::Error { ecode } = &response {
113            anyhow::bail!("9P error: errno {ecode}");
114        }
115        Ok(response)
116    }
117
118    // ────────────────────────────────────────────────────────────────────────
119    // Public operations
120    // ────────────────────────────────────────────────────────────────────────
121
122    /// Walk a path from root, returning a new fid.
123    pub async fn walk(&self, components: &[&str]) -> anyhow::Result<(u32, Vec<Qid>)> {
124        let newfid = self.alloc_fid();
125        let tag = self.alloc_tag();
126        let msg = msg::twalk(tag, self.root_fid, newfid, components);
127        let resp = self.rpc(&msg).await?;
128        match resp {
129            Response::Walk { qids } => Ok((newfid, qids)),
130            _ => anyhow::bail!("unexpected response to Twalk"),
131        }
132    }
133
134    /// Open a fid for I/O.
135    pub async fn open(&self, fid: u32, flags: u32) -> anyhow::Result<(Qid, u32)> {
136        let tag = self.alloc_tag();
137        let msg = msg::tlopen(tag, fid, flags);
138        let resp = self.rpc(&msg).await?;
139        match resp {
140            Response::Lopen { qid, iounit } => Ok((qid, iounit)),
141            _ => anyhow::bail!("unexpected response to Tlopen"),
142        }
143    }
144
145    /// Read data from an open fid.
146    pub async fn read(&self, fid: u32, offset: u64, count: u32) -> anyhow::Result<Vec<u8>> {
147        let tag = self.alloc_tag();
148        let msg = msg::tread(tag, fid, offset, count);
149        let resp = self.rpc(&msg).await?;
150        match resp {
151            Response::Read { data } => Ok(data),
152            _ => anyhow::bail!("unexpected response to Tread"),
153        }
154    }
155
156    /// Write data to an open fid.
157    pub async fn write(&self, fid: u32, offset: u64, data: &[u8]) -> anyhow::Result<u32> {
158        let tag = self.alloc_tag();
159        let msg = msg::twrite(tag, fid, offset, data);
160        let resp = self.rpc(&msg).await?;
161        match resp {
162            Response::Write { count } => Ok(count),
163            _ => anyhow::bail!("unexpected response to Twrite"),
164        }
165    }
166
167    /// Close a fid.
168    pub async fn clunk(&self, fid: u32) -> anyhow::Result<()> {
169        let tag = self.alloc_tag();
170        let msg = msg::tclunk(tag, fid);
171        self.rpc(&msg).await?;
172        Ok(())
173    }
174
175    /// Get file attributes.
176    pub async fn getattr(&self, fid: u32) -> anyhow::Result<(Qid, u32, u64, u64)> {
177        let tag = self.alloc_tag();
178        // P9_GETATTR_BASIC = 0x7ff
179        let msg = msg::tgetattr(tag, fid, 0x7ff);
180        let resp = self.rpc(&msg).await?;
181        match resp {
182            Response::Getattr {
183                qid,
184                mode,
185                size,
186                mtime_sec,
187            } => Ok((qid, mode, size, mtime_sec)),
188            _ => anyhow::bail!("unexpected response to Tgetattr"),
189        }
190    }
191
192    /// Read directory entries.
193    pub async fn readdir(
194        &self,
195        fid: u32,
196        offset: u64,
197        count: u32,
198    ) -> anyhow::Result<Vec<msg::DirEntryP9>> {
199        let tag = self.alloc_tag();
200        let msg = msg::treaddir(tag, fid, offset, count);
201        let resp = self.rpc(&msg).await?;
202        match resp {
203            Response::Readdir { data } => msg::parse_readdir_entries(&data),
204            _ => anyhow::bail!("unexpected response to Treaddir"),
205        }
206    }
207
208    /// Get the root fid.
209    pub fn root_fid(&self) -> u32 {
210        self.root_fid
211    }
212}