Skip to main content

plexus_core/plexus/remote_child/
dial_in.rs

1//! VISION-5 (LOCAL-5) · dial-in peers: a service that dialed in, offered a
2//! surface on its own socket (plexus-wire spec/14, `{svc}.offer`), and is
3//! mounted here under a name for as long as that socket lives.
4//!
5//! [`Peers`] is an activation (its namespace `peers` by default) whose
6//! children are the peers connected now: `peers.<name>.<method>` reaches
7//! the peer `<name>`, `peers.list` names every one, `peers.watch` follows
8//! them coming and going. Each peer is a [`RemoteChild`] whose connection
9//! is the socket the peer opened — the calls into it are spec/12's, sent
10//! the other way along that socket (spec/14 rule 1), with the hop naming
11//! the service acting (`principal`) and the caller it acts for (`for`).
12//!
13//! The transport stays outside: plexus-core has no WebSocket server, so a
14//! transport hands each accepted socket to [`Peers::socket`] and feeds it
15//! (plexus-transport: a `ConnectionHook` calling [`PeerSocket::on_frame`]
16//! and [`PeerSocket::on_close`], and a task writing what
17//! [`PeerSocket`]'s receiver yields through the connection's writer).
18//!
19//! | when | then |
20//! | -- | -- |
21//! | a socket sends `{svc}.offer {namespace, mount?}` | its principal must hold `peers.offer` on the mount name (the gate, when one is given); its schema is asked over the socket; it is mounted as `peers.<mount>` and the offer is answered `{offered, mount, path, schema_hash, service}` |
22//! | an anonymous socket offers | refused `unauthenticated`; nothing is mounted |
23//! | the name is held by another principal's socket | refused `name_taken` |
24//! | the same principal offers the name from a new socket | the new socket takes it over (a reconnect) |
25//! | a caller calls `peers.<mount>.<m>` | the service's gate decides `peers.<mount>.<m>` first; the call crosses with the hop, the peer decides again (spec/12) |
26//! | the socket closes | the mount goes, now: `peers.<mount>` is not found, a call open on it ends `child_unavailable` |
27//! | NEST-25: an [`Admission`] is set | it decides the offer before anything is asked of the socket — now, refused, or **pending** (the node told only [`OFFER_PENDING`] and its pairing code; nothing mounted, nothing served) — vets the schema read before the mount, and hears each mount and each close |
28//! | NEST-25: `_info {nonce, commit}` | answered with a fresh `host_nonce` beside the key proof; the offer reveals the node's nonce (`pairing_nonce`, checked against `commit`) and signs both nonces with the node's key (`possession`): the pairing code ([`super::pairing`]) and a proof of the key bound to this connection |
29//! | NEST-25: the peer calls back (`_host.call`) | taken into the mount's calls back, as a dialed child's: under a call it serves, as that call's caller |
30
31use std::collections::BTreeMap;
32use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
33use std::sync::{Arc, Mutex, RwLock};
34use std::time::{Duration, Instant};
35
36use async_trait::async_trait;
37use futures::future::BoxFuture;
38use futures::stream::BoxStream;
39use futures::StreamExt;
40use plexus_auth_core::grants::{Gate, Grant, GrantSet, Refusal, RoleTable, Roles};
41use schemars::JsonSchema;
42use serde::{Deserialize, Serialize};
43use serde_json::{json, Value};
44use tokio::sync::{broadcast, mpsc};
45
46use super::link::{gone, meta, Conn, Kept, Shared};
47use super::{mount_schema, node_schema, Backoff, ChildOptions, ChildSpec, Inner, MountTimings, PeerIdentity, RemoteChild};
48use crate::plexus::auth::AuthContext;
49use crate::plexus::method_enum::MethodEnumSchema;
50use crate::plexus::plexus::{route_to_child, Activation, ChildRouter, PlexusError};
51use crate::plexus::schema::{Cardinality, MethodRole, MethodSchema, PluginSchema};
52use crate::plexus::streaming::PlexusStream;
53use crate::plexus::types::PlexusStreamItem;
54
55/// NEST-25: the notice a host writes on a dialing node's socket while its
56/// offer waits for an operator — `{"method": "_offer.pending", "params":
57/// {"id": <the offer's id>, "code": <the pairing code, if any>}}` — and
58/// nothing else.
59pub const OFFER_PENDING: &str = "_offer.pending";
60
61/// The domain of the node's proof of its key at the offer (`possession`).
62const POSSESSION_CONTEXT: &str = "plexus-dial-offer/v1";
63
64/// NEST-25: what the node signs at its offer, with the key it proved at the
65/// upgrade — the host's key and nonce, its own key and nonce, the service
66/// and the mount name: its key, proven on this connection.
67pub fn possession_input(host_key: &str, node_key: &str, node_nonce: &str, host_nonce: &str, service: &str, mount: &str) -> String {
68    format!("{POSSESSION_CONTEXT}\n{host_key}\n{node_key}\n{node_nonce}\n{host_nonce}\n{service}\n{mount}")
69}
70
71/// NEST-25: an offer, as an [`Admission`] decides it.
72#[derive(Debug, Clone)]
73pub struct Offer {
74    /// The socket's id (as [`PeerSocket::id`]).
75    pub socket: u64,
76    /// The mount name asked for.
77    pub name: String,
78    /// The namespace offered.
79    pub namespace: String,
80    /// The principal the socket signed in as at the upgrade.
81    pub principal: String,
82    /// Whether that principal's key signed this connection's nonces at the
83    /// offer (`possession`): its key, proven here and now. Without it the
84    /// principal is only what the upgrade's credential said.
85    pub key_proven: bool,
86    /// The address it came from, as the transport saw it.
87    pub from: Option<String>,
88    /// The pairing code of this connection, when the node asked for one.
89    pub code: Option<String>,
90}
91
92/// NEST-25: an offer refused: its `error_kind` and why.
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct OfferRefused {
95    pub kind: String,
96    pub message: String,
97}
98
99impl OfferRefused {
100    pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
101        Self { kind: kind.into(), message: message.into() }
102    }
103}
104
105/// NEST-25: what an [`Admission`] says of an offer.
106pub enum Decision {
107    /// Go on: its schema is asked and, once vetted, it is mounted.
108    Admit,
109    /// Refused: nothing asked, nothing mounted.
110    Refuse(OfferRefused),
111    /// Held: nothing asked, nothing mounted, the node told only
112    /// [`OFFER_PENDING`]; the future says, in time, admitted or refused.
113    Pending(BoxFuture<'static, Result<(), OfferRefused>>),
114}
115
116/// NEST-25: who may be mounted, decided by the embedder (plexus-dyn's
117/// table) before anything is mounted — in place of the gate's `peers.offer`.
118pub trait Admission: Send + Sync + 'static {
119    /// Before anything is asked of the socket.
120    fn decide(&self, offer: &Offer) -> Decision;
121    /// Its schema read, before it is mounted: the last word.
122    fn vet(&self, offer: &Offer, child: &RemoteChild) -> Result<(), OfferRefused>;
123    /// Mounted here (the offer about to be answered): put it in the
124    /// embedder's table, or refuse it — then it is taken out of this table
125    /// again and the offer is refused (review L1: a refusal racing the mount).
126    fn mounted(&self, offer: &Offer, child: &RemoteChild, socket: &Arc<PeerSocket>) -> Result<(), OfferRefused>;
127    /// The socket is gone (once): `mount` the name it held, if it held one.
128    fn closed(&self, socket: u64, mount: Option<&str>, why: &str);
129}
130
131/// One peer, as `peers.list` names it.
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
133pub struct PeerInfo {
134    /// The mount name: the peer is `peers.<name>`.
135    pub name: String,
136    /// The principal its socket proved at the upgrade (spec/00).
137    pub principal: String,
138    /// The namespace it offered (its own `{ns}`).
139    pub namespace: String,
140    /// Its methods, as its schema lists them.
141    pub methods: Vec<String>,
142    /// Seconds since it was mounted.
143    pub connected_secs: u64,
144}
145
146/// What `peers.watch` says: a peer came or went.
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
148#[serde(tag = "type", rename_all = "snake_case")]
149pub enum PeerEvent {
150    /// Mounted (or, on a watch's start, mounted already).
151    Mounted { name: String, principal: String, namespace: String, methods: Vec<String> },
152    /// Its socket closed, or a new socket of the same principal took the name.
153    Unmounted { name: String, why: String },
154}
155
156/// [`Peers`]' own methods are named, not a Rust enum of the macro's.
157#[derive(Debug, Clone, Copy)]
158pub enum PeersMethods {}
159
160impl JsonSchema for PeersMethods {
161    fn schema_name() -> std::borrow::Cow<'static, str> {
162        "PeersMethods".into()
163    }
164
165    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
166        schemars::json_schema!({ "description": "list, watch, offer — and every peer connected, by its mount name" })
167    }
168}
169
170impl MethodEnumSchema for PeersMethods {
171    fn method_names() -> &'static [&'static str] {
172        &["list", "watch", "offer"]
173    }
174
175    fn schema_with_consts() -> Value {
176        serde_json::to_value(schemars::schema_for!(PeersMethods)).unwrap_or(Value::Null)
177    }
178}
179
180/// A mounted peer.
181struct Entry {
182    child: RemoteChild,
183    principal: String,
184    namespace: String,
185    socket: u64,
186    since: Instant,
187    /// NEST-25 (review R2-4): the socket that holds it, to know it is still open.
188    holder: std::sync::Weak<PeerSocket>,
189}
190
191impl Entry {
192    fn info(&self, name: &str) -> PeerInfo {
193        PeerInfo {
194            name: name.to_string(),
195            principal: self.principal.clone(),
196            namespace: self.namespace.clone(),
197            methods: self.child.inner.schema.methods.iter().map(|m| m.name.clone()).collect(),
198            connected_secs: self.since.elapsed().as_secs(),
199        }
200    }
201}
202
203struct PeersInner {
204    ns: String,
205    service: String,
206    principal: String,
207    gate: RwLock<Option<Arc<Gate>>>,
208    opts: ChildOptions,
209    table: RwLock<BTreeMap<String, Entry>>,
210    events: broadcast::Sender<PeerEvent>,
211    next_socket: AtomicU64,
212    on_change: RwLock<Vec<Box<dyn Fn() + Send + Sync>>>,
213    /// KEEL-8: the key the relay proves to a peer's `_info {nonce}`.
214    key: Option<Arc<crate::plexus::peer_token::PeerKey>>,
215    /// NEST-25: who may be mounted, when the embedder decides.
216    admission: RwLock<Option<Arc<dyn Admission>>>,
217}
218
219/// The peers connected now, as an activation: `peers.list`, `peers.watch`,
220/// and `peers.<name>.<method>` into each. Cheap to clone.
221#[derive(Clone)]
222pub struct Peers {
223    inner: Arc<PeersInner>,
224}
225
226impl std::fmt::Debug for Peers {
227    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228        f.debug_struct("Peers").field("ns", &self.inner.ns).field("names", &self.names()).finish()
229    }
230}
231
232/// A name a peer may be mounted under: one segment, not one of
233/// [`Peers`]' own methods.
234fn valid_name(name: &str) -> Result<(), String> {
235    if name.is_empty() || name.len() > 64 {
236        return Err("a mount name is 1–64 characters".into());
237    }
238    if let Some(bad) = name.chars().find(|c| !(c.is_ascii_alphanumeric() || *c == '_' || *c == '-')) {
239        return Err(format!("the mount name `{name}` holds `{bad}`: only letters, digits, `_` and `-`"));
240    }
241    if matches!(name, "list" | "watch" | "offer" | "schema") {
242        return Err(format!("`{name}` is one of the peers' own methods"));
243    }
244    Ok(())
245}
246
247impl Peers {
248    /// Peers mounted under `ns` (`peers`) of the service `service` (whose
249    /// `{service}.offer` a socket sends), calling into each as `principal`
250    /// (the hop's acting service: its key's principal, or `service:<ns>`).
251    pub fn new(ns: impl Into<String>, service: impl Into<String>, principal: impl Into<String>) -> Self {
252        let service = service.into();
253        let opts = ChildOptions {
254            // A dial-in peer is never redialed: it comes back by dialing again.
255            backoff: Backoff { initial: Duration::ZERO, max: Duration::ZERO, per_minute: 0 },
256            ..ChildOptions::for_service(&service)
257        };
258        Self {
259            inner: Arc::new(PeersInner {
260                ns: ns.into(),
261                service,
262                principal: principal.into(),
263                gate: RwLock::new(None),
264                opts,
265                table: RwLock::new(BTreeMap::new()),
266                events: broadcast::channel(256).0,
267                next_socket: AtomicU64::new(1),
268                on_change: RwLock::new(Vec::new()),
269                key: None,
270                admission: RwLock::new(None),
271            }),
272        }
273    }
274
275    /// The gate that decides offers (`<ns>.offer` on the mount name). Calls
276    /// into a peer are decided by the service's own gate, as every call.
277    /// Without one every signed-in socket may offer.
278    pub fn with_gate(self, gate: Arc<Gate>) -> Self {
279        *self.inner.gate.write().unwrap() = Some(gate);
280        self
281    }
282
283    /// [`Self::with_gate`] on a `Peers` already registered (the gate is made
284    /// from the service's roles, which need the activation first).
285    pub fn set_gate(&self, gate: Arc<Gate>) {
286        *self.inner.gate.write().unwrap() = Some(gate);
287    }
288
289    /// Each call into a peer opens within this, and the peer's schema is
290    /// answered within it at the offer. Default 10 s.
291    pub fn with_timeout(self, timeout: Duration) -> Self {
292        let mut s = self;
293        if let Some(inner) = Arc::get_mut(&mut s.inner) {
294            inner.opts.timeout = timeout;
295        }
296        s
297    }
298
299    /// NEST-25: the options each mount is made with (the host its calls
300    /// back reach, the token issuer, the call cap, the timeout, consent held
301    /// from the handshake). A dial-in peer is never redialed: the backoff
302    /// stays none whatever `opts` says.
303    pub fn with_options(self, opts: ChildOptions) -> Self {
304        let mut s = self;
305        if let Some(inner) = Arc::get_mut(&mut s.inner) {
306            inner.opts = ChildOptions { backoff: Backoff { initial: Duration::ZERO, max: Duration::ZERO, per_minute: 0 }, ..opts };
307        }
308        s
309    }
310
311    /// NEST-25: `admission` decides every offer, before anything is
312    /// mounted, in place of the gate's `peers.offer` (which still applies
313    /// when a gate is set too).
314    pub fn with_admission(self, admission: Arc<dyn Admission>) -> Self {
315        *self.inner.admission.write().unwrap() = Some(admission);
316        self
317    }
318
319    /// KEEL-8: the relay's own key. A peer dialing out names the relay by
320    /// it ([`DialOut::trust`](super::DialOut::trust)) and asks it proved:
321    /// a socket's `_info {nonce}` is answered `{backend, key, proof}` (the
322    /// nonce and the service's name signed, DYNAUTH-5's proof), and the
323    /// hop's acting service is this key's principal. Without one a peer
324    /// that dials out is refused at its `_info`.
325    pub fn with_key(self, key: crate::plexus::peer_token::PeerKey) -> Self {
326        let mut s = self;
327        if let Some(inner) = Arc::get_mut(&mut s.inner) {
328            inner.principal = key.kid().to_string();
329            inner.key = Some(Arc::new(key));
330        }
331        s
332    }
333
334    /// Call `f` whenever a peer is mounted or goes — the service's
335    /// [`DynamicHub::schema_moved`](crate::DynamicHub::schema_moved), so the
336    /// next `schema` it answers lists the peers as they stand.
337    pub fn on_change(&self, f: impl Fn() + Send + Sync + 'static) {
338        self.inner.on_change.write().unwrap().push(Box::new(f));
339    }
340
341    /// A peer came or went: the gate's grants moved (the roles grow and
342    /// shrink with the peers) and what the service describes moved.
343    fn moved(&self) {
344        if let Some(g) = self.inner.gate.read().unwrap().as_ref() {
345            g.generation().bump();
346        }
347        for f in self.inner.on_change.read().unwrap().iter() {
348            f();
349        }
350    }
351
352    /// The names mounted now.
353    pub fn names(&self) -> Vec<String> {
354        self.inner.table.read().unwrap().keys().cloned().collect()
355    }
356
357    /// Every peer mounted now.
358    pub fn list(&self) -> Vec<PeerInfo> {
359        self.inner.table.read().unwrap().iter().map(|(n, e)| e.info(n)).collect()
360    }
361
362    /// The peer mounted as `name`, if one is.
363    pub fn get(&self, name: &str) -> Option<RemoteChild> {
364        self.inner.table.read().unwrap().get(name).map(|e| e.child.clone())
365    }
366
367    /// Peers coming and going, from now.
368    pub fn events(&self) -> broadcast::Receiver<PeerEvent> {
369        self.inner.events.subscribe()
370    }
371
372    /// Roles over `base` that also hold what the peers connected now
373    /// declare (each peer's `roles`, under `<ns>.<name>.<method>`), and —
374    /// when `every` names a role — every method of every peer for it, with
375    /// `<ns>.list`, `<ns>.watch` and `<ns>.offer`. Answered from memory, as
376    /// the table stands at each check.
377    /// A `base` that is a [`RoleStore`](crate::plexus::RoleStore) (an
378    /// admin's `auth.role_set`) makes the result one too.
379    pub fn roles<R: Roles>(&self, base: R, every: Option<&str>) -> PeerRoles<R> {
380        PeerRoles { base, peers: self.clone(), every: every.map(str::to_string) }
381    }
382
383    /// A socket the transport accepted, signed in as `auth` (or anonymous).
384    /// Feed it every inbound frame ([`PeerSocket::on_frame`]) and its close
385    /// ([`PeerSocket::on_close`]); write every frame the receiver yields on
386    /// the socket, in order.
387    pub fn socket(&self, auth: Option<AuthContext>) -> (Arc<PeerSocket>, mpsc::UnboundedReceiver<Vec<u8>>) {
388        self.socket_from(auth, None, None)
389    }
390
391    /// NEST-25: [`Self::socket`], with the address it came from and how the
392    /// transport closes it ([`PeerSocket::close`]: a revoke, a disconnect, a
393    /// name taken over by a reconnect).
394    pub fn socket_from(&self, auth: Option<AuthContext>, from: Option<String>, close: Option<Box<dyn Fn() + Send + Sync>>) -> (Arc<PeerSocket>, mpsc::UnboundedReceiver<Vec<u8>>) {
395        let (out, rx) = mpsc::unbounded_channel();
396        let (inbound, mut in_rx) = mpsc::unbounded_channel::<Vec<u8>>();
397        let socket = Arc::new(PeerSocket {
398            peers: self.clone(),
399            id: self.inner.next_socket.fetch_add(1, Ordering::Relaxed),
400            principal: auth.as_ref().and_then(|a| a.principal()).map(|p| p.to_string()),
401            auth,
402            out,
403            inbound,
404            link: Mutex::new(None),
405            mount: Mutex::new(None),
406            from,
407            close,
408            closed: AtomicBool::new(false),
409            offering: AtomicBool::new(false),
410            pairing: Mutex::new(None),
411        });
412        // The answers and items of this side's calls, routed in arrival
413        // order (spec/14 rule 7), never on the transport's reader.
414        let weak = Arc::downgrade(&socket);
415        tokio::spawn(async move {
416            while let Some(frame) = in_rx.recv().await {
417                let link = weak.upgrade().and_then(|s| s.link.lock().unwrap().clone());
418                if let Some((conn, _)) = link {
419                    conn.on_message(&frame).await;
420                }
421            }
422        });
423        (socket, rx)
424    }
425
426    fn unmount(&self, name: &str, socket: u64, why: &str) {
427        let removed = {
428            let mut t = self.inner.table.write().unwrap();
429            match t.get(name) {
430                Some(e) if e.socket == socket => t.remove(name),
431                _ => None,
432            }
433        };
434        if let Some(e) = removed {
435            tracing::info!(target: "plexus::peers", peer = %name, "peer unmounted: {why}");
436            // KEEL-59: its calls are told why first — the move below would
437            // otherwise end them as callers no longer allowed a name that
438            // is gone.
439            e.child.stop(why);
440            self.moved();
441            let _ = self.inner.events.send(PeerEvent::Unmounted { name: name.to_string(), why: why.to_string() });
442        }
443    }
444
445    fn data(&self, method: &str, content: Value) -> PlexusStreamItem {
446        let ns = &self.inner.ns;
447        PlexusStreamItem::Data { metadata: meta(ns).into(), content_type: format!("{ns}.{method}").into(), content: content.into() }
448    }
449
450    fn done(&self) -> PlexusStreamItem {
451        PlexusStreamItem::Done { metadata: meta(&self.inner.ns) }
452    }
453
454    fn own_methods(&self) -> Vec<MethodSchema> {
455        let ns = &self.inner.ns;
456        vec![
457            MethodSchema::new("list", "The peers connected now: each one's mount name, principal, namespace and methods", "")
458                .with_cardinality(Cardinality::Many)
459                .with_returns(schemars::schema_for!(PeerInfo))
460                .with_grant(format!("{ns}.list"))
461                .with_content_hash(),
462            MethodSchema::new("watch", "Peers as they come and go: those mounted now, then each mount and unmount", "")
463                .with_cardinality(Cardinality::Many)
464                .with_returns(schemars::schema_for!(PeerEvent))
465                .with_grant(format!("{ns}.watch"))
466                .with_content_hash(),
467            MethodSchema::new("offer", "Offered on a peer's own socket (`{service}.offer`, spec/14), not called: its grant decides who may be mounted, on the mount name", "")
468                .with_cardinality(Cardinality::One)
469                .with_grant(format!("{ns}.offer"))
470                .with_content_hash(),
471        ]
472    }
473}
474
475/// [`Peers::roles`]: a role table that grows with the peers connected.
476pub struct PeerRoles<R = RoleTable> {
477    base: R,
478    peers: Peers,
479    every: Option<String>,
480}
481
482#[async_trait]
483impl<R: crate::plexus::RoleStore> crate::plexus::RoleStore for PeerRoles<R> {
484    async fn set(&self, role: &plexus_auth_core::audit::RoleName, grants: GrantSet) -> Result<(), crate::plexus::StoreError> {
485        self.base.set(role, grants).await
486    }
487}
488
489impl<R: Roles> Roles for PeerRoles<R> {
490    fn grants(&self, role: &plexus_auth_core::audit::RoleName) -> Option<GrantSet> {
491        let base = self.base.grants(role);
492        if matches!(base, Some(GrantSet::All)) {
493            return base;
494        }
495        let mut set = match base {
496            Some(GrantSet::Listed(s)) => s,
497            _ => Default::default(),
498        };
499        let every = self.every.as_deref() == Some(role.as_str());
500        let ns = &self.peers.inner.ns;
501        if every {
502            for m in ["list", "watch", "offer"] {
503                set.insert(Grant::new(format!("{ns}.{m}")));
504            }
505        }
506        let mut known = every || self.base.grants(role).is_some();
507        for (name, e) in self.peers.inner.table.read().unwrap().iter() {
508            let schema = &e.child.inner.schema;
509            if every {
510                set.extend(schema.methods.iter().map(|m| Grant::new(format!("{ns}.{name}.{}", m.name))));
511            }
512            // A peer's own roles are already `<ns>.<name>.<method>` (the mount
513            // requalified them under its path).
514            if let Some(gs) = schema.roles.get(role.as_str()) {
515                known = true;
516                set.extend(gs.iter().map(Grant::new));
517            }
518            // Its entry in `<ns>.schema` (a child's), seen by whoever may
519            // call something in it.
520            if every || schema.roles.get(role.as_str()).is_some_and(|g| !g.is_empty()) {
521                set.insert(Grant::new(format!("{ns}.{name}")));
522            }
523        }
524        known.then_some(GrantSet::Listed(set))
525    }
526
527    fn names(&self) -> Vec<plexus_auth_core::audit::RoleName> {
528        let mut names = self.base.names();
529        if let Some(e) = &self.every {
530            names.push(plexus_auth_core::audit::RoleName::new(e));
531        }
532        names
533    }
534}
535
536/// One accepted socket, as [`Peers`] sees it: the offer it may make, the
537/// answers and items of the calls made into it, its close.
538pub struct PeerSocket {
539    peers: Peers,
540    id: u64,
541    auth: Option<AuthContext>,
542    principal: Option<String>,
543    out: mpsc::UnboundedSender<Vec<u8>>,
544    inbound: mpsc::UnboundedSender<Vec<u8>>,
545    /// Once offered: the connection the calls into the peer ride.
546    link: Mutex<Option<(Arc<Conn>, Arc<Shared>)>>,
547    /// The name it is mounted under.
548    mount: Mutex<Option<String>>,
549    /// NEST-25: where it came from, and how the transport closes it.
550    from: Option<String>,
551    close: Option<Box<dyn Fn() + Send + Sync>>,
552    /// Gone (its close heard, or closed here): nothing mounts on it.
553    closed: AtomicBool,
554    /// An offer is being decided or mounted.
555    offering: AtomicBool,
556    /// NEST-25: the node's commitment and the host's nonce, from `_info`.
557    pairing: Mutex<Option<(String, String)>>,
558}
559
560/// The parts of a frame its shape is read by (spec/14 rule 2).
561#[derive(Deserialize)]
562struct Shape {
563    #[serde(default)]
564    id: Option<Value>,
565    #[serde(default)]
566    method: Option<String>,
567    #[serde(default)]
568    params: Option<Value>,
569}
570
571/// A refusal of an offer: spec/05's error with a typed `data.error_kind`.
572fn refusal(id: &Value, code: i64, kind: &str, message: &str) -> Vec<u8> {
573    serde_json::to_vec(&json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message, "data": { "error_kind": kind } } })).unwrap_or_default()
574}
575
576impl PeerSocket {
577    /// NEST-25: its id (an [`Offer`]'s `socket`).
578    pub fn id(&self) -> u64 {
579        self.id
580    }
581
582    /// NEST-25: whether it is gone.
583    pub fn is_closed(&self) -> bool {
584        self.closed.load(Ordering::Acquire)
585    }
586
587    /// NEST-25: close it from this side — every call into the peer ends
588    /// `child_unavailable`, its mount goes, and the transport is told to
589    /// drop the socket.
590    pub fn close(&self, why: &str) {
591        self.ended(why);
592        if let Some(close) = &self.close {
593            close();
594        }
595    }
596
597    /// The principal the socket proved, if any.
598    pub fn principal(&self) -> Option<&str> {
599        self.principal.as_deref()
600    }
601
602    /// The name it is mounted under, once its offer was taken.
603    pub fn mount(&self) -> Option<String> {
604        self.mount.lock().unwrap().clone()
605    }
606
607    /// One inbound frame, before the method table sees it. `true`: taken —
608    /// the offer, or an answer or item of a call this side opened into the
609    /// peer; anything else is the transport's (a call into the service).
610    pub fn on_frame(self: &Arc<Self>, frame: &[u8]) -> bool {
611        let Ok(shape) = serde_json::from_slice::<Shape>(frame) else { return false };
612        match (&shape.method, &shape.id) {
613            // KEEL-8: the relay proves its key over a dialing peer's nonce.
614            (Some(m), Some(id)) if m == "_info" && self.peers.inner.key.is_some() && shape.params.as_ref().and_then(|p| p.get("nonce")).is_some_and(Value::is_string) => {
615                let nonce = shape.params.as_ref().and_then(|p| p.get("nonce")).and_then(Value::as_str).unwrap_or_default();
616                let commit = shape.params.as_ref().and_then(|p| p.get("commit")).and_then(Value::as_str);
617                self.prove(id, nonce, commit);
618                true
619            }
620            // NEST-25: a call back from the peer, under a call it serves —
621            // the mount's (NEST-11), once it is mounted.
622            (Some(m), Some(_)) if m == super::upcall::HOST_CALL || m == super::upcall::HOST_CALL_UNSUB => {
623                self.mount.lock().unwrap().is_some() && self.link.lock().unwrap().is_some() && self.inbound.send(frame.to_vec()).is_ok()
624            }
625            (Some(m), Some(id)) if *m == format!("{}.offer", self.peers.inner.service) => {
626                let (me, id, params) = (Arc::clone(self), id.clone(), shape.params.unwrap_or(Value::Null));
627                tokio::spawn(async move {
628                    let answer = me.offer(&id, params).await;
629                    let _ = me.out.send(answer);
630                });
631                true
632            }
633            // A response: to a request of this side's (rule 2) — when it has
634            // made any.
635            (None, Some(_)) => self.link.lock().unwrap().is_some() && self.inbound.send(frame.to_vec()).is_ok(),
636            // An item of a call this side opened (`params.result`).
637            (Some(_), None) => {
638                let item = shape.params.as_ref().is_some_and(|p| p.get("subscription").is_some() && p.get("result").is_some());
639                item && self.link.lock().unwrap().is_some() && self.inbound.send(frame.to_vec()).is_ok()
640            }
641            _ => false,
642        }
643    }
644
645    /// KEEL-8: `_info {nonce}` answered as a subscription of one item —
646    /// `{backend, key, proof}` — and its end.
647    fn prove(&self, id: &Value, nonce: &str, commit: Option<&str>) {
648        let Some(key) = &self.peers.inner.key else { return };
649        let service = &self.peers.inner.service;
650        let sid = format!("info-{}", self.id);
651        // KEEL-19: made for the dialing peer the socket proved, no other.
652        let asker = self.principal.clone().unwrap_or_default();
653        let mut content = json!({ "backend": service, "key": key.kid(), "proof": key.key_proof_for(nonce, service, &asker), "asker": asker });
654        // NEST-25: the host's nonce, fresh, after the node committed to its
655        // own (once per socket: a second `_info` gets none).
656        if let Some(commit) = commit {
657            let mut pairing = self.pairing.lock().unwrap();
658            if pairing.is_none() {
659                let host_nonce = crate::plexus::peer_token::random_nonce();
660                content["host_nonce"] = json!(host_nonce);
661                *pairing = Some((commit.to_string(), host_nonce));
662            }
663        }
664        let item = PlexusStreamItem::data(meta(service), "_info".into(), content);
665        let frames = [
666            json!({ "jsonrpc": "2.0", "id": id, "result": sid }),
667            json!({ "jsonrpc": "2.0", "method": "_info", "params": { "subscription": sid, "result": item } }),
668            json!({ "jsonrpc": "2.0", "method": "_info", "params": { "subscription": sid, "result": PlexusStreamItem::done(meta(service)) } }),
669        ];
670        for f in frames {
671            let _ = self.out.send(serde_json::to_vec(&f).unwrap_or_default());
672        }
673    }
674
675    /// The socket is gone: every call into the peer ends
676    /// `child_unavailable`, and its mount goes.
677    pub fn on_close(&self) {
678        self.ended("its connection closed");
679    }
680
681    /// Its end, once: the calls into it ended, its mount gone, the
682    /// admission told.
683    fn ended(&self, why: &str) {
684        let (first, name) = {
685            let mut m = self.mount.lock().unwrap();
686            (!self.closed.swap(true, Ordering::AcqRel), m.take())
687        };
688        if let Some((conn, shared)) = self.link.lock().unwrap().take() {
689            gone(&Arc::downgrade(&shared), &conn, why);
690        }
691        if let Some(name) = &name {
692            self.peers.unmount(name, self.id, why);
693        }
694        if first {
695            let admission = self.peers.inner.admission.read().unwrap().clone();
696            if let Some(a) = admission {
697                a.closed(self.id, name.as_deref(), why);
698            }
699        }
700    }
701
702    /// NEST-25: the pairing code and whether the node proved its key on this
703    /// connection, from what the offer reveals and signs.
704    fn paired(&self, params: &Value, principal: &str, name: &str) -> Result<(Option<String>, bool), OfferRefused> {
705        let Some((commit, host_nonce)) = self.pairing.lock().unwrap().clone() else { return Ok((None, false)) };
706        let Some(node_nonce) = params.get("pairing_nonce").and_then(Value::as_str) else { return Ok((None, false)) };
707        if !super::pairing::commits_to(&commit, node_nonce) {
708            return Err(OfferRefused::new("pairing_mismatch", "the offer's nonce is not the one committed to at `_info`"));
709        }
710        let host_key = self.peers.inner.key.as_ref().map(|k| k.kid().to_string()).unwrap_or_default();
711        let code = super::pairing::pairing_code(&host_key, principal, node_nonce, &host_nonce);
712        let proven = match (params.get("possession").and_then(Value::as_str), crate::plexus::peer_token::key_of(principal)) {
713            (Some(sig), Some(vk)) => {
714                let input = possession_input(&host_key, principal, node_nonce, &host_nonce, &self.peers.inner.service, name);
715                let sig = base64::Engine::decode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, sig).ok().and_then(|b| <[u8; 64]>::try_from(b.as_slice()).ok());
716                match sig {
717                    Some(sig) if vk.verify_strict(input.as_bytes(), &ed25519_dalek::Signature::from_bytes(&sig)).is_ok() => true,
718                    _ => return Err(OfferRefused::new("unauthenticated", format!("the offer's `possession` is not {principal}'s signature over this connection"))),
719                }
720            }
721            _ => false,
722        };
723        Ok((Some(code), proven))
724    }
725
726    async fn offer(self: &Arc<Self>, id: &Value, params: Value) -> Vec<u8> {
727        let peers = &self.peers;
728        let Some(namespace) = params.get("namespace").and_then(Value::as_str).map(str::to_string) else {
729            return refusal(id, -32602, "invalid_params", "an offer names its `namespace`");
730        };
731        let name = params.get("mount").and_then(Value::as_str).unwrap_or(&namespace).to_string();
732        if let Err(why) = valid_name(&name).and_then(|_| valid_name(&namespace).map_err(|w| format!("its namespace: {w}"))) {
733            return refusal(id, -32602, "invalid_params", &why);
734        }
735        let Some(principal) = self.principal.clone() else {
736            return refusal(id, -32001, "unauthenticated", "sign in first: an anonymous socket offers nothing");
737        };
738        // NEST-25: one offer a socket, decided before anything is asked of it.
739        if self.offering.swap(true, Ordering::AcqRel) {
740            return refusal(id, -32602, "invalid_params", "this socket has offered already");
741        }
742        let (code, key_proven) = match self.paired(&params, &principal, &name) {
743            Ok(p) => p,
744            Err(r) => return refusal(id, -32001, &r.kind, &r.message),
745        };
746        let offer = Offer { socket: self.id, name: name.clone(), namespace: namespace.clone(), principal: principal.clone(), key_proven, from: self.from.clone(), code: code.clone() };
747        let admission = peers.inner.admission.read().unwrap().clone();
748        if let Some(a) = &admission {
749            let decided = match a.decide(&offer) {
750                Decision::Admit => Ok(()),
751                Decision::Refuse(r) => Err(r),
752                Decision::Pending(wait) => {
753                    let notice = json!({ "jsonrpc": "2.0", "method": OFFER_PENDING, "params": { "id": id, "code": code } });
754                    let _ = self.out.send(serde_json::to_vec(&notice).unwrap_or_default());
755                    tracing::info!(target: "plexus::audit", peer = %name, %principal, from = ?self.from, "dial-in offer pending");
756                    wait.await
757                }
758            };
759            if let Err(r) = decided {
760                tracing::warn!(target: "plexus::audit", peer = %name, %principal, from = ?self.from, kind = %r.kind, "dial-in offer refused: {}", r.message);
761                return refusal(id, -32003, &r.kind, &r.message);
762            }
763            if self.is_closed() {
764                return refusal(id, -32000, "child_unavailable", "the socket closed while its offer waited");
765            }
766        }
767        let gate = peers.inner.gate.read().unwrap().clone();
768        if let Some(gate) = gate {
769            let grant = Grant::new(format!("{}.offer", peers.inner.ns));
770            if let Err(r) = gate.check(self.auth.as_ref(), &grant, Some(&name)) {
771                let (code, kind, message) = match r {
772                    Refusal::Unauthenticated | Refusal::Ended { .. } => (-32001, "unauthenticated", r.to_string()),
773                    Refusal::MissingGrant { .. } => (-32003, "forbidden", format!("{principal} holds no `{grant}` on `{name}`")),
774                };
775                return refusal(id, code, kind, &message);
776            }
777        }
778        if let Some(e) = peers.inner.table.read().unwrap().get(&name) {
779            if e.principal != principal {
780                return refusal(id, -32010, "name_taken", &format!("`{name}` is held by another principal's connection"));
781            }
782        }
783        // The calls into the peer ride this socket, from now (its schema first).
784        let path = format!("{}.{name}", peers.inner.ns);
785        let spec = ChildSpec::Ws { name: path.clone(), url: format!("dial-in:{principal}") };
786        let shared = Shared::new(spec, peers.inner.opts.clone(), peers.inner.principal.clone());
787        let conn = Conn::new(&path, None, self.out.clone(), peers.inner.opts.buffer, Arc::clone(&shared.counters));
788        let _ = conn.ns.set(namespace.clone());
789        // NEST-25: its calls back are the mount's, as a dialed child's; and
790        // a key it proved on this connection is its identity's (what consent
791        // and a minted token are bound to).
792        let _ = conn.up.set(Arc::clone(&shared.upcalls));
793        if key_proven {
794            let _ = conn.peer_key.set(principal.clone());
795        }
796        let _ = shared.identity.set(PeerIdentity::of(&conn));
797        shared.install(Arc::clone(&conn));
798        *self.link.lock().unwrap() = Some((Arc::clone(&conn), Arc::clone(&shared)));
799        let t0 = Instant::now();
800        let hop = json!({ "principal": peers.inner.principal, "for": [], "limit": null, "call": uuid::Uuid::new_v4().to_string() });
801        let asked = ask(&conn, &format!("{namespace}.call"), json!({ "method": format!("{namespace}.schema"), "params": {}, "hop": hop }), peers.inner.opts.timeout).await;
802        // NEST-4 (vision merge): a dial-in peer's static tree is walked and
803        // kept as a dialed child's is, within the same one timeout.
804        let mounted = match asked {
805            Ok(raw) => {
806                let deadline = t0 + peers.inner.opts.timeout;
807                shared.walk(&conn, &namespace, &raw, deadline).await.map(|nodes| Kept { top: raw, nodes })
808            }
809            Err(e) => Err(e),
810        };
811        let mounted = mounted.and_then(|kept| {
812            let hash = kept.hash();
813            let schema = mount_schema(&path, kept.top)?;
814            let nodes = kept.nodes.into_iter().map(|(p, raw)| node_schema(&p, raw).map(|s| (p, s))).collect::<Result<Vec<_>, _>>()?;
815            let _ = shared.mounted_hash.set(hash.clone());
816            Ok((schema, nodes, hash))
817        });
818        let (schema, nodes, hash) = match mounted {
819            Ok(m) => m,
820            Err(why) => {
821                self.link.lock().unwrap().take();
822                return refusal(id, -32000, "invalid_params", &format!("not mounted: {why}"));
823            }
824        };
825        let timings = MountTimings { spawn_ms: 0.0, schema_ms: t0.elapsed().as_secs_f64() * 1e3, merge_ms: 0.0 };
826        let methods: Vec<String> = schema.methods.iter().map(|m| m.name.clone()).collect();
827        let child = RemoteChild { inner: Arc::new(Inner::new(shared, schema, nodes, timings)) };
828        // NEST-16: its calls back are held to what it needs.
829        child.inner.shared.upcalls.set_needs(child.inner.needs.as_deref());
830        if let Some(a) = &admission {
831            if let Err(r) = a.vet(&offer, &child) {
832                self.link.lock().unwrap().take();
833                tracing::warn!(target: "plexus::audit", peer = %name, %principal, kind = %r.kind, "dial-in offer refused at its schema: {}", r.message);
834                return refusal(id, -32003, &r.kind, &r.message);
835            }
836        }
837        let replaced = {
838            let mut m = self.mount.lock().unwrap();
839            if self.is_closed() {
840                drop(m);
841                self.link.lock().unwrap().take();
842                return refusal(id, -32000, "child_unavailable", "the socket closed while it was mounted");
843            }
844            let replaced = peers.inner.table.write().unwrap().insert(name.clone(), Entry { child: child.clone(), principal: principal.clone(), namespace: namespace.clone(), socket: self.id, since: Instant::now(), holder: Arc::downgrade(self) });
845            *m = Some(name.clone());
846            replaced
847        };
848        if let Some(a) = &admission {
849            if let Err(r) = a.mounted(&offer, &child, self) {
850                // Out of this table again, as it was before the offer.
851                self.mount.lock().unwrap().take();
852                if let Some((conn, shared)) = self.link.lock().unwrap().take() {
853                    gone(&Arc::downgrade(&shared), &conn, &r.message);
854                }
855                {
856                    let mut t = peers.inner.table.write().unwrap();
857                    if t.get(&name).is_some_and(|e| e.socket == self.id) {
858                        t.remove(&name);
859                    }
860                    // Put back only while its socket is open (review R2-4): a
861                    // closed one would hold the name for its key until a restart.
862                    if let Some(old) = replaced.filter(|e| e.holder.upgrade().is_some_and(|s| !s.is_closed())) {
863                        t.entry(name.clone()).or_insert(old);
864                    }
865                }
866                tracing::warn!(target: "plexus::audit", peer = %name, %principal, kind = %r.kind, "dial-in offer refused as it was mounted: {}", r.message);
867                return refusal(id, -32003, &r.kind, &r.message);
868            }
869        }
870        if replaced.is_some() {
871            let _ = peers.inner.events.send(PeerEvent::Unmounted { name: name.clone(), why: "a new connection of the same principal took the name".into() });
872        }
873        tracing::info!(target: "plexus::peers", peer = %name, %principal, %namespace, methods = methods.len(), "peer mounted");
874        peers.moved();
875        let _ = peers.inner.events.send(PeerEvent::Mounted { name: name.clone(), principal, namespace: namespace.clone(), methods });
876        serde_json::to_vec(&json!({ "jsonrpc": "2.0", "id": id, "result": {
877            "offered": namespace,
878            "mount": name,
879            "path": path,
880            "schema_hash": params.get("schema_hash").cloned().unwrap_or(Value::String(hash)),
881            "service": { "namespace": peers.inner.service, "principal": peers.inner.principal },
882        } }))
883        .unwrap_or_default()
884    }
885}
886
887/// One unary call into the peer: the first `data`'s content.
888async fn ask(conn: &Conn, method: &str, params: Value, timeout: Duration) -> Result<Value, String> {
889    let (_, mut rx) = conn.open(method, params, timeout, None).await.map_err(|e| match e {
890        PlexusStreamItem::Error { message, .. } => message,
891        other => format!("{other:?}"),
892    })?;
893    let deadline = tokio::time::Instant::now() + timeout;
894    let mut first = None;
895    loop {
896        match tokio::time::timeout_at(deadline, rx.recv()).await {
897            Ok(Some(PlexusStreamItem::Data { content, .. })) => {
898                first.get_or_insert(content.into_value());
899            }
900            Ok(Some(PlexusStreamItem::Error { message, .. })) => return Err(message),
901            Ok(Some(PlexusStreamItem::Done { .. })) | Ok(None) => break,
902            Ok(Some(_)) => {}
903            Err(_) => return Err(format!("no answer in {timeout:?}")),
904        }
905    }
906    first.ok_or_else(|| "it answered no data".to_string())
907}
908
909#[async_trait]
910impl Activation for Peers {
911    type Methods = PeersMethods;
912
913    fn namespace(&self) -> &str {
914        &self.inner.ns
915    }
916
917    fn version(&self) -> &str {
918        env!("CARGO_PKG_VERSION")
919    }
920
921    fn description(&self) -> &str {
922        "The peers connected now: services that dialed in and offered a surface, each mounted by name while its socket lives"
923    }
924
925    fn methods(&self) -> Vec<&str> {
926        vec!["list", "watch", "offer"]
927    }
928
929    fn method_help(&self, method: &str) -> Option<String> {
930        self.own_methods().into_iter().find(|m| m.name == method).map(|m| m.description)
931    }
932
933    async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>, raw: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
934        match method {
935            "schema" => {
936                let schema = self.plugin_schema();
937                let content = match params.get("method").and_then(Value::as_str) {
938                    Some(m) => match schema.methods.iter().find(|x| x.name == m) {
939                        Some(ms) => serde_json::to_value(ms).unwrap_or_default(),
940                        None => return Err(PlexusError::MethodNotFound { activation: self.inner.ns.clone(), method: m.to_string() }),
941                    },
942                    None => serde_json::to_value(&schema).unwrap_or_default(),
943                };
944                let ns = &self.inner.ns;
945                let item = PlexusStreamItem::Data { metadata: meta(ns).into(), content_type: format!("{ns}.schema").into(), content: content.into() };
946                Ok(Box::pin(futures::stream::iter([item, self.done()])))
947            }
948            "list" => {
949                let items: Vec<PlexusStreamItem> = self.list().into_iter().map(|p| self.data("list", serde_json::to_value(p).unwrap_or_default())).chain([self.done()]).collect();
950                Ok(Box::pin(futures::stream::iter(items)))
951            }
952            "watch" => {
953                let mut rx = self.events();
954                let now: Vec<PeerEvent> = self
955                    .list()
956                    .into_iter()
957                    .map(|p| PeerEvent::Mounted { name: p.name, principal: p.principal, namespace: p.namespace, methods: p.methods })
958                    .collect();
959                let me = self.clone();
960                Ok(Box::pin(async_stream::stream! {
961                    for e in now {
962                        yield me.data("watch", serde_json::to_value(e).unwrap_or_default());
963                    }
964                    loop {
965                        match rx.recv().await {
966                            Ok(e) => yield me.data("watch", serde_json::to_value(e).unwrap_or_default()),
967                            Err(broadcast::error::RecvError::Lagged(_)) => continue,
968                            Err(broadcast::error::RecvError::Closed) => break,
969                        }
970                    }
971                    yield me.done();
972                }))
973            }
974            "offer" => Err(PlexusError::ExecutionError(format!(
975                "an offer is made on the peer's own socket, as `{}.offer` (spec/14), not called",
976                self.inner.service
977            ))),
978            m if m.contains('.') => route_to_child(self, m, params, auth, raw).await,
979            m if self.get(m).is_some() => Err(PlexusError::MethodNotFound { activation: format!("{}.{m}", self.inner.ns), method: String::new() }),
980            m => Err(PlexusError::MethodNotFound { activation: self.inner.ns.clone(), method: m.to_string() }),
981        }
982    }
983
984    /// Nothing of its own on the socket: reached through `{service}.call`,
985    /// behind the service's gate.
986    fn into_rpc_methods(self) -> jsonrpsee::Methods {
987        jsonrpsee::Methods::new()
988    }
989
990    /// Its own methods, and each peer connected now as a child (a method of
991    /// role `static_child` named for it), as the table stands.
992    fn plugin_schema(&self) -> PluginSchema {
993        let mut methods = self.own_methods();
994        let mut children = Vec::new();
995        for (name, e) in self.inner.table.read().unwrap().iter() {
996            let s = &e.child.inner.schema;
997            let description = format!("a peer: {} ({}, connected as {})", s.description, e.namespace, e.principal);
998            methods.push(MethodSchema::new(name.clone(), description.clone(), s.hash.clone()).with_role(MethodRole::StaticChild));
999            // IR-4's side-table, still what a client navigates by (synapse).
1000            children.push(crate::plexus::schema::ChildSummary { namespace: name.clone(), description, hash: s.hash.clone() });
1001        }
1002        let mut schema = PluginSchema::leaf(self.inner.ns.clone(), self.version(), self.description(), methods);
1003        #[allow(deprecated)]
1004        if !children.is_empty() {
1005            schema.children = Some(children);
1006        }
1007        let ns = &self.inner.ns;
1008        schema.roles.insert("viewer".into(), vec![format!("{ns}.list"), format!("{ns}.watch")]);
1009        schema
1010    }
1011}
1012
1013#[async_trait]
1014impl ChildRouter for Peers {
1015    fn router_namespace(&self) -> &str {
1016        &self.inner.ns
1017    }
1018
1019    async fn router_call(&self, method: &str, params: Value, auth: Option<&AuthContext>, raw: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
1020        Activation::call(self, method, params, auth, raw).await
1021    }
1022
1023    async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
1024        self.get(name).map(|c| Box::new(c) as Box<dyn ChildRouter>)
1025    }
1026
1027    async fn list_children(&self) -> Option<BoxStream<'_, String>> {
1028        Some(futures::stream::iter(self.names()).boxed())
1029    }
1030}
1031
1032#[cfg(test)]
1033mod tests {
1034    use super::*;
1035
1036    #[test]
1037    fn a_mount_name_is_one_segment_and_not_a_method() {
1038        assert!(valid_name("alice").is_ok());
1039        assert!(valid_name("a-b_9").is_ok());
1040        assert!(valid_name("a.b").is_err());
1041        assert!(valid_name("").is_err());
1042        assert!(valid_name("list").is_err());
1043    }
1044}