1use 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, thiserror::Error)]
58#[serde(tag = "error_kind", rename_all = "snake_case")]
59pub enum PeerError {
60 #[error("no peer named `{name}`")]
62 NotFound { name: String },
63 #[error("nothing is grafted at `{at}` as `{name}` (it would serve `{interface}`)")]
65 NotGrafted { at: String, name: String, interface: String },
66 #[error("the peer is unavailable: {reason}")]
68 Unavailable { reason: String },
69 #[error("the peer serves another shape (wanted {wanted}, got {got}): {}", methods.join(", "))]
72 ShapeMismatch { wanted: String, got: String, methods: Vec<String> },
73 #[error("the peer did not answer in time")]
75 Timeout,
76 #[error("not allowed: {grant}")]
78 Forbidden { grant: String },
79}
80
81impl PeerError {
82 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 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 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 pub fn from_item(item: &PlexusStreamItem) -> Option<PeerError> {
128 item.remote_error().and_then(PeerError::from_remote)
129 }
130
131 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 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 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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
167pub struct Interface {
168 pub name: String,
171 pub hash: String,
173 pub ir: ServiceIr,
175 #[serde(default)]
177 pub methods: BTreeMap<String, String>,
178 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
190fn 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 pub fn of(schema: &PluginSchema) -> Self {
200 Self::named(&schema.namespace, schema)
201 }
202
203 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 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 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 pub fn schema(&self) -> &PluginSchema {
255 &self.schema
256 }
257
258 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 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#[async_trait]
292pub trait Peer: Send + Sync {
293 fn interface(&self) -> Interface;
295 async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>) -> Result<PlexusStream, PlexusError>;
297 async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError>;
299}
300
301#[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
321pub 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
353pub 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
398pub type FindPeer = Arc<dyn Fn(String) -> futures::future::BoxFuture<'static, Result<Box<dyn Peer>, PeerError>> + Send + Sync>;
401
402pub struct PeerSlot {
407 namespace: String,
408 interface: Option<Interface>,
409 find: FindPeer,
410 list: Option<ListPeers>,
411}
412
413pub type ListPeers = Arc<dyn Fn() -> futures::future::BoxFuture<'static, Vec<String>> + Send + Sync>;
415
416impl PeerSlot {
417 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 pub fn with_list(mut self, list: ListPeers) -> Self {
425 self.list = Some(list);
426 self
427 }
428
429 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 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 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 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
516pub trait Contract {
523 fn interface() -> Interface;
525 fn stamp() -> &'static Stamp;
527}
528
529#[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 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#[derive(Debug, Clone, PartialEq, Eq)]
558pub struct Drift {
559 pub from: String,
560 pub to: String,
561}
562
563#[derive(Default)]
564struct CheckState {
565 interface: Option<Interface>,
567 moved: Vec<String>,
569 seen: Option<String>,
571 stale: bool,
573 drift: Option<Drift>,
574 drifts_said: usize,
575 checks: usize,
576}
577
578#[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 pub fn interface(&self) -> Option<Interface> {
598 self.lock().interface.clone()
599 }
600
601 pub fn drift(&self) -> Option<Drift> {
603 self.lock().drift.clone()
604 }
605
606 pub fn checks(&self) -> usize {
608 self.lock().checks
609 }
610
611 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 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 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 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 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 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 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
774fn 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#[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}