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 fn slot_key(&self, path: &str) -> String {
1298 if let Some(k) = self.slots.resolve(path) {
1299 return k;
1300 }
1301 const PROBE: &str = ".\u{0}";
1303 match self.slots.resolve(&format!("{path}{PROBE}")) {
1304 Some(k) => k.strip_suffix(PROBE).map(str::to_string).unwrap_or(k),
1305 None => path.to_string(),
1306 }
1307 }
1308}
1309
1310
1311#[derive(Clone)]
1333pub struct DynamicHub {
1334 inner: Arc<DynamicHubInner>,
1335}
1336
1337struct IrView {
1339 base: Arc<super::view::Described>,
1340 shaped: Option<Arc<super::view::Shaped>>,
1342 hash: String,
1344}
1345
1346impl IrView {
1347 fn root(&self) -> PluginSchema {
1348 match &self.shaped {
1349 Some(v) => v.service.clone(),
1350 None => self.base.service.clone(),
1351 }
1352 }
1353
1354 fn top(&self, ns: &str) -> Option<PluginSchema> {
1355 match &self.shaped {
1356 Some(v) => v.schema_of(&self.base, ns).filter(|_| ns != v.service.namespace),
1357 None => self.base.activations.iter().find(|a| a.namespace == ns).cloned(),
1358 }
1359 }
1360
1361 fn shows(&self, ns: &str) -> bool {
1362 match &self.shaped {
1363 Some(v) => v.shows(ns),
1364 None => self.base.activations.iter().any(|a| a.namespace == ns),
1365 }
1366 }
1367
1368 fn names(&self, service: &str) -> Vec<String> {
1372 let mut out = vec![String::new()];
1373 out.extend(self.base.activations.iter().map(|a| a.namespace.clone()).filter(|ns| ns != service && self.shows(ns)));
1374 for path in self.base.nested() {
1375 let mut segs = path.split('.');
1376 let (Some(top), Some(entry)) = (segs.next(), segs.next()) else { continue };
1377 let reached = self.shows(top)
1378 && match &self.shaped {
1379 Some(v) => v.method_of(&self.base, top, entry).is_some(),
1380 None => true,
1381 };
1382 if reached {
1383 out.push(path.to_string());
1384 }
1385 }
1386 out
1387 }
1388}
1389
1390impl DynamicHub {
1395 pub(crate) fn from_inner(inner: Arc<DynamicHubInner>) -> Self {
1397 Self { inner }
1398 }
1399
1400 pub fn new(namespace: impl Into<String>) -> Self {
1426 Self {
1427 inner: Arc::new(DynamicHubInner {
1428 namespace: namespace.into(),
1429 root: Default::default(),
1430 root_watch: tokio::sync::watch::Sender::new(String::new()),
1431 registry: std::sync::RwLock::new(PluginRegistry::new()),
1432 pending_rpc: std::sync::Mutex::new(Vec::new()),
1433 auth_capabilities: None,
1434 forward_policies: super::forward_registry::ForwardPolicyRegistry::new(),
1435 scope_registry: None,
1436 default_deny: false,
1437 audit_sink: Arc::new(plexus_auth_core::TracingAuditSink),
1438 duplex_gate: std::sync::OnceLock::new(),
1439 gate_index: Default::default(),
1440 input_index: Default::default(),
1441 gate: None,
1442 signed_in_grants: std::collections::BTreeSet::new(),
1443 resource_metadata: None,
1444 auth_catalog: None,
1445 describe: Default::default(),
1446 ir_cache: Default::default(),
1447 notices: tokio::sync::broadcast::Sender::new(64),
1448 config: std::sync::OnceLock::new(),
1449 }),
1450 }
1451 }
1452
1453 fn inner_mut(&mut self, refused: &str) -> &mut DynamicHubInner {
1458 let inner = Arc::get_mut(&mut self.inner).expect(refused);
1459 inner.describe.reset();
1460 *inner.gate_index.get_mut().unwrap_or_else(|p| p.into_inner()) = None;
1461 *inner.input_index.get_mut().unwrap_or_else(|p| p.into_inner()) = None;
1462 inner
1463 }
1464
1465
1466 pub fn with_scope_registry(mut self, registry: plexus_auth_core::ScopeRegistry) -> Self {
1486 let inner = self.inner_mut("Cannot set scope_registry: DynamicHub has multiple references");
1487 inner.scope_registry = Some(Arc::new(registry));
1488 self
1489 }
1490
1491 pub fn with_default_deny(mut self, default_deny: bool) -> Self {
1510 let inner = self.inner_mut("Cannot set default_deny: DynamicHub has multiple references");
1511 inner.default_deny = default_deny;
1512 self
1513 }
1514
1515 pub fn with_audit_sink(mut self, sink: Arc<dyn plexus_auth_core::AuditSink>) -> Self {
1526 let inner = self.inner_mut("Cannot set audit_sink: DynamicHub has multiple references");
1527 inner.audit_sink = sink;
1528 self
1529 }
1530
1531 pub fn with_gate(mut self, gate: Arc<plexus_auth_core::grants::Gate>) -> Self {
1556 let inner = self.inner_mut("Cannot set gate: DynamicHub has multiple references");
1557 inner.gate = Some(gate);
1558 self
1559 }
1560
1561 pub fn gate(&self) -> Option<&Arc<plexus_auth_core::grants::Gate>> {
1563 self.inner.gate.as_ref()
1564 }
1565
1566 pub fn with_resource_metadata(mut self, url: impl Into<String>) -> Self {
1571 let inner = self.inner_mut("Cannot set resource_metadata: DynamicHub has multiple references");
1572 inner.resource_metadata = Some(url.into());
1573 self
1574 }
1575
1576 pub fn with_signed_in_grants<I, S>(mut self, grants: I) -> Self
1583 where
1584 I: IntoIterator<Item = S>,
1585 S: Into<String>,
1586 {
1587 let inner = self.inner_mut("Cannot set signed_in grants: DynamicHub has multiple references");
1588 inner.signed_in_grants.extend(grants.into_iter().map(Into::into));
1589 self
1590 }
1591
1592 pub fn with_auth(mut self, setup: super::auth_activation::AuthSetup) -> Self {
1609 let catalog = super::auth_activation::Catalog::default();
1610 catalog.add(&Activation::plugin_schema(&self));
1611 for e in self.table().entries.values() {
1612 catalog.add(&e.object.plugin_schema());
1613 }
1614 for child in self.described_children() {
1618 catalog.add(&child);
1619 }
1620 let (_, untyped) = self.slot_children();
1621 catalog.add_slots(&untyped);
1622 let (auth, gate) = super::auth_activation::AuthActivation::mount(setup, catalog.clone());
1623 if let Err(why) = super::grant_gate::require_everywhere(&Activation::plugin_schema(&auth), super::auth_activation::EVERYWHERE) {
1626 panic!("{why}");
1627 }
1628 {
1629 let inner = self.inner_mut("Cannot mount auth: DynamicHub has multiple references");
1630 inner.auth_catalog = Some(catalog);
1631 inner.gate = Some(Arc::new(gate));
1632 }
1633 self.register(auth)
1634 .with_signed_in_grants(super::auth_activation::SIGNED_IN_GRANTS.iter().copied())
1635 }
1636
1637 pub fn view(&self, caller: Option<&super::auth::AuthContext>) -> super::view::View {
1655 match self.inner.gate.as_ref() {
1656 None => self.described().whole(),
1657 Some(_) => {
1658 let (base, view) = self.shaped(caller);
1659 view.view(&base)
1660 }
1661 }
1662 }
1663
1664 pub fn schema_moved(&self) {
1670 self.inner.describe.schema_moved();
1671 }
1672
1673 fn described(&self) -> Arc<super::view::Described> {
1677 let at = self.inner.describe.schema_generation();
1678 match self.inner.describe.base(at) {
1679 Some(cell) => cell.get_or_init(|| Arc::new(self.describe_now())).clone(),
1680 None => Arc::new(self.describe_now()),
1681 }
1682 }
1683
1684 fn describe_now(&self) -> super::view::Described {
1685 let service = Activation::plugin_schema(self);
1686 let activations: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).collect();
1687 super::view::Described::new(service, activations, self.described_children())
1691 }
1692
1693 fn shaped(&self, caller: Option<&super::auth::AuthContext>) -> (Arc<super::view::Described>, Arc<super::view::Shaped>) {
1699 let gate = self.inner.gate.as_ref().expect("a view is a gated service's");
1700 let schema_at = self.inner.describe.schema_generation();
1701 let grants_at = gate.generation().current();
1702 let (caller, _) = super::grant_gate::standing(gate, caller);
1705 let who = caller.and_then(|c| gate.fingerprint(c));
1706 let shape = |base: &super::view::Described| {
1707 Arc::new(super::view::shape(gate, &self.inner.signed_in_grants, who.as_ref(), base))
1708 };
1709 match self.inner.describe.view(schema_at, grants_at, &who) {
1710 Some((base, view)) => {
1711 let base = base.get_or_init(|| Arc::new(self.describe_now())).clone();
1712 let view = view.get_or_init(|| shape(&base)).clone();
1713 (base, view)
1714 }
1715 None => {
1716 let base = Arc::new(self.describe_now());
1717 let view = shape(&base);
1718 (base, view)
1719 }
1720 }
1721 }
1722
1723 pub fn info(&self, caller: Option<&super::auth::AuthContext>) -> serde_json::Value {
1729 if self.inner.gate.is_none() {
1730 return build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1731 }
1732 let (base, view) = self.shaped(caller);
1734 view.info
1735 .get_or_init(|| {
1736 let mut payload = build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1737 if let Some(obj) = payload.as_object_mut() {
1738 obj.insert("view".into(), view.kind.as_str().into());
1739 obj.insert("view_hash".into(), view.hash.clone().into());
1740 if view.kind == super::ViewKind::Anonymous {
1741 let mut auth = serde_json::Map::new();
1742 auth.insert("methods".into(), view.public_methods(&base).into());
1743 if let Some(url) = self.inner.resource_metadata.as_ref() {
1744 auth.insert("resource_metadata".into(), url.clone().into());
1745 }
1746 obj.insert("auth".into(), serde_json::Value::Object(auth));
1747 }
1748 }
1749 payload
1750 })
1751 .clone()
1752 }
1753
1754 async fn introspect_in_view(
1760 &self,
1761 method: &str,
1762 params: &Value,
1763 auth: Option<&super::auth::AuthContext>,
1764 raw_ctx: Option<&crate::request::RawRequestContext>,
1765 ) -> Option<Result<PlexusStream, PlexusError>> {
1766 let (ns, rest) = method.split_once('.')?;
1767 let hub_ns = self.inner.namespace.as_str();
1768 let (base, view) = self.shaped(auth);
1770 let not_found = || PlexusError::ActivationNotFound(ns.to_string());
1771 let content: serde_json::Value = match rest {
1772 "schema" => {
1773 if !view.shows(ns) {
1774 return Some(Err(not_found()));
1775 }
1776 let mut result = match params.get("method").and_then(|v| v.as_str()) {
1777 Some(name) => match view.method_of(&base, ns, name) {
1778 Some(m) => super::SchemaResult::Method(m),
1779 None => {
1780 return Some(Err(PlexusError::MethodNotFound {
1781 activation: ns.to_string(),
1782 method: name.to_string(),
1783 }))
1784 }
1785 },
1786 None => super::SchemaResult::Plugin(view.schema_of(&base, ns)?),
1787 };
1788 if let Some(site) = self.derived_site_hint() {
1789 result.fill_site_hints(&site);
1790 }
1791 serde_json::to_value(&result).ok()?
1792 }
1793 "hash" if ns == hub_ns => serde_json::to_value(HashEvent::Hash { value: view.hash.clone() }).ok()?,
1794 "hashes" if ns == hub_ns => serde_json::to_value(view.hashes()).ok()?,
1795 r if r.ends_with(".schema") => {
1796 if !view.shows(ns) {
1797 return Some(Err(not_found()));
1798 }
1799 let name = r.trim_end_matches(".schema");
1800 match view.method_of(&base, ns, name) {
1801 Some(m) if matches!(m.role, super::MethodRole::Rpc) => {
1802 serde_json::to_value(super::SchemaResult::Method(m)).ok()?
1803 }
1804 Some(_) => return None,
1806 None if ns != hub_ns
1815 && (name.contains('.') || base.activations.iter().any(|a| a.namespace == ns && a.methods.iter().any(|m| m.role.is_slot())))
1816 && self.shows_path(&format!("{ns}.{name}"), auth) =>
1817 {
1818 return None
1819 }
1820 None => {
1821 return Some(Err(PlexusError::MethodNotFound {
1822 activation: ns.to_string(),
1823 method: name.to_string(),
1824 }))
1825 }
1826 }
1827 }
1828 _ => return None,
1829 };
1830 use futures::StreamExt;
1833 let with = |content: serde_json::Value| {
1834 move |item: super::types::PlexusStreamItem| match item {
1837 super::types::PlexusStreamItem::Data { metadata, content_type, .. } => {
1838 super::types::PlexusStreamItem::Data { metadata, content_type, content: content.clone().into() }
1839 }
1840 other => other,
1841 }
1842 };
1843 if self.inner.scope_registry.is_some() || self.inner.default_deny {
1846 let routed = self.route_ungated(method, params.clone(), auth, raw_ctx).await;
1847 return Some(routed.map(|s| -> PlexusStream { Box::pin(s.map(with(content))) }));
1848 }
1849 let key = format!("{method}\n{params}");
1853 if let Some(shell) = base.shell(&key) {
1854 return Some(Ok(Box::pin(futures::stream::iter(shell.answer(content)))));
1855 }
1856 let items: Vec<super::types::PlexusStreamItem> = match self.route_ungated(method, params.clone(), auth, raw_ctx).await {
1857 Ok(s) => s.collect().await,
1858 Err(e) => return Some(Err(e)),
1859 };
1860 if let Some(shell) = super::view::Shell::of(&items) {
1861 base.keep_shell(key, shell);
1862 }
1863 Some(Ok(Box::pin(futures::stream::iter(items.into_iter().map(with(content))))))
1864 }
1865
1866 fn bare_introspection<'m>(&self, method: &'m str) -> &'m str {
1873 let Some(rest) = method.strip_prefix(self.inner.namespace.as_str()).and_then(|r| r.strip_prefix('.')) else {
1874 return method;
1875 };
1876 let Some((first, _)) = rest.split_once('.') else { return method };
1877 let own = self.described().service.methods.iter().any(|m| m.name == first);
1878 if own || first.is_empty() {
1879 method
1880 } else {
1881 rest
1882 }
1883 }
1884
1885 pub(crate) fn bare_schema_path(&self, method: &str) -> String {
1888 self.bare_introspection(method).trim_end_matches(".schema").to_string()
1889 }
1890
1891 pub(crate) fn crosses_slot(&self, path: &str) -> bool {
1895 self.gate_index().slot_key(path) != path
1896 }
1897
1898 fn shows_path(&self, path: &str, auth: Option<&super::auth::AuthContext>) -> bool {
1907 let Some(gate) = self.inner.gate.as_ref() else { return true };
1908 let signed_in = auth.and_then(|a| a.principal()).is_some();
1909 let holds = |grant: &str, public: bool, everywhere: bool| {
1910 if public || (signed_in && self.inner.signed_in_grants.contains(grant)) {
1911 return true;
1912 }
1913 let Some(a) = auth else { return false };
1914 let held = gate.held_on(a, &plexus_auth_core::grants::Grant::new(grant));
1915 if everywhere {
1916 held.iter().any(plexus_auth_core::grants::ScopeRef::is_everywhere)
1917 } else {
1918 !held.is_empty()
1919 }
1920 };
1921 if holds(path, false, false) {
1922 return true;
1923 }
1924 let index = self.gate_index();
1925 let key = index.slot_key(path);
1926 let below = format!("{key}.");
1927 index.methods.iter().any(|(at, info)| {
1928 (*at == key || at.starts_with(&below))
1929 && holds(info.grant.as_deref().unwrap_or(at), info.public, info.everywhere)
1930 })
1931 }
1932
1933 pub async fn service_ir(
1947 &self,
1948 namespaces: &[String],
1949 caller: Option<&super::auth::AuthContext>,
1950 ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
1951 let roots = super::ir::roots(&self.inner.namespace, namespaces);
1952 let view = self.ir_view(caller);
1953 let permitted = match self.inner.scope_registry.is_some() || self.inner.default_deny {
1954 false => None,
1955 true => {
1956 let mut answered = Vec::new();
1960 for name in view.names(&self.inner.namespace) {
1961 let under = roots.iter().any(|r| {
1962 let r = r.join(".");
1963 r.is_empty() || name == r || name.starts_with(&format!("{r}."))
1964 });
1965 if under && self.scope_answers(&self.schema_method(&name), caller).await {
1966 answered.push(name);
1967 }
1968 }
1969 Some(answered)
1970 }
1971 };
1972 let key = super::ir::IrKey { view: view.hash.clone(), roots: roots.clone(), permitted: permitted.clone() };
1973 self.inner
1974 .ir_cache
1975 .get_or_build(key, || async {
1976 let mut schemas: BTreeMap<Vec<String>, Value> = BTreeMap::new();
1977 let mut todo: Vec<Vec<String>> = roots.clone();
1978 while let Some(path) = todo.pop() {
1979 if schemas.contains_key(&path) || permitted.as_ref().is_some_and(|p| !p.contains(&path.join("."))) {
1980 continue;
1981 }
1982 if path.len() > 1 && !self.shows_path(&path.join("."), caller) {
1985 continue;
1986 }
1987 let Some(schema) = self.ir_schema(&view, &path, caller).await else { continue };
1989 for child in schema.get("children").and_then(Value::as_array).into_iter().flatten() {
1990 if let Some(ns) = child.get("namespace").and_then(Value::as_str) {
1991 let mut next = path.clone();
1992 next.push(ns.to_string());
1993 todo.push(next);
1994 }
1995 }
1996 schemas.insert(path, schema);
1997 }
1998 let service = self.inner.namespace.clone();
1999 crate::rt::spawn_blocking(move || super::ir::answer(&service, &roots, &schemas))
2000 .await
2001 .unwrap_or_else(|e| Err(super::ir::IrError::Unreadable { namespace: String::new(), message: format!("the IR's build failed: {e}") }))
2002 })
2003 .await
2004 }
2005
2006 pub fn ir_builds(&self) -> usize {
2009 self.inner.ir_cache.builds()
2010 }
2011
2012 fn ir_view(&self, caller: Option<&super::auth::AuthContext>) -> IrView {
2016 match self.inner.gate {
2017 Some(_) => {
2018 let (base, shaped) = self.shaped(caller);
2019 IrView { hash: shaped.hash.clone(), base, shaped: Some(shaped) }
2020 }
2021 None => {
2022 let base = self.described();
2023 IrView { hash: base.service.hash.clone(), base, shaped: None }
2024 }
2025 }
2026 }
2027
2028 fn schema_method(&self, dotted: &str) -> String {
2030 if dotted.is_empty() { format!("{}.schema", self.inner.namespace) } else { format!("{dotted}.schema") }
2031 }
2032
2033 async fn scope_answers(&self, method: &str, caller: Option<&super::auth::AuthContext>) -> bool {
2036 let registry = self.inner.scope_registry.as_deref().unwrap_or_else(|| super::scope_gate::empty_registry());
2037 super::scope_gate::answers(registry, self.inner.default_deny, method, self.gate_index().info(method), caller).await
2038 }
2039
2040 async fn ir_schema(&self, view: &IrView, path: &[String], caller: Option<&super::auth::AuthContext>) -> Option<Value> {
2045 use futures::StreamExt;
2046 let shown = match path {
2047 [] => Some(view.root()),
2048 [ns] => view.top(ns),
2049 [top, below @ ..] => {
2050 let activation = self.table().entries.get(top.as_str())?.object.clone();
2053 let mut stream = activation.call(&format!("{}.schema", below.join(".")), Value::Null, caller, None).await.ok()?;
2054 if let Some(site) = self.derived_site_hint() {
2055 stream = fill_site_hints_in_schema_stream(stream, site);
2056 }
2057 let items: Vec<super::types::PlexusStreamItem> = stream.collect().await;
2058 return items.into_iter().find_map(|item| match item {
2059 super::types::PlexusStreamItem::Data { content_type, content, .. } if content_type.ends_with(".schema") => {
2060 Some(content.into_value())
2061 }
2062 _ => None,
2063 });
2064 }
2065 };
2066 let mut schema = shown?;
2067 if let Some(site) = self.derived_site_hint() {
2068 schema.fill_site_hints(&site);
2069 }
2070 serde_json::to_value(super::SchemaResult::Plugin(schema)).ok()
2071 }
2072
2073 fn check_ir_names(&self, params: &Value, caller: Option<&super::auth::AuthContext>) -> Result<(), PlexusError> {
2077 let asked = match params.get("namespaces") {
2078 None | Some(Value::Null) => return Ok(()),
2079 Some(Value::Array(a)) => a,
2080 Some(_) => return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")),
2081 };
2082 let most = {
2086 let table = self.table();
2087 1 + table.entries.len() + table.nested
2088 };
2089 if asked.len() > most {
2090 return Err(PlexusError::malformed_param(
2091 "namespaces",
2092 format!("{} namespaces asked; more than this service shows you", asked.len()),
2093 ));
2094 }
2095 let names: std::collections::HashSet<String> = self.ir_view(caller).names(&self.inner.namespace).into_iter().collect();
2096 if asked.len() > names.len() {
2097 return Err(PlexusError::malformed_param(
2098 "namespaces",
2099 format!("{} namespaces asked; this service shows you {}", asked.len(), names.len()),
2100 ));
2101 }
2102 for n in asked {
2103 let Some(n) = n.as_str() else { return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")) };
2104 let known = n == self.inner.namespace || names.contains(n);
2105 if !known {
2106 return Err(PlexusError::malformed_param("namespaces", format!("no namespace `{n}` in this service")));
2107 }
2108 }
2109 Ok(())
2110 }
2111
2112 pub fn declared_roles(&self) -> std::collections::BTreeMap<String, Vec<String>> {
2120 let mut out: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
2121 let schemas = self.table().entries.values().map(|e| e.object.plugin_schema()).chain(self.described_children()).collect::<Vec<_>>();
2125 for schema in schemas {
2126 for (role, grants) in schema.roles {
2127 let entry = out.entry(role).or_default();
2128 for g in grants {
2129 if !entry.contains(&g) {
2130 entry.push(g);
2131 }
2132 }
2133 }
2134 }
2135 out
2136 }
2137
2138 pub fn static_children(&self) -> Vec<PluginSchema> {
2144 self.table()
2145 .entries
2146 .values()
2147 .flat_map(|e| super::children::qualified(&e.object.plugin_schema().namespace, e.object.static_child_schemas()))
2148 .collect()
2149 }
2150
2151 pub fn scope_registry(&self) -> Option<&plexus_auth_core::ScopeRegistry> {
2156 self.inner.scope_registry.as_deref()
2157 }
2158
2159 pub(crate) fn input_terms(&self, method: &str, params: &Value) -> Result<InputTerms, PlexusError> {
2163 if self.inner.gate.is_none() {
2164 return Ok(InputTerms { grant: method.to_string(), targets: Vec::new(), recheck: false });
2165 }
2166 let index = self.gate_index();
2167 let info = index.info(method);
2168 let grant = info.and_then(|i| i.grant.clone()).unwrap_or_else(|| method.to_string());
2169 let open = info.is_some_and(|i| i.public) || self.inner.signed_in_grants.contains(grant.as_str());
2170 let targets = match info.and_then(|i| i.target.as_deref()) {
2171 Some(param) => super::grant_gate::target_values(params, param)?.unwrap_or_default(),
2172 None => Vec::new(),
2173 };
2174 Ok(InputTerms { grant, targets, recheck: !open })
2175 }
2176
2177 pub(crate) fn duplex_gate(&self) -> &super::duplex_gate::DuplexGate {
2180 self.inner.duplex_gate.get_or_init(|| match &self.inner.gate {
2181 Some(gate) => {
2182 let (audit, drain) = plexus_auth_core::audit::AuditQueue::new(1024, self.inner.audit_sink.clone());
2183 crate::rt::spawn(drain);
2184 super::duplex_gate::DuplexGate::new((**gate).clone()).with_audit(audit)
2185 }
2186 None => super::duplex_gate::DuplexGate::ungated(),
2187 })
2188 }
2189
2190 pub(crate) fn may_take_input(&self, method: &str) -> bool {
2195 let kept = self.inner.input_index.read().unwrap_or_else(|p| p.into_inner()).clone();
2196 let index = match kept {
2197 Some(index) => index,
2198 None => {
2199 let own = Activation::plugin_schema(self).methods.into_iter().map(|m| (format!("{}.{}", self.inner.namespace, m.name), m.input.is_some()));
2200 let schemas: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).chain(self.static_children()).collect();
2201 let theirs = schemas.into_iter().flat_map(|schema| {
2202 let ns = schema.namespace;
2203 schema.methods.into_iter().map(move |m| (format!("{ns}.{}", m.name), m.input.is_some()))
2204 });
2205 let index: Arc<HashMap<String, bool>> = Arc::new(own.chain(theirs).collect());
2206 *self.inner.input_index.write().unwrap_or_else(|p| p.into_inner()) = Some(index.clone());
2207 index
2208 }
2209 };
2210 index.get(method).copied().unwrap_or(true)
2211 }
2212
2213 pub fn slot_children(&self) -> (Vec<PluginSchema>, Vec<String>) {
2218 let (mut typed, mut untyped) = (Vec::new(), Vec::new());
2219 let schemas = self.table().entries.values().map(|e| e.object.plugin_schema()).chain(self.static_children()).collect::<Vec<_>>();
2220 for schema in schemas {
2221 super::slots::slot_schemas(&schema, &mut typed, &mut untyped);
2222 }
2223 (typed, untyped)
2224 }
2225
2226 pub fn described_children(&self) -> Vec<PluginSchema> {
2231 let mut out = self.static_children();
2232 out.extend(self.slot_children().0);
2233 out
2234 }
2235
2236 fn gate_index(&self) -> Arc<GateIndex> {
2239 if let Some(index) = self.inner.gate_index.read().unwrap_or_else(|p| p.into_inner()).as_ref() {
2240 return index.clone();
2241 }
2242 let index = Arc::new(self.build_gate_index());
2243 *self.inner.gate_index.write().unwrap_or_else(|p| p.into_inner()) = Some(index.clone());
2244 index
2245 }
2246
2247 fn build_gate_index(&self) -> GateIndex {
2248 {
2249 let mut index = HashMap::new();
2250 for m in &Activation::plugin_schema(self).methods {
2252 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
2253 info.grant = Some(format!("{}.{}", self.inner.namespace, m.name));
2256 index.insert(format!("{}.{}", self.inner.namespace, m.name), info);
2257 }
2258 let (typed, untyped) = self.slot_children();
2270 let activations: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).collect();
2271
2272 let statics = self.static_children();
2273 for schema in activations.iter().chain(statics.iter()).chain(typed.iter()) {
2274 for m in &schema.methods {
2275 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
2276 info.grant = Some(m.grant_or(&schema.namespace));
2277 index.insert(format!("{}.{}", schema.namespace, m.name), info);
2278 }
2279 }
2280 for path in &untyped {
2281 index.insert(
2282 path.clone(),
2283 super::scope_gate::MethodGateInfo { grant: Some(path.clone()), ..Default::default() },
2284 );
2285 }
2286 let slots = super::slots::Slots::of(activations.iter().chain(statics.iter()).chain(typed.iter()), &untyped);
2287 GateIndex { methods: index, slots }
2288 }
2289 }
2290
2291 pub fn with_forward_policy(
2312 mut self,
2313 callee_ns: impl Into<String>,
2314 policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>,
2315 ) -> Self {
2316 let inner = self.inner_mut("Cannot register forward policy: DynamicHub has multiple references");
2317 inner.forward_policies.register(callee_ns, policy);
2318 self
2319 }
2320
2321 pub fn forward_policies(&self) -> &super::forward_registry::ForwardPolicyRegistry {
2326 &self.inner.forward_policies
2327 }
2328
2329 pub fn with_auth_capabilities(
2365 mut self,
2366 caps: plexus_auth_core::BackendAuthCapabilities,
2367 ) -> Self {
2368 let inner = self.inner_mut("Cannot set auth_capabilities: DynamicHub has multiple references");
2369 inner.auth_capabilities = Some(caps);
2370 self
2371 }
2372
2373 pub fn auth_capabilities(&self) -> Option<&plexus_auth_core::BackendAuthCapabilities> {
2380 self.inner.auth_capabilities.as_ref()
2381 }
2382
2383 #[deprecated(since = "0.3.0", note = "Use DynamicHub::new(namespace) instead")]
2385 pub fn with_namespace(namespace: impl Into<String>) -> Self {
2386 Self::new(namespace)
2387 }
2388
2389 pub fn runtime_namespace(&self) -> &str {
2391 &self.inner.namespace
2392 }
2393
2394 pub fn registry(&self) -> std::sync::RwLockReadGuard<'_, PluginRegistry> {
2396 self.inner.registry.read().unwrap()
2397 }
2398
2399 fn assert_no_root_shadow(&self, child_namespace: &str) {
2410 if child_namespace == self.inner.namespace {
2411 panic!(
2412 "DynamicHub namespace shadow: activation namespace '{child}' collides with the hub root namespace '{root}'. \
2413 The hub root name is a routing namespace, not a label — routing resolves the root first, so a like-named \
2414 child activation is unreachable (every '{child}.<method>' call resolves to the hub root and fails with \
2415 'Command not found', and navigation resolves the child back to the root schema). \
2416 Fix: rename the hub root so it differs from every registered activation's namespace, \
2417 e.g. DynamicHub::new(\"{root}_hub\").register(...). [Z2H-8 / HOSTLESS-3]",
2418 child = child_namespace,
2419 root = self.inner.namespace,
2420 );
2421 }
2422 }
2423
2424 pub fn register<A: Activation + ChildRouter + Clone + 'static>(self, activation: A) -> Self {
2433 self.register_entry(activation)
2434 }
2435
2436 #[deprecated(since = "0.5.0", note = "Use register() — it now handles both leaf and hub activations")]
2446 pub fn register_hub<A: Activation + ChildRouter + Clone + 'static>(self, activation: A) -> Self {
2447 self.register_entry(activation)
2448 }
2449
2450 pub(crate) fn entry_of<A: Activation + ChildRouter + Clone + 'static>(activation: A) -> super::service_root::Entry {
2452 let router = Arc::new(activation.clone());
2453 super::service_root::Entry { object: Arc::new(ActivationWrapper { inner: activation }), router }
2454 }
2455
2456 fn register_entry<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2460 let namespace = activation.namespace().to_string();
2461 self.assert_no_root_shadow(&namespace);
2462 let activation_for_rpc = activation.clone();
2463 let entry = Self::entry_of(activation);
2464 let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2465 Self::index_entry(inner.registry.get_mut().unwrap_or_else(|p| p.into_inner()), inner.auth_catalog.as_ref(), &namespace, &entry);
2466 let table = Arc::make_mut(inner.root.get_mut().unwrap_or_else(|p| p.into_inner()));
2467 if let Some(old) = table.entries.insert(namespace, entry.clone()) {
2468 table.nested -= old.object.static_child_schemas().len();
2469 }
2470 table.nested += entry.object.static_child_schemas().len();
2472 inner.pending_rpc.lock().unwrap()
2473 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2474 self
2475 }
2476
2477 fn index_entry(
2481 registry: &mut PluginRegistry,
2482 catalog: Option<&super::auth_activation::Catalog>,
2483 namespace: &str,
2484 entry: &super::service_root::Entry,
2485 ) {
2486 registry.register(entry.object.plugin_id(), namespace.to_string(), namespace.to_string());
2487 if let Some(catalog) = catalog {
2488 let schema = entry.object.plugin_schema();
2489 let statics = super::children::qualified(&schema.namespace, entry.object.static_child_schemas());
2491 let (mut typed, mut untyped) = (Vec::new(), Vec::new());
2494 for s in std::iter::once(&schema).chain(statics.iter()) {
2495 super::slots::slot_schemas(s, &mut typed, &mut untyped);
2496 }
2497 for child in statics.iter().chain(typed.iter()) {
2498 catalog.add(child);
2499 }
2500 catalog.add_slots(&untyped);
2501 catalog.add(&schema);
2502 }
2503 }
2504
2505 pub fn root(&self) -> super::service_root::ServiceRoot {
2508 super::service_root::ServiceRoot { hub: self.clone() }
2509 }
2510
2511 pub(crate) fn table(&self) -> Arc<super::service_root::Table> {
2513 self.inner.root.read().unwrap_or_else(|p| p.into_inner()).clone()
2514 }
2515
2516 pub(crate) fn watch_root(&self) -> tokio::sync::watch::Receiver<String> {
2518 self.inner.root_watch.subscribe()
2519 }
2520
2521 pub(crate) fn insert_entry(&self, name: String, entry: super::service_root::Entry, replace: bool) -> Result<bool, super::service_root::RootError> {
2525 super::service_root::check_name(&name)?;
2526 if name == self.inner.namespace {
2527 return Err(super::service_root::RootError::Shadows { name });
2528 }
2529 if let Some(needs) = entry.object.needs() {
2531 self.check_needs(&name, &needs).map_err(super::service_root::RootError::Needs)?;
2532 }
2533 let before = self.compute_hash();
2534 let replaced = self.change_table(|table| {
2535 if !replace && table.entries.contains_key(&name) {
2536 return Err(super::service_root::RootError::Taken { name: name.clone() });
2537 }
2538 let nested = entry.object.static_child_schemas().len();
2539 let old = table.entries.insert(name.clone(), entry.clone());
2540 if let Some(old) = old.as_ref() {
2541 table.nested -= old.object.static_child_schemas().len();
2542 }
2543 table.nested += nested;
2544 Ok(old.is_some())
2545 })?;
2546 Self::index_entry(&mut self.inner.registry.write().unwrap_or_else(|p| p.into_inner()), self.inner.auth_catalog.as_ref(), &name, &entry);
2547 self.table_moved(before);
2548 Ok(replaced)
2549 }
2550
2551 pub fn config(&self) -> super::config::Config {
2556 self.inner.config.get_or_init(super::config::Config::new).clone()
2557 }
2558
2559 pub fn with_config(mut self, config: super::config::Config) -> Self {
2562 let inner = self.inner_mut("Cannot set config: DynamicHub has multiple references");
2563 inner.config = std::sync::OnceLock::from(config);
2564 self
2565 }
2566
2567 pub fn with_config_service(self) -> Self {
2571 let config = self.config();
2572 if let Err(why) = super::config::require_everywhere() {
2574 panic!("{why}");
2575 }
2576 self.register(super::config::ConfigActivation::new(config))
2577 }
2578
2579 pub fn notices(&self) -> tokio::sync::broadcast::Receiver<super::parent::Notice> {
2582 self.inner.notices.subscribe()
2583 }
2584
2585 pub fn notify(&self, notice: super::parent::Notice) -> u64 {
2587 self.inner.notices.send(notice).map(|n| n as u64).unwrap_or(0)
2588 }
2589
2590 pub fn method_at(&self, path: &str) -> Option<(String, String)> {
2596 let own = Activation::plugin_schema(self);
2597 if let Some(m) = path.strip_prefix(&format!("{}.", self.inner.namespace)).and_then(|m| own.methods.iter().find(|x| x.name == m)) {
2598 return Some((super::peer::Interface::method_hash(m), path.to_string()));
2599 }
2600 let (at, name) = path.rsplit_once('.')?;
2601 let activations: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).collect();
2602 let statics = self.static_children();
2603 let typed = self.slot_children().0;
2604 activations
2605 .iter()
2606 .chain(statics.iter())
2607 .chain(typed.iter())
2608 .filter(|s| s.namespace == at)
2609 .flat_map(|s| s.methods.iter().map(move |m| (s, m)))
2610 .find(|(_, m)| m.name == name && matches!(m.role, super::schema::MethodRole::Rpc))
2611 .map(|(s, m)| (super::peer::Interface::method_hash(m), m.grant_or(&s.namespace)))
2612 }
2613
2614 pub(crate) fn grant_at(&self, path: &str) -> Option<String> {
2617 self.gate_index().info(path).and_then(|i| i.grant.clone())
2618 }
2619
2620 pub fn check_needs(&self, child: &str, needs: &[super::schema::Need]) -> Result<(), super::parent::NeedsMiss> {
2623 super::parent::check_needs(child, &self.inner.namespace, needs, |p| {
2626 self.method_at(p).map(|(h, _)| h).or_else(|| self.gate_index().slots.resolve(p).map(|_| String::new()))
2627 })
2628 }
2629
2630 pub fn check_grafts(&self) -> Result<(), Vec<super::parent::NeedsMiss>> {
2634 let misses: Vec<_> = self
2635 .table()
2636 .entries
2637 .iter()
2638 .filter_map(|(name, e)| e.object.needs().map(|n| (name.clone(), n)))
2639 .filter_map(|(name, needs)| self.check_needs(&name, &needs).err())
2640 .collect();
2641 if misses.is_empty() { Ok(()) } else { Err(misses) }
2642 }
2643
2644 pub(crate) fn remove_entry(&self, name: &str) -> bool {
2646 let before = self.compute_hash();
2647 let gone = self.change_table(|table| {
2648 let old = table.entries.remove(name);
2649 if let Some(old) = old.as_ref() {
2650 table.nested -= old.object.static_child_schemas().len();
2651 }
2652 old
2653 });
2654 let Some(old) = gone else { return false };
2655 self.inner.registry.write().unwrap_or_else(|p| p.into_inner()).remove(old.object.plugin_id());
2656 if let Some(catalog) = self.inner.auth_catalog.as_ref() {
2657 catalog.remove_under(name);
2658 }
2659 self.table_moved(before);
2660 true
2661 }
2662
2663 fn change_table<R>(&self, change: impl FnOnce(&mut super::service_root::Table) -> R) -> R {
2665 let mut root = self.inner.root.write().unwrap_or_else(|p| p.into_inner());
2666 let mut table = (**root).clone();
2667 let out = change(&mut table);
2668 *root = Arc::new(table);
2669 out
2670 }
2671
2672 fn table_moved(&self, before: String) {
2677 *self.inner.gate_index.write().unwrap_or_else(|p| p.into_inner()) = None;
2678 *self.inner.input_index.write().unwrap_or_else(|p| p.into_inner()) = None;
2679 self.inner.describe.schema_moved();
2680 let after = self.compute_hash();
2681 PlexusContext::moved(&before, &after);
2682 self.inner.root_watch.send_replace(after);
2683 }
2684
2685 pub fn list_methods(&self) -> Vec<String> {
2687 let mut methods = Vec::new();
2688
2689 for m in Activation::methods(self) {
2691 methods.push(format!("{}.{}", self.inner.namespace, m));
2692 }
2693
2694 for (ns, e) in &self.table().entries {
2696 let act = &e.object;
2697 for m in act.methods() {
2698 methods.push(format!("{}.{}", ns, m));
2699 }
2700 }
2701 methods.sort();
2702 methods
2703 }
2704
2705 pub fn list_activations_info(&self) -> Vec<ActivationInfo> {
2707 let mut activations = Vec::new();
2708
2709 activations.push(ActivationInfo {
2711 namespace: Activation::namespace(self).to_string(),
2712 version: Activation::version(self).to_string(),
2713 description: Activation::description(self).to_string(),
2714 methods: Activation::methods(self).iter().map(|s| s.to_string()).collect(),
2715 });
2716
2717 for e in self.table().entries.values() {
2719 let a = &e.object;
2720 activations.push(ActivationInfo {
2721 namespace: a.namespace().to_string(),
2722 version: a.version().to_string(),
2723 description: a.description().to_string(),
2724 methods: a.methods().iter().map(|s| s.to_string()).collect(),
2725 });
2726 }
2727
2728 activations
2729 }
2730
2731 pub fn compute_hash(&self) -> String {
2739 self.described().service.hash.clone()
2741 }
2742
2743 fn own_hash(&self, caller: Option<&super::auth::AuthContext>) -> String {
2747 match self.inner.gate {
2748 Some(_) => self.shaped(caller).1.hash.clone(),
2749 None => self.described().service.hash.clone(),
2750 }
2751 }
2752
2753 fn own_schema(&self, caller: Option<&super::auth::AuthContext>) -> PluginSchema {
2756 match self.inner.gate {
2757 Some(_) => self.shaped(caller).1.service.clone(),
2758 None => self.described().service.clone(),
2759 }
2760 }
2761
2762 pub async fn route(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>) -> Result<PlexusStream, PlexusError> {
2764 self.route_with_ctx(method, params, auth, None).await
2765 }
2766
2767 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> {
2775 if super::service_scope::entered() {
2776 return self.route_entered(method, params, auth, raw_ctx).await;
2777 }
2778 super::service_scope::scope(self.downgrade(), self.route_entered(method, params, auth, raw_ctx)).await
2779 }
2780
2781 pub fn downgrade(&self) -> super::service_scope::WeakService {
2784 super::service_scope::WeakService::new(Arc::downgrade(&self.inner))
2785 }
2786
2787 pub(crate) async fn schema_for_child(&self, method: &str, params: Value) -> Result<PlexusStream, PlexusError> {
2792 let (_, name) = self.parse_method(method)?;
2793 if !Self::is_schema_query(name) {
2794 return Err(PlexusError::Unauthenticated(format!(
2795 "`{method}` is not a schema: outside a call, a child asks its service only for a schema"
2796 )));
2797 }
2798 let ctx = crate::call::CallContext::admitted(None, plexus_auth_core::grants::Reach::nowhere());
2801 let routed = self.route_ungated(method, params, None, None);
2802 super::service_scope::scope(self.downgrade(), in_call(ctx, routed)).await
2803 }
2804
2805 async fn route_entered(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2807 if let Some(gate) = self.inner.gate.as_ref() {
2810 let (auth, ended) = super::grant_gate::standing(gate, auth);
2812 let decide = |info| super::grant_gate::decide(gate, &self.inner.namespace, method, info, ¶ms, auth, &self.inner.signed_in_grants);
2813 let index = self.gate_index();
2814 let admit = match index.methods.get(method) {
2815 Some(info) => decide(Some(info)),
2816 None => match index.info(method) {
2820 Some(slot) => {
2823 let literal = super::scope_gate::MethodGateInfo { everywhere: slot.everywhere, ..Default::default() };
2824 decide(Some(&literal)).or_else(|_| decide(Some(slot)))
2825 }
2826 None => decide(None),
2827 },
2828 }
2829 .map_err(|e| super::grant_gate::say_ended(e, ended.as_deref()))?;
2830 return match admit {
2831 super::grant_gate::Admit::Open => {
2835 let method = self.bare_introspection(method);
2837 let grant = plexus_auth_core::grants::Grant::new(method.to_string());
2838 in_call(crate::call::CallContext::introspection(auth, Arc::clone(gate), grant), async {
2839 match self.introspect_in_view(method, ¶ms, auth, raw_ctx).await {
2840 Some(answer) => answer,
2841 None => self.route_ungated(method, params, auth, raw_ctx).await,
2842 }
2843 })
2844 .await
2845 }
2846 super::grant_gate::Admit::Reach(reach) => {
2847 in_call(crate::call::CallContext::admitted(auth, reach), self.route_ungated(method, params, auth, raw_ctx)).await
2848 }
2849 };
2850 }
2851 let ctx = match crate::call::context() {
2858 Ok(outer) => outer.with_auth(auth),
2859 Err(_) => crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere()),
2860 };
2861 in_call(ctx, self.route_ungated(method, params, auth, raw_ctx)).await
2862 }
2863
2864 async fn route_ungated(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2866 if self.inner.scope_registry.is_some() || self.inner.default_deny {
2871 let registry = self
2872 .inner
2873 .scope_registry
2874 .as_deref()
2875 .unwrap_or_else(|| super::scope_gate::empty_registry());
2876 super::scope_gate::enforce(
2877 registry,
2878 self.inner.default_deny,
2879 &self.inner.audit_sink,
2880 method,
2881 self.gate_index().info(method),
2882 auth,
2883 raw_ctx.and_then(|ctx| ctx.peer.map(|peer| peer.ip())),
2884 )
2885 .await?;
2886 }
2887
2888 let (namespace, method_name) = self.parse_method(method)?;
2889
2890 if namespace == self.inner.namespace && method_name == "ir" {
2892 self.check_ir_names(¶ms, auth)?;
2893 }
2894
2895 let stream = if namespace == self.inner.namespace {
2900 Activation::call(self, method_name, params, auth, raw_ctx).await?
2901 } else {
2902 let entry = self.table().entries.get(namespace).map(|e| e.object.clone())
2903 .ok_or_else(|| PlexusError::ActivationNotFound(namespace.to_string()))?;
2904
2905 entry.call(method_name, params, auth, raw_ctx).await?
2906 };
2907
2908 if Self::is_schema_query(method_name) {
2915 if let Some(site) = self.derived_site_hint() {
2916 return Ok(fill_site_hints_in_schema_stream(stream, site));
2917 }
2918 }
2919 Ok(stream)
2920 }
2921
2922 fn is_schema_query(method_name: &str) -> bool {
2927 method_name == "schema" || method_name.ends_with(".schema")
2928 }
2929
2930 pub fn derived_site_hint(&self) -> Option<plexus_auth_core::AttachmentSite> {
2936 self.inner
2937 .auth_capabilities
2938 .as_ref()
2939 .and_then(|caps| caps.implied_attachment_site())
2940 }
2941
2942 pub async fn do_resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
2946 let path = self.inner.registry.read().unwrap()
2947 .lookup(handle.plugin_id)
2948 .map(|s| s.to_string())
2949 .ok_or_else(|| PlexusError::ActivationNotFound(handle.plugin_id.to_string()))?;
2950
2951 let activation = self.table().entries.get(&path).map(|e| e.object.clone())
2952 .ok_or_else(|| PlexusError::ActivationNotFound(path.clone()))?;
2953 activation.resolve_handle(handle).await
2954 }
2955
2956 pub fn get_activation_schema(&self, namespace: &str) -> Option<Schema> {
2958 self.table().entries.get(namespace).map(|e| e.object.schema())
2959 }
2960
2961 pub fn registry_snapshot(&self) -> PluginRegistrySnapshot {
2963 let guard = self.inner.registry.read().unwrap();
2964 PluginRegistrySnapshot {
2965 by_id: guard.by_id.clone(),
2966 by_path: guard.by_path.clone(),
2967 }
2968 }
2969
2970 pub fn lookup_plugin(&self, id: uuid::Uuid) -> Option<String> {
2972 self.inner.registry.read().unwrap().lookup(id).map(|s| s.to_string())
2973 }
2974
2975 pub fn lookup_plugin_by_path(&self, path: &str) -> Option<uuid::Uuid> {
2977 self.inner.registry.read().unwrap().lookup_by_path(path)
2978 }
2979
2980 pub fn list_plugin_schemas(&self) -> Vec<PluginSchema> {
2982 let mut schemas = Vec::new();
2983
2984 schemas.push(Activation::plugin_schema(self));
2986
2987 for e in self.table().entries.values() {
2989 schemas.push(e.object.plugin_schema());
2990 }
2991
2992 schemas
2993 }
2994
2995 #[deprecated(note = "Use list_plugin_schemas instead")]
2997 pub fn list_full_schemas(&self) -> Vec<PluginSchema> {
2998 self.list_plugin_schemas()
2999 }
3000
3001 pub fn get_method_help(&self, method: &str) -> Option<String> {
3003 let (namespace, method_name) = self.parse_method(method).ok()?;
3004 let table = self.table();
3005 table.entries.get(namespace)?.object.method_help(method_name)
3006 }
3007
3008 fn parse_method<'a>(&self, method: &'a str) -> Result<(&'a str, &'a str), PlexusError> {
3009 let parts: Vec<&str> = method.splitn(2, '.').collect();
3010 if parts.len() != 2 {
3011 return Err(PlexusError::InvalidParams {
3012 param: Some("method".into()),
3013 problem: ParamProblem::Malformed {
3014 detail: format!("expected `namespace.method`, got `{}`", method),
3015 },
3016 });
3017 }
3018 Ok((parts[0], parts[1]))
3019 }
3020
3021 pub fn plugin_children(&self) -> Vec<ChildSummary> {
3026 self.table().entries.values()
3027 .map(|e| {
3028 let schema = e.object.plugin_schema();
3029 ChildSummary {
3030 namespace: schema.namespace,
3031 description: schema.description,
3032 hash: schema.hash,
3033 }
3034 })
3035 .collect()
3036 }
3037
3038 pub fn into_rpc_module(self) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
3040 let mut module = RpcModule::new(());
3041
3042 if let Err(misses) = self.check_grafts() {
3045 panic!("{}", misses.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "));
3046 }
3047 PlexusContext::init(self.compute_hash());
3048
3049 let ns = self.runtime_namespace();
3052 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
3053 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
3054 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
3055 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
3056 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
3057 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
3058 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
3059 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
3060 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
3061
3062 let plexus_for_call = self.clone();
3064 module.register_subscription(
3065 call_method,
3066 PLEXUS_NOTIF_METHOD,
3067 call_unsub,
3068 move |params, pending, _ctx, ext| {
3069 let plexus = plexus_for_call.clone();
3070 let identified = plexus.inner.gate.is_some();
3074 serve_call(plexus, params, pending, ext, ns_static, identified)
3075 }
3076 )?;
3077
3078 register_input_methods(&mut module, ns_static)?;
3079
3080 let plexus_for_hash = self.clone();
3082 module.register_subscription(
3083 hash_method,
3084 PLEXUS_NOTIF_METHOD,
3085 hash_unsub,
3086 move |_params, pending, _ctx, ext| {
3087 let plexus = plexus_for_hash.clone();
3088 Box::pin(async move {
3089 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3091 let value = plexus.own_hash(auth);
3092 let stream = async_stream::stream! {
3093 yield HashEvent::Hash { value };
3094 };
3095 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
3096 pipe_stream_to_subscription(pending, wrapped, &ext).await
3097 })
3098 }
3099 )?;
3100
3101 let plexus_for_schema = self.clone();
3103 module.register_subscription(
3104 schema_method,
3105 PLEXUS_NOTIF_METHOD,
3106 schema_unsub,
3107 move |params, pending, _ctx, ext| {
3108 let plexus = plexus_for_schema.clone();
3109 Box::pin(async move {
3110 let p: SchemaParams = params.parse().unwrap_or_default();
3111 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3113 let mut plugin_schema = plexus.own_schema(auth);
3114 if let Some(site) = plexus.derived_site_hint() {
3116 plugin_schema.fill_site_hints(&site);
3117 }
3118
3119 let result = if let Some(ref name) = p.method {
3120 plugin_schema.methods.iter()
3121 .find(|m| m.name == *name)
3122 .map(|m| super::SchemaResult::Method(m.clone()))
3123 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
3124 -32602,
3125 format!("Method '{}' not found", name),
3126 None::<()>,
3127 ))?
3128 } else {
3129 super::SchemaResult::Plugin(plugin_schema)
3130 };
3131
3132 let stream = async_stream::stream! { yield result; };
3133 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
3134 pipe_stream_to_subscription(pending, wrapped, &ext).await
3135 })
3136 }
3137 )?;
3138
3139 let info_payload = build_info_payload(
3145 self.runtime_namespace(),
3146 self.inner.auth_capabilities.as_ref(),
3147 );
3148 let plexus_for_info = self.inner.gate.is_some().then(|| self.clone());
3151 module.register_subscription(
3152 "_info",
3153 PLEXUS_NOTIF_METHOD,
3154 "_info_unsub",
3155 move |_params, pending, _ctx, ext| {
3156 let payload = match plexus_for_info.as_ref() {
3157 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
3158 None => info_payload.clone(),
3159 };
3160 Box::pin(async move {
3161 let info_stream = futures::stream::once(async move { payload });
3163
3164 let wrapped = super::streaming::wrap_stream(
3166 info_stream,
3167 "_info",
3168 vec![]
3169 );
3170
3171 pipe_stream_to_subscription(pending, wrapped, &ext).await
3173 })
3174 }
3175 )?;
3176
3177 let pending = std::mem::take(&mut *self.inner.pending_rpc.lock().unwrap());
3181 if self.inner.gate.is_none() {
3182 for factory in pending {
3183 module.merge(factory())?;
3184 }
3185 }
3186
3187 if self.inner.gate.is_none() {
3192 for (ns, e) in self.table().entries.iter() {
3193 register_child_capability_methods(&mut module, ns, e.router.clone())?;
3194 }
3195 }
3196
3197 Ok(module)
3198 }
3199
3200 pub fn serve_call(
3211 &self,
3212 params: jsonrpsee::types::Params<'static>,
3213 pending: jsonrpsee::PendingSubscriptionSink,
3214 ext: http::Extensions,
3215 ns: &'static str,
3216 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>> {
3217 serve_call(self.clone(), params, pending, ext, ns, true)
3218 }
3219
3220 pub fn arc_into_rpc_module(hub: Arc<Self>) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
3226 let mut module = RpcModule::new(());
3227
3228 if let Err(misses) = hub.check_grafts() {
3231 panic!("{}", misses.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "));
3232 }
3233 PlexusContext::init(hub.compute_hash());
3234
3235 let ns = hub.runtime_namespace();
3238 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
3239 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
3240 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
3241 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
3242 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
3243 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
3244 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
3245 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
3246 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
3247
3248 let hub_for_call = hub.clone();
3250 module.register_subscription(
3251 call_method,
3252 call_method,
3253 call_unsub,
3254 move |params, pending, _ctx, ext| {
3255 let hub = hub_for_call.clone();
3256 let hub = (*hub).clone();
3257 serve_call(hub, params, pending, ext, ns_static, true)
3258 }
3259 )?;
3260
3261 register_input_methods(&mut module, ns_static)?;
3262
3263 let hub_for_hash = hub.clone();
3265 module.register_subscription(
3266 hash_method,
3267 PLEXUS_NOTIF_METHOD,
3268 hash_unsub,
3269 move |_params, pending, _ctx, ext| {
3270 let hub = hub_for_hash.clone();
3271 Box::pin(async move {
3272 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3274 let value = hub.own_hash(auth);
3275 let stream = async_stream::stream! {
3276 yield HashEvent::Hash { value };
3277 };
3278 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
3279 pipe_stream_to_subscription(pending, wrapped, &ext).await
3280 })
3281 }
3282 )?;
3283
3284 let hub_for_schema = hub.clone();
3286 module.register_subscription(
3287 schema_method,
3288 PLEXUS_NOTIF_METHOD,
3289 schema_unsub,
3290 move |params, pending, _ctx, ext| {
3291 let hub = hub_for_schema.clone();
3292 Box::pin(async move {
3293 let p: SchemaParams = params.parse().unwrap_or_default();
3294 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3296 let mut plugin_schema = hub.own_schema(auth);
3297 if let Some(site) = hub.derived_site_hint() {
3299 plugin_schema.fill_site_hints(&site);
3300 }
3301
3302 let result = if let Some(ref name) = p.method {
3303 plugin_schema.methods.iter()
3304 .find(|m| m.name == *name)
3305 .map(|m| super::SchemaResult::Method(m.clone()))
3306 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
3307 -32602,
3308 format!("Method '{}' not found", name),
3309 None::<()>,
3310 ))?
3311 } else {
3312 super::SchemaResult::Plugin(plugin_schema)
3313 };
3314
3315 let stream = async_stream::stream! {
3316 yield result;
3317 };
3318 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
3319 pipe_stream_to_subscription(pending, wrapped, &ext).await
3320 })
3321 }
3322 )?;
3323
3324 let info_payload = build_info_payload(
3329 hub.runtime_namespace(),
3330 hub.inner.auth_capabilities.as_ref(),
3331 );
3332 let hub_for_info = hub.inner.gate.is_some().then(|| hub.clone());
3335 module.register_subscription(
3336 "_info",
3337 PLEXUS_NOTIF_METHOD,
3338 "_info_unsub",
3339 move |_params, pending, _ctx, ext| {
3340 let payload = match hub_for_info.as_ref() {
3341 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
3342 None => info_payload.clone(),
3343 };
3344 Box::pin(async move {
3345 let info_stream = futures::stream::once(async move { payload });
3347
3348 let wrapped = super::streaming::wrap_stream(
3350 info_stream,
3351 "_info",
3352 vec![]
3353 );
3354
3355 pipe_stream_to_subscription(pending, wrapped, &ext).await
3357 })
3358 }
3359 )?;
3360
3361 let mut pending = std::mem::take(&mut *hub.inner.pending_rpc.lock().unwrap());
3364 if hub.inner.gate.is_some() {
3365 pending.clear();
3366 }
3367 tracing::trace!(factories = pending.len(), "merging activation RPC factories");
3368 for (idx, factory) in pending.into_iter().enumerate() {
3369 tracing::trace!(factory_idx = idx, "calling factory to get Methods");
3370 let methods = factory();
3371 let method_count = methods.method_names().count();
3372 tracing::trace!(factory_idx = idx, methods = method_count, "factory returned Methods; merging into module");
3373 module.merge(methods)?;
3374 tracing::trace!(factory_idx = idx, "successfully merged factory methods");
3375 }
3376 tracing::trace!("all activations merged successfully");
3377
3378 if hub.inner.gate.is_none() {
3382 for (ns, e) in hub.table().entries.iter() {
3383 register_child_capability_methods(&mut module, ns, e.router.clone())?;
3384 }
3385 }
3386
3387 Ok(module)
3388 }
3389}
3390
3391fn listing_context(ext: &jsonrpsee::Extensions) -> crate::call::CallContext {
3416 let auth = ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3417 crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere())
3418}
3419
3420#[allow(deprecated)] fn register_child_capability_methods(
3422 module: &mut RpcModule<()>,
3423 namespace: &str,
3424 router: Arc<dyn ChildRouter>,
3425) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3426 let caps = router.capabilities();
3427 if caps.is_empty() {
3428 return Ok(());
3429 }
3430
3431 let ns_static: &'static str = Box::leak(namespace.to_string().into_boxed_str());
3432
3433 if caps.contains(ChildCapabilities::LIST) {
3434 let list_method: &'static str =
3435 Box::leak(format!("{}.list_children", namespace).into_boxed_str());
3436 let list_unsub: &'static str =
3437 Box::leak(format!("{}.list_children_unsub", namespace).into_boxed_str());
3438 let router_for_list = router.clone();
3439 module.register_subscription(
3440 list_method,
3441 PLEXUS_NOTIF_METHOD,
3442 list_unsub,
3443 move |_params, pending, _ctx, ext| {
3444 let router = router_for_list.clone();
3445 let ctx = listing_context(&ext);
3446 Box::pin(async move {
3447 let collected: Vec<String> = crate::call::scope(ctx, async {
3454 match router.list_children().await {
3455 Some(mut s) => {
3456 use futures::StreamExt;
3457 let mut acc = Vec::new();
3458 while let Some(name) = s.next().await {
3459 acc.push(name);
3460 }
3461 acc
3462 }
3463 None => Vec::new(),
3464 }
3465 })
3466 .await;
3467 let stream = async_stream::stream! {
3468 for name in collected {
3469 yield name;
3470 }
3471 };
3472 let wrapped = super::streaming::wrap_stream(
3473 stream,
3474 "list_children",
3475 vec![ns_static.into()],
3476 );
3477 pipe_stream_to_subscription(pending, wrapped, &ext).await
3478 })
3479 },
3480 )?;
3481 }
3482
3483 if caps.contains(ChildCapabilities::SEARCH) {
3484 let search_method: &'static str =
3485 Box::leak(format!("{}.search_children", namespace).into_boxed_str());
3486 let search_unsub: &'static str =
3487 Box::leak(format!("{}.search_children_unsub", namespace).into_boxed_str());
3488 let router_for_search = router.clone();
3489 module.register_subscription(
3490 search_method,
3491 PLEXUS_NOTIF_METHOD,
3492 search_unsub,
3493 move |params, pending, _ctx, ext| {
3494 let router = router_for_search.clone();
3495 let ctx = listing_context(&ext);
3496 Box::pin(async move {
3497 let p: SearchChildrenParams = params.parse()?;
3498 let collected: Vec<String> = crate::call::scope(ctx, async {
3499 match router.search_children(&p.query).await {
3500 Some(mut s) => {
3501 use futures::StreamExt;
3502 let mut acc = Vec::new();
3503 while let Some(name) = s.next().await {
3504 acc.push(name);
3505 }
3506 acc
3507 }
3508 None => Vec::new(),
3509 }
3510 })
3511 .await;
3512 let stream = async_stream::stream! {
3513 for name in collected {
3514 yield name;
3515 }
3516 };
3517 let wrapped = super::streaming::wrap_stream(
3518 stream,
3519 "search_children",
3520 vec![ns_static.into()],
3521 );
3522 pipe_stream_to_subscription(pending, wrapped, &ext).await
3523 })
3524 },
3525 )?;
3526 }
3527
3528 Ok(())
3529}
3530
3531#[derive(Debug, serde::Deserialize)]
3533struct SearchChildrenParams {
3534 query: String,
3535}
3536
3537#[derive(Debug, serde::Deserialize)]
3539pub(crate) struct CallParams {
3540 pub(crate) method: String,
3541 #[serde(default)]
3542 pub(crate) params: Option<Value>,
3543}
3544
3545pub(crate) struct InputTerms {
3547 pub(crate) grant: String,
3548 pub(crate) targets: Vec<String>,
3549 pub(crate) recheck: bool,
3550}
3551
3552use super::schema::SchemaParams;
3554
3555fn serve_call(
3568 service: DynamicHub,
3569 params: jsonrpsee::types::Params<'static>,
3570 pending: jsonrpsee::PendingSubscriptionSink,
3571 ext: http::Extensions,
3572 ns: &'static str,
3573 identified: bool,
3574) -> CallFuture {
3575 let call: CallParams = match params.parse() {
3578 Ok(call) => call,
3579 Err(e) => return Box::pin(async move { Err(e.into()) }),
3580 };
3581 if service.may_take_input(&call.method) {
3582 return Box::pin(serve_seamed(service, call, params, pending, ext, ns, identified));
3583 }
3584 let CallParams { method, params: args } = call;
3585 Box::pin(async move {
3586 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref()) } else { None };
3587 match service.route(&method, args.unwrap_or_default(), caller).await {
3588 Ok(stream) => pipe_stream_to_subscription(pending, stream, &ext).await,
3589 Err(e) => {
3590 let sink = pending.accept().await?;
3591 if let Some(raw) = error_item_raw(ns, &e) {
3592 let _ = sink.send(raw).await;
3593 }
3594 Ok(())
3595 }
3596 }
3597 })
3598}
3599
3600type CallFuture = std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>>;
3603
3604async fn serve_seamed(
3609 service: DynamicHub,
3610 call: CallParams,
3611 params: jsonrpsee::types::Params<'static>,
3612 pending: jsonrpsee::PendingSubscriptionSink,
3613 ext: http::Extensions,
3614 ns: &'static str,
3615 identified: bool,
3616) -> jsonrpsee::core::SubscriptionResult {
3617 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().cloned() } else { None };
3618 let seen = service.inner.gate.as_ref().map_or(0, |g| g.generation().current());
3619 let opened = Arc::new(std::sync::Mutex::new(None::<super::input::Opened>));
3620 let take = || opened.lock().unwrap_or_else(|e| e.into_inner()).take();
3621 let mut scoped = std::pin::pin!(super::input::CALL.scope(
3622 std::cell::RefCell::new(super::input::Seam { service: service.clone(), params, pending: Some(pending), ext, seen, opened: opened.clone(), refused: None }),
3623 service.route(&call.method, call.params.unwrap_or_default(), caller.as_deref()),
3624 ));
3625 let answered = std::future::poll_fn(|cx| match std::future::Future::poll(scoped.as_mut(), cx) {
3630 std::task::Poll::Ready(answer) => std::task::Poll::Ready(Some(answer)),
3631 std::task::Poll::Pending if opened.lock().unwrap_or_else(|e| e.into_inner()).is_some() => std::task::Poll::Ready(None),
3632 std::task::Poll::Pending => std::task::Poll::Pending,
3633 })
3634 .await;
3635 let Some(answer) = answered else {
3636 let super::input::Opened { sink, duplex } = take().expect("opened, the route still resolving");
3637 let mut routing = std::pin::pin!(async { scoped.as_mut().await.map_err(|e| error_item(ns, &e)) });
3638 return Box::pin(super::wire::pipe_duplex(sink, super::wire::Output::Routing(routing.as_mut()), duplex)).await;
3639 };
3640 let super::input::Seam { pending, ext, refused, .. } = scoped.as_mut().take_value().expect("the scope ran to its end").into_inner();
3641 match (answer, take()) {
3642 (Ok(stream), Some(opened)) => Box::pin(super::wire::pipe_duplex(opened.sink, super::wire::Output::Ready(stream), opened.duplex)).await,
3644 (Ok(stream), None) => {
3645 let pending = pending.expect("only an open takes it, and an open is `opened`");
3646 pipe_stream_to_subscription(pending, stream, &ext).await
3647 }
3648 (Err(e), opened) => {
3649 let sink = match (opened, pending) {
3650 (Some(opened), _) => opened.sink,
3651 (None, Some(pending)) => pending.accept().await?,
3652 (None, None) => return Ok(()),
3653 };
3654 let raw = match refused {
3655 Some(item) => serde_json::value::to_raw_value(&item).ok(),
3656 None => error_item_raw(ns, &e),
3657 };
3658 if let Some(raw) = raw {
3659 let _ = sink.send(raw).await;
3660 }
3661 Ok(())
3662 }
3663 }
3664}
3665
3666fn register_input_methods(module: &mut RpcModule<()>, ns: &'static str) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3672 use super::input::{Delivered, InputTable};
3673 use jsonrpsee::types::ErrorObjectOwned;
3674
3675 fn answer(delivered: Delivered) -> Result<bool, ErrorObjectOwned> {
3676 match delivered {
3677 Delivered::Taken => Ok(true),
3678 Delivered::Dropped | Delivered::Refused => Ok(false),
3679 Delivered::NotThisCall => Err(ErrorObjectOwned::owned(
3680 -32003,
3681 "not_this_call: input comes from the connection that opened the call",
3682 Some(serde_json::json!({"error_kind": "not_this_call"})),
3683 )),
3684 Delivered::Malformed => Err(ErrorObjectOwned::owned(-32602, "invalid params: subscription, seq and items", None::<()>)),
3685 }
3686 }
3687 fn table(ext: &http::Extensions) -> Result<&Arc<InputTable>, ErrorObjectOwned> {
3688 ext.get::<super::wire::FrameSink>()
3689 .and_then(super::wire::FrameSink::inputs)
3690 .ok_or_else(|| ErrorObjectOwned::owned(-32601, "this transport carries no input half: call over a WebSocket", None::<()>))
3691 }
3692
3693 let input_method: &'static str = Box::leak(format!("{ns}.input").into_boxed_str());
3694 let end_method: &'static str = Box::leak(format!("{ns}.end").into_boxed_str());
3695 module.register_method(input_method, move |params, _ctx, ext| {
3696 let frame = bytes::Bytes::copy_from_slice(params.as_str().unwrap_or("null").as_bytes());
3697 answer(table(ext)?.input(ns, &frame, &frame))
3698 })?;
3699 module.register_method(end_method, move |params, _ctx, ext| answer(table(ext)?.end(ns, params.as_str().unwrap_or("null").as_bytes())))?;
3700 Ok(())
3701}
3702
3703async fn pipe_stream_to_subscription(
3714 pending: jsonrpsee::PendingSubscriptionSink,
3715 stream: PlexusStream,
3716 ext: &http::Extensions,
3717) -> jsonrpsee::core::SubscriptionResult {
3718 let sink = pending.accept().await?;
3719 super::wire::pipe(sink, stream, ext).await
3720}
3721
3722#[plexus_macros::activation(
3727 namespace = "plexus",
3728 version = "1.0.0",
3729 description = "Central routing and introspection",
3730 hub,
3731 namespace_fn = "runtime_namespace"
3732)]
3733#[allow(deprecated)]
3734impl DynamicHub {
3735 #[plexus_macros::method(
3737 description = "Route a call to a registered activation",
3738 params(
3739 method = "The method to call (format: namespace.method)",
3740 params = "Parameters to pass to the method (optional, defaults to {})"
3741 )
3742 )]
3743 async fn call(
3744 &self,
3745 method: String,
3746 params: Option<Value>,
3747 ) -> impl Stream<Item = super::types::PlexusStreamItem> + Send + 'static {
3748 use super::context::PlexusContext;
3749 use super::types::{PlexusStreamItem, StreamMetadata};
3750
3751 let result = self.route(&method, params.unwrap_or_default(), None).await;
3752
3753 match result {
3754 Ok(plexus_stream) => {
3755 plexus_stream
3757 }
3758 Err(e) => {
3759 let metadata = StreamMetadata::new(
3761 vec![self.inner.namespace.clone()],
3762 PlexusContext::hash(),
3763 );
3764 Box::pin(futures::stream::once(async move {
3765 PlexusStreamItem::from_plexus_error(metadata, &e, false)
3766 }))
3767 }
3768 }
3769 }
3770
3771 #[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.")]
3776 async fn hash(&self) -> impl Stream<Item = HashEvent> + Send + 'static {
3777 let schema = Activation::plugin_schema(self);
3778 stream! { yield HashEvent::Hash { value: schema.hash }; }
3779 }
3780
3781 #[plexus_macros::method(description = "Get plugin hashes for cache validation")]
3783 #[allow(deprecated)]
3784 async fn hashes(&self) -> impl Stream<Item = PluginHashes> + Send + 'static {
3785 let schema = Activation::plugin_schema(self);
3786
3787 stream! {
3788 yield PluginHashes {
3789 namespace: schema.namespace.clone(),
3790 self_hash: schema.self_hash.clone(),
3791 children_hash: schema.children_hash.clone(),
3792 hash: schema.hash.clone(),
3793 children: schema.children.as_ref().map(|kids| {
3794 kids.iter()
3795 .map(|c| ChildHashes {
3796 namespace: c.namespace.clone(),
3797 hash: c.hash.clone(),
3798 })
3799 .collect()
3800 }),
3801 };
3802 }
3803 }
3804
3805 #[plexus_macros::method(
3811 description = "The service's IR (3.0): every type once, each method referring to them — of the namespaces asked, or the whole service",
3812 params(namespaces = "The namespaces (dotted paths) to describe; none: the whole service")
3813 )]
3814 async fn ir(
3815 &self,
3816 auth: Option<&super::auth::AuthContext>,
3817 namespaces: Option<Vec<String>>,
3818 ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
3819 self.service_ir(&namespaces.unwrap_or_default(), auth).await
3820 }
3821
3822 }
3824
3825use super::hub_context::HubContext;
3830use std::sync::Weak;
3831
3832#[async_trait]
3838impl HubContext for Weak<DynamicHub> {
3839 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
3840 let hub = self.upgrade().ok_or_else(|| {
3841 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3842 })?;
3843 hub.do_resolve_handle(handle).await
3844 }
3845
3846 async fn call(&self, method: &str, params: serde_json::Value) -> Result<PlexusStream, PlexusError> {
3847 let hub = self.upgrade().ok_or_else(|| {
3848 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3849 })?;
3850 hub.route(method, params, None).await
3851 }
3852
3853 fn is_valid(&self) -> bool {
3854 self.upgrade().is_some()
3855 }
3856}
3857
3858#[async_trait]
3863impl ChildRouter for DynamicHub {
3864 fn router_namespace(&self) -> &str {
3865 &self.inner.namespace
3866 }
3867
3868 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
3869 self.route_with_ctx(method, params, auth, raw_ctx).await
3872 }
3873
3874 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3875 self.table().entries.get(name).map(|e| e.router.clone())
3877 .map(|router| {
3878
3879 Box::new(ArcChildRouter(router.clone())) as Box<dyn ChildRouter>
3881 })
3882 }
3883
3884 fn forward_policy_for(
3887 &self,
3888 callee_ns: &str,
3889 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
3890 self.inner.forward_policies.get(callee_ns)
3891 }
3892
3893 }
3900
3901#[cfg(test)]
3902#[allow(deprecated)]
3903mod tests {
3904 use super::*;
3905
3906 #[test]
3907 fn dynamic_hub_implements_activation() {
3908 fn assert_activation<T: Activation>() {}
3909 assert_activation::<DynamicHub>();
3910 }
3911
3912 #[test]
3913 fn dynamic_hub_methods() {
3914 let hub = DynamicHub::new("test");
3915 let methods = hub.methods();
3916 assert!(methods.contains(&"call"));
3917 assert!(methods.contains(&"hash"));
3918 assert!(methods.contains(&"schema"));
3919 }
3921
3922 #[test]
3923 fn dynamic_hub_hash_stable() {
3924 let h1 = DynamicHub::new("test");
3925 let h2 = DynamicHub::new("test");
3926 assert_eq!(h1.compute_hash(), h2.compute_hash());
3927 }
3928
3929 #[test]
3930 fn dynamic_hub_is_hub() {
3931 use crate::activations::health::Health;
3932 let hub = DynamicHub::new("test").register(Health::new());
3933 let schema = hub.plugin_schema();
3934
3935 assert!(schema.is_hub(), "dynamic hub should be a hub");
3937 assert!(!schema.is_leaf(), "dynamic hub should not be a leaf");
3938
3939 let children = schema.children.expect("dynamic hub should have children");
3941 assert!(!children.is_empty(), "dynamic hub should have at least one child");
3942
3943 let health = children.iter().find(|c| c.namespace == "health").expect("should have health child");
3945 assert!(!health.hash.is_empty(), "health should have a hash");
3946 }
3947
3948 #[test]
3953 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3954 fn dynamic_hub_rejects_root_namespace_shadow() {
3955 use crate::activations::health::Health;
3956 let _hub = DynamicHub::new("health").register(Health::new());
3957 }
3958
3959 #[test]
3962 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3963 fn dynamic_hub_register_hub_rejects_root_namespace_shadow() {
3964 use crate::activations::health::Health;
3965 let _hub = DynamicHub::new("health").register_hub(Health::new());
3966 }
3967
3968 #[test]
3972 fn dynamic_hub_shadow_error_names_collision_and_fix() {
3973 use crate::activations::health::Health;
3974 let result = std::panic::catch_unwind(|| {
3975 let _hub = DynamicHub::new("health").register(Health::new());
3976 });
3977 let err = result.expect_err("shadow registration must panic");
3978 let msg = err
3979 .downcast_ref::<String>()
3980 .cloned()
3981 .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
3982 .expect("panic payload should be a string");
3983 assert!(msg.contains("'health'"), "must name the colliding namespace: {msg}");
3984 assert!(msg.contains("hub root namespace"), "must name the root side: {msg}");
3985 assert!(msg.contains("rename the hub root"), "must suggest the fix: {msg}");
3986 assert!(msg.contains("Z2H-8"), "must cite the ticket: {msg}");
3987 }
3988
3989 #[test]
3992 fn dynamic_hub_non_colliding_registration_unaffected() {
3993 use crate::activations::health::Health;
3994 let hub = DynamicHub::new("health_hub").register(Health::new());
3995 assert_eq!(hub.runtime_namespace(), "health_hub");
3996 let schema = hub.plugin_schema();
3997 let children = schema.children.expect("hub should have children");
3998 assert!(
3999 children.iter().any(|c| c.namespace == "health"),
4000 "health child must be registered"
4001 );
4002 assert!(hub.list_methods().iter().any(|m| m.starts_with("health.")));
4003 }
4004
4005 #[test]
4006 fn dynamic_hub_schema_structure() {
4007 use crate::activations::health::Health;
4008 let hub = DynamicHub::new("test").register(Health::new());
4009 let schema = hub.plugin_schema();
4010
4011 let json = serde_json::to_string_pretty(&schema).unwrap();
4013 println!("DynamicHub schema:\n{}", json);
4014
4015 assert_eq!(schema.namespace, "test");
4017 assert!(schema.methods.iter().any(|m| m.name == "call"));
4018 assert!(schema.children.is_some());
4019 }
4020
4021 #[tokio::test]
4026 async fn invariant_resolve_handle_unknown_activation() {
4027 use crate::activations::health::Health;
4028 use crate::types::Handle;
4029 use uuid::Uuid;
4030
4031 let hub = DynamicHub::new("test").register(Health::new());
4032
4033 let unknown_plugin_id = Uuid::new_v4();
4035 let handle = Handle::new(unknown_plugin_id, "1.0.0", "some_method");
4036
4037 let result = hub.do_resolve_handle(&handle).await;
4038
4039 match result {
4040 Err(PlexusError::ActivationNotFound(_)) => {
4041 }
4043 Err(other) => panic!("Expected ActivationNotFound, got {:?}", other),
4044 Ok(_) => panic!("Expected error for unknown activation"),
4045 }
4046 }
4047
4048 #[tokio::test]
4049 async fn invariant_resolve_handle_unsupported() {
4050 use crate::activations::health::Health;
4051 use crate::types::Handle;
4052
4053 let hub = DynamicHub::new("test").register(Health::new());
4054
4055 let handle = Handle::new(Health::PLUGIN_ID, "1.0.0", "check");
4057
4058 let result = hub.do_resolve_handle(&handle).await;
4059
4060 match result {
4061 Err(PlexusError::HandleNotSupported(name)) => {
4062 assert_eq!(name, "health");
4063 }
4064 Err(other) => panic!("Expected HandleNotSupported, got {:?}", other),
4065 Ok(_) => panic!("Expected error for unsupported handle"),
4066 }
4067 }
4068
4069 #[tokio::test]
4070 async fn invariant_resolve_handle_routes_by_plugin_id() {
4071 use crate::activations::health::Health;
4072 use crate::activations::echo::EchoActivation;
4073 use crate::types::Handle;
4074 use uuid::Uuid;
4075
4076 let health = Health::new();
4077 let echo = EchoActivation::new();
4078 let health_plugin_id = health.plugin_id();
4079 let echo_plugin_id = echo.plugin_id();
4080
4081 let hub = DynamicHub::new("test")
4082 .register(health)
4083 .register(echo);
4084
4085 let health_handle = Handle::new(health_plugin_id, "1.0.0", "check");
4087 match hub.do_resolve_handle(&health_handle).await {
4088 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "health"),
4089 Err(other) => panic!("health handle should route to health activation, got {:?}", other),
4090 Ok(_) => panic!("health handle should return HandleNotSupported"),
4091 }
4092
4093 let echo_handle = Handle::new(echo_plugin_id, "1.0.0", "echo");
4095 match hub.do_resolve_handle(&echo_handle).await {
4096 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "echo"),
4097 Err(other) => panic!("echo handle should route to echo activation, got {:?}", other),
4098 Ok(_) => panic!("echo handle should return HandleNotSupported"),
4099 }
4100
4101 let unknown_handle = Handle::new(Uuid::new_v4(), "1.0.0", "method");
4103 match hub.do_resolve_handle(&unknown_handle).await {
4104 Err(PlexusError::ActivationNotFound(_)) => { },
4105 Err(other) => panic!("unknown handle should return ActivationNotFound, got {:?}", other),
4106 Ok(_) => panic!("unknown handle should return ActivationNotFound"),
4107 }
4108 }
4109
4110 #[test]
4111 fn invariant_handle_plugin_id_determines_routing() {
4112 use crate::activations::health::Health;
4113 use crate::activations::echo::EchoActivation;
4114 use crate::types::Handle;
4115
4116 let health = Health::new();
4117 let echo = EchoActivation::new();
4118
4119 let health_handle = Handle::new(health.plugin_id(), "1.0.0", "check")
4121 .with_meta(vec!["msg-123".into(), "user".into()]);
4122 let echo_handle = Handle::new(echo.plugin_id(), "1.0.0", "echo")
4123 .with_meta(vec!["msg-123".into(), "user".into()]);
4124
4125 assert_ne!(health_handle.plugin_id, echo_handle.plugin_id);
4127 }
4128
4129 #[test]
4134 fn plugin_registry_basic_operations() {
4135 let mut registry = PluginRegistry::new();
4136 let id = uuid::Uuid::new_v4();
4137
4138 registry.register(id, "test_plugin".to_string(), "test".to_string());
4140
4141 assert_eq!(registry.lookup(id), Some("test_plugin"));
4143
4144 assert_eq!(registry.lookup_by_path("test_plugin"), Some(id));
4146
4147 let entry = registry.get(id).expect("should have entry");
4149 assert_eq!(entry.path, "test_plugin");
4150 assert_eq!(entry.plugin_type, "test");
4151 }
4152
4153 #[test]
4154 fn plugin_registry_populated_on_register() {
4155 use crate::activations::health::Health;
4156
4157 let hub = DynamicHub::new("test").register(Health::new());
4158
4159 let registry = hub.registry();
4160 assert!(!registry.is_empty(), "registry should not be empty after registration");
4161
4162 let health_id = registry.lookup_by_path("health");
4164 assert!(health_id.is_some(), "health should be registered by path");
4165
4166 let health_uuid = health_id.unwrap();
4168 assert_eq!(registry.lookup(health_uuid), Some("health"));
4169 }
4170
4171 #[test]
4172 fn plugin_registry_deterministic_uuid() {
4173 use crate::activations::health::Health;
4174
4175 let health1 = Health::new();
4177 let health2 = Health::new();
4178
4179 assert_eq!(health1.plugin_id(), health2.plugin_id(),
4180 "same activation type should have deterministic UUID");
4181
4182 let expected = uuid::Uuid::new_v5(
4184 &uuid::Uuid::NAMESPACE_OID,
4185 b"health@1"
4186 );
4187 assert_eq!(health1.plugin_id(), expected,
4188 "plugin_id should be deterministic from namespace@major_version");
4189 }
4190
4191 struct MinimalRouter;
4199
4200 #[async_trait]
4201 impl ChildRouter for MinimalRouter {
4202 fn router_namespace(&self) -> &str {
4203 "minimal"
4204 }
4205
4206 async fn router_call(
4207 &self,
4208 _method: &str,
4209 _params: Value,
4210 _auth: Option<&super::super::auth::AuthContext>,
4211 _raw_ctx: Option<&crate::request::RawRequestContext>,
4212 ) -> Result<PlexusStream, PlexusError> {
4213 Err(PlexusError::MethodNotFound {
4214 activation: "minimal".into(),
4215 method: "none".into(),
4216 })
4217 }
4218
4219 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
4220 None
4221 }
4222 }
4223
4224 #[tokio::test]
4225 async fn child_router_defaults_report_no_capabilities_and_none_streams() {
4226 let router = MinimalRouter;
4227
4228 assert_eq!(
4229 router.capabilities(),
4230 ChildCapabilities::empty(),
4231 "default capabilities should be empty"
4232 );
4233 assert!(
4234 router.list_children().await.is_none(),
4235 "default list_children should be None"
4236 );
4237 assert!(
4238 router.search_children("anything").await.is_none(),
4239 "default search_children should be None"
4240 );
4241 }
4242
4243 struct ListingRouter {
4245 names: Vec<String>,
4246 }
4247
4248 #[async_trait]
4249 impl ChildRouter for ListingRouter {
4250 fn router_namespace(&self) -> &str {
4251 "listing"
4252 }
4253
4254 async fn router_call(
4255 &self,
4256 _method: &str,
4257 _params: Value,
4258 _auth: Option<&super::super::auth::AuthContext>,
4259 _raw_ctx: Option<&crate::request::RawRequestContext>,
4260 ) -> Result<PlexusStream, PlexusError> {
4261 Err(PlexusError::MethodNotFound {
4262 activation: "listing".into(),
4263 method: "none".into(),
4264 })
4265 }
4266
4267 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
4268 if self.names.iter().any(|n| n == name) {
4269 Some(Box::new(ListingRouter { names: vec![] }))
4272 } else {
4273 None
4274 }
4275 }
4276
4277 fn capabilities(&self) -> ChildCapabilities {
4278 ChildCapabilities::LIST | ChildCapabilities::SEARCH
4279 }
4280
4281 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
4282 let stream = futures::stream::iter(self.names.iter().cloned());
4283 Some(Box::pin(stream))
4284 }
4285
4286 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
4287 let q = query.to_string();
4288 let stream = futures::stream::iter(
4289 self.names
4290 .iter()
4291 .filter(move |n| n.contains(&q))
4292 .cloned()
4293 .collect::<Vec<_>>(),
4294 );
4295 Some(Box::pin(stream))
4296 }
4297 }
4298
4299 #[tokio::test]
4300 async fn child_router_overrides_report_capabilities_and_yield_streams() {
4301 use futures::StreamExt;
4302
4303 let router = ListingRouter {
4304 names: vec!["alpha".into(), "beta".into(), "alphabet".into()],
4305 };
4306
4307 let caps = router.capabilities();
4309 assert!(caps.contains(ChildCapabilities::LIST));
4310 assert!(caps.contains(ChildCapabilities::SEARCH));
4311 assert_eq!(caps, ChildCapabilities::LIST | ChildCapabilities::SEARCH);
4312
4313 let list_stream = router
4315 .list_children()
4316 .await
4317 .expect("LIST capability set — expected Some(stream)");
4318 let listed: Vec<String> = list_stream.collect().await;
4319 assert_eq!(listed, vec!["alpha".to_string(), "beta".into(), "alphabet".into()]);
4320
4321 let search_stream = router
4323 .search_children("alpha")
4324 .await
4325 .expect("SEARCH capability set — expected Some(stream)");
4326 let matched: Vec<String> = search_stream.collect().await;
4327 assert_eq!(matched, vec!["alpha".to_string(), "alphabet".into()]);
4328 }
4329
4330 struct WireFixture {
4345 names: Vec<String>,
4346 caps: ChildCapabilities,
4347 }
4348
4349 #[async_trait]
4350 impl ChildRouter for WireFixture {
4351 fn router_namespace(&self) -> &str {
4352 "wirefixture"
4353 }
4354 async fn router_call(
4355 &self,
4356 _method: &str,
4357 _params: Value,
4358 _auth: Option<&super::super::auth::AuthContext>,
4359 _raw_ctx: Option<&crate::request::RawRequestContext>,
4360 ) -> Result<PlexusStream, PlexusError> {
4361 Err(PlexusError::MethodNotFound {
4362 activation: "wirefixture".into(),
4363 method: "none".into(),
4364 })
4365 }
4366 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
4367 None
4368 }
4369 fn capabilities(&self) -> ChildCapabilities {
4370 self.caps
4371 }
4372 async fn list_children(&self) -> Option<futures_core::stream::BoxStream<'_, String>> {
4373 if !self.caps.contains(ChildCapabilities::LIST) {
4374 return None;
4375 }
4376 Some(Box::pin(futures::stream::iter(self.names.clone())))
4377 }
4378 async fn search_children(
4379 &self,
4380 query: &str,
4381 ) -> Option<futures_core::stream::BoxStream<'_, String>> {
4382 if !self.caps.contains(ChildCapabilities::SEARCH) {
4383 return None;
4384 }
4385 let q = query.to_lowercase();
4386 let filtered: Vec<String> = self
4387 .names
4388 .iter()
4389 .filter(|n| n.to_lowercase().contains(&q))
4390 .cloned()
4391 .collect();
4392 Some(Box::pin(futures::stream::iter(filtered)))
4393 }
4394 }
4395
4396 fn build_module_for(router: WireFixture, ns: &str) -> RpcModule<()> {
4397 let mut module = RpcModule::new(());
4398 let arc: Arc<dyn ChildRouter> = Arc::new(router);
4399 register_child_capability_methods(&mut module, ns, arc).expect("register");
4400 module
4401 }
4402
4403 #[tokio::test]
4404 async fn child_wire_registers_both_methods_when_both_bits_set() {
4405 let module = build_module_for(
4406 WireFixture {
4407 names: vec!["alpha".into(), "beta".into()],
4408 caps: ChildCapabilities::LIST | ChildCapabilities::SEARCH,
4409 },
4410 "fixture",
4411 );
4412 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4413 assert!(
4414 names.contains(&"fixture.list_children".to_string()),
4415 "expected fixture.list_children, got: {:?}",
4416 names
4417 );
4418 assert!(
4419 names.contains(&"fixture.search_children".to_string()),
4420 "expected fixture.search_children, got: {:?}",
4421 names
4422 );
4423 }
4424
4425 #[tokio::test]
4426 async fn child_wire_registers_nothing_when_no_bits_set() {
4427 let module = build_module_for(
4428 WireFixture {
4429 names: vec!["alpha".into()],
4430 caps: ChildCapabilities::empty(),
4431 },
4432 "fixture",
4433 );
4434 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4435 assert!(
4436 !names.contains(&"fixture.list_children".to_string()),
4437 "fixture.list_children should NOT be registered when cap absent"
4438 );
4439 assert!(
4440 !names.contains(&"fixture.search_children".to_string()),
4441 "fixture.search_children should NOT be registered when cap absent"
4442 );
4443 }
4444
4445 #[tokio::test]
4446 async fn child_wire_registers_only_list_when_only_list_bit() {
4447 let module = build_module_for(
4448 WireFixture {
4449 names: vec!["alpha".into()],
4450 caps: ChildCapabilities::LIST,
4451 },
4452 "fixture",
4453 );
4454 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4455 assert!(names.contains(&"fixture.list_children".to_string()));
4456 assert!(!names.contains(&"fixture.search_children".to_string()));
4457 }
4458
4459 }