Skip to main content

plexus_core/plexus/remote_child/
link.rs

1//! One connection to a child — its frames out, its answers routed back —
2//! and the supervisor that starts it, notices it gone and starts it again.
3//!
4//! A [`Conn`] is one process (stdio) or one socket (ws): a writer task that
5//! drains everything queued into one write per wakeup (spec/11), a reader
6//! that routes a response by `id` to the call that opened it (registering
7//! the subscription before the next message is read, so an item can never
8//! beat its id — spec/02) and an item by `subscription` to that call's
9//! bounded channel, and — when the far side goes — one `child_unavailable`
10//! to every call it held. A [`Shared`] outlives its connections: it keeps
11//! the schema's hash, the counters and the restart window.
12
13use std::borrow::Cow;
14use std::collections::{HashMap, HashSet, VecDeque};
15use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
16use std::sync::{Arc, Mutex, OnceLock, Weak};
17use std::time::{Duration, Instant};
18
19use serde::Deserialize;
20use serde_json::value::RawValue;
21use serde_json::{json, Value};
22use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWriteExt, BufReader};
23use tokio::sync::{mpsc, oneshot, Notify};
24
25use super::spec::{ChildOptions, ChildSpec};
26use super::upcall::{self, Served, Upcalls};
27use crate::plexus::types::{PlexusStreamItem, StreamMetadata};
28use plexus_client::RemoteError;
29
30/// A subscription id as the child spelled it (its JSON text: `4`, `"a"`).
31pub(super) type SubKey = String;
32
33pub(super) fn meta(name: &str) -> StreamMetadata {
34    StreamMetadata::new(vec![name.to_string()], crate::plexus::context::PlexusContext::hash())
35}
36
37/// `child_unavailable` (spec/12 rule 5): one error, and the end.
38pub(super) fn unavailable(name: &str, why: &str) -> PlexusStreamItem {
39    PlexusStreamItem::error(meta(name), RemoteError::ChildUnavailable { child: name.into(), reason: why.into() }, true)
40}
41
42/// `child_timeout`: the child did not open the call in the service's time.
43pub(super) fn timed_out(name: &str, timeout: Duration) -> PlexusStreamItem {
44    let error = RemoteError::ChildTimeout { child: name.into(), timeout_ms: timeout.as_millis() as u64 };
45    let mut item = PlexusStreamItem::error(meta(name), error, true);
46    if let PlexusStreamItem::Error { message, .. } = &mut item {
47        *message = format!("child {name} did not open the call in {timeout:?}");
48    }
49    item
50}
51
52/// `too_many_calls` (spec/05, 09): as a connection's limit answers.
53pub(super) fn too_many(name: &str, max: usize) -> PlexusStreamItem {
54    PlexusStreamItem::error(meta(name), RemoteError::TooManyCalls { max: max as u64, child: Some(name.into()) }, true)
55}
56
57/// A call the child refused at the JSON-RPC layer (`{code, message,
58/// data?}`): its `data` when that is a typed [`RemoteError`] (RETURNS-6),
59/// else what its code says; spec/05's `message` and `code` as it sent them.
60fn refused(name: &str, e: &Value) -> PlexusStreamItem {
61    let code = e.get("code").map(|c| match c {
62        Value::String(s) => s.clone(),
63        other => other.to_string(),
64    });
65    let message = e.get("message").and_then(Value::as_str).unwrap_or("the child refused the call").to_string();
66    let error = e
67        .get("data")
68        .and_then(|d| serde_json::from_value::<RemoteError>(d.clone()).ok())
69        .unwrap_or_else(|| super::peer::remote_error_of_code(e.get("code").and_then(Value::as_i64).unwrap_or(-32000), &message));
70    let fields = crate::plexus::types::spec_fields(&error);
71    PlexusStreamItem::Error { metadata: meta(name), message, code, recoverable: false, error, fields }
72}
73
74/// Counters that outlive a connection.
75#[derive(Default)]
76pub(super) struct Counters {
77    pub unasked: AtomicU64,
78    pub calls: AtomicU64,
79    pub restarts: AtomicU64,
80    pub open: AtomicUsize,
81}
82
83/// How a call's open failed.
84pub(super) enum OpenFail {
85    /// The connection went before the child answered.
86    Gone(String),
87    /// The child answered the open with a JSON-RPC error.
88    Refused(Value),
89}
90
91struct Opening {
92    reply: oneshot::Sender<Result<SubKey, OpenFail>>,
93    items: Sub,
94}
95
96/// An open call's items: where they go, and the method called — the
97/// `content_type` a progress item as main wrote it (none of its own) is
98/// named for (RETURNS-36, re-review #3).
99struct Sub {
100    tx: mpsc::Sender<PlexusStreamItem>,
101    method: Arc<str>,
102}
103
104/// How long after its `true` an unsubscribed call's late item is still the
105/// cancel's tail: spec/04 lets an item already in flight land just after
106/// the response (the kit allows 50 ms).
107const TAIL: Duration = Duration::from_millis(250);
108
109#[derive(Default)]
110struct Routes {
111    pending: HashMap<u64, Opening>,
112    subs: HashMap<SubKey, Sub>,
113    /// Unsubscribes sent and not yet answered, and those answered within
114    /// [`TAIL`]: their late items are the cancel's tail, dropped quietly
115    /// (not "unasked").
116    closing: HashMap<u64, SubKey>,
117    closing_subs: HashSet<SubKey>,
118    answered: VecDeque<(Instant, SubKey)>,
119    /// Opens past their timeout: a late answer is unsubscribed at once.
120    abandoned: HashSet<u64>,
121}
122
123impl Routes {
124    /// Forget the cancels answered more than [`TAIL`] ago.
125    fn expire_tails(&mut self, now: Instant) {
126        while self.answered.front().is_some_and(|(t, _)| now.duration_since(*t) >= TAIL) {
127            if let Some((_, key)) = self.answered.pop_front() {
128                self.closing_subs.remove(&key);
129            }
130        }
131    }
132}
133
134/// One connection to the child.
135pub(super) struct Conn {
136    pub name: String,
137    pub pid: Option<u32>,
138    /// The child's own namespace (its `_info`'s `backend`).
139    pub ns: OnceLock<String>,
140    out: mpsc::UnboundedSender<Vec<u8>>,
141    routes: Mutex<Routes>,
142    next_id: AtomicU64,
143    alive: AtomicBool,
144    /// Asked to end (the service let go of the child, or refused its schema).
145    pub shutdown: Notify,
146    buffer: usize,
147    counters: Arc<Counters>,
148    /// NEST-11: the mount's calls back from its child, when it takes them
149    /// (a child it spawned or dialed); unset, a request from the far side
150    /// is refused.
151    pub up: OnceLock<Arc<Upcalls>>,
152    /// NEST-11: the calls back this connection is serving.
153    served: Arc<Served>,
154    /// DYNAUTH-8: on `wss://`, the sha256 (hex) of the key the far side's
155    /// certificate holds (its SubjectPublicKeyInfo).
156    pub tls_key: OnceLock<String>,
157    /// DYNAUTH-5: the Ed25519 key the far side proved at `_info`
158    /// (`key:<hex>`), if it proved one.
159    pub peer_key: OnceLock<String>,
160}
161
162/// One message, read in one pass: a notification's item stays raw until
163/// its call is known (then it is read once, as the item).
164#[derive(Deserialize)]
165struct Msg<'a> {
166    #[serde(default)]
167    id: Option<Value>,
168    #[serde(default, borrow)]
169    result: Option<&'a RawValue>,
170    #[serde(default)]
171    error: Option<Value>,
172    #[serde(default, borrow)]
173    method: Option<Cow<'a, str>>,
174    #[serde(default, borrow)]
175    params: Option<Notif<'a>>,
176}
177
178#[derive(Deserialize)]
179struct Notif<'a> {
180    #[serde(default)]
181    subscription: Option<Value>,
182    #[serde(default, borrow)]
183    result: Option<&'a RawValue>,
184}
185
186/// A message whose `params` are not an object (a request with positional
187/// params): read loosely, only to answer it.
188#[derive(Deserialize)]
189struct Loose<'a> {
190    #[serde(default)]
191    id: Option<Value>,
192    #[serde(default, borrow)]
193    method: Option<Cow<'a, str>>,
194}
195
196#[derive(Deserialize)]
197struct Kind<'a> {
198    #[serde(rename = "type", borrow)]
199    kind: Cow<'a, str>,
200}
201
202impl Conn {
203    pub(super) fn new(name: &str, pid: Option<u32>, out: mpsc::UnboundedSender<Vec<u8>>, buffer: usize, counters: Arc<Counters>) -> Arc<Self> {
204        Arc::new(Self {
205            name: name.to_string(),
206            pid,
207            ns: OnceLock::new(),
208            out,
209            routes: Mutex::new(Routes::default()),
210            next_id: AtomicU64::new(1),
211            alive: AtomicBool::new(true),
212            shutdown: Notify::new(),
213            buffer,
214            counters,
215            up: OnceLock::new(),
216            served: Arc::default(),
217            tls_key: OnceLock::new(),
218            peer_key: OnceLock::new(),
219        })
220    }
221
222    pub(super) fn alive(&self) -> bool {
223        self.alive.load(Ordering::Acquire)
224    }
225
226    pub(super) fn ns(&self) -> &str {
227        self.ns.get().map(String::as_str).unwrap_or(&self.name)
228    }
229
230    fn send(&self, frame: &Value) {
231        let _ = self.out.send(serde_json::to_vec(frame).unwrap_or_default());
232    }
233
234    /// Open a call: `method` with `params` (a `{ns}.call`'s params, or
235    /// `_info`'s null); the subscription id back within `timeout`, its items
236    /// already routed to the receiver.
237    pub(super) async fn open(&self, method: &str, params: Value, timeout: Duration) -> Result<(SubKey, mpsc::Receiver<PlexusStreamItem>), PlexusStreamItem> {
238        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
239        let (tx, rx) = mpsc::channel(self.buffer);
240        let (reply, answer) = oneshot::channel();
241        {
242            let mut r = self.routes.lock().unwrap();
243            if !self.alive() {
244                return Err(unavailable(&self.name, "the connection has closed"));
245            }
246            // a `{ns}.call`'s params name the method called (`echo.count`)
247            let called = params.get("method").and_then(Value::as_str).unwrap_or(method);
248            r.pending.insert(id, Opening { reply, items: Sub { tx, method: called.into() } });
249        }
250        self.send(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }));
251        match tokio::time::timeout(timeout, answer).await {
252            Ok(Ok(Ok(key))) => Ok((key, rx)),
253            Ok(Ok(Err(OpenFail::Gone(why)))) => Err(unavailable(&self.name, &why)),
254            Ok(Err(_)) => Err(unavailable(&self.name, "the connection closed before the call opened")),
255            Ok(Ok(Err(OpenFail::Refused(e)))) => Err(refused(&self.name, &e)),
256            Err(_) => {
257                let mut r = self.routes.lock().unwrap();
258                if r.pending.remove(&id).is_some() {
259                    r.abandoned.insert(id);
260                }
261                Err(timed_out(&self.name, timeout))
262            }
263        }
264    }
265
266    /// The caller let go of `key` before its end: forget it, and tell the
267    /// child (`{ns}.call_unsub [sid]`, spec/04).
268    pub(super) fn unsubscribe(&self, key: &str) {
269        let id = {
270            let mut r = self.routes.lock().unwrap();
271            if r.subs.remove(key).is_none() || !self.alive() {
272                return;
273            }
274            let id = self.next_id.fetch_add(1, Ordering::Relaxed);
275            r.closing.insert(id, key.to_string());
276            r.closing_subs.insert(key.to_string());
277            id
278        };
279        let method = serde_json::to_string(&format!("{}.call_unsub", self.ns())).unwrap_or_default();
280        let frame = format!(r#"{{"jsonrpc":"2.0","id":{id},"method":{method},"params":[{key}]}}"#);
281        let _ = self.out.send(frame.into_bytes());
282    }
283
284    /// How many subscriptions are routed now.
285    pub(super) fn routed(&self) -> usize {
286        self.routes.lock().unwrap().subs.len()
287    }
288
289    /// One message from the child.
290    pub(super) async fn on_message(&self, raw: &[u8]) {
291        let msg: Msg<'_> = match serde_json::from_slice(raw) {
292            Ok(m) => m,
293            Err(e) => match serde_json::from_slice::<Loose<'_>>(raw) {
294                Ok(Loose { id: Some(id), method: Some(method) }) => return self.request(id, &method, raw),
295                _ => {
296                    tracing::warn!(target: "plexus::child", child = %self.name, "an unreadable message from the child: {e}");
297                    return;
298                }
299            },
300        };
301        if let Some(method) = msg.method {
302            if let Some(id) = msg.id {
303                return self.request(id, &method, raw);
304            }
305            match msg.params {
306                Some(Notif { subscription: Some(sub), result: Some(item) }) => self.route(sub.to_string(), item).await,
307                _ => tracing::warn!(target: "plexus::child", child = %self.name, %method, "a notification without subscription and result"),
308            }
309            return;
310        }
311        let Some(id) = msg.id.as_ref().and_then(Value::as_u64) else { return };
312        let mut r = self.routes.lock().unwrap();
313        if let Some(open) = r.pending.remove(&id) {
314            match (msg.result, msg.error) {
315                (Some(sid), _) => {
316                    let key = match serde_json::from_str::<Value>(sid.get()) {
317                        Ok(v) => v.to_string(),
318                        Err(_) => sid.get().to_string(),
319                    };
320                    r.subs.insert(key.clone(), open.items);
321                    let _ = open.reply.send(Ok(key));
322                }
323                (None, e) => {
324                    let _ = open.reply.send(Err(OpenFail::Refused(e.unwrap_or_else(|| json!({ "message": "an answer with neither result nor error" })))));
325                }
326            }
327        } else if let Some(key) = r.closing.remove(&id) {
328            // Answered: an item still in flight is the tail for TAIL more.
329            let now = Instant::now();
330            r.expire_tails(now);
331            r.answered.push_back((now, key));
332        } else if r.abandoned.remove(&id) {
333            // A call opened after its caller was told `child_timeout`: stop it.
334            if let Some(sid) = msg.result.and_then(|s| serde_json::from_str::<Value>(s.get()).ok()) {
335                let key = sid.to_string();
336                let uid = self.next_id.fetch_add(1, Ordering::Relaxed);
337                r.closing.insert(uid, key.clone());
338                r.closing_subs.insert(key.clone());
339                drop(r);
340                let method = serde_json::to_string(&format!("{}.call_unsub", self.ns())).unwrap_or_default();
341                let _ = self.out.send(format!(r#"{{"jsonrpc":"2.0","id":{uid},"method":{method},"params":[{key}]}}"#).into_bytes());
342            }
343        }
344    }
345
346    /// A request from the child: a call back under a call it serves
347    /// (NEST-11, `_host.call`), when this mount takes them; anything else is
348    /// refused.
349    fn request(&self, id: Value, method: &str, raw: &[u8]) {
350        if let (Some(up), true) = (self.up.get(), method == upcall::HOST_CALL || method == upcall::HOST_CALL_UNSUB) {
351            let params = serde_json::from_slice::<Value>(raw).ok().and_then(|mut v| v.get_mut("params").map(Value::take)).unwrap_or(Value::Null);
352            return upcall::on_request(up, &self.served, &self.out, &self.name, id, method, params);
353        }
354        self.refuse_request(id, method)
355    }
356
357    /// A child asks its service nothing else (spec/12): answered, not served.
358    fn refuse_request(&self, id: Value, method: &str) {
359        tracing::warn!(target: "plexus::child", child = %self.name, %method, "a request from the child refused");
360        self.send(&json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": "a service answers no requests from its child" } }));
361    }
362
363    async fn route(&self, key: SubKey, raw: &RawValue) {
364        let (tx, method) = {
365            let mut r = self.routes.lock().unwrap();
366            match r.subs.get(&key) {
367                Some(sub) => (sub.tx.clone(), Arc::clone(&sub.method)),
368                None => {
369                    r.expire_tails(Instant::now());
370                    if !r.closing_subs.contains(&key) {
371                        drop(r);
372                        self.counters.unasked.fetch_add(1, Ordering::Relaxed);
373                        tracing::warn!(target: "plexus::child", child = %self.name, subscription = %key, "unasked item dropped");
374                    }
375                    return;
376                }
377            }
378        };
379        // RETURNS-36: a peer on plexus-wire's spec as main wrote it is read
380        // into 0.8's shape (`peer::item`) when — only when — it does not
381        // read as 0.8.
382        let parsed = serde_json::from_str::<PlexusStreamItem>(raw.get()).or_else(|e| {
383            super::peer::item(raw.get(), &method)
384                .and_then(|v| serde_json::from_value::<PlexusStreamItem>(v).ok())
385                .ok_or(e)
386        });
387        let item = match parsed {
388            Ok(item) => item,
389            Err(e) => {
390                let kind = serde_json::from_str::<Kind<'_>>(raw.get()).map(|k| k.kind.into_owned()).unwrap_or_default();
391                if kind != "error" {
392                    // An item kind this service does not know (spec/03: a
393                    // reader skips it) — or one that does not read at all.
394                    tracing::debug!(target: "plexus::child", child = %self.name, subscription = %key, %kind, "an item kind not relayed: {e}");
395                    return;
396                }
397                // RETURNS-36 (review #4): an error item is the call's end
398                // (spec/03); skipped, the call would wait for an end that
399                // never comes. It ends here, naming what could not be read,
400                // and the child is told to stop.
401                tracing::warn!(target: "plexus::child", child = %self.name, subscription = %key, "an error item not read: {e}");
402                self.unsubscribe(&key);
403                let error = plexus_client::RemoteError::Execution {
404                    message: format!("child {} sent an error item this service could not read: {e}", self.name),
405                };
406                PlexusStreamItem::error(meta(&self.name), error, false)
407            }
408        };
409        if matches!(item, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. }) {
410            self.routes.lock().unwrap().subs.remove(&key);
411        }
412        match tx.try_send(item) {
413            Ok(()) => {}
414            // The caller has not read the call's buffer: wait for it
415            // (lossless; the child's other calls wait behind it).
416            Err(mpsc::error::TrySendError::Full(item)) => {
417                let _ = tx.send(item).await;
418            }
419            Err(mpsc::error::TrySendError::Closed(_)) => {}
420        }
421    }
422
423    /// The far side is gone: every open call gets one `child_unavailable`.
424    pub(super) fn on_gone(&self, why: &str) {
425        let (subs, pending) = {
426            let mut r = self.routes.lock().unwrap();
427            self.alive.store(false, Ordering::Release);
428            self.served.abort_all();
429            r.closing.clear();
430            r.closing_subs.clear();
431            r.answered.clear();
432            r.abandoned.clear();
433            (std::mem::take(&mut r.subs), std::mem::take(&mut r.pending))
434        };
435        for (_, Sub { tx, .. }) in subs {
436            match tx.try_send(unavailable(&self.name, why)) {
437                Err(mpsc::error::TrySendError::Full(item)) => {
438                    tokio::spawn(async move {
439                        let _ = tx.send(item).await;
440                    });
441                }
442                _ => {}
443            }
444        }
445        for (_, open) in pending {
446            let _ = open.reply.send(Err(OpenFail::Gone(why.to_string())));
447        }
448    }
449}
450
451/// Read newline-delimited messages from `r`, one wakeup per read: every
452/// whole line in the buffer is routed before the next read.
453pub(super) async fn read_lines<R: AsyncRead + Unpin>(conn: &Conn, r: R) {
454    let mut r = BufReader::with_capacity(1 << 17, r);
455    let mut carry: Vec<u8> = Vec::new();
456    loop {
457        let buf = match r.fill_buf().await {
458            Ok(b) if !b.is_empty() => b,
459            _ => break,
460        };
461        let n = buf.len();
462        let mut start = 0;
463        while let Some(i) = buf[start..].iter().position(|b| *b == b'\n') {
464            let end = start + i;
465            if carry.is_empty() {
466                let line = &buf[start..end];
467                if line.iter().any(|b| !b.is_ascii_whitespace()) {
468                    conn.on_message(line).await;
469                }
470            } else {
471                carry.extend_from_slice(&buf[start..end]);
472                let line = std::mem::take(&mut carry);
473                if line.iter().any(|b| !b.is_ascii_whitespace()) {
474                    conn.on_message(&line).await;
475                }
476            }
477            start = end + 1;
478        }
479        carry.extend_from_slice(&buf[start..]);
480        r.consume(n);
481    }
482}
483
484/// The writer: everything queued, one write per wakeup, each line whole.
485pub(super) async fn write_lines<W: tokio::io::AsyncWrite + Unpin>(mut w: W, mut rx: mpsc::UnboundedReceiver<Vec<u8>>) {
486    while let Some(first) = rx.recv().await {
487        let mut buf = first;
488        buf.push(b'\n');
489        while let Ok(more) = rx.try_recv() {
490            buf.extend_from_slice(&more);
491            buf.push(b'\n');
492        }
493        if w.write_all(&buf).await.is_err() || w.flush().await.is_err() {
494            break;
495        }
496    }
497}
498
499/// When the child was mounted, how long each step took.
500#[derive(Debug, Clone, Copy, Default, PartialEq)]
501pub struct MountTimings {
502    /// Spawn (or dial) → its `_info` answered.
503    pub spawn_ms: f64,
504    /// `_info` → its schema answered.
505    pub schema_ms: f64,
506    /// The schema requalified under the mount name and kept.
507    pub merge_ms: f64,
508}
509
510struct LinkState {
511    conn: Option<Arc<Conn>>,
512    down_since: Option<Instant>,
513    why: String,
514    window: VecDeque<Instant>,
515    /// Never again (a restart published another schema): the reason.
516    dead: Option<String>,
517}
518
519/// The child across its connections.
520/// KEEL-19: the word a mount's refusal starts with when a keyed peer meets
521/// a service with no dial key.
522pub const KEYED_MOUNT_NEEDS_A_KEY: &str = "keyed_mount_needs_a_key";
523
524pub(super) struct Shared {
525    pub spec: ChildSpec,
526    pub opts: ChildOptions,
527    pub name: String,
528    /// The hop's `principal`.
529    pub principal: String,
530    pub counters: Arc<Counters>,
531    state: Mutex<LinkState>,
532    dial: tokio::sync::Mutex<()>,
533    /// The mounted schema's hash, as the child published it.
534    pub mounted_hash: OnceLock<String>,
535    /// NEST-11: the child's calls back into the service.
536    pub upcalls: Arc<Upcalls>,
537    /// DYNAUTH-8 (TM-3): who the child proved it was at the mount, pinned:
538    /// a restart that proves another is refused, as one that publishes
539    /// another schema is.
540    pub identity: OnceLock<super::PeerIdentity>,
541}
542
543impl Drop for Shared {
544    fn drop(&mut self) {
545        if let Ok(st) = self.state.lock() {
546            if let Some(c) = &st.conn {
547                c.shutdown.notify_one();
548            }
549        }
550    }
551}
552
553/// The hash a child's schema is compared by across restarts.
554pub(super) fn schema_hash(raw: &Value) -> String {
555    match raw.get("hash").and_then(Value::as_str) {
556        Some(h) => h.to_string(),
557        None => raw.get("methods").map(Value::to_string).unwrap_or_default(),
558    }
559}
560
561/// NEST-4 · what a mount keeps of a child: its own schema and, walked at
562/// mount, every static child below it by dotted path (`a`, `a.b`), each as
563/// the child published it.
564#[derive(Debug, Clone)]
565pub(super) struct Kept {
566    pub top: Value,
567    pub nodes: Vec<(String, Value)>,
568}
569
570impl Kept {
571    /// The whole tree's hash, compared across restarts: a flat child's is its
572    /// schema's, as before; a child with children adds each one's, by path,
573    /// so a changed grandchild changes it whatever the child's own hash
574    /// covers.
575    pub fn hash(&self) -> String {
576        let mut h = schema_hash(&self.top);
577        for (path, raw) in &self.nodes {
578            h.push_str(&format!(" {path}={}", schema_hash(raw)));
579        }
580        h
581    }
582}
583
584/// The static children a schema names, by the name each is reached through:
585/// its methods whose role is `static_child` when any method states a child
586/// role; else its `children` side-table (IR-4) — a service's root, whose
587/// registered activations are listed there and nowhere else.
588pub(super) fn static_children(raw: &Value) -> Vec<String> {
589    let methods = raw.get("methods").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
590    let kind = |m: &Value| m.get("role").and_then(|r| r.get("kind").or(Some(r))).and_then(Value::as_str).map(str::to_string);
591    // A macro-built activation says its children by role (a static child's
592    // name is its method's, which may differ from the child's namespace);
593    // a service's root (a DynamicHub) lists its activations in `children`.
594    if methods.iter().any(|m| kind(m).is_some_and(|k| k.ends_with("_child"))) {
595        // NEST-6: a peer slot is a `static_child` marked `peer` on the
596        // wire (NEST-7) — a slot, reached by name, not a level to walk.
597        let peer = |m: &Value| m.get("role").and_then(|r| r.get("peer")).and_then(Value::as_bool).unwrap_or(false);
598        return methods.iter().filter(|m| kind(m).as_deref() == Some("static_child") && !peer(m)).filter_map(|m| m.get("name").and_then(Value::as_str)).map(str::to_string).collect();
599    }
600    raw.get("children").and_then(Value::as_array).map(|c| c.iter().filter_map(|c| c.get("namespace").and_then(Value::as_str)).map(str::to_string).collect()).unwrap_or_default()
601}
602
603impl Shared {
604    pub(super) fn new(spec: ChildSpec, opts: ChildOptions, principal: String) -> Arc<Self> {
605        let upcalls = Upcalls::new(opts.host.clone().or_else(crate::plexus::service_scope::current), opts.legacy_upcalls);
606        upcalls.set_schemas(&opts.schemas);
607        // KEEL-32 (R3-1): before the handshake — a child that asks at once
608        // finds nothing consented and, revoked, nothing at all.
609        if opts.consent_required {
610            upcalls.set_consent(Some(Vec::new()));
611        }
612        if let Some(why) = &opts.revoked {
613            upcalls.revoke(why);
614        }
615        Arc::new(Self {
616            upcalls,
617            name: spec.name().to_string(),
618            spec,
619            opts,
620            principal,
621            counters: Arc::new(Counters::default()),
622            state: Mutex::new(LinkState { conn: None, down_since: None, why: String::new(), window: VecDeque::new(), dead: None }),
623            dial: tokio::sync::Mutex::new(()),
624            mounted_hash: OnceLock::new(),
625            identity: OnceLock::new(),
626        })
627    }
628
629    pub(super) fn current(&self) -> Option<Arc<Conn>> {
630        self.state.lock().unwrap().conn.clone()
631    }
632
633    pub(super) fn install(&self, conn: Arc<Conn>) {
634        self.state.lock().unwrap().conn = Some(conn);
635    }
636
637    /// The service asks for itself (the mount): no caller, no verdict.
638    fn own_hop(&self) -> Value {
639        json!({ "principal": self.principal, "for": [], "limit": null, "call": uuid::Uuid::new_v4().to_string() })
640    }
641
642    /// Start (or dial) the child and ask its `_info` and its schema, then
643    /// walk its static children (NEST-4), all within one `timeout`.
644    pub(super) async fn connect_once(self: &Arc<Self>) -> Result<(Arc<Conn>, Kept, MountTimings), String> {
645        let t0 = Instant::now();
646        let conn = match &self.spec {
647            ChildSpec::Stdio { argv, .. } => self.spawn_stdio(argv)?,
648            ChildSpec::Ws { url, .. } => self.dial_ws(url).await?,
649        };
650        let asked = async {
651            // DYNAUTH-5: `_info` carries a nonce; a far side with a key of
652            // its own answers it signed (`key`, `proof`), and that key is
653            // registered and pinned with the mount. One that answers a key
654            // it cannot prove is refused; one that names none has none.
655            // KEEL-19: the proof is made for this service — the principal its
656            // connection proved (`asker` on a pipe, where nothing is proved):
657            // one made for another asker, relayed, is refused.
658            let nonce = crate::plexus::peer_token::random_nonce();
659            let info = ask(&conn, "_info", json!({ "nonce": nonce, "asker": self.principal }), self.opts.timeout).await.map_err(|e| format!("`_info`: {e}"))?;
660            let ns = info.get("backend").and_then(Value::as_str).ok_or("its `_info` names no backend")?.to_string();
661            if let Some(key) = info.get("key").and_then(Value::as_str) {
662                // KEEL-19: the asker a key proof is made for is this
663                // service's key, which its dial proved; a principal no
664                // transport proves (`service:dyn`) is every service's.
665                if crate::plexus::peer_token::key_of(&self.principal).is_none() {
666                    return Err(format!(
667                        "{KEYED_MOUNT_NEEDS_A_KEY}: its `_info` proves the key {key}, and this service dials as `{}`, which no transport proves: give the service a dial key (ChildOptions::key) to mount a keyed peer",
668                        self.principal
669                    ));
670                }
671                let proof = info.get("proof").and_then(Value::as_str).unwrap_or_default();
672                crate::plexus::peer_token::check_key_proof_for(key, proof, &nonce, &ns, &self.principal).map_err(|e| {
673                    let made_for = info.get("asker").and_then(Value::as_str).filter(|a| *a != self.principal).map(|a| format!(" (it was made for {a}, not for {})", self.principal)).unwrap_or_default();
674                    format!("its `_info` names the key {key} without proving it to this service: {e}{made_for}")
675                })?;
676                let _ = conn.peer_key.set(key.to_string());
677            }
678            let _ = conn.ns.set(ns.clone());
679            let t1 = Instant::now();
680            let deadline = t1 + self.opts.timeout;
681            let params = json!({ "method": format!("{ns}.schema"), "params": {}, "hop": self.own_hop() });
682            let schema = ask(&conn, &format!("{ns}.call"), params, self.opts.timeout).await.map_err(|e| format!("its schema: {e}"))?;
683            let nodes = self.walk(&conn, &ns, &schema, deadline).await?;
684            Ok::<_, String>((Kept { top: schema, nodes }, t1))
685        };
686        match asked.await {
687            Ok((schema, t1)) => {
688                let t = MountTimings { spawn_ms: (t1 - t0).as_secs_f64() * 1e3, schema_ms: t1.elapsed().as_secs_f64() * 1e3, merge_ms: 0.0 };
689                Ok((conn, schema, t))
690            }
691            Err(why) => {
692                conn.shutdown.notify_one();
693                Err(why)
694            }
695        }
696    }
697
698    /// NEST-4 · the static tree below `top`, depth-first: `{ns}.<path>.schema`
699    /// for each static child, at most `max_depth` levels down and before
700    /// `deadline` (the mount's one timeout), each asked as the mount asks the
701    /// child's own (no caller, no verdict). A dynamic child is not walked:
702    /// its role, on its parent's schema, is the slot. Past the depth, or the
703    /// time, the mount fails naming the path.
704    pub(super) async fn walk(&self, conn: &Conn, ns: &str, top: &Value, deadline: Instant) -> Result<Vec<(String, Value)>, String> {
705        let mut out = Vec::new();
706        let mut stack: Vec<String> = static_children(top).into_iter().rev().collect();
707        while let Some(path) = stack.pop() {
708            let depth = path.split('.').count();
709            if depth > self.opts.max_depth {
710                return Err(format!("its child `{path}` is {depth} levels down, past --child-max-depth ({})", self.opts.max_depth));
711            }
712            let left = deadline.saturating_duration_since(Instant::now());
713            if left.is_zero() {
714                return Err(format!("its tree was not walked within {:?}: stopped at `{path}`", self.opts.timeout));
715            }
716            let params = json!({ "method": format!("{ns}.{path}.schema"), "params": {}, "hop": self.own_hop() });
717            let raw = ask(conn, &format!("{ns}.call"), params, left).await.map_err(|e| format!("the schema of its child `{path}`: {e}"))?;
718            for child in static_children(&raw).into_iter().rev() {
719                stack.push(format!("{path}.{child}"));
720            }
721            out.push((path, raw));
722        }
723        Ok(out)
724    }
725
726    fn spawn_stdio(self: &Arc<Self>, argv: &[String]) -> Result<Arc<Conn>, String> {
727        let mut cmd = tokio::process::Command::new(&argv[0]);
728        cmd.args(&argv[1..])
729            .env_clear()
730            .envs(["PATH", "HOME", "LANG"].iter().map(|k| k.to_string()).chain(self.opts.env.iter().cloned()).filter_map(|k| std::env::var(&k).ok().map(|v| (k, v))))
731            .env("PLEXUS_CHILD_NAME", &self.name)
732            .stdin(std::process::Stdio::piped())
733            .stdout(std::process::Stdio::piped())
734            .stderr(std::process::Stdio::piped())
735            .kill_on_drop(true);
736        let mut child = cmd.spawn().map_err(|e| format!("spawning `{}`: {e}", argv[0]))?;
737        let (stdin, stdout, stderr) = (child.stdin.take(), child.stdout.take(), child.stderr.take());
738        let (Some(stdin), Some(stdout), Some(stderr)) = (stdin, stdout, stderr) else {
739            return Err("its pipes were not opened".into());
740        };
741        let (out, out_rx) = mpsc::unbounded_channel();
742        let conn = Conn::new(&self.name, child.id(), out, self.opts.buffer, Arc::clone(&self.counters));
743        let _ = conn.up.set(Arc::clone(&self.upcalls));
744        tokio::spawn(write_lines(stdin, out_rx));
745        let reader = Arc::clone(&conn);
746        let shared = Arc::downgrade(self);
747        tokio::spawn(async move {
748            tokio::select! {
749                _ = read_lines(&reader, stdout) => {}
750                _ = reader.shutdown.notified() => {
751                    let _ = child.start_kill();
752                }
753            }
754            let status = child.wait().await.map(|s| s.to_string()).unwrap_or_else(|e| e.to_string());
755            gone(&shared, &reader, &format!("the process exited ({status})"));
756        });
757        let name = self.name.clone();
758        tokio::spawn(async move {
759            let span = tracing::info_span!(target: "plexus::child", "plexus::child", name = %name);
760            let mut lines = BufReader::new(stderr).lines();
761            while let Ok(Some(l)) = lines.next_line().await {
762                let _e = span.enter();
763                // DYNAUTH-8: a child that logs its frames (plexus-transport's
764                // stdio at debug did) never puts a credential in this log.
765                tracing::info!(target: "plexus::child", child = %name, "{}", crate::plexus::redact::redact_str(&l));
766            }
767        });
768        Ok(conn)
769    }
770
771    #[cfg(feature = "child-ws")]
772    async fn dial_ws(self: &Arc<Self>, url: &str) -> Result<Arc<Conn>, String> {
773        super::ws::dial(self, url).await
774    }
775
776    #[cfg(not(feature = "child-ws"))]
777    async fn dial_ws(self: &Arc<Self>, _url: &str) -> Result<Arc<Conn>, String> {
778        Err("a WebSocket child needs plexus-core's `child-ws` feature".into())
779    }
780
781    /// The connection `conn` is gone; the next call starts another.
782    pub(super) fn lost(&self, conn: &Arc<Conn>, why: &str) {
783        let mut st = self.state.lock().unwrap();
784        if st.conn.as_ref().is_some_and(|c| Arc::ptr_eq(c, conn)) {
785            st.conn = None;
786            st.down_since = Some(Instant::now());
787            st.why = why.to_string();
788            drop(st);
789            tracing::warn!(target: "plexus::child", child = %self.name, "child gone: {why}");
790        }
791    }
792
793    /// A live connection, starting the child again if it died — within the
794    /// backoff, and never past `per_minute` restarts a minute.
795    pub(super) async fn ensure(self: &Arc<Self>) -> Result<Arc<Conn>, PlexusStreamItem> {
796        if let Some(c) = self.live()? {
797            return Ok(c);
798        }
799        let _g = self.dial.lock().await;
800        if let Some(c) = self.live()? {
801            return Ok(c);
802        }
803        let b = self.opts.backoff;
804        let wait = {
805            let mut st = self.state.lock().unwrap();
806            let now = Instant::now();
807            while st.window.front().is_some_and(|t| now.duration_since(*t) >= Duration::from_secs(60)) {
808                st.window.pop_front();
809            }
810            if st.window.len() >= b.per_minute {
811                let next = st.window.front().map(|t| Duration::from_secs(60).saturating_sub(now.duration_since(*t))).unwrap_or_default();
812                return Err(unavailable(&self.name, &format!("{} (restarted {} times in the last minute; the next restart in {:.1} s)", st.why, st.window.len(), next.as_secs_f64())));
813            }
814            let due = st.down_since.unwrap_or(now) + b.delay(st.window.len());
815            due.saturating_duration_since(now)
816        };
817        if wait > self.opts.timeout {
818            let why = self.state.lock().unwrap().why.clone();
819            return Err(unavailable(&self.name, &format!("{why} (restarting in {:.1} s)", wait.as_secs_f64())));
820        }
821        tokio::time::sleep(wait).await;
822        self.state.lock().unwrap().window.push_back(Instant::now());
823        self.counters.restarts.fetch_add(1, Ordering::Relaxed);
824        match self.connect_once().await {
825            Ok((conn, kept, t)) => {
826                let hash = kept.hash();
827                if self.mounted_hash.get().is_some_and(|h| *h != hash) {
828                    conn.shutdown.notify_one();
829                    let why = "schema changed; restart the service".to_string();
830                    tracing::error!(target: "plexus::child", child = %self.name, mounted = ?self.mounted_hash.get(), published = %hash, "the restarted child published another schema; not remounted: restart the service");
831                    self.state.lock().unwrap().dead = Some(why.clone());
832                    return Err(unavailable(&self.name, &why));
833                }
834                let proved = super::PeerIdentity::of(&conn);
835                if let Some(pinned) = self.identity.get().filter(|p| **p != proved) {
836                    conn.shutdown.notify_one();
837                    let why = format!("its identity changed: {pinned}, now {proved}; connect it again to trust the new one");
838                    tracing::error!(target: "plexus::child", child = %self.name, %pinned, %proved, "the restarted child proved another identity; not remounted");
839                    self.state.lock().unwrap().dead = Some(why.clone());
840                    return Err(unavailable(&self.name, &why));
841                }
842                tracing::info!(target: "plexus::child", child = %self.name, spawn_ms = t.spawn_ms, schema_ms = t.schema_ms, "child restarted");
843                self.state.lock().unwrap().conn = Some(Arc::clone(&conn));
844                Ok(conn)
845            }
846            Err(why) => {
847                let mut st = self.state.lock().unwrap();
848                st.down_since = Some(Instant::now());
849                st.why = why.clone();
850                Err(unavailable(&self.name, &why))
851            }
852        }
853    }
854
855    /// Why the child will never be mounted again, if it will not (a restart
856    /// published another schema).
857    pub(super) fn dead(&self) -> Option<String> {
858        self.state.lock().unwrap().dead.clone()
859    }
860
861    /// Why the child is down, when it is: the last connection's end, or the
862    /// last start that failed.
863    pub(super) fn why_down(&self) -> Option<String> {
864        let st = self.state.lock().unwrap();
865        if st.dead.is_some() {
866            return st.dead.clone();
867        }
868        match &st.conn {
869            Some(c) if c.alive() => None,
870            _ => Some(if st.why.is_empty() { "not connected".to_string() } else { st.why.clone() }),
871        }
872    }
873
874    /// Whether a live connection is up now.
875    pub(super) fn is_up(&self) -> bool {
876        let st = self.state.lock().unwrap();
877        st.dead.is_none() && st.conn.as_ref().is_some_and(|c| c.alive())
878    }
879
880    fn live(&self) -> Result<Option<Arc<Conn>>, PlexusStreamItem> {
881        let st = self.state.lock().unwrap();
882        if let Some(why) = &st.dead {
883            return Err(unavailable(&self.name, why));
884        }
885        Ok(st.conn.clone().filter(|c| c.alive()))
886    }
887}
888
889/// The reader's end: every open call told, the supervisor told.
890pub(super) fn gone(shared: &Weak<Shared>, conn: &Arc<Conn>, why: &str) {
891    conn.on_gone(why);
892    if let Some(s) = shared.upgrade() {
893        s.lost(conn, why);
894    }
895}
896
897/// One unary call: the first `data`'s content (the rest read to the end).
898async fn ask(conn: &Conn, method: &str, params: Value, timeout: Duration) -> Result<Value, String> {
899    let (_, mut rx) = conn.open(method, params, timeout).await.map_err(|e| match e {
900        PlexusStreamItem::Error { message, .. } => message,
901        other => format!("{other:?}"),
902    })?;
903    let deadline = tokio::time::Instant::now() + timeout;
904    let mut first = None;
905    loop {
906        match tokio::time::timeout_at(deadline, rx.recv()).await {
907            Ok(Some(PlexusStreamItem::Data { content, .. })) => {
908                if first.is_none() {
909                    first = Some(content.into_value());
910                }
911            }
912            Ok(Some(PlexusStreamItem::Error { message, .. })) => return Err(message),
913            Ok(Some(PlexusStreamItem::Done { .. })) | Ok(None) => break,
914            Ok(Some(_)) => {}
915            Err(_) => return Err(format!("no answer in {timeout:?}")),
916        }
917    }
918    first.ok_or_else(|| "it answered no data".to_string())
919}