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 method = self.call_path(method);
1929 let info = self.gate_index().get(method);
1930 let grant = info.and_then(|i| i.grant.clone()).unwrap_or_else(|| method.to_string());
1931 let open = info.is_some_and(|i| i.public) || self.inner.signed_in_grants.contains(grant.as_str());
1932 let targets = match info.and_then(|i| i.target.as_deref()) {
1933 Some(param) => super::grant_gate::target_values(params, param)?.unwrap_or_default(),
1934 None => Vec::new(),
1935 };
1936 Ok(InputTerms { grant, targets, recheck: !open })
1937 }
1938
1939 pub(crate) fn duplex_gate(&self) -> &super::duplex_gate::DuplexGate {
1942 self.inner.duplex_gate.get_or_init(|| match &self.inner.gate {
1943 Some(gate) => {
1944 let (audit, drain) = plexus_auth_core::audit::AuditQueue::new(1024, self.inner.audit_sink.clone());
1945 tokio::spawn(drain);
1946 super::duplex_gate::DuplexGate::new((**gate).clone()).with_audit(audit)
1947 }
1948 None => super::duplex_gate::DuplexGate::ungated(),
1949 })
1950 }
1951
1952 pub(crate) fn may_take_input(&self, method: &str) -> bool {
1957 let index = self.inner.input_index.get_or_init(|| {
1958 let own = Activation::plugin_schema(self).methods.into_iter().map(|m| (format!("{}.{}", self.inner.namespace, m.name), m.input.is_some()));
1959 let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
1960 let theirs = schemas.flat_map(|schema| {
1961 let ns = schema.namespace;
1962 schema.methods.into_iter().map(move |m| (format!("{ns}.{}", m.name), m.input.is_some()))
1963 });
1964 own.chain(theirs).collect()
1965 });
1966 index.get(method).copied().unwrap_or(true)
1967 }
1968
1969 fn gate_index(&self) -> &HashMap<String, super::scope_gate::MethodGateInfo> {
1972 self.inner.gate_index.get_or_init(|| {
1973 let mut index = HashMap::new();
1974 for m in &Activation::plugin_schema(self).methods {
1976 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
1977 info.grant = Some(format!("{}.{}", self.inner.namespace, m.name));
1980 index.insert(format!("{}.{}", self.inner.namespace, m.name), info);
1981 }
1982 let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
1991 for schema in schemas {
1992 for m in &schema.methods {
1993 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
1994 info.grant = Some(m.grant_or(&schema.namespace));
1995 index.insert(format!("{}.{}", schema.namespace, m.name), info);
1996 }
1997 }
1998 index
1999 })
2000 }
2001
2002 pub fn with_forward_policy(
2023 mut self,
2024 callee_ns: impl Into<String>,
2025 policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>,
2026 ) -> Self {
2027 let inner = self.inner_mut("Cannot register forward policy: DynamicHub has multiple references");
2028 inner.forward_policies.register(callee_ns, policy);
2029 self
2030 }
2031
2032 pub fn forward_policies(&self) -> &super::forward_registry::ForwardPolicyRegistry {
2037 &self.inner.forward_policies
2038 }
2039
2040 pub fn with_auth_capabilities(
2076 mut self,
2077 caps: plexus_auth_core::BackendAuthCapabilities,
2078 ) -> Self {
2079 let inner = self.inner_mut("Cannot set auth_capabilities: DynamicHub has multiple references");
2080 inner.auth_capabilities = Some(caps);
2081 self
2082 }
2083
2084 pub fn auth_capabilities(&self) -> Option<&plexus_auth_core::BackendAuthCapabilities> {
2091 self.inner.auth_capabilities.as_ref()
2092 }
2093
2094 #[deprecated(since = "0.3.0", note = "Use DynamicHub::new(namespace) instead")]
2096 pub fn with_namespace(namespace: impl Into<String>) -> Self {
2097 Self::new(namespace)
2098 }
2099
2100 pub fn runtime_namespace(&self) -> &str {
2102 &self.inner.namespace
2103 }
2104
2105 pub fn registry(&self) -> std::sync::RwLockReadGuard<'_, PluginRegistry> {
2107 self.inner.registry.read().unwrap()
2108 }
2109
2110 fn assert_no_root_shadow(&self, child_namespace: &str) {
2121 if child_namespace == self.inner.namespace {
2122 panic!(
2123 "DynamicHub namespace shadow: activation namespace '{child}' collides with the hub root namespace '{root}'. \
2124 The hub root name is a routing namespace, not a label — routing resolves the root first, so a like-named \
2125 child activation is unreachable (every '{child}.<method>' call resolves to the hub root and fails with \
2126 'Command not found', and navigation resolves the child back to the root schema). \
2127 Fix: rename the hub root so it differs from every registered activation's namespace, \
2128 e.g. DynamicHub::new(\"{root}_hub\").register(...). [Z2H-8 / HOSTLESS-3]",
2129 child = child_namespace,
2130 root = self.inner.namespace,
2131 );
2132 }
2133 }
2134
2135 pub fn register<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2144 let namespace = activation.namespace().to_string();
2145 self.assert_no_root_shadow(&namespace);
2146 let plugin_id = activation.plugin_id();
2147 let activation_for_rpc = activation.clone();
2148 let activation_for_router = activation.clone();
2149
2150 let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2151
2152 inner.registry.write().unwrap().register(
2154 plugin_id,
2155 namespace.clone(),
2156 namespace.clone(), );
2158
2159 if let Some(catalog) = inner.auth_catalog.as_ref() {
2162 let schema = activation.plugin_schema();
2163 for child in super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation)) {
2165 catalog.add(&child);
2166 }
2167 catalog.add(&schema);
2168 }
2169 inner.nested_count += Activation::static_child_schemas(&activation).len();
2171 inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
2172 inner.child_routers.insert(namespace.clone(), Arc::new(activation_for_router));
2173 inner.pending_rpc.lock().unwrap()
2174 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2175 self
2176 }
2177
2178 #[deprecated(since = "0.5.0", note = "Use register() — it now handles both leaf and hub activations")]
2188 pub fn register_hub<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2189 let namespace = activation.namespace().to_string();
2190 self.assert_no_root_shadow(&namespace);
2191 let plugin_id = activation.plugin_id();
2192 let activation_for_rpc = activation.clone();
2193 let activation_for_router = activation.clone();
2194
2195 let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2196
2197 inner.registry.write().unwrap().register(
2199 plugin_id,
2200 namespace.clone(),
2201 namespace.clone(), );
2203
2204 if let Some(catalog) = inner.auth_catalog.as_ref() {
2205 let schema = activation.plugin_schema();
2206 for child in super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation)) {
2208 catalog.add(&child);
2209 }
2210 catalog.add(&schema);
2211 }
2212 inner.nested_count += Activation::static_child_schemas(&activation).len();
2214 inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
2215 inner.child_routers.insert(namespace, Arc::new(activation_for_router));
2216 inner.pending_rpc.lock().unwrap()
2217 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2218 self
2219 }
2220
2221 pub fn list_methods(&self) -> Vec<String> {
2223 let mut methods = Vec::new();
2224
2225 for m in Activation::methods(self) {
2227 methods.push(format!("{}.{}", self.inner.namespace, m));
2228 }
2229
2230 for (ns, act) in &self.inner.activations {
2232 for m in act.methods() {
2233 methods.push(format!("{}.{}", ns, m));
2234 }
2235 }
2236 methods.sort();
2237 methods
2238 }
2239
2240 pub fn list_activations_info(&self) -> Vec<ActivationInfo> {
2242 let mut activations = Vec::new();
2243
2244 activations.push(ActivationInfo {
2246 namespace: Activation::namespace(self).to_string(),
2247 version: Activation::version(self).to_string(),
2248 description: Activation::description(self).to_string(),
2249 methods: Activation::methods(self).iter().map(|s| s.to_string()).collect(),
2250 });
2251
2252 for a in self.inner.activations.values() {
2254 activations.push(ActivationInfo {
2255 namespace: a.namespace().to_string(),
2256 version: a.version().to_string(),
2257 description: a.description().to_string(),
2258 methods: a.methods().iter().map(|s| s.to_string()).collect(),
2259 });
2260 }
2261
2262 activations
2263 }
2264
2265 pub fn compute_hash(&self) -> String {
2273 self.described().service.hash.clone()
2275 }
2276
2277 fn own_hash(&self, caller: Option<&super::auth::AuthContext>) -> String {
2281 match self.inner.gate {
2282 Some(_) => self.shaped(caller).1.hash.clone(),
2283 None => self.described().service.hash.clone(),
2284 }
2285 }
2286
2287 fn own_schema(&self, caller: Option<&super::auth::AuthContext>) -> PluginSchema {
2290 match self.inner.gate {
2291 Some(_) => self.shaped(caller).1.service.clone(),
2292 None => self.described().service.clone(),
2293 }
2294 }
2295
2296 pub async fn route(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>) -> Result<PlexusStream, PlexusError> {
2298 self.route_with_ctx(method, params, auth, None).await
2299 }
2300
2301 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> {
2303 if let Some(gate) = self.inner.gate.as_ref() {
2306 let method = self.call_path(method);
2308 let (auth, ended) = super::grant_gate::standing(gate, auth);
2310 let admit = super::grant_gate::decide(
2311 gate,
2312 &self.inner.namespace,
2313 method,
2314 self.gate_index().get(method),
2315 ¶ms,
2316 auth,
2317 &self.inner.signed_in_grants,
2318 )
2319 .map_err(|e| super::grant_gate::say_ended(e, ended.as_deref()))?;
2320 return match admit {
2321 super::grant_gate::Admit::Open => match self.introspect_in_view(method, ¶ms, auth, raw_ctx).await {
2323 Some(answer) => answer,
2324 None => self.route_ungated(method, params, auth, raw_ctx).await,
2325 },
2326 super::grant_gate::Admit::Reach(reach) => {
2327 super::grant_gate::with_reach(reach, self.route_ungated(method, params, auth, raw_ctx)).await
2328 }
2329 };
2330 }
2331 self.route_ungated(method, params, auth, raw_ctx).await
2332 }
2333
2334 fn call_path<'m>(&self, method: &'m str) -> &'m str {
2341 let ns = self.inner.namespace.as_str();
2342 let Some(rest) = method.strip_prefix(ns).and_then(|r| r.strip_prefix('.')) else {
2343 return method;
2344 };
2345 match rest.split_once('.') {
2346 Some((first, _)) if !first.is_empty() && first != ns && first != "schema" && !Activation::methods(self).contains(&first) => rest,
2347 _ => method,
2348 }
2349 }
2350
2351 async fn route_ungated(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2353 if self.inner.scope_registry.is_some() || self.inner.default_deny {
2358 let registry = self
2359 .inner
2360 .scope_registry
2361 .as_deref()
2362 .unwrap_or_else(|| super::scope_gate::empty_registry());
2363 super::scope_gate::enforce(
2364 registry,
2365 self.inner.default_deny,
2366 &self.inner.audit_sink,
2367 method,
2368 self.gate_index().get(method),
2369 auth,
2370 raw_ctx.and_then(|ctx| ctx.peer.map(|peer| peer.ip())),
2371 )
2372 .await?;
2373 }
2374
2375 let (namespace, method_name) = self.parse_method(method)?;
2376
2377 if namespace == self.inner.namespace && method_name == "ir" {
2379 self.check_ir_names(¶ms, auth)?;
2380 }
2381
2382 let stream = if namespace == self.inner.namespace {
2384 Activation::call(self, method_name, params, auth, raw_ctx).await?
2385 } else {
2386 let activation = self.inner.activations.get(namespace)
2387 .ok_or_else(|| PlexusError::ActivationNotFound(namespace.to_string()))?;
2388
2389 activation.call(method_name, params, auth, raw_ctx).await?
2390 };
2391
2392 if Self::is_schema_query(method_name) {
2399 if let Some(site) = self.derived_site_hint() {
2400 return Ok(fill_site_hints_in_schema_stream(stream, site));
2401 }
2402 }
2403 Ok(stream)
2404 }
2405
2406 fn is_schema_query(method_name: &str) -> bool {
2411 method_name == "schema" || method_name.ends_with(".schema")
2412 }
2413
2414 pub fn derived_site_hint(&self) -> Option<plexus_auth_core::AttachmentSite> {
2420 self.inner
2421 .auth_capabilities
2422 .as_ref()
2423 .and_then(|caps| caps.implied_attachment_site())
2424 }
2425
2426 pub async fn do_resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
2430 let path = self.inner.registry.read().unwrap()
2431 .lookup(handle.plugin_id)
2432 .map(|s| s.to_string())
2433 .ok_or_else(|| PlexusError::ActivationNotFound(handle.plugin_id.to_string()))?;
2434
2435 let activation = self.inner.activations.get(&path)
2436 .ok_or_else(|| PlexusError::ActivationNotFound(path.clone()))?;
2437 activation.resolve_handle(handle).await
2438 }
2439
2440 pub fn get_activation_schema(&self, namespace: &str) -> Option<Schema> {
2442 self.inner.activations.get(namespace).map(|a| a.schema())
2443 }
2444
2445 pub fn registry_snapshot(&self) -> PluginRegistrySnapshot {
2447 let guard = self.inner.registry.read().unwrap();
2448 PluginRegistrySnapshot {
2449 by_id: guard.by_id.clone(),
2450 by_path: guard.by_path.clone(),
2451 }
2452 }
2453
2454 pub fn lookup_plugin(&self, id: uuid::Uuid) -> Option<String> {
2456 self.inner.registry.read().unwrap().lookup(id).map(|s| s.to_string())
2457 }
2458
2459 pub fn lookup_plugin_by_path(&self, path: &str) -> Option<uuid::Uuid> {
2461 self.inner.registry.read().unwrap().lookup_by_path(path)
2462 }
2463
2464 pub fn list_plugin_schemas(&self) -> Vec<PluginSchema> {
2466 let mut schemas = Vec::new();
2467
2468 schemas.push(Activation::plugin_schema(self));
2470
2471 for a in self.inner.activations.values() {
2473 schemas.push(a.plugin_schema());
2474 }
2475
2476 schemas
2477 }
2478
2479 #[deprecated(note = "Use list_plugin_schemas instead")]
2481 pub fn list_full_schemas(&self) -> Vec<PluginSchema> {
2482 self.list_plugin_schemas()
2483 }
2484
2485 pub fn get_method_help(&self, method: &str) -> Option<String> {
2487 let (namespace, method_name) = self.parse_method(method).ok()?;
2488 let activation = self.inner.activations.get(namespace)?;
2489 activation.method_help(method_name)
2490 }
2491
2492 fn parse_method<'a>(&self, method: &'a str) -> Result<(&'a str, &'a str), PlexusError> {
2493 let parts: Vec<&str> = method.splitn(2, '.').collect();
2494 if parts.len() != 2 {
2495 return Err(PlexusError::InvalidParams {
2496 param: Some("method".into()),
2497 problem: ParamProblem::Malformed {
2498 detail: format!("expected `namespace.method`, got `{}`", method),
2499 },
2500 });
2501 }
2502 Ok((parts[0], parts[1]))
2503 }
2504
2505 pub fn plugin_children(&self) -> Vec<ChildSummary> {
2510 self.inner.activations.values()
2511 .map(|a| {
2512 let schema = a.plugin_schema();
2513 ChildSummary {
2514 namespace: schema.namespace,
2515 description: schema.description,
2516 hash: schema.hash,
2517 }
2518 })
2519 .collect()
2520 }
2521
2522 pub fn into_rpc_module(self) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2524 let mut module = RpcModule::new(());
2525
2526 PlexusContext::init(self.compute_hash());
2527
2528 let ns = self.runtime_namespace();
2531 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2532 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2533 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2534 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2535 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2536 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2537 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2538 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2539 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2540
2541 let plexus_for_call = self.clone();
2543 module.register_subscription(
2544 call_method,
2545 PLEXUS_NOTIF_METHOD,
2546 call_unsub,
2547 move |params, pending, _ctx, ext| {
2548 let plexus = plexus_for_call.clone();
2549 let identified = plexus.inner.gate.is_some();
2553 serve_call(plexus, params, pending, ext, ns_static, identified)
2554 }
2555 )?;
2556
2557 register_input_methods(&mut module, ns_static)?;
2558
2559 let plexus_for_hash = self.clone();
2561 module.register_subscription(
2562 hash_method,
2563 PLEXUS_NOTIF_METHOD,
2564 hash_unsub,
2565 move |_params, pending, _ctx, ext| {
2566 let plexus = plexus_for_hash.clone();
2567 Box::pin(async move {
2568 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2570 let value = plexus.own_hash(auth);
2571 let stream = async_stream::stream! {
2572 yield HashEvent::Hash { value };
2573 };
2574 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2575 pipe_stream_to_subscription(pending, wrapped, &ext).await
2576 })
2577 }
2578 )?;
2579
2580 let plexus_for_schema = self.clone();
2582 module.register_subscription(
2583 schema_method,
2584 PLEXUS_NOTIF_METHOD,
2585 schema_unsub,
2586 move |params, pending, _ctx, ext| {
2587 let plexus = plexus_for_schema.clone();
2588 Box::pin(async move {
2589 let p: SchemaParams = params.parse().unwrap_or_default();
2590 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2592 let mut plugin_schema = plexus.own_schema(auth);
2593 if let Some(site) = plexus.derived_site_hint() {
2595 plugin_schema.fill_site_hints(&site);
2596 }
2597
2598 let result = if let Some(ref name) = p.method {
2599 plugin_schema.methods.iter()
2600 .find(|m| m.name == *name)
2601 .map(|m| super::SchemaResult::Method(m.clone()))
2602 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
2603 -32602,
2604 format!("Method '{}' not found", name),
2605 None::<()>,
2606 ))?
2607 } else {
2608 super::SchemaResult::Plugin(plugin_schema)
2609 };
2610
2611 let stream = async_stream::stream! { yield result; };
2612 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
2613 pipe_stream_to_subscription(pending, wrapped, &ext).await
2614 })
2615 }
2616 )?;
2617
2618 let info_payload = build_info_payload(
2624 self.runtime_namespace(),
2625 self.inner.auth_capabilities.as_ref(),
2626 );
2627 let plexus_for_info = self.inner.gate.is_some().then(|| self.clone());
2630 module.register_subscription(
2631 "_info",
2632 PLEXUS_NOTIF_METHOD,
2633 "_info_unsub",
2634 move |_params, pending, _ctx, ext| {
2635 let payload = match plexus_for_info.as_ref() {
2636 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
2637 None => info_payload.clone(),
2638 };
2639 Box::pin(async move {
2640 let info_stream = futures::stream::once(async move { payload });
2642
2643 let wrapped = super::streaming::wrap_stream(
2645 info_stream,
2646 "_info",
2647 vec![]
2648 );
2649
2650 pipe_stream_to_subscription(pending, wrapped, &ext).await
2652 })
2653 }
2654 )?;
2655
2656 let pending = std::mem::take(&mut *self.inner.pending_rpc.lock().unwrap());
2660 if self.inner.gate.is_none() {
2661 for factory in pending {
2662 module.merge(factory())?;
2663 }
2664 }
2665
2666 for (ns, router) in self.inner.child_routers.iter() {
2670 register_child_capability_methods(&mut module, ns, router.clone())?;
2671 }
2672
2673 Ok(module)
2674 }
2675
2676 pub fn arc_into_rpc_module(hub: Arc<Self>) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2682 let mut module = RpcModule::new(());
2683
2684 PlexusContext::init(hub.compute_hash());
2685
2686 let ns = hub.runtime_namespace();
2689 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2690 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2691 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2692 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2693 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2694 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2695 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2696 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2697 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2698
2699 let hub_for_call = hub.clone();
2701 module.register_subscription(
2702 call_method,
2703 call_method,
2704 call_unsub,
2705 move |params, pending, _ctx, ext| {
2706 let hub = hub_for_call.clone();
2707 let hub = (*hub).clone();
2708 serve_call(hub, params, pending, ext, ns_static, true)
2709 }
2710 )?;
2711
2712 register_input_methods(&mut module, ns_static)?;
2713
2714 let hub_for_hash = hub.clone();
2716 module.register_subscription(
2717 hash_method,
2718 PLEXUS_NOTIF_METHOD,
2719 hash_unsub,
2720 move |_params, pending, _ctx, ext| {
2721 let hub = hub_for_hash.clone();
2722 Box::pin(async move {
2723 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2725 let value = hub.own_hash(auth);
2726 let stream = async_stream::stream! {
2727 yield HashEvent::Hash { value };
2728 };
2729 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2730 pipe_stream_to_subscription(pending, wrapped, &ext).await
2731 })
2732 }
2733 )?;
2734
2735 let hub_for_schema = hub.clone();
2737 module.register_subscription(
2738 schema_method,
2739 PLEXUS_NOTIF_METHOD,
2740 schema_unsub,
2741 move |params, pending, _ctx, ext| {
2742 let hub = hub_for_schema.clone();
2743 Box::pin(async move {
2744 let p: SchemaParams = params.parse().unwrap_or_default();
2745 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2747 let mut plugin_schema = hub.own_schema(auth);
2748 if let Some(site) = hub.derived_site_hint() {
2750 plugin_schema.fill_site_hints(&site);
2751 }
2752
2753 let result = if let Some(ref name) = p.method {
2754 plugin_schema.methods.iter()
2755 .find(|m| m.name == *name)
2756 .map(|m| super::SchemaResult::Method(m.clone()))
2757 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
2758 -32602,
2759 format!("Method '{}' not found", name),
2760 None::<()>,
2761 ))?
2762 } else {
2763 super::SchemaResult::Plugin(plugin_schema)
2764 };
2765
2766 let stream = async_stream::stream! {
2767 yield result;
2768 };
2769 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
2770 pipe_stream_to_subscription(pending, wrapped, &ext).await
2771 })
2772 }
2773 )?;
2774
2775 let info_payload = build_info_payload(
2780 hub.runtime_namespace(),
2781 hub.inner.auth_capabilities.as_ref(),
2782 );
2783 let hub_for_info = hub.inner.gate.is_some().then(|| hub.clone());
2786 module.register_subscription(
2787 "_info",
2788 PLEXUS_NOTIF_METHOD,
2789 "_info_unsub",
2790 move |_params, pending, _ctx, ext| {
2791 let payload = match hub_for_info.as_ref() {
2792 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
2793 None => info_payload.clone(),
2794 };
2795 Box::pin(async move {
2796 let info_stream = futures::stream::once(async move { payload });
2798
2799 let wrapped = super::streaming::wrap_stream(
2801 info_stream,
2802 "_info",
2803 vec![]
2804 );
2805
2806 pipe_stream_to_subscription(pending, wrapped, &ext).await
2808 })
2809 }
2810 )?;
2811
2812 let respond_method: &'static str = Box::leak(format!("{}.respond", ns).into_boxed_str());
2815 module.register_async_method(respond_method, |params, _ctx, ext| async move {
2820 use super::bidirectional::{answer_pending, BidirError};
2821
2822 let p: RespondParams = params.parse()?;
2823 let from = ext.get::<jsonrpsee::ConnectionId>().map(|c| c.0);
2824
2825 tracing::debug!(
2826 request_id = %p.request_id,
2827 connection = ?from,
2828 "Handling {}.respond via WebSocket",
2829 "plexus"
2830 );
2831
2832 match answer_pending(&p.request_id, from, p.response_data) {
2833 Ok(()) => Ok(serde_json::json!({"success": true})),
2834 Err(BidirError::NotThisCall) => {
2835 tracing::warn!(request_id = %p.request_id, connection = ?from, "respond from a connection that was not asked");
2836 Err(jsonrpsee::types::ErrorObject::owned(
2837 -32003,
2838 format!("not_this_call: request {} was asked on another connection", p.request_id),
2839 Some(serde_json::json!({"error_kind": "not_this_call", "request_id": p.request_id})),
2840 ))
2841 }
2842 Err(BidirError::UnknownRequest) => {
2843 tracing::warn!(request_id = %p.request_id, "Unknown request ID in respond");
2844 Err(jsonrpsee::types::ErrorObject::owned(
2845 -32602,
2846 format!("Unknown request ID: {}. The request may have timed out or been cancelled.", p.request_id),
2847 None::<()>,
2848 ))
2849 }
2850 Err(BidirError::ChannelClosed) => {
2851 tracing::warn!(request_id = %p.request_id, "Channel closed in respond");
2852 Err(jsonrpsee::types::ErrorObject::owned(
2853 -32000,
2854 "Response channel was closed (request may have timed out)",
2855 None::<()>,
2856 ))
2857 }
2858 Err(e) => {
2859 tracing::error!(request_id = %p.request_id, error = ?e, "Error in respond");
2860 Err(jsonrpsee::types::ErrorObject::owned(
2861 -32000,
2862 format!("Failed to deliver response: {}", e),
2863 None::<()>,
2864 ))
2865 }
2866 }
2867 })?;
2868
2869 let mut pending = std::mem::take(&mut *hub.inner.pending_rpc.lock().unwrap());
2872 if hub.inner.gate.is_some() {
2873 pending.clear();
2874 }
2875 tracing::trace!(factories = pending.len(), "merging activation RPC factories");
2876 for (idx, factory) in pending.into_iter().enumerate() {
2877 tracing::trace!(factory_idx = idx, "calling factory to get Methods");
2878 let methods = factory();
2879 let method_count = methods.method_names().count();
2880 tracing::trace!(factory_idx = idx, methods = method_count, "factory returned Methods; merging into module");
2881 module.merge(methods)?;
2882 tracing::trace!(factory_idx = idx, "successfully merged factory methods");
2883 }
2884 tracing::trace!("all activations merged successfully");
2885
2886 for (ns, router) in hub.inner.child_routers.iter() {
2889 register_child_capability_methods(&mut module, ns, router.clone())?;
2890 }
2891
2892 Ok(module)
2893 }
2894}
2895
2896#[allow(deprecated)] fn register_child_capability_methods(
2911 module: &mut RpcModule<()>,
2912 namespace: &str,
2913 router: Arc<dyn ChildRouter>,
2914) -> Result<(), jsonrpsee::core::RegisterMethodError> {
2915 let caps = router.capabilities();
2916 if caps.is_empty() {
2917 return Ok(());
2918 }
2919
2920 let ns_static: &'static str = Box::leak(namespace.to_string().into_boxed_str());
2921
2922 if caps.contains(ChildCapabilities::LIST) {
2923 let list_method: &'static str =
2924 Box::leak(format!("{}.list_children", namespace).into_boxed_str());
2925 let list_unsub: &'static str =
2926 Box::leak(format!("{}.list_children_unsub", namespace).into_boxed_str());
2927 let router_for_list = router.clone();
2928 module.register_subscription(
2929 list_method,
2930 PLEXUS_NOTIF_METHOD,
2931 list_unsub,
2932 move |_params, pending, _ctx, ext| {
2933 let router = router_for_list.clone();
2934 Box::pin(async move {
2935 let collected: Vec<String> = match router.list_children().await {
2942 Some(mut s) => {
2943 use futures::StreamExt;
2944 let mut acc = Vec::new();
2945 while let Some(name) = s.next().await {
2946 acc.push(name);
2947 }
2948 acc
2949 }
2950 None => Vec::new(),
2951 };
2952 let stream = async_stream::stream! {
2953 for name in collected {
2954 yield name;
2955 }
2956 };
2957 let wrapped = super::streaming::wrap_stream(
2958 stream,
2959 "list_children",
2960 vec![ns_static.into()],
2961 );
2962 pipe_stream_to_subscription(pending, wrapped, &ext).await
2963 })
2964 },
2965 )?;
2966 }
2967
2968 if caps.contains(ChildCapabilities::SEARCH) {
2969 let search_method: &'static str =
2970 Box::leak(format!("{}.search_children", namespace).into_boxed_str());
2971 let search_unsub: &'static str =
2972 Box::leak(format!("{}.search_children_unsub", namespace).into_boxed_str());
2973 let router_for_search = router.clone();
2974 module.register_subscription(
2975 search_method,
2976 PLEXUS_NOTIF_METHOD,
2977 search_unsub,
2978 move |params, pending, _ctx, ext| {
2979 let router = router_for_search.clone();
2980 Box::pin(async move {
2981 let p: SearchChildrenParams = params.parse()?;
2982 let collected: Vec<String> = match router.search_children(&p.query).await {
2983 Some(mut s) => {
2984 use futures::StreamExt;
2985 let mut acc = Vec::new();
2986 while let Some(name) = s.next().await {
2987 acc.push(name);
2988 }
2989 acc
2990 }
2991 None => Vec::new(),
2992 };
2993 let stream = async_stream::stream! {
2994 for name in collected {
2995 yield name;
2996 }
2997 };
2998 let wrapped = super::streaming::wrap_stream(
2999 stream,
3000 "search_children",
3001 vec![ns_static.into()],
3002 );
3003 pipe_stream_to_subscription(pending, wrapped, &ext).await
3004 })
3005 },
3006 )?;
3007 }
3008
3009 Ok(())
3010}
3011
3012#[derive(Debug, serde::Deserialize)]
3014struct SearchChildrenParams {
3015 query: String,
3016}
3017
3018#[derive(Debug, serde::Deserialize)]
3020pub(crate) struct CallParams {
3021 pub(crate) method: String,
3022 #[serde(default)]
3023 pub(crate) params: Option<Value>,
3024}
3025
3026pub(crate) struct InputTerms {
3028 pub(crate) grant: String,
3029 pub(crate) targets: Vec<String>,
3030 pub(crate) recheck: bool,
3031}
3032
3033use super::schema::SchemaParams;
3035
3036#[derive(Debug, serde::Deserialize)]
3038struct RespondParams {
3039 request_id: String,
3040 response_data: Value,
3041}
3042
3043fn serve_call(
3056 service: DynamicHub,
3057 params: jsonrpsee::types::Params<'static>,
3058 pending: jsonrpsee::PendingSubscriptionSink,
3059 ext: http::Extensions,
3060 ns: &'static str,
3061 identified: bool,
3062) -> CallFuture {
3063 let call: CallParams = match params.parse() {
3066 Ok(call) => call,
3067 Err(e) => return Box::pin(async move { Err(e.into()) }),
3068 };
3069 if service.may_take_input(&call.method) {
3070 return Box::pin(serve_seamed(service, call, params, pending, ext, ns, identified));
3071 }
3072 let CallParams { method, params: args } = call;
3073 Box::pin(async move {
3074 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref()) } else { None };
3075 match service.route(&method, args.unwrap_or_default(), caller).await {
3076 Ok(stream) => pipe_stream_to_subscription(pending, stream, &ext).await,
3077 Err(e) => {
3078 let sink = pending.accept().await?;
3079 if let Some(raw) = error_item_raw(ns, &e) {
3080 let _ = sink.send(raw).await;
3081 }
3082 Ok(())
3083 }
3084 }
3085 })
3086}
3087
3088type CallFuture = std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>>;
3091
3092async fn serve_seamed(
3097 service: DynamicHub,
3098 call: CallParams,
3099 params: jsonrpsee::types::Params<'static>,
3100 pending: jsonrpsee::PendingSubscriptionSink,
3101 ext: http::Extensions,
3102 ns: &'static str,
3103 identified: bool,
3104) -> jsonrpsee::core::SubscriptionResult {
3105 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().cloned() } else { None };
3106 let seen = service.inner.gate.as_ref().map_or(0, |g| g.generation().current());
3107 let opened = Arc::new(std::sync::Mutex::new(None::<super::input::Opened>));
3108 let take = || opened.lock().unwrap_or_else(|e| e.into_inner()).take();
3109 let mut scoped = std::pin::pin!(super::input::CALL.scope(
3110 std::cell::RefCell::new(super::input::Seam { service: service.clone(), params, pending: Some(pending), ext, seen, opened: opened.clone(), refused: None }),
3111 service.route(&call.method, call.params.unwrap_or_default(), caller.as_deref()),
3112 ));
3113 let answered = std::future::poll_fn(|cx| match std::future::Future::poll(scoped.as_mut(), cx) {
3118 std::task::Poll::Ready(answer) => std::task::Poll::Ready(Some(answer)),
3119 std::task::Poll::Pending if opened.lock().unwrap_or_else(|e| e.into_inner()).is_some() => std::task::Poll::Ready(None),
3120 std::task::Poll::Pending => std::task::Poll::Pending,
3121 })
3122 .await;
3123 let Some(answer) = answered else {
3124 let super::input::Opened { sink, duplex } = take().expect("opened, the route still resolving");
3125 let mut routing = std::pin::pin!(async { scoped.as_mut().await.map_err(|e| error_item(ns, &e)) });
3126 return Box::pin(super::wire::pipe_duplex(sink, super::wire::Output::Routing(routing.as_mut()), duplex)).await;
3127 };
3128 let super::input::Seam { pending, ext, refused, .. } = scoped.as_mut().take_value().expect("the scope ran to its end").into_inner();
3129 match (answer, take()) {
3130 (Ok(stream), Some(opened)) => Box::pin(super::wire::pipe_duplex(opened.sink, super::wire::Output::Ready(stream), opened.duplex)).await,
3132 (Ok(stream), None) => {
3133 let pending = pending.expect("only an open takes it, and an open is `opened`");
3134 pipe_stream_to_subscription(pending, stream, &ext).await
3135 }
3136 (Err(e), opened) => {
3137 let sink = match (opened, pending) {
3138 (Some(opened), _) => opened.sink,
3139 (None, Some(pending)) => pending.accept().await?,
3140 (None, None) => return Ok(()),
3141 };
3142 let raw = match refused {
3143 Some(item) => serde_json::value::to_raw_value(&item).ok(),
3144 None => error_item_raw(ns, &e),
3145 };
3146 if let Some(raw) = raw {
3147 let _ = sink.send(raw).await;
3148 }
3149 Ok(())
3150 }
3151 }
3152}
3153
3154fn register_input_methods(module: &mut RpcModule<()>, ns: &'static str) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3160 use super::input::{Delivered, InputTable};
3161 use jsonrpsee::types::ErrorObjectOwned;
3162
3163 fn answer(delivered: Delivered) -> Result<bool, ErrorObjectOwned> {
3164 match delivered {
3165 Delivered::Taken => Ok(true),
3166 Delivered::Dropped | Delivered::Refused => Ok(false),
3167 Delivered::NotThisCall => Err(ErrorObjectOwned::owned(
3168 -32003,
3169 "not_this_call: input comes from the connection that opened the call",
3170 Some(serde_json::json!({"error_kind": "not_this_call"})),
3171 )),
3172 Delivered::Malformed => Err(ErrorObjectOwned::owned(-32602, "invalid params: subscription, seq and items", None::<()>)),
3173 }
3174 }
3175 fn table(ext: &http::Extensions) -> Result<&Arc<InputTable>, ErrorObjectOwned> {
3176 ext.get::<super::wire::FrameSink>()
3177 .and_then(super::wire::FrameSink::inputs)
3178 .ok_or_else(|| ErrorObjectOwned::owned(-32601, "this transport carries no input half: call over a WebSocket", None::<()>))
3179 }
3180
3181 let input_method: &'static str = Box::leak(format!("{ns}.input").into_boxed_str());
3182 let end_method: &'static str = Box::leak(format!("{ns}.end").into_boxed_str());
3183 module.register_method(input_method, move |params, _ctx, ext| {
3184 let frame = bytes::Bytes::copy_from_slice(params.as_str().unwrap_or("null").as_bytes());
3185 answer(table(ext)?.input(ns, &frame, &frame))
3186 })?;
3187 module.register_method(end_method, move |params, _ctx, ext| answer(table(ext)?.end(ns, params.as_str().unwrap_or("null").as_bytes())))?;
3188 Ok(())
3189}
3190
3191async fn pipe_stream_to_subscription(
3206 pending: jsonrpsee::PendingSubscriptionSink,
3207 stream: PlexusStream,
3208 ext: &http::Extensions,
3209) -> jsonrpsee::core::SubscriptionResult {
3210 let sink = pending.accept().await?;
3211 super::wire::pipe(sink, stream, ext).await
3212}
3213
3214#[plexus_macros::activation(
3219 namespace = "plexus",
3220 version = "1.0.0",
3221 description = "Central routing and introspection",
3222 hub,
3223 namespace_fn = "runtime_namespace"
3224)]
3225#[allow(deprecated)]
3226impl DynamicHub {
3227 #[plexus_macros::method(
3229 description = "Route a call to a registered activation",
3230 params(
3231 method = "The method to call (format: namespace.method)",
3232 params = "Parameters to pass to the method (optional, defaults to {})"
3233 )
3234 )]
3235 async fn call(
3236 &self,
3237 method: String,
3238 params: Option<Value>,
3239 ) -> impl Stream<Item = super::types::PlexusStreamItem> + Send + 'static {
3240 use super::context::PlexusContext;
3241 use super::types::{PlexusStreamItem, StreamMetadata};
3242
3243 let result = self.route(&method, params.unwrap_or_default(), None).await;
3244
3245 match result {
3246 Ok(plexus_stream) => {
3247 plexus_stream
3249 }
3250 Err(e) => {
3251 let metadata = StreamMetadata::new(
3253 vec![self.inner.namespace.clone()],
3254 PlexusContext::hash(),
3255 );
3256 Box::pin(futures::stream::once(async move {
3257 PlexusStreamItem::from_plexus_error(metadata, &e, false)
3258 }))
3259 }
3260 }
3261 }
3262
3263 #[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.")]
3268 async fn hash(&self) -> impl Stream<Item = HashEvent> + Send + 'static {
3269 let schema = Activation::plugin_schema(self);
3270 stream! { yield HashEvent::Hash { value: schema.hash }; }
3271 }
3272
3273 #[plexus_macros::method(description = "Get plugin hashes for cache validation")]
3275 #[allow(deprecated)]
3276 async fn hashes(&self) -> impl Stream<Item = PluginHashes> + Send + 'static {
3277 let schema = Activation::plugin_schema(self);
3278
3279 stream! {
3280 yield PluginHashes {
3281 namespace: schema.namespace.clone(),
3282 self_hash: schema.self_hash.clone(),
3283 children_hash: schema.children_hash.clone(),
3284 hash: schema.hash.clone(),
3285 children: schema.children.as_ref().map(|kids| {
3286 kids.iter()
3287 .map(|c| ChildHashes {
3288 namespace: c.namespace.clone(),
3289 hash: c.hash.clone(),
3290 })
3291 .collect()
3292 }),
3293 };
3294 }
3295 }
3296
3297 #[plexus_macros::method(
3303 description = "The service's IR (3.0): every type once, each method referring to them — of the namespaces asked, or the whole service",
3304 params(namespaces = "The namespaces (dotted paths) to describe; none: the whole service")
3305 )]
3306 async fn ir(
3307 &self,
3308 auth: Option<&super::auth::AuthContext>,
3309 namespaces: Option<Vec<String>>,
3310 ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
3311 self.service_ir(&namespaces.unwrap_or_default(), auth).await
3312 }
3313
3314 }
3316
3317use super::hub_context::HubContext;
3322use std::sync::Weak;
3323
3324#[async_trait]
3330impl HubContext for Weak<DynamicHub> {
3331 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
3332 let hub = self.upgrade().ok_or_else(|| {
3333 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3334 })?;
3335 hub.do_resolve_handle(handle).await
3336 }
3337
3338 async fn call(&self, method: &str, params: serde_json::Value) -> Result<PlexusStream, PlexusError> {
3339 let hub = self.upgrade().ok_or_else(|| {
3340 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3341 })?;
3342 hub.route(method, params, None).await
3343 }
3344
3345 fn is_valid(&self) -> bool {
3346 self.upgrade().is_some()
3347 }
3348}
3349
3350#[async_trait]
3355impl ChildRouter for DynamicHub {
3356 fn router_namespace(&self) -> &str {
3357 &self.inner.namespace
3358 }
3359
3360 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
3361 self.route_with_ctx(method, params, auth, raw_ctx).await
3364 }
3365
3366 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3367 self.inner.child_routers.get(name)
3369 .map(|router| {
3370 Box::new(ArcChildRouter(router.clone())) as Box<dyn ChildRouter>
3372 })
3373 }
3374
3375 fn forward_policy_for(
3378 &self,
3379 callee_ns: &str,
3380 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
3381 self.inner.forward_policies.get(callee_ns)
3382 }
3383
3384 }
3391
3392#[cfg(test)]
3393#[allow(deprecated)]
3394mod tests {
3395 use super::*;
3396
3397 #[test]
3398 fn dynamic_hub_implements_activation() {
3399 fn assert_activation<T: Activation>() {}
3400 assert_activation::<DynamicHub>();
3401 }
3402
3403 #[test]
3404 fn dynamic_hub_methods() {
3405 let hub = DynamicHub::new("test");
3406 let methods = hub.methods();
3407 assert!(methods.contains(&"call"));
3408 assert!(methods.contains(&"hash"));
3409 assert!(methods.contains(&"schema"));
3410 }
3412
3413 #[test]
3414 fn dynamic_hub_hash_stable() {
3415 let h1 = DynamicHub::new("test");
3416 let h2 = DynamicHub::new("test");
3417 assert_eq!(h1.compute_hash(), h2.compute_hash());
3418 }
3419
3420 #[test]
3421 fn dynamic_hub_is_hub() {
3422 use crate::activations::health::Health;
3423 let hub = DynamicHub::new("test").register(Health::new());
3424 let schema = hub.plugin_schema();
3425
3426 assert!(schema.is_hub(), "dynamic hub should be a hub");
3428 assert!(!schema.is_leaf(), "dynamic hub should not be a leaf");
3429
3430 let children = schema.children.expect("dynamic hub should have children");
3432 assert!(!children.is_empty(), "dynamic hub should have at least one child");
3433
3434 let health = children.iter().find(|c| c.namespace == "health").expect("should have health child");
3436 assert!(!health.hash.is_empty(), "health should have a hash");
3437 }
3438
3439 #[test]
3444 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3445 fn dynamic_hub_rejects_root_namespace_shadow() {
3446 use crate::activations::health::Health;
3447 let _hub = DynamicHub::new("health").register(Health::new());
3448 }
3449
3450 #[test]
3453 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3454 fn dynamic_hub_register_hub_rejects_root_namespace_shadow() {
3455 use crate::activations::health::Health;
3456 let _hub = DynamicHub::new("health").register_hub(Health::new());
3457 }
3458
3459 #[test]
3463 fn dynamic_hub_shadow_error_names_collision_and_fix() {
3464 use crate::activations::health::Health;
3465 let result = std::panic::catch_unwind(|| {
3466 let _hub = DynamicHub::new("health").register(Health::new());
3467 });
3468 let err = result.expect_err("shadow registration must panic");
3469 let msg = err
3470 .downcast_ref::<String>()
3471 .cloned()
3472 .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
3473 .expect("panic payload should be a string");
3474 assert!(msg.contains("'health'"), "must name the colliding namespace: {msg}");
3475 assert!(msg.contains("hub root namespace"), "must name the root side: {msg}");
3476 assert!(msg.contains("rename the hub root"), "must suggest the fix: {msg}");
3477 assert!(msg.contains("Z2H-8"), "must cite the ticket: {msg}");
3478 }
3479
3480 #[test]
3483 fn dynamic_hub_non_colliding_registration_unaffected() {
3484 use crate::activations::health::Health;
3485 let hub = DynamicHub::new("health_hub").register(Health::new());
3486 assert_eq!(hub.runtime_namespace(), "health_hub");
3487 let schema = hub.plugin_schema();
3488 let children = schema.children.expect("hub should have children");
3489 assert!(
3490 children.iter().any(|c| c.namespace == "health"),
3491 "health child must be registered"
3492 );
3493 assert!(hub.list_methods().iter().any(|m| m.starts_with("health.")));
3494 }
3495
3496 #[test]
3497 fn dynamic_hub_schema_structure() {
3498 use crate::activations::health::Health;
3499 let hub = DynamicHub::new("test").register(Health::new());
3500 let schema = hub.plugin_schema();
3501
3502 let json = serde_json::to_string_pretty(&schema).unwrap();
3504 println!("DynamicHub schema:\n{}", json);
3505
3506 assert_eq!(schema.namespace, "test");
3508 assert!(schema.methods.iter().any(|m| m.name == "call"));
3509 assert!(schema.children.is_some());
3510 }
3511
3512 #[tokio::test]
3517 async fn invariant_resolve_handle_unknown_activation() {
3518 use crate::activations::health::Health;
3519 use crate::types::Handle;
3520 use uuid::Uuid;
3521
3522 let hub = DynamicHub::new("test").register(Health::new());
3523
3524 let unknown_plugin_id = Uuid::new_v4();
3526 let handle = Handle::new(unknown_plugin_id, "1.0.0", "some_method");
3527
3528 let result = hub.do_resolve_handle(&handle).await;
3529
3530 match result {
3531 Err(PlexusError::ActivationNotFound(_)) => {
3532 }
3534 Err(other) => panic!("Expected ActivationNotFound, got {:?}", other),
3535 Ok(_) => panic!("Expected error for unknown activation"),
3536 }
3537 }
3538
3539 #[tokio::test]
3540 async fn invariant_resolve_handle_unsupported() {
3541 use crate::activations::health::Health;
3542 use crate::types::Handle;
3543
3544 let hub = DynamicHub::new("test").register(Health::new());
3545
3546 let handle = Handle::new(Health::PLUGIN_ID, "1.0.0", "check");
3548
3549 let result = hub.do_resolve_handle(&handle).await;
3550
3551 match result {
3552 Err(PlexusError::HandleNotSupported(name)) => {
3553 assert_eq!(name, "health");
3554 }
3555 Err(other) => panic!("Expected HandleNotSupported, got {:?}", other),
3556 Ok(_) => panic!("Expected error for unsupported handle"),
3557 }
3558 }
3559
3560 #[tokio::test]
3561 async fn invariant_resolve_handle_routes_by_plugin_id() {
3562 use crate::activations::health::Health;
3563 use crate::activations::echo::EchoActivation;
3564 use crate::types::Handle;
3565 use uuid::Uuid;
3566
3567 let health = Health::new();
3568 let echo = EchoActivation::new();
3569 let health_plugin_id = health.plugin_id();
3570 let echo_plugin_id = echo.plugin_id();
3571
3572 let hub = DynamicHub::new("test")
3573 .register(health)
3574 .register(echo);
3575
3576 let health_handle = Handle::new(health_plugin_id, "1.0.0", "check");
3578 match hub.do_resolve_handle(&health_handle).await {
3579 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "health"),
3580 Err(other) => panic!("health handle should route to health activation, got {:?}", other),
3581 Ok(_) => panic!("health handle should return HandleNotSupported"),
3582 }
3583
3584 let echo_handle = Handle::new(echo_plugin_id, "1.0.0", "echo");
3586 match hub.do_resolve_handle(&echo_handle).await {
3587 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "echo"),
3588 Err(other) => panic!("echo handle should route to echo activation, got {:?}", other),
3589 Ok(_) => panic!("echo handle should return HandleNotSupported"),
3590 }
3591
3592 let unknown_handle = Handle::new(Uuid::new_v4(), "1.0.0", "method");
3594 match hub.do_resolve_handle(&unknown_handle).await {
3595 Err(PlexusError::ActivationNotFound(_)) => { },
3596 Err(other) => panic!("unknown handle should return ActivationNotFound, got {:?}", other),
3597 Ok(_) => panic!("unknown handle should return ActivationNotFound"),
3598 }
3599 }
3600
3601 #[test]
3602 fn invariant_handle_plugin_id_determines_routing() {
3603 use crate::activations::health::Health;
3604 use crate::activations::echo::EchoActivation;
3605 use crate::types::Handle;
3606
3607 let health = Health::new();
3608 let echo = EchoActivation::new();
3609
3610 let health_handle = Handle::new(health.plugin_id(), "1.0.0", "check")
3612 .with_meta(vec!["msg-123".into(), "user".into()]);
3613 let echo_handle = Handle::new(echo.plugin_id(), "1.0.0", "echo")
3614 .with_meta(vec!["msg-123".into(), "user".into()]);
3615
3616 assert_ne!(health_handle.plugin_id, echo_handle.plugin_id);
3618 }
3619
3620 #[test]
3625 fn plugin_registry_basic_operations() {
3626 let mut registry = PluginRegistry::new();
3627 let id = uuid::Uuid::new_v4();
3628
3629 registry.register(id, "test_plugin".to_string(), "test".to_string());
3631
3632 assert_eq!(registry.lookup(id), Some("test_plugin"));
3634
3635 assert_eq!(registry.lookup_by_path("test_plugin"), Some(id));
3637
3638 let entry = registry.get(id).expect("should have entry");
3640 assert_eq!(entry.path, "test_plugin");
3641 assert_eq!(entry.plugin_type, "test");
3642 }
3643
3644 #[test]
3645 fn plugin_registry_populated_on_register() {
3646 use crate::activations::health::Health;
3647
3648 let hub = DynamicHub::new("test").register(Health::new());
3649
3650 let registry = hub.registry();
3651 assert!(!registry.is_empty(), "registry should not be empty after registration");
3652
3653 let health_id = registry.lookup_by_path("health");
3655 assert!(health_id.is_some(), "health should be registered by path");
3656
3657 let health_uuid = health_id.unwrap();
3659 assert_eq!(registry.lookup(health_uuid), Some("health"));
3660 }
3661
3662 #[test]
3663 fn plugin_registry_deterministic_uuid() {
3664 use crate::activations::health::Health;
3665
3666 let health1 = Health::new();
3668 let health2 = Health::new();
3669
3670 assert_eq!(health1.plugin_id(), health2.plugin_id(),
3671 "same activation type should have deterministic UUID");
3672
3673 let expected = uuid::Uuid::new_v5(
3675 &uuid::Uuid::NAMESPACE_OID,
3676 b"health@1"
3677 );
3678 assert_eq!(health1.plugin_id(), expected,
3679 "plugin_id should be deterministic from namespace@major_version");
3680 }
3681
3682 struct MinimalRouter;
3690
3691 #[async_trait]
3692 impl ChildRouter for MinimalRouter {
3693 fn router_namespace(&self) -> &str {
3694 "minimal"
3695 }
3696
3697 async fn router_call(
3698 &self,
3699 _method: &str,
3700 _params: Value,
3701 _auth: Option<&super::super::auth::AuthContext>,
3702 _raw_ctx: Option<&crate::request::RawRequestContext>,
3703 ) -> Result<PlexusStream, PlexusError> {
3704 Err(PlexusError::MethodNotFound {
3705 activation: "minimal".into(),
3706 method: "none".into(),
3707 })
3708 }
3709
3710 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
3711 None
3712 }
3713 }
3714
3715 #[tokio::test]
3716 async fn child_router_defaults_report_no_capabilities_and_none_streams() {
3717 let router = MinimalRouter;
3718
3719 assert_eq!(
3720 router.capabilities(),
3721 ChildCapabilities::empty(),
3722 "default capabilities should be empty"
3723 );
3724 assert!(
3725 router.list_children().await.is_none(),
3726 "default list_children should be None"
3727 );
3728 assert!(
3729 router.search_children("anything").await.is_none(),
3730 "default search_children should be None"
3731 );
3732 }
3733
3734 struct ListingRouter {
3736 names: Vec<String>,
3737 }
3738
3739 #[async_trait]
3740 impl ChildRouter for ListingRouter {
3741 fn router_namespace(&self) -> &str {
3742 "listing"
3743 }
3744
3745 async fn router_call(
3746 &self,
3747 _method: &str,
3748 _params: Value,
3749 _auth: Option<&super::super::auth::AuthContext>,
3750 _raw_ctx: Option<&crate::request::RawRequestContext>,
3751 ) -> Result<PlexusStream, PlexusError> {
3752 Err(PlexusError::MethodNotFound {
3753 activation: "listing".into(),
3754 method: "none".into(),
3755 })
3756 }
3757
3758 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3759 if self.names.iter().any(|n| n == name) {
3760 Some(Box::new(ListingRouter { names: vec![] }))
3763 } else {
3764 None
3765 }
3766 }
3767
3768 fn capabilities(&self) -> ChildCapabilities {
3769 ChildCapabilities::LIST | ChildCapabilities::SEARCH
3770 }
3771
3772 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
3773 let stream = futures::stream::iter(self.names.iter().cloned());
3774 Some(Box::pin(stream))
3775 }
3776
3777 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
3778 let q = query.to_string();
3779 let stream = futures::stream::iter(
3780 self.names
3781 .iter()
3782 .filter(move |n| n.contains(&q))
3783 .cloned()
3784 .collect::<Vec<_>>(),
3785 );
3786 Some(Box::pin(stream))
3787 }
3788 }
3789
3790 #[tokio::test]
3791 async fn child_router_overrides_report_capabilities_and_yield_streams() {
3792 use futures::StreamExt;
3793
3794 let router = ListingRouter {
3795 names: vec!["alpha".into(), "beta".into(), "alphabet".into()],
3796 };
3797
3798 let caps = router.capabilities();
3800 assert!(caps.contains(ChildCapabilities::LIST));
3801 assert!(caps.contains(ChildCapabilities::SEARCH));
3802 assert_eq!(caps, ChildCapabilities::LIST | ChildCapabilities::SEARCH);
3803
3804 let list_stream = router
3806 .list_children()
3807 .await
3808 .expect("LIST capability set — expected Some(stream)");
3809 let listed: Vec<String> = list_stream.collect().await;
3810 assert_eq!(listed, vec!["alpha".to_string(), "beta".into(), "alphabet".into()]);
3811
3812 let search_stream = router
3814 .search_children("alpha")
3815 .await
3816 .expect("SEARCH capability set — expected Some(stream)");
3817 let matched: Vec<String> = search_stream.collect().await;
3818 assert_eq!(matched, vec!["alpha".to_string(), "alphabet".into()]);
3819 }
3820
3821 struct WireFixture {
3836 names: Vec<String>,
3837 caps: ChildCapabilities,
3838 }
3839
3840 #[async_trait]
3841 impl ChildRouter for WireFixture {
3842 fn router_namespace(&self) -> &str {
3843 "wirefixture"
3844 }
3845 async fn router_call(
3846 &self,
3847 _method: &str,
3848 _params: Value,
3849 _auth: Option<&super::super::auth::AuthContext>,
3850 _raw_ctx: Option<&crate::request::RawRequestContext>,
3851 ) -> Result<PlexusStream, PlexusError> {
3852 Err(PlexusError::MethodNotFound {
3853 activation: "wirefixture".into(),
3854 method: "none".into(),
3855 })
3856 }
3857 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
3858 None
3859 }
3860 fn capabilities(&self) -> ChildCapabilities {
3861 self.caps
3862 }
3863 async fn list_children(&self) -> Option<futures_core::stream::BoxStream<'_, String>> {
3864 if !self.caps.contains(ChildCapabilities::LIST) {
3865 return None;
3866 }
3867 Some(Box::pin(futures::stream::iter(self.names.clone())))
3868 }
3869 async fn search_children(
3870 &self,
3871 query: &str,
3872 ) -> Option<futures_core::stream::BoxStream<'_, String>> {
3873 if !self.caps.contains(ChildCapabilities::SEARCH) {
3874 return None;
3875 }
3876 let q = query.to_lowercase();
3877 let filtered: Vec<String> = self
3878 .names
3879 .iter()
3880 .filter(|n| n.to_lowercase().contains(&q))
3881 .cloned()
3882 .collect();
3883 Some(Box::pin(futures::stream::iter(filtered)))
3884 }
3885 }
3886
3887 fn build_module_for(router: WireFixture, ns: &str) -> RpcModule<()> {
3888 let mut module = RpcModule::new(());
3889 let arc: Arc<dyn ChildRouter> = Arc::new(router);
3890 register_child_capability_methods(&mut module, ns, arc).expect("register");
3891 module
3892 }
3893
3894 #[tokio::test]
3895 async fn child_wire_registers_both_methods_when_both_bits_set() {
3896 let module = build_module_for(
3897 WireFixture {
3898 names: vec!["alpha".into(), "beta".into()],
3899 caps: ChildCapabilities::LIST | ChildCapabilities::SEARCH,
3900 },
3901 "fixture",
3902 );
3903 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3904 assert!(
3905 names.contains(&"fixture.list_children".to_string()),
3906 "expected fixture.list_children, got: {:?}",
3907 names
3908 );
3909 assert!(
3910 names.contains(&"fixture.search_children".to_string()),
3911 "expected fixture.search_children, got: {:?}",
3912 names
3913 );
3914 }
3915
3916 #[tokio::test]
3917 async fn child_wire_registers_nothing_when_no_bits_set() {
3918 let module = build_module_for(
3919 WireFixture {
3920 names: vec!["alpha".into()],
3921 caps: ChildCapabilities::empty(),
3922 },
3923 "fixture",
3924 );
3925 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3926 assert!(
3927 !names.contains(&"fixture.list_children".to_string()),
3928 "fixture.list_children should NOT be registered when cap absent"
3929 );
3930 assert!(
3931 !names.contains(&"fixture.search_children".to_string()),
3932 "fixture.search_children should NOT be registered when cap absent"
3933 );
3934 }
3935
3936 #[tokio::test]
3937 async fn child_wire_registers_only_list_when_only_list_bit() {
3938 let module = build_module_for(
3939 WireFixture {
3940 names: vec!["alpha".into()],
3941 caps: ChildCapabilities::LIST,
3942 },
3943 "fixture",
3944 );
3945 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3946 assert!(names.contains(&"fixture.list_children".to_string()));
3947 assert!(!names.contains(&"fixture.search_children".to_string()));
3948 }
3949
3950 }