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 NotNeeded {
111 method: String,
113 },
114}
115
116#[derive(Debug, Clone, Serialize, Deserialize)]
117#[serde(tag = "error_kind", rename_all = "snake_case")]
118pub enum TransportErrorKind {
119 ConnectionRefused { host: String, port: u16 },
120 ConnectionTimeout { host: String, port: u16 },
121 ProtocolError { message: String },
122 NetworkError { message: String },
123}
124
125impl std::fmt::Display for TransportErrorKind {
126 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127 match self {
128 TransportErrorKind::ConnectionRefused { host, port } => {
129 write!(f, "Connection refused to {}:{}", host, port)
130 }
131 TransportErrorKind::ConnectionTimeout { host, port } => {
132 write!(f, "Connection timeout to {}:{}", host, port)
133 }
134 TransportErrorKind::ProtocolError { message } => {
135 write!(f, "Protocol error: {}", message)
136 }
137 TransportErrorKind::NetworkError { message } => {
138 write!(f, "Network error: {}", message)
139 }
140 }
141 }
142}
143
144impl std::fmt::Display for PlexusError {
145 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146 match self {
147 PlexusError::ActivationNotFound(name) => write!(f, "Activation not found: {}", name),
148 PlexusError::MethodNotFound { activation, method } => {
149 write!(f, "Method not found: {}.{}", activation, method)
150 }
151 PlexusError::InvalidParams { param, problem } => match (param, problem) {
155 (Some(p), ParamProblem::Missing) => {
156 write!(f, "Invalid params: missing field: {}", p)
157 }
158 (None, ParamProblem::Missing) => {
159 write!(f, "Invalid params: a required parameter is missing")
160 }
161 (Some(p), ParamProblem::Malformed { detail }) => {
162 write!(f, "Invalid params: {}: {}", p, detail)
163 }
164 (None, ParamProblem::Malformed { detail }) => {
165 write!(f, "Invalid params: {}", detail)
166 }
167 },
168 PlexusError::ExecutionError(msg) => write!(f, "Execution error: {}", msg),
169 PlexusError::HandleNotSupported(activation) => {
170 write!(f, "Handle resolution not supported by activation: {}", activation)
171 }
172 PlexusError::TransportError(kind) => match kind {
173 TransportErrorKind::ConnectionRefused { host, port } => {
174 write!(f, "Connection refused to {}:{}", host, port)
175 }
176 TransportErrorKind::ConnectionTimeout { host, port } => {
177 write!(f, "Connection timeout to {}:{}", host, port)
178 }
179 TransportErrorKind::ProtocolError { message } => {
180 write!(f, "Protocol error: {}", message)
181 }
182 TransportErrorKind::NetworkError { message } => {
183 write!(f, "Network error: {}", message)
184 }
185 }
186 PlexusError::Unauthenticated(msg) => write!(f, "Authentication required: {}", msg),
187 PlexusError::Forbidden { reason } => match reason {
188 AuthzDenyReason::MissingScope { scope } => {
192 write!(f, "Forbidden: missing required scope '{}'", scope)
193 }
194 AuthzDenyReason::TenantBoundary => write!(f, "Forbidden: tenant boundary"),
195 AuthzDenyReason::NotAccepted => write!(f, "Forbidden: call not accepted"),
196 AuthzDenyReason::MissingGrant { grant, scope, .. } if scope.is_everywhere() => {
198 write!(f, "needs {}", grant)
199 }
200 AuthzDenyReason::MissingGrant { grant, scope, .. } => {
201 write!(f, "needs {} on {}", grant, scope)
202 }
203 AuthzDenyReason::NotNeeded { method } => {
204 write!(f, "`{method}` is not among the methods this child needs (its schema's `needs`)")
205 }
206 },
207 }
208 }
209}
210
211impl std::error::Error for PlexusError {}
212
213impl PlexusError {
214 pub fn invalid_params(detail: impl Into<String>) -> Self {
217 PlexusError::InvalidParams { param: None, problem: ParamProblem::Malformed { detail: detail.into() } }
218 }
219
220 pub fn malformed_param(param: impl Into<String>, detail: impl Into<String>) -> Self {
223 PlexusError::InvalidParams {
224 param: Some(param.into()),
225 problem: ParamProblem::Malformed { detail: detail.into() },
226 }
227 }
228}
229
230impl From<&PlexusError> for RemoteError {
248 fn from(e: &PlexusError) -> Self {
249 match e {
250 PlexusError::ActivationNotFound(name) => RemoteError::ActivationNotFound {
251 activation: name.clone(),
252 },
253 PlexusError::MethodNotFound { activation, method } => RemoteError::MethodNotFound {
254 activation: activation.clone(),
255 method: method.clone(),
256 },
257 PlexusError::InvalidParams { param, problem } => RemoteError::InvalidParams {
258 param: param.clone(),
259 problem: problem.clone(),
260 },
261 PlexusError::ExecutionError(message) => RemoteError::Execution {
262 message: message.clone(),
263 },
264 PlexusError::HandleNotSupported(activation) => RemoteError::HandleNotSupported {
265 activation: activation.clone(),
266 },
267 PlexusError::TransportError(kind) => RemoteError::Execution {
268 message: kind.to_string(),
269 },
270 PlexusError::Unauthenticated(_) => RemoteError::Unauthenticated,
271 PlexusError::Forbidden { reason } => RemoteError::Forbidden {
272 reason: match reason {
273 AuthzDenyReason::MissingScope { scope } => DenyReason::MissingScope {
274 scope: scope.as_str().to_string(),
275 },
276 AuthzDenyReason::TenantBoundary => DenyReason::TenantBoundary,
277 AuthzDenyReason::NotAccepted => DenyReason::NotAccepted,
278 AuthzDenyReason::NotNeeded { method } => DenyReason::NotNeeded { method: method.clone() },
279 AuthzDenyReason::MissingGrant { grant, scope, roles, held_on } => {
282 DenyReason::MissingGrant {
283 grant: grant.as_str().to_string(),
284 scope: scope.as_str().to_string(),
285 roles: roles.iter().map(|r| r.as_str().to_string()).collect(),
286 held_on: held_on.iter().map(|s| s.as_str().to_string()).collect(),
287 }
288 }
289 },
290 },
291 }
292 }
293}
294
295async fn in_child<F>(ctx: Option<crate::call::CallContext>, routed: F) -> Result<PlexusStream, PlexusError>
298where
299 F: std::future::Future<Output = Result<PlexusStream, PlexusError>>,
300{
301 match ctx {
302 Some(ctx) => in_call(ctx, routed).await,
303 None => routed.await,
304 }
305}
306
307async fn in_call<F>(ctx: crate::call::CallContext, routed: F) -> Result<PlexusStream, PlexusError>
311where
312 F: std::future::Future<Output = Result<PlexusStream, PlexusError>>,
313{
314 let stream = crate::call::scope(ctx.clone(), routed).await?;
315 Ok(Box::pin(crate::call::InCall::new(ctx, stream)))
316}
317
318fn plexus_error_code(e: &PlexusError) -> i32 {
327 match e {
328 PlexusError::Unauthenticated(_) => -32001,
329 PlexusError::Forbidden { .. } => -32003,
330 PlexusError::InvalidParams { .. } => -32602,
331 PlexusError::MethodNotFound { .. } | PlexusError::ActivationNotFound(_) => -32601,
332 _ => -32000,
333 }
334}
335
336pub fn plexus_error_to_jsonrpc(e: &PlexusError) -> jsonrpsee::types::ErrorObjectOwned {
347 let error = RemoteError::from(e);
348 jsonrpsee::types::ErrorObject::owned(plexus_error_code(e), error.to_string(), Some(error))
349}
350
351pub(crate) fn error_item_raw(ns: &str, e: &PlexusError) -> Option<Box<serde_json::value::RawValue>> {
357 serde_json::value::to_raw_value(&error_item(ns, e)).ok()
358}
359
360pub fn error_item(ns: &str, e: &PlexusError) -> serde_json::Value {
366 let item = super::types::PlexusStreamItem::from_plexus_error(
369 super::types::StreamMetadata::new(vec![ns.into()], super::context::PlexusContext::hash()),
370 e,
371 false,
372 );
373 serde_json::to_value(&item).unwrap_or(serde_json::Value::Null)
374}
375
376#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
381pub struct ActivationInfo {
382 pub namespace: String,
383 pub version: String,
384 pub description: String,
385 pub methods: Vec<String>,
386}
387
388#[async_trait]
393pub trait Activation: Send + Sync + 'static {
394 type Methods: MethodEnumSchema;
395
396 fn namespace(&self) -> &str;
397 fn version(&self) -> &str;
398 fn description(&self) -> &str { "No description available" }
400 fn long_description(&self) -> Option<&str> { None }
402 fn methods(&self) -> Vec<&str>;
403 fn method_help(&self, _method: &str) -> Option<String> { None }
404 fn plugin_id(&self) -> uuid::Uuid {
408 let major_version = self.version().split('.').next().unwrap_or("0");
409 uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, format!("{}@{}", self.namespace(), major_version).as_bytes())
410 }
411
412 async fn call(
413 &self,
414 method: &str,
415 params: Value,
416 auth: Option<&super::auth::AuthContext>,
417 raw_ctx: Option<&crate::request::RawRequestContext>,
418 ) -> Result<PlexusStream, PlexusError>;
419 async fn resolve_handle(&self, _handle: &Handle) -> Result<PlexusStream, PlexusError> {
420 Err(PlexusError::HandleNotSupported(self.namespace().to_string()))
421 }
422
423 fn into_rpc_methods(self) -> Methods where Self: Sized;
424
425 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
438 Vec::new()
439 }
440
441 fn slot_schema() -> Option<PluginSchema>
448 where
449 Self: Sized,
450 {
451 None
452 }
453
454 fn needs(&self) -> Option<Vec<super::schema::Need>> {
459 None
460 }
461
462 fn plugin_schema(&self) -> PluginSchema {
464 let methods: Vec<MethodSchema> = self.methods().iter().map(|name| {
468 let desc = self.method_help(name).unwrap_or_default();
469 MethodSchema::new(name.to_string(), desc, String::new()).with_content_hash()
470 }).collect();
471
472 if let Some(long_desc) = self.long_description() {
473 PluginSchema::leaf_with_long_description(
474 self.namespace(),
475 self.version(),
476 self.description(),
477 long_desc,
478 methods,
479 )
480 } else {
481 PluginSchema::leaf(
482 self.namespace(),
483 self.version(),
484 self.description(),
485 methods,
486 )
487 }
488 }
489}
490
491bitflags! {
496 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
525 #[deprecated(
526 since = "0.5",
527 note = "Use MethodRole::DynamicChild { list_method, search_method } instead. Removed in 0.7."
528 )]
529 pub struct ChildCapabilities: u32 {
530 const LIST = 0b0000_0001;
532 const SEARCH = 0b0000_0010;
535 }
536}
537
538#[async_trait]
555pub trait ChildRouter: Send + Sync {
556 fn router_namespace(&self) -> &str;
558
559 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
561
562 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>>;
564
565 async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, super::peer::PeerError> {
572 Ok(self.get_child(name).await)
573 }
574
575 #[allow(deprecated)]
580 fn capabilities(&self) -> ChildCapabilities {
581 ChildCapabilities::empty()
582 }
583
584 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
592 None
593 }
594
595 async fn search_children(&self, _query: &str) -> Option<BoxStream<'_, String>> {
603 None
604 }
605
606 fn forward_policy_for(
621 &self,
622 _callee_ns: &str,
623 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
624 None
625 }
626
627 fn router_schema(&self) -> Option<PluginSchema> {
634 None
635 }
636
637 fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
650 Vec::new()
651 }
652
653 fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
662 plexus_auth_core::Principal::Anonymous
663 }
664}
665
666pub async fn route_to_child<T: ChildRouter + ?Sized>(
697 parent: &T,
698 method: &str,
699 params: Value,
700 auth: Option<&super::auth::AuthContext>,
701 raw_ctx: Option<&crate::request::RawRequestContext>,
702) -> Result<PlexusStream, PlexusError> {
703 if let Some((child_name, rest)) = method.split_once('.') {
705 let found = match parent.peer_child(child_name).await {
707 Ok(found) => found,
708 Err(e) => {
709 return Ok(e.stream(vec![parent.router_namespace().to_string(), child_name.to_string()]));
710 }
711 };
712 if let Some(child) = found {
713 let policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy> = parent
723 .forward_policy_for(child_name)
724 .unwrap_or_else(|| {
725 std::sync::Arc::new(plexus_auth_core::IdentityOnly)
726 as std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>
727 });
728
729 let callee_method_str = format!("{}.{}", child_name, rest);
735 let callee_method = plexus_auth_core::MethodPath::try_new(callee_method_str.as_str())
736 .map_err(|e| PlexusError::ExecutionError(format!(
737 "framework-built MethodPath rejected: {} ({:?})",
738 callee_method_str, e
739 )))?;
740 let site = plexus_auth_core::CallSite::new(
741 parent.framework_stamped_principal(),
742 callee_method,
743 );
744
745 let anonymous_owned;
749 let caller_ctx: &super::auth::AuthContext = match auth {
750 Some(ctx) => ctx,
751 None => {
752 anonymous_owned = super::auth::AuthContext::anonymous();
753 &anonymous_owned
754 }
755 };
756 let derivation = policy.forward(caller_ctx, &site);
757
758 tracing::trace!(
779 target: "plexus::audit",
780 policy = policy.name().as_str(),
781 callee_method = %site.callee_method.as_str(),
782 derivation_keep_verified_user = derivation.keep_verified_user,
783 derivation_keep_roles = derivation.keep_roles,
784 derivation_keep_capabilities = derivation.keep_capabilities,
785 derivation_keep_metadata = derivation.keep_metadata,
786 "forward_policy_applied (audit-record emission stubbed pending PRIVACY-1)"
787 );
788
789 let outer = crate::call::context().ok();
802 let keeps_identity = derivation.keep_verified_user;
803 return match auth {
804 Some(caller_ctx) => {
805 caller_ctx
806 .with_callee_context(&derivation, &site.caller, |callee_ctx| async move {
807 let ctx = outer.map(|o| o.for_child(Some(&callee_ctx), keeps_identity));
808 in_child(ctx, child.router_call(rest, params, Some(&callee_ctx), raw_ctx)).await
809 })
810 .await
811 }
812 None => {
813 let ctx = outer.map(|o| o.for_child(None, keeps_identity));
814 in_child(ctx, child.router_call(rest, params, None, raw_ctx)).await
815 }
816 };
817 }
818 return Err(PlexusError::ActivationNotFound(child_name.to_string()));
819 }
820
821 Err(PlexusError::MethodNotFound {
823 activation: parent.router_namespace().to_string(),
824 method: method.to_string(),
825 })
826}
827
828struct ArcChildRouter(Arc<dyn ChildRouter>);
832
833#[async_trait]
834impl ChildRouter for ArcChildRouter {
835 fn router_namespace(&self) -> &str {
836 self.0.router_namespace()
837 }
838
839 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
840 self.0.router_call(method, params, auth, raw_ctx).await
841 }
842
843 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
844 self.0.get_child(name).await
845 }
846
847 async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, super::peer::PeerError> {
848 self.0.peer_child(name).await
849 }
850
851 #[allow(deprecated)]
852 fn capabilities(&self) -> ChildCapabilities {
853 self.0.capabilities()
854 }
855
856 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
857 self.0.list_children().await
858 }
859
860 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
861 self.0.search_children(query).await
862 }
863
864 fn forward_policy_for(
868 &self,
869 callee_ns: &str,
870 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
871 self.0.forward_policy_for(callee_ns)
872 }
873
874 fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
875 self.0.framework_stamped_principal()
876 }
877
878 fn router_schema(&self) -> Option<PluginSchema> {
879 self.0.router_schema()
880 }
881
882 fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
883 self.0.router_static_child_schemas()
884 }
885}
886
887#[async_trait]
892#[allow(dead_code)] pub(crate) trait ActivationObject: Send + Sync + 'static {
894 fn namespace(&self) -> &str;
895 fn version(&self) -> &str;
896 fn description(&self) -> &str;
897 fn long_description(&self) -> Option<&str>;
898 fn methods(&self) -> Vec<&str>;
899 fn method_help(&self, method: &str) -> Option<String>;
900 fn plugin_id(&self) -> uuid::Uuid;
901 async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
902 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError>;
903 fn plugin_schema(&self) -> PluginSchema;
904 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)>;
905 fn schema(&self) -> Schema;
906 fn needs(&self) -> Option<Vec<super::schema::Need>> {
908 None
909 }
910}
911
912struct ActivationWrapper<A: Activation> {
913 inner: A,
914}
915
916#[async_trait]
917impl<A: Activation> ActivationObject for ActivationWrapper<A> {
918 fn namespace(&self) -> &str { self.inner.namespace() }
919 fn version(&self) -> &str { self.inner.version() }
920 fn description(&self) -> &str { self.inner.description() }
921 fn long_description(&self) -> Option<&str> { self.inner.long_description() }
922 fn methods(&self) -> Vec<&str> { self.inner.methods() }
923 fn method_help(&self, method: &str) -> Option<String> { self.inner.method_help(method) }
924 fn plugin_id(&self) -> uuid::Uuid { self.inner.plugin_id() }
925
926 async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
927 self.inner.call(method, params, auth, raw_ctx).await
928 }
929
930 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
931 self.inner.resolve_handle(handle).await
932 }
933
934 fn plugin_schema(&self) -> PluginSchema { self.inner.plugin_schema() }
935
936 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> { self.inner.static_child_schemas() }
937
938 fn needs(&self) -> Option<Vec<super::schema::Need>> { self.inner.needs() }
939
940 fn schema(&self) -> Schema {
941 let schema = schemars::schema_for!(A::Methods);
942 serde_json::from_value(serde_json::to_value(schema).expect("serialize"))
943 .expect("parse schema")
944 }
945}
946
947#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
952#[serde(tag = "event", rename_all = "snake_case")]
953pub enum HashEvent {
954 Hash { value: String },
955}
956
957#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
959#[serde(tag = "event", rename_all = "snake_case")]
960pub enum SchemaEvent {
961 Schema(PluginSchema),
963}
964
965#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
967pub struct PluginHashes {
968 pub namespace: String,
969 pub self_hash: String,
970 #[serde(skip_serializing_if = "Option::is_none")]
971 pub children_hash: Option<String>,
972 pub hash: String,
973 #[serde(skip_serializing_if = "Option::is_none")]
975 pub children: Option<Vec<ChildHashes>>,
976}
977
978#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
980pub struct ChildHashes {
981 pub namespace: String,
982 pub hash: String,
983}
984
985
986#[derive(Debug, Clone)]
992pub struct PluginEntry {
993 pub id: uuid::Uuid,
995 pub path: String,
997 pub plugin_type: String,
999}
1000
1001#[derive(Default)]
1006pub struct PluginRegistry {
1007 by_id: HashMap<uuid::Uuid, PluginEntry>,
1009 by_path: HashMap<String, uuid::Uuid>,
1011}
1012
1013#[derive(Clone)]
1017pub struct PluginRegistrySnapshot {
1018 by_id: HashMap<uuid::Uuid, PluginEntry>,
1019 by_path: HashMap<String, uuid::Uuid>,
1020}
1021
1022impl PluginRegistrySnapshot {
1023 pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
1025 self.by_id.get(&id).map(|e| e.path.as_str())
1026 }
1027
1028 pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
1030 self.by_path.get(path).copied()
1031 }
1032
1033 pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
1035 self.by_id.get(&id)
1036 }
1037
1038 pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
1040 self.by_id.values()
1041 }
1042
1043 pub fn len(&self) -> usize {
1045 self.by_id.len()
1046 }
1047
1048 pub fn is_empty(&self) -> bool {
1050 self.by_id.is_empty()
1051 }
1052}
1053
1054impl PluginRegistry {
1055 pub fn new() -> Self {
1057 Self::default()
1058 }
1059
1060 pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
1062 self.by_id.get(&id).map(|e| e.path.as_str())
1063 }
1064
1065 pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
1067 self.by_path.get(path).copied()
1068 }
1069
1070 pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
1072 self.by_id.get(&id)
1073 }
1074
1075 pub fn register(&mut self, id: uuid::Uuid, path: String, plugin_type: String) {
1077 let entry = PluginEntry { id, path: path.clone(), plugin_type };
1078 self.by_id.insert(id, entry);
1079 self.by_path.insert(path, id);
1080 }
1081
1082 pub(crate) fn remove(&mut self, id: uuid::Uuid) {
1085 if let Some(entry) = self.by_id.remove(&id) {
1086 if self.by_path.get(&entry.path) == Some(&id) {
1087 self.by_path.remove(&entry.path);
1088 }
1089 }
1090 }
1091
1092 pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
1094 self.by_id.values()
1095 }
1096
1097 pub fn len(&self) -> usize {
1099 self.by_id.len()
1100 }
1101
1102 pub fn is_empty(&self) -> bool {
1104 self.by_id.is_empty()
1105 }
1106}
1107
1108fn build_info_payload(
1121 namespace: &str,
1122 caps: Option<&plexus_auth_core::BackendAuthCapabilities>,
1123) -> serde_json::Value {
1124 let advertised = match caps {
1125 Some(c) => c.clone(),
1126 None => plexus_auth_core::BackendAuthCapabilities::anonymous_default(),
1127 };
1128 serde_json::json!({
1129 "backend": namespace,
1130 "auth_capabilities": advertised,
1131 })
1132}
1133
1134fn fill_site_hints_in_schema_stream(
1145 stream: PlexusStream,
1146 site: plexus_auth_core::AttachmentSite,
1147) -> PlexusStream {
1148 use futures::StreamExt;
1149 Box::pin(stream.map(move |item| match item {
1150 super::types::PlexusStreamItem::Data {
1151 metadata,
1152 content_type,
1153 content,
1154 } if content_type.ends_with(".schema") || content_type.ends_with(".method_schema") => {
1155 let content = match content.decode::<super::SchemaResult>() {
1157 Ok(mut result) => {
1158 result.fill_site_hints(&site);
1159 match serde_json::to_value(&result) {
1160 Ok(v) => v.into(),
1161 Err(_) => content,
1162 }
1163 }
1164 Err(_) => content,
1165 };
1166 super::types::PlexusStreamItem::Data {
1167 metadata,
1168 content_type,
1169 content,
1170 }
1171 }
1172 other => other,
1173 }))
1174}
1175
1176pub(crate) struct DynamicHubInner {
1177 namespace: String,
1179 root: std::sync::RwLock<Arc<super::service_root::Table>>,
1188 root_watch: tokio::sync::watch::Sender<String>,
1190 registry: std::sync::RwLock<PluginRegistry>,
1192 pending_rpc: std::sync::Mutex<Vec<Box<dyn FnOnce() -> Methods + Send>>>,
1193 auth_capabilities: Option<plexus_auth_core::BackendAuthCapabilities>,
1204 forward_policies: super::forward_registry::ForwardPolicyRegistry,
1213 scope_registry: Option<Arc<plexus_auth_core::ScopeRegistry>>,
1219 default_deny: bool,
1226 audit_sink: Arc<dyn plexus_auth_core::AuditSink>,
1232 duplex_gate: std::sync::OnceLock<super::duplex_gate::DuplexGate>,
1234 gate_index: std::sync::RwLock<Option<Arc<GateIndex>>>,
1245 input_index: std::sync::RwLock<Option<Arc<HashMap<String, bool>>>>,
1249 gate: Option<Arc<plexus_auth_core::grants::Gate>>,
1253 signed_in_grants: std::collections::BTreeSet<String>,
1257 resource_metadata: Option<String>,
1260 auth_catalog: Option<super::auth_activation::Catalog>,
1264 describe: super::view::Cache,
1268 ir_cache: super::ir::IrCache,
1271 notices: tokio::sync::broadcast::Sender<super::parent::Notice>,
1274 config: std::sync::OnceLock<super::config::Config>,
1276}
1277
1278#[derive(Debug, Default)]
1281pub(crate) struct GateIndex {
1282 methods: HashMap<String, super::scope_gate::MethodGateInfo>,
1283 slots: super::slots::Slots,
1284}
1285
1286impl GateIndex {
1287 fn info(&self, method: &str) -> Option<&super::scope_gate::MethodGateInfo> {
1290 self.methods.get(method).or_else(|| self.slots.resolve(method).and_then(|k| self.methods.get(&k)))
1291 }
1292}
1293
1294
1295#[derive(Clone)]
1317pub struct DynamicHub {
1318 inner: Arc<DynamicHubInner>,
1319}
1320
1321struct IrView {
1323 base: Arc<super::view::Described>,
1324 shaped: Option<Arc<super::view::Shaped>>,
1326 hash: String,
1328}
1329
1330impl IrView {
1331 fn root(&self) -> PluginSchema {
1332 match &self.shaped {
1333 Some(v) => v.service.clone(),
1334 None => self.base.service.clone(),
1335 }
1336 }
1337
1338 fn top(&self, ns: &str) -> Option<PluginSchema> {
1339 match &self.shaped {
1340 Some(v) => v.schema_of(&self.base, ns).filter(|_| ns != v.service.namespace),
1341 None => self.base.activations.iter().find(|a| a.namespace == ns).cloned(),
1342 }
1343 }
1344
1345 fn shows(&self, ns: &str) -> bool {
1346 match &self.shaped {
1347 Some(v) => v.shows(ns),
1348 None => self.base.activations.iter().any(|a| a.namespace == ns),
1349 }
1350 }
1351
1352 fn names(&self, service: &str) -> Vec<String> {
1356 let mut out = vec![String::new()];
1357 out.extend(self.base.activations.iter().map(|a| a.namespace.clone()).filter(|ns| ns != service && self.shows(ns)));
1358 for path in self.base.nested() {
1359 let mut segs = path.split('.');
1360 let (Some(top), Some(entry)) = (segs.next(), segs.next()) else { continue };
1361 let reached = self.shows(top)
1362 && match &self.shaped {
1363 Some(v) => v.method_of(&self.base, top, entry).is_some(),
1364 None => true,
1365 };
1366 if reached {
1367 out.push(path.to_string());
1368 }
1369 }
1370 out
1371 }
1372}
1373
1374impl DynamicHub {
1379 pub(crate) fn from_inner(inner: Arc<DynamicHubInner>) -> Self {
1381 Self { inner }
1382 }
1383
1384 pub fn new(namespace: impl Into<String>) -> Self {
1410 Self {
1411 inner: Arc::new(DynamicHubInner {
1412 namespace: namespace.into(),
1413 root: Default::default(),
1414 root_watch: tokio::sync::watch::Sender::new(String::new()),
1415 registry: std::sync::RwLock::new(PluginRegistry::new()),
1416 pending_rpc: std::sync::Mutex::new(Vec::new()),
1417 auth_capabilities: None,
1418 forward_policies: super::forward_registry::ForwardPolicyRegistry::new(),
1419 scope_registry: None,
1420 default_deny: false,
1421 audit_sink: Arc::new(plexus_auth_core::TracingAuditSink),
1422 duplex_gate: std::sync::OnceLock::new(),
1423 gate_index: Default::default(),
1424 input_index: Default::default(),
1425 gate: None,
1426 signed_in_grants: std::collections::BTreeSet::new(),
1427 resource_metadata: None,
1428 auth_catalog: None,
1429 describe: Default::default(),
1430 ir_cache: Default::default(),
1431 notices: tokio::sync::broadcast::Sender::new(64),
1432 config: std::sync::OnceLock::new(),
1433 }),
1434 }
1435 }
1436
1437 fn inner_mut(&mut self, refused: &str) -> &mut DynamicHubInner {
1442 let inner = Arc::get_mut(&mut self.inner).expect(refused);
1443 inner.describe.reset();
1444 *inner.gate_index.get_mut().unwrap_or_else(|p| p.into_inner()) = None;
1445 *inner.input_index.get_mut().unwrap_or_else(|p| p.into_inner()) = None;
1446 inner
1447 }
1448
1449
1450 pub fn with_scope_registry(mut self, registry: plexus_auth_core::ScopeRegistry) -> Self {
1470 let inner = self.inner_mut("Cannot set scope_registry: DynamicHub has multiple references");
1471 inner.scope_registry = Some(Arc::new(registry));
1472 self
1473 }
1474
1475 pub fn with_default_deny(mut self, default_deny: bool) -> Self {
1494 let inner = self.inner_mut("Cannot set default_deny: DynamicHub has multiple references");
1495 inner.default_deny = default_deny;
1496 self
1497 }
1498
1499 pub fn with_audit_sink(mut self, sink: Arc<dyn plexus_auth_core::AuditSink>) -> Self {
1510 let inner = self.inner_mut("Cannot set audit_sink: DynamicHub has multiple references");
1511 inner.audit_sink = sink;
1512 self
1513 }
1514
1515 pub fn with_gate(mut self, gate: Arc<plexus_auth_core::grants::Gate>) -> Self {
1540 let inner = self.inner_mut("Cannot set gate: DynamicHub has multiple references");
1541 inner.gate = Some(gate);
1542 self
1543 }
1544
1545 pub fn gate(&self) -> Option<&Arc<plexus_auth_core::grants::Gate>> {
1547 self.inner.gate.as_ref()
1548 }
1549
1550 pub fn with_resource_metadata(mut self, url: impl Into<String>) -> Self {
1555 let inner = self.inner_mut("Cannot set resource_metadata: DynamicHub has multiple references");
1556 inner.resource_metadata = Some(url.into());
1557 self
1558 }
1559
1560 pub fn with_signed_in_grants<I, S>(mut self, grants: I) -> Self
1567 where
1568 I: IntoIterator<Item = S>,
1569 S: Into<String>,
1570 {
1571 let inner = self.inner_mut("Cannot set signed_in grants: DynamicHub has multiple references");
1572 inner.signed_in_grants.extend(grants.into_iter().map(Into::into));
1573 self
1574 }
1575
1576 pub fn with_auth(mut self, setup: super::auth_activation::AuthSetup) -> Self {
1593 let catalog = super::auth_activation::Catalog::default();
1594 catalog.add(&Activation::plugin_schema(&self));
1595 for e in self.table().entries.values() {
1596 catalog.add(&e.object.plugin_schema());
1597 }
1598 for child in self.described_children() {
1602 catalog.add(&child);
1603 }
1604 let (_, untyped) = self.slot_children();
1605 catalog.add_slots(&untyped);
1606 let (auth, gate) = super::auth_activation::AuthActivation::mount(setup, catalog.clone());
1607 {
1608 let inner = self.inner_mut("Cannot mount auth: DynamicHub has multiple references");
1609 inner.auth_catalog = Some(catalog);
1610 inner.gate = Some(Arc::new(gate));
1611 }
1612 self.register(auth)
1613 .with_signed_in_grants(super::auth_activation::SIGNED_IN_GRANTS.iter().copied())
1614 }
1615
1616 pub fn view(&self, caller: Option<&super::auth::AuthContext>) -> super::view::View {
1634 match self.inner.gate.as_ref() {
1635 None => self.described().whole(),
1636 Some(_) => {
1637 let (base, view) = self.shaped(caller);
1638 view.view(&base)
1639 }
1640 }
1641 }
1642
1643 pub fn schema_moved(&self) {
1649 self.inner.describe.schema_moved();
1650 }
1651
1652 fn described(&self) -> Arc<super::view::Described> {
1656 let at = self.inner.describe.schema_generation();
1657 match self.inner.describe.base(at) {
1658 Some(cell) => cell.get_or_init(|| Arc::new(self.describe_now())).clone(),
1659 None => Arc::new(self.describe_now()),
1660 }
1661 }
1662
1663 fn describe_now(&self) -> super::view::Described {
1664 let service = Activation::plugin_schema(self);
1665 let activations: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).collect();
1666 super::view::Described::new(service, activations, self.described_children())
1670 }
1671
1672 fn shaped(&self, caller: Option<&super::auth::AuthContext>) -> (Arc<super::view::Described>, Arc<super::view::Shaped>) {
1678 let gate = self.inner.gate.as_ref().expect("a view is a gated service's");
1679 let schema_at = self.inner.describe.schema_generation();
1680 let grants_at = gate.generation().current();
1681 let (caller, _) = super::grant_gate::standing(gate, caller);
1684 let who = caller.and_then(|c| gate.fingerprint(c));
1685 let shape = |base: &super::view::Described| {
1686 Arc::new(super::view::shape(gate, &self.inner.signed_in_grants, who.as_ref(), base))
1687 };
1688 match self.inner.describe.view(schema_at, grants_at, &who) {
1689 Some((base, view)) => {
1690 let base = base.get_or_init(|| Arc::new(self.describe_now())).clone();
1691 let view = view.get_or_init(|| shape(&base)).clone();
1692 (base, view)
1693 }
1694 None => {
1695 let base = Arc::new(self.describe_now());
1696 let view = shape(&base);
1697 (base, view)
1698 }
1699 }
1700 }
1701
1702 pub fn info(&self, caller: Option<&super::auth::AuthContext>) -> serde_json::Value {
1708 if self.inner.gate.is_none() {
1709 return build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1710 }
1711 let (base, view) = self.shaped(caller);
1713 view.info
1714 .get_or_init(|| {
1715 let mut payload = build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1716 if let Some(obj) = payload.as_object_mut() {
1717 obj.insert("view".into(), view.kind.as_str().into());
1718 obj.insert("view_hash".into(), view.hash.clone().into());
1719 if view.kind == super::ViewKind::Anonymous {
1720 let mut auth = serde_json::Map::new();
1721 auth.insert("methods".into(), view.public_methods(&base).into());
1722 if let Some(url) = self.inner.resource_metadata.as_ref() {
1723 auth.insert("resource_metadata".into(), url.clone().into());
1724 }
1725 obj.insert("auth".into(), serde_json::Value::Object(auth));
1726 }
1727 }
1728 payload
1729 })
1730 .clone()
1731 }
1732
1733 async fn introspect_in_view(
1739 &self,
1740 method: &str,
1741 params: &Value,
1742 auth: Option<&super::auth::AuthContext>,
1743 raw_ctx: Option<&crate::request::RawRequestContext>,
1744 ) -> Option<Result<PlexusStream, PlexusError>> {
1745 let (ns, rest) = method.split_once('.')?;
1746 let hub_ns = self.inner.namespace.as_str();
1747 let (base, view) = self.shaped(auth);
1749 let not_found = || PlexusError::ActivationNotFound(ns.to_string());
1750 let content: serde_json::Value = match rest {
1751 "schema" => {
1752 if !view.shows(ns) {
1753 return Some(Err(not_found()));
1754 }
1755 let mut result = match params.get("method").and_then(|v| v.as_str()) {
1756 Some(name) => match view.method_of(&base, ns, name) {
1757 Some(m) => super::SchemaResult::Method(m),
1758 None => {
1759 return Some(Err(PlexusError::MethodNotFound {
1760 activation: ns.to_string(),
1761 method: name.to_string(),
1762 }))
1763 }
1764 },
1765 None => super::SchemaResult::Plugin(view.schema_of(&base, ns)?),
1766 };
1767 if let Some(site) = self.derived_site_hint() {
1768 result.fill_site_hints(&site);
1769 }
1770 serde_json::to_value(&result).ok()?
1771 }
1772 "hash" if ns == hub_ns => serde_json::to_value(HashEvent::Hash { value: view.hash.clone() }).ok()?,
1773 "hashes" if ns == hub_ns => serde_json::to_value(view.hashes()).ok()?,
1774 r if r.ends_with(".schema") => {
1775 if !view.shows(ns) {
1776 return Some(Err(not_found()));
1777 }
1778 let name = r.trim_end_matches(".schema");
1779 match view.method_of(&base, ns, name) {
1780 Some(m) if matches!(m.role, super::MethodRole::Rpc) => {
1781 serde_json::to_value(super::SchemaResult::Method(m)).ok()?
1782 }
1783 Some(_) => return None,
1785 None if name.contains('.') => return None,
1786 None if base.activations.iter().any(|a| a.namespace == ns && a.methods.iter().any(|m| m.role.is_slot())) => return None,
1790 None => {
1791 return Some(Err(PlexusError::MethodNotFound {
1792 activation: ns.to_string(),
1793 method: name.to_string(),
1794 }))
1795 }
1796 }
1797 }
1798 _ => return None,
1799 };
1800 use futures::StreamExt;
1803 let with = |content: serde_json::Value| {
1804 move |item: super::types::PlexusStreamItem| match item {
1807 super::types::PlexusStreamItem::Data { metadata, content_type, .. } => {
1808 super::types::PlexusStreamItem::Data { metadata, content_type, content: content.clone().into() }
1809 }
1810 other => other,
1811 }
1812 };
1813 if self.inner.scope_registry.is_some() || self.inner.default_deny {
1816 let routed = self.route_ungated(method, params.clone(), auth, raw_ctx).await;
1817 return Some(routed.map(|s| -> PlexusStream { Box::pin(s.map(with(content))) }));
1818 }
1819 let key = format!("{method}\n{params}");
1823 if let Some(shell) = base.shell(&key) {
1824 return Some(Ok(Box::pin(futures::stream::iter(shell.answer(content)))));
1825 }
1826 let items: Vec<super::types::PlexusStreamItem> = match self.route_ungated(method, params.clone(), auth, raw_ctx).await {
1827 Ok(s) => s.collect().await,
1828 Err(e) => return Some(Err(e)),
1829 };
1830 if let Some(shell) = super::view::Shell::of(&items) {
1831 base.keep_shell(key, shell);
1832 }
1833 Some(Ok(Box::pin(futures::stream::iter(items.into_iter().map(with(content))))))
1834 }
1835
1836 pub async fn service_ir(
1850 &self,
1851 namespaces: &[String],
1852 caller: Option<&super::auth::AuthContext>,
1853 ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
1854 let roots = super::ir::roots(&self.inner.namespace, namespaces);
1855 let view = self.ir_view(caller);
1856 let permitted = match self.inner.scope_registry.is_some() || self.inner.default_deny {
1857 false => None,
1858 true => {
1859 let mut answered = Vec::new();
1863 for name in view.names(&self.inner.namespace) {
1864 let under = roots.iter().any(|r| {
1865 let r = r.join(".");
1866 r.is_empty() || name == r || name.starts_with(&format!("{r}."))
1867 });
1868 if under && self.scope_answers(&self.schema_method(&name), caller).await {
1869 answered.push(name);
1870 }
1871 }
1872 Some(answered)
1873 }
1874 };
1875 let key = super::ir::IrKey { view: view.hash.clone(), roots: roots.clone(), permitted: permitted.clone() };
1876 self.inner
1877 .ir_cache
1878 .get_or_build(key, || async {
1879 let mut schemas: BTreeMap<Vec<String>, Value> = BTreeMap::new();
1880 let mut todo: Vec<Vec<String>> = roots.clone();
1881 while let Some(path) = todo.pop() {
1882 if schemas.contains_key(&path) || permitted.as_ref().is_some_and(|p| !p.contains(&path.join("."))) {
1883 continue;
1884 }
1885 let Some(schema) = self.ir_schema(&view, &path, caller).await else { continue };
1887 for child in schema.get("children").and_then(Value::as_array).into_iter().flatten() {
1888 if let Some(ns) = child.get("namespace").and_then(Value::as_str) {
1889 let mut next = path.clone();
1890 next.push(ns.to_string());
1891 todo.push(next);
1892 }
1893 }
1894 schemas.insert(path, schema);
1895 }
1896 let service = self.inner.namespace.clone();
1897 crate::rt::spawn_blocking(move || super::ir::answer(&service, &roots, &schemas))
1898 .await
1899 .unwrap_or_else(|e| Err(super::ir::IrError::Unreadable { namespace: String::new(), message: format!("the IR's build failed: {e}") }))
1900 })
1901 .await
1902 }
1903
1904 pub fn ir_builds(&self) -> usize {
1907 self.inner.ir_cache.builds()
1908 }
1909
1910 fn ir_view(&self, caller: Option<&super::auth::AuthContext>) -> IrView {
1914 match self.inner.gate {
1915 Some(_) => {
1916 let (base, shaped) = self.shaped(caller);
1917 IrView { hash: shaped.hash.clone(), base, shaped: Some(shaped) }
1918 }
1919 None => {
1920 let base = self.described();
1921 IrView { hash: base.service.hash.clone(), base, shaped: None }
1922 }
1923 }
1924 }
1925
1926 fn schema_method(&self, dotted: &str) -> String {
1928 if dotted.is_empty() { format!("{}.schema", self.inner.namespace) } else { format!("{dotted}.schema") }
1929 }
1930
1931 async fn scope_answers(&self, method: &str, caller: Option<&super::auth::AuthContext>) -> bool {
1934 let registry = self.inner.scope_registry.as_deref().unwrap_or_else(|| super::scope_gate::empty_registry());
1935 super::scope_gate::answers(registry, self.inner.default_deny, method, self.gate_index().info(method), caller).await
1936 }
1937
1938 async fn ir_schema(&self, view: &IrView, path: &[String], caller: Option<&super::auth::AuthContext>) -> Option<Value> {
1943 use futures::StreamExt;
1944 let shown = match path {
1945 [] => Some(view.root()),
1946 [ns] => view.top(ns),
1947 [top, below @ ..] => {
1948 let activation = self.table().entries.get(top.as_str())?.object.clone();
1951 let mut stream = activation.call(&format!("{}.schema", below.join(".")), Value::Null, caller, None).await.ok()?;
1952 if let Some(site) = self.derived_site_hint() {
1953 stream = fill_site_hints_in_schema_stream(stream, site);
1954 }
1955 let items: Vec<super::types::PlexusStreamItem> = stream.collect().await;
1956 return items.into_iter().find_map(|item| match item {
1957 super::types::PlexusStreamItem::Data { content_type, content, .. } if content_type.ends_with(".schema") => {
1958 Some(content.into_value())
1959 }
1960 _ => None,
1961 });
1962 }
1963 };
1964 let mut schema = shown?;
1965 if let Some(site) = self.derived_site_hint() {
1966 schema.fill_site_hints(&site);
1967 }
1968 serde_json::to_value(super::SchemaResult::Plugin(schema)).ok()
1969 }
1970
1971 fn check_ir_names(&self, params: &Value, caller: Option<&super::auth::AuthContext>) -> Result<(), PlexusError> {
1975 let asked = match params.get("namespaces") {
1976 None | Some(Value::Null) => return Ok(()),
1977 Some(Value::Array(a)) => a,
1978 Some(_) => return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")),
1979 };
1980 let most = {
1984 let table = self.table();
1985 1 + table.entries.len() + table.nested
1986 };
1987 if asked.len() > most {
1988 return Err(PlexusError::malformed_param(
1989 "namespaces",
1990 format!("{} namespaces asked; more than this service shows you", asked.len()),
1991 ));
1992 }
1993 let names: std::collections::HashSet<String> = self.ir_view(caller).names(&self.inner.namespace).into_iter().collect();
1994 if asked.len() > names.len() {
1995 return Err(PlexusError::malformed_param(
1996 "namespaces",
1997 format!("{} namespaces asked; this service shows you {}", asked.len(), names.len()),
1998 ));
1999 }
2000 for n in asked {
2001 let Some(n) = n.as_str() else { return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")) };
2002 let known = n == self.inner.namespace || names.contains(n);
2003 if !known {
2004 return Err(PlexusError::malformed_param("namespaces", format!("no namespace `{n}` in this service")));
2005 }
2006 }
2007 Ok(())
2008 }
2009
2010 pub fn declared_roles(&self) -> std::collections::BTreeMap<String, Vec<String>> {
2018 let mut out: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
2019 let schemas = self.table().entries.values().map(|e| e.object.plugin_schema()).chain(self.described_children()).collect::<Vec<_>>();
2023 for schema in schemas {
2024 for (role, grants) in schema.roles {
2025 let entry = out.entry(role).or_default();
2026 for g in grants {
2027 if !entry.contains(&g) {
2028 entry.push(g);
2029 }
2030 }
2031 }
2032 }
2033 out
2034 }
2035
2036 pub fn static_children(&self) -> Vec<PluginSchema> {
2042 self.table()
2043 .entries
2044 .values()
2045 .flat_map(|e| super::children::qualified(&e.object.plugin_schema().namespace, e.object.static_child_schemas()))
2046 .collect()
2047 }
2048
2049 pub fn scope_registry(&self) -> Option<&plexus_auth_core::ScopeRegistry> {
2054 self.inner.scope_registry.as_deref()
2055 }
2056
2057 pub(crate) fn input_terms(&self, method: &str, params: &Value) -> Result<InputTerms, PlexusError> {
2061 if self.inner.gate.is_none() {
2062 return Ok(InputTerms { grant: method.to_string(), targets: Vec::new(), recheck: false });
2063 }
2064 let index = self.gate_index();
2065 let info = index.info(method);
2066 let grant = info.and_then(|i| i.grant.clone()).unwrap_or_else(|| method.to_string());
2067 let open = info.is_some_and(|i| i.public) || self.inner.signed_in_grants.contains(grant.as_str());
2068 let targets = match info.and_then(|i| i.target.as_deref()) {
2069 Some(param) => super::grant_gate::target_values(params, param)?.unwrap_or_default(),
2070 None => Vec::new(),
2071 };
2072 Ok(InputTerms { grant, targets, recheck: !open })
2073 }
2074
2075 pub(crate) fn duplex_gate(&self) -> &super::duplex_gate::DuplexGate {
2078 self.inner.duplex_gate.get_or_init(|| match &self.inner.gate {
2079 Some(gate) => {
2080 let (audit, drain) = plexus_auth_core::audit::AuditQueue::new(1024, self.inner.audit_sink.clone());
2081 crate::rt::spawn(drain);
2082 super::duplex_gate::DuplexGate::new((**gate).clone()).with_audit(audit)
2083 }
2084 None => super::duplex_gate::DuplexGate::ungated(),
2085 })
2086 }
2087
2088 pub(crate) fn may_take_input(&self, method: &str) -> bool {
2093 let kept = self.inner.input_index.read().unwrap_or_else(|p| p.into_inner()).clone();
2094 let index = match kept {
2095 Some(index) => index,
2096 None => {
2097 let own = Activation::plugin_schema(self).methods.into_iter().map(|m| (format!("{}.{}", self.inner.namespace, m.name), m.input.is_some()));
2098 let schemas: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).chain(self.static_children()).collect();
2099 let theirs = schemas.into_iter().flat_map(|schema| {
2100 let ns = schema.namespace;
2101 schema.methods.into_iter().map(move |m| (format!("{ns}.{}", m.name), m.input.is_some()))
2102 });
2103 let index: Arc<HashMap<String, bool>> = Arc::new(own.chain(theirs).collect());
2104 *self.inner.input_index.write().unwrap_or_else(|p| p.into_inner()) = Some(index.clone());
2105 index
2106 }
2107 };
2108 index.get(method).copied().unwrap_or(true)
2109 }
2110
2111 pub fn slot_children(&self) -> (Vec<PluginSchema>, Vec<String>) {
2116 let (mut typed, mut untyped) = (Vec::new(), Vec::new());
2117 let schemas = self.table().entries.values().map(|e| e.object.plugin_schema()).chain(self.static_children()).collect::<Vec<_>>();
2118 for schema in schemas {
2119 super::slots::slot_schemas(&schema, &mut typed, &mut untyped);
2120 }
2121 (typed, untyped)
2122 }
2123
2124 pub fn described_children(&self) -> Vec<PluginSchema> {
2129 let mut out = self.static_children();
2130 out.extend(self.slot_children().0);
2131 out
2132 }
2133
2134 fn gate_index(&self) -> Arc<GateIndex> {
2137 if let Some(index) = self.inner.gate_index.read().unwrap_or_else(|p| p.into_inner()).as_ref() {
2138 return index.clone();
2139 }
2140 let index = Arc::new(self.build_gate_index());
2141 *self.inner.gate_index.write().unwrap_or_else(|p| p.into_inner()) = Some(index.clone());
2142 index
2143 }
2144
2145 fn build_gate_index(&self) -> GateIndex {
2146 {
2147 let mut index = HashMap::new();
2148 for m in &Activation::plugin_schema(self).methods {
2150 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
2151 info.grant = Some(format!("{}.{}", self.inner.namespace, m.name));
2154 index.insert(format!("{}.{}", self.inner.namespace, m.name), info);
2155 }
2156 let (typed, untyped) = self.slot_children();
2168 let activations: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).collect();
2169
2170 let statics = self.static_children();
2171 for schema in activations.iter().chain(statics.iter()).chain(typed.iter()) {
2172 for m in &schema.methods {
2173 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
2174 info.grant = Some(m.grant_or(&schema.namespace));
2175 index.insert(format!("{}.{}", schema.namespace, m.name), info);
2176 }
2177 }
2178 for path in &untyped {
2179 index.insert(
2180 path.clone(),
2181 super::scope_gate::MethodGateInfo { grant: Some(path.clone()), ..Default::default() },
2182 );
2183 }
2184 let slots = super::slots::Slots::of(activations.iter().chain(statics.iter()).chain(typed.iter()), &untyped);
2185 GateIndex { methods: index, slots }
2186 }
2187 }
2188
2189 pub fn with_forward_policy(
2210 mut self,
2211 callee_ns: impl Into<String>,
2212 policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>,
2213 ) -> Self {
2214 let inner = self.inner_mut("Cannot register forward policy: DynamicHub has multiple references");
2215 inner.forward_policies.register(callee_ns, policy);
2216 self
2217 }
2218
2219 pub fn forward_policies(&self) -> &super::forward_registry::ForwardPolicyRegistry {
2224 &self.inner.forward_policies
2225 }
2226
2227 pub fn with_auth_capabilities(
2263 mut self,
2264 caps: plexus_auth_core::BackendAuthCapabilities,
2265 ) -> Self {
2266 let inner = self.inner_mut("Cannot set auth_capabilities: DynamicHub has multiple references");
2267 inner.auth_capabilities = Some(caps);
2268 self
2269 }
2270
2271 pub fn auth_capabilities(&self) -> Option<&plexus_auth_core::BackendAuthCapabilities> {
2278 self.inner.auth_capabilities.as_ref()
2279 }
2280
2281 #[deprecated(since = "0.3.0", note = "Use DynamicHub::new(namespace) instead")]
2283 pub fn with_namespace(namespace: impl Into<String>) -> Self {
2284 Self::new(namespace)
2285 }
2286
2287 pub fn runtime_namespace(&self) -> &str {
2289 &self.inner.namespace
2290 }
2291
2292 pub fn registry(&self) -> std::sync::RwLockReadGuard<'_, PluginRegistry> {
2294 self.inner.registry.read().unwrap()
2295 }
2296
2297 fn assert_no_root_shadow(&self, child_namespace: &str) {
2308 if child_namespace == self.inner.namespace {
2309 panic!(
2310 "DynamicHub namespace shadow: activation namespace '{child}' collides with the hub root namespace '{root}'. \
2311 The hub root name is a routing namespace, not a label — routing resolves the root first, so a like-named \
2312 child activation is unreachable (every '{child}.<method>' call resolves to the hub root and fails with \
2313 'Command not found', and navigation resolves the child back to the root schema). \
2314 Fix: rename the hub root so it differs from every registered activation's namespace, \
2315 e.g. DynamicHub::new(\"{root}_hub\").register(...). [Z2H-8 / HOSTLESS-3]",
2316 child = child_namespace,
2317 root = self.inner.namespace,
2318 );
2319 }
2320 }
2321
2322 pub fn register<A: Activation + ChildRouter + Clone + 'static>(self, activation: A) -> Self {
2331 self.register_entry(activation)
2332 }
2333
2334 #[deprecated(since = "0.5.0", note = "Use register() — it now handles both leaf and hub activations")]
2344 pub fn register_hub<A: Activation + ChildRouter + Clone + 'static>(self, activation: A) -> Self {
2345 self.register_entry(activation)
2346 }
2347
2348 pub(crate) fn entry_of<A: Activation + ChildRouter + Clone + 'static>(activation: A) -> super::service_root::Entry {
2350 let router = Arc::new(activation.clone());
2351 super::service_root::Entry { object: Arc::new(ActivationWrapper { inner: activation }), router }
2352 }
2353
2354 fn register_entry<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2358 let namespace = activation.namespace().to_string();
2359 self.assert_no_root_shadow(&namespace);
2360 let activation_for_rpc = activation.clone();
2361 let entry = Self::entry_of(activation);
2362 let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2363 Self::index_entry(inner.registry.get_mut().unwrap_or_else(|p| p.into_inner()), inner.auth_catalog.as_ref(), &namespace, &entry);
2364 let table = Arc::make_mut(inner.root.get_mut().unwrap_or_else(|p| p.into_inner()));
2365 if let Some(old) = table.entries.insert(namespace, entry.clone()) {
2366 table.nested -= old.object.static_child_schemas().len();
2367 }
2368 table.nested += entry.object.static_child_schemas().len();
2370 inner.pending_rpc.lock().unwrap()
2371 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2372 self
2373 }
2374
2375 fn index_entry(
2379 registry: &mut PluginRegistry,
2380 catalog: Option<&super::auth_activation::Catalog>,
2381 namespace: &str,
2382 entry: &super::service_root::Entry,
2383 ) {
2384 registry.register(entry.object.plugin_id(), namespace.to_string(), namespace.to_string());
2385 if let Some(catalog) = catalog {
2386 let schema = entry.object.plugin_schema();
2387 let statics = super::children::qualified(&schema.namespace, entry.object.static_child_schemas());
2389 let (mut typed, mut untyped) = (Vec::new(), Vec::new());
2392 for s in std::iter::once(&schema).chain(statics.iter()) {
2393 super::slots::slot_schemas(s, &mut typed, &mut untyped);
2394 }
2395 for child in statics.iter().chain(typed.iter()) {
2396 catalog.add(child);
2397 }
2398 catalog.add_slots(&untyped);
2399 catalog.add(&schema);
2400 }
2401 }
2402
2403 pub fn root(&self) -> super::service_root::ServiceRoot {
2406 super::service_root::ServiceRoot { hub: self.clone() }
2407 }
2408
2409 pub(crate) fn table(&self) -> Arc<super::service_root::Table> {
2411 self.inner.root.read().unwrap_or_else(|p| p.into_inner()).clone()
2412 }
2413
2414 pub(crate) fn watch_root(&self) -> tokio::sync::watch::Receiver<String> {
2416 self.inner.root_watch.subscribe()
2417 }
2418
2419 pub(crate) fn insert_entry(&self, name: String, entry: super::service_root::Entry, replace: bool) -> Result<bool, super::service_root::RootError> {
2423 super::service_root::check_name(&name)?;
2424 if name == self.inner.namespace {
2425 return Err(super::service_root::RootError::Shadows { name });
2426 }
2427 if let Some(needs) = entry.object.needs() {
2429 self.check_needs(&name, &needs).map_err(super::service_root::RootError::Needs)?;
2430 }
2431 let before = self.compute_hash();
2432 let replaced = self.change_table(|table| {
2433 if !replace && table.entries.contains_key(&name) {
2434 return Err(super::service_root::RootError::Taken { name: name.clone() });
2435 }
2436 let nested = entry.object.static_child_schemas().len();
2437 let old = table.entries.insert(name.clone(), entry.clone());
2438 if let Some(old) = old.as_ref() {
2439 table.nested -= old.object.static_child_schemas().len();
2440 }
2441 table.nested += nested;
2442 Ok(old.is_some())
2443 })?;
2444 Self::index_entry(&mut self.inner.registry.write().unwrap_or_else(|p| p.into_inner()), self.inner.auth_catalog.as_ref(), &name, &entry);
2445 self.table_moved(before);
2446 Ok(replaced)
2447 }
2448
2449 pub fn config(&self) -> super::config::Config {
2454 self.inner.config.get_or_init(super::config::Config::new).clone()
2455 }
2456
2457 pub fn with_config(mut self, config: super::config::Config) -> Self {
2460 let inner = self.inner_mut("Cannot set config: DynamicHub has multiple references");
2461 inner.config = std::sync::OnceLock::from(config);
2462 self
2463 }
2464
2465 pub fn with_config_service(self) -> Self {
2469 let config = self.config();
2470 self.register(super::config::ConfigActivation::new(config))
2471 }
2472
2473 pub fn notices(&self) -> tokio::sync::broadcast::Receiver<super::parent::Notice> {
2476 self.inner.notices.subscribe()
2477 }
2478
2479 pub fn notify(&self, notice: super::parent::Notice) -> u64 {
2481 self.inner.notices.send(notice).map(|n| n as u64).unwrap_or(0)
2482 }
2483
2484 pub fn method_at(&self, path: &str) -> Option<(String, String)> {
2490 let own = Activation::plugin_schema(self);
2491 if let Some(m) = path.strip_prefix(&format!("{}.", self.inner.namespace)).and_then(|m| own.methods.iter().find(|x| x.name == m)) {
2492 return Some((super::peer::Interface::method_hash(m), path.to_string()));
2493 }
2494 let (at, name) = path.rsplit_once('.')?;
2495 let activations: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).collect();
2496 let statics = self.static_children();
2497 let typed = self.slot_children().0;
2498 activations
2499 .iter()
2500 .chain(statics.iter())
2501 .chain(typed.iter())
2502 .filter(|s| s.namespace == at)
2503 .flat_map(|s| s.methods.iter().map(move |m| (s, m)))
2504 .find(|(_, m)| m.name == name && matches!(m.role, super::schema::MethodRole::Rpc))
2505 .map(|(s, m)| (super::peer::Interface::method_hash(m), m.grant_or(&s.namespace)))
2506 }
2507
2508 pub(crate) fn grant_at(&self, path: &str) -> Option<String> {
2511 self.gate_index().info(path).and_then(|i| i.grant.clone())
2512 }
2513
2514 pub fn check_needs(&self, child: &str, needs: &[super::schema::Need]) -> Result<(), super::parent::NeedsMiss> {
2517 super::parent::check_needs(child, &self.inner.namespace, needs, |p| {
2520 self.method_at(p).map(|(h, _)| h).or_else(|| self.gate_index().slots.resolve(p).map(|_| String::new()))
2521 })
2522 }
2523
2524 pub fn check_grafts(&self) -> Result<(), Vec<super::parent::NeedsMiss>> {
2528 let misses: Vec<_> = self
2529 .table()
2530 .entries
2531 .iter()
2532 .filter_map(|(name, e)| e.object.needs().map(|n| (name.clone(), n)))
2533 .filter_map(|(name, needs)| self.check_needs(&name, &needs).err())
2534 .collect();
2535 if misses.is_empty() { Ok(()) } else { Err(misses) }
2536 }
2537
2538 pub(crate) fn remove_entry(&self, name: &str) -> bool {
2540 let before = self.compute_hash();
2541 let gone = self.change_table(|table| {
2542 let old = table.entries.remove(name);
2543 if let Some(old) = old.as_ref() {
2544 table.nested -= old.object.static_child_schemas().len();
2545 }
2546 old
2547 });
2548 let Some(old) = gone else { return false };
2549 self.inner.registry.write().unwrap_or_else(|p| p.into_inner()).remove(old.object.plugin_id());
2550 if let Some(catalog) = self.inner.auth_catalog.as_ref() {
2551 catalog.remove_under(name);
2552 }
2553 self.table_moved(before);
2554 true
2555 }
2556
2557 fn change_table<R>(&self, change: impl FnOnce(&mut super::service_root::Table) -> R) -> R {
2559 let mut root = self.inner.root.write().unwrap_or_else(|p| p.into_inner());
2560 let mut table = (**root).clone();
2561 let out = change(&mut table);
2562 *root = Arc::new(table);
2563 out
2564 }
2565
2566 fn table_moved(&self, before: String) {
2571 *self.inner.gate_index.write().unwrap_or_else(|p| p.into_inner()) = None;
2572 *self.inner.input_index.write().unwrap_or_else(|p| p.into_inner()) = None;
2573 self.inner.describe.schema_moved();
2574 let after = self.compute_hash();
2575 PlexusContext::moved(&before, &after);
2576 self.inner.root_watch.send_replace(after);
2577 }
2578
2579 pub fn list_methods(&self) -> Vec<String> {
2581 let mut methods = Vec::new();
2582
2583 for m in Activation::methods(self) {
2585 methods.push(format!("{}.{}", self.inner.namespace, m));
2586 }
2587
2588 for (ns, e) in &self.table().entries {
2590 let act = &e.object;
2591 for m in act.methods() {
2592 methods.push(format!("{}.{}", ns, m));
2593 }
2594 }
2595 methods.sort();
2596 methods
2597 }
2598
2599 pub fn list_activations_info(&self) -> Vec<ActivationInfo> {
2601 let mut activations = Vec::new();
2602
2603 activations.push(ActivationInfo {
2605 namespace: Activation::namespace(self).to_string(),
2606 version: Activation::version(self).to_string(),
2607 description: Activation::description(self).to_string(),
2608 methods: Activation::methods(self).iter().map(|s| s.to_string()).collect(),
2609 });
2610
2611 for e in self.table().entries.values() {
2613 let a = &e.object;
2614 activations.push(ActivationInfo {
2615 namespace: a.namespace().to_string(),
2616 version: a.version().to_string(),
2617 description: a.description().to_string(),
2618 methods: a.methods().iter().map(|s| s.to_string()).collect(),
2619 });
2620 }
2621
2622 activations
2623 }
2624
2625 pub fn compute_hash(&self) -> String {
2633 self.described().service.hash.clone()
2635 }
2636
2637 fn own_hash(&self, caller: Option<&super::auth::AuthContext>) -> String {
2641 match self.inner.gate {
2642 Some(_) => self.shaped(caller).1.hash.clone(),
2643 None => self.described().service.hash.clone(),
2644 }
2645 }
2646
2647 fn own_schema(&self, caller: Option<&super::auth::AuthContext>) -> PluginSchema {
2650 match self.inner.gate {
2651 Some(_) => self.shaped(caller).1.service.clone(),
2652 None => self.described().service.clone(),
2653 }
2654 }
2655
2656 pub async fn route(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>) -> Result<PlexusStream, PlexusError> {
2658 self.route_with_ctx(method, params, auth, None).await
2659 }
2660
2661 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> {
2669 if super::service_scope::entered() {
2670 return self.route_entered(method, params, auth, raw_ctx).await;
2671 }
2672 super::service_scope::scope(self.downgrade(), self.route_entered(method, params, auth, raw_ctx)).await
2673 }
2674
2675 pub fn downgrade(&self) -> super::service_scope::WeakService {
2678 super::service_scope::WeakService::new(Arc::downgrade(&self.inner))
2679 }
2680
2681 pub(crate) async fn schema_for_child(&self, method: &str, params: Value) -> Result<PlexusStream, PlexusError> {
2686 let (_, name) = self.parse_method(method)?;
2687 if !Self::is_schema_query(name) {
2688 return Err(PlexusError::Unauthenticated(format!(
2689 "`{method}` is not a schema: outside a call, a child asks its service only for a schema"
2690 )));
2691 }
2692 let ctx = crate::call::CallContext::admitted(None, plexus_auth_core::grants::Reach::everywhere());
2693 let routed = self.route_ungated(method, params, None, None);
2694 super::service_scope::scope(self.downgrade(), in_call(ctx, routed)).await
2695 }
2696
2697 async fn route_entered(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2699 if let Some(gate) = self.inner.gate.as_ref() {
2702 let (auth, ended) = super::grant_gate::standing(gate, auth);
2704 let decide = |info| super::grant_gate::decide(gate, &self.inner.namespace, method, info, ¶ms, auth, &self.inner.signed_in_grants);
2705 let index = self.gate_index();
2706 let admit = match index.methods.get(method) {
2707 Some(info) => decide(Some(info)),
2708 None => match index.info(method) {
2712 Some(slot) => decide(None).or_else(|_| decide(Some(slot))),
2713 None => decide(None),
2714 },
2715 }
2716 .map_err(|e| super::grant_gate::say_ended(e, ended.as_deref()))?;
2717 return match admit {
2718 super::grant_gate::Admit::Open => {
2722 let grant = plexus_auth_core::grants::Grant::new(method.to_string());
2723 in_call(crate::call::CallContext::introspection(auth, Arc::clone(gate), grant), async {
2724 match self.introspect_in_view(method, ¶ms, auth, raw_ctx).await {
2725 Some(answer) => answer,
2726 None => self.route_ungated(method, params, auth, raw_ctx).await,
2727 }
2728 })
2729 .await
2730 }
2731 super::grant_gate::Admit::Reach(reach) => {
2732 in_call(crate::call::CallContext::admitted(auth, reach), self.route_ungated(method, params, auth, raw_ctx)).await
2733 }
2734 };
2735 }
2736 let ctx = match crate::call::context() {
2743 Ok(outer) => outer.with_auth(auth),
2744 Err(_) => crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere()),
2745 };
2746 in_call(ctx, self.route_ungated(method, params, auth, raw_ctx)).await
2747 }
2748
2749 async fn route_ungated(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2751 if self.inner.scope_registry.is_some() || self.inner.default_deny {
2756 let registry = self
2757 .inner
2758 .scope_registry
2759 .as_deref()
2760 .unwrap_or_else(|| super::scope_gate::empty_registry());
2761 super::scope_gate::enforce(
2762 registry,
2763 self.inner.default_deny,
2764 &self.inner.audit_sink,
2765 method,
2766 self.gate_index().info(method),
2767 auth,
2768 raw_ctx.and_then(|ctx| ctx.peer.map(|peer| peer.ip())),
2769 )
2770 .await?;
2771 }
2772
2773 let (namespace, method_name) = self.parse_method(method)?;
2774
2775 if namespace == self.inner.namespace && method_name == "ir" {
2777 self.check_ir_names(¶ms, auth)?;
2778 }
2779
2780 let stream = if namespace == self.inner.namespace {
2785 Activation::call(self, method_name, params, auth, raw_ctx).await?
2786 } else {
2787 let entry = self.table().entries.get(namespace).map(|e| e.object.clone())
2788 .ok_or_else(|| PlexusError::ActivationNotFound(namespace.to_string()))?;
2789
2790 entry.call(method_name, params, auth, raw_ctx).await?
2791 };
2792
2793 if Self::is_schema_query(method_name) {
2800 if let Some(site) = self.derived_site_hint() {
2801 return Ok(fill_site_hints_in_schema_stream(stream, site));
2802 }
2803 }
2804 Ok(stream)
2805 }
2806
2807 fn is_schema_query(method_name: &str) -> bool {
2812 method_name == "schema" || method_name.ends_with(".schema")
2813 }
2814
2815 pub fn derived_site_hint(&self) -> Option<plexus_auth_core::AttachmentSite> {
2821 self.inner
2822 .auth_capabilities
2823 .as_ref()
2824 .and_then(|caps| caps.implied_attachment_site())
2825 }
2826
2827 pub async fn do_resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
2831 let path = self.inner.registry.read().unwrap()
2832 .lookup(handle.plugin_id)
2833 .map(|s| s.to_string())
2834 .ok_or_else(|| PlexusError::ActivationNotFound(handle.plugin_id.to_string()))?;
2835
2836 let activation = self.table().entries.get(&path).map(|e| e.object.clone())
2837 .ok_or_else(|| PlexusError::ActivationNotFound(path.clone()))?;
2838 activation.resolve_handle(handle).await
2839 }
2840
2841 pub fn get_activation_schema(&self, namespace: &str) -> Option<Schema> {
2843 self.table().entries.get(namespace).map(|e| e.object.schema())
2844 }
2845
2846 pub fn registry_snapshot(&self) -> PluginRegistrySnapshot {
2848 let guard = self.inner.registry.read().unwrap();
2849 PluginRegistrySnapshot {
2850 by_id: guard.by_id.clone(),
2851 by_path: guard.by_path.clone(),
2852 }
2853 }
2854
2855 pub fn lookup_plugin(&self, id: uuid::Uuid) -> Option<String> {
2857 self.inner.registry.read().unwrap().lookup(id).map(|s| s.to_string())
2858 }
2859
2860 pub fn lookup_plugin_by_path(&self, path: &str) -> Option<uuid::Uuid> {
2862 self.inner.registry.read().unwrap().lookup_by_path(path)
2863 }
2864
2865 pub fn list_plugin_schemas(&self) -> Vec<PluginSchema> {
2867 let mut schemas = Vec::new();
2868
2869 schemas.push(Activation::plugin_schema(self));
2871
2872 for e in self.table().entries.values() {
2874 schemas.push(e.object.plugin_schema());
2875 }
2876
2877 schemas
2878 }
2879
2880 #[deprecated(note = "Use list_plugin_schemas instead")]
2882 pub fn list_full_schemas(&self) -> Vec<PluginSchema> {
2883 self.list_plugin_schemas()
2884 }
2885
2886 pub fn get_method_help(&self, method: &str) -> Option<String> {
2888 let (namespace, method_name) = self.parse_method(method).ok()?;
2889 let table = self.table();
2890 table.entries.get(namespace)?.object.method_help(method_name)
2891 }
2892
2893 fn parse_method<'a>(&self, method: &'a str) -> Result<(&'a str, &'a str), PlexusError> {
2894 let parts: Vec<&str> = method.splitn(2, '.').collect();
2895 if parts.len() != 2 {
2896 return Err(PlexusError::InvalidParams {
2897 param: Some("method".into()),
2898 problem: ParamProblem::Malformed {
2899 detail: format!("expected `namespace.method`, got `{}`", method),
2900 },
2901 });
2902 }
2903 Ok((parts[0], parts[1]))
2904 }
2905
2906 pub fn plugin_children(&self) -> Vec<ChildSummary> {
2911 self.table().entries.values()
2912 .map(|e| {
2913 let schema = e.object.plugin_schema();
2914 ChildSummary {
2915 namespace: schema.namespace,
2916 description: schema.description,
2917 hash: schema.hash,
2918 }
2919 })
2920 .collect()
2921 }
2922
2923 pub fn into_rpc_module(self) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2925 let mut module = RpcModule::new(());
2926
2927 if let Err(misses) = self.check_grafts() {
2930 panic!("{}", misses.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "));
2931 }
2932 PlexusContext::init(self.compute_hash());
2933
2934 let ns = self.runtime_namespace();
2937 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2938 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2939 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2940 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2941 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2942 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2943 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2944 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2945 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2946
2947 let plexus_for_call = self.clone();
2949 module.register_subscription(
2950 call_method,
2951 PLEXUS_NOTIF_METHOD,
2952 call_unsub,
2953 move |params, pending, _ctx, ext| {
2954 let plexus = plexus_for_call.clone();
2955 let identified = plexus.inner.gate.is_some();
2959 serve_call(plexus, params, pending, ext, ns_static, identified)
2960 }
2961 )?;
2962
2963 register_input_methods(&mut module, ns_static)?;
2964
2965 let plexus_for_hash = self.clone();
2967 module.register_subscription(
2968 hash_method,
2969 PLEXUS_NOTIF_METHOD,
2970 hash_unsub,
2971 move |_params, pending, _ctx, ext| {
2972 let plexus = plexus_for_hash.clone();
2973 Box::pin(async move {
2974 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2976 let value = plexus.own_hash(auth);
2977 let stream = async_stream::stream! {
2978 yield HashEvent::Hash { value };
2979 };
2980 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2981 pipe_stream_to_subscription(pending, wrapped, &ext).await
2982 })
2983 }
2984 )?;
2985
2986 let plexus_for_schema = self.clone();
2988 module.register_subscription(
2989 schema_method,
2990 PLEXUS_NOTIF_METHOD,
2991 schema_unsub,
2992 move |params, pending, _ctx, ext| {
2993 let plexus = plexus_for_schema.clone();
2994 Box::pin(async move {
2995 let p: SchemaParams = params.parse().unwrap_or_default();
2996 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2998 let mut plugin_schema = plexus.own_schema(auth);
2999 if let Some(site) = plexus.derived_site_hint() {
3001 plugin_schema.fill_site_hints(&site);
3002 }
3003
3004 let result = if let Some(ref name) = p.method {
3005 plugin_schema.methods.iter()
3006 .find(|m| m.name == *name)
3007 .map(|m| super::SchemaResult::Method(m.clone()))
3008 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
3009 -32602,
3010 format!("Method '{}' not found", name),
3011 None::<()>,
3012 ))?
3013 } else {
3014 super::SchemaResult::Plugin(plugin_schema)
3015 };
3016
3017 let stream = async_stream::stream! { yield result; };
3018 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
3019 pipe_stream_to_subscription(pending, wrapped, &ext).await
3020 })
3021 }
3022 )?;
3023
3024 let info_payload = build_info_payload(
3030 self.runtime_namespace(),
3031 self.inner.auth_capabilities.as_ref(),
3032 );
3033 let plexus_for_info = self.inner.gate.is_some().then(|| self.clone());
3036 module.register_subscription(
3037 "_info",
3038 PLEXUS_NOTIF_METHOD,
3039 "_info_unsub",
3040 move |_params, pending, _ctx, ext| {
3041 let payload = match plexus_for_info.as_ref() {
3042 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
3043 None => info_payload.clone(),
3044 };
3045 Box::pin(async move {
3046 let info_stream = futures::stream::once(async move { payload });
3048
3049 let wrapped = super::streaming::wrap_stream(
3051 info_stream,
3052 "_info",
3053 vec![]
3054 );
3055
3056 pipe_stream_to_subscription(pending, wrapped, &ext).await
3058 })
3059 }
3060 )?;
3061
3062 let pending = std::mem::take(&mut *self.inner.pending_rpc.lock().unwrap());
3066 if self.inner.gate.is_none() {
3067 for factory in pending {
3068 module.merge(factory())?;
3069 }
3070 }
3071
3072 for (ns, e) in self.table().entries.iter() {
3076 register_child_capability_methods(&mut module, ns, e.router.clone(), self.inner.gate.clone())?;
3077 }
3078
3079 Ok(module)
3080 }
3081
3082 pub fn serve_call(
3093 &self,
3094 params: jsonrpsee::types::Params<'static>,
3095 pending: jsonrpsee::PendingSubscriptionSink,
3096 ext: http::Extensions,
3097 ns: &'static str,
3098 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>> {
3099 serve_call(self.clone(), params, pending, ext, ns, true)
3100 }
3101
3102 pub fn arc_into_rpc_module(hub: Arc<Self>) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
3108 let mut module = RpcModule::new(());
3109
3110 if let Err(misses) = hub.check_grafts() {
3113 panic!("{}", misses.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "));
3114 }
3115 PlexusContext::init(hub.compute_hash());
3116
3117 let ns = hub.runtime_namespace();
3120 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
3121 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
3122 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
3123 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
3124 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
3125 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
3126 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
3127 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
3128 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
3129
3130 let hub_for_call = hub.clone();
3132 module.register_subscription(
3133 call_method,
3134 call_method,
3135 call_unsub,
3136 move |params, pending, _ctx, ext| {
3137 let hub = hub_for_call.clone();
3138 let hub = (*hub).clone();
3139 serve_call(hub, params, pending, ext, ns_static, true)
3140 }
3141 )?;
3142
3143 register_input_methods(&mut module, ns_static)?;
3144
3145 let hub_for_hash = hub.clone();
3147 module.register_subscription(
3148 hash_method,
3149 PLEXUS_NOTIF_METHOD,
3150 hash_unsub,
3151 move |_params, pending, _ctx, ext| {
3152 let hub = hub_for_hash.clone();
3153 Box::pin(async move {
3154 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3156 let value = hub.own_hash(auth);
3157 let stream = async_stream::stream! {
3158 yield HashEvent::Hash { value };
3159 };
3160 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
3161 pipe_stream_to_subscription(pending, wrapped, &ext).await
3162 })
3163 }
3164 )?;
3165
3166 let hub_for_schema = hub.clone();
3168 module.register_subscription(
3169 schema_method,
3170 PLEXUS_NOTIF_METHOD,
3171 schema_unsub,
3172 move |params, pending, _ctx, ext| {
3173 let hub = hub_for_schema.clone();
3174 Box::pin(async move {
3175 let p: SchemaParams = params.parse().unwrap_or_default();
3176 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3178 let mut plugin_schema = hub.own_schema(auth);
3179 if let Some(site) = hub.derived_site_hint() {
3181 plugin_schema.fill_site_hints(&site);
3182 }
3183
3184 let result = if let Some(ref name) = p.method {
3185 plugin_schema.methods.iter()
3186 .find(|m| m.name == *name)
3187 .map(|m| super::SchemaResult::Method(m.clone()))
3188 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
3189 -32602,
3190 format!("Method '{}' not found", name),
3191 None::<()>,
3192 ))?
3193 } else {
3194 super::SchemaResult::Plugin(plugin_schema)
3195 };
3196
3197 let stream = async_stream::stream! {
3198 yield result;
3199 };
3200 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
3201 pipe_stream_to_subscription(pending, wrapped, &ext).await
3202 })
3203 }
3204 )?;
3205
3206 let info_payload = build_info_payload(
3211 hub.runtime_namespace(),
3212 hub.inner.auth_capabilities.as_ref(),
3213 );
3214 let hub_for_info = hub.inner.gate.is_some().then(|| hub.clone());
3217 module.register_subscription(
3218 "_info",
3219 PLEXUS_NOTIF_METHOD,
3220 "_info_unsub",
3221 move |_params, pending, _ctx, ext| {
3222 let payload = match hub_for_info.as_ref() {
3223 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
3224 None => info_payload.clone(),
3225 };
3226 Box::pin(async move {
3227 let info_stream = futures::stream::once(async move { payload });
3229
3230 let wrapped = super::streaming::wrap_stream(
3232 info_stream,
3233 "_info",
3234 vec![]
3235 );
3236
3237 pipe_stream_to_subscription(pending, wrapped, &ext).await
3239 })
3240 }
3241 )?;
3242
3243 let mut pending = std::mem::take(&mut *hub.inner.pending_rpc.lock().unwrap());
3246 if hub.inner.gate.is_some() {
3247 pending.clear();
3248 }
3249 tracing::trace!(factories = pending.len(), "merging activation RPC factories");
3250 for (idx, factory) in pending.into_iter().enumerate() {
3251 tracing::trace!(factory_idx = idx, "calling factory to get Methods");
3252 let methods = factory();
3253 let method_count = methods.method_names().count();
3254 tracing::trace!(factory_idx = idx, methods = method_count, "factory returned Methods; merging into module");
3255 module.merge(methods)?;
3256 tracing::trace!(factory_idx = idx, "successfully merged factory methods");
3257 }
3258 tracing::trace!("all activations merged successfully");
3259
3260 for (ns, e) in hub.table().entries.iter() {
3263 register_child_capability_methods(&mut module, ns, e.router.clone(), hub.inner.gate.clone())?;
3264 }
3265
3266 Ok(module)
3267 }
3268}
3269
3270fn listing_context(
3290 gate: Option<&Arc<plexus_auth_core::grants::Gate>>,
3291 ext: &jsonrpsee::Extensions,
3292 method: &str,
3293) -> crate::call::CallContext {
3294 let auth = ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3295 match gate {
3296 None => crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere()),
3297 Some(gate) => {
3298 let (auth, _) = super::grant_gate::standing(gate, auth);
3299 crate::call::CallContext::introspection(auth, Arc::clone(gate), plexus_auth_core::grants::Grant::new(method.to_string()))
3300 }
3301 }
3302}
3303
3304#[allow(deprecated)] fn register_child_capability_methods(
3306 module: &mut RpcModule<()>,
3307 namespace: &str,
3308 router: Arc<dyn ChildRouter>,
3309 gate: Option<Arc<plexus_auth_core::grants::Gate>>,
3310) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3311 let caps = router.capabilities();
3312 if caps.is_empty() {
3313 return Ok(());
3314 }
3315
3316 let ns_static: &'static str = Box::leak(namespace.to_string().into_boxed_str());
3317
3318 if caps.contains(ChildCapabilities::LIST) {
3319 let list_method: &'static str =
3320 Box::leak(format!("{}.list_children", namespace).into_boxed_str());
3321 let list_unsub: &'static str =
3322 Box::leak(format!("{}.list_children_unsub", namespace).into_boxed_str());
3323 let router_for_list = router.clone();
3324 let gate_for_list = gate.clone();
3325 module.register_subscription(
3326 list_method,
3327 PLEXUS_NOTIF_METHOD,
3328 list_unsub,
3329 move |_params, pending, _ctx, ext| {
3330 let router = router_for_list.clone();
3331 let ctx = listing_context(gate_for_list.as_ref(), &ext, list_method);
3332 Box::pin(async move {
3333 let collected: Vec<String> = crate::call::scope(ctx, async {
3340 match router.list_children().await {
3341 Some(mut s) => {
3342 use futures::StreamExt;
3343 let mut acc = Vec::new();
3344 while let Some(name) = s.next().await {
3345 acc.push(name);
3346 }
3347 acc
3348 }
3349 None => Vec::new(),
3350 }
3351 })
3352 .await;
3353 let stream = async_stream::stream! {
3354 for name in collected {
3355 yield name;
3356 }
3357 };
3358 let wrapped = super::streaming::wrap_stream(
3359 stream,
3360 "list_children",
3361 vec![ns_static.into()],
3362 );
3363 pipe_stream_to_subscription(pending, wrapped, &ext).await
3364 })
3365 },
3366 )?;
3367 }
3368
3369 if caps.contains(ChildCapabilities::SEARCH) {
3370 let search_method: &'static str =
3371 Box::leak(format!("{}.search_children", namespace).into_boxed_str());
3372 let search_unsub: &'static str =
3373 Box::leak(format!("{}.search_children_unsub", namespace).into_boxed_str());
3374 let router_for_search = router.clone();
3375 let gate_for_search = gate.clone();
3376 module.register_subscription(
3377 search_method,
3378 PLEXUS_NOTIF_METHOD,
3379 search_unsub,
3380 move |params, pending, _ctx, ext| {
3381 let router = router_for_search.clone();
3382 let ctx = listing_context(gate_for_search.as_ref(), &ext, search_method);
3383 Box::pin(async move {
3384 let p: SearchChildrenParams = params.parse()?;
3385 let collected: Vec<String> = crate::call::scope(ctx, async {
3386 match router.search_children(&p.query).await {
3387 Some(mut s) => {
3388 use futures::StreamExt;
3389 let mut acc = Vec::new();
3390 while let Some(name) = s.next().await {
3391 acc.push(name);
3392 }
3393 acc
3394 }
3395 None => Vec::new(),
3396 }
3397 })
3398 .await;
3399 let stream = async_stream::stream! {
3400 for name in collected {
3401 yield name;
3402 }
3403 };
3404 let wrapped = super::streaming::wrap_stream(
3405 stream,
3406 "search_children",
3407 vec![ns_static.into()],
3408 );
3409 pipe_stream_to_subscription(pending, wrapped, &ext).await
3410 })
3411 },
3412 )?;
3413 }
3414
3415 Ok(())
3416}
3417
3418#[derive(Debug, serde::Deserialize)]
3420struct SearchChildrenParams {
3421 query: String,
3422}
3423
3424#[derive(Debug, serde::Deserialize)]
3426pub(crate) struct CallParams {
3427 pub(crate) method: String,
3428 #[serde(default)]
3429 pub(crate) params: Option<Value>,
3430}
3431
3432pub(crate) struct InputTerms {
3434 pub(crate) grant: String,
3435 pub(crate) targets: Vec<String>,
3436 pub(crate) recheck: bool,
3437}
3438
3439use super::schema::SchemaParams;
3441
3442fn serve_call(
3455 service: DynamicHub,
3456 params: jsonrpsee::types::Params<'static>,
3457 pending: jsonrpsee::PendingSubscriptionSink,
3458 ext: http::Extensions,
3459 ns: &'static str,
3460 identified: bool,
3461) -> CallFuture {
3462 let call: CallParams = match params.parse() {
3465 Ok(call) => call,
3466 Err(e) => return Box::pin(async move { Err(e.into()) }),
3467 };
3468 if service.may_take_input(&call.method) {
3469 return Box::pin(serve_seamed(service, call, params, pending, ext, ns, identified));
3470 }
3471 let CallParams { method, params: args } = call;
3472 Box::pin(async move {
3473 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref()) } else { None };
3474 match service.route(&method, args.unwrap_or_default(), caller).await {
3475 Ok(stream) => pipe_stream_to_subscription(pending, stream, &ext).await,
3476 Err(e) => {
3477 let sink = pending.accept().await?;
3478 if let Some(raw) = error_item_raw(ns, &e) {
3479 let _ = sink.send(raw).await;
3480 }
3481 Ok(())
3482 }
3483 }
3484 })
3485}
3486
3487type CallFuture = std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>>;
3490
3491async fn serve_seamed(
3496 service: DynamicHub,
3497 call: CallParams,
3498 params: jsonrpsee::types::Params<'static>,
3499 pending: jsonrpsee::PendingSubscriptionSink,
3500 ext: http::Extensions,
3501 ns: &'static str,
3502 identified: bool,
3503) -> jsonrpsee::core::SubscriptionResult {
3504 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().cloned() } else { None };
3505 let seen = service.inner.gate.as_ref().map_or(0, |g| g.generation().current());
3506 let opened = Arc::new(std::sync::Mutex::new(None::<super::input::Opened>));
3507 let take = || opened.lock().unwrap_or_else(|e| e.into_inner()).take();
3508 let mut scoped = std::pin::pin!(super::input::CALL.scope(
3509 std::cell::RefCell::new(super::input::Seam { service: service.clone(), params, pending: Some(pending), ext, seen, opened: opened.clone(), refused: None }),
3510 service.route(&call.method, call.params.unwrap_or_default(), caller.as_deref()),
3511 ));
3512 let answered = std::future::poll_fn(|cx| match std::future::Future::poll(scoped.as_mut(), cx) {
3517 std::task::Poll::Ready(answer) => std::task::Poll::Ready(Some(answer)),
3518 std::task::Poll::Pending if opened.lock().unwrap_or_else(|e| e.into_inner()).is_some() => std::task::Poll::Ready(None),
3519 std::task::Poll::Pending => std::task::Poll::Pending,
3520 })
3521 .await;
3522 let Some(answer) = answered else {
3523 let super::input::Opened { sink, duplex } = take().expect("opened, the route still resolving");
3524 let mut routing = std::pin::pin!(async { scoped.as_mut().await.map_err(|e| error_item(ns, &e)) });
3525 return Box::pin(super::wire::pipe_duplex(sink, super::wire::Output::Routing(routing.as_mut()), duplex)).await;
3526 };
3527 let super::input::Seam { pending, ext, refused, .. } = scoped.as_mut().take_value().expect("the scope ran to its end").into_inner();
3528 match (answer, take()) {
3529 (Ok(stream), Some(opened)) => Box::pin(super::wire::pipe_duplex(opened.sink, super::wire::Output::Ready(stream), opened.duplex)).await,
3531 (Ok(stream), None) => {
3532 let pending = pending.expect("only an open takes it, and an open is `opened`");
3533 pipe_stream_to_subscription(pending, stream, &ext).await
3534 }
3535 (Err(e), opened) => {
3536 let sink = match (opened, pending) {
3537 (Some(opened), _) => opened.sink,
3538 (None, Some(pending)) => pending.accept().await?,
3539 (None, None) => return Ok(()),
3540 };
3541 let raw = match refused {
3542 Some(item) => serde_json::value::to_raw_value(&item).ok(),
3543 None => error_item_raw(ns, &e),
3544 };
3545 if let Some(raw) = raw {
3546 let _ = sink.send(raw).await;
3547 }
3548 Ok(())
3549 }
3550 }
3551}
3552
3553fn register_input_methods(module: &mut RpcModule<()>, ns: &'static str) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3559 use super::input::{Delivered, InputTable};
3560 use jsonrpsee::types::ErrorObjectOwned;
3561
3562 fn answer(delivered: Delivered) -> Result<bool, ErrorObjectOwned> {
3563 match delivered {
3564 Delivered::Taken => Ok(true),
3565 Delivered::Dropped | Delivered::Refused => Ok(false),
3566 Delivered::NotThisCall => Err(ErrorObjectOwned::owned(
3567 -32003,
3568 "not_this_call: input comes from the connection that opened the call",
3569 Some(serde_json::json!({"error_kind": "not_this_call"})),
3570 )),
3571 Delivered::Malformed => Err(ErrorObjectOwned::owned(-32602, "invalid params: subscription, seq and items", None::<()>)),
3572 }
3573 }
3574 fn table(ext: &http::Extensions) -> Result<&Arc<InputTable>, ErrorObjectOwned> {
3575 ext.get::<super::wire::FrameSink>()
3576 .and_then(super::wire::FrameSink::inputs)
3577 .ok_or_else(|| ErrorObjectOwned::owned(-32601, "this transport carries no input half: call over a WebSocket", None::<()>))
3578 }
3579
3580 let input_method: &'static str = Box::leak(format!("{ns}.input").into_boxed_str());
3581 let end_method: &'static str = Box::leak(format!("{ns}.end").into_boxed_str());
3582 module.register_method(input_method, move |params, _ctx, ext| {
3583 let frame = bytes::Bytes::copy_from_slice(params.as_str().unwrap_or("null").as_bytes());
3584 answer(table(ext)?.input(ns, &frame, &frame))
3585 })?;
3586 module.register_method(end_method, move |params, _ctx, ext| answer(table(ext)?.end(ns, params.as_str().unwrap_or("null").as_bytes())))?;
3587 Ok(())
3588}
3589
3590async fn pipe_stream_to_subscription(
3601 pending: jsonrpsee::PendingSubscriptionSink,
3602 stream: PlexusStream,
3603 ext: &http::Extensions,
3604) -> jsonrpsee::core::SubscriptionResult {
3605 let sink = pending.accept().await?;
3606 super::wire::pipe(sink, stream, ext).await
3607}
3608
3609#[plexus_macros::activation(
3614 namespace = "plexus",
3615 version = "1.0.0",
3616 description = "Central routing and introspection",
3617 hub,
3618 namespace_fn = "runtime_namespace"
3619)]
3620#[allow(deprecated)]
3621impl DynamicHub {
3622 #[plexus_macros::method(
3624 description = "Route a call to a registered activation",
3625 params(
3626 method = "The method to call (format: namespace.method)",
3627 params = "Parameters to pass to the method (optional, defaults to {})"
3628 )
3629 )]
3630 async fn call(
3631 &self,
3632 method: String,
3633 params: Option<Value>,
3634 ) -> impl Stream<Item = super::types::PlexusStreamItem> + Send + 'static {
3635 use super::context::PlexusContext;
3636 use super::types::{PlexusStreamItem, StreamMetadata};
3637
3638 let result = self.route(&method, params.unwrap_or_default(), None).await;
3639
3640 match result {
3641 Ok(plexus_stream) => {
3642 plexus_stream
3644 }
3645 Err(e) => {
3646 let metadata = StreamMetadata::new(
3648 vec![self.inner.namespace.clone()],
3649 PlexusContext::hash(),
3650 );
3651 Box::pin(futures::stream::once(async move {
3652 PlexusStreamItem::from_plexus_error(metadata, &e, false)
3653 }))
3654 }
3655 }
3656 }
3657
3658 #[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.")]
3663 async fn hash(&self) -> impl Stream<Item = HashEvent> + Send + 'static {
3664 let schema = Activation::plugin_schema(self);
3665 stream! { yield HashEvent::Hash { value: schema.hash }; }
3666 }
3667
3668 #[plexus_macros::method(description = "Get plugin hashes for cache validation")]
3670 #[allow(deprecated)]
3671 async fn hashes(&self) -> impl Stream<Item = PluginHashes> + Send + 'static {
3672 let schema = Activation::plugin_schema(self);
3673
3674 stream! {
3675 yield PluginHashes {
3676 namespace: schema.namespace.clone(),
3677 self_hash: schema.self_hash.clone(),
3678 children_hash: schema.children_hash.clone(),
3679 hash: schema.hash.clone(),
3680 children: schema.children.as_ref().map(|kids| {
3681 kids.iter()
3682 .map(|c| ChildHashes {
3683 namespace: c.namespace.clone(),
3684 hash: c.hash.clone(),
3685 })
3686 .collect()
3687 }),
3688 };
3689 }
3690 }
3691
3692 #[plexus_macros::method(
3698 description = "The service's IR (3.0): every type once, each method referring to them — of the namespaces asked, or the whole service",
3699 params(namespaces = "The namespaces (dotted paths) to describe; none: the whole service")
3700 )]
3701 async fn ir(
3702 &self,
3703 auth: Option<&super::auth::AuthContext>,
3704 namespaces: Option<Vec<String>>,
3705 ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
3706 self.service_ir(&namespaces.unwrap_or_default(), auth).await
3707 }
3708
3709 }
3711
3712use super::hub_context::HubContext;
3717use std::sync::Weak;
3718
3719#[async_trait]
3725impl HubContext for Weak<DynamicHub> {
3726 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
3727 let hub = self.upgrade().ok_or_else(|| {
3728 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3729 })?;
3730 hub.do_resolve_handle(handle).await
3731 }
3732
3733 async fn call(&self, method: &str, params: serde_json::Value) -> Result<PlexusStream, PlexusError> {
3734 let hub = self.upgrade().ok_or_else(|| {
3735 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3736 })?;
3737 hub.route(method, params, None).await
3738 }
3739
3740 fn is_valid(&self) -> bool {
3741 self.upgrade().is_some()
3742 }
3743}
3744
3745#[async_trait]
3750impl ChildRouter for DynamicHub {
3751 fn router_namespace(&self) -> &str {
3752 &self.inner.namespace
3753 }
3754
3755 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
3756 self.route_with_ctx(method, params, auth, raw_ctx).await
3759 }
3760
3761 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3762 self.table().entries.get(name).map(|e| e.router.clone())
3764 .map(|router| {
3765
3766 Box::new(ArcChildRouter(router.clone())) as Box<dyn ChildRouter>
3768 })
3769 }
3770
3771 fn forward_policy_for(
3774 &self,
3775 callee_ns: &str,
3776 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
3777 self.inner.forward_policies.get(callee_ns)
3778 }
3779
3780 }
3787
3788#[cfg(test)]
3789#[allow(deprecated)]
3790mod tests {
3791 use super::*;
3792
3793 #[test]
3794 fn dynamic_hub_implements_activation() {
3795 fn assert_activation<T: Activation>() {}
3796 assert_activation::<DynamicHub>();
3797 }
3798
3799 #[test]
3800 fn dynamic_hub_methods() {
3801 let hub = DynamicHub::new("test");
3802 let methods = hub.methods();
3803 assert!(methods.contains(&"call"));
3804 assert!(methods.contains(&"hash"));
3805 assert!(methods.contains(&"schema"));
3806 }
3808
3809 #[test]
3810 fn dynamic_hub_hash_stable() {
3811 let h1 = DynamicHub::new("test");
3812 let h2 = DynamicHub::new("test");
3813 assert_eq!(h1.compute_hash(), h2.compute_hash());
3814 }
3815
3816 #[test]
3817 fn dynamic_hub_is_hub() {
3818 use crate::activations::health::Health;
3819 let hub = DynamicHub::new("test").register(Health::new());
3820 let schema = hub.plugin_schema();
3821
3822 assert!(schema.is_hub(), "dynamic hub should be a hub");
3824 assert!(!schema.is_leaf(), "dynamic hub should not be a leaf");
3825
3826 let children = schema.children.expect("dynamic hub should have children");
3828 assert!(!children.is_empty(), "dynamic hub should have at least one child");
3829
3830 let health = children.iter().find(|c| c.namespace == "health").expect("should have health child");
3832 assert!(!health.hash.is_empty(), "health should have a hash");
3833 }
3834
3835 #[test]
3840 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3841 fn dynamic_hub_rejects_root_namespace_shadow() {
3842 use crate::activations::health::Health;
3843 let _hub = DynamicHub::new("health").register(Health::new());
3844 }
3845
3846 #[test]
3849 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3850 fn dynamic_hub_register_hub_rejects_root_namespace_shadow() {
3851 use crate::activations::health::Health;
3852 let _hub = DynamicHub::new("health").register_hub(Health::new());
3853 }
3854
3855 #[test]
3859 fn dynamic_hub_shadow_error_names_collision_and_fix() {
3860 use crate::activations::health::Health;
3861 let result = std::panic::catch_unwind(|| {
3862 let _hub = DynamicHub::new("health").register(Health::new());
3863 });
3864 let err = result.expect_err("shadow registration must panic");
3865 let msg = err
3866 .downcast_ref::<String>()
3867 .cloned()
3868 .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
3869 .expect("panic payload should be a string");
3870 assert!(msg.contains("'health'"), "must name the colliding namespace: {msg}");
3871 assert!(msg.contains("hub root namespace"), "must name the root side: {msg}");
3872 assert!(msg.contains("rename the hub root"), "must suggest the fix: {msg}");
3873 assert!(msg.contains("Z2H-8"), "must cite the ticket: {msg}");
3874 }
3875
3876 #[test]
3879 fn dynamic_hub_non_colliding_registration_unaffected() {
3880 use crate::activations::health::Health;
3881 let hub = DynamicHub::new("health_hub").register(Health::new());
3882 assert_eq!(hub.runtime_namespace(), "health_hub");
3883 let schema = hub.plugin_schema();
3884 let children = schema.children.expect("hub should have children");
3885 assert!(
3886 children.iter().any(|c| c.namespace == "health"),
3887 "health child must be registered"
3888 );
3889 assert!(hub.list_methods().iter().any(|m| m.starts_with("health.")));
3890 }
3891
3892 #[test]
3893 fn dynamic_hub_schema_structure() {
3894 use crate::activations::health::Health;
3895 let hub = DynamicHub::new("test").register(Health::new());
3896 let schema = hub.plugin_schema();
3897
3898 let json = serde_json::to_string_pretty(&schema).unwrap();
3900 println!("DynamicHub schema:\n{}", json);
3901
3902 assert_eq!(schema.namespace, "test");
3904 assert!(schema.methods.iter().any(|m| m.name == "call"));
3905 assert!(schema.children.is_some());
3906 }
3907
3908 #[tokio::test]
3913 async fn invariant_resolve_handle_unknown_activation() {
3914 use crate::activations::health::Health;
3915 use crate::types::Handle;
3916 use uuid::Uuid;
3917
3918 let hub = DynamicHub::new("test").register(Health::new());
3919
3920 let unknown_plugin_id = Uuid::new_v4();
3922 let handle = Handle::new(unknown_plugin_id, "1.0.0", "some_method");
3923
3924 let result = hub.do_resolve_handle(&handle).await;
3925
3926 match result {
3927 Err(PlexusError::ActivationNotFound(_)) => {
3928 }
3930 Err(other) => panic!("Expected ActivationNotFound, got {:?}", other),
3931 Ok(_) => panic!("Expected error for unknown activation"),
3932 }
3933 }
3934
3935 #[tokio::test]
3936 async fn invariant_resolve_handle_unsupported() {
3937 use crate::activations::health::Health;
3938 use crate::types::Handle;
3939
3940 let hub = DynamicHub::new("test").register(Health::new());
3941
3942 let handle = Handle::new(Health::PLUGIN_ID, "1.0.0", "check");
3944
3945 let result = hub.do_resolve_handle(&handle).await;
3946
3947 match result {
3948 Err(PlexusError::HandleNotSupported(name)) => {
3949 assert_eq!(name, "health");
3950 }
3951 Err(other) => panic!("Expected HandleNotSupported, got {:?}", other),
3952 Ok(_) => panic!("Expected error for unsupported handle"),
3953 }
3954 }
3955
3956 #[tokio::test]
3957 async fn invariant_resolve_handle_routes_by_plugin_id() {
3958 use crate::activations::health::Health;
3959 use crate::activations::echo::EchoActivation;
3960 use crate::types::Handle;
3961 use uuid::Uuid;
3962
3963 let health = Health::new();
3964 let echo = EchoActivation::new();
3965 let health_plugin_id = health.plugin_id();
3966 let echo_plugin_id = echo.plugin_id();
3967
3968 let hub = DynamicHub::new("test")
3969 .register(health)
3970 .register(echo);
3971
3972 let health_handle = Handle::new(health_plugin_id, "1.0.0", "check");
3974 match hub.do_resolve_handle(&health_handle).await {
3975 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "health"),
3976 Err(other) => panic!("health handle should route to health activation, got {:?}", other),
3977 Ok(_) => panic!("health handle should return HandleNotSupported"),
3978 }
3979
3980 let echo_handle = Handle::new(echo_plugin_id, "1.0.0", "echo");
3982 match hub.do_resolve_handle(&echo_handle).await {
3983 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "echo"),
3984 Err(other) => panic!("echo handle should route to echo activation, got {:?}", other),
3985 Ok(_) => panic!("echo handle should return HandleNotSupported"),
3986 }
3987
3988 let unknown_handle = Handle::new(Uuid::new_v4(), "1.0.0", "method");
3990 match hub.do_resolve_handle(&unknown_handle).await {
3991 Err(PlexusError::ActivationNotFound(_)) => { },
3992 Err(other) => panic!("unknown handle should return ActivationNotFound, got {:?}", other),
3993 Ok(_) => panic!("unknown handle should return ActivationNotFound"),
3994 }
3995 }
3996
3997 #[test]
3998 fn invariant_handle_plugin_id_determines_routing() {
3999 use crate::activations::health::Health;
4000 use crate::activations::echo::EchoActivation;
4001 use crate::types::Handle;
4002
4003 let health = Health::new();
4004 let echo = EchoActivation::new();
4005
4006 let health_handle = Handle::new(health.plugin_id(), "1.0.0", "check")
4008 .with_meta(vec!["msg-123".into(), "user".into()]);
4009 let echo_handle = Handle::new(echo.plugin_id(), "1.0.0", "echo")
4010 .with_meta(vec!["msg-123".into(), "user".into()]);
4011
4012 assert_ne!(health_handle.plugin_id, echo_handle.plugin_id);
4014 }
4015
4016 #[test]
4021 fn plugin_registry_basic_operations() {
4022 let mut registry = PluginRegistry::new();
4023 let id = uuid::Uuid::new_v4();
4024
4025 registry.register(id, "test_plugin".to_string(), "test".to_string());
4027
4028 assert_eq!(registry.lookup(id), Some("test_plugin"));
4030
4031 assert_eq!(registry.lookup_by_path("test_plugin"), Some(id));
4033
4034 let entry = registry.get(id).expect("should have entry");
4036 assert_eq!(entry.path, "test_plugin");
4037 assert_eq!(entry.plugin_type, "test");
4038 }
4039
4040 #[test]
4041 fn plugin_registry_populated_on_register() {
4042 use crate::activations::health::Health;
4043
4044 let hub = DynamicHub::new("test").register(Health::new());
4045
4046 let registry = hub.registry();
4047 assert!(!registry.is_empty(), "registry should not be empty after registration");
4048
4049 let health_id = registry.lookup_by_path("health");
4051 assert!(health_id.is_some(), "health should be registered by path");
4052
4053 let health_uuid = health_id.unwrap();
4055 assert_eq!(registry.lookup(health_uuid), Some("health"));
4056 }
4057
4058 #[test]
4059 fn plugin_registry_deterministic_uuid() {
4060 use crate::activations::health::Health;
4061
4062 let health1 = Health::new();
4064 let health2 = Health::new();
4065
4066 assert_eq!(health1.plugin_id(), health2.plugin_id(),
4067 "same activation type should have deterministic UUID");
4068
4069 let expected = uuid::Uuid::new_v5(
4071 &uuid::Uuid::NAMESPACE_OID,
4072 b"health@1"
4073 );
4074 assert_eq!(health1.plugin_id(), expected,
4075 "plugin_id should be deterministic from namespace@major_version");
4076 }
4077
4078 struct MinimalRouter;
4086
4087 #[async_trait]
4088 impl ChildRouter for MinimalRouter {
4089 fn router_namespace(&self) -> &str {
4090 "minimal"
4091 }
4092
4093 async fn router_call(
4094 &self,
4095 _method: &str,
4096 _params: Value,
4097 _auth: Option<&super::super::auth::AuthContext>,
4098 _raw_ctx: Option<&crate::request::RawRequestContext>,
4099 ) -> Result<PlexusStream, PlexusError> {
4100 Err(PlexusError::MethodNotFound {
4101 activation: "minimal".into(),
4102 method: "none".into(),
4103 })
4104 }
4105
4106 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
4107 None
4108 }
4109 }
4110
4111 #[tokio::test]
4112 async fn child_router_defaults_report_no_capabilities_and_none_streams() {
4113 let router = MinimalRouter;
4114
4115 assert_eq!(
4116 router.capabilities(),
4117 ChildCapabilities::empty(),
4118 "default capabilities should be empty"
4119 );
4120 assert!(
4121 router.list_children().await.is_none(),
4122 "default list_children should be None"
4123 );
4124 assert!(
4125 router.search_children("anything").await.is_none(),
4126 "default search_children should be None"
4127 );
4128 }
4129
4130 struct ListingRouter {
4132 names: Vec<String>,
4133 }
4134
4135 #[async_trait]
4136 impl ChildRouter for ListingRouter {
4137 fn router_namespace(&self) -> &str {
4138 "listing"
4139 }
4140
4141 async fn router_call(
4142 &self,
4143 _method: &str,
4144 _params: Value,
4145 _auth: Option<&super::super::auth::AuthContext>,
4146 _raw_ctx: Option<&crate::request::RawRequestContext>,
4147 ) -> Result<PlexusStream, PlexusError> {
4148 Err(PlexusError::MethodNotFound {
4149 activation: "listing".into(),
4150 method: "none".into(),
4151 })
4152 }
4153
4154 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
4155 if self.names.iter().any(|n| n == name) {
4156 Some(Box::new(ListingRouter { names: vec![] }))
4159 } else {
4160 None
4161 }
4162 }
4163
4164 fn capabilities(&self) -> ChildCapabilities {
4165 ChildCapabilities::LIST | ChildCapabilities::SEARCH
4166 }
4167
4168 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
4169 let stream = futures::stream::iter(self.names.iter().cloned());
4170 Some(Box::pin(stream))
4171 }
4172
4173 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
4174 let q = query.to_string();
4175 let stream = futures::stream::iter(
4176 self.names
4177 .iter()
4178 .filter(move |n| n.contains(&q))
4179 .cloned()
4180 .collect::<Vec<_>>(),
4181 );
4182 Some(Box::pin(stream))
4183 }
4184 }
4185
4186 #[tokio::test]
4187 async fn child_router_overrides_report_capabilities_and_yield_streams() {
4188 use futures::StreamExt;
4189
4190 let router = ListingRouter {
4191 names: vec!["alpha".into(), "beta".into(), "alphabet".into()],
4192 };
4193
4194 let caps = router.capabilities();
4196 assert!(caps.contains(ChildCapabilities::LIST));
4197 assert!(caps.contains(ChildCapabilities::SEARCH));
4198 assert_eq!(caps, ChildCapabilities::LIST | ChildCapabilities::SEARCH);
4199
4200 let list_stream = router
4202 .list_children()
4203 .await
4204 .expect("LIST capability set — expected Some(stream)");
4205 let listed: Vec<String> = list_stream.collect().await;
4206 assert_eq!(listed, vec!["alpha".to_string(), "beta".into(), "alphabet".into()]);
4207
4208 let search_stream = router
4210 .search_children("alpha")
4211 .await
4212 .expect("SEARCH capability set — expected Some(stream)");
4213 let matched: Vec<String> = search_stream.collect().await;
4214 assert_eq!(matched, vec!["alpha".to_string(), "alphabet".into()]);
4215 }
4216
4217 struct WireFixture {
4232 names: Vec<String>,
4233 caps: ChildCapabilities,
4234 }
4235
4236 #[async_trait]
4237 impl ChildRouter for WireFixture {
4238 fn router_namespace(&self) -> &str {
4239 "wirefixture"
4240 }
4241 async fn router_call(
4242 &self,
4243 _method: &str,
4244 _params: Value,
4245 _auth: Option<&super::super::auth::AuthContext>,
4246 _raw_ctx: Option<&crate::request::RawRequestContext>,
4247 ) -> Result<PlexusStream, PlexusError> {
4248 Err(PlexusError::MethodNotFound {
4249 activation: "wirefixture".into(),
4250 method: "none".into(),
4251 })
4252 }
4253 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
4254 None
4255 }
4256 fn capabilities(&self) -> ChildCapabilities {
4257 self.caps
4258 }
4259 async fn list_children(&self) -> Option<futures_core::stream::BoxStream<'_, String>> {
4260 if !self.caps.contains(ChildCapabilities::LIST) {
4261 return None;
4262 }
4263 Some(Box::pin(futures::stream::iter(self.names.clone())))
4264 }
4265 async fn search_children(
4266 &self,
4267 query: &str,
4268 ) -> Option<futures_core::stream::BoxStream<'_, String>> {
4269 if !self.caps.contains(ChildCapabilities::SEARCH) {
4270 return None;
4271 }
4272 let q = query.to_lowercase();
4273 let filtered: Vec<String> = self
4274 .names
4275 .iter()
4276 .filter(|n| n.to_lowercase().contains(&q))
4277 .cloned()
4278 .collect();
4279 Some(Box::pin(futures::stream::iter(filtered)))
4280 }
4281 }
4282
4283 fn build_module_for(router: WireFixture, ns: &str) -> RpcModule<()> {
4284 let mut module = RpcModule::new(());
4285 let arc: Arc<dyn ChildRouter> = Arc::new(router);
4286 register_child_capability_methods(&mut module, ns, arc, None).expect("register");
4287 module
4288 }
4289
4290 #[tokio::test]
4291 async fn child_wire_registers_both_methods_when_both_bits_set() {
4292 let module = build_module_for(
4293 WireFixture {
4294 names: vec!["alpha".into(), "beta".into()],
4295 caps: ChildCapabilities::LIST | ChildCapabilities::SEARCH,
4296 },
4297 "fixture",
4298 );
4299 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4300 assert!(
4301 names.contains(&"fixture.list_children".to_string()),
4302 "expected fixture.list_children, got: {:?}",
4303 names
4304 );
4305 assert!(
4306 names.contains(&"fixture.search_children".to_string()),
4307 "expected fixture.search_children, got: {:?}",
4308 names
4309 );
4310 }
4311
4312 #[tokio::test]
4313 async fn child_wire_registers_nothing_when_no_bits_set() {
4314 let module = build_module_for(
4315 WireFixture {
4316 names: vec!["alpha".into()],
4317 caps: ChildCapabilities::empty(),
4318 },
4319 "fixture",
4320 );
4321 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4322 assert!(
4323 !names.contains(&"fixture.list_children".to_string()),
4324 "fixture.list_children should NOT be registered when cap absent"
4325 );
4326 assert!(
4327 !names.contains(&"fixture.search_children".to_string()),
4328 "fixture.search_children should NOT be registered when cap absent"
4329 );
4330 }
4331
4332 #[tokio::test]
4333 async fn child_wire_registers_only_list_when_only_list_bit() {
4334 let module = build_module_for(
4335 WireFixture {
4336 names: vec!["alpha".into()],
4337 caps: ChildCapabilities::LIST,
4338 },
4339 "fixture",
4340 );
4341 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4342 assert!(names.contains(&"fixture.list_children".to_string()));
4343 assert!(!names.contains(&"fixture.search_children".to_string()));
4344 }
4345
4346 }