Skip to main content

microvms_protocol/
exec.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Exec wire types: the bodies, queries, and SSE event payloads of `/v1/exec/*`.
3//!
4//! Every type here derives both halves of serde. The daemon needs only one half of
5//! each and a client needs the other, and a type that carries one half is a type the
6//! other side has to hand-write — which is the drift this crate exists to prevent.
7//! The published `docs/schema.json` is generated from these same attributes under
8//! both contracts, so a shape change is a schema diff rather than a surprise.
9
10use std::borrow::Cow;
11use std::collections::HashMap;
12
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15
16/// Where an exec sits in its lifecycle. Mirrors `ExecPhase` in the model crate.
17///
18/// `JsonSchema` rides along with `Serialize` on every type from here down that
19/// crosses the wire. schemars reads the same `#[serde(...)]` attributes serde
20/// does, so the published schema describes what the daemon actually emits — the
21/// `rename_all` below is the reason this matters rather than a formality.
22#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
23#[serde(rename_all = "snake_case")]
24pub enum Phase {
25    /// Child spawned, still running (or its pipes still held by a grandchild).
26    Running,
27    /// Child exited and output is buffered and readable.
28    Exited,
29    /// Caller acked; output has been released and the entry awaits collection.
30    Acked,
31}
32
33impl Phase {
34    /// Every phase, in lifecycle order.
35    ///
36    /// Public because a client that publishes the closed set — both bindings do, in
37    /// their `session_constants` — needs the list from the type rather than a spelled-out
38    /// copy that goes stale the first time a phase is added. The round-trip test below
39    /// holds `ALL` complete by exhaustive match.
40    pub const ALL: [Phase; 3] = [Phase::Running, Phase::Exited, Phase::Acked];
41
42    /// The wire spelling — the exact string serde writes under `rename_all` above.
43    ///
44    /// Here rather than in each client because two bindings each grew their own
45    /// three-arm match over this enum; a variant renamed on the wire must change
46    /// exactly one table, and the test below is what keeps this one equal to serde's.
47    pub const fn as_str(self) -> &'static str {
48        match self {
49            Phase::Running => "running",
50            Phase::Exited => "exited",
51            Phase::Acked => "acked",
52        }
53    }
54}
55
56/// Captured output and exit status of a finished exec.
57#[derive(Clone, Debug, Default, Deserialize, JsonSchema, Serialize)]
58pub struct Outcome {
59    /// Exit code, or `None` when the child died to a signal.
60    pub exit_code: Option<i32>,
61    /// Signal number that killed the child, when one did.
62    pub signal: Option<i32>,
63    /// The daemon execution deadline fired. Absent on older daemons, which cannot
64    /// distinguish deadline expiry from other signal deaths.
65    #[serde(default)]
66    pub timed_out: bool,
67    pub stdout: String,
68    pub stderr: String,
69    /// Set when either stream hit `max_output_bytes` and was cut. An explicit
70    /// flag rather than a sentinel string in the output: a marker inside the
71    /// bytes is indistinguishable from output that happens to contain it.
72    pub truncated: bool,
73    /// Set when the post-exit linger deadline expired with the pipes still open,
74    /// meaning some grandchild is alive and may write more that nobody will see.
75    /// Reported rather than hidden, because a harness that sees empty output from
76    /// a command it knows produced some needs to be able to tell why.
77    pub writers_may_be_alive: bool,
78}
79
80/// Which pipe a streamed chunk came from. Both share one offset space, so a
81/// client holds one cursor rather than two that can disagree about ordering.
82#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
83#[serde(rename_all = "snake_case")]
84pub enum StreamKind {
85    Stdout,
86    Stderr,
87}
88
89impl StreamKind {
90    /// Both kinds, in the order the daemon documents them.
91    ///
92    /// Same reason as [`Phase::ALL`]: the bindings publish this closed set, and a
93    /// list they spell themselves is a list the enum can outgrow.
94    pub const ALL: [StreamKind; 2] = [StreamKind::Stdout, StreamKind::Stderr];
95
96    /// The wire spelling — the exact string serde writes under `rename_all` above.
97    pub const fn as_str(self) -> &'static str {
98        match self {
99            StreamKind::Stdout => "stdout",
100            StreamKind::Stderr => "stderr",
101        }
102    }
103}
104
105/// A user or group as a start request names it: a numeric id, or a name the daemon
106/// resolves against the guest's `/etc/passwd` or `/etc/group`.
107///
108/// Untagged, so the wire carries a bare JSON integer or a bare JSON string and nothing
109/// else. An integer serializes exactly as the `u32` this field used to be, which is what
110/// keeps a client that only ever sends ids byte-compatible with a daemon that predates
111/// names. A string sent to such a daemon is refused as `malformed_request` rather than
112/// misread.
113///
114/// A string that names no row and is all ASCII digits is read as that id, the way
115/// `docker exec -u 1000` reads it: a harness that carries a uid as a string reaches the
116/// same account an integer would.
117#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
118#[serde(untagged)]
119pub enum NameOrId {
120    /// A numeric uid or gid, applied as given.
121    Id(u32),
122    /// A user or group name, resolved in the guest before anything is spawned.
123    Name(String),
124}
125
126impl From<u32> for NameOrId {
127    fn from(id: u32) -> Self {
128        NameOrId::Id(id)
129    }
130}
131
132impl From<&str> for NameOrId {
133    fn from(name: &str) -> Self {
134        NameOrId::Name(name.to_string())
135    }
136}
137
138impl From<String> for NameOrId {
139    fn from(name: String) -> Self {
140        NameOrId::Name(name)
141    }
142}
143
144impl std::str::FromStr for NameOrId {
145    type Err = std::convert::Infallible;
146
147    /// A command-line spelling: all digits is an id, anything else is a name.
148    ///
149    /// An id is sent as an integer rather than as its digits so a daemon that predates
150    /// names still accepts it.
151    fn from_str(raw: &str) -> Result<Self, Self::Err> {
152        Ok(match raw.parse::<u32>() {
153            Ok(id) if raw.bytes().all(|b| b.is_ascii_digit()) => NameOrId::Id(id),
154            _ => NameOrId::Name(raw.to_string()),
155        })
156    }
157}
158
159impl std::fmt::Display for NameOrId {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        match self {
162            NameOrId::Id(id) => write!(f, "{id}"),
163            NameOrId::Name(name) => f.write_str(name),
164        }
165    }
166}
167
168/// How a start request's `command` is run: `false` (an argv), `true` (`/bin/sh -c`), or
169/// the name of a shell the daemon resolves and runs as `<shell> -c`.
170///
171/// Untagged for [`NameOrId`]'s reason: a boolean serializes exactly as the field always
172/// did, so an old daemon keeps accepting it, and a string sent to an old daemon is refused
173/// rather than misread.
174#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
175#[serde(untagged)]
176pub enum Shell {
177    /// `false` execs `command` as an argv; `true` runs it under `/bin/sh -c`.
178    Flag(bool),
179    /// A shell name such as `"bash"` (resolved on the child's `PATH`, the image's `PATH`,
180    /// `/bin` and `/usr/bin`) or an absolute path to one.
181    Named(String),
182}
183
184impl Default for Shell {
185    fn default() -> Self {
186        Shell::Flag(false)
187    }
188}
189
190impl From<bool> for Shell {
191    fn from(flag: bool) -> Self {
192        Shell::Flag(flag)
193    }
194}
195
196impl From<&str> for Shell {
197    fn from(name: &str) -> Self {
198        Shell::Named(name.to_string())
199    }
200}
201
202impl From<String> for Shell {
203    fn from(name: String) -> Self {
204        Shell::Named(name)
205    }
206}
207
208impl Shell {
209    /// Whether `command` is a script for a shell rather than an argv.
210    pub fn is_shell(&self) -> bool {
211        !matches!(self, Shell::Flag(false))
212    }
213}
214
215/// A start request. `command` is either an argv array or, with `shell` set, a single
216/// script string.
217#[derive(Debug, Deserialize, JsonSchema, Serialize)]
218#[non_exhaustive]
219pub struct StartRequest {
220    /// Caller-minted idempotency key. Harbor retries, and a retry must not
221    /// produce a second child.
222    pub exec_id: String,
223    /// argv when `shell` is false, or the script when it is set.
224    pub command: Vec<String>,
225    /// `false`, `true` (`/bin/sh -c`), or a shell name such as `"bash"`. A name the guest
226    /// cannot resolve answers 400 `unknown_shell` before anything is spawned.
227    #[serde(default)]
228    pub shell: Shell,
229    /// Omitted means inherit the daemon's working directory. See the module docs.
230    #[serde(default)]
231    pub cwd: Option<String>,
232    #[serde(default)]
233    pub env: HashMap<String, String>,
234    /// The user to demote to: a numeric uid, or a name resolved against the guest's
235    /// `/etc/passwd`. Optional; omitted means run as the daemon's own user. A name the
236    /// guest does not have answers 400 `unknown_user` before anything is spawned.
237    ///
238    /// A user with a passwd row, however it was given, gets `HOME`, `USER` and `LOGNAME`
239    /// from the row, beneath the launch environment and `env`. A user given by name also
240    /// gets the row's primary gid when `group` is omitted; a numeric uid keeps the
241    /// daemon's group, as it always did.
242    #[serde(default)]
243    pub user: Option<NameOrId>,
244    /// The group to demote to: a numeric gid, or a name resolved against `/etc/group`. A
245    /// name the guest does not have answers 400 `unknown_group`.
246    #[serde(default)]
247    pub group: Option<NameOrId>,
248    /// Wall-clock budget. Validated before the child spawns — the predecessor
249    /// raised on a bad value inside the waiter thread, by which point the child
250    /// was already running and became an orphan.
251    #[serde(default)]
252    pub timeout_sec: Option<f64>,
253    /// Whether to give the child a writable stdin pipe. Defaults to false, which
254    /// keeps `Stdio::null()`.
255    ///
256    /// Opt-in rather than always-on, and not only for tidiness: a child holding an
257    /// open stdin pipe nobody will ever write to is a child that blocks forever
258    /// the first time it reads. `/bin/sh` reading a script from stdin, `git`
259    /// deciding it can prompt, any tool that probes for input — all of them behave
260    /// differently against a pipe than against `/dev/null`. Every existing caller
261    /// gets today's behavior by not setting this.
262    #[serde(default)]
263    pub stdin: bool,
264    /// Whether to signal the exec's whole process group once its own child exits.
265    ///
266    /// Off by default, and the default is the contract this daemon has always had:
267    /// a backgrounded grandchild that inherited the output pipe keeps running and
268    /// keeps writing, and the linger deadline is what bounds how long the daemon
269    /// waits on it. That is the "backgrounded server keeps logging" guarantee, and
270    /// callers rely on it. Set to `true`, the daemon runs the same SIGTERM-then-
271    /// SIGKILL escalation `POST /v1/exec/{id}/kill` uses against the group as soon
272    /// as the child's exit is observed, so nothing the command left behind outlives
273    /// it and the linger sees EOF rather than `writers_may_be_alive`. A timed-out
274    /// exec is already escalated and is not escalated twice.
275    #[serde(default)]
276    pub reap_group_on_exit: bool,
277    /// Whether the child's environment starts from the image's `ENV`.
278    ///
279    /// Off by default, which keeps the property the daemon has always had: nothing from
280    /// its own environment reaches a child. Set, the environment the daemon inherited as
281    /// the container `CMD`, minus every `AGENTD_*` variable, is the lowest layer, under
282    /// the passwd identity, the launch environment and `env`. The agent token is never in
283    /// that snapshot: it arrives in the run hook, after the snapshot is taken.
284    ///
285    /// A daemon that predates this field ignores it, as serde ignores any unknown key; a
286    /// caller that depends on it can read `image_env_keys` on `GET /v1/health`, which such
287    /// a daemon does not report.
288    #[serde(default)]
289    pub inherit_image_env: bool,
290}
291
292/// `POST /v1/exec/{id}/stdin` body.
293///
294/// Both fields optional and both meaningful together: a final chunk plus EOF in
295/// one request is the common case for feeding a prompt, and forcing two round
296/// trips would leave a window where the child has the bytes but not the EOF that
297/// tells it the input is complete.
298#[derive(Debug, Default, Deserialize, JsonSchema, Serialize)]
299pub struct StdinRequest {
300    /// Base64 so arbitrary bytes survive JSON. A JSON string cannot carry
301    /// non-UTF-8, and stdin is bytes.
302    #[serde(default)]
303    pub data_b64: Option<String>,
304    /// `"eof"` closes the pipe after any `data_b64` is written. Named rather than
305    /// a bare boolean so the field has somewhere to grow.
306    #[serde(default)]
307    pub signal: Option<String>,
308}
309
310/// `POST /v1/exec/{id}/stdin` response.
311///
312/// `pub` rather than private, like every other type in this module the schema
313/// route publishes: the generator names them by type, so a response shape that
314/// stays private is a shape a consumer cannot be told about.
315#[derive(Debug, Deserialize, JsonSchema, Serialize)]
316pub struct StdinResponse {
317    pub exec_id: String,
318    pub written: usize,
319    pub eof: bool,
320}
321
322/// `GET /v1/exec/{id}/stream` query.
323#[derive(Debug, Default, Deserialize, JsonSchema, Serialize)]
324pub struct StreamQuery {
325    /// Byte offset to resume from. Absent means 0, i.e. everything still in the
326    /// replay window.
327    #[serde(default)]
328    pub offset: Option<u64>,
329}
330
331/// One `output` SSE event.
332#[derive(Debug, Deserialize, JsonSchema, Serialize)]
333pub struct OutputEvent {
334    pub offset: u64,
335    pub stream: StreamKind,
336    pub output: String,
337}
338
339/// One `gap` SSE event: the byte range a lagging or late subscriber lost.
340#[derive(Debug, Deserialize, JsonSchema, Serialize)]
341pub struct GapEvent {
342    pub from: u64,
343    pub to: u64,
344}
345
346/// The terminal `exit` SSE event. Emitted before the stream ends, so a client
347/// that sees the body close without one knows the connection failed rather than
348/// the command finishing.
349#[derive(Debug, Deserialize, JsonSchema, Serialize)]
350pub struct ExitEvent {
351    pub exit_code: Option<i32>,
352    pub signal: Option<i32>,
353    /// The daemon execution deadline fired. Absent on older daemons, which cannot
354    /// distinguish deadline expiry from other signal deaths.
355    #[serde(default)]
356    pub timed_out: bool,
357    pub truncated: bool,
358    pub writers_may_be_alive: bool,
359    /// Total bytes published, so a client can assert it saw all of them.
360    pub offset: u64,
361}
362
363#[derive(Debug, Deserialize, JsonSchema, Serialize)]
364pub struct StartResponse {
365    pub exec_id: String,
366    pub phase: Phase,
367}
368
369/// `POST /v1/exec/{id}/kill` response.
370///
371/// A named type rather than the `serde_json::json!` literal this used to be: an
372/// ad-hoc `Value` has no schema to derive, so the one route whose body a client
373/// most needs to branch on — `killed` distinguishes "signalled" from "the group
374/// was already gone", and both are 200 — would have been the one route the
375/// published document could not describe.
376#[derive(Debug, Deserialize, JsonSchema, Serialize)]
377pub struct KillResponse {
378    pub exec_id: String,
379    /// Whether a signal was actually delivered. `false` with a 200 means the
380    /// process group had already exited, which is the outcome a kill wanted.
381    pub killed: bool,
382}
383
384/// One entry of `GET /v1/procs`: an exec's process group as the daemon sees it.
385///
386/// The exec registry knows the group (`pgid`) and whether the direct child has
387/// exited; `/proc` knows which pids are still in that group. Both halves are here
388/// because the interesting case is their disagreement — `child_exited: true` with a
389/// non-empty `pids` is a command that finished while something it started did not,
390/// which is exactly what a caller asking "did this step leave anything behind"
391/// needs to see and could not before.
392#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
393pub struct ProcGroup {
394    pub exec_id: String,
395    /// The process group id captured at spawn. `None` when the child was reaped
396    /// before it could be read, in which case `pids` is empty because there is no
397    /// group to scan for.
398    pub pgid: Option<u32>,
399    /// Seconds since the epoch on the daemon's clock when the child was spawned.
400    /// The same convention as a hook observation's `fired_at`.
401    pub started_at: u64,
402    /// Whether the exec's own child has exited. Read from the terminal marker an
403    /// ack cannot take, so an acked exec still reads as exited here.
404    pub child_exited: bool,
405    /// Whether the exec was started with `reap_group_on_exit`.
406    pub reap: bool,
407    /// Live pids whose process group is `pgid`, read from `/proc`. Zombies are not
408    /// live and are not listed. Empty once the group is gone, and empty for an
409    /// entry whose `pgid` is `None`.
410    pub pids: Vec<u32>,
411}
412
413/// `GET /v1/procs` response.
414#[derive(Debug, Default, Deserialize, JsonSchema, Serialize)]
415pub struct ProcsResponse {
416    /// Every registered exec, in registry order, whether or not anything in its
417    /// group is still alive. An exec that exited cleanly with nothing left behind
418    /// is listed with `child_exited: true` and `pids: []`.
419    pub procs: Vec<ProcGroup>,
420}
421
422#[derive(Debug, Deserialize, JsonSchema, Serialize)]
423pub struct PollResponse {
424    pub exec_id: String,
425    pub phase: Phase,
426    #[serde(skip_serializing_if = "Option::is_none")]
427    #[serde(flatten)]
428    pub result: Option<Outcome>,
429}
430
431/// The JSON error body every failing control route returns.
432///
433/// `error` is a stable machine-readable slug and `detail` is prose for a human
434/// reading a log. A client branches on `error` and the status code, never on
435/// `detail` — which is why the slug is one of the constants below, chosen at each
436/// call site, rather than a formatted string. `Cow` so the daemon keeps naming a
437/// `&'static str` while a client deserializes into an owned one.
438#[derive(Debug, Deserialize, JsonSchema, Serialize)]
439pub struct ErrorBody {
440    pub error: Cow<'static, str>,
441    pub detail: String,
442}
443
444/// The `event:` names on `GET /v1/exec/{id}/stream`.
445///
446/// Named rather than spelled at each `Event::default().event(..)` call: the daemon
447/// writes these and a client matches on them, and a typo on either side is a
448/// stream that silently carries events nobody dispatches.
449pub const EVENT_OUTPUT: &str = "output";
450pub const EVENT_GAP: &str = "gap";
451pub const EVENT_EXIT: &str = "exit";
452
453// The `ErrorBody::error` slugs. Every failing control route returns one of these,
454// they are the part of the surface a client branches on, and they are `&'static
455// str` for the same reason the status code is a number: the pairing of the two is
456// the contract, and neither is derivable from the other.
457
458/// The body is not a valid request for this route. Always 400, never 404.
459pub const ERROR_MALFORMED_REQUEST: &str = "malformed_request";
460/// No exec is registered under this id, or its entry was collected after an ack.
461pub const ERROR_UNKNOWN_EXEC: &str = "unknown_exec";
462/// The child could not be spawned. 500, deliberately not 404.
463pub const ERROR_SPAWN_FAILED: &str = "spawn_failed";
464/// The exec has not exited, so acking would drop output still being written.
465pub const ERROR_STILL_RUNNING: &str = "still_running";
466/// An earlier ack already released the output.
467pub const ERROR_ALREADY_ACKED: &str = "already_acked";
468/// The exec was started without `stdin: true`. Fixable at start time, hence 409.
469pub const ERROR_STDIN_NOT_REQUESTED: &str = "stdin_not_requested";
470/// stdin was closed by an earlier eof, or the child stopped reading. 410: a retry
471/// will never succeed.
472pub const ERROR_STDIN_CLOSED: &str = "stdin_closed";
473/// The child did not read within the configured window. Retryable, and some bytes
474/// may already have been written.
475pub const ERROR_STDIN_WRITE_TIMEOUT: &str = "stdin_write_timeout";
476/// The decoded write exceeds the configured per-write cap.
477pub const ERROR_STDIN_WRITE_TOO_LARGE: &str = "stdin_write_too_large";
478/// The write to the pipe failed for a reason other than a broken pipe.
479pub const ERROR_STDIN_WRITE_FAILED: &str = "stdin_write_failed";
480/// A start request named a user the guest's `/etc/passwd` does not contain. 400, and
481/// nothing was spawned; `detail` names the user.
482pub const ERROR_UNKNOWN_USER: &str = "unknown_user";
483/// A start request named a group the guest's `/etc/group` does not contain. 400, and
484/// nothing was spawned; `detail` names the group.
485pub const ERROR_UNKNOWN_GROUP: &str = "unknown_group";
486/// A start request named a shell that no searched directory holds as an executable
487/// file. 400, and nothing was spawned; `detail` names the shell and where it looked.
488pub const ERROR_UNKNOWN_SHELL: &str = "unknown_shell";
489
490impl StartRequest {
491    /// A request to run `command` as an argv under the idempotency key `exec_id`, with
492    /// every other field at the default a body that omits it gets.
493    ///
494    /// `exec_id` has no default here: minting one needs a clock and a random source,
495    /// which this crate doesn't have, and a shared fixed key would answer a second exec
496    /// from the first one's record.
497    ///
498    /// This and the `with_*` setters are the only way to build a request outside this
499    /// crate, because `StartRequest` is `#[non_exhaustive]`. The builder is where every
500    /// optional field gets its one default, the same one serde gives a body that omits it,
501    /// so a client can't pick its own `timeout_sec`, `reap_group_on_exit` or
502    /// `inherit_image_env` by writing the struct out, and a field added here reaches every
503    /// caller as its default instead of as a build error in each client. (The struct's own
504    /// doc comment is the published schema's description, so this lives here.)
505    ///
506    /// ```
507    /// # use microvms_protocol::exec::StartRequest;
508    /// let request: StartRequest = StartRequest::new("e1", vec!["true".into()]);
509    /// # assert!(!request.reap_group_on_exit);
510    /// ```
511    ///
512    /// The same request as a struct expression doesn't build outside this crate (E0639):
513    ///
514    /// ```compile_fail,E0639
515    /// # use microvms_protocol::exec::StartRequest;
516    /// let request: StartRequest = StartRequest { ..StartRequest::new("e1", vec!["true".into()]) };
517    /// # assert!(!request.reap_group_on_exit);
518    /// ```
519    pub fn new(exec_id: impl Into<String>, command: Vec<String>) -> Self {
520        StartRequest {
521            exec_id: exec_id.into(),
522            command,
523            shell: Shell::default(),
524            cwd: None,
525            env: HashMap::new(),
526            user: None,
527            group: None,
528            timeout_sec: None,
529            stdin: false,
530            reap_group_on_exit: false,
531            inherit_image_env: false,
532        }
533    }
534
535    /// Run `command` as a script under this shell, or as an argv for `false`.
536    pub fn with_shell(mut self, shell: impl Into<Shell>) -> Self {
537        self.shell = shell.into();
538        self
539    }
540
541    /// The child's working directory; `None` inherits the daemon's.
542    pub fn with_cwd(mut self, cwd: Option<String>) -> Self {
543        self.cwd = cwd;
544        self
545    }
546
547    /// The top layer of the child's environment.
548    pub fn with_env(mut self, env: HashMap<String, String>) -> Self {
549        self.env = env;
550        self
551    }
552
553    /// The user to demote to; `None` runs as the daemon's own user.
554    pub fn with_user(mut self, user: Option<NameOrId>) -> Self {
555        self.user = user;
556        self
557    }
558
559    /// The group to demote to; `None` follows [`StartRequest::user`]'s rule.
560    pub fn with_group(mut self, group: Option<NameOrId>) -> Self {
561        self.group = group;
562        self
563    }
564
565    /// The daemon's wall-clock budget for the child; `None` sets none.
566    pub fn with_timeout_sec(mut self, timeout_sec: Option<f64>) -> Self {
567        self.timeout_sec = timeout_sec;
568        self
569    }
570
571    /// Give the child a writable stdin pipe.
572    pub fn with_stdin(mut self, stdin: bool) -> Self {
573        self.stdin = stdin;
574        self
575    }
576
577    /// Signal the exec's process group once its own child exits.
578    pub fn with_reap_group_on_exit(mut self, reap: bool) -> Self {
579        self.reap_group_on_exit = reap;
580        self
581    }
582
583    /// Start the child's environment from the image's `ENV`.
584    pub fn with_inherit_image_env(mut self, inherit: bool) -> Self {
585        self.inherit_image_env = inherit;
586        self
587    }
588}
589
590#[cfg(test)]
591mod tests {
592    use super::*;
593
594    /// The `rename_all` is the reason these types are shared rather than mirrored:
595    /// a client that spelled the variants from the Rust identifiers would send
596    /// `Running` where the daemon emits `running`.
597    #[test]
598    fn phase_and_stream_kind_round_trip_through_their_serde_names() {
599        assert_eq!(
600            serde_json::to_string(&Phase::Running).expect("serializes"),
601            "\"running\""
602        );
603        assert_eq!(
604            serde_json::from_str::<Phase>("\"acked\"").expect("deserializes"),
605            Phase::Acked
606        );
607        assert_eq!(
608            serde_json::to_string(&StreamKind::Stderr).expect("serializes"),
609            "\"stderr\""
610        );
611    }
612
613    /// `as_str` is a second spelling of what serde already writes, so the two must be
614    /// equal for every variant or the bindings publish names the wire never carries.
615    ///
616    /// `ALL` is held complete by exhaustion rather than by a length check: the matches
617    /// below have no wildcard arm, so a variant added to either enum fails to compile
618    /// here until it is added to its `ALL` too.
619    #[test]
620    fn as_str_agrees_with_serde_for_every_phase_and_stream_kind() {
621        for phase in Phase::ALL {
622            assert_eq!(
623                serde_json::to_string(&phase).expect("serializes"),
624                format!("\"{}\"", phase.as_str()),
625                "{phase:?} spells differently through as_str and serde"
626            );
627            match phase {
628                Phase::Running | Phase::Exited | Phase::Acked => {}
629            }
630        }
631        for kind in StreamKind::ALL {
632            assert_eq!(
633                serde_json::to_string(&kind).expect("serializes"),
634                format!("\"{}\"", kind.as_str()),
635                "{kind:?} spells differently through as_str and serde"
636            );
637            match kind {
638                StreamKind::Stdout | StreamKind::Stderr => {}
639            }
640        }
641    }
642
643    /// Both halves of serde on one type is the whole point of the crate: what the
644    /// daemon writes is what a client reads, checked rather than assumed.
645    #[test]
646    fn a_response_the_daemon_writes_deserializes_on_the_client_side() {
647        let written = serde_json::to_string(&StartResponse {
648            exec_id: "e1".into(),
649            phase: Phase::Running,
650        })
651        .expect("serializes");
652        let read: StartResponse = serde_json::from_str(&written).expect("deserializes");
653        assert_eq!(read.exec_id, "e1");
654        assert_eq!(read.phase, Phase::Running);
655    }
656
657    /// A request the client writes is one the daemon's extractor accepts, including
658    /// every serde default — the fields a caller omits are the ones most likely to
659    /// disagree across a hand-written mirror.
660    #[test]
661    fn a_start_request_omitting_every_defaulted_field_deserializes() {
662        let request: StartRequest =
663            serde_json::from_str(r#"{"exec_id":"e1","command":["true"]}"#).expect("deserializes");
664        assert_eq!(request.shell, Shell::Flag(false));
665        assert!(!request.shell.is_shell());
666        assert!(request.user.is_none() && request.group.is_none());
667        assert!(
668            !request.inherit_image_env,
669            "inheriting the image env is opt-in: an old client keeps the exact launch map"
670        );
671        assert!(request.cwd.is_none());
672        assert!(request.env.is_empty());
673        assert!(request.timeout_sec.is_none());
674        assert!(!request.stdin);
675        assert!(
676            !request.reap_group_on_exit,
677            "reaping is opt-in: an old client that never heard of the flag keeps today's \
678             grandchild-output guarantee"
679        );
680    }
681
682    /// The builder's defaults are the wire's: a request built with nothing set writes the
683    /// same body the daemon reads from one that omits every optional field. A builder that
684    /// picked its own default would send a different request than an old client does.
685    ///
686    /// **Falsification**: 2026-09-27. Defaulting `reap_group_on_exit` to `true` in
687    /// `StartRequest::new` turned this red; restored after.
688    #[test]
689    fn the_builder_defaults_are_the_ones_serde_gives_an_omitted_field() {
690        let built = StartRequest::new("e1", vec!["true".into()]);
691        let read: StartRequest =
692            serde_json::from_str(r#"{"exec_id":"e1","command":["true"]}"#).expect("deserializes");
693        assert_eq!(
694            serde_json::to_value(&built).expect("serializes"),
695            serde_json::to_value(&read).expect("serializes"),
696        );
697    }
698
699    /// The union fields read both spellings and write each back as it came, so a client
700    /// that only ever sends integers and booleans sends the bytes it always did.
701    #[test]
702    fn user_group_and_shell_read_both_spellings_and_write_them_back() {
703        let request: StartRequest = serde_json::from_str(
704            r#"{"exec_id":"e1","command":["id"],"user":1000,"group":"staff","shell":"bash","inherit_image_env":true}"#,
705        )
706        .expect("deserializes");
707        assert_eq!(request.user, Some(NameOrId::Id(1000)));
708        assert_eq!(request.group, Some(NameOrId::Name("staff".into())));
709        assert_eq!(request.shell, Shell::Named("bash".into()));
710        assert!(request.inherit_image_env);
711
712        let written = serde_json::to_value(&request).expect("serializes");
713        assert_eq!(written["user"], 1000);
714        assert_eq!(written["group"], "staff");
715        assert_eq!(written["shell"], "bash");
716
717        let legacy: StartRequest =
718            serde_json::from_str(r#"{"exec_id":"e1","command":["id"],"shell":true,"user":0}"#)
719                .expect("deserializes");
720        assert_eq!(legacy.shell, Shell::Flag(true));
721        let written = serde_json::to_value(&legacy).expect("serializes");
722        assert_eq!(written["shell"], true);
723        assert_eq!(written["user"], 0);
724    }
725
726    /// Anything but an integer or a string for a user, or a boolean or a string for a
727    /// shell, is a malformed body rather than a coerced value.
728    #[test]
729    fn other_json_types_for_the_union_fields_are_refused() {
730        for body in [
731            r#"{"exec_id":"e1","command":["id"],"user":-1}"#,
732            r#"{"exec_id":"e1","command":["id"],"user":1.5}"#,
733            r#"{"exec_id":"e1","command":["id"],"user":["root"]}"#,
734            r#"{"exec_id":"e1","command":["id"],"group":{"name":"x"}}"#,
735            r#"{"exec_id":"e1","command":["id"],"shell":1}"#,
736            r#"{"exec_id":"e1","command":["id"],"shell":null}"#,
737        ] {
738            assert!(
739                serde_json::from_str::<StartRequest>(body).is_err(),
740                "accepted {body}"
741            );
742        }
743    }
744
745    /// The command-line spelling: digits are an id and go out as an integer.
746    #[test]
747    fn a_flag_of_digits_is_an_id_and_anything_else_a_name() {
748        assert_eq!("1000".parse::<NameOrId>(), Ok(NameOrId::Id(1000)));
749        assert_eq!("0".parse::<NameOrId>(), Ok(NameOrId::Id(0)));
750        assert_eq!(
751            "agent".parse::<NameOrId>(),
752            Ok(NameOrId::Name("agent".into()))
753        );
754        assert_eq!("+1".parse::<NameOrId>(), Ok(NameOrId::Name("+1".into())));
755        assert_eq!(
756            "99999999999".parse::<NameOrId>(),
757            Ok(NameOrId::Name("99999999999".into()))
758        );
759    }
760
761    /// The procs body round-trips with every field present, `pgid: null` included, so a
762    /// client can tell "no group was ever captured" from "the group is empty".
763    #[test]
764    fn a_procs_response_round_trips_with_a_missing_pgid() {
765        let written = serde_json::to_string(&ProcsResponse {
766            procs: vec![ProcGroup {
767                exec_id: "e1".into(),
768                pgid: None,
769                started_at: 1_756_500_000,
770                child_exited: true,
771                reap: false,
772                pids: Vec::new(),
773            }],
774        })
775        .expect("serializes");
776        assert_eq!(
777            written,
778            r#"{"procs":[{"exec_id":"e1","pgid":null,"started_at":1756500000,"child_exited":true,"reap":false,"pids":[]}]}"#
779        );
780        let read: ProcsResponse = serde_json::from_str(&written).expect("deserializes");
781        assert_eq!(read.procs.len(), 1);
782        assert_eq!(read.procs[0].pgid, None);
783        assert!(read.procs[0].child_exited);
784    }
785
786    /// The flatten-plus-skip on `PollResponse.result` is the one shape whose two
787    /// serde contracts genuinely differ — absent on the way out while running, and
788    /// the same absence has to read back as `None` on the way in. Both directions,
789    /// because a client that read a running exec's missing outcome as an error would
790    /// fail on every poll before the first one that mattered.
791    #[test]
792    fn a_poll_response_round_trips_with_and_without_an_outcome() {
793        let running = serde_json::to_string(&PollResponse {
794            exec_id: "e1".into(),
795            phase: Phase::Running,
796            result: None,
797        })
798        .expect("serializes");
799        assert_eq!(running, r#"{"exec_id":"e1","phase":"running"}"#);
800        let read: PollResponse = serde_json::from_str(&running).expect("deserializes");
801        assert!(read.result.is_none());
802
803        let exited = serde_json::to_string(&PollResponse {
804            exec_id: "e1".into(),
805            phase: Phase::Exited,
806            result: Some(Outcome {
807                exit_code: Some(0),
808                stdout: "hi".into(),
809                ..Outcome::default()
810            }),
811        })
812        .expect("serializes");
813        let read: PollResponse = serde_json::from_str(&exited).expect("deserializes");
814        let outcome = read.result.expect("the outcome is flattened into the body");
815        assert_eq!(outcome.exit_code, Some(0));
816        assert_eq!(outcome.stdout, "hi");
817    }
818
819    /// `error` is a `Cow`, so the daemon's borrowed slug and a client's owned string
820    /// are the same type on the wire.
821    #[test]
822    fn an_error_body_carries_a_borrowed_slug_and_reads_back_owned() {
823        let written = serde_json::to_string(&ErrorBody {
824            error: Cow::Borrowed(ERROR_UNKNOWN_EXEC),
825            detail: "e1".into(),
826        })
827        .expect("serializes");
828        assert_eq!(written, r#"{"error":"unknown_exec","detail":"e1"}"#);
829        let read: ErrorBody = serde_json::from_str(&written).expect("deserializes");
830        assert_eq!(read.error, ERROR_UNKNOWN_EXEC);
831    }
832}