Skip to main content

hyprstream_rpc_std/
vfs_mount.rs

1//! Generic VFS Mount driven by codegen — no per-service manual wrappers.
2//!
3//! `ServiceMount` uses the proc-macro-generated `dispatch()`, `schema_metadata()`,
4//! and `render_doc()` functions to serve any service through the VFS. All
5//! serialization, method routing, and documentation are codegen-driven.
6//!
7//! Mount points:
8//!   /srv/{service}     → ServiceMount (ctl for mutations, cat for queries)
9//!   /srv/{service}/doc → DocMount (man pages from schema annotations)
10//!   /wanix             → WanixMount (Wanix-native VFS via 9P2000.L over DMA;
11//!                        optional — mounted only when running under Wanix,
12//!                        see [`mount_wanix`]). #409/#391.
13
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::sync::Arc;
16
17use parking_lot::Mutex;
18
19use async_trait::async_trait;
20use hyprstream_rpc::rpc_client::RpcClient;
21use hyprstream_rpc::Subject;
22use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Stat};
23
24// ============================================================================
25// RpcClient is already Send + Sync — no wrapper needed.
26// ============================================================================
27
28// ============================================================================
29// Fid state
30// ============================================================================
31
32#[derive(Clone, Debug)]
33struct VfsFidState {
34    path: Vec<String>,
35    opened: bool,
36}
37
38/// Apply offset+count slicing to a read result (9P semantics).
39fn slice_read(data: Vec<u8>, offset: u64, count: u32) -> Vec<u8> {
40    let start = (offset as usize).min(data.len());
41    let end = (start + count as usize).min(data.len());
42    data[start..end].to_vec()
43}
44
45/// Generate an ephemeral ECDH keypair as 64 bytes: `[secret_scalar(32) | pubkey(32)]`.
46///
47/// Same layout the streaming handshake expects (secret first, pubkey at `[32..64]`),
48/// built directly from `DefaultKeyExchange` so it works on native and wasm alike.
49fn ephemeral_keypair_64() -> Result<Vec<u8>, String> {
50    use hyprstream_rpc::crypto::key_exchange::DefaultKeyExchange;
51    use hyprstream_rpc::crypto::KeyExchange;
52
53    let (secret, public) = DefaultKeyExchange::generate_keypair();
54    let mut out = Vec::with_capacity(64);
55    out.extend_from_slice(secret.scalar().as_bytes());
56    out.extend_from_slice(&DefaultKeyExchange::pubkey_to_bytes(&public));
57    if out.len() != 64 {
58        return Err(format!("ephemeral keypair wrong length: {}", out.len()));
59    }
60    Ok(out)
61}
62
63// ============================================================================
64// CtlResponseCache — stores write→read response for ctl pattern
65// ============================================================================
66
67struct CtlResponseCache(Mutex<Option<Vec<u8>>>);
68
69impl CtlResponseCache {
70    fn new() -> Self {
71        Self(Mutex::new(None))
72    }
73    fn take(&self) -> Option<Vec<u8>> {
74        self.0.lock().take()
75    }
76    fn set(&self, data: Vec<u8>) {
77        *self.0.lock() = Some(data);
78    }
79}
80
81/// Monotonic counter for request IDs.
82struct IdCounter(AtomicU64);
83impl IdCounter {
84    fn new() -> Self {
85        Self(AtomicU64::new(1))
86    }
87    fn next(&self) -> u64 {
88        self.0.fetch_add(1, Ordering::Relaxed)
89    }
90}
91
92// ============================================================================
93// GenericServiceMount — codegen-driven mount for any service
94// ============================================================================
95
96/// Result from service dispatch — normal response or stream setup.
97pub enum ServiceDispatchResult {
98    /// Normal JSON response string.
99    Response(String),
100    /// Streaming — the VERIFIED-capnp `StreamInfo` library type (decoded +
101    /// COSE-verified upstream, carried typed — NOT a JSON string to re-parse,
102    /// #468) + ephemeral keypair for ECDH.
103    Stream {
104        info: Box<hyprstream_rpc::stream_info::StreamInfo>,
105        /// 64 bytes: [secret(32) | pubkey(32)]
106        ephemeral_keypair: Vec<u8>,
107    },
108}
109
110/// Trait for service-specific dispatch. Implemented via macro from generated code.
111#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
112#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
113pub trait ServiceDispatch: Send + Sync {
114    async fn dispatch(
115        &self,
116        method: &str,
117        args_json: &str,
118        client: &dyn RpcClient,
119    ) -> Result<ServiceDispatchResult, String>;
120    fn metadata(
121        &self,
122    ) -> (
123        &'static str,
124        &'static [hyprstream_rpc::metadata::MethodMeta],
125    );
126}
127
128/// Generic VFS mount driven by a ServiceDispatch implementation.
129pub struct GenericServiceMount {
130    client: Arc<dyn RpcClient>,
131    service: Box<dyn ServiceDispatch>,
132    next_id: IdCounter,
133    ctl_response: CtlResponseCache,
134    stream_registry: std::sync::Arc<crate::stream_mount::StreamRegistry>,
135}
136
137impl GenericServiceMount {
138    pub fn new(
139        client: Arc<dyn RpcClient>,
140        service: Box<dyn ServiceDispatch>,
141        stream_registry: std::sync::Arc<crate::stream_mount::StreamRegistry>,
142    ) -> Self {
143        Self {
144            client,
145            service,
146            next_id: IdCounter::new(),
147            ctl_response: CtlResponseCache::new(),
148            stream_registry,
149        }
150    }
151
152    fn next_id(&self) -> u64 {
153        self.next_id.next()
154    }
155}
156
157#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
158#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
159impl Mount for GenericServiceMount {
160    async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
161        Ok(Fid::new(VfsFidState {
162            path: components.iter().map(|s| s.to_string()).collect(),
163            opened: false,
164        }))
165    }
166
167    async fn open(&self, fid: &mut Fid, _mode: u8, _caller: &Subject) -> Result<(), MountError> {
168        if let Some(state) = fid.downcast_mut::<VfsFidState>() {
169            state.opened = true;
170        }
171        Ok(())
172    }
173
174    async fn read(
175        &self,
176        fid: &Fid,
177        offset: u64,
178        count: u32,
179        _caller: &Subject,
180    ) -> Result<Vec<u8>, MountError> {
181        // Check for ctl response first (from previous write)
182        if let Some(resp) = self.ctl_response.take() {
183            return Ok(slice_read(resp, offset, count));
184        }
185
186        let state = fid
187            .downcast_ref::<VfsFidState>()
188            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
189
190        if state.path.is_empty() {
191            // After ctl write→read, second read returns empty (EOF)
192            // For plain cat on root, this is also correct (it's a directory)
193            return Ok(Vec::new());
194        }
195
196        // cat /srv/{service}/{method} → dispatch query method with empty args
197        let method = &state.path[0];
198        match self
199            .service
200            .dispatch(method, "{}", self.client.as_ref())
201            .await
202            .map_err(MountError::Io)?
203        {
204            ServiceDispatchResult::Response(json) => {
205                Ok(slice_read(json.into_bytes(), offset, count))
206            }
207            ServiceDispatchResult::Stream { .. } => Err(MountError::NotSupported(
208                "use ctl to start streams, then read from /stream/{topic}/data".into(),
209            )),
210        }
211    }
212
213    async fn write(
214        &self,
215        fid: &Fid,
216        _offset: u64,
217        data: &[u8],
218        _caller: &Subject,
219    ) -> Result<u32, MountError> {
220        let state = fid
221            .downcast_ref::<VfsFidState>()
222            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
223
224        // ctl pattern: data = "command {json_args}" or "command json_args"
225        // Tcl brace quoting strips outer {} so we may receive bare JSON fields.
226        let data_str = std::str::from_utf8(data).unwrap_or("").trim();
227
228        // Strip shell quotes from around JSON if present
229        let stripped = data_str.trim_end_matches('\'').trim_end_matches('"');
230
231        let (cmd, args_owned);
232        if let Some(brace) = stripped.find('{') {
233            let cmd_part = stripped[..brace]
234                .trim()
235                .trim_end_matches('\'')
236                .trim_end_matches('"')
237                .trim();
238            let args_part = &stripped[brace..];
239            cmd = if cmd_part.is_empty() {
240                state.path.first().map(|s| s.as_str()).unwrap_or("")
241            } else {
242                cmd_part
243            };
244            args_owned = args_part.to_owned();
245        } else if stripped.contains(':') && stripped.contains('"') {
246            // Looks like stripped JSON (Tcl brace quoting removed outer {})
247            // Split on first whitespace to find command, rest is bare JSON
248            let (c, rest) = stripped
249                .split_once(char::is_whitespace)
250                .unwrap_or((stripped, ""));
251            cmd = c.trim();
252            // Re-wrap bare JSON fields with braces
253            args_owned = format!("{{{}}}", rest.trim());
254        } else {
255            cmd = if stripped.is_empty() {
256                state.path.first().map(|s| s.as_str()).unwrap_or("")
257            } else {
258                stripped
259            };
260            args_owned = "{}".to_owned();
261        };
262        let args_str = args_owned.as_str();
263
264        let dispatch_result = self
265            .service
266            .dispatch(cmd, args_str, self.client.as_ref())
267            .await
268            .map_err(MountError::Io)?;
269
270        let resp = match dispatch_result {
271            ServiceDispatchResult::Response(json) => json.into_bytes(),
272            ServiceDispatchResult::Stream {
273                info,
274                ephemeral_keypair,
275            } => {
276                // #468: `info` is the VERIFIED-capnp StreamInfo library type carried
277                // typed through dispatch (decoded + COSE-verified upstream) — no
278                // serde_json round-trip / re-parse at this boundary.
279                //
280                // The dispatch already sent the streaming request and got StreamInfo back.
281                // Now we open a stream handle. open_stream() would do the full flow
282                // (send + ECDH + subscribe), but dispatch already sent the request, so we
283                // do the ECDH + subscribe part here using the verified StreamInfo.
284                let client_secret = &ephemeral_keypair[..32];
285                let client_pubkey = &ephemeral_keypair[32..64];
286                let mut secret_32 = [0u8; 32];
287                let mut pubkey_32 = [0u8; 32];
288                secret_32.copy_from_slice(client_secret);
289                pubkey_32.copy_from_slice(client_pubkey);
290
291                // Open verified stream handle via RpcClient
292                let handle = self
293                    .client
294                    .open_stream_from_info(*info.clone(), secret_32, pubkey_32)
295                    .await
296                    .map_err(|e| MountError::Io(format!("open stream: {e}")))?;
297
298                let topic = handle.stream_id().to_owned();
299
300                self.stream_registry.register(
301                    topic.clone(),
302                    crate::stream_mount::StreamEntry::stream(
303                        Some(handle),
304                        _caller.name().unwrap_or("anonymous").to_owned(),
305                    ),
306                );
307
308                let result = serde_json::json!({
309                    "streamId": info.stream_id,
310                    "topic": topic,
311                });
312                serde_json::to_string(&result)
313                    .unwrap_or_default()
314                    .into_bytes()
315            }
316        };
317        let len = resp.len() as u32;
318        self.ctl_response.set(resp);
319        Ok(len)
320    }
321
322    async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
323        let state = fid
324            .downcast_ref::<VfsFidState>()
325            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
326
327        if state.path.is_empty() {
328            // Root: list methods from metadata
329            let (_, methods) = self.service.metadata();
330            Ok(methods
331                .iter()
332                .filter(|m| !m.hidden)
333                .map(|m| DirEntry {
334                    name: m.name.to_owned(),
335                    is_dir: m.is_scoped,
336                    size: 0,
337                    stat: None,
338                })
339                .collect())
340        } else {
341            Err(MountError::NotDirectory(state.path.join("/")))
342        }
343    }
344
345    async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
346        let state = fid
347            .downcast_ref::<VfsFidState>()
348            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
349        let (svc_name, _) = self.service.metadata();
350        let name = state.path.last().map(|s| s.as_str()).unwrap_or(svc_name);
351        Ok(Stat::unknown_qid(
352            if state.path.is_empty() { 0x80 } else { 0 },
353            0,
354            name.to_string(),
355            0,
356        ))
357    }
358
359    async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
360}
361
362// ============================================================================
363// DocMount — serves man pages from compiled schema metadata
364// ============================================================================
365
366pub struct DocMount {
367    render: fn(&[&str]) -> Option<String>,
368    metadata: fn() -> (
369        &'static str,
370        &'static [hyprstream_rpc::metadata::MethodMeta],
371    ),
372}
373
374impl DocMount {
375    pub fn new(
376        render: fn(&[&str]) -> Option<String>,
377        metadata: fn() -> (
378            &'static str,
379            &'static [hyprstream_rpc::metadata::MethodMeta],
380        ),
381    ) -> Self {
382        Self { render, metadata }
383    }
384}
385
386#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
387#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
388impl Mount for DocMount {
389    async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
390        Ok(Fid::new(VfsFidState {
391            path: components.iter().map(|s| s.to_string()).collect(),
392            opened: false,
393        }))
394    }
395
396    async fn open(&self, fid: &mut Fid, _mode: u8, _caller: &Subject) -> Result<(), MountError> {
397        if let Some(state) = fid.downcast_mut::<VfsFidState>() {
398            state.opened = true;
399        }
400        Ok(())
401    }
402
403    async fn read(
404        &self,
405        fid: &Fid,
406        offset: u64,
407        count: u32,
408        _caller: &Subject,
409    ) -> Result<Vec<u8>, MountError> {
410        let state = fid
411            .downcast_ref::<VfsFidState>()
412            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
413
414        let path_refs: Vec<&str> = state.path.iter().map(|s| s.as_str()).collect();
415        match (self.render)(&path_refs) {
416            Some(text) => {
417                let bytes = text.into_bytes();
418                Ok(slice_read(bytes, offset, count))
419            }
420            None => Err(MountError::NotFound(state.path.join("/"))),
421        }
422    }
423
424    async fn write(
425        &self,
426        _fid: &Fid,
427        _offset: u64,
428        _data: &[u8],
429        _caller: &Subject,
430    ) -> Result<u32, MountError> {
431        Err(MountError::NotSupported("docs are read-only".into()))
432    }
433
434    async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
435        let state = fid
436            .downcast_ref::<VfsFidState>()
437            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
438
439        if state.path.is_empty() {
440            let (_, methods) = (self.metadata)();
441            Ok(methods
442                .iter()
443                .filter(|m| !m.hidden)
444                .map(|m| DirEntry {
445                    name: m.name.to_owned(),
446                    is_dir: m.is_scoped,
447                    size: 0,
448                    stat: None,
449                })
450                .collect())
451        } else {
452            Err(MountError::NotDirectory(state.path.join("/")))
453        }
454    }
455
456    async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
457        let state = fid
458            .downcast_ref::<VfsFidState>()
459            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
460        let name = state.path.last().map(|s| s.as_str()).unwrap_or("doc");
461        Ok(Stat::unknown_qid(
462            if state.path.is_empty() { 0x80 } else { 0 },
463            0,
464            name.to_string(),
465            0,
466        ))
467    }
468
469    async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
470}
471
472// ============================================================================
473// Per-service dispatch wrappers — thin adapters calling generated dispatch()
474// ============================================================================
475
476// ============================================================================
477// Auto-mount registry (#543, T4) — service → /srv/{name} mount, no manual wiring
478// ============================================================================
479
480/// Resolve an `Arc<dyn RpcClient>` for a service by name. Owns the signing key +
481/// destination-key (trust store) resolution — kept as a boxed closure so
482/// `hyprstream-rpc-std` stays free of the identity/config types.
483#[cfg(not(target_arch = "wasm32"))]
484type ClientDialer = Box<dyn Fn(&str) -> anyhow::Result<Arc<dyn RpcClient>> + Send + Sync>;
485
486/// Context threaded into a [`MountFactory`] to build a service's mount.
487///
488/// A `MountFactory::construct` is a plain `fn` pointer (inventory constraint) and
489/// therefore cannot capture the per-process transport/identity state a
490/// [`GenericServiceMount`] needs — an `Arc<dyn RpcClient>` and the shared
491/// [`StreamRegistry`](crate::stream_mount::StreamRegistry). `MountContext`
492/// carries that state, mirroring how [`ServiceFactory`]'s `fn(&ServiceContext)`
493/// threads spawn-time state. It resolves an `Arc<dyn RpcClient>` per service by
494/// name via the caller-supplied `dial` closure (which owns the signing key +
495/// trust-store lookup), so this crate stays free of identity/config types.
496#[cfg(not(target_arch = "wasm32"))]
497pub struct MountContext {
498    dial: ClientDialer,
499    /// Shared stream registry — all service mounts in one namespace share it so
500    /// `/stream` named pipes are visible across services.
501    stream_registry: Arc<crate::stream_mount::StreamRegistry>,
502}
503
504#[cfg(not(target_arch = "wasm32"))]
505impl MountContext {
506    /// Build a context from a per-service client dialer. The `stream_registry`
507    /// is created fresh; use [`with_stream_registry`](Self::with_stream_registry)
508    /// to share one across builders.
509    pub fn new(
510        dial: impl Fn(&str) -> anyhow::Result<Arc<dyn RpcClient>> + Send + Sync + 'static,
511    ) -> Self {
512        Self {
513            dial: Box::new(dial),
514            stream_registry: Arc::new(crate::stream_mount::StreamRegistry::new()),
515        }
516    }
517
518    /// Use an existing shared [`StreamRegistry`] instead of a fresh one.
519    pub fn with_stream_registry(
520        mut self,
521        stream_registry: Arc<crate::stream_mount::StreamRegistry>,
522    ) -> Self {
523        self.stream_registry = stream_registry;
524        self
525    }
526
527    /// The shared stream registry these mounts publish into.
528    pub fn stream_registry(&self) -> &Arc<crate::stream_mount::StreamRegistry> {
529        &self.stream_registry
530    }
531
532    /// Resolve an `Arc<dyn RpcClient>` for `service`.
533    pub fn dial(&self, service: &str) -> anyhow::Result<Arc<dyn RpcClient>> {
534        (self.dial)(service)
535    }
536}
537
538/// Inventory entry that registers a service's generated mount.
539///
540/// Emitted by [`impl_service_dispatch!`] alongside the per-service dispatch
541/// wrapper (the only site that knows both the service name and the concrete
542/// `ServiceDispatch` type). Mirrors [`ServiceFactory`] for the mount surface:
543/// implement the dispatch, get a `/srv/{name}` mount for free.
544#[cfg(not(target_arch = "wasm32"))]
545pub struct MountFactory {
546    /// Service name; the default mount point is `/srv/{name}` (advisory
547    /// convention — the auto-mount loop's prefix is overridable by the caller's
548    /// later binds, not a contract).
549    pub name: &'static str,
550    /// Construct the service's `Mount` from a [`MountContext`].
551    pub construct: fn(&MountContext) -> anyhow::Result<Arc<dyn Mount>>,
552}
553
554#[cfg(not(target_arch = "wasm32"))]
555inventory::collect!(MountFactory);
556
557/// Mount every inventory-registered service into `ns` at `/srv/{name}`.
558///
559/// This is the auto-wire path (#543): a service that `impl_service_dispatch!`s
560/// gets a `/srv/{name}` mount with no per-service code here. `/srv/{name}` is
561/// advisory convention; a caller may `bind_mount` a different prefix before or
562/// after. A service whose `construct` fails (e.g. its transport can't be
563/// resolved yet) is logged and skipped — one unavailable service does not block
564/// the others.
565///
566/// Mounts land in `ns` directly; because [`Namespace::fork`] clones the mount
567/// table by `Arc`, a namespace forked after this call inherits every auto-mount
568/// (per-sandbox isolation is by *forking* the namespace, FS-D #365 — not by
569/// re-running this loop).
570#[cfg(not(target_arch = "wasm32"))]
571pub fn mount_all_services(ns: &mut hyprstream_vfs::Namespace, ctx: &MountContext) -> usize {
572    let mut mounted = 0;
573    for factory in inventory::iter::<MountFactory> {
574        match (factory.construct)(ctx) {
575            Ok(mount) => {
576                let prefix = format!("/srv/{}", factory.name);
577                if let Err(e) = ns.mount(&prefix, mount) {
578                    tracing::warn!(service = factory.name, %prefix, error = %e, "auto-mount failed");
579                } else {
580                    mounted += 1;
581                }
582            }
583            Err(e) => {
584                tracing::debug!(service = factory.name, error = %e, "service mount unavailable; skipping");
585            }
586        }
587    }
588    mounted
589}
590
591macro_rules! impl_service_dispatch {
592    ($name:ident, $svc_name:literal, $mod:path) => {
593        struct $name;
594
595        // Auto-register a `/srv/{svc_name}` mount for this service (#543, T4).
596        // This is the only site with both the service name and the concrete
597        // dispatch type in scope, so the `MountFactory` constructor is emitted
598        // here. `$svc_name` is the same name the service's `schema_metadata()`
599        // reports and matches the `#[service_factory]` registration.
600        #[cfg(not(target_arch = "wasm32"))]
601        inventory::submit! {
602            crate::vfs_mount::MountFactory {
603                name: $svc_name,
604                construct: |ctx: &crate::vfs_mount::MountContext| -> anyhow::Result<std::sync::Arc<dyn Mount>> {
605                    let client = ctx.dial($svc_name)?;
606                    Ok(std::sync::Arc::new(GenericServiceMount::new(
607                        client,
608                        Box::new($name),
609                        std::sync::Arc::clone(ctx.stream_registry()),
610                    )))
611                },
612            }
613        }
614
615        #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
616#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
617        impl ServiceDispatch for $name {
618            async fn dispatch(&self, method: &str, args_json: &str, client: &dyn RpcClient) -> Result<ServiceDispatchResult, String> {
619                use $mod as svc;
620
621                // Generate ephemeral keypair upfront — used by streaming methods,
622                // ignored by non-streaming (the send closure decides which transport to use).
623                let keypair = crate::vfs_mount::ephemeral_keypair_64()
624                    .map_err(|e| format!("keypair: {e}"))?;
625                let ephemeral_pubkey = keypair[32..64].to_vec();
626
627                let result = svc::dispatch(method, args_json, 0, |payload: Vec<u8>| async move {
628                    // Use call_streaming which injects ephemeral_pubkey into the
629                    // RequestEnvelope. For non-streaming methods, the server ignores
630                    // the pubkey — it only matters for streaming handshakes.
631                    client.call_streaming(payload, {
632                        let mut epk = [0u8; 32];
633                        epk.copy_from_slice(&ephemeral_pubkey);
634                        epk
635                    }).await
636                        .map_err(|e| format!("{e:?}"))
637                }).await?;
638
639                Ok(match result {
640                    svc::DispatchResult::Response(json) => ServiceDispatchResult::Response(json),
641                    svc::DispatchResult::Stream(info) => ServiceDispatchResult::Stream {
642                        info: Box::new(info),
643                        ephemeral_keypair: keypair,
644                    },
645                })
646            }
647
648            fn metadata(&self) -> (&'static str, &'static [hyprstream_rpc::metadata::MethodMeta]) {
649                use $mod as svc;
650                svc::schema_metadata()
651            }
652        }
653    };
654}
655
656impl_service_dispatch!(RegistryDispatch, "registry", crate::registry_client);
657impl_service_dispatch!(ModelDispatch, "model", crate::model_client);
658impl_service_dispatch!(PolicyDispatch, "policy", crate::policy_client);
659impl_service_dispatch!(McpDispatch, "mcp", crate::mcp_client);
660impl_service_dispatch!(InferenceDispatch, "inference", crate::inference_client);
661
662// ============================================================================
663// Builder — construct a Namespace with all service mounts
664// ============================================================================
665
666/// Build a VFS namespace with codegen-driven service mounts.
667///
668/// Per #389 + #391 (Option 1: shared content model), this builder mounts the
669/// same content trees as the native namespace builder
670/// (`hyprstream::cli::shell_handlers`) so `/srv/registry` and `/srv/model`
671/// resolve to the same spine-backed content in either context. The transport
672/// leaf (DMA/SAB ring buffers here vs ZMQ in the native builder) is
673/// correctly-scoped glue and is NOT part of the convergence contract — see
674/// `hyprstream_vfs::STANDARD_NAMESPACE_PATHS`.
675///
676/// Note: `/worktree` is bind-mounted to `/srv/registry` for path-shape
677/// parity with the native namespace. In the browser this exposes the
678/// GenericServiceMount (ctl-style service-as-files: `ls`, `cat`, `ctl`);
679/// in the native namespace the same path exposes the worktree filesystem
680/// (`RemoteRegistryMount`, real qids). The convergence is at the path +
681/// backing-service level; the access style differs by transport capability.
682///
683/// Browser-only: it wires the wasm transport clients into the browser namespace.
684/// The `GenericServiceMount`/`DocMount`/`StreamMount` building blocks it uses are
685/// target-agnostic; native callers compose them through the standard namespace
686/// builder + `#[service_factory]` auto-mount (#543) instead.
687#[cfg(target_arch = "wasm32")]
688pub fn build_browser_namespace(
689    registry_client: Arc<dyn RpcClient>,
690    model_client: Arc<dyn RpcClient>,
691) -> (
692    hyprstream_vfs::Namespace,
693    Arc<crate::stream_mount::StreamRegistry>,
694) {
695    let stream_registry = Arc::new(crate::stream_mount::StreamRegistry::new());
696    let mut ns = hyprstream_vfs::Namespace::new();
697
698    // Service mounts — all use GenericServiceMount with generated dispatch
699    let registry_mount: Arc<GenericServiceMount> = Arc::new(GenericServiceMount::new(
700        Arc::clone(&registry_client),
701        Box::new(RegistryDispatch),
702        Arc::clone(&stream_registry),
703    ));
704    ns.mount("/srv/registry", registry_mount.clone())
705        .expect("mount /srv/registry");
706    // `/worktree` aliases `/srv/registry` for path-shape parity with the
707    // native namespace (see `hyprstream_vfs::STANDARD_NAMESPACE_PATHS`).
708    ns.bind_mount("/worktree", registry_mount, hyprstream_vfs::BindFlag::After)
709        .expect("bind mount /worktree");
710    ns.mount(
711        "/srv/model",
712        Arc::new(GenericServiceMount::new(
713            Arc::clone(&model_client),
714            Box::new(ModelDispatch),
715            Arc::clone(&stream_registry),
716        )),
717    )
718    .expect("mount /srv/model");
719
720    // Documentation mounts — generated at compile time from schema annotations
721    ns.mount(
722        "/srv/registry/doc",
723        Arc::new(DocMount::new(
724            crate::registry_client::render_doc,
725            crate::registry_client::schema_metadata,
726        )),
727    )
728    .expect("mount /srv/registry/doc");
729    ns.mount(
730        "/srv/model/doc",
731        Arc::new(DocMount::new(
732            crate::model_client::render_doc,
733            crate::model_client::schema_metadata,
734        )),
735    )
736    .expect("mount /srv/model/doc");
737    ns.mount(
738        "/srv/inference/doc",
739        Arc::new(DocMount::new(
740            crate::inference_client::render_doc,
741            crate::inference_client::schema_metadata,
742        )),
743    )
744    .expect("mount /srv/inference/doc");
745    ns.mount(
746        "/srv/policy/doc",
747        Arc::new(DocMount::new(
748            crate::policy_client::render_doc,
749            crate::policy_client::schema_metadata,
750        )),
751    )
752    .expect("mount /srv/policy/doc");
753    ns.mount(
754        "/srv/mcp/doc",
755        Arc::new(DocMount::new(
756            crate::mcp_client::render_doc,
757            crate::mcp_client::schema_metadata,
758        )),
759    )
760    .expect("mount /srv/mcp/doc");
761
762    // Stream mount — named pipes for active streaming data
763    ns.mount(
764        "/stream",
765        Arc::new(crate::stream_mount::StreamMount::new(Arc::clone(
766            &stream_registry,
767        ))),
768    )
769    .expect("mount /stream");
770
771    // `/wanix` is NOT mounted here: it needs a Wanix-provided SharedArrayBuffer
772    // that the browser only has when running under Wanix. Wire it separately
773    // via [`mount_wanix`] after this builder returns. See #409/#391.
774
775    (ns, stream_registry)
776}
777
778// ============================================================================
779// WanixMount wiring — #409/#391 (Wanix-native VFS access)
780// ============================================================================
781
782/// Mount the Wanix 9P filesystem into the namespace at `/wanix` (#409/#391).
783///
784/// `client` is a `P9Client` already connected over a `P9Transport` (e.g. the
785/// `DmaTransport` SharedArrayBuffer bridge). Every VFS op under `/wanix` is
786/// translated to 9P2000.L and forwarded — the Wanix half of the "browser
787/// both-paths" model, riding the same wasm transport substrate as the service
788/// mounts above.
789///
790/// This is the rpc-std seam that makes `WanixMount` reachable from the browser
791/// namespace now that `hyprstream-9p` is a wasm32 dependency.
792///
793/// # Breaking change (#465)
794///
795/// This signature replaces the previous `async fn mount_wanix(ns, sab, uname,
796/// aname) -> anyhow::Result<()>`, which performed the 9P version/attach handshake
797/// internally over a `DmaTransport` built from a `SharedArrayBuffer`. The handshake
798/// (and transport construction) now happen at the call site, so callers pass an
799/// already-connected `P9Client<T>` and this function is **synchronous**, returning
800/// [`hyprstream_vfs::NamespaceError`] instead of `anyhow::Result<()>`. Update call
801/// sites: `mount_wanix(ns, &sab, uname, aname).await?` →
802/// `let client = P9Client::connect(DmaTransport::new(&sab, true), uname, aname).await?;
803/// mount_wanix(ns, client)?;`.
804///
805/// Wasm-only: `WanixMount`/`P9Client`/`DmaTransport` are SharedArrayBuffer-DMA
806/// types compiled only for the browser target.
807#[cfg(target_arch = "wasm32")]
808pub fn mount_wanix<T>(
809    ns: &mut hyprstream_vfs::Namespace,
810    client: hyprstream_9p::client::P9Client<T>,
811) -> Result<(), hyprstream_vfs::NamespaceError>
812where
813    T: hyprstream_9p::client::P9Transport + 'static,
814{
815    ns.mount(
816        "/wanix",
817        Arc::new(hyprstream_9p::wanix_mount::WanixMount::new(client)),
818    )
819}
820
821// ============================================================================
822// Compile-time Send + Sync guarantees (#539 T3)
823// ============================================================================
824
825/// The generic service→9p mounts must be `Send + Sync` to serve behind the
826/// native (multi-threaded) `Mount` trait. These are compiler-enforced, not
827/// assumed — the whole point of the native port.
828#[cfg(not(target_arch = "wasm32"))]
829const _: () = {
830    fn assert_send_sync<T: Send + Sync>() {}
831    fn assertions() {
832        assert_send_sync::<GenericServiceMount>();
833        assert_send_sync::<DocMount>();
834        // The registry is the shared state behind the native mount; it must be
835        // Send + Sync even though a `StreamEntry`'s `Box<dyn StreamHandle>` is
836        // only `Send` (guarded by the registry's `Mutex`).
837        assert_send_sync::<crate::stream_mount::StreamRegistry>();
838    }
839    let _ = assertions;
840};
841
842#[cfg(all(test, not(target_arch = "wasm32")))]
843mod automount_tests {
844    #![allow(clippy::expect_used, clippy::unwrap_used)]
845    use super::*;
846    use hyprstream_rpc::rpc_client::{CallOptions, RpcClient};
847    use hyprstream_rpc::stream_consumer::StreamHandle;
848
849    /// A stand-in `RpcClient` for the auto-mount wiring test. The end-to-end
850    /// path exercised (`mount_all_services` → `walk` → `readdir` at the mount
851    /// root) reads method names from the service's compiled `schema_metadata()`
852    /// and never dials the client, so these methods only need to type-check.
853    struct NoopClient;
854
855    #[async_trait]
856    impl RpcClient for NoopClient {
857        async fn call(&self, _payload: Vec<u8>) -> anyhow::Result<Vec<u8>> {
858            anyhow::bail!("NoopClient: no transport")
859        }
860        async fn call_for_service(
861            &self,
862            _service_domain: &str,
863            _payload: Vec<u8>,
864        ) -> anyhow::Result<Vec<u8>> {
865            anyhow::bail!("NoopClient: no transport")
866        }
867        async fn call_for_service_with_method(
868            &self,
869            _service_domain: &str,
870            _method_discriminator: u16,
871            _payload: Vec<u8>,
872        ) -> anyhow::Result<Vec<u8>> {
873            anyhow::bail!("NoopClient: no transport")
874        }
875        async fn call_with_options(
876            &self,
877            _payload: Vec<u8>,
878            _options: CallOptions,
879        ) -> anyhow::Result<Vec<u8>> {
880            anyhow::bail!("NoopClient: no transport")
881        }
882        async fn call_with_options_for_service(
883            &self,
884            _service_domain: &str,
885            _payload: Vec<u8>,
886            _options: CallOptions,
887        ) -> anyhow::Result<Vec<u8>> {
888            anyhow::bail!("NoopClient: no transport")
889        }
890        async fn call_streaming(
891            &self,
892            _payload: Vec<u8>,
893            _ephemeral_pubkey: [u8; 32],
894        ) -> anyhow::Result<Vec<u8>> {
895            anyhow::bail!("NoopClient: no transport")
896        }
897        async fn call_streaming_for_service(
898            &self,
899            _service_domain: &str,
900            _payload: Vec<u8>,
901            _ephemeral_pubkey: [u8; 32],
902        ) -> anyhow::Result<Vec<u8>> {
903            anyhow::bail!("NoopClient: no transport")
904        }
905        async fn call_streaming_for_service_with_method(
906            &self,
907            _service_domain: &str,
908            _method_discriminator: u16,
909            _payload: Vec<u8>,
910            _ephemeral_pubkey: [u8; 32],
911        ) -> anyhow::Result<Vec<u8>> {
912            anyhow::bail!("NoopClient: no transport")
913        }
914        async fn open_stream(&self, _payload: Vec<u8>) -> anyhow::Result<Box<dyn StreamHandle>> {
915            anyhow::bail!("NoopClient: no transport")
916        }
917        async fn open_stream_from_info(
918            &self,
919            _stream_info: hyprstream_rpc::stream_info::StreamInfo,
920            _client_secret: [u8; 32],
921            _client_pubkey: [u8; 32],
922        ) -> anyhow::Result<Box<dyn StreamHandle>> {
923            anyhow::bail!("NoopClient: no transport")
924        }
925        fn next_id(&self) -> u64 {
926            0
927        }
928    }
929
930    /// Every service that `impl_service_dispatch!`s registers a `MountFactory`,
931    /// so `mount_all_services` yields a `/srv/{name}` mount with no per-service
932    /// wiring here. Then `walk`/`readdir` works end-to-end through the
933    /// auto-registered mount (listing the service's methods from schema
934    /// metadata — the proof the generated mount is actually reachable).
935    #[tokio::test]
936    async fn auto_mount_registers_and_serves_srv_paths() {
937        // At least the five `impl_service_dispatch!` services must be present.
938        let registered: Vec<&str> = inventory::iter::<MountFactory>
939            .into_iter()
940            .map(|f| f.name)
941            .collect();
942        for expected in ["registry", "model", "policy", "mcp", "inference"] {
943            assert!(
944                registered.contains(&expected),
945                "service {expected} must self-register a MountFactory; got {registered:?}"
946            );
947        }
948
949        let ctx = MountContext::new(|_service| Ok(Arc::new(NoopClient) as Arc<dyn RpcClient>));
950        let mut ns = hyprstream_vfs::Namespace::new();
951        let mounted = mount_all_services(&mut ns, &ctx);
952        assert_eq!(
953            mounted,
954            registered.len(),
955            "every registered service must mount with the NoopClient dialer"
956        );
957
958        // The auto-mount landed at /srv/{name}.
959        let prefixes = ns.mount_prefixes();
960        assert!(
961            prefixes.contains(&"/srv/registry"),
962            "prefixes: {prefixes:?}"
963        );
964        assert!(prefixes.contains(&"/srv/model"), "prefixes: {prefixes:?}");
965
966        // End-to-end through the auto-registered mount: walk the mount root and
967        // readdir it — the entries are the service's methods, served by the
968        // generated GenericServiceMount with no per-service code.
969        let subject = Subject::anonymous();
970        let entries = ns
971            .ls("/srv/registry", &subject)
972            .await
973            .expect("readdir /srv/registry through the auto-mounted service");
974        assert!(
975            !entries.is_empty(),
976            "auto-mounted /srv/registry must expose the registry's methods"
977        );
978    }
979
980    /// A namespace forked after auto-mount inherits every mount (the FS-D #365
981    /// per-sandbox isolation model: fork the namespace, don't re-run the loop).
982    #[tokio::test]
983    async fn forked_namespace_inherits_auto_mounts() {
984        let ctx = MountContext::new(|_service| Ok(Arc::new(NoopClient) as Arc<dyn RpcClient>));
985        let mut ns = hyprstream_vfs::Namespace::new();
986        mount_all_services(&mut ns, &ctx);
987
988        let child = ns.fork();
989        assert!(
990            child.mount_prefixes().contains(&"/srv/registry"),
991            "forked namespace must inherit /srv/registry; got {:?}",
992            child.mount_prefixes()
993        );
994    }
995}