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}
155
156/// One message, read in one pass: a notification's item stays raw until
157/// its call is known (then it is read once, as the item).
158#[derive(Deserialize)]
159struct Msg<'a> {
160    #[serde(default)]
161    id: Option<Value>,
162    #[serde(default, borrow)]
163    result: Option<&'a RawValue>,
164    #[serde(default)]
165    error: Option<Value>,
166    #[serde(default, borrow)]
167    method: Option<Cow<'a, str>>,
168    #[serde(default, borrow)]
169    params: Option<Notif<'a>>,
170}
171
172#[derive(Deserialize)]
173struct Notif<'a> {
174    #[serde(default)]
175    subscription: Option<Value>,
176    #[serde(default, borrow)]
177    result: Option<&'a RawValue>,
178}
179
180/// A message whose `params` are not an object (a request with positional
181/// params): read loosely, only to answer it.
182#[derive(Deserialize)]
183struct Loose<'a> {
184    #[serde(default)]
185    id: Option<Value>,
186    #[serde(default, borrow)]
187    method: Option<Cow<'a, str>>,
188}
189
190#[derive(Deserialize)]
191struct Kind<'a> {
192    #[serde(rename = "type", borrow)]
193    kind: Cow<'a, str>,
194}
195
196impl Conn {
197    pub(super) fn new(name: &str, pid: Option<u32>, out: mpsc::UnboundedSender<Vec<u8>>, buffer: usize, counters: Arc<Counters>) -> Arc<Self> {
198        Arc::new(Self {
199            name: name.to_string(),
200            pid,
201            ns: OnceLock::new(),
202            out,
203            routes: Mutex::new(Routes::default()),
204            next_id: AtomicU64::new(1),
205            alive: AtomicBool::new(true),
206            shutdown: Notify::new(),
207            buffer,
208            counters,
209            up: OnceLock::new(),
210            served: Arc::default(),
211        })
212    }
213
214    pub(super) fn alive(&self) -> bool {
215        self.alive.load(Ordering::Acquire)
216    }
217
218    pub(super) fn ns(&self) -> &str {
219        self.ns.get().map(String::as_str).unwrap_or(&self.name)
220    }
221
222    fn send(&self, frame: &Value) {
223        let _ = self.out.send(serde_json::to_vec(frame).unwrap_or_default());
224    }
225
226    /// Open a call: `method` with `params` (a `{ns}.call`'s params, or
227    /// `_info`'s null); the subscription id back within `timeout`, its items
228    /// already routed to the receiver.
229    pub(super) async fn open(&self, method: &str, params: Value, timeout: Duration) -> Result<(SubKey, mpsc::Receiver<PlexusStreamItem>), PlexusStreamItem> {
230        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
231        let (tx, rx) = mpsc::channel(self.buffer);
232        let (reply, answer) = oneshot::channel();
233        {
234            let mut r = self.routes.lock().unwrap();
235            if !self.alive() {
236                return Err(unavailable(&self.name, "the connection has closed"));
237            }
238            // a `{ns}.call`'s params name the method called (`echo.count`)
239            let called = params.get("method").and_then(Value::as_str).unwrap_or(method);
240            r.pending.insert(id, Opening { reply, items: Sub { tx, method: called.into() } });
241        }
242        self.send(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }));
243        match tokio::time::timeout(timeout, answer).await {
244            Ok(Ok(Ok(key))) => Ok((key, rx)),
245            Ok(Ok(Err(OpenFail::Gone(why)))) => Err(unavailable(&self.name, &why)),
246            Ok(Err(_)) => Err(unavailable(&self.name, "the connection closed before the call opened")),
247            Ok(Ok(Err(OpenFail::Refused(e)))) => Err(refused(&self.name, &e)),
248            Err(_) => {
249                let mut r = self.routes.lock().unwrap();
250                if r.pending.remove(&id).is_some() {
251                    r.abandoned.insert(id);
252                }
253                Err(timed_out(&self.name, timeout))
254            }
255        }
256    }
257
258    /// The caller let go of `key` before its end: forget it, and tell the
259    /// child (`{ns}.call_unsub [sid]`, spec/04).
260    pub(super) fn unsubscribe(&self, key: &str) {
261        let id = {
262            let mut r = self.routes.lock().unwrap();
263            if r.subs.remove(key).is_none() || !self.alive() {
264                return;
265            }
266            let id = self.next_id.fetch_add(1, Ordering::Relaxed);
267            r.closing.insert(id, key.to_string());
268            r.closing_subs.insert(key.to_string());
269            id
270        };
271        let method = serde_json::to_string(&format!("{}.call_unsub", self.ns())).unwrap_or_default();
272        let frame = format!(r#"{{"jsonrpc":"2.0","id":{id},"method":{method},"params":[{key}]}}"#);
273        let _ = self.out.send(frame.into_bytes());
274    }
275
276    /// How many subscriptions are routed now.
277    pub(super) fn routed(&self) -> usize {
278        self.routes.lock().unwrap().subs.len()
279    }
280
281    /// One message from the child.
282    pub(super) async fn on_message(&self, raw: &[u8]) {
283        let msg: Msg<'_> = match serde_json::from_slice(raw) {
284            Ok(m) => m,
285            Err(e) => match serde_json::from_slice::<Loose<'_>>(raw) {
286                Ok(Loose { id: Some(id), method: Some(method) }) => return self.request(id, &method, raw),
287                _ => {
288                    tracing::warn!(target: "plexus::child", child = %self.name, "an unreadable message from the child: {e}");
289                    return;
290                }
291            },
292        };
293        if let Some(method) = msg.method {
294            if let Some(id) = msg.id {
295                return self.request(id, &method, raw);
296            }
297            match msg.params {
298                Some(Notif { subscription: Some(sub), result: Some(item) }) => self.route(sub.to_string(), item).await,
299                _ => tracing::warn!(target: "plexus::child", child = %self.name, %method, "a notification without subscription and result"),
300            }
301            return;
302        }
303        let Some(id) = msg.id.as_ref().and_then(Value::as_u64) else { return };
304        let mut r = self.routes.lock().unwrap();
305        if let Some(open) = r.pending.remove(&id) {
306            match (msg.result, msg.error) {
307                (Some(sid), _) => {
308                    let key = match serde_json::from_str::<Value>(sid.get()) {
309                        Ok(v) => v.to_string(),
310                        Err(_) => sid.get().to_string(),
311                    };
312                    r.subs.insert(key.clone(), open.items);
313                    let _ = open.reply.send(Ok(key));
314                }
315                (None, e) => {
316                    let _ = open.reply.send(Err(OpenFail::Refused(e.unwrap_or_else(|| json!({ "message": "an answer with neither result nor error" })))));
317                }
318            }
319        } else if let Some(key) = r.closing.remove(&id) {
320            // Answered: an item still in flight is the tail for TAIL more.
321            let now = Instant::now();
322            r.expire_tails(now);
323            r.answered.push_back((now, key));
324        } else if r.abandoned.remove(&id) {
325            // A call opened after its caller was told `child_timeout`: stop it.
326            if let Some(sid) = msg.result.and_then(|s| serde_json::from_str::<Value>(s.get()).ok()) {
327                let key = sid.to_string();
328                let uid = self.next_id.fetch_add(1, Ordering::Relaxed);
329                r.closing.insert(uid, key.clone());
330                r.closing_subs.insert(key.clone());
331                drop(r);
332                let method = serde_json::to_string(&format!("{}.call_unsub", self.ns())).unwrap_or_default();
333                let _ = self.out.send(format!(r#"{{"jsonrpc":"2.0","id":{uid},"method":{method},"params":[{key}]}}"#).into_bytes());
334            }
335        }
336    }
337
338    /// A request from the child: a call back under a call it serves
339    /// (NEST-11, `_host.call`), when this mount takes them; anything else is
340    /// refused.
341    fn request(&self, id: Value, method: &str, raw: &[u8]) {
342        if let (Some(up), true) = (self.up.get(), method == upcall::HOST_CALL || method == upcall::HOST_CALL_UNSUB) {
343            let params = serde_json::from_slice::<Value>(raw).ok().and_then(|mut v| v.get_mut("params").map(Value::take)).unwrap_or(Value::Null);
344            return upcall::on_request(up, &self.served, &self.out, &self.name, id, method, params);
345        }
346        self.refuse_request(id, method)
347    }
348
349    /// A child asks its service nothing else (spec/12): answered, not served.
350    fn refuse_request(&self, id: Value, method: &str) {
351        tracing::warn!(target: "plexus::child", child = %self.name, %method, "a request from the child refused");
352        self.send(&json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": "a service answers no requests from its child" } }));
353    }
354
355    async fn route(&self, key: SubKey, raw: &RawValue) {
356        let (tx, method) = {
357            let mut r = self.routes.lock().unwrap();
358            match r.subs.get(&key) {
359                Some(sub) => (sub.tx.clone(), Arc::clone(&sub.method)),
360                None => {
361                    r.expire_tails(Instant::now());
362                    if !r.closing_subs.contains(&key) {
363                        drop(r);
364                        self.counters.unasked.fetch_add(1, Ordering::Relaxed);
365                        tracing::warn!(target: "plexus::child", child = %self.name, subscription = %key, "unasked item dropped");
366                    }
367                    return;
368                }
369            }
370        };
371        // RETURNS-36: a peer on plexus-wire's spec as main wrote it is read
372        // into 0.8's shape (`peer::item`) when — only when — it does not
373        // read as 0.8.
374        let parsed = serde_json::from_str::<PlexusStreamItem>(raw.get()).or_else(|e| {
375            super::peer::item(raw.get(), &method)
376                .and_then(|v| serde_json::from_value::<PlexusStreamItem>(v).ok())
377                .ok_or(e)
378        });
379        let item = match parsed {
380            Ok(item) => item,
381            Err(e) => {
382                let kind = serde_json::from_str::<Kind<'_>>(raw.get()).map(|k| k.kind.into_owned()).unwrap_or_default();
383                if kind != "error" {
384                    // An item kind this service does not know (spec/03: a
385                    // reader skips it) — or one that does not read at all.
386                    tracing::debug!(target: "plexus::child", child = %self.name, subscription = %key, %kind, "an item kind not relayed: {e}");
387                    return;
388                }
389                // RETURNS-36 (review #4): an error item is the call's end
390                // (spec/03); skipped, the call would wait for an end that
391                // never comes. It ends here, naming what could not be read,
392                // and the child is told to stop.
393                tracing::warn!(target: "plexus::child", child = %self.name, subscription = %key, "an error item not read: {e}");
394                self.unsubscribe(&key);
395                let error = plexus_client::RemoteError::Execution {
396                    message: format!("child {} sent an error item this service could not read: {e}", self.name),
397                };
398                PlexusStreamItem::error(meta(&self.name), error, false)
399            }
400        };
401        if matches!(item, PlexusStreamItem::Done { .. } | PlexusStreamItem::Error { .. }) {
402            self.routes.lock().unwrap().subs.remove(&key);
403        }
404        match tx.try_send(item) {
405            Ok(()) => {}
406            // The caller has not read the call's buffer: wait for it
407            // (lossless; the child's other calls wait behind it).
408            Err(mpsc::error::TrySendError::Full(item)) => {
409                let _ = tx.send(item).await;
410            }
411            Err(mpsc::error::TrySendError::Closed(_)) => {}
412        }
413    }
414
415    /// The far side is gone: every open call gets one `child_unavailable`.
416    pub(super) fn on_gone(&self, why: &str) {
417        let (subs, pending) = {
418            let mut r = self.routes.lock().unwrap();
419            self.alive.store(false, Ordering::Release);
420            self.served.abort_all();
421            r.closing.clear();
422            r.closing_subs.clear();
423            r.answered.clear();
424            r.abandoned.clear();
425            (std::mem::take(&mut r.subs), std::mem::take(&mut r.pending))
426        };
427        for (_, Sub { tx, .. }) in subs {
428            match tx.try_send(unavailable(&self.name, why)) {
429                Err(mpsc::error::TrySendError::Full(item)) => {
430                    tokio::spawn(async move {
431                        let _ = tx.send(item).await;
432                    });
433                }
434                _ => {}
435            }
436        }
437        for (_, open) in pending {
438            let _ = open.reply.send(Err(OpenFail::Gone(why.to_string())));
439        }
440    }
441}
442
443/// Read newline-delimited messages from `r`, one wakeup per read: every
444/// whole line in the buffer is routed before the next read.
445pub(super) async fn read_lines<R: AsyncRead + Unpin>(conn: &Conn, r: R) {
446    let mut r = BufReader::with_capacity(1 << 17, r);
447    let mut carry: Vec<u8> = Vec::new();
448    loop {
449        let buf = match r.fill_buf().await {
450            Ok(b) if !b.is_empty() => b,
451            _ => break,
452        };
453        let n = buf.len();
454        let mut start = 0;
455        while let Some(i) = buf[start..].iter().position(|b| *b == b'\n') {
456            let end = start + i;
457            if carry.is_empty() {
458                let line = &buf[start..end];
459                if line.iter().any(|b| !b.is_ascii_whitespace()) {
460                    conn.on_message(line).await;
461                }
462            } else {
463                carry.extend_from_slice(&buf[start..end]);
464                let line = std::mem::take(&mut carry);
465                if line.iter().any(|b| !b.is_ascii_whitespace()) {
466                    conn.on_message(&line).await;
467                }
468            }
469            start = end + 1;
470        }
471        carry.extend_from_slice(&buf[start..]);
472        r.consume(n);
473    }
474}
475
476/// The writer: everything queued, one write per wakeup, each line whole.
477pub(super) async fn write_lines<W: tokio::io::AsyncWrite + Unpin>(mut w: W, mut rx: mpsc::UnboundedReceiver<Vec<u8>>) {
478    while let Some(first) = rx.recv().await {
479        let mut buf = first;
480        buf.push(b'\n');
481        while let Ok(more) = rx.try_recv() {
482            buf.extend_from_slice(&more);
483            buf.push(b'\n');
484        }
485        if w.write_all(&buf).await.is_err() || w.flush().await.is_err() {
486            break;
487        }
488    }
489}
490
491/// When the child was mounted, how long each step took.
492#[derive(Debug, Clone, Copy, Default, PartialEq)]
493pub struct MountTimings {
494    /// Spawn (or dial) → its `_info` answered.
495    pub spawn_ms: f64,
496    /// `_info` → its schema answered.
497    pub schema_ms: f64,
498    /// The schema requalified under the mount name and kept.
499    pub merge_ms: f64,
500}
501
502struct LinkState {
503    conn: Option<Arc<Conn>>,
504    down_since: Option<Instant>,
505    why: String,
506    window: VecDeque<Instant>,
507    /// Never again (a restart published another schema): the reason.
508    dead: Option<String>,
509}
510
511/// The child across its connections.
512pub(super) struct Shared {
513    pub spec: ChildSpec,
514    pub opts: ChildOptions,
515    pub name: String,
516    /// The hop's `principal`.
517    pub principal: String,
518    pub counters: Arc<Counters>,
519    state: Mutex<LinkState>,
520    dial: tokio::sync::Mutex<()>,
521    /// The mounted schema's hash, as the child published it.
522    pub mounted_hash: OnceLock<String>,
523    /// NEST-11: the child's calls back into the service.
524    pub upcalls: Arc<Upcalls>,
525}
526
527impl Drop for Shared {
528    fn drop(&mut self) {
529        if let Ok(st) = self.state.lock() {
530            if let Some(c) = &st.conn {
531                c.shutdown.notify_one();
532            }
533        }
534    }
535}
536
537/// The hash a child's schema is compared by across restarts.
538pub(super) fn schema_hash(raw: &Value) -> String {
539    match raw.get("hash").and_then(Value::as_str) {
540        Some(h) => h.to_string(),
541        None => raw.get("methods").map(Value::to_string).unwrap_or_default(),
542    }
543}
544
545/// NEST-4 · what a mount keeps of a child: its own schema and, walked at
546/// mount, every static child below it by dotted path (`a`, `a.b`), each as
547/// the child published it.
548#[derive(Debug, Clone)]
549pub(super) struct Kept {
550    pub top: Value,
551    pub nodes: Vec<(String, Value)>,
552}
553
554impl Kept {
555    /// The whole tree's hash, compared across restarts: a flat child's is its
556    /// schema's, as before; a child with children adds each one's, by path,
557    /// so a changed grandchild changes it whatever the child's own hash
558    /// covers.
559    pub fn hash(&self) -> String {
560        let mut h = schema_hash(&self.top);
561        for (path, raw) in &self.nodes {
562            h.push_str(&format!(" {path}={}", schema_hash(raw)));
563        }
564        h
565    }
566}
567
568/// The static children a schema names, by the name each is reached through:
569/// its methods whose role is `static_child` when any method states a child
570/// role; else its `children` side-table (IR-4) — a service's root, whose
571/// registered activations are listed there and nowhere else.
572pub(super) fn static_children(raw: &Value) -> Vec<String> {
573    let methods = raw.get("methods").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
574    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);
575    // A macro-built activation says its children by role (a static child's
576    // name is its method's, which may differ from the child's namespace);
577    // a service's root (a DynamicHub) lists its activations in `children`.
578    if methods.iter().any(|m| kind(m).is_some_and(|k| k.ends_with("_child"))) {
579        // NEST-6: a peer slot is a `static_child` marked `peer` on the
580        // wire (NEST-7) — a slot, reached by name, not a level to walk.
581        let peer = |m: &Value| m.get("role").and_then(|r| r.get("peer")).and_then(Value::as_bool).unwrap_or(false);
582        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();
583    }
584    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()
585}
586
587impl Shared {
588    pub(super) fn new(spec: ChildSpec, opts: ChildOptions, principal: String) -> Arc<Self> {
589        let upcalls = Upcalls::new(opts.host.clone().or_else(crate::plexus::service_scope::current));
590        Arc::new(Self {
591            upcalls,
592            name: spec.name().to_string(),
593            spec,
594            opts,
595            principal,
596            counters: Arc::new(Counters::default()),
597            state: Mutex::new(LinkState { conn: None, down_since: None, why: String::new(), window: VecDeque::new(), dead: None }),
598            dial: tokio::sync::Mutex::new(()),
599            mounted_hash: OnceLock::new(),
600        })
601    }
602
603    pub(super) fn current(&self) -> Option<Arc<Conn>> {
604        self.state.lock().unwrap().conn.clone()
605    }
606
607    pub(super) fn install(&self, conn: Arc<Conn>) {
608        self.state.lock().unwrap().conn = Some(conn);
609    }
610
611    /// The service asks for itself (the mount): no caller, no verdict.
612    fn own_hop(&self) -> Value {
613        json!({ "principal": self.principal, "for": [], "limit": null, "call": uuid::Uuid::new_v4().to_string() })
614    }
615
616    /// Start (or dial) the child and ask its `_info` and its schema, then
617    /// walk its static children (NEST-4), all within one `timeout`.
618    pub(super) async fn connect_once(self: &Arc<Self>) -> Result<(Arc<Conn>, Kept, MountTimings), String> {
619        let t0 = Instant::now();
620        let conn = match &self.spec {
621            ChildSpec::Stdio { argv, .. } => self.spawn_stdio(argv)?,
622            ChildSpec::Ws { url, .. } => self.dial_ws(url).await?,
623        };
624        let asked = async {
625            let info = ask(&conn, "_info", Value::Null, self.opts.timeout).await.map_err(|e| format!("`_info`: {e}"))?;
626            let ns = info.get("backend").and_then(Value::as_str).ok_or("its `_info` names no backend")?.to_string();
627            let _ = conn.ns.set(ns.clone());
628            let t1 = Instant::now();
629            let deadline = t1 + self.opts.timeout;
630            let params = json!({ "method": format!("{ns}.schema"), "params": {}, "hop": self.own_hop() });
631            let schema = ask(&conn, &format!("{ns}.call"), params, self.opts.timeout).await.map_err(|e| format!("its schema: {e}"))?;
632            let nodes = self.walk(&conn, &ns, &schema, deadline).await?;
633            Ok::<_, String>((Kept { top: schema, nodes }, t1))
634        };
635        match asked.await {
636            Ok((schema, t1)) => {
637                let t = MountTimings { spawn_ms: (t1 - t0).as_secs_f64() * 1e3, schema_ms: t1.elapsed().as_secs_f64() * 1e3, merge_ms: 0.0 };
638                Ok((conn, schema, t))
639            }
640            Err(why) => {
641                conn.shutdown.notify_one();
642                Err(why)
643            }
644        }
645    }
646
647    /// NEST-4 · the static tree below `top`, depth-first: `{ns}.<path>.schema`
648    /// for each static child, at most `max_depth` levels down and before
649    /// `deadline` (the mount's one timeout), each asked as the mount asks the
650    /// child's own (no caller, no verdict). A dynamic child is not walked:
651    /// its role, on its parent's schema, is the slot. Past the depth, or the
652    /// time, the mount fails naming the path.
653    pub(super) async fn walk(&self, conn: &Conn, ns: &str, top: &Value, deadline: Instant) -> Result<Vec<(String, Value)>, String> {
654        let mut out = Vec::new();
655        let mut stack: Vec<String> = static_children(top).into_iter().rev().collect();
656        while let Some(path) = stack.pop() {
657            let depth = path.split('.').count();
658            if depth > self.opts.max_depth {
659                return Err(format!("its child `{path}` is {depth} levels down, past --child-max-depth ({})", self.opts.max_depth));
660            }
661            let left = deadline.saturating_duration_since(Instant::now());
662            if left.is_zero() {
663                return Err(format!("its tree was not walked within {:?}: stopped at `{path}`", self.opts.timeout));
664            }
665            let params = json!({ "method": format!("{ns}.{path}.schema"), "params": {}, "hop": self.own_hop() });
666            let raw = ask(conn, &format!("{ns}.call"), params, left).await.map_err(|e| format!("the schema of its child `{path}`: {e}"))?;
667            for child in static_children(&raw).into_iter().rev() {
668                stack.push(format!("{path}.{child}"));
669            }
670            out.push((path, raw));
671        }
672        Ok(out)
673    }
674
675    fn spawn_stdio(self: &Arc<Self>, argv: &[String]) -> Result<Arc<Conn>, String> {
676        let mut cmd = tokio::process::Command::new(&argv[0]);
677        cmd.args(&argv[1..])
678            .env_clear()
679            .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))))
680            .env("PLEXUS_CHILD_NAME", &self.name)
681            .stdin(std::process::Stdio::piped())
682            .stdout(std::process::Stdio::piped())
683            .stderr(std::process::Stdio::piped())
684            .kill_on_drop(true);
685        let mut child = cmd.spawn().map_err(|e| format!("spawning `{}`: {e}", argv[0]))?;
686        let (stdin, stdout, stderr) = (child.stdin.take(), child.stdout.take(), child.stderr.take());
687        let (Some(stdin), Some(stdout), Some(stderr)) = (stdin, stdout, stderr) else {
688            return Err("its pipes were not opened".into());
689        };
690        let (out, out_rx) = mpsc::unbounded_channel();
691        let conn = Conn::new(&self.name, child.id(), out, self.opts.buffer, Arc::clone(&self.counters));
692        let _ = conn.up.set(Arc::clone(&self.upcalls));
693        tokio::spawn(write_lines(stdin, out_rx));
694        let reader = Arc::clone(&conn);
695        let shared = Arc::downgrade(self);
696        tokio::spawn(async move {
697            tokio::select! {
698                _ = read_lines(&reader, stdout) => {}
699                _ = reader.shutdown.notified() => {
700                    let _ = child.start_kill();
701                }
702            }
703            let status = child.wait().await.map(|s| s.to_string()).unwrap_or_else(|e| e.to_string());
704            gone(&shared, &reader, &format!("the process exited ({status})"));
705        });
706        let name = self.name.clone();
707        tokio::spawn(async move {
708            let span = tracing::info_span!(target: "plexus::child", "plexus::child", name = %name);
709            let mut lines = BufReader::new(stderr).lines();
710            while let Ok(Some(l)) = lines.next_line().await {
711                let _e = span.enter();
712                tracing::info!(target: "plexus::child", child = %name, "{l}");
713            }
714        });
715        Ok(conn)
716    }
717
718    #[cfg(feature = "child-ws")]
719    async fn dial_ws(self: &Arc<Self>, url: &str) -> Result<Arc<Conn>, String> {
720        super::ws::dial(self, url).await
721    }
722
723    #[cfg(not(feature = "child-ws"))]
724    async fn dial_ws(self: &Arc<Self>, _url: &str) -> Result<Arc<Conn>, String> {
725        Err("a WebSocket child needs plexus-core's `child-ws` feature".into())
726    }
727
728    /// The connection `conn` is gone; the next call starts another.
729    pub(super) fn lost(&self, conn: &Arc<Conn>, why: &str) {
730        let mut st = self.state.lock().unwrap();
731        if st.conn.as_ref().is_some_and(|c| Arc::ptr_eq(c, conn)) {
732            st.conn = None;
733            st.down_since = Some(Instant::now());
734            st.why = why.to_string();
735            drop(st);
736            tracing::warn!(target: "plexus::child", child = %self.name, "child gone: {why}");
737        }
738    }
739
740    /// A live connection, starting the child again if it died — within the
741    /// backoff, and never past `per_minute` restarts a minute.
742    pub(super) async fn ensure(self: &Arc<Self>) -> Result<Arc<Conn>, PlexusStreamItem> {
743        if let Some(c) = self.live()? {
744            return Ok(c);
745        }
746        let _g = self.dial.lock().await;
747        if let Some(c) = self.live()? {
748            return Ok(c);
749        }
750        let b = self.opts.backoff;
751        let wait = {
752            let mut st = self.state.lock().unwrap();
753            let now = Instant::now();
754            while st.window.front().is_some_and(|t| now.duration_since(*t) >= Duration::from_secs(60)) {
755                st.window.pop_front();
756            }
757            if st.window.len() >= b.per_minute {
758                let next = st.window.front().map(|t| Duration::from_secs(60).saturating_sub(now.duration_since(*t))).unwrap_or_default();
759                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())));
760            }
761            let due = st.down_since.unwrap_or(now) + b.delay(st.window.len());
762            due.saturating_duration_since(now)
763        };
764        if wait > self.opts.timeout {
765            let why = self.state.lock().unwrap().why.clone();
766            return Err(unavailable(&self.name, &format!("{why} (restarting in {:.1} s)", wait.as_secs_f64())));
767        }
768        tokio::time::sleep(wait).await;
769        self.state.lock().unwrap().window.push_back(Instant::now());
770        self.counters.restarts.fetch_add(1, Ordering::Relaxed);
771        match self.connect_once().await {
772            Ok((conn, kept, t)) => {
773                let hash = kept.hash();
774                if self.mounted_hash.get().is_some_and(|h| *h != hash) {
775                    conn.shutdown.notify_one();
776                    let why = "schema changed; restart the service".to_string();
777                    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");
778                    self.state.lock().unwrap().dead = Some(why.clone());
779                    return Err(unavailable(&self.name, &why));
780                }
781                tracing::info!(target: "plexus::child", child = %self.name, spawn_ms = t.spawn_ms, schema_ms = t.schema_ms, "child restarted");
782                self.state.lock().unwrap().conn = Some(Arc::clone(&conn));
783                Ok(conn)
784            }
785            Err(why) => {
786                let mut st = self.state.lock().unwrap();
787                st.down_since = Some(Instant::now());
788                st.why = why.clone();
789                Err(unavailable(&self.name, &why))
790            }
791        }
792    }
793
794    /// Why the child will never be mounted again, if it will not (a restart
795    /// published another schema).
796    pub(super) fn dead(&self) -> Option<String> {
797        self.state.lock().unwrap().dead.clone()
798    }
799
800    /// Why the child is down, when it is: the last connection's end, or the
801    /// last start that failed.
802    pub(super) fn why_down(&self) -> Option<String> {
803        let st = self.state.lock().unwrap();
804        if st.dead.is_some() {
805            return st.dead.clone();
806        }
807        match &st.conn {
808            Some(c) if c.alive() => None,
809            _ => Some(if st.why.is_empty() { "not connected".to_string() } else { st.why.clone() }),
810        }
811    }
812
813    /// Whether a live connection is up now.
814    pub(super) fn is_up(&self) -> bool {
815        let st = self.state.lock().unwrap();
816        st.dead.is_none() && st.conn.as_ref().is_some_and(|c| c.alive())
817    }
818
819    fn live(&self) -> Result<Option<Arc<Conn>>, PlexusStreamItem> {
820        let st = self.state.lock().unwrap();
821        if let Some(why) = &st.dead {
822            return Err(unavailable(&self.name, why));
823        }
824        Ok(st.conn.clone().filter(|c| c.alive()))
825    }
826}
827
828/// The reader's end: every open call told, the supervisor told.
829pub(super) fn gone(shared: &Weak<Shared>, conn: &Arc<Conn>, why: &str) {
830    conn.on_gone(why);
831    if let Some(s) = shared.upgrade() {
832        s.lost(conn, why);
833    }
834}
835
836/// One unary call: the first `data`'s content (the rest read to the end).
837async fn ask(conn: &Conn, method: &str, params: Value, timeout: Duration) -> Result<Value, String> {
838    let (_, mut rx) = conn.open(method, params, timeout).await.map_err(|e| match e {
839        PlexusStreamItem::Error { message, .. } => message,
840        other => format!("{other:?}"),
841    })?;
842    let deadline = tokio::time::Instant::now() + timeout;
843    let mut first = None;
844    loop {
845        match tokio::time::timeout_at(deadline, rx.recv()).await {
846            Ok(Some(PlexusStreamItem::Data { content, .. })) => {
847                if first.is_none() {
848                    first = Some(content.into_value());
849                }
850            }
851            Ok(Some(PlexusStreamItem::Error { message, .. })) => return Err(message),
852            Ok(Some(PlexusStreamItem::Done { .. })) | Ok(None) => break,
853            Ok(Some(_)) => {}
854            Err(_) => return Err(format!("no answer in {timeout:?}")),
855        }
856    }
857    first.ok_or_else(|| "it answered no data".to_string())
858}