Skip to main content

plexus_core/plexus/remote_child/
spec.rs

1//! What a child is (`ChildSpec`), how the service reaches it
2//! (`ChildOptions`, `Backoff`) and how that fails (`ChildError`).
3
4use std::fmt;
5use std::path::PathBuf;
6use std::str::FromStr;
7use std::time::Duration;
8
9/// A child service: an activation in another process, mounted under `name`.
10///
11/// Spelled `NAME=stdio:CMD ARGS…` (the command split as a shell would split
12/// it, then run without one) or `NAME=ws://HOST:PORT[/PATH]` (`wss://` with
13/// the `child-wss` feature). `NAME` is one segment of `[A-Za-z0-9_-]` — the
14/// mount name, which wins over the namespace the child declares.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum ChildSpec {
17    /// A process the service spawns; frames on its stdin / stdout (spec/11).
18    Stdio { name: String, argv: Vec<String> },
19    /// A service the service dials; frames on a WebSocket (spec/00, 01).
20    Ws { name: String, url: String },
21}
22
23impl ChildSpec {
24    /// The mount name.
25    pub fn name(&self) -> &str {
26        match self {
27            Self::Stdio { name, .. } | Self::Ws { name, .. } => name,
28        }
29    }
30}
31
32impl fmt::Display for ChildSpec {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::Stdio { name, argv } => write!(f, "{name}=stdio:{}", shell_words::join(argv)),
36            Self::Ws { name, url } => write!(f, "{name}={url}"),
37        }
38    }
39}
40
41fn spec_err(s: &str, why: impl fmt::Display) -> ChildError {
42    ChildError::Spec(format!("`{s}`: {why}"))
43}
44
45impl FromStr for ChildSpec {
46    type Err = ChildError;
47
48    fn from_str(s: &str) -> Result<Self, ChildError> {
49        let (name, rest) = s.split_once('=').ok_or_else(|| spec_err(s, "no `=`: a child is NAME=stdio:CMD or NAME=ws://HOST:PORT"))?;
50        let name = name.trim();
51        if name.is_empty() {
52            return Err(spec_err(s, "an empty mount name"));
53        }
54        if name.contains('.') {
55            return Err(spec_err(s, format!("the mount name `{name}` is dotted: it is one segment (a method's path is `{name}.<method>`)")));
56        }
57        if let Some(bad) = name.chars().find(|c| !(c.is_ascii_alphanumeric() || *c == '_' || *c == '-')) {
58            return Err(spec_err(s, format!("the mount name `{name}` holds `{bad}`: only letters, digits, `_` and `-`")));
59        }
60        let name = name.to_string();
61        if let Some(cmd) = rest.strip_prefix("stdio:") {
62            let mut argv = shell_words::split(cmd).map_err(|e| spec_err(s, format!("its command does not split: {e}")))?;
63            // `NAME=stdio:"CMD ARGS"` with the quotes kept (an env var, a
64            // config file): one quoted word is the whole command.
65            if argv.len() == 1 && argv[0].contains(char::is_whitespace) {
66                argv = shell_words::split(&argv[0]).map_err(|e| spec_err(s, format!("its command does not split: {e}")))?;
67            }
68            if argv.is_empty() {
69                return Err(spec_err(s, "no command after `stdio:`"));
70            }
71            return Ok(Self::Stdio { name, argv });
72        }
73        if rest.starts_with("ws://") || rest.starts_with("wss://") {
74            let host = rest.split_once("://").map(|(_, h)| h).unwrap_or("");
75            let host = host.split(['/', '?', '#']).next().unwrap_or("");
76            if host.is_empty() || host.starts_with(':') {
77                return Err(spec_err(s, "a WebSocket child names its host: ws://HOST:PORT"));
78            }
79            return Ok(Self::Ws { name, url: rest.to_string() });
80        }
81        let scheme = rest.split_once(':').map(|(a, _)| a).unwrap_or(rest);
82        Err(spec_err(s, format!("unknown scheme `{scheme}`: a child is reached by `stdio:CMD`, `ws://…` or `wss://…`")))
83    }
84}
85
86/// KEEL-7: the reason a dial refused for its transport gives, as plexus-dyn's
87/// `refused` says it.
88pub const INSECURE_TRANSPORT: &str = "insecure_transport";
89
90/// KEEL-7 (DYNAUTH-8, TM-3): whether the service may dial `url` — `wss://`
91/// anywhere, `ws://` only to loopback ([`is_loopback_host`]) unless
92/// `insecure_ws` (`transport.insecure_ws`) allows it. Every dial the
93/// service makes asks it before a socket opens: a `ws://` child's, a
94/// dial-out's, plexus-dyn's. `Err`: why, said (the reason is
95/// [`INSECURE_TRANSPORT`]).
96pub fn check_ws_url(url: &str, insecure_ws: bool) -> Result<(), String> {
97    let rest = if let Some(r) = url.strip_prefix("wss://") {
98        return match url_host(r) {
99            Some(_) => Ok(()),
100            None => Err(format!("`{url}` names no host")),
101        };
102    } else if let Some(r) = url.strip_prefix("ws://") {
103        r
104    } else {
105        return Err(format!("`{url}`: a peer is reached by ws:// or wss://"));
106    };
107    let Some(host) = url_host(rest) else { return Err(format!("`{url}` names no host")) };
108    if is_loopback_host(&host) || insecure_ws {
109        return Ok(());
110    }
111    Err(format!(
112        "`{url}`: plain ws:// only to loopback (127.0.0.0/8, ::1, localhost); a peer beyond it is reached by wss://, its hop (who calls, under what ceiling) never in clear (`transport.insecure_ws` allows it, a test network's)"
113    ))
114}
115
116/// KEEL-7: whether `url` is plain `ws://` beyond loopback — a dial
117/// [`check_ws_url`] admits only under `transport.insecure_ws`, and which
118/// says so where its mount is listed.
119pub fn is_insecure_ws(url: &str) -> bool {
120    url.starts_with("ws://") && check_ws_url(url, false).is_err() && check_ws_url(url, true).is_ok()
121}
122
123/// The host of `authority[/path]`: no user info, no port, an IPv6
124/// literal without its brackets, lower case.
125fn url_host(rest: &str) -> Option<String> {
126    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
127    let authority = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
128    let host = if let Some(v6) = authority.strip_prefix('[') {
129        v6.split_once(']')?.0
130    } else {
131        authority.split(':').next().unwrap_or("")
132    };
133    (!host.is_empty()).then(|| host.to_ascii_lowercase())
134}
135
136/// KEEL-7: loopback as every dial reads it — `127.0.0.0/8`, `::1`, an
137/// IPv4-mapped `127.x`, and `localhost` (a trailing dot allowed); a name
138/// that only begins so (`localhost.example.com`) is not.
139pub fn is_loopback_host(host: &str) -> bool {
140    let host = host.trim_end_matches('.');
141    if host.eq_ignore_ascii_case("localhost") {
142        return true;
143    }
144    match host.parse::<std::net::IpAddr>() {
145        Ok(std::net::IpAddr::V4(a)) => a.is_loopback(),
146        Ok(std::net::IpAddr::V6(a)) => a.is_loopback() || a.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback()),
147        Err(_) => false,
148    }
149}
150
151/// How fast a child that died is started (or dialed) again: the n-th restart
152/// within a minute waits `initial · 2ⁿ`, at most `max`, after the death; past
153/// `per_minute` restarts in the last minute a call is answered
154/// `child_unavailable` at once until the minute has passed.
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub struct Backoff {
157    pub initial: Duration,
158    pub max: Duration,
159    pub per_minute: usize,
160}
161
162impl Default for Backoff {
163    /// 0.5 s → 30 s, at most 5 restarts a minute.
164    fn default() -> Self {
165        Self { initial: Duration::from_millis(500), max: Duration::from_secs(30), per_minute: 5 }
166    }
167}
168
169impl Backoff {
170    /// The wait before restart number `n + 1` of the current minute.
171    pub fn delay(&self, n: usize) -> Duration {
172        let factor = 1u32.checked_shl(n.min(31) as u32).unwrap_or(u32::MAX);
173        self.initial.saturating_mul(factor).min(self.max)
174    }
175}
176
177/// How the service reaches its children.
178#[derive(Debug, Clone)]
179pub struct ChildOptions {
180    /// The hop's `principal` (spec/12) on stdio, where no upgrade proves one:
181    /// the service naming itself, `service:<its namespace>`. Over a
182    /// WebSocket with a [`key`](Self::key) the principal is that key's.
183    pub principal: String,
184    /// A key file (synapse's `~/.plexus/keys/<name>.key`: a 32-byte Ed25519
185    /// seed, base64, mode 0600): a WebSocket child is dialed with its proof
186    /// (spec/00). Read at each dial and never kept, logged or passed on.
187    pub key: Option<PathBuf>,
188    /// The proof's agent id (spec/00): 1–64 of `[A-Za-z0-9._-]`.
189    pub agent: String,
190    /// A child's answer to `_info`, its schema, and every call's open.
191    pub timeout: Duration,
192    /// Calls open on one child at once; past it, `too_many_calls`.
193    pub max_calls: usize,
194    /// Items held for one call whose caller has not read them; past it the
195    /// child's reader waits (lossless; the child's other calls wait too).
196    pub buffer: usize,
197    /// Variables passed from the service's environment to a stdio child,
198    /// beyond `PATH`, `HOME`, `LANG` and `PLEXUS_CHILD_NAME`.
199    pub env: Vec<String>,
200    /// Restarting (or redialing) a child that died.
201    pub backoff: Backoff,
202    /// NEST-4: how many levels of static children a mount walks
203    /// (`--child-max-depth`); a deeper one fails the mount, naming it.
204    pub max_depth: usize,
205    /// NEST-6: how many dynamic instances' schemas a mount keeps
206    /// (`--child-schema-cache`), the least recently used out first; 0
207    /// keeps none.
208    pub schema_cache: usize,
209    /// NEST-11: the service the child is mounted in, whose routing and gate
210    /// take the calls the child makes back (`_host.call`). `None`: the
211    /// service a call was routed in when the child was connected (inside a
212    /// call), else the service of the first call forwarded to it.
213    pub host: Option<crate::plexus::service_scope::WeakService>,
214    /// NEST-12: a WebSocket child is pinged this often, and marked down —
215    /// every open call `child_unavailable`, the next one redialing — when
216    /// nothing has come from it for twice as long. `None`: never pinged.
217    pub ping: Option<Duration>,
218    /// NEST-16: a child whose schema declares no `needs` may call up, under
219    /// a call it serves, anything that call's caller could (NEST-11's rule,
220    /// `--child-legacy-upcalls`). Off: such a child has the standard upward
221    /// interface alone (`host.schema`, `host.whoami`, `host.log`,
222    /// `host.notify`). Kept for one release, for dendrites built before
223    /// `needs`; a child that declares needs is held to them either way.
224    pub legacy_upcalls: bool,
225    /// DYNAUTH-8: a PEM file of certificate authorities a `wss://` child's
226    /// certificate may chain to, beside the webpki roots (a private CA, a
227    /// test network's). Certificates are always validated; nothing turns
228    /// that off.
229    pub tls_roots: Option<PathBuf>,
230    /// KEEL-7: dial plain `ws://` beyond loopback (`transport.insecure_ws`,
231    /// a test network's). Off: such a child is refused before a socket
232    /// opens ([`check_ws_url`]); on: dialed, and its mount says
233    /// [`insecure`](crate::plexus::RemoteChild::insecure).
234    pub insecure_ws: bool,
235    /// DYNAUTH-12: the service's peer-token issuer. With one, every call
236    /// forwarded for a signed-in caller carries a token minted for it
237    /// (`hop.token`): `aud` the child's proved key (bound to it), or
238    /// `pipe:<name>` for a child on the service's own pipe; scope the
239    /// forwarded grant and the child's needs (consented), within the call's
240    /// reach. A WebSocket child that proved no key gets none. A keyed child
241    /// calling back presents a proof of possession with each call.
242    pub tokens: Option<std::sync::Arc<crate::plexus::peer_token::TokenIssuer>>,
243}
244
245impl Default for ChildOptions {
246    fn default() -> Self {
247        Self {
248            principal: "service:service".into(),
249            key: None,
250            agent: "service".into(),
251            timeout: Duration::from_secs(5),
252            max_calls: 1024,
253            buffer: 1024,
254            env: Vec::new(),
255            backoff: Backoff::default(),
256            max_depth: 8,
257            schema_cache: 1024,
258            host: None,
259            ping: None,
260            legacy_upcalls: false,
261            tls_roots: None,
262            insecure_ws: false,
263            tokens: None,
264        }
265    }
266}
267
268impl ChildOptions {
269    /// The defaults for the service named `service`: its hop principal
270    /// `service:<service>`, its proof's agent id `service`.
271    pub fn for_service(service: &str) -> Self {
272        Self { principal: format!("service:{service}"), agent: service.to_string(), ..Self::default() }
273    }
274
275    /// NEST-11: these options, the child mounted in `service` (see
276    /// [`ChildOptions::host`]).
277    /// NEST-16: NEST-11's broad rule for a child that declares no `needs`
278    /// ([`ChildOptions::legacy_upcalls`]).
279    pub fn with_legacy_upcalls(mut self, on: bool) -> Self {
280        self.legacy_upcalls = on;
281        self
282    }
283
284    pub fn with_host(mut self, service: &crate::plexus::DynamicHub) -> Self {
285        self.host = Some(service.downgrade());
286        self
287    }
288}
289
290/// Why a child was not mounted.
291#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
292pub enum ChildError {
293    /// A `--child` value that does not read.
294    #[error("child spec {0}")]
295    Spec(String),
296    /// The child did not start, did not answer, or answered a schema the
297    /// service will not mount: `(mount name, why)`.
298    #[error("child {0}: {1}")]
299    Start(String, String),
300}
301
302/// `5s`, `500ms`, `2m`, `1.5` (seconds) — `--child-timeout`'s spelling.
303pub fn parse_duration(s: &str) -> Result<Duration, String> {
304    let s = s.trim();
305    let (num, unit) = match s.find(|c: char| !(c.is_ascii_digit() || c == '.')) {
306        Some(i) => (&s[..i], s[i..].trim()),
307        None => (s, "s"),
308    };
309    let n: f64 = num.parse().map_err(|_| format!("`{s}` is not a duration (5s, 500ms, 2m)"))?;
310    let secs = match unit {
311        "ms" => n / 1e3,
312        "s" | "" => n,
313        "m" => n * 60.0,
314        _ => return Err(format!("`{s}`: the unit is ms, s or m")),
315    };
316    if !secs.is_finite() || secs <= 0.0 {
317        return Err(format!("`{s}` is not a positive duration"));
318    }
319    Ok(Duration::from_secs_f64(secs))
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    #[test]
327    fn child_spec_parses() {
328        let s: ChildSpec = r#"echo=stdio:python -I -m echo --x "a b""#.parse().unwrap();
329        assert_eq!(s, ChildSpec::Stdio { name: "echo".into(), argv: vec!["python".into(), "-I".into(), "-m".into(), "echo".into(), "--x".into(), "a b".into()] });
330        let s: ChildSpec = r#"echo=stdio:"python3 -I stub.py --stdio""#.parse().unwrap();
331        assert_eq!(s, ChildSpec::Stdio { name: "echo".into(), argv: vec!["python3".into(), "-I".into(), "stub.py".into(), "--stdio".into()] });
332        assert_eq!("echo=ws://h:1".parse::<ChildSpec>().unwrap(), ChildSpec::Ws { name: "echo".into(), url: "ws://h:1".into() });
333        assert_eq!("e-2=wss://h/ws".parse::<ChildSpec>().unwrap(), ChildSpec::Ws { name: "e-2".into(), url: "wss://h/ws".into() });
334        let refused = |s: &str, why: &str| {
335            let e = s.parse::<ChildSpec>().unwrap_err().to_string();
336            assert!(e.contains(why), "{s}: {e}");
337        };
338        refused("echo", "no `=`");
339        refused("=stdio:x", "empty mount name");
340        refused("a.b=stdio:x", "dotted");
341        refused("a b=stdio:x", "holds ` `");
342        refused("echo=tcp://h:1", "unknown scheme `tcp`");
343        refused("echo=stdio:", "no command");
344        refused(r#"echo=stdio:python "unclosed"#, "does not split");
345        refused("echo=ws://:1", "names its host");
346    }
347
348    #[test]
349    fn child_spec_round_trips() {
350        for s in [r#"echo=stdio:python -I "a b""#, "echo=ws://127.0.0.1:4480"] {
351            let spec: ChildSpec = s.parse().unwrap();
352            assert_eq!(spec.to_string().parse::<ChildSpec>().unwrap(), spec);
353        }
354    }
355
356    #[test]
357    fn backoff_doubles_to_its_cap() {
358        let b = Backoff::default();
359        let ms: Vec<u128> = (0..8).map(|n| b.delay(n).as_millis()).collect();
360        assert_eq!(ms, [500, 1000, 2000, 4000, 8000, 16000, 30000, 30000]);
361    }
362
363    #[test]
364    fn durations_read() {
365        assert_eq!(parse_duration("5s").unwrap(), Duration::from_secs(5));
366        assert_eq!(parse_duration("250ms").unwrap(), Duration::from_millis(250));
367        assert_eq!(parse_duration("2").unwrap(), Duration::from_secs(2));
368        assert_eq!(parse_duration("1m").unwrap(), Duration::from_secs(60));
369        assert!(parse_duration("0s").is_err() && parse_duration("x").is_err() && parse_duration("3h").is_err());
370    }
371}