1use 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
30pub(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
37pub(super) fn unavailable(name: &str, why: &str) -> PlexusStreamItem {
39 PlexusStreamItem::error(meta(name), RemoteError::ChildUnavailable { child: name.into(), reason: why.into() }, true)
40}
41
42pub(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
52pub(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
57fn 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#[derive(Default)]
76pub(super) struct Counters {
77 pub unasked: AtomicU64,
78 pub calls: AtomicU64,
79 pub restarts: AtomicU64,
80 pub open: AtomicUsize,
81}
82
83pub(super) enum OpenFail {
85 Gone(String),
87 Refused(Value),
89}
90
91struct Opening {
92 reply: oneshot::Sender<Result<SubKey, OpenFail>>,
93 items: Sub,
94}
95
96struct Sub {
100 tx: mpsc::Sender<PlexusStreamItem>,
101 method: Arc<str>,
102}
103
104const TAIL: Duration = Duration::from_millis(250);
108
109#[derive(Default)]
110struct Routes {
111 pending: HashMap<u64, Opening>,
112 subs: HashMap<SubKey, Sub>,
113 closing: HashMap<u64, SubKey>,
117 closing_subs: HashSet<SubKey>,
118 answered: VecDeque<(Instant, SubKey)>,
119 abandoned: HashSet<u64>,
121}
122
123impl Routes {
124 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
134pub(super) struct Conn {
136 pub name: String,
137 pub pid: Option<u32>,
138 pub ns: OnceLock<String>,
140 out: mpsc::UnboundedSender<Vec<u8>>,
141 routes: Mutex<Routes>,
142 next_id: AtomicU64,
143 alive: AtomicBool,
144 pub shutdown: Notify,
146 buffer: usize,
147 counters: Arc<Counters>,
148 pub up: OnceLock<Arc<Upcalls>>,
152 served: Arc<Served>,
154 pub tls_key: OnceLock<String>,
157 pub peer_key: OnceLock<String>,
160}
161
162#[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#[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 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 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 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 pub(super) fn routed(&self) -> usize {
286 self.routes.lock().unwrap().subs.len()
287 }
288
289 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 let now = Instant::now();
330 r.expire_tails(now);
331 r.answered.push_back((now, key));
332 } else if r.abandoned.remove(&id) {
333 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 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 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 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 tracing::debug!(target: "plexus::child", child = %self.name, subscription = %key, %kind, "an item kind not relayed: {e}");
395 return;
396 }
397 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 Err(mpsc::error::TrySendError::Full(item)) => {
417 let _ = tx.send(item).await;
418 }
419 Err(mpsc::error::TrySendError::Closed(_)) => {}
420 }
421 }
422
423 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
451pub(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
484pub(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#[derive(Debug, Clone, Copy, Default, PartialEq)]
501pub struct MountTimings {
502 pub spawn_ms: f64,
504 pub schema_ms: f64,
506 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 dead: Option<String>,
517}
518
519pub(super) struct Shared {
521 pub spec: ChildSpec,
522 pub opts: ChildOptions,
523 pub name: String,
524 pub principal: String,
526 pub counters: Arc<Counters>,
527 state: Mutex<LinkState>,
528 dial: tokio::sync::Mutex<()>,
529 pub mounted_hash: OnceLock<String>,
531 pub upcalls: Arc<Upcalls>,
533 pub identity: OnceLock<super::PeerIdentity>,
537 pub revoked: Mutex<Option<String>>,
539}
540
541impl Drop for Shared {
542 fn drop(&mut self) {
543 if let Ok(st) = self.state.lock() {
544 if let Some(c) = &st.conn {
545 c.shutdown.notify_one();
546 }
547 }
548 }
549}
550
551pub(super) fn schema_hash(raw: &Value) -> String {
553 match raw.get("hash").and_then(Value::as_str) {
554 Some(h) => h.to_string(),
555 None => raw.get("methods").map(Value::to_string).unwrap_or_default(),
556 }
557}
558
559#[derive(Debug, Clone)]
563pub(super) struct Kept {
564 pub top: Value,
565 pub nodes: Vec<(String, Value)>,
566}
567
568impl Kept {
569 pub fn hash(&self) -> String {
574 let mut h = schema_hash(&self.top);
575 for (path, raw) in &self.nodes {
576 h.push_str(&format!(" {path}={}", schema_hash(raw)));
577 }
578 h
579 }
580}
581
582pub(super) fn static_children(raw: &Value) -> Vec<String> {
587 let methods = raw.get("methods").and_then(Value::as_array).map(Vec::as_slice).unwrap_or_default();
588 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);
589 if methods.iter().any(|m| kind(m).is_some_and(|k| k.ends_with("_child"))) {
593 let peer = |m: &Value| m.get("role").and_then(|r| r.get("peer")).and_then(Value::as_bool).unwrap_or(false);
596 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();
597 }
598 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()
599}
600
601impl Shared {
602 pub(super) fn new(spec: ChildSpec, opts: ChildOptions, principal: String) -> Arc<Self> {
603 let upcalls = Upcalls::new(opts.host.clone().or_else(crate::plexus::service_scope::current), opts.legacy_upcalls);
604 Arc::new(Self {
605 upcalls,
606 name: spec.name().to_string(),
607 spec,
608 opts,
609 principal,
610 counters: Arc::new(Counters::default()),
611 state: Mutex::new(LinkState { conn: None, down_since: None, why: String::new(), window: VecDeque::new(), dead: None }),
612 dial: tokio::sync::Mutex::new(()),
613 mounted_hash: OnceLock::new(),
614 identity: OnceLock::new(),
615 revoked: Mutex::new(None),
616 })
617 }
618
619 pub(super) fn current(&self) -> Option<Arc<Conn>> {
620 self.state.lock().unwrap().conn.clone()
621 }
622
623 pub(super) fn install(&self, conn: Arc<Conn>) {
624 self.state.lock().unwrap().conn = Some(conn);
625 }
626
627 fn own_hop(&self) -> Value {
629 json!({ "principal": self.principal, "for": [], "limit": null, "call": uuid::Uuid::new_v4().to_string() })
630 }
631
632 pub(super) async fn connect_once(self: &Arc<Self>) -> Result<(Arc<Conn>, Kept, MountTimings), String> {
635 let t0 = Instant::now();
636 let conn = match &self.spec {
637 ChildSpec::Stdio { argv, .. } => self.spawn_stdio(argv)?,
638 ChildSpec::Ws { url, .. } => self.dial_ws(url).await?,
639 };
640 let asked = async {
641 let nonce = crate::plexus::peer_token::random_nonce();
646 let info = ask(&conn, "_info", json!({ "nonce": nonce }), self.opts.timeout).await.map_err(|e| format!("`_info`: {e}"))?;
647 let ns = info.get("backend").and_then(Value::as_str).ok_or("its `_info` names no backend")?.to_string();
648 if let Some(key) = info.get("key").and_then(Value::as_str) {
649 let proof = info.get("proof").and_then(Value::as_str).unwrap_or_default();
650 crate::plexus::peer_token::check_key_proof(key, proof, &nonce, &ns).map_err(|e| format!("its `_info` names the key {key} without proving it: {e}"))?;
651 let _ = conn.peer_key.set(key.to_string());
652 }
653 let _ = conn.ns.set(ns.clone());
654 let t1 = Instant::now();
655 let deadline = t1 + self.opts.timeout;
656 let params = json!({ "method": format!("{ns}.schema"), "params": {}, "hop": self.own_hop() });
657 let schema = ask(&conn, &format!("{ns}.call"), params, self.opts.timeout).await.map_err(|e| format!("its schema: {e}"))?;
658 let nodes = self.walk(&conn, &ns, &schema, deadline).await?;
659 Ok::<_, String>((Kept { top: schema, nodes }, t1))
660 };
661 match asked.await {
662 Ok((schema, t1)) => {
663 let t = MountTimings { spawn_ms: (t1 - t0).as_secs_f64() * 1e3, schema_ms: t1.elapsed().as_secs_f64() * 1e3, merge_ms: 0.0 };
664 Ok((conn, schema, t))
665 }
666 Err(why) => {
667 conn.shutdown.notify_one();
668 Err(why)
669 }
670 }
671 }
672
673 pub(super) async fn walk(&self, conn: &Conn, ns: &str, top: &Value, deadline: Instant) -> Result<Vec<(String, Value)>, String> {
680 let mut out = Vec::new();
681 let mut stack: Vec<String> = static_children(top).into_iter().rev().collect();
682 while let Some(path) = stack.pop() {
683 let depth = path.split('.').count();
684 if depth > self.opts.max_depth {
685 return Err(format!("its child `{path}` is {depth} levels down, past --child-max-depth ({})", self.opts.max_depth));
686 }
687 let left = deadline.saturating_duration_since(Instant::now());
688 if left.is_zero() {
689 return Err(format!("its tree was not walked within {:?}: stopped at `{path}`", self.opts.timeout));
690 }
691 let params = json!({ "method": format!("{ns}.{path}.schema"), "params": {}, "hop": self.own_hop() });
692 let raw = ask(conn, &format!("{ns}.call"), params, left).await.map_err(|e| format!("the schema of its child `{path}`: {e}"))?;
693 for child in static_children(&raw).into_iter().rev() {
694 stack.push(format!("{path}.{child}"));
695 }
696 out.push((path, raw));
697 }
698 Ok(out)
699 }
700
701 fn spawn_stdio(self: &Arc<Self>, argv: &[String]) -> Result<Arc<Conn>, String> {
702 let mut cmd = tokio::process::Command::new(&argv[0]);
703 cmd.args(&argv[1..])
704 .env_clear()
705 .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))))
706 .env("PLEXUS_CHILD_NAME", &self.name)
707 .stdin(std::process::Stdio::piped())
708 .stdout(std::process::Stdio::piped())
709 .stderr(std::process::Stdio::piped())
710 .kill_on_drop(true);
711 let mut child = cmd.spawn().map_err(|e| format!("spawning `{}`: {e}", argv[0]))?;
712 let (stdin, stdout, stderr) = (child.stdin.take(), child.stdout.take(), child.stderr.take());
713 let (Some(stdin), Some(stdout), Some(stderr)) = (stdin, stdout, stderr) else {
714 return Err("its pipes were not opened".into());
715 };
716 let (out, out_rx) = mpsc::unbounded_channel();
717 let conn = Conn::new(&self.name, child.id(), out, self.opts.buffer, Arc::clone(&self.counters));
718 let _ = conn.up.set(Arc::clone(&self.upcalls));
719 tokio::spawn(write_lines(stdin, out_rx));
720 let reader = Arc::clone(&conn);
721 let shared = Arc::downgrade(self);
722 tokio::spawn(async move {
723 tokio::select! {
724 _ = read_lines(&reader, stdout) => {}
725 _ = reader.shutdown.notified() => {
726 let _ = child.start_kill();
727 }
728 }
729 let status = child.wait().await.map(|s| s.to_string()).unwrap_or_else(|e| e.to_string());
730 gone(&shared, &reader, &format!("the process exited ({status})"));
731 });
732 let name = self.name.clone();
733 tokio::spawn(async move {
734 let span = tracing::info_span!(target: "plexus::child", "plexus::child", name = %name);
735 let mut lines = BufReader::new(stderr).lines();
736 while let Ok(Some(l)) = lines.next_line().await {
737 let _e = span.enter();
738 tracing::info!(target: "plexus::child", child = %name, "{}", crate::plexus::redact::redact_str(&l));
741 }
742 });
743 Ok(conn)
744 }
745
746 #[cfg(feature = "child-ws")]
747 async fn dial_ws(self: &Arc<Self>, url: &str) -> Result<Arc<Conn>, String> {
748 super::ws::dial(self, url).await
749 }
750
751 #[cfg(not(feature = "child-ws"))]
752 async fn dial_ws(self: &Arc<Self>, _url: &str) -> Result<Arc<Conn>, String> {
753 Err("a WebSocket child needs plexus-core's `child-ws` feature".into())
754 }
755
756 pub(super) fn lost(&self, conn: &Arc<Conn>, why: &str) {
758 let mut st = self.state.lock().unwrap();
759 if st.conn.as_ref().is_some_and(|c| Arc::ptr_eq(c, conn)) {
760 st.conn = None;
761 st.down_since = Some(Instant::now());
762 st.why = why.to_string();
763 drop(st);
764 tracing::warn!(target: "plexus::child", child = %self.name, "child gone: {why}");
765 }
766 }
767
768 pub(super) async fn ensure(self: &Arc<Self>) -> Result<Arc<Conn>, PlexusStreamItem> {
771 if let Some(c) = self.live()? {
772 return Ok(c);
773 }
774 let _g = self.dial.lock().await;
775 if let Some(c) = self.live()? {
776 return Ok(c);
777 }
778 let b = self.opts.backoff;
779 let wait = {
780 let mut st = self.state.lock().unwrap();
781 let now = Instant::now();
782 while st.window.front().is_some_and(|t| now.duration_since(*t) >= Duration::from_secs(60)) {
783 st.window.pop_front();
784 }
785 if st.window.len() >= b.per_minute {
786 let next = st.window.front().map(|t| Duration::from_secs(60).saturating_sub(now.duration_since(*t))).unwrap_or_default();
787 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())));
788 }
789 let due = st.down_since.unwrap_or(now) + b.delay(st.window.len());
790 due.saturating_duration_since(now)
791 };
792 if wait > self.opts.timeout {
793 let why = self.state.lock().unwrap().why.clone();
794 return Err(unavailable(&self.name, &format!("{why} (restarting in {:.1} s)", wait.as_secs_f64())));
795 }
796 tokio::time::sleep(wait).await;
797 self.state.lock().unwrap().window.push_back(Instant::now());
798 self.counters.restarts.fetch_add(1, Ordering::Relaxed);
799 match self.connect_once().await {
800 Ok((conn, kept, t)) => {
801 let hash = kept.hash();
802 if self.mounted_hash.get().is_some_and(|h| *h != hash) {
803 conn.shutdown.notify_one();
804 let why = "schema changed; restart the service".to_string();
805 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");
806 self.state.lock().unwrap().dead = Some(why.clone());
807 return Err(unavailable(&self.name, &why));
808 }
809 let proved = super::PeerIdentity::of(&conn);
810 if let Some(pinned) = self.identity.get().filter(|p| **p != proved) {
811 conn.shutdown.notify_one();
812 let why = format!("its identity changed: {pinned}, now {proved}; connect it again to trust the new one");
813 tracing::error!(target: "plexus::child", child = %self.name, %pinned, %proved, "the restarted child proved another identity; not remounted");
814 self.state.lock().unwrap().dead = Some(why.clone());
815 return Err(unavailable(&self.name, &why));
816 }
817 tracing::info!(target: "plexus::child", child = %self.name, spawn_ms = t.spawn_ms, schema_ms = t.schema_ms, "child restarted");
818 self.state.lock().unwrap().conn = Some(Arc::clone(&conn));
819 Ok(conn)
820 }
821 Err(why) => {
822 let mut st = self.state.lock().unwrap();
823 st.down_since = Some(Instant::now());
824 st.why = why.clone();
825 Err(unavailable(&self.name, &why))
826 }
827 }
828 }
829
830 pub(super) fn dead(&self) -> Option<String> {
833 self.state.lock().unwrap().dead.clone()
834 }
835
836 pub(super) fn why_down(&self) -> Option<String> {
839 let st = self.state.lock().unwrap();
840 if st.dead.is_some() {
841 return st.dead.clone();
842 }
843 match &st.conn {
844 Some(c) if c.alive() => None,
845 _ => Some(if st.why.is_empty() { "not connected".to_string() } else { st.why.clone() }),
846 }
847 }
848
849 pub(super) fn is_up(&self) -> bool {
851 let st = self.state.lock().unwrap();
852 st.dead.is_none() && st.conn.as_ref().is_some_and(|c| c.alive())
853 }
854
855 fn live(&self) -> Result<Option<Arc<Conn>>, PlexusStreamItem> {
856 let st = self.state.lock().unwrap();
857 if let Some(why) = &st.dead {
858 return Err(unavailable(&self.name, why));
859 }
860 Ok(st.conn.clone().filter(|c| c.alive()))
861 }
862}
863
864pub(super) fn gone(shared: &Weak<Shared>, conn: &Arc<Conn>, why: &str) {
866 conn.on_gone(why);
867 if let Some(s) = shared.upgrade() {
868 s.lost(conn, why);
869 }
870}
871
872async fn ask(conn: &Conn, method: &str, params: Value, timeout: Duration) -> Result<Value, String> {
874 let (_, mut rx) = conn.open(method, params, timeout).await.map_err(|e| match e {
875 PlexusStreamItem::Error { message, .. } => message,
876 other => format!("{other:?}"),
877 })?;
878 let deadline = tokio::time::Instant::now() + timeout;
879 let mut first = None;
880 loop {
881 match tokio::time::timeout_at(deadline, rx.recv()).await {
882 Ok(Some(PlexusStreamItem::Data { content, .. })) => {
883 if first.is_none() {
884 first = Some(content.into_value());
885 }
886 }
887 Ok(Some(PlexusStreamItem::Error { message, .. })) => return Err(message),
888 Ok(Some(PlexusStreamItem::Done { .. })) | Ok(None) => break,
889 Ok(Some(_)) => {}
890 Err(_) => return Err(format!("no answer in {timeout:?}")),
891 }
892 }
893 first.ok_or_else(|| "it answered no data".to_string())
894}