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 plexus_client::{DenyReason, ParamProblem, RemoteError};
17use async_trait::async_trait;
18use bitflags::bitflags;
19use futures::Stream;
20use futures_core::stream::BoxStream;
21use jsonrpsee::core::server::Methods;
22use jsonrpsee::RpcModule;
23
24pub const PLEXUS_NOTIF_METHOD: &str = "result";
30use schemars::JsonSchema;
31use serde::{Deserialize, Serialize};
32use serde_json::Value;
33use std::collections::{BTreeMap, HashMap};
34use std::sync::Arc;
35
36#[derive(Debug, Clone)]
48pub enum PlexusError {
49 ActivationNotFound(String),
50 MethodNotFound { activation: String, method: String },
51 InvalidParams {
55 param: Option<String>,
56 problem: ParamProblem,
57 },
58 ExecutionError(String),
59 HandleNotSupported(String),
60 TransportError(TransportErrorKind),
61 Unauthenticated(String),
62 Forbidden { reason: AuthzDenyReason },
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
79pub enum AuthzDenyReason {
80 MissingScope { scope: plexus_auth_core::Scope },
84 TenantBoundary,
88 NotAccepted,
91 MissingGrant {
98 grant: plexus_auth_core::grants::Grant,
100 scope: plexus_auth_core::grants::ScopeRef,
103 roles: Vec<plexus_auth_core::RoleName>,
105 held_on: Vec<plexus_auth_core::grants::ScopeRef>,
107 },
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
111#[serde(tag = "error_kind", rename_all = "snake_case")]
112pub enum TransportErrorKind {
113 ConnectionRefused { host: String, port: u16 },
114 ConnectionTimeout { host: String, port: u16 },
115 ProtocolError { message: String },
116 NetworkError { message: String },
117}
118
119impl std::fmt::Display for TransportErrorKind {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 match self {
122 TransportErrorKind::ConnectionRefused { host, port } => {
123 write!(f, "Connection refused to {}:{}", host, port)
124 }
125 TransportErrorKind::ConnectionTimeout { host, port } => {
126 write!(f, "Connection timeout to {}:{}", host, port)
127 }
128 TransportErrorKind::ProtocolError { message } => {
129 write!(f, "Protocol error: {}", message)
130 }
131 TransportErrorKind::NetworkError { message } => {
132 write!(f, "Network error: {}", message)
133 }
134 }
135 }
136}
137
138impl std::fmt::Display for PlexusError {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 match self {
141 PlexusError::ActivationNotFound(name) => write!(f, "Activation not found: {}", name),
142 PlexusError::MethodNotFound { activation, method } => {
143 write!(f, "Method not found: {}.{}", activation, method)
144 }
145 PlexusError::InvalidParams { param, problem } => match (param, problem) {
149 (Some(p), ParamProblem::Missing) => {
150 write!(f, "Invalid params: missing field: {}", p)
151 }
152 (None, ParamProblem::Missing) => {
153 write!(f, "Invalid params: a required parameter is missing")
154 }
155 (Some(p), ParamProblem::Malformed { detail }) => {
156 write!(f, "Invalid params: {}: {}", p, detail)
157 }
158 (None, ParamProblem::Malformed { detail }) => {
159 write!(f, "Invalid params: {}", detail)
160 }
161 },
162 PlexusError::ExecutionError(msg) => write!(f, "Execution error: {}", msg),
163 PlexusError::HandleNotSupported(activation) => {
164 write!(f, "Handle resolution not supported by activation: {}", activation)
165 }
166 PlexusError::TransportError(kind) => match kind {
167 TransportErrorKind::ConnectionRefused { host, port } => {
168 write!(f, "Connection refused to {}:{}", host, port)
169 }
170 TransportErrorKind::ConnectionTimeout { host, port } => {
171 write!(f, "Connection timeout to {}:{}", host, port)
172 }
173 TransportErrorKind::ProtocolError { message } => {
174 write!(f, "Protocol error: {}", message)
175 }
176 TransportErrorKind::NetworkError { message } => {
177 write!(f, "Network error: {}", message)
178 }
179 }
180 PlexusError::Unauthenticated(msg) => write!(f, "Authentication required: {}", msg),
181 PlexusError::Forbidden { reason } => match reason {
182 AuthzDenyReason::MissingScope { scope } => {
186 write!(f, "Forbidden: missing required scope '{}'", scope)
187 }
188 AuthzDenyReason::TenantBoundary => write!(f, "Forbidden: tenant boundary"),
189 AuthzDenyReason::NotAccepted => write!(f, "Forbidden: call not accepted"),
190 AuthzDenyReason::MissingGrant { grant, scope, .. } if scope.is_everywhere() => {
192 write!(f, "needs {}", grant)
193 }
194 AuthzDenyReason::MissingGrant { grant, scope, .. } => {
195 write!(f, "needs {} on {}", grant, scope)
196 }
197 },
198 }
199 }
200}
201
202impl std::error::Error for PlexusError {}
203
204impl PlexusError {
205 pub fn invalid_params(detail: impl Into<String>) -> Self {
208 PlexusError::InvalidParams { param: None, problem: ParamProblem::Malformed { detail: detail.into() } }
209 }
210
211 pub fn malformed_param(param: impl Into<String>, detail: impl Into<String>) -> Self {
214 PlexusError::InvalidParams {
215 param: Some(param.into()),
216 problem: ParamProblem::Malformed { detail: detail.into() },
217 }
218 }
219}
220
221impl From<&PlexusError> for RemoteError {
239 fn from(e: &PlexusError) -> Self {
240 match e {
241 PlexusError::ActivationNotFound(name) => RemoteError::ActivationNotFound {
242 activation: name.clone(),
243 },
244 PlexusError::MethodNotFound { activation, method } => RemoteError::MethodNotFound {
245 activation: activation.clone(),
246 method: method.clone(),
247 },
248 PlexusError::InvalidParams { param, problem } => RemoteError::InvalidParams {
249 param: param.clone(),
250 problem: problem.clone(),
251 },
252 PlexusError::ExecutionError(message) => RemoteError::Execution {
253 message: message.clone(),
254 },
255 PlexusError::HandleNotSupported(activation) => RemoteError::HandleNotSupported {
256 activation: activation.clone(),
257 },
258 PlexusError::TransportError(kind) => RemoteError::Execution {
259 message: kind.to_string(),
260 },
261 PlexusError::Unauthenticated(_) => RemoteError::Unauthenticated,
262 PlexusError::Forbidden { reason } => RemoteError::Forbidden {
263 reason: match reason {
264 AuthzDenyReason::MissingScope { scope } => DenyReason::MissingScope {
265 scope: scope.as_str().to_string(),
266 },
267 AuthzDenyReason::TenantBoundary => DenyReason::TenantBoundary,
268 AuthzDenyReason::NotAccepted => DenyReason::NotAccepted,
269 AuthzDenyReason::MissingGrant { grant, scope, roles, held_on } => {
272 DenyReason::MissingGrant {
273 grant: grant.as_str().to_string(),
274 scope: scope.as_str().to_string(),
275 roles: roles.iter().map(|r| r.as_str().to_string()).collect(),
276 held_on: held_on.iter().map(|s| s.as_str().to_string()).collect(),
277 }
278 }
279 },
280 },
281 }
282 }
283}
284
285fn plexus_error_code(e: &PlexusError) -> i32 {
294 match e {
295 PlexusError::Unauthenticated(_) => -32001,
296 PlexusError::Forbidden { .. } => -32003,
297 PlexusError::InvalidParams { .. } => -32602,
298 PlexusError::MethodNotFound { .. } | PlexusError::ActivationNotFound(_) => -32601,
299 _ => -32000,
300 }
301}
302
303pub fn plexus_error_to_jsonrpc(e: &PlexusError) -> jsonrpsee::types::ErrorObjectOwned {
314 let error = RemoteError::from(e);
315 jsonrpsee::types::ErrorObject::owned(plexus_error_code(e), error.to_string(), Some(error))
316}
317
318pub(crate) fn error_item_raw(ns: &str, e: &PlexusError) -> Option<Box<serde_json::value::RawValue>> {
324 serde_json::value::to_raw_value(&error_item(ns, e)).ok()
325}
326
327pub fn error_item(ns: &str, e: &PlexusError) -> serde_json::Value {
333 let item = super::types::PlexusStreamItem::from_plexus_error(
336 super::types::StreamMetadata::new(vec![ns.into()], super::context::PlexusContext::hash()),
337 e,
338 false,
339 );
340 serde_json::to_value(&item).unwrap_or(serde_json::Value::Null)
341}
342
343#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
348pub struct ActivationInfo {
349 pub namespace: String,
350 pub version: String,
351 pub description: String,
352 pub methods: Vec<String>,
353}
354
355#[async_trait]
360pub trait Activation: Send + Sync + 'static {
361 type Methods: MethodEnumSchema;
362
363 fn namespace(&self) -> &str;
364 fn version(&self) -> &str;
365 fn description(&self) -> &str { "No description available" }
367 fn long_description(&self) -> Option<&str> { None }
369 fn methods(&self) -> Vec<&str>;
370 fn method_help(&self, _method: &str) -> Option<String> { None }
371 fn plugin_id(&self) -> uuid::Uuid {
375 let major_version = self.version().split('.').next().unwrap_or("0");
376 uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, format!("{}@{}", self.namespace(), major_version).as_bytes())
377 }
378
379 async fn call(
380 &self,
381 method: &str,
382 params: Value,
383 auth: Option<&super::auth::AuthContext>,
384 raw_ctx: Option<&crate::request::RawRequestContext>,
385 ) -> Result<PlexusStream, PlexusError>;
386 async fn resolve_handle(&self, _handle: &Handle) -> Result<PlexusStream, PlexusError> {
387 Err(PlexusError::HandleNotSupported(self.namespace().to_string()))
388 }
389
390 fn into_rpc_methods(self) -> Methods where Self: Sized;
391
392 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
405 Vec::new()
406 }
407
408 fn plugin_schema(&self) -> PluginSchema {
410 let methods: Vec<MethodSchema> = self.methods().iter().map(|name| {
414 let desc = self.method_help(name).unwrap_or_default();
415 MethodSchema::new(name.to_string(), desc, String::new()).with_content_hash()
416 }).collect();
417
418 if let Some(long_desc) = self.long_description() {
419 PluginSchema::leaf_with_long_description(
420 self.namespace(),
421 self.version(),
422 self.description(),
423 long_desc,
424 methods,
425 )
426 } else {
427 PluginSchema::leaf(
428 self.namespace(),
429 self.version(),
430 self.description(),
431 methods,
432 )
433 }
434 }
435}
436
437bitflags! {
442 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
471 #[deprecated(
472 since = "0.5",
473 note = "Use MethodRole::DynamicChild { list_method, search_method } instead. Removed in 0.7."
474 )]
475 pub struct ChildCapabilities: u32 {
476 const LIST = 0b0000_0001;
478 const SEARCH = 0b0000_0010;
481 }
482}
483
484#[async_trait]
501pub trait ChildRouter: Send + Sync {
502 fn router_namespace(&self) -> &str;
504
505 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
507
508 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>>;
510
511 #[allow(deprecated)]
516 fn capabilities(&self) -> ChildCapabilities {
517 ChildCapabilities::empty()
518 }
519
520 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
528 None
529 }
530
531 async fn search_children(&self, _query: &str) -> Option<BoxStream<'_, String>> {
539 None
540 }
541
542 fn forward_policy_for(
557 &self,
558 _callee_ns: &str,
559 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
560 None
561 }
562
563 fn router_schema(&self) -> Option<PluginSchema> {
570 None
571 }
572
573 fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
586 Vec::new()
587 }
588
589 fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
598 plexus_auth_core::Principal::Anonymous
599 }
600}
601
602pub async fn route_to_child<T: ChildRouter + ?Sized>(
633 parent: &T,
634 method: &str,
635 params: Value,
636 auth: Option<&super::auth::AuthContext>,
637 raw_ctx: Option<&crate::request::RawRequestContext>,
638) -> Result<PlexusStream, PlexusError> {
639 if let Some((child_name, rest)) = method.split_once('.') {
641 if let Some(child) = parent.get_child(child_name).await {
642 let policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy> = parent
652 .forward_policy_for(child_name)
653 .unwrap_or_else(|| {
654 std::sync::Arc::new(plexus_auth_core::IdentityOnly)
655 as std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>
656 });
657
658 let callee_method_str = format!("{}.{}", child_name, rest);
664 let callee_method = plexus_auth_core::MethodPath::try_new(callee_method_str.as_str())
665 .map_err(|e| PlexusError::ExecutionError(format!(
666 "framework-built MethodPath rejected: {} ({:?})",
667 callee_method_str, e
668 )))?;
669 let site = plexus_auth_core::CallSite::new(
670 parent.framework_stamped_principal(),
671 callee_method,
672 );
673
674 let anonymous_owned;
678 let caller_ctx: &super::auth::AuthContext = match auth {
679 Some(ctx) => ctx,
680 None => {
681 anonymous_owned = super::auth::AuthContext::anonymous();
682 &anonymous_owned
683 }
684 };
685 let derivation = policy.forward(caller_ctx, &site);
686
687 tracing::trace!(
708 target: "plexus::audit",
709 policy = policy.name().as_str(),
710 callee_method = %site.callee_method.as_str(),
711 derivation_keep_verified_user = derivation.keep_verified_user,
712 derivation_keep_roles = derivation.keep_roles,
713 derivation_keep_capabilities = derivation.keep_capabilities,
714 derivation_keep_metadata = derivation.keep_metadata,
715 "forward_policy_applied (audit-record emission stubbed pending PRIVACY-1)"
716 );
717
718 return match auth {
725 Some(caller_ctx) => {
726 caller_ctx
727 .with_callee_context(&derivation, &site.caller, |callee_ctx| async move {
728 child
729 .router_call(rest, params, Some(&callee_ctx), raw_ctx)
730 .await
731 })
732 .await
733 }
734 None => child.router_call(rest, params, None, raw_ctx).await,
735 };
736 }
737 return Err(PlexusError::ActivationNotFound(child_name.to_string()));
738 }
739
740 Err(PlexusError::MethodNotFound {
742 activation: parent.router_namespace().to_string(),
743 method: method.to_string(),
744 })
745}
746
747struct ArcChildRouter(Arc<dyn ChildRouter>);
751
752#[async_trait]
753impl ChildRouter for ArcChildRouter {
754 fn router_namespace(&self) -> &str {
755 self.0.router_namespace()
756 }
757
758 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
759 self.0.router_call(method, params, auth, raw_ctx).await
760 }
761
762 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
763 self.0.get_child(name).await
764 }
765
766 #[allow(deprecated)]
767 fn capabilities(&self) -> ChildCapabilities {
768 self.0.capabilities()
769 }
770
771 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
772 self.0.list_children().await
773 }
774
775 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
776 self.0.search_children(query).await
777 }
778
779 fn forward_policy_for(
783 &self,
784 callee_ns: &str,
785 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
786 self.0.forward_policy_for(callee_ns)
787 }
788
789 fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
790 self.0.framework_stamped_principal()
791 }
792
793 fn router_schema(&self) -> Option<PluginSchema> {
794 self.0.router_schema()
795 }
796
797 fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
798 self.0.router_static_child_schemas()
799 }
800}
801
802#[async_trait]
807#[allow(dead_code)] trait ActivationObject: Send + Sync + 'static {
809 fn namespace(&self) -> &str;
810 fn version(&self) -> &str;
811 fn description(&self) -> &str;
812 fn long_description(&self) -> Option<&str>;
813 fn methods(&self) -> Vec<&str>;
814 fn method_help(&self, method: &str) -> Option<String>;
815 fn plugin_id(&self) -> uuid::Uuid;
816 async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
817 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError>;
818 fn plugin_schema(&self) -> PluginSchema;
819 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)>;
820 fn schema(&self) -> Schema;
821}
822
823struct ActivationWrapper<A: Activation> {
824 inner: A,
825}
826
827#[async_trait]
828impl<A: Activation> ActivationObject for ActivationWrapper<A> {
829 fn namespace(&self) -> &str { self.inner.namespace() }
830 fn version(&self) -> &str { self.inner.version() }
831 fn description(&self) -> &str { self.inner.description() }
832 fn long_description(&self) -> Option<&str> { self.inner.long_description() }
833 fn methods(&self) -> Vec<&str> { self.inner.methods() }
834 fn method_help(&self, method: &str) -> Option<String> { self.inner.method_help(method) }
835 fn plugin_id(&self) -> uuid::Uuid { self.inner.plugin_id() }
836
837 async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
838 self.inner.call(method, params, auth, raw_ctx).await
839 }
840
841 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
842 self.inner.resolve_handle(handle).await
843 }
844
845 fn plugin_schema(&self) -> PluginSchema { self.inner.plugin_schema() }
846
847 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> { self.inner.static_child_schemas() }
848
849 fn schema(&self) -> Schema {
850 let schema = schemars::schema_for!(A::Methods);
851 serde_json::from_value(serde_json::to_value(schema).expect("serialize"))
852 .expect("parse schema")
853 }
854}
855
856#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
861#[serde(tag = "event", rename_all = "snake_case")]
862pub enum HashEvent {
863 Hash { value: String },
864}
865
866#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
868#[serde(tag = "event", rename_all = "snake_case")]
869pub enum SchemaEvent {
870 Schema(PluginSchema),
872}
873
874#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
876pub struct PluginHashes {
877 pub namespace: String,
878 pub self_hash: String,
879 #[serde(skip_serializing_if = "Option::is_none")]
880 pub children_hash: Option<String>,
881 pub hash: String,
882 #[serde(skip_serializing_if = "Option::is_none")]
884 pub children: Option<Vec<ChildHashes>>,
885}
886
887#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
889pub struct ChildHashes {
890 pub namespace: String,
891 pub hash: String,
892}
893
894
895#[derive(Debug, Clone)]
901pub struct PluginEntry {
902 pub id: uuid::Uuid,
904 pub path: String,
906 pub plugin_type: String,
908}
909
910#[derive(Default)]
915pub struct PluginRegistry {
916 by_id: HashMap<uuid::Uuid, PluginEntry>,
918 by_path: HashMap<String, uuid::Uuid>,
920}
921
922#[derive(Clone)]
926pub struct PluginRegistrySnapshot {
927 by_id: HashMap<uuid::Uuid, PluginEntry>,
928 by_path: HashMap<String, uuid::Uuid>,
929}
930
931impl PluginRegistrySnapshot {
932 pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
934 self.by_id.get(&id).map(|e| e.path.as_str())
935 }
936
937 pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
939 self.by_path.get(path).copied()
940 }
941
942 pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
944 self.by_id.get(&id)
945 }
946
947 pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
949 self.by_id.values()
950 }
951
952 pub fn len(&self) -> usize {
954 self.by_id.len()
955 }
956
957 pub fn is_empty(&self) -> bool {
959 self.by_id.is_empty()
960 }
961}
962
963impl PluginRegistry {
964 pub fn new() -> Self {
966 Self::default()
967 }
968
969 pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
971 self.by_id.get(&id).map(|e| e.path.as_str())
972 }
973
974 pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
976 self.by_path.get(path).copied()
977 }
978
979 pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
981 self.by_id.get(&id)
982 }
983
984 pub fn register(&mut self, id: uuid::Uuid, path: String, plugin_type: String) {
986 let entry = PluginEntry { id, path: path.clone(), plugin_type };
987 self.by_id.insert(id, entry);
988 self.by_path.insert(path, id);
989 }
990
991 pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
993 self.by_id.values()
994 }
995
996 pub fn len(&self) -> usize {
998 self.by_id.len()
999 }
1000
1001 pub fn is_empty(&self) -> bool {
1003 self.by_id.is_empty()
1004 }
1005}
1006
1007fn build_info_payload(
1020 namespace: &str,
1021 caps: Option<&plexus_auth_core::BackendAuthCapabilities>,
1022) -> serde_json::Value {
1023 let advertised = match caps {
1024 Some(c) => c.clone(),
1025 None => plexus_auth_core::BackendAuthCapabilities::anonymous_default(),
1026 };
1027 serde_json::json!({
1028 "backend": namespace,
1029 "auth_capabilities": advertised,
1030 })
1031}
1032
1033fn fill_site_hints_in_schema_stream(
1044 stream: PlexusStream,
1045 site: plexus_auth_core::AttachmentSite,
1046) -> PlexusStream {
1047 use futures::StreamExt;
1048 Box::pin(stream.map(move |item| match item {
1049 super::types::PlexusStreamItem::Data {
1050 metadata,
1051 content_type,
1052 content,
1053 } if content_type.ends_with(".schema") || content_type.ends_with(".method_schema") => {
1054 let content = match content.decode::<super::SchemaResult>() {
1056 Ok(mut result) => {
1057 result.fill_site_hints(&site);
1058 match serde_json::to_value(&result) {
1059 Ok(v) => v.into(),
1060 Err(_) => content,
1061 }
1062 }
1063 Err(_) => content,
1064 };
1065 super::types::PlexusStreamItem::Data {
1066 metadata,
1067 content_type,
1068 content,
1069 }
1070 }
1071 other => other,
1072 }))
1073}
1074
1075struct DynamicHubInner {
1076 namespace: String,
1078 activations: BTreeMap<String, Arc<dyn ActivationObject>>,
1087 child_routers: BTreeMap<String, Arc<dyn ChildRouter>>,
1090 registry: std::sync::RwLock<PluginRegistry>,
1092 pending_rpc: std::sync::Mutex<Vec<Box<dyn FnOnce() -> Methods + Send>>>,
1093 auth_capabilities: Option<plexus_auth_core::BackendAuthCapabilities>,
1104 forward_policies: super::forward_registry::ForwardPolicyRegistry,
1113 scope_registry: Option<Arc<plexus_auth_core::ScopeRegistry>>,
1119 default_deny: bool,
1126 audit_sink: Arc<dyn plexus_auth_core::AuditSink>,
1132 duplex_gate: std::sync::OnceLock<super::duplex_gate::DuplexGate>,
1134 gate_index: std::sync::OnceLock<HashMap<String, super::scope_gate::MethodGateInfo>>,
1142 input_index: std::sync::OnceLock<HashMap<String, bool>>,
1146 gate: Option<Arc<plexus_auth_core::grants::Gate>>,
1150 signed_in_grants: std::collections::BTreeSet<String>,
1154 resource_metadata: Option<String>,
1157 auth_catalog: Option<super::auth_activation::Catalog>,
1161 describe: super::view::Cache,
1165 ir_cache: super::ir::IrCache,
1168 nested_count: usize,
1172}
1173
1174impl DynamicHubInner {
1175 fn nested_count(&self) -> usize {
1176 self.nested_count
1177 }
1178}
1179
1180#[derive(Clone)]
1202pub struct DynamicHub {
1203 inner: Arc<DynamicHubInner>,
1204}
1205
1206struct IrView {
1208 base: Arc<super::view::Described>,
1209 shaped: Option<Arc<super::view::Shaped>>,
1211 hash: String,
1213}
1214
1215impl IrView {
1216 fn root(&self) -> PluginSchema {
1217 match &self.shaped {
1218 Some(v) => v.service.clone(),
1219 None => self.base.service.clone(),
1220 }
1221 }
1222
1223 fn top(&self, ns: &str) -> Option<PluginSchema> {
1224 match &self.shaped {
1225 Some(v) => v.schema_of(&self.base, ns).filter(|_| ns != v.service.namespace),
1226 None => self.base.activations.iter().find(|a| a.namespace == ns).cloned(),
1227 }
1228 }
1229
1230 fn shows(&self, ns: &str) -> bool {
1231 match &self.shaped {
1232 Some(v) => v.shows(ns),
1233 None => self.base.activations.iter().any(|a| a.namespace == ns),
1234 }
1235 }
1236
1237 fn names(&self, service: &str) -> Vec<String> {
1241 let mut out = vec![String::new()];
1242 out.extend(self.base.activations.iter().map(|a| a.namespace.clone()).filter(|ns| ns != service && self.shows(ns)));
1243 for path in self.base.nested() {
1244 let mut segs = path.split('.');
1245 let (Some(top), Some(entry)) = (segs.next(), segs.next()) else { continue };
1246 let reached = self.shows(top)
1247 && match &self.shaped {
1248 Some(v) => v.method_of(&self.base, top, entry).is_some(),
1249 None => true,
1250 };
1251 if reached {
1252 out.push(path.to_string());
1253 }
1254 }
1255 out
1256 }
1257}
1258
1259impl DynamicHub {
1264 pub fn new(namespace: impl Into<String>) -> Self {
1290 Self {
1291 inner: Arc::new(DynamicHubInner {
1292 namespace: namespace.into(),
1293 activations: BTreeMap::new(),
1294 child_routers: BTreeMap::new(),
1295 registry: std::sync::RwLock::new(PluginRegistry::new()),
1296 pending_rpc: std::sync::Mutex::new(Vec::new()),
1297 auth_capabilities: None,
1298 forward_policies: super::forward_registry::ForwardPolicyRegistry::new(),
1299 scope_registry: None,
1300 default_deny: false,
1301 audit_sink: Arc::new(plexus_auth_core::TracingAuditSink),
1302 duplex_gate: std::sync::OnceLock::new(),
1303 gate_index: std::sync::OnceLock::new(),
1304 input_index: std::sync::OnceLock::new(),
1305 gate: None,
1306 signed_in_grants: std::collections::BTreeSet::new(),
1307 resource_metadata: None,
1308 auth_catalog: None,
1309 describe: Default::default(),
1310 ir_cache: Default::default(),
1311 nested_count: Default::default(),
1312 }),
1313 }
1314 }
1315
1316 fn inner_mut(&mut self, refused: &str) -> &mut DynamicHubInner {
1321 let inner = Arc::get_mut(&mut self.inner).expect(refused);
1322 inner.describe.reset();
1323 inner
1324 }
1325
1326 pub fn with_scope_registry(mut self, registry: plexus_auth_core::ScopeRegistry) -> Self {
1346 let inner = self.inner_mut("Cannot set scope_registry: DynamicHub has multiple references");
1347 inner.scope_registry = Some(Arc::new(registry));
1348 self
1349 }
1350
1351 pub fn with_default_deny(mut self, default_deny: bool) -> Self {
1370 let inner = self.inner_mut("Cannot set default_deny: DynamicHub has multiple references");
1371 inner.default_deny = default_deny;
1372 self
1373 }
1374
1375 pub fn with_audit_sink(mut self, sink: Arc<dyn plexus_auth_core::AuditSink>) -> Self {
1386 let inner = self.inner_mut("Cannot set audit_sink: DynamicHub has multiple references");
1387 inner.audit_sink = sink;
1388 self
1389 }
1390
1391 pub fn with_gate(mut self, gate: Arc<plexus_auth_core::grants::Gate>) -> Self {
1416 let inner = self.inner_mut("Cannot set gate: DynamicHub has multiple references");
1417 inner.gate = Some(gate);
1418 self
1419 }
1420
1421 pub fn gate(&self) -> Option<&Arc<plexus_auth_core::grants::Gate>> {
1423 self.inner.gate.as_ref()
1424 }
1425
1426 pub fn with_resource_metadata(mut self, url: impl Into<String>) -> Self {
1431 let inner = self.inner_mut("Cannot set resource_metadata: DynamicHub has multiple references");
1432 inner.resource_metadata = Some(url.into());
1433 self
1434 }
1435
1436 pub fn with_signed_in_grants<I, S>(mut self, grants: I) -> Self
1443 where
1444 I: IntoIterator<Item = S>,
1445 S: Into<String>,
1446 {
1447 let inner = self.inner_mut("Cannot set signed_in grants: DynamicHub has multiple references");
1448 inner.signed_in_grants.extend(grants.into_iter().map(Into::into));
1449 self
1450 }
1451
1452 pub fn with_auth(mut self, setup: super::auth_activation::AuthSetup) -> Self {
1469 let catalog = super::auth_activation::Catalog::default();
1470 catalog.add(&Activation::plugin_schema(&self));
1471 for a in self.inner.activations.values() {
1472 catalog.add(&a.plugin_schema());
1473 }
1474 for child in self.static_children() {
1476 catalog.add(&child);
1477 }
1478 let (auth, gate) = super::auth_activation::AuthActivation::mount(setup, catalog.clone());
1479 {
1480 let inner = self.inner_mut("Cannot mount auth: DynamicHub has multiple references");
1481 inner.auth_catalog = Some(catalog);
1482 inner.gate = Some(Arc::new(gate));
1483 }
1484 self.register(auth)
1485 .with_signed_in_grants(super::auth_activation::SIGNED_IN_GRANTS.iter().copied())
1486 }
1487
1488 pub fn view(&self, caller: Option<&super::auth::AuthContext>) -> super::view::View {
1506 match self.inner.gate.as_ref() {
1507 None => self.described().whole(),
1508 Some(_) => {
1509 let (base, view) = self.shaped(caller);
1510 view.view(&base)
1511 }
1512 }
1513 }
1514
1515 pub fn schema_moved(&self) {
1521 self.inner.describe.schema_moved();
1522 }
1523
1524 fn described(&self) -> Arc<super::view::Described> {
1528 let at = self.inner.describe.schema_generation();
1529 match self.inner.describe.base(at) {
1530 Some(cell) => cell.get_or_init(|| Arc::new(self.describe_now())).clone(),
1531 None => Arc::new(self.describe_now()),
1532 }
1533 }
1534
1535 fn describe_now(&self) -> super::view::Described {
1536 let service = Activation::plugin_schema(self);
1537 let activations: Vec<PluginSchema> = self.inner.activations.values().map(|a| a.plugin_schema()).collect();
1538 super::view::Described::new(service, activations, self.static_children())
1541 }
1542
1543 fn shaped(&self, caller: Option<&super::auth::AuthContext>) -> (Arc<super::view::Described>, Arc<super::view::Shaped>) {
1549 let gate = self.inner.gate.as_ref().expect("a view is a gated service's");
1550 let schema_at = self.inner.describe.schema_generation();
1551 let grants_at = gate.generation().current();
1552 let (caller, _) = super::grant_gate::standing(gate, caller);
1555 let who = caller.and_then(|c| gate.fingerprint(c));
1556 let shape = |base: &super::view::Described| {
1557 Arc::new(super::view::shape(gate, &self.inner.signed_in_grants, who.as_ref(), base))
1558 };
1559 match self.inner.describe.view(schema_at, grants_at, &who) {
1560 Some((base, view)) => {
1561 let base = base.get_or_init(|| Arc::new(self.describe_now())).clone();
1562 let view = view.get_or_init(|| shape(&base)).clone();
1563 (base, view)
1564 }
1565 None => {
1566 let base = Arc::new(self.describe_now());
1567 let view = shape(&base);
1568 (base, view)
1569 }
1570 }
1571 }
1572
1573 pub fn info(&self, caller: Option<&super::auth::AuthContext>) -> serde_json::Value {
1579 if self.inner.gate.is_none() {
1580 return build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1581 }
1582 let (base, view) = self.shaped(caller);
1584 view.info
1585 .get_or_init(|| {
1586 let mut payload = build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1587 if let Some(obj) = payload.as_object_mut() {
1588 obj.insert("view".into(), view.kind.as_str().into());
1589 obj.insert("view_hash".into(), view.hash.clone().into());
1590 if view.kind == super::ViewKind::Anonymous {
1591 let mut auth = serde_json::Map::new();
1592 auth.insert("methods".into(), view.public_methods(&base).into());
1593 if let Some(url) = self.inner.resource_metadata.as_ref() {
1594 auth.insert("resource_metadata".into(), url.clone().into());
1595 }
1596 obj.insert("auth".into(), serde_json::Value::Object(auth));
1597 }
1598 }
1599 payload
1600 })
1601 .clone()
1602 }
1603
1604 async fn introspect_in_view(
1610 &self,
1611 method: &str,
1612 params: &Value,
1613 auth: Option<&super::auth::AuthContext>,
1614 raw_ctx: Option<&crate::request::RawRequestContext>,
1615 ) -> Option<Result<PlexusStream, PlexusError>> {
1616 let (ns, rest) = method.split_once('.')?;
1617 let hub_ns = self.inner.namespace.as_str();
1618 let (base, view) = self.shaped(auth);
1620 let not_found = || PlexusError::ActivationNotFound(ns.to_string());
1621 let content: serde_json::Value = match rest {
1622 "schema" => {
1623 if !view.shows(ns) {
1624 return Some(Err(not_found()));
1625 }
1626 let mut result = match params.get("method").and_then(|v| v.as_str()) {
1627 Some(name) => match view.method_of(&base, ns, name) {
1628 Some(m) => super::SchemaResult::Method(m),
1629 None => {
1630 return Some(Err(PlexusError::MethodNotFound {
1631 activation: ns.to_string(),
1632 method: name.to_string(),
1633 }))
1634 }
1635 },
1636 None => super::SchemaResult::Plugin(view.schema_of(&base, ns)?),
1637 };
1638 if let Some(site) = self.derived_site_hint() {
1639 result.fill_site_hints(&site);
1640 }
1641 serde_json::to_value(&result).ok()?
1642 }
1643 "hash" if ns == hub_ns => serde_json::to_value(HashEvent::Hash { value: view.hash.clone() }).ok()?,
1644 "hashes" if ns == hub_ns => serde_json::to_value(view.hashes()).ok()?,
1645 r if r.ends_with(".schema") => {
1646 if !view.shows(ns) {
1647 return Some(Err(not_found()));
1648 }
1649 let name = r.trim_end_matches(".schema");
1650 match view.method_of(&base, ns, name) {
1651 Some(m) if matches!(m.role, super::MethodRole::Rpc) => {
1652 serde_json::to_value(super::SchemaResult::Method(m)).ok()?
1653 }
1654 Some(_) => return None,
1656 None if name.contains('.') => return None,
1657 None => {
1658 return Some(Err(PlexusError::MethodNotFound {
1659 activation: ns.to_string(),
1660 method: name.to_string(),
1661 }))
1662 }
1663 }
1664 }
1665 _ => return None,
1666 };
1667 use futures::StreamExt;
1670 let with = |content: serde_json::Value| {
1671 move |item: super::types::PlexusStreamItem| match item {
1674 super::types::PlexusStreamItem::Data { metadata, content_type, .. } => {
1675 super::types::PlexusStreamItem::Data { metadata, content_type, content: content.clone().into() }
1676 }
1677 other => other,
1678 }
1679 };
1680 if self.inner.scope_registry.is_some() || self.inner.default_deny {
1683 let routed = self.route_ungated(method, params.clone(), auth, raw_ctx).await;
1684 return Some(routed.map(|s| -> PlexusStream { Box::pin(s.map(with(content))) }));
1685 }
1686 let key = format!("{method}\n{params}");
1690 if let Some(shell) = base.shell(&key) {
1691 return Some(Ok(Box::pin(futures::stream::iter(shell.answer(content)))));
1692 }
1693 let items: Vec<super::types::PlexusStreamItem> = match self.route_ungated(method, params.clone(), auth, raw_ctx).await {
1694 Ok(s) => s.collect().await,
1695 Err(e) => return Some(Err(e)),
1696 };
1697 if let Some(shell) = super::view::Shell::of(&items) {
1698 base.keep_shell(key, shell);
1699 }
1700 Some(Ok(Box::pin(futures::stream::iter(items.into_iter().map(with(content))))))
1701 }
1702
1703 pub async fn service_ir(
1717 &self,
1718 namespaces: &[String],
1719 caller: Option<&super::auth::AuthContext>,
1720 ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
1721 let roots = super::ir::roots(&self.inner.namespace, namespaces);
1722 let view = self.ir_view(caller);
1723 let permitted = match self.inner.scope_registry.is_some() || self.inner.default_deny {
1724 false => None,
1725 true => {
1726 let mut answered = Vec::new();
1730 for name in view.names(&self.inner.namespace) {
1731 let under = roots.iter().any(|r| {
1732 let r = r.join(".");
1733 r.is_empty() || name == r || name.starts_with(&format!("{r}."))
1734 });
1735 if under && self.scope_answers(&self.schema_method(&name), caller).await {
1736 answered.push(name);
1737 }
1738 }
1739 Some(answered)
1740 }
1741 };
1742 let key = super::ir::IrKey { view: view.hash.clone(), roots: roots.clone(), permitted: permitted.clone() };
1743 self.inner
1744 .ir_cache
1745 .get_or_build(key, || async {
1746 let mut schemas: BTreeMap<Vec<String>, Value> = BTreeMap::new();
1747 let mut todo: Vec<Vec<String>> = roots.clone();
1748 while let Some(path) = todo.pop() {
1749 if schemas.contains_key(&path) || permitted.as_ref().is_some_and(|p| !p.contains(&path.join("."))) {
1750 continue;
1751 }
1752 let Some(schema) = self.ir_schema(&view, &path, caller).await else { continue };
1754 for child in schema.get("children").and_then(Value::as_array).into_iter().flatten() {
1755 if let Some(ns) = child.get("namespace").and_then(Value::as_str) {
1756 let mut next = path.clone();
1757 next.push(ns.to_string());
1758 todo.push(next);
1759 }
1760 }
1761 schemas.insert(path, schema);
1762 }
1763 let service = self.inner.namespace.clone();
1764 tokio::task::spawn_blocking(move || super::ir::answer(&service, &roots, &schemas))
1765 .await
1766 .unwrap_or_else(|e| Err(super::ir::IrError::Unreadable { namespace: String::new(), message: format!("the IR's build failed: {e}") }))
1767 })
1768 .await
1769 }
1770
1771 pub fn ir_builds(&self) -> usize {
1774 self.inner.ir_cache.builds()
1775 }
1776
1777 fn ir_view(&self, caller: Option<&super::auth::AuthContext>) -> IrView {
1781 match self.inner.gate {
1782 Some(_) => {
1783 let (base, shaped) = self.shaped(caller);
1784 IrView { hash: shaped.hash.clone(), base, shaped: Some(shaped) }
1785 }
1786 None => {
1787 let base = self.described();
1788 IrView { hash: base.service.hash.clone(), base, shaped: None }
1789 }
1790 }
1791 }
1792
1793 fn schema_method(&self, dotted: &str) -> String {
1795 if dotted.is_empty() { format!("{}.schema", self.inner.namespace) } else { format!("{dotted}.schema") }
1796 }
1797
1798 async fn scope_answers(&self, method: &str, caller: Option<&super::auth::AuthContext>) -> bool {
1801 let registry = self.inner.scope_registry.as_deref().unwrap_or_else(|| super::scope_gate::empty_registry());
1802 super::scope_gate::answers(registry, self.inner.default_deny, method, self.gate_index().get(method), caller).await
1803 }
1804
1805 async fn ir_schema(&self, view: &IrView, path: &[String], caller: Option<&super::auth::AuthContext>) -> Option<Value> {
1810 use futures::StreamExt;
1811 let shown = match path {
1812 [] => Some(view.root()),
1813 [ns] => view.top(ns),
1814 [top, below @ ..] => {
1815 let activation = self.inner.activations.get(top.as_str())?;
1818 let mut stream = activation.call(&format!("{}.schema", below.join(".")), Value::Null, caller, None).await.ok()?;
1819 if let Some(site) = self.derived_site_hint() {
1820 stream = fill_site_hints_in_schema_stream(stream, site);
1821 }
1822 let items: Vec<super::types::PlexusStreamItem> = stream.collect().await;
1823 return items.into_iter().find_map(|item| match item {
1824 super::types::PlexusStreamItem::Data { content_type, content, .. } if content_type.ends_with(".schema") => {
1825 Some(content.into_value())
1826 }
1827 _ => None,
1828 });
1829 }
1830 };
1831 let mut schema = shown?;
1832 if let Some(site) = self.derived_site_hint() {
1833 schema.fill_site_hints(&site);
1834 }
1835 serde_json::to_value(super::SchemaResult::Plugin(schema)).ok()
1836 }
1837
1838 fn check_ir_names(&self, params: &Value, caller: Option<&super::auth::AuthContext>) -> Result<(), PlexusError> {
1842 let asked = match params.get("namespaces") {
1843 None | Some(Value::Null) => return Ok(()),
1844 Some(Value::Array(a)) => a,
1845 Some(_) => return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")),
1846 };
1847 let most = 1 + self.inner.activations.len() + self.inner.nested_count();
1851 if asked.len() > most {
1852 return Err(PlexusError::malformed_param(
1853 "namespaces",
1854 format!("{} namespaces asked; more than this service shows you", asked.len()),
1855 ));
1856 }
1857 let names: std::collections::HashSet<String> = self.ir_view(caller).names(&self.inner.namespace).into_iter().collect();
1858 if asked.len() > names.len() {
1859 return Err(PlexusError::malformed_param(
1860 "namespaces",
1861 format!("{} namespaces asked; this service shows you {}", asked.len(), names.len()),
1862 ));
1863 }
1864 for n in asked {
1865 let Some(n) = n.as_str() else { return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")) };
1866 let known = n == self.inner.namespace || names.contains(n);
1867 if !known {
1868 return Err(PlexusError::malformed_param("namespaces", format!("no namespace `{n}` in this service")));
1869 }
1870 }
1871 Ok(())
1872 }
1873
1874 pub fn declared_roles(&self) -> std::collections::BTreeMap<String, Vec<String>> {
1882 let mut out: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
1883 let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
1886 for schema in schemas {
1887 for (role, grants) in schema.roles {
1888 let entry = out.entry(role).or_default();
1889 for g in grants {
1890 if !entry.contains(&g) {
1891 entry.push(g);
1892 }
1893 }
1894 }
1895 }
1896 out
1897 }
1898
1899 pub fn static_children(&self) -> Vec<PluginSchema> {
1905 self.inner
1906 .activations
1907 .values()
1908 .flat_map(|a| super::children::qualified(&a.plugin_schema().namespace, a.static_child_schemas()))
1909 .collect()
1910 }
1911
1912 pub fn scope_registry(&self) -> Option<&plexus_auth_core::ScopeRegistry> {
1917 self.inner.scope_registry.as_deref()
1918 }
1919
1920 pub(crate) fn input_terms(&self, method: &str, params: &Value) -> Result<InputTerms, PlexusError> {
1924 if self.inner.gate.is_none() {
1925 return Ok(InputTerms { grant: method.to_string(), targets: Vec::new(), recheck: false });
1926 }
1927 let info = self.gate_index().get(method);
1928 let grant = info.and_then(|i| i.grant.clone()).unwrap_or_else(|| method.to_string());
1929 let open = info.is_some_and(|i| i.public) || self.inner.signed_in_grants.contains(grant.as_str());
1930 let targets = match info.and_then(|i| i.target.as_deref()) {
1931 Some(param) => super::grant_gate::target_values(params, param)?.unwrap_or_default(),
1932 None => Vec::new(),
1933 };
1934 Ok(InputTerms { grant, targets, recheck: !open })
1935 }
1936
1937 pub(crate) fn duplex_gate(&self) -> &super::duplex_gate::DuplexGate {
1940 self.inner.duplex_gate.get_or_init(|| match &self.inner.gate {
1941 Some(gate) => {
1942 let (audit, drain) = plexus_auth_core::audit::AuditQueue::new(1024, self.inner.audit_sink.clone());
1943 tokio::spawn(drain);
1944 super::duplex_gate::DuplexGate::new((**gate).clone()).with_audit(audit)
1945 }
1946 None => super::duplex_gate::DuplexGate::ungated(),
1947 })
1948 }
1949
1950 pub(crate) fn may_take_input(&self, method: &str) -> bool {
1955 let index = self.inner.input_index.get_or_init(|| {
1956 let own = Activation::plugin_schema(self).methods.into_iter().map(|m| (format!("{}.{}", self.inner.namespace, m.name), m.input.is_some()));
1957 let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
1958 let theirs = schemas.flat_map(|schema| {
1959 let ns = schema.namespace;
1960 schema.methods.into_iter().map(move |m| (format!("{ns}.{}", m.name), m.input.is_some()))
1961 });
1962 own.chain(theirs).collect()
1963 });
1964 index.get(method).copied().unwrap_or(true)
1965 }
1966
1967 fn gate_index(&self) -> &HashMap<String, super::scope_gate::MethodGateInfo> {
1970 self.inner.gate_index.get_or_init(|| {
1971 let mut index = HashMap::new();
1972 for m in &Activation::plugin_schema(self).methods {
1974 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
1975 info.grant = Some(format!("{}.{}", self.inner.namespace, m.name));
1978 index.insert(format!("{}.{}", self.inner.namespace, m.name), info);
1979 }
1980 let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
1989 for schema in schemas {
1990 for m in &schema.methods {
1991 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
1992 info.grant = Some(m.grant_or(&schema.namespace));
1993 index.insert(format!("{}.{}", schema.namespace, m.name), info);
1994 }
1995 }
1996 index
1997 })
1998 }
1999
2000 pub fn with_forward_policy(
2021 mut self,
2022 callee_ns: impl Into<String>,
2023 policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>,
2024 ) -> Self {
2025 let inner = self.inner_mut("Cannot register forward policy: DynamicHub has multiple references");
2026 inner.forward_policies.register(callee_ns, policy);
2027 self
2028 }
2029
2030 pub fn forward_policies(&self) -> &super::forward_registry::ForwardPolicyRegistry {
2035 &self.inner.forward_policies
2036 }
2037
2038 pub fn with_auth_capabilities(
2074 mut self,
2075 caps: plexus_auth_core::BackendAuthCapabilities,
2076 ) -> Self {
2077 let inner = self.inner_mut("Cannot set auth_capabilities: DynamicHub has multiple references");
2078 inner.auth_capabilities = Some(caps);
2079 self
2080 }
2081
2082 pub fn auth_capabilities(&self) -> Option<&plexus_auth_core::BackendAuthCapabilities> {
2089 self.inner.auth_capabilities.as_ref()
2090 }
2091
2092 #[deprecated(since = "0.3.0", note = "Use DynamicHub::new(namespace) instead")]
2094 pub fn with_namespace(namespace: impl Into<String>) -> Self {
2095 Self::new(namespace)
2096 }
2097
2098 pub fn runtime_namespace(&self) -> &str {
2100 &self.inner.namespace
2101 }
2102
2103 pub fn registry(&self) -> std::sync::RwLockReadGuard<'_, PluginRegistry> {
2105 self.inner.registry.read().unwrap()
2106 }
2107
2108 fn assert_no_root_shadow(&self, child_namespace: &str) {
2119 if child_namespace == self.inner.namespace {
2120 panic!(
2121 "DynamicHub namespace shadow: activation namespace '{child}' collides with the hub root namespace '{root}'. \
2122 The hub root name is a routing namespace, not a label — routing resolves the root first, so a like-named \
2123 child activation is unreachable (every '{child}.<method>' call resolves to the hub root and fails with \
2124 'Command not found', and navigation resolves the child back to the root schema). \
2125 Fix: rename the hub root so it differs from every registered activation's namespace, \
2126 e.g. DynamicHub::new(\"{root}_hub\").register(...). [Z2H-8 / HOSTLESS-3]",
2127 child = child_namespace,
2128 root = self.inner.namespace,
2129 );
2130 }
2131 }
2132
2133 pub fn register<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2142 let namespace = activation.namespace().to_string();
2143 self.assert_no_root_shadow(&namespace);
2144 let plugin_id = activation.plugin_id();
2145 let activation_for_rpc = activation.clone();
2146 let activation_for_router = activation.clone();
2147
2148 let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2149
2150 inner.registry.write().unwrap().register(
2152 plugin_id,
2153 namespace.clone(),
2154 namespace.clone(), );
2156
2157 if let Some(catalog) = inner.auth_catalog.as_ref() {
2160 let schema = activation.plugin_schema();
2161 for child in super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation)) {
2163 catalog.add(&child);
2164 }
2165 catalog.add(&schema);
2166 }
2167 inner.nested_count += Activation::static_child_schemas(&activation).len();
2169 inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
2170 inner.child_routers.insert(namespace.clone(), Arc::new(activation_for_router));
2171 inner.pending_rpc.lock().unwrap()
2172 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2173 self
2174 }
2175
2176 #[deprecated(since = "0.5.0", note = "Use register() — it now handles both leaf and hub activations")]
2186 pub fn register_hub<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2187 let namespace = activation.namespace().to_string();
2188 self.assert_no_root_shadow(&namespace);
2189 let plugin_id = activation.plugin_id();
2190 let activation_for_rpc = activation.clone();
2191 let activation_for_router = activation.clone();
2192
2193 let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2194
2195 inner.registry.write().unwrap().register(
2197 plugin_id,
2198 namespace.clone(),
2199 namespace.clone(), );
2201
2202 if let Some(catalog) = inner.auth_catalog.as_ref() {
2203 let schema = activation.plugin_schema();
2204 for child in super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation)) {
2206 catalog.add(&child);
2207 }
2208 catalog.add(&schema);
2209 }
2210 inner.nested_count += Activation::static_child_schemas(&activation).len();
2212 inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
2213 inner.child_routers.insert(namespace, Arc::new(activation_for_router));
2214 inner.pending_rpc.lock().unwrap()
2215 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2216 self
2217 }
2218
2219 pub fn list_methods(&self) -> Vec<String> {
2221 let mut methods = Vec::new();
2222
2223 for m in Activation::methods(self) {
2225 methods.push(format!("{}.{}", self.inner.namespace, m));
2226 }
2227
2228 for (ns, act) in &self.inner.activations {
2230 for m in act.methods() {
2231 methods.push(format!("{}.{}", ns, m));
2232 }
2233 }
2234 methods.sort();
2235 methods
2236 }
2237
2238 pub fn list_activations_info(&self) -> Vec<ActivationInfo> {
2240 let mut activations = Vec::new();
2241
2242 activations.push(ActivationInfo {
2244 namespace: Activation::namespace(self).to_string(),
2245 version: Activation::version(self).to_string(),
2246 description: Activation::description(self).to_string(),
2247 methods: Activation::methods(self).iter().map(|s| s.to_string()).collect(),
2248 });
2249
2250 for a in self.inner.activations.values() {
2252 activations.push(ActivationInfo {
2253 namespace: a.namespace().to_string(),
2254 version: a.version().to_string(),
2255 description: a.description().to_string(),
2256 methods: a.methods().iter().map(|s| s.to_string()).collect(),
2257 });
2258 }
2259
2260 activations
2261 }
2262
2263 pub fn compute_hash(&self) -> String {
2271 self.described().service.hash.clone()
2273 }
2274
2275 fn own_hash(&self, caller: Option<&super::auth::AuthContext>) -> String {
2279 match self.inner.gate {
2280 Some(_) => self.shaped(caller).1.hash.clone(),
2281 None => self.described().service.hash.clone(),
2282 }
2283 }
2284
2285 fn own_schema(&self, caller: Option<&super::auth::AuthContext>) -> PluginSchema {
2288 match self.inner.gate {
2289 Some(_) => self.shaped(caller).1.service.clone(),
2290 None => self.described().service.clone(),
2291 }
2292 }
2293
2294 pub async fn route(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>) -> Result<PlexusStream, PlexusError> {
2296 self.route_with_ctx(method, params, auth, None).await
2297 }
2298
2299 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> {
2301 if let Some(gate) = self.inner.gate.as_ref() {
2304 let (auth, ended) = super::grant_gate::standing(gate, auth);
2306 let admit = super::grant_gate::decide(
2307 gate,
2308 &self.inner.namespace,
2309 method,
2310 self.gate_index().get(method),
2311 ¶ms,
2312 auth,
2313 &self.inner.signed_in_grants,
2314 )
2315 .map_err(|e| super::grant_gate::say_ended(e, ended.as_deref()))?;
2316 return match admit {
2317 super::grant_gate::Admit::Open => match self.introspect_in_view(method, ¶ms, auth, raw_ctx).await {
2319 Some(answer) => answer,
2320 None => self.route_ungated(method, params, auth, raw_ctx).await,
2321 },
2322 super::grant_gate::Admit::Reach(reach) => {
2323 super::grant_gate::with_reach(reach, self.route_ungated(method, params, auth, raw_ctx)).await
2324 }
2325 };
2326 }
2327 self.route_ungated(method, params, auth, raw_ctx).await
2328 }
2329
2330 async fn route_ungated(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2332 if self.inner.scope_registry.is_some() || self.inner.default_deny {
2337 let registry = self
2338 .inner
2339 .scope_registry
2340 .as_deref()
2341 .unwrap_or_else(|| super::scope_gate::empty_registry());
2342 super::scope_gate::enforce(
2343 registry,
2344 self.inner.default_deny,
2345 &self.inner.audit_sink,
2346 method,
2347 self.gate_index().get(method),
2348 auth,
2349 raw_ctx.and_then(|ctx| ctx.peer.map(|peer| peer.ip())),
2350 )
2351 .await?;
2352 }
2353
2354 let (namespace, method_name) = self.parse_method(method)?;
2355
2356 if namespace == self.inner.namespace && method_name == "ir" {
2358 self.check_ir_names(¶ms, auth)?;
2359 }
2360
2361 let stream = if namespace == self.inner.namespace {
2363 Activation::call(self, method_name, params, auth, raw_ctx).await?
2364 } else {
2365 let activation = self.inner.activations.get(namespace)
2366 .ok_or_else(|| PlexusError::ActivationNotFound(namespace.to_string()))?;
2367
2368 activation.call(method_name, params, auth, raw_ctx).await?
2369 };
2370
2371 if Self::is_schema_query(method_name) {
2378 if let Some(site) = self.derived_site_hint() {
2379 return Ok(fill_site_hints_in_schema_stream(stream, site));
2380 }
2381 }
2382 Ok(stream)
2383 }
2384
2385 fn is_schema_query(method_name: &str) -> bool {
2390 method_name == "schema" || method_name.ends_with(".schema")
2391 }
2392
2393 pub fn derived_site_hint(&self) -> Option<plexus_auth_core::AttachmentSite> {
2399 self.inner
2400 .auth_capabilities
2401 .as_ref()
2402 .and_then(|caps| caps.implied_attachment_site())
2403 }
2404
2405 pub async fn do_resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
2409 let path = self.inner.registry.read().unwrap()
2410 .lookup(handle.plugin_id)
2411 .map(|s| s.to_string())
2412 .ok_or_else(|| PlexusError::ActivationNotFound(handle.plugin_id.to_string()))?;
2413
2414 let activation = self.inner.activations.get(&path)
2415 .ok_or_else(|| PlexusError::ActivationNotFound(path.clone()))?;
2416 activation.resolve_handle(handle).await
2417 }
2418
2419 pub fn get_activation_schema(&self, namespace: &str) -> Option<Schema> {
2421 self.inner.activations.get(namespace).map(|a| a.schema())
2422 }
2423
2424 pub fn registry_snapshot(&self) -> PluginRegistrySnapshot {
2426 let guard = self.inner.registry.read().unwrap();
2427 PluginRegistrySnapshot {
2428 by_id: guard.by_id.clone(),
2429 by_path: guard.by_path.clone(),
2430 }
2431 }
2432
2433 pub fn lookup_plugin(&self, id: uuid::Uuid) -> Option<String> {
2435 self.inner.registry.read().unwrap().lookup(id).map(|s| s.to_string())
2436 }
2437
2438 pub fn lookup_plugin_by_path(&self, path: &str) -> Option<uuid::Uuid> {
2440 self.inner.registry.read().unwrap().lookup_by_path(path)
2441 }
2442
2443 pub fn list_plugin_schemas(&self) -> Vec<PluginSchema> {
2445 let mut schemas = Vec::new();
2446
2447 schemas.push(Activation::plugin_schema(self));
2449
2450 for a in self.inner.activations.values() {
2452 schemas.push(a.plugin_schema());
2453 }
2454
2455 schemas
2456 }
2457
2458 #[deprecated(note = "Use list_plugin_schemas instead")]
2460 pub fn list_full_schemas(&self) -> Vec<PluginSchema> {
2461 self.list_plugin_schemas()
2462 }
2463
2464 pub fn get_method_help(&self, method: &str) -> Option<String> {
2466 let (namespace, method_name) = self.parse_method(method).ok()?;
2467 let activation = self.inner.activations.get(namespace)?;
2468 activation.method_help(method_name)
2469 }
2470
2471 fn parse_method<'a>(&self, method: &'a str) -> Result<(&'a str, &'a str), PlexusError> {
2472 let parts: Vec<&str> = method.splitn(2, '.').collect();
2473 if parts.len() != 2 {
2474 return Err(PlexusError::InvalidParams {
2475 param: Some("method".into()),
2476 problem: ParamProblem::Malformed {
2477 detail: format!("expected `namespace.method`, got `{}`", method),
2478 },
2479 });
2480 }
2481 Ok((parts[0], parts[1]))
2482 }
2483
2484 pub fn plugin_children(&self) -> Vec<ChildSummary> {
2489 self.inner.activations.values()
2490 .map(|a| {
2491 let schema = a.plugin_schema();
2492 ChildSummary {
2493 namespace: schema.namespace,
2494 description: schema.description,
2495 hash: schema.hash,
2496 }
2497 })
2498 .collect()
2499 }
2500
2501 pub fn into_rpc_module(self) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2503 let mut module = RpcModule::new(());
2504
2505 PlexusContext::init(self.compute_hash());
2506
2507 let ns = self.runtime_namespace();
2510 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2511 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2512 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2513 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2514 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2515 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2516 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2517 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2518 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2519
2520 let plexus_for_call = self.clone();
2522 module.register_subscription(
2523 call_method,
2524 PLEXUS_NOTIF_METHOD,
2525 call_unsub,
2526 move |params, pending, _ctx, ext| {
2527 let plexus = plexus_for_call.clone();
2528 let identified = plexus.inner.gate.is_some();
2532 serve_call(plexus, params, pending, ext, ns_static, identified)
2533 }
2534 )?;
2535
2536 register_input_methods(&mut module, ns_static)?;
2537
2538 let plexus_for_hash = self.clone();
2540 module.register_subscription(
2541 hash_method,
2542 PLEXUS_NOTIF_METHOD,
2543 hash_unsub,
2544 move |_params, pending, _ctx, ext| {
2545 let plexus = plexus_for_hash.clone();
2546 Box::pin(async move {
2547 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2549 let value = plexus.own_hash(auth);
2550 let stream = async_stream::stream! {
2551 yield HashEvent::Hash { value };
2552 };
2553 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2554 pipe_stream_to_subscription(pending, wrapped, &ext).await
2555 })
2556 }
2557 )?;
2558
2559 let plexus_for_schema = self.clone();
2561 module.register_subscription(
2562 schema_method,
2563 PLEXUS_NOTIF_METHOD,
2564 schema_unsub,
2565 move |params, pending, _ctx, ext| {
2566 let plexus = plexus_for_schema.clone();
2567 Box::pin(async move {
2568 let p: SchemaParams = params.parse().unwrap_or_default();
2569 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2571 let mut plugin_schema = plexus.own_schema(auth);
2572 if let Some(site) = plexus.derived_site_hint() {
2574 plugin_schema.fill_site_hints(&site);
2575 }
2576
2577 let result = if let Some(ref name) = p.method {
2578 plugin_schema.methods.iter()
2579 .find(|m| m.name == *name)
2580 .map(|m| super::SchemaResult::Method(m.clone()))
2581 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
2582 -32602,
2583 format!("Method '{}' not found", name),
2584 None::<()>,
2585 ))?
2586 } else {
2587 super::SchemaResult::Plugin(plugin_schema)
2588 };
2589
2590 let stream = async_stream::stream! { yield result; };
2591 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
2592 pipe_stream_to_subscription(pending, wrapped, &ext).await
2593 })
2594 }
2595 )?;
2596
2597 let info_payload = build_info_payload(
2603 self.runtime_namespace(),
2604 self.inner.auth_capabilities.as_ref(),
2605 );
2606 let plexus_for_info = self.inner.gate.is_some().then(|| self.clone());
2609 module.register_subscription(
2610 "_info",
2611 PLEXUS_NOTIF_METHOD,
2612 "_info_unsub",
2613 move |_params, pending, _ctx, ext| {
2614 let payload = match plexus_for_info.as_ref() {
2615 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
2616 None => info_payload.clone(),
2617 };
2618 Box::pin(async move {
2619 let info_stream = futures::stream::once(async move { payload });
2621
2622 let wrapped = super::streaming::wrap_stream(
2624 info_stream,
2625 "_info",
2626 vec![]
2627 );
2628
2629 pipe_stream_to_subscription(pending, wrapped, &ext).await
2631 })
2632 }
2633 )?;
2634
2635 let pending = std::mem::take(&mut *self.inner.pending_rpc.lock().unwrap());
2639 if self.inner.gate.is_none() {
2640 for factory in pending {
2641 module.merge(factory())?;
2642 }
2643 }
2644
2645 for (ns, router) in self.inner.child_routers.iter() {
2649 register_child_capability_methods(&mut module, ns, router.clone())?;
2650 }
2651
2652 Ok(module)
2653 }
2654
2655 pub fn arc_into_rpc_module(hub: Arc<Self>) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2661 let mut module = RpcModule::new(());
2662
2663 PlexusContext::init(hub.compute_hash());
2664
2665 let ns = hub.runtime_namespace();
2668 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2669 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2670 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2671 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2672 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2673 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2674 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2675 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2676 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2677
2678 let hub_for_call = hub.clone();
2680 module.register_subscription(
2681 call_method,
2682 call_method,
2683 call_unsub,
2684 move |params, pending, _ctx, ext| {
2685 let hub = hub_for_call.clone();
2686 let hub = (*hub).clone();
2687 serve_call(hub, params, pending, ext, ns_static, true)
2688 }
2689 )?;
2690
2691 register_input_methods(&mut module, ns_static)?;
2692
2693 let hub_for_hash = hub.clone();
2695 module.register_subscription(
2696 hash_method,
2697 PLEXUS_NOTIF_METHOD,
2698 hash_unsub,
2699 move |_params, pending, _ctx, ext| {
2700 let hub = hub_for_hash.clone();
2701 Box::pin(async move {
2702 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2704 let value = hub.own_hash(auth);
2705 let stream = async_stream::stream! {
2706 yield HashEvent::Hash { value };
2707 };
2708 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2709 pipe_stream_to_subscription(pending, wrapped, &ext).await
2710 })
2711 }
2712 )?;
2713
2714 let hub_for_schema = hub.clone();
2716 module.register_subscription(
2717 schema_method,
2718 PLEXUS_NOTIF_METHOD,
2719 schema_unsub,
2720 move |params, pending, _ctx, ext| {
2721 let hub = hub_for_schema.clone();
2722 Box::pin(async move {
2723 let p: SchemaParams = params.parse().unwrap_or_default();
2724 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2726 let mut plugin_schema = hub.own_schema(auth);
2727 if let Some(site) = hub.derived_site_hint() {
2729 plugin_schema.fill_site_hints(&site);
2730 }
2731
2732 let result = if let Some(ref name) = p.method {
2733 plugin_schema.methods.iter()
2734 .find(|m| m.name == *name)
2735 .map(|m| super::SchemaResult::Method(m.clone()))
2736 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
2737 -32602,
2738 format!("Method '{}' not found", name),
2739 None::<()>,
2740 ))?
2741 } else {
2742 super::SchemaResult::Plugin(plugin_schema)
2743 };
2744
2745 let stream = async_stream::stream! {
2746 yield result;
2747 };
2748 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
2749 pipe_stream_to_subscription(pending, wrapped, &ext).await
2750 })
2751 }
2752 )?;
2753
2754 let info_payload = build_info_payload(
2759 hub.runtime_namespace(),
2760 hub.inner.auth_capabilities.as_ref(),
2761 );
2762 let hub_for_info = hub.inner.gate.is_some().then(|| hub.clone());
2765 module.register_subscription(
2766 "_info",
2767 PLEXUS_NOTIF_METHOD,
2768 "_info_unsub",
2769 move |_params, pending, _ctx, ext| {
2770 let payload = match hub_for_info.as_ref() {
2771 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
2772 None => info_payload.clone(),
2773 };
2774 Box::pin(async move {
2775 let info_stream = futures::stream::once(async move { payload });
2777
2778 let wrapped = super::streaming::wrap_stream(
2780 info_stream,
2781 "_info",
2782 vec![]
2783 );
2784
2785 pipe_stream_to_subscription(pending, wrapped, &ext).await
2787 })
2788 }
2789 )?;
2790
2791 let respond_method: &'static str = Box::leak(format!("{}.respond", ns).into_boxed_str());
2794 module.register_async_method(respond_method, |params, _ctx, ext| async move {
2799 use super::bidirectional::{answer_pending, BidirError};
2800
2801 let p: RespondParams = params.parse()?;
2802 let from = ext.get::<jsonrpsee::ConnectionId>().map(|c| c.0);
2803
2804 tracing::debug!(
2805 request_id = %p.request_id,
2806 connection = ?from,
2807 "Handling {}.respond via WebSocket",
2808 "plexus"
2809 );
2810
2811 match answer_pending(&p.request_id, from, p.response_data) {
2812 Ok(()) => Ok(serde_json::json!({"success": true})),
2813 Err(BidirError::NotThisCall) => {
2814 tracing::warn!(request_id = %p.request_id, connection = ?from, "respond from a connection that was not asked");
2815 Err(jsonrpsee::types::ErrorObject::owned(
2816 -32003,
2817 format!("not_this_call: request {} was asked on another connection", p.request_id),
2818 Some(serde_json::json!({"error_kind": "not_this_call", "request_id": p.request_id})),
2819 ))
2820 }
2821 Err(BidirError::UnknownRequest) => {
2822 tracing::warn!(request_id = %p.request_id, "Unknown request ID in respond");
2823 Err(jsonrpsee::types::ErrorObject::owned(
2824 -32602,
2825 format!("Unknown request ID: {}. The request may have timed out or been cancelled.", p.request_id),
2826 None::<()>,
2827 ))
2828 }
2829 Err(BidirError::ChannelClosed) => {
2830 tracing::warn!(request_id = %p.request_id, "Channel closed in respond");
2831 Err(jsonrpsee::types::ErrorObject::owned(
2832 -32000,
2833 "Response channel was closed (request may have timed out)",
2834 None::<()>,
2835 ))
2836 }
2837 Err(e) => {
2838 tracing::error!(request_id = %p.request_id, error = ?e, "Error in respond");
2839 Err(jsonrpsee::types::ErrorObject::owned(
2840 -32000,
2841 format!("Failed to deliver response: {}", e),
2842 None::<()>,
2843 ))
2844 }
2845 }
2846 })?;
2847
2848 let mut pending = std::mem::take(&mut *hub.inner.pending_rpc.lock().unwrap());
2851 if hub.inner.gate.is_some() {
2852 pending.clear();
2853 }
2854 tracing::trace!(factories = pending.len(), "merging activation RPC factories");
2855 for (idx, factory) in pending.into_iter().enumerate() {
2856 tracing::trace!(factory_idx = idx, "calling factory to get Methods");
2857 let methods = factory();
2858 let method_count = methods.method_names().count();
2859 tracing::trace!(factory_idx = idx, methods = method_count, "factory returned Methods; merging into module");
2860 module.merge(methods)?;
2861 tracing::trace!(factory_idx = idx, "successfully merged factory methods");
2862 }
2863 tracing::trace!("all activations merged successfully");
2864
2865 for (ns, router) in hub.inner.child_routers.iter() {
2868 register_child_capability_methods(&mut module, ns, router.clone())?;
2869 }
2870
2871 Ok(module)
2872 }
2873}
2874
2875#[allow(deprecated)] fn register_child_capability_methods(
2890 module: &mut RpcModule<()>,
2891 namespace: &str,
2892 router: Arc<dyn ChildRouter>,
2893) -> Result<(), jsonrpsee::core::RegisterMethodError> {
2894 let caps = router.capabilities();
2895 if caps.is_empty() {
2896 return Ok(());
2897 }
2898
2899 let ns_static: &'static str = Box::leak(namespace.to_string().into_boxed_str());
2900
2901 if caps.contains(ChildCapabilities::LIST) {
2902 let list_method: &'static str =
2903 Box::leak(format!("{}.list_children", namespace).into_boxed_str());
2904 let list_unsub: &'static str =
2905 Box::leak(format!("{}.list_children_unsub", namespace).into_boxed_str());
2906 let router_for_list = router.clone();
2907 module.register_subscription(
2908 list_method,
2909 PLEXUS_NOTIF_METHOD,
2910 list_unsub,
2911 move |_params, pending, _ctx, ext| {
2912 let router = router_for_list.clone();
2913 Box::pin(async move {
2914 let collected: Vec<String> = match router.list_children().await {
2921 Some(mut s) => {
2922 use futures::StreamExt;
2923 let mut acc = Vec::new();
2924 while let Some(name) = s.next().await {
2925 acc.push(name);
2926 }
2927 acc
2928 }
2929 None => Vec::new(),
2930 };
2931 let stream = async_stream::stream! {
2932 for name in collected {
2933 yield name;
2934 }
2935 };
2936 let wrapped = super::streaming::wrap_stream(
2937 stream,
2938 "list_children",
2939 vec![ns_static.into()],
2940 );
2941 pipe_stream_to_subscription(pending, wrapped, &ext).await
2942 })
2943 },
2944 )?;
2945 }
2946
2947 if caps.contains(ChildCapabilities::SEARCH) {
2948 let search_method: &'static str =
2949 Box::leak(format!("{}.search_children", namespace).into_boxed_str());
2950 let search_unsub: &'static str =
2951 Box::leak(format!("{}.search_children_unsub", namespace).into_boxed_str());
2952 let router_for_search = router.clone();
2953 module.register_subscription(
2954 search_method,
2955 PLEXUS_NOTIF_METHOD,
2956 search_unsub,
2957 move |params, pending, _ctx, ext| {
2958 let router = router_for_search.clone();
2959 Box::pin(async move {
2960 let p: SearchChildrenParams = params.parse()?;
2961 let collected: Vec<String> = match router.search_children(&p.query).await {
2962 Some(mut s) => {
2963 use futures::StreamExt;
2964 let mut acc = Vec::new();
2965 while let Some(name) = s.next().await {
2966 acc.push(name);
2967 }
2968 acc
2969 }
2970 None => Vec::new(),
2971 };
2972 let stream = async_stream::stream! {
2973 for name in collected {
2974 yield name;
2975 }
2976 };
2977 let wrapped = super::streaming::wrap_stream(
2978 stream,
2979 "search_children",
2980 vec![ns_static.into()],
2981 );
2982 pipe_stream_to_subscription(pending, wrapped, &ext).await
2983 })
2984 },
2985 )?;
2986 }
2987
2988 Ok(())
2989}
2990
2991#[derive(Debug, serde::Deserialize)]
2993struct SearchChildrenParams {
2994 query: String,
2995}
2996
2997#[derive(Debug, serde::Deserialize)]
2999pub(crate) struct CallParams {
3000 pub(crate) method: String,
3001 #[serde(default)]
3002 pub(crate) params: Option<Value>,
3003}
3004
3005pub(crate) struct InputTerms {
3007 pub(crate) grant: String,
3008 pub(crate) targets: Vec<String>,
3009 pub(crate) recheck: bool,
3010}
3011
3012use super::schema::SchemaParams;
3014
3015#[derive(Debug, serde::Deserialize)]
3017struct RespondParams {
3018 request_id: String,
3019 response_data: Value,
3020}
3021
3022fn serve_call(
3035 service: DynamicHub,
3036 params: jsonrpsee::types::Params<'static>,
3037 pending: jsonrpsee::PendingSubscriptionSink,
3038 ext: http::Extensions,
3039 ns: &'static str,
3040 identified: bool,
3041) -> CallFuture {
3042 let call: CallParams = match params.parse() {
3045 Ok(call) => call,
3046 Err(e) => return Box::pin(async move { Err(e.into()) }),
3047 };
3048 if service.may_take_input(&call.method) {
3049 return Box::pin(serve_seamed(service, call, params, pending, ext, ns, identified));
3050 }
3051 let CallParams { method, params: args } = call;
3052 Box::pin(async move {
3053 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref()) } else { None };
3054 match service.route(&method, args.unwrap_or_default(), caller).await {
3055 Ok(stream) => pipe_stream_to_subscription(pending, stream, &ext).await,
3056 Err(e) => {
3057 let sink = pending.accept().await?;
3058 if let Some(raw) = error_item_raw(ns, &e) {
3059 let _ = sink.send(raw).await;
3060 }
3061 Ok(())
3062 }
3063 }
3064 })
3065}
3066
3067type CallFuture = std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>>;
3070
3071async fn serve_seamed(
3076 service: DynamicHub,
3077 call: CallParams,
3078 params: jsonrpsee::types::Params<'static>,
3079 pending: jsonrpsee::PendingSubscriptionSink,
3080 ext: http::Extensions,
3081 ns: &'static str,
3082 identified: bool,
3083) -> jsonrpsee::core::SubscriptionResult {
3084 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().cloned() } else { None };
3085 let seen = service.inner.gate.as_ref().map_or(0, |g| g.generation().current());
3086 let opened = Arc::new(std::sync::Mutex::new(None::<super::input::Opened>));
3087 let take = || opened.lock().unwrap_or_else(|e| e.into_inner()).take();
3088 let mut scoped = std::pin::pin!(super::input::CALL.scope(
3089 std::cell::RefCell::new(super::input::Seam { service: service.clone(), params, pending: Some(pending), ext, seen, opened: opened.clone(), refused: None }),
3090 service.route(&call.method, call.params.unwrap_or_default(), caller.as_deref()),
3091 ));
3092 let answered = std::future::poll_fn(|cx| match std::future::Future::poll(scoped.as_mut(), cx) {
3097 std::task::Poll::Ready(answer) => std::task::Poll::Ready(Some(answer)),
3098 std::task::Poll::Pending if opened.lock().unwrap_or_else(|e| e.into_inner()).is_some() => std::task::Poll::Ready(None),
3099 std::task::Poll::Pending => std::task::Poll::Pending,
3100 })
3101 .await;
3102 let Some(answer) = answered else {
3103 let super::input::Opened { sink, duplex } = take().expect("opened, the route still resolving");
3104 let mut routing = std::pin::pin!(async { scoped.as_mut().await.map_err(|e| error_item(ns, &e)) });
3105 return Box::pin(super::wire::pipe_duplex(sink, super::wire::Output::Routing(routing.as_mut()), duplex)).await;
3106 };
3107 let super::input::Seam { pending, ext, refused, .. } = scoped.as_mut().take_value().expect("the scope ran to its end").into_inner();
3108 match (answer, take()) {
3109 (Ok(stream), Some(opened)) => Box::pin(super::wire::pipe_duplex(opened.sink, super::wire::Output::Ready(stream), opened.duplex)).await,
3111 (Ok(stream), None) => {
3112 let pending = pending.expect("only an open takes it, and an open is `opened`");
3113 pipe_stream_to_subscription(pending, stream, &ext).await
3114 }
3115 (Err(e), opened) => {
3116 let sink = match (opened, pending) {
3117 (Some(opened), _) => opened.sink,
3118 (None, Some(pending)) => pending.accept().await?,
3119 (None, None) => return Ok(()),
3120 };
3121 let raw = match refused {
3122 Some(item) => serde_json::value::to_raw_value(&item).ok(),
3123 None => error_item_raw(ns, &e),
3124 };
3125 if let Some(raw) = raw {
3126 let _ = sink.send(raw).await;
3127 }
3128 Ok(())
3129 }
3130 }
3131}
3132
3133fn register_input_methods(module: &mut RpcModule<()>, ns: &'static str) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3139 use super::input::{Delivered, InputTable};
3140 use jsonrpsee::types::ErrorObjectOwned;
3141
3142 fn answer(delivered: Delivered) -> Result<bool, ErrorObjectOwned> {
3143 match delivered {
3144 Delivered::Taken => Ok(true),
3145 Delivered::Dropped | Delivered::Refused => Ok(false),
3146 Delivered::NotThisCall => Err(ErrorObjectOwned::owned(
3147 -32003,
3148 "not_this_call: input comes from the connection that opened the call",
3149 Some(serde_json::json!({"error_kind": "not_this_call"})),
3150 )),
3151 Delivered::Malformed => Err(ErrorObjectOwned::owned(-32602, "invalid params: subscription, seq and items", None::<()>)),
3152 }
3153 }
3154 fn table(ext: &http::Extensions) -> Result<&Arc<InputTable>, ErrorObjectOwned> {
3155 ext.get::<super::wire::FrameSink>()
3156 .and_then(super::wire::FrameSink::inputs)
3157 .ok_or_else(|| ErrorObjectOwned::owned(-32601, "this transport carries no input half: call over a WebSocket", None::<()>))
3158 }
3159
3160 let input_method: &'static str = Box::leak(format!("{ns}.input").into_boxed_str());
3161 let end_method: &'static str = Box::leak(format!("{ns}.end").into_boxed_str());
3162 module.register_method(input_method, move |params, _ctx, ext| {
3163 let frame = bytes::Bytes::copy_from_slice(params.as_str().unwrap_or("null").as_bytes());
3164 answer(table(ext)?.input(ns, &frame, &frame))
3165 })?;
3166 module.register_method(end_method, move |params, _ctx, ext| answer(table(ext)?.end(ns, params.as_str().unwrap_or("null").as_bytes())))?;
3167 Ok(())
3168}
3169
3170async fn pipe_stream_to_subscription(
3185 pending: jsonrpsee::PendingSubscriptionSink,
3186 stream: PlexusStream,
3187 ext: &http::Extensions,
3188) -> jsonrpsee::core::SubscriptionResult {
3189 let sink = pending.accept().await?;
3190 super::wire::pipe(sink, stream, ext).await
3191}
3192
3193#[plexus_macros::activation(
3198 namespace = "plexus",
3199 version = "1.0.0",
3200 description = "Central routing and introspection",
3201 hub,
3202 namespace_fn = "runtime_namespace"
3203)]
3204#[allow(deprecated)]
3205impl DynamicHub {
3206 #[plexus_macros::method(
3208 description = "Route a call to a registered activation",
3209 params(
3210 method = "The method to call (format: namespace.method)",
3211 params = "Parameters to pass to the method (optional, defaults to {})"
3212 )
3213 )]
3214 async fn call(
3215 &self,
3216 method: String,
3217 params: Option<Value>,
3218 ) -> impl Stream<Item = super::types::PlexusStreamItem> + Send + 'static {
3219 use super::context::PlexusContext;
3220 use super::types::{PlexusStreamItem, StreamMetadata};
3221
3222 let result = self.route(&method, params.unwrap_or_default(), None).await;
3223
3224 match result {
3225 Ok(plexus_stream) => {
3226 plexus_stream
3228 }
3229 Err(e) => {
3230 let metadata = StreamMetadata::new(
3232 vec![self.inner.namespace.clone()],
3233 PlexusContext::hash(),
3234 );
3235 Box::pin(futures::stream::once(async move {
3236 PlexusStreamItem::from_plexus_error(metadata, &e, false)
3237 }))
3238 }
3239 }
3240 }
3241
3242 #[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.")]
3247 async fn hash(&self) -> impl Stream<Item = HashEvent> + Send + 'static {
3248 let schema = Activation::plugin_schema(self);
3249 stream! { yield HashEvent::Hash { value: schema.hash }; }
3250 }
3251
3252 #[plexus_macros::method(description = "Get plugin hashes for cache validation")]
3254 #[allow(deprecated)]
3255 async fn hashes(&self) -> impl Stream<Item = PluginHashes> + Send + 'static {
3256 let schema = Activation::plugin_schema(self);
3257
3258 stream! {
3259 yield PluginHashes {
3260 namespace: schema.namespace.clone(),
3261 self_hash: schema.self_hash.clone(),
3262 children_hash: schema.children_hash.clone(),
3263 hash: schema.hash.clone(),
3264 children: schema.children.as_ref().map(|kids| {
3265 kids.iter()
3266 .map(|c| ChildHashes {
3267 namespace: c.namespace.clone(),
3268 hash: c.hash.clone(),
3269 })
3270 .collect()
3271 }),
3272 };
3273 }
3274 }
3275
3276 #[plexus_macros::method(
3282 description = "The service's IR (3.0): every type once, each method referring to them — of the namespaces asked, or the whole service",
3283 params(namespaces = "The namespaces (dotted paths) to describe; none: the whole service")
3284 )]
3285 async fn ir(
3286 &self,
3287 auth: Option<&super::auth::AuthContext>,
3288 namespaces: Option<Vec<String>>,
3289 ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
3290 self.service_ir(&namespaces.unwrap_or_default(), auth).await
3291 }
3292
3293 }
3295
3296use super::hub_context::HubContext;
3301use std::sync::Weak;
3302
3303#[async_trait]
3309impl HubContext for Weak<DynamicHub> {
3310 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
3311 let hub = self.upgrade().ok_or_else(|| {
3312 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3313 })?;
3314 hub.do_resolve_handle(handle).await
3315 }
3316
3317 async fn call(&self, method: &str, params: serde_json::Value) -> Result<PlexusStream, PlexusError> {
3318 let hub = self.upgrade().ok_or_else(|| {
3319 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3320 })?;
3321 hub.route(method, params, None).await
3322 }
3323
3324 fn is_valid(&self) -> bool {
3325 self.upgrade().is_some()
3326 }
3327}
3328
3329#[async_trait]
3334impl ChildRouter for DynamicHub {
3335 fn router_namespace(&self) -> &str {
3336 &self.inner.namespace
3337 }
3338
3339 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
3340 self.route_with_ctx(method, params, auth, raw_ctx).await
3343 }
3344
3345 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3346 self.inner.child_routers.get(name)
3348 .map(|router| {
3349 Box::new(ArcChildRouter(router.clone())) as Box<dyn ChildRouter>
3351 })
3352 }
3353
3354 fn forward_policy_for(
3357 &self,
3358 callee_ns: &str,
3359 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
3360 self.inner.forward_policies.get(callee_ns)
3361 }
3362
3363 }
3370
3371#[cfg(test)]
3372#[allow(deprecated)]
3373mod tests {
3374 use super::*;
3375
3376 #[test]
3377 fn dynamic_hub_implements_activation() {
3378 fn assert_activation<T: Activation>() {}
3379 assert_activation::<DynamicHub>();
3380 }
3381
3382 #[test]
3383 fn dynamic_hub_methods() {
3384 let hub = DynamicHub::new("test");
3385 let methods = hub.methods();
3386 assert!(methods.contains(&"call"));
3387 assert!(methods.contains(&"hash"));
3388 assert!(methods.contains(&"schema"));
3389 }
3391
3392 #[test]
3393 fn dynamic_hub_hash_stable() {
3394 let h1 = DynamicHub::new("test");
3395 let h2 = DynamicHub::new("test");
3396 assert_eq!(h1.compute_hash(), h2.compute_hash());
3397 }
3398
3399 #[test]
3400 fn dynamic_hub_is_hub() {
3401 use crate::activations::health::Health;
3402 let hub = DynamicHub::new("test").register(Health::new());
3403 let schema = hub.plugin_schema();
3404
3405 assert!(schema.is_hub(), "dynamic hub should be a hub");
3407 assert!(!schema.is_leaf(), "dynamic hub should not be a leaf");
3408
3409 let children = schema.children.expect("dynamic hub should have children");
3411 assert!(!children.is_empty(), "dynamic hub should have at least one child");
3412
3413 let health = children.iter().find(|c| c.namespace == "health").expect("should have health child");
3415 assert!(!health.hash.is_empty(), "health should have a hash");
3416 }
3417
3418 #[test]
3423 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3424 fn dynamic_hub_rejects_root_namespace_shadow() {
3425 use crate::activations::health::Health;
3426 let _hub = DynamicHub::new("health").register(Health::new());
3427 }
3428
3429 #[test]
3432 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3433 fn dynamic_hub_register_hub_rejects_root_namespace_shadow() {
3434 use crate::activations::health::Health;
3435 let _hub = DynamicHub::new("health").register_hub(Health::new());
3436 }
3437
3438 #[test]
3442 fn dynamic_hub_shadow_error_names_collision_and_fix() {
3443 use crate::activations::health::Health;
3444 let result = std::panic::catch_unwind(|| {
3445 let _hub = DynamicHub::new("health").register(Health::new());
3446 });
3447 let err = result.expect_err("shadow registration must panic");
3448 let msg = err
3449 .downcast_ref::<String>()
3450 .cloned()
3451 .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
3452 .expect("panic payload should be a string");
3453 assert!(msg.contains("'health'"), "must name the colliding namespace: {msg}");
3454 assert!(msg.contains("hub root namespace"), "must name the root side: {msg}");
3455 assert!(msg.contains("rename the hub root"), "must suggest the fix: {msg}");
3456 assert!(msg.contains("Z2H-8"), "must cite the ticket: {msg}");
3457 }
3458
3459 #[test]
3462 fn dynamic_hub_non_colliding_registration_unaffected() {
3463 use crate::activations::health::Health;
3464 let hub = DynamicHub::new("health_hub").register(Health::new());
3465 assert_eq!(hub.runtime_namespace(), "health_hub");
3466 let schema = hub.plugin_schema();
3467 let children = schema.children.expect("hub should have children");
3468 assert!(
3469 children.iter().any(|c| c.namespace == "health"),
3470 "health child must be registered"
3471 );
3472 assert!(hub.list_methods().iter().any(|m| m.starts_with("health.")));
3473 }
3474
3475 #[test]
3476 fn dynamic_hub_schema_structure() {
3477 use crate::activations::health::Health;
3478 let hub = DynamicHub::new("test").register(Health::new());
3479 let schema = hub.plugin_schema();
3480
3481 let json = serde_json::to_string_pretty(&schema).unwrap();
3483 println!("DynamicHub schema:\n{}", json);
3484
3485 assert_eq!(schema.namespace, "test");
3487 assert!(schema.methods.iter().any(|m| m.name == "call"));
3488 assert!(schema.children.is_some());
3489 }
3490
3491 #[tokio::test]
3496 async fn invariant_resolve_handle_unknown_activation() {
3497 use crate::activations::health::Health;
3498 use crate::types::Handle;
3499 use uuid::Uuid;
3500
3501 let hub = DynamicHub::new("test").register(Health::new());
3502
3503 let unknown_plugin_id = Uuid::new_v4();
3505 let handle = Handle::new(unknown_plugin_id, "1.0.0", "some_method");
3506
3507 let result = hub.do_resolve_handle(&handle).await;
3508
3509 match result {
3510 Err(PlexusError::ActivationNotFound(_)) => {
3511 }
3513 Err(other) => panic!("Expected ActivationNotFound, got {:?}", other),
3514 Ok(_) => panic!("Expected error for unknown activation"),
3515 }
3516 }
3517
3518 #[tokio::test]
3519 async fn invariant_resolve_handle_unsupported() {
3520 use crate::activations::health::Health;
3521 use crate::types::Handle;
3522
3523 let hub = DynamicHub::new("test").register(Health::new());
3524
3525 let handle = Handle::new(Health::PLUGIN_ID, "1.0.0", "check");
3527
3528 let result = hub.do_resolve_handle(&handle).await;
3529
3530 match result {
3531 Err(PlexusError::HandleNotSupported(name)) => {
3532 assert_eq!(name, "health");
3533 }
3534 Err(other) => panic!("Expected HandleNotSupported, got {:?}", other),
3535 Ok(_) => panic!("Expected error for unsupported handle"),
3536 }
3537 }
3538
3539 #[tokio::test]
3540 async fn invariant_resolve_handle_routes_by_plugin_id() {
3541 use crate::activations::health::Health;
3542 use crate::activations::echo::EchoActivation;
3543 use crate::types::Handle;
3544 use uuid::Uuid;
3545
3546 let health = Health::new();
3547 let echo = EchoActivation::new();
3548 let health_plugin_id = health.plugin_id();
3549 let echo_plugin_id = echo.plugin_id();
3550
3551 let hub = DynamicHub::new("test")
3552 .register(health)
3553 .register(echo);
3554
3555 let health_handle = Handle::new(health_plugin_id, "1.0.0", "check");
3557 match hub.do_resolve_handle(&health_handle).await {
3558 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "health"),
3559 Err(other) => panic!("health handle should route to health activation, got {:?}", other),
3560 Ok(_) => panic!("health handle should return HandleNotSupported"),
3561 }
3562
3563 let echo_handle = Handle::new(echo_plugin_id, "1.0.0", "echo");
3565 match hub.do_resolve_handle(&echo_handle).await {
3566 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "echo"),
3567 Err(other) => panic!("echo handle should route to echo activation, got {:?}", other),
3568 Ok(_) => panic!("echo handle should return HandleNotSupported"),
3569 }
3570
3571 let unknown_handle = Handle::new(Uuid::new_v4(), "1.0.0", "method");
3573 match hub.do_resolve_handle(&unknown_handle).await {
3574 Err(PlexusError::ActivationNotFound(_)) => { },
3575 Err(other) => panic!("unknown handle should return ActivationNotFound, got {:?}", other),
3576 Ok(_) => panic!("unknown handle should return ActivationNotFound"),
3577 }
3578 }
3579
3580 #[test]
3581 fn invariant_handle_plugin_id_determines_routing() {
3582 use crate::activations::health::Health;
3583 use crate::activations::echo::EchoActivation;
3584 use crate::types::Handle;
3585
3586 let health = Health::new();
3587 let echo = EchoActivation::new();
3588
3589 let health_handle = Handle::new(health.plugin_id(), "1.0.0", "check")
3591 .with_meta(vec!["msg-123".into(), "user".into()]);
3592 let echo_handle = Handle::new(echo.plugin_id(), "1.0.0", "echo")
3593 .with_meta(vec!["msg-123".into(), "user".into()]);
3594
3595 assert_ne!(health_handle.plugin_id, echo_handle.plugin_id);
3597 }
3598
3599 #[test]
3604 fn plugin_registry_basic_operations() {
3605 let mut registry = PluginRegistry::new();
3606 let id = uuid::Uuid::new_v4();
3607
3608 registry.register(id, "test_plugin".to_string(), "test".to_string());
3610
3611 assert_eq!(registry.lookup(id), Some("test_plugin"));
3613
3614 assert_eq!(registry.lookup_by_path("test_plugin"), Some(id));
3616
3617 let entry = registry.get(id).expect("should have entry");
3619 assert_eq!(entry.path, "test_plugin");
3620 assert_eq!(entry.plugin_type, "test");
3621 }
3622
3623 #[test]
3624 fn plugin_registry_populated_on_register() {
3625 use crate::activations::health::Health;
3626
3627 let hub = DynamicHub::new("test").register(Health::new());
3628
3629 let registry = hub.registry();
3630 assert!(!registry.is_empty(), "registry should not be empty after registration");
3631
3632 let health_id = registry.lookup_by_path("health");
3634 assert!(health_id.is_some(), "health should be registered by path");
3635
3636 let health_uuid = health_id.unwrap();
3638 assert_eq!(registry.lookup(health_uuid), Some("health"));
3639 }
3640
3641 #[test]
3642 fn plugin_registry_deterministic_uuid() {
3643 use crate::activations::health::Health;
3644
3645 let health1 = Health::new();
3647 let health2 = Health::new();
3648
3649 assert_eq!(health1.plugin_id(), health2.plugin_id(),
3650 "same activation type should have deterministic UUID");
3651
3652 let expected = uuid::Uuid::new_v5(
3654 &uuid::Uuid::NAMESPACE_OID,
3655 b"health@1"
3656 );
3657 assert_eq!(health1.plugin_id(), expected,
3658 "plugin_id should be deterministic from namespace@major_version");
3659 }
3660
3661 struct MinimalRouter;
3669
3670 #[async_trait]
3671 impl ChildRouter for MinimalRouter {
3672 fn router_namespace(&self) -> &str {
3673 "minimal"
3674 }
3675
3676 async fn router_call(
3677 &self,
3678 _method: &str,
3679 _params: Value,
3680 _auth: Option<&super::super::auth::AuthContext>,
3681 _raw_ctx: Option<&crate::request::RawRequestContext>,
3682 ) -> Result<PlexusStream, PlexusError> {
3683 Err(PlexusError::MethodNotFound {
3684 activation: "minimal".into(),
3685 method: "none".into(),
3686 })
3687 }
3688
3689 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
3690 None
3691 }
3692 }
3693
3694 #[tokio::test]
3695 async fn child_router_defaults_report_no_capabilities_and_none_streams() {
3696 let router = MinimalRouter;
3697
3698 assert_eq!(
3699 router.capabilities(),
3700 ChildCapabilities::empty(),
3701 "default capabilities should be empty"
3702 );
3703 assert!(
3704 router.list_children().await.is_none(),
3705 "default list_children should be None"
3706 );
3707 assert!(
3708 router.search_children("anything").await.is_none(),
3709 "default search_children should be None"
3710 );
3711 }
3712
3713 struct ListingRouter {
3715 names: Vec<String>,
3716 }
3717
3718 #[async_trait]
3719 impl ChildRouter for ListingRouter {
3720 fn router_namespace(&self) -> &str {
3721 "listing"
3722 }
3723
3724 async fn router_call(
3725 &self,
3726 _method: &str,
3727 _params: Value,
3728 _auth: Option<&super::super::auth::AuthContext>,
3729 _raw_ctx: Option<&crate::request::RawRequestContext>,
3730 ) -> Result<PlexusStream, PlexusError> {
3731 Err(PlexusError::MethodNotFound {
3732 activation: "listing".into(),
3733 method: "none".into(),
3734 })
3735 }
3736
3737 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3738 if self.names.iter().any(|n| n == name) {
3739 Some(Box::new(ListingRouter { names: vec![] }))
3742 } else {
3743 None
3744 }
3745 }
3746
3747 fn capabilities(&self) -> ChildCapabilities {
3748 ChildCapabilities::LIST | ChildCapabilities::SEARCH
3749 }
3750
3751 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
3752 let stream = futures::stream::iter(self.names.iter().cloned());
3753 Some(Box::pin(stream))
3754 }
3755
3756 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
3757 let q = query.to_string();
3758 let stream = futures::stream::iter(
3759 self.names
3760 .iter()
3761 .filter(move |n| n.contains(&q))
3762 .cloned()
3763 .collect::<Vec<_>>(),
3764 );
3765 Some(Box::pin(stream))
3766 }
3767 }
3768
3769 #[tokio::test]
3770 async fn child_router_overrides_report_capabilities_and_yield_streams() {
3771 use futures::StreamExt;
3772
3773 let router = ListingRouter {
3774 names: vec!["alpha".into(), "beta".into(), "alphabet".into()],
3775 };
3776
3777 let caps = router.capabilities();
3779 assert!(caps.contains(ChildCapabilities::LIST));
3780 assert!(caps.contains(ChildCapabilities::SEARCH));
3781 assert_eq!(caps, ChildCapabilities::LIST | ChildCapabilities::SEARCH);
3782
3783 let list_stream = router
3785 .list_children()
3786 .await
3787 .expect("LIST capability set — expected Some(stream)");
3788 let listed: Vec<String> = list_stream.collect().await;
3789 assert_eq!(listed, vec!["alpha".to_string(), "beta".into(), "alphabet".into()]);
3790
3791 let search_stream = router
3793 .search_children("alpha")
3794 .await
3795 .expect("SEARCH capability set — expected Some(stream)");
3796 let matched: Vec<String> = search_stream.collect().await;
3797 assert_eq!(matched, vec!["alpha".to_string(), "alphabet".into()]);
3798 }
3799
3800 struct WireFixture {
3815 names: Vec<String>,
3816 caps: ChildCapabilities,
3817 }
3818
3819 #[async_trait]
3820 impl ChildRouter for WireFixture {
3821 fn router_namespace(&self) -> &str {
3822 "wirefixture"
3823 }
3824 async fn router_call(
3825 &self,
3826 _method: &str,
3827 _params: Value,
3828 _auth: Option<&super::super::auth::AuthContext>,
3829 _raw_ctx: Option<&crate::request::RawRequestContext>,
3830 ) -> Result<PlexusStream, PlexusError> {
3831 Err(PlexusError::MethodNotFound {
3832 activation: "wirefixture".into(),
3833 method: "none".into(),
3834 })
3835 }
3836 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
3837 None
3838 }
3839 fn capabilities(&self) -> ChildCapabilities {
3840 self.caps
3841 }
3842 async fn list_children(&self) -> Option<futures_core::stream::BoxStream<'_, String>> {
3843 if !self.caps.contains(ChildCapabilities::LIST) {
3844 return None;
3845 }
3846 Some(Box::pin(futures::stream::iter(self.names.clone())))
3847 }
3848 async fn search_children(
3849 &self,
3850 query: &str,
3851 ) -> Option<futures_core::stream::BoxStream<'_, String>> {
3852 if !self.caps.contains(ChildCapabilities::SEARCH) {
3853 return None;
3854 }
3855 let q = query.to_lowercase();
3856 let filtered: Vec<String> = self
3857 .names
3858 .iter()
3859 .filter(|n| n.to_lowercase().contains(&q))
3860 .cloned()
3861 .collect();
3862 Some(Box::pin(futures::stream::iter(filtered)))
3863 }
3864 }
3865
3866 fn build_module_for(router: WireFixture, ns: &str) -> RpcModule<()> {
3867 let mut module = RpcModule::new(());
3868 let arc: Arc<dyn ChildRouter> = Arc::new(router);
3869 register_child_capability_methods(&mut module, ns, arc).expect("register");
3870 module
3871 }
3872
3873 #[tokio::test]
3874 async fn child_wire_registers_both_methods_when_both_bits_set() {
3875 let module = build_module_for(
3876 WireFixture {
3877 names: vec!["alpha".into(), "beta".into()],
3878 caps: ChildCapabilities::LIST | ChildCapabilities::SEARCH,
3879 },
3880 "fixture",
3881 );
3882 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3883 assert!(
3884 names.contains(&"fixture.list_children".to_string()),
3885 "expected fixture.list_children, got: {:?}",
3886 names
3887 );
3888 assert!(
3889 names.contains(&"fixture.search_children".to_string()),
3890 "expected fixture.search_children, got: {:?}",
3891 names
3892 );
3893 }
3894
3895 #[tokio::test]
3896 async fn child_wire_registers_nothing_when_no_bits_set() {
3897 let module = build_module_for(
3898 WireFixture {
3899 names: vec!["alpha".into()],
3900 caps: ChildCapabilities::empty(),
3901 },
3902 "fixture",
3903 );
3904 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3905 assert!(
3906 !names.contains(&"fixture.list_children".to_string()),
3907 "fixture.list_children should NOT be registered when cap absent"
3908 );
3909 assert!(
3910 !names.contains(&"fixture.search_children".to_string()),
3911 "fixture.search_children should NOT be registered when cap absent"
3912 );
3913 }
3914
3915 #[tokio::test]
3916 async fn child_wire_registers_only_list_when_only_list_bit() {
3917 let module = build_module_for(
3918 WireFixture {
3919 names: vec!["alpha".into()],
3920 caps: ChildCapabilities::LIST,
3921 },
3922 "fixture",
3923 );
3924 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3925 assert!(names.contains(&"fixture.list_children".to_string()));
3926 assert!(!names.contains(&"fixture.search_children".to_string()));
3927 }
3928
3929 }