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
28use std::collections::BTreeMap;
29use std::sync::atomic::{AtomicU64, Ordering};
30use std::sync::{Arc, Mutex, RwLock};
31use std::time::{Duration, Instant};
32
33use async_trait::async_trait;
34use futures::stream::BoxStream;
35use futures::StreamExt;
36use plexus_auth_core::grants::{Gate, Grant, GrantSet, Refusal, RoleTable, Roles};
37use schemars::JsonSchema;
38use serde::{Deserialize, Serialize};
39use serde_json::{json, Value};
40use tokio::sync::{broadcast, mpsc};
41
42use super::link::{gone, meta, Conn, Kept, Shared};
43use super::{mount_schema, node_schema, Backoff, ChildOptions, ChildSpec, Inner, MountTimings, RemoteChild};
44use crate::plexus::auth::AuthContext;
45use crate::plexus::method_enum::MethodEnumSchema;
46use crate::plexus::plexus::{route_to_child, Activation, ChildRouter, PlexusError};
47use crate::plexus::schema::{Cardinality, MethodRole, MethodSchema, PluginSchema};
48use crate::plexus::streaming::PlexusStream;
49use crate::plexus::types::PlexusStreamItem;
50
51/// One peer, as `peers.list` names it.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
53pub struct PeerInfo {
54    /// The mount name: the peer is `peers.<name>`.
55    pub name: String,
56    /// The principal its socket proved at the upgrade (spec/00).
57    pub principal: String,
58    /// The namespace it offered (its own `{ns}`).
59    pub namespace: String,
60    /// Its methods, as its schema lists them.
61    pub methods: Vec<String>,
62    /// Seconds since it was mounted.
63    pub connected_secs: u64,
64}
65
66/// What `peers.watch` says: a peer came or went.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
68#[serde(tag = "type", rename_all = "snake_case")]
69pub enum PeerEvent {
70    /// Mounted (or, on a watch's start, mounted already).
71    Mounted { name: String, principal: String, namespace: String, methods: Vec<String> },
72    /// Its socket closed, or a new socket of the same principal took the name.
73    Unmounted { name: String, why: String },
74}
75
76/// [`Peers`]' own methods are named, not a Rust enum of the macro's.
77#[derive(Debug, Clone, Copy)]
78pub enum PeersMethods {}
79
80impl JsonSchema for PeersMethods {
81    fn schema_name() -> std::borrow::Cow<'static, str> {
82        "PeersMethods".into()
83    }
84
85    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
86        schemars::json_schema!({ "description": "list, watch, offer — and every peer connected, by its mount name" })
87    }
88}
89
90impl MethodEnumSchema for PeersMethods {
91    fn method_names() -> &'static [&'static str] {
92        &["list", "watch", "offer"]
93    }
94
95    fn schema_with_consts() -> Value {
96        serde_json::to_value(schemars::schema_for!(PeersMethods)).unwrap_or(Value::Null)
97    }
98}
99
100/// A mounted peer.
101struct Entry {
102    child: RemoteChild,
103    principal: String,
104    namespace: String,
105    socket: u64,
106    since: Instant,
107}
108
109impl Entry {
110    fn info(&self, name: &str) -> PeerInfo {
111        PeerInfo {
112            name: name.to_string(),
113            principal: self.principal.clone(),
114            namespace: self.namespace.clone(),
115            methods: self.child.inner.schema.methods.iter().map(|m| m.name.clone()).collect(),
116            connected_secs: self.since.elapsed().as_secs(),
117        }
118    }
119}
120
121struct PeersInner {
122    ns: String,
123    service: String,
124    principal: String,
125    gate: RwLock<Option<Arc<Gate>>>,
126    opts: ChildOptions,
127    table: RwLock<BTreeMap<String, Entry>>,
128    events: broadcast::Sender<PeerEvent>,
129    next_socket: AtomicU64,
130    on_change: RwLock<Vec<Box<dyn Fn() + Send + Sync>>>,
131    /// KEEL-8: the key the relay proves to a peer's `_info {nonce}`.
132    key: Option<Arc<crate::plexus::peer_token::PeerKey>>,
133}
134
135/// The peers connected now, as an activation: `peers.list`, `peers.watch`,
136/// and `peers.<name>.<method>` into each. Cheap to clone.
137#[derive(Clone)]
138pub struct Peers {
139    inner: Arc<PeersInner>,
140}
141
142impl std::fmt::Debug for Peers {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        f.debug_struct("Peers").field("ns", &self.inner.ns).field("names", &self.names()).finish()
145    }
146}
147
148/// A name a peer may be mounted under: one segment, not one of
149/// [`Peers`]' own methods.
150fn valid_name(name: &str) -> Result<(), String> {
151    if name.is_empty() || name.len() > 64 {
152        return Err("a mount name is 1–64 characters".into());
153    }
154    if let Some(bad) = name.chars().find(|c| !(c.is_ascii_alphanumeric() || *c == '_' || *c == '-')) {
155        return Err(format!("the mount name `{name}` holds `{bad}`: only letters, digits, `_` and `-`"));
156    }
157    if matches!(name, "list" | "watch" | "offer" | "schema") {
158        return Err(format!("`{name}` is one of the peers' own methods"));
159    }
160    Ok(())
161}
162
163impl Peers {
164    /// Peers mounted under `ns` (`peers`) of the service `service` (whose
165    /// `{service}.offer` a socket sends), calling into each as `principal`
166    /// (the hop's acting service: its key's principal, or `service:<ns>`).
167    pub fn new(ns: impl Into<String>, service: impl Into<String>, principal: impl Into<String>) -> Self {
168        let service = service.into();
169        let opts = ChildOptions {
170            // A dial-in peer is never redialed: it comes back by dialing again.
171            backoff: Backoff { initial: Duration::ZERO, max: Duration::ZERO, per_minute: 0 },
172            ..ChildOptions::for_service(&service)
173        };
174        Self {
175            inner: Arc::new(PeersInner {
176                ns: ns.into(),
177                service,
178                principal: principal.into(),
179                gate: RwLock::new(None),
180                opts,
181                table: RwLock::new(BTreeMap::new()),
182                events: broadcast::channel(256).0,
183                next_socket: AtomicU64::new(1),
184                on_change: RwLock::new(Vec::new()),
185                key: None,
186            }),
187        }
188    }
189
190    /// The gate that decides offers (`<ns>.offer` on the mount name). Calls
191    /// into a peer are decided by the service's own gate, as every call.
192    /// Without one every signed-in socket may offer.
193    pub fn with_gate(self, gate: Arc<Gate>) -> Self {
194        *self.inner.gate.write().unwrap() = Some(gate);
195        self
196    }
197
198    /// [`Self::with_gate`] on a `Peers` already registered (the gate is made
199    /// from the service's roles, which need the activation first).
200    pub fn set_gate(&self, gate: Arc<Gate>) {
201        *self.inner.gate.write().unwrap() = Some(gate);
202    }
203
204    /// Each call into a peer opens within this, and the peer's schema is
205    /// answered within it at the offer. Default 10 s.
206    pub fn with_timeout(self, timeout: Duration) -> Self {
207        let mut s = self;
208        if let Some(inner) = Arc::get_mut(&mut s.inner) {
209            inner.opts.timeout = timeout;
210        }
211        s
212    }
213
214    /// KEEL-8: the relay's own key. A peer dialing out names the relay by
215    /// it ([`DialOut::trust`](super::DialOut::trust)) and asks it proved:
216    /// a socket's `_info {nonce}` is answered `{backend, key, proof}` (the
217    /// nonce and the service's name signed, DYNAUTH-5's proof), and the
218    /// hop's acting service is this key's principal. Without one a peer
219    /// that dials out is refused at its `_info`.
220    pub fn with_key(self, key: crate::plexus::peer_token::PeerKey) -> Self {
221        let mut s = self;
222        if let Some(inner) = Arc::get_mut(&mut s.inner) {
223            inner.principal = key.kid().to_string();
224            inner.key = Some(Arc::new(key));
225        }
226        s
227    }
228
229    /// Call `f` whenever a peer is mounted or goes — the service's
230    /// [`DynamicHub::schema_moved`](crate::DynamicHub::schema_moved), so the
231    /// next `schema` it answers lists the peers as they stand.
232    pub fn on_change(&self, f: impl Fn() + Send + Sync + 'static) {
233        self.inner.on_change.write().unwrap().push(Box::new(f));
234    }
235
236    /// A peer came or went: the gate's grants moved (the roles grow and
237    /// shrink with the peers) and what the service describes moved.
238    fn moved(&self) {
239        if let Some(g) = self.inner.gate.read().unwrap().as_ref() {
240            g.generation().bump();
241        }
242        for f in self.inner.on_change.read().unwrap().iter() {
243            f();
244        }
245    }
246
247    /// The names mounted now.
248    pub fn names(&self) -> Vec<String> {
249        self.inner.table.read().unwrap().keys().cloned().collect()
250    }
251
252    /// Every peer mounted now.
253    pub fn list(&self) -> Vec<PeerInfo> {
254        self.inner.table.read().unwrap().iter().map(|(n, e)| e.info(n)).collect()
255    }
256
257    /// The peer mounted as `name`, if one is.
258    pub fn get(&self, name: &str) -> Option<RemoteChild> {
259        self.inner.table.read().unwrap().get(name).map(|e| e.child.clone())
260    }
261
262    /// Peers coming and going, from now.
263    pub fn events(&self) -> broadcast::Receiver<PeerEvent> {
264        self.inner.events.subscribe()
265    }
266
267    /// Roles over `base` that also hold what the peers connected now
268    /// declare (each peer's `roles`, under `<ns>.<name>.<method>`), and —
269    /// when `every` names a role — every method of every peer for it, with
270    /// `<ns>.list`, `<ns>.watch` and `<ns>.offer`. Answered from memory, as
271    /// the table stands at each check.
272    /// A `base` that is a [`RoleStore`](crate::plexus::RoleStore) (an
273    /// admin's `auth.role_set`) makes the result one too.
274    pub fn roles<R: Roles>(&self, base: R, every: Option<&str>) -> PeerRoles<R> {
275        PeerRoles { base, peers: self.clone(), every: every.map(str::to_string) }
276    }
277
278    /// A socket the transport accepted, signed in as `auth` (or anonymous).
279    /// Feed it every inbound frame ([`PeerSocket::on_frame`]) and its close
280    /// ([`PeerSocket::on_close`]); write every frame the receiver yields on
281    /// the socket, in order.
282    pub fn socket(&self, auth: Option<AuthContext>) -> (Arc<PeerSocket>, mpsc::UnboundedReceiver<Vec<u8>>) {
283        let (out, rx) = mpsc::unbounded_channel();
284        let (inbound, mut in_rx) = mpsc::unbounded_channel::<Vec<u8>>();
285        let socket = Arc::new(PeerSocket {
286            peers: self.clone(),
287            id: self.inner.next_socket.fetch_add(1, Ordering::Relaxed),
288            principal: auth.as_ref().and_then(|a| a.principal()).map(|p| p.to_string()),
289            auth,
290            out,
291            inbound,
292            link: Mutex::new(None),
293            mount: Mutex::new(None),
294        });
295        // The answers and items of this side's calls, routed in arrival
296        // order (spec/14 rule 7), never on the transport's reader.
297        let weak = Arc::downgrade(&socket);
298        tokio::spawn(async move {
299            while let Some(frame) = in_rx.recv().await {
300                let link = weak.upgrade().and_then(|s| s.link.lock().unwrap().clone());
301                if let Some((conn, _)) = link {
302                    conn.on_message(&frame).await;
303                }
304            }
305        });
306        (socket, rx)
307    }
308
309    fn unmount(&self, name: &str, socket: u64, why: &str) {
310        let removed = {
311            let mut t = self.inner.table.write().unwrap();
312            match t.get(name) {
313                Some(e) if e.socket == socket => t.remove(name),
314                _ => None,
315            }
316        };
317        if removed.is_some() {
318            tracing::info!(target: "plexus::peers", peer = %name, "peer unmounted: {why}");
319            self.moved();
320            let _ = self.inner.events.send(PeerEvent::Unmounted { name: name.to_string(), why: why.to_string() });
321        }
322    }
323
324    fn data(&self, method: &str, content: Value) -> PlexusStreamItem {
325        let ns = &self.inner.ns;
326        PlexusStreamItem::Data { metadata: meta(ns).into(), content_type: format!("{ns}.{method}").into(), content: content.into() }
327    }
328
329    fn done(&self) -> PlexusStreamItem {
330        PlexusStreamItem::Done { metadata: meta(&self.inner.ns) }
331    }
332
333    fn own_methods(&self) -> Vec<MethodSchema> {
334        let ns = &self.inner.ns;
335        vec![
336            MethodSchema::new("list", "The peers connected now: each one's mount name, principal, namespace and methods", "")
337                .with_cardinality(Cardinality::Many)
338                .with_returns(schemars::schema_for!(PeerInfo))
339                .with_grant(format!("{ns}.list"))
340                .with_content_hash(),
341            MethodSchema::new("watch", "Peers as they come and go: those mounted now, then each mount and unmount", "")
342                .with_cardinality(Cardinality::Many)
343                .with_returns(schemars::schema_for!(PeerEvent))
344                .with_grant(format!("{ns}.watch"))
345                .with_content_hash(),
346            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", "")
347                .with_cardinality(Cardinality::One)
348                .with_grant(format!("{ns}.offer"))
349                .with_content_hash(),
350        ]
351    }
352}
353
354/// [`Peers::roles`]: a role table that grows with the peers connected.
355pub struct PeerRoles<R = RoleTable> {
356    base: R,
357    peers: Peers,
358    every: Option<String>,
359}
360
361#[async_trait]
362impl<R: crate::plexus::RoleStore> crate::plexus::RoleStore for PeerRoles<R> {
363    async fn set(&self, role: &plexus_auth_core::audit::RoleName, grants: GrantSet) -> Result<(), crate::plexus::StoreError> {
364        self.base.set(role, grants).await
365    }
366}
367
368impl<R: Roles> Roles for PeerRoles<R> {
369    fn grants(&self, role: &plexus_auth_core::audit::RoleName) -> Option<GrantSet> {
370        let base = self.base.grants(role);
371        if matches!(base, Some(GrantSet::All)) {
372            return base;
373        }
374        let mut set = match base {
375            Some(GrantSet::Listed(s)) => s,
376            _ => Default::default(),
377        };
378        let every = self.every.as_deref() == Some(role.as_str());
379        let ns = &self.peers.inner.ns;
380        if every {
381            for m in ["list", "watch", "offer"] {
382                set.insert(Grant::new(format!("{ns}.{m}")));
383            }
384        }
385        let mut known = every || self.base.grants(role).is_some();
386        for (name, e) in self.peers.inner.table.read().unwrap().iter() {
387            let schema = &e.child.inner.schema;
388            if every {
389                set.extend(schema.methods.iter().map(|m| Grant::new(format!("{ns}.{name}.{}", m.name))));
390            }
391            // A peer's own roles are already `<ns>.<name>.<method>` (the mount
392            // requalified them under its path).
393            if let Some(gs) = schema.roles.get(role.as_str()) {
394                known = true;
395                set.extend(gs.iter().map(Grant::new));
396            }
397            // Its entry in `<ns>.schema` (a child's), seen by whoever may
398            // call something in it.
399            if every || schema.roles.get(role.as_str()).is_some_and(|g| !g.is_empty()) {
400                set.insert(Grant::new(format!("{ns}.{name}")));
401            }
402        }
403        known.then_some(GrantSet::Listed(set))
404    }
405
406    fn names(&self) -> Vec<plexus_auth_core::audit::RoleName> {
407        let mut names = self.base.names();
408        if let Some(e) = &self.every {
409            names.push(plexus_auth_core::audit::RoleName::new(e));
410        }
411        names
412    }
413}
414
415/// One accepted socket, as [`Peers`] sees it: the offer it may make, the
416/// answers and items of the calls made into it, its close.
417pub struct PeerSocket {
418    peers: Peers,
419    id: u64,
420    auth: Option<AuthContext>,
421    principal: Option<String>,
422    out: mpsc::UnboundedSender<Vec<u8>>,
423    inbound: mpsc::UnboundedSender<Vec<u8>>,
424    /// Once offered: the connection the calls into the peer ride.
425    link: Mutex<Option<(Arc<Conn>, Arc<Shared>)>>,
426    /// The name it is mounted under.
427    mount: Mutex<Option<String>>,
428}
429
430/// The parts of a frame its shape is read by (spec/14 rule 2).
431#[derive(Deserialize)]
432struct Shape {
433    #[serde(default)]
434    id: Option<Value>,
435    #[serde(default)]
436    method: Option<String>,
437    #[serde(default)]
438    params: Option<Value>,
439}
440
441/// A refusal of an offer: spec/05's error with a typed `data.error_kind`.
442fn refusal(id: &Value, code: i64, kind: &str, message: &str) -> Vec<u8> {
443    serde_json::to_vec(&json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message, "data": { "error_kind": kind } } })).unwrap_or_default()
444}
445
446impl PeerSocket {
447    /// The principal the socket proved, if any.
448    pub fn principal(&self) -> Option<&str> {
449        self.principal.as_deref()
450    }
451
452    /// The name it is mounted under, once its offer was taken.
453    pub fn mount(&self) -> Option<String> {
454        self.mount.lock().unwrap().clone()
455    }
456
457    /// One inbound frame, before the method table sees it. `true`: taken —
458    /// the offer, or an answer or item of a call this side opened into the
459    /// peer; anything else is the transport's (a call into the service).
460    pub fn on_frame(self: &Arc<Self>, frame: &[u8]) -> bool {
461        let Ok(shape) = serde_json::from_slice::<Shape>(frame) else { return false };
462        match (&shape.method, &shape.id) {
463            // KEEL-8: the relay proves its key over a dialing peer's nonce.
464            (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) => {
465                let nonce = shape.params.as_ref().and_then(|p| p.get("nonce")).and_then(Value::as_str).unwrap_or_default();
466                self.prove(id, nonce);
467                true
468            }
469            (Some(m), Some(id)) if *m == format!("{}.offer", self.peers.inner.service) => {
470                let (me, id, params) = (Arc::clone(self), id.clone(), shape.params.unwrap_or(Value::Null));
471                tokio::spawn(async move {
472                    let answer = me.offer(&id, params).await;
473                    let _ = me.out.send(answer);
474                });
475                true
476            }
477            // A response: to a request of this side's (rule 2) — when it has
478            // made any.
479            (None, Some(_)) => self.link.lock().unwrap().is_some() && self.inbound.send(frame.to_vec()).is_ok(),
480            // An item of a call this side opened (`params.result`).
481            (Some(_), None) => {
482                let item = shape.params.as_ref().is_some_and(|p| p.get("subscription").is_some() && p.get("result").is_some());
483                item && self.link.lock().unwrap().is_some() && self.inbound.send(frame.to_vec()).is_ok()
484            }
485            _ => false,
486        }
487    }
488
489    /// KEEL-8: `_info {nonce}` answered as a subscription of one item —
490    /// `{backend, key, proof}` — and its end.
491    fn prove(&self, id: &Value, nonce: &str) {
492        let Some(key) = &self.peers.inner.key else { return };
493        let service = &self.peers.inner.service;
494        let sid = format!("info-{}", self.id);
495        // KEEL-19: made for the dialing peer the socket proved, no other.
496        let asker = self.principal.clone().unwrap_or_default();
497        let content = json!({ "backend": service, "key": key.kid(), "proof": key.key_proof_for(nonce, service, &asker), "asker": asker });
498        let item = PlexusStreamItem::data(meta(service), "_info".into(), content);
499        let frames = [
500            json!({ "jsonrpc": "2.0", "id": id, "result": sid }),
501            json!({ "jsonrpc": "2.0", "method": "_info", "params": { "subscription": sid, "result": item } }),
502            json!({ "jsonrpc": "2.0", "method": "_info", "params": { "subscription": sid, "result": PlexusStreamItem::done(meta(service)) } }),
503        ];
504        for f in frames {
505            let _ = self.out.send(serde_json::to_vec(&f).unwrap_or_default());
506        }
507    }
508
509    /// The socket is gone: every call into the peer ends
510    /// `child_unavailable`, and its mount goes.
511    pub fn on_close(&self) {
512        let why = "its connection closed";
513        if let Some((conn, shared)) = self.link.lock().unwrap().take() {
514            gone(&Arc::downgrade(&shared), &conn, why);
515        }
516        if let Some(name) = self.mount.lock().unwrap().take() {
517            self.peers.unmount(&name, self.id, why);
518        }
519    }
520
521    async fn offer(self: &Arc<Self>, id: &Value, params: Value) -> Vec<u8> {
522        let peers = &self.peers;
523        let Some(namespace) = params.get("namespace").and_then(Value::as_str).map(str::to_string) else {
524            return refusal(id, -32602, "invalid_params", "an offer names its `namespace`");
525        };
526        let name = params.get("mount").and_then(Value::as_str).unwrap_or(&namespace).to_string();
527        if let Err(why) = valid_name(&name).and_then(|_| valid_name(&namespace).map_err(|w| format!("its namespace: {w}"))) {
528            return refusal(id, -32602, "invalid_params", &why);
529        }
530        let Some(principal) = self.principal.clone() else {
531            return refusal(id, -32001, "unauthenticated", "sign in first: an anonymous socket offers nothing");
532        };
533        let gate = peers.inner.gate.read().unwrap().clone();
534        if let Some(gate) = gate {
535            let grant = Grant::new(format!("{}.offer", peers.inner.ns));
536            if let Err(r) = gate.check(self.auth.as_ref(), &grant, Some(&name)) {
537                let (code, kind, message) = match r {
538                    Refusal::Unauthenticated | Refusal::Ended { .. } => (-32001, "unauthenticated", r.to_string()),
539                    Refusal::MissingGrant { .. } => (-32003, "forbidden", format!("{principal} holds no `{grant}` on `{name}`")),
540                };
541                return refusal(id, code, kind, &message);
542            }
543        }
544        if self.link.lock().unwrap().is_some() {
545            return refusal(id, -32602, "invalid_params", "this socket has offered already");
546        }
547        if let Some(e) = peers.inner.table.read().unwrap().get(&name) {
548            if e.principal != principal {
549                return refusal(id, -32010, "name_taken", &format!("`{name}` is held by another principal's connection"));
550            }
551        }
552        // The calls into the peer ride this socket, from now (its schema first).
553        let path = format!("{}.{name}", peers.inner.ns);
554        let spec = ChildSpec::Ws { name: path.clone(), url: format!("dial-in:{principal}") };
555        let shared = Shared::new(spec, peers.inner.opts.clone(), peers.inner.principal.clone());
556        let conn = Conn::new(&path, None, self.out.clone(), peers.inner.opts.buffer, Arc::clone(&shared.counters));
557        let _ = conn.ns.set(namespace.clone());
558        shared.install(Arc::clone(&conn));
559        *self.link.lock().unwrap() = Some((Arc::clone(&conn), Arc::clone(&shared)));
560        let t0 = Instant::now();
561        let hop = json!({ "principal": peers.inner.principal, "for": [], "limit": null, "call": uuid::Uuid::new_v4().to_string() });
562        let asked = ask(&conn, &format!("{namespace}.call"), json!({ "method": format!("{namespace}.schema"), "params": {}, "hop": hop }), peers.inner.opts.timeout).await;
563        // NEST-4 (vision merge): a dial-in peer's static tree is walked and
564        // kept as a dialed child's is, within the same one timeout.
565        let mounted = match asked {
566            Ok(raw) => {
567                let deadline = t0 + peers.inner.opts.timeout;
568                shared.walk(&conn, &namespace, &raw, deadline).await.map(|nodes| Kept { top: raw, nodes })
569            }
570            Err(e) => Err(e),
571        };
572        let mounted = mounted.and_then(|kept| {
573            let hash = kept.hash();
574            let schema = mount_schema(&path, kept.top)?;
575            let nodes = kept.nodes.into_iter().map(|(p, raw)| node_schema(&p, raw).map(|s| (p, s))).collect::<Result<Vec<_>, _>>()?;
576            let _ = shared.mounted_hash.set(hash.clone());
577            Ok((schema, nodes, hash))
578        });
579        let (schema, nodes, hash) = match mounted {
580            Ok(m) => m,
581            Err(why) => {
582                self.link.lock().unwrap().take();
583                return refusal(id, -32000, "invalid_params", &format!("not mounted: {why}"));
584            }
585        };
586        let timings = MountTimings { spawn_ms: 0.0, schema_ms: t0.elapsed().as_secs_f64() * 1e3, merge_ms: 0.0 };
587        let methods: Vec<String> = schema.methods.iter().map(|m| m.name.clone()).collect();
588        let child = RemoteChild { inner: Arc::new(Inner::new(shared, schema, nodes, timings)) };
589        // NEST-16: its calls back are held to what it needs.
590        child.inner.shared.upcalls.set_needs(child.inner.needs.as_deref());
591        let replaced = peers.inner.table.write().unwrap().insert(name.clone(), Entry { child, principal: principal.clone(), namespace: namespace.clone(), socket: self.id, since: Instant::now() });
592        *self.mount.lock().unwrap() = Some(name.clone());
593        if replaced.is_some() {
594            let _ = peers.inner.events.send(PeerEvent::Unmounted { name: name.clone(), why: "a new connection of the same principal took the name".into() });
595        }
596        tracing::info!(target: "plexus::peers", peer = %name, %principal, %namespace, methods = methods.len(), "peer mounted");
597        peers.moved();
598        let _ = peers.inner.events.send(PeerEvent::Mounted { name: name.clone(), principal, namespace: namespace.clone(), methods });
599        serde_json::to_vec(&json!({ "jsonrpc": "2.0", "id": id, "result": {
600            "offered": namespace,
601            "mount": name,
602            "path": path,
603            "schema_hash": params.get("schema_hash").cloned().unwrap_or(Value::String(hash)),
604            "service": { "namespace": peers.inner.service, "principal": peers.inner.principal },
605        } }))
606        .unwrap_or_default()
607    }
608}
609
610/// One unary call into the peer: the first `data`'s content.
611async fn ask(conn: &Conn, method: &str, params: Value, timeout: Duration) -> Result<Value, String> {
612    let (_, mut rx) = conn.open(method, params, timeout).await.map_err(|e| match e {
613        PlexusStreamItem::Error { message, .. } => message,
614        other => format!("{other:?}"),
615    })?;
616    let deadline = tokio::time::Instant::now() + timeout;
617    let mut first = None;
618    loop {
619        match tokio::time::timeout_at(deadline, rx.recv()).await {
620            Ok(Some(PlexusStreamItem::Data { content, .. })) => {
621                first.get_or_insert(content.into_value());
622            }
623            Ok(Some(PlexusStreamItem::Error { message, .. })) => return Err(message),
624            Ok(Some(PlexusStreamItem::Done { .. })) | Ok(None) => break,
625            Ok(Some(_)) => {}
626            Err(_) => return Err(format!("no answer in {timeout:?}")),
627        }
628    }
629    first.ok_or_else(|| "it answered no data".to_string())
630}
631
632#[async_trait]
633impl Activation for Peers {
634    type Methods = PeersMethods;
635
636    fn namespace(&self) -> &str {
637        &self.inner.ns
638    }
639
640    fn version(&self) -> &str {
641        env!("CARGO_PKG_VERSION")
642    }
643
644    fn description(&self) -> &str {
645        "The peers connected now: services that dialed in and offered a surface, each mounted by name while its socket lives"
646    }
647
648    fn methods(&self) -> Vec<&str> {
649        vec!["list", "watch", "offer"]
650    }
651
652    fn method_help(&self, method: &str) -> Option<String> {
653        self.own_methods().into_iter().find(|m| m.name == method).map(|m| m.description)
654    }
655
656    async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>, raw: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
657        match method {
658            "schema" => {
659                let schema = self.plugin_schema();
660                let content = match params.get("method").and_then(Value::as_str) {
661                    Some(m) => match schema.methods.iter().find(|x| x.name == m) {
662                        Some(ms) => serde_json::to_value(ms).unwrap_or_default(),
663                        None => return Err(PlexusError::MethodNotFound { activation: self.inner.ns.clone(), method: m.to_string() }),
664                    },
665                    None => serde_json::to_value(&schema).unwrap_or_default(),
666                };
667                let ns = &self.inner.ns;
668                let item = PlexusStreamItem::Data { metadata: meta(ns).into(), content_type: format!("{ns}.schema").into(), content: content.into() };
669                Ok(Box::pin(futures::stream::iter([item, self.done()])))
670            }
671            "list" => {
672                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();
673                Ok(Box::pin(futures::stream::iter(items)))
674            }
675            "watch" => {
676                let mut rx = self.events();
677                let now: Vec<PeerEvent> = self
678                    .list()
679                    .into_iter()
680                    .map(|p| PeerEvent::Mounted { name: p.name, principal: p.principal, namespace: p.namespace, methods: p.methods })
681                    .collect();
682                let me = self.clone();
683                Ok(Box::pin(async_stream::stream! {
684                    for e in now {
685                        yield me.data("watch", serde_json::to_value(e).unwrap_or_default());
686                    }
687                    loop {
688                        match rx.recv().await {
689                            Ok(e) => yield me.data("watch", serde_json::to_value(e).unwrap_or_default()),
690                            Err(broadcast::error::RecvError::Lagged(_)) => continue,
691                            Err(broadcast::error::RecvError::Closed) => break,
692                        }
693                    }
694                    yield me.done();
695                }))
696            }
697            "offer" => Err(PlexusError::ExecutionError(format!(
698                "an offer is made on the peer's own socket, as `{}.offer` (spec/14), not called",
699                self.inner.service
700            ))),
701            m if m.contains('.') => route_to_child(self, m, params, auth, raw).await,
702            m if self.get(m).is_some() => Err(PlexusError::MethodNotFound { activation: format!("{}.{m}", self.inner.ns), method: String::new() }),
703            m => Err(PlexusError::MethodNotFound { activation: self.inner.ns.clone(), method: m.to_string() }),
704        }
705    }
706
707    /// Nothing of its own on the socket: reached through `{service}.call`,
708    /// behind the service's gate.
709    fn into_rpc_methods(self) -> jsonrpsee::Methods {
710        jsonrpsee::Methods::new()
711    }
712
713    /// Its own methods, and each peer connected now as a child (a method of
714    /// role `static_child` named for it), as the table stands.
715    fn plugin_schema(&self) -> PluginSchema {
716        let mut methods = self.own_methods();
717        let mut children = Vec::new();
718        for (name, e) in self.inner.table.read().unwrap().iter() {
719            let s = &e.child.inner.schema;
720            let description = format!("a peer: {} ({}, connected as {})", s.description, e.namespace, e.principal);
721            methods.push(MethodSchema::new(name.clone(), description.clone(), s.hash.clone()).with_role(MethodRole::StaticChild));
722            // IR-4's side-table, still what a client navigates by (synapse).
723            children.push(crate::plexus::schema::ChildSummary { namespace: name.clone(), description, hash: s.hash.clone() });
724        }
725        let mut schema = PluginSchema::leaf(self.inner.ns.clone(), self.version(), self.description(), methods);
726        #[allow(deprecated)]
727        if !children.is_empty() {
728            schema.children = Some(children);
729        }
730        let ns = &self.inner.ns;
731        schema.roles.insert("viewer".into(), vec![format!("{ns}.list"), format!("{ns}.watch")]);
732        schema
733    }
734}
735
736#[async_trait]
737impl ChildRouter for Peers {
738    fn router_namespace(&self) -> &str {
739        &self.inner.ns
740    }
741
742    async fn router_call(&self, method: &str, params: Value, auth: Option<&AuthContext>, raw: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
743        Activation::call(self, method, params, auth, raw).await
744    }
745
746    async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
747        self.get(name).map(|c| Box::new(c) as Box<dyn ChildRouter>)
748    }
749
750    async fn list_children(&self) -> Option<BoxStream<'_, String>> {
751        Some(futures::stream::iter(self.names()).boxed())
752    }
753}
754
755#[cfg(test)]
756mod tests {
757    use super::*;
758
759    #[test]
760    fn a_mount_name_is_one_segment_and_not_a_method() {
761        assert!(valid_name("alice").is_ok());
762        assert!(valid_name("a-b_9").is_ok());
763        assert!(valid_name("a.b").is_err());
764        assert!(valid_name("").is_err());
765        assert!(valid_name("list").is_err());
766    }
767}