1use std::path::{Path, PathBuf};
45use std::sync::Arc;
46
47use async_trait::async_trait;
48
49use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Stat, Subject};
50
51use super::store::{digest_to_filename, RafsStore};
52
53const QTDIR: u8 = 0x80;
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59enum TopDir {
60 Refs,
61 Bootstrap,
62 Blobs,
63}
64
65impl TopDir {
66 fn name(self) -> &'static str {
67 match self {
68 Self::Refs => "refs",
69 Self::Bootstrap => "bootstrap",
70 Self::Blobs => "blobs",
71 }
72 }
73
74 fn parse(s: &str) -> Option<Self> {
75 match s {
76 "refs" => Some(Self::Refs),
77 "bootstrap" => Some(Self::Bootstrap),
78 "blobs" => Some(Self::Blobs),
79 _ => None,
80 }
81 }
82}
83
84#[derive(Clone, Debug)]
86enum NodeKind {
87 Root,
89 TopDir(TopDir),
91 File { dir: TopDir, on_disk: PathBuf },
94}
95
96struct StoreFid {
98 kind: NodeKind,
99}
100
101pub struct RafsStoreMount {
104 store: Arc<RafsStore>,
105}
106
107impl RafsStoreMount {
108 pub fn new(store: Arc<RafsStore>) -> Self {
110 Self { store }
111 }
112
113 fn dir_path(&self, dir: TopDir) -> &Path {
115 match dir {
116 TopDir::Refs => self.store.refs_dir(),
117 TopDir::Bootstrap => self.store.bootstrap_dir(),
118 TopDir::Blobs => self.store.blobs_dir(),
119 }
120 }
121
122 fn resolve_leaf(&self, dir: TopDir, name: &str) -> Option<PathBuf> {
127 let base = self.dir_path(dir);
128
129 let direct = base.join(name);
132 if direct.exists() {
133 return Some(direct);
134 }
135
136 if dir == TopDir::Blobs && name.contains(':') {
138 let sanitized = base.join(digest_to_filename(name));
139 if sanitized.exists() {
140 return Some(sanitized);
141 }
142 }
143
144 None
145 }
146
147 fn read_leaf_bytes(&self, dir: TopDir, on_disk: &Path) -> Result<Vec<u8>, MountError> {
151 let path = if dir == TopDir::Refs {
152 std::fs::read_link(on_disk)
153 .map_err(|e| MountError::Io(format!("failed to resolve ref symlink: {e}")))?
154 } else {
155 on_disk.to_path_buf()
156 };
157 std::fs::read(&path)
158 .map_err(|e| MountError::Io(format!("failed to read {}: {e}", path.display())))
159 }
160
161 fn list_dir(&self, dir: TopDir) -> Result<Vec<DirEntry>, MountError> {
163 let base = self.dir_path(dir);
164 if !base.exists() {
165 return Ok(Vec::new());
166 }
167 let mut entries = Vec::new();
168 let read_dir = std::fs::read_dir(base)
169 .map_err(|e| MountError::Io(format!("failed to read {}: {e}", base.display())))?;
170 for entry in read_dir {
171 let entry = entry.map_err(|e| MountError::Io(e.to_string()))?;
172 let name = entry.file_name().to_string_lossy().into_owned();
173 let size = self.leaf_size(dir, &entry.path()).unwrap_or(0);
174 entries.push(DirEntry {
175 name,
176 is_dir: false,
177 size,
178 stat: None,
179 });
180 }
181 Ok(entries)
182 }
183
184 fn leaf_size(&self, dir: TopDir, on_disk: &Path) -> Option<u64> {
186 let path = if dir == TopDir::Refs {
187 std::fs::read_link(on_disk).ok()?
188 } else {
189 on_disk.to_path_buf()
190 };
191 std::fs::metadata(&path).ok().map(|m| m.len())
192 }
193}
194
195#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
196#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
197impl Mount for RafsStoreMount {
198 async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
199 let kind = match components {
203 [] => NodeKind::Root,
204 [top] => {
205 let dir =
206 TopDir::parse(top).ok_or_else(|| MountError::NotFound(components.join("/")))?;
207 NodeKind::TopDir(dir)
208 }
209 [top, name] => {
210 let dir =
211 TopDir::parse(top).ok_or_else(|| MountError::NotFound(components.join("/")))?;
212 let on_disk = self
213 .resolve_leaf(dir, name)
214 .ok_or_else(|| MountError::NotFound(components.join("/")))?;
215 NodeKind::File { dir, on_disk }
216 }
217 _ => return Err(MountError::NotFound(components.join("/"))),
218 };
219
220 Ok(Fid::new(StoreFid { kind }))
221 }
222
223 async fn open(&self, _fid: &mut Fid, mode: u8, _caller: &Subject) -> Result<(), MountError> {
224 if mode & 0x03 != 0 {
226 return Err(MountError::PermissionDenied(
227 "RafsStoreMount is read-only".into(),
228 ));
229 }
230 Ok(())
231 }
232
233 async fn read(
234 &self,
235 fid: &Fid,
236 offset: u64,
237 count: u32,
238 _caller: &Subject,
239 ) -> Result<Vec<u8>, MountError> {
240 let inner = fid
241 .downcast_ref::<StoreFid>()
242 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
243
244 let data = match &inner.kind {
245 NodeKind::File { dir, on_disk } => self.read_leaf_bytes(*dir, on_disk)?,
246 NodeKind::Root | NodeKind::TopDir(_) => {
247 return Err(MountError::IsDirectory("use readdir".into()));
248 }
249 };
250
251 let start = (offset as usize).min(data.len());
252 let end = start.saturating_add(count as usize).min(data.len());
253 Ok(data[start..end].to_vec())
254 }
255
256 async fn write(
257 &self,
258 _fid: &Fid,
259 _offset: u64,
260 _data: &[u8],
261 _caller: &Subject,
262 ) -> Result<u32, MountError> {
263 Err(MountError::NotSupported(
264 "RafsStoreMount is read-only; ingest goes through RafsStore's pull/gc/remove API"
265 .into(),
266 ))
267 }
268
269 async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
270 let inner = fid
271 .downcast_ref::<StoreFid>()
272 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
273
274 match &inner.kind {
275 NodeKind::Root => Ok([TopDir::Refs, TopDir::Bootstrap, TopDir::Blobs]
276 .into_iter()
277 .map(|d| DirEntry {
278 name: d.name().to_owned(),
279 is_dir: true,
280 size: 0,
281 stat: None,
282 })
283 .collect()),
284 NodeKind::TopDir(dir) => self.list_dir(*dir),
285 NodeKind::File { .. } => Err(MountError::NotDirectory(format!("{:?}", inner.kind))),
286 }
287 }
288
289 async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
290 let inner = fid
291 .downcast_ref::<StoreFid>()
292 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
293
294 let (name, qtype, size) = match &inner.kind {
295 NodeKind::Root => (String::new(), QTDIR, 0),
296 NodeKind::TopDir(dir) => (dir.name().to_owned(), QTDIR, 0),
297 NodeKind::File { dir, on_disk } => {
298 let name = on_disk
299 .file_name()
300 .map(|n| n.to_string_lossy().into_owned())
301 .unwrap_or_default();
302 let size = self.leaf_size(*dir, on_disk).unwrap_or(0);
303 (name, 0, size)
304 }
305 };
306
307 Ok(Stat::unknown_qid(qtype, size, name, 0))
308 }
309
310 async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
311}
312
313#[cfg(test)]
314#[allow(clippy::unwrap_used)]
315mod tests {
316 use super::*;
317 use crate::config::ImageConfig;
318
319 fn subject() -> Subject {
320 Subject::anonymous()
321 }
322
323 fn make_store_with_fake_image() -> (tempfile::TempDir, Arc<RafsStore>, &'static str) {
329 let tmp = tempfile::tempdir().unwrap();
330 let root = tmp.path();
331 let config = ImageConfig {
332 blobs_dir: root.join("blobs"),
333 bootstrap_dir: root.join("bootstrap"),
334 refs_dir: root.join("refs"),
335 cache_dir: root.join("cache"),
336 ..Default::default()
337 };
338 for dir in [
339 &config.blobs_dir,
340 &config.bootstrap_dir,
341 &config.refs_dir,
342 &config.cache_dir,
343 ] {
344 std::fs::create_dir_all(dir).unwrap();
345 }
346
347 let image_id = "sha256:deadbeef";
348 let digest_filename = digest_to_filename(image_id); std::fs::write(config.blobs_dir.join(&digest_filename), b"blob-bytes").unwrap();
352
353 let metadata = super::super::store::ImageMetadata {
355 image_ref: "example.com/repo:tag".to_owned(),
356 image_id: image_id.to_owned(),
357 config_digest: image_id.to_owned(),
358 layers: vec![image_id.to_owned()],
359 host: "example.com".to_owned(),
360 repository: "repo".to_owned(),
361 };
362 let metadata_path = config.bootstrap_dir.join(format!("{digest_filename}.json"));
363 std::fs::write(&metadata_path, serde_json::to_vec(&metadata).unwrap()).unwrap();
364
365 let ref_name = "example.com_repo_tag";
367 std::os::unix::fs::symlink(&metadata_path, config.refs_dir.join(ref_name)).unwrap();
368
369 let store = Arc::new(RafsStore::new(config).unwrap());
370 (tmp, store, "example.com_repo_tag")
371 }
372
373 #[tokio::test]
374 async fn root_lists_three_top_dirs() {
375 let (_tmp, store, _ref_name) = make_store_with_fake_image();
376 let mount = RafsStoreMount::new(store);
377
378 let fid = mount.walk(&[], &subject()).await.unwrap();
379 let entries = mount.readdir(&fid, &subject()).await.unwrap();
380 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
381 assert!(names.contains(&"refs"));
382 assert!(names.contains(&"bootstrap"));
383 assert!(names.contains(&"blobs"));
384 assert!(entries.iter().all(|e| e.is_dir));
385 }
386
387 #[tokio::test]
388 async fn refs_dir_lists_the_ref_and_reads_pointed_metadata() {
389 let (_tmp, store, ref_name) = make_store_with_fake_image();
390 let mount = RafsStoreMount::new(store);
391
392 let dir_fid = mount.walk(&["refs"], &subject()).await.unwrap();
393 let entries = mount.readdir(&dir_fid, &subject()).await.unwrap();
394 assert_eq!(entries.len(), 1);
395 assert_eq!(entries[0].name, ref_name);
396
397 let mut leaf_fid = mount.walk(&["refs", ref_name], &subject()).await.unwrap();
398 mount.open(&mut leaf_fid, 0, &subject()).await.unwrap();
399 let data = mount.read(&leaf_fid, 0, 4096, &subject()).await.unwrap();
400 let text = String::from_utf8(data).unwrap();
401 assert!(text.contains("example.com/repo:tag"), "got: {text}");
402 }
403
404 #[tokio::test]
405 async fn blobs_addressable_by_on_disk_name_and_oci_digest() {
406 let (_tmp, store, _ref_name) = make_store_with_fake_image();
407 let mount = RafsStoreMount::new(store);
408
409 let mut fid1 = mount
411 .walk(&["blobs", "sha256_deadbeef"], &subject())
412 .await
413 .unwrap();
414 mount.open(&mut fid1, 0, &subject()).await.unwrap();
415 let data1 = mount.read(&fid1, 0, 4096, &subject()).await.unwrap();
416 assert_eq!(data1, b"blob-bytes");
417
418 let mut fid2 = mount
420 .walk(&["blobs", "sha256:deadbeef"], &subject())
421 .await
422 .unwrap();
423 mount.open(&mut fid2, 0, &subject()).await.unwrap();
424 let data2 = mount.read(&fid2, 0, 4096, &subject()).await.unwrap();
425 assert_eq!(data2, b"blob-bytes");
426 }
427
428 #[tokio::test]
429 async fn bootstrap_dir_lists_metadata_file() {
430 let (_tmp, store, _ref_name) = make_store_with_fake_image();
431 let mount = RafsStoreMount::new(store);
432
433 let fid = mount.walk(&["bootstrap"], &subject()).await.unwrap();
434 let entries = mount.readdir(&fid, &subject()).await.unwrap();
435 assert_eq!(entries.len(), 1);
436 assert!(entries[0].name.ends_with(".json"));
437 }
438
439 #[tokio::test]
440 async fn read_respects_offset_and_count() {
441 let (_tmp, store, _ref_name) = make_store_with_fake_image();
442 let mount = RafsStoreMount::new(store);
443
444 let mut fid = mount
445 .walk(&["blobs", "sha256_deadbeef"], &subject())
446 .await
447 .unwrap();
448 mount.open(&mut fid, 0, &subject()).await.unwrap();
449 let data = mount.read(&fid, 5, 3, &subject()).await.unwrap();
450 assert_eq!(data, b"byt"); }
452
453 #[tokio::test]
454 async fn unknown_top_dir_not_found() {
455 let (_tmp, store, _ref_name) = make_store_with_fake_image();
456 let mount = RafsStoreMount::new(store);
457 let result = mount.walk(&["nope"], &subject()).await;
458 assert!(matches!(result, Err(MountError::NotFound(_))));
459 }
460
461 #[tokio::test]
462 async fn unknown_blob_not_found() {
463 let (_tmp, store, _ref_name) = make_store_with_fake_image();
464 let mount = RafsStoreMount::new(store);
465 let result = mount.walk(&["blobs", "sha256:missing"], &subject()).await;
466 assert!(matches!(result, Err(MountError::NotFound(_))));
467 }
468
469 #[tokio::test]
470 async fn write_is_rejected() {
471 let (_tmp, store, _ref_name) = make_store_with_fake_image();
472 let mount = RafsStoreMount::new(store);
473 let mut fid = mount
474 .walk(&["blobs", "sha256_deadbeef"], &subject())
475 .await
476 .unwrap();
477 mount.open(&mut fid, 0, &subject()).await.unwrap();
478 let result = mount.write(&fid, 0, b"x", &subject()).await;
479 assert!(matches!(result, Err(MountError::NotSupported(_))));
480 }
481
482 #[tokio::test]
483 async fn open_for_write_rejected() {
484 let (_tmp, store, _ref_name) = make_store_with_fake_image();
485 let mount = RafsStoreMount::new(store);
486 let mut fid = mount
487 .walk(&["blobs", "sha256_deadbeef"], &subject())
488 .await
489 .unwrap();
490 let result = mount
491 .open(&mut fid, hyprstream_vfs::OWRITE, &subject())
492 .await;
493 assert!(matches!(result, Err(MountError::PermissionDenied(_))));
494 }
495
496 #[tokio::test]
497 async fn stat_root_is_dir() {
498 let (_tmp, store, _ref_name) = make_store_with_fake_image();
499 let mount = RafsStoreMount::new(store);
500 let fid = mount.walk(&[], &subject()).await.unwrap();
501 let st = mount.stat(&fid, &subject()).await.unwrap();
502 assert_eq!(st.qtype, QTDIR);
503 }
504
505 #[tokio::test]
506 async fn stat_blob_reports_size() {
507 let (_tmp, store, _ref_name) = make_store_with_fake_image();
508 let mount = RafsStoreMount::new(store);
509 let fid = mount
510 .walk(&["blobs", "sha256_deadbeef"], &subject())
511 .await
512 .unwrap();
513 let st = mount.stat(&fid, &subject()).await.unwrap();
514 assert_eq!(st.size, b"blob-bytes".len() as u64);
515 assert_eq!(st.qtype, 0);
516 }
517}