plexus_core/plexus/plexus.rs
1//! DynamicHub - the central routing layer for activations
2//!
3//! DynamicHub IS an activation that also serves as the registry for other activations.
4//! It implements the Plexus RPC protocol for routing and introspection.
5//! It uses hub-macro for its methods, with the `call` method using the streaming
6//! pattern to forward responses from routed methods.
7
8use 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
24/// The JSON-RPC method name used in all plexus subscription notifications.
25///
26/// Every subscription registered by plexus (`.call`, `.hash`, `.schema`, `_info`)
27/// sends notifications with `"method": PLEXUS_NOTIF_METHOD` on the wire.
28/// Clients must match against this value when dispatching raw subscription frames.
29pub 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// ============================================================================
37// Error Types
38// ============================================================================
39
40/// Why the service could not or would not run a call — the server side of the
41/// wire's [`RemoteError`].
42///
43/// Every variant converts to a `RemoteError` (`From<&PlexusError>`), which
44/// is what crosses the wire: in an error frame
45/// (`PlexusStreamItem::error(metadata, RemoteError::from(&e), recoverable)`)
46/// and in the `data` of a JSON-RPC rejection ([`plexus_error_to_jsonrpc`]).
47#[derive(Debug, Clone)]
48pub enum PlexusError {
49 ActivationNotFound(String),
50 MethodNotFound { activation: String, method: String },
51 /// The call's params did not fit the method (RETURNS-6: structured, was
52 /// `InvalidParams(String)`). `param` names the parameter at fault when
53 /// the failure is about one; `problem` says what is wrong with it.
54 InvalidParams {
55 param: Option<String>,
56 problem: ParamProblem,
57 },
58 ExecutionError(String),
59 HandleNotSupported(String),
60 TransportError(TransportErrorKind),
61 Unauthenticated(String),
62 /// Layer-2+ denial from the layered denial model (AUTHZ-0 §4, R-5):
63 /// the caller is authenticated but the call is not authorized.
64 ///
65 /// Produced by the scope gate ([`super::scope_gate`]) when a required
66 /// scope is unmet. The full wire-side rendering policy is
67 /// AUTHZ-PRIVACY-4's (`plexus_error_to_jsonrpc`); this variant only
68 /// commits to the typed server-side value.
69 Forbidden { reason: AuthzDenyReason },
70}
71
72/// Why a [`PlexusError::Forbidden`] denial fired — the layered denial
73/// model's typed discriminator (AUTHZ-S01-output §1, R-5).
74///
75/// No-enumeration posture per AUTHZ-CORE-1/5: each variant carries at most
76/// the single fact the caller already failed. The registry's role taxonomy
77/// and the method's full requirement set are never rendered.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub enum AuthzDenyReason {
80 /// Layer 2 (method authorization): the caller's effective scope set
81 /// does not satisfy `scope` — the FIRST unmet required scope.
82 /// Emitted by the scope gate (R-5 / AUTHZ-CORE-5).
83 MissingScope { scope: plexus_auth_core::Scope },
84 /// Layer 4 (data isolation): typed here per AUTHZ-S01-output §1 but
85 /// NOT emitted by the scope gate — the tenant-scoped storage layer
86 /// (AUTHZ-DATA) owns its emission.
87 TenantBoundary,
88 /// Layer 3 (action context): typed here but NOT emitted by the scope
89 /// gate — AUTHLANG-3's action gate owns its emission.
90 NotAccepted,
91 /// AUTH-2: the grant gate's refusal — the caller does not hold `grant`
92 /// on `scope` (within its session's ceiling). Unlike `MissingScope` it
93 /// names what was needed and where the caller does hold it (owner,
94 /// 2026-10-10: "return the grants required to hit an endpoint"); the
95 /// gate gives it only to a signed-in caller — an anonymous one gets
96 /// [`PlexusError::Unauthenticated`].
97 MissingGrant {
98 /// The method's grant, `<activation>.<method>`.
99 grant: plexus_auth_core::grants::Grant,
100 /// Where it was needed: the target's innermost scope, or `*` for a
101 /// method without a target.
102 scope: plexus_auth_core::grants::ScopeRef,
103 /// The roles that list the grant, `admin` last.
104 roles: Vec<plexus_auth_core::RoleName>,
105 /// Where the caller holds it.
106 held_on: Vec<plexus_auth_core::grants::ScopeRef>,
107 },
108}
109
110#[derive(Debug, Clone, Serialize, Deserialize)]
111#[serde(tag = "error_kind", rename_all = "snake_case")]
112pub enum TransportErrorKind {
113 ConnectionRefused { host: String, port: u16 },
114 ConnectionTimeout { host: String, port: u16 },
115 ProtocolError { message: String },
116 NetworkError { message: String },
117}
118
119impl std::fmt::Display for TransportErrorKind {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 match self {
122 TransportErrorKind::ConnectionRefused { host, port } => {
123 write!(f, "Connection refused to {}:{}", host, port)
124 }
125 TransportErrorKind::ConnectionTimeout { host, port } => {
126 write!(f, "Connection timeout to {}:{}", host, port)
127 }
128 TransportErrorKind::ProtocolError { message } => {
129 write!(f, "Protocol error: {}", message)
130 }
131 TransportErrorKind::NetworkError { message } => {
132 write!(f, "Network error: {}", message)
133 }
134 }
135 }
136}
137
138impl std::fmt::Display for PlexusError {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 match self {
141 PlexusError::ActivationNotFound(name) => write!(f, "Activation not found: {}", name),
142 PlexusError::MethodNotFound { activation, method } => {
143 write!(f, "Method not found: {}.{}", activation, method)
144 }
145 // MACRO-15's lines: the parameter's wire name first, so the
146 // message names it (spec/05) — `Invalid params: id: <serde's
147 // message>`, `Invalid params: missing field: id`.
148 PlexusError::InvalidParams { param, problem } => match (param, problem) {
149 (Some(p), ParamProblem::Missing) => {
150 write!(f, "Invalid params: missing field: {}", p)
151 }
152 (None, ParamProblem::Missing) => {
153 write!(f, "Invalid params: a required parameter is missing")
154 }
155 (Some(p), ParamProblem::Malformed { detail }) => {
156 write!(f, "Invalid params: {}: {}", p, detail)
157 }
158 (None, ParamProblem::Malformed { detail }) => {
159 write!(f, "Invalid params: {}", detail)
160 }
161 },
162 PlexusError::ExecutionError(msg) => write!(f, "Execution error: {}", msg),
163 PlexusError::HandleNotSupported(activation) => {
164 write!(f, "Handle resolution not supported by activation: {}", activation)
165 }
166 PlexusError::TransportError(kind) => match kind {
167 TransportErrorKind::ConnectionRefused { host, port } => {
168 write!(f, "Connection refused to {}:{}", host, port)
169 }
170 TransportErrorKind::ConnectionTimeout { host, port } => {
171 write!(f, "Connection timeout to {}:{}", host, port)
172 }
173 TransportErrorKind::ProtocolError { message } => {
174 write!(f, "Protocol error: {}", message)
175 }
176 TransportErrorKind::NetworkError { message } => {
177 write!(f, "Network error: {}", message)
178 }
179 }
180 PlexusError::Unauthenticated(msg) => write!(f, "Authentication required: {}", msg),
181 PlexusError::Forbidden { reason } => match reason {
182 // Names ONLY the unmet scope — never the registry's
183 // taxonomy or the method's full requirement set
184 // (no-enumeration posture, AUTHZ-CORE-1/5).
185 AuthzDenyReason::MissingScope { scope } => {
186 write!(f, "Forbidden: missing required scope '{}'", scope)
187 }
188 AuthzDenyReason::TenantBoundary => write!(f, "Forbidden: tenant boundary"),
189 AuthzDenyReason::NotAccepted => write!(f, "Forbidden: call not accepted"),
190 // AUTH-2: the wire's `message` for a refusal.
191 AuthzDenyReason::MissingGrant { grant, scope, .. } if scope.is_everywhere() => {
192 write!(f, "needs {}", grant)
193 }
194 AuthzDenyReason::MissingGrant { grant, scope, .. } => {
195 write!(f, "needs {} on {}", grant, scope)
196 }
197 },
198 }
199 }
200}
201
202impl std::error::Error for PlexusError {}
203
204impl PlexusError {
205 /// `InvalidParams` naming no one parameter: `detail` says what is wrong
206 /// (`Invalid params: <detail>`).
207 pub fn invalid_params(detail: impl Into<String>) -> Self {
208 PlexusError::InvalidParams { param: None, problem: ParamProblem::Malformed { detail: detail.into() } }
209 }
210
211 /// `InvalidParams` naming the parameter at fault
212 /// (`Invalid params: <param>: <detail>`).
213 pub fn malformed_param(param: impl Into<String>, detail: impl Into<String>) -> Self {
214 PlexusError::InvalidParams {
215 param: Some(param.into()),
216 problem: ParamProblem::Malformed { detail: detail.into() },
217 }
218 }
219}
220
221/// RETURNS-6: the server's failure, as the wire carries it.
222///
223/// | `PlexusError` | `RemoteError` |
224/// |---|---|
225/// | `ActivationNotFound(name)` | `ActivationNotFound { activation: name }` |
226/// | `MethodNotFound { activation, method }` | same |
227/// | `InvalidParams { param, problem }` | same |
228/// | `ExecutionError(msg)` | `Execution { message: msg }` |
229/// | `HandleNotSupported(ns)` | `HandleNotSupported { activation: ns }` |
230/// | `TransportError(kind)` — a service forwarding upstream failed | `Execution { message: kind.to_string() }` |
231/// | `Unauthenticated(_)` | `Unauthenticated` — the server-side reason stays server-side |
232/// | `Forbidden { reason }` | `Forbidden { reason: DenyReason }` |
233///
234/// `Forbidden` renders at most the single fact the caller already failed
235/// (AUTHZ-CORE-1/5): `MissingScope` names the one unmet scope — the fact
236/// the 0.6 wire already carried in its `Display` line — and
237/// `TenantBoundary` / `NotAccepted` carry nothing.
238impl From<&PlexusError> for RemoteError {
239 fn from(e: &PlexusError) -> Self {
240 match e {
241 PlexusError::ActivationNotFound(name) => RemoteError::ActivationNotFound {
242 activation: name.clone(),
243 },
244 PlexusError::MethodNotFound { activation, method } => RemoteError::MethodNotFound {
245 activation: activation.clone(),
246 method: method.clone(),
247 },
248 PlexusError::InvalidParams { param, problem } => RemoteError::InvalidParams {
249 param: param.clone(),
250 problem: problem.clone(),
251 },
252 PlexusError::ExecutionError(message) => RemoteError::Execution {
253 message: message.clone(),
254 },
255 PlexusError::HandleNotSupported(activation) => RemoteError::HandleNotSupported {
256 activation: activation.clone(),
257 },
258 PlexusError::TransportError(kind) => RemoteError::Execution {
259 message: kind.to_string(),
260 },
261 PlexusError::Unauthenticated(_) => RemoteError::Unauthenticated,
262 PlexusError::Forbidden { reason } => RemoteError::Forbidden {
263 reason: match reason {
264 AuthzDenyReason::MissingScope { scope } => DenyReason::MissingScope {
265 scope: scope.as_str().to_string(),
266 },
267 AuthzDenyReason::TenantBoundary => DenyReason::TenantBoundary,
268 AuthzDenyReason::NotAccepted => DenyReason::NotAccepted,
269 // AUTH-2's refusal, whole: what was needed, where, the
270 // roles listing it and where the caller holds it.
271 AuthzDenyReason::MissingGrant { grant, scope, roles, held_on } => {
272 DenyReason::MissingGrant {
273 grant: grant.as_str().to_string(),
274 scope: scope.as_str().to_string(),
275 roles: roles.iter().map(|r| r.as_str().to_string()).collect(),
276 held_on: held_on.iter().map(|s| s.as_str().to_string()).collect(),
277 }
278 }
279 },
280 },
281 }
282 }
283}
284
285/// RETURNS-47: a child's call inside its own context (when the parent's call
286/// had one), its stream carrying it.
287async fn in_child<F>(ctx: Option<crate::call::CallContext>, routed: F) -> Result<PlexusStream, PlexusError>
288where
289 F: std::future::Future<Output = Result<PlexusStream, PlexusError>>,
290{
291 match ctx {
292 Some(ctx) => in_call(ctx, routed).await,
293 None => routed.await,
294 }
295}
296
297/// RETURNS-47: run a call's routing inside its context, and hand back its
298/// stream carrying that context, so the method's stream reads its caller as
299/// its first line does ([`crate::call`]).
300async fn in_call<F>(ctx: crate::call::CallContext, routed: F) -> Result<PlexusStream, PlexusError>
301where
302 F: std::future::Future<Output = Result<PlexusStream, PlexusError>>,
303{
304 let stream = crate::call::scope(ctx.clone(), routed).await?;
305 Ok(Box::pin(crate::call::InCall::new(ctx, stream)))
306}
307
308/// Get the semantic JSON-RPC error code for a PlexusError.
309///
310/// Codes:
311/// - `-32001`: Authentication required (custom app-level error)
312/// - `-32003`: Forbidden — authenticated but not authorized (custom app-level error)
313/// - `-32601`: Method/activation not found (standard JSON-RPC)
314/// - `-32602`: Invalid parameters (standard JSON-RPC)
315/// - `-32000`: Generic server error (execution, transport, handle errors)
316fn plexus_error_code(e: &PlexusError) -> i32 {
317 match e {
318 PlexusError::Unauthenticated(_) => -32001,
319 PlexusError::Forbidden { .. } => -32003,
320 PlexusError::InvalidParams { .. } => -32602,
321 PlexusError::MethodNotFound { .. } | PlexusError::ActivationNotFound(_) => -32601,
322 _ => -32000,
323 }
324}
325
326/// Convert a PlexusError to a JSON-RPC rejection.
327///
328/// JSON-RPC 2.0 requires `code` and `message`, so they stay: `code` is the
329/// semantic code above, `message` the `RemoteError`'s `Display` line. `data`
330/// always carries the typed [`RemoteError`] (RETURNS-6):
331///
332/// ```text
333/// {"code": -32601, "message": "method not found: tickets.frob",
334/// "data": {"kind": "method_not_found", "activation": "tickets", "method": "frob"}}
335/// ```
336pub fn plexus_error_to_jsonrpc(e: &PlexusError) -> jsonrpsee::types::ErrorObjectOwned {
337 let error = RemoteError::from(e);
338 jsonrpsee::types::ErrorObject::owned(plexus_error_code(e), error.to_string(), Some(error))
339}
340
341/// The error stream item a failed dispatch sends: `{"type":"error",
342/// "metadata", "message", "code", "recoverable"}`, plus — for an auth
343/// refusal — AUTH-2's typed fields (`error_kind`, and for a missing grant
344/// `grant`, `scope`, `roles`, `held_on`; see
345/// [`super::types::spec_fields`]), and RETURNS-6's typed `error` beside them.
346pub(crate) fn error_item_raw(ns: &str, e: &PlexusError) -> Option<Box<serde_json::value::RawValue>> {
347 serde_json::value::to_raw_value(&error_item(ns, e)).ok()
348}
349
350/// AUTH-2: the error stream item a failed dispatch of `ns.call` sends for
351/// `e`, as JSON — `{"type":"error","metadata","message","code",
352/// "recoverable"}` plus, for an auth refusal, `error_kind` and (a missing
353/// grant) `grant`, `scope`, `roles`, `held_on`. Public so a transport that
354/// renders dispatch errors itself renders them the same way.
355pub fn error_item(ns: &str, e: &PlexusError) -> serde_json::Value {
356 // POLYGLOT-5: the typed refusal's fields ride in the item itself, and
357 // RETURNS-6's typed `error` beside them.
358 let item = super::types::PlexusStreamItem::from_plexus_error(
359 super::types::StreamMetadata::new(vec![ns.into()], super::context::PlexusContext::hash()),
360 e,
361 false,
362 );
363 serde_json::to_value(&item).unwrap_or(serde_json::Value::Null)
364}
365
366// ============================================================================
367// Schema Types
368// ============================================================================
369
370#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
371pub struct ActivationInfo {
372 pub namespace: String,
373 pub version: String,
374 pub description: String,
375 pub methods: Vec<String>,
376}
377
378// ============================================================================
379// Activation Trait
380// ============================================================================
381
382#[async_trait]
383pub trait Activation: Send + Sync + 'static {
384 type Methods: MethodEnumSchema;
385
386 fn namespace(&self) -> &str;
387 fn version(&self) -> &str;
388 /// Short description (max 15 words)
389 fn description(&self) -> &str { "No description available" }
390 /// Long description (optional, for detailed documentation)
391 fn long_description(&self) -> Option<&str> { None }
392 fn methods(&self) -> Vec<&str>;
393 fn method_help(&self, _method: &str) -> Option<String> { None }
394 /// Stable activation instance ID for handle routing
395 /// By default generates a deterministic UUID from namespace+major_version
396 /// Using major version only ensures handles survive minor/patch upgrades (semver)
397 fn plugin_id(&self) -> uuid::Uuid {
398 let major_version = self.version().split('.').next().unwrap_or("0");
399 uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, format!("{}@{}", self.namespace(), major_version).as_bytes())
400 }
401
402 async fn call(
403 &self,
404 method: &str,
405 params: Value,
406 auth: Option<&super::auth::AuthContext>,
407 raw_ctx: Option<&crate::request::RawRequestContext>,
408 ) -> Result<PlexusStream, PlexusError>;
409 async fn resolve_handle(&self, _handle: &Handle) -> Result<PlexusStream, PlexusError> {
410 Err(PlexusError::HandleNotSupported(self.namespace().to_string()))
411 }
412
413 fn into_rpc_methods(self) -> Methods where Self: Sized;
414
415 /// MACRO-20: this activation's static children and theirs, as
416 /// `(path, schema)` — the same list as
417 /// [`ChildRouter::router_static_child_schemas`], reachable from the
418 /// hub's type-erased registry (which holds `Activation`s).
419 ///
420 /// Default empty; `#[plexus_macros::activation]` emits it for an
421 /// activation with static `#[plexus_macros::child]`ren. A
422 /// [`DynamicHub`] indexes each child's methods for its gate
423 /// (`<activation>.<path>.<method>`, the child's own `target`), merges the
424 /// children's `roles(...)` into [`DynamicHub::declared_roles`], and lists
425 /// them in `auth.requires` and the caller's view — every grant qualified
426 /// by the path (see [`super::children`]).
427 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
428 Vec::new()
429 }
430
431 /// NEST-5: this activation's schema without an instance — what a
432 /// parent's dynamic `#[child]` publishes as its slot's type
433 /// (`MethodRole::DynamicChild { child }`). `None` (the default) for an
434 /// activation the macro did not write; `#[plexus_macros::activation]`
435 /// emits it (its static namespace, version, description, methods and
436 /// roles).
437 fn slot_schema() -> Option<PluginSchema>
438 where
439 Self: Sized,
440 {
441 None
442 }
443
444 /// Return this activation's schema (methods + optional children)
445 fn plugin_schema(&self) -> PluginSchema {
446 // A method of an activation not built with `#[activation]` is known
447 // by its name and help text alone; its hash is that schema's content
448 // hash (RETURNS-10), as a macro-built method's is of its whole schema.
449 let methods: Vec<MethodSchema> = self.methods().iter().map(|name| {
450 let desc = self.method_help(name).unwrap_or_default();
451 MethodSchema::new(name.to_string(), desc, String::new()).with_content_hash()
452 }).collect();
453
454 if let Some(long_desc) = self.long_description() {
455 PluginSchema::leaf_with_long_description(
456 self.namespace(),
457 self.version(),
458 self.description(),
459 long_desc,
460 methods,
461 )
462 } else {
463 PluginSchema::leaf(
464 self.namespace(),
465 self.version(),
466 self.description(),
467 methods,
468 )
469 }
470 }
471}
472
473// ============================================================================
474// Child Routing for Hub Plugins
475// ============================================================================
476
477bitflags! {
478 /// Opt-in capability flags advertising which optional `ChildRouter`
479 /// operations a router supports.
480 ///
481 /// The Plexus RPC network is a *graph*, not a tree: children may be
482 /// remote, infinite, or deliberately private. Listing and searching
483 /// children are therefore opt-in — routers must declare them here
484 /// before callers can rely on them.
485 ///
486 /// # Contract
487 ///
488 /// | Condition | Expected |
489 /// |---|---|
490 /// | `capabilities().contains(LIST)` is `true` | `list_children().await` returns `Some(stream)` |
491 /// | `capabilities().contains(LIST)` is `false` | `list_children().await` returns `None` |
492 /// | `capabilities().contains(SEARCH)` is `true` | `search_children(q).await` returns `Some(stream)` for every `q` |
493 /// | `capabilities().contains(SEARCH)` is `false` | `search_children(q).await` returns `None` for every `q` |
494 ///
495 /// These rules are not runtime-enforced; advertising a capability you
496 /// do not implement is a correctness bug in the router.
497 ///
498 /// # Deprecated (IR-4)
499 ///
500 /// This bitflags type is superseded by the `MethodRole::DynamicChild {
501 /// list_method, search_method }` tag on the corresponding gate method.
502 /// Consumers that want to know whether a child router supports list /
503 /// search operations should inspect the gate method's role instead of
504 /// calling `ChildRouter::capabilities()`. The type stays on the wire for
505 /// the 0.5 transition window and is slated for removal in 0.7.
506 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
507 #[deprecated(
508 since = "0.5",
509 note = "Use MethodRole::DynamicChild { list_method, search_method } instead. Removed in 0.7."
510 )]
511 pub struct ChildCapabilities: u32 {
512 /// The router promises `list_children()` returns `Some(stream)`.
513 const LIST = 0b0000_0001;
514 /// The router promises `search_children(query)` returns
515 /// `Some(stream)` for any query.
516 const SEARCH = 0b0000_0010;
517 }
518}
519
520/// Trait for activations that can route to child activations
521///
522/// Hub activations implement this to support nested method routing.
523/// When a method like "mercury.info" is called on a solar activation,
524/// this trait enables routing to the mercury child.
525///
526/// This trait is separate from Activation to avoid associated type issues
527/// with dynamic dispatch.
528///
529/// # Optional capabilities
530///
531/// In addition to the required `router_namespace` + `get_child` surface,
532/// routers may opt in to advertising enumerable and searchable children
533/// via [`ChildCapabilities`]. When a flag is set, the corresponding
534/// `list_children` / `search_children` method must return `Some(stream)`.
535/// The default implementations report no capabilities and return `None`.
536#[async_trait]
537pub trait ChildRouter: Send + Sync {
538 /// Get the namespace of this router (for error messages)
539 fn router_namespace(&self) -> &str;
540
541 /// Call a method on this router
542 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
543
544 /// Get a child activation instance by name for nested routing
545 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>>;
546
547 /// NEST-7: the child or peer named `name`, or why a peer could not be
548 /// returned — what routing asks, so a caller gets a typed error item
549 /// (`not_grafted`, `unavailable`, `shape_mismatch`, …), never "not
550 /// found", for a peer that failed. Default: [`Self::get_child`], which
551 /// cannot fail. `#[plexus_macros::activation]` overrides it for an
552 /// activation with a `#[plexus_macros::peer]` slot.
553 async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, super::peer::PeerError> {
554 Ok(self.get_child(name).await)
555 }
556
557 /// Which optional operations (list / search) this router supports.
558 ///
559 /// Defaults to [`ChildCapabilities::empty()`]: a router that only
560 /// exposes `get_child` for exact-name lookup.
561 #[allow(deprecated)]
562 fn capabilities(&self) -> ChildCapabilities {
563 ChildCapabilities::empty()
564 }
565
566 /// Stream every child name the router is willing to enumerate.
567 ///
568 /// Returns `None` when the router does not support listing — callers
569 /// should check [`ChildRouter::capabilities`] first.
570 ///
571 /// Routers that implement this **must** set
572 /// [`ChildCapabilities::LIST`] in [`ChildRouter::capabilities`].
573 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
574 None
575 }
576
577 /// Stream child names matching the router-defined query semantics.
578 ///
579 /// Returns `None` when the router does not support searching — callers
580 /// should check [`ChildRouter::capabilities`] first.
581 ///
582 /// Routers that implement this **must** set
583 /// [`ChildCapabilities::SEARCH`] in [`ChildRouter::capabilities`].
584 async fn search_children(&self, _query: &str) -> Option<BoxStream<'_, String>> {
585 None
586 }
587
588 // AUTHLANG-3 — three default-implemented methods that the framework's
589 // dispatch path (`route_to_child` below) consults. Existing impls keep
590 // compiling unchanged: they inherit the defaults below. Hub-level impls
591 // (DynamicHub) override them to consult the registry/principal/sink the
592 // hub holds.
593
594 /// Look up the forward policy declared for a callee namespace.
595 ///
596 /// Default: returns `None`, which the framework interprets as
597 /// [`plexus_auth_core::IdentityOnly`] — the safe default per
598 /// `AUTHLANG-S01-output` §5. Macro-emitted impls (AUTHLANG-4) override
599 /// this from the `#[plexus::activation(forward_policy = ...)]`
600 /// attribute; the [`DynamicHub`] override consults its
601 /// [`ForwardPolicyRegistry`](super::forward_registry::ForwardPolicyRegistry).
602 fn forward_policy_for(
603 &self,
604 _callee_ns: &str,
605 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
606 None
607 }
608
609 /// MACRO-20: this router's own schema, when it has one.
610 ///
611 /// Default `None` (a hand-written router describes nothing). The
612 /// `ChildRouter` impl `#[plexus_macros::activation]` emits answers its
613 /// activation's [`Activation::plugin_schema`], which is how a parent
614 /// describes its static children ([`Self::router_static_child_schemas`]).
615 fn router_schema(&self) -> Option<PluginSchema> {
616 None
617 }
618
619 /// MACRO-20: every static child below this router that describes itself,
620 /// as `(path, schema)` — `path` relative to this router, dotted for a
621 /// grandchild (`"commits"`, `"commits.audit"`), `schema` the child's own
622 /// (its methods' grants and its `roles` relative to it, as its macro
623 /// wrote them).
624 ///
625 /// Default empty. `#[plexus_macros::activation]` emits it for an
626 /// activation with static `#[plexus_macros::child]`ren: each child's
627 /// [`Self::router_schema`], then its own static children under its name.
628 /// A dynamic child (an open name set) is never listed. The hub reads it
629 /// through [`Activation::static_child_schemas`] to gate a child's method
630 /// by its whole path ([`super::children`]).
631 fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
632 Vec::new()
633 }
634
635 /// Framework-stamped immediate-caller [`plexus_auth_core::Principal`] of
636 /// this router.
637 ///
638 /// Default: [`plexus_auth_core::Principal::Anonymous`]. The dispatch
639 /// path passes this into the [`plexus_auth_core::CallSite`] handed to
640 /// the policy so policies can implement callee-and-caller-aware
641 /// decisions (e.g., "PassThrough only when callee is in `audit.*`").
642 /// Hub-level impls override to return the per-connection stamp.
643 fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
644 plexus_auth_core::Principal::Anonymous
645 }
646}
647
648/// Route a method call to a child activation
649///
650/// This is called from generated code when a hub activation receives
651/// a method that doesn't match its local methods. If the method
652/// contains a dot (e.g., "mercury.info"), it routes to the child.
653///
654/// # AUTHLANG-3 dispatch sequence
655///
656/// Between callee resolution (`get_child`) and the actual dispatch
657/// (`router_call`), the framework runs the forwarding-policy step pinned
658/// in `plans/AUTHLANG/AUTHLANG-S01-output.md` §3:
659///
660/// 1. Resolve the policy registered for the callee namespace via
661/// [`ChildRouter::forward_policy_for`]; default
662/// [`plexus_auth_core::IdentityOnly`] when none is declared.
663/// 2. Build a [`plexus_auth_core::CallSite`] from the parent router's
664/// framework-stamped principal and the callee's [`MethodPath`].
665/// 3. Invoke [`plexus_auth_core::ForwardPolicy::forward`] to obtain a
666/// [`plexus_auth_core::ForwardDerivation`].
667/// 4. *(deferred — PRIVACY-1)* Emit one `AuditRecord` with
668/// `kind: ForwardPolicyApplied` to the configured `AuditSink`.
669/// 5. Mint the callee `AuthContext` via the framework-only constructor
670/// [`plexus_auth_core::AuthContext::derive_callee_context`].
671/// 6. Dispatch to `child.router_call(...)` with the derived context.
672///
673/// The policy step is invisible to activation authors per AUTHZ-0
674/// principle 1 ("trust is structural, not procedural"). The
675/// [`plexus_auth_core::ForwardPolicy::forward`] surface returns
676/// *parameters*, never a constructed `AuthContext`; the framework is the
677/// only entity that can mint one, per the sealed-type pattern.
678pub async fn route_to_child<T: ChildRouter + ?Sized>(
679 parent: &T,
680 method: &str,
681 params: Value,
682 auth: Option<&super::auth::AuthContext>,
683 raw_ctx: Option<&crate::request::RawRequestContext>,
684) -> Result<PlexusStream, PlexusError> {
685 // Try to split on first dot for nested routing
686 if let Some((child_name, rest)) = method.split_once('.') {
687 // NEST-7: a peer that could not be returned is its typed error item.
688 let found = match parent.peer_child(child_name).await {
689 Ok(found) => found,
690 Err(e) => {
691 return Ok(e.stream(vec![parent.router_namespace().to_string(), child_name.to_string()]));
692 }
693 };
694 if let Some(child) = found {
695 // ── AUTHLANG-3: forwarding-policy dispatch sequence ───────────
696 // Steps 1–3, 5–6 per the pinned spike §3. Step 4 (audit
697 // emission) is deferred until PRIVACY-1 lands `AuditRecord` /
698 // `AuditSink` / `ForwardPolicyApplied`; the TODO below marks
699 // the exact insertion point. See run-notes on the ticket.
700
701 // Step 1: resolve the policy registered for the callee
702 // namespace; default to IdentityOnly per the spike-pinned safe
703 // default (AUTHLANG-S01-output §5).
704 let policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy> = parent
705 .forward_policy_for(child_name)
706 .unwrap_or_else(|| {
707 std::sync::Arc::new(plexus_auth_core::IdentityOnly)
708 as std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>
709 });
710
711 // Step 2: build the CallSite. The framework-built path string
712 // is always a valid MethodPath because the caller already
713 // validated the inbound method on its way in; if validation
714 // ever fails here it indicates a framework bug, not a user
715 // input error.
716 let callee_method_str = format!("{}.{}", child_name, rest);
717 let callee_method = plexus_auth_core::MethodPath::try_new(callee_method_str.as_str())
718 .map_err(|e| PlexusError::ExecutionError(format!(
719 "framework-built MethodPath rejected: {} ({:?})",
720 callee_method_str, e
721 )))?;
722 let site = plexus_auth_core::CallSite::new(
723 parent.framework_stamped_principal(),
724 callee_method,
725 );
726
727 // Step 3: invoke the policy. When the caller has no
728 // AuthContext (anonymous edge), feed the policy the anonymous
729 // sealed context so the policy contract is honored uniformly.
730 let anonymous_owned;
731 let caller_ctx: &super::auth::AuthContext = match auth {
732 Some(ctx) => ctx,
733 None => {
734 anonymous_owned = super::auth::AuthContext::anonymous();
735 &anonymous_owned
736 }
737 };
738 let derivation = policy.forward(caller_ctx, &site);
739
740 // Step 4 (DEFERRED — PRIVACY-1): emit AuditRecord with
741 // kind: ForwardPolicyApplied before dispatch. When PRIVACY-1
742 // lands `AuditRecord`, `AuditSink`, and `ForwardPolicyApplied`
743 // in `plexus_auth_core`, add a `ChildRouter::audit_sink()`
744 // default method (returning a no-op sink) and call:
745 //
746 // parent.audit_sink().write(
747 // AuditRecord::for_forward(
748 // &site.callee_method,
749 // &site.caller,
750 // policy.name(),
751 // derivation,
752 // auth.and_then(|c| c.verified_user_id()),
753 // )
754 // ).await;
755 //
756 // Sink failure must be logged at WARN and NOT propagated
757 // (acceptance-criteria row 4 in AUTHLANG-3 §"Required
758 // behavior"). Until then, log a structured trace event so
759 // operators can confirm the policy step ran:
760 tracing::trace!(
761 target: "plexus::audit",
762 policy = policy.name().as_str(),
763 callee_method = %site.callee_method.as_str(),
764 derivation_keep_verified_user = derivation.keep_verified_user,
765 derivation_keep_roles = derivation.keep_roles,
766 derivation_keep_capabilities = derivation.keep_capabilities,
767 derivation_keep_metadata = derivation.keep_metadata,
768 "forward_policy_applied (audit-record emission stubbed pending PRIVACY-1)"
769 );
770
771 // Step 5+6: framework-blessed derivation of the callee sealed
772 // AuthContext, and dispatch with it. The policy NEVER sees the
773 // constructed value — it returned *parameters*; the framework
774 // consumed them via `with_callee_context`, which scopes the
775 // callee to the dispatch closure (the raw constructor remains
776 // pub(crate) to plexus-auth-core).
777 // RETURNS-47 (owner, 2026-11-04: children receive auth): the
778 // child's call runs in a context of its own, as the policy
779 // derived it — its caller the derived context, its reach the
780 // call's when the policy keeps the caller's identity, nowhere
781 // when not — so `caller()`, `current_reach()` and `required` in a
782 // child answer as the policy says, not as the outer call does.
783 let outer = crate::call::context().ok();
784 let keeps_identity = derivation.keep_verified_user;
785 return match auth {
786 Some(caller_ctx) => {
787 caller_ctx
788 .with_callee_context(&derivation, &site.caller, |callee_ctx| async move {
789 let ctx = outer.map(|o| o.for_child(Some(&callee_ctx), keeps_identity));
790 in_child(ctx, child.router_call(rest, params, Some(&callee_ctx), raw_ctx)).await
791 })
792 .await
793 }
794 None => {
795 let ctx = outer.map(|o| o.for_child(None, keeps_identity));
796 in_child(ctx, child.router_call(rest, params, None, raw_ctx)).await
797 }
798 };
799 }
800 return Err(PlexusError::ActivationNotFound(child_name.to_string()));
801 }
802
803 // No dot - method simply not found
804 Err(PlexusError::MethodNotFound {
805 activation: parent.router_namespace().to_string(),
806 method: method.to_string(),
807 })
808}
809
810/// Wrapper to implement ChildRouter for Arc<dyn ChildRouter>
811///
812/// This allows DynamicHub to return its stored Arc<dyn ChildRouter> from get_child()
813struct ArcChildRouter(Arc<dyn ChildRouter>);
814
815#[async_trait]
816impl ChildRouter for ArcChildRouter {
817 fn router_namespace(&self) -> &str {
818 self.0.router_namespace()
819 }
820
821 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
822 self.0.router_call(method, params, auth, raw_ctx).await
823 }
824
825 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
826 self.0.get_child(name).await
827 }
828
829 async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, super::peer::PeerError> {
830 self.0.peer_child(name).await
831 }
832
833 #[allow(deprecated)]
834 fn capabilities(&self) -> ChildCapabilities {
835 self.0.capabilities()
836 }
837
838 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
839 self.0.list_children().await
840 }
841
842 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
843 self.0.search_children(query).await
844 }
845
846 // AUTHLANG-3 — forward the new ChildRouter trait methods through the
847 // Arc wrapper so a `DynamicHub` reached via `get_child` keeps its
848 // overrides (especially `forward_policy_for`).
849 fn forward_policy_for(
850 &self,
851 callee_ns: &str,
852 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
853 self.0.forward_policy_for(callee_ns)
854 }
855
856 fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
857 self.0.framework_stamped_principal()
858 }
859
860 fn router_schema(&self) -> Option<PluginSchema> {
861 self.0.router_schema()
862 }
863
864 fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
865 self.0.router_static_child_schemas()
866 }
867}
868
869// ============================================================================
870// Internal Type-Erased Activation
871// ============================================================================
872
873#[async_trait]
874#[allow(dead_code)] // Methods exist for completeness but some aren't called post-erasure yet
875trait ActivationObject: Send + Sync + 'static {
876 fn namespace(&self) -> &str;
877 fn version(&self) -> &str;
878 fn description(&self) -> &str;
879 fn long_description(&self) -> Option<&str>;
880 fn methods(&self) -> Vec<&str>;
881 fn method_help(&self, method: &str) -> Option<String>;
882 fn plugin_id(&self) -> uuid::Uuid;
883 async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
884 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError>;
885 fn plugin_schema(&self) -> PluginSchema;
886 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)>;
887 fn schema(&self) -> Schema;
888}
889
890struct ActivationWrapper<A: Activation> {
891 inner: A,
892}
893
894#[async_trait]
895impl<A: Activation> ActivationObject for ActivationWrapper<A> {
896 fn namespace(&self) -> &str { self.inner.namespace() }
897 fn version(&self) -> &str { self.inner.version() }
898 fn description(&self) -> &str { self.inner.description() }
899 fn long_description(&self) -> Option<&str> { self.inner.long_description() }
900 fn methods(&self) -> Vec<&str> { self.inner.methods() }
901 fn method_help(&self, method: &str) -> Option<String> { self.inner.method_help(method) }
902 fn plugin_id(&self) -> uuid::Uuid { self.inner.plugin_id() }
903
904 async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
905 self.inner.call(method, params, auth, raw_ctx).await
906 }
907
908 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
909 self.inner.resolve_handle(handle).await
910 }
911
912 fn plugin_schema(&self) -> PluginSchema { self.inner.plugin_schema() }
913
914 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> { self.inner.static_child_schemas() }
915
916 fn schema(&self) -> Schema {
917 let schema = schemars::schema_for!(A::Methods);
918 serde_json::from_value(serde_json::to_value(schema).expect("serialize"))
919 .expect("parse schema")
920 }
921}
922
923// ============================================================================
924// Plexus Event Types
925// ============================================================================
926
927#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
928#[serde(tag = "event", rename_all = "snake_case")]
929pub enum HashEvent {
930 Hash { value: String },
931}
932
933/// Event for schema() RPC method - returns plugin schema
934#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
935#[serde(tag = "event", rename_all = "snake_case")]
936pub enum SchemaEvent {
937 /// This plugin's schema
938 Schema(PluginSchema),
939}
940
941/// Lightweight hash information for cache validation
942#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
943pub struct PluginHashes {
944 pub namespace: String,
945 pub self_hash: String,
946 #[serde(skip_serializing_if = "Option::is_none")]
947 pub children_hash: Option<String>,
948 pub hash: String,
949 /// Child plugin hashes (for recursive checking)
950 #[serde(skip_serializing_if = "Option::is_none")]
951 pub children: Option<Vec<ChildHashes>>,
952}
953
954/// Hash information for a child plugin
955#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
956pub struct ChildHashes {
957 pub namespace: String,
958 pub hash: String,
959}
960
961
962// ============================================================================
963// Activation Registry
964// ============================================================================
965
966/// Entry in the activation registry
967#[derive(Debug, Clone)]
968pub struct PluginEntry {
969 /// Stable activation instance ID
970 pub id: uuid::Uuid,
971 /// Current path/namespace for this activation
972 pub path: String,
973 /// Activation type (e.g., "cone", "bash", "arbor")
974 pub plugin_type: String,
975}
976
977/// Registry mapping activation UUIDs to their current paths
978///
979/// This enables handle routing without path dependency - handles reference
980/// activations by their stable UUID, and the registry maps to the current path.
981#[derive(Default)]
982pub struct PluginRegistry {
983 /// Lookup by plugin UUID
984 by_id: HashMap<uuid::Uuid, PluginEntry>,
985 /// Lookup by current path (for reverse lookup)
986 by_path: HashMap<String, uuid::Uuid>,
987}
988
989/// Read-only snapshot of the activation registry
990///
991/// Safe to use outside of DynamicHub locks.
992#[derive(Clone)]
993pub struct PluginRegistrySnapshot {
994 by_id: HashMap<uuid::Uuid, PluginEntry>,
995 by_path: HashMap<String, uuid::Uuid>,
996}
997
998impl PluginRegistrySnapshot {
999 /// Look up an activation's path by its UUID
1000 pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
1001 self.by_id.get(&id).map(|e| e.path.as_str())
1002 }
1003
1004 /// Look up an activation's UUID by its path
1005 pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
1006 self.by_path.get(path).copied()
1007 }
1008
1009 /// Get an activation entry by its UUID
1010 pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
1011 self.by_id.get(&id)
1012 }
1013
1014 /// List all registered activations
1015 pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
1016 self.by_id.values()
1017 }
1018
1019 /// Get the number of registered plugins
1020 pub fn len(&self) -> usize {
1021 self.by_id.len()
1022 }
1023
1024 /// Check if the registry is empty
1025 pub fn is_empty(&self) -> bool {
1026 self.by_id.is_empty()
1027 }
1028}
1029
1030impl PluginRegistry {
1031 /// Create a new empty registry
1032 pub fn new() -> Self {
1033 Self::default()
1034 }
1035
1036 /// Look up an activation's path by its UUID
1037 pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
1038 self.by_id.get(&id).map(|e| e.path.as_str())
1039 }
1040
1041 /// Look up an activation's UUID by its path
1042 pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
1043 self.by_path.get(path).copied()
1044 }
1045
1046 /// Get an activation entry by its UUID
1047 pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
1048 self.by_id.get(&id)
1049 }
1050
1051 /// Register an activation
1052 pub fn register(&mut self, id: uuid::Uuid, path: String, plugin_type: String) {
1053 let entry = PluginEntry { id, path: path.clone(), plugin_type };
1054 self.by_id.insert(id, entry);
1055 self.by_path.insert(path, id);
1056 }
1057
1058 /// List all registered activations
1059 pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
1060 self.by_id.values()
1061 }
1062
1063 /// Get the number of registered plugins
1064 pub fn len(&self) -> usize {
1065 self.by_id.len()
1066 }
1067
1068 /// Check if the registry is empty
1069 pub fn is_empty(&self) -> bool {
1070 self.by_id.is_empty()
1071 }
1072}
1073
1074// ============================================================================
1075// DynamicHub (formerly Plexus)
1076// ============================================================================
1077
1078/// Build the JSON payload for the `_info` well-known endpoint.
1079///
1080/// The shape is `{"backend": "<ns>", "auth_capabilities": {…}}` per
1081/// AUTHZ-S01-output §2 / AUTHZ-CORE-3. When the backend has not declared its
1082/// capabilities via [`DynamicHub::with_auth_capabilities`], the field falls
1083/// back to [`plexus_auth_core::BackendAuthCapabilities::anonymous_default`]
1084/// (a single `Anonymous` mechanism). The `_info` endpoint itself remains
1085/// public — no authentication is required to read it.
1086fn build_info_payload(
1087 namespace: &str,
1088 caps: Option<&plexus_auth_core::BackendAuthCapabilities>,
1089) -> serde_json::Value {
1090 let advertised = match caps {
1091 Some(c) => c.clone(),
1092 None => plexus_auth_core::BackendAuthCapabilities::anonymous_default(),
1093 };
1094 serde_json::json!({
1095 "backend": namespace,
1096 "auth_capabilities": advertised,
1097 })
1098}
1099
1100/// CA-1 (trak facet `ccc924ad-0e78-4d4b-b71f-0018d249d0bf`): map a schema
1101/// response stream so every `requires_credential` lacking a `site_hint`
1102/// gets the hub-derived attach site.
1103///
1104/// Only `Data` items whose `content_type` is a schema payload
1105/// (`*.schema` / `*.method_schema`) are touched; their `content` is decoded
1106/// as a [`super::SchemaResult`], hint-filled, and re-encoded. Items that do
1107/// not decode (defensive: a custom activation emitting a non-standard
1108/// payload under a schema content type) pass through unchanged, as do all
1109/// non-`Data` items.
1110fn fill_site_hints_in_schema_stream(
1111 stream: PlexusStream,
1112 site: plexus_auth_core::AttachmentSite,
1113) -> PlexusStream {
1114 use futures::StreamExt;
1115 Box::pin(stream.map(move |item| match item {
1116 super::types::PlexusStreamItem::Data {
1117 metadata,
1118 content_type,
1119 content,
1120 } if content_type.ends_with(".schema") || content_type.ends_with(".method_schema") => {
1121 // PERF-7: an encoded content is decoded straight from its bytes.
1122 let content = match content.decode::<super::SchemaResult>() {
1123 Ok(mut result) => {
1124 result.fill_site_hints(&site);
1125 match serde_json::to_value(&result) {
1126 Ok(v) => v.into(),
1127 Err(_) => content,
1128 }
1129 }
1130 Err(_) => content,
1131 };
1132 super::types::PlexusStreamItem::Data {
1133 metadata,
1134 content_type,
1135 content,
1136 }
1137 }
1138 other => other,
1139 }))
1140}
1141
1142pub(crate) struct DynamicHubInner {
1143 /// Custom namespace for this hub instance (defaults to "plexus")
1144 namespace: String,
1145 /// The registered activations, by namespace. PERF-21: ordered, so every
1146 /// list of them — the service schema's `children`
1147 /// ([`DynamicHub::plugin_children`]), what the self-description cache
1148 /// keeps, the static children, the declared roles — is in namespace
1149 /// order: a function of what the service serves, the same at every
1150 /// start. A `HashMap` listed them in the process's own order, and every
1151 /// hash over the service (its own, the `plexus_hash` its items carry,
1152 /// each caller's view hash) moved with it.
1153 activations: BTreeMap<String, Arc<dyn ActivationObject>>,
1154 /// Child routers for direct nested routing (e.g.
1155 /// `service.solar.mercury.info`), by namespace as `activations` are.
1156 child_routers: BTreeMap<String, Arc<dyn ChildRouter>>,
1157 /// Activation registry mapping UUIDs to paths
1158 registry: std::sync::RwLock<PluginRegistry>,
1159 pending_rpc: std::sync::Mutex<Vec<Box<dyn FnOnce() -> Methods + Send>>>,
1160 /// What this backend advertises at `_info`'s `auth_capabilities` field.
1161 ///
1162 /// `None` means the backend has not called
1163 /// [`DynamicHub::with_auth_capabilities`]; `_info` falls back to
1164 /// [`plexus_auth_core::BackendAuthCapabilities::anonymous_default`]
1165 /// (a single `Anonymous` mechanism, no default). This preserves today's
1166 /// no-auth substrate behavior while signaling "no auth wired" to
1167 /// capability-aware clients.
1168 ///
1169 /// Per AUTHZ-CORE-3 and AUTHZ-S01-output §2.
1170 auth_capabilities: Option<plexus_auth_core::BackendAuthCapabilities>,
1171 /// AUTHLANG-3 — per-hub mapping from callee namespace to the
1172 /// [`plexus_auth_core::ForwardPolicy`] consulted at every
1173 /// cross-boundary call routed through this hub. Populated declaratively
1174 /// (by the AUTHLANG-4 macro emission) or imperatively (via
1175 /// [`DynamicHub::with_forward_policy`]). When the registry has no entry
1176 /// for a callee namespace, the framework falls back to
1177 /// [`plexus_auth_core::IdentityOnly`] per the spike-pinned safe
1178 /// default. See `plans/AUTHLANG/AUTHLANG-S01-output.md` §3.
1179 forward_policies: super::forward_registry::ForwardPolicyRegistry,
1180 /// R-5 (AUTHZ-CORE-4 acceptance 8) — the deployment's role→scope
1181 /// taxonomy, consulted by the scope gate at every dispatch through
1182 /// [`DynamicHub::route_with_ctx`]. `None` means no registry is
1183 /// configured: with `default_deny` also off (the default), dispatch
1184 /// behaves byte-for-byte as before the gate existed.
1185 scope_registry: Option<Arc<plexus_auth_core::ScopeRegistry>>,
1186 /// R-5 (AUTHZ-CORE-1) — the default-deny posture. **Ships OFF.**
1187 ///
1188 /// Whether / when each backend flips this ON is an open human decision
1189 /// (R-S01 open question 4); see [`super::scope_gate`] module docs for
1190 /// the full decision table and the deviation note (runtime builder
1191 /// option here vs CORE-1's Cargo feature flag).
1192 default_deny: bool,
1193 /// Where the scope gate writes its `ScopeCheck` [`AuditRecord`]s
1194 /// (AUTHZ-CORE-5). Defaults to [`plexus_auth_core::TracingAuditSink`];
1195 /// override via [`DynamicHub::with_audit_sink`].
1196 ///
1197 /// [`AuditRecord`]: plexus_auth_core::AuditRecord
1198 audit_sink: Arc<dyn plexus_auth_core::AuditSink>,
1199 /// BIDIR-6: see [`DynamicHub::duplex_gate`].
1200 duplex_gate: std::sync::OnceLock<super::duplex_gate::DuplexGate>,
1201 /// Lazily-built index from full dotted method path
1202 /// (`<activation>.<method>`, hub-own methods under
1203 /// `<hub-ns>.<method>`) to the gate-relevant schema facts. Built once
1204 /// on the first gated dispatch so the gate never re-walks plugin
1205 /// schemas on the hot path; activations registered after the first
1206 /// gated dispatch are not in the index (registration is builder-time,
1207 /// before serving, in every supported composition).
1208 /// NEST-5: and the service's slots, so a literal path through a
1209 /// dynamic child (`solar.earth.info`) finds its slot's entry
1210 /// (`solar.{planet}.info`).
1211 gate_index: std::sync::OnceLock<GateIndex>,
1212 /// BIDIR-6: every method path the service knows, and whether it takes an
1213 /// `Input` (see [`DynamicHub::may_take_input`]). Built once, on the first
1214 /// call.
1215 input_index: std::sync::OnceLock<HashMap<String, bool>>,
1216 /// AUTH-2 — the grant gate: when set, every call is decided by it
1217 /// before routing (default deny). `None` (the default): dispatch exactly
1218 /// as before it existed. See [`super::grant_gate`].
1219 gate: Option<Arc<plexus_auth_core::grants::Gate>>,
1220 /// AUTH-4/AUTH-5: grants every signed-in caller reaches whatever its
1221 /// roles or ceiling (the auth activation's `whoami`, `logout`,
1222 /// `requires`). Empty unless [`DynamicHub::with_auth`] mounted it.
1223 signed_in_grants: std::collections::BTreeSet<String>,
1224 /// AUTH-4: the RFC 9728 metadata URL an anonymous `_info` names
1225 /// (`auth.resource_metadata`). See [`DynamicHub::with_resource_metadata`].
1226 resource_metadata: Option<String>,
1227 /// AUTH-5: what each method requires — grant, target, public — kept
1228 /// for `auth.requires`; present only when the auth activation is
1229 /// mounted, and fed by every [`DynamicHub::register`].
1230 auth_catalog: Option<super::auth_activation::Catalog>,
1231 /// PERF-15: the self-description cache — what the service's schemas
1232 /// show, and each caller's view of them — that `_info`, `hash`, `hashes`
1233 /// and every `<ns>.schema` answer from. See [`super::view`].
1234 describe: super::view::Cache,
1235 /// RETURNS-40: the `ir` answers kept, by the hash the caller sees and
1236 /// the namespaces asked. See [`DynamicHub::service_ir`].
1237 ir_cache: super::ir::IrCache,
1238 /// RETURNS-40: how many static children the registered activations
1239 /// have (and theirs), counted as each registers — the cheap bound on
1240 /// `ir`'s names, read with no schema built.
1241 nested_count: usize,
1242}
1243
1244impl DynamicHubInner {
1245 fn nested_count(&self) -> usize {
1246 self.nested_count
1247 }
1248}
1249
1250/// NEST-5: the gate's index — every method path to its gate facts, and the
1251/// service's slots, through which a literal path finds its slot's entry.
1252#[derive(Debug, Default)]
1253pub(crate) struct GateIndex {
1254 methods: HashMap<String, super::scope_gate::MethodGateInfo>,
1255 slots: super::slots::Slots,
1256}
1257
1258/// DynamicHub - an activation that routes to dynamically registered child activations
1259///
1260/// Unlike hub activations with hardcoded children (like Solar),
1261/// DynamicHub allows registering activations at runtime via `.register()`.
1262///
1263/// # Direct Hosting
1264///
1265/// For a single activation, host it directly:
1266/// ```ignore
1267/// let solar = Arc::new(Solar::new());
1268/// TransportServer::builder(solar, converter).serve().await?;
1269/// ```
1270///
1271/// # Composition
1272///
1273/// For multiple top-level activations, use DynamicHub:
1274/// ```ignore
1275/// let hub = DynamicHub::with_namespace("myapp")
1276/// .register(Solar::new())
1277/// .register(EchoActivation::new());
1278/// ```
1279#[derive(Clone)]
1280pub struct DynamicHub {
1281 inner: Arc<DynamicHubInner>,
1282}
1283
1284/// RETURNS-40: one snapshot of what a caller is shown, an IR is built from.
1285struct IrView {
1286 base: Arc<super::view::Described>,
1287 /// The caller's view under the grant gate; `None`: the whole service.
1288 shaped: Option<Arc<super::view::Shaped>>,
1289 /// The view's hash (the service's own without a gate).
1290 hash: String,
1291}
1292
1293impl IrView {
1294 fn root(&self) -> PluginSchema {
1295 match &self.shaped {
1296 Some(v) => v.service.clone(),
1297 None => self.base.service.clone(),
1298 }
1299 }
1300
1301 fn top(&self, ns: &str) -> Option<PluginSchema> {
1302 match &self.shaped {
1303 Some(v) => v.schema_of(&self.base, ns).filter(|_| ns != v.service.namespace),
1304 None => self.base.activations.iter().find(|a| a.namespace == ns).cloned(),
1305 }
1306 }
1307
1308 fn shows(&self, ns: &str) -> bool {
1309 match &self.shaped {
1310 Some(v) => v.shows(ns),
1311 None => self.base.activations.iter().any(|a| a.namespace == ns),
1312 }
1313 }
1314
1315 /// Every namespace the snapshot shows, dotted (`""`: the service's own):
1316 /// the root, each activation shown, and each static child below one —
1317 /// in a gated view, when the entry that reaches it is shown.
1318 fn names(&self, service: &str) -> Vec<String> {
1319 let mut out = vec![String::new()];
1320 out.extend(self.base.activations.iter().map(|a| a.namespace.clone()).filter(|ns| ns != service && self.shows(ns)));
1321 for path in self.base.nested() {
1322 let mut segs = path.split('.');
1323 let (Some(top), Some(entry)) = (segs.next(), segs.next()) else { continue };
1324 let reached = self.shows(top)
1325 && match &self.shaped {
1326 Some(v) => v.method_of(&self.base, top, entry).is_some(),
1327 None => true,
1328 };
1329 if reached {
1330 out.push(path.to_string());
1331 }
1332 }
1333 out
1334 }
1335}
1336
1337// ============================================================================
1338// DynamicHub Infrastructure (non-RPC methods)
1339// ============================================================================
1340
1341impl DynamicHub {
1342 /// NEST-11: the service a [`super::service_scope::WeakService`] upgrades to.
1343 pub(crate) fn from_inner(inner: Arc<DynamicHubInner>) -> Self {
1344 Self { inner }
1345 }
1346
1347 /// Create a new DynamicHub with explicit namespace
1348 ///
1349 /// Unlike single activations which have fixed namespaces, DynamicHub is a
1350 /// composition tool that can be named based on your application. Common choices:
1351 /// - "hub" - generic default
1352 /// - "substrate" - for substrate server
1353 /// - "myapp" - for your application name
1354 ///
1355 /// The namespace appears in method calls: `{namespace}.call`, `{namespace}.schema`
1356 ///
1357 /// # The root name is a routing namespace, not a label
1358 ///
1359 /// Routing resolves the hub root namespace **before** registered
1360 /// activations, so the root name must differ from the namespace of every
1361 /// activation you later [`register`](Self::register). A hub root that
1362 /// shares its name with a child (`DynamicHub::new("echo").register(Echo)`
1363 /// where `Echo`'s namespace is also `"echo"`) makes every method on that
1364 /// child unreachable: `echo.<method>` resolves to the hub root and fails
1365 /// with `Command not found`, and navigators resolve the like-named child
1366 /// back to the root schema. This is silent at construction and fatal at
1367 /// call time, so [`register`](Self::register) rejects the collision with
1368 /// a panic. Pick a distinct root name (e.g. `"echo_hub"`).
1369 ///
1370 /// Z2H-8 / HOSTLESS-3 — register-time detection of the root/activation
1371 /// namespace shadow.
1372 pub fn new(namespace: impl Into<String>) -> Self {
1373 Self {
1374 inner: Arc::new(DynamicHubInner {
1375 namespace: namespace.into(),
1376 activations: BTreeMap::new(),
1377 child_routers: BTreeMap::new(),
1378 registry: std::sync::RwLock::new(PluginRegistry::new()),
1379 pending_rpc: std::sync::Mutex::new(Vec::new()),
1380 auth_capabilities: None,
1381 forward_policies: super::forward_registry::ForwardPolicyRegistry::new(),
1382 scope_registry: None,
1383 default_deny: false,
1384 audit_sink: Arc::new(plexus_auth_core::TracingAuditSink),
1385 duplex_gate: std::sync::OnceLock::new(),
1386 gate_index: std::sync::OnceLock::new(),
1387 input_index: std::sync::OnceLock::new(),
1388 gate: None,
1389 signed_in_grants: std::collections::BTreeSet::new(),
1390 resource_metadata: None,
1391 auth_catalog: None,
1392 describe: Default::default(),
1393 ir_cache: Default::default(),
1394 nested_count: Default::default(),
1395 }),
1396 }
1397 }
1398
1399 /// The service's state while it is built — every builder's way in;
1400 /// panics with `refused` once the service is shared. PERF-15: a change
1401 /// made here may change what the service describes, so the
1402 /// self-description cache starts over.
1403 fn inner_mut(&mut self, refused: &str) -> &mut DynamicHubInner {
1404 let inner = Arc::get_mut(&mut self.inner).expect(refused);
1405 inner.describe.reset();
1406 inner
1407 }
1408
1409 /// Configure the deployment's [`ScopeRegistry`] — the scope gate's
1410 /// source of truth for role→scope expansion, public-method
1411 /// declarations, and per-method scope overlays (R-5 / AUTHZ-CORE-4
1412 /// acceptance 8).
1413 ///
1414 /// Once a registry is configured, every dispatch through this hub
1415 /// consults the gate: methods whose [`MethodSchema`] carries
1416 /// `requires_credential` scopes (or that have a registry overlay) are
1417 /// enforced; `public` methods bypass; methods with no declared
1418 /// requirement pass through unchanged unless
1419 /// [`DynamicHub::with_default_deny`] is also set.
1420 ///
1421 /// A hub that never calls this (and never sets `default_deny`)
1422 /// dispatches byte-for-byte as before the gate existed.
1423 ///
1424 /// See [`super::scope_gate`] for the full decision table.
1425 ///
1426 /// [`ScopeRegistry`]: plexus_auth_core::ScopeRegistry
1427 /// [`MethodSchema`]: super::schema::MethodSchema
1428 pub fn with_scope_registry(mut self, registry: plexus_auth_core::ScopeRegistry) -> Self {
1429 let inner = self.inner_mut("Cannot set scope_registry: DynamicHub has multiple references");
1430 inner.scope_registry = Some(Arc::new(registry));
1431 self
1432 }
1433
1434 /// Set the default-deny posture (R-5 / AUTHZ-CORE-1). **Ships OFF.**
1435 ///
1436 /// With it ON, methods with NO declared requirement are enforced
1437 /// against the implicit full-path scope
1438 /// ([`ScopeRegistry::required_scopes_for`]'s implicit rule) — fail
1439 /// closed, including when no registry is configured at all. With it
1440 /// OFF (the default), such methods behave exactly as today.
1441 ///
1442 /// **Open human decision (R-S01 Q4):** whether / when each backend
1443 /// flips this ON (inside the ROLES wave's completion gate vs left to
1444 /// backend epics à la AUTHZ-FLOWS-4) is unresolved. Until that call is
1445 /// made, no backend should enable it in production.
1446 ///
1447 /// Deviation from AUTHZ-CORE-1: this is a runtime builder option, not
1448 /// the Cargo feature flag CORE-1 pinned — see [`super::scope_gate`]
1449 /// module docs for the rationale.
1450 ///
1451 /// [`ScopeRegistry::required_scopes_for`]: plexus_auth_core::ScopeRegistry::required_scopes_for
1452 pub fn with_default_deny(mut self, default_deny: bool) -> Self {
1453 let inner = self.inner_mut("Cannot set default_deny: DynamicHub has multiple references");
1454 inner.default_deny = default_deny;
1455 self
1456 }
1457
1458 /// Override where the scope gate writes its `ScopeCheck`
1459 /// [`AuditRecord`]s (AUTHZ-CORE-5). Default:
1460 /// [`plexus_auth_core::TracingAuditSink`] (`tracing::info!` events on
1461 /// the `plexus::audit` target).
1462 ///
1463 /// The gate awaits the sink's write BEFORE the dispatch responds
1464 /// ("audit before respond", AUTHZ-S01-output §8). Sink implementors
1465 /// are responsible for low-latency writes.
1466 ///
1467 /// [`AuditRecord`]: plexus_auth_core::AuditRecord
1468 pub fn with_audit_sink(mut self, sink: Arc<dyn plexus_auth_core::AuditSink>) -> Self {
1469 let inner = self.inner_mut("Cannot set audit_sink: DynamicHub has multiple references");
1470 inner.audit_sink = sink;
1471 self
1472 }
1473
1474 /// AUTH-2: put every call through `gate` before routing — default deny.
1475 ///
1476 /// With a gate, a call runs only if the caller holds the method's grant
1477 /// (`MethodSchema.grant`, else `<activation>.<method>`) through a role
1478 /// on the scope its target param resolves to — or anywhere, for a method
1479 /// without a target — within the session's ceiling. `public` methods run
1480 /// for anyone; an anonymous caller reaches nothing else
1481 /// ([`PlexusError::Unauthenticated`]); a refusal is
1482 /// [`AuthzDenyReason::MissingGrant`], rendered on the wire as an error
1483 /// item with `error_kind: "forbidden"`, `grant`, `scope`, `roles`,
1484 /// `held_on`. The routed call runs with the gate's [`Reach`] as
1485 /// [`super::grant_gate::current_reach`], which `#[plexus_macros::method]`
1486 /// hands a method declaring `reach: Reach`.
1487 ///
1488 /// A gated hub also stops merging its activations' direct JSON-RPC
1489 /// methods (`<activation>.<method>` registered beside `<hub>.call`):
1490 /// they carry no auth and would pass around the gate. Every call goes
1491 /// through `<hub>.call`.
1492 ///
1493 /// A hub that never calls this dispatches exactly as before. R-5's
1494 /// [`DynamicHub::with_scope_registry`] / [`DynamicHub::with_default_deny`]
1495 /// still apply after it when configured.
1496 ///
1497 /// [`Reach`]: plexus_auth_core::grants::Reach
1498 pub fn with_gate(mut self, gate: Arc<plexus_auth_core::grants::Gate>) -> Self {
1499 let inner = self.inner_mut("Cannot set gate: DynamicHub has multiple references");
1500 inner.gate = Some(gate);
1501 self
1502 }
1503
1504 /// AUTH-2: the configured gate, if any.
1505 pub fn gate(&self) -> Option<&Arc<plexus_auth_core::grants::Gate>> {
1506 self.inner.gate.as_ref()
1507 }
1508
1509 /// AUTH-4: the RFC 9728 protected-resource metadata URL
1510 /// (`…/.well-known/oauth-protected-resource`, AUTH-6) an anonymous
1511 /// caller's `_info` names as `auth.resource_metadata`. Only a gated hub
1512 /// says it; without a gate `_info` is unchanged.
1513 pub fn with_resource_metadata(mut self, url: impl Into<String>) -> Self {
1514 let inner = self.inner_mut("Cannot set resource_metadata: DynamicHub has multiple references");
1515 inner.resource_metadata = Some(url.into());
1516 self
1517 }
1518
1519 /// AUTH-4/AUTH-5: grants every signed-in caller reaches whatever its
1520 /// roles or ceiling — admitted by the gate like a `public` method, but
1521 /// only with a principal, and shown in every caller's view.
1522 /// [`DynamicHub::with_auth`] sets the auth activation's `whoami`,
1523 /// `logout` and `requires`; a hub calls this only for a method of its
1524 /// own of the same kind.
1525 pub fn with_signed_in_grants<I, S>(mut self, grants: I) -> Self
1526 where
1527 I: IntoIterator<Item = S>,
1528 S: Into<String>,
1529 {
1530 let inner = self.inner_mut("Cannot set signed_in grants: DynamicHub has multiple references");
1531 inner.signed_in_grants.extend(grants.into_iter().map(Into::into));
1532 self
1533 }
1534
1535 /// AUTH-5: mount the `auth` activation ([`super::auth_activation::AuthActivation`])
1536 /// and put every call through a gate built from the same stores — the
1537 /// one way a service turns login on. `setup` carries what only the
1538 /// service knows: its [`AuthBackend`] (providers, login flows, sessions,
1539 /// signup's waiting list), its editable [`RoleStore`] and
1540 /// [`MembershipStore`], and its scope [`Resolve`]r.
1541 ///
1542 /// Call it **after** registering the service's own activations or
1543 /// before — either way `auth.requires` knows every method (later
1544 /// registrations are added as they come). It replaces a gate set by
1545 /// [`DynamicHub::with_gate`].
1546 ///
1547 /// [`AuthBackend`]: super::auth_activation::AuthBackend
1548 /// [`RoleStore`]: super::auth_activation::RoleStore
1549 /// [`MembershipStore`]: super::auth_activation::MembershipStore
1550 /// [`Resolve`]: plexus_auth_core::grants::Resolve
1551 pub fn with_auth(mut self, setup: super::auth_activation::AuthSetup) -> Self {
1552 let catalog = super::auth_activation::Catalog::default();
1553 catalog.add(&Activation::plugin_schema(&self));
1554 for a in self.inner.activations.values() {
1555 catalog.add(&a.plugin_schema());
1556 }
1557 // MACRO-20: a static child's methods, by their whole path; NEST-5:
1558 // a typed slot's, by the slot's (`solar.{planet}.info`), and an
1559 // untyped slot whole (`solar.{planet}`).
1560 for child in self.described_children() {
1561 catalog.add(&child);
1562 }
1563 let (_, untyped) = self.slot_children();
1564 catalog.add_slots(&untyped);
1565 let (auth, gate) = super::auth_activation::AuthActivation::mount(setup, catalog.clone());
1566 {
1567 let inner = self.inner_mut("Cannot mount auth: DynamicHub has multiple references");
1568 inner.auth_catalog = Some(catalog);
1569 inner.gate = Some(Arc::new(gate));
1570 }
1571 self.register(auth)
1572 .with_signed_in_grants(super::auth_activation::SIGNED_IN_GRANTS.iter().copied())
1573 }
1574
1575 /// AUTH-4: the hub as `caller` may see it — what `_info`, the hub's
1576 /// `schema` / `hash` / `hashes` and every `<ns>.schema` answer that
1577 /// caller on a gated hub. Anonymous: the `public` methods only (the
1578 /// auth activation's door). Signed in: each method whose grant a role
1579 /// the caller holds lists (within its ceiling), with `held_on`; the
1580 /// public methods; the signed-in methods (`auth.whoami`, …). Methods
1581 /// the caller cannot use are absent; activations left with none are
1582 /// absent. The hub's own methods are in every view.
1583 ///
1584 /// Without a gate: the whole hub, as every caller sees it today
1585 /// ([`ViewKind::Caller`](super::ViewKind::Caller), the hub's own hash).
1586 /// See [`super::view`].
1587 ///
1588 /// PERF-15: answered from the service's self-description cache — built
1589 /// once per schema generation and, for a gated service, once per view
1590 /// key (the caller's grants' fingerprint, or anonymous) and grants
1591 /// generation.
1592 pub fn view(&self, caller: Option<&super::auth::AuthContext>) -> super::view::View {
1593 match self.inner.gate.as_ref() {
1594 None => self.described().whole(),
1595 Some(_) => {
1596 let (base, view) = self.shaped(caller);
1597 view.view(&base)
1598 }
1599 }
1600 }
1601
1602 /// PERF-15: something this service describes changed after it was built
1603 /// — a child mounted or gone while it serves, an activation whose schema
1604 /// changed: what the self-description cache kept is dropped, and the
1605 /// next `_info`, `hash` or `schema` builds it again. Registering, and
1606 /// every other change while the service is built, does this by itself.
1607 pub fn schema_moved(&self) {
1608 self.inner.describe.schema_moved();
1609 }
1610
1611 /// PERF-15: what the service's schemas show whoever asks — its own,
1612 /// every activation's, every static child's — kept per schema
1613 /// generation.
1614 fn described(&self) -> Arc<super::view::Described> {
1615 let at = self.inner.describe.schema_generation();
1616 match self.inner.describe.base(at) {
1617 Some(cell) => cell.get_or_init(|| Arc::new(self.describe_now())).clone(),
1618 None => Arc::new(self.describe_now()),
1619 }
1620 }
1621
1622 fn describe_now(&self) -> super::view::Described {
1623 let service = Activation::plugin_schema(self);
1624 let activations: Vec<PluginSchema> = self.inner.activations.values().map(|a| a.plugin_schema()).collect();
1625 // MACRO-20: a static child's entry stays in its parent's view when
1626 // the caller can use something below it.
1627 // NEST-5: and a slot's (`solar.planet`) when something in the slot.
1628 super::view::Described::new(service, activations, self.described_children())
1629 }
1630
1631 /// PERF-15: a gated service's view for `caller`, kept per view key and
1632 /// grants generation, with what it was decided over. The generations
1633 /// are read before anything they cover, so a write that lands while a
1634 /// view is built leaves it under the generation before — dropped at the
1635 /// next ask.
1636 fn shaped(&self, caller: Option<&super::auth::AuthContext>) -> (Arc<super::view::Described>, Arc<super::view::Shaped>) {
1637 let gate = self.inner.gate.as_ref().expect("a view is a gated service's");
1638 let schema_at = self.inner.describe.schema_generation();
1639 let grants_at = gate.generation().current();
1640 // AUTH-11: a sign-in that ended sees the anonymous view — asked on
1641 // every ask, never kept.
1642 let (caller, _) = super::grant_gate::standing(gate, caller);
1643 let who = caller.and_then(|c| gate.fingerprint(c));
1644 let shape = |base: &super::view::Described| {
1645 Arc::new(super::view::shape(gate, &self.inner.signed_in_grants, who.as_ref(), base))
1646 };
1647 match self.inner.describe.view(schema_at, grants_at, &who) {
1648 Some((base, view)) => {
1649 let base = base.get_or_init(|| Arc::new(self.describe_now())).clone();
1650 let view = view.get_or_init(|| shape(&base)).clone();
1651 (base, view)
1652 }
1653 None => {
1654 let base = Arc::new(self.describe_now());
1655 let view = shape(&base);
1656 (base, view)
1657 }
1658 }
1659 }
1660
1661 /// AUTH-4: `_info`'s content for `caller`. Without a gate, exactly
1662 /// today's `{backend, auth_capabilities}` whoever asks. With one, also
1663 /// `view` (`anonymous` | `caller`) and `view_hash`; and, to an
1664 /// anonymous caller, `auth: {methods: [the public methods' grants],
1665 /// resource_metadata?}` — how to sign in.
1666 pub fn info(&self, caller: Option<&super::auth::AuthContext>) -> serde_json::Value {
1667 if self.inner.gate.is_none() {
1668 return build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1669 }
1670 // PERF-15: built once per view, kept with it.
1671 let (base, view) = self.shaped(caller);
1672 view.info
1673 .get_or_init(|| {
1674 let mut payload = build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1675 if let Some(obj) = payload.as_object_mut() {
1676 obj.insert("view".into(), view.kind.as_str().into());
1677 obj.insert("view_hash".into(), view.hash.clone().into());
1678 if view.kind == super::ViewKind::Anonymous {
1679 let mut auth = serde_json::Map::new();
1680 auth.insert("methods".into(), view.public_methods(&base).into());
1681 if let Some(url) = self.inner.resource_metadata.as_ref() {
1682 auth.insert("resource_metadata".into(), url.clone().into());
1683 }
1684 obj.insert("auth".into(), serde_json::Value::Object(auth));
1685 }
1686 }
1687 payload
1688 })
1689 .clone()
1690 }
1691
1692 /// AUTH-4: a gated hub's introspection (`<ns>.schema`, the hub's
1693 /// `hash` / `hashes`, `<ns>.<method>.schema`) answered from the
1694 /// caller's view: the stream the hub would send, its content replaced
1695 /// by the view's. `None`: not answered here (a nested child path of a
1696 /// visible activation) — route it as before.
1697 async fn introspect_in_view(
1698 &self,
1699 method: &str,
1700 params: &Value,
1701 auth: Option<&super::auth::AuthContext>,
1702 raw_ctx: Option<&crate::request::RawRequestContext>,
1703 ) -> Option<Result<PlexusStream, PlexusError>> {
1704 let (ns, rest) = method.split_once('.')?;
1705 let hub_ns = self.inner.namespace.as_str();
1706 // PERF-15: the view, and what it was decided over, from the cache.
1707 let (base, view) = self.shaped(auth);
1708 let not_found = || PlexusError::ActivationNotFound(ns.to_string());
1709 let content: serde_json::Value = match rest {
1710 "schema" => {
1711 if !view.shows(ns) {
1712 return Some(Err(not_found()));
1713 }
1714 let mut result = match params.get("method").and_then(|v| v.as_str()) {
1715 Some(name) => match view.method_of(&base, ns, name) {
1716 Some(m) => super::SchemaResult::Method(m),
1717 None => {
1718 return Some(Err(PlexusError::MethodNotFound {
1719 activation: ns.to_string(),
1720 method: name.to_string(),
1721 }))
1722 }
1723 },
1724 None => super::SchemaResult::Plugin(view.schema_of(&base, ns)?),
1725 };
1726 if let Some(site) = self.derived_site_hint() {
1727 result.fill_site_hints(&site);
1728 }
1729 serde_json::to_value(&result).ok()?
1730 }
1731 "hash" if ns == hub_ns => serde_json::to_value(HashEvent::Hash { value: view.hash.clone() }).ok()?,
1732 "hashes" if ns == hub_ns => serde_json::to_value(view.hashes()).ok()?,
1733 r if r.ends_with(".schema") => {
1734 if !view.shows(ns) {
1735 return Some(Err(not_found()));
1736 }
1737 let name = r.trim_end_matches(".schema");
1738 match view.method_of(&base, ns, name) {
1739 Some(m) if matches!(m.role, super::MethodRole::Rpc) => {
1740 serde_json::to_value(super::SchemaResult::Method(m)).ok()?
1741 }
1742 // A visible nested child: its own routing answers.
1743 Some(_) => return None,
1744 None if name.contains('.') => return None,
1745 // NEST-6: a name in the activation's dynamic slot
1746 // (`solar.earth.schema`): the instance's own schema,
1747 // which its routing answers.
1748 None if base.activations.iter().any(|a| a.namespace == ns && a.methods.iter().any(|m| m.role.is_slot())) => return None,
1749 None => {
1750 return Some(Err(PlexusError::MethodNotFound {
1751 activation: ns.to_string(),
1752 method: name.to_string(),
1753 }))
1754 }
1755 }
1756 }
1757 _ => return None,
1758 };
1759 // The stream the service sends today, so content types and metadata
1760 // stay what clients know; only the content is the view's.
1761 use futures::StreamExt;
1762 let with = |content: serde_json::Value| {
1763 // PERF-7: an encoded item is a `Data` item: its content is
1764 // replaced whole, whatever it was made as.
1765 move |item: super::types::PlexusStreamItem| match item {
1766 super::types::PlexusStreamItem::Data { metadata, content_type, .. } => {
1767 super::types::PlexusStreamItem::Data { metadata, content_type, content: content.clone().into() }
1768 }
1769 other => other,
1770 }
1771 };
1772 // R-5's scope gate decides introspection on every call, and audits
1773 // it: routed every time, as before.
1774 if self.inner.scope_registry.is_some() || self.inner.default_deny {
1775 let routed = self.route_ungated(method, params.clone(), auth, raw_ctx).await;
1776 return Some(routed.map(|s| -> PlexusStream { Box::pin(s.map(with(content))) }));
1777 }
1778 // PERF-15: that stream's envelope is learned from the first answer
1779 // routed for this method and params, and kept with what the service
1780 // describes; after it no activation builds its schema to say it.
1781 let key = format!("{method}\n{params}");
1782 if let Some(shell) = base.shell(&key) {
1783 return Some(Ok(Box::pin(futures::stream::iter(shell.answer(content)))));
1784 }
1785 let items: Vec<super::types::PlexusStreamItem> = match self.route_ungated(method, params.clone(), auth, raw_ctx).await {
1786 Ok(s) => s.collect().await,
1787 Err(e) => return Some(Err(e)),
1788 };
1789 if let Some(shell) = super::view::Shell::of(&items) {
1790 base.keep_shell(key, shell);
1791 }
1792 Some(Ok(Box::pin(futures::stream::iter(items.into_iter().map(with(content))))))
1793 }
1794
1795 /// RETURNS-40: the service's IR of the walks from `namespaces` (dotted
1796 /// paths; none: the whole service) as `caller` sees it — what its `ir`
1797 /// method answers. Synapse's walk, made in process over **one snapshot**
1798 /// of what the caller is shown (RETURNS-40 review #2): the service's own
1799 /// schema and each activation's from that one view (a grant that moves
1800 /// while the IR is built moves the next view, not this one), a static
1801 /// child's as its activation answers it, each child summary followed;
1802 /// under the R-5 scope gate only the schemas the caller's own calls are
1803 /// answered (#3). Built off the runtime (`spawn_blocking`), once per key
1804 /// at a time, and kept by the view's hash, the roots and — under the
1805 /// scope gate — what the caller is answered ([`super::ir::IrCache`],
1806 /// #4); a refusal is not kept. The IR is [`super::ir::build`]'s, equal
1807 /// to synapse's `buildIRFromSchemas` over the same schemas.
1808 pub async fn service_ir(
1809 &self,
1810 namespaces: &[String],
1811 caller: Option<&super::auth::AuthContext>,
1812 ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
1813 let roots = super::ir::roots(&self.inner.namespace, namespaces);
1814 let view = self.ir_view(caller);
1815 let permitted = match self.inner.scope_registry.is_some() || self.inner.default_deny {
1816 false => None,
1817 true => {
1818 // re-review #4: decided for the names under the roots asked
1819 // alone, and written to no audit sink — the `ir` call was
1820 // enforced, and audited, once
1821 let mut answered = Vec::new();
1822 for name in view.names(&self.inner.namespace) {
1823 let under = roots.iter().any(|r| {
1824 let r = r.join(".");
1825 r.is_empty() || name == r || name.starts_with(&format!("{r}."))
1826 });
1827 if under && self.scope_answers(&self.schema_method(&name), caller).await {
1828 answered.push(name);
1829 }
1830 }
1831 Some(answered)
1832 }
1833 };
1834 let key = super::ir::IrKey { view: view.hash.clone(), roots: roots.clone(), permitted: permitted.clone() };
1835 self.inner
1836 .ir_cache
1837 .get_or_build(key, || async {
1838 let mut schemas: BTreeMap<Vec<String>, Value> = BTreeMap::new();
1839 let mut todo: Vec<Vec<String>> = roots.clone();
1840 while let Some(path) = todo.pop() {
1841 if schemas.contains_key(&path) || permitted.as_ref().is_some_and(|p| !p.contains(&path.join("."))) {
1842 continue;
1843 }
1844 // a schema the caller is not answered is one the walk skips
1845 let Some(schema) = self.ir_schema(&view, &path, caller).await else { continue };
1846 for child in schema.get("children").and_then(Value::as_array).into_iter().flatten() {
1847 if let Some(ns) = child.get("namespace").and_then(Value::as_str) {
1848 let mut next = path.clone();
1849 next.push(ns.to_string());
1850 todo.push(next);
1851 }
1852 }
1853 schemas.insert(path, schema);
1854 }
1855 let service = self.inner.namespace.clone();
1856 crate::rt::spawn_blocking(move || super::ir::answer(&service, &roots, &schemas))
1857 .await
1858 .unwrap_or_else(|e| Err(super::ir::IrError::Unreadable { namespace: String::new(), message: format!("the IR's build failed: {e}") }))
1859 })
1860 .await
1861 }
1862
1863 /// How many IR builds this service has run — its `ir` answers built
1864 /// rather than kept.
1865 pub fn ir_builds(&self) -> usize {
1866 self.inner.ir_cache.builds()
1867 }
1868
1869 /// RETURNS-40: one snapshot of what `caller` is shown — the caller's view
1870 /// under the grant gate (one [`DynamicHub::shaped`]), the whole service
1871 /// otherwise.
1872 fn ir_view(&self, caller: Option<&super::auth::AuthContext>) -> IrView {
1873 match self.inner.gate {
1874 Some(_) => {
1875 let (base, shaped) = self.shaped(caller);
1876 IrView { hash: shaped.hash.clone(), base, shaped: Some(shaped) }
1877 }
1878 None => {
1879 let base = self.described();
1880 IrView { hash: base.service.hash.clone(), base, shaped: None }
1881 }
1882 }
1883 }
1884
1885 /// `<path>.schema` (the service's own `<ns>.schema` at `[]`).
1886 fn schema_method(&self, dotted: &str) -> String {
1887 if dotted.is_empty() { format!("{}.schema", self.inner.namespace) } else { format!("{dotted}.schema") }
1888 }
1889
1890 /// Whether the R-5 scope gate answers `caller`'s `method` — the gate the
1891 /// call itself would meet.
1892 async fn scope_answers(&self, method: &str, caller: Option<&super::auth::AuthContext>) -> bool {
1893 let registry = self.inner.scope_registry.as_deref().unwrap_or_else(|| super::scope_gate::empty_registry());
1894 super::scope_gate::answers(registry, self.inner.default_deny, method, self.gate_info(method), caller).await
1895 }
1896
1897 /// The schema at `path` as the snapshot answers it — what `<path>.schema`
1898 /// answers the caller: the service's own and each activation's from the
1899 /// view, a static child's (which no view shapes) as its activation
1900 /// answers it, asked of the activation as the route asks it.
1901 async fn ir_schema(&self, view: &IrView, path: &[String], caller: Option<&super::auth::AuthContext>) -> Option<Value> {
1902 use futures::StreamExt;
1903 let shown = match path {
1904 [] => Some(view.root()),
1905 [ns] => view.top(ns),
1906 [top, below @ ..] => {
1907 // asked of its activation as the route asks it past both
1908 // gates — the scope gate decided this name already, silently
1909 let activation = self.inner.activations.get(top.as_str())?;
1910 let mut stream = activation.call(&format!("{}.schema", below.join(".")), Value::Null, caller, None).await.ok()?;
1911 if let Some(site) = self.derived_site_hint() {
1912 stream = fill_site_hints_in_schema_stream(stream, site);
1913 }
1914 let items: Vec<super::types::PlexusStreamItem> = stream.collect().await;
1915 return items.into_iter().find_map(|item| match item {
1916 super::types::PlexusStreamItem::Data { content_type, content, .. } if content_type.ends_with(".schema") => {
1917 Some(content.into_value())
1918 }
1919 _ => None,
1920 });
1921 }
1922 };
1923 let mut schema = shown?;
1924 if let Some(site) = self.derived_site_hint() {
1925 schema.fill_site_hints(&site);
1926 }
1927 serde_json::to_value(super::SchemaResult::Plugin(schema)).ok()
1928 }
1929
1930 /// RETURNS-40 review #1: `ir`'s `namespaces` refused before any work —
1931 /// more names than the caller's view of the service has, or a name it
1932 /// has not (named), is `invalid_params`.
1933 fn check_ir_names(&self, params: &Value, caller: Option<&super::auth::AuthContext>) -> Result<(), PlexusError> {
1934 let asked = match params.get("namespaces") {
1935 None | Some(Value::Null) => return Ok(()),
1936 Some(Value::Array(a)) => a,
1937 Some(_) => return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")),
1938 };
1939 // the cheap bound first, read with no schema built: no view shows
1940 // more than the service has — said without the service's size
1941 // (re-review #3), which the caller's view may not show
1942 let most = 1 + self.inner.activations.len() + self.inner.nested_count();
1943 if asked.len() > most {
1944 return Err(PlexusError::malformed_param(
1945 "namespaces",
1946 format!("{} namespaces asked; more than this service shows you", asked.len()),
1947 ));
1948 }
1949 let names: std::collections::HashSet<String> = self.ir_view(caller).names(&self.inner.namespace).into_iter().collect();
1950 if asked.len() > names.len() {
1951 return Err(PlexusError::malformed_param(
1952 "namespaces",
1953 format!("{} namespaces asked; this service shows you {}", asked.len(), names.len()),
1954 ));
1955 }
1956 for n in asked {
1957 let Some(n) = n.as_str() else { return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")) };
1958 let known = n == self.inner.namespace || names.contains(n);
1959 if !known {
1960 return Err(PlexusError::malformed_param("namespaces", format!("no namespace `{n}` in this service")));
1961 }
1962 }
1963 Ok(())
1964 }
1965
1966 /// AUTH-2/AUTH-3: the default roles every registered activation
1967 /// declares (`#[plexus_macros::activation(roles(...))]`), merged by role
1968 /// name — what a service seeds its [`Roles`] with
1969 /// ([`RoleTable::from_lists`]) before an admin's edits.
1970 ///
1971 /// [`Roles`]: plexus_auth_core::grants::Roles
1972 /// [`RoleTable::from_lists`]: plexus_auth_core::grants::RoleTable::from_lists
1973 pub fn declared_roles(&self) -> std::collections::BTreeMap<String, Vec<String>> {
1974 let mut out: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
1975 // MACRO-20: and every static child's, its grants qualified by the
1976 // path it is reached through (`commits.link` → `tickets.commits.link`).
1977 // NEST-5: and every typed slot's, by the slot's path.
1978 let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.described_children());
1979 for schema in schemas {
1980 for (role, grants) in schema.roles {
1981 let entry = out.entry(role).or_default();
1982 for g in grants {
1983 if !entry.contains(&g) {
1984 entry.push(g);
1985 }
1986 }
1987 }
1988 }
1989 out
1990 }
1991
1992 /// MACRO-20: every registered activation's static children (and
1993 /// theirs), each a schema whose namespace is its whole path
1994 /// (`tickets.commits`) and whose grants and roles are qualified by it —
1995 /// see [`super::children`]. Empty for a hub whose activations have no
1996 /// static `#[plexus_macros::child]`.
1997 pub fn static_children(&self) -> Vec<PluginSchema> {
1998 self.inner
1999 .activations
2000 .values()
2001 .flat_map(|a| super::children::qualified(&a.plugin_schema().namespace, a.static_child_schemas()))
2002 .collect()
2003 }
2004
2005 /// Read-only view of the configured [`ScopeRegistry`], if any.
2006 /// Test-side accessor.
2007 ///
2008 /// [`ScopeRegistry`]: plexus_auth_core::ScopeRegistry
2009 pub fn scope_registry(&self) -> Option<&plexus_auth_core::ScopeRegistry> {
2010 self.inner.scope_registry.as_deref()
2011 }
2012
2013 /// BIDIR-6: what a call with an input half is held to when it is asked
2014 /// again: the grant and targets the gate decided it on. Read only when a
2015 /// method with an `Input` opens, so no other call pays for it.
2016 pub(crate) fn input_terms(&self, method: &str, params: &Value) -> Result<InputTerms, PlexusError> {
2017 if self.inner.gate.is_none() {
2018 return Ok(InputTerms { grant: method.to_string(), targets: Vec::new(), recheck: false });
2019 }
2020 let info = self.gate_info(method);
2021 let grant = info.and_then(|i| i.grant.clone()).unwrap_or_else(|| method.to_string());
2022 let open = info.is_some_and(|i| i.public) || self.inner.signed_in_grants.contains(grant.as_str());
2023 let targets = match info.and_then(|i| i.target.as_deref()) {
2024 Some(param) => super::grant_gate::target_values(params, param)?.unwrap_or_default(),
2025 None => Vec::new(),
2026 };
2027 Ok(InputTerms { grant, targets, recheck: !open })
2028 }
2029
2030 /// BIDIR-6: the gate over this service's duplex calls, made when the
2031 /// first one opens (in the runtime, which runs its audit's drain).
2032 pub(crate) fn duplex_gate(&self) -> &super::duplex_gate::DuplexGate {
2033 self.inner.duplex_gate.get_or_init(|| match &self.inner.gate {
2034 Some(gate) => {
2035 let (audit, drain) = plexus_auth_core::audit::AuditQueue::new(1024, self.inner.audit_sink.clone());
2036 crate::rt::spawn(drain);
2037 super::duplex_gate::DuplexGate::new((**gate).clone()).with_audit(audit)
2038 }
2039 None => super::duplex_gate::DuplexGate::ungated(),
2040 })
2041 }
2042
2043 /// BIDIR-6: whether `method` (a `{ns}.call`'s dotted path) may take an
2044 /// `Input`: `false` only for a method this service's schemas show has
2045 /// none — its own, each activation's, each static child's. A path they do
2046 /// not show (a dynamic child's) may.
2047 pub(crate) fn may_take_input(&self, method: &str) -> bool {
2048 let index = self.inner.input_index.get_or_init(|| {
2049 let own = Activation::plugin_schema(self).methods.into_iter().map(|m| (format!("{}.{}", self.inner.namespace, m.name), m.input.is_some()));
2050 let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
2051 let theirs = schemas.flat_map(|schema| {
2052 let ns = schema.namespace;
2053 schema.methods.into_iter().map(move |m| (format!("{ns}.{}", m.name), m.input.is_some()))
2054 });
2055 own.chain(theirs).collect()
2056 });
2057 index.get(method).copied().unwrap_or(true)
2058 }
2059
2060 /// NEST-5: the gate's facts for `method` — its own entry, else its
2061 /// slot's (`solar.earth.info` → `solar.{planet}.info`; through an
2062 /// untyped slot, `solar.{planet}`). A literal entry always wins.
2063 fn gate_info(&self, method: &str) -> Option<&super::scope_gate::MethodGateInfo> {
2064 let index = self.gate_index();
2065 index.methods.get(method).or_else(|| index.slots.resolve(method).and_then(|k| index.methods.get(&k)))
2066 }
2067
2068 /// NEST-5: every slot of every registered activation and static child
2069 /// (to any depth): each typed slot as a schema at its path
2070 /// (`tickets.{item}`, grants qualified — [`super::slots`]), and each
2071 /// untyped slot's path.
2072 pub fn slot_children(&self) -> (Vec<PluginSchema>, Vec<String>) {
2073 let (mut typed, mut untyped) = (Vec::new(), Vec::new());
2074 let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
2075 for schema in schemas {
2076 super::slots::slot_schemas(&schema, &mut typed, &mut untyped);
2077 }
2078 (typed, untyped)
2079 }
2080
2081 /// MACRO-20 and NEST-5: every static child and every typed slot, each a
2082 /// schema whose namespace is its whole path and whose grants are
2083 /// qualified by it — what the gate, the roles, `auth.requires` and the
2084 /// caller's view read below an activation.
2085 pub fn described_children(&self) -> Vec<PluginSchema> {
2086 let mut out = self.static_children();
2087 out.extend(self.slot_children().0);
2088 out
2089 }
2090
2091 /// The gate's path→schema-facts index; built once on first gated
2092 /// dispatch. See the field docs on `DynamicHubInner::gate_index`.
2093 fn gate_index(&self) -> &GateIndex {
2094 self.inner.gate_index.get_or_init(|| {
2095 let mut index = HashMap::new();
2096 // The hub's own methods, addressable as "<hub-ns>.<method>".
2097 for m in &Activation::plugin_schema(self).methods {
2098 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
2099 // The hub's own methods are granted under its runtime
2100 // namespace (the macro's static one is "plexus").
2101 info.grant = Some(format!("{}.{}", self.inner.namespace, m.name));
2102 index.insert(format!("{}.{}", self.inner.namespace, m.name), info);
2103 }
2104 // Each registered activation's methods, addressable as
2105 // "<activation-ns>.<method>"; MACRO-20: and each static child's,
2106 // as "<activation-ns>.<path>.<method>", with the child's own
2107 // target and its grant qualified by the path
2108 // (`tickets.commits.link`, see `super::children`). A dynamic
2109 // child (an open name set) has no MethodSchema at this hub's
2110 // level; the gate treats its paths as schema-less (grant = the
2111 // dotted path; registry overlay / default_deny still apply).
2112 // NEST-5: and each typed slot's, as `<parent>.{<slot>}.<method>`
2113 // with its grant qualified by the slot's path; an untyped slot
2114 // is one entry, `<parent>.{<slot>}`, granted whole.
2115 let (typed, untyped) = self.slot_children();
2116 let activations: Vec<PluginSchema> = self.inner.activations.values().map(|a| a.plugin_schema()).collect();
2117 let statics = self.static_children();
2118 for schema in activations.iter().chain(statics.iter()).chain(typed.iter()) {
2119 for m in &schema.methods {
2120 let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
2121 info.grant = Some(m.grant_or(&schema.namespace));
2122 index.insert(format!("{}.{}", schema.namespace, m.name), info);
2123 }
2124 }
2125 for path in &untyped {
2126 index.insert(
2127 path.clone(),
2128 super::scope_gate::MethodGateInfo { grant: Some(path.clone()), ..Default::default() },
2129 );
2130 }
2131 let slots = super::slots::Slots::of(activations.iter().chain(statics.iter()).chain(typed.iter()), &untyped);
2132 GateIndex { methods: index, slots }
2133 })
2134 }
2135
2136 /// Register a [`plexus_auth_core::ForwardPolicy`] for a callee
2137 /// namespace.
2138 ///
2139 /// AUTHLANG-3 — every cross-boundary call through this hub consults
2140 /// the registry at dispatch time. When `callee_ns` has no entry, the
2141 /// framework falls back to [`plexus_auth_core::IdentityOnly`].
2142 ///
2143 /// AUTHLANG-4's `#[plexus::activation(forward_policy = ...)]`
2144 /// attribute is the declarative path; this builder is the imperative
2145 /// escape hatch used by integration tests and hand-rolled wiring.
2146 ///
2147 /// # Example
2148 ///
2149 /// ```ignore
2150 /// use plexus_auth_core::PassThrough;
2151 /// use std::sync::Arc;
2152 ///
2153 /// let hub = DynamicHub::new("my-backend")
2154 /// .with_forward_policy("solar", Arc::new(PassThrough));
2155 /// ```
2156 pub fn with_forward_policy(
2157 mut self,
2158 callee_ns: impl Into<String>,
2159 policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>,
2160 ) -> Self {
2161 let inner = self.inner_mut("Cannot register forward policy: DynamicHub has multiple references");
2162 inner.forward_policies.register(callee_ns, policy);
2163 self
2164 }
2165
2166 /// Read-only view of the registered forward policies.
2167 ///
2168 /// Test-side accessor; production dispatch consults the registry via
2169 /// the [`ChildRouter::forward_policy_for`] override.
2170 pub fn forward_policies(&self) -> &super::forward_registry::ForwardPolicyRegistry {
2171 &self.inner.forward_policies
2172 }
2173
2174 /// Declare the backend's authentication capabilities, served at `_info`.
2175 ///
2176 /// Backends call this at builder time to advertise which auth mechanisms
2177 /// they support (Bearer, Cookie, OIDC, Anonymous). Generic clients
2178 /// (synapse CLI, gamma, generated SDKs) read the advertisement to decide
2179 /// which authentication flow to drive.
2180 ///
2181 /// Without calling this method, `_info` emits the
2182 /// [`plexus_auth_core::BackendAuthCapabilities::anonymous_default`]
2183 /// fallback: a single `Anonymous` mechanism, no default. This preserves
2184 /// today's no-auth substrate behavior.
2185 ///
2186 /// Per AUTHZ-CORE-3 / AUTHZ-S01-output §2.
2187 ///
2188 /// # Example
2189 ///
2190 /// ```no_run
2191 /// # use plexus_core::DynamicHub;
2192 /// use plexus_auth_core::{
2193 /// AuthMechanism, BackendAuthCapabilities, CookieName, MethodPath,
2194 /// };
2195 ///
2196 /// let caps = BackendAuthCapabilities::new(
2197 /// vec![AuthMechanism::Cookie {
2198 /// cookie: CookieName::try_new("plexus_session").unwrap(),
2199 /// login: MethodPath::try_new("auth.login").unwrap(),
2200 /// refresh: None,
2201 /// logout: None,
2202 /// }],
2203 /// Some(0),
2204 /// )
2205 /// .unwrap();
2206 ///
2207 /// let hub = DynamicHub::new("my-backend").with_auth_capabilities(caps);
2208 /// ```
2209 pub fn with_auth_capabilities(
2210 mut self,
2211 caps: plexus_auth_core::BackendAuthCapabilities,
2212 ) -> Self {
2213 let inner = self.inner_mut("Cannot set auth_capabilities: DynamicHub has multiple references");
2214 inner.auth_capabilities = Some(caps);
2215 self
2216 }
2217
2218 /// Returns the configured [`BackendAuthCapabilities`], or `None` if the
2219 /// backend has not called [`Self::with_auth_capabilities`].
2220 ///
2221 /// Test-side accessor; production code reads the advertisement off `_info`.
2222 ///
2223 /// [`BackendAuthCapabilities`]: plexus_auth_core::BackendAuthCapabilities
2224 pub fn auth_capabilities(&self) -> Option<&plexus_auth_core::BackendAuthCapabilities> {
2225 self.inner.auth_capabilities.as_ref()
2226 }
2227
2228 /// Deprecated: Use new() with explicit namespace instead
2229 #[deprecated(since = "0.3.0", note = "Use DynamicHub::new(namespace) instead")]
2230 pub fn with_namespace(namespace: impl Into<String>) -> Self {
2231 Self::new(namespace)
2232 }
2233
2234 /// Get the runtime namespace for this DynamicHub instance
2235 pub fn runtime_namespace(&self) -> &str {
2236 &self.inner.namespace
2237 }
2238
2239 /// Get access to the activation registry
2240 pub fn registry(&self) -> std::sync::RwLockReadGuard<'_, PluginRegistry> {
2241 self.inner.registry.read().unwrap()
2242 }
2243
2244 /// Panic if `child_namespace` shadows the hub root namespace.
2245 ///
2246 /// Z2H-8 / HOSTLESS-3 — routing resolves the hub root before registered
2247 /// activations (see [`Self::route_with_ctx`]), so a child activation whose
2248 /// namespace equals the hub root name is silently unreachable: every
2249 /// `<ns>.<method>` call resolves to the root (which only has
2250 /// call/hash/hashes/schema) and navigators resolve the like-named child
2251 /// back to the root schema. The published echo example shipped exactly
2252 /// this shape and was dead on arrival. A loud, immediate error at
2253 /// registration time beats silent unreachability at call time.
2254 fn assert_no_root_shadow(&self, child_namespace: &str) {
2255 if child_namespace == self.inner.namespace {
2256 panic!(
2257 "DynamicHub namespace shadow: activation namespace '{child}' collides with the hub root namespace '{root}'. \
2258 The hub root name is a routing namespace, not a label — routing resolves the root first, so a like-named \
2259 child activation is unreachable (every '{child}.<method>' call resolves to the hub root and fails with \
2260 'Command not found', and navigation resolves the child back to the root schema). \
2261 Fix: rename the hub root so it differs from every registered activation's namespace, \
2262 e.g. DynamicHub::new(\"{root}_hub\").register(...). [Z2H-8 / HOSTLESS-3]",
2263 child = child_namespace,
2264 root = self.inner.namespace,
2265 );
2266 }
2267 }
2268
2269 /// Register an activation
2270 ///
2271 /// # Panics
2272 ///
2273 /// Panics if the activation's namespace equals the hub root namespace —
2274 /// such a child would be unreachable at call time (Z2H-8 / HOSTLESS-3,
2275 /// see [`Self::new`]). Also panics if the hub has already been shared
2276 /// (multiple `Arc` references).
2277 pub fn register<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2278 let namespace = activation.namespace().to_string();
2279 self.assert_no_root_shadow(&namespace);
2280 let plugin_id = activation.plugin_id();
2281 let activation_for_rpc = activation.clone();
2282 let activation_for_router = activation.clone();
2283
2284 let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2285
2286 // Register in the activation registry
2287 inner.registry.write().unwrap().register(
2288 plugin_id,
2289 namespace.clone(),
2290 namespace.clone(), // Use namespace as plugin_type for now
2291 );
2292
2293 // AUTH-5: `auth.requires` knows every method, registered before
2294 // the auth activation was mounted or after.
2295 if let Some(catalog) = inner.auth_catalog.as_ref() {
2296 let schema = activation.plugin_schema();
2297 // MACRO-20: and its static children's methods, by their whole path.
2298 let statics = super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation));
2299 // NEST-5: and its slots — a typed slot's methods by the slot's
2300 // path, an untyped slot whole.
2301 let (mut typed, mut untyped) = (Vec::new(), Vec::new());
2302 for s in std::iter::once(&schema).chain(statics.iter()) {
2303 super::slots::slot_schemas(s, &mut typed, &mut untyped);
2304 }
2305 for child in statics.iter().chain(typed.iter()) {
2306 catalog.add(child);
2307 }
2308 catalog.add_slots(&untyped);
2309 catalog.add(&schema);
2310 }
2311 // RETURNS-40: the cheap bound on `ir`'s names, counted here, once
2312 inner.nested_count += Activation::static_child_schemas(&activation).len();
2313 inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
2314 inner.child_routers.insert(namespace.clone(), Arc::new(activation_for_router));
2315 inner.pending_rpc.lock().unwrap()
2316 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2317 self
2318 }
2319
2320 /// Register a hub activation that supports nested routing
2321 ///
2322 /// Hub activations implement `ChildRouter`, enabling direct nested method calls
2323 /// like `hub.solar.mercury.info` at the RPC layer (no hub.call indirection).
2324 ///
2325 /// # Panics
2326 ///
2327 /// Same contract as [`Self::register`]: panics on a root/activation
2328 /// namespace collision (Z2H-8 / HOSTLESS-3).
2329 #[deprecated(since = "0.5.0", note = "Use register() — it now handles both leaf and hub activations")]
2330 pub fn register_hub<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2331 let namespace = activation.namespace().to_string();
2332 self.assert_no_root_shadow(&namespace);
2333 let plugin_id = activation.plugin_id();
2334 let activation_for_rpc = activation.clone();
2335 let activation_for_router = activation.clone();
2336
2337 let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2338
2339 // Register in the activation registry
2340 inner.registry.write().unwrap().register(
2341 plugin_id,
2342 namespace.clone(),
2343 namespace.clone(), // Use namespace as plugin_type for now
2344 );
2345
2346 if let Some(catalog) = inner.auth_catalog.as_ref() {
2347 let schema = activation.plugin_schema();
2348 // MACRO-20: and its static children's methods, by their whole path.
2349 let statics = super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation));
2350 // NEST-5: and its slots — a typed slot's methods by the slot's
2351 // path, an untyped slot whole.
2352 let (mut typed, mut untyped) = (Vec::new(), Vec::new());
2353 for s in std::iter::once(&schema).chain(statics.iter()) {
2354 super::slots::slot_schemas(s, &mut typed, &mut untyped);
2355 }
2356 for child in statics.iter().chain(typed.iter()) {
2357 catalog.add(child);
2358 }
2359 catalog.add_slots(&untyped);
2360 catalog.add(&schema);
2361 }
2362 // RETURNS-40: the cheap bound on `ir`'s names, counted here, once
2363 inner.nested_count += Activation::static_child_schemas(&activation).len();
2364 inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
2365 inner.child_routers.insert(namespace, Arc::new(activation_for_router));
2366 inner.pending_rpc.lock().unwrap()
2367 .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2368 self
2369 }
2370
2371 /// List all methods across all activations
2372 pub fn list_methods(&self) -> Vec<String> {
2373 let mut methods = Vec::new();
2374
2375 // Include hub's own methods
2376 for m in Activation::methods(self) {
2377 methods.push(format!("{}.{}", self.inner.namespace, m));
2378 }
2379
2380 // Include registered activation methods
2381 for (ns, act) in &self.inner.activations {
2382 for m in act.methods() {
2383 methods.push(format!("{}.{}", ns, m));
2384 }
2385 }
2386 methods.sort();
2387 methods
2388 }
2389
2390 /// List all activations (including this hub itself)
2391 pub fn list_activations_info(&self) -> Vec<ActivationInfo> {
2392 let mut activations = Vec::new();
2393
2394 // Include this hub itself
2395 activations.push(ActivationInfo {
2396 namespace: Activation::namespace(self).to_string(),
2397 version: Activation::version(self).to_string(),
2398 description: Activation::description(self).to_string(),
2399 methods: Activation::methods(self).iter().map(|s| s.to_string()).collect(),
2400 });
2401
2402 // Include registered activations
2403 for a in self.inner.activations.values() {
2404 activations.push(ActivationInfo {
2405 namespace: a.namespace().to_string(),
2406 version: a.version().to_string(),
2407 description: a.description().to_string(),
2408 methods: a.methods().iter().map(|s| s.to_string()).collect(),
2409 });
2410 }
2411
2412 activations
2413 }
2414
2415 /// Compute hash for cache invalidation
2416 ///
2417 /// Returns the hash from the recursive plugin schema. This hash changes
2418 /// whenever any method definition or child plugin changes — and,
2419 /// PERF-21, only then: the children are listed by namespace, so every
2420 /// start of the same build computes the same hash (the `plexus_hash`
2421 /// every item carries, [`PlexusContext::init`]).
2422 pub fn compute_hash(&self) -> String {
2423 // PERF-15: from what the service describes, kept per schema generation.
2424 self.described().service.hash.clone()
2425 }
2426
2427 /// PERF-15: the service's own `hash` answer for `caller` — the caller's
2428 /// view's on a gated service (AUTH-4), the service's own otherwise —
2429 /// from the cache.
2430 fn own_hash(&self, caller: Option<&super::auth::AuthContext>) -> String {
2431 match self.inner.gate {
2432 Some(_) => self.shaped(caller).1.hash.clone(),
2433 None => self.described().service.hash.clone(),
2434 }
2435 }
2436
2437 /// PERF-15: the service's own schema as `caller` sees it — the
2438 /// `{ns}.schema` answer before its site hints — from the cache.
2439 fn own_schema(&self, caller: Option<&super::auth::AuthContext>) -> PluginSchema {
2440 match self.inner.gate {
2441 Some(_) => self.shaped(caller).1.service.clone(),
2442 None => self.described().service.clone(),
2443 }
2444 }
2445
2446 /// Route a call to the appropriate activation
2447 pub async fn route(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>) -> Result<PlexusStream, PlexusError> {
2448 self.route_with_ctx(method, params, auth, None).await
2449 }
2450
2451 /// Route a call to the appropriate activation, with optional raw HTTP request context.
2452 ///
2453 /// NEST-11: the call is routed knowing its service — the outermost
2454 /// service a call entered — so a child mounted below it
2455 /// ([`RemoteChild`](super::RemoteChild)) can take the calls its far side
2456 /// makes back under a forwarded call through this service's own routing
2457 /// and gate ([`super::service_scope`]).
2458 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> {
2459 if super::service_scope::entered() {
2460 return self.route_entered(method, params, auth, raw_ctx).await;
2461 }
2462 super::service_scope::scope(self.downgrade(), self.route_entered(method, params, auth, raw_ctx)).await
2463 }
2464
2465 /// NEST-11: a weak handle to this service — what a child mounted below
2466 /// it keeps, so a child never keeps its service alive.
2467 pub fn downgrade(&self) -> super::service_scope::WeakService {
2468 super::service_scope::WeakService::new(Arc::downgrade(&self.inner))
2469 }
2470
2471 /// NEST-11: a schema the service answers for one of its own children
2472 /// outside any call (a child asking, at its start, for the shape of what
2473 /// it will call): the service's whole description at `method` (a
2474 /// `….schema` path), as the service itself sees it — no caller's view.
2475 pub(crate) async fn schema_for_child(&self, method: &str, params: Value) -> Result<PlexusStream, PlexusError> {
2476 let (_, name) = self.parse_method(method)?;
2477 if !Self::is_schema_query(name) {
2478 return Err(PlexusError::Unauthenticated(format!(
2479 "`{method}` is not a schema: outside a call, a child asks its service only for a schema"
2480 )));
2481 }
2482 let ctx = crate::call::CallContext::admitted(None, plexus_auth_core::grants::Reach::everywhere());
2483 let routed = self.route_ungated(method, params, None, None);
2484 super::service_scope::scope(self.downgrade(), in_call(ctx, routed)).await
2485 }
2486
2487 /// [`DynamicHub::route_with_ctx`], inside its service's scope.
2488 async fn route_entered(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2489 // AUTH-2 grant gate: only when configured — a hub without one pays
2490 // this one branch and dispatches as before.
2491 if let Some(gate) = self.inner.gate.as_ref() {
2492 // AUTH-11: a sign-in that ended proves no one, on every method.
2493 let (auth, ended) = super::grant_gate::standing(gate, auth);
2494 let decide = |info| super::grant_gate::decide(gate, &self.inner.namespace, method, info, ¶ms, auth, &self.inner.signed_in_grants);
2495 let admit = match self.gate_index().methods.get(method) {
2496 Some(info) => decide(Some(info)),
2497 // NEST-5: a path through a slot is decided on the slot's
2498 // grant; a grant written as its literal path still decides
2499 // first (the slot grant is additive).
2500 None => match self.gate_info(method) {
2501 Some(slot) => decide(None).or_else(|_| decide(Some(slot))),
2502 None => decide(None),
2503 },
2504 }
2505 .map_err(|e| super::grant_gate::say_ended(e, ended.as_deref()))?;
2506 return match admit {
2507 // AUTH-4: introspection answers from the caller's view.
2508 // RETURNS-47: in a context too — the caller's reach for the
2509 // path, as the gate gives a public method's — never none.
2510 super::grant_gate::Admit::Open => {
2511 let grant = plexus_auth_core::grants::Grant::new(method.to_string());
2512 in_call(crate::call::CallContext::introspection(auth, Arc::clone(gate), grant), async {
2513 match self.introspect_in_view(method, ¶ms, auth, raw_ctx).await {
2514 Some(answer) => answer,
2515 None => self.route_ungated(method, params, auth, raw_ctx).await,
2516 }
2517 })
2518 .await
2519 }
2520 super::grant_gate::Admit::Reach(reach) => {
2521 in_call(crate::call::CallContext::admitted(auth, reach), self.route_ungated(method, params, auth, raw_ctx)).await
2522 }
2523 };
2524 }
2525 // RETURNS-47: no gate — the call is admitted everywhere, said here
2526 // rather than assumed by `current_reach` (which fails closed). A
2527 // service without a gate reached from inside a call (a nested
2528 // service, a method calling its parent) keeps that call's reach and
2529 // hop, as the task-local reach always carried through, with this
2530 // call's identity.
2531 let ctx = match crate::call::context() {
2532 Ok(outer) => outer.with_auth(auth),
2533 Err(_) => crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere()),
2534 };
2535 in_call(ctx, self.route_ungated(method, params, auth, raw_ctx)).await
2536 }
2537
2538 /// Everything [`DynamicHub::route_with_ctx`] does after the grant gate.
2539 async fn route_ungated(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2540 // R-5 scope gate (AUTHZ-CORE-1 + CORE-5). Inactive unless a
2541 // ScopeRegistry is configured or default_deny is set — a hub with
2542 // neither pays exactly this one branch and dispatches as before
2543 // the gate existed (the hard backward-safety constraint).
2544 if self.inner.scope_registry.is_some() || self.inner.default_deny {
2545 let registry = self
2546 .inner
2547 .scope_registry
2548 .as_deref()
2549 .unwrap_or_else(|| super::scope_gate::empty_registry());
2550 super::scope_gate::enforce(
2551 registry,
2552 self.inner.default_deny,
2553 &self.inner.audit_sink,
2554 method,
2555 self.gate_info(method),
2556 auth,
2557 raw_ctx.and_then(|ctx| ctx.peer.map(|peer| peer.ip())),
2558 )
2559 .await?;
2560 }
2561
2562 let (namespace, method_name) = self.parse_method(method)?;
2563
2564 // RETURNS-40 review #1: `ir`'s names, before any work
2565 if namespace == self.inner.namespace && method_name == "ir" {
2566 self.check_ir_names(¶ms, auth)?;
2567 }
2568
2569 // Handle plexus's own methods
2570 let stream = if namespace == self.inner.namespace {
2571 Activation::call(self, method_name, params, auth, raw_ctx).await?
2572 } else {
2573 let activation = self.inner.activations.get(namespace)
2574 .ok_or_else(|| PlexusError::ActivationNotFound(namespace.to_string()))?;
2575
2576 activation.call(method_name, params, auth, raw_ctx).await?
2577 };
2578
2579 // CA-1 (trak facet ccc924ad): schema responses leaving this hub get
2580 // their `requires_credential.site_hint` filled from the backend's
2581 // advertised auth capabilities. Backends that never call
2582 // `with_auth_capabilities` (or advertise anonymous-only) derive no
2583 // site, and the stream passes through untouched — byte-identical to
2584 // pre-CA-1 emissions.
2585 if Self::is_schema_query(method_name) {
2586 if let Some(site) = self.derived_site_hint() {
2587 return Ok(fill_site_hints_in_schema_stream(stream, site));
2588 }
2589 }
2590 Ok(stream)
2591 }
2592
2593 /// Whether a routed `method_name` (the part after the first dot) is a
2594 /// schema query: `"schema"` (`<ns>.schema`, with or without a `method`
2595 /// param) or a nested `"<child...>.schema"` path routed into a child
2596 /// activation.
2597 fn is_schema_query(method_name: &str) -> bool {
2598 method_name == "schema" || method_name.ends_with(".schema")
2599 }
2600
2601 /// CA-1: the [`AttachmentSite`] implied by this backend's advertised
2602 /// auth capabilities, or `None` when no capabilities are configured or
2603 /// none of the advertised mechanisms implies a site.
2604 ///
2605 /// [`AttachmentSite`]: plexus_auth_core::AttachmentSite
2606 pub fn derived_site_hint(&self) -> Option<plexus_auth_core::AttachmentSite> {
2607 self.inner
2608 .auth_capabilities
2609 .as_ref()
2610 .and_then(|caps| caps.implied_attachment_site())
2611 }
2612
2613 /// Resolve a handle using the activation registry
2614 ///
2615 /// Looks up the activation by its UUID in the registry.
2616 pub async fn do_resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
2617 let path = self.inner.registry.read().unwrap()
2618 .lookup(handle.plugin_id)
2619 .map(|s| s.to_string())
2620 .ok_or_else(|| PlexusError::ActivationNotFound(handle.plugin_id.to_string()))?;
2621
2622 let activation = self.inner.activations.get(&path)
2623 .ok_or_else(|| PlexusError::ActivationNotFound(path.clone()))?;
2624 activation.resolve_handle(handle).await
2625 }
2626
2627 /// Get activation schema
2628 pub fn get_activation_schema(&self, namespace: &str) -> Option<Schema> {
2629 self.inner.activations.get(namespace).map(|a| a.schema())
2630 }
2631
2632 /// Get a snapshot of the activation registry (safe to use outside locks)
2633 pub fn registry_snapshot(&self) -> PluginRegistrySnapshot {
2634 let guard = self.inner.registry.read().unwrap();
2635 PluginRegistrySnapshot {
2636 by_id: guard.by_id.clone(),
2637 by_path: guard.by_path.clone(),
2638 }
2639 }
2640
2641 /// Look up an activation path by its UUID
2642 pub fn lookup_plugin(&self, id: uuid::Uuid) -> Option<String> {
2643 self.inner.registry.read().unwrap().lookup(id).map(|s| s.to_string())
2644 }
2645
2646 /// Look up an activation UUID by its path
2647 pub fn lookup_plugin_by_path(&self, path: &str) -> Option<uuid::Uuid> {
2648 self.inner.registry.read().unwrap().lookup_by_path(path)
2649 }
2650
2651 /// Get activation schemas for all activations (including this hub itself)
2652 pub fn list_plugin_schemas(&self) -> Vec<PluginSchema> {
2653 let mut schemas = Vec::new();
2654
2655 // Include this hub itself
2656 schemas.push(Activation::plugin_schema(self));
2657
2658 // Include registered activations
2659 for a in self.inner.activations.values() {
2660 schemas.push(a.plugin_schema());
2661 }
2662
2663 schemas
2664 }
2665
2666 /// Deprecated: use list_plugin_schemas instead
2667 #[deprecated(note = "Use list_plugin_schemas instead")]
2668 pub fn list_full_schemas(&self) -> Vec<PluginSchema> {
2669 self.list_plugin_schemas()
2670 }
2671
2672 /// Get help for a method
2673 pub fn get_method_help(&self, method: &str) -> Option<String> {
2674 let (namespace, method_name) = self.parse_method(method).ok()?;
2675 let activation = self.inner.activations.get(namespace)?;
2676 activation.method_help(method_name)
2677 }
2678
2679 fn parse_method<'a>(&self, method: &'a str) -> Result<(&'a str, &'a str), PlexusError> {
2680 let parts: Vec<&str> = method.splitn(2, '.').collect();
2681 if parts.len() != 2 {
2682 return Err(PlexusError::InvalidParams {
2683 param: Some("method".into()),
2684 problem: ParamProblem::Malformed {
2685 detail: format!("expected `namespace.method`, got `{}`", method),
2686 },
2687 });
2688 }
2689 Ok((parts[0], parts[1]))
2690 }
2691
2692 /// Get child activation summaries: one per registered activation, in
2693 /// namespace order (PERF-21) — the service schema's `children`, which
2694 /// its `hash` and every caller's view hash digest in this order.
2695 /// Called by `#[plexus_macros::activation]` when its `hub` flag is set.
2696 pub fn plugin_children(&self) -> Vec<ChildSummary> {
2697 self.inner.activations.values()
2698 .map(|a| {
2699 let schema = a.plugin_schema();
2700 ChildSummary {
2701 namespace: schema.namespace,
2702 description: schema.description,
2703 hash: schema.hash,
2704 }
2705 })
2706 .collect()
2707 }
2708
2709 /// Convert to RPC module
2710 pub fn into_rpc_module(self) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2711 let mut module = RpcModule::new(());
2712
2713 PlexusContext::init(self.compute_hash());
2714
2715 // Register hub methods with runtime namespace using dot notation (e.g., "plexus.call" or "hub.call")
2716 // Note: we leak these strings to get 'static lifetime required by jsonrpsee
2717 let ns = self.runtime_namespace();
2718 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2719 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2720 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2721 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2722 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2723 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2724 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2725 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2726 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2727
2728 // Register {ns}.call subscription
2729 let plexus_for_call = self.clone();
2730 module.register_subscription(
2731 call_method,
2732 PLEXUS_NOTIF_METHOD,
2733 call_unsub,
2734 move |params, pending, _ctx, ext| {
2735 let plexus = plexus_for_call.clone();
2736 // AUTH-4: a gated hub reads the connection's identity (as
2737 // arc_into_rpc_module always has); a hub without a gate
2738 // dispatches anonymously here, as before.
2739 let identified = plexus.inner.gate.is_some();
2740 serve_call(plexus, params, pending, ext, ns_static, identified)
2741 }
2742 )?;
2743
2744 register_input_methods(&mut module, ns_static)?;
2745
2746 // Register {ns}.hash subscription
2747 let plexus_for_hash = self.clone();
2748 module.register_subscription(
2749 hash_method,
2750 PLEXUS_NOTIF_METHOD,
2751 hash_unsub,
2752 move |_params, pending, _ctx, ext| {
2753 let plexus = plexus_for_hash.clone();
2754 Box::pin(async move {
2755 // AUTH-4: a gated hub's hash is the caller's view's.
2756 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2757 let value = plexus.own_hash(auth);
2758 let stream = async_stream::stream! {
2759 yield HashEvent::Hash { value };
2760 };
2761 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2762 pipe_stream_to_subscription(pending, wrapped, &ext).await
2763 })
2764 }
2765 )?;
2766
2767 // Register {ns}.schema subscription
2768 let plexus_for_schema = self.clone();
2769 module.register_subscription(
2770 schema_method,
2771 PLEXUS_NOTIF_METHOD,
2772 schema_unsub,
2773 move |params, pending, _ctx, ext| {
2774 let plexus = plexus_for_schema.clone();
2775 Box::pin(async move {
2776 let p: SchemaParams = params.parse().unwrap_or_default();
2777 // AUTH-4: a gated hub answers from the caller's view.
2778 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2779 let mut plugin_schema = plexus.own_schema(auth);
2780 // CA-1: hub-derived site hints on the hub's own schema.
2781 if let Some(site) = plexus.derived_site_hint() {
2782 plugin_schema.fill_site_hints(&site);
2783 }
2784
2785 let result = if let Some(ref name) = p.method {
2786 plugin_schema.methods.iter()
2787 .find(|m| m.name == *name)
2788 .map(|m| super::SchemaResult::Method(m.clone()))
2789 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
2790 -32602,
2791 format!("Method '{}' not found", name),
2792 None::<()>,
2793 ))?
2794 } else {
2795 super::SchemaResult::Plugin(plugin_schema)
2796 };
2797
2798 let stream = async_stream::stream! { yield result; };
2799 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
2800 pipe_stream_to_subscription(pending, wrapped, &ext).await
2801 })
2802 }
2803 )?;
2804
2805 // Register _info well-known endpoint (no namespace prefix).
2806 // Returns backend name + auth_capabilities (AUTHZ-CORE-3) as a
2807 // single-item stream with automatic Done event. Backends that have not
2808 // called with_auth_capabilities get the anonymous-default fallback so
2809 // capability-aware clients can still discover the auth surface.
2810 let info_payload = build_info_payload(
2811 self.runtime_namespace(),
2812 self.inner.auth_capabilities.as_ref(),
2813 );
2814 // AUTH-4: a gated hub answers `_info` per caller; without a gate the
2815 // payload is built once, as before.
2816 let plexus_for_info = self.inner.gate.is_some().then(|| self.clone());
2817 module.register_subscription(
2818 "_info",
2819 PLEXUS_NOTIF_METHOD,
2820 "_info_unsub",
2821 move |_params, pending, _ctx, ext| {
2822 let payload = match plexus_for_info.as_ref() {
2823 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
2824 None => info_payload.clone(),
2825 };
2826 Box::pin(async move {
2827 // Create a single-item stream with the info response
2828 let info_stream = futures::stream::once(async move { payload });
2829
2830 // Wrap to auto-append Done event
2831 let wrapped = super::streaming::wrap_stream(
2832 info_stream,
2833 "_info",
2834 vec![]
2835 );
2836
2837 // Pipe to subscription (handles Done automatically)
2838 pipe_stream_to_subscription(pending, wrapped, &ext).await
2839 })
2840 }
2841 )?;
2842
2843 // Add all registered activation RPC methods — unless a grant gate
2844 // is set (AUTH-2): those direct methods carry no auth and would pass
2845 // around it, so a gated hub is reached only through `<ns>.call`.
2846 let pending = std::mem::take(&mut *self.inner.pending_rpc.lock().unwrap());
2847 if self.inner.gate.is_none() {
2848 for factory in pending {
2849 module.merge(factory())?;
2850 }
2851 }
2852
2853 // CHILD-WIRE: for each registered child router with capability bits set,
2854 // register {ns}.list_children / {ns}.search_children as subscriptions.
2855 // Per-activation namespaced (not top-level _list_children).
2856 for (ns, router) in self.inner.child_routers.iter() {
2857 register_child_capability_methods(&mut module, ns, router.clone(), self.inner.gate.clone())?;
2858 }
2859
2860 Ok(module)
2861 }
2862
2863 /// V2-57: serve one `{ns}.call` exactly as this service's own `{ns}.call`
2864 /// does: routed as the connection's caller (the `AuthContext` the upgrade
2865 /// put in `ext`), a method with an `Input` taking its input half from
2866 /// `pending` (BIDIR-6), each item piped, a dispatch error sent as an
2867 /// item. For a host that registers `{ns}.call` itself to check its own
2868 /// limits first (menger's call layer): it removes the module's
2869 /// `{ns}.call`, registers its own, and hands each call it admits here.
2870 /// Routing with [`route`](Self::route) instead runs outside the call's
2871 /// seam, so an `Input` method answers that the transport carries none.
2872 /// `ns` is the service's runtime namespace, the error items' source.
2873 pub fn serve_call(
2874 &self,
2875 params: jsonrpsee::types::Params<'static>,
2876 pending: jsonrpsee::PendingSubscriptionSink,
2877 ext: http::Extensions,
2878 ns: &'static str,
2879 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>> {
2880 serve_call(self.clone(), params, pending, ext, ns, true)
2881 }
2882
2883 /// Convert Arc<DynamicHub> to RPC module while keeping the Arc alive
2884 ///
2885 /// Unlike `into_rpc_module`, this keeps the Arc<DynamicHub> reference alive,
2886 /// which is necessary when activations hold Weak<DynamicHub> references that
2887 /// need to remain upgradeable.
2888 pub fn arc_into_rpc_module(hub: Arc<Self>) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2889 let mut module = RpcModule::new(());
2890
2891 PlexusContext::init(hub.compute_hash());
2892
2893 // Register hub methods with runtime namespace using dot notation (e.g., "plexus.call" or "hub.call")
2894 // Note: we leak these strings to get 'static lifetime required by jsonrpsee
2895 let ns = hub.runtime_namespace();
2896 let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2897 let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2898 let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2899 let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2900 let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2901 let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2902 let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2903 let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2904 let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2905
2906 // Register {ns}.call subscription - clone Arc to keep reference alive
2907 let hub_for_call = hub.clone();
2908 module.register_subscription(
2909 call_method,
2910 call_method,
2911 call_unsub,
2912 move |params, pending, _ctx, ext| {
2913 let hub = hub_for_call.clone();
2914 let hub = (*hub).clone();
2915 serve_call(hub, params, pending, ext, ns_static, true)
2916 }
2917 )?;
2918
2919 register_input_methods(&mut module, ns_static)?;
2920
2921 // Register {ns}.hash subscription
2922 let hub_for_hash = hub.clone();
2923 module.register_subscription(
2924 hash_method,
2925 PLEXUS_NOTIF_METHOD,
2926 hash_unsub,
2927 move |_params, pending, _ctx, ext| {
2928 let hub = hub_for_hash.clone();
2929 Box::pin(async move {
2930 // AUTH-4: a gated hub's hash is the caller's view's.
2931 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2932 let value = hub.own_hash(auth);
2933 let stream = async_stream::stream! {
2934 yield HashEvent::Hash { value };
2935 };
2936 let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2937 pipe_stream_to_subscription(pending, wrapped, &ext).await
2938 })
2939 }
2940 )?;
2941
2942 // Register {ns}.schema subscription
2943 let hub_for_schema = hub.clone();
2944 module.register_subscription(
2945 schema_method,
2946 PLEXUS_NOTIF_METHOD,
2947 schema_unsub,
2948 move |params, pending, _ctx, ext| {
2949 let hub = hub_for_schema.clone();
2950 Box::pin(async move {
2951 let p: SchemaParams = params.parse().unwrap_or_default();
2952 // AUTH-4: a gated hub answers from the caller's view.
2953 let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2954 let mut plugin_schema = hub.own_schema(auth);
2955 // CA-1: hub-derived site hints on the hub's own schema.
2956 if let Some(site) = hub.derived_site_hint() {
2957 plugin_schema.fill_site_hints(&site);
2958 }
2959
2960 let result = if let Some(ref name) = p.method {
2961 plugin_schema.methods.iter()
2962 .find(|m| m.name == *name)
2963 .map(|m| super::SchemaResult::Method(m.clone()))
2964 .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
2965 -32602,
2966 format!("Method '{}' not found", name),
2967 None::<()>,
2968 ))?
2969 } else {
2970 super::SchemaResult::Plugin(plugin_schema)
2971 };
2972
2973 let stream = async_stream::stream! {
2974 yield result;
2975 };
2976 let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
2977 pipe_stream_to_subscription(pending, wrapped, &ext).await
2978 })
2979 }
2980 )?;
2981
2982 // Register _info well-known endpoint (no namespace prefix).
2983 // Returns backend name + auth_capabilities (AUTHZ-CORE-3) as a
2984 // single-item stream with automatic Done event. Same payload shape as
2985 // the sibling registration in into_rpc_module.
2986 let info_payload = build_info_payload(
2987 hub.runtime_namespace(),
2988 hub.inner.auth_capabilities.as_ref(),
2989 );
2990 // AUTH-4: a gated hub answers `_info` per caller; without a gate the
2991 // payload is built once, as before.
2992 let hub_for_info = hub.inner.gate.is_some().then(|| hub.clone());
2993 module.register_subscription(
2994 "_info",
2995 PLEXUS_NOTIF_METHOD,
2996 "_info_unsub",
2997 move |_params, pending, _ctx, ext| {
2998 let payload = match hub_for_info.as_ref() {
2999 Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
3000 None => info_payload.clone(),
3001 };
3002 Box::pin(async move {
3003 // Create a single-item stream with the info response
3004 let info_stream = futures::stream::once(async move { payload });
3005
3006 // Wrap to auto-append Done event
3007 let wrapped = super::streaming::wrap_stream(
3008 info_stream,
3009 "_info",
3010 vec![]
3011 );
3012
3013 // Pipe to subscription (handles Done automatically)
3014 pipe_stream_to_subscription(pending, wrapped, &ext).await
3015 })
3016 }
3017 )?;
3018
3019 // Register pending RPC methods from activations
3020 // AUTH-2: not under a grant gate — see `into_rpc_module`.
3021 let mut pending = std::mem::take(&mut *hub.inner.pending_rpc.lock().unwrap());
3022 if hub.inner.gate.is_some() {
3023 pending.clear();
3024 }
3025 tracing::trace!(factories = pending.len(), "merging activation RPC factories");
3026 for (idx, factory) in pending.into_iter().enumerate() {
3027 tracing::trace!(factory_idx = idx, "calling factory to get Methods");
3028 let methods = factory();
3029 let method_count = methods.method_names().count();
3030 tracing::trace!(factory_idx = idx, methods = method_count, "factory returned Methods; merging into module");
3031 module.merge(methods)?;
3032 tracing::trace!(factory_idx = idx, "successfully merged factory methods");
3033 }
3034 tracing::trace!("all activations merged successfully");
3035
3036 // CHILD-WIRE: for each registered child router with capability bits set,
3037 // register {ns}.list_children / {ns}.search_children as subscriptions.
3038 for (ns, router) in hub.inner.child_routers.iter() {
3039 register_child_capability_methods(&mut module, ns, router.clone(), hub.inner.gate.clone())?;
3040 }
3041
3042 Ok(module)
3043 }
3044}
3045
3046/// CHILD-WIRE: register per-activation namespaced `<ns>.list_children` and
3047/// `<ns>.search_children` as subscription methods when the router advertises
3048/// the corresponding capability bits.
3049///
3050/// Each name returned by `ChildRouter::list_children` / `search_children` is
3051/// emitted as a `data` envelope with `content_type` set to the method name
3052/// (`"list_children"` or `"search_children"`) and `content` carrying the name
3053/// string. Termination is `done`. Mirrors the standard `wrap_stream` shape
3054/// used by every other framework subscription.
3055///
3056/// Activations that advertise neither bit produce no registrations — calling
3057/// the methods returns standard `methodNotFound`. That's the wire-level
3058/// signal that the activation doesn't support enumeration / search.
3059/// RETURNS-47: the context a `{ns}.list_children` / `{ns}.search_children`
3060/// call runs in, so a dynamic child's list or search method reads its caller
3061/// as any method does: everywhere on a service without a gate; on a gated
3062/// one the caller's reach for the method's path, asked of the gate only if
3063/// read (as an introspection call's). These methods are not decided by the
3064/// gate (a gap of their own); the context only says who is asking.
3065fn listing_context(
3066 gate: Option<&Arc<plexus_auth_core::grants::Gate>>,
3067 ext: &jsonrpsee::Extensions,
3068 method: &str,
3069) -> crate::call::CallContext {
3070 let auth = ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3071 match gate {
3072 None => crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere()),
3073 Some(gate) => {
3074 let (auth, _) = super::grant_gate::standing(gate, auth);
3075 crate::call::CallContext::introspection(auth, Arc::clone(gate), plexus_auth_core::grants::Grant::new(method.to_string()))
3076 }
3077 }
3078}
3079
3080#[allow(deprecated)] // ChildCapabilities is deprecated by IR-4 but still the wire-level signal
3081fn register_child_capability_methods(
3082 module: &mut RpcModule<()>,
3083 namespace: &str,
3084 router: Arc<dyn ChildRouter>,
3085 gate: Option<Arc<plexus_auth_core::grants::Gate>>,
3086) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3087 let caps = router.capabilities();
3088 if caps.is_empty() {
3089 return Ok(());
3090 }
3091
3092 let ns_static: &'static str = Box::leak(namespace.to_string().into_boxed_str());
3093
3094 if caps.contains(ChildCapabilities::LIST) {
3095 let list_method: &'static str =
3096 Box::leak(format!("{}.list_children", namespace).into_boxed_str());
3097 let list_unsub: &'static str =
3098 Box::leak(format!("{}.list_children_unsub", namespace).into_boxed_str());
3099 let router_for_list = router.clone();
3100 let gate_for_list = gate.clone();
3101 module.register_subscription(
3102 list_method,
3103 PLEXUS_NOTIF_METHOD,
3104 list_unsub,
3105 move |_params, pending, _ctx, ext| {
3106 let router = router_for_list.clone();
3107 let ctx = listing_context(gate_for_list.as_ref(), &ext, list_method);
3108 Box::pin(async move {
3109 // Collect names eagerly so the BoxStream's borrow on the
3110 // router doesn't outlive list_children's call. For v1 this
3111 // matches the typical pattern (small finite child sets like
3112 // Solar's eight planets). A future variant could keep the
3113 // Arc-borrow alive across the stream by binding the BoxStream
3114 // to the Arc directly — out of scope here.
3115 let collected: Vec<String> = crate::call::scope(ctx, async {
3116 match router.list_children().await {
3117 Some(mut s) => {
3118 use futures::StreamExt;
3119 let mut acc = Vec::new();
3120 while let Some(name) = s.next().await {
3121 acc.push(name);
3122 }
3123 acc
3124 }
3125 None => Vec::new(),
3126 }
3127 })
3128 .await;
3129 let stream = async_stream::stream! {
3130 for name in collected {
3131 yield name;
3132 }
3133 };
3134 let wrapped = super::streaming::wrap_stream(
3135 stream,
3136 "list_children",
3137 vec![ns_static.into()],
3138 );
3139 pipe_stream_to_subscription(pending, wrapped, &ext).await
3140 })
3141 },
3142 )?;
3143 }
3144
3145 if caps.contains(ChildCapabilities::SEARCH) {
3146 let search_method: &'static str =
3147 Box::leak(format!("{}.search_children", namespace).into_boxed_str());
3148 let search_unsub: &'static str =
3149 Box::leak(format!("{}.search_children_unsub", namespace).into_boxed_str());
3150 let router_for_search = router.clone();
3151 let gate_for_search = gate.clone();
3152 module.register_subscription(
3153 search_method,
3154 PLEXUS_NOTIF_METHOD,
3155 search_unsub,
3156 move |params, pending, _ctx, ext| {
3157 let router = router_for_search.clone();
3158 let ctx = listing_context(gate_for_search.as_ref(), &ext, search_method);
3159 Box::pin(async move {
3160 let p: SearchChildrenParams = params.parse()?;
3161 let collected: Vec<String> = crate::call::scope(ctx, async {
3162 match router.search_children(&p.query).await {
3163 Some(mut s) => {
3164 use futures::StreamExt;
3165 let mut acc = Vec::new();
3166 while let Some(name) = s.next().await {
3167 acc.push(name);
3168 }
3169 acc
3170 }
3171 None => Vec::new(),
3172 }
3173 })
3174 .await;
3175 let stream = async_stream::stream! {
3176 for name in collected {
3177 yield name;
3178 }
3179 };
3180 let wrapped = super::streaming::wrap_stream(
3181 stream,
3182 "search_children",
3183 vec![ns_static.into()],
3184 );
3185 pipe_stream_to_subscription(pending, wrapped, &ext).await
3186 })
3187 },
3188 )?;
3189 }
3190
3191 Ok(())
3192}
3193
3194/// Params for `<ns>.search_children`
3195#[derive(Debug, serde::Deserialize)]
3196struct SearchChildrenParams {
3197 query: String,
3198}
3199
3200/// Params for {ns}.call
3201#[derive(Debug, serde::Deserialize)]
3202pub(crate) struct CallParams {
3203 pub(crate) method: String,
3204 #[serde(default)]
3205 pub(crate) params: Option<Value>,
3206}
3207
3208/// BIDIR-6: [`DynamicHub::input_terms`]' answer.
3209pub(crate) struct InputTerms {
3210 pub(crate) grant: String,
3211 pub(crate) targets: Vec<String>,
3212 pub(crate) recheck: bool,
3213}
3214
3215/// Params for {ns}.schema (SYNAPSE-CC-9: the published type)
3216use super::schema::SchemaParams;
3217
3218/// `{ns}.call`: route the call, then pipe what it answers.
3219///
3220/// The call's future is boxed here, and is its one allocation of that size,
3221/// so it is chosen before it is made: a method the service knows has no
3222/// `Input` is routed and piped as it was before BIDIR-6,
3223/// holding nothing of the input half (the seam inline in one future for both
3224/// was 1,024 bytes more a call, and the params kept beside it 176 more);
3225/// any other ([`DynamicHub::may_take_input`]) is [`serve_seamed`]. A
3226/// dispatch error is sent as a stream item on the
3227/// accepted subscription: this preserves its message and code, where
3228/// returning it from a subscription handler has jsonrpsee wrap it as generic
3229/// -32603.
3230fn serve_call(
3231 service: DynamicHub,
3232 params: jsonrpsee::types::Params<'static>,
3233 pending: jsonrpsee::PendingSubscriptionSink,
3234 ext: http::Extensions,
3235 ns: &'static str,
3236 identified: bool,
3237) -> CallFuture {
3238 // Read here, not in the future: the choice of future is made on it, and
3239 // the plain one then holds neither the params' text nor the method name.
3240 let call: CallParams = match params.parse() {
3241 Ok(call) => call,
3242 Err(e) => return Box::pin(async move { Err(e.into()) }),
3243 };
3244 if service.may_take_input(&call.method) {
3245 return Box::pin(serve_seamed(service, call, params, pending, ext, ns, identified));
3246 }
3247 let CallParams { method, params: args } = call;
3248 Box::pin(async move {
3249 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref()) } else { None };
3250 match service.route(&method, args.unwrap_or_default(), caller).await {
3251 Ok(stream) => pipe_stream_to_subscription(pending, stream, &ext).await,
3252 Err(e) => {
3253 let sink = pending.accept().await?;
3254 if let Some(raw) = error_item_raw(ns, &e) {
3255 let _ = sink.send(raw).await;
3256 }
3257 Ok(())
3258 }
3259 }
3260 })
3261}
3262
3263/// A `{ns}.call`'s future, boxed: one allocation a call, the size of the
3264/// path it takes.
3265type CallFuture = std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>>;
3266
3267/// [`serve_call`] for a method that may take an `Input`: the route runs
3268/// inside [`super::input::CALL`], holding the unaccepted subscription and the
3269/// extensions, and a method with an `Input` parameter takes them there
3270/// (BIDIR-6); one without leaves them.
3271async fn serve_seamed(
3272 service: DynamicHub,
3273 call: CallParams,
3274 params: jsonrpsee::types::Params<'static>,
3275 pending: jsonrpsee::PendingSubscriptionSink,
3276 ext: http::Extensions,
3277 ns: &'static str,
3278 identified: bool,
3279) -> jsonrpsee::core::SubscriptionResult {
3280 let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().cloned() } else { None };
3281 let seen = service.inner.gate.as_ref().map_or(0, |g| g.generation().current());
3282 let opened = Arc::new(std::sync::Mutex::new(None::<super::input::Opened>));
3283 let take = || opened.lock().unwrap_or_else(|e| e.into_inner()).take();
3284 let mut scoped = std::pin::pin!(super::input::CALL.scope(
3285 std::cell::RefCell::new(super::input::Seam { service: service.clone(), params, pending: Some(pending), ext, seen, opened: opened.clone(), refused: None }),
3286 service.route(&call.method, call.params.unwrap_or_default(), caller.as_deref()),
3287 ));
3288 // The route runs until it answers, or until the method has opened its
3289 // input half: a handler may read its input before it returns its stream,
3290 // so from the open the pipe runs (credit, items, cancel) beside the
3291 // route still resolving.
3292 let answered = std::future::poll_fn(|cx| match std::future::Future::poll(scoped.as_mut(), cx) {
3293 std::task::Poll::Ready(answer) => std::task::Poll::Ready(Some(answer)),
3294 std::task::Poll::Pending if opened.lock().unwrap_or_else(|e| e.into_inner()).is_some() => std::task::Poll::Ready(None),
3295 std::task::Poll::Pending => std::task::Poll::Pending,
3296 })
3297 .await;
3298 let Some(answer) = answered else {
3299 let super::input::Opened { sink, duplex } = take().expect("opened, the route still resolving");
3300 let mut routing = std::pin::pin!(async { scoped.as_mut().await.map_err(|e| error_item(ns, &e)) });
3301 return Box::pin(super::wire::pipe_duplex(sink, super::wire::Output::Routing(routing.as_mut()), duplex)).await;
3302 };
3303 let super::input::Seam { pending, ext, refused, .. } = scoped.as_mut().take_value().expect("the scope ran to its end").into_inner();
3304 match (answer, take()) {
3305 // Boxed: a call with no input half does not carry its room.
3306 (Ok(stream), Some(opened)) => Box::pin(super::wire::pipe_duplex(opened.sink, super::wire::Output::Ready(stream), opened.duplex)).await,
3307 (Ok(stream), None) => {
3308 let pending = pending.expect("only an open takes it, and an open is `opened`");
3309 pipe_stream_to_subscription(pending, stream, &ext).await
3310 }
3311 (Err(e), opened) => {
3312 let sink = match (opened, pending) {
3313 (Some(opened), _) => opened.sink,
3314 (None, Some(pending)) => pending.accept().await?,
3315 (None, None) => return Ok(()),
3316 };
3317 let raw = match refused {
3318 Some(item) => serde_json::value::to_raw_value(&item).ok(),
3319 None => error_item_raw(ns, &e),
3320 };
3321 if let Some(raw) = raw {
3322 let _ = sink.send(raw).await;
3323 }
3324 Ok(())
3325 }
3326 }
3327}
3328
3329/// BIDIR-6: `{ns}.input` and `{ns}.end` in the method table, for a client
3330/// that sends them as requests and wants an answer (`true`: it reached the
3331/// call; `false`: a resend, or the half has closed). The notification, which
3332/// is what a client normally sends, is taken on the socket's reader before
3333/// the table. Sync methods, so a request is run in place, in order.
3334fn register_input_methods(module: &mut RpcModule<()>, ns: &'static str) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3335 use super::input::{Delivered, InputTable};
3336 use jsonrpsee::types::ErrorObjectOwned;
3337
3338 fn answer(delivered: Delivered) -> Result<bool, ErrorObjectOwned> {
3339 match delivered {
3340 Delivered::Taken => Ok(true),
3341 Delivered::Dropped | Delivered::Refused => Ok(false),
3342 Delivered::NotThisCall => Err(ErrorObjectOwned::owned(
3343 -32003,
3344 "not_this_call: input comes from the connection that opened the call",
3345 Some(serde_json::json!({"error_kind": "not_this_call"})),
3346 )),
3347 Delivered::Malformed => Err(ErrorObjectOwned::owned(-32602, "invalid params: subscription, seq and items", None::<()>)),
3348 }
3349 }
3350 fn table(ext: &http::Extensions) -> Result<&Arc<InputTable>, ErrorObjectOwned> {
3351 ext.get::<super::wire::FrameSink>()
3352 .and_then(super::wire::FrameSink::inputs)
3353 .ok_or_else(|| ErrorObjectOwned::owned(-32601, "this transport carries no input half: call over a WebSocket", None::<()>))
3354 }
3355
3356 let input_method: &'static str = Box::leak(format!("{ns}.input").into_boxed_str());
3357 let end_method: &'static str = Box::leak(format!("{ns}.end").into_boxed_str());
3358 module.register_method(input_method, move |params, _ctx, ext| {
3359 let frame = bytes::Bytes::copy_from_slice(params.as_str().unwrap_or("null").as_bytes());
3360 answer(table(ext)?.input(ns, &frame, &frame))
3361 })?;
3362 module.register_method(end_method, move |params, _ctx, ext| answer(table(ext)?.end(ns, params.as_str().unwrap_or("null").as_bytes())))?;
3363 Ok(())
3364}
3365
3366/// Pipe a call's stream to its subscription: accept it, then
3367/// [`super::wire::pipe`] — each item encoded once and written as one frame
3368/// (PERF-7), on the transport's own frames when the call's extensions
3369/// carry them.
3370///
3371/// Notifications are sent with the `notif_method_name` each
3372/// `register_subscription` call set.
3373///
3374/// The pipe watches the sink's close (an unsubscribe, a lost socket),
3375/// dropping the stream at once.
3376async fn pipe_stream_to_subscription(
3377 pending: jsonrpsee::PendingSubscriptionSink,
3378 stream: PlexusStream,
3379 ext: &http::Extensions,
3380) -> jsonrpsee::core::SubscriptionResult {
3381 let sink = pending.accept().await?;
3382 super::wire::pipe(sink, stream, ext).await
3383}
3384
3385// ============================================================================
3386// DynamicHub RPC Methods (via plexus-macros)
3387// ============================================================================
3388
3389#[plexus_macros::activation(
3390 namespace = "plexus",
3391 version = "1.0.0",
3392 description = "Central routing and introspection",
3393 hub,
3394 namespace_fn = "runtime_namespace"
3395)]
3396#[allow(deprecated)]
3397impl DynamicHub {
3398 /// Route a call to a registered activation
3399 #[plexus_macros::method(
3400 description = "Route a call to a registered activation",
3401 params(
3402 method = "The method to call (format: namespace.method)",
3403 params = "Parameters to pass to the method (optional, defaults to {})"
3404 )
3405 )]
3406 async fn call(
3407 &self,
3408 method: String,
3409 params: Option<Value>,
3410 ) -> impl Stream<Item = super::types::PlexusStreamItem> + Send + 'static {
3411 use super::context::PlexusContext;
3412 use super::types::{PlexusStreamItem, StreamMetadata};
3413
3414 let result = self.route(&method, params.unwrap_or_default(), None).await;
3415
3416 match result {
3417 Ok(plexus_stream) => {
3418 // Forward the routed stream directly - it already contains PlexusStreamItems
3419 plexus_stream
3420 }
3421 Err(e) => {
3422 // Return error as a PlexusStreamItem stream
3423 let metadata = StreamMetadata::new(
3424 vec![self.inner.namespace.clone()],
3425 PlexusContext::hash(),
3426 );
3427 Box::pin(futures::stream::once(async move {
3428 PlexusStreamItem::from_plexus_error(metadata, &e, false)
3429 }))
3430 }
3431 }
3432 }
3433
3434 /// Get Plexus RPC server configuration hash (from the recursive schema)
3435 ///
3436 /// This hash changes whenever any method or child activation changes.
3437 /// It's computed from the method hashes rolled up through the schema tree.
3438 #[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.")]
3439 async fn hash(&self) -> impl Stream<Item = HashEvent> + Send + 'static {
3440 let schema = Activation::plugin_schema(self);
3441 stream! { yield HashEvent::Hash { value: schema.hash }; }
3442 }
3443
3444 /// Get plugin hashes for cache validation (lightweight alternative to full schema)
3445 #[plexus_macros::method(description = "Get plugin hashes for cache validation")]
3446 #[allow(deprecated)]
3447 async fn hashes(&self) -> impl Stream<Item = PluginHashes> + Send + 'static {
3448 let schema = Activation::plugin_schema(self);
3449
3450 stream! {
3451 yield PluginHashes {
3452 namespace: schema.namespace.clone(),
3453 self_hash: schema.self_hash.clone(),
3454 children_hash: schema.children_hash.clone(),
3455 hash: schema.hash.clone(),
3456 children: schema.children.as_ref().map(|kids| {
3457 kids.iter()
3458 .map(|c| ChildHashes {
3459 namespace: c.namespace.clone(),
3460 hash: c.hash.clone(),
3461 })
3462 .collect()
3463 }),
3464 };
3465 }
3466 }
3467
3468 /// RETURNS-40: the service's IR — IR 3.0, every type once and each
3469 /// method referring to them — of the namespaces asked (none: the whole
3470 /// service), as the caller sees the service. The one way to ask for
3471 /// several schemas; `<ns>.schema` answers one. Equal to what synapse
3472 /// builds from the same raw schemas.
3473 #[plexus_macros::method(
3474 description = "The service's IR (3.0): every type once, each method referring to them — of the namespaces asked, or the whole service",
3475 params(namespaces = "The namespaces (dotted paths) to describe; none: the whole service")
3476 )]
3477 async fn ir(
3478 &self,
3479 auth: Option<&super::auth::AuthContext>,
3480 namespaces: Option<Vec<String>>,
3481 ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
3482 self.service_ir(&namespaces.unwrap_or_default(), auth).await
3483 }
3484
3485 // Note: schema() method is auto-generated by hub-macro for all activations
3486}
3487
3488// ============================================================================
3489// HubContext Implementation for Weak<DynamicHub>
3490// ============================================================================
3491
3492use super::hub_context::HubContext;
3493use std::sync::Weak;
3494
3495/// HubContext implementation for Weak<DynamicHub>
3496///
3497/// This enables activations to receive a weak reference to their parent DynamicHub,
3498/// allowing them to resolve handles and route calls through the hub without
3499/// creating reference cycles.
3500#[async_trait]
3501impl HubContext for Weak<DynamicHub> {
3502 async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
3503 let hub = self.upgrade().ok_or_else(|| {
3504 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3505 })?;
3506 hub.do_resolve_handle(handle).await
3507 }
3508
3509 async fn call(&self, method: &str, params: serde_json::Value) -> Result<PlexusStream, PlexusError> {
3510 let hub = self.upgrade().ok_or_else(|| {
3511 PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3512 })?;
3513 hub.route(method, params, None).await
3514 }
3515
3516 fn is_valid(&self) -> bool {
3517 self.upgrade().is_some()
3518 }
3519}
3520
3521/// ChildRouter implementation for DynamicHub
3522///
3523/// This enables nested routing through registered activations.
3524/// e.g., hub.call("solar.mercury.info") routes to solar → mercury → info
3525#[async_trait]
3526impl ChildRouter for DynamicHub {
3527 fn router_namespace(&self) -> &str {
3528 &self.inner.namespace
3529 }
3530
3531 async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
3532 // DynamicHub routes via its registered activations
3533 // Method format: "activation.method" or "activation.child.method"
3534 self.route_with_ctx(method, params, auth, raw_ctx).await
3535 }
3536
3537 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3538 // Look up registered activations that implement ChildRouter
3539 self.inner.child_routers.get(name)
3540 .map(|router| {
3541 // Clone the Arc and wrap in Box for the trait object
3542 Box::new(ArcChildRouter(router.clone())) as Box<dyn ChildRouter>
3543 })
3544 }
3545
3546 /// AUTHLANG-3 — consult the hub's
3547 /// [`ForwardPolicyRegistry`](super::forward_registry::ForwardPolicyRegistry).
3548 fn forward_policy_for(
3549 &self,
3550 callee_ns: &str,
3551 ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
3552 self.inner.forward_policies.get(callee_ns)
3553 }
3554
3555 // `framework_stamped_principal` retains the trait default
3556 // (`Principal::Anonymous`) for now. AUTHLANG-3 wires the dispatch path
3557 // to read this; populating it with the per-connection stamp lands
3558 // when the principal-minting service (post-AUTHZ-0 / future
3559 // CRED-CORE) is wired into the WS upgrade path. The current
3560 // anonymous return value is correct under today's no-auth substrate.
3561}
3562
3563#[cfg(test)]
3564#[allow(deprecated)]
3565mod tests {
3566 use super::*;
3567
3568 #[test]
3569 fn dynamic_hub_implements_activation() {
3570 fn assert_activation<T: Activation>() {}
3571 assert_activation::<DynamicHub>();
3572 }
3573
3574 #[test]
3575 fn dynamic_hub_methods() {
3576 let hub = DynamicHub::new("test");
3577 let methods = hub.methods();
3578 assert!(methods.contains(&"call"));
3579 assert!(methods.contains(&"hash"));
3580 assert!(methods.contains(&"schema"));
3581 // list_activations was removed - use schema() instead
3582 }
3583
3584 #[test]
3585 fn dynamic_hub_hash_stable() {
3586 let h1 = DynamicHub::new("test");
3587 let h2 = DynamicHub::new("test");
3588 assert_eq!(h1.compute_hash(), h2.compute_hash());
3589 }
3590
3591 #[test]
3592 fn dynamic_hub_is_hub() {
3593 use crate::activations::health::Health;
3594 let hub = DynamicHub::new("test").register(Health::new());
3595 let schema = hub.plugin_schema();
3596
3597 // DynamicHub should be a hub (has children)
3598 assert!(schema.is_hub(), "dynamic hub should be a hub");
3599 assert!(!schema.is_leaf(), "dynamic hub should not be a leaf");
3600
3601 // Should have children (as summaries)
3602 let children = schema.children.expect("dynamic hub should have children");
3603 assert!(!children.is_empty(), "dynamic hub should have at least one child");
3604
3605 // Health should be in the children summaries
3606 let health = children.iter().find(|c| c.namespace == "health").expect("should have health child");
3607 assert!(!health.hash.is_empty(), "health should have a hash");
3608 }
3609
3610 /// Z2H-8 / HOSTLESS-3 — a hub root that shares its name with a registered
3611 /// activation's namespace is rejected loudly at registration time instead
3612 /// of producing a silently unreachable child (the shipped echo example's
3613 /// exact failure shape).
3614 #[test]
3615 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3616 fn dynamic_hub_rejects_root_namespace_shadow() {
3617 use crate::activations::health::Health;
3618 let _hub = DynamicHub::new("health").register(Health::new());
3619 }
3620
3621 /// Z2H-8 / HOSTLESS-3 — the deprecated register_hub path enforces the
3622 /// same collision contract.
3623 #[test]
3624 #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3625 fn dynamic_hub_register_hub_rejects_root_namespace_shadow() {
3626 use crate::activations::health::Health;
3627 let _hub = DynamicHub::new("health").register_hub(Health::new());
3628 }
3629
3630 /// Z2H-8 — the shadow error names both colliding strings and suggests the
3631 /// fix (rename the hub root), so the failure is actionable without
3632 /// reading plexus-core source.
3633 #[test]
3634 fn dynamic_hub_shadow_error_names_collision_and_fix() {
3635 use crate::activations::health::Health;
3636 let result = std::panic::catch_unwind(|| {
3637 let _hub = DynamicHub::new("health").register(Health::new());
3638 });
3639 let err = result.expect_err("shadow registration must panic");
3640 let msg = err
3641 .downcast_ref::<String>()
3642 .cloned()
3643 .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
3644 .expect("panic payload should be a string");
3645 assert!(msg.contains("'health'"), "must name the colliding namespace: {msg}");
3646 assert!(msg.contains("hub root namespace"), "must name the root side: {msg}");
3647 assert!(msg.contains("rename the hub root"), "must suggest the fix: {msg}");
3648 assert!(msg.contains("Z2H-8"), "must cite the ticket: {msg}");
3649 }
3650
3651 /// Z2H-8 — non-colliding registration is unaffected by shadow detection:
3652 /// the child registers, routes, and appears in the schema.
3653 #[test]
3654 fn dynamic_hub_non_colliding_registration_unaffected() {
3655 use crate::activations::health::Health;
3656 let hub = DynamicHub::new("health_hub").register(Health::new());
3657 assert_eq!(hub.runtime_namespace(), "health_hub");
3658 let schema = hub.plugin_schema();
3659 let children = schema.children.expect("hub should have children");
3660 assert!(
3661 children.iter().any(|c| c.namespace == "health"),
3662 "health child must be registered"
3663 );
3664 assert!(hub.list_methods().iter().any(|m| m.starts_with("health.")));
3665 }
3666
3667 #[test]
3668 fn dynamic_hub_schema_structure() {
3669 use crate::activations::health::Health;
3670 let hub = DynamicHub::new("test").register(Health::new());
3671 let schema = hub.plugin_schema();
3672
3673 // Pretty print the schema
3674 let json = serde_json::to_string_pretty(&schema).unwrap();
3675 println!("DynamicHub schema:\n{}", json);
3676
3677 // Verify structure
3678 assert_eq!(schema.namespace, "test");
3679 assert!(schema.methods.iter().any(|m| m.name == "call"));
3680 assert!(schema.children.is_some());
3681 }
3682
3683 // ========================================================================
3684 // INVARIANT: Handle routing - resolves to correct plugin
3685 // ========================================================================
3686
3687 #[tokio::test]
3688 async fn invariant_resolve_handle_unknown_activation() {
3689 use crate::activations::health::Health;
3690 use crate::types::Handle;
3691 use uuid::Uuid;
3692
3693 let hub = DynamicHub::new("test").register(Health::new());
3694
3695 // Handle for an unregistered activation (random UUID)
3696 let unknown_plugin_id = Uuid::new_v4();
3697 let handle = Handle::new(unknown_plugin_id, "1.0.0", "some_method");
3698
3699 let result = hub.do_resolve_handle(&handle).await;
3700
3701 match result {
3702 Err(PlexusError::ActivationNotFound(_)) => {
3703 // Expected - activation not found
3704 }
3705 Err(other) => panic!("Expected ActivationNotFound, got {:?}", other),
3706 Ok(_) => panic!("Expected error for unknown activation"),
3707 }
3708 }
3709
3710 #[tokio::test]
3711 async fn invariant_resolve_handle_unsupported() {
3712 use crate::activations::health::Health;
3713 use crate::types::Handle;
3714
3715 let hub = DynamicHub::new("test").register(Health::new());
3716
3717 // Handle for health activation (which doesn't support handle resolution)
3718 let handle = Handle::new(Health::PLUGIN_ID, "1.0.0", "check");
3719
3720 let result = hub.do_resolve_handle(&handle).await;
3721
3722 match result {
3723 Err(PlexusError::HandleNotSupported(name)) => {
3724 assert_eq!(name, "health");
3725 }
3726 Err(other) => panic!("Expected HandleNotSupported, got {:?}", other),
3727 Ok(_) => panic!("Expected error for unsupported handle"),
3728 }
3729 }
3730
3731 #[tokio::test]
3732 async fn invariant_resolve_handle_routes_by_plugin_id() {
3733 use crate::activations::health::Health;
3734 use crate::activations::echo::EchoActivation;
3735 use crate::types::Handle;
3736 use uuid::Uuid;
3737
3738 let health = Health::new();
3739 let echo = EchoActivation::new();
3740 let health_plugin_id = health.plugin_id();
3741 let echo_plugin_id = echo.plugin_id();
3742
3743 let hub = DynamicHub::new("test")
3744 .register(health)
3745 .register(echo);
3746
3747 // Health handle → health activation
3748 let health_handle = Handle::new(health_plugin_id, "1.0.0", "check");
3749 match hub.do_resolve_handle(&health_handle).await {
3750 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "health"),
3751 Err(other) => panic!("health handle should route to health activation, got {:?}", other),
3752 Ok(_) => panic!("health handle should return HandleNotSupported"),
3753 }
3754
3755 // Echo handle → echo activation
3756 let echo_handle = Handle::new(echo_plugin_id, "1.0.0", "echo");
3757 match hub.do_resolve_handle(&echo_handle).await {
3758 Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "echo"),
3759 Err(other) => panic!("echo handle should route to echo activation, got {:?}", other),
3760 Ok(_) => panic!("echo handle should return HandleNotSupported"),
3761 }
3762
3763 // Unknown handle → ActivationNotFound (random UUID not registered)
3764 let unknown_handle = Handle::new(Uuid::new_v4(), "1.0.0", "method");
3765 match hub.do_resolve_handle(&unknown_handle).await {
3766 Err(PlexusError::ActivationNotFound(_)) => { /* expected */ },
3767 Err(other) => panic!("unknown handle should return ActivationNotFound, got {:?}", other),
3768 Ok(_) => panic!("unknown handle should return ActivationNotFound"),
3769 }
3770 }
3771
3772 #[test]
3773 fn invariant_handle_plugin_id_determines_routing() {
3774 use crate::activations::health::Health;
3775 use crate::activations::echo::EchoActivation;
3776 use crate::types::Handle;
3777
3778 let health = Health::new();
3779 let echo = EchoActivation::new();
3780
3781 // Same meta, different activations → different routing targets (by plugin_id)
3782 let health_handle = Handle::new(health.plugin_id(), "1.0.0", "check")
3783 .with_meta(vec!["msg-123".into(), "user".into()]);
3784 let echo_handle = Handle::new(echo.plugin_id(), "1.0.0", "echo")
3785 .with_meta(vec!["msg-123".into(), "user".into()]);
3786
3787 // Different plugin_ids ensure different routing
3788 assert_ne!(health_handle.plugin_id, echo_handle.plugin_id);
3789 }
3790
3791 // ========================================================================
3792 // Plugin Registry Tests
3793 // ========================================================================
3794
3795 #[test]
3796 fn plugin_registry_basic_operations() {
3797 let mut registry = PluginRegistry::new();
3798 let id = uuid::Uuid::new_v4();
3799
3800 // Register an activation
3801 registry.register(id, "test_plugin".to_string(), "test".to_string());
3802
3803 // Lookup by ID
3804 assert_eq!(registry.lookup(id), Some("test_plugin"));
3805
3806 // Lookup by path
3807 assert_eq!(registry.lookup_by_path("test_plugin"), Some(id));
3808
3809 // Get entry
3810 let entry = registry.get(id).expect("should have entry");
3811 assert_eq!(entry.path, "test_plugin");
3812 assert_eq!(entry.plugin_type, "test");
3813 }
3814
3815 #[test]
3816 fn plugin_registry_populated_on_register() {
3817 use crate::activations::health::Health;
3818
3819 let hub = DynamicHub::new("test").register(Health::new());
3820
3821 let registry = hub.registry();
3822 assert!(!registry.is_empty(), "registry should not be empty after registration");
3823
3824 // Health activation should be registered
3825 let health_id = registry.lookup_by_path("health");
3826 assert!(health_id.is_some(), "health should be registered by path");
3827
3828 // Should be able to look up path by ID
3829 let health_uuid = health_id.unwrap();
3830 assert_eq!(registry.lookup(health_uuid), Some("health"));
3831 }
3832
3833 #[test]
3834 fn plugin_registry_deterministic_uuid() {
3835 use crate::activations::health::Health;
3836
3837 // Same activation registered twice should produce same UUID
3838 let health1 = Health::new();
3839 let health2 = Health::new();
3840
3841 assert_eq!(health1.plugin_id(), health2.plugin_id(),
3842 "same activation type should have deterministic UUID");
3843
3844 // UUID should be based on namespace+major_version (semver compatibility)
3845 let expected = uuid::Uuid::new_v5(
3846 &uuid::Uuid::NAMESPACE_OID,
3847 b"health@1"
3848 );
3849 assert_eq!(health1.plugin_id(), expected,
3850 "plugin_id should be deterministic from namespace@major_version");
3851 }
3852
3853 // ========================================================================
3854 // CHILD-2: ChildRouter capabilities + opt-in list/search
3855 // ========================================================================
3856
3857 /// A minimal `ChildRouter` that overrides only the required methods.
3858 /// Exercises default implementations of `capabilities`, `list_children`
3859 /// and `search_children`.
3860 struct MinimalRouter;
3861
3862 #[async_trait]
3863 impl ChildRouter for MinimalRouter {
3864 fn router_namespace(&self) -> &str {
3865 "minimal"
3866 }
3867
3868 async fn router_call(
3869 &self,
3870 _method: &str,
3871 _params: Value,
3872 _auth: Option<&super::super::auth::AuthContext>,
3873 _raw_ctx: Option<&crate::request::RawRequestContext>,
3874 ) -> Result<PlexusStream, PlexusError> {
3875 Err(PlexusError::MethodNotFound {
3876 activation: "minimal".into(),
3877 method: "none".into(),
3878 })
3879 }
3880
3881 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
3882 None
3883 }
3884 }
3885
3886 #[tokio::test]
3887 async fn child_router_defaults_report_no_capabilities_and_none_streams() {
3888 let router = MinimalRouter;
3889
3890 assert_eq!(
3891 router.capabilities(),
3892 ChildCapabilities::empty(),
3893 "default capabilities should be empty"
3894 );
3895 assert!(
3896 router.list_children().await.is_none(),
3897 "default list_children should be None"
3898 );
3899 assert!(
3900 router.search_children("anything").await.is_none(),
3901 "default search_children should be None"
3902 );
3903 }
3904
3905 /// A `ChildRouter` that opts in to both LIST and SEARCH.
3906 struct ListingRouter {
3907 names: Vec<String>,
3908 }
3909
3910 #[async_trait]
3911 impl ChildRouter for ListingRouter {
3912 fn router_namespace(&self) -> &str {
3913 "listing"
3914 }
3915
3916 async fn router_call(
3917 &self,
3918 _method: &str,
3919 _params: Value,
3920 _auth: Option<&super::super::auth::AuthContext>,
3921 _raw_ctx: Option<&crate::request::RawRequestContext>,
3922 ) -> Result<PlexusStream, PlexusError> {
3923 Err(PlexusError::MethodNotFound {
3924 activation: "listing".into(),
3925 method: "none".into(),
3926 })
3927 }
3928
3929 async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3930 if self.names.iter().any(|n| n == name) {
3931 // Return the same type to keep the test simple; we only care
3932 // that the override compiles and is reachable.
3933 Some(Box::new(ListingRouter { names: vec![] }))
3934 } else {
3935 None
3936 }
3937 }
3938
3939 fn capabilities(&self) -> ChildCapabilities {
3940 ChildCapabilities::LIST | ChildCapabilities::SEARCH
3941 }
3942
3943 async fn list_children(&self) -> Option<BoxStream<'_, String>> {
3944 let stream = futures::stream::iter(self.names.iter().cloned());
3945 Some(Box::pin(stream))
3946 }
3947
3948 async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
3949 let q = query.to_string();
3950 let stream = futures::stream::iter(
3951 self.names
3952 .iter()
3953 .filter(move |n| n.contains(&q))
3954 .cloned()
3955 .collect::<Vec<_>>(),
3956 );
3957 Some(Box::pin(stream))
3958 }
3959 }
3960
3961 #[tokio::test]
3962 async fn child_router_overrides_report_capabilities_and_yield_streams() {
3963 use futures::StreamExt;
3964
3965 let router = ListingRouter {
3966 names: vec!["alpha".into(), "beta".into(), "alphabet".into()],
3967 };
3968
3969 // Capabilities
3970 let caps = router.capabilities();
3971 assert!(caps.contains(ChildCapabilities::LIST));
3972 assert!(caps.contains(ChildCapabilities::SEARCH));
3973 assert_eq!(caps, ChildCapabilities::LIST | ChildCapabilities::SEARCH);
3974
3975 // list_children yields the full, non-empty, finite sequence.
3976 let list_stream = router
3977 .list_children()
3978 .await
3979 .expect("LIST capability set — expected Some(stream)");
3980 let listed: Vec<String> = list_stream.collect().await;
3981 assert_eq!(listed, vec!["alpha".to_string(), "beta".into(), "alphabet".into()]);
3982
3983 // search_children filters by the query string.
3984 let search_stream = router
3985 .search_children("alpha")
3986 .await
3987 .expect("SEARCH capability set — expected Some(stream)");
3988 let matched: Vec<String> = search_stream.collect().await;
3989 assert_eq!(matched, vec!["alpha".to_string(), "alphabet".into()]);
3990 }
3991
3992 // ========================================================================
3993 // CHILD-WIRE: per-activation namespaced wire exposure for
3994 // <ns>.list_children / <ns>.search_children
3995 //
3996 // These tests exercise `register_child_capability_methods` directly with
3997 // hand-built fixtures, then drive the resulting RpcModule through the
3998 // in-process subscription path. Mirrors the existing
3999 // `auth_capabilities_info` integration pattern but verifies the
4000 // child-router wire registration instead of the _info payload.
4001 // ========================================================================
4002
4003 /// Like `EnumerableRouter` above but with configurable capability bits +
4004 /// a fixed name set. Used to drive CHILD-WIRE registration through
4005 /// different capability combinations.
4006 struct WireFixture {
4007 names: Vec<String>,
4008 caps: ChildCapabilities,
4009 }
4010
4011 #[async_trait]
4012 impl ChildRouter for WireFixture {
4013 fn router_namespace(&self) -> &str {
4014 "wirefixture"
4015 }
4016 async fn router_call(
4017 &self,
4018 _method: &str,
4019 _params: Value,
4020 _auth: Option<&super::super::auth::AuthContext>,
4021 _raw_ctx: Option<&crate::request::RawRequestContext>,
4022 ) -> Result<PlexusStream, PlexusError> {
4023 Err(PlexusError::MethodNotFound {
4024 activation: "wirefixture".into(),
4025 method: "none".into(),
4026 })
4027 }
4028 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
4029 None
4030 }
4031 fn capabilities(&self) -> ChildCapabilities {
4032 self.caps
4033 }
4034 async fn list_children(&self) -> Option<futures_core::stream::BoxStream<'_, String>> {
4035 if !self.caps.contains(ChildCapabilities::LIST) {
4036 return None;
4037 }
4038 Some(Box::pin(futures::stream::iter(self.names.clone())))
4039 }
4040 async fn search_children(
4041 &self,
4042 query: &str,
4043 ) -> Option<futures_core::stream::BoxStream<'_, String>> {
4044 if !self.caps.contains(ChildCapabilities::SEARCH) {
4045 return None;
4046 }
4047 let q = query.to_lowercase();
4048 let filtered: Vec<String> = self
4049 .names
4050 .iter()
4051 .filter(|n| n.to_lowercase().contains(&q))
4052 .cloned()
4053 .collect();
4054 Some(Box::pin(futures::stream::iter(filtered)))
4055 }
4056 }
4057
4058 fn build_module_for(router: WireFixture, ns: &str) -> RpcModule<()> {
4059 let mut module = RpcModule::new(());
4060 let arc: Arc<dyn ChildRouter> = Arc::new(router);
4061 register_child_capability_methods(&mut module, ns, arc, None).expect("register");
4062 module
4063 }
4064
4065 #[tokio::test]
4066 async fn child_wire_registers_both_methods_when_both_bits_set() {
4067 let module = build_module_for(
4068 WireFixture {
4069 names: vec!["alpha".into(), "beta".into()],
4070 caps: ChildCapabilities::LIST | ChildCapabilities::SEARCH,
4071 },
4072 "fixture",
4073 );
4074 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4075 assert!(
4076 names.contains(&"fixture.list_children".to_string()),
4077 "expected fixture.list_children, got: {:?}",
4078 names
4079 );
4080 assert!(
4081 names.contains(&"fixture.search_children".to_string()),
4082 "expected fixture.search_children, got: {:?}",
4083 names
4084 );
4085 }
4086
4087 #[tokio::test]
4088 async fn child_wire_registers_nothing_when_no_bits_set() {
4089 let module = build_module_for(
4090 WireFixture {
4091 names: vec!["alpha".into()],
4092 caps: ChildCapabilities::empty(),
4093 },
4094 "fixture",
4095 );
4096 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4097 assert!(
4098 !names.contains(&"fixture.list_children".to_string()),
4099 "fixture.list_children should NOT be registered when cap absent"
4100 );
4101 assert!(
4102 !names.contains(&"fixture.search_children".to_string()),
4103 "fixture.search_children should NOT be registered when cap absent"
4104 );
4105 }
4106
4107 #[tokio::test]
4108 async fn child_wire_registers_only_list_when_only_list_bit() {
4109 let module = build_module_for(
4110 WireFixture {
4111 names: vec!["alpha".into()],
4112 caps: ChildCapabilities::LIST,
4113 },
4114 "fixture",
4115 );
4116 let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4117 assert!(names.contains(&"fixture.list_children".to_string()));
4118 assert!(!names.contains(&"fixture.search_children".to_string()));
4119 }
4120
4121 // Live wire-call behavior (subscription stream content, methodNotFound on
4122 // unregistered names, error envelopes) is verified end-to-end against
4123 // running substrate Solar — that's the canonical integration gate per
4124 // the CHILD-WIRE acceptance criteria. The unit-level introspection
4125 // tests above assert the registration shape; the substrate verification
4126 // asserts the live behavior. Splitting it that way avoids forcing the
4127 // unit test to construct a working RpcSubscriptionSink, which is not
4128 // straightforward in the bare jsonrpsee API.
4129}