Skip to main content

zero_headless/
protocol.rs

1//! Line-delimited JSON IPC protocol between the `zero` CLI and
2//! the `zero-headlessd` daemon.
3//!
4//! # Framing
5//!
6//! One JSON object per line. The newline `\n` is the record
7//! separator; no embedded newlines are permitted in the payload
8//! (serde_json's default emitter satisfies this). Line framing
9//! was chosen over length-prefixed framing so that an operator
10//! debugging a stuck daemon can run
11//!
12//! ```sh
13//! { echo '{"kind":"status"}'; sleep 0.2; } | nc -U <zero_dir>/operators/<operator-slug>/sock
14//! ```
15//!
16//! and see the reply without needing a framing parser. The M2
17//! spec treats this as a hard operability requirement, not a
18//! nice-to-have.
19//!
20//! # Extensibility
21//!
22//! Each envelope is `#[serde(tag = "kind", rename_all = …)]`
23//! so adding a new variant is additive: old daemons will
24//! reject unknown kinds with a structured `Response::Error`
25//! rather than silently accepting them. The protocol version
26//! is bumped [`PROTOCOL_VERSION`] whenever the wire format
27//! changes in a non-additive way — matching versions is the
28//! dialer's responsibility.
29
30use chrono::{DateTime, Utc};
31use serde::{Deserialize, Serialize};
32
33/// Protocol version. Bump on non-additive changes (removing
34/// variants, changing field types). Additive changes (new
35/// variants, new optional fields) do not require a bump, but
36/// the daemon must tolerate unknown additive fields from
37/// newer clients without erroring.
38pub const PROTOCOL_VERSION: u32 = 1;
39
40/// Request frame sent by the CLI.
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
42#[serde(tag = "kind", rename_all = "snake_case")]
43pub enum Request {
44    /// Health + state probe. Always safe — the daemon must
45    /// answer even while draining.
46    Status,
47    /// Arm the operator-intent flag (the daemon stays up; the
48    /// flag persists across restarts so a crash-and-respawn
49    /// recovers the operator's posture).
50    Start,
51    /// Disarm the operator-intent flag. Does *not* shut the
52    /// daemon process down; use [`Request::Kill`] for that.
53    /// Keeping start/stop and kill distinct lets an operator
54    /// say "disarm but stay reachable" without burning the
55    /// launchd/systemd supervisor's restart budget.
56    Stop,
57    /// Immediate kill-switch: graceful drain then exit. This
58    /// is the path `/kill` + SIGTERM funnel through. Never
59    /// gated, never silently dropped.
60    Kill,
61}
62
63/// Response frame returned by the daemon. `Status` is the only
64/// variant that carries a non-trivial payload; the others are
65/// ack/error shapes so a misbehaving daemon cannot pretend to
66/// have acted when it has not.
67#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
68#[serde(tag = "kind", rename_all = "snake_case")]
69pub enum Response {
70    /// Three-questions answer from [`StatusReply`].
71    Status(StatusReply),
72    /// Request accepted; daemon will (or has) acted. Carries
73    /// the post-action state so the CLI can render it without
74    /// a follow-up round-trip.
75    Accepted {
76        state: SupervisorState,
77        protocol_version: u32,
78    },
79    /// Request understood but refused. Carries a single-line
80    /// operator-readable reason — never the empty string.
81    Refused { reason: String },
82    /// Request malformed or unsupported. Dialer should surface
83    /// this verbatim; this is the "I don't know that verb"
84    /// path, not the "I tried and failed" path.
85    Error { reason: String },
86}
87
88/// Status payload — the spec's three honest questions.
89///
90/// 1. `state` — is the operator-intent flag on?
91/// 2. `engine` — can the daemon see the engine right now?
92/// 3. `latest_action` — what was my most recent decision?
93///
94/// All three fields are mandatory on the wire. A `None` on
95/// `latest_action` means "I haven't acted yet since boot",
96/// which is a truthful answer; it is *not* the same as "I'm
97/// suppressing this field". Structural honesty beats
98/// convenience here.
99#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
100pub struct StatusReply {
101    pub state: SupervisorState,
102    pub engine: EngineHealth,
103    pub latest_action: Option<ActionRecord>,
104    pub protocol_version: u32,
105}
106
107/// Operator-intent flag — what the operator *asked* the daemon
108/// to do, not whether the daemon's socket is currently
109/// listening (if you're receiving a reply, it is).
110#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
111#[serde(rename_all = "snake_case")]
112pub enum SupervisorState {
113    On,
114    Off,
115}
116
117/// Engine reachability from the daemon's perspective.
118#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
119#[serde(tag = "kind", rename_all = "snake_case")]
120pub enum EngineHealth {
121    /// Daemon has never probed — state file said "off" since
122    /// boot and no Start request has arrived. The honest
123    /// answer under those conditions is "unknown".
124    Unknown,
125    /// Most recent probe succeeded at `at`.
126    Reachable { at: DateTime<Utc> },
127    /// Most recent probe failed at `at` with `reason`.
128    Unreachable { at: DateTime<Utc>, reason: String },
129}
130
131/// One durable record of a daemon decision. `kind` is a
132/// coarse-grained enum so `/headless status` can paint a terse
133/// "last 3 decisions" line without loading the full log.
134#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
135pub struct ActionRecord {
136    pub kind: ActionKind,
137    pub at: DateTime<Utc>,
138    /// One-line operator-readable summary. Must be non-empty.
139    pub note: String,
140}
141
142#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
143#[serde(rename_all = "snake_case")]
144pub enum ActionKind {
145    /// Arming succeeded.
146    Started,
147    /// Disarming succeeded.
148    Stopped,
149    /// Kill switch fired — daemon is draining.
150    Killed,
151    /// Probe result observed (reachable or unreachable).
152    Probed,
153    /// Refusal recorded (e.g. missing config).
154    Refused,
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn request_round_trips_through_json() {
163        for req in [
164            Request::Status,
165            Request::Start,
166            Request::Stop,
167            Request::Kill,
168        ] {
169            let line = serde_json::to_string(&req).unwrap();
170            assert!(!line.contains('\n'), "line framing broken: {line}");
171            let back: Request = serde_json::from_str(&line).unwrap();
172            assert_eq!(req, back);
173        }
174    }
175
176    #[test]
177    fn status_reply_answers_three_questions() {
178        let reply = StatusReply {
179            state: SupervisorState::On,
180            engine: EngineHealth::Unknown,
181            latest_action: None,
182            protocol_version: PROTOCOL_VERSION,
183        };
184        let line = serde_json::to_string(&reply).unwrap();
185        // All three fields are on the wire — even the `None`
186        // latest_action is explicitly `null`, not dropped.
187        assert!(line.contains("\"state\""));
188        assert!(line.contains("\"engine\""));
189        assert!(line.contains("\"latest_action\""));
190    }
191
192    #[test]
193    fn unknown_kind_fails_to_deserialize() {
194        // Old daemon, new verb → explicit error, not silent accept.
195        let bogus = "{\"kind\":\"detonate\"}";
196        let parsed: Result<Request, _> = serde_json::from_str(bogus);
197        assert!(parsed.is_err());
198    }
199
200    #[test]
201    fn protocol_version_is_one() {
202        assert_eq!(PROTOCOL_VERSION, 1);
203    }
204}