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