use std::collections::{BTreeMap, HashMap};
use std::sync::{Arc, Mutex, OnceLock};
use async_trait::async_trait;
use futures::StreamExt;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::auth::AuthContext;
use super::content_hash::{canonical_json, hash16};
use super::ir::ServiceIr;
use super::plexus::{Activation, ChildRouter, PlexusError};
use super::schema::{MethodRole, MethodSchema, PluginSchema};
use super::streaming::PlexusStream;
use super::types::{PlexusStreamItem, StreamMetadata};
use plexus_client::{DenyReason, OtherError, RemoteError};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, thiserror::Error)]
#[serde(tag = "error_kind", rename_all = "snake_case")]
pub enum PeerError {
#[error("no peer named `{name}`")]
NotFound { name: String },
#[error("nothing is grafted at `{at}` as `{name}` (it would serve `{interface}`)")]
NotGrafted { at: String, name: String, interface: String },
#[error("the peer is unavailable: {reason}")]
Unavailable { reason: String },
#[error("the peer serves another shape (wanted {wanted}, got {got}): {}", methods.join(", "))]
ShapeMismatch { wanted: String, got: String, methods: Vec<String> },
#[error("the peer did not answer in time")]
Timeout,
#[error("not allowed: {grant}")]
Forbidden { grant: String },
}
impl PeerError {
pub fn kind(&self) -> &'static str {
match self {
PeerError::NotFound { .. } => "not_found",
PeerError::NotGrafted { .. } => "not_grafted",
PeerError::Unavailable { .. } => "unavailable",
PeerError::ShapeMismatch { .. } => "shape_mismatch",
PeerError::Timeout => "timeout",
PeerError::Forbidden { .. } => "forbidden",
}
}
pub fn to_remote(&self) -> RemoteError {
match self {
PeerError::Forbidden { grant } => RemoteError::Forbidden {
reason: DenyReason::MissingGrant { grant: grant.clone(), scope: "*".into(), roles: vec![], held_on: vec![] },
},
other => {
let mut fields = match serde_json::to_value(other) {
Ok(Value::Object(m)) => m,
_ => serde_json::Map::new(),
};
fields.remove("error_kind");
RemoteError::Other(OtherError { kind: other.kind().into(), fields })
}
}
}
pub fn from_remote(e: &RemoteError) -> Option<PeerError> {
match e {
RemoteError::Forbidden { reason: DenyReason::MissingGrant { grant, .. } } => Some(PeerError::Forbidden { grant: grant.clone() }),
RemoteError::Other(o) => {
let mut m = o.fields.clone();
m.insert("error_kind".into(), Value::String(o.kind.clone()));
serde_json::from_value(Value::Object(m)).ok()
}
_ => None,
}
}
pub fn from_item(item: &PlexusStreamItem) -> Option<PeerError> {
item.remote_error().and_then(PeerError::from_remote)
}
pub fn from_client(e: &plexus_client::ClientError) -> PeerError {
if let plexus_client::ClientError::Remote(r) = e {
if let Some(p) = PeerError::from_remote(r) {
return p;
}
}
PeerError::Unavailable { reason: e.to_string() }
}
pub fn item(&self, provenance: Vec<String>) -> PlexusStreamItem {
let metadata = StreamMetadata::new(provenance, super::context::PlexusContext::hash());
let mut item = PlexusStreamItem::error(metadata, self.to_remote(), matches!(self, PeerError::Unavailable { .. } | PeerError::Timeout));
if let PlexusStreamItem::Error { message, .. } = &mut item {
*message = self.to_string();
}
item
}
pub fn stream(&self, provenance: Vec<String>) -> PlexusStream {
let item = self.item(provenance);
Box::pin(futures::stream::once(async move { item }))
}
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Interface {
pub name: String,
pub hash: String,
pub ir: ServiceIr,
#[serde(default)]
pub methods: BTreeMap<String, String>,
pub schema: Box<PluginSchema>,
}
impl PartialEq for Interface {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.hash == other.hash
}
}
impl Eq for Interface {}
fn cache() -> &'static Mutex<HashMap<(String, String), Interface>> {
static CACHE: OnceLock<Mutex<HashMap<(String, String), Interface>>> = OnceLock::new();
CACHE.get_or_init(Default::default)
}
impl Interface {
pub fn of(schema: &PluginSchema) -> Self {
Self::named(&schema.namespace, schema)
}
pub fn named(name: &str, schema: &PluginSchema) -> Self {
let key = (name.to_string(), if schema.hash.is_empty() { canonical_json(&serde_json::to_value(schema).unwrap_or_default()) } else { schema.hash.clone() });
if let Some(i) = cache().lock().unwrap_or_else(|p| p.into_inner()).get(&key) {
return i.clone();
}
let methods: BTreeMap<String, String> = schema
.methods
.iter()
.filter(|m| !m.is_auto_schema() && matches!(m.role, MethodRole::Rpc))
.map(|m| (m.name.clone(), Self::method_hash(m)))
.collect();
let hash = hash16(canonical_json(&serde_json::to_value(&methods).unwrap_or_default()).as_bytes());
let mut schemas = BTreeMap::new();
schemas.insert(Vec::<String>::new(), serde_json::to_value(schema).unwrap_or_default());
let ir = super::ir::answer(name, &[vec![]], &schemas).unwrap_or_else(|_| null_ir());
let i = Interface { name: name.to_string(), hash, ir, methods, schema: Box::new(schema.clone()) };
cache().lock().unwrap_or_else(|p| p.into_inner()).insert(key, i.clone());
i
}
pub fn unknown(name: &str) -> Self {
Interface {
name: name.to_string(),
hash: String::new(),
ir: null_ir(),
methods: BTreeMap::new(),
schema: Box::new(PluginSchema::leaf(name, "", "", vec![])),
}
}
pub fn method_hash(m: &MethodSchema) -> String {
let shape = serde_json::json!({
"name": m.name,
"params": m.params,
"returns": m.returns,
"error": m.error,
"progress": m.progress,
"cardinality": m.cardinality,
"input": m.input,
"role": m.role,
});
hash16(canonical_json(&shape).as_bytes())
}
pub fn schema(&self) -> &PluginSchema {
&self.schema
}
pub fn moved_from(&self, wanted: &BTreeMap<String, String>) -> Vec<String> {
wanted.iter().filter(|(name, hash)| self.methods.get(*name) != Some(*hash)).map(|(n, _)| n.clone()).collect()
}
pub fn satisfies(&self, wanted: &Interface) -> Result<(), PeerError> {
if self.hash == wanted.hash {
return Ok(());
}
let moved = self.moved_from(&wanted.methods);
if moved.is_empty() {
Ok(())
} else {
Err(PeerError::ShapeMismatch { wanted: wanted.hash.clone(), got: self.hash.clone(), methods: moved })
}
}
}
fn null_ir() -> ServiceIr {
ServiceIr(Arc::from(serde_json::value::RawValue::from_string("null".into()).expect("null is JSON")))
}
#[async_trait]
pub trait Peer: Send + Sync {
fn interface(&self) -> Interface;
async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>) -> Result<PlexusStream, PlexusError>;
async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError>;
}
#[async_trait]
impl<T: Activation + ChildRouter> Peer for T {
fn interface(&self) -> Interface {
Interface::of(&Activation::plugin_schema(self))
}
async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>) -> Result<PlexusStream, PlexusError> {
Activation::call(self, method, params, auth, None).await
}
async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
match ChildRouter::peer_child(self, name).await? {
Some(router) => Ok(Box::new(RouterPeer::new(router))),
None => Err(PeerError::NotFound { name: name.to_string() }),
}
}
}
pub struct RouterPeer {
router: Box<dyn ChildRouter>,
}
impl RouterPeer {
pub fn new(router: Box<dyn ChildRouter>) -> Self {
Self { router }
}
}
#[async_trait]
impl Peer for RouterPeer {
fn interface(&self) -> Interface {
match self.router.router_schema() {
Some(s) => Interface::of(&s),
None => Interface::unknown(self.router.router_namespace()),
}
}
async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>) -> Result<PlexusStream, PlexusError> {
self.router.router_call(method, params, auth, None).await
}
async fn peer(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
match self.router.peer_child(name).await? {
Some(router) => Ok(Box::new(RouterPeer::new(router))),
None => Err(PeerError::NotFound { name: name.to_string() }),
}
}
}
pub struct PeerRouter {
peer: Box<dyn Peer>,
namespace: String,
}
impl PeerRouter {
pub fn new(peer: Box<dyn Peer>) -> Self {
let namespace = peer.interface().name;
Self { peer, namespace }
}
}
#[async_trait]
impl ChildRouter for PeerRouter {
fn router_namespace(&self) -> &str {
&self.namespace
}
async fn router_call(
&self,
method: &str,
params: Value,
auth: Option<&AuthContext>,
_raw_ctx: Option<&crate::request::RawRequestContext>,
) -> Result<PlexusStream, PlexusError> {
self.peer.call(method, params, auth).await
}
async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
self.peer.peer(name).await.ok().map(|p| Box::new(PeerRouter::new(p)) as Box<dyn ChildRouter>)
}
async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, PeerError> {
let p = self.peer.peer(name).await?;
Ok(Some(Box::new(PeerRouter::new(p))))
}
fn router_schema(&self) -> Option<PluginSchema> {
let i = self.peer.interface();
(!i.hash.is_empty()).then(|| i.schema().clone())
}
}
pub type FindPeer = Arc<dyn Fn(String) -> futures::future::BoxFuture<'static, Result<Box<dyn Peer>, PeerError>> + Send + Sync>;
pub struct PeerSlot {
namespace: String,
interface: Option<Interface>,
find: FindPeer,
list: Option<ListPeers>,
}
pub type ListPeers = Arc<dyn Fn() -> futures::future::BoxFuture<'static, Vec<String>> + Send + Sync>;
impl PeerSlot {
pub fn new(name: impl Into<String>, interface: Option<Interface>, find: FindPeer) -> Self {
Self { namespace: name.into(), interface, find, list: None }
}
pub fn with_list(mut self, list: ListPeers) -> Self {
self.list = Some(list);
self
}
pub fn schema(&self) -> PluginSchema {
let entry = MethodSchema::new(self.namespace.clone(), "a peer, by name".to_string(), String::new())
.with_role(MethodRole::DynamicChild {
list_method: None,
search_method: None,
child: self.interface.as_ref().map(|i| Box::new(i.schema().clone())),
})
.with_content_hash();
let mut s = PluginSchema::leaf(&self.namespace, "", "a peer slot", vec![entry]);
s.hash = hash16(self.namespace.as_bytes());
s
}
pub async fn get(&self, name: &str) -> Result<Box<dyn Peer>, PeerError> {
let peer = (self.find)(name.to_string()).await?;
if let Some(wanted) = &self.interface {
peer.interface().satisfies(wanted)?;
}
Ok(peer)
}
}
#[async_trait]
impl ChildRouter for PeerSlot {
fn router_namespace(&self) -> &str {
&self.namespace
}
async fn router_call(
&self,
method: &str,
params: Value,
auth: Option<&AuthContext>,
raw_ctx: Option<&crate::request::RawRequestContext>,
) -> Result<PlexusStream, PlexusError> {
if method == "schema" {
let mut schema = self.schema();
if let Some(list) = &self.list {
let hash = self.interface.as_ref().map(|i| i.hash.clone());
#[allow(deprecated)]
{
schema.children = Some(
list()
.await
.into_iter()
.map(|name| super::schema::ChildSummary {
hash: hash16(format!("{}:{}.{name}", hash.clone().unwrap_or_default(), self.namespace).as_bytes()),
description: format!("the peer `{name}`"),
namespace: name,
})
.collect(),
);
}
}
let content = serde_json::to_value(super::schema::SchemaResult::Plugin(schema)).unwrap_or_default();
let metadata = StreamMetadata::new(vec![self.namespace.clone()], super::context::PlexusContext::hash());
let items = vec![
PlexusStreamItem::data(metadata.clone(), format!("{}.schema", self.namespace), content),
PlexusStreamItem::done(metadata),
];
return Ok(Box::pin(futures::stream::iter(items)));
}
super::plexus::route_to_child(self, method, params, auth, raw_ctx).await
}
async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
self.peer_child(name).await.ok().flatten()
}
async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, PeerError> {
let peer = self.get(name).await?;
Ok(Some(Box::new(PeerRouter::new(peer))))
}
fn router_schema(&self) -> Option<PluginSchema> {
Some(self.schema())
}
}
pub trait Contract {
fn interface() -> Interface;
fn stamp() -> &'static Stamp;
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Stamp {
pub interface: String,
pub version: String,
pub hash: String,
pub methods: Vec<(String, String)>,
}
impl Stamp {
pub fn of(version: &str, interface: &Interface) -> Self {
Stamp {
interface: interface.name.clone(),
version: version.to_string(),
hash: interface.hash.clone(),
methods: interface.methods.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
}
}
fn method_map(&self) -> BTreeMap<String, String> {
self.methods.iter().cloned().collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Drift {
pub from: String,
pub to: String,
}
#[derive(Default)]
struct CheckState {
interface: Option<Interface>,
moved: Vec<String>,
seen: Option<String>,
stale: bool,
drift: Option<Drift>,
drifts_said: usize,
checks: usize,
}
#[derive(Clone)]
pub struct PeerTransport<T> {
inner: T,
state: Arc<Mutex<CheckState>>,
}
impl<T> PeerTransport<T> {
pub fn new(inner: T) -> Self {
Self { inner, state: Arc::default() }
}
pub fn inner(&self) -> &T {
&self.inner
}
pub fn interface(&self) -> Option<Interface> {
self.lock().interface.clone()
}
pub fn drift(&self) -> Option<Drift> {
self.lock().drift.clone()
}
pub fn checks(&self) -> usize {
self.lock().checks
}
pub fn drifts_said(&self) -> usize {
self.lock().drifts_said
}
fn lock(&self) -> std::sync::MutexGuard<'_, CheckState> {
self.state.lock().unwrap_or_else(|p| p.into_inner())
}
fn observe(&self, plexus_hash: &str) {
if plexus_hash.is_empty() {
return;
}
let mut s = self.lock();
match &s.seen {
Some(seen) if seen != plexus_hash => {
s.stale = true;
s.seen = Some(plexus_hash.to_string());
}
None => s.seen = Some(plexus_hash.to_string()),
_ => {}
}
}
}
#[cfg(not(target_arch = "wasm32"))]
impl<T: plexus_client::Transport + Clone + Send + Sync + 'static> PeerTransport<T> {
pub async fn check(&self, path: &str, stamp: &Stamp) -> Result<(), PeerError> {
let method = plexus_client::MethodRef::new(intern(&stamp.interface), "schema").at(path.to_string());
let mut items = self.inner.call(method, serde_json::json!({}));
let mut schema: Option<PluginSchema> = None;
let mut plexus_hash = None;
while let Some(item) = items.next().await {
match item {
Ok(plexus_client::StreamItem::Data { metadata, content, .. }) => {
plexus_hash = metadata.map(|m| m.plexus_hash);
schema = serde_json::from_value(content).ok();
}
Ok(plexus_client::StreamItem::Error { error, .. }) => {
return Err(PeerError::from_remote(&error).unwrap_or(PeerError::Unavailable { reason: error.to_string() }));
}
Ok(_) => {}
Err(e) => return Err(PeerError::Unavailable { reason: e.to_string() }),
}
}
drop(items);
let schema = schema.ok_or_else(|| PeerError::Unavailable { reason: format!("`{path}.schema` answered no schema") })?;
let got = Interface::named(&stamp.interface, &schema);
let moved = if got.hash == stamp.hash { vec![] } else { got.moved_from(&stamp.method_map()) };
let mut s = self.lock();
s.checks += 1;
s.stale = false;
if let Some(h) = plexus_hash {
s.seen = Some(h);
}
if got.hash != stamp.hash && moved.is_empty() {
let drift = Drift { from: stamp.hash.clone(), to: got.hash.clone() };
if s.drift.as_ref() != Some(&drift) {
tracing::warn!(target: "plexus::peer", interface = %stamp.interface, from = %drift.from, to = %drift.to, "drift: the backend's interface moved within the stamp");
s.drifts_said += 1;
s.drift = Some(drift);
}
}
s.moved = moved;
s.interface = Some(got);
Ok(())
}
pub async fn admit(&self, path: &str, stamp: &Stamp) -> Result<(), PeerError> {
self.check(path, stamp).await?;
let s = self.lock();
if s.moved.is_empty() {
Ok(())
} else {
Err(PeerError::ShapeMismatch {
wanted: stamp.hash.clone(),
got: s.interface.as_ref().map(|i| i.hash.clone()).unwrap_or_default(),
methods: s.moved.clone(),
})
}
}
pub async fn guard(&self, path: &str, stamp: &Stamp, method: &str) -> Result<(), PeerError> {
let ask = {
let s = self.lock();
s.interface.is_none() || s.stale
};
if ask {
self.check(path, stamp).await?;
}
let s = self.lock();
if s.moved.iter().any(|m| m == method) {
return Err(PeerError::ShapeMismatch {
wanted: stamp.hash.clone(),
got: s.interface.as_ref().map(|i| i.hash.clone()).unwrap_or_default(),
methods: vec![method.to_string()],
});
}
Ok(())
}
pub async fn after(&self, path: &str, stamp: &Stamp, method: &str) -> Result<(), PeerError> {
if self.lock().stale {
self.guard(path, stamp, method).await?;
}
Ok(())
}
pub async fn call_peer(&self, path: &str, method: &str, params: Value, known: &Interface) -> Result<PlexusStream, PlexusError> {
let (prefix, name) = match method.rsplit_once('.') {
Some((p, n)) => (Some(p), n),
None => (None, method),
};
if prefix.is_some() || (name != "schema" && !known.methods.contains_key(name)) {
return Err(PlexusError::MethodNotFound { activation: known.name.clone(), method: method.to_string() });
}
let name: &'static str = intern(name);
let mref = plexus_client::MethodRef::new(intern(&known.name), name).at(path.to_string());
let this = self.clone();
let items = self.inner.call(mref, params).map(move |item| {
let item = match item {
Ok(i) => i,
Err(e) => {
let pe = PeerError::Unavailable { reason: e.to_string() };
return pe.item(vec![]);
}
};
if let Some(m) = item_metadata(&item) {
this.observe(&m);
}
let v = serde_json::to_value(&item).unwrap_or(Value::Null);
serde_json::from_value::<PlexusStreamItem>(v).unwrap_or_else(|e| PeerError::Unavailable { reason: e.to_string() }.item(vec![]))
});
let collected: Vec<PlexusStreamItem> = items.collect().await;
Ok(Box::pin(futures::stream::iter(collected)))
}
}
fn item_metadata(item: &plexus_client::StreamItem) -> Option<String> {
match item {
plexus_client::StreamItem::Data { metadata, .. }
| plexus_client::StreamItem::Progress { metadata, .. }
| plexus_client::StreamItem::Error { metadata, .. } => metadata.as_ref().map(|m| m.plexus_hash.clone()),
_ => None,
}
}
fn intern(s: &str) -> &'static str {
static NAMES: OnceLock<Mutex<std::collections::HashSet<&'static str>>> = OnceLock::new();
let mut names = NAMES.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
if let Some(n) = names.get(s) {
return n;
}
let leaked: &'static str = Box::leak(s.to_string().into_boxed_str());
names.insert(leaked);
leaked
}
#[cfg(not(target_arch = "wasm32"))]
impl<T: plexus_client::Transport + Send + Sync> plexus_client::Transport for PeerTransport<T> {
fn call(&self, method: plexus_client::MethodRef, params: Value) -> plexus_client::ItemStream<'_> {
Box::pin(self.inner.call(method, params).map(move |item| {
if let Ok(i) = &item {
if let Some(h) = item_metadata(i) {
self.observe(&h);
}
}
item
}))
}
fn call_raw(&self, method: plexus_client::MethodRef, params: Value) -> plexus_client::RawItemStream<'_> {
Box::pin(self.call(method, params).map(|item| item.map(plexus_client::RawItem::from)))
}
}