1use super::{
9 context::PlexusContext,
10 method_enum::MethodEnumSchema,
11 schema::{ChildSummary, MethodSchema, PluginSchema, Schema},
12 streaming::PlexusStream,
13};
14use crate::types::Handle;
15use async_stream::stream;
16use async_trait::async_trait;
17use bitflags::bitflags;
18use futures::Stream;
19use futures_core::stream::BoxStream;
20use jsonrpsee::core::server::Methods;
21use jsonrpsee::RpcModule;
22
23pub const PLEXUS_NOTIF_METHOD: &str = "result";
29use schemars::JsonSchema;
30use serde::{Deserialize, Serialize};
31use serde_json::Value;
32use std::collections::HashMap;
33use std::sync::Arc;
34
35#[derive(Debug, Clone)]
40pub enum PlexusError {
41 ActivationNotFound(String),
42 MethodNotFound { activation: String, method: String },
43 InvalidParams(String),
44 ExecutionError(String),
45 HandleNotSupported(String),
46 TransportError(TransportErrorKind),
47 Unauthenticated(String),
48 Forbidden { reason: AuthzDenyReason },
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
65pub enum AuthzDenyReason {
66 MissingScope { scope: plexus_auth_core::Scope },
70 TenantBoundary,
74 NotAccepted,
77 MissingGrant {
84 grant: plexus_auth_core::grants::Grant,
86 scope: plexus_auth_core::grants::ScopeRef,
89 roles: Vec<plexus_auth_core::RoleName>,
91 held_on: Vec<plexus_auth_core::grants::ScopeRef>,
93 },
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
97#[serde(tag = "error_kind", rename_all = "snake_case")]
98pub enum TransportErrorKind {
99 ConnectionRefused { host: String, port: u16 },
100 ConnectionTimeout { host: String, port: u16 },
101 ProtocolError { message: String },
102 NetworkError { message: String },
103}
104
105impl std::fmt::Display for TransportErrorKind {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 match self {
108 TransportErrorKind::ConnectionRefused { host, port } => {
109 write!(f, "Connection refused to {}:{}", host, port)
110 }
111 TransportErrorKind::ConnectionTimeout { host, port } => {
112 write!(f, "Connection timeout to {}:{}", host, port)
113 }
114 TransportErrorKind::ProtocolError { message } => {
115 write!(f, "Protocol error: {}", message)
116 }
117 TransportErrorKind::NetworkError { message } => {
118 write!(f, "Network error: {}", message)
119 }
120 }
121 }
122}
123
124impl std::fmt::Display for PlexusError {
125 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126 match self {
127 PlexusError::ActivationNotFound(name) => write!(f, "Activation not found: {}", name),
128 PlexusError::MethodNotFound { activation, method } => {
129 write!(f, "Method not found: {}.{}", activation, method)
130 }
131 PlexusError::InvalidParams(msg) => write!(f, "Invalid params: {}", msg),
132 PlexusError::ExecutionError(msg) => write!(f, "Execution error: {}", msg),
133 PlexusError::HandleNotSupported(activation) => {
134 write!(f, "Handle resolution not supported by activation: {}", activation)
135 }
136 PlexusError::TransportError(kind) => match kind {
137 TransportErrorKind::ConnectionRefused { host, port } => {
138 write!(f, "Connection refused to {}:{}", host, port)
139 }
140 TransportErrorKind::ConnectionTimeout { host, port } => {
141 write!(f, "Connection timeout to {}:{}", host, port)
142 }
143 TransportErrorKind::ProtocolError { message } => {
144 write!(f, "Protocol error: {}", message)
145 }
146 TransportErrorKind::NetworkError { message } => {
147 write!(f, "Network error: {}", message)
148 }
149 }
150 PlexusError::Unauthenticated(msg) => write!(f, "Authentication required: {}", msg),
151 PlexusError::Forbidden { reason } => match reason {
152 AuthzDenyReason::MissingScope { scope } => {
156 write!(f, "Forbidden: missing required scope '{}'", scope)
157 }
158 AuthzDenyReason::TenantBoundary => write!(f, "Forbidden: tenant boundary"),
159 AuthzDenyReason::NotAccepted => write!(f, "Forbidden: call not accepted"),
160 AuthzDenyReason::MissingGrant { grant, scope, .. } if scope.is_everywhere() => {
162 write!(f, "needs {}", grant)
163 }
164 AuthzDenyReason::MissingGrant { grant, scope, .. } => {
165 write!(f, "needs {} on {}", grant, scope)
166 }
167 },
168 }
169 }
170}
171
172impl std::error::Error for PlexusError {}
173
174fn plexus_error_code(e: &PlexusError) -> i32 {
184 match e {
185 PlexusError::Unauthenticated(_) => -32001,
186 PlexusError::Forbidden { .. } => -32003,
187 PlexusError::InvalidParams(_) => -32602,
188 PlexusError::MethodNotFound { .. } | PlexusError::ActivationNotFound(_) => -32601,
189 _ => -32000,
190 }
191}
192
193fn plexus_error_to_jsonrpc(e: &PlexusError) -> jsonrpsee::types::ErrorObjectOwned {
195 jsonrpsee::types::ErrorObject::owned(plexus_error_code(e), e.to_string(), None::<()>)
196}
197
198pub(crate) fn error_item_raw(ns: &str, e: &PlexusError) -> Option<Box<serde_json::value::RawValue>> {
205 serde_json::value::to_raw_value(&error_item(ns, e)).ok()
206}
207
208pub fn error_item(ns: &str, e: &PlexusError) -> serde_json::Value {
214 let item = super::types::PlexusStreamItem::Error {
215 metadata: super::types::StreamMetadata::new(vec![ns.into()], super::context::PlexusContext::hash()),
216 message: e.to_string(),
217 code: Some(plexus_error_code(e).to_string()),
218 recoverable: false,
219 };
220 let mut value = serde_json::to_value(&item).unwrap_or(serde_json::Value::Null);
221 if let (Some(obj), Some(extra)) = (value.as_object_mut(), super::grant_gate::error_fields(e)) {
222 obj.extend(extra);
223 }
224 value
225}
226
227#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
232pub struct ActivationInfo {
233 pub namespace: String,
234 pub version: String,
235 pub description: String,
236 pub methods: Vec<String>,
237}
238
239#[async_trait]
244pub trait Activation: Send + Sync + 'static {
245 type Methods: MethodEnumSchema;
246
247 fn namespace(&self) -> &str;
248 fn version(&self) -> &str;
249 fn description(&self) -> &str { "No description available" }
251 fn long_description(&self) -> Option<&str> { None }
253 fn methods(&self) -> Vec<&str>;
254 fn method_help(&self, _method: &str) -> Option<String> { None }
255 fn plugin_id(&self) -> uuid::Uuid {
259 let major_version = self.version().split('.').next().unwrap_or("0");
260 uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, format!("{}@{}", self.namespace(), major_version).as_bytes())
261 }
262
263 async fn call(
264 &self,
265 method: &str,
266 params: Value,
267 auth: Option<&super::auth::AuthContext>,
268 raw_ctx: Option<&crate::request::RawRequestContext>,
269 ) -> Result<PlexusStream, PlexusError>;
270 async fn resolve_handle(&self, _handle: &Handle) -> Result<PlexusStream, PlexusError> {
271 Err(PlexusError::HandleNotSupported(self.namespace().to_string()))
272 }
273
274 fn into_rpc_methods(self) -> Methods where Self: Sized;
275
276 fn plugin_schema(&self) -> PluginSchema {
278 use std::collections::hash_map::DefaultHasher;
279 use std::hash::{Hash, Hasher};
280
281 let methods: Vec<MethodSchema> = self.methods().iter().map(|name| {
282 let desc = self.method_help(name).unwrap_or_default();
283 let mut hasher = DefaultHasher::new();
285 name.hash(&mut hasher);
286 desc.hash(&mut hasher);
287 let hash = format!("{:016x}", hasher.finish());
288 MethodSchema::new(name.to_string(), desc, hash)
289 }).collect();
290
291 if let Some(long_desc) = self.long_description() {
292 PluginSchema::leaf_with_long_description(
293 self.namespace(),
294 self.version(),
295 self.description(),
296 long_desc,
297 methods,
298 )
299 } else {
300 PluginSchema::leaf(
301 self.namespace(),
302 self.version(),
303 self.description(),
304 methods,
305 )
306 }
307 }
308}
309
310bitflags! {
315 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
344 #[deprecated(
345 since = "0.5",
346 note = "Use MethodRole::DynamicChild { list_method, search_method } instead. Removed in 0.7."
347 )]
348 pub struct ChildCapabilities: u32 {
349 const LIST = 0b0000_0001;
351 const SEARCH = 0b0000_0010;
354 }
355}
356
357#[async_trait]
374pub trait ChildRouter: Send + Sync {
375 fn router_namespace(&self) -> &str;
377
378 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
380
381 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>>;
383
384 #[allow(deprecated)]
389 fn capabilities(&self) -> ChildCapabilities {
390 ChildCapabilities::empty()
391 }
392
393 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
401 None
402 }
403
404 async fn search_children(&self, _query: &str) -> Option<BoxStream<'_, String>> {
412 None
413 }
414
415 fn forward_policy_for(
430 &self,
431 _callee_ns: &str,
432 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
433 None
434 }
435
436 fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
445 plexus_auth_core::Principal::Anonymous
446 }
447}
448
449pub async fn route_to_child<T: ChildRouter + ?Sized>(
480 parent: &T,
481 method: &str,
482 params: Value,
483 auth: Option<&super::auth::AuthContext>,
484 raw_ctx: Option<&crate::request::RawRequestContext>,
485) -> Result<PlexusStream, PlexusError> {
486 if let Some((child_name, rest)) = method.split_once('.') {
488 if let Some(child) = parent.get_child(child_name).await {
489 let policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy> = parent
499 .forward_policy_for(child_name)
500 .unwrap_or_else(|| {
501 std::sync::Arc::new(plexus_auth_core::IdentityOnly)
502 as std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>
503 });
504
505 let callee_method_str = format!("{}.{}", child_name, rest);
511 let callee_method = plexus_auth_core::MethodPath::try_new(callee_method_str.as_str())
512 .map_err(|e| PlexusError::ExecutionError(format!(
513 "framework-built MethodPath rejected: {} ({:?})",
514 callee_method_str, e
515 )))?;
516 let site = plexus_auth_core::CallSite::new(
517 parent.framework_stamped_principal(),
518 callee_method,
519 );
520
521 let anonymous_owned;
525 let caller_ctx: &super::auth::AuthContext = match auth {
526 Some(ctx) => ctx,
527 None => {
528 anonymous_owned = super::auth::AuthContext::anonymous();
529 &anonymous_owned
530 }
531 };
532 let derivation = policy.forward(caller_ctx, &site);
533
534 tracing::trace!(
555 target: "plexus::audit",
556 policy = policy.name().as_str(),
557 callee_method = %site.callee_method.as_str(),
558 derivation_keep_verified_user = derivation.keep_verified_user,
559 derivation_keep_roles = derivation.keep_roles,
560 derivation_keep_capabilities = derivation.keep_capabilities,
561 derivation_keep_metadata = derivation.keep_metadata,
562 "forward_policy_applied (audit-record emission stubbed pending PRIVACY-1)"
563 );
564
565 return match auth {
572 Some(caller_ctx) => {
573 caller_ctx
574 .with_callee_context(&derivation, &site.caller, |callee_ctx| async move {
575 child
576 .router_call(rest, params, Some(&callee_ctx), raw_ctx)
577 .await
578 })
579 .await
580 }
581 None => child.router_call(rest, params, None, raw_ctx).await,
582 };
583 }
584 return Err(PlexusError::ActivationNotFound(child_name.to_string()));
585 }
586
587 Err(PlexusError::MethodNotFound {
589 activation: parent.router_namespace().to_string(),
590 method: method.to_string(),
591 })
592}
593
594struct ArcChildRouter(Arc<dyn ChildRouter>);
598
599#[async_trait]
600impl ChildRouter for ArcChildRouter {
601 fn router_namespace(&self) -> &str {
602 self.0.router_namespace()
603 }
604
605 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
606 self.0.router_call(method, params, auth, raw_ctx).await
607 }
608
609 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
610 self.0.get_child(name).await
611 }
612
613 #[allow(deprecated)]
614 fn capabilities(&self) -> ChildCapabilities {
615 self.0.capabilities()
616 }
617
618 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
619 self.0.list_children().await
620 }
621
622 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
623 self.0.search_children(query).await
624 }
625
626 fn forward_policy_for(
630 &self,
631 callee_ns: &str,
632 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
633 self.0.forward_policy_for(callee_ns)
634 }
635
636 fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
637 self.0.framework_stamped_principal()
638 }
639}
640
641#[async_trait]
646#[allow(dead_code)] trait ActivationObject: Send + Sync + 'static {
648 fn namespace(&self) -> &str;
649 fn version(&self) -> &str;
650 fn description(&self) -> &str;
651 fn long_description(&self) -> Option<&str>;
652 fn methods(&self) -> Vec<&str>;
653 fn method_help(&self, method: &str) -> Option<String>;
654 fn plugin_id(&self) -> uuid::Uuid;
655 async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
656 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError>;
657 fn plugin_schema(&self) -> PluginSchema;
658 fn schema(&self) -> Schema;
659}
660
661struct ActivationWrapper<A: Activation> {
662 inner: A,
663}
664
665#[async_trait]
666impl<A: Activation> ActivationObject for ActivationWrapper<A> {
667 fn namespace(&self) -> &str { self.inner.namespace() }
668 fn version(&self) -> &str { self.inner.version() }
669 fn description(&self) -> &str { self.inner.description() }
670 fn long_description(&self) -> Option<&str> { self.inner.long_description() }
671 fn methods(&self) -> Vec<&str> { self.inner.methods() }
672 fn method_help(&self, method: &str) -> Option<String> { self.inner.method_help(method) }
673 fn plugin_id(&self) -> uuid::Uuid { self.inner.plugin_id() }
674
675 async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
676 self.inner.call(method, params, auth, raw_ctx).await
677 }
678
679 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
680 self.inner.resolve_handle(handle).await
681 }
682
683 fn plugin_schema(&self) -> PluginSchema { self.inner.plugin_schema() }
684
685 fn schema(&self) -> Schema {
686 let schema = schemars::schema_for!(A::Methods);
687 serde_json::from_value(serde_json::to_value(schema).expect("serialize"))
688 .expect("parse schema")
689 }
690}
691
692#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
697#[serde(tag = "event", rename_all = "snake_case")]
698pub enum HashEvent {
699 Hash { value: String },
700}
701
702#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
704#[serde(tag = "event", rename_all = "snake_case")]
705pub enum SchemaEvent {
706 Schema(PluginSchema),
708}
709
710#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
712pub struct PluginHashes {
713 pub namespace: String,
714 pub self_hash: String,
715 #[serde(skip_serializing_if = "Option::is_none")]
716 pub children_hash: Option<String>,
717 pub hash: String,
718 #[serde(skip_serializing_if = "Option::is_none")]
720 pub children: Option<Vec<ChildHashes>>,
721}
722
723#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
725pub struct ChildHashes {
726 pub namespace: String,
727 pub hash: String,
728}
729
730
731#[derive(Debug, Clone)]
737pub struct PluginEntry {
738 pub id: uuid::Uuid,
740 pub path: String,
742 pub plugin_type: String,
744}
745
746#[derive(Default)]
751pub struct PluginRegistry {
752 by_id: HashMap<uuid::Uuid, PluginEntry>,
754 by_path: HashMap<String, uuid::Uuid>,
756}
757
758#[derive(Clone)]
762pub struct PluginRegistrySnapshot {
763 by_id: HashMap<uuid::Uuid, PluginEntry>,
764 by_path: HashMap<String, uuid::Uuid>,
765}
766
767impl PluginRegistrySnapshot {
768 pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
770 self.by_id.get(&id).map(|e| e.path.as_str())
771 }
772
773 pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
775 self.by_path.get(path).copied()
776 }
777
778 pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
780 self.by_id.get(&id)
781 }
782
783 pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
785 self.by_id.values()
786 }
787
788 pub fn len(&self) -> usize {
790 self.by_id.len()
791 }
792
793 pub fn is_empty(&self) -> bool {
795 self.by_id.is_empty()
796 }
797}
798
799impl PluginRegistry {
800 pub fn new() -> Self {
802 Self::default()
803 }
804
805 pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
807 self.by_id.get(&id).map(|e| e.path.as_str())
808 }
809
810 pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
812 self.by_path.get(path).copied()
813 }
814
815 pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
817 self.by_id.get(&id)
818 }
819
820 pub fn register(&mut self, id: uuid::Uuid, path: String, plugin_type: String) {
822 let entry = PluginEntry { id, path: path.clone(), plugin_type };
823 self.by_id.insert(id, entry);
824 self.by_path.insert(path, id);
825 }
826
827 pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
829 self.by_id.values()
830 }
831
832 pub fn len(&self) -> usize {
834 self.by_id.len()
835 }
836
837 pub fn is_empty(&self) -> bool {
839 self.by_id.is_empty()
840 }
841}
842
843fn build_info_payload(
856 namespace: &str,
857 caps: Option<&plexus_auth_core::BackendAuthCapabilities>,
858) -> serde_json::Value {
859 let advertised = match caps {
860 Some(c) => c.clone(),
861 None => plexus_auth_core::BackendAuthCapabilities::anonymous_default(),
862 };
863 serde_json::json!({
864 "backend": namespace,
865 "auth_capabilities": advertised,
866 })
867}
868
869fn fill_site_hints_in_schema_stream(
880 stream: PlexusStream,
881 site: plexus_auth_core::AttachmentSite,
882) -> PlexusStream {
883 use futures::StreamExt;
884 Box::pin(stream.map(move |item| match item {
885 super::types::PlexusStreamItem::Data {
886 metadata,
887 content_type,
888 content,
889 } if content_type.ends_with(".schema") || content_type.ends_with(".method_schema") => {
890 let content = match serde_json::from_value::<super::SchemaResult>(content.clone()) {
891 Ok(mut result) => {
892 result.fill_site_hints(&site);
893 serde_json::to_value(&result).unwrap_or(content)
894 }
895 Err(_) => content,
896 };
897 super::types::PlexusStreamItem::Data {
898 metadata,
899 content_type,
900 content,
901 }
902 }
903 other => other,
904 }))
905}
906
907struct DynamicHubInner {
908 namespace: String,
910 activations: HashMap<String, Arc<dyn ActivationObject>>,
911 child_routers: HashMap<String, Arc<dyn ChildRouter>>,
913 registry: std::sync::RwLock<PluginRegistry>,
915 pending_rpc: std::sync::Mutex<Vec<Box<dyn FnOnce() -> Methods + Send>>>,
916 auth_capabilities: Option<plexus_auth_core::BackendAuthCapabilities>,
927 forward_policies: super::forward_registry::ForwardPolicyRegistry,
936 scope_registry: Option<Arc<plexus_auth_core::ScopeRegistry>>,
942 default_deny: bool,
949 audit_sink: Arc<dyn plexus_auth_core::AuditSink>,
955 gate_index: std::sync::OnceLock<HashMap<String, super::scope_gate::MethodGateInfo>>,
963 gate: Option<Arc<plexus_auth_core::grants::Gate>>,
967 signed_in_grants: std::collections::BTreeSet<String>,
971 resource_metadata: Option<String>,
974 auth_catalog: Option<super::auth_activation::Catalog>,
978}
979
980#[derive(Clone)]
1002pub struct DynamicHub {
1003 inner: Arc<DynamicHubInner>,
1004}
1005
1006impl DynamicHub {
1011 pub fn new(namespace: impl Into<String>) -> Self {
1037 Self {
1038 inner: Arc::new(DynamicHubInner {
1039 namespace: namespace.into(),
1040 activations: HashMap::new(),
1041 child_routers: HashMap::new(),
1042 registry: std::sync::RwLock::new(PluginRegistry::new()),
1043 pending_rpc: std::sync::Mutex::new(Vec::new()),
1044 auth_capabilities: None,
1045 forward_policies: super::forward_registry::ForwardPolicyRegistry::new(),
1046 scope_registry: None,
1047 default_deny: false,
1048 audit_sink: Arc::new(plexus_auth_core::TracingAuditSink),
1049 gate_index: std::sync::OnceLock::new(),
1050 gate: None,
1051 signed_in_grants: std::collections::BTreeSet::new(),
1052 resource_metadata: None,
1053 auth_catalog: None,
1054 }),
1055 }
1056 }
1057
1058 pub fn with_scope_registry(mut self, registry: plexus_auth_core::ScopeRegistry) -> Self {
1078 let inner = Arc::get_mut(&mut self.inner)
1079 .expect("Cannot set scope_registry: DynamicHub has multiple references");
1080 inner.scope_registry = Some(Arc::new(registry));
1081 self
1082 }
1083
1084 pub fn with_default_deny(mut self, default_deny: bool) -> Self {
1103 let inner = Arc::get_mut(&mut self.inner)
1104 .expect("Cannot set default_deny: DynamicHub has multiple references");
1105 inner.default_deny = default_deny;
1106 self
1107 }
1108
1109 pub fn with_audit_sink(mut self, sink: Arc<dyn plexus_auth_core::AuditSink>) -> Self {
1120 let inner = Arc::get_mut(&mut self.inner)
1121 .expect("Cannot set audit_sink: DynamicHub has multiple references");
1122 inner.audit_sink = sink;
1123 self
1124 }
1125
1126 pub fn with_gate(mut self, gate: Arc<plexus_auth_core::grants::Gate>) -> Self {
1151 let inner = Arc::get_mut(&mut self.inner)
1152 .expect("Cannot set gate: DynamicHub has multiple references");
1153 inner.gate = Some(gate);
1154 self
1155 }
1156
1157 pub fn gate(&self) -> Option<&Arc<plexus_auth_core::grants::Gate>> {
1159 self.inner.gate.as_ref()
1160 }
1161
1162 pub fn with_resource_metadata(mut self, url: impl Into<String>) -> Self {
1167 let inner = Arc::get_mut(&mut self.inner)
1168 .expect("Cannot set resource_metadata: DynamicHub has multiple references");
1169 inner.resource_metadata = Some(url.into());
1170 self
1171 }
1172
1173 pub fn with_signed_in_grants<I, S>(mut self, grants: I) -> Self
1180 where
1181 I: IntoIterator<Item = S>,
1182 S: Into<String>,
1183 {
1184 let inner = Arc::get_mut(&mut self.inner)
1185 .expect("Cannot set signed_in grants: DynamicHub has multiple references");
1186 inner.signed_in_grants.extend(grants.into_iter().map(Into::into));
1187 self
1188 }
1189
1190 pub fn with_auth(mut self, setup: super::auth_activation::AuthSetup) -> Self {
1207 let catalog = super::auth_activation::Catalog::default();
1208 catalog.add(&Activation::plugin_schema(&self));
1209 for a in self.inner.activations.values() {
1210 catalog.add(&a.plugin_schema());
1211 }
1212 let (auth, gate) = super::auth_activation::Auth::mount(setup, catalog.clone());
1213 {
1214 let inner = Arc::get_mut(&mut self.inner)
1215 .expect("Cannot mount auth: DynamicHub has multiple references");
1216 inner.auth_catalog = Some(catalog);
1217 inner.gate = Some(Arc::new(gate));
1218 }
1219 self.register(auth)
1220 .with_signed_in_grants(super::auth_activation::SIGNED_IN_GRANTS.iter().copied())
1221 }
1222
1223 pub fn view(&self, caller: Option<&super::auth::AuthContext>) -> super::view::View {
1236 let hub = Activation::plugin_schema(self);
1237 let activations: Vec<PluginSchema> = self.inner.activations.values().map(|a| a.plugin_schema()).collect();
1238 match self.inner.gate.as_ref() {
1239 None => super::view::whole(hub, activations),
1240 Some(gate) => {
1241 let (caller, _) = super::grant_gate::standing(gate, caller);
1243 super::view::build(gate, &self.inner.signed_in_grants, caller, hub, activations)
1244 }
1245 }
1246 }
1247
1248 pub fn info(&self, caller: Option<&super::auth::AuthContext>) -> serde_json::Value {
1254 let mut payload = build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1255 if self.inner.gate.is_none() {
1256 return payload;
1257 }
1258 let view = self.view(caller);
1259 if let Some(obj) = payload.as_object_mut() {
1260 obj.insert("view".into(), view.kind.as_str().into());
1261 obj.insert("view_hash".into(), view.hash.clone().into());
1262 if view.kind == super::ViewKind::Anonymous {
1263 let mut auth = serde_json::Map::new();
1264 auth.insert("methods".into(), view.public_methods().into());
1265 if let Some(url) = self.inner.resource_metadata.as_ref() {
1266 auth.insert("resource_metadata".into(), url.clone().into());
1267 }
1268 obj.insert("auth".into(), serde_json::Value::Object(auth));
1269 }
1270 }
1271 payload
1272 }
1273
1274 async fn introspect_in_view(
1280 &self,
1281 method: &str,
1282 params: &Value,
1283 auth: Option<&super::auth::AuthContext>,
1284 raw_ctx: Option<&crate::request::RawRequestContext>,
1285 ) -> Option<Result<PlexusStream, PlexusError>> {
1286 let (ns, rest) = method.split_once('.')?;
1287 let hub_ns = self.inner.namespace.as_str();
1288 let view = self.view(auth);
1289 let not_found = || PlexusError::ActivationNotFound(ns.to_string());
1290 let content: serde_json::Value = match rest {
1291 "schema" => {
1292 let Some(schema) = view.schema_of(ns) else { return Some(Err(not_found())) };
1293 let mut result = match params.get("method").and_then(|v| v.as_str()) {
1294 Some(name) => match schema.methods.iter().find(|m| m.name == name) {
1295 Some(m) => super::SchemaResult::Method(m.clone()),
1296 None => {
1297 return Some(Err(PlexusError::MethodNotFound {
1298 activation: ns.to_string(),
1299 method: name.to_string(),
1300 }))
1301 }
1302 },
1303 None => super::SchemaResult::Plugin(schema.clone()),
1304 };
1305 if let Some(site) = self.derived_site_hint() {
1306 result.fill_site_hints(&site);
1307 }
1308 serde_json::to_value(&result).ok()?
1309 }
1310 "hash" if ns == hub_ns => serde_json::to_value(HashEvent::Hash { value: view.hash.clone() }).ok()?,
1311 "hashes" if ns == hub_ns => serde_json::to_value(view.hashes()).ok()?,
1312 r if r.ends_with(".schema") => {
1313 let Some(schema) = view.schema_of(ns) else { return Some(Err(not_found())) };
1314 let name = r.trim_end_matches(".schema");
1315 match schema.methods.iter().find(|m| m.name == name) {
1316 Some(m) if matches!(m.role, super::MethodRole::Rpc) => {
1317 serde_json::to_value(super::SchemaResult::Method(m.clone())).ok()?
1318 }
1319 Some(_) => return None,
1321 None if name.contains('.') => return None,
1322 None => {
1323 return Some(Err(PlexusError::MethodNotFound {
1324 activation: ns.to_string(),
1325 method: name.to_string(),
1326 }))
1327 }
1328 }
1329 }
1330 _ => return None,
1331 };
1332 let stream = match self.route_ungated(method, params.clone(), auth, raw_ctx).await {
1335 Ok(s) => s,
1336 Err(e) => return Some(Err(e)),
1337 };
1338 use futures::StreamExt;
1339 Some(Ok(Box::pin(stream.map(move |item| match item {
1340 super::types::PlexusStreamItem::Data { metadata, content_type, .. } => {
1341 super::types::PlexusStreamItem::Data { metadata, content_type, content: content.clone() }
1342 }
1343 other => other,
1344 }))))
1345 }
1346
1347 pub fn declared_roles(&self) -> std::collections::BTreeMap<String, Vec<String>> {
1355 let mut out: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
1356 for activation in self.inner.activations.values() {
1357 for (role, grants) in activation.plugin_schema().roles {
1358 let entry = out.entry(role).or_default();
1359 for g in grants {
1360 if !entry.contains(&g) {
1361 entry.push(g);
1362 }
1363 }
1364 }
1365 }
1366 out
1367 }
1368
1369 pub fn scope_registry(&self) -> Option<&plexus_auth_core::ScopeRegistry> {
1374 self.inner.scope_registry.as_deref()
1375 }
1376
1377 fn gate_index(&self) -> &HashMap<String, super::scope_gate::MethodGateInfo> {
1380 self.inner.gate_index.get_or_init(|| {
1381 let mut index = HashMap::new();
1382 for m in &Activation::plugin_schema(self).methods {
1384 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
1385 info.grant = Some(format!("{}.{}", self.inner.namespace, m.name));
1388 index.insert(format!("{}.{}", self.inner.namespace, m.name), info);
1389 }
1390 for activation in self.inner.activations.values() {
1396 let schema = activation.plugin_schema();
1397 for m in &schema.methods {
1398 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
1399 info.grant = Some(m.grant_or(&schema.namespace));
1400 index.insert(format!("{}.{}", schema.namespace, m.name), info);
1401 }
1402 }
1403 index
1404 })
1405 }
1406
1407 pub fn with_forward_policy(
1428 mut self,
1429 callee_ns: impl Into<String>,
1430 policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>,
1431 ) -> Self {
1432 let inner = Arc::get_mut(&mut self.inner)
1433 .expect("Cannot register forward policy: DynamicHub has multiple references");
1434 inner.forward_policies.register(callee_ns, policy);
1435 self
1436 }
1437
1438 pub fn forward_policies(&self) -> &super::forward_registry::ForwardPolicyRegistry {
1443 &self.inner.forward_policies
1444 }
1445
1446 pub fn with_auth_capabilities(
1482 mut self,
1483 caps: plexus_auth_core::BackendAuthCapabilities,
1484 ) -> Self {
1485 let inner = Arc::get_mut(&mut self.inner)
1486 .expect("Cannot set auth_capabilities: DynamicHub has multiple references");
1487 inner.auth_capabilities = Some(caps);
1488 self
1489 }
1490
1491 pub fn auth_capabilities(&self) -> Option<&plexus_auth_core::BackendAuthCapabilities> {
1498 self.inner.auth_capabilities.as_ref()
1499 }
1500
1501 #[deprecated(since = "0.3.0", note = "Use DynamicHub::new(namespace) instead")]
1503 pub fn with_namespace(namespace: impl Into<String>) -> Self {
1504 Self::new(namespace)
1505 }
1506
1507 pub fn runtime_namespace(&self) -> &str {
1509 &self.inner.namespace
1510 }
1511
1512 pub fn registry(&self) -> std::sync::RwLockReadGuard<'_, PluginRegistry> {
1514 self.inner.registry.read().unwrap()
1515 }
1516
1517 fn assert_no_root_shadow(&self, child_namespace: &str) {
1528 if child_namespace == self.inner.namespace {
1529 panic!(
1530 "DynamicHub namespace shadow: activation namespace '{child}' collides with the hub root namespace '{root}'. \
1531 The hub root name is a routing namespace, not a label — routing resolves the root first, so a like-named \
1532 child activation is unreachable (every '{child}.<method>' call resolves to the hub root and fails with \
1533 'Command not found', and navigation resolves the child back to the root schema). \
1534 Fix: rename the hub root so it differs from every registered activation's namespace, \
1535 e.g. DynamicHub::new(\"{root}_hub\").register(...). [Z2H-8 / HOSTLESS-3]",
1536 child = child_namespace,
1537 root = self.inner.namespace,
1538 );
1539 }
1540 }
1541
1542 pub fn register<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
1551 let namespace = activation.namespace().to_string();
1552 self.assert_no_root_shadow(&namespace);
1553 let plugin_id = activation.plugin_id();
1554 let activation_for_rpc = activation.clone();
1555 let activation_for_router = activation.clone();
1556
1557 let inner = Arc::get_mut(&mut self.inner)
1558 .expect("Cannot register: DynamicHub has multiple references");
1559
1560 inner.registry.write().unwrap().register(
1562 plugin_id,
1563 namespace.clone(),
1564 namespace.clone(), );
1566
1567 if let Some(catalog) = inner.auth_catalog.as_ref() {
1570 catalog.add(&activation.plugin_schema());
1571 }
1572 inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
1573 inner.child_routers.insert(namespace.clone(), Arc::new(activation_for_router));
1574 inner.pending_rpc.lock().unwrap()
1575 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
1576 self
1577 }
1578
1579 #[deprecated(since = "0.5.0", note = "Use register() — it now handles both leaf and hub activations")]
1589 pub fn register_hub<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
1590 let namespace = activation.namespace().to_string();
1591 self.assert_no_root_shadow(&namespace);
1592 let plugin_id = activation.plugin_id();
1593 let activation_for_rpc = activation.clone();
1594 let activation_for_router = activation.clone();
1595
1596 let inner = Arc::get_mut(&mut self.inner)
1597 .expect("Cannot register: DynamicHub has multiple references");
1598
1599 inner.registry.write().unwrap().register(
1601 plugin_id,
1602 namespace.clone(),
1603 namespace.clone(), );
1605
1606 if let Some(catalog) = inner.auth_catalog.as_ref() {
1607 catalog.add(&activation.plugin_schema());
1608 }
1609 inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
1610 inner.child_routers.insert(namespace, Arc::new(activation_for_router));
1611 inner.pending_rpc.lock().unwrap()
1612 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
1613 self
1614 }
1615
1616 pub fn list_methods(&self) -> Vec<String> {
1618 let mut methods = Vec::new();
1619
1620 for m in Activation::methods(self) {
1622 methods.push(format!("{}.{}", self.inner.namespace, m));
1623 }
1624
1625 for (ns, act) in &self.inner.activations {
1627 for m in act.methods() {
1628 methods.push(format!("{}.{}", ns, m));
1629 }
1630 }
1631 methods.sort();
1632 methods
1633 }
1634
1635 pub fn list_activations_info(&self) -> Vec<ActivationInfo> {
1637 let mut activations = Vec::new();
1638
1639 activations.push(ActivationInfo {
1641 namespace: Activation::namespace(self).to_string(),
1642 version: Activation::version(self).to_string(),
1643 description: Activation::description(self).to_string(),
1644 methods: Activation::methods(self).iter().map(|s| s.to_string()).collect(),
1645 });
1646
1647 for a in self.inner.activations.values() {
1649 activations.push(ActivationInfo {
1650 namespace: a.namespace().to_string(),
1651 version: a.version().to_string(),
1652 description: a.description().to_string(),
1653 methods: a.methods().iter().map(|s| s.to_string()).collect(),
1654 });
1655 }
1656
1657 activations
1658 }
1659
1660 pub fn compute_hash(&self) -> String {
1665 Activation::plugin_schema(self).hash
1666 }
1667
1668 pub async fn route(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>) -> Result<PlexusStream, PlexusError> {
1670 self.route_with_ctx(method, params, auth, None).await
1671 }
1672
1673 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> {
1675 if let Some(gate) = self.inner.gate.as_ref() {
1678 let (auth, ended) = super::grant_gate::standing(gate, auth);
1680 let admit = super::grant_gate::decide(
1681 gate,
1682 &self.inner.namespace,
1683 method,
1684 self.gate_index().get(method),
1685 ¶ms,
1686 auth,
1687 &self.inner.signed_in_grants,
1688 )
1689 .map_err(|e| super::grant_gate::say_ended(e, ended.as_deref()))?;
1690 return match admit {
1691 super::grant_gate::Admit::Open => match self.introspect_in_view(method, ¶ms, auth, raw_ctx).await {
1693 Some(answer) => answer,
1694 None => self.route_ungated(method, params, auth, raw_ctx).await,
1695 },
1696 super::grant_gate::Admit::Reach(reach) => {
1697 super::grant_gate::with_reach(reach, self.route_ungated(method, params, auth, raw_ctx)).await
1698 }
1699 };
1700 }
1701 self.route_ungated(method, params, auth, raw_ctx).await
1702 }
1703
1704 async fn route_ungated(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
1706 if self.inner.scope_registry.is_some() || self.inner.default_deny {
1711 let registry = self
1712 .inner
1713 .scope_registry
1714 .as_deref()
1715 .unwrap_or_else(|| super::scope_gate::empty_registry());
1716 super::scope_gate::enforce(
1717 registry,
1718 self.inner.default_deny,
1719 &self.inner.audit_sink,
1720 method,
1721 self.gate_index().get(method),
1722 auth,
1723 raw_ctx.and_then(|ctx| ctx.peer.map(|peer| peer.ip())),
1724 )
1725 .await?;
1726 }
1727
1728 let (namespace, method_name) = self.parse_method(method)?;
1729
1730 let stream = if namespace == self.inner.namespace {
1732 Activation::call(self, method_name, params, auth, raw_ctx).await?
1733 } else {
1734 let activation = self.inner.activations.get(namespace)
1735 .ok_or_else(|| PlexusError::ActivationNotFound(namespace.to_string()))?;
1736
1737 activation.call(method_name, params, auth, raw_ctx).await?
1738 };
1739
1740 if Self::is_schema_query(method_name) {
1747 if let Some(site) = self.derived_site_hint() {
1748 return Ok(fill_site_hints_in_schema_stream(stream, site));
1749 }
1750 }
1751 Ok(stream)
1752 }
1753
1754 fn is_schema_query(method_name: &str) -> bool {
1759 method_name == "schema" || method_name.ends_with(".schema")
1760 }
1761
1762 pub fn derived_site_hint(&self) -> Option<plexus_auth_core::AttachmentSite> {
1768 self.inner
1769 .auth_capabilities
1770 .as_ref()
1771 .and_then(|caps| caps.implied_attachment_site())
1772 }
1773
1774 pub async fn do_resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
1778 let path = self.inner.registry.read().unwrap()
1779 .lookup(handle.plugin_id)
1780 .map(|s| s.to_string())
1781 .ok_or_else(|| PlexusError::ActivationNotFound(handle.plugin_id.to_string()))?;
1782
1783 let activation = self.inner.activations.get(&path)
1784 .ok_or_else(|| PlexusError::ActivationNotFound(path.clone()))?;
1785 activation.resolve_handle(handle).await
1786 }
1787
1788 pub fn get_activation_schema(&self, namespace: &str) -> Option<Schema> {
1790 self.inner.activations.get(namespace).map(|a| a.schema())
1791 }
1792
1793 pub fn registry_snapshot(&self) -> PluginRegistrySnapshot {
1795 let guard = self.inner.registry.read().unwrap();
1796 PluginRegistrySnapshot {
1797 by_id: guard.by_id.clone(),
1798 by_path: guard.by_path.clone(),
1799 }
1800 }
1801
1802 pub fn lookup_plugin(&self, id: uuid::Uuid) -> Option<String> {
1804 self.inner.registry.read().unwrap().lookup(id).map(|s| s.to_string())
1805 }
1806
1807 pub fn lookup_plugin_by_path(&self, path: &str) -> Option<uuid::Uuid> {
1809 self.inner.registry.read().unwrap().lookup_by_path(path)
1810 }
1811
1812 pub fn list_plugin_schemas(&self) -> Vec<PluginSchema> {
1814 let mut schemas = Vec::new();
1815
1816 schemas.push(Activation::plugin_schema(self));
1818
1819 for a in self.inner.activations.values() {
1821 schemas.push(a.plugin_schema());
1822 }
1823
1824 schemas
1825 }
1826
1827 #[deprecated(note = "Use list_plugin_schemas instead")]
1829 pub fn list_full_schemas(&self) -> Vec<PluginSchema> {
1830 self.list_plugin_schemas()
1831 }
1832
1833 pub fn get_method_help(&self, method: &str) -> Option<String> {
1835 let (namespace, method_name) = self.parse_method(method).ok()?;
1836 let activation = self.inner.activations.get(namespace)?;
1837 activation.method_help(method_name)
1838 }
1839
1840 fn parse_method<'a>(&self, method: &'a str) -> Result<(&'a str, &'a str), PlexusError> {
1841 let parts: Vec<&str> = method.splitn(2, '.').collect();
1842 if parts.len() != 2 {
1843 return Err(PlexusError::InvalidParams(format!("Invalid method format: {}", method)));
1844 }
1845 Ok((parts[0], parts[1]))
1846 }
1847
1848 pub fn plugin_children(&self) -> Vec<ChildSummary> {
1851 self.inner.activations.values()
1852 .map(|a| {
1853 let schema = a.plugin_schema();
1854 ChildSummary {
1855 namespace: schema.namespace,
1856 description: schema.description,
1857 hash: schema.hash,
1858 }
1859 })
1860 .collect()
1861 }
1862
1863 pub fn into_rpc_module(self) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
1865 let mut module = RpcModule::new(());
1866
1867 PlexusContext::init(self.compute_hash());
1868
1869 let ns = self.runtime_namespace();
1872 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
1873 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
1874 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
1875 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
1876 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
1877 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
1878 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
1879 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
1880 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
1881
1882 let plexus_for_call = self.clone();
1884 module.register_subscription(
1885 call_method,
1886 PLEXUS_NOTIF_METHOD,
1887 call_unsub,
1888 move |params, pending, _ctx, ext| {
1889 let plexus = plexus_for_call.clone();
1890 Box::pin(async move {
1891 let p: CallParams = params.parse()?;
1892 let auth = if plexus.inner.gate.is_some() {
1896 ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())
1897 } else {
1898 None
1899 };
1900 match plexus.route(&p.method, p.params.unwrap_or_default(), auth).await {
1901 Ok(stream) => pipe_stream_to_subscription(pending, stream).await,
1902 Err(e) => {
1903 let sink = pending.accept().await?;
1904 if let Some(raw) = error_item_raw(ns_static, &e) {
1905 let _ = sink.send(raw).await;
1906 }
1907 Ok(())
1908 }
1909 }
1910 })
1911 }
1912 )?;
1913
1914 let plexus_for_hash = self.clone();
1916 module.register_subscription(
1917 hash_method,
1918 PLEXUS_NOTIF_METHOD,
1919 hash_unsub,
1920 move |_params, pending, _ctx, ext| {
1921 let plexus = plexus_for_hash.clone();
1922 Box::pin(async move {
1923 let value = if plexus.inner.gate.is_some() {
1925 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
1926 plexus.view(auth).hash
1927 } else {
1928 Activation::plugin_schema(&plexus).hash
1929 };
1930 let stream = async_stream::stream! {
1931 yield HashEvent::Hash { value };
1932 };
1933 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
1934 pipe_stream_to_subscription(pending, wrapped).await
1935 })
1936 }
1937 )?;
1938
1939 let plexus_for_schema = self.clone();
1941 module.register_subscription(
1942 schema_method,
1943 PLEXUS_NOTIF_METHOD,
1944 schema_unsub,
1945 move |params, pending, _ctx, ext| {
1946 let plexus = plexus_for_schema.clone();
1947 Box::pin(async move {
1948 let p: SchemaParams = params.parse().unwrap_or_default();
1949 let mut plugin_schema = if plexus.inner.gate.is_some() {
1951 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
1952 plexus.view(auth).schema
1953 } else {
1954 Activation::plugin_schema(&plexus)
1955 };
1956 if let Some(site) = plexus.derived_site_hint() {
1958 plugin_schema.fill_site_hints(&site);
1959 }
1960
1961 let result = if let Some(ref name) = p.method {
1962 plugin_schema.methods.iter()
1963 .find(|m| m.name == *name)
1964 .map(|m| super::SchemaResult::Method(m.clone()))
1965 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
1966 -32602,
1967 format!("Method '{}' not found", name),
1968 None::<()>,
1969 ))?
1970 } else {
1971 super::SchemaResult::Plugin(plugin_schema)
1972 };
1973
1974 let stream = async_stream::stream! { yield result; };
1975 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
1976 pipe_stream_to_subscription(pending, wrapped).await
1977 })
1978 }
1979 )?;
1980
1981 let info_payload = build_info_payload(
1987 self.runtime_namespace(),
1988 self.inner.auth_capabilities.as_ref(),
1989 );
1990 let plexus_for_info = self.inner.gate.is_some().then(|| self.clone());
1993 module.register_subscription(
1994 "_info",
1995 PLEXUS_NOTIF_METHOD,
1996 "_info_unsub",
1997 move |_params, pending, _ctx, ext| {
1998 let payload = match plexus_for_info.as_ref() {
1999 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
2000 None => info_payload.clone(),
2001 };
2002 Box::pin(async move {
2003 let info_stream = futures::stream::once(async move { payload });
2005
2006 let wrapped = super::streaming::wrap_stream(
2008 info_stream,
2009 "_info",
2010 vec![]
2011 );
2012
2013 pipe_stream_to_subscription(pending, wrapped).await
2015 })
2016 }
2017 )?;
2018
2019 let pending = std::mem::take(&mut *self.inner.pending_rpc.lock().unwrap());
2023 if self.inner.gate.is_none() {
2024 for factory in pending {
2025 module.merge(factory())?;
2026 }
2027 }
2028
2029 for (ns, router) in self.inner.child_routers.iter() {
2033 register_child_capability_methods(&mut module, ns, router.clone())?;
2034 }
2035
2036 Ok(module)
2037 }
2038
2039 pub fn arc_into_rpc_module(hub: Arc<Self>) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2045 let mut module = RpcModule::new(());
2046
2047 PlexusContext::init(hub.compute_hash());
2048
2049 let ns = hub.runtime_namespace();
2052 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2053 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2054 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2055 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2056 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2057 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2058 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2059 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2060 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2061
2062 let hub_for_call = hub.clone();
2064 module.register_subscription(
2065 call_method,
2066 call_method,
2067 call_unsub,
2068 move |params, pending, _ctx, ext| {
2069 let hub = hub_for_call.clone();
2070 Box::pin(async move {
2071 let p: CallParams = params.parse()?;
2072 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>()
2074 .map(|arc| arc.as_ref());
2075 match hub.route(&p.method, p.params.unwrap_or_default(), auth).await {
2076 Ok(stream) => pipe_stream_to_subscription(pending, stream).await,
2077 Err(e) => {
2078 let sink = pending.accept().await?;
2083 if let Some(raw) = error_item_raw(ns_static, &e) {
2084 let _ = sink.send(raw).await;
2085 }
2086 Ok(())
2087 }
2088 }
2089 })
2090 }
2091 )?;
2092
2093 let hub_for_hash = hub.clone();
2095 module.register_subscription(
2096 hash_method,
2097 PLEXUS_NOTIF_METHOD,
2098 hash_unsub,
2099 move |_params, pending, _ctx, ext| {
2100 let hub = hub_for_hash.clone();
2101 Box::pin(async move {
2102 let value = if hub.inner.gate.is_some() {
2104 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2105 hub.view(auth).hash
2106 } else {
2107 Activation::plugin_schema(&*hub).hash
2108 };
2109 let stream = async_stream::stream! {
2110 yield HashEvent::Hash { value };
2111 };
2112 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2113 pipe_stream_to_subscription(pending, wrapped).await
2114 })
2115 }
2116 )?;
2117
2118 let hub_for_schema = hub.clone();
2120 module.register_subscription(
2121 schema_method,
2122 PLEXUS_NOTIF_METHOD,
2123 schema_unsub,
2124 move |params, pending, _ctx, ext| {
2125 let hub = hub_for_schema.clone();
2126 Box::pin(async move {
2127 let p: SchemaParams = params.parse().unwrap_or_default();
2128 let mut plugin_schema = if hub.inner.gate.is_some() {
2130 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2131 hub.view(auth).schema
2132 } else {
2133 Activation::plugin_schema(&*hub)
2134 };
2135 if let Some(site) = hub.derived_site_hint() {
2137 plugin_schema.fill_site_hints(&site);
2138 }
2139
2140 let result = if let Some(ref name) = p.method {
2141 plugin_schema.methods.iter()
2142 .find(|m| m.name == *name)
2143 .map(|m| super::SchemaResult::Method(m.clone()))
2144 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
2145 -32602,
2146 format!("Method '{}' not found", name),
2147 None::<()>,
2148 ))?
2149 } else {
2150 super::SchemaResult::Plugin(plugin_schema)
2151 };
2152
2153 let stream = async_stream::stream! {
2154 yield result;
2155 };
2156 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
2157 pipe_stream_to_subscription(pending, wrapped).await
2158 })
2159 }
2160 )?;
2161
2162 let info_payload = build_info_payload(
2167 hub.runtime_namespace(),
2168 hub.inner.auth_capabilities.as_ref(),
2169 );
2170 let hub_for_info = hub.inner.gate.is_some().then(|| hub.clone());
2173 module.register_subscription(
2174 "_info",
2175 PLEXUS_NOTIF_METHOD,
2176 "_info_unsub",
2177 move |_params, pending, _ctx, ext| {
2178 let payload = match hub_for_info.as_ref() {
2179 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
2180 None => info_payload.clone(),
2181 };
2182 Box::pin(async move {
2183 let info_stream = futures::stream::once(async move { payload });
2185
2186 let wrapped = super::streaming::wrap_stream(
2188 info_stream,
2189 "_info",
2190 vec![]
2191 );
2192
2193 pipe_stream_to_subscription(pending, wrapped).await
2195 })
2196 }
2197 )?;
2198
2199 let respond_method: &'static str = Box::leak(format!("{}.respond", ns).into_boxed_str());
2202 module.register_async_method(respond_method, |params, _ctx, _ext| async move {
2203 use super::bidirectional::{handle_pending_response, BidirError};
2204
2205 let p: RespondParams = params.parse()?;
2206
2207 tracing::debug!(
2208 request_id = %p.request_id,
2209 "Handling {}.respond via WebSocket",
2210 "plexus"
2211 );
2212
2213 match handle_pending_response(&p.request_id, p.response_data) {
2214 Ok(()) => Ok(serde_json::json!({"success": true})),
2215 Err(BidirError::UnknownRequest) => {
2216 tracing::warn!(request_id = %p.request_id, "Unknown request ID in respond");
2217 Err(jsonrpsee::types::ErrorObject::owned(
2218 -32602,
2219 format!("Unknown request ID: {}. The request may have timed out or been cancelled.", p.request_id),
2220 None::<()>,
2221 ))
2222 }
2223 Err(BidirError::ChannelClosed) => {
2224 tracing::warn!(request_id = %p.request_id, "Channel closed in respond");
2225 Err(jsonrpsee::types::ErrorObject::owned(
2226 -32000,
2227 "Response channel was closed (request may have timed out)",
2228 None::<()>,
2229 ))
2230 }
2231 Err(e) => {
2232 tracing::error!(request_id = %p.request_id, error = ?e, "Error in respond");
2233 Err(jsonrpsee::types::ErrorObject::owned(
2234 -32000,
2235 format!("Failed to deliver response: {}", e),
2236 None::<()>,
2237 ))
2238 }
2239 }
2240 })?;
2241
2242 let mut pending = std::mem::take(&mut *hub.inner.pending_rpc.lock().unwrap());
2245 if hub.inner.gate.is_some() {
2246 pending.clear();
2247 }
2248 tracing::trace!(factories = pending.len(), "merging activation RPC factories");
2249 for (idx, factory) in pending.into_iter().enumerate() {
2250 tracing::trace!(factory_idx = idx, "calling factory to get Methods");
2251 let methods = factory();
2252 let method_count = methods.method_names().count();
2253 tracing::trace!(factory_idx = idx, methods = method_count, "factory returned Methods; merging into module");
2254 module.merge(methods)?;
2255 tracing::trace!(factory_idx = idx, "successfully merged factory methods");
2256 }
2257 tracing::trace!("all activations merged successfully");
2258
2259 for (ns, router) in hub.inner.child_routers.iter() {
2262 register_child_capability_methods(&mut module, ns, router.clone())?;
2263 }
2264
2265 Ok(module)
2266 }
2267}
2268
2269#[allow(deprecated)] fn register_child_capability_methods(
2284 module: &mut RpcModule<()>,
2285 namespace: &str,
2286 router: Arc<dyn ChildRouter>,
2287) -> Result<(), jsonrpsee::core::RegisterMethodError> {
2288 let caps = router.capabilities();
2289 if caps.is_empty() {
2290 return Ok(());
2291 }
2292
2293 let ns_static: &'static str = Box::leak(namespace.to_string().into_boxed_str());
2294
2295 if caps.contains(ChildCapabilities::LIST) {
2296 let list_method: &'static str =
2297 Box::leak(format!("{}.list_children", namespace).into_boxed_str());
2298 let list_unsub: &'static str =
2299 Box::leak(format!("{}.list_children_unsub", namespace).into_boxed_str());
2300 let router_for_list = router.clone();
2301 module.register_subscription(
2302 list_method,
2303 PLEXUS_NOTIF_METHOD,
2304 list_unsub,
2305 move |_params, pending, _ctx, _ext| {
2306 let router = router_for_list.clone();
2307 Box::pin(async move {
2308 let collected: Vec<String> = match router.list_children().await {
2315 Some(mut s) => {
2316 use futures::StreamExt;
2317 let mut acc = Vec::new();
2318 while let Some(name) = s.next().await {
2319 acc.push(name);
2320 }
2321 acc
2322 }
2323 None => Vec::new(),
2324 };
2325 let stream = async_stream::stream! {
2326 for name in collected {
2327 yield name;
2328 }
2329 };
2330 let wrapped = super::streaming::wrap_stream(
2331 stream,
2332 "list_children",
2333 vec![ns_static.into()],
2334 );
2335 pipe_stream_to_subscription(pending, wrapped).await
2336 })
2337 },
2338 )?;
2339 }
2340
2341 if caps.contains(ChildCapabilities::SEARCH) {
2342 let search_method: &'static str =
2343 Box::leak(format!("{}.search_children", namespace).into_boxed_str());
2344 let search_unsub: &'static str =
2345 Box::leak(format!("{}.search_children_unsub", namespace).into_boxed_str());
2346 let router_for_search = router.clone();
2347 module.register_subscription(
2348 search_method,
2349 PLEXUS_NOTIF_METHOD,
2350 search_unsub,
2351 move |params, pending, _ctx, _ext| {
2352 let router = router_for_search.clone();
2353 Box::pin(async move {
2354 let p: SearchChildrenParams = params.parse()?;
2355 let collected: Vec<String> = match router.search_children(&p.query).await {
2356 Some(mut s) => {
2357 use futures::StreamExt;
2358 let mut acc = Vec::new();
2359 while let Some(name) = s.next().await {
2360 acc.push(name);
2361 }
2362 acc
2363 }
2364 None => Vec::new(),
2365 };
2366 let stream = async_stream::stream! {
2367 for name in collected {
2368 yield name;
2369 }
2370 };
2371 let wrapped = super::streaming::wrap_stream(
2372 stream,
2373 "search_children",
2374 vec![ns_static.into()],
2375 );
2376 pipe_stream_to_subscription(pending, wrapped).await
2377 })
2378 },
2379 )?;
2380 }
2381
2382 Ok(())
2383}
2384
2385#[derive(Debug, serde::Deserialize)]
2387struct SearchChildrenParams {
2388 query: String,
2389}
2390
2391#[derive(Debug, serde::Deserialize)]
2393struct CallParams {
2394 method: String,
2395 #[serde(default)]
2396 params: Option<Value>,
2397}
2398
2399#[derive(Debug, Default, serde::Deserialize)]
2401struct SchemaParams {
2402 method: Option<String>,
2403}
2404
2405#[derive(Debug, serde::Deserialize)]
2407struct RespondParams {
2408 request_id: String,
2409 response_data: Value,
2410}
2411
2412async fn pipe_stream_to_subscription(
2417 pending: jsonrpsee::PendingSubscriptionSink,
2418 mut stream: PlexusStream,
2419) -> jsonrpsee::core::SubscriptionResult {
2420 use futures::StreamExt;
2421
2422 let sink = pending.accept().await?;
2423 while let Some(item) = stream.next().await {
2424 let json = serde_json::value::to_raw_value(&item)?;
2425 sink.send(json).await?;
2426 }
2427 Ok(())
2428}
2429
2430#[plexus_macros::activation(
2435 namespace = "plexus",
2436 version = "1.0.0",
2437 description = "Central routing and introspection",
2438 hub,
2439 namespace_fn = "runtime_namespace"
2440)]
2441#[allow(deprecated)]
2442impl DynamicHub {
2443 #[plexus_macros::method(
2445 streaming,
2446 description = "Route a call to a registered activation",
2447 params(
2448 method = "The method to call (format: namespace.method)",
2449 params = "Parameters to pass to the method (optional, defaults to {})"
2450 )
2451 )]
2452 async fn call(
2453 &self,
2454 method: String,
2455 params: Option<Value>,
2456 ) -> impl Stream<Item = super::types::PlexusStreamItem> + Send + 'static {
2457 use super::context::PlexusContext;
2458 use super::types::{PlexusStreamItem, StreamMetadata};
2459
2460 let result = self.route(&method, params.unwrap_or_default(), None).await;
2461
2462 match result {
2463 Ok(plexus_stream) => {
2464 plexus_stream
2466 }
2467 Err(e) => {
2468 let metadata = StreamMetadata::new(
2470 vec![self.inner.namespace.clone()],
2471 PlexusContext::hash(),
2472 );
2473 Box::pin(futures::stream::once(async move {
2474 PlexusStreamItem::Error {
2475 metadata,
2476 message: e.to_string(),
2477 code: None,
2478 recoverable: false,
2479 }
2480 }))
2481 }
2482 }
2483 }
2484
2485 #[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.")]
2490 async fn hash(&self) -> impl Stream<Item = HashEvent> + Send + 'static {
2491 let schema = Activation::plugin_schema(self);
2492 stream! { yield HashEvent::Hash { value: schema.hash }; }
2493 }
2494
2495 #[plexus_macros::method(description = "Get plugin hashes for cache validation")]
2497 #[allow(deprecated)]
2498 async fn hashes(&self) -> impl Stream<Item = PluginHashes> + Send + 'static {
2499 let schema = Activation::plugin_schema(self);
2500
2501 stream! {
2502 yield PluginHashes {
2503 namespace: schema.namespace.clone(),
2504 self_hash: schema.self_hash.clone(),
2505 children_hash: schema.children_hash.clone(),
2506 hash: schema.hash.clone(),
2507 children: schema.children.as_ref().map(|kids| {
2508 kids.iter()
2509 .map(|c| ChildHashes {
2510 namespace: c.namespace.clone(),
2511 hash: c.hash.clone(),
2512 })
2513 .collect()
2514 }),
2515 };
2516 }
2517 }
2518
2519 }
2521
2522use super::hub_context::HubContext;
2527use std::sync::Weak;
2528
2529#[async_trait]
2535impl HubContext for Weak<DynamicHub> {
2536 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
2537 let hub = self.upgrade().ok_or_else(|| {
2538 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
2539 })?;
2540 hub.do_resolve_handle(handle).await
2541 }
2542
2543 async fn call(&self, method: &str, params: serde_json::Value) -> Result<PlexusStream, PlexusError> {
2544 let hub = self.upgrade().ok_or_else(|| {
2545 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
2546 })?;
2547 hub.route(method, params, None).await
2548 }
2549
2550 fn is_valid(&self) -> bool {
2551 self.upgrade().is_some()
2552 }
2553}
2554
2555#[async_trait]
2560impl ChildRouter for DynamicHub {
2561 fn router_namespace(&self) -> &str {
2562 &self.inner.namespace
2563 }
2564
2565 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2566 self.route_with_ctx(method, params, auth, raw_ctx).await
2569 }
2570
2571 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
2572 self.inner.child_routers.get(name)
2574 .map(|router| {
2575 Box::new(ArcChildRouter(router.clone())) as Box<dyn ChildRouter>
2577 })
2578 }
2579
2580 fn forward_policy_for(
2583 &self,
2584 callee_ns: &str,
2585 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
2586 self.inner.forward_policies.get(callee_ns)
2587 }
2588
2589 }
2596
2597#[cfg(test)]
2598#[allow(deprecated)]
2599mod tests {
2600 use super::*;
2601
2602 #[test]
2603 fn dynamic_hub_implements_activation() {
2604 fn assert_activation<T: Activation>() {}
2605 assert_activation::<DynamicHub>();
2606 }
2607
2608 #[test]
2609 fn dynamic_hub_methods() {
2610 let hub = DynamicHub::new("test");
2611 let methods = hub.methods();
2612 assert!(methods.contains(&"call"));
2613 assert!(methods.contains(&"hash"));
2614 assert!(methods.contains(&"schema"));
2615 }
2617
2618 #[test]
2619 fn dynamic_hub_hash_stable() {
2620 let h1 = DynamicHub::new("test");
2621 let h2 = DynamicHub::new("test");
2622 assert_eq!(h1.compute_hash(), h2.compute_hash());
2623 }
2624
2625 #[test]
2626 fn dynamic_hub_is_hub() {
2627 use crate::activations::health::Health;
2628 let hub = DynamicHub::new("test").register(Health::new());
2629 let schema = hub.plugin_schema();
2630
2631 assert!(schema.is_hub(), "dynamic hub should be a hub");
2633 assert!(!schema.is_leaf(), "dynamic hub should not be a leaf");
2634
2635 let children = schema.children.expect("dynamic hub should have children");
2637 assert!(!children.is_empty(), "dynamic hub should have at least one child");
2638
2639 let health = children.iter().find(|c| c.namespace == "health").expect("should have health child");
2641 assert!(!health.hash.is_empty(), "health should have a hash");
2642 }
2643
2644 #[test]
2649 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
2650 fn dynamic_hub_rejects_root_namespace_shadow() {
2651 use crate::activations::health::Health;
2652 let _hub = DynamicHub::new("health").register(Health::new());
2653 }
2654
2655 #[test]
2658 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
2659 fn dynamic_hub_register_hub_rejects_root_namespace_shadow() {
2660 use crate::activations::health::Health;
2661 let _hub = DynamicHub::new("health").register_hub(Health::new());
2662 }
2663
2664 #[test]
2668 fn dynamic_hub_shadow_error_names_collision_and_fix() {
2669 use crate::activations::health::Health;
2670 let result = std::panic::catch_unwind(|| {
2671 let _hub = DynamicHub::new("health").register(Health::new());
2672 });
2673 let err = result.expect_err("shadow registration must panic");
2674 let msg = err
2675 .downcast_ref::<String>()
2676 .cloned()
2677 .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
2678 .expect("panic payload should be a string");
2679 assert!(msg.contains("'health'"), "must name the colliding namespace: {msg}");
2680 assert!(msg.contains("hub root namespace"), "must name the root side: {msg}");
2681 assert!(msg.contains("rename the hub root"), "must suggest the fix: {msg}");
2682 assert!(msg.contains("Z2H-8"), "must cite the ticket: {msg}");
2683 }
2684
2685 #[test]
2688 fn dynamic_hub_non_colliding_registration_unaffected() {
2689 use crate::activations::health::Health;
2690 let hub = DynamicHub::new("health_hub").register(Health::new());
2691 assert_eq!(hub.runtime_namespace(), "health_hub");
2692 let schema = hub.plugin_schema();
2693 let children = schema.children.expect("hub should have children");
2694 assert!(
2695 children.iter().any(|c| c.namespace == "health"),
2696 "health child must be registered"
2697 );
2698 assert!(hub.list_methods().iter().any(|m| m.starts_with("health.")));
2699 }
2700
2701 #[test]
2702 fn dynamic_hub_schema_structure() {
2703 use crate::activations::health::Health;
2704 let hub = DynamicHub::new("test").register(Health::new());
2705 let schema = hub.plugin_schema();
2706
2707 let json = serde_json::to_string_pretty(&schema).unwrap();
2709 println!("DynamicHub schema:\n{}", json);
2710
2711 assert_eq!(schema.namespace, "test");
2713 assert!(schema.methods.iter().any(|m| m.name == "call"));
2714 assert!(schema.children.is_some());
2715 }
2716
2717 #[tokio::test]
2722 async fn invariant_resolve_handle_unknown_activation() {
2723 use crate::activations::health::Health;
2724 use crate::types::Handle;
2725 use uuid::Uuid;
2726
2727 let hub = DynamicHub::new("test").register(Health::new());
2728
2729 let unknown_plugin_id = Uuid::new_v4();
2731 let handle = Handle::new(unknown_plugin_id, "1.0.0", "some_method");
2732
2733 let result = hub.do_resolve_handle(&handle).await;
2734
2735 match result {
2736 Err(PlexusError::ActivationNotFound(_)) => {
2737 }
2739 Err(other) => panic!("Expected ActivationNotFound, got {:?}", other),
2740 Ok(_) => panic!("Expected error for unknown activation"),
2741 }
2742 }
2743
2744 #[tokio::test]
2745 async fn invariant_resolve_handle_unsupported() {
2746 use crate::activations::health::Health;
2747 use crate::types::Handle;
2748
2749 let hub = DynamicHub::new("test").register(Health::new());
2750
2751 let handle = Handle::new(Health::PLUGIN_ID, "1.0.0", "check");
2753
2754 let result = hub.do_resolve_handle(&handle).await;
2755
2756 match result {
2757 Err(PlexusError::HandleNotSupported(name)) => {
2758 assert_eq!(name, "health");
2759 }
2760 Err(other) => panic!("Expected HandleNotSupported, got {:?}", other),
2761 Ok(_) => panic!("Expected error for unsupported handle"),
2762 }
2763 }
2764
2765 #[tokio::test]
2766 async fn invariant_resolve_handle_routes_by_plugin_id() {
2767 use crate::activations::health::Health;
2768 use crate::activations::echo::Echo;
2769 use crate::types::Handle;
2770 use uuid::Uuid;
2771
2772 let health = Health::new();
2773 let echo = Echo::new();
2774 let health_plugin_id = health.plugin_id();
2775 let echo_plugin_id = echo.plugin_id();
2776
2777 let hub = DynamicHub::new("test")
2778 .register(health)
2779 .register(echo);
2780
2781 let health_handle = Handle::new(health_plugin_id, "1.0.0", "check");
2783 match hub.do_resolve_handle(&health_handle).await {
2784 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "health"),
2785 Err(other) => panic!("health handle should route to health activation, got {:?}", other),
2786 Ok(_) => panic!("health handle should return HandleNotSupported"),
2787 }
2788
2789 let echo_handle = Handle::new(echo_plugin_id, "1.0.0", "echo");
2791 match hub.do_resolve_handle(&echo_handle).await {
2792 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "echo"),
2793 Err(other) => panic!("echo handle should route to echo activation, got {:?}", other),
2794 Ok(_) => panic!("echo handle should return HandleNotSupported"),
2795 }
2796
2797 let unknown_handle = Handle::new(Uuid::new_v4(), "1.0.0", "method");
2799 match hub.do_resolve_handle(&unknown_handle).await {
2800 Err(PlexusError::ActivationNotFound(_)) => { },
2801 Err(other) => panic!("unknown handle should return ActivationNotFound, got {:?}", other),
2802 Ok(_) => panic!("unknown handle should return ActivationNotFound"),
2803 }
2804 }
2805
2806 #[test]
2807 fn invariant_handle_plugin_id_determines_routing() {
2808 use crate::activations::health::Health;
2809 use crate::activations::echo::Echo;
2810 use crate::types::Handle;
2811
2812 let health = Health::new();
2813 let echo = Echo::new();
2814
2815 let health_handle = Handle::new(health.plugin_id(), "1.0.0", "check")
2817 .with_meta(vec!["msg-123".into(), "user".into()]);
2818 let echo_handle = Handle::new(echo.plugin_id(), "1.0.0", "echo")
2819 .with_meta(vec!["msg-123".into(), "user".into()]);
2820
2821 assert_ne!(health_handle.plugin_id, echo_handle.plugin_id);
2823 }
2824
2825 #[test]
2830 fn plugin_registry_basic_operations() {
2831 let mut registry = PluginRegistry::new();
2832 let id = uuid::Uuid::new_v4();
2833
2834 registry.register(id, "test_plugin".to_string(), "test".to_string());
2836
2837 assert_eq!(registry.lookup(id), Some("test_plugin"));
2839
2840 assert_eq!(registry.lookup_by_path("test_plugin"), Some(id));
2842
2843 let entry = registry.get(id).expect("should have entry");
2845 assert_eq!(entry.path, "test_plugin");
2846 assert_eq!(entry.plugin_type, "test");
2847 }
2848
2849 #[test]
2850 fn plugin_registry_populated_on_register() {
2851 use crate::activations::health::Health;
2852
2853 let hub = DynamicHub::new("test").register(Health::new());
2854
2855 let registry = hub.registry();
2856 assert!(!registry.is_empty(), "registry should not be empty after registration");
2857
2858 let health_id = registry.lookup_by_path("health");
2860 assert!(health_id.is_some(), "health should be registered by path");
2861
2862 let health_uuid = health_id.unwrap();
2864 assert_eq!(registry.lookup(health_uuid), Some("health"));
2865 }
2866
2867 #[test]
2868 fn plugin_registry_deterministic_uuid() {
2869 use crate::activations::health::Health;
2870
2871 let health1 = Health::new();
2873 let health2 = Health::new();
2874
2875 assert_eq!(health1.plugin_id(), health2.plugin_id(),
2876 "same activation type should have deterministic UUID");
2877
2878 let expected = uuid::Uuid::new_v5(
2880 &uuid::Uuid::NAMESPACE_OID,
2881 b"health@1"
2882 );
2883 assert_eq!(health1.plugin_id(), expected,
2884 "plugin_id should be deterministic from namespace@major_version");
2885 }
2886
2887 struct MinimalRouter;
2895
2896 #[async_trait]
2897 impl ChildRouter for MinimalRouter {
2898 fn router_namespace(&self) -> &str {
2899 "minimal"
2900 }
2901
2902 async fn router_call(
2903 &self,
2904 _method: &str,
2905 _params: Value,
2906 _auth: Option<&super::super::auth::AuthContext>,
2907 _raw_ctx: Option<&crate::request::RawRequestContext>,
2908 ) -> Result<PlexusStream, PlexusError> {
2909 Err(PlexusError::MethodNotFound {
2910 activation: "minimal".into(),
2911 method: "none".into(),
2912 })
2913 }
2914
2915 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
2916 None
2917 }
2918 }
2919
2920 #[tokio::test]
2921 async fn child_router_defaults_report_no_capabilities_and_none_streams() {
2922 let router = MinimalRouter;
2923
2924 assert_eq!(
2925 router.capabilities(),
2926 ChildCapabilities::empty(),
2927 "default capabilities should be empty"
2928 );
2929 assert!(
2930 router.list_children().await.is_none(),
2931 "default list_children should be None"
2932 );
2933 assert!(
2934 router.search_children("anything").await.is_none(),
2935 "default search_children should be None"
2936 );
2937 }
2938
2939 struct ListingRouter {
2941 names: Vec<String>,
2942 }
2943
2944 #[async_trait]
2945 impl ChildRouter for ListingRouter {
2946 fn router_namespace(&self) -> &str {
2947 "listing"
2948 }
2949
2950 async fn router_call(
2951 &self,
2952 _method: &str,
2953 _params: Value,
2954 _auth: Option<&super::super::auth::AuthContext>,
2955 _raw_ctx: Option<&crate::request::RawRequestContext>,
2956 ) -> Result<PlexusStream, PlexusError> {
2957 Err(PlexusError::MethodNotFound {
2958 activation: "listing".into(),
2959 method: "none".into(),
2960 })
2961 }
2962
2963 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
2964 if self.names.iter().any(|n| n == name) {
2965 Some(Box::new(ListingRouter { names: vec![] }))
2968 } else {
2969 None
2970 }
2971 }
2972
2973 fn capabilities(&self) -> ChildCapabilities {
2974 ChildCapabilities::LIST | ChildCapabilities::SEARCH
2975 }
2976
2977 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
2978 let stream = futures::stream::iter(self.names.iter().cloned());
2979 Some(Box::pin(stream))
2980 }
2981
2982 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
2983 let q = query.to_string();
2984 let stream = futures::stream::iter(
2985 self.names
2986 .iter()
2987 .filter(move |n| n.contains(&q))
2988 .cloned()
2989 .collect::<Vec<_>>(),
2990 );
2991 Some(Box::pin(stream))
2992 }
2993 }
2994
2995 #[tokio::test]
2996 async fn child_router_overrides_report_capabilities_and_yield_streams() {
2997 use futures::StreamExt;
2998
2999 let router = ListingRouter {
3000 names: vec!["alpha".into(), "beta".into(), "alphabet".into()],
3001 };
3002
3003 let caps = router.capabilities();
3005 assert!(caps.contains(ChildCapabilities::LIST));
3006 assert!(caps.contains(ChildCapabilities::SEARCH));
3007 assert_eq!(caps, ChildCapabilities::LIST | ChildCapabilities::SEARCH);
3008
3009 let list_stream = router
3011 .list_children()
3012 .await
3013 .expect("LIST capability set — expected Some(stream)");
3014 let listed: Vec<String> = list_stream.collect().await;
3015 assert_eq!(listed, vec!["alpha".to_string(), "beta".into(), "alphabet".into()]);
3016
3017 let search_stream = router
3019 .search_children("alpha")
3020 .await
3021 .expect("SEARCH capability set — expected Some(stream)");
3022 let matched: Vec<String> = search_stream.collect().await;
3023 assert_eq!(matched, vec!["alpha".to_string(), "alphabet".into()]);
3024 }
3025
3026 struct WireFixture {
3041 names: Vec<String>,
3042 caps: ChildCapabilities,
3043 }
3044
3045 #[async_trait]
3046 impl ChildRouter for WireFixture {
3047 fn router_namespace(&self) -> &str {
3048 "wirefixture"
3049 }
3050 async fn router_call(
3051 &self,
3052 _method: &str,
3053 _params: Value,
3054 _auth: Option<&super::super::auth::AuthContext>,
3055 _raw_ctx: Option<&crate::request::RawRequestContext>,
3056 ) -> Result<PlexusStream, PlexusError> {
3057 Err(PlexusError::MethodNotFound {
3058 activation: "wirefixture".into(),
3059 method: "none".into(),
3060 })
3061 }
3062 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
3063 None
3064 }
3065 fn capabilities(&self) -> ChildCapabilities {
3066 self.caps
3067 }
3068 async fn list_children(&self) -> Option<futures_core::stream::BoxStream<'_, String>> {
3069 if !self.caps.contains(ChildCapabilities::LIST) {
3070 return None;
3071 }
3072 Some(Box::pin(futures::stream::iter(self.names.clone())))
3073 }
3074 async fn search_children(
3075 &self,
3076 query: &str,
3077 ) -> Option<futures_core::stream::BoxStream<'_, String>> {
3078 if !self.caps.contains(ChildCapabilities::SEARCH) {
3079 return None;
3080 }
3081 let q = query.to_lowercase();
3082 let filtered: Vec<String> = self
3083 .names
3084 .iter()
3085 .filter(|n| n.to_lowercase().contains(&q))
3086 .cloned()
3087 .collect();
3088 Some(Box::pin(futures::stream::iter(filtered)))
3089 }
3090 }
3091
3092 fn build_module_for(router: WireFixture, ns: &str) -> RpcModule<()> {
3093 let mut module = RpcModule::new(());
3094 let arc: Arc<dyn ChildRouter> = Arc::new(router);
3095 register_child_capability_methods(&mut module, ns, arc).expect("register");
3096 module
3097 }
3098
3099 #[tokio::test]
3100 async fn child_wire_registers_both_methods_when_both_bits_set() {
3101 let module = build_module_for(
3102 WireFixture {
3103 names: vec!["alpha".into(), "beta".into()],
3104 caps: ChildCapabilities::LIST | ChildCapabilities::SEARCH,
3105 },
3106 "fixture",
3107 );
3108 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3109 assert!(
3110 names.contains(&"fixture.list_children".to_string()),
3111 "expected fixture.list_children, got: {:?}",
3112 names
3113 );
3114 assert!(
3115 names.contains(&"fixture.search_children".to_string()),
3116 "expected fixture.search_children, got: {:?}",
3117 names
3118 );
3119 }
3120
3121 #[tokio::test]
3122 async fn child_wire_registers_nothing_when_no_bits_set() {
3123 let module = build_module_for(
3124 WireFixture {
3125 names: vec!["alpha".into()],
3126 caps: ChildCapabilities::empty(),
3127 },
3128 "fixture",
3129 );
3130 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3131 assert!(
3132 !names.contains(&"fixture.list_children".to_string()),
3133 "fixture.list_children should NOT be registered when cap absent"
3134 );
3135 assert!(
3136 !names.contains(&"fixture.search_children".to_string()),
3137 "fixture.search_children should NOT be registered when cap absent"
3138 );
3139 }
3140
3141 #[tokio::test]
3142 async fn child_wire_registers_only_list_when_only_list_bit() {
3143 let module = build_module_for(
3144 WireFixture {
3145 names: vec!["alpha".into()],
3146 caps: ChildCapabilities::LIST,
3147 },
3148 "fixture",
3149 );
3150 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3151 assert!(names.contains(&"fixture.list_children".to_string()));
3152 assert!(!names.contains(&"fixture.search_children".to_string()));
3153 }
3154
3155 }