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