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/// How fast a child that died is started (or dialed) again: the n-th restart
87/// within a minute waits `initial · 2ⁿ`, at most `max`, after the death; past
88/// `per_minute` restarts in the last minute a call is answered
89/// `child_unavailable` at once until the minute has passed.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub struct Backoff {
92    pub initial: Duration,
93    pub max: Duration,
94    pub per_minute: usize,
95}
96
97impl Default for Backoff {
98    /// 0.5 s → 30 s, at most 5 restarts a minute.
99    fn default() -> Self {
100        Self { initial: Duration::from_millis(500), max: Duration::from_secs(30), per_minute: 5 }
101    }
102}
103
104impl Backoff {
105    /// The wait before restart number `n + 1` of the current minute.
106    pub fn delay(&self, n: usize) -> Duration {
107        let factor = 1u32.checked_shl(n.min(31) as u32).unwrap_or(u32::MAX);
108        self.initial.saturating_mul(factor).min(self.max)
109    }
110}
111
112/// How the service reaches its children.
113#[derive(Debug, Clone)]
114pub struct ChildOptions {
115    /// The hop's `principal` (spec/12) on stdio, where no upgrade proves one:
116    /// the service naming itself, `service:<its namespace>`. Over a
117    /// WebSocket with a [`key`](Self::key) the principal is that key's.
118    pub principal: String,
119    /// A key file (synapse's `~/.plexus/keys/<name>.key`: a 32-byte Ed25519
120    /// seed, base64, mode 0600): a WebSocket child is dialed with its proof
121    /// (spec/00). Read at each dial and never kept, logged or passed on.
122    pub key: Option<PathBuf>,
123    /// The proof's agent id (spec/00): 1–64 of `[A-Za-z0-9._-]`.
124    pub agent: String,
125    /// A child's answer to `_info`, its schema, and every call's open.
126    pub timeout: Duration,
127    /// Calls open on one child at once; past it, `too_many_calls`.
128    pub max_calls: usize,
129    /// Items held for one call whose caller has not read them; past it the
130    /// child's reader waits (lossless; the child's other calls wait too).
131    pub buffer: usize,
132    /// Variables passed from the service's environment to a stdio child,
133    /// beyond `PATH`, `HOME`, `LANG` and `PLEXUS_CHILD_NAME`.
134    pub env: Vec<String>,
135    /// Restarting (or redialing) a child that died.
136    pub backoff: Backoff,
137    /// NEST-4: how many levels of static children a mount walks
138    /// (`--child-max-depth`); a deeper one fails the mount, naming it.
139    pub max_depth: usize,
140    /// NEST-6: how many dynamic instances' schemas a mount keeps
141    /// (`--child-schema-cache`), the least recently used out first; 0
142    /// keeps none.
143    pub schema_cache: usize,
144}
145
146impl Default for ChildOptions {
147    fn default() -> Self {
148        Self {
149            principal: "service:service".into(),
150            key: None,
151            agent: "service".into(),
152            timeout: Duration::from_secs(5),
153            max_calls: 1024,
154            buffer: 1024,
155            env: Vec::new(),
156            backoff: Backoff::default(),
157            max_depth: 8,
158            schema_cache: 1024,
159        }
160    }
161}
162
163impl ChildOptions {
164    /// The defaults for the service named `service`: its hop principal
165    /// `service:<service>`, its proof's agent id `service`.
166    pub fn for_service(service: &str) -> Self {
167        Self { principal: format!("service:{service}"), agent: service.to_string(), ..Self::default() }
168    }
169}
170
171/// Why a child was not mounted.
172#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
173pub enum ChildError {
174    /// A `--child` value that does not read.
175    #[error("child spec {0}")]
176    Spec(String),
177    /// The child did not start, did not answer, or answered a schema the
178    /// service will not mount: `(mount name, why)`.
179    #[error("child {0}: {1}")]
180    Start(String, String),
181}
182
183/// `5s`, `500ms`, `2m`, `1.5` (seconds) — `--child-timeout`'s spelling.
184pub fn parse_duration(s: &str) -> Result<Duration, String> {
185    let s = s.trim();
186    let (num, unit) = match s.find(|c: char| !(c.is_ascii_digit() || c == '.')) {
187        Some(i) => (&s[..i], s[i..].trim()),
188        None => (s, "s"),
189    };
190    let n: f64 = num.parse().map_err(|_| format!("`{s}` is not a duration (5s, 500ms, 2m)"))?;
191    let secs = match unit {
192        "ms" => n / 1e3,
193        "s" | "" => n,
194        "m" => n * 60.0,
195        _ => return Err(format!("`{s}`: the unit is ms, s or m")),
196    };
197    if !secs.is_finite() || secs <= 0.0 {
198        return Err(format!("`{s}` is not a positive duration"));
199    }
200    Ok(Duration::from_secs_f64(secs))
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    #[test]
208    fn child_spec_parses() {
209        let s: ChildSpec = r#"echo=stdio:python -I -m echo --x "a b""#.parse().unwrap();
210        assert_eq!(s, ChildSpec::Stdio { name: "echo".into(), argv: vec!["python".into(), "-I".into(), "-m".into(), "echo".into(), "--x".into(), "a b".into()] });
211        let s: ChildSpec = r#"echo=stdio:"python3 -I stub.py --stdio""#.parse().unwrap();
212        assert_eq!(s, ChildSpec::Stdio { name: "echo".into(), argv: vec!["python3".into(), "-I".into(), "stub.py".into(), "--stdio".into()] });
213        assert_eq!("echo=ws://h:1".parse::<ChildSpec>().unwrap(), ChildSpec::Ws { name: "echo".into(), url: "ws://h:1".into() });
214        assert_eq!("e-2=wss://h/ws".parse::<ChildSpec>().unwrap(), ChildSpec::Ws { name: "e-2".into(), url: "wss://h/ws".into() });
215        let refused = |s: &str, why: &str| {
216            let e = s.parse::<ChildSpec>().unwrap_err().to_string();
217            assert!(e.contains(why), "{s}: {e}");
218        };
219        refused("echo", "no `=`");
220        refused("=stdio:x", "empty mount name");
221        refused("a.b=stdio:x", "dotted");
222        refused("a b=stdio:x", "holds ` `");
223        refused("echo=tcp://h:1", "unknown scheme `tcp`");
224        refused("echo=stdio:", "no command");
225        refused(r#"echo=stdio:python "unclosed"#, "does not split");
226        refused("echo=ws://:1", "names its host");
227    }
228
229    #[test]
230    fn child_spec_round_trips() {
231        for s in [r#"echo=stdio:python -I "a b""#, "echo=ws://127.0.0.1:4480"] {
232            let spec: ChildSpec = s.parse().unwrap();
233            assert_eq!(spec.to_string().parse::<ChildSpec>().unwrap(), spec);
234        }
235    }
236
237    #[test]
238    fn backoff_doubles_to_its_cap() {
239        let b = Backoff::default();
240        let ms: Vec<u128> = (0..8).map(|n| b.delay(n).as_millis()).collect();
241        assert_eq!(ms, [500, 1000, 2000, 4000, 8000, 16000, 30000, 30000]);
242    }
243
244    #[test]
245    fn durations_read() {
246        assert_eq!(parse_duration("5s").unwrap(), Duration::from_secs(5));
247        assert_eq!(parse_duration("250ms").unwrap(), Duration::from_millis(250));
248        assert_eq!(parse_duration("2").unwrap(), Duration::from_secs(2));
249        assert_eq!(parse_duration("1m").unwrap(), Duration::from_secs(60));
250        assert!(parse_duration("0s").is_err() && parse_duration("x").is_err() && parse_duration("3h").is_err());
251    }
252}