Skip to main content

hyprstream_9p/
memory.rs

1//! In-memory [`Backend`] for standalone translator tests.
2//!
3//! Holds a flat map of absolute path → file contents plus a per-fid map of
4//! open state (offset cursor, resolved path). The translator drives this
5//! exactly as it would drive a `ModelBackend` (capnp RPC), so tests exercise
6//! the full 9P codec + fid-table + dispatch path with no network.
7
8use parking_lot::Mutex;
9use std::collections::HashMap;
10
11use async_trait::async_trait;
12
13use crate::backend::{Backend, OpenResult, StatResult, WalkResult};
14use crate::msg::Qid;
15
16/// Path → bytes for a single open file. Fids reference these by allocated id.
17struct FileEntry {
18    bytes: Vec<u8>,
19    qid: Qid,
20}
21
22/// Per-fid live state: which path it points at (None = root).
23#[derive(Clone)]
24struct FidLink {
25    path: Option<String>,
26    qid: Qid,
27    is_dir: bool,
28}
29
30/// In-memory backend.
31#[derive(Default)]
32pub struct MemoryBackend {
33    files: Mutex<HashMap<String, FileEntry>>,
34    fids: Mutex<HashMap<u32, FidLink>>,
35    next_path: Mutex<u64>,
36}
37
38impl MemoryBackend {
39    /// Add a file at an absolute path (e.g. `/hello.txt`).
40    pub fn add_file(&self, path: &str, contents: &[u8]) {
41        let mut path_no_root = path.trim_start_matches('/');
42        // Treat top-level files as single-component names.
43        if let Some(stripped) = path_no_root.strip_prefix('/') {
44            path_no_root = stripped;
45        }
46        let mut files = self.files.lock();
47        let qid = Qid {
48            qtype: 0, // QTFILE
49            version: 1,
50            path: {
51                let mut np = self.next_path.lock();
52                *np += 1;
53                *np
54            },
55        };
56        files.insert(
57            path_no_root.to_owned(),
58            FileEntry {
59                bytes: contents.to_vec(),
60                qid,
61            },
62        );
63    }
64
65    fn root_qid() -> Qid {
66        Qid {
67            qtype: 0x80,
68            version: 1,
69            path: 0,
70        } // QTDIR
71    }
72}
73
74#[async_trait]
75impl Backend for MemoryBackend {
76    async fn walk(
77        &self,
78        _fid: u32,
79        newfid: u32,
80        components: &[String],
81    ) -> anyhow::Result<WalkResult> {
82        // An empty walk clones an existing fid. During attach the source fid
83        // is not bound yet, so materialize the root instead.
84        if components.is_empty() {
85            let mut fids = self.fids.lock();
86            if let Some(link) = fids.get(&_fid).cloned() {
87                fids.insert(newfid, link);
88                return Ok(WalkResult {
89                    qids: Vec::new(),
90                    reached: Vec::new(),
91                });
92            }
93            let link = FidLink {
94                path: None,
95                qid: Self::root_qid(),
96                is_dir: true,
97            };
98            fids.insert(newfid, link);
99            return Ok(WalkResult {
100                qids: vec![Self::root_qid()],
101                reached: Vec::new(),
102            });
103        }
104
105        let name = &components[0];
106        let files = self.files.lock();
107        let entry = files
108            .get(name)
109            .ok_or_else(|| anyhow::anyhow!("no such file: {name}"))?;
110        let qid = entry.qid.clone();
111        drop(files);
112
113        let link = FidLink {
114            path: Some(name.clone()),
115            qid: qid.clone(),
116            is_dir: false,
117        };
118        self.fids.lock().insert(newfid, link);
119        Ok(WalkResult {
120            qids: vec![qid],
121            reached: vec![name.clone()],
122        })
123    }
124
125    async fn open(&self, fid: u32, _flags: u32) -> anyhow::Result<OpenResult> {
126        let fids = self.fids.lock();
127        let link = fids
128            .get(&fid)
129            .ok_or_else(|| anyhow::anyhow!("unknown fid {fid}"))?;
130        Ok(OpenResult {
131            qid: link.qid.clone(),
132            iounit: 8 * 1024,
133        })
134    }
135
136    async fn read(&self, fid: u32, offset: u64, count: u32) -> anyhow::Result<Vec<u8>> {
137        let fids = self.fids.lock();
138        let link = fids
139            .get(&fid)
140            .ok_or_else(|| anyhow::anyhow!("unknown fid {fid}"))?;
141        if link.is_dir {
142            // Directory read: emit standard 9P2000.L Rreaddir dirent records
143            // (`qid[13] offset[8] type[1] name[s]`) — the same wire format the
144            // Mount export path and any standard client (incl. this crate's own
145            // `client.rs`, which parses via `parse_readdir_entries`) expect.
146            let files = self.files.lock();
147            let records: Vec<crate::msg::ReaddirEntry> = files
148                .iter()
149                .map(|(name, entry)| crate::msg::ReaddirEntry {
150                    qid: entry.qid.clone(),
151                    name: name.clone(),
152                })
153                .collect();
154            drop(files);
155            return Ok(crate::msg::encode_readdir_page(&records, offset, count));
156        }
157        let path = link.path.clone().unwrap_or_default();
158        let files = self.files.lock();
159        let entry = files
160            .get(&path)
161            .ok_or_else(|| anyhow::anyhow!("fid {fid} has no backing file"))?;
162        let off = offset as usize;
163        if off >= entry.bytes.len() {
164            return Ok(Vec::new());
165        }
166        let end = (off + count as usize).min(entry.bytes.len());
167        Ok(entry.bytes[off..end].to_vec())
168    }
169
170    async fn write(&self, fid: u32, offset: u64, data: &[u8]) -> anyhow::Result<u32> {
171        let fids = self.fids.lock();
172        let link = fids
173            .get(&fid)
174            .ok_or_else(|| anyhow::anyhow!("unknown fid {fid}"))?;
175        if link.is_dir {
176            anyhow::bail!("cannot write to directory fid {fid}");
177        }
178        let path = link.path.clone().unwrap_or_default();
179        drop(fids);
180
181        let mut files = self.files.lock();
182        let entry = files
183            .get_mut(&path)
184            .ok_or_else(|| anyhow::anyhow!("fid {fid} has no backing file"))?;
185        let off = offset as usize;
186        if off + data.len() > entry.bytes.len() {
187            entry.bytes.resize(off + data.len(), 0);
188        }
189        entry.bytes[off..off + data.len()].copy_from_slice(data);
190        Ok(data.len() as u32)
191    }
192
193    async fn stat(&self, fid: u32) -> anyhow::Result<StatResult> {
194        let fids = self.fids.lock();
195        let link = fids
196            .get(&fid)
197            .ok_or_else(|| anyhow::anyhow!("unknown fid {fid}"))?;
198        let (size, mode) = if link.is_dir {
199            (0, 0o040755)
200        } else {
201            let path = link.path.clone().unwrap_or_default();
202            let files = self.files.lock();
203            let len = files.get(&path).map(|e| e.bytes.len() as u64).unwrap_or(0);
204            (len, 0o100644)
205        };
206        Ok(StatResult {
207            qid: link.qid.clone(),
208            mode,
209            size,
210            mtime_sec: 0,
211        })
212    }
213
214    async fn readdir(&self, fid: u32, offset: u64, count: u32) -> anyhow::Result<Vec<u8>> {
215        // Same encoding as read() for directories.
216        self.read(fid, offset, count).await
217    }
218
219    async fn clunk(&self, fid: u32) -> anyhow::Result<()> {
220        self.fids.lock().remove(&fid);
221        Ok(())
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[tokio::test]
230    async fn walk_read_roundtrip() {
231        let b = MemoryBackend::default();
232        b.add_file("/greeting", b"hi");
233        let w = b.walk(0, 1, &["greeting".into()]).await.unwrap();
234        assert_eq!(w.qids.len(), 1);
235        let o = b.open(1, 0).await.unwrap();
236        assert_eq!(o.iounit, 8 * 1024);
237        let d = b.read(1, 0, 16).await.unwrap();
238        assert_eq!(&d, b"hi");
239        b.clunk(1).await.unwrap();
240    }
241
242    #[tokio::test]
243    async fn write_extends_file() {
244        let b = MemoryBackend::default();
245        b.add_file("/log", b"");
246        b.walk(0, 1, &["log".into()]).await.unwrap();
247        b.write(1, 0, b"abc").await.unwrap();
248        let d = b.read(1, 0, 8).await.unwrap();
249        assert_eq!(&d, b"abc");
250    }
251}