1use parking_lot::Mutex;
46
47use crate::mount::{DirEntry, MountError};
48
49#[cfg(not(target_arch = "wasm32"))]
54pub type DevFuture<'a, T> = futures::future::BoxFuture<'a, T>;
57
58#[cfg(target_arch = "wasm32")]
59pub type DevFuture<'a, T> = futures::future::LocalBoxFuture<'a, T>;
62
63#[derive(Default)]
75pub struct DevFileState {
76 latched: Mutex<Vec<u8>>,
77}
78
79impl DevFileState {
80 pub fn new() -> Self {
82 Self::default()
83 }
84
85 pub fn latch(&self, data: Vec<u8>) {
87 *self.latched.lock() = data;
88 }
89
90 pub fn latched(&self) -> Vec<u8> {
92 self.latched.lock().clone()
93 }
94}
95
96pub fn read_from_offset(data: &[u8], offset: u64) -> Vec<u8> {
102 let start = offset as usize;
103 if start >= data.len() {
104 Vec::new()
105 } else {
106 data[start..].to_vec()
107 }
108}
109
110pub struct ControlFile<F> {
141 handler: F,
142}
143
144impl<F> ControlFile<F>
145where
146 F: Fn(Vec<u8>) -> DevFuture<'static, Result<Vec<u8>, MountError>> + Send + Sync,
147{
148 pub fn new(handler: F) -> Self {
150 Self { handler }
151 }
152
153 pub fn new_fid(&self) -> DevFileState {
155 DevFileState::new()
156 }
157
158 pub async fn handle_write(&self, state: &DevFileState, data: &[u8]) -> Result<u32, MountError> {
163 let len = data.len();
164 let result = (self.handler)(data.to_vec()).await?;
165 state.latch(result);
166 Ok(len as u32)
167 }
168
169 pub fn handle_read(&self, state: &DevFileState, offset: u64) -> Vec<u8> {
172 read_from_offset(&state.latched(), offset)
173 }
174}
175
176pub struct FieldFile<G, S = NoSetter> {
195 get: G,
196 set: S,
197}
198
199#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
204#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
205pub trait FieldSetter: Send + Sync {
206 async fn set(&self, data: Vec<u8>) -> Result<(), MountError>;
208}
209
210pub struct NoSetter;
212
213#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
214#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
215impl FieldSetter for NoSetter {
216 async fn set(&self, _data: Vec<u8>) -> Result<(), MountError> {
217 Err(MountError::NotSupported("field is read-only".into()))
218 }
219}
220
221#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
222#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
223impl<S> FieldSetter for S
224where
225 S: Fn(Vec<u8>) -> DevFuture<'static, Result<(), MountError>> + Send + Sync,
226{
227 async fn set(&self, data: Vec<u8>) -> Result<(), MountError> {
228 (self)(data).await
229 }
230}
231
232impl<G> FieldFile<G, NoSetter>
233where
234 G: Fn() -> DevFuture<'static, Option<Vec<u8>>> + Send + Sync,
235{
236 pub fn read_only(get: G) -> Self {
240 Self { get, set: NoSetter }
241 }
242}
243
244impl<G, S> FieldFile<G, S>
245where
246 G: Fn() -> DevFuture<'static, Option<Vec<u8>>> + Send + Sync,
247 S: Fn(Vec<u8>) -> DevFuture<'static, Result<(), MountError>> + Send + Sync,
248{
249 pub fn read_write(get: G, set: S) -> Self {
251 Self { get, set }
252 }
253}
254
255impl<G, S> FieldFile<G, S>
256where
257 G: Fn() -> DevFuture<'static, Option<Vec<u8>>> + Send + Sync,
258 S: FieldSetter,
259{
260 pub async fn handle_read(&self, offset: u64, name: &str) -> Result<Vec<u8>, MountError> {
262 let data = (self.get)()
263 .await
264 .ok_or_else(|| MountError::NotFound(name.to_string()))?;
265 Ok(read_from_offset(&data, offset))
266 }
267
268 pub async fn handle_write(&self, data: &[u8]) -> Result<u32, MountError> {
270 self.set.set(data.to_vec()).await?;
271 Ok(data.len() as u32)
272 }
273}
274
275pub struct DynamicDir<L, G> {
289 list: L,
290 get: G,
291}
292
293impl<L, G> DynamicDir<L, G>
294where
295 L: Fn() -> DevFuture<'static, Vec<String>> + Send + Sync,
296 G: Fn(String) -> DevFuture<'static, Result<Option<Vec<u8>>, MountError>> + Send + Sync,
297{
298 pub fn new(list: L, get: G) -> Self {
308 Self { list, get }
309 }
310
311 pub async fn readdir(&self) -> Vec<DirEntry> {
314 (self.list)()
315 .await
316 .into_iter()
317 .map(|name| DirEntry {
318 name,
319 is_dir: false,
320 size: 0,
321 stat: None,
322 })
323 .collect()
324 }
325
326 pub async fn read(&self, name: &str, offset: u64) -> Result<Vec<u8>, MountError> {
330 let data = (self.get)(name.to_string())
331 .await?
332 .ok_or_else(|| MountError::NotFound(name.to_string()))?;
333 Ok(read_from_offset(&data, offset))
334 }
335}
336
337#[cfg(test)]
342#[allow(clippy::unwrap_used)]
343mod tests {
344 use super::*;
345 use crate::mount::{Fid, Mount, Stat};
346 use async_trait::async_trait;
347 use hyprstream_rpc::Subject;
348 use std::sync::Arc;
349 use tokio::sync::Mutex as AsyncMutex;
350
351 fn subj() -> Subject {
352 Subject::new("tester")
353 }
354
355 #[tokio::test]
358 async fn control_file_write_then_read_latches_result() {
359 let ctl = ControlFile::new(|data: Vec<u8>| {
360 let s = String::from_utf8_lossy(&data).into_owned();
361 Box::pin(async move { Ok(format!("echo: {s}").into_bytes()) }) as DevFuture<'static, _>
362 });
363 let state = ctl.new_fid();
364
365 assert!(ctl.handle_read(&state, 0).is_empty());
367
368 let n = ctl.handle_write(&state, b"hello").await.unwrap();
369 assert_eq!(n, 5);
370
371 let out = ctl.handle_read(&state, 0);
372 assert_eq!(out, b"echo: hello");
373 }
374
375 #[tokio::test]
376 async fn control_file_offset_slices_latched_result() {
377 let ctl = ControlFile::new(|_data: Vec<u8>| {
378 Box::pin(async move { Ok(b"0123456789".to_vec()) }) as DevFuture<'static, _>
379 });
380 let state = ctl.new_fid();
381 ctl.handle_write(&state, b"x").await.unwrap();
382 assert_eq!(ctl.handle_read(&state, 5), b"56789");
383 assert_eq!(ctl.handle_read(&state, 100), b"");
384 }
385
386 #[tokio::test]
387 async fn control_file_handler_error_propagates_not_latched() {
388 let ctl = ControlFile::new(|_data: Vec<u8>| {
389 Box::pin(async move { Err(MountError::Io("boom".into())) }) as DevFuture<'static, _>
390 });
391 let state = ctl.new_fid();
392 let res = ctl.handle_write(&state, b"x").await;
393 assert!(res.is_err());
394 assert!(ctl.handle_read(&state, 0).is_empty());
396 }
397
398 #[tokio::test]
399 async fn control_file_second_write_replaces_latch() {
400 let ctl = ControlFile::new(|data: Vec<u8>| {
401 Box::pin(async move { Ok(data) }) as DevFuture<'static, _>
402 });
403 let state = ctl.new_fid();
404 ctl.handle_write(&state, b"first").await.unwrap();
405 assert_eq!(ctl.handle_read(&state, 0), b"first");
406 ctl.handle_write(&state, b"second").await.unwrap();
407 assert_eq!(ctl.handle_read(&state, 0), b"second");
408 }
409
410 #[tokio::test]
413 async fn field_file_read_only_get() {
414 let field = FieldFile::read_only(|| {
415 Box::pin(async { Some(b"42".to_vec()) }) as DevFuture<'static, _>
416 });
417 let out = field.handle_read(0, "x").await.unwrap();
418 assert_eq!(out, b"42");
419 }
420
421 #[tokio::test]
422 async fn field_file_read_only_missing_is_not_found() {
423 let field = FieldFile::read_only(|| Box::pin(async { None }) as DevFuture<'static, _>);
424 let res = field.handle_read(0, "missing").await;
425 assert!(matches!(res, Err(MountError::NotFound(_))));
426 }
427
428 #[tokio::test]
429 async fn field_file_read_only_rejects_write() {
430 let field = FieldFile::read_only(|| {
431 Box::pin(async { Some(b"v".to_vec()) }) as DevFuture<'static, _>
432 });
433 let res = field.handle_write(b"new").await;
434 assert!(matches!(res, Err(MountError::NotSupported(_))));
435 }
436
437 #[tokio::test]
438 async fn field_file_read_write_round_trips_through_shared_state() {
439 let store: Arc<AsyncMutex<String>> = Arc::new(AsyncMutex::new("init".to_string()));
440
441 let get_store = store.clone();
442 let set_store = store.clone();
443 let field = FieldFile::read_write(
444 move || {
445 let store = get_store.clone();
446 Box::pin(async move { Some(store.lock().await.clone().into_bytes()) })
447 as DevFuture<'static, _>
448 },
449 move |data: Vec<u8>| {
450 let store = set_store.clone();
451 Box::pin(async move {
452 *store.lock().await = String::from_utf8_lossy(&data).into_owned();
453 Ok(())
454 }) as DevFuture<'static, _>
455 },
456 );
457
458 assert_eq!(field.handle_read(0, "f").await.unwrap(), b"init");
459 let n = field.handle_write(b"updated").await.unwrap();
460 assert_eq!(n, 7);
461 assert_eq!(field.handle_read(0, "f").await.unwrap(), b"updated");
462 }
463
464 #[tokio::test]
467 async fn dynamic_dir_lists_and_reads_names() {
468 let dir = DynamicDir::new(
469 || Box::pin(async { vec!["a".to_string(), "b".to_string()] }) as DevFuture<'static, _>,
470 |name: String| {
471 Box::pin(async move {
472 Ok(match name.as_str() {
473 "a" => Some(b"1".to_vec()),
474 "b" => Some(b"2".to_vec()),
475 _ => None,
476 })
477 }) as DevFuture<'static, _>
478 },
479 );
480
481 let entries = dir.readdir().await;
482 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
483 assert_eq!(names, vec!["a", "b"]);
484 assert!(entries.iter().all(|e| !e.is_dir));
485
486 assert_eq!(dir.read("a", 0).await.unwrap(), b"1");
487 assert_eq!(dir.read("b", 0).await.unwrap(), b"2");
488 assert!(matches!(
489 dir.read("z", 0).await,
490 Err(MountError::NotFound(_))
491 ));
492 }
493
494 #[tokio::test]
495 async fn dynamic_dir_getter_error_propagates_distinct_from_not_found() {
496 let dir = DynamicDir::new(
499 || Box::pin(async { vec!["a".to_string()] }) as DevFuture<'static, _>,
500 |_name: String| {
501 Box::pin(async { Err(MountError::Io("backend gone".into())) })
502 as DevFuture<'static, _>
503 },
504 );
505 assert!(matches!(dir.read("a", 0).await, Err(MountError::Io(_))));
506 }
507
508 enum DemoFidKind {
511 Root,
512 Eval,
513 VarsDir,
514 Var(String),
515 }
516
517 struct DemoFid {
518 kind: DemoFidKind,
519 ctl_state: DevFileState,
520 }
521
522 type CtlHandler =
523 Box<dyn Fn(Vec<u8>) -> DevFuture<'static, Result<Vec<u8>, MountError>> + Send + Sync>;
524 type ListFn = Box<dyn Fn() -> DevFuture<'static, Vec<String>> + Send + Sync>;
525 type GetFn = Box<
526 dyn Fn(String) -> DevFuture<'static, Result<Option<Vec<u8>>, MountError>> + Send + Sync,
527 >;
528
529 struct DemoMount {
534 ctl: ControlFile<CtlHandler>,
535 vars: DynamicDir<ListFn, GetFn>,
536 }
537
538 fn uppercase_ctl(data: Vec<u8>) -> DevFuture<'static, Result<Vec<u8>, MountError>> {
539 let s = String::from_utf8_lossy(&data).to_uppercase();
540 Box::pin(async move { Ok(s.into_bytes()) })
541 }
542
543 impl DemoMount {
544 fn new() -> Self {
545 let ctl = ControlFile::new(Box::new(uppercase_ctl) as CtlHandler);
546
547 let vars = DynamicDir::new(
548 Box::new(|| {
549 Box::pin(async { vec!["x".to_string(), "y".to_string()] })
550 as DevFuture<'static, _>
551 }) as ListFn,
552 Box::new(|name: String| {
553 Box::pin(async move {
554 Ok(match name.as_str() {
555 "x" => Some(b"42".to_vec()),
556 "y" => Some(b"hello".to_vec()),
557 _ => None,
558 })
559 }) as DevFuture<'static, _>
560 }) as GetFn,
561 );
562
563 Self { ctl, vars }
564 }
565 }
566
567 #[async_trait]
568 impl Mount for DemoMount {
569 async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
570 let kind = match components {
571 [] => DemoFidKind::Root,
572 ["eval"] => DemoFidKind::Eval,
573 ["vars"] => DemoFidKind::VarsDir,
574 ["vars", name] => DemoFidKind::Var((*name).to_owned()),
575 _ => return Err(MountError::NotFound(components.join("/"))),
576 };
577 Ok(Fid::new(DemoFid {
578 kind,
579 ctl_state: DevFileState::new(),
580 }))
581 }
582
583 async fn open(
584 &self,
585 _fid: &mut Fid,
586 _mode: u8,
587 _caller: &Subject,
588 ) -> Result<(), MountError> {
589 Ok(())
590 }
591
592 async fn read(
593 &self,
594 fid: &Fid,
595 offset: u64,
596 _count: u32,
597 _caller: &Subject,
598 ) -> Result<Vec<u8>, MountError> {
599 let inner = fid
600 .downcast_ref::<DemoFid>()
601 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
602 match &inner.kind {
603 DemoFidKind::Eval => Ok(self.ctl.handle_read(&inner.ctl_state, offset)),
604 DemoFidKind::Var(name) => self.vars.read(name, offset).await,
605 DemoFidKind::Root | DemoFidKind::VarsDir => {
606 Err(MountError::IsDirectory("use readdir".into()))
607 }
608 }
609 }
610
611 async fn write(
612 &self,
613 fid: &Fid,
614 _offset: u64,
615 data: &[u8],
616 _caller: &Subject,
617 ) -> Result<u32, MountError> {
618 let inner = fid
619 .downcast_ref::<DemoFid>()
620 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
621 match &inner.kind {
622 DemoFidKind::Eval => self.ctl.handle_write(&inner.ctl_state, data).await,
623 _ => Err(MountError::NotSupported("read-only".into())),
624 }
625 }
626
627 async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
628 let inner = fid
629 .downcast_ref::<DemoFid>()
630 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
631 match &inner.kind {
632 DemoFidKind::Root => Ok(vec![
633 DirEntry {
634 name: "eval".into(),
635 is_dir: false,
636 size: 0,
637 stat: None,
638 },
639 DirEntry {
640 name: "vars".into(),
641 is_dir: true,
642 size: 0,
643 stat: None,
644 },
645 ]),
646 DemoFidKind::VarsDir => Ok(self.vars.readdir().await),
647 _ => Err(MountError::NotDirectory("not a directory".into())),
648 }
649 }
650
651 async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
652 let inner = fid
653 .downcast_ref::<DemoFid>()
654 .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
655 let (name, qtype) = match &inner.kind {
656 DemoFidKind::Root => ("demo".to_string(), 0x80),
657 DemoFidKind::Eval => ("eval".to_string(), 0),
658 DemoFidKind::VarsDir => ("vars".to_string(), 0x80),
659 DemoFidKind::Var(n) => (n.clone(), 0),
660 };
661 Ok(Stat {
662 qtype,
663 version: 0,
664 path: 0,
665 size: 0,
666 name,
667 mtime: 0,
668 })
669 }
670
671 async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
672 }
673
674 #[tokio::test]
675 async fn demo_mount_eval_ctl_round_trip() {
676 let mount = DemoMount::new();
677 let s = subj();
678 let mut fid = mount.walk(&["eval"], &s).await.unwrap();
679 mount.open(&mut fid, 1, &s).await.unwrap();
680 mount.write(&fid, 0, b"hello", &s).await.unwrap();
681 let out = mount.read(&fid, 0, 4096, &s).await.unwrap();
682 assert_eq!(out, b"HELLO");
683 }
684
685 #[tokio::test]
686 async fn demo_mount_vars_dir_listing_and_leaves() {
687 let mount = DemoMount::new();
688 let s = subj();
689
690 let dir_fid = mount.walk(&["vars"], &s).await.unwrap();
691 let entries = mount.readdir(&dir_fid, &s).await.unwrap();
692 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
693 assert!(names.contains(&"x"));
694 assert!(names.contains(&"y"));
695
696 let x_fid = mount.walk(&["vars", "x"], &s).await.unwrap();
697 let out = mount.read(&x_fid, 0, 4096, &s).await.unwrap();
698 assert_eq!(out, b"42");
699
700 let missing = mount.walk(&["vars", "z"], &s).await.unwrap();
701 assert!(mount.read(&missing, 0, 4096, &s).await.is_err());
702 }
703
704 #[tokio::test]
705 async fn demo_mount_readdir_root() {
706 let mount = DemoMount::new();
707 let s = subj();
708 let fid = mount.walk(&[], &s).await.unwrap();
709 let entries = mount.readdir(&fid, &s).await.unwrap();
710 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
711 assert!(names.contains(&"eval"));
712 assert!(names.contains(&"vars"));
713 }
714}