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    pub stdout: String,
64    pub stderr: String,
65    /// Set when either stream hit `max_output_bytes` and was cut. An explicit
66    /// flag rather than a sentinel string in the output: a marker inside the
67    /// bytes is indistinguishable from output that happens to contain it.
68    pub truncated: bool,
69    /// Set when the post-exit linger deadline expired with the pipes still open,
70    /// meaning some grandchild is alive and may write more that nobody will see.
71    /// Reported rather than hidden, because a harness that sees empty output from
72    /// a command it knows produced some needs to be able to tell why.
73    pub writers_may_be_alive: bool,
74}
75
76/// Which pipe a streamed chunk came from. Both share one offset space, so a
77/// client holds one cursor rather than two that can disagree about ordering.
78#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
79#[serde(rename_all = "snake_case")]
80pub enum StreamKind {
81    Stdout,
82    Stderr,
83}
84
85impl StreamKind {
86    /// Both kinds, in the order the daemon documents them.
87    ///
88    /// Same reason as [`Phase::ALL`]: the bindings publish this closed set, and a
89    /// list they spell themselves is a list the enum can outgrow.
90    pub const ALL: [StreamKind; 2] = [StreamKind::Stdout, StreamKind::Stderr];
91
92    /// The wire spelling — the exact string serde writes under `rename_all` above.
93    pub const fn as_str(self) -> &'static str {
94        match self {
95            StreamKind::Stdout => "stdout",
96            StreamKind::Stderr => "stderr",
97        }
98    }
99}
100
101/// A start request. `command` is either an argv array or, with `shell: true`, a
102/// single script string.
103#[derive(Debug, Deserialize, JsonSchema, Serialize)]
104pub struct StartRequest {
105    /// Caller-minted idempotency key. Harbor retries, and a retry must not
106    /// produce a second child.
107    pub exec_id: String,
108    /// argv when `shell` is false, or the script when it is true.
109    pub command: Vec<String>,
110    #[serde(default)]
111    pub shell: bool,
112    /// Omitted means inherit the daemon's working directory. See the module docs.
113    #[serde(default)]
114    pub cwd: Option<String>,
115    #[serde(default)]
116    pub env: HashMap<String, String>,
117    /// Numeric uid to demote to. Optional; omitted means run as the daemon's own
118    /// user.
119    #[serde(default)]
120    pub user: Option<u32>,
121    #[serde(default)]
122    pub group: Option<u32>,
123    /// Wall-clock budget. Validated before the child spawns — the predecessor
124    /// raised on a bad value inside the waiter thread, by which point the child
125    /// was already running and became an orphan.
126    #[serde(default)]
127    pub timeout_sec: Option<f64>,
128    /// Whether to give the child a writable stdin pipe. Defaults to false, which
129    /// keeps `Stdio::null()`.
130    ///
131    /// Opt-in rather than always-on, and not only for tidiness: a child holding an
132    /// open stdin pipe nobody will ever write to is a child that blocks forever
133    /// the first time it reads. `/bin/sh` reading a script from stdin, `git`
134    /// deciding it can prompt, any tool that probes for input — all of them behave
135    /// differently against a pipe than against `/dev/null`. Every existing caller
136    /// gets today's behavior by not setting this.
137    #[serde(default)]
138    pub stdin: bool,
139    /// Whether to signal the exec's whole process group once its own child exits.
140    ///
141    /// Off by default, and the default is the contract this daemon has always had:
142    /// a backgrounded grandchild that inherited the output pipe keeps running and
143    /// keeps writing, and the linger deadline is what bounds how long the daemon
144    /// waits on it. That is the "backgrounded server keeps logging" guarantee, and
145    /// callers rely on it. Set to `true`, the daemon runs the same SIGTERM-then-
146    /// SIGKILL escalation `POST /v1/exec/{id}/kill` uses against the group as soon
147    /// as the child's exit is observed, so nothing the command left behind outlives
148    /// it and the linger sees EOF rather than `writers_may_be_alive`. A timed-out
149    /// exec is already escalated and is not escalated twice.
150    #[serde(default)]
151    pub reap_group_on_exit: bool,
152}
153
154/// `POST /v1/exec/{id}/stdin` body.
155///
156/// Both fields optional and both meaningful together: a final chunk plus EOF in
157/// one request is the common case for feeding a prompt, and forcing two round
158/// trips would leave a window where the child has the bytes but not the EOF that
159/// tells it the input is complete.
160#[derive(Debug, Default, Deserialize, JsonSchema, Serialize)]
161pub struct StdinRequest {
162    /// Base64 so arbitrary bytes survive JSON. A JSON string cannot carry
163    /// non-UTF-8, and stdin is bytes.
164    #[serde(default)]
165    pub data_b64: Option<String>,
166    /// `"eof"` closes the pipe after any `data_b64` is written. Named rather than
167    /// a bare boolean so the field has somewhere to grow.
168    #[serde(default)]
169    pub signal: Option<String>,
170}
171
172/// `POST /v1/exec/{id}/stdin` response.
173///
174/// `pub` rather than private, like every other type in this module the schema
175/// route publishes: the generator names them by type, so a response shape that
176/// stays private is a shape a consumer cannot be told about.
177#[derive(Debug, Deserialize, JsonSchema, Serialize)]
178pub struct StdinResponse {
179    pub exec_id: String,
180    pub written: usize,
181    pub eof: bool,
182}
183
184/// `GET /v1/exec/{id}/stream` query.
185#[derive(Debug, Default, Deserialize, JsonSchema, Serialize)]
186pub struct StreamQuery {
187    /// Byte offset to resume from. Absent means 0, i.e. everything still in the
188    /// replay window.
189    #[serde(default)]
190    pub offset: Option<u64>,
191}
192
193/// One `output` SSE event.
194#[derive(Debug, Deserialize, JsonSchema, Serialize)]
195pub struct OutputEvent {
196    pub offset: u64,
197    pub stream: StreamKind,
198    pub output: String,
199}
200
201/// One `gap` SSE event: the byte range a lagging or late subscriber lost.
202#[derive(Debug, Deserialize, JsonSchema, Serialize)]
203pub struct GapEvent {
204    pub from: u64,
205    pub to: u64,
206}
207
208/// The terminal `exit` SSE event. Emitted before the stream ends, so a client
209/// that sees the body close without one knows the connection failed rather than
210/// the command finishing.
211#[derive(Debug, Deserialize, JsonSchema, Serialize)]
212pub struct ExitEvent {
213    pub exit_code: Option<i32>,
214    pub signal: Option<i32>,
215    pub truncated: bool,
216    pub writers_may_be_alive: bool,
217    /// Total bytes published, so a client can assert it saw all of them.
218    pub offset: u64,
219}
220
221#[derive(Debug, Deserialize, JsonSchema, Serialize)]
222pub struct StartResponse {
223    pub exec_id: String,
224    pub phase: Phase,
225}
226
227/// `POST /v1/exec/{id}/kill` response.
228///
229/// A named type rather than the `serde_json::json!` literal this used to be: an
230/// ad-hoc `Value` has no schema to derive, so the one route whose body a client
231/// most needs to branch on — `killed` distinguishes "signalled" from "the group
232/// was already gone", and both are 200 — would have been the one route the
233/// published document could not describe.
234#[derive(Debug, Deserialize, JsonSchema, Serialize)]
235pub struct KillResponse {
236    pub exec_id: String,
237    /// Whether a signal was actually delivered. `false` with a 200 means the
238    /// process group had already exited, which is the outcome a kill wanted.
239    pub killed: bool,
240}
241
242/// One entry of `GET /v1/procs`: an exec's process group as the daemon sees it.
243///
244/// The exec registry knows the group (`pgid`) and whether the direct child has
245/// exited; `/proc` knows which pids are still in that group. Both halves are here
246/// because the interesting case is their disagreement — `child_exited: true` with a
247/// non-empty `pids` is a command that finished while something it started did not,
248/// which is exactly what a caller asking "did this step leave anything behind"
249/// needs to see and could not before.
250#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize)]
251pub struct ProcGroup {
252    pub exec_id: String,
253    /// The process group id captured at spawn. `None` when the child was reaped
254    /// before it could be read, in which case `pids` is empty because there is no
255    /// group to scan for.
256    pub pgid: Option<u32>,
257    /// Seconds since the epoch on the daemon's clock when the child was spawned.
258    /// The same convention as a hook observation's `fired_at`.
259    pub started_at: u64,
260    /// Whether the exec's own child has exited. Read from the terminal marker an
261    /// ack cannot take, so an acked exec still reads as exited here.
262    pub child_exited: bool,
263    /// Whether the exec was started with `reap_group_on_exit`.
264    pub reap: bool,
265    /// Live pids whose process group is `pgid`, read from `/proc`. Zombies are not
266    /// live and are not listed. Empty once the group is gone, and empty for an
267    /// entry whose `pgid` is `None`.
268    pub pids: Vec<u32>,
269}
270
271/// `GET /v1/procs` response.
272#[derive(Debug, Default, Deserialize, JsonSchema, Serialize)]
273pub struct ProcsResponse {
274    /// Every registered exec, in registry order, whether or not anything in its
275    /// group is still alive. An exec that exited cleanly with nothing left behind
276    /// is listed with `child_exited: true` and `pids: []`.
277    pub procs: Vec<ProcGroup>,
278}
279
280#[derive(Debug, Deserialize, JsonSchema, Serialize)]
281pub struct PollResponse {
282    pub exec_id: String,
283    pub phase: Phase,
284    #[serde(skip_serializing_if = "Option::is_none")]
285    #[serde(flatten)]
286    pub result: Option<Outcome>,
287}
288
289/// The JSON error body every failing control route returns.
290///
291/// `error` is a stable machine-readable slug and `detail` is prose for a human
292/// reading a log. A client branches on `error` and the status code, never on
293/// `detail` — which is why the slug is one of the constants below, chosen at each
294/// call site, rather than a formatted string. `Cow` so the daemon keeps naming a
295/// `&'static str` while a client deserializes into an owned one.
296#[derive(Debug, Deserialize, JsonSchema, Serialize)]
297pub struct ErrorBody {
298    pub error: Cow<'static, str>,
299    pub detail: String,
300}
301
302/// The `event:` names on `GET /v1/exec/{id}/stream`.
303///
304/// Named rather than spelled at each `Event::default().event(..)` call: the daemon
305/// writes these and a client matches on them, and a typo on either side is a
306/// stream that silently carries events nobody dispatches.
307pub const EVENT_OUTPUT: &str = "output";
308pub const EVENT_GAP: &str = "gap";
309pub const EVENT_EXIT: &str = "exit";
310
311// The `ErrorBody::error` slugs. Every failing control route returns one of these,
312// they are the part of the surface a client branches on, and they are `&'static
313// str` for the same reason the status code is a number: the pairing of the two is
314// the contract, and neither is derivable from the other.
315
316/// The body is not a valid request for this route. Always 400, never 404.
317pub const ERROR_MALFORMED_REQUEST: &str = "malformed_request";
318/// No exec is registered under this id, or its entry was collected after an ack.
319pub const ERROR_UNKNOWN_EXEC: &str = "unknown_exec";
320/// The child could not be spawned. 500, deliberately not 404.
321pub const ERROR_SPAWN_FAILED: &str = "spawn_failed";
322/// The exec has not exited, so acking would drop output still being written.
323pub const ERROR_STILL_RUNNING: &str = "still_running";
324/// An earlier ack already released the output.
325pub const ERROR_ALREADY_ACKED: &str = "already_acked";
326/// The exec was started without `stdin: true`. Fixable at start time, hence 409.
327pub const ERROR_STDIN_NOT_REQUESTED: &str = "stdin_not_requested";
328/// stdin was closed by an earlier eof, or the child stopped reading. 410: a retry
329/// will never succeed.
330pub const ERROR_STDIN_CLOSED: &str = "stdin_closed";
331/// The child did not read within the configured window. Retryable, and some bytes
332/// may already have been written.
333pub const ERROR_STDIN_WRITE_TIMEOUT: &str = "stdin_write_timeout";
334/// The decoded write exceeds the configured per-write cap.
335pub const ERROR_STDIN_WRITE_TOO_LARGE: &str = "stdin_write_too_large";
336/// The write to the pipe failed for a reason other than a broken pipe.
337pub const ERROR_STDIN_WRITE_FAILED: &str = "stdin_write_failed";
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    /// The `rename_all` is the reason these types are shared rather than mirrored:
344    /// a client that spelled the variants from the Rust identifiers would send
345    /// `Running` where the daemon emits `running`.
346    #[test]
347    fn phase_and_stream_kind_round_trip_through_their_serde_names() {
348        assert_eq!(
349            serde_json::to_string(&Phase::Running).expect("serializes"),
350            "\"running\""
351        );
352        assert_eq!(
353            serde_json::from_str::<Phase>("\"acked\"").expect("deserializes"),
354            Phase::Acked
355        );
356        assert_eq!(
357            serde_json::to_string(&StreamKind::Stderr).expect("serializes"),
358            "\"stderr\""
359        );
360    }
361
362    /// `as_str` is a second spelling of what serde already writes, so the two must be
363    /// equal for every variant or the bindings publish names the wire never carries.
364    ///
365    /// `ALL` is held complete by exhaustion rather than by a length check: the matches
366    /// below have no wildcard arm, so a variant added to either enum fails to compile
367    /// here until it is added to its `ALL` too.
368    #[test]
369    fn as_str_agrees_with_serde_for_every_phase_and_stream_kind() {
370        for phase in Phase::ALL {
371            assert_eq!(
372                serde_json::to_string(&phase).expect("serializes"),
373                format!("\"{}\"", phase.as_str()),
374                "{phase:?} spells differently through as_str and serde"
375            );
376            match phase {
377                Phase::Running | Phase::Exited | Phase::Acked => {}
378            }
379        }
380        for kind in StreamKind::ALL {
381            assert_eq!(
382                serde_json::to_string(&kind).expect("serializes"),
383                format!("\"{}\"", kind.as_str()),
384                "{kind:?} spells differently through as_str and serde"
385            );
386            match kind {
387                StreamKind::Stdout | StreamKind::Stderr => {}
388            }
389        }
390    }
391
392    /// Both halves of serde on one type is the whole point of the crate: what the
393    /// daemon writes is what a client reads, checked rather than assumed.
394    #[test]
395    fn a_response_the_daemon_writes_deserializes_on_the_client_side() {
396        let written = serde_json::to_string(&StartResponse {
397            exec_id: "e1".into(),
398            phase: Phase::Running,
399        })
400        .expect("serializes");
401        let read: StartResponse = serde_json::from_str(&written).expect("deserializes");
402        assert_eq!(read.exec_id, "e1");
403        assert_eq!(read.phase, Phase::Running);
404    }
405
406    /// A request the client writes is one the daemon's extractor accepts, including
407    /// every serde default — the fields a caller omits are the ones most likely to
408    /// disagree across a hand-written mirror.
409    #[test]
410    fn a_start_request_omitting_every_defaulted_field_deserializes() {
411        let request: StartRequest =
412            serde_json::from_str(r#"{"exec_id":"e1","command":["true"]}"#).expect("deserializes");
413        assert!(!request.shell);
414        assert!(request.cwd.is_none());
415        assert!(request.env.is_empty());
416        assert!(request.timeout_sec.is_none());
417        assert!(!request.stdin);
418        assert!(
419            !request.reap_group_on_exit,
420            "reaping is opt-in: an old client that never heard of the flag keeps today's \
421             grandchild-output guarantee"
422        );
423    }
424
425    /// The procs body round-trips with every field present, `pgid: null` included, so a
426    /// client can tell "no group was ever captured" from "the group is empty".
427    #[test]
428    fn a_procs_response_round_trips_with_a_missing_pgid() {
429        let written = serde_json::to_string(&ProcsResponse {
430            procs: vec![ProcGroup {
431                exec_id: "e1".into(),
432                pgid: None,
433                started_at: 1_756_500_000,
434                child_exited: true,
435                reap: false,
436                pids: Vec::new(),
437            }],
438        })
439        .expect("serializes");
440        assert_eq!(
441            written,
442            r#"{"procs":[{"exec_id":"e1","pgid":null,"started_at":1756500000,"child_exited":true,"reap":false,"pids":[]}]}"#
443        );
444        let read: ProcsResponse = serde_json::from_str(&written).expect("deserializes");
445        assert_eq!(read.procs.len(), 1);
446        assert_eq!(read.procs[0].pgid, None);
447        assert!(read.procs[0].child_exited);
448    }
449
450    /// The flatten-plus-skip on `PollResponse.result` is the one shape whose two
451    /// serde contracts genuinely differ — absent on the way out while running, and
452    /// the same absence has to read back as `None` on the way in. Both directions,
453    /// because a client that read a running exec's missing outcome as an error would
454    /// fail on every poll before the first one that mattered.
455    #[test]
456    fn a_poll_response_round_trips_with_and_without_an_outcome() {
457        let running = serde_json::to_string(&PollResponse {
458            exec_id: "e1".into(),
459            phase: Phase::Running,
460            result: None,
461        })
462        .expect("serializes");
463        assert_eq!(running, r#"{"exec_id":"e1","phase":"running"}"#);
464        let read: PollResponse = serde_json::from_str(&running).expect("deserializes");
465        assert!(read.result.is_none());
466
467        let exited = serde_json::to_string(&PollResponse {
468            exec_id: "e1".into(),
469            phase: Phase::Exited,
470            result: Some(Outcome {
471                exit_code: Some(0),
472                stdout: "hi".into(),
473                ..Outcome::default()
474            }),
475        })
476        .expect("serializes");
477        let read: PollResponse = serde_json::from_str(&exited).expect("deserializes");
478        let outcome = read.result.expect("the outcome is flattened into the body");
479        assert_eq!(outcome.exit_code, Some(0));
480        assert_eq!(outcome.stdout, "hi");
481    }
482
483    /// `error` is a `Cow`, so the daemon's borrowed slug and a client's owned string
484    /// are the same type on the wire.
485    #[test]
486    fn an_error_body_carries_a_borrowed_slug_and_reads_back_owned() {
487        let written = serde_json::to_string(&ErrorBody {
488            error: Cow::Borrowed(ERROR_UNKNOWN_EXEC),
489            detail: "e1".into(),
490        })
491        .expect("serializes");
492        assert_eq!(written, r#"{"error":"unknown_exec","detail":"e1"}"#);
493        let read: ErrorBody = serde_json::from_str(&written).expect("deserializes");
494        assert_eq!(read.error, ERROR_UNKNOWN_EXEC);
495    }
496}