1mod host;
65mod link;
66mod names;
68mod peer;
70mod spec;
71mod upcall;
73#[cfg(feature = "child-ws")]
74mod ws;
75#[cfg(feature = "clap")]
76mod args;
77mod dial_in;
80#[cfg(feature = "child-ws")]
81mod dial_out;
82
83use std::pin::Pin;
84use std::sync::atomic::Ordering;
85use std::sync::Arc;
86use std::task::{Context, Poll};
87use std::time::Instant;
88
89use async_trait::async_trait;
90use futures::Stream;
91use plexus_auth_core::grants::{GrantsGeneration, Reach};
92use serde_json::{json, Value};
93use tokio::sync::mpsc;
94
95pub use host::{host, serve_child, serve_child_on, serve_child_stdio, ChildPeer, HostTransport};
96pub use upcall::{HOST_CALL, HOST_CALL_UNSUB};
97pub use link::MountTimings;
98pub use spec::{parse_duration, Backoff, ChildError, ChildOptions, ChildSpec};
99#[cfg(feature = "clap")]
100pub use args::ChildArgs;
101pub use dial_in::{PeerEvent, PeerInfo, PeerRoles, PeerSocket, Peers, PeersMethods};
102#[cfg(feature = "child-ws")]
103pub use dial_out::{key_principal, DialOut, DialState, Exposed};
104
105use link::{meta, too_many, unavailable, Conn, Counters, Shared, SubKey};
106
107use super::auth::AuthContext;
108use super::method_enum::MethodEnumSchema;
109use super::plexus::{Activation, ChildRouter, PlexusError};
110use super::schema::{MethodRole, PluginSchema};
111use super::streaming::PlexusStream;
112use super::types::PlexusStreamItem;
113
114#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
116pub struct ChildStats {
117 pub open: usize,
119 pub unasked: u64,
121 pub restarts: u64,
123 pub calls: u64,
125 pub name_schemas: u64,
128 pub name_schema_hits: u64,
130 pub names_kept: usize,
133 pub calls_back: u64,
135 pub up: bool,
137}
138
139#[derive(Debug, Clone, Copy)]
142pub enum ChildMethods {}
143
144impl schemars::JsonSchema for ChildMethods {
145 fn schema_name() -> std::borrow::Cow<'static, str> {
146 "ChildMethods".into()
147 }
148
149 fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
150 schemars::json_schema!({
151 "description": "A child service's methods are data: its schema, asked when it was mounted (`<mount>.schema`)."
152 })
153 }
154}
155
156impl MethodEnumSchema for ChildMethods {
157 fn method_names() -> &'static [&'static str] {
158 &[]
159 }
160
161 fn schema_with_consts() -> Value {
162 serde_json::to_value(schemars::schema_for!(ChildMethods)).unwrap_or(Value::Null)
163 }
164}
165
166struct Inner {
167 shared: Arc<Shared>,
168 schema: PluginSchema,
169 nodes: Vec<(String, PluginSchema)>,
174 timings: MountTimings,
175 names: names::Names,
177}
178
179impl Inner {
180 pub(super) fn new(shared: Arc<Shared>, schema: PluginSchema, nodes: Vec<(String, PluginSchema)>, timings: MountTimings) -> Self {
181 let names = names::Names::new(shared.opts.schema_cache);
182 Self { shared, schema, nodes, timings, names }
183 }
184}
185
186#[derive(Clone)]
190pub struct RemoteChild {
191 inner: Arc<Inner>,
192}
193
194impl std::fmt::Debug for RemoteChild {
195 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196 f.debug_struct("RemoteChild").field("spec", &self.inner.shared.spec.to_string()).field("stats", &self.stats()).finish()
197 }
198}
199
200fn read_schema(raw: Value) -> Result<PluginSchema, String> {
202 serde_json::from_value(peer::schema(raw)?).map_err(|e| format!("its schema does not read: {e}"))
203}
204
205pub(super) fn node_schema(path: &str, raw: Value) -> Result<PluginSchema, String> {
209 read_schema(raw).map_err(|e| format!("its child `{path}`: {e}"))
210}
211
212fn mount_schema(name: &str, raw: Value) -> Result<PluginSchema, String> {
218 let mut schema = read_schema(raw)?;
219 if schema.namespace != name {
220 tracing::info!(target: "plexus::child", child = %name, declared = %schema.namespace, "mounted under its mount name, not the namespace it declares");
221 }
222 let prefix = format!("{}.", schema.namespace);
223 let requalify = |g: &String| match g.strip_prefix(&prefix) {
224 Some(m) => format!("{name}.{m}"),
225 None => format!("{name}.{g}"),
226 };
227 schema.roles = schema.roles.iter().map(|(r, gs)| (r.clone(), gs.iter().map(requalify).collect())).collect();
228 for m in schema.methods.iter_mut() {
229 if let Some(g) = m.grant.as_ref() {
230 m.grant = Some(requalify(g));
231 }
232 }
233 schema.namespace = name.to_string();
234 Ok(schema)
235}
236
237impl RemoteChild {
238 pub async fn connect(spec: ChildSpec, opts: ChildOptions) -> Result<Self, ChildError> {
243 let name = spec.name().to_string();
244 let start = |why: String| ChildError::Start(name.clone(), why);
245 if opts.max_calls == 0 || opts.buffer == 0 {
246 return Err(start("max_calls and buffer are at least 1".into()));
247 }
248 let principal = Self::principal_for(&spec, &opts).map_err(start)?;
249 let shared = Shared::new(spec, opts, principal);
250 let (conn, kept, mut timings) = shared.connect_once().await.map_err(start)?;
251 let t = Instant::now();
252 let hash = kept.hash();
253 let read = mount_schema(&name, kept.top).and_then(|schema| {
254 let nodes = kept.nodes.into_iter().map(|(path, raw)| node_schema(&path, raw).map(|s| (path, s))).collect::<Result<Vec<_>, _>>()?;
255 Ok((schema, nodes))
256 });
257 let (schema, nodes) = match read {
258 Ok(s) => s,
259 Err(why) => {
260 conn.shutdown.notify_one();
261 return Err(start(why));
262 }
263 };
264 let _ = shared.mounted_hash.set(hash);
265 shared.install(conn);
266 timings.merge_ms = t.elapsed().as_secs_f64() * 1e3;
267 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");
268 Ok(Self { inner: Arc::new(Inner::new(shared, schema, nodes, timings)) })
269 }
270
271 #[allow(unused_variables)]
272 fn principal_for(spec: &ChildSpec, opts: &ChildOptions) -> Result<String, String> {
273 #[cfg(feature = "child-ws")]
274 if let (ChildSpec::Ws { .. }, Some(path)) = (spec, &opts.key) {
275 return Ok(ws::principal_of(&ws::read_seed(path)?));
276 }
277 Ok(opts.principal.clone())
278 }
279
280 pub fn stats(&self) -> ChildStats {
282 let c: &Counters = &self.inner.shared.counters;
283 ChildStats {
284 open: c.open.load(Ordering::Relaxed),
285 unasked: c.unasked.load(Ordering::Relaxed),
286 restarts: c.restarts.load(Ordering::Relaxed),
287 calls: c.calls.load(Ordering::Relaxed),
288 name_schemas: self.inner.names.hops.load(Ordering::Relaxed),
289 name_schema_hits: self.inner.names.hits.load(Ordering::Relaxed),
290 names_kept: self.inner.names.len(c.restarts.load(Ordering::Relaxed)),
291 calls_back: self.inner.shared.upcalls.made.load(Ordering::Relaxed),
292 up: self.inner.shared.is_up(),
293 }
294 }
295
296 pub fn is_up(&self) -> bool {
298 self.inner.shared.is_up()
299 }
300
301 pub fn dead(&self) -> Option<String> {
306 self.inner.shared.dead()
307 }
308
309 pub fn why_down(&self) -> Option<String> {
313 self.inner.shared.why_down()
314 }
315
316 pub async fn up(&self) -> Result<(), String> {
320 match self.inner.shared.ensure().await {
321 Ok(_) => Ok(()),
322 Err(PlexusStreamItem::Error { message, error, .. }) => Err(match error {
323 plexus_client::RemoteError::ChildUnavailable { reason, .. } => reason,
324 _ => message,
325 }),
326 Err(other) => Err(format!("{other:?}")),
327 }
328 }
329
330 pub fn calls_open_back(&self) -> usize {
332 self.inner.shared.upcalls.open_now()
333 }
334
335 pub fn mounted_hash(&self) -> &str {
338 self.inner.shared.mounted_hash.get().map(String::as_str).unwrap_or_default()
339 }
340
341 pub fn pid(&self) -> Option<u32> {
343 self.inner.shared.current().and_then(|c| c.pid)
344 }
345
346 pub fn name(&self) -> &str {
348 &self.inner.shared.name
349 }
350
351 pub fn spec(&self) -> &ChildSpec {
353 &self.inner.shared.spec
354 }
355
356 pub fn principal(&self) -> &str {
358 &self.inner.shared.principal
359 }
360
361 pub fn mount_timings(&self) -> MountTimings {
363 self.inner.timings
364 }
365
366 pub fn routed(&self) -> usize {
368 self.inner.shared.current().map_or(0, |c| c.routed())
369 }
370
371 fn hop(&self, conn: &Conn, auth: Option<&AuthContext>, reach: &Reach, method: &str) -> (Value, String) {
375 let for_: Vec<String> = auth.and_then(|a| a.principal()).map(|p| p.to_string()).into_iter().collect();
376 let limit = reach.grant().map(|g| {
377 let grant = match g.as_str().strip_prefix(&format!("{}.", self.name())) {
378 Some(m) => format!("{}.{m}", conn.ns()),
379 None => format!("{}.{method}", conn.ns()),
384 };
385 let held_on: Vec<String> = reach.held_on().iter().map(|s| s.to_string()).collect();
386 json!({ "grant": grant, "held_on": held_on })
387 });
388 let call = uuid::Uuid::new_v4().to_string();
389 (json!({ "principal": self.inner.shared.principal, "for": for_, "limit": limit, "call": call }), call)
390 }
391
392 fn node(&self, path: &str) -> Option<&PluginSchema> {
394 self.inner.nodes.iter().find(|(p, _)| p == path).map(|(_, s)| s)
395 }
396
397 fn slot_of(&self, path: &str) -> Option<(String, String)> {
403 let segs: Vec<&str> = path.split('.').collect();
404 let (n, schema) = (1..segs.len())
405 .rev()
406 .find_map(|n| self.node(&segs[..n].join(".")).map(|s| (n, s)))
407 .unwrap_or((0, &self.inner.schema));
408 let parent = std::iter::once(self.name()).chain(segs[..n].iter().copied()).collect::<Vec<_>>().join(".");
409 let next = segs[n];
410 if schema.methods.iter().any(|m| m.name == next && matches!(m.role, MethodRole::Peer { .. })) {
412 return Some((crate::plexus::slots::slot_path(&parent, next), segs[..(n + 2).min(segs.len())].join(".")));
413 }
414 let slot = schema.methods.iter().find(|m| matches!(m.role, MethodRole::DynamicChild { .. }))?;
415 Some((crate::plexus::slots::slot_path(&parent, &slot.name), segs[..=n].join(".")))
416 }
417
418 fn unreached(&self, method: &str) -> PlexusError {
420 PlexusError::MethodNotFound { activation: self.name().to_string(), method: method.to_string() }
421 }
422
423 async fn name_schema(&self, path: &str, params: &Value, auth: Option<&AuthContext>) -> PlexusStream {
430 let epoch = self.inner.shared.counters.restarts.load(Ordering::Relaxed);
431 if let Some(s) = self.inner.names.get(path, epoch) {
432 return self.schema_stream_of(&s, &s.namespace, params);
433 }
434 self.inner.names.crossed();
435 let items: Vec<PlexusStreamItem> = futures::StreamExt::collect(self.forward(&format!("{path}.schema"), json!({}), auth, None).await).await;
436 let kept = items.iter().find_map(|i| match i {
437 PlexusStreamItem::Data { metadata, content, .. } => Some((metadata.plexus_hash.clone(), content.clone().into_value())),
438 _ => None,
439 });
440 let Some((seen, raw)) = kept else {
441 return Box::pin(futures::stream::iter(items));
442 };
443 match read_schema(raw) {
444 Ok(schema) => {
445 let epoch = self.inner.shared.counters.restarts.load(Ordering::Relaxed);
447 self.inner.names.put(path, schema.clone(), seen, epoch);
448 self.schema_stream_of(&schema, &schema.namespace, params)
449 }
450 Err(_) => Box::pin(futures::stream::iter(items)),
451 }
452 }
453
454 fn schema_stream(&self, params: &Value) -> PlexusStream {
455 self.schema_stream_of(&self.inner.schema, self.name(), params)
456 }
457
458 fn schema_stream_of(&self, schema: &PluginSchema, label: &str, params: &Value) -> PlexusStream {
461 let ns = label.to_string();
462 let content = match params.get("method").and_then(Value::as_str) {
463 Some(m) => match schema.methods.iter().find(|x| x.name == m) {
464 Some(ms) => serde_json::to_value(ms).unwrap_or_default(),
465 None => {
466 let error = plexus_client::RemoteError::MethodNotFound { activation: ns.clone(), method: m.to_string() };
467 let mut e = PlexusStreamItem::error(meta(&ns), error, false);
468 if let PlexusStreamItem::Error { message, code, .. } = &mut e {
469 *message = format!("Method '{m}' not found");
470 *code = Some("-32602".into());
471 }
472 return Box::pin(futures::stream::iter([e]));
473 }
474 },
475 None => serde_json::to_value(schema).unwrap_or_default(),
476 };
477 Box::pin(futures::stream::iter([
478 PlexusStreamItem::Data { metadata: meta(&ns).into(), content_type: format!("{ns}.schema").into(), content: content.into() },
479 PlexusStreamItem::Done { metadata: meta(&ns) },
480 ]))
481 }
482
483 async fn forward(&self, method: &str, params: Value, auth: Option<&AuthContext>, instance: Option<String>) -> PlexusStream {
486 let shared = &self.inner.shared;
487 let one = |item: PlexusStreamItem| -> PlexusStream { Box::pin(futures::stream::iter([item])) };
488 let reach = match super::grant_gate::current_reach() {
491 Ok(reach) => reach,
492 Err(e) => return one(PlexusStreamItem::from_plexus_error(meta(self.name()), &e, false)),
493 };
494 let max = shared.opts.max_calls;
495 if shared.counters.open.fetch_add(1, Ordering::AcqRel) >= max {
496 shared.counters.open.fetch_sub(1, Ordering::AcqRel);
497 return one(too_many(self.name(), max));
498 }
499 let guard = OpenGuard(Arc::clone(&shared.counters));
500 let conn = match shared.ensure().await {
501 Ok(c) => c,
502 Err(item) => return one(item),
503 };
504 shared.counters.calls.fetch_add(1, Ordering::Relaxed);
505 let (hop, call_id) = self.hop(&conn, auth, &reach, method);
506 let under = shared.upcalls.open(&call_id, auth, &reach);
508 let path = format!("{}.{method}", conn.ns());
509 let call = json!({ "method": path, "params": params, "hop": hop });
510 match conn.open(&format!("{}.call", conn.ns()), call, shared.opts.timeout).await {
511 Ok((sid, rx)) => {
512 let generation = reach.generation().cloned();
513 let seen = generation.as_ref().map_or(0, GrantsGeneration::current);
514 let instance = instance.map(|path| (Arc::clone(&self.inner), path));
515 Box::pin(CallStream { rx, sid, conn, over: false, _guard: guard, reach, generation, seen, name: self.name().to_string(), instance, under })
516 }
517 Err(item) => one(item),
518 }
519 }
520}
521
522struct OpenGuard(Arc<Counters>);
524
525impl Drop for OpenGuard {
526 fn drop(&mut self) {
527 self.0.open.fetch_sub(1, Ordering::AcqRel);
528 }
529}
530
531struct CallStream {
534 rx: mpsc::Receiver<PlexusStreamItem>,
535 sid: SubKey,
536 conn: Arc<Conn>,
537 over: bool,
538 _guard: OpenGuard,
539 reach: Reach,
542 generation: Option<GrantsGeneration>,
543 seen: u64,
544 name: String,
545 instance: Option<(Arc<Inner>, String)>,
548 under: Option<upcall::UnderGuard>,
551}
552
553impl CallStream {
554 fn finish(&mut self, why: &str) {
556 self.over = true;
557 if let Some(u) = self.under.take() {
558 u.end(why);
559 }
560 }
561
562 fn revoked(&self) -> PlexusStreamItem {
564 let grant = self.reach.grant().map(|g| g.as_str().to_string()).unwrap_or_default();
565 let error = plexus_client::RemoteError::Forbidden {
566 reason: plexus_client::DenyReason::MissingGrant {
567 grant: grant.clone(),
568 scope: "*".into(),
569 roles: Vec::new(),
570 held_on: Vec::new(),
571 },
572 };
573 let mut item = PlexusStreamItem::error(meta(&self.name), error, false);
574 if let PlexusStreamItem::Error { message, .. } = &mut item {
575 *message = format!("Forbidden: `{grant}` is no longer held — the call's grant moved while it ran");
576 }
577 item
578 }
579}
580
581impl Stream for CallStream {
582 type Item = PlexusStreamItem;
583
584 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
585 if self.over {
586 return Poll::Ready(None);
587 }
588 match self.rx.poll_recv(cx) {
589 Poll::Ready(Some(item)) => {
590 if let (Some((inner, path)), Some(m)) = (&self.instance, item.metadata()) {
591 inner.names.observe(path, &m.plexus_hash);
592 }
593 let terminal = matches!(item, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. });
594 let moved = self.generation.as_ref().map(GrantsGeneration::current).filter(|g| *g != self.seen);
595 if let (false, Some(g)) = (terminal, moved) {
596 self.seen = g;
597 if self.reach.current().is_none() {
598 let sid = self.sid.clone();
599 self.conn.unsubscribe(&sid);
600 self.finish("its grant was revoked");
601 return Poll::Ready(Some(self.revoked()));
602 }
603 }
604 if terminal {
605 self.finish("it ended");
606 }
607 Poll::Ready(Some(item))
608 }
609 Poll::Ready(None) => {
610 self.finish("the connection closed");
612 Poll::Ready(Some(unavailable(&self.name, "the connection closed")))
613 }
614 Poll::Pending => Poll::Pending,
615 }
616 }
617}
618
619impl Drop for CallStream {
620 fn drop(&mut self) {
621 if !self.over {
622 self.conn.unsubscribe(&self.sid);
623 }
624 }
625}
626
627#[async_trait]
628impl Activation for RemoteChild {
629 type Methods = ChildMethods;
630
631 fn namespace(&self) -> &str {
632 self.name()
633 }
634
635 fn version(&self) -> &str {
636 &self.inner.schema.version
637 }
638
639 fn description(&self) -> &str {
640 &self.inner.schema.description
641 }
642
643 fn long_description(&self) -> Option<&str> {
644 self.inner.schema.long_description.as_deref()
645 }
646
647 fn methods(&self) -> Vec<&str> {
648 self.inner.schema.methods.iter().map(|m| m.name.as_str()).collect()
649 }
650
651 fn method_help(&self, method: &str) -> Option<String> {
652 self.inner.schema.methods.iter().find(|m| m.name == method).map(|m| m.description.clone())
653 }
654
655 async fn call(&self, method: &str, params: Value, auth: Option<&AuthContext>, _raw: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
656 if method == "schema" {
657 return Ok(self.schema_stream(¶ms));
658 }
659 if let Some(path) = method.strip_suffix(".schema") {
661 if let Some(s) = self.node(path) {
662 return Ok(self.schema_stream_of(s, &s.namespace, ¶ms));
663 }
664 return match self.slot_of(path) {
667 Some(_) => Ok(self.name_schema(path, ¶ms, auth).await),
668 None => Err(self.unreached(method)),
669 };
670 }
671 let found = match method.rsplit_once('.') {
672 Some((path, name)) => match self.node(path) {
674 Some(s) => s.methods.iter().find(|m| m.name == name && m.role == MethodRole::Rpc),
675 None => match self.slot_of(path) {
680 Some((_, instance)) => return Ok(self.forward(method, params, auth, Some(instance)).await),
681 None => return Err(self.unreached(method)),
682 },
683 },
684 None => self.inner.schema.methods.iter().find(|m| m.name == method && m.role == MethodRole::Rpc),
685 };
686 let Some(m) = found else {
687 return Err(PlexusError::MethodNotFound { activation: self.name().to_string(), method: method.to_string() });
688 };
689 if m.input.is_some() {
692 return Err(PlexusError::ExecutionError(format!(
693 "`{}.{method}` takes an input stream, and a hop to a remote child does not forward one yet",
694 self.name()
695 )));
696 }
697 Ok(self.forward(method, params, auth, None).await)
698 }
699
700 fn into_rpc_methods(self) -> jsonrpsee::Methods {
703 jsonrpsee::Methods::new()
704 }
705
706 fn plugin_schema(&self) -> PluginSchema {
707 self.inner.schema.clone()
708 }
709
710 fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
714 self.inner.nodes.clone()
715 }
716}
717
718#[async_trait]
719impl ChildRouter for RemoteChild {
720 fn router_namespace(&self) -> &str {
721 self.name()
722 }
723
724 async fn router_call(&self, method: &str, params: Value, auth: Option<&AuthContext>, raw: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
725 Activation::call(self, method, params, auth, raw).await
726 }
727
728 async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
729 None
730 }
731
732 fn router_schema(&self) -> Option<PluginSchema> {
733 Some(self.inner.schema.clone())
734 }
735
736 fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
737 self.inner.nodes.clone()
738 }
739}
740
741#[cfg(test)]
742mod tests {
743 use super::*;
744
745 fn raw(methods: Value, roles: Value) -> Value {
746 json!({ "namespace": "stub", "version": "0.1.0", "description": "d", "self_hash": "h", "hash": "h", "methods": methods, "roles": roles })
747 }
748
749 fn m(name: &str) -> Value {
750 json!({ "name": name, "description": "", "hash": "x", "streaming": false, "bidirectional": false })
751 }
752
753 #[test]
757 fn a_method_stating_neither_cardinality_nor_streaming_is_refused() {
758 let silent = json!({ "name": "quiet", "description": "", "hash": "x" });
759 let e = mount_schema("echo", raw(json!([m("echo"), silent]), json!({}))).unwrap_err();
760 assert!(e.contains("`quiet`") && e.contains("neither cardinality"), "{e}");
761 }
762
763 #[test]
764 fn the_mount_name_wins_and_roles_are_requalified() {
765 let s = mount_schema("echo", raw(json!([m("echo"), m("shout")]), json!({ "viewer": ["stub.echo"], "editor": ["stub.echo", "stub.shout"] }))).unwrap();
766 assert_eq!(s.namespace, "echo");
767 assert_eq!(s.roles["viewer"], vec!["echo.echo".to_string()]);
768 assert_eq!(s.roles["editor"], vec!["echo.echo".to_string(), "echo.shout".to_string()]);
769 }
770
771 #[test]
773 fn a_child_with_children_mounts_and_its_method_grants_are_requalified() {
774 let mut inner = m("inner");
775 inner["role"] = json!({ "kind": "static_child" });
776 let mut own = m("echo");
777 own["grant"] = json!("stub.echo");
778 let s = mount_schema("echo", raw(json!([own, inner]), json!({}))).unwrap();
779 assert_eq!(s.methods[0].grant.as_deref(), Some("echo.echo"));
780 assert_eq!(s.methods[1].role, MethodRole::StaticChild);
781 let mut slot = m("item");
782 slot["role"] = json!({ "kind": "dynamic_child", "list_method": "names" });
783 let nested = raw(json!([m("echo"), s_inner(), slot]), json!({}));
784 assert_eq!(link::static_children(&nested), vec!["inner".to_string()], "a dynamic child is a slot, not walked");
785 let mut root = raw(json!([m("call")]), json!({}));
787 root["children"] = json!([{ "namespace": "greeter", "description": "", "hash": "g" }]);
788 assert_eq!(link::static_children(&root), vec!["greeter".to_string()]);
789 }
790
791 fn s_inner() -> Value {
792 let mut inner = m("inner");
793 inner["role"] = json!({ "kind": "static_child" });
794 inner
795 }
796
797 #[test]
799 fn the_tree_hash_covers_every_level() {
800 let top = raw(json!([m("echo")]), json!({}));
801 let flat = link::Kept { top: top.clone(), nodes: vec![] };
802 assert_eq!(flat.hash(), link::schema_hash(&top), "a flat child's hash is its schema's, as before");
803 let mut c = raw(json!([m("m")]), json!({}));
804 let one = link::Kept { top: top.clone(), nodes: vec![("a.b".into(), c.clone())] }.hash();
805 c["hash"] = json!("other");
806 let two = link::Kept { top, nodes: vec![("a.b".into(), c)] }.hash();
807 assert_ne!(one, two);
808 }
809
810 #[test]
811 fn typed_error_fields_cross_whole() {
812 let item = unavailable("echo", "gone");
813 let v = serde_json::to_value(&item).unwrap();
814 assert_eq!(v["error_kind"], "child_unavailable");
815 assert_eq!(v["code"], "child_unavailable");
816 assert_eq!(v["child"], "echo");
817 let back: PlexusStreamItem = serde_json::from_value(v.clone()).unwrap();
818 assert_eq!(back.error_kind(), Some("child_unavailable"));
819 assert_eq!(serde_json::to_value(&back).unwrap(), v);
820 let plain = PlexusStreamItem::error(meta("x"), plexus_client::RemoteError::Execution { message: "m".into() }, false);
823 let pv = serde_json::to_value(&plain).unwrap();
824 let keys: Vec<_> = pv.as_object().unwrap().keys().cloned().collect();
825 assert_eq!(keys, ["code", "error", "message", "metadata", "recoverable", "type"]);
826 }
827}