Skip to main content

plexus_core/plexus/
peer.rs

1//! NEST-7 — **the primitive: an activation returns an activation.**
2//!
3//! A *peer* is an activation found by name, in this process or across the
4//! network; the caller cannot tell which. An activation returns one from a
5//! `#[plexus_macros::peer]` method:
6//!
7//! ```ignore
8//! #[plexus_macros::peer(list = "integrations")]
9//! async fn integration(&self, name: &str) -> Result<Box<dyn forge::ForgePeer>, PeerError>; // typed
10//! #[plexus_macros::peer(list = "dendrites", search = "find")]
11//! async fn dendrite(&self, name: &str) -> Result<Box<dyn Peer>, PeerError>;               // untyped
12//! ```
13//!
14//! - [`Peer`] is the erased activation (`dyn Activation` cannot be written:
15//!   `Activation` has an associated type). Every `Activation + ChildRouter`
16//!   is one (the blanket impl below), `RemoteChild` included.
17//! - [`Interface`] is a peer's shape, named and content-addressed: the IR of
18//!   what it serves, its hash, and each method's own hash; two peers with one
19//!   hash serve one shape, and [`Interface::satisfies`] is the shape check.
20//! - [`PeerError`] is why a peer could not be returned, typed on the wire as
21//!   an error item whose `error_kind` is the variant (`not_grafted`,
22//!   `shape_mismatch`, …), never "method not found".
23//! - A contract (a bodiless activation every method of which answers
24//!   `Result<T, E>`) is a typed slot's interface: the macro emits
25//!   `trait ForgePeer: Forge + Peer`, its [`Contract`] (the interface and the
26//!   [`Stamp`] its client was generated from), and `ForgePeer` for the
27//!   client over a [`PeerTransport`], which checks the backend's interface
28//!   against the stamp — equal, go; it still [`satisfies`](Interface::satisfies)
29//!   the stamp, say `drift` once and go; else [`PeerError::ShapeMismatch`] —
30//!   and again whenever an item's `plexus_hash` moves.
31
32use std::collections::{BTreeMap, HashMap};
33use std::sync::{Arc, Mutex, OnceLock};
34
35use async_trait::async_trait;
36use futures::StreamExt;
37use schemars::JsonSchema;
38use serde::{Deserialize, Serialize};
39use serde_json::Value;
40
41use super::auth::AuthContext;
42use super::content_hash::{canonical_json, hash16};
43use super::ir::ServiceIr;
44use super::plexus::{Activation, ChildRouter, PlexusError};
45use super::schema::{MethodRole, MethodSchema, PluginSchema};
46use super::streaming::PlexusStream;
47use super::types::{PlexusStreamItem, StreamMetadata};
48use plexus_client::{DenyReason, OtherError, RemoteError};
49
50// ===========================================================================
51// PeerError
52// ===========================================================================
53
54/// Why a peer could not be returned — each failure typed, on the wire as an
55/// error item whose `error_kind` is the variant's snake_case name, its fields
56/// beside it.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, thiserror::Error)]
58#[serde(tag = "error_kind", rename_all = "snake_case")]
59pub enum PeerError {
60    /// No peer by this name.
61    #[error("no peer named `{name}`")]
62    NotFound { name: String },
63    /// A graft point with nothing grafted under this name (GRAFT-1).
64    #[error("nothing is grafted at `{at}` as `{name}` (it would serve `{interface}`)")]
65    NotGrafted { at: String, name: String, interface: String },
66    /// The peer is there but cannot be reached.
67    #[error("the peer is unavailable: {reason}")]
68    Unavailable { reason: String },
69    /// The peer serves another shape: `wanted` and `got` are interface
70    /// hashes, `methods` the methods missing or changed.
71    #[error("the peer serves another shape (wanted {wanted}, got {got}): {}", methods.join(", "))]
72    ShapeMismatch { wanted: String, got: String, methods: Vec<String> },
73    /// The peer did not answer in time.
74    #[error("the peer did not answer in time")]
75    Timeout,
76    /// The caller may not reach this peer.
77    #[error("not allowed: {grant}")]
78    Forbidden { grant: String },
79}
80
81impl PeerError {
82    /// The wire's `error_kind`.
83    pub fn kind(&self) -> &'static str {
84        match self {
85            PeerError::NotFound { .. } => "not_found",
86            PeerError::NotGrafted { .. } => "not_grafted",
87            PeerError::Unavailable { .. } => "unavailable",
88            PeerError::ShapeMismatch { .. } => "shape_mismatch",
89            PeerError::Timeout => "timeout",
90            PeerError::Forbidden { .. } => "forbidden",
91        }
92    }
93
94    /// As the typed error an error item carries: a kind plexus-client does
95    /// not know is [`RemoteError::Other`] with its fields; `forbidden` is the
96    /// known refusal, naming the grant.
97    pub fn to_remote(&self) -> RemoteError {
98        match self {
99            PeerError::Forbidden { grant } => RemoteError::Forbidden {
100                reason: DenyReason::MissingGrant { grant: grant.clone(), scope: "*".into(), roles: vec![], held_on: vec![] },
101            },
102            other => {
103                let mut fields = match serde_json::to_value(other) {
104                    Ok(Value::Object(m)) => m,
105                    _ => serde_json::Map::new(),
106                };
107                fields.remove("error_kind");
108                RemoteError::Other(OtherError { kind: other.kind().into(), fields })
109            }
110        }
111    }
112
113    /// Back from the typed error an error item carries, when it is one.
114    pub fn from_remote(e: &RemoteError) -> Option<PeerError> {
115        match e {
116            RemoteError::Forbidden { reason: DenyReason::MissingGrant { grant, .. } } => Some(PeerError::Forbidden { grant: grant.clone() }),
117            RemoteError::Other(o) => {
118                let mut m = o.fields.clone();
119                m.insert("error_kind".into(), Value::String(o.kind.clone()));
120                serde_json::from_value(Value::Object(m)).ok()
121            }
122            _ => None,
123        }
124    }
125
126    /// From an error item, when it carries one.
127    pub fn from_item(item: &PlexusStreamItem) -> Option<PeerError> {
128        item.remote_error().and_then(PeerError::from_remote)
129    }
130
131    /// From a client's failure: a typed peer error the server sent, else the
132    /// peer unavailable, saying why.
133    pub fn from_client(e: &plexus_client::ClientError) -> PeerError {
134        if let plexus_client::ClientError::Remote(r) = e {
135            if let Some(p) = PeerError::from_remote(r) {
136                return p;
137            }
138        }
139        PeerError::Unavailable { reason: e.to_string() }
140    }
141
142    /// The error item a caller gets for it.
143    pub fn item(&self, provenance: Vec<String>) -> PlexusStreamItem {
144        let metadata = StreamMetadata::new(provenance, super::context::PlexusContext::hash());
145        let mut item = PlexusStreamItem::error(metadata, self.to_remote(), matches!(self, PeerError::Unavailable { .. } | PeerError::Timeout));
146        if let PlexusStreamItem::Error { message, .. } = &mut item {
147            *message = self.to_string();
148        }
149        item
150    }
151
152    /// A stream of the one error item.
153    pub fn stream(&self, provenance: Vec<String>) -> PlexusStream {
154        let item = self.item(provenance);
155        Box::pin(futures::stream::once(async move { item }))
156    }
157}
158
159// ===========================================================================
160// Interface
161// ===========================================================================
162
163/// A peer's shape, named and content-addressed: what `<ns>.ir` answers for
164/// it, its hash, and each method's own hash. Two interfaces with one hash
165/// serve one shape (descriptions, grants and the name aside).
166#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
167pub struct Interface {
168    /// The interface's name: a contract's namespace (`"forge"`), or the
169    /// peer's own.
170    pub name: String,
171    /// The shape's hash: of every method's own hash, by name.
172    pub hash: String,
173    /// The IR of the shape (IR 3.0, as `<ns>.ir` writes it).
174    pub ir: ServiceIr,
175    /// Each method's own hash, by name ([`Interface::method_hash`]).
176    #[serde(default)]
177    pub methods: BTreeMap<String, String>,
178    /// The schema the interface was read from: what a gate indexes for a
179    /// typed slot (its methods' grants, targets and roles).
180    pub schema: Box<PluginSchema>,
181}
182
183impl PartialEq for Interface {
184    fn eq(&self, other: &Self) -> bool {
185        self.name == other.name && self.hash == other.hash
186    }
187}
188impl Eq for Interface {}
189
190/// Interfaces already built, by schema hash and name: an activation's
191/// `interface()` is asked on every peer it becomes.
192fn cache() -> &'static Mutex<HashMap<(String, String), Interface>> {
193    static CACHE: OnceLock<Mutex<HashMap<(String, String), Interface>>> = OnceLock::new();
194    CACHE.get_or_init(Default::default)
195}
196
197impl Interface {
198    /// The interface of `schema`, named after its namespace.
199    pub fn of(schema: &PluginSchema) -> Self {
200        Self::named(&schema.namespace, schema)
201    }
202
203    /// The interface of `schema`, named `name`.
204    pub fn named(name: &str, schema: &PluginSchema) -> Self {
205        let key = (name.to_string(), if schema.hash.is_empty() { canonical_json(&serde_json::to_value(schema).unwrap_or_default()) } else { schema.hash.clone() });
206        if let Some(i) = cache().lock().unwrap_or_else(|p| p.into_inner()).get(&key) {
207            return i.clone();
208        }
209        let methods: BTreeMap<String, String> = schema
210            .methods
211            .iter()
212            .filter(|m| !m.is_auto_schema() && matches!(m.role, MethodRole::Rpc))
213            .map(|m| (m.name.clone(), Self::method_hash(m)))
214            .collect();
215        let hash = hash16(canonical_json(&serde_json::to_value(&methods).unwrap_or_default()).as_bytes());
216        let mut schemas = BTreeMap::new();
217        schemas.insert(Vec::<String>::new(), serde_json::to_value(schema).unwrap_or_default());
218        let ir = super::ir::answer(name, &[vec![]], &schemas).unwrap_or_else(|_| null_ir());
219        let i = Interface { name: name.to_string(), hash, ir, methods, schema: Box::new(schema.clone()) };
220        cache().lock().unwrap_or_else(|p| p.into_inner()).insert(key, i.clone());
221        i
222    }
223
224    /// The interface of a peer that describes nothing (a hand-written
225    /// router): no methods, an empty hash.
226    pub fn unknown(name: &str) -> Self {
227        Interface {
228            name: name.to_string(),
229            hash: String::new(),
230            ir: null_ir(),
231            methods: BTreeMap::new(),
232            schema: Box::new(PluginSchema::leaf(name, "", "", vec![])),
233        }
234    }
235
236    /// A method's own hash: of its shape — its name, params, item, error,
237    /// progress, cardinality, input and role — not its description, grant
238    /// or hash, which say nothing of what crosses the wire.
239    pub fn method_hash(m: &MethodSchema) -> String {
240        let shape = serde_json::json!({
241            "name": m.name,
242            "params": m.params,
243            "returns": m.returns,
244            "error": m.error,
245            "progress": m.progress,
246            "cardinality": m.cardinality,
247            "input": m.input,
248            "role": m.role,
249        });
250        hash16(canonical_json(&shape).as_bytes())
251    }
252
253    /// The schema the interface was read from.
254    pub fn schema(&self) -> &PluginSchema {
255        &self.schema
256    }
257
258    /// The methods `wanted` has that `self` lacks or serves under another
259    /// hash, by name.
260    pub fn moved_from(&self, wanted: &BTreeMap<String, String>) -> Vec<String> {
261        wanted.iter().filter(|(name, hash)| self.methods.get(*name) != Some(*hash)).map(|(n, _)| n.clone()).collect()
262    }
263
264    /// GRAFT-1's shape check: does `self` serve at least `wanted`? Every
265    /// method `wanted` has, under the same hash; `Err` names the methods
266    /// missing or changed.
267    pub fn satisfies(&self, wanted: &Interface) -> Result<(), PeerError> {
268        if self.hash == wanted.hash {
269            return Ok(());
270        }
271        let moved = self.moved_from(&wanted.methods);
272        if moved.is_empty() {
273            Ok(())
274        } else {
275            Err(PeerError::ShapeMismatch { wanted: wanted.hash.clone(), got: self.hash.clone(), methods: moved })
276        }
277    }
278}
279
280fn null_ir() -> ServiceIr {
281    ServiceIr(Arc::from(serde_json::value::RawValue::from_string("null".into()).expect("null is JSON")))
282}
283
284// ===========================================================================
285// Peer
286// ===========================================================================
287
288/// What a peer is: an activation, erased — `dyn Activation` cannot be
289/// written (the associated `Methods` type), so this is the object-safe form.
290/// Every `Activation + ChildRouter` is one.
291#[async_trait]
292pub trait Peer: Send + Sync {
293    /// The shape this peer serves.
294    fn interface(&self) -> Interface;
295    /// Call one of its methods (`repos`, or a path below it: `child.m`).
296    async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>) -> Result<PlexusStream, PlexusError>;
297    /// The primitive, one level down: this peer's own peers by name.
298    async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError>;
299}
300
301/// Every activation is a peer, local or remote: `RemoteChild` is an
302/// `Activation + ChildRouter`, so it is one too.
303#[async_trait]
304impl<T: Activation + ChildRouter> Peer for T {
305    fn interface(&self) -> Interface {
306        Interface::of(&Activation::plugin_schema(self))
307    }
308
309    async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>) -> Result<PlexusStream, PlexusError> {
310        Activation::call(self, method, params, auth, None).await
311    }
312
313    async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
314        match ChildRouter::peer_child(self, name).await? {
315            Some(router) => Ok(Box::new(RouterPeer::new(router))),
316            None => Err(PeerError::NotFound { name: name.to_string() }),
317        }
318    }
319}
320
321/// A child router (what routing holds) as a peer.
322pub struct RouterPeer {
323    router: Box<dyn ChildRouter>,
324}
325
326impl RouterPeer {
327    pub fn new(router: Box<dyn ChildRouter>) -> Self {
328        Self { router }
329    }
330}
331
332#[async_trait]
333impl Peer for RouterPeer {
334    fn interface(&self) -> Interface {
335        match self.router.router_schema() {
336            Some(s) => Interface::of(&s),
337            None => Interface::unknown(self.router.router_namespace()),
338        }
339    }
340
341    async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>) -> Result<PlexusStream, PlexusError> {
342        self.router.router_call(method, params, auth, None).await
343    }
344
345    async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
346        match self.router.peer_child(name).await? {
347            Some(router) => Ok(Box::new(RouterPeer::new(router))),
348            None => Err(PeerError::NotFound { name: name.to_string() }),
349        }
350    }
351}
352
353/// A peer as a child router: what a `#[peer]` slot hands routing. Calls go
354/// to the peer's `call`; its own peers are its children.
355pub struct PeerRouter {
356    peer: Box<dyn Peer>,
357    namespace: String,
358}
359
360impl PeerRouter {
361    pub fn new(peer: Box<dyn Peer>) -> Self {
362        let namespace = peer.interface().name;
363        Self { peer, namespace }
364    }
365}
366
367#[async_trait]
368impl ChildRouter for PeerRouter {
369    fn router_namespace(&self) -> &str {
370        &self.namespace
371    }
372
373    async fn router_call(
374        &self,
375        method: &str,
376        params: Value,
377        auth: Option<&AuthContext>,
378        _raw_ctx: Option<&crate::request::RawRequestContext>,
379    ) -> Result<PlexusStream, PlexusError> {
380        self.peer.call(method, params, auth).await
381    }
382
383    async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
384        self.peer.peer(name).await.ok().map(|p| Box::new(PeerRouter::new(p)) as Box<dyn ChildRouter>)
385    }
386
387    async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, PeerError> {
388        let p = self.peer.peer(name).await?;
389        Ok(Some(Box::new(PeerRouter::new(p))))
390    }
391
392    fn router_schema(&self) -> Option<PluginSchema> {
393        let i = self.peer.interface();
394        (!i.hash.is_empty()).then(|| i.schema().clone())
395    }
396}
397
398/// How a `#[peer]` slot finds a peer by name: the slot's function, with
399/// its activation.
400pub type FindPeer = Arc<dyn Fn(String) -> futures::future::BoxFuture<'static, Result<Box<dyn Peer>, PeerError>> + Send + Sync>;
401
402/// A `#[peer]` slot as routing holds it: reached as `<parent>.<slot>`, its
403/// children are the peers the slot's function returns by name — a typed
404/// slot's checked against its interface first (`ShapeMismatch` by interface
405/// hash). `<parent>.<slot>.<name>.<method>` is a peer's method.
406pub struct PeerSlot {
407    namespace: String,
408    interface: Option<Interface>,
409    find: FindPeer,
410    list: Option<ListPeers>,
411}
412
413/// How a `#[peer]` slot lists its names: its `list` sibling, collected.
414pub type ListPeers = Arc<dyn Fn() -> futures::future::BoxFuture<'static, Vec<String>> + Send + Sync>;
415
416impl PeerSlot {
417    /// The slot `name` (`integration`), typed by `interface` (or not).
418    pub fn new(name: impl Into<String>, interface: Option<Interface>, find: FindPeer) -> Self {
419        Self { namespace: name.into(), interface, find, list: None }
420    }
421
422    /// The slot's names, listed (`#[peer(list = "…")]`): its schema lists
423    /// each as a child, so a navigator steps to `<slot>.<name>`.
424    pub fn with_list(mut self, list: ListPeers) -> Self {
425        self.list = Some(list);
426        self
427    }
428
429    /// The slot as a schema: one dynamic child (any name), typed by the
430    /// slot's interface.
431    pub fn schema(&self) -> PluginSchema {
432        let entry = MethodSchema::new(self.namespace.clone(), "a peer, by name".to_string(), String::new())
433            .with_role(MethodRole::DynamicChild {
434                list_method: None,
435                search_method: None,
436                child: self.interface.as_ref().map(|i| Box::new(i.schema().clone())),
437            })
438            .with_content_hash();
439        let mut s = PluginSchema::leaf(&self.namespace, "", "a peer slot", vec![entry]);
440        s.hash = hash16(self.namespace.as_bytes());
441        s
442    }
443
444    /// The peer named `name`, checked against the slot's interface.
445    pub async fn get(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
446        let peer = (self.find)(name.to_string()).await?;
447        if let Some(wanted) = &self.interface {
448            peer.interface().satisfies(wanted)?;
449        }
450        Ok(peer)
451    }
452}
453
454#[async_trait]
455impl ChildRouter for PeerSlot {
456    fn router_namespace(&self) -> &str {
457        &self.namespace
458    }
459
460    async fn router_call(
461        &self,
462        method: &str,
463        params: Value,
464        auth: Option<&AuthContext>,
465        raw_ctx: Option<&crate::request::RawRequestContext>,
466    ) -> Result<PlexusStream, PlexusError> {
467        // The slot's own schema: one dynamic child, any name — what a
468        // navigator (synapse) reads to step from `host.integration` to
469        // `host.integration.github`.
470        if method == "schema" {
471            let mut schema = self.schema();
472            if let Some(list) = &self.list {
473                let hash = self.interface.as_ref().map(|i| i.hash.clone());
474                #[allow(deprecated)]
475                {
476                    schema.children = Some(
477                        list()
478                            .await
479                            .into_iter()
480                            .map(|name| super::schema::ChildSummary {
481                                // Each name its own: a navigator keys its cache, and
482                                // its cycle check, by this hash.
483                                hash: hash16(format!("{}:{}.{name}", hash.clone().unwrap_or_default(), self.namespace).as_bytes()),
484                                description: format!("the peer `{name}`"),
485                                namespace: name,
486                            })
487                            .collect(),
488                    );
489                }
490            }
491            let content = serde_json::to_value(super::schema::SchemaResult::Plugin(schema)).unwrap_or_default();
492            let metadata = StreamMetadata::new(vec![self.namespace.clone()], super::context::PlexusContext::hash());
493            let items = vec![
494                PlexusStreamItem::data(metadata.clone(), format!("{}.schema", self.namespace), content),
495                PlexusStreamItem::done(metadata),
496            ];
497            return Ok(Box::pin(futures::stream::iter(items)));
498        }
499        super::plexus::route_to_child(self, method, params, auth, raw_ctx).await
500    }
501
502    async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
503        self.peer_child(name).await.ok().flatten()
504    }
505
506    async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, PeerError> {
507        let peer = self.get(name).await?;
508        Ok(Some(Box::new(PeerRouter::new(peer))))
509    }
510
511    fn router_schema(&self) -> Option<PluginSchema> {
512        Some(self.schema())
513    }
514}
515
516// ===========================================================================
517// Contracts, stamps and the client's check
518// ===========================================================================
519
520/// A contract's shape, as a typed slot names it: implemented by the macro for
521/// `dyn ForgePeer` (a contract's peer trait).
522pub trait Contract {
523    /// The contract's interface, at compile time's schema.
524    fn interface() -> Interface;
525    /// What its client was generated from.
526    fn stamp() -> &'static Stamp;
527}
528
529/// What a generated client was built against: the interface's name, the
530/// backend crate's version, the interface hash and each method's hash.
531#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
532pub struct Stamp {
533    pub interface: String,
534    pub version: String,
535    pub hash: String,
536    pub methods: Vec<(String, String)>,
537}
538
539impl Stamp {
540    /// The stamp of `interface`, at `version`.
541    pub fn of(version: &str, interface: &Interface) -> Self {
542        Stamp {
543            interface: interface.name.clone(),
544            version: version.to_string(),
545            hash: interface.hash.clone(),
546            methods: interface.methods.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
547        }
548    }
549
550    fn method_map(&self) -> BTreeMap<String, String> {
551        self.methods.iter().cloned().collect()
552    }
553}
554
555/// The backend's interface moved but still serves every method the stamp
556/// has: said once.
557#[derive(Debug, Clone, PartialEq, Eq)]
558pub struct Drift {
559    pub from: String,
560    pub to: String,
561}
562
563#[derive(Default)]
564struct CheckState {
565    /// The backend's interface, as last checked.
566    interface: Option<Interface>,
567    /// The stamp's methods it serves under another hash, or not at all.
568    moved: Vec<String>,
569    /// The last `plexus_hash` seen; a different one asks again.
570    seen: Option<String>,
571    /// Set when an item's `plexus_hash` moved since the last check.
572    stale: bool,
573    drift: Option<Drift>,
574    drifts_said: usize,
575    checks: usize,
576}
577
578/// A transport for a contract's client that checks the backend against the
579/// client's [`Stamp`]: the backend's interface is asked once (and again when
580/// an item's `plexus_hash` moves); every item is watched for that.
581#[derive(Clone)]
582pub struct PeerTransport<T> {
583    inner: T,
584    state: Arc<Mutex<CheckState>>,
585}
586
587impl<T> PeerTransport<T> {
588    pub fn new(inner: T) -> Self {
589        Self { inner, state: Arc::default() }
590    }
591
592    pub fn inner(&self) -> &T {
593        &self.inner
594    }
595
596    /// The backend's interface as last checked.
597    pub fn interface(&self) -> Option<Interface> {
598        self.lock().interface.clone()
599    }
600
601    /// The drift said, if the backend moved within the stamp.
602    pub fn drift(&self) -> Option<Drift> {
603        self.lock().drift.clone()
604    }
605
606    /// How many times the backend's interface was asked.
607    pub fn checks(&self) -> usize {
608        self.lock().checks
609    }
610
611    /// How many times drift was said (at most once per change).
612    pub fn drifts_said(&self) -> usize {
613        self.lock().drifts_said
614    }
615
616    fn lock(&self) -> std::sync::MutexGuard<'_, CheckState> {
617        self.state.lock().unwrap_or_else(|p| p.into_inner())
618    }
619
620    fn observe(&self, plexus_hash: &str) {
621        if plexus_hash.is_empty() {
622            return;
623        }
624        let mut s = self.lock();
625        match &s.seen {
626            Some(seen) if seen != plexus_hash => {
627                s.stale = true;
628                s.seen = Some(plexus_hash.to_string());
629            }
630            None => s.seen = Some(plexus_hash.to_string()),
631            _ => {}
632        }
633    }
634}
635
636#[cfg(not(target_arch = "wasm32"))]
637impl<T: plexus_client::Transport + Clone + Send + Sync + 'static> PeerTransport<T> {
638    /// Ask the backend's interface at `path` (its `schema`) and check it
639    /// against `stamp`: equal → go; it serves every method of the stamp
640    /// under the same hash → go, saying `drift` once; else the methods that
641    /// moved are kept, and [`Self::admit`] refuses them all, a call only its
642    /// own.
643    pub async fn check(&self, path: &str, stamp: &Stamp) -> Result<(), PeerError> {
644        let method = plexus_client::MethodRef::new(intern(&stamp.interface), "schema").at(path.to_string());
645        let mut items = self.inner.call(method, serde_json::json!({}));
646        let mut schema: Option<PluginSchema> = None;
647        let mut plexus_hash = None;
648        while let Some(item) = items.next().await {
649            match item {
650                Ok(plexus_client::StreamItem::Data { metadata, content, .. }) => {
651                    plexus_hash = metadata.map(|m| m.plexus_hash);
652                    schema = serde_json::from_value(content).ok();
653                }
654                Ok(plexus_client::StreamItem::Error { error, .. }) => {
655                    return Err(PeerError::from_remote(&error).unwrap_or(PeerError::Unavailable { reason: error.to_string() }));
656                }
657                Ok(_) => {}
658                Err(e) => return Err(PeerError::Unavailable { reason: e.to_string() }),
659            }
660        }
661        drop(items);
662        let schema = schema.ok_or_else(|| PeerError::Unavailable { reason: format!("`{path}.schema` answered no schema") })?;
663        let got = Interface::named(&stamp.interface, &schema);
664        let moved = if got.hash == stamp.hash { vec![] } else { got.moved_from(&stamp.method_map()) };
665        let mut s = self.lock();
666        s.checks += 1;
667        s.stale = false;
668        if let Some(h) = plexus_hash {
669            s.seen = Some(h);
670        }
671        if got.hash != stamp.hash && moved.is_empty() {
672            let drift = Drift { from: stamp.hash.clone(), to: got.hash.clone() };
673            if s.drift.as_ref() != Some(&drift) {
674                tracing::warn!(target: "plexus::peer", interface = %stamp.interface, from = %drift.from, to = %drift.to, "drift: the backend's interface moved within the stamp");
675                s.drifts_said += 1;
676                s.drift = Some(drift);
677            }
678        }
679        s.moved = moved;
680        s.interface = Some(got);
681        Ok(())
682    }
683
684    /// Becoming a peer: check, and refuse a backend any of the stamp's
685    /// methods moved on.
686    pub async fn admit(&self, path: &str, stamp: &Stamp) -> Result<(), PeerError> {
687        self.check(path, stamp).await?;
688        let s = self.lock();
689        if s.moved.is_empty() {
690            Ok(())
691        } else {
692            Err(PeerError::ShapeMismatch {
693                wanted: stamp.hash.clone(),
694                got: s.interface.as_ref().map(|i| i.hash.clone()).unwrap_or_default(),
695                methods: s.moved.clone(),
696            })
697        }
698    }
699
700    /// Before a call of `method`: check when never checked or when an item's
701    /// `plexus_hash` moved; refuse the call when its own method moved.
702    pub async fn guard(&self, path: &str, stamp: &Stamp, method: &str) -> Result<(), PeerError> {
703        let ask = {
704            let s = self.lock();
705            s.interface.is_none() || s.stale
706        };
707        if ask {
708            self.check(path, stamp).await?;
709        }
710        let s = self.lock();
711        if s.moved.iter().any(|m| m == method) {
712            return Err(PeerError::ShapeMismatch {
713                wanted: stamp.hash.clone(),
714                got: s.interface.as_ref().map(|i| i.hash.clone()).unwrap_or_default(),
715                methods: vec![method.to_string()],
716            });
717        }
718        Ok(())
719    }
720
721    /// After a call of `method`: when its items' `plexus_hash` moved, ask
722    /// again once — and fail this call if its own method moved.
723    pub async fn after(&self, path: &str, stamp: &Stamp, method: &str) -> Result<(), PeerError> {
724        if self.lock().stale {
725            self.guard(path, stamp, method).await?;
726        }
727        Ok(())
728    }
729
730    /// A peer's `call` through the client's transport: `method` (`repos`,
731    /// or a path below the contract) at `path`, its items as the service's.
732    /// Only a method the interface names is called (a name from a caller is
733    /// never interned otherwise).
734    pub async fn call_peer(&self, path: &str, method: &str, params: Value, known: &Interface) -> Result<PlexusStream, PlexusError> {
735        let (prefix, name) = match method.rsplit_once('.') {
736            Some((p, n)) => (Some(p), n),
737            None => (None, method),
738        };
739        if prefix.is_some() || (name != "schema" && !known.methods.contains_key(name)) {
740            return Err(PlexusError::MethodNotFound { activation: known.name.clone(), method: method.to_string() });
741        }
742        let name: &'static str = intern(name);
743        let mref = plexus_client::MethodRef::new(intern(&known.name), name).at(path.to_string());
744        let this = self.clone();
745        let items = self.inner.call(mref, params).map(move |item| {
746            let item = match item {
747                Ok(i) => i,
748                Err(e) => {
749                    let pe = PeerError::Unavailable { reason: e.to_string() };
750                    return pe.item(vec![]);
751                }
752            };
753            if let Some(m) = item_metadata(&item) {
754                this.observe(&m);
755            }
756            let v = serde_json::to_value(&item).unwrap_or(Value::Null);
757            serde_json::from_value::<PlexusStreamItem>(v).unwrap_or_else(|e| PeerError::Unavailable { reason: e.to_string() }.item(vec![]))
758        });
759        // Collected into an owned stream: the transport's borrows `self.inner`.
760        let collected: Vec<PlexusStreamItem> = items.collect().await;
761        Ok(Box::pin(futures::stream::iter(collected)))
762    }
763}
764
765fn item_metadata(item: &plexus_client::StreamItem) -> Option<String> {
766    match item {
767        plexus_client::StreamItem::Data { metadata, .. }
768        | plexus_client::StreamItem::Progress { metadata, .. }
769        | plexus_client::StreamItem::Error { metadata, .. } => metadata.as_ref().map(|m| m.plexus_hash.clone()),
770        _ => None,
771    }
772}
773
774/// A method or interface name as `&'static str`, each distinct one leaked
775/// once — only names an interface declares reach here.
776fn intern(s: &str) -> &'static str {
777    static NAMES: OnceLock<Mutex<std::collections::HashSet<&'static str>>> = OnceLock::new();
778    let mut names = NAMES.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
779    if let Some(n) = names.get(s) {
780        return n;
781    }
782    let leaked: &'static str = Box::leak(s.to_string().into_boxed_str());
783    names.insert(leaked);
784    leaked
785}
786
787/// Every item a transport yields is watched for its `plexus_hash`.
788#[cfg(not(target_arch = "wasm32"))]
789impl<T: plexus_client::Transport + Send + Sync> plexus_client::Transport for PeerTransport<T> {
790    fn call(&self, method: plexus_client::MethodRef, params: Value) -> plexus_client::ItemStream<'_> {
791        Box::pin(self.inner.call(method, params).map(move |item| {
792            if let Ok(i) = &item {
793                if let Some(h) = item_metadata(i) {
794                    self.observe(&h);
795                }
796            }
797            item
798        }))
799    }
800
801    fn call_raw(&self, method: plexus_client::MethodRef, params: Value) -> plexus_client::RawItemStream<'_> {
802        Box::pin(self.call(method, params).map(|item| item.map(plexus_client::RawItem::from)))
803    }
804}