use super::{
context::PlexusContext,
method_enum::MethodEnumSchema,
schema::{ChildSummary, MethodSchema, PluginSchema, Schema},
streaming::PlexusStream,
};
use crate::types::Handle;
use async_stream::stream;
use plexus_client::{DenyReason, ParamProblem, RemoteError};
use async_trait::async_trait;
use bitflags::bitflags;
use futures::Stream;
use futures_core::stream::BoxStream;
use jsonrpsee::core::server::Methods;
use jsonrpsee::RpcModule;
pub const PLEXUS_NOTIF_METHOD: &str = "result";
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
#[derive(Debug, Clone)]
pub enum PlexusError {
ActivationNotFound(String),
MethodNotFound { activation: String, method: String },
InvalidParams {
param: Option<String>,
problem: ParamProblem,
},
ExecutionError(String),
HandleNotSupported(String),
TransportError(TransportErrorKind),
Unauthenticated(String),
Forbidden { reason: AuthzDenyReason },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthzDenyReason {
MissingScope { scope: plexus_auth_core::Scope },
TenantBoundary,
NotAccepted,
MissingGrant {
grant: plexus_auth_core::grants::Grant,
scope: plexus_auth_core::grants::ScopeRef,
roles: Vec<plexus_auth_core::RoleName>,
held_on: Vec<plexus_auth_core::grants::ScopeRef>,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "error_kind", rename_all = "snake_case")]
pub enum TransportErrorKind {
ConnectionRefused { host: String, port: u16 },
ConnectionTimeout { host: String, port: u16 },
ProtocolError { message: String },
NetworkError { message: String },
}
impl std::fmt::Display for TransportErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TransportErrorKind::ConnectionRefused { host, port } => {
write!(f, "Connection refused to {}:{}", host, port)
}
TransportErrorKind::ConnectionTimeout { host, port } => {
write!(f, "Connection timeout to {}:{}", host, port)
}
TransportErrorKind::ProtocolError { message } => {
write!(f, "Protocol error: {}", message)
}
TransportErrorKind::NetworkError { message } => {
write!(f, "Network error: {}", message)
}
}
}
}
impl std::fmt::Display for PlexusError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PlexusError::ActivationNotFound(name) => write!(f, "Activation not found: {}", name),
PlexusError::MethodNotFound { activation, method } => {
write!(f, "Method not found: {}.{}", activation, method)
}
PlexusError::InvalidParams { param, problem } => match (param, problem) {
(Some(p), ParamProblem::Missing) => {
write!(f, "Invalid params: missing field: {}", p)
}
(None, ParamProblem::Missing) => {
write!(f, "Invalid params: a required parameter is missing")
}
(Some(p), ParamProblem::Malformed { detail }) => {
write!(f, "Invalid params: {}: {}", p, detail)
}
(None, ParamProblem::Malformed { detail }) => {
write!(f, "Invalid params: {}", detail)
}
},
PlexusError::ExecutionError(msg) => write!(f, "Execution error: {}", msg),
PlexusError::HandleNotSupported(activation) => {
write!(f, "Handle resolution not supported by activation: {}", activation)
}
PlexusError::TransportError(kind) => match kind {
TransportErrorKind::ConnectionRefused { host, port } => {
write!(f, "Connection refused to {}:{}", host, port)
}
TransportErrorKind::ConnectionTimeout { host, port } => {
write!(f, "Connection timeout to {}:{}", host, port)
}
TransportErrorKind::ProtocolError { message } => {
write!(f, "Protocol error: {}", message)
}
TransportErrorKind::NetworkError { message } => {
write!(f, "Network error: {}", message)
}
}
PlexusError::Unauthenticated(msg) => write!(f, "Authentication required: {}", msg),
PlexusError::Forbidden { reason } => match reason {
AuthzDenyReason::MissingScope { scope } => {
write!(f, "Forbidden: missing required scope '{}'", scope)
}
AuthzDenyReason::TenantBoundary => write!(f, "Forbidden: tenant boundary"),
AuthzDenyReason::NotAccepted => write!(f, "Forbidden: call not accepted"),
AuthzDenyReason::MissingGrant { grant, scope, .. } if scope.is_everywhere() => {
write!(f, "needs {}", grant)
}
AuthzDenyReason::MissingGrant { grant, scope, .. } => {
write!(f, "needs {} on {}", grant, scope)
}
},
}
}
}
impl std::error::Error for PlexusError {}
impl PlexusError {
pub fn invalid_params(detail: impl Into<String>) -> Self {
PlexusError::InvalidParams { param: None, problem: ParamProblem::Malformed { detail: detail.into() } }
}
pub fn malformed_param(param: impl Into<String>, detail: impl Into<String>) -> Self {
PlexusError::InvalidParams {
param: Some(param.into()),
problem: ParamProblem::Malformed { detail: detail.into() },
}
}
}
impl From<&PlexusError> for RemoteError {
fn from(e: &PlexusError) -> Self {
match e {
PlexusError::ActivationNotFound(name) => RemoteError::ActivationNotFound {
activation: name.clone(),
},
PlexusError::MethodNotFound { activation, method } => RemoteError::MethodNotFound {
activation: activation.clone(),
method: method.clone(),
},
PlexusError::InvalidParams { param, problem } => RemoteError::InvalidParams {
param: param.clone(),
problem: problem.clone(),
},
PlexusError::ExecutionError(message) => RemoteError::Execution {
message: message.clone(),
},
PlexusError::HandleNotSupported(activation) => RemoteError::HandleNotSupported {
activation: activation.clone(),
},
PlexusError::TransportError(kind) => RemoteError::Execution {
message: kind.to_string(),
},
PlexusError::Unauthenticated(_) => RemoteError::Unauthenticated,
PlexusError::Forbidden { reason } => RemoteError::Forbidden {
reason: match reason {
AuthzDenyReason::MissingScope { scope } => DenyReason::MissingScope {
scope: scope.as_str().to_string(),
},
AuthzDenyReason::TenantBoundary => DenyReason::TenantBoundary,
AuthzDenyReason::NotAccepted => DenyReason::NotAccepted,
AuthzDenyReason::MissingGrant { grant, scope, roles, held_on } => {
DenyReason::MissingGrant {
grant: grant.as_str().to_string(),
scope: scope.as_str().to_string(),
roles: roles.iter().map(|r| r.as_str().to_string()).collect(),
held_on: held_on.iter().map(|s| s.as_str().to_string()).collect(),
}
}
},
},
}
}
}
async fn in_child<F>(ctx: Option<crate::call::CallContext>, routed: F) -> Result<PlexusStream, PlexusError>
where
F: std::future::Future<Output = Result<PlexusStream, PlexusError>>,
{
match ctx {
Some(ctx) => in_call(ctx, routed).await,
None => routed.await,
}
}
async fn in_call<F>(ctx: crate::call::CallContext, routed: F) -> Result<PlexusStream, PlexusError>
where
F: std::future::Future<Output = Result<PlexusStream, PlexusError>>,
{
let stream = crate::call::scope(ctx.clone(), routed).await?;
Ok(Box::pin(crate::call::InCall::new(ctx, stream)))
}
fn plexus_error_code(e: &PlexusError) -> i32 {
match e {
PlexusError::Unauthenticated(_) => -32001,
PlexusError::Forbidden { .. } => -32003,
PlexusError::InvalidParams { .. } => -32602,
PlexusError::MethodNotFound { .. } | PlexusError::ActivationNotFound(_) => -32601,
_ => -32000,
}
}
pub fn plexus_error_to_jsonrpc(e: &PlexusError) -> jsonrpsee::types::ErrorObjectOwned {
let error = RemoteError::from(e);
jsonrpsee::types::ErrorObject::owned(plexus_error_code(e), error.to_string(), Some(error))
}
pub(crate) fn error_item_raw(ns: &str, e: &PlexusError) -> Option<Box<serde_json::value::RawValue>> {
serde_json::value::to_raw_value(&error_item(ns, e)).ok()
}
pub fn error_item(ns: &str, e: &PlexusError) -> serde_json::Value {
let item = super::types::PlexusStreamItem::from_plexus_error(
super::types::StreamMetadata::new(vec![ns.into()], super::context::PlexusContext::hash()),
e,
false,
);
serde_json::to_value(&item).unwrap_or(serde_json::Value::Null)
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ActivationInfo {
pub namespace: String,
pub version: String,
pub description: String,
pub methods: Vec<String>,
}
#[async_trait]
pub trait Activation: Send + Sync + 'static {
type Methods: MethodEnumSchema;
fn namespace(&self) -> &str;
fn version(&self) -> &str;
fn description(&self) -> &str { "No description available" }
fn long_description(&self) -> Option<&str> { None }
fn methods(&self) -> Vec<&str>;
fn method_help(&self, _method: &str) -> Option<String> { None }
fn plugin_id(&self) -> uuid::Uuid {
let major_version = self.version().split('.').next().unwrap_or("0");
uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, format!("{}@{}", self.namespace(), major_version).as_bytes())
}
async fn call(
&self,
method: &str,
params: Value,
auth: Option<&super::auth::AuthContext>,
raw_ctx: Option<&crate::request::RawRequestContext>,
) -> Result<PlexusStream, PlexusError>;
async fn resolve_handle(&self, _handle: &Handle) -> Result<PlexusStream, PlexusError> {
Err(PlexusError::HandleNotSupported(self.namespace().to_string()))
}
fn into_rpc_methods(self) -> Methods where Self: Sized;
fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
Vec::new()
}
fn slot_schema() -> Option<PluginSchema>
where
Self: Sized,
{
None
}
fn plugin_schema(&self) -> PluginSchema {
let methods: Vec<MethodSchema> = self.methods().iter().map(|name| {
let desc = self.method_help(name).unwrap_or_default();
MethodSchema::new(name.to_string(), desc, String::new()).with_content_hash()
}).collect();
if let Some(long_desc) = self.long_description() {
PluginSchema::leaf_with_long_description(
self.namespace(),
self.version(),
self.description(),
long_desc,
methods,
)
} else {
PluginSchema::leaf(
self.namespace(),
self.version(),
self.description(),
methods,
)
}
}
}
bitflags! {
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
#[deprecated(
since = "0.5",
note = "Use MethodRole::DynamicChild { list_method, search_method } instead. Removed in 0.7."
)]
pub struct ChildCapabilities: u32 {
const LIST = 0b0000_0001;
const SEARCH = 0b0000_0010;
}
}
#[async_trait]
pub trait ChildRouter: Send + Sync {
fn router_namespace(&self) -> &str;
async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>>;
async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, super::peer::PeerError> {
Ok(self.get_child(name).await)
}
#[allow(deprecated)]
fn capabilities(&self) -> ChildCapabilities {
ChildCapabilities::empty()
}
async fn list_children(&self) -> Option<BoxStream<'_, String>> {
None
}
async fn search_children(&self, _query: &str) -> Option<BoxStream<'_, String>> {
None
}
fn forward_policy_for(
&self,
_callee_ns: &str,
) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
None
}
fn router_schema(&self) -> Option<PluginSchema> {
None
}
fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
Vec::new()
}
fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
plexus_auth_core::Principal::Anonymous
}
}
pub async fn route_to_child<T: ChildRouter + ?Sized>(
parent: &T,
method: &str,
params: Value,
auth: Option<&super::auth::AuthContext>,
raw_ctx: Option<&crate::request::RawRequestContext>,
) -> Result<PlexusStream, PlexusError> {
if let Some((child_name, rest)) = method.split_once('.') {
let found = match parent.peer_child(child_name).await {
Ok(found) => found,
Err(e) => {
return Ok(e.stream(vec![parent.router_namespace().to_string(), child_name.to_string()]));
}
};
if let Some(child) = found {
let policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy> = parent
.forward_policy_for(child_name)
.unwrap_or_else(|| {
std::sync::Arc::new(plexus_auth_core::IdentityOnly)
as std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>
});
let callee_method_str = format!("{}.{}", child_name, rest);
let callee_method = plexus_auth_core::MethodPath::try_new(callee_method_str.as_str())
.map_err(|e| PlexusError::ExecutionError(format!(
"framework-built MethodPath rejected: {} ({:?})",
callee_method_str, e
)))?;
let site = plexus_auth_core::CallSite::new(
parent.framework_stamped_principal(),
callee_method,
);
let anonymous_owned;
let caller_ctx: &super::auth::AuthContext = match auth {
Some(ctx) => ctx,
None => {
anonymous_owned = super::auth::AuthContext::anonymous();
&anonymous_owned
}
};
let derivation = policy.forward(caller_ctx, &site);
tracing::trace!(
target: "plexus::audit",
policy = policy.name().as_str(),
callee_method = %site.callee_method.as_str(),
derivation_keep_verified_user = derivation.keep_verified_user,
derivation_keep_roles = derivation.keep_roles,
derivation_keep_capabilities = derivation.keep_capabilities,
derivation_keep_metadata = derivation.keep_metadata,
"forward_policy_applied (audit-record emission stubbed pending PRIVACY-1)"
);
let outer = crate::call::context().ok();
let keeps_identity = derivation.keep_verified_user;
return match auth {
Some(caller_ctx) => {
caller_ctx
.with_callee_context(&derivation, &site.caller, |callee_ctx| async move {
let ctx = outer.map(|o| o.for_child(Some(&callee_ctx), keeps_identity));
in_child(ctx, child.router_call(rest, params, Some(&callee_ctx), raw_ctx)).await
})
.await
}
None => {
let ctx = outer.map(|o| o.for_child(None, keeps_identity));
in_child(ctx, child.router_call(rest, params, None, raw_ctx)).await
}
};
}
return Err(PlexusError::ActivationNotFound(child_name.to_string()));
}
Err(PlexusError::MethodNotFound {
activation: parent.router_namespace().to_string(),
method: method.to_string(),
})
}
struct ArcChildRouter(Arc<dyn ChildRouter>);
#[async_trait]
impl ChildRouter for ArcChildRouter {
fn router_namespace(&self) -> &str {
self.0.router_namespace()
}
async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
self.0.router_call(method, params, auth, raw_ctx).await
}
async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
self.0.get_child(name).await
}
async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, super::peer::PeerError> {
self.0.peer_child(name).await
}
#[allow(deprecated)]
fn capabilities(&self) -> ChildCapabilities {
self.0.capabilities()
}
async fn list_children(&self) -> Option<BoxStream<'_, String>> {
self.0.list_children().await
}
async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
self.0.search_children(query).await
}
fn forward_policy_for(
&self,
callee_ns: &str,
) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
self.0.forward_policy_for(callee_ns)
}
fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
self.0.framework_stamped_principal()
}
fn router_schema(&self) -> Option<PluginSchema> {
self.0.router_schema()
}
fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
self.0.router_static_child_schemas()
}
}
#[async_trait]
#[allow(dead_code)] trait ActivationObject: Send + Sync + 'static {
fn namespace(&self) -> &str;
fn version(&self) -> &str;
fn description(&self) -> &str;
fn long_description(&self) -> Option<&str>;
fn methods(&self) -> Vec<&str>;
fn method_help(&self, method: &str) -> Option<String>;
fn plugin_id(&self) -> uuid::Uuid;
async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError>;
fn plugin_schema(&self) -> PluginSchema;
fn static_child_schemas(&self) -> Vec<(String, PluginSchema)>;
fn schema(&self) -> Schema;
}
struct ActivationWrapper<A: Activation> {
inner: A,
}
#[async_trait]
impl<A: Activation> ActivationObject for ActivationWrapper<A> {
fn namespace(&self) -> &str { self.inner.namespace() }
fn version(&self) -> &str { self.inner.version() }
fn description(&self) -> &str { self.inner.description() }
fn long_description(&self) -> Option<&str> { self.inner.long_description() }
fn methods(&self) -> Vec<&str> { self.inner.methods() }
fn method_help(&self, method: &str) -> Option<String> { self.inner.method_help(method) }
fn plugin_id(&self) -> uuid::Uuid { self.inner.plugin_id() }
async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
self.inner.call(method, params, auth, raw_ctx).await
}
async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
self.inner.resolve_handle(handle).await
}
fn plugin_schema(&self) -> PluginSchema { self.inner.plugin_schema() }
fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> { self.inner.static_child_schemas() }
fn schema(&self) -> Schema {
let schema = schemars::schema_for!(A::Methods);
serde_json::from_value(serde_json::to_value(schema).expect("serialize"))
.expect("parse schema")
}
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum HashEvent {
Hash { value: String },
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum SchemaEvent {
Schema(PluginSchema),
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PluginHashes {
pub namespace: String,
pub self_hash: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub children_hash: Option<String>,
pub hash: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub children: Option<Vec<ChildHashes>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ChildHashes {
pub namespace: String,
pub hash: String,
}
#[derive(Debug, Clone)]
pub struct PluginEntry {
pub id: uuid::Uuid,
pub path: String,
pub plugin_type: String,
}
#[derive(Default)]
pub struct PluginRegistry {
by_id: HashMap<uuid::Uuid, PluginEntry>,
by_path: HashMap<String, uuid::Uuid>,
}
#[derive(Clone)]
pub struct PluginRegistrySnapshot {
by_id: HashMap<uuid::Uuid, PluginEntry>,
by_path: HashMap<String, uuid::Uuid>,
}
impl PluginRegistrySnapshot {
pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
self.by_id.get(&id).map(|e| e.path.as_str())
}
pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
self.by_path.get(path).copied()
}
pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
self.by_id.get(&id)
}
pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
self.by_id.values()
}
pub fn len(&self) -> usize {
self.by_id.len()
}
pub fn is_empty(&self) -> bool {
self.by_id.is_empty()
}
}
impl PluginRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
self.by_id.get(&id).map(|e| e.path.as_str())
}
pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
self.by_path.get(path).copied()
}
pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
self.by_id.get(&id)
}
pub fn register(&mut self, id: uuid::Uuid, path: String, plugin_type: String) {
let entry = PluginEntry { id, path: path.clone(), plugin_type };
self.by_id.insert(id, entry);
self.by_path.insert(path, id);
}
pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
self.by_id.values()
}
pub fn len(&self) -> usize {
self.by_id.len()
}
pub fn is_empty(&self) -> bool {
self.by_id.is_empty()
}
}
fn build_info_payload(
namespace: &str,
caps: Option<&plexus_auth_core::BackendAuthCapabilities>,
) -> serde_json::Value {
let advertised = match caps {
Some(c) => c.clone(),
None => plexus_auth_core::BackendAuthCapabilities::anonymous_default(),
};
serde_json::json!({
"backend": namespace,
"auth_capabilities": advertised,
})
}
fn fill_site_hints_in_schema_stream(
stream: PlexusStream,
site: plexus_auth_core::AttachmentSite,
) -> PlexusStream {
use futures::StreamExt;
Box::pin(stream.map(move |item| match item {
super::types::PlexusStreamItem::Data {
metadata,
content_type,
content,
} if content_type.ends_with(".schema") || content_type.ends_with(".method_schema") => {
let content = match content.decode::<super::SchemaResult>() {
Ok(mut result) => {
result.fill_site_hints(&site);
match serde_json::to_value(&result) {
Ok(v) => v.into(),
Err(_) => content,
}
}
Err(_) => content,
};
super::types::PlexusStreamItem::Data {
metadata,
content_type,
content,
}
}
other => other,
}))
}
pub(crate) struct DynamicHubInner {
namespace: String,
activations: BTreeMap<String, Arc<dyn ActivationObject>>,
child_routers: BTreeMap<String, Arc<dyn ChildRouter>>,
registry: std::sync::RwLock<PluginRegistry>,
pending_rpc: std::sync::Mutex<Vec<Box<dyn FnOnce() -> Methods + Send>>>,
auth_capabilities: Option<plexus_auth_core::BackendAuthCapabilities>,
forward_policies: super::forward_registry::ForwardPolicyRegistry,
scope_registry: Option<Arc<plexus_auth_core::ScopeRegistry>>,
default_deny: bool,
audit_sink: Arc<dyn plexus_auth_core::AuditSink>,
duplex_gate: std::sync::OnceLock<super::duplex_gate::DuplexGate>,
gate_index: std::sync::OnceLock<GateIndex>,
input_index: std::sync::OnceLock<HashMap<String, bool>>,
gate: Option<Arc<plexus_auth_core::grants::Gate>>,
signed_in_grants: std::collections::BTreeSet<String>,
resource_metadata: Option<String>,
auth_catalog: Option<super::auth_activation::Catalog>,
describe: super::view::Cache,
ir_cache: super::ir::IrCache,
nested_count: usize,
}
impl DynamicHubInner {
fn nested_count(&self) -> usize {
self.nested_count
}
}
#[derive(Debug, Default)]
pub(crate) struct GateIndex {
methods: HashMap<String, super::scope_gate::MethodGateInfo>,
slots: super::slots::Slots,
}
#[derive(Clone)]
pub struct DynamicHub {
inner: Arc<DynamicHubInner>,
}
struct IrView {
base: Arc<super::view::Described>,
shaped: Option<Arc<super::view::Shaped>>,
hash: String,
}
impl IrView {
fn root(&self) -> PluginSchema {
match &self.shaped {
Some(v) => v.service.clone(),
None => self.base.service.clone(),
}
}
fn top(&self, ns: &str) -> Option<PluginSchema> {
match &self.shaped {
Some(v) => v.schema_of(&self.base, ns).filter(|_| ns != v.service.namespace),
None => self.base.activations.iter().find(|a| a.namespace == ns).cloned(),
}
}
fn shows(&self, ns: &str) -> bool {
match &self.shaped {
Some(v) => v.shows(ns),
None => self.base.activations.iter().any(|a| a.namespace == ns),
}
}
fn names(&self, service: &str) -> Vec<String> {
let mut out = vec![String::new()];
out.extend(self.base.activations.iter().map(|a| a.namespace.clone()).filter(|ns| ns != service && self.shows(ns)));
for path in self.base.nested() {
let mut segs = path.split('.');
let (Some(top), Some(entry)) = (segs.next(), segs.next()) else { continue };
let reached = self.shows(top)
&& match &self.shaped {
Some(v) => v.method_of(&self.base, top, entry).is_some(),
None => true,
};
if reached {
out.push(path.to_string());
}
}
out
}
}
impl DynamicHub {
pub(crate) fn from_inner(inner: Arc<DynamicHubInner>) -> Self {
Self { inner }
}
pub fn new(namespace: impl Into<String>) -> Self {
Self {
inner: Arc::new(DynamicHubInner {
namespace: namespace.into(),
activations: BTreeMap::new(),
child_routers: BTreeMap::new(),
registry: std::sync::RwLock::new(PluginRegistry::new()),
pending_rpc: std::sync::Mutex::new(Vec::new()),
auth_capabilities: None,
forward_policies: super::forward_registry::ForwardPolicyRegistry::new(),
scope_registry: None,
default_deny: false,
audit_sink: Arc::new(plexus_auth_core::TracingAuditSink),
duplex_gate: std::sync::OnceLock::new(),
gate_index: std::sync::OnceLock::new(),
input_index: std::sync::OnceLock::new(),
gate: None,
signed_in_grants: std::collections::BTreeSet::new(),
resource_metadata: None,
auth_catalog: None,
describe: Default::default(),
ir_cache: Default::default(),
nested_count: Default::default(),
}),
}
}
fn inner_mut(&mut self, refused: &str) -> &mut DynamicHubInner {
let inner = Arc::get_mut(&mut self.inner).expect(refused);
inner.describe.reset();
inner
}
pub fn with_scope_registry(mut self, registry: plexus_auth_core::ScopeRegistry) -> Self {
let inner = self.inner_mut("Cannot set scope_registry: DynamicHub has multiple references");
inner.scope_registry = Some(Arc::new(registry));
self
}
pub fn with_default_deny(mut self, default_deny: bool) -> Self {
let inner = self.inner_mut("Cannot set default_deny: DynamicHub has multiple references");
inner.default_deny = default_deny;
self
}
pub fn with_audit_sink(mut self, sink: Arc<dyn plexus_auth_core::AuditSink>) -> Self {
let inner = self.inner_mut("Cannot set audit_sink: DynamicHub has multiple references");
inner.audit_sink = sink;
self
}
pub fn with_gate(mut self, gate: Arc<plexus_auth_core::grants::Gate>) -> Self {
let inner = self.inner_mut("Cannot set gate: DynamicHub has multiple references");
inner.gate = Some(gate);
self
}
pub fn gate(&self) -> Option<&Arc<plexus_auth_core::grants::Gate>> {
self.inner.gate.as_ref()
}
pub fn with_resource_metadata(mut self, url: impl Into<String>) -> Self {
let inner = self.inner_mut("Cannot set resource_metadata: DynamicHub has multiple references");
inner.resource_metadata = Some(url.into());
self
}
pub fn with_signed_in_grants<I, S>(mut self, grants: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
let inner = self.inner_mut("Cannot set signed_in grants: DynamicHub has multiple references");
inner.signed_in_grants.extend(grants.into_iter().map(Into::into));
self
}
pub fn with_auth(mut self, setup: super::auth_activation::AuthSetup) -> Self {
let catalog = super::auth_activation::Catalog::default();
catalog.add(&Activation::plugin_schema(&self));
for a in self.inner.activations.values() {
catalog.add(&a.plugin_schema());
}
for child in self.described_children() {
catalog.add(&child);
}
let (_, untyped) = self.slot_children();
catalog.add_slots(&untyped);
let (auth, gate) = super::auth_activation::AuthActivation::mount(setup, catalog.clone());
{
let inner = self.inner_mut("Cannot mount auth: DynamicHub has multiple references");
inner.auth_catalog = Some(catalog);
inner.gate = Some(Arc::new(gate));
}
self.register(auth)
.with_signed_in_grants(super::auth_activation::SIGNED_IN_GRANTS.iter().copied())
}
pub fn view(&self, caller: Option<&super::auth::AuthContext>) -> super::view::View {
match self.inner.gate.as_ref() {
None => self.described().whole(),
Some(_) => {
let (base, view) = self.shaped(caller);
view.view(&base)
}
}
}
pub fn schema_moved(&self) {
self.inner.describe.schema_moved();
}
fn described(&self) -> Arc<super::view::Described> {
let at = self.inner.describe.schema_generation();
match self.inner.describe.base(at) {
Some(cell) => cell.get_or_init(|| Arc::new(self.describe_now())).clone(),
None => Arc::new(self.describe_now()),
}
}
fn describe_now(&self) -> super::view::Described {
let service = Activation::plugin_schema(self);
let activations: Vec<PluginSchema> = self.inner.activations.values().map(|a| a.plugin_schema()).collect();
super::view::Described::new(service, activations, self.described_children())
}
fn shaped(&self, caller: Option<&super::auth::AuthContext>) -> (Arc<super::view::Described>, Arc<super::view::Shaped>) {
let gate = self.inner.gate.as_ref().expect("a view is a gated service's");
let schema_at = self.inner.describe.schema_generation();
let grants_at = gate.generation().current();
let (caller, _) = super::grant_gate::standing(gate, caller);
let who = caller.and_then(|c| gate.fingerprint(c));
let shape = |base: &super::view::Described| {
Arc::new(super::view::shape(gate, &self.inner.signed_in_grants, who.as_ref(), base))
};
match self.inner.describe.view(schema_at, grants_at, &who) {
Some((base, view)) => {
let base = base.get_or_init(|| Arc::new(self.describe_now())).clone();
let view = view.get_or_init(|| shape(&base)).clone();
(base, view)
}
None => {
let base = Arc::new(self.describe_now());
let view = shape(&base);
(base, view)
}
}
}
pub fn info(&self, caller: Option<&super::auth::AuthContext>) -> serde_json::Value {
if self.inner.gate.is_none() {
return build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
}
let (base, view) = self.shaped(caller);
view.info
.get_or_init(|| {
let mut payload = build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
if let Some(obj) = payload.as_object_mut() {
obj.insert("view".into(), view.kind.as_str().into());
obj.insert("view_hash".into(), view.hash.clone().into());
if view.kind == super::ViewKind::Anonymous {
let mut auth = serde_json::Map::new();
auth.insert("methods".into(), view.public_methods(&base).into());
if let Some(url) = self.inner.resource_metadata.as_ref() {
auth.insert("resource_metadata".into(), url.clone().into());
}
obj.insert("auth".into(), serde_json::Value::Object(auth));
}
}
payload
})
.clone()
}
async fn introspect_in_view(
&self,
method: &str,
params: &Value,
auth: Option<&super::auth::AuthContext>,
raw_ctx: Option<&crate::request::RawRequestContext>,
) -> Option<Result<PlexusStream, PlexusError>> {
let (ns, rest) = method.split_once('.')?;
let hub_ns = self.inner.namespace.as_str();
let (base, view) = self.shaped(auth);
let not_found = || PlexusError::ActivationNotFound(ns.to_string());
let content: serde_json::Value = match rest {
"schema" => {
if !view.shows(ns) {
return Some(Err(not_found()));
}
let mut result = match params.get("method").and_then(|v| v.as_str()) {
Some(name) => match view.method_of(&base, ns, name) {
Some(m) => super::SchemaResult::Method(m),
None => {
return Some(Err(PlexusError::MethodNotFound {
activation: ns.to_string(),
method: name.to_string(),
}))
}
},
None => super::SchemaResult::Plugin(view.schema_of(&base, ns)?),
};
if let Some(site) = self.derived_site_hint() {
result.fill_site_hints(&site);
}
serde_json::to_value(&result).ok()?
}
"hash" if ns == hub_ns => serde_json::to_value(HashEvent::Hash { value: view.hash.clone() }).ok()?,
"hashes" if ns == hub_ns => serde_json::to_value(view.hashes()).ok()?,
r if r.ends_with(".schema") => {
if !view.shows(ns) {
return Some(Err(not_found()));
}
let name = r.trim_end_matches(".schema");
match view.method_of(&base, ns, name) {
Some(m) if matches!(m.role, super::MethodRole::Rpc) => {
serde_json::to_value(super::SchemaResult::Method(m)).ok()?
}
Some(_) => return None,
None if name.contains('.') => return None,
None if base.activations.iter().any(|a| a.namespace == ns && a.methods.iter().any(|m| m.role.is_slot())) => return None,
None => {
return Some(Err(PlexusError::MethodNotFound {
activation: ns.to_string(),
method: name.to_string(),
}))
}
}
}
_ => return None,
};
use futures::StreamExt;
let with = |content: serde_json::Value| {
move |item: super::types::PlexusStreamItem| match item {
super::types::PlexusStreamItem::Data { metadata, content_type, .. } => {
super::types::PlexusStreamItem::Data { metadata, content_type, content: content.clone().into() }
}
other => other,
}
};
if self.inner.scope_registry.is_some() || self.inner.default_deny {
let routed = self.route_ungated(method, params.clone(), auth, raw_ctx).await;
return Some(routed.map(|s| -> PlexusStream { Box::pin(s.map(with(content))) }));
}
let key = format!("{method}\n{params}");
if let Some(shell) = base.shell(&key) {
return Some(Ok(Box::pin(futures::stream::iter(shell.answer(content)))));
}
let items: Vec<super::types::PlexusStreamItem> = match self.route_ungated(method, params.clone(), auth, raw_ctx).await {
Ok(s) => s.collect().await,
Err(e) => return Some(Err(e)),
};
if let Some(shell) = super::view::Shell::of(&items) {
base.keep_shell(key, shell);
}
Some(Ok(Box::pin(futures::stream::iter(items.into_iter().map(with(content))))))
}
pub async fn service_ir(
&self,
namespaces: &[String],
caller: Option<&super::auth::AuthContext>,
) -> Result<super::ir::ServiceIr, super::ir::IrError> {
let roots = super::ir::roots(&self.inner.namespace, namespaces);
let view = self.ir_view(caller);
let permitted = match self.inner.scope_registry.is_some() || self.inner.default_deny {
false => None,
true => {
let mut answered = Vec::new();
for name in view.names(&self.inner.namespace) {
let under = roots.iter().any(|r| {
let r = r.join(".");
r.is_empty() || name == r || name.starts_with(&format!("{r}."))
});
if under && self.scope_answers(&self.schema_method(&name), caller).await {
answered.push(name);
}
}
Some(answered)
}
};
let key = super::ir::IrKey { view: view.hash.clone(), roots: roots.clone(), permitted: permitted.clone() };
self.inner
.ir_cache
.get_or_build(key, || async {
let mut schemas: BTreeMap<Vec<String>, Value> = BTreeMap::new();
let mut todo: Vec<Vec<String>> = roots.clone();
while let Some(path) = todo.pop() {
if schemas.contains_key(&path) || permitted.as_ref().is_some_and(|p| !p.contains(&path.join("."))) {
continue;
}
let Some(schema) = self.ir_schema(&view, &path, caller).await else { continue };
for child in schema.get("children").and_then(Value::as_array).into_iter().flatten() {
if let Some(ns) = child.get("namespace").and_then(Value::as_str) {
let mut next = path.clone();
next.push(ns.to_string());
todo.push(next);
}
}
schemas.insert(path, schema);
}
let service = self.inner.namespace.clone();
crate::rt::spawn_blocking(move || super::ir::answer(&service, &roots, &schemas))
.await
.unwrap_or_else(|e| Err(super::ir::IrError::Unreadable { namespace: String::new(), message: format!("the IR's build failed: {e}") }))
})
.await
}
pub fn ir_builds(&self) -> usize {
self.inner.ir_cache.builds()
}
fn ir_view(&self, caller: Option<&super::auth::AuthContext>) -> IrView {
match self.inner.gate {
Some(_) => {
let (base, shaped) = self.shaped(caller);
IrView { hash: shaped.hash.clone(), base, shaped: Some(shaped) }
}
None => {
let base = self.described();
IrView { hash: base.service.hash.clone(), base, shaped: None }
}
}
}
fn schema_method(&self, dotted: &str) -> String {
if dotted.is_empty() { format!("{}.schema", self.inner.namespace) } else { format!("{dotted}.schema") }
}
async fn scope_answers(&self, method: &str, caller: Option<&super::auth::AuthContext>) -> bool {
let registry = self.inner.scope_registry.as_deref().unwrap_or_else(|| super::scope_gate::empty_registry());
super::scope_gate::answers(registry, self.inner.default_deny, method, self.gate_info(method), caller).await
}
async fn ir_schema(&self, view: &IrView, path: &[String], caller: Option<&super::auth::AuthContext>) -> Option<Value> {
use futures::StreamExt;
let shown = match path {
[] => Some(view.root()),
[ns] => view.top(ns),
[top, below @ ..] => {
let activation = self.inner.activations.get(top.as_str())?;
let mut stream = activation.call(&format!("{}.schema", below.join(".")), Value::Null, caller, None).await.ok()?;
if let Some(site) = self.derived_site_hint() {
stream = fill_site_hints_in_schema_stream(stream, site);
}
let items: Vec<super::types::PlexusStreamItem> = stream.collect().await;
return items.into_iter().find_map(|item| match item {
super::types::PlexusStreamItem::Data { content_type, content, .. } if content_type.ends_with(".schema") => {
Some(content.into_value())
}
_ => None,
});
}
};
let mut schema = shown?;
if let Some(site) = self.derived_site_hint() {
schema.fill_site_hints(&site);
}
serde_json::to_value(super::SchemaResult::Plugin(schema)).ok()
}
fn check_ir_names(&self, params: &Value, caller: Option<&super::auth::AuthContext>) -> Result<(), PlexusError> {
let asked = match params.get("namespaces") {
None | Some(Value::Null) => return Ok(()),
Some(Value::Array(a)) => a,
Some(_) => return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")),
};
let most = 1 + self.inner.activations.len() + self.inner.nested_count();
if asked.len() > most {
return Err(PlexusError::malformed_param(
"namespaces",
format!("{} namespaces asked; more than this service shows you", asked.len()),
));
}
let names: std::collections::HashSet<String> = self.ir_view(caller).names(&self.inner.namespace).into_iter().collect();
if asked.len() > names.len() {
return Err(PlexusError::malformed_param(
"namespaces",
format!("{} namespaces asked; this service shows you {}", asked.len(), names.len()),
));
}
for n in asked {
let Some(n) = n.as_str() else { return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")) };
let known = n == self.inner.namespace || names.contains(n);
if !known {
return Err(PlexusError::malformed_param("namespaces", format!("no namespace `{n}` in this service")));
}
}
Ok(())
}
pub fn declared_roles(&self) -> std::collections::BTreeMap<String, Vec<String>> {
let mut out: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.described_children());
for schema in schemas {
for (role, grants) in schema.roles {
let entry = out.entry(role).or_default();
for g in grants {
if !entry.contains(&g) {
entry.push(g);
}
}
}
}
out
}
pub fn static_children(&self) -> Vec<PluginSchema> {
self.inner
.activations
.values()
.flat_map(|a| super::children::qualified(&a.plugin_schema().namespace, a.static_child_schemas()))
.collect()
}
pub fn scope_registry(&self) -> Option<&plexus_auth_core::ScopeRegistry> {
self.inner.scope_registry.as_deref()
}
pub(crate) fn input_terms(&self, method: &str, params: &Value) -> Result<InputTerms, PlexusError> {
if self.inner.gate.is_none() {
return Ok(InputTerms { grant: method.to_string(), targets: Vec::new(), recheck: false });
}
let info = self.gate_info(method);
let grant = info.and_then(|i| i.grant.clone()).unwrap_or_else(|| method.to_string());
let open = info.is_some_and(|i| i.public) || self.inner.signed_in_grants.contains(grant.as_str());
let targets = match info.and_then(|i| i.target.as_deref()) {
Some(param) => super::grant_gate::target_values(params, param)?.unwrap_or_default(),
None => Vec::new(),
};
Ok(InputTerms { grant, targets, recheck: !open })
}
pub(crate) fn duplex_gate(&self) -> &super::duplex_gate::DuplexGate {
self.inner.duplex_gate.get_or_init(|| match &self.inner.gate {
Some(gate) => {
let (audit, drain) = plexus_auth_core::audit::AuditQueue::new(1024, self.inner.audit_sink.clone());
crate::rt::spawn(drain);
super::duplex_gate::DuplexGate::new((**gate).clone()).with_audit(audit)
}
None => super::duplex_gate::DuplexGate::ungated(),
})
}
pub(crate) fn may_take_input(&self, method: &str) -> bool {
let index = self.inner.input_index.get_or_init(|| {
let own = Activation::plugin_schema(self).methods.into_iter().map(|m| (format!("{}.{}", self.inner.namespace, m.name), m.input.is_some()));
let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
let theirs = schemas.flat_map(|schema| {
let ns = schema.namespace;
schema.methods.into_iter().map(move |m| (format!("{ns}.{}", m.name), m.input.is_some()))
});
own.chain(theirs).collect()
});
index.get(method).copied().unwrap_or(true)
}
fn gate_info(&self, method: &str) -> Option<&super::scope_gate::MethodGateInfo> {
let index = self.gate_index();
index.methods.get(method).or_else(|| index.slots.resolve(method).and_then(|k| index.methods.get(&k)))
}
pub fn slot_children(&self) -> (Vec<PluginSchema>, Vec<String>) {
let (mut typed, mut untyped) = (Vec::new(), Vec::new());
let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
for schema in schemas {
super::slots::slot_schemas(&schema, &mut typed, &mut untyped);
}
(typed, untyped)
}
pub fn described_children(&self) -> Vec<PluginSchema> {
let mut out = self.static_children();
out.extend(self.slot_children().0);
out
}
fn gate_index(&self) -> &GateIndex {
self.inner.gate_index.get_or_init(|| {
let mut index = HashMap::new();
for m in &Activation::plugin_schema(self).methods {
let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
info.grant = Some(format!("{}.{}", self.inner.namespace, m.name));
index.insert(format!("{}.{}", self.inner.namespace, m.name), info);
}
let (typed, untyped) = self.slot_children();
let activations: Vec<PluginSchema> = self.inner.activations.values().map(|a| a.plugin_schema()).collect();
let statics = self.static_children();
for schema in activations.iter().chain(statics.iter()).chain(typed.iter()) {
for m in &schema.methods {
let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
info.grant = Some(m.grant_or(&schema.namespace));
index.insert(format!("{}.{}", schema.namespace, m.name), info);
}
}
for path in &untyped {
index.insert(
path.clone(),
super::scope_gate::MethodGateInfo { grant: Some(path.clone()), ..Default::default() },
);
}
let slots = super::slots::Slots::of(activations.iter().chain(statics.iter()).chain(typed.iter()), &untyped);
GateIndex { methods: index, slots }
})
}
pub fn with_forward_policy(
mut self,
callee_ns: impl Into<String>,
policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>,
) -> Self {
let inner = self.inner_mut("Cannot register forward policy: DynamicHub has multiple references");
inner.forward_policies.register(callee_ns, policy);
self
}
pub fn forward_policies(&self) -> &super::forward_registry::ForwardPolicyRegistry {
&self.inner.forward_policies
}
pub fn with_auth_capabilities(
mut self,
caps: plexus_auth_core::BackendAuthCapabilities,
) -> Self {
let inner = self.inner_mut("Cannot set auth_capabilities: DynamicHub has multiple references");
inner.auth_capabilities = Some(caps);
self
}
pub fn auth_capabilities(&self) -> Option<&plexus_auth_core::BackendAuthCapabilities> {
self.inner.auth_capabilities.as_ref()
}
#[deprecated(since = "0.3.0", note = "Use DynamicHub::new(namespace) instead")]
pub fn with_namespace(namespace: impl Into<String>) -> Self {
Self::new(namespace)
}
pub fn runtime_namespace(&self) -> &str {
&self.inner.namespace
}
pub fn registry(&self) -> std::sync::RwLockReadGuard<'_, PluginRegistry> {
self.inner.registry.read().unwrap()
}
fn assert_no_root_shadow(&self, child_namespace: &str) {
if child_namespace == self.inner.namespace {
panic!(
"DynamicHub namespace shadow: activation namespace '{child}' collides with the hub root namespace '{root}'. \
The hub root name is a routing namespace, not a label — routing resolves the root first, so a like-named \
child activation is unreachable (every '{child}.<method>' call resolves to the hub root and fails with \
'Command not found', and navigation resolves the child back to the root schema). \
Fix: rename the hub root so it differs from every registered activation's namespace, \
e.g. DynamicHub::new(\"{root}_hub\").register(...). [Z2H-8 / HOSTLESS-3]",
child = child_namespace,
root = self.inner.namespace,
);
}
}
pub fn register<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
let namespace = activation.namespace().to_string();
self.assert_no_root_shadow(&namespace);
let plugin_id = activation.plugin_id();
let activation_for_rpc = activation.clone();
let activation_for_router = activation.clone();
let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
inner.registry.write().unwrap().register(
plugin_id,
namespace.clone(),
namespace.clone(), );
if let Some(catalog) = inner.auth_catalog.as_ref() {
let schema = activation.plugin_schema();
let statics = super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation));
let (mut typed, mut untyped) = (Vec::new(), Vec::new());
for s in std::iter::once(&schema).chain(statics.iter()) {
super::slots::slot_schemas(s, &mut typed, &mut untyped);
}
for child in statics.iter().chain(typed.iter()) {
catalog.add(child);
}
catalog.add_slots(&untyped);
catalog.add(&schema);
}
inner.nested_count += Activation::static_child_schemas(&activation).len();
inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
inner.child_routers.insert(namespace.clone(), Arc::new(activation_for_router));
inner.pending_rpc.lock().unwrap()
.push(Box::new(move || activation_for_rpc.into_rpc_methods()));
self
}
#[deprecated(since = "0.5.0", note = "Use register() — it now handles both leaf and hub activations")]
pub fn register_hub<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
let namespace = activation.namespace().to_string();
self.assert_no_root_shadow(&namespace);
let plugin_id = activation.plugin_id();
let activation_for_rpc = activation.clone();
let activation_for_router = activation.clone();
let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
inner.registry.write().unwrap().register(
plugin_id,
namespace.clone(),
namespace.clone(), );
if let Some(catalog) = inner.auth_catalog.as_ref() {
let schema = activation.plugin_schema();
let statics = super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation));
let (mut typed, mut untyped) = (Vec::new(), Vec::new());
for s in std::iter::once(&schema).chain(statics.iter()) {
super::slots::slot_schemas(s, &mut typed, &mut untyped);
}
for child in statics.iter().chain(typed.iter()) {
catalog.add(child);
}
catalog.add_slots(&untyped);
catalog.add(&schema);
}
inner.nested_count += Activation::static_child_schemas(&activation).len();
inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
inner.child_routers.insert(namespace, Arc::new(activation_for_router));
inner.pending_rpc.lock().unwrap()
.push(Box::new(move || activation_for_rpc.into_rpc_methods()));
self
}
pub fn list_methods(&self) -> Vec<String> {
let mut methods = Vec::new();
for m in Activation::methods(self) {
methods.push(format!("{}.{}", self.inner.namespace, m));
}
for (ns, act) in &self.inner.activations {
for m in act.methods() {
methods.push(format!("{}.{}", ns, m));
}
}
methods.sort();
methods
}
pub fn list_activations_info(&self) -> Vec<ActivationInfo> {
let mut activations = Vec::new();
activations.push(ActivationInfo {
namespace: Activation::namespace(self).to_string(),
version: Activation::version(self).to_string(),
description: Activation::description(self).to_string(),
methods: Activation::methods(self).iter().map(|s| s.to_string()).collect(),
});
for a in self.inner.activations.values() {
activations.push(ActivationInfo {
namespace: a.namespace().to_string(),
version: a.version().to_string(),
description: a.description().to_string(),
methods: a.methods().iter().map(|s| s.to_string()).collect(),
});
}
activations
}
pub fn compute_hash(&self) -> String {
self.described().service.hash.clone()
}
fn own_hash(&self, caller: Option<&super::auth::AuthContext>) -> String {
match self.inner.gate {
Some(_) => self.shaped(caller).1.hash.clone(),
None => self.described().service.hash.clone(),
}
}
fn own_schema(&self, caller: Option<&super::auth::AuthContext>) -> PluginSchema {
match self.inner.gate {
Some(_) => self.shaped(caller).1.service.clone(),
None => self.described().service.clone(),
}
}
pub async fn route(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>) -> Result<PlexusStream, PlexusError> {
self.route_with_ctx(method, params, auth, None).await
}
pub async fn route_with_ctx(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
if super::service_scope::entered() {
return self.route_entered(method, params, auth, raw_ctx).await;
}
super::service_scope::scope(self.downgrade(), self.route_entered(method, params, auth, raw_ctx)).await
}
pub fn downgrade(&self) -> super::service_scope::WeakService {
super::service_scope::WeakService::new(Arc::downgrade(&self.inner))
}
pub(crate) async fn schema_for_child(&self, method: &str, params: Value) -> Result<PlexusStream, PlexusError> {
let (_, name) = self.parse_method(method)?;
if !Self::is_schema_query(name) {
return Err(PlexusError::Unauthenticated(format!(
"`{method}` is not a schema: outside a call, a child asks its service only for a schema"
)));
}
let ctx = crate::call::CallContext::admitted(None, plexus_auth_core::grants::Reach::everywhere());
let routed = self.route_ungated(method, params, None, None);
super::service_scope::scope(self.downgrade(), in_call(ctx, routed)).await
}
async fn route_entered(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
if let Some(gate) = self.inner.gate.as_ref() {
let (auth, ended) = super::grant_gate::standing(gate, auth);
let decide = |info| super::grant_gate::decide(gate, &self.inner.namespace, method, info, ¶ms, auth, &self.inner.signed_in_grants);
let admit = match self.gate_index().methods.get(method) {
Some(info) => decide(Some(info)),
None => match self.gate_info(method) {
Some(slot) => decide(None).or_else(|_| decide(Some(slot))),
None => decide(None),
},
}
.map_err(|e| super::grant_gate::say_ended(e, ended.as_deref()))?;
return match admit {
super::grant_gate::Admit::Open => {
let grant = plexus_auth_core::grants::Grant::new(method.to_string());
in_call(crate::call::CallContext::introspection(auth, Arc::clone(gate), grant), async {
match self.introspect_in_view(method, ¶ms, auth, raw_ctx).await {
Some(answer) => answer,
None => self.route_ungated(method, params, auth, raw_ctx).await,
}
})
.await
}
super::grant_gate::Admit::Reach(reach) => {
in_call(crate::call::CallContext::admitted(auth, reach), self.route_ungated(method, params, auth, raw_ctx)).await
}
};
}
let ctx = match crate::call::context() {
Ok(outer) => outer.with_auth(auth),
Err(_) => crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere()),
};
in_call(ctx, self.route_ungated(method, params, auth, raw_ctx)).await
}
async fn route_ungated(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
if self.inner.scope_registry.is_some() || self.inner.default_deny {
let registry = self
.inner
.scope_registry
.as_deref()
.unwrap_or_else(|| super::scope_gate::empty_registry());
super::scope_gate::enforce(
registry,
self.inner.default_deny,
&self.inner.audit_sink,
method,
self.gate_info(method),
auth,
raw_ctx.and_then(|ctx| ctx.peer.map(|peer| peer.ip())),
)
.await?;
}
let (namespace, method_name) = self.parse_method(method)?;
if namespace == self.inner.namespace && method_name == "ir" {
self.check_ir_names(¶ms, auth)?;
}
let stream = if namespace == self.inner.namespace {
Activation::call(self, method_name, params, auth, raw_ctx).await?
} else {
let activation = self.inner.activations.get(namespace)
.ok_or_else(|| PlexusError::ActivationNotFound(namespace.to_string()))?;
activation.call(method_name, params, auth, raw_ctx).await?
};
if Self::is_schema_query(method_name) {
if let Some(site) = self.derived_site_hint() {
return Ok(fill_site_hints_in_schema_stream(stream, site));
}
}
Ok(stream)
}
fn is_schema_query(method_name: &str) -> bool {
method_name == "schema" || method_name.ends_with(".schema")
}
pub fn derived_site_hint(&self) -> Option<plexus_auth_core::AttachmentSite> {
self.inner
.auth_capabilities
.as_ref()
.and_then(|caps| caps.implied_attachment_site())
}
pub async fn do_resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
let path = self.inner.registry.read().unwrap()
.lookup(handle.plugin_id)
.map(|s| s.to_string())
.ok_or_else(|| PlexusError::ActivationNotFound(handle.plugin_id.to_string()))?;
let activation = self.inner.activations.get(&path)
.ok_or_else(|| PlexusError::ActivationNotFound(path.clone()))?;
activation.resolve_handle(handle).await
}
pub fn get_activation_schema(&self, namespace: &str) -> Option<Schema> {
self.inner.activations.get(namespace).map(|a| a.schema())
}
pub fn registry_snapshot(&self) -> PluginRegistrySnapshot {
let guard = self.inner.registry.read().unwrap();
PluginRegistrySnapshot {
by_id: guard.by_id.clone(),
by_path: guard.by_path.clone(),
}
}
pub fn lookup_plugin(&self, id: uuid::Uuid) -> Option<String> {
self.inner.registry.read().unwrap().lookup(id).map(|s| s.to_string())
}
pub fn lookup_plugin_by_path(&self, path: &str) -> Option<uuid::Uuid> {
self.inner.registry.read().unwrap().lookup_by_path(path)
}
pub fn list_plugin_schemas(&self) -> Vec<PluginSchema> {
let mut schemas = Vec::new();
schemas.push(Activation::plugin_schema(self));
for a in self.inner.activations.values() {
schemas.push(a.plugin_schema());
}
schemas
}
#[deprecated(note = "Use list_plugin_schemas instead")]
pub fn list_full_schemas(&self) -> Vec<PluginSchema> {
self.list_plugin_schemas()
}
pub fn get_method_help(&self, method: &str) -> Option<String> {
let (namespace, method_name) = self.parse_method(method).ok()?;
let activation = self.inner.activations.get(namespace)?;
activation.method_help(method_name)
}
fn parse_method<'a>(&self, method: &'a str) -> Result<(&'a str, &'a str), PlexusError> {
let parts: Vec<&str> = method.splitn(2, '.').collect();
if parts.len() != 2 {
return Err(PlexusError::InvalidParams {
param: Some("method".into()),
problem: ParamProblem::Malformed {
detail: format!("expected `namespace.method`, got `{}`", method),
},
});
}
Ok((parts[0], parts[1]))
}
pub fn plugin_children(&self) -> Vec<ChildSummary> {
self.inner.activations.values()
.map(|a| {
let schema = a.plugin_schema();
ChildSummary {
namespace: schema.namespace,
description: schema.description,
hash: schema.hash,
}
})
.collect()
}
pub fn into_rpc_module(self) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
let mut module = RpcModule::new(());
PlexusContext::init(self.compute_hash());
let ns = self.runtime_namespace();
let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
let plexus_for_call = self.clone();
module.register_subscription(
call_method,
PLEXUS_NOTIF_METHOD,
call_unsub,
move |params, pending, _ctx, ext| {
let plexus = plexus_for_call.clone();
let identified = plexus.inner.gate.is_some();
serve_call(plexus, params, pending, ext, ns_static, identified)
}
)?;
register_input_methods(&mut module, ns_static)?;
let plexus_for_hash = self.clone();
module.register_subscription(
hash_method,
PLEXUS_NOTIF_METHOD,
hash_unsub,
move |_params, pending, _ctx, ext| {
let plexus = plexus_for_hash.clone();
Box::pin(async move {
let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
let value = plexus.own_hash(auth);
let stream = async_stream::stream! {
yield HashEvent::Hash { value };
};
let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
pipe_stream_to_subscription(pending, wrapped, &ext).await
})
}
)?;
let plexus_for_schema = self.clone();
module.register_subscription(
schema_method,
PLEXUS_NOTIF_METHOD,
schema_unsub,
move |params, pending, _ctx, ext| {
let plexus = plexus_for_schema.clone();
Box::pin(async move {
let p: SchemaParams = params.parse().unwrap_or_default();
let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
let mut plugin_schema = plexus.own_schema(auth);
if let Some(site) = plexus.derived_site_hint() {
plugin_schema.fill_site_hints(&site);
}
let result = if let Some(ref name) = p.method {
plugin_schema.methods.iter()
.find(|m| m.name == *name)
.map(|m| super::SchemaResult::Method(m.clone()))
.ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
-32602,
format!("Method '{}' not found", name),
None::<()>,
))?
} else {
super::SchemaResult::Plugin(plugin_schema)
};
let stream = async_stream::stream! { yield result; };
let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
pipe_stream_to_subscription(pending, wrapped, &ext).await
})
}
)?;
let info_payload = build_info_payload(
self.runtime_namespace(),
self.inner.auth_capabilities.as_ref(),
);
let plexus_for_info = self.inner.gate.is_some().then(|| self.clone());
module.register_subscription(
"_info",
PLEXUS_NOTIF_METHOD,
"_info_unsub",
move |_params, pending, _ctx, ext| {
let payload = match plexus_for_info.as_ref() {
Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
None => info_payload.clone(),
};
Box::pin(async move {
let info_stream = futures::stream::once(async move { payload });
let wrapped = super::streaming::wrap_stream(
info_stream,
"_info",
vec![]
);
pipe_stream_to_subscription(pending, wrapped, &ext).await
})
}
)?;
let pending = std::mem::take(&mut *self.inner.pending_rpc.lock().unwrap());
if self.inner.gate.is_none() {
for factory in pending {
module.merge(factory())?;
}
}
for (ns, router) in self.inner.child_routers.iter() {
register_child_capability_methods(&mut module, ns, router.clone(), self.inner.gate.clone())?;
}
Ok(module)
}
pub fn serve_call(
&self,
params: jsonrpsee::types::Params<'static>,
pending: jsonrpsee::PendingSubscriptionSink,
ext: http::Extensions,
ns: &'static str,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>> {
serve_call(self.clone(), params, pending, ext, ns, true)
}
pub fn arc_into_rpc_module(hub: Arc<Self>) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
let mut module = RpcModule::new(());
PlexusContext::init(hub.compute_hash());
let ns = hub.runtime_namespace();
let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
let hub_for_call = hub.clone();
module.register_subscription(
call_method,
call_method,
call_unsub,
move |params, pending, _ctx, ext| {
let hub = hub_for_call.clone();
let hub = (*hub).clone();
serve_call(hub, params, pending, ext, ns_static, true)
}
)?;
register_input_methods(&mut module, ns_static)?;
let hub_for_hash = hub.clone();
module.register_subscription(
hash_method,
PLEXUS_NOTIF_METHOD,
hash_unsub,
move |_params, pending, _ctx, ext| {
let hub = hub_for_hash.clone();
Box::pin(async move {
let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
let value = hub.own_hash(auth);
let stream = async_stream::stream! {
yield HashEvent::Hash { value };
};
let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
pipe_stream_to_subscription(pending, wrapped, &ext).await
})
}
)?;
let hub_for_schema = hub.clone();
module.register_subscription(
schema_method,
PLEXUS_NOTIF_METHOD,
schema_unsub,
move |params, pending, _ctx, ext| {
let hub = hub_for_schema.clone();
Box::pin(async move {
let p: SchemaParams = params.parse().unwrap_or_default();
let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
let mut plugin_schema = hub.own_schema(auth);
if let Some(site) = hub.derived_site_hint() {
plugin_schema.fill_site_hints(&site);
}
let result = if let Some(ref name) = p.method {
plugin_schema.methods.iter()
.find(|m| m.name == *name)
.map(|m| super::SchemaResult::Method(m.clone()))
.ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
-32602,
format!("Method '{}' not found", name),
None::<()>,
))?
} else {
super::SchemaResult::Plugin(plugin_schema)
};
let stream = async_stream::stream! {
yield result;
};
let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
pipe_stream_to_subscription(pending, wrapped, &ext).await
})
}
)?;
let info_payload = build_info_payload(
hub.runtime_namespace(),
hub.inner.auth_capabilities.as_ref(),
);
let hub_for_info = hub.inner.gate.is_some().then(|| hub.clone());
module.register_subscription(
"_info",
PLEXUS_NOTIF_METHOD,
"_info_unsub",
move |_params, pending, _ctx, ext| {
let payload = match hub_for_info.as_ref() {
Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
None => info_payload.clone(),
};
Box::pin(async move {
let info_stream = futures::stream::once(async move { payload });
let wrapped = super::streaming::wrap_stream(
info_stream,
"_info",
vec![]
);
pipe_stream_to_subscription(pending, wrapped, &ext).await
})
}
)?;
let mut pending = std::mem::take(&mut *hub.inner.pending_rpc.lock().unwrap());
if hub.inner.gate.is_some() {
pending.clear();
}
tracing::trace!(factories = pending.len(), "merging activation RPC factories");
for (idx, factory) in pending.into_iter().enumerate() {
tracing::trace!(factory_idx = idx, "calling factory to get Methods");
let methods = factory();
let method_count = methods.method_names().count();
tracing::trace!(factory_idx = idx, methods = method_count, "factory returned Methods; merging into module");
module.merge(methods)?;
tracing::trace!(factory_idx = idx, "successfully merged factory methods");
}
tracing::trace!("all activations merged successfully");
for (ns, router) in hub.inner.child_routers.iter() {
register_child_capability_methods(&mut module, ns, router.clone(), hub.inner.gate.clone())?;
}
Ok(module)
}
}
fn listing_context(
gate: Option<&Arc<plexus_auth_core::grants::Gate>>,
ext: &jsonrpsee::Extensions,
method: &str,
) -> crate::call::CallContext {
let auth = ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
match gate {
None => crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere()),
Some(gate) => {
let (auth, _) = super::grant_gate::standing(gate, auth);
crate::call::CallContext::introspection(auth, Arc::clone(gate), plexus_auth_core::grants::Grant::new(method.to_string()))
}
}
}
#[allow(deprecated)] fn register_child_capability_methods(
module: &mut RpcModule<()>,
namespace: &str,
router: Arc<dyn ChildRouter>,
gate: Option<Arc<plexus_auth_core::grants::Gate>>,
) -> Result<(), jsonrpsee::core::RegisterMethodError> {
let caps = router.capabilities();
if caps.is_empty() {
return Ok(());
}
let ns_static: &'static str = Box::leak(namespace.to_string().into_boxed_str());
if caps.contains(ChildCapabilities::LIST) {
let list_method: &'static str =
Box::leak(format!("{}.list_children", namespace).into_boxed_str());
let list_unsub: &'static str =
Box::leak(format!("{}.list_children_unsub", namespace).into_boxed_str());
let router_for_list = router.clone();
let gate_for_list = gate.clone();
module.register_subscription(
list_method,
PLEXUS_NOTIF_METHOD,
list_unsub,
move |_params, pending, _ctx, ext| {
let router = router_for_list.clone();
let ctx = listing_context(gate_for_list.as_ref(), &ext, list_method);
Box::pin(async move {
let collected: Vec<String> = crate::call::scope(ctx, async {
match router.list_children().await {
Some(mut s) => {
use futures::StreamExt;
let mut acc = Vec::new();
while let Some(name) = s.next().await {
acc.push(name);
}
acc
}
None => Vec::new(),
}
})
.await;
let stream = async_stream::stream! {
for name in collected {
yield name;
}
};
let wrapped = super::streaming::wrap_stream(
stream,
"list_children",
vec![ns_static.into()],
);
pipe_stream_to_subscription(pending, wrapped, &ext).await
})
},
)?;
}
if caps.contains(ChildCapabilities::SEARCH) {
let search_method: &'static str =
Box::leak(format!("{}.search_children", namespace).into_boxed_str());
let search_unsub: &'static str =
Box::leak(format!("{}.search_children_unsub", namespace).into_boxed_str());
let router_for_search = router.clone();
let gate_for_search = gate.clone();
module.register_subscription(
search_method,
PLEXUS_NOTIF_METHOD,
search_unsub,
move |params, pending, _ctx, ext| {
let router = router_for_search.clone();
let ctx = listing_context(gate_for_search.as_ref(), &ext, search_method);
Box::pin(async move {
let p: SearchChildrenParams = params.parse()?;
let collected: Vec<String> = crate::call::scope(ctx, async {
match router.search_children(&p.query).await {
Some(mut s) => {
use futures::StreamExt;
let mut acc = Vec::new();
while let Some(name) = s.next().await {
acc.push(name);
}
acc
}
None => Vec::new(),
}
})
.await;
let stream = async_stream::stream! {
for name in collected {
yield name;
}
};
let wrapped = super::streaming::wrap_stream(
stream,
"search_children",
vec![ns_static.into()],
);
pipe_stream_to_subscription(pending, wrapped, &ext).await
})
},
)?;
}
Ok(())
}
#[derive(Debug, serde::Deserialize)]
struct SearchChildrenParams {
query: String,
}
#[derive(Debug, serde::Deserialize)]
pub(crate) struct CallParams {
pub(crate) method: String,
#[serde(default)]
pub(crate) params: Option<Value>,
}
pub(crate) struct InputTerms {
pub(crate) grant: String,
pub(crate) targets: Vec<String>,
pub(crate) recheck: bool,
}
use super::schema::SchemaParams;
fn serve_call(
service: DynamicHub,
params: jsonrpsee::types::Params<'static>,
pending: jsonrpsee::PendingSubscriptionSink,
ext: http::Extensions,
ns: &'static str,
identified: bool,
) -> CallFuture {
let call: CallParams = match params.parse() {
Ok(call) => call,
Err(e) => return Box::pin(async move { Err(e.into()) }),
};
if service.may_take_input(&call.method) {
return Box::pin(serve_seamed(service, call, params, pending, ext, ns, identified));
}
let CallParams { method, params: args } = call;
Box::pin(async move {
let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref()) } else { None };
match service.route(&method, args.unwrap_or_default(), caller).await {
Ok(stream) => pipe_stream_to_subscription(pending, stream, &ext).await,
Err(e) => {
let sink = pending.accept().await?;
if let Some(raw) = error_item_raw(ns, &e) {
let _ = sink.send(raw).await;
}
Ok(())
}
}
})
}
type CallFuture = std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>>;
async fn serve_seamed(
service: DynamicHub,
call: CallParams,
params: jsonrpsee::types::Params<'static>,
pending: jsonrpsee::PendingSubscriptionSink,
ext: http::Extensions,
ns: &'static str,
identified: bool,
) -> jsonrpsee::core::SubscriptionResult {
let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().cloned() } else { None };
let seen = service.inner.gate.as_ref().map_or(0, |g| g.generation().current());
let opened = Arc::new(std::sync::Mutex::new(None::<super::input::Opened>));
let take = || opened.lock().unwrap_or_else(|e| e.into_inner()).take();
let mut scoped = std::pin::pin!(super::input::CALL.scope(
std::cell::RefCell::new(super::input::Seam { service: service.clone(), params, pending: Some(pending), ext, seen, opened: opened.clone(), refused: None }),
service.route(&call.method, call.params.unwrap_or_default(), caller.as_deref()),
));
let answered = std::future::poll_fn(|cx| match std::future::Future::poll(scoped.as_mut(), cx) {
std::task::Poll::Ready(answer) => std::task::Poll::Ready(Some(answer)),
std::task::Poll::Pending if opened.lock().unwrap_or_else(|e| e.into_inner()).is_some() => std::task::Poll::Ready(None),
std::task::Poll::Pending => std::task::Poll::Pending,
})
.await;
let Some(answer) = answered else {
let super::input::Opened { sink, duplex } = take().expect("opened, the route still resolving");
let mut routing = std::pin::pin!(async { scoped.as_mut().await.map_err(|e| error_item(ns, &e)) });
return Box::pin(super::wire::pipe_duplex(sink, super::wire::Output::Routing(routing.as_mut()), duplex)).await;
};
let super::input::Seam { pending, ext, refused, .. } = scoped.as_mut().take_value().expect("the scope ran to its end").into_inner();
match (answer, take()) {
(Ok(stream), Some(opened)) => Box::pin(super::wire::pipe_duplex(opened.sink, super::wire::Output::Ready(stream), opened.duplex)).await,
(Ok(stream), None) => {
let pending = pending.expect("only an open takes it, and an open is `opened`");
pipe_stream_to_subscription(pending, stream, &ext).await
}
(Err(e), opened) => {
let sink = match (opened, pending) {
(Some(opened), _) => opened.sink,
(None, Some(pending)) => pending.accept().await?,
(None, None) => return Ok(()),
};
let raw = match refused {
Some(item) => serde_json::value::to_raw_value(&item).ok(),
None => error_item_raw(ns, &e),
};
if let Some(raw) = raw {
let _ = sink.send(raw).await;
}
Ok(())
}
}
}
fn register_input_methods(module: &mut RpcModule<()>, ns: &'static str) -> Result<(), jsonrpsee::core::RegisterMethodError> {
use super::input::{Delivered, InputTable};
use jsonrpsee::types::ErrorObjectOwned;
fn answer(delivered: Delivered) -> Result<bool, ErrorObjectOwned> {
match delivered {
Delivered::Taken => Ok(true),
Delivered::Dropped | Delivered::Refused => Ok(false),
Delivered::NotThisCall => Err(ErrorObjectOwned::owned(
-32003,
"not_this_call: input comes from the connection that opened the call",
Some(serde_json::json!({"error_kind": "not_this_call"})),
)),
Delivered::Malformed => Err(ErrorObjectOwned::owned(-32602, "invalid params: subscription, seq and items", None::<()>)),
}
}
fn table(ext: &http::Extensions) -> Result<&Arc<InputTable>, ErrorObjectOwned> {
ext.get::<super::wire::FrameSink>()
.and_then(super::wire::FrameSink::inputs)
.ok_or_else(|| ErrorObjectOwned::owned(-32601, "this transport carries no input half: call over a WebSocket", None::<()>))
}
let input_method: &'static str = Box::leak(format!("{ns}.input").into_boxed_str());
let end_method: &'static str = Box::leak(format!("{ns}.end").into_boxed_str());
module.register_method(input_method, move |params, _ctx, ext| {
let frame = bytes::Bytes::copy_from_slice(params.as_str().unwrap_or("null").as_bytes());
answer(table(ext)?.input(ns, &frame, &frame))
})?;
module.register_method(end_method, move |params, _ctx, ext| answer(table(ext)?.end(ns, params.as_str().unwrap_or("null").as_bytes())))?;
Ok(())
}
async fn pipe_stream_to_subscription(
pending: jsonrpsee::PendingSubscriptionSink,
stream: PlexusStream,
ext: &http::Extensions,
) -> jsonrpsee::core::SubscriptionResult {
let sink = pending.accept().await?;
super::wire::pipe(sink, stream, ext).await
}
#[plexus_macros::activation(
namespace = "plexus",
version = "1.0.0",
description = "Central routing and introspection",
hub,
namespace_fn = "runtime_namespace"
)]
#[allow(deprecated)]
impl DynamicHub {
#[plexus_macros::method(
description = "Route a call to a registered activation",
params(
method = "The method to call (format: namespace.method)",
params = "Parameters to pass to the method (optional, defaults to {})"
)
)]
async fn call(
&self,
method: String,
params: Option<Value>,
) -> impl Stream<Item = super::types::PlexusStreamItem> + Send + 'static {
use super::context::PlexusContext;
use super::types::{PlexusStreamItem, StreamMetadata};
let result = self.route(&method, params.unwrap_or_default(), None).await;
match result {
Ok(plexus_stream) => {
plexus_stream
}
Err(e) => {
let metadata = StreamMetadata::new(
vec![self.inner.namespace.clone()],
PlexusContext::hash(),
);
Box::pin(futures::stream::once(async move {
PlexusStreamItem::from_plexus_error(metadata, &e, false)
}))
}
}
}
#[plexus_macros::method(description = "Get plexus configuration hash (from the recursive schema)\n\n This hash changes whenever any method or child plugin changes.\n It's computed from the method hashes rolled up through the schema tree.")]
async fn hash(&self) -> impl Stream<Item = HashEvent> + Send + 'static {
let schema = Activation::plugin_schema(self);
stream! { yield HashEvent::Hash { value: schema.hash }; }
}
#[plexus_macros::method(description = "Get plugin hashes for cache validation")]
#[allow(deprecated)]
async fn hashes(&self) -> impl Stream<Item = PluginHashes> + Send + 'static {
let schema = Activation::plugin_schema(self);
stream! {
yield PluginHashes {
namespace: schema.namespace.clone(),
self_hash: schema.self_hash.clone(),
children_hash: schema.children_hash.clone(),
hash: schema.hash.clone(),
children: schema.children.as_ref().map(|kids| {
kids.iter()
.map(|c| ChildHashes {
namespace: c.namespace.clone(),
hash: c.hash.clone(),
})
.collect()
}),
};
}
}
#[plexus_macros::method(
description = "The service's IR (3.0): every type once, each method referring to them — of the namespaces asked, or the whole service",
params(namespaces = "The namespaces (dotted paths) to describe; none: the whole service")
)]
async fn ir(
&self,
auth: Option<&super::auth::AuthContext>,
namespaces: Option<Vec<String>>,
) -> Result<super::ir::ServiceIr, super::ir::IrError> {
self.service_ir(&namespaces.unwrap_or_default(), auth).await
}
}
use super::hub_context::HubContext;
use std::sync::Weak;
#[async_trait]
impl HubContext for Weak<DynamicHub> {
async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
let hub = self.upgrade().ok_or_else(|| {
PlexusError::ExecutionError("Parent hub has been dropped".to_string())
})?;
hub.do_resolve_handle(handle).await
}
async fn call(&self, method: &str, params: serde_json::Value) -> Result<PlexusStream, PlexusError> {
let hub = self.upgrade().ok_or_else(|| {
PlexusError::ExecutionError("Parent hub has been dropped".to_string())
})?;
hub.route(method, params, None).await
}
fn is_valid(&self) -> bool {
self.upgrade().is_some()
}
}
#[async_trait]
impl ChildRouter for DynamicHub {
fn router_namespace(&self) -> &str {
&self.inner.namespace
}
async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
self.route_with_ctx(method, params, auth, raw_ctx).await
}
async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
self.inner.child_routers.get(name)
.map(|router| {
Box::new(ArcChildRouter(router.clone())) as Box<dyn ChildRouter>
})
}
fn forward_policy_for(
&self,
callee_ns: &str,
) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
self.inner.forward_policies.get(callee_ns)
}
}
#[cfg(test)]
#[allow(deprecated)]
mod tests {
use super::*;
#[test]
fn dynamic_hub_implements_activation() {
fn assert_activation<T: Activation>() {}
assert_activation::<DynamicHub>();
}
#[test]
fn dynamic_hub_methods() {
let hub = DynamicHub::new("test");
let methods = hub.methods();
assert!(methods.contains(&"call"));
assert!(methods.contains(&"hash"));
assert!(methods.contains(&"schema"));
}
#[test]
fn dynamic_hub_hash_stable() {
let h1 = DynamicHub::new("test");
let h2 = DynamicHub::new("test");
assert_eq!(h1.compute_hash(), h2.compute_hash());
}
#[test]
fn dynamic_hub_is_hub() {
use crate::activations::health::Health;
let hub = DynamicHub::new("test").register(Health::new());
let schema = hub.plugin_schema();
assert!(schema.is_hub(), "dynamic hub should be a hub");
assert!(!schema.is_leaf(), "dynamic hub should not be a leaf");
let children = schema.children.expect("dynamic hub should have children");
assert!(!children.is_empty(), "dynamic hub should have at least one child");
let health = children.iter().find(|c| c.namespace == "health").expect("should have health child");
assert!(!health.hash.is_empty(), "health should have a hash");
}
#[test]
#[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
fn dynamic_hub_rejects_root_namespace_shadow() {
use crate::activations::health::Health;
let _hub = DynamicHub::new("health").register(Health::new());
}
#[test]
#[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
fn dynamic_hub_register_hub_rejects_root_namespace_shadow() {
use crate::activations::health::Health;
let _hub = DynamicHub::new("health").register_hub(Health::new());
}
#[test]
fn dynamic_hub_shadow_error_names_collision_and_fix() {
use crate::activations::health::Health;
let result = std::panic::catch_unwind(|| {
let _hub = DynamicHub::new("health").register(Health::new());
});
let err = result.expect_err("shadow registration must panic");
let msg = err
.downcast_ref::<String>()
.cloned()
.or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
.expect("panic payload should be a string");
assert!(msg.contains("'health'"), "must name the colliding namespace: {msg}");
assert!(msg.contains("hub root namespace"), "must name the root side: {msg}");
assert!(msg.contains("rename the hub root"), "must suggest the fix: {msg}");
assert!(msg.contains("Z2H-8"), "must cite the ticket: {msg}");
}
#[test]
fn dynamic_hub_non_colliding_registration_unaffected() {
use crate::activations::health::Health;
let hub = DynamicHub::new("health_hub").register(Health::new());
assert_eq!(hub.runtime_namespace(), "health_hub");
let schema = hub.plugin_schema();
let children = schema.children.expect("hub should have children");
assert!(
children.iter().any(|c| c.namespace == "health"),
"health child must be registered"
);
assert!(hub.list_methods().iter().any(|m| m.starts_with("health.")));
}
#[test]
fn dynamic_hub_schema_structure() {
use crate::activations::health::Health;
let hub = DynamicHub::new("test").register(Health::new());
let schema = hub.plugin_schema();
let json = serde_json::to_string_pretty(&schema).unwrap();
println!("DynamicHub schema:\n{}", json);
assert_eq!(schema.namespace, "test");
assert!(schema.methods.iter().any(|m| m.name == "call"));
assert!(schema.children.is_some());
}
#[tokio::test]
async fn invariant_resolve_handle_unknown_activation() {
use crate::activations::health::Health;
use crate::types::Handle;
use uuid::Uuid;
let hub = DynamicHub::new("test").register(Health::new());
let unknown_plugin_id = Uuid::new_v4();
let handle = Handle::new(unknown_plugin_id, "1.0.0", "some_method");
let result = hub.do_resolve_handle(&handle).await;
match result {
Err(PlexusError::ActivationNotFound(_)) => {
}
Err(other) => panic!("Expected ActivationNotFound, got {:?}", other),
Ok(_) => panic!("Expected error for unknown activation"),
}
}
#[tokio::test]
async fn invariant_resolve_handle_unsupported() {
use crate::activations::health::Health;
use crate::types::Handle;
let hub = DynamicHub::new("test").register(Health::new());
let handle = Handle::new(Health::PLUGIN_ID, "1.0.0", "check");
let result = hub.do_resolve_handle(&handle).await;
match result {
Err(PlexusError::HandleNotSupported(name)) => {
assert_eq!(name, "health");
}
Err(other) => panic!("Expected HandleNotSupported, got {:?}", other),
Ok(_) => panic!("Expected error for unsupported handle"),
}
}
#[tokio::test]
async fn invariant_resolve_handle_routes_by_plugin_id() {
use crate::activations::health::Health;
use crate::activations::echo::EchoActivation;
use crate::types::Handle;
use uuid::Uuid;
let health = Health::new();
let echo = EchoActivation::new();
let health_plugin_id = health.plugin_id();
let echo_plugin_id = echo.plugin_id();
let hub = DynamicHub::new("test")
.register(health)
.register(echo);
let health_handle = Handle::new(health_plugin_id, "1.0.0", "check");
match hub.do_resolve_handle(&health_handle).await {
Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "health"),
Err(other) => panic!("health handle should route to health activation, got {:?}", other),
Ok(_) => panic!("health handle should return HandleNotSupported"),
}
let echo_handle = Handle::new(echo_plugin_id, "1.0.0", "echo");
match hub.do_resolve_handle(&echo_handle).await {
Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "echo"),
Err(other) => panic!("echo handle should route to echo activation, got {:?}", other),
Ok(_) => panic!("echo handle should return HandleNotSupported"),
}
let unknown_handle = Handle::new(Uuid::new_v4(), "1.0.0", "method");
match hub.do_resolve_handle(&unknown_handle).await {
Err(PlexusError::ActivationNotFound(_)) => { },
Err(other) => panic!("unknown handle should return ActivationNotFound, got {:?}", other),
Ok(_) => panic!("unknown handle should return ActivationNotFound"),
}
}
#[test]
fn invariant_handle_plugin_id_determines_routing() {
use crate::activations::health::Health;
use crate::activations::echo::EchoActivation;
use crate::types::Handle;
let health = Health::new();
let echo = EchoActivation::new();
let health_handle = Handle::new(health.plugin_id(), "1.0.0", "check")
.with_meta(vec!["msg-123".into(), "user".into()]);
let echo_handle = Handle::new(echo.plugin_id(), "1.0.0", "echo")
.with_meta(vec!["msg-123".into(), "user".into()]);
assert_ne!(health_handle.plugin_id, echo_handle.plugin_id);
}
#[test]
fn plugin_registry_basic_operations() {
let mut registry = PluginRegistry::new();
let id = uuid::Uuid::new_v4();
registry.register(id, "test_plugin".to_string(), "test".to_string());
assert_eq!(registry.lookup(id), Some("test_plugin"));
assert_eq!(registry.lookup_by_path("test_plugin"), Some(id));
let entry = registry.get(id).expect("should have entry");
assert_eq!(entry.path, "test_plugin");
assert_eq!(entry.plugin_type, "test");
}
#[test]
fn plugin_registry_populated_on_register() {
use crate::activations::health::Health;
let hub = DynamicHub::new("test").register(Health::new());
let registry = hub.registry();
assert!(!registry.is_empty(), "registry should not be empty after registration");
let health_id = registry.lookup_by_path("health");
assert!(health_id.is_some(), "health should be registered by path");
let health_uuid = health_id.unwrap();
assert_eq!(registry.lookup(health_uuid), Some("health"));
}
#[test]
fn plugin_registry_deterministic_uuid() {
use crate::activations::health::Health;
let health1 = Health::new();
let health2 = Health::new();
assert_eq!(health1.plugin_id(), health2.plugin_id(),
"same activation type should have deterministic UUID");
let expected = uuid::Uuid::new_v5(
&uuid::Uuid::NAMESPACE_OID,
b"health@1"
);
assert_eq!(health1.plugin_id(), expected,
"plugin_id should be deterministic from namespace@major_version");
}
struct MinimalRouter;
#[async_trait]
impl ChildRouter for MinimalRouter {
fn router_namespace(&self) -> &str {
"minimal"
}
async fn router_call(
&self,
_method: &str,
_params: Value,
_auth: Option<&super::super::auth::AuthContext>,
_raw_ctx: Option<&crate::request::RawRequestContext>,
) -> Result<PlexusStream, PlexusError> {
Err(PlexusError::MethodNotFound {
activation: "minimal".into(),
method: "none".into(),
})
}
async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
None
}
}
#[tokio::test]
async fn child_router_defaults_report_no_capabilities_and_none_streams() {
let router = MinimalRouter;
assert_eq!(
router.capabilities(),
ChildCapabilities::empty(),
"default capabilities should be empty"
);
assert!(
router.list_children().await.is_none(),
"default list_children should be None"
);
assert!(
router.search_children("anything").await.is_none(),
"default search_children should be None"
);
}
struct ListingRouter {
names: Vec<String>,
}
#[async_trait]
impl ChildRouter for ListingRouter {
fn router_namespace(&self) -> &str {
"listing"
}
async fn router_call(
&self,
_method: &str,
_params: Value,
_auth: Option<&super::super::auth::AuthContext>,
_raw_ctx: Option<&crate::request::RawRequestContext>,
) -> Result<PlexusStream, PlexusError> {
Err(PlexusError::MethodNotFound {
activation: "listing".into(),
method: "none".into(),
})
}
async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
if self.names.iter().any(|n| n == name) {
Some(Box::new(ListingRouter { names: vec![] }))
} else {
None
}
}
fn capabilities(&self) -> ChildCapabilities {
ChildCapabilities::LIST | ChildCapabilities::SEARCH
}
async fn list_children(&self) -> Option<BoxStream<'_, String>> {
let stream = futures::stream::iter(self.names.iter().cloned());
Some(Box::pin(stream))
}
async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
let q = query.to_string();
let stream = futures::stream::iter(
self.names
.iter()
.filter(move |n| n.contains(&q))
.cloned()
.collect::<Vec<_>>(),
);
Some(Box::pin(stream))
}
}
#[tokio::test]
async fn child_router_overrides_report_capabilities_and_yield_streams() {
use futures::StreamExt;
let router = ListingRouter {
names: vec!["alpha".into(), "beta".into(), "alphabet".into()],
};
let caps = router.capabilities();
assert!(caps.contains(ChildCapabilities::LIST));
assert!(caps.contains(ChildCapabilities::SEARCH));
assert_eq!(caps, ChildCapabilities::LIST | ChildCapabilities::SEARCH);
let list_stream = router
.list_children()
.await
.expect("LIST capability set — expected Some(stream)");
let listed: Vec<String> = list_stream.collect().await;
assert_eq!(listed, vec!["alpha".to_string(), "beta".into(), "alphabet".into()]);
let search_stream = router
.search_children("alpha")
.await
.expect("SEARCH capability set — expected Some(stream)");
let matched: Vec<String> = search_stream.collect().await;
assert_eq!(matched, vec!["alpha".to_string(), "alphabet".into()]);
}
struct WireFixture {
names: Vec<String>,
caps: ChildCapabilities,
}
#[async_trait]
impl ChildRouter for WireFixture {
fn router_namespace(&self) -> &str {
"wirefixture"
}
async fn router_call(
&self,
_method: &str,
_params: Value,
_auth: Option<&super::super::auth::AuthContext>,
_raw_ctx: Option<&crate::request::RawRequestContext>,
) -> Result<PlexusStream, PlexusError> {
Err(PlexusError::MethodNotFound {
activation: "wirefixture".into(),
method: "none".into(),
})
}
async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
None
}
fn capabilities(&self) -> ChildCapabilities {
self.caps
}
async fn list_children(&self) -> Option<futures_core::stream::BoxStream<'_, String>> {
if !self.caps.contains(ChildCapabilities::LIST) {
return None;
}
Some(Box::pin(futures::stream::iter(self.names.clone())))
}
async fn search_children(
&self,
query: &str,
) -> Option<futures_core::stream::BoxStream<'_, String>> {
if !self.caps.contains(ChildCapabilities::SEARCH) {
return None;
}
let q = query.to_lowercase();
let filtered: Vec<String> = self
.names
.iter()
.filter(|n| n.to_lowercase().contains(&q))
.cloned()
.collect();
Some(Box::pin(futures::stream::iter(filtered)))
}
}
fn build_module_for(router: WireFixture, ns: &str) -> RpcModule<()> {
let mut module = RpcModule::new(());
let arc: Arc<dyn ChildRouter> = Arc::new(router);
register_child_capability_methods(&mut module, ns, arc, None).expect("register");
module
}
#[tokio::test]
async fn child_wire_registers_both_methods_when_both_bits_set() {
let module = build_module_for(
WireFixture {
names: vec!["alpha".into(), "beta".into()],
caps: ChildCapabilities::LIST | ChildCapabilities::SEARCH,
},
"fixture",
);
let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
assert!(
names.contains(&"fixture.list_children".to_string()),
"expected fixture.list_children, got: {:?}",
names
);
assert!(
names.contains(&"fixture.search_children".to_string()),
"expected fixture.search_children, got: {:?}",
names
);
}
#[tokio::test]
async fn child_wire_registers_nothing_when_no_bits_set() {
let module = build_module_for(
WireFixture {
names: vec!["alpha".into()],
caps: ChildCapabilities::empty(),
},
"fixture",
);
let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
assert!(
!names.contains(&"fixture.list_children".to_string()),
"fixture.list_children should NOT be registered when cap absent"
);
assert!(
!names.contains(&"fixture.search_children".to_string()),
"fixture.search_children should NOT be registered when cap absent"
);
}
#[tokio::test]
async fn child_wire_registers_only_list_when_only_list_bit() {
let module = build_module_for(
WireFixture {
names: vec!["alpha".into()],
caps: ChildCapabilities::LIST,
},
"fixture",
);
let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
assert!(names.contains(&"fixture.list_children".to_string()));
assert!(!names.contains(&"fixture.search_children".to_string()));
}
}