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
285async fn in_child<F>(ctx: Option<crate::call::CallContext>, routed: F) -> Result<PlexusStream, PlexusError>
288where
289 F: std::future::Future<Output = Result<PlexusStream, PlexusError>>,
290{
291 match ctx {
292 Some(ctx) => in_call(ctx, routed).await,
293 None => routed.await,
294 }
295}
296
297async fn in_call<F>(ctx: crate::call::CallContext, routed: F) -> Result<PlexusStream, PlexusError>
301where
302 F: std::future::Future<Output = Result<PlexusStream, PlexusError>>,
303{
304 let stream = crate::call::scope(ctx.clone(), routed).await?;
305 Ok(Box::pin(crate::call::InCall::new(ctx, stream)))
306}
307
308fn plexus_error_code(e: &PlexusError) -> i32 {
317 match e {
318 PlexusError::Unauthenticated(_) => -32001,
319 PlexusError::Forbidden { .. } => -32003,
320 PlexusError::InvalidParams { .. } => -32602,
321 PlexusError::MethodNotFound { .. } | PlexusError::ActivationNotFound(_) => -32601,
322 _ => -32000,
323 }
324}
325
326pub fn plexus_error_to_jsonrpc(e: &PlexusError) -> jsonrpsee::types::ErrorObjectOwned {
337 let error = RemoteError::from(e);
338 jsonrpsee::types::ErrorObject::owned(plexus_error_code(e), error.to_string(), Some(error))
339}
340
341pub(crate) fn error_item_raw(ns: &str, e: &PlexusError) -> Option<Box<serde_json::value::RawValue>> {
347 serde_json::value::to_raw_value(&error_item(ns, e)).ok()
348}
349
350pub fn error_item(ns: &str, e: &PlexusError) -> serde_json::Value {
356 let item = super::types::PlexusStreamItem::from_plexus_error(
359 super::types::StreamMetadata::new(vec![ns.into()], super::context::PlexusContext::hash()),
360 e,
361 false,
362 );
363 serde_json::to_value(&item).unwrap_or(serde_json::Value::Null)
364}
365
366#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
371pub struct ActivationInfo {
372 pub namespace: String,
373 pub version: String,
374 pub description: String,
375 pub methods: Vec<String>,
376}
377
378#[async_trait]
383pub trait Activation: Send + Sync + 'static {
384 type Methods: MethodEnumSchema;
385
386 fn namespace(&self) -> &str;
387 fn version(&self) -> &str;
388 fn description(&self) -> &str { "No description available" }
390 fn long_description(&self) -> Option<&str> { None }
392 fn methods(&self) -> Vec<&str>;
393 fn method_help(&self, _method: &str) -> Option<String> { None }
394 fn plugin_id(&self) -> uuid::Uuid {
398 let major_version = self.version().split('.').next().unwrap_or("0");
399 uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, format!("{}@{}", self.namespace(), major_version).as_bytes())
400 }
401
402 async fn call(
403 &self,
404 method: &str,
405 params: Value,
406 auth: Option<&super::auth::AuthContext>,
407 raw_ctx: Option<&crate::request::RawRequestContext>,
408 ) -> Result<PlexusStream, PlexusError>;
409 async fn resolve_handle(&self, _handle: &Handle) -> Result<PlexusStream, PlexusError> {
410 Err(PlexusError::HandleNotSupported(self.namespace().to_string()))
411 }
412
413 fn into_rpc_methods(self) -> Methods where Self: Sized;
414
415 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
428 Vec::new()
429 }
430
431 fn plugin_schema(&self) -> PluginSchema {
433 let methods: Vec<MethodSchema> = self.methods().iter().map(|name| {
437 let desc = self.method_help(name).unwrap_or_default();
438 MethodSchema::new(name.to_string(), desc, String::new()).with_content_hash()
439 }).collect();
440
441 if let Some(long_desc) = self.long_description() {
442 PluginSchema::leaf_with_long_description(
443 self.namespace(),
444 self.version(),
445 self.description(),
446 long_desc,
447 methods,
448 )
449 } else {
450 PluginSchema::leaf(
451 self.namespace(),
452 self.version(),
453 self.description(),
454 methods,
455 )
456 }
457 }
458}
459
460bitflags! {
465 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
494 #[deprecated(
495 since = "0.5",
496 note = "Use MethodRole::DynamicChild { list_method, search_method } instead. Removed in 0.7."
497 )]
498 pub struct ChildCapabilities: u32 {
499 const LIST = 0b0000_0001;
501 const SEARCH = 0b0000_0010;
504 }
505}
506
507#[async_trait]
524pub trait ChildRouter: Send + Sync {
525 fn router_namespace(&self) -> &str;
527
528 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
530
531 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>>;
533
534 #[allow(deprecated)]
539 fn capabilities(&self) -> ChildCapabilities {
540 ChildCapabilities::empty()
541 }
542
543 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
551 None
552 }
553
554 async fn search_children(&self, _query: &str) -> Option<BoxStream<'_, String>> {
562 None
563 }
564
565 fn forward_policy_for(
580 &self,
581 _callee_ns: &str,
582 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
583 None
584 }
585
586 fn router_schema(&self) -> Option<PluginSchema> {
593 None
594 }
595
596 fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
609 Vec::new()
610 }
611
612 fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
621 plexus_auth_core::Principal::Anonymous
622 }
623}
624
625pub async fn route_to_child<T: ChildRouter + ?Sized>(
656 parent: &T,
657 method: &str,
658 params: Value,
659 auth: Option<&super::auth::AuthContext>,
660 raw_ctx: Option<&crate::request::RawRequestContext>,
661) -> Result<PlexusStream, PlexusError> {
662 if let Some((child_name, rest)) = method.split_once('.') {
664 if let Some(child) = parent.get_child(child_name).await {
665 let policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy> = parent
675 .forward_policy_for(child_name)
676 .unwrap_or_else(|| {
677 std::sync::Arc::new(plexus_auth_core::IdentityOnly)
678 as std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>
679 });
680
681 let callee_method_str = format!("{}.{}", child_name, rest);
687 let callee_method = plexus_auth_core::MethodPath::try_new(callee_method_str.as_str())
688 .map_err(|e| PlexusError::ExecutionError(format!(
689 "framework-built MethodPath rejected: {} ({:?})",
690 callee_method_str, e
691 )))?;
692 let site = plexus_auth_core::CallSite::new(
693 parent.framework_stamped_principal(),
694 callee_method,
695 );
696
697 let anonymous_owned;
701 let caller_ctx: &super::auth::AuthContext = match auth {
702 Some(ctx) => ctx,
703 None => {
704 anonymous_owned = super::auth::AuthContext::anonymous();
705 &anonymous_owned
706 }
707 };
708 let derivation = policy.forward(caller_ctx, &site);
709
710 tracing::trace!(
731 target: "plexus::audit",
732 policy = policy.name().as_str(),
733 callee_method = %site.callee_method.as_str(),
734 derivation_keep_verified_user = derivation.keep_verified_user,
735 derivation_keep_roles = derivation.keep_roles,
736 derivation_keep_capabilities = derivation.keep_capabilities,
737 derivation_keep_metadata = derivation.keep_metadata,
738 "forward_policy_applied (audit-record emission stubbed pending PRIVACY-1)"
739 );
740
741 let outer = crate::call::context().ok();
754 let keeps_identity = derivation.keep_verified_user;
755 return match auth {
756 Some(caller_ctx) => {
757 caller_ctx
758 .with_callee_context(&derivation, &site.caller, |callee_ctx| async move {
759 let ctx = outer.map(|o| o.for_child(Some(&callee_ctx), keeps_identity));
760 in_child(ctx, child.router_call(rest, params, Some(&callee_ctx), raw_ctx)).await
761 })
762 .await
763 }
764 None => {
765 let ctx = outer.map(|o| o.for_child(None, keeps_identity));
766 in_child(ctx, child.router_call(rest, params, None, raw_ctx)).await
767 }
768 };
769 }
770 return Err(PlexusError::ActivationNotFound(child_name.to_string()));
771 }
772
773 Err(PlexusError::MethodNotFound {
775 activation: parent.router_namespace().to_string(),
776 method: method.to_string(),
777 })
778}
779
780struct ArcChildRouter(Arc<dyn ChildRouter>);
784
785#[async_trait]
786impl ChildRouter for ArcChildRouter {
787 fn router_namespace(&self) -> &str {
788 self.0.router_namespace()
789 }
790
791 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
792 self.0.router_call(method, params, auth, raw_ctx).await
793 }
794
795 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
796 self.0.get_child(name).await
797 }
798
799 #[allow(deprecated)]
800 fn capabilities(&self) -> ChildCapabilities {
801 self.0.capabilities()
802 }
803
804 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
805 self.0.list_children().await
806 }
807
808 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
809 self.0.search_children(query).await
810 }
811
812 fn forward_policy_for(
816 &self,
817 callee_ns: &str,
818 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
819 self.0.forward_policy_for(callee_ns)
820 }
821
822 fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
823 self.0.framework_stamped_principal()
824 }
825
826 fn router_schema(&self) -> Option<PluginSchema> {
827 self.0.router_schema()
828 }
829
830 fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
831 self.0.router_static_child_schemas()
832 }
833}
834
835#[async_trait]
840#[allow(dead_code)] trait ActivationObject: Send + Sync + 'static {
842 fn namespace(&self) -> &str;
843 fn version(&self) -> &str;
844 fn description(&self) -> &str;
845 fn long_description(&self) -> Option<&str>;
846 fn methods(&self) -> Vec<&str>;
847 fn method_help(&self, method: &str) -> Option<String>;
848 fn plugin_id(&self) -> uuid::Uuid;
849 async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
850 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError>;
851 fn plugin_schema(&self) -> PluginSchema;
852 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)>;
853 fn schema(&self) -> Schema;
854}
855
856struct ActivationWrapper<A: Activation> {
857 inner: A,
858}
859
860#[async_trait]
861impl<A: Activation> ActivationObject for ActivationWrapper<A> {
862 fn namespace(&self) -> &str { self.inner.namespace() }
863 fn version(&self) -> &str { self.inner.version() }
864 fn description(&self) -> &str { self.inner.description() }
865 fn long_description(&self) -> Option<&str> { self.inner.long_description() }
866 fn methods(&self) -> Vec<&str> { self.inner.methods() }
867 fn method_help(&self, method: &str) -> Option<String> { self.inner.method_help(method) }
868 fn plugin_id(&self) -> uuid::Uuid { self.inner.plugin_id() }
869
870 async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
871 self.inner.call(method, params, auth, raw_ctx).await
872 }
873
874 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
875 self.inner.resolve_handle(handle).await
876 }
877
878 fn plugin_schema(&self) -> PluginSchema { self.inner.plugin_schema() }
879
880 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> { self.inner.static_child_schemas() }
881
882 fn schema(&self) -> Schema {
883 let schema = schemars::schema_for!(A::Methods);
884 serde_json::from_value(serde_json::to_value(schema).expect("serialize"))
885 .expect("parse schema")
886 }
887}
888
889#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
894#[serde(tag = "event", rename_all = "snake_case")]
895pub enum HashEvent {
896 Hash { value: String },
897}
898
899#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
901#[serde(tag = "event", rename_all = "snake_case")]
902pub enum SchemaEvent {
903 Schema(PluginSchema),
905}
906
907#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
909pub struct PluginHashes {
910 pub namespace: String,
911 pub self_hash: String,
912 #[serde(skip_serializing_if = "Option::is_none")]
913 pub children_hash: Option<String>,
914 pub hash: String,
915 #[serde(skip_serializing_if = "Option::is_none")]
917 pub children: Option<Vec<ChildHashes>>,
918}
919
920#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
922pub struct ChildHashes {
923 pub namespace: String,
924 pub hash: String,
925}
926
927
928#[derive(Debug, Clone)]
934pub struct PluginEntry {
935 pub id: uuid::Uuid,
937 pub path: String,
939 pub plugin_type: String,
941}
942
943#[derive(Default)]
948pub struct PluginRegistry {
949 by_id: HashMap<uuid::Uuid, PluginEntry>,
951 by_path: HashMap<String, uuid::Uuid>,
953}
954
955#[derive(Clone)]
959pub struct PluginRegistrySnapshot {
960 by_id: HashMap<uuid::Uuid, PluginEntry>,
961 by_path: HashMap<String, uuid::Uuid>,
962}
963
964impl PluginRegistrySnapshot {
965 pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
967 self.by_id.get(&id).map(|e| e.path.as_str())
968 }
969
970 pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
972 self.by_path.get(path).copied()
973 }
974
975 pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
977 self.by_id.get(&id)
978 }
979
980 pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
982 self.by_id.values()
983 }
984
985 pub fn len(&self) -> usize {
987 self.by_id.len()
988 }
989
990 pub fn is_empty(&self) -> bool {
992 self.by_id.is_empty()
993 }
994}
995
996impl PluginRegistry {
997 pub fn new() -> Self {
999 Self::default()
1000 }
1001
1002 pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
1004 self.by_id.get(&id).map(|e| e.path.as_str())
1005 }
1006
1007 pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
1009 self.by_path.get(path).copied()
1010 }
1011
1012 pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
1014 self.by_id.get(&id)
1015 }
1016
1017 pub fn register(&mut self, id: uuid::Uuid, path: String, plugin_type: String) {
1019 let entry = PluginEntry { id, path: path.clone(), plugin_type };
1020 self.by_id.insert(id, entry);
1021 self.by_path.insert(path, id);
1022 }
1023
1024 pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
1026 self.by_id.values()
1027 }
1028
1029 pub fn len(&self) -> usize {
1031 self.by_id.len()
1032 }
1033
1034 pub fn is_empty(&self) -> bool {
1036 self.by_id.is_empty()
1037 }
1038}
1039
1040fn build_info_payload(
1053 namespace: &str,
1054 caps: Option<&plexus_auth_core::BackendAuthCapabilities>,
1055) -> serde_json::Value {
1056 let advertised = match caps {
1057 Some(c) => c.clone(),
1058 None => plexus_auth_core::BackendAuthCapabilities::anonymous_default(),
1059 };
1060 serde_json::json!({
1061 "backend": namespace,
1062 "auth_capabilities": advertised,
1063 })
1064}
1065
1066fn fill_site_hints_in_schema_stream(
1077 stream: PlexusStream,
1078 site: plexus_auth_core::AttachmentSite,
1079) -> PlexusStream {
1080 use futures::StreamExt;
1081 Box::pin(stream.map(move |item| match item {
1082 super::types::PlexusStreamItem::Data {
1083 metadata,
1084 content_type,
1085 content,
1086 } if content_type.ends_with(".schema") || content_type.ends_with(".method_schema") => {
1087 let content = match content.decode::<super::SchemaResult>() {
1089 Ok(mut result) => {
1090 result.fill_site_hints(&site);
1091 match serde_json::to_value(&result) {
1092 Ok(v) => v.into(),
1093 Err(_) => content,
1094 }
1095 }
1096 Err(_) => content,
1097 };
1098 super::types::PlexusStreamItem::Data {
1099 metadata,
1100 content_type,
1101 content,
1102 }
1103 }
1104 other => other,
1105 }))
1106}
1107
1108struct DynamicHubInner {
1109 namespace: String,
1111 activations: BTreeMap<String, Arc<dyn ActivationObject>>,
1120 child_routers: BTreeMap<String, Arc<dyn ChildRouter>>,
1123 registry: std::sync::RwLock<PluginRegistry>,
1125 pending_rpc: std::sync::Mutex<Vec<Box<dyn FnOnce() -> Methods + Send>>>,
1126 auth_capabilities: Option<plexus_auth_core::BackendAuthCapabilities>,
1137 forward_policies: super::forward_registry::ForwardPolicyRegistry,
1146 scope_registry: Option<Arc<plexus_auth_core::ScopeRegistry>>,
1152 default_deny: bool,
1159 audit_sink: Arc<dyn plexus_auth_core::AuditSink>,
1165 duplex_gate: std::sync::OnceLock<super::duplex_gate::DuplexGate>,
1167 gate_index: std::sync::OnceLock<HashMap<String, super::scope_gate::MethodGateInfo>>,
1175 input_index: std::sync::OnceLock<HashMap<String, bool>>,
1179 gate: Option<Arc<plexus_auth_core::grants::Gate>>,
1183 signed_in_grants: std::collections::BTreeSet<String>,
1187 resource_metadata: Option<String>,
1190 auth_catalog: Option<super::auth_activation::Catalog>,
1194 describe: super::view::Cache,
1198 ir_cache: super::ir::IrCache,
1201 nested_count: usize,
1205}
1206
1207impl DynamicHubInner {
1208 fn nested_count(&self) -> usize {
1209 self.nested_count
1210 }
1211}
1212
1213#[derive(Clone)]
1235pub struct DynamicHub {
1236 inner: Arc<DynamicHubInner>,
1237}
1238
1239struct IrView {
1241 base: Arc<super::view::Described>,
1242 shaped: Option<Arc<super::view::Shaped>>,
1244 hash: String,
1246}
1247
1248impl IrView {
1249 fn root(&self) -> PluginSchema {
1250 match &self.shaped {
1251 Some(v) => v.service.clone(),
1252 None => self.base.service.clone(),
1253 }
1254 }
1255
1256 fn top(&self, ns: &str) -> Option<PluginSchema> {
1257 match &self.shaped {
1258 Some(v) => v.schema_of(&self.base, ns).filter(|_| ns != v.service.namespace),
1259 None => self.base.activations.iter().find(|a| a.namespace == ns).cloned(),
1260 }
1261 }
1262
1263 fn shows(&self, ns: &str) -> bool {
1264 match &self.shaped {
1265 Some(v) => v.shows(ns),
1266 None => self.base.activations.iter().any(|a| a.namespace == ns),
1267 }
1268 }
1269
1270 fn names(&self, service: &str) -> Vec<String> {
1274 let mut out = vec![String::new()];
1275 out.extend(self.base.activations.iter().map(|a| a.namespace.clone()).filter(|ns| ns != service && self.shows(ns)));
1276 for path in self.base.nested() {
1277 let mut segs = path.split('.');
1278 let (Some(top), Some(entry)) = (segs.next(), segs.next()) else { continue };
1279 let reached = self.shows(top)
1280 && match &self.shaped {
1281 Some(v) => v.method_of(&self.base, top, entry).is_some(),
1282 None => true,
1283 };
1284 if reached {
1285 out.push(path.to_string());
1286 }
1287 }
1288 out
1289 }
1290}
1291
1292impl DynamicHub {
1297 pub fn new(namespace: impl Into<String>) -> Self {
1323 Self {
1324 inner: Arc::new(DynamicHubInner {
1325 namespace: namespace.into(),
1326 activations: BTreeMap::new(),
1327 child_routers: BTreeMap::new(),
1328 registry: std::sync::RwLock::new(PluginRegistry::new()),
1329 pending_rpc: std::sync::Mutex::new(Vec::new()),
1330 auth_capabilities: None,
1331 forward_policies: super::forward_registry::ForwardPolicyRegistry::new(),
1332 scope_registry: None,
1333 default_deny: false,
1334 audit_sink: Arc::new(plexus_auth_core::TracingAuditSink),
1335 duplex_gate: std::sync::OnceLock::new(),
1336 gate_index: std::sync::OnceLock::new(),
1337 input_index: std::sync::OnceLock::new(),
1338 gate: None,
1339 signed_in_grants: std::collections::BTreeSet::new(),
1340 resource_metadata: None,
1341 auth_catalog: None,
1342 describe: Default::default(),
1343 ir_cache: Default::default(),
1344 nested_count: Default::default(),
1345 }),
1346 }
1347 }
1348
1349 fn inner_mut(&mut self, refused: &str) -> &mut DynamicHubInner {
1354 let inner = Arc::get_mut(&mut self.inner).expect(refused);
1355 inner.describe.reset();
1356 inner
1357 }
1358
1359 pub fn with_scope_registry(mut self, registry: plexus_auth_core::ScopeRegistry) -> Self {
1379 let inner = self.inner_mut("Cannot set scope_registry: DynamicHub has multiple references");
1380 inner.scope_registry = Some(Arc::new(registry));
1381 self
1382 }
1383
1384 pub fn with_default_deny(mut self, default_deny: bool) -> Self {
1403 let inner = self.inner_mut("Cannot set default_deny: DynamicHub has multiple references");
1404 inner.default_deny = default_deny;
1405 self
1406 }
1407
1408 pub fn with_audit_sink(mut self, sink: Arc<dyn plexus_auth_core::AuditSink>) -> Self {
1419 let inner = self.inner_mut("Cannot set audit_sink: DynamicHub has multiple references");
1420 inner.audit_sink = sink;
1421 self
1422 }
1423
1424 pub fn with_gate(mut self, gate: Arc<plexus_auth_core::grants::Gate>) -> Self {
1449 let inner = self.inner_mut("Cannot set gate: DynamicHub has multiple references");
1450 inner.gate = Some(gate);
1451 self
1452 }
1453
1454 pub fn gate(&self) -> Option<&Arc<plexus_auth_core::grants::Gate>> {
1456 self.inner.gate.as_ref()
1457 }
1458
1459 pub fn with_resource_metadata(mut self, url: impl Into<String>) -> Self {
1464 let inner = self.inner_mut("Cannot set resource_metadata: DynamicHub has multiple references");
1465 inner.resource_metadata = Some(url.into());
1466 self
1467 }
1468
1469 pub fn with_signed_in_grants<I, S>(mut self, grants: I) -> Self
1476 where
1477 I: IntoIterator<Item = S>,
1478 S: Into<String>,
1479 {
1480 let inner = self.inner_mut("Cannot set signed_in grants: DynamicHub has multiple references");
1481 inner.signed_in_grants.extend(grants.into_iter().map(Into::into));
1482 self
1483 }
1484
1485 pub fn with_auth(mut self, setup: super::auth_activation::AuthSetup) -> Self {
1502 let catalog = super::auth_activation::Catalog::default();
1503 catalog.add(&Activation::plugin_schema(&self));
1504 for a in self.inner.activations.values() {
1505 catalog.add(&a.plugin_schema());
1506 }
1507 for child in self.static_children() {
1509 catalog.add(&child);
1510 }
1511 let (auth, gate) = super::auth_activation::AuthActivation::mount(setup, catalog.clone());
1512 {
1513 let inner = self.inner_mut("Cannot mount auth: DynamicHub has multiple references");
1514 inner.auth_catalog = Some(catalog);
1515 inner.gate = Some(Arc::new(gate));
1516 }
1517 self.register(auth)
1518 .with_signed_in_grants(super::auth_activation::SIGNED_IN_GRANTS.iter().copied())
1519 }
1520
1521 pub fn view(&self, caller: Option<&super::auth::AuthContext>) -> super::view::View {
1539 match self.inner.gate.as_ref() {
1540 None => self.described().whole(),
1541 Some(_) => {
1542 let (base, view) = self.shaped(caller);
1543 view.view(&base)
1544 }
1545 }
1546 }
1547
1548 pub fn schema_moved(&self) {
1554 self.inner.describe.schema_moved();
1555 }
1556
1557 fn described(&self) -> Arc<super::view::Described> {
1561 let at = self.inner.describe.schema_generation();
1562 match self.inner.describe.base(at) {
1563 Some(cell) => cell.get_or_init(|| Arc::new(self.describe_now())).clone(),
1564 None => Arc::new(self.describe_now()),
1565 }
1566 }
1567
1568 fn describe_now(&self) -> super::view::Described {
1569 let service = Activation::plugin_schema(self);
1570 let activations: Vec<PluginSchema> = self.inner.activations.values().map(|a| a.plugin_schema()).collect();
1571 super::view::Described::new(service, activations, self.static_children())
1574 }
1575
1576 fn shaped(&self, caller: Option<&super::auth::AuthContext>) -> (Arc<super::view::Described>, Arc<super::view::Shaped>) {
1582 let gate = self.inner.gate.as_ref().expect("a view is a gated service's");
1583 let schema_at = self.inner.describe.schema_generation();
1584 let grants_at = gate.generation().current();
1585 let (caller, _) = super::grant_gate::standing(gate, caller);
1588 let who = caller.and_then(|c| gate.fingerprint(c));
1589 let shape = |base: &super::view::Described| {
1590 Arc::new(super::view::shape(gate, &self.inner.signed_in_grants, who.as_ref(), base))
1591 };
1592 match self.inner.describe.view(schema_at, grants_at, &who) {
1593 Some((base, view)) => {
1594 let base = base.get_or_init(|| Arc::new(self.describe_now())).clone();
1595 let view = view.get_or_init(|| shape(&base)).clone();
1596 (base, view)
1597 }
1598 None => {
1599 let base = Arc::new(self.describe_now());
1600 let view = shape(&base);
1601 (base, view)
1602 }
1603 }
1604 }
1605
1606 pub fn info(&self, caller: Option<&super::auth::AuthContext>) -> serde_json::Value {
1612 if self.inner.gate.is_none() {
1613 return build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1614 }
1615 let (base, view) = self.shaped(caller);
1617 view.info
1618 .get_or_init(|| {
1619 let mut payload = build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1620 if let Some(obj) = payload.as_object_mut() {
1621 obj.insert("view".into(), view.kind.as_str().into());
1622 obj.insert("view_hash".into(), view.hash.clone().into());
1623 if view.kind == super::ViewKind::Anonymous {
1624 let mut auth = serde_json::Map::new();
1625 auth.insert("methods".into(), view.public_methods(&base).into());
1626 if let Some(url) = self.inner.resource_metadata.as_ref() {
1627 auth.insert("resource_metadata".into(), url.clone().into());
1628 }
1629 obj.insert("auth".into(), serde_json::Value::Object(auth));
1630 }
1631 }
1632 payload
1633 })
1634 .clone()
1635 }
1636
1637 async fn introspect_in_view(
1643 &self,
1644 method: &str,
1645 params: &Value,
1646 auth: Option<&super::auth::AuthContext>,
1647 raw_ctx: Option<&crate::request::RawRequestContext>,
1648 ) -> Option<Result<PlexusStream, PlexusError>> {
1649 let (ns, rest) = method.split_once('.')?;
1650 let hub_ns = self.inner.namespace.as_str();
1651 let (base, view) = self.shaped(auth);
1653 let not_found = || PlexusError::ActivationNotFound(ns.to_string());
1654 let content: serde_json::Value = match rest {
1655 "schema" => {
1656 if !view.shows(ns) {
1657 return Some(Err(not_found()));
1658 }
1659 let mut result = match params.get("method").and_then(|v| v.as_str()) {
1660 Some(name) => match view.method_of(&base, ns, name) {
1661 Some(m) => super::SchemaResult::Method(m),
1662 None => {
1663 return Some(Err(PlexusError::MethodNotFound {
1664 activation: ns.to_string(),
1665 method: name.to_string(),
1666 }))
1667 }
1668 },
1669 None => super::SchemaResult::Plugin(view.schema_of(&base, ns)?),
1670 };
1671 if let Some(site) = self.derived_site_hint() {
1672 result.fill_site_hints(&site);
1673 }
1674 serde_json::to_value(&result).ok()?
1675 }
1676 "hash" if ns == hub_ns => serde_json::to_value(HashEvent::Hash { value: view.hash.clone() }).ok()?,
1677 "hashes" if ns == hub_ns => serde_json::to_value(view.hashes()).ok()?,
1678 r if r.ends_with(".schema") => {
1679 if !view.shows(ns) {
1680 return Some(Err(not_found()));
1681 }
1682 let name = r.trim_end_matches(".schema");
1683 match view.method_of(&base, ns, name) {
1684 Some(m) if matches!(m.role, super::MethodRole::Rpc) => {
1685 serde_json::to_value(super::SchemaResult::Method(m)).ok()?
1686 }
1687 Some(_) => return None,
1689 None if name.contains('.') => return None,
1690 None => {
1691 return Some(Err(PlexusError::MethodNotFound {
1692 activation: ns.to_string(),
1693 method: name.to_string(),
1694 }))
1695 }
1696 }
1697 }
1698 _ => return None,
1699 };
1700 use futures::StreamExt;
1703 let with = |content: serde_json::Value| {
1704 move |item: super::types::PlexusStreamItem| match item {
1707 super::types::PlexusStreamItem::Data { metadata, content_type, .. } => {
1708 super::types::PlexusStreamItem::Data { metadata, content_type, content: content.clone().into() }
1709 }
1710 other => other,
1711 }
1712 };
1713 if self.inner.scope_registry.is_some() || self.inner.default_deny {
1716 let routed = self.route_ungated(method, params.clone(), auth, raw_ctx).await;
1717 return Some(routed.map(|s| -> PlexusStream { Box::pin(s.map(with(content))) }));
1718 }
1719 let key = format!("{method}\n{params}");
1723 if let Some(shell) = base.shell(&key) {
1724 return Some(Ok(Box::pin(futures::stream::iter(shell.answer(content)))));
1725 }
1726 let items: Vec<super::types::PlexusStreamItem> = match self.route_ungated(method, params.clone(), auth, raw_ctx).await {
1727 Ok(s) => s.collect().await,
1728 Err(e) => return Some(Err(e)),
1729 };
1730 if let Some(shell) = super::view::Shell::of(&items) {
1731 base.keep_shell(key, shell);
1732 }
1733 Some(Ok(Box::pin(futures::stream::iter(items.into_iter().map(with(content))))))
1734 }
1735
1736 pub async fn service_ir(
1750 &self,
1751 namespaces: &[String],
1752 caller: Option<&super::auth::AuthContext>,
1753 ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
1754 let roots = super::ir::roots(&self.inner.namespace, namespaces);
1755 let view = self.ir_view(caller);
1756 let permitted = match self.inner.scope_registry.is_some() || self.inner.default_deny {
1757 false => None,
1758 true => {
1759 let mut answered = Vec::new();
1763 for name in view.names(&self.inner.namespace) {
1764 let under = roots.iter().any(|r| {
1765 let r = r.join(".");
1766 r.is_empty() || name == r || name.starts_with(&format!("{r}."))
1767 });
1768 if under && self.scope_answers(&self.schema_method(&name), caller).await {
1769 answered.push(name);
1770 }
1771 }
1772 Some(answered)
1773 }
1774 };
1775 let key = super::ir::IrKey { view: view.hash.clone(), roots: roots.clone(), permitted: permitted.clone() };
1776 self.inner
1777 .ir_cache
1778 .get_or_build(key, || async {
1779 let mut schemas: BTreeMap<Vec<String>, Value> = BTreeMap::new();
1780 let mut todo: Vec<Vec<String>> = roots.clone();
1781 while let Some(path) = todo.pop() {
1782 if schemas.contains_key(&path) || permitted.as_ref().is_some_and(|p| !p.contains(&path.join("."))) {
1783 continue;
1784 }
1785 let Some(schema) = self.ir_schema(&view, &path, caller).await else { continue };
1787 for child in schema.get("children").and_then(Value::as_array).into_iter().flatten() {
1788 if let Some(ns) = child.get("namespace").and_then(Value::as_str) {
1789 let mut next = path.clone();
1790 next.push(ns.to_string());
1791 todo.push(next);
1792 }
1793 }
1794 schemas.insert(path, schema);
1795 }
1796 let service = self.inner.namespace.clone();
1797 crate::rt::spawn_blocking(move || super::ir::answer(&service, &roots, &schemas))
1798 .await
1799 .unwrap_or_else(|e| Err(super::ir::IrError::Unreadable { namespace: String::new(), message: format!("the IR's build failed: {e}") }))
1800 })
1801 .await
1802 }
1803
1804 pub fn ir_builds(&self) -> usize {
1807 self.inner.ir_cache.builds()
1808 }
1809
1810 fn ir_view(&self, caller: Option<&super::auth::AuthContext>) -> IrView {
1814 match self.inner.gate {
1815 Some(_) => {
1816 let (base, shaped) = self.shaped(caller);
1817 IrView { hash: shaped.hash.clone(), base, shaped: Some(shaped) }
1818 }
1819 None => {
1820 let base = self.described();
1821 IrView { hash: base.service.hash.clone(), base, shaped: None }
1822 }
1823 }
1824 }
1825
1826 fn schema_method(&self, dotted: &str) -> String {
1828 if dotted.is_empty() { format!("{}.schema", self.inner.namespace) } else { format!("{dotted}.schema") }
1829 }
1830
1831 async fn scope_answers(&self, method: &str, caller: Option<&super::auth::AuthContext>) -> bool {
1834 let registry = self.inner.scope_registry.as_deref().unwrap_or_else(|| super::scope_gate::empty_registry());
1835 super::scope_gate::answers(registry, self.inner.default_deny, method, self.gate_index().get(method), caller).await
1836 }
1837
1838 async fn ir_schema(&self, view: &IrView, path: &[String], caller: Option<&super::auth::AuthContext>) -> Option<Value> {
1843 use futures::StreamExt;
1844 let shown = match path {
1845 [] => Some(view.root()),
1846 [ns] => view.top(ns),
1847 [top, below @ ..] => {
1848 let activation = self.inner.activations.get(top.as_str())?;
1851 let mut stream = activation.call(&format!("{}.schema", below.join(".")), Value::Null, caller, None).await.ok()?;
1852 if let Some(site) = self.derived_site_hint() {
1853 stream = fill_site_hints_in_schema_stream(stream, site);
1854 }
1855 let items: Vec<super::types::PlexusStreamItem> = stream.collect().await;
1856 return items.into_iter().find_map(|item| match item {
1857 super::types::PlexusStreamItem::Data { content_type, content, .. } if content_type.ends_with(".schema") => {
1858 Some(content.into_value())
1859 }
1860 _ => None,
1861 });
1862 }
1863 };
1864 let mut schema = shown?;
1865 if let Some(site) = self.derived_site_hint() {
1866 schema.fill_site_hints(&site);
1867 }
1868 serde_json::to_value(super::SchemaResult::Plugin(schema)).ok()
1869 }
1870
1871 fn check_ir_names(&self, params: &Value, caller: Option<&super::auth::AuthContext>) -> Result<(), PlexusError> {
1875 let asked = match params.get("namespaces") {
1876 None | Some(Value::Null) => return Ok(()),
1877 Some(Value::Array(a)) => a,
1878 Some(_) => return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")),
1879 };
1880 let most = 1 + self.inner.activations.len() + self.inner.nested_count();
1884 if asked.len() > most {
1885 return Err(PlexusError::malformed_param(
1886 "namespaces",
1887 format!("{} namespaces asked; more than this service shows you", asked.len()),
1888 ));
1889 }
1890 let names: std::collections::HashSet<String> = self.ir_view(caller).names(&self.inner.namespace).into_iter().collect();
1891 if asked.len() > names.len() {
1892 return Err(PlexusError::malformed_param(
1893 "namespaces",
1894 format!("{} namespaces asked; this service shows you {}", asked.len(), names.len()),
1895 ));
1896 }
1897 for n in asked {
1898 let Some(n) = n.as_str() else { return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")) };
1899 let known = n == self.inner.namespace || names.contains(n);
1900 if !known {
1901 return Err(PlexusError::malformed_param("namespaces", format!("no namespace `{n}` in this service")));
1902 }
1903 }
1904 Ok(())
1905 }
1906
1907 pub fn declared_roles(&self) -> std::collections::BTreeMap<String, Vec<String>> {
1915 let mut out: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
1916 let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
1919 for schema in schemas {
1920 for (role, grants) in schema.roles {
1921 let entry = out.entry(role).or_default();
1922 for g in grants {
1923 if !entry.contains(&g) {
1924 entry.push(g);
1925 }
1926 }
1927 }
1928 }
1929 out
1930 }
1931
1932 pub fn static_children(&self) -> Vec<PluginSchema> {
1938 self.inner
1939 .activations
1940 .values()
1941 .flat_map(|a| super::children::qualified(&a.plugin_schema().namespace, a.static_child_schemas()))
1942 .collect()
1943 }
1944
1945 pub fn scope_registry(&self) -> Option<&plexus_auth_core::ScopeRegistry> {
1950 self.inner.scope_registry.as_deref()
1951 }
1952
1953 pub(crate) fn input_terms(&self, method: &str, params: &Value) -> Result<InputTerms, PlexusError> {
1957 if self.inner.gate.is_none() {
1958 return Ok(InputTerms { grant: method.to_string(), targets: Vec::new(), recheck: false });
1959 }
1960 let info = self.gate_index().get(method);
1961 let grant = info.and_then(|i| i.grant.clone()).unwrap_or_else(|| method.to_string());
1962 let open = info.is_some_and(|i| i.public) || self.inner.signed_in_grants.contains(grant.as_str());
1963 let targets = match info.and_then(|i| i.target.as_deref()) {
1964 Some(param) => super::grant_gate::target_values(params, param)?.unwrap_or_default(),
1965 None => Vec::new(),
1966 };
1967 Ok(InputTerms { grant, targets, recheck: !open })
1968 }
1969
1970 pub(crate) fn duplex_gate(&self) -> &super::duplex_gate::DuplexGate {
1973 self.inner.duplex_gate.get_or_init(|| match &self.inner.gate {
1974 Some(gate) => {
1975 let (audit, drain) = plexus_auth_core::audit::AuditQueue::new(1024, self.inner.audit_sink.clone());
1976 crate::rt::spawn(drain);
1977 super::duplex_gate::DuplexGate::new((**gate).clone()).with_audit(audit)
1978 }
1979 None => super::duplex_gate::DuplexGate::ungated(),
1980 })
1981 }
1982
1983 pub(crate) fn may_take_input(&self, method: &str) -> bool {
1988 let index = self.inner.input_index.get_or_init(|| {
1989 let own = Activation::plugin_schema(self).methods.into_iter().map(|m| (format!("{}.{}", self.inner.namespace, m.name), m.input.is_some()));
1990 let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
1991 let theirs = schemas.flat_map(|schema| {
1992 let ns = schema.namespace;
1993 schema.methods.into_iter().map(move |m| (format!("{ns}.{}", m.name), m.input.is_some()))
1994 });
1995 own.chain(theirs).collect()
1996 });
1997 index.get(method).copied().unwrap_or(true)
1998 }
1999
2000 fn gate_index(&self) -> &HashMap<String, super::scope_gate::MethodGateInfo> {
2003 self.inner.gate_index.get_or_init(|| {
2004 let mut index = HashMap::new();
2005 for m in &Activation::plugin_schema(self).methods {
2007 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
2008 info.grant = Some(format!("{}.{}", self.inner.namespace, m.name));
2011 index.insert(format!("{}.{}", self.inner.namespace, m.name), info);
2012 }
2013 let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
2022 for schema in schemas {
2023 for m in &schema.methods {
2024 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
2025 info.grant = Some(m.grant_or(&schema.namespace));
2026 index.insert(format!("{}.{}", schema.namespace, m.name), info);
2027 }
2028 }
2029 index
2030 })
2031 }
2032
2033 pub fn with_forward_policy(
2054 mut self,
2055 callee_ns: impl Into<String>,
2056 policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>,
2057 ) -> Self {
2058 let inner = self.inner_mut("Cannot register forward policy: DynamicHub has multiple references");
2059 inner.forward_policies.register(callee_ns, policy);
2060 self
2061 }
2062
2063 pub fn forward_policies(&self) -> &super::forward_registry::ForwardPolicyRegistry {
2068 &self.inner.forward_policies
2069 }
2070
2071 pub fn with_auth_capabilities(
2107 mut self,
2108 caps: plexus_auth_core::BackendAuthCapabilities,
2109 ) -> Self {
2110 let inner = self.inner_mut("Cannot set auth_capabilities: DynamicHub has multiple references");
2111 inner.auth_capabilities = Some(caps);
2112 self
2113 }
2114
2115 pub fn auth_capabilities(&self) -> Option<&plexus_auth_core::BackendAuthCapabilities> {
2122 self.inner.auth_capabilities.as_ref()
2123 }
2124
2125 #[deprecated(since = "0.3.0", note = "Use DynamicHub::new(namespace) instead")]
2127 pub fn with_namespace(namespace: impl Into<String>) -> Self {
2128 Self::new(namespace)
2129 }
2130
2131 pub fn runtime_namespace(&self) -> &str {
2133 &self.inner.namespace
2134 }
2135
2136 pub fn registry(&self) -> std::sync::RwLockReadGuard<'_, PluginRegistry> {
2138 self.inner.registry.read().unwrap()
2139 }
2140
2141 fn assert_no_root_shadow(&self, child_namespace: &str) {
2152 if child_namespace == self.inner.namespace {
2153 panic!(
2154 "DynamicHub namespace shadow: activation namespace '{child}' collides with the hub root namespace '{root}'. \
2155 The hub root name is a routing namespace, not a label — routing resolves the root first, so a like-named \
2156 child activation is unreachable (every '{child}.<method>' call resolves to the hub root and fails with \
2157 'Command not found', and navigation resolves the child back to the root schema). \
2158 Fix: rename the hub root so it differs from every registered activation's namespace, \
2159 e.g. DynamicHub::new(\"{root}_hub\").register(...). [Z2H-8 / HOSTLESS-3]",
2160 child = child_namespace,
2161 root = self.inner.namespace,
2162 );
2163 }
2164 }
2165
2166 pub fn register<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2175 let namespace = activation.namespace().to_string();
2176 self.assert_no_root_shadow(&namespace);
2177 let plugin_id = activation.plugin_id();
2178 let activation_for_rpc = activation.clone();
2179 let activation_for_router = activation.clone();
2180
2181 let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2182
2183 inner.registry.write().unwrap().register(
2185 plugin_id,
2186 namespace.clone(),
2187 namespace.clone(), );
2189
2190 if let Some(catalog) = inner.auth_catalog.as_ref() {
2193 let schema = activation.plugin_schema();
2194 for child in super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation)) {
2196 catalog.add(&child);
2197 }
2198 catalog.add(&schema);
2199 }
2200 inner.nested_count += Activation::static_child_schemas(&activation).len();
2202 inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
2203 inner.child_routers.insert(namespace.clone(), Arc::new(activation_for_router));
2204 inner.pending_rpc.lock().unwrap()
2205 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2206 self
2207 }
2208
2209 #[deprecated(since = "0.5.0", note = "Use register() — it now handles both leaf and hub activations")]
2219 pub fn register_hub<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2220 let namespace = activation.namespace().to_string();
2221 self.assert_no_root_shadow(&namespace);
2222 let plugin_id = activation.plugin_id();
2223 let activation_for_rpc = activation.clone();
2224 let activation_for_router = activation.clone();
2225
2226 let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2227
2228 inner.registry.write().unwrap().register(
2230 plugin_id,
2231 namespace.clone(),
2232 namespace.clone(), );
2234
2235 if let Some(catalog) = inner.auth_catalog.as_ref() {
2236 let schema = activation.plugin_schema();
2237 for child in super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation)) {
2239 catalog.add(&child);
2240 }
2241 catalog.add(&schema);
2242 }
2243 inner.nested_count += Activation::static_child_schemas(&activation).len();
2245 inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
2246 inner.child_routers.insert(namespace, Arc::new(activation_for_router));
2247 inner.pending_rpc.lock().unwrap()
2248 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2249 self
2250 }
2251
2252 pub fn list_methods(&self) -> Vec<String> {
2254 let mut methods = Vec::new();
2255
2256 for m in Activation::methods(self) {
2258 methods.push(format!("{}.{}", self.inner.namespace, m));
2259 }
2260
2261 for (ns, act) in &self.inner.activations {
2263 for m in act.methods() {
2264 methods.push(format!("{}.{}", ns, m));
2265 }
2266 }
2267 methods.sort();
2268 methods
2269 }
2270
2271 pub fn list_activations_info(&self) -> Vec<ActivationInfo> {
2273 let mut activations = Vec::new();
2274
2275 activations.push(ActivationInfo {
2277 namespace: Activation::namespace(self).to_string(),
2278 version: Activation::version(self).to_string(),
2279 description: Activation::description(self).to_string(),
2280 methods: Activation::methods(self).iter().map(|s| s.to_string()).collect(),
2281 });
2282
2283 for a in self.inner.activations.values() {
2285 activations.push(ActivationInfo {
2286 namespace: a.namespace().to_string(),
2287 version: a.version().to_string(),
2288 description: a.description().to_string(),
2289 methods: a.methods().iter().map(|s| s.to_string()).collect(),
2290 });
2291 }
2292
2293 activations
2294 }
2295
2296 pub fn compute_hash(&self) -> String {
2304 self.described().service.hash.clone()
2306 }
2307
2308 fn own_hash(&self, caller: Option<&super::auth::AuthContext>) -> String {
2312 match self.inner.gate {
2313 Some(_) => self.shaped(caller).1.hash.clone(),
2314 None => self.described().service.hash.clone(),
2315 }
2316 }
2317
2318 fn own_schema(&self, caller: Option<&super::auth::AuthContext>) -> PluginSchema {
2321 match self.inner.gate {
2322 Some(_) => self.shaped(caller).1.service.clone(),
2323 None => self.described().service.clone(),
2324 }
2325 }
2326
2327 pub async fn route(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>) -> Result<PlexusStream, PlexusError> {
2329 self.route_with_ctx(method, params, auth, None).await
2330 }
2331
2332 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> {
2334 if let Some(gate) = self.inner.gate.as_ref() {
2337 let (auth, ended) = super::grant_gate::standing(gate, auth);
2339 let admit = super::grant_gate::decide(
2340 gate,
2341 &self.inner.namespace,
2342 method,
2343 self.gate_index().get(method),
2344 ¶ms,
2345 auth,
2346 &self.inner.signed_in_grants,
2347 )
2348 .map_err(|e| super::grant_gate::say_ended(e, ended.as_deref()))?;
2349 return match admit {
2350 super::grant_gate::Admit::Open => {
2354 let grant = plexus_auth_core::grants::Grant::new(method.to_string());
2355 in_call(crate::call::CallContext::introspection(auth, Arc::clone(gate), grant), async {
2356 match self.introspect_in_view(method, ¶ms, auth, raw_ctx).await {
2357 Some(answer) => answer,
2358 None => self.route_ungated(method, params, auth, raw_ctx).await,
2359 }
2360 })
2361 .await
2362 }
2363 super::grant_gate::Admit::Reach(reach) => {
2364 in_call(crate::call::CallContext::admitted(auth, reach), self.route_ungated(method, params, auth, raw_ctx)).await
2365 }
2366 };
2367 }
2368 let ctx = match crate::call::context() {
2375 Ok(outer) => outer.with_auth(auth),
2376 Err(_) => crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere()),
2377 };
2378 in_call(ctx, self.route_ungated(method, params, auth, raw_ctx)).await
2379 }
2380
2381 async fn route_ungated(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2383 if self.inner.scope_registry.is_some() || self.inner.default_deny {
2388 let registry = self
2389 .inner
2390 .scope_registry
2391 .as_deref()
2392 .unwrap_or_else(|| super::scope_gate::empty_registry());
2393 super::scope_gate::enforce(
2394 registry,
2395 self.inner.default_deny,
2396 &self.inner.audit_sink,
2397 method,
2398 self.gate_index().get(method),
2399 auth,
2400 raw_ctx.and_then(|ctx| ctx.peer.map(|peer| peer.ip())),
2401 )
2402 .await?;
2403 }
2404
2405 let (namespace, method_name) = self.parse_method(method)?;
2406
2407 if namespace == self.inner.namespace && method_name == "ir" {
2409 self.check_ir_names(¶ms, auth)?;
2410 }
2411
2412 let stream = if namespace == self.inner.namespace {
2414 Activation::call(self, method_name, params, auth, raw_ctx).await?
2415 } else {
2416 let activation = self.inner.activations.get(namespace)
2417 .ok_or_else(|| PlexusError::ActivationNotFound(namespace.to_string()))?;
2418
2419 activation.call(method_name, params, auth, raw_ctx).await?
2420 };
2421
2422 if Self::is_schema_query(method_name) {
2429 if let Some(site) = self.derived_site_hint() {
2430 return Ok(fill_site_hints_in_schema_stream(stream, site));
2431 }
2432 }
2433 Ok(stream)
2434 }
2435
2436 fn is_schema_query(method_name: &str) -> bool {
2441 method_name == "schema" || method_name.ends_with(".schema")
2442 }
2443
2444 pub fn derived_site_hint(&self) -> Option<plexus_auth_core::AttachmentSite> {
2450 self.inner
2451 .auth_capabilities
2452 .as_ref()
2453 .and_then(|caps| caps.implied_attachment_site())
2454 }
2455
2456 pub async fn do_resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
2460 let path = self.inner.registry.read().unwrap()
2461 .lookup(handle.plugin_id)
2462 .map(|s| s.to_string())
2463 .ok_or_else(|| PlexusError::ActivationNotFound(handle.plugin_id.to_string()))?;
2464
2465 let activation = self.inner.activations.get(&path)
2466 .ok_or_else(|| PlexusError::ActivationNotFound(path.clone()))?;
2467 activation.resolve_handle(handle).await
2468 }
2469
2470 pub fn get_activation_schema(&self, namespace: &str) -> Option<Schema> {
2472 self.inner.activations.get(namespace).map(|a| a.schema())
2473 }
2474
2475 pub fn registry_snapshot(&self) -> PluginRegistrySnapshot {
2477 let guard = self.inner.registry.read().unwrap();
2478 PluginRegistrySnapshot {
2479 by_id: guard.by_id.clone(),
2480 by_path: guard.by_path.clone(),
2481 }
2482 }
2483
2484 pub fn lookup_plugin(&self, id: uuid::Uuid) -> Option<String> {
2486 self.inner.registry.read().unwrap().lookup(id).map(|s| s.to_string())
2487 }
2488
2489 pub fn lookup_plugin_by_path(&self, path: &str) -> Option<uuid::Uuid> {
2491 self.inner.registry.read().unwrap().lookup_by_path(path)
2492 }
2493
2494 pub fn list_plugin_schemas(&self) -> Vec<PluginSchema> {
2496 let mut schemas = Vec::new();
2497
2498 schemas.push(Activation::plugin_schema(self));
2500
2501 for a in self.inner.activations.values() {
2503 schemas.push(a.plugin_schema());
2504 }
2505
2506 schemas
2507 }
2508
2509 #[deprecated(note = "Use list_plugin_schemas instead")]
2511 pub fn list_full_schemas(&self) -> Vec<PluginSchema> {
2512 self.list_plugin_schemas()
2513 }
2514
2515 pub fn get_method_help(&self, method: &str) -> Option<String> {
2517 let (namespace, method_name) = self.parse_method(method).ok()?;
2518 let activation = self.inner.activations.get(namespace)?;
2519 activation.method_help(method_name)
2520 }
2521
2522 fn parse_method<'a>(&self, method: &'a str) -> Result<(&'a str, &'a str), PlexusError> {
2523 let parts: Vec<&str> = method.splitn(2, '.').collect();
2524 if parts.len() != 2 {
2525 return Err(PlexusError::InvalidParams {
2526 param: Some("method".into()),
2527 problem: ParamProblem::Malformed {
2528 detail: format!("expected `namespace.method`, got `{}`", method),
2529 },
2530 });
2531 }
2532 Ok((parts[0], parts[1]))
2533 }
2534
2535 pub fn plugin_children(&self) -> Vec<ChildSummary> {
2540 self.inner.activations.values()
2541 .map(|a| {
2542 let schema = a.plugin_schema();
2543 ChildSummary {
2544 namespace: schema.namespace,
2545 description: schema.description,
2546 hash: schema.hash,
2547 }
2548 })
2549 .collect()
2550 }
2551
2552 pub fn into_rpc_module(self) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2554 let mut module = RpcModule::new(());
2555
2556 PlexusContext::init(self.compute_hash());
2557
2558 let ns = self.runtime_namespace();
2561 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2562 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2563 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2564 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2565 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2566 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2567 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2568 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2569 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2570
2571 let plexus_for_call = self.clone();
2573 module.register_subscription(
2574 call_method,
2575 PLEXUS_NOTIF_METHOD,
2576 call_unsub,
2577 move |params, pending, _ctx, ext| {
2578 let plexus = plexus_for_call.clone();
2579 let identified = plexus.inner.gate.is_some();
2583 serve_call(plexus, params, pending, ext, ns_static, identified)
2584 }
2585 )?;
2586
2587 register_input_methods(&mut module, ns_static)?;
2588
2589 let plexus_for_hash = self.clone();
2591 module.register_subscription(
2592 hash_method,
2593 PLEXUS_NOTIF_METHOD,
2594 hash_unsub,
2595 move |_params, pending, _ctx, ext| {
2596 let plexus = plexus_for_hash.clone();
2597 Box::pin(async move {
2598 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2600 let value = plexus.own_hash(auth);
2601 let stream = async_stream::stream! {
2602 yield HashEvent::Hash { value };
2603 };
2604 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2605 pipe_stream_to_subscription(pending, wrapped, &ext).await
2606 })
2607 }
2608 )?;
2609
2610 let plexus_for_schema = self.clone();
2612 module.register_subscription(
2613 schema_method,
2614 PLEXUS_NOTIF_METHOD,
2615 schema_unsub,
2616 move |params, pending, _ctx, ext| {
2617 let plexus = plexus_for_schema.clone();
2618 Box::pin(async move {
2619 let p: SchemaParams = params.parse().unwrap_or_default();
2620 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2622 let mut plugin_schema = plexus.own_schema(auth);
2623 if let Some(site) = plexus.derived_site_hint() {
2625 plugin_schema.fill_site_hints(&site);
2626 }
2627
2628 let result = if let Some(ref name) = p.method {
2629 plugin_schema.methods.iter()
2630 .find(|m| m.name == *name)
2631 .map(|m| super::SchemaResult::Method(m.clone()))
2632 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
2633 -32602,
2634 format!("Method '{}' not found", name),
2635 None::<()>,
2636 ))?
2637 } else {
2638 super::SchemaResult::Plugin(plugin_schema)
2639 };
2640
2641 let stream = async_stream::stream! { yield result; };
2642 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
2643 pipe_stream_to_subscription(pending, wrapped, &ext).await
2644 })
2645 }
2646 )?;
2647
2648 let info_payload = build_info_payload(
2654 self.runtime_namespace(),
2655 self.inner.auth_capabilities.as_ref(),
2656 );
2657 let plexus_for_info = self.inner.gate.is_some().then(|| self.clone());
2660 module.register_subscription(
2661 "_info",
2662 PLEXUS_NOTIF_METHOD,
2663 "_info_unsub",
2664 move |_params, pending, _ctx, ext| {
2665 let payload = match plexus_for_info.as_ref() {
2666 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
2667 None => info_payload.clone(),
2668 };
2669 Box::pin(async move {
2670 let info_stream = futures::stream::once(async move { payload });
2672
2673 let wrapped = super::streaming::wrap_stream(
2675 info_stream,
2676 "_info",
2677 vec![]
2678 );
2679
2680 pipe_stream_to_subscription(pending, wrapped, &ext).await
2682 })
2683 }
2684 )?;
2685
2686 let pending = std::mem::take(&mut *self.inner.pending_rpc.lock().unwrap());
2690 if self.inner.gate.is_none() {
2691 for factory in pending {
2692 module.merge(factory())?;
2693 }
2694 }
2695
2696 for (ns, router) in self.inner.child_routers.iter() {
2700 register_child_capability_methods(&mut module, ns, router.clone(), self.inner.gate.clone())?;
2701 }
2702
2703 Ok(module)
2704 }
2705
2706 pub fn arc_into_rpc_module(hub: Arc<Self>) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2712 let mut module = RpcModule::new(());
2713
2714 PlexusContext::init(hub.compute_hash());
2715
2716 let ns = hub.runtime_namespace();
2719 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2720 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2721 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2722 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2723 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2724 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2725 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2726 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2727 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2728
2729 let hub_for_call = hub.clone();
2731 module.register_subscription(
2732 call_method,
2733 call_method,
2734 call_unsub,
2735 move |params, pending, _ctx, ext| {
2736 let hub = hub_for_call.clone();
2737 let hub = (*hub).clone();
2738 serve_call(hub, params, pending, ext, ns_static, true)
2739 }
2740 )?;
2741
2742 register_input_methods(&mut module, ns_static)?;
2743
2744 let hub_for_hash = hub.clone();
2746 module.register_subscription(
2747 hash_method,
2748 PLEXUS_NOTIF_METHOD,
2749 hash_unsub,
2750 move |_params, pending, _ctx, ext| {
2751 let hub = hub_for_hash.clone();
2752 Box::pin(async move {
2753 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2755 let value = hub.own_hash(auth);
2756 let stream = async_stream::stream! {
2757 yield HashEvent::Hash { value };
2758 };
2759 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2760 pipe_stream_to_subscription(pending, wrapped, &ext).await
2761 })
2762 }
2763 )?;
2764
2765 let hub_for_schema = hub.clone();
2767 module.register_subscription(
2768 schema_method,
2769 PLEXUS_NOTIF_METHOD,
2770 schema_unsub,
2771 move |params, pending, _ctx, ext| {
2772 let hub = hub_for_schema.clone();
2773 Box::pin(async move {
2774 let p: SchemaParams = params.parse().unwrap_or_default();
2775 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2777 let mut plugin_schema = hub.own_schema(auth);
2778 if let Some(site) = hub.derived_site_hint() {
2780 plugin_schema.fill_site_hints(&site);
2781 }
2782
2783 let result = if let Some(ref name) = p.method {
2784 plugin_schema.methods.iter()
2785 .find(|m| m.name == *name)
2786 .map(|m| super::SchemaResult::Method(m.clone()))
2787 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
2788 -32602,
2789 format!("Method '{}' not found", name),
2790 None::<()>,
2791 ))?
2792 } else {
2793 super::SchemaResult::Plugin(plugin_schema)
2794 };
2795
2796 let stream = async_stream::stream! {
2797 yield result;
2798 };
2799 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
2800 pipe_stream_to_subscription(pending, wrapped, &ext).await
2801 })
2802 }
2803 )?;
2804
2805 let info_payload = build_info_payload(
2810 hub.runtime_namespace(),
2811 hub.inner.auth_capabilities.as_ref(),
2812 );
2813 let hub_for_info = hub.inner.gate.is_some().then(|| hub.clone());
2816 module.register_subscription(
2817 "_info",
2818 PLEXUS_NOTIF_METHOD,
2819 "_info_unsub",
2820 move |_params, pending, _ctx, ext| {
2821 let payload = match hub_for_info.as_ref() {
2822 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
2823 None => info_payload.clone(),
2824 };
2825 Box::pin(async move {
2826 let info_stream = futures::stream::once(async move { payload });
2828
2829 let wrapped = super::streaming::wrap_stream(
2831 info_stream,
2832 "_info",
2833 vec![]
2834 );
2835
2836 pipe_stream_to_subscription(pending, wrapped, &ext).await
2838 })
2839 }
2840 )?;
2841
2842 let respond_method: &'static str = Box::leak(format!("{}.respond", ns).into_boxed_str());
2845 module.register_async_method(respond_method, |params, _ctx, ext| async move {
2850 use super::bidirectional::{answer_pending, BidirError};
2851
2852 let p: RespondParams = params.parse()?;
2853 let from = ext.get::<jsonrpsee::ConnectionId>().map(|c| c.0);
2854
2855 tracing::debug!(
2856 request_id = %p.request_id,
2857 connection = ?from,
2858 "Handling {}.respond via WebSocket",
2859 "plexus"
2860 );
2861
2862 match answer_pending(&p.request_id, from, p.response_data) {
2863 Ok(()) => Ok(serde_json::json!({"success": true})),
2864 Err(BidirError::NotThisCall) => {
2865 tracing::warn!(request_id = %p.request_id, connection = ?from, "respond from a connection that was not asked");
2866 Err(jsonrpsee::types::ErrorObject::owned(
2867 -32003,
2868 format!("not_this_call: request {} was asked on another connection", p.request_id),
2869 Some(serde_json::json!({"error_kind": "not_this_call", "request_id": p.request_id})),
2870 ))
2871 }
2872 Err(BidirError::UnknownRequest) => {
2873 tracing::warn!(request_id = %p.request_id, "Unknown request ID in respond");
2874 Err(jsonrpsee::types::ErrorObject::owned(
2875 -32602,
2876 format!("Unknown request ID: {}. The request may have timed out or been cancelled.", p.request_id),
2877 None::<()>,
2878 ))
2879 }
2880 Err(BidirError::ChannelClosed) => {
2881 tracing::warn!(request_id = %p.request_id, "Channel closed in respond");
2882 Err(jsonrpsee::types::ErrorObject::owned(
2883 -32000,
2884 "Response channel was closed (request may have timed out)",
2885 None::<()>,
2886 ))
2887 }
2888 Err(e) => {
2889 tracing::error!(request_id = %p.request_id, error = ?e, "Error in respond");
2890 Err(jsonrpsee::types::ErrorObject::owned(
2891 -32000,
2892 format!("Failed to deliver response: {}", e),
2893 None::<()>,
2894 ))
2895 }
2896 }
2897 })?;
2898
2899 let mut pending = std::mem::take(&mut *hub.inner.pending_rpc.lock().unwrap());
2902 if hub.inner.gate.is_some() {
2903 pending.clear();
2904 }
2905 tracing::trace!(factories = pending.len(), "merging activation RPC factories");
2906 for (idx, factory) in pending.into_iter().enumerate() {
2907 tracing::trace!(factory_idx = idx, "calling factory to get Methods");
2908 let methods = factory();
2909 let method_count = methods.method_names().count();
2910 tracing::trace!(factory_idx = idx, methods = method_count, "factory returned Methods; merging into module");
2911 module.merge(methods)?;
2912 tracing::trace!(factory_idx = idx, "successfully merged factory methods");
2913 }
2914 tracing::trace!("all activations merged successfully");
2915
2916 for (ns, router) in hub.inner.child_routers.iter() {
2919 register_child_capability_methods(&mut module, ns, router.clone(), hub.inner.gate.clone())?;
2920 }
2921
2922 Ok(module)
2923 }
2924}
2925
2926fn listing_context(
2946 gate: Option<&Arc<plexus_auth_core::grants::Gate>>,
2947 ext: &jsonrpsee::Extensions,
2948 method: &str,
2949) -> crate::call::CallContext {
2950 let auth = ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2951 match gate {
2952 None => crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere()),
2953 Some(gate) => {
2954 let (auth, _) = super::grant_gate::standing(gate, auth);
2955 crate::call::CallContext::introspection(auth, Arc::clone(gate), plexus_auth_core::grants::Grant::new(method.to_string()))
2956 }
2957 }
2958}
2959
2960#[allow(deprecated)] fn register_child_capability_methods(
2962 module: &mut RpcModule<()>,
2963 namespace: &str,
2964 router: Arc<dyn ChildRouter>,
2965 gate: Option<Arc<plexus_auth_core::grants::Gate>>,
2966) -> Result<(), jsonrpsee::core::RegisterMethodError> {
2967 let caps = router.capabilities();
2968 if caps.is_empty() {
2969 return Ok(());
2970 }
2971
2972 let ns_static: &'static str = Box::leak(namespace.to_string().into_boxed_str());
2973
2974 if caps.contains(ChildCapabilities::LIST) {
2975 let list_method: &'static str =
2976 Box::leak(format!("{}.list_children", namespace).into_boxed_str());
2977 let list_unsub: &'static str =
2978 Box::leak(format!("{}.list_children_unsub", namespace).into_boxed_str());
2979 let router_for_list = router.clone();
2980 let gate_for_list = gate.clone();
2981 module.register_subscription(
2982 list_method,
2983 PLEXUS_NOTIF_METHOD,
2984 list_unsub,
2985 move |_params, pending, _ctx, ext| {
2986 let router = router_for_list.clone();
2987 let ctx = listing_context(gate_for_list.as_ref(), &ext, list_method);
2988 Box::pin(async move {
2989 let collected: Vec<String> = crate::call::scope(ctx, async {
2996 match router.list_children().await {
2997 Some(mut s) => {
2998 use futures::StreamExt;
2999 let mut acc = Vec::new();
3000 while let Some(name) = s.next().await {
3001 acc.push(name);
3002 }
3003 acc
3004 }
3005 None => Vec::new(),
3006 }
3007 })
3008 .await;
3009 let stream = async_stream::stream! {
3010 for name in collected {
3011 yield name;
3012 }
3013 };
3014 let wrapped = super::streaming::wrap_stream(
3015 stream,
3016 "list_children",
3017 vec![ns_static.into()],
3018 );
3019 pipe_stream_to_subscription(pending, wrapped, &ext).await
3020 })
3021 },
3022 )?;
3023 }
3024
3025 if caps.contains(ChildCapabilities::SEARCH) {
3026 let search_method: &'static str =
3027 Box::leak(format!("{}.search_children", namespace).into_boxed_str());
3028 let search_unsub: &'static str =
3029 Box::leak(format!("{}.search_children_unsub", namespace).into_boxed_str());
3030 let router_for_search = router.clone();
3031 let gate_for_search = gate.clone();
3032 module.register_subscription(
3033 search_method,
3034 PLEXUS_NOTIF_METHOD,
3035 search_unsub,
3036 move |params, pending, _ctx, ext| {
3037 let router = router_for_search.clone();
3038 let ctx = listing_context(gate_for_search.as_ref(), &ext, search_method);
3039 Box::pin(async move {
3040 let p: SearchChildrenParams = params.parse()?;
3041 let collected: Vec<String> = crate::call::scope(ctx, async {
3042 match router.search_children(&p.query).await {
3043 Some(mut s) => {
3044 use futures::StreamExt;
3045 let mut acc = Vec::new();
3046 while let Some(name) = s.next().await {
3047 acc.push(name);
3048 }
3049 acc
3050 }
3051 None => Vec::new(),
3052 }
3053 })
3054 .await;
3055 let stream = async_stream::stream! {
3056 for name in collected {
3057 yield name;
3058 }
3059 };
3060 let wrapped = super::streaming::wrap_stream(
3061 stream,
3062 "search_children",
3063 vec![ns_static.into()],
3064 );
3065 pipe_stream_to_subscription(pending, wrapped, &ext).await
3066 })
3067 },
3068 )?;
3069 }
3070
3071 Ok(())
3072}
3073
3074#[derive(Debug, serde::Deserialize)]
3076struct SearchChildrenParams {
3077 query: String,
3078}
3079
3080#[derive(Debug, serde::Deserialize)]
3082pub(crate) struct CallParams {
3083 pub(crate) method: String,
3084 #[serde(default)]
3085 pub(crate) params: Option<Value>,
3086}
3087
3088pub(crate) struct InputTerms {
3090 pub(crate) grant: String,
3091 pub(crate) targets: Vec<String>,
3092 pub(crate) recheck: bool,
3093}
3094
3095use super::schema::SchemaParams;
3097
3098#[derive(Debug, serde::Deserialize)]
3100struct RespondParams {
3101 request_id: String,
3102 response_data: Value,
3103}
3104
3105fn serve_call(
3118 service: DynamicHub,
3119 params: jsonrpsee::types::Params<'static>,
3120 pending: jsonrpsee::PendingSubscriptionSink,
3121 ext: http::Extensions,
3122 ns: &'static str,
3123 identified: bool,
3124) -> CallFuture {
3125 let call: CallParams = match params.parse() {
3128 Ok(call) => call,
3129 Err(e) => return Box::pin(async move { Err(e.into()) }),
3130 };
3131 if service.may_take_input(&call.method) {
3132 return Box::pin(serve_seamed(service, call, params, pending, ext, ns, identified));
3133 }
3134 let CallParams { method, params: args } = call;
3135 Box::pin(async move {
3136 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref()) } else { None };
3137 match service.route(&method, args.unwrap_or_default(), caller).await {
3138 Ok(stream) => pipe_stream_to_subscription(pending, stream, &ext).await,
3139 Err(e) => {
3140 let sink = pending.accept().await?;
3141 if let Some(raw) = error_item_raw(ns, &e) {
3142 let _ = sink.send(raw).await;
3143 }
3144 Ok(())
3145 }
3146 }
3147 })
3148}
3149
3150type CallFuture = std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>>;
3153
3154async fn serve_seamed(
3159 service: DynamicHub,
3160 call: CallParams,
3161 params: jsonrpsee::types::Params<'static>,
3162 pending: jsonrpsee::PendingSubscriptionSink,
3163 ext: http::Extensions,
3164 ns: &'static str,
3165 identified: bool,
3166) -> jsonrpsee::core::SubscriptionResult {
3167 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().cloned() } else { None };
3168 let seen = service.inner.gate.as_ref().map_or(0, |g| g.generation().current());
3169 let opened = Arc::new(std::sync::Mutex::new(None::<super::input::Opened>));
3170 let take = || opened.lock().unwrap_or_else(|e| e.into_inner()).take();
3171 let mut scoped = std::pin::pin!(super::input::CALL.scope(
3172 std::cell::RefCell::new(super::input::Seam { service: service.clone(), params, pending: Some(pending), ext, seen, opened: opened.clone(), refused: None }),
3173 service.route(&call.method, call.params.unwrap_or_default(), caller.as_deref()),
3174 ));
3175 let answered = std::future::poll_fn(|cx| match std::future::Future::poll(scoped.as_mut(), cx) {
3180 std::task::Poll::Ready(answer) => std::task::Poll::Ready(Some(answer)),
3181 std::task::Poll::Pending if opened.lock().unwrap_or_else(|e| e.into_inner()).is_some() => std::task::Poll::Ready(None),
3182 std::task::Poll::Pending => std::task::Poll::Pending,
3183 })
3184 .await;
3185 let Some(answer) = answered else {
3186 let super::input::Opened { sink, duplex } = take().expect("opened, the route still resolving");
3187 let mut routing = std::pin::pin!(async { scoped.as_mut().await.map_err(|e| error_item(ns, &e)) });
3188 return Box::pin(super::wire::pipe_duplex(sink, super::wire::Output::Routing(routing.as_mut()), duplex)).await;
3189 };
3190 let super::input::Seam { pending, ext, refused, .. } = scoped.as_mut().take_value().expect("the scope ran to its end").into_inner();
3191 match (answer, take()) {
3192 (Ok(stream), Some(opened)) => Box::pin(super::wire::pipe_duplex(opened.sink, super::wire::Output::Ready(stream), opened.duplex)).await,
3194 (Ok(stream), None) => {
3195 let pending = pending.expect("only an open takes it, and an open is `opened`");
3196 pipe_stream_to_subscription(pending, stream, &ext).await
3197 }
3198 (Err(e), opened) => {
3199 let sink = match (opened, pending) {
3200 (Some(opened), _) => opened.sink,
3201 (None, Some(pending)) => pending.accept().await?,
3202 (None, None) => return Ok(()),
3203 };
3204 let raw = match refused {
3205 Some(item) => serde_json::value::to_raw_value(&item).ok(),
3206 None => error_item_raw(ns, &e),
3207 };
3208 if let Some(raw) = raw {
3209 let _ = sink.send(raw).await;
3210 }
3211 Ok(())
3212 }
3213 }
3214}
3215
3216fn register_input_methods(module: &mut RpcModule<()>, ns: &'static str) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3222 use super::input::{Delivered, InputTable};
3223 use jsonrpsee::types::ErrorObjectOwned;
3224
3225 fn answer(delivered: Delivered) -> Result<bool, ErrorObjectOwned> {
3226 match delivered {
3227 Delivered::Taken => Ok(true),
3228 Delivered::Dropped | Delivered::Refused => Ok(false),
3229 Delivered::NotThisCall => Err(ErrorObjectOwned::owned(
3230 -32003,
3231 "not_this_call: input comes from the connection that opened the call",
3232 Some(serde_json::json!({"error_kind": "not_this_call"})),
3233 )),
3234 Delivered::Malformed => Err(ErrorObjectOwned::owned(-32602, "invalid params: subscription, seq and items", None::<()>)),
3235 }
3236 }
3237 fn table(ext: &http::Extensions) -> Result<&Arc<InputTable>, ErrorObjectOwned> {
3238 ext.get::<super::wire::FrameSink>()
3239 .and_then(super::wire::FrameSink::inputs)
3240 .ok_or_else(|| ErrorObjectOwned::owned(-32601, "this transport carries no input half: call over a WebSocket", None::<()>))
3241 }
3242
3243 let input_method: &'static str = Box::leak(format!("{ns}.input").into_boxed_str());
3244 let end_method: &'static str = Box::leak(format!("{ns}.end").into_boxed_str());
3245 module.register_method(input_method, move |params, _ctx, ext| {
3246 let frame = bytes::Bytes::copy_from_slice(params.as_str().unwrap_or("null").as_bytes());
3247 answer(table(ext)?.input(ns, &frame, &frame))
3248 })?;
3249 module.register_method(end_method, move |params, _ctx, ext| answer(table(ext)?.end(ns, params.as_str().unwrap_or("null").as_bytes())))?;
3250 Ok(())
3251}
3252
3253async fn pipe_stream_to_subscription(
3268 pending: jsonrpsee::PendingSubscriptionSink,
3269 stream: PlexusStream,
3270 ext: &http::Extensions,
3271) -> jsonrpsee::core::SubscriptionResult {
3272 let sink = pending.accept().await?;
3273 super::wire::pipe(sink, stream, ext).await
3274}
3275
3276#[plexus_macros::activation(
3281 namespace = "plexus",
3282 version = "1.0.0",
3283 description = "Central routing and introspection",
3284 hub,
3285 namespace_fn = "runtime_namespace"
3286)]
3287#[allow(deprecated)]
3288impl DynamicHub {
3289 #[plexus_macros::method(
3291 description = "Route a call to a registered activation",
3292 params(
3293 method = "The method to call (format: namespace.method)",
3294 params = "Parameters to pass to the method (optional, defaults to {})"
3295 )
3296 )]
3297 async fn call(
3298 &self,
3299 method: String,
3300 params: Option<Value>,
3301 ) -> impl Stream<Item = super::types::PlexusStreamItem> + Send + 'static {
3302 use super::context::PlexusContext;
3303 use super::types::{PlexusStreamItem, StreamMetadata};
3304
3305 let result = self.route(&method, params.unwrap_or_default(), None).await;
3306
3307 match result {
3308 Ok(plexus_stream) => {
3309 plexus_stream
3311 }
3312 Err(e) => {
3313 let metadata = StreamMetadata::new(
3315 vec![self.inner.namespace.clone()],
3316 PlexusContext::hash(),
3317 );
3318 Box::pin(futures::stream::once(async move {
3319 PlexusStreamItem::from_plexus_error(metadata, &e, false)
3320 }))
3321 }
3322 }
3323 }
3324
3325 #[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.")]
3330 async fn hash(&self) -> impl Stream<Item = HashEvent> + Send + 'static {
3331 let schema = Activation::plugin_schema(self);
3332 stream! { yield HashEvent::Hash { value: schema.hash }; }
3333 }
3334
3335 #[plexus_macros::method(description = "Get plugin hashes for cache validation")]
3337 #[allow(deprecated)]
3338 async fn hashes(&self) -> impl Stream<Item = PluginHashes> + Send + 'static {
3339 let schema = Activation::plugin_schema(self);
3340
3341 stream! {
3342 yield PluginHashes {
3343 namespace: schema.namespace.clone(),
3344 self_hash: schema.self_hash.clone(),
3345 children_hash: schema.children_hash.clone(),
3346 hash: schema.hash.clone(),
3347 children: schema.children.as_ref().map(|kids| {
3348 kids.iter()
3349 .map(|c| ChildHashes {
3350 namespace: c.namespace.clone(),
3351 hash: c.hash.clone(),
3352 })
3353 .collect()
3354 }),
3355 };
3356 }
3357 }
3358
3359 #[plexus_macros::method(
3365 description = "The service's IR (3.0): every type once, each method referring to them — of the namespaces asked, or the whole service",
3366 params(namespaces = "The namespaces (dotted paths) to describe; none: the whole service")
3367 )]
3368 async fn ir(
3369 &self,
3370 auth: Option<&super::auth::AuthContext>,
3371 namespaces: Option<Vec<String>>,
3372 ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
3373 self.service_ir(&namespaces.unwrap_or_default(), auth).await
3374 }
3375
3376 }
3378
3379use super::hub_context::HubContext;
3384use std::sync::Weak;
3385
3386#[async_trait]
3392impl HubContext for Weak<DynamicHub> {
3393 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
3394 let hub = self.upgrade().ok_or_else(|| {
3395 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3396 })?;
3397 hub.do_resolve_handle(handle).await
3398 }
3399
3400 async fn call(&self, method: &str, params: serde_json::Value) -> Result<PlexusStream, PlexusError> {
3401 let hub = self.upgrade().ok_or_else(|| {
3402 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3403 })?;
3404 hub.route(method, params, None).await
3405 }
3406
3407 fn is_valid(&self) -> bool {
3408 self.upgrade().is_some()
3409 }
3410}
3411
3412#[async_trait]
3417impl ChildRouter for DynamicHub {
3418 fn router_namespace(&self) -> &str {
3419 &self.inner.namespace
3420 }
3421
3422 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
3423 self.route_with_ctx(method, params, auth, raw_ctx).await
3426 }
3427
3428 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3429 self.inner.child_routers.get(name)
3431 .map(|router| {
3432 Box::new(ArcChildRouter(router.clone())) as Box<dyn ChildRouter>
3434 })
3435 }
3436
3437 fn forward_policy_for(
3440 &self,
3441 callee_ns: &str,
3442 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
3443 self.inner.forward_policies.get(callee_ns)
3444 }
3445
3446 }
3453
3454#[cfg(test)]
3455#[allow(deprecated)]
3456mod tests {
3457 use super::*;
3458
3459 #[test]
3460 fn dynamic_hub_implements_activation() {
3461 fn assert_activation<T: Activation>() {}
3462 assert_activation::<DynamicHub>();
3463 }
3464
3465 #[test]
3466 fn dynamic_hub_methods() {
3467 let hub = DynamicHub::new("test");
3468 let methods = hub.methods();
3469 assert!(methods.contains(&"call"));
3470 assert!(methods.contains(&"hash"));
3471 assert!(methods.contains(&"schema"));
3472 }
3474
3475 #[test]
3476 fn dynamic_hub_hash_stable() {
3477 let h1 = DynamicHub::new("test");
3478 let h2 = DynamicHub::new("test");
3479 assert_eq!(h1.compute_hash(), h2.compute_hash());
3480 }
3481
3482 #[test]
3483 fn dynamic_hub_is_hub() {
3484 use crate::activations::health::Health;
3485 let hub = DynamicHub::new("test").register(Health::new());
3486 let schema = hub.plugin_schema();
3487
3488 assert!(schema.is_hub(), "dynamic hub should be a hub");
3490 assert!(!schema.is_leaf(), "dynamic hub should not be a leaf");
3491
3492 let children = schema.children.expect("dynamic hub should have children");
3494 assert!(!children.is_empty(), "dynamic hub should have at least one child");
3495
3496 let health = children.iter().find(|c| c.namespace == "health").expect("should have health child");
3498 assert!(!health.hash.is_empty(), "health should have a hash");
3499 }
3500
3501 #[test]
3506 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3507 fn dynamic_hub_rejects_root_namespace_shadow() {
3508 use crate::activations::health::Health;
3509 let _hub = DynamicHub::new("health").register(Health::new());
3510 }
3511
3512 #[test]
3515 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3516 fn dynamic_hub_register_hub_rejects_root_namespace_shadow() {
3517 use crate::activations::health::Health;
3518 let _hub = DynamicHub::new("health").register_hub(Health::new());
3519 }
3520
3521 #[test]
3525 fn dynamic_hub_shadow_error_names_collision_and_fix() {
3526 use crate::activations::health::Health;
3527 let result = std::panic::catch_unwind(|| {
3528 let _hub = DynamicHub::new("health").register(Health::new());
3529 });
3530 let err = result.expect_err("shadow registration must panic");
3531 let msg = err
3532 .downcast_ref::<String>()
3533 .cloned()
3534 .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
3535 .expect("panic payload should be a string");
3536 assert!(msg.contains("'health'"), "must name the colliding namespace: {msg}");
3537 assert!(msg.contains("hub root namespace"), "must name the root side: {msg}");
3538 assert!(msg.contains("rename the hub root"), "must suggest the fix: {msg}");
3539 assert!(msg.contains("Z2H-8"), "must cite the ticket: {msg}");
3540 }
3541
3542 #[test]
3545 fn dynamic_hub_non_colliding_registration_unaffected() {
3546 use crate::activations::health::Health;
3547 let hub = DynamicHub::new("health_hub").register(Health::new());
3548 assert_eq!(hub.runtime_namespace(), "health_hub");
3549 let schema = hub.plugin_schema();
3550 let children = schema.children.expect("hub should have children");
3551 assert!(
3552 children.iter().any(|c| c.namespace == "health"),
3553 "health child must be registered"
3554 );
3555 assert!(hub.list_methods().iter().any(|m| m.starts_with("health.")));
3556 }
3557
3558 #[test]
3559 fn dynamic_hub_schema_structure() {
3560 use crate::activations::health::Health;
3561 let hub = DynamicHub::new("test").register(Health::new());
3562 let schema = hub.plugin_schema();
3563
3564 let json = serde_json::to_string_pretty(&schema).unwrap();
3566 println!("DynamicHub schema:\n{}", json);
3567
3568 assert_eq!(schema.namespace, "test");
3570 assert!(schema.methods.iter().any(|m| m.name == "call"));
3571 assert!(schema.children.is_some());
3572 }
3573
3574 #[tokio::test]
3579 async fn invariant_resolve_handle_unknown_activation() {
3580 use crate::activations::health::Health;
3581 use crate::types::Handle;
3582 use uuid::Uuid;
3583
3584 let hub = DynamicHub::new("test").register(Health::new());
3585
3586 let unknown_plugin_id = Uuid::new_v4();
3588 let handle = Handle::new(unknown_plugin_id, "1.0.0", "some_method");
3589
3590 let result = hub.do_resolve_handle(&handle).await;
3591
3592 match result {
3593 Err(PlexusError::ActivationNotFound(_)) => {
3594 }
3596 Err(other) => panic!("Expected ActivationNotFound, got {:?}", other),
3597 Ok(_) => panic!("Expected error for unknown activation"),
3598 }
3599 }
3600
3601 #[tokio::test]
3602 async fn invariant_resolve_handle_unsupported() {
3603 use crate::activations::health::Health;
3604 use crate::types::Handle;
3605
3606 let hub = DynamicHub::new("test").register(Health::new());
3607
3608 let handle = Handle::new(Health::PLUGIN_ID, "1.0.0", "check");
3610
3611 let result = hub.do_resolve_handle(&handle).await;
3612
3613 match result {
3614 Err(PlexusError::HandleNotSupported(name)) => {
3615 assert_eq!(name, "health");
3616 }
3617 Err(other) => panic!("Expected HandleNotSupported, got {:?}", other),
3618 Ok(_) => panic!("Expected error for unsupported handle"),
3619 }
3620 }
3621
3622 #[tokio::test]
3623 async fn invariant_resolve_handle_routes_by_plugin_id() {
3624 use crate::activations::health::Health;
3625 use crate::activations::echo::EchoActivation;
3626 use crate::types::Handle;
3627 use uuid::Uuid;
3628
3629 let health = Health::new();
3630 let echo = EchoActivation::new();
3631 let health_plugin_id = health.plugin_id();
3632 let echo_plugin_id = echo.plugin_id();
3633
3634 let hub = DynamicHub::new("test")
3635 .register(health)
3636 .register(echo);
3637
3638 let health_handle = Handle::new(health_plugin_id, "1.0.0", "check");
3640 match hub.do_resolve_handle(&health_handle).await {
3641 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "health"),
3642 Err(other) => panic!("health handle should route to health activation, got {:?}", other),
3643 Ok(_) => panic!("health handle should return HandleNotSupported"),
3644 }
3645
3646 let echo_handle = Handle::new(echo_plugin_id, "1.0.0", "echo");
3648 match hub.do_resolve_handle(&echo_handle).await {
3649 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "echo"),
3650 Err(other) => panic!("echo handle should route to echo activation, got {:?}", other),
3651 Ok(_) => panic!("echo handle should return HandleNotSupported"),
3652 }
3653
3654 let unknown_handle = Handle::new(Uuid::new_v4(), "1.0.0", "method");
3656 match hub.do_resolve_handle(&unknown_handle).await {
3657 Err(PlexusError::ActivationNotFound(_)) => { },
3658 Err(other) => panic!("unknown handle should return ActivationNotFound, got {:?}", other),
3659 Ok(_) => panic!("unknown handle should return ActivationNotFound"),
3660 }
3661 }
3662
3663 #[test]
3664 fn invariant_handle_plugin_id_determines_routing() {
3665 use crate::activations::health::Health;
3666 use crate::activations::echo::EchoActivation;
3667 use crate::types::Handle;
3668
3669 let health = Health::new();
3670 let echo = EchoActivation::new();
3671
3672 let health_handle = Handle::new(health.plugin_id(), "1.0.0", "check")
3674 .with_meta(vec!["msg-123".into(), "user".into()]);
3675 let echo_handle = Handle::new(echo.plugin_id(), "1.0.0", "echo")
3676 .with_meta(vec!["msg-123".into(), "user".into()]);
3677
3678 assert_ne!(health_handle.plugin_id, echo_handle.plugin_id);
3680 }
3681
3682 #[test]
3687 fn plugin_registry_basic_operations() {
3688 let mut registry = PluginRegistry::new();
3689 let id = uuid::Uuid::new_v4();
3690
3691 registry.register(id, "test_plugin".to_string(), "test".to_string());
3693
3694 assert_eq!(registry.lookup(id), Some("test_plugin"));
3696
3697 assert_eq!(registry.lookup_by_path("test_plugin"), Some(id));
3699
3700 let entry = registry.get(id).expect("should have entry");
3702 assert_eq!(entry.path, "test_plugin");
3703 assert_eq!(entry.plugin_type, "test");
3704 }
3705
3706 #[test]
3707 fn plugin_registry_populated_on_register() {
3708 use crate::activations::health::Health;
3709
3710 let hub = DynamicHub::new("test").register(Health::new());
3711
3712 let registry = hub.registry();
3713 assert!(!registry.is_empty(), "registry should not be empty after registration");
3714
3715 let health_id = registry.lookup_by_path("health");
3717 assert!(health_id.is_some(), "health should be registered by path");
3718
3719 let health_uuid = health_id.unwrap();
3721 assert_eq!(registry.lookup(health_uuid), Some("health"));
3722 }
3723
3724 #[test]
3725 fn plugin_registry_deterministic_uuid() {
3726 use crate::activations::health::Health;
3727
3728 let health1 = Health::new();
3730 let health2 = Health::new();
3731
3732 assert_eq!(health1.plugin_id(), health2.plugin_id(),
3733 "same activation type should have deterministic UUID");
3734
3735 let expected = uuid::Uuid::new_v5(
3737 &uuid::Uuid::NAMESPACE_OID,
3738 b"health@1"
3739 );
3740 assert_eq!(health1.plugin_id(), expected,
3741 "plugin_id should be deterministic from namespace@major_version");
3742 }
3743
3744 struct MinimalRouter;
3752
3753 #[async_trait]
3754 impl ChildRouter for MinimalRouter {
3755 fn router_namespace(&self) -> &str {
3756 "minimal"
3757 }
3758
3759 async fn router_call(
3760 &self,
3761 _method: &str,
3762 _params: Value,
3763 _auth: Option<&super::super::auth::AuthContext>,
3764 _raw_ctx: Option<&crate::request::RawRequestContext>,
3765 ) -> Result<PlexusStream, PlexusError> {
3766 Err(PlexusError::MethodNotFound {
3767 activation: "minimal".into(),
3768 method: "none".into(),
3769 })
3770 }
3771
3772 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
3773 None
3774 }
3775 }
3776
3777 #[tokio::test]
3778 async fn child_router_defaults_report_no_capabilities_and_none_streams() {
3779 let router = MinimalRouter;
3780
3781 assert_eq!(
3782 router.capabilities(),
3783 ChildCapabilities::empty(),
3784 "default capabilities should be empty"
3785 );
3786 assert!(
3787 router.list_children().await.is_none(),
3788 "default list_children should be None"
3789 );
3790 assert!(
3791 router.search_children("anything").await.is_none(),
3792 "default search_children should be None"
3793 );
3794 }
3795
3796 struct ListingRouter {
3798 names: Vec<String>,
3799 }
3800
3801 #[async_trait]
3802 impl ChildRouter for ListingRouter {
3803 fn router_namespace(&self) -> &str {
3804 "listing"
3805 }
3806
3807 async fn router_call(
3808 &self,
3809 _method: &str,
3810 _params: Value,
3811 _auth: Option<&super::super::auth::AuthContext>,
3812 _raw_ctx: Option<&crate::request::RawRequestContext>,
3813 ) -> Result<PlexusStream, PlexusError> {
3814 Err(PlexusError::MethodNotFound {
3815 activation: "listing".into(),
3816 method: "none".into(),
3817 })
3818 }
3819
3820 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3821 if self.names.iter().any(|n| n == name) {
3822 Some(Box::new(ListingRouter { names: vec![] }))
3825 } else {
3826 None
3827 }
3828 }
3829
3830 fn capabilities(&self) -> ChildCapabilities {
3831 ChildCapabilities::LIST | ChildCapabilities::SEARCH
3832 }
3833
3834 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
3835 let stream = futures::stream::iter(self.names.iter().cloned());
3836 Some(Box::pin(stream))
3837 }
3838
3839 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
3840 let q = query.to_string();
3841 let stream = futures::stream::iter(
3842 self.names
3843 .iter()
3844 .filter(move |n| n.contains(&q))
3845 .cloned()
3846 .collect::<Vec<_>>(),
3847 );
3848 Some(Box::pin(stream))
3849 }
3850 }
3851
3852 #[tokio::test]
3853 async fn child_router_overrides_report_capabilities_and_yield_streams() {
3854 use futures::StreamExt;
3855
3856 let router = ListingRouter {
3857 names: vec!["alpha".into(), "beta".into(), "alphabet".into()],
3858 };
3859
3860 let caps = router.capabilities();
3862 assert!(caps.contains(ChildCapabilities::LIST));
3863 assert!(caps.contains(ChildCapabilities::SEARCH));
3864 assert_eq!(caps, ChildCapabilities::LIST | ChildCapabilities::SEARCH);
3865
3866 let list_stream = router
3868 .list_children()
3869 .await
3870 .expect("LIST capability set — expected Some(stream)");
3871 let listed: Vec<String> = list_stream.collect().await;
3872 assert_eq!(listed, vec!["alpha".to_string(), "beta".into(), "alphabet".into()]);
3873
3874 let search_stream = router
3876 .search_children("alpha")
3877 .await
3878 .expect("SEARCH capability set — expected Some(stream)");
3879 let matched: Vec<String> = search_stream.collect().await;
3880 assert_eq!(matched, vec!["alpha".to_string(), "alphabet".into()]);
3881 }
3882
3883 struct WireFixture {
3898 names: Vec<String>,
3899 caps: ChildCapabilities,
3900 }
3901
3902 #[async_trait]
3903 impl ChildRouter for WireFixture {
3904 fn router_namespace(&self) -> &str {
3905 "wirefixture"
3906 }
3907 async fn router_call(
3908 &self,
3909 _method: &str,
3910 _params: Value,
3911 _auth: Option<&super::super::auth::AuthContext>,
3912 _raw_ctx: Option<&crate::request::RawRequestContext>,
3913 ) -> Result<PlexusStream, PlexusError> {
3914 Err(PlexusError::MethodNotFound {
3915 activation: "wirefixture".into(),
3916 method: "none".into(),
3917 })
3918 }
3919 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
3920 None
3921 }
3922 fn capabilities(&self) -> ChildCapabilities {
3923 self.caps
3924 }
3925 async fn list_children(&self) -> Option<futures_core::stream::BoxStream<'_, String>> {
3926 if !self.caps.contains(ChildCapabilities::LIST) {
3927 return None;
3928 }
3929 Some(Box::pin(futures::stream::iter(self.names.clone())))
3930 }
3931 async fn search_children(
3932 &self,
3933 query: &str,
3934 ) -> Option<futures_core::stream::BoxStream<'_, String>> {
3935 if !self.caps.contains(ChildCapabilities::SEARCH) {
3936 return None;
3937 }
3938 let q = query.to_lowercase();
3939 let filtered: Vec<String> = self
3940 .names
3941 .iter()
3942 .filter(|n| n.to_lowercase().contains(&q))
3943 .cloned()
3944 .collect();
3945 Some(Box::pin(futures::stream::iter(filtered)))
3946 }
3947 }
3948
3949 fn build_module_for(router: WireFixture, ns: &str) -> RpcModule<()> {
3950 let mut module = RpcModule::new(());
3951 let arc: Arc<dyn ChildRouter> = Arc::new(router);
3952 register_child_capability_methods(&mut module, ns, arc, None).expect("register");
3953 module
3954 }
3955
3956 #[tokio::test]
3957 async fn child_wire_registers_both_methods_when_both_bits_set() {
3958 let module = build_module_for(
3959 WireFixture {
3960 names: vec!["alpha".into(), "beta".into()],
3961 caps: ChildCapabilities::LIST | ChildCapabilities::SEARCH,
3962 },
3963 "fixture",
3964 );
3965 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3966 assert!(
3967 names.contains(&"fixture.list_children".to_string()),
3968 "expected fixture.list_children, got: {:?}",
3969 names
3970 );
3971 assert!(
3972 names.contains(&"fixture.search_children".to_string()),
3973 "expected fixture.search_children, got: {:?}",
3974 names
3975 );
3976 }
3977
3978 #[tokio::test]
3979 async fn child_wire_registers_nothing_when_no_bits_set() {
3980 let module = build_module_for(
3981 WireFixture {
3982 names: vec!["alpha".into()],
3983 caps: ChildCapabilities::empty(),
3984 },
3985 "fixture",
3986 );
3987 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3988 assert!(
3989 !names.contains(&"fixture.list_children".to_string()),
3990 "fixture.list_children should NOT be registered when cap absent"
3991 );
3992 assert!(
3993 !names.contains(&"fixture.search_children".to_string()),
3994 "fixture.search_children should NOT be registered when cap absent"
3995 );
3996 }
3997
3998 #[tokio::test]
3999 async fn child_wire_registers_only_list_when_only_list_bit() {
4000 let module = build_module_for(
4001 WireFixture {
4002 names: vec!["alpha".into()],
4003 caps: ChildCapabilities::LIST,
4004 },
4005 "fixture",
4006 );
4007 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4008 assert!(names.contains(&"fixture.list_children".to_string()));
4009 assert!(!names.contains(&"fixture.search_children".to_string()));
4010 }
4011
4012 }