1mod host;
65mod link;
66mod names;
68mod peer;
70mod spec;
71mod upcall;
73mod proven;
75#[cfg(feature = "child-ws")]
76mod ws;
77#[cfg(feature = "clap")]
78mod args;
79mod dial_in;
82#[cfg(feature = "child-ws")]
83mod dial_out;
84pub mod pairing;
86
87use std::pin::Pin;
88use std::sync::atomic::Ordering;
89use std::sync::Arc;
90use std::task::{Context, Poll};
91use std::time::Instant;
92
93use async_trait::async_trait;
94use futures::Stream;
95use plexus_auth_core::grants::{GrantsGeneration, Reach};
96use serde_json::{json, Value};
97use tokio::sync::mpsc;
98
99pub use host::{host, serve_child, serve_child_on, serve_child_proven, serve_child_stdio, serve_child_with, ChildPeer, HostTransport, ServeChild};
100pub use upcall::{Consented, HOST_CALL, HOST_CALL_UNSUB};
101pub use link::{MountTimings, KEYED_MOUNT_NEEDS_A_KEY};
102pub use spec::{check_ws_url, is_insecure_ws, is_loopback_host, parse_duration, Backoff, ChildError, ChildOptions, ChildSpec, INSECURE_TRANSPORT};
103#[cfg(feature = "clap")]
104pub use args::ChildArgs;
105pub use dial_in::{possession_input, Admission, Decision, Offer, OfferRefused, PeerEvent, PeerInfo, PeerRoles, PeerSocket, Peers, PeersMethods, OFFER_PENDING};
106#[cfg(feature = "child-ws")]
107pub use dial_out::{key_principal, DialOut, DialState, Exposed, FirstContact};
108#[cfg(feature = "child-ws")]
109pub use ws::serve_child_ws;
110pub use proven::{dial_proof, KeyedUpgrade, Proven, CHILD_DIAL_AGENT, UPGRADE_LEDGER_MAX};
111
112use link::{meta, too_many, unavailable, Conn, Counters, Shared, SubKey};
113
114use super::auth::AuthContext;
115use super::method_enum::MethodEnumSchema;
116use super::plexus::{Activation, ChildRouter, PlexusError};
117use super::schema::{MethodRole, PluginSchema};
118use super::streaming::PlexusStream;
119use super::types::PlexusStreamItem;
120
121#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
129pub struct PeerIdentity {
130 pub backend: String,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub tls_key: Option<String>,
135 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub key: Option<String>,
139}
140
141impl PeerIdentity {
142 fn of(conn: &Conn) -> Self {
143 Self { backend: conn.ns().to_string(), tls_key: conn.tls_key.get().cloned(), key: conn.peer_key.get().cloned() }
144 }
145}
146
147impl std::fmt::Display for PeerIdentity {
148 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149 write!(f, "backend `{}`", self.backend)?;
150 match &self.tls_key {
151 Some(k) => write!(f, ", TLS key {}", &k[..k.len().min(16)]),
152 None => write!(f, ", no TLS key"),
153 }?;
154 match &self.key {
155 Some(k) => write!(f, ", key {}", &k[..k.len().min(20)]),
156 None => Ok(()),
157 }
158 }
159}
160
161#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
163pub struct ChildStats {
164 pub open: usize,
166 pub unasked: u64,
168 pub restarts: u64,
170 pub calls: u64,
172 pub name_schemas: u64,
175 pub name_schema_hits: u64,
177 pub names_kept: usize,
180 pub calls_back: u64,
182 pub up: bool,
184}
185
186#[derive(Debug, Clone, Copy)]
189pub enum ChildMethods {}
190
191impl schemars::JsonSchema for ChildMethods {
192 fn schema_name() -> std::borrow::Cow<'static, str> {
193 "ChildMethods".into()
194 }
195
196 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
197 schemars::json_schema!({
198 "description": "A child service's methods are data: its schema, asked when it was mounted (`<mount>.schema`)."
199 })
200 }
201}
202
203impl MethodEnumSchema for ChildMethods {
204 fn method_names() -> &'static [&'static str] {
205 &[]
206 }
207
208 fn schema_with_consts() -> Value {
209 serde_json::to_value(schemars::schema_for!(ChildMethods)).unwrap_or(Value::Null)
210 }
211}
212
213struct Inner {
214 shared: Arc<Shared>,
215 schema: PluginSchema,
216 nodes: Vec<(String, PluginSchema)>,
221 timings: MountTimings,
222 names: names::Names,
224 needs: Option<Vec<crate::plexus::schema::Need>>,
227}
228
229impl Inner {
230 pub(super) fn new(shared: Arc<Shared>, schema: PluginSchema, nodes: Vec<(String, PluginSchema)>, timings: MountTimings) -> Self {
231 let names = names::Names::new(shared.opts.schema_cache);
232 let declared = schema.needs.is_some() || nodes.iter().any(|(_, n)| n.needs.is_some());
233 let mut needs: Vec<crate::plexus::schema::Need> = schema.needs.iter().chain(nodes.iter().filter_map(|(_, n)| n.needs.as_ref())).flatten().cloned().collect();
234 needs.sort();
235 needs.dedup_by(|a, b| a.method == b.method);
236 let needs = declared.then_some(needs);
237 Self { shared, schema, nodes, timings, names, needs }
238 }
239}
240
241#[derive(Clone)]
245pub struct RemoteChild {
246 inner: Arc<Inner>,
247}
248
249impl std::fmt::Debug for RemoteChild {
250 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251 f.debug_struct("RemoteChild").field("spec", &self.inner.shared.spec.to_string()).field("insecure", &self.insecure()).field("stats", &self.stats()).finish()
252 }
253}
254
255fn read_schema(raw: Value) -> Result<PluginSchema, String> {
257 serde_json::from_value(peer::schema(raw)?).map_err(|e| format!("its schema does not read: {e}"))
258}
259
260pub(super) fn node_schema(path: &str, raw: Value) -> Result<PluginSchema, String> {
264 read_schema(raw).map_err(|e| format!("its child `{path}`: {e}"))
265}
266
267fn mount_schema(name: &str, raw: Value) -> Result<PluginSchema, String> {
273 let mut schema = read_schema(raw)?;
274 if schema.namespace != name {
275 tracing::info!(target: "plexus::child", child = %name, declared = %schema.namespace, "mounted under its mount name, not the namespace it declares");
276 }
277 let prefix = format!("{}.", schema.namespace);
278 let requalify = |g: &String| match g.strip_prefix(&prefix) {
279 Some(m) => format!("{name}.{m}"),
280 None => format!("{name}.{g}"),
281 };
282 schema.roles = schema.roles.iter().map(|(r, gs)| (r.clone(), gs.iter().map(requalify).collect())).collect();
283 for m in schema.methods.iter_mut() {
284 if let Some(g) = m.grant.as_ref() {
285 m.grant = Some(requalify(g));
286 }
287 }
288 schema.namespace = name.to_string();
289 Ok(schema)
290}
291
292impl RemoteChild {
293 pub async fn connect(spec: ChildSpec, opts: ChildOptions) -> Result<Self, ChildError> {
298 let name = spec.name().to_string();
299 let start = |why: String| ChildError::Start(name.clone(), why);
300 if opts.max_calls == 0 || opts.buffer == 0 {
301 return Err(start("max_calls and buffer are at least 1".into()));
302 }
303 let principal = Self::principal_for(&spec, &opts).map_err(start)?;
304 let shared = Shared::new(spec, opts, principal);
305 let (conn, kept, mut timings) = shared.connect_once().await.map_err(start)?;
306 let t = Instant::now();
307 let hash = kept.hash();
308 let read = mount_schema(&name, kept.top).and_then(|schema| {
309 let nodes = kept.nodes.into_iter().map(|(path, raw)| node_schema(&path, raw).map(|s| (path, s))).collect::<Result<Vec<_>, _>>()?;
310 Ok((schema, nodes))
311 });
312 let (schema, nodes) = match read {
313 Ok(s) => s,
314 Err(why) => {
315 conn.shutdown.notify_one();
316 return Err(start(why));
317 }
318 };
319 let _ = shared.mounted_hash.set(hash);
320 let _ = shared.identity.set(PeerIdentity::of(&conn));
321 shared.install(conn);
322 timings.merge_ms = t.elapsed().as_secs_f64() * 1e3;
323 tracing::info!(target: "plexus::child", child = %name, spawn_ms = timings.spawn_ms, schema_ms = timings.schema_ms, merge_ms = timings.merge_ms, methods = schema.methods.len(), children = nodes.len(), "child mounted");
324 if let ChildSpec::Ws { url, .. } = &shared.spec {
325 if is_insecure_ws(url) {
326 tracing::warn!(target: "plexus::child", child = %name, %url, "insecure: mounted over plain ws:// beyond loopback (transport.insecure_ws); its hops and key proof cross in clear");
327 }
328 }
329 let inner = Inner::new(shared, schema, nodes, timings);
330 inner.shared.upcalls.set_needs(inner.needs.as_deref());
332 Ok(Self { inner: Arc::new(inner) })
333 }
334
335 #[allow(unused_variables)]
336 fn principal_for(spec: &ChildSpec, opts: &ChildOptions) -> Result<String, String> {
337 #[cfg(feature = "child-ws")]
338 if let (ChildSpec::Ws { .. }, Some(path)) = (spec, &opts.key) {
339 return Ok(ws::principal_of(&ws::read_seed(path)?));
340 }
341 Ok(opts.principal.clone())
342 }
343
344 pub fn stats(&self) -> ChildStats {
346 let c: &Counters = &self.inner.shared.counters;
347 ChildStats {
348 open: c.open.load(Ordering::Relaxed),
349 unasked: c.unasked.load(Ordering::Relaxed),
350 restarts: c.restarts.load(Ordering::Relaxed),
351 calls: c.calls.load(Ordering::Relaxed),
352 name_schemas: self.inner.names.hops.load(Ordering::Relaxed),
353 name_schema_hits: self.inner.names.hits.load(Ordering::Relaxed),
354 names_kept: self.inner.names.len(c.restarts.load(Ordering::Relaxed)),
355 calls_back: self.inner.shared.upcalls.made.load(Ordering::Relaxed),
356 up: self.inner.shared.is_up(),
357 }
358 }
359
360 pub fn identity(&self) -> Option<&PeerIdentity> {
364 self.inner.shared.identity.get()
365 }
366
367 pub fn set_consent(&self, consent: Option<Vec<Consented>>) {
372 self.inner.shared.upcalls.set_consent(consent);
373 }
374
375 pub fn consent(&self) -> Option<Vec<Consented>> {
377 self.inner.shared.upcalls.consent().map(|c| c.to_vec())
378 }
379
380 pub fn revoke(&self, why: &str) {
389 self.inner.shared.upcalls.revoke(why);
390 self.inner.shared.stop(&format!("revoked: {why}"));
391 tracing::warn!(target: "plexus::audit", child = %self.name(), %why, "child revoked");
392 }
393
394 pub fn stop(&self, why: &str) {
400 let shared = &self.inner.shared;
401 shared.stop(why);
402 shared.upcalls.end_all(why);
403 tracing::info!(target: "plexus::child", child = %self.name(), %why, "child cut off: its calls ended");
404 }
405
406 pub fn stopped(&self) -> Option<String> {
409 self.inner.shared.stopped().map(str::to_string)
410 }
411
412 pub fn revoked(&self) -> Option<String> {
414 self.inner.shared.upcalls.revoked()
415 }
416
417 pub fn may_exchange(&self, need: &str, forwarded: &str, presented: &crate::plexus::peer_token::PeerClaims) -> Result<Vec<String>, String> {
426 if self.peer_key() != Some(presented.aud.as_str()) {
427 return Err(format!("the token presented is not `{}`'s", self.name()));
428 }
429 let up = &self.inner.shared.upcalls;
430 let svc = up.host().and_then(|h| h.upgrade()).ok_or_else(|| format!("`{}`'s service is not known yet", self.name()))?;
431 let decided = up.decide(need, Some((&svc, presented))).map_err(|(_, said)| said)?;
432 let Some(upcall::Decided { held: Some(held), .. }) = decided else {
433 return Err(format!("`{need}` is not among `{}`'s needs", self.name()));
434 };
435 Ok(held.iter().map(|s| format!("{forwarded}@{s}")).collect())
436 }
437
438 pub fn peer_key(&self) -> Option<&str> {
441 self.identity().and_then(|i| i.key.as_deref())
442 }
443
444 pub fn is_up(&self) -> bool {
446 self.inner.shared.is_up()
447 }
448
449 pub fn dead(&self) -> Option<String> {
454 self.inner.shared.dead()
455 }
456
457 pub fn why_down(&self) -> Option<String> {
461 self.inner.shared.why_down()
462 }
463
464 pub async fn up(&self) -> Result<(), String> {
468 match self.inner.shared.ensure().await {
469 Ok(_) => Ok(()),
470 Err(PlexusStreamItem::Error { message, error, .. }) => Err(match error {
471 plexus_client::RemoteError::ChildUnavailable { reason, .. } => reason,
472 _ => message,
473 }),
474 Err(other) => Err(format!("{other:?}")),
475 }
476 }
477
478 pub fn needs(&self) -> Option<&[crate::plexus::schema::Need]> {
481 self.inner.needs.as_deref()
482 }
483
484 pub fn calls_open_back(&self) -> usize {
486 self.inner.shared.upcalls.open_now()
487 }
488
489 pub fn mounted_hash(&self) -> &str {
492 self.inner.shared.mounted_hash.get().map(String::as_str).unwrap_or_default()
493 }
494
495 pub fn pid(&self) -> Option<u32> {
497 self.inner.shared.current().and_then(|c| c.pid)
498 }
499
500 pub fn name(&self) -> &str {
502 &self.inner.shared.name
503 }
504
505 pub fn insecure(&self) -> bool {
509 matches!(&self.inner.shared.spec, ChildSpec::Ws { url, .. } if is_insecure_ws(url))
510 }
511
512 pub fn spec(&self) -> &ChildSpec {
514 &self.inner.shared.spec
515 }
516
517 pub fn principal(&self) -> &str {
519 &self.inner.shared.principal
520 }
521
522 pub fn mount_timings(&self) -> MountTimings {
524 self.inner.timings
525 }
526
527 pub fn routed(&self) -> usize {
529 self.inner.shared.current().map_or(0, |c| c.routed())
530 }
531
532 fn hop(&self, conn: &Conn, auth: Option<&AuthContext>, reach: &Reach, method: &str, door: Option<bool>) -> (Value, String) {
548 let for_: Vec<String> = auth.and_then(|a| a.principal()).map(|p| p.to_string()).into_iter().collect();
549 let limit = reach.grant().map(|g| {
550 let grant = match g.as_str().strip_prefix(&format!("{}.", self.name())) {
551 Some(m) => format!("{}.{m}", conn.ns()),
552 None => format!("{}.{method}", conn.ns()),
557 };
558 let held_on: Vec<String> = reach.held_on().iter().map(|s| s.to_string()).collect();
559 match door {
560 Some(true) => json!({ "grant": grant, "held_on": held_on, "door": format!("/{}.{method}", conn.ns()), "door_own": true }),
561 Some(false) => json!({ "grant": grant, "held_on": held_on, "door": format!("/{}.{method}", conn.ns()) }),
562 None => json!({ "grant": grant, "held_on": held_on }),
563 }
564 });
565 let call = uuid::Uuid::new_v4().to_string();
566 (json!({ "principal": self.inner.shared.principal, "for": for_, "limit": limit, "call": call }), call)
567 }
568
569 fn door_of(&self, reach: &Reach, method: &str) -> Option<plexus_auth_core::grants::DispatchedCall> {
577 if !super::grant_gate::is_door(reach) {
578 return None;
579 }
580 let call = crate::call::context().ok()?.door()?.clone();
581 let own = format!("{}.{method}", self.name());
582 let path = call.at().path();
583 let this = path == own || path.ends_with(&format!(".{own}"));
584 (this && Some(call.grant()) == reach.grant()).then_some(call)
585 }
586
587 fn mint(&self, auth: Option<&AuthContext>, reach: &Reach, hop: &Value, path: &str, call: &str) -> Result<Option<upcall::Minted>, String> {
592 use crate::plexus::peer_token::{mint_scope, onward_scope, MintRequest};
593 let Some(issuer) = self.inner.shared.opts.tokens.as_ref() else { return Ok(None) };
594 if let Some(why) = self.inner.shared.upcalls.revoked() {
597 return Err(format!("`{}` is revoked ({why})", self.name()));
598 }
599 let Some(sub) = auth.and_then(|a| a.principal()).map(|p| p.to_string()) else { return Ok(None) };
600 let peer_key = self.peer_key().map(str::to_string);
601 if peer_key.is_none() && !matches!(self.spec(), ChildSpec::Stdio { .. }) {
602 return Ok(None);
603 }
604 if peer_key.is_some() && crate::plexus::peer_token::key_of(&self.inner.shared.principal).is_none() {
607 return Err(format!("{KEYED_MOUNT_NEEDS_A_KEY}: this service dials as `{}`, not a key", self.inner.shared.principal));
608 }
609 let held: Vec<String> = if reach.is_everywhere() { vec!["*".into()] } else { reach.held_on().iter().map(|s| s.to_string()).collect() };
610 let needs = crate::plexus::service_scope::current()
611 .and_then(|w| w.upgrade())
612 .map(|svc| self.inner.shared.upcalls.need_grants(&svc))
613 .unwrap_or_default();
614 let forwarded = hop.get("limit").and_then(|l| l.get("grant")).and_then(Value::as_str);
615 let presented = upcall::presented();
616 let mut scope = match &presented {
618 Some(p) => onward_scope(p, reach.grant().map(|g| g.as_str()), forwarded, &held, &needs),
619 None => mint_scope(forwarded, &held, &needs),
620 };
621 let door = hop.get("limit").and_then(|l| l.get("door")).and_then(Value::as_str);
625 if let (Some(g), Some(at)) = (forwarded, door) {
626 let admitted = reach.grant().map(|g| g.as_str());
627 let onward_held = presented.as_ref().is_none_or(|p| admitted.is_some_and(|a| p.scopes_for(a).iter().any(|s| s == "*")));
628 if onward_held {
629 scope.push(format!("{g}@{at}"));
630 }
631 }
632 let req = MintRequest { sub, peer_key, name: self.name().to_string(), scope, call: call.to_string(), method: path.to_string(), presented };
633 let (token, claims) = issuer.mint(req).map_err(|e| e.to_string())?;
634 Ok(Some(upcall::Minted { token, claims }))
635 }
636
637 fn node(&self, path: &str) -> Option<&PluginSchema> {
639 self.inner.nodes.iter().find(|(p, _)| p == path).map(|(_, s)| s)
640 }
641
642 fn slot_of(&self, path: &str) -> Option<(String, String)> {
648 let segs: Vec<&str> = path.split('.').collect();
649 let (n, schema) = (1..segs.len())
650 .rev()
651 .find_map(|n| self.node(&segs[..n].join(".")).map(|s| (n, s)))
652 .unwrap_or((0, &self.inner.schema));
653 let parent = std::iter::once(self.name()).chain(segs[..n].iter().copied()).collect::<Vec<_>>().join(".");
654 let next = segs[n];
655 if schema.methods.iter().any(|m| m.name == next && matches!(m.role, MethodRole::Peer { .. })) {
657 return Some((crate::plexus::slots::slot_path(&parent, next), segs[..(n + 2).min(segs.len())].join(".")));
658 }
659 let slot = schema.methods.iter().find(|m| matches!(m.role, MethodRole::DynamicChild { .. }))?;
660 Some((crate::plexus::slots::slot_path(&parent, &slot.name), segs[..=n].join(".")))
661 }
662
663 fn unreached(&self, method: &str) -> PlexusError {
665 PlexusError::MethodNotFound { activation: self.name().to_string(), method: method.to_string() }
666 }
667
668 async fn name_schema(&self, path: &str, params: &Value, auth: Option<&AuthContext>) -> PlexusStream {
675 let epoch = self.inner.shared.counters.restarts.load(Ordering::Relaxed);
676 if let Some(s) = self.inner.names.get(path, epoch) {
677 return self.schema_stream_of(&s, &s.namespace, params);
678 }
679 self.inner.names.crossed();
680 let items: Vec<PlexusStreamItem> = futures::StreamExt::collect(self.forward(&format!("{path}.schema"), json!({}), auth, None).await).await;
681 let kept = items.iter().find_map(|i| match i {
682 PlexusStreamItem::Data { metadata, content, .. } => Some((metadata.plexus_hash.clone(), content.clone().into_value())),
683 _ => None,
684 });
685 let Some((seen, raw)) = kept else {
686 return Box::pin(futures::stream::iter(items));
687 };
688 match read_schema(raw) {
689 Ok(schema) => {
690 let epoch = self.inner.shared.counters.restarts.load(Ordering::Relaxed);
692 self.inner.names.put(path, schema.clone(), seen, epoch);
693 self.schema_stream_of(&schema, &schema.namespace, params)
694 }
695 Err(_) => Box::pin(futures::stream::iter(items)),
696 }
697 }
698
699 fn schema_stream(&self, params: &Value) -> PlexusStream {
700 self.schema_stream_of(&self.inner.schema, self.name(), params)
701 }
702
703 fn schema_stream_of(&self, schema: &PluginSchema, label: &str, params: &Value) -> PlexusStream {
706 let ns = label.to_string();
707 let content = match params.get("method").and_then(Value::as_str) {
708 Some(m) => match schema.methods.iter().find(|x| x.name == m) {
709 Some(ms) => serde_json::to_value(ms).unwrap_or_default(),
710 None => {
711 let error = plexus_client::RemoteError::MethodNotFound { activation: ns.clone(), method: m.to_string() };
712 let mut e = PlexusStreamItem::error(meta(&ns), error, false);
713 if let PlexusStreamItem::Error { message, code, .. } = &mut e {
714 *message = format!("Method '{m}' not found");
715 *code = Some("-32602".into());
716 }
717 return Box::pin(futures::stream::iter([e]));
718 }
719 },
720 None => serde_json::to_value(schema).unwrap_or_default(),
721 };
722 Box::pin(futures::stream::iter([
723 PlexusStreamItem::Data { metadata: meta(&ns).into(), content_type: format!("{ns}.schema").into(), content: content.into() },
724 PlexusStreamItem::Done { metadata: meta(&ns) },
725 ]))
726 }
727
728 async fn forward(&self, method: &str, params: Value, auth: Option<&AuthContext>, instance: Option<String>) -> PlexusStream {
731 let shared = &self.inner.shared;
732 let one = |item: PlexusStreamItem| -> PlexusStream { Box::pin(futures::stream::iter([item])) };
733 if let Some(why) = shared.upcalls.revoked() {
735 let e = PlexusError::Unauthenticated(format!("`{}` is revoked ({why}): no call is forwarded to it", self.name()));
736 return one(PlexusStreamItem::from_plexus_error(meta(self.name()), &e, false));
737 }
738 if let Some(why) = shared.stopped() {
740 return one(unavailable(self.name(), why));
741 }
742 let reach = match super::grant_gate::current_reach() {
745 Ok(reach) => reach,
746 Err(e) => return one(PlexusStreamItem::from_plexus_error(meta(self.name()), &e, false)),
747 };
748 let max = shared.opts.max_calls;
749 if shared.counters.open.fetch_add(1, Ordering::AcqRel) >= max {
750 shared.counters.open.fetch_sub(1, Ordering::AcqRel);
751 return one(too_many(self.name(), max));
752 }
753 let guard = OpenGuard(Arc::clone(&shared.counters));
754 let conn = match shared.ensure().await {
755 Ok(c) => c,
756 Err(item) => return one(item),
757 };
758 shared.counters.calls.fetch_add(1, Ordering::Relaxed);
759 let door = self.door_of(&reach, method);
761 let own = door.is_some() && crate::call::context().is_ok_and(|c| c.door_own());
762 let (mut hop, call_id) = self.hop(&conn, auth, &reach, method, door.as_ref().map(|_| own));
763 let path = format!("{}.{method}", conn.ns());
764 let minted = match self.mint(auth, &reach, &hop, &path, &call_id) {
766 Ok(m) => m,
767 Err(why) => {
768 let e = PlexusError::Unauthenticated(format!("no token could be minted for `{}`: {why}", self.name()));
769 return one(PlexusStreamItem::from_plexus_error(meta(self.name()), &e, false));
770 }
771 };
772 if let Some(m) = &minted {
773 hop["token"] = json!(m.token);
774 if let Some(issuer) = shared.opts.tokens.as_ref() {
778 match issuer.prove_forward(&m.token, &m.claims) {
779 Ok(p) => hop["proof"] = json!(p),
780 Err(why) => {
781 let e = PlexusError::Unauthenticated(format!("no proof could be signed for `{}`'s token: {why}", self.name()));
782 return one(PlexusStreamItem::from_plexus_error(meta(self.name()), &e, false));
783 }
784 }
785 }
786 }
787 let under = shared.upcalls.open(&call_id, auth, &reach, minted, door);
790 if let Some(why) = shared.upcalls.revoked() {
793 drop(under);
794 let e = PlexusError::Unauthenticated(format!("`{}` is revoked ({why}): no call is forwarded to it", self.name()));
795 return one(PlexusStreamItem::from_plexus_error(meta(self.name()), &e, false));
796 }
797 if let Some(why) = shared.stopped() {
798 drop(under);
799 return one(unavailable(self.name(), why));
800 }
801 let call = json!({ "method": path, "params": params, "hop": hop });
802 let mark = link::PeerMark::here();
803 match conn.open(&format!("{}.call", conn.ns()), call, shared.opts.timeout, Some(mark.clone())).await {
804 Ok((sid, rx)) => {
805 let generation = reach.generation().cloned();
806 let seen = generation.as_ref().map_or(0, GrantsGeneration::current);
807 let instance = instance.map(|path| (Arc::clone(&self.inner), path));
808 Box::pin(CallStream { rx, sid, conn, over: false, _guard: guard, reach, generation, seen, name: self.name().to_string(), instance, under, mark })
809 }
810 Err(item) => one(item),
811 }
812 }
813}
814
815struct OpenGuard(Arc<Counters>);
817
818impl Drop for OpenGuard {
819 fn drop(&mut self) {
820 self.0.open.fetch_sub(1, Ordering::AcqRel);
821 }
822}
823
824struct CallStream {
827 rx: mpsc::Receiver<PlexusStreamItem>,
828 sid: SubKey,
829 conn: Arc<Conn>,
830 over: bool,
831 _guard: OpenGuard,
832 reach: Reach,
835 generation: Option<GrantsGeneration>,
836 seen: u64,
837 name: String,
838 instance: Option<(Arc<Inner>, String)>,
841 under: Option<upcall::UnderGuard>,
844 mark: Arc<link::PeerMark>,
846}
847
848impl CallStream {
849 fn finish(&mut self, why: &str) {
851 self.over = true;
852 if let Some(u) = self.under.take() {
853 u.end(why);
854 }
855 }
856
857 fn revoked(&self) -> PlexusStreamItem {
859 let grant = self.reach.grant().map(|g| g.as_str().to_string()).unwrap_or_default();
860 let error = plexus_client::RemoteError::Forbidden {
861 reason: plexus_client::DenyReason::MissingGrant {
862 grant: grant.clone(),
863 scope: "*".into(),
864 roles: Vec::new(),
865 held_on: Vec::new(),
866 },
867 };
868 let mut item = PlexusStreamItem::error(meta(&self.name), error, false);
869 if let PlexusStreamItem::Error { message, .. } = &mut item {
870 *message = format!("Forbidden: `{grant}` is no longer held — the call's grant moved while it ran");
871 }
872 item
873 }
874}
875
876impl Stream for CallStream {
877 type Item = PlexusStreamItem;
878
879 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
880 if self.over {
881 return Poll::Ready(None);
882 }
883 if let Some(why) = self.conn.stopped() {
886 let item = unavailable(&self.name, why);
887 let why = why.to_string();
888 self.finish(&why);
889 return Poll::Ready(Some(item));
890 }
891 match self.rx.poll_recv(cx) {
892 Poll::Ready(Some(item)) => {
893 if let (Some((inner, path)), Some(m)) = (&self.instance, item.metadata()) {
894 inner.names.observe(path, &m.plexus_hash);
895 }
896 let terminal = matches!(item, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. });
897 let moved = self.generation.as_ref().map(GrantsGeneration::current).filter(|g| *g != self.seen);
898 if let (false, Some(g)) = (terminal, moved) {
899 self.seen = g;
900 if self.reach.current().is_none() {
901 let sid = self.sid.clone();
902 self.conn.unsubscribe(&sid);
903 self.finish("its grant was revoked");
904 return Poll::Ready(Some(self.revoked()));
905 }
906 }
907 if terminal {
908 self.finish("it ended");
909 }
910 Poll::Ready(Some(item))
911 }
912 Poll::Ready(None) => {
913 self.finish("the connection closed");
915 Poll::Ready(Some(unavailable(&self.name, "the connection closed")))
916 }
917 Poll::Pending => Poll::Pending,
918 }
919 }
920}
921
922impl Drop for CallStream {
923 fn drop(&mut self) {
924 self.mark.taken();
925 if !self.over {
926 self.conn.unsubscribe(&self.sid);
927 }
928 }
929}
930
931#[async_trait]
932impl Activation for RemoteChild {
933 type Methods = ChildMethods;
934
935 fn needs(&self) -> Option<Vec<crate::plexus::schema::Need>> {
936 self.inner.needs.clone()
937 }
938
939 fn namespace(&self) -> &str {
940 self.name()
941 }
942
943 fn version(&self) -> &str {
944 &self.inner.schema.version
945 }
946
947 fn description(&self) -> &str {
948 &self.inner.schema.description
949 }
950
951 fn long_description(&self) -> Option<&str> {
952 self.inner.schema.long_description.as_deref()
953 }
954
955 fn methods(&self) -> Vec<&str> {
956 self.inner.schema.methods.iter().map(|m| m.name.as_str()).collect()
957 }
958
959 fn method_help(&self, method: &str) -> Option<String> {
960 self.inner.schema.methods.iter().find(|m| m.name == method).map(|m| m.description.clone())
961 }
962
963 async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>, _raw: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
964 if method == "schema" {
965 return Ok(self.schema_stream(¶ms));
966 }
967 if let Some(path) = method.strip_suffix(".schema") {
969 if let Some(s) = self.node(path) {
970 return Ok(self.schema_stream_of(s, &s.namespace, ¶ms));
971 }
972 return match self.slot_of(path) {
975 Some(_) => Ok(self.name_schema(path, ¶ms, auth).await),
976 None => Err(self.unreached(method)),
977 };
978 }
979 let found = match method.rsplit_once('.') {
980 Some((path, name)) => match self.node(path) {
982 Some(s) => s.methods.iter().find(|m| m.name == name && m.role == MethodRole::Rpc),
983 None => match self.slot_of(path) {
988 Some((_, instance)) => return Ok(self.forward(method, params, auth, Some(instance)).await),
989 None => return Err(self.unreached(method)),
990 },
991 },
992 None => self.inner.schema.methods.iter().find(|m| m.name == method && m.role == MethodRole::Rpc),
993 };
994 let Some(m) = found else {
995 return Err(PlexusError::MethodNotFound { activation: self.name().to_string(), method: method.to_string() });
996 };
997 if m.everywhere {
1001 crate::call::admits_everywhere(&format!("{}.{method}", self.name()))?;
1002 }
1003 if m.input.is_some() {
1006 return Err(PlexusError::ExecutionError(format!(
1007 "`{}.{method}` takes an input stream, and a hop to a remote child does not forward one yet",
1008 self.name()
1009 )));
1010 }
1011 Ok(self.forward(method, params, auth, None).await)
1012 }
1013
1014 fn into_rpc_methods(self) -> jsonrpsee::Methods {
1017 jsonrpsee::Methods::new()
1018 }
1019
1020 fn plugin_schema(&self) -> PluginSchema {
1021 self.inner.schema.clone()
1022 }
1023
1024 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
1028 self.inner.nodes.clone()
1029 }
1030}
1031
1032#[async_trait]
1033impl ChildRouter for RemoteChild {
1034 fn router_namespace(&self) -> &str {
1035 self.name()
1036 }
1037
1038 async fn router_call(&self, method: &str, params: Value, auth: Option<&AuthContext>, raw: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
1039 Activation::call(self, method, params, auth, raw).await
1040 }
1041
1042 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
1043 None
1044 }
1045
1046 fn router_schema(&self) -> Option<PluginSchema> {
1047 Some(self.inner.schema.clone())
1048 }
1049
1050 fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
1051 self.inner.nodes.clone()
1052 }
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057 use super::*;
1058
1059 fn raw(methods: Value, roles: Value) -> Value {
1060 json!({ "namespace": "stub", "version": "0.1.0", "description": "d", "self_hash": "h", "hash": "h", "methods": methods, "roles": roles })
1061 }
1062
1063 fn m(name: &str) -> Value {
1064 json!({ "name": name, "description": "", "hash": "x", "streaming": false, "bidirectional": false })
1065 }
1066
1067 #[test]
1071 fn a_method_stating_neither_cardinality_nor_streaming_is_refused() {
1072 let silent = json!({ "name": "quiet", "description": "", "hash": "x" });
1073 let e = mount_schema("echo", raw(json!([m("echo"), silent]), json!({}))).unwrap_err();
1074 assert!(e.contains("`quiet`") && e.contains("neither cardinality"), "{e}");
1075 }
1076
1077 #[test]
1078 fn the_mount_name_wins_and_roles_are_requalified() {
1079 let s = mount_schema("echo", raw(json!([m("echo"), m("shout")]), json!({ "viewer": ["stub.echo"], "editor": ["stub.echo", "stub.shout"] }))).unwrap();
1080 assert_eq!(s.namespace, "echo");
1081 assert_eq!(s.roles["viewer"], vec!["echo.echo".to_string()]);
1082 assert_eq!(s.roles["editor"], vec!["echo.echo".to_string(), "echo.shout".to_string()]);
1083 }
1084
1085 #[test]
1087 fn a_child_with_children_mounts_and_its_method_grants_are_requalified() {
1088 let mut inner = m("inner");
1089 inner["role"] = json!({ "kind": "static_child" });
1090 let mut own = m("echo");
1091 own["grant"] = json!("stub.echo");
1092 let s = mount_schema("echo", raw(json!([own, inner]), json!({}))).unwrap();
1093 assert_eq!(s.methods[0].grant.as_deref(), Some("echo.echo"));
1094 assert_eq!(s.methods[1].role, MethodRole::StaticChild);
1095 let mut slot = m("item");
1096 slot["role"] = json!({ "kind": "dynamic_child", "list_method": "names" });
1097 let nested = raw(json!([m("echo"), s_inner(), slot]), json!({}));
1098 assert_eq!(link::static_children(&nested), vec!["inner".to_string()], "a dynamic child is a slot, not walked");
1099 let mut root = raw(json!([m("call")]), json!({}));
1101 root["children"] = json!([{ "namespace": "greeter", "description": "", "hash": "g" }]);
1102 assert_eq!(link::static_children(&root), vec!["greeter".to_string()]);
1103 }
1104
1105 fn s_inner() -> Value {
1106 let mut inner = m("inner");
1107 inner["role"] = json!({ "kind": "static_child" });
1108 inner
1109 }
1110
1111 #[test]
1113 fn the_tree_hash_covers_every_level() {
1114 let top = raw(json!([m("echo")]), json!({}));
1115 let flat = link::Kept { top: top.clone(), nodes: vec![] };
1116 assert_eq!(flat.hash(), link::schema_hash(&top), "a flat child's hash is its schema's, as before");
1117 let mut c = raw(json!([m("m")]), json!({}));
1118 let one = link::Kept { top: top.clone(), nodes: vec![("a.b".into(), c.clone())] }.hash();
1119 c["hash"] = json!("other");
1120 let two = link::Kept { top, nodes: vec![("a.b".into(), c)] }.hash();
1121 assert_ne!(one, two);
1122 }
1123
1124 #[test]
1125 fn typed_error_fields_cross_whole() {
1126 let item = unavailable("echo", "gone");
1127 let v = serde_json::to_value(&item).unwrap();
1128 assert_eq!(v["error_kind"], "child_unavailable");
1129 assert_eq!(v["code"], "child_unavailable");
1130 assert_eq!(v["child"], "echo");
1131 let back: PlexusStreamItem = serde_json::from_value(v.clone()).unwrap();
1132 assert_eq!(back.error_kind(), Some("child_unavailable"));
1133 assert_eq!(serde_json::to_value(&back).unwrap(), v);
1134 let plain = PlexusStreamItem::error(meta("x"), plexus_client::RemoteError::Execution { message: "m".into() }, false);
1137 let pv = serde_json::to_value(&plain).unwrap();
1138 let keys: Vec<_> = pv.as_object().unwrap().keys().cloned().collect();
1139 assert_eq!(keys, ["code", "error", "message", "metadata", "recoverable", "type"]);
1140 }
1141}