Skip to main content

micromux_control/
protocol.rs

1//! The control wire protocol: newline-delimited JSON request/response envelopes.
2//!
3//! Domain payloads (`ServiceSnapshot`, `HealthAttempt`, `LogLine`, `SessionChange`,
4//! `ServiceCommandAck`, `DynamicServiceAck`, `ReconcileReceipt`, `ResolvedEnvironment`,
5//! `ServiceEvent`, and `DynamicServiceParams`) are the stable core types reused directly — no DTO
6//! mirror.
7//! The session and the proxy accept peers that speak the same major protocol version, so
8//! additive payload changes do not orphan already-running sessions.
9
10use base64::Engine as _;
11use micromux::{
12    DynamicServiceAck, DynamicServiceParams, HealthAttempt, Lease, LogLine, LogRunSummary,
13    ReconcileReceipt, ResolvedEnvironment, ServiceCommandAck, ServiceEvent, ServiceID,
14    ServiceSnapshot, SessionChange,
15};
16use schemars::JsonSchema;
17use serde::{Deserialize, Serialize};
18
19/// The current control protocol version.
20///
21/// Bump the minor for additive changes (new optional/defaulted fields, new tools that reuse
22/// existing requests), and bump the major for incompatible request/response semantics.
23pub const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 20);
24
25/// The first protocol revision whose sessions answer [`Request::GetEvents`].
26pub const EVENTS_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 3);
27
28/// The first protocol revision whose sessions answer [`Request::GetEnvironment`].
29pub const ENVIRONMENT_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 15);
30
31/// The first protocol revision whose sessions answer [`Request::GetSessionEnvironment`] and
32/// [`Request::WriteEnvironmentFile`], and load a session-wide `env_file`.
33///
34/// An older session has no session-wide `env_file`, so its variables alone, which
35/// [`Request::GetEnvironment`] returns without a service, are its whole environment.
36pub const SESSION_ENV_FILE_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 20);
37
38/// The first protocol revision whose sessions answer [`Request::SendInput`] and
39/// [`Request::ResizeTerminal`].
40pub const TERMINAL_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 18);
41
42/// The largest paste one [`Request::SendInput`] carries.
43///
44/// Its base64 encoding, about a third larger, must fit one [`crate::MAX_FRAME_BYTES`] frame with
45/// room for the envelope, so it stays below the in-process TUI's [`micromux::MAX_PTY_PASTE_BYTES`].
46pub const MAX_REMOTE_PASTE_BYTES: usize = 512 * 1024;
47
48const _: () = assert!(
49    MAX_REMOTE_PASTE_BYTES.div_ceil(3) * 4 + 64 * 1024 <= crate::MAX_FRAME_BYTES,
50    "a maximal remote paste must fit one control frame"
51);
52
53pub(crate) const fn supports_versioned_subscriptions(version: ProtocolVersion) -> bool {
54    version.major() == PROTOCOL_VERSION.major() && version.minor() >= 7
55}
56
57/// A typed control protocol version.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
59pub struct ProtocolVersion {
60    major: u16,
61    minor: u16,
62}
63
64impl ProtocolVersion {
65    /// Build a protocol version from major/minor components.
66    #[must_use]
67    pub const fn new(major: u16, minor: u16) -> Self {
68        Self { major, minor }
69    }
70
71    /// Major compatibility line.
72    #[must_use]
73    pub const fn major(self) -> u16 {
74        self.major
75    }
76
77    /// Additive revision within one major line.
78    #[must_use]
79    pub const fn minor(self) -> u16 {
80        self.minor
81    }
82
83    /// Return whether two peers can speak the same protocol.
84    #[must_use]
85    pub const fn is_compatible_with(self, peer: Self) -> bool {
86        self.major == peer.major
87    }
88
89    /// Return whether a peer speaking this version understands everything `revision` added.
90    ///
91    /// That holds on the same major line at `revision`'s minor or a later one.
92    #[must_use]
93    pub const fn supports(self, revision: Self) -> bool {
94        self.major == revision.major && self.minor >= revision.minor
95    }
96}
97
98impl std::fmt::Display for ProtocolVersion {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        write!(f, "{}.{}", self.major(), self.minor())
101    }
102}
103
104/// A request from a client (the `micromux ctl` CLI or the MCP proxy) to a session's control server.
105#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
106pub enum Request {
107    /// Return session identity and metadata.
108    Describe,
109    /// List every service with its current snapshot.
110    ///
111    /// This response is not paged. A roster that exceeds the protocol frame budget returns
112    /// [`ErrorCode::LimitExceeded`].
113    ListServices,
114    /// Return one service by stable id or human-readable name.
115    ///
116    /// Exact ids take precedence; duplicate display names resolve to the first service.
117    GetService {
118        /// Service id or display name.
119        service: ServiceID,
120    },
121    /// Return recent log records for a service.
122    GetLogs {
123        /// Target service.
124        service: ServiceID,
125        /// Specific disk-retained run generation to read. Omit to read the bounded visible log
126        /// stream.
127        run_generation: Option<u64>,
128        /// Bound the result to the most recent records.
129        tail: Option<usize>,
130    },
131    /// Return log records strictly after a monotonic cursor, for gap-free incremental following.
132    FollowLogs {
133        /// Target service.
134        service: ServiceID,
135        /// Specific disk-retained run generation to follow. Omit to follow the bounded visible log
136        /// stream.
137        run_generation: Option<u64>,
138        /// Return only records with `seq` greater than this cursor (all retained records if
139        /// `None`).
140        after: Option<u64>,
141    },
142    /// Return summaries of retained log runs for a service.
143    ///
144    /// This response is not paged. A run index that exceeds the protocol frame budget returns
145    /// [`ErrorCode::LimitExceeded`].
146    ListLogRuns {
147        /// Target service.
148        service: ServiceID,
149    },
150    /// Return the latest healthcheck attempt for a service's current live run.
151    GetHealth {
152        /// Target service.
153        service: ServiceID,
154    },
155    /// Return retained healthcheck attempts for a service's current or latest run.
156    GetHealthHistory {
157        /// Target service.
158        service: ServiceID,
159    },
160    /// Return retained scheduler lifecycle events for a service.
161    ///
162    /// Sessions answer it from protocol [`EVENTS_PROTOCOL_VERSION`] on.
163    GetEvents {
164        /// Target service.
165        service: ServiceID,
166        /// Return events with a sequence strictly greater than this cursor.
167        after: Option<u64>,
168        /// Bound the result; when `after` is absent this selects the newest events.
169        tail: Option<usize>,
170    },
171    /// Restart a single service.
172    Restart {
173        /// Target service.
174        service: ServiceID,
175    },
176    /// Restart all enabled services.
177    RestartAll,
178    /// Enable (and start) a single service.
179    Enable {
180        /// Target service.
181        service: ServiceID,
182    },
183    /// Disable a single service.
184    Disable {
185        /// Target service.
186        service: ServiceID,
187    },
188    /// Create and start a dynamic service.
189    StartDynamicService {
190        /// Definition, clone source, and lease request.
191        params: DynamicServiceParams,
192    },
193    /// Replace or revive a dynamic service.
194    ReplaceDynamicService {
195        /// Existing dynamic service id.
196        service: ServiceID,
197        /// Required current revision.
198        expected_revision: u64,
199        /// Replacement definition, clone source, and lease request.
200        params: DynamicServiceParams,
201    },
202    /// Renew a live dynamic service's lease without restarting it.
203    RenewDynamicService {
204        /// Existing dynamic service id.
205        service: ServiceID,
206        /// Required current revision.
207        expected_revision: u64,
208        /// Requested replacement lease; omission uses the session policy default.
209        expires_after: Option<Lease>,
210    },
211    /// Retire a dynamic service.
212    StopDynamicService {
213        /// Dynamic service id.
214        service: ServiceID,
215    },
216    /// Return the session's variables, or one service's resolved environment, with their values.
217    ///
218    /// Sessions answer it from protocol [`ENVIRONMENT_PROTOCOL_VERSION`] on; older ones reject it
219    /// as a bad request.
220    /// Without a service it never includes the session-wide `env_file`, whose values may be
221    /// secrets, because clients predating [`Request::GetSessionEnvironment`] show these values
222    /// unasked.
223    /// See [`micromux::ServiceControl::environment`] for what the variables are.
224    GetEnvironment {
225        /// Service id, matched exactly, or `None` for the session's variables.
226        service: Option<ServiceID>,
227    },
228    /// Return the session's own environment, with its values: the session-wide `env_file`, read
229    /// from disk for this request, and the session's variables over it.
230    ///
231    /// Sessions answer it from protocol [`SESSION_ENV_FILE_PROTOCOL_VERSION`] on; older ones
232    /// reject it as a bad request.
233    GetSessionEnvironment,
234    /// Write the environment [`Request::GetEnvironment`] returns for a service, or
235    /// [`Request::GetSessionEnvironment`] without one, to a dotenv file the session owns, and
236    /// return its path.
237    ///
238    /// Sessions answer it from protocol [`SESSION_ENV_FILE_PROTOCOL_VERSION`] on.
239    /// An environment the file cannot carry literally fails the request, see
240    /// [`micromux::to_dotenv`], and leaves an earlier file as it was.
241    /// Each request rewrites the file at the same path, in a private directory next to the
242    /// session's control socket, and the session removes the directory when it stops.
243    /// The format is [`micromux::to_dotenv`]'s.
244    WriteEnvironmentFile {
245        /// Service id, matched exactly, or `None` for the session's own environment.
246        service: Option<ServiceID>,
247    },
248    /// Reconcile configured services against the session's on-disk config.
249    ///
250    /// The config file is the authority, so this operation has no dynamic-service capability gate.
251    ReconcileConfig {
252        /// Compute the semantic diff without mutating the session. Deliberately a required
253        /// field: omission must never silently mean "apply".
254        dry_run: bool,
255    },
256    /// Write bytes to a service's PTY, as typed into an attached TUI.
257    ///
258    /// Sessions answer it from protocol [`TERMINAL_PROTOCOL_VERSION`] on; older ones reject it as a
259    /// bad request.
260    /// Input from every client, the session's own TUI included, is written in the order the
261    /// session receives it, and one request's bytes are written contiguously.
262    /// The MCP server never sends it: agents get no tool that types into a service.
263    SendInput {
264        /// Target service id, matched exactly.
265        service: ServiceID,
266        /// The bytes to write, at most [`micromux::MAX_PTY_INPUT_BATCH_BYTES`] unless `paste` is
267        /// set.
268        data: InputBytes,
269        /// Whether the bytes are one paste, which may be up to [`MAX_REMOTE_PASTE_BYTES`].
270        #[serde(default)]
271        paste: bool,
272    },
273    /// Resize every service PTY in the session.
274    ///
275    /// Sessions answer it from protocol [`TERMINAL_PROTOCOL_VERSION`] on.
276    /// The last resize the session receives wins, whichever client sent it, the session's own TUI
277    /// included, and runs started later take that size too.
278    ResizeTerminal {
279        /// Columns, at least one.
280        cols: u16,
281        /// Rows, at least one.
282        rows: u16,
283    },
284    /// Stop the whole session: stop every service and exit the session process (graceful, like the
285    /// operator pressing Ctrl-C), freeing its ports. Acknowledged with [`Response::ShuttingDown`]
286    /// just before the endpoint goes away.
287    Shutdown,
288    /// Stream [`SessionChange`] notifications until the client disconnects.
289    Subscribe,
290    /// Stream change notifications and negotiate additive subscription behavior.
291    SubscribeWithVersion {
292        /// Protocol version spoken by the subscribing client.
293        protocol_version: ProtocolVersion,
294    },
295}
296
297impl Request {
298    /// Whether a client may repeat the request after losing the connection before its response.
299    ///
300    /// Mutations are deliberately excluded even when they are usually idempotent: a lost
301    /// acknowledgement does not prove whether the scheduler accepted the first request.
302    #[must_use]
303    pub const fn is_retry_safe(&self) -> bool {
304        matches!(
305            self,
306            Self::Describe
307                | Self::ListServices
308                | Self::GetService { .. }
309                | Self::GetLogs { .. }
310                | Self::FollowLogs { .. }
311                | Self::ListLogRuns { .. }
312                | Self::GetHealth { .. }
313                | Self::GetHealthHistory { .. }
314                | Self::GetEvents { .. }
315                | Self::GetEnvironment { .. }
316                | Self::GetSessionEnvironment
317                | Self::WriteEnvironmentFile { .. }
318                | Self::ReconcileConfig { dry_run: true }
319        )
320    }
321}
322
323/// Raw PTY input carried by [`Request::SendInput`].
324///
325/// It travels as standard padded base64, so arbitrary bytes, control characters included, take a
326/// predictable share of a frame.
327/// Its `Debug` output names only the length, because the bytes may be a typed password.
328#[derive(Clone, PartialEq, Eq)]
329pub struct InputBytes(Vec<u8>);
330
331impl InputBytes {
332    /// The raw bytes.
333    #[must_use]
334    pub fn as_bytes(&self) -> &[u8] {
335        &self.0
336    }
337
338    /// Consumes the wrapper, returning the raw bytes.
339    #[must_use]
340    pub fn into_inner(self) -> Vec<u8> {
341        self.0
342    }
343}
344
345impl From<Vec<u8>> for InputBytes {
346    fn from(bytes: Vec<u8>) -> Self {
347        Self(bytes)
348    }
349}
350
351impl std::fmt::Debug for InputBytes {
352    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
353        write!(f, "InputBytes({} bytes)", self.0.len())
354    }
355}
356
357impl Serialize for InputBytes {
358    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
359        serializer.serialize_str(&base64::engine::general_purpose::STANDARD.encode(&self.0))
360    }
361}
362
363impl<'de> Deserialize<'de> for InputBytes {
364    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
365        let encoded = String::deserialize(deserializer)?;
366        base64::engine::general_purpose::STANDARD
367            .decode(encoded)
368            .map(Self)
369            .map_err(serde::de::Error::custom)
370    }
371}
372
373impl JsonSchema for InputBytes {
374    fn schema_name() -> std::borrow::Cow<'static, str> {
375        "InputBytes".into()
376    }
377
378    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
379        schemars::json_schema!({
380            "type": "string",
381            "contentEncoding": "base64",
382        })
383    }
384}
385
386/// A brief, identity-only view of a service for [`SessionInfo`].
387#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
388pub struct ServiceBrief {
389    /// Stable service identifier.
390    pub id: ServiceID,
391    /// Human-readable service name.
392    #[serde(default)]
393    pub name: String,
394}
395
396/// Live session identity returned by [`Request::Describe`]. Never stored on disk.
397#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
398pub struct SessionInfo {
399    /// The protocol version this session speaks.
400    pub protocol_version: ProtocolVersion,
401    /// Deterministic session id: the endpoint hash of the canonical config path.
402    pub id: String,
403    /// Process id of the session.
404    pub pid: u32,
405    /// Monotonic session start token as Unix nanoseconds. With `pid`, forms a start token.
406    pub start_time: u64,
407    /// Session name (config `name:` if set, else `basename(working_dir)`).
408    #[serde(default)]
409    pub name: String,
410    /// The directory the session was launched in.
411    #[serde(default)]
412    pub working_dir: String,
413    /// The canonical config path that keys this session's endpoint.
414    #[serde(default)]
415    pub config_path: String,
416    /// The services this session supervises.
417    #[serde(default)]
418    pub services: Vec<ServiceBrief>,
419    /// Whether the service index was shortened to fit the control frame.
420    ///
421    /// Use [`Request::GetService`] for targeted lookup when this is true.
422    #[serde(default)]
423    pub services_truncated: bool,
424    /// The micromux version of the session binary.
425    #[serde(default)]
426    pub micromux_version: String,
427    /// The session's name, browser URLs, allocated ports, and routing status (protocol 3.11+).
428    #[serde(default, skip_serializing_if = "Option::is_none")]
429    pub session: Option<Box<micromux::SessionSummary>>,
430    /// Optional capabilities advertised by newer sessions.
431    #[serde(default, skip_serializing_if = "Option::is_none")]
432    pub capabilities: Option<SessionCapabilities>,
433}
434
435/// Optional session features and their current limits.
436#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
437pub struct SessionCapabilities {
438    /// Dynamic-service limits, or `None` when runtime creation is not permitted.
439    #[serde(default, skip_serializing_if = "Option::is_none")]
440    pub dynamic_services: Option<DynamicServicesCaps>,
441    /// Capacity and health of the bounded disk-log read pool.
442    #[serde(default, skip_serializing_if = "Option::is_none")]
443    pub disk_log_reads: Option<DiskLogReadHealth>,
444}
445
446/// Current capacity, occupancy, and timeout history of the disk-log read pool.
447#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
448pub struct DiskLogReadHealth {
449    /// Whether the pool has started its workers.
450    #[serde(default = "default_initialized_disk_log_pool")]
451    pub initialized: bool,
452    /// Whether the pool can initialize or has an unoccupied worker.
453    pub available: bool,
454    /// Worker slots configured for the pool.
455    pub workers: usize,
456    /// Worker threads currently executing a filesystem read.
457    pub active: usize,
458    /// Maximum reads that may wait for a worker.
459    pub queue_capacity: usize,
460    /// Reads currently waiting for a worker.
461    pub queued: usize,
462    /// Reads whose callers timed out or disconnected while the filesystem call remained blocked.
463    #[serde(default)]
464    pub abandoned: usize,
465    /// Requests that have exceeded the read deadline since this session started.
466    #[serde(default)]
467    pub timed_out_requests: usize,
468}
469
470impl Default for DiskLogReadHealth {
471    fn default() -> Self {
472        Self {
473            initialized: default_initialized_disk_log_pool(),
474            available: false,
475            workers: 0,
476            active: 0,
477            queue_capacity: 0,
478            queued: 0,
479            abandoned: 0,
480            timed_out_requests: 0,
481        }
482    }
483}
484
485const fn default_initialized_disk_log_pool() -> bool {
486    // Protocol 3.8 created the pool while building `Describe`, before this field existed.
487    true
488}
489
490/// Dynamic-service limits and current usage advertised by a session.
491#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
492pub struct DynamicServicesCaps {
493    /// Maximum non-retired dynamic services.
494    pub max_services: usize,
495    /// Current non-retired dynamic-service count.
496    pub live_services: usize,
497    /// Maximum and default lease duration in seconds, or `None` for session-lifetime leases.
498    #[serde(default, skip_serializing_if = "Option::is_none")]
499    pub max_lifetime_secs: Option<u64>,
500    /// Canonical working-directory roots accepted by the session.
501    pub allowed_working_roots: Vec<String>,
502}
503
504impl SessionInfo {
505    /// Return whether another `Describe` response names the same running session instance.
506    #[must_use]
507    pub fn is_same_instance(&self, other: &Self) -> bool {
508        self.id == other.id && self.pid == other.pid && self.start_time == other.start_time
509    }
510}
511
512/// A typed error code shared by the protocol and the proxy diagnostics.
513#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
514pub enum ErrorCode {
515    /// No service with the given id exists.
516    UnknownService,
517    /// The requested service run is no longer retained or never existed.
518    UnknownRun,
519    /// No session answered the request.
520    NoSession,
521    /// More than one live session matched the selector.
522    Ambiguous,
523    /// A live session is busy (connect/reply timeout); never a reason to delete it.
524    Busy,
525    /// A request timed out.
526    Timeout,
527    /// The command is invalid in the service's current state.
528    InvalidState,
529    /// The latest config could not be reloaded before a restart/enable command.
530    ConfigReload,
531    /// The target session's policy denied the operation.
532    PolicyDenied,
533    /// A target-session resource limit was reached.
534    LimitExceeded,
535    /// An optimistic-concurrency revision was stale.
536    RevisionMismatch,
537    /// A dynamic service definition was invalid.
538    InvalidSpec,
539    /// The scheduler stopped before acknowledging a command.
540    SchedulerStopped,
541    /// The control plane is not supported on this platform.
542    UnsupportedPlatform,
543    /// The peer speaks an incompatible protocol version.
544    ProtocolVersionMismatch,
545    /// The request could not be parsed.
546    BadRequest,
547    /// An unexpected internal error.
548    Internal,
549    /// A newer peer returned an error code this binary does not know yet.
550    #[serde(other)]
551    Unknown,
552}
553
554/// A response from a session's control server.
555#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
556pub enum Response {
557    /// Reply to [`Request::Describe`].
558    Description(SessionInfo),
559    /// Reply to [`Request::ListServices`].
560    Services(Vec<ServiceSnapshot>),
561    /// Reply to [`Request::GetService`].
562    Service(Box<ServiceSnapshot>),
563    /// Reply to [`Request::GetLogs`].
564    Logs {
565        /// The recent log records.
566        lines: Vec<LogLine>,
567        /// Whether the session had to drop older records to respect server response limits.
568        #[serde(default)]
569        truncated: bool,
570        /// First sequence still retained by the visible in-memory stream.
571        ///
572        /// Present only for visible-stream responses. A cursor whose next expected sequence is
573        /// below this value has crossed a retention gap and should resume here.
574        #[serde(default, skip_serializing_if = "Option::is_none")]
575        first_retained_seq: Option<u64>,
576    },
577    /// Reply to [`Request::ListLogRuns`].
578    LogRuns {
579        /// Retained runs, oldest first.
580        runs: Vec<LogRunSummary>,
581    },
582    /// Reply to [`Request::GetHealth`].
583    Health(Option<HealthAttempt>),
584    /// Reply to [`Request::GetHealthHistory`].
585    HealthHistory {
586        /// Retained attempts in oldest-first order.
587        attempts: Vec<HealthAttempt>,
588    },
589    /// Reply to [`Request::GetEvents`].
590    Events {
591        /// Retained lifecycle events in ascending sequence order.
592        events: Vec<ServiceEvent>,
593        /// Whether matching events were omitted by the response bound.
594        truncated: bool,
595    },
596    /// A mutation was *accepted* (validated + queued), not necessarily completed. Carries each
597    /// affected service's latched generation.
598    Accepted {
599        /// Per-service acknowledgements.
600        services: Vec<ServiceCommandAck>,
601    },
602    /// Reply to a dynamic-service mutation.
603    DynamicService(DynamicServiceAck),
604    /// Reply to a config reconciliation.
605    Reconcile(ReconcileReceipt),
606    /// Reply to [`Request::GetEnvironment`] and [`Request::GetSessionEnvironment`].
607    Environment(ResolvedEnvironment),
608    /// Reply to [`Request::WriteEnvironmentFile`].
609    EnvironmentFile {
610        /// Absolute path of the written file.
611        path: String,
612        /// As [`ResolvedEnvironment::stale`].
613        stale: bool,
614    },
615    /// A streamed change notification (only after [`Request::Subscribe`]).
616    Change(SessionChange),
617    /// Reply to [`Request::SendInput`] and [`Request::ResizeTerminal`]: the session queued the input
618    /// or resize for its PTYs.
619    ///
620    /// A service that is not running refuses input with [`ErrorCode::InvalidState`] instead.
621    /// Input that races with the process exiting is still dropped later, and recorded as an
622    /// `InputDropped` service event.
623    TerminalQueued,
624    /// Acknowledgement of [`Request::Shutdown`], written just before the session begins exiting.
625    ShuttingDown,
626    /// A typed error.
627    Error {
628        /// The error code.
629        code: ErrorCode,
630        /// A human-readable message.
631        message: String,
632    },
633}
634
635impl Response {
636    /// Build an [`Response::Error`] from a code and message.
637    #[must_use]
638    pub fn error(code: ErrorCode, message: impl Into<String>) -> Self {
639        Self::Error {
640            code,
641            message: message.into(),
642        }
643    }
644}
645
646#[cfg(test)]
647mod tests {
648    use std::assert_matches;
649
650    use super::*;
651    use serde_json::json;
652    use similar_asserts::assert_eq;
653
654    fn session(id: &str, pid: u32, start_time: u64, name: &str) -> SessionInfo {
655        SessionInfo {
656            session: None,
657            protocol_version: PROTOCOL_VERSION,
658            id: id.to_string(),
659            pid,
660            start_time,
661            name: name.to_string(),
662            working_dir: ".".to_string(),
663            config_path: "/project/micromux.yaml".to_string(),
664            services: Vec::new(),
665            services_truncated: false,
666            micromux_version: env!("CARGO_PKG_VERSION").to_string(),
667            capabilities: None,
668        }
669    }
670
671    #[test]
672    fn session_instance_identity_uses_stable_start_token() {
673        let first = session("aaa", 42, 100, "app");
674        let alias = session("aaa", 42, 100, "renamed");
675        let replacement = session("aaa", 42, 101, "app");
676
677        assert!(first.is_same_instance(&alias));
678        assert!(!first.is_same_instance(&replacement));
679    }
680
681    #[test]
682    fn protocol_version_uses_major_minor_shape_and_accepts_same_major() {
683        assert_eq!(
684            serde_json::to_value(PROTOCOL_VERSION).unwrap(),
685            json!({ "major": 3, "minor": 20 })
686        );
687        assert_eq!(
688            serde_json::from_value::<ProtocolVersion>(json!({ "major": 1, "minor": 0 })).unwrap(),
689            ProtocolVersion::new(1, 0)
690        );
691
692        assert!(PROTOCOL_VERSION.is_compatible_with(ProtocolVersion::new(3, 19)));
693        assert!(!PROTOCOL_VERSION.is_compatible_with(ProtocolVersion::new(2, 9)));
694        assert!(!supports_versioned_subscriptions(ProtocolVersion::new(
695            3, 6
696        )));
697        assert!(supports_versioned_subscriptions(ProtocolVersion::new(3, 7)));
698    }
699
700    /// A session answers `GetEvents` only from 3.3 on, and never across a major line.
701    #[test]
702    fn events_require_protocol_3_3_on_the_same_major_line() {
703        assert!(ProtocolVersion::new(3, 3).supports(EVENTS_PROTOCOL_VERSION));
704        assert!(!ProtocolVersion::new(3, 2).supports(EVENTS_PROTOCOL_VERSION));
705        assert!(!ProtocolVersion::new(4, 3).supports(EVENTS_PROTOCOL_VERSION));
706        assert!(PROTOCOL_VERSION.supports(EVENTS_PROTOCOL_VERSION));
707    }
708
709    /// A session answers `GetEnvironment` only from 3.15 on, and never across a major line.
710    #[test]
711    fn environment_requires_protocol_3_15_on_the_same_major_line() {
712        assert!(ProtocolVersion::new(3, 15).supports(ENVIRONMENT_PROTOCOL_VERSION));
713        assert!(ProtocolVersion::new(3, 16).supports(ENVIRONMENT_PROTOCOL_VERSION));
714        assert!(!ProtocolVersion::new(3, 14).supports(ENVIRONMENT_PROTOCOL_VERSION));
715        assert!(!ProtocolVersion::new(4, 15).supports(ENVIRONMENT_PROTOCOL_VERSION));
716        assert!(PROTOCOL_VERSION.supports(ENVIRONMENT_PROTOCOL_VERSION));
717    }
718
719    /// A session answers the requests for its own environment and its env files only from 3.20
720    /// on, and never across a major line.
721    #[test]
722    fn session_env_files_require_protocol_3_20_on_the_same_major_line() {
723        assert!(ProtocolVersion::new(3, 20).supports(SESSION_ENV_FILE_PROTOCOL_VERSION));
724        assert!(!ProtocolVersion::new(3, 19).supports(SESSION_ENV_FILE_PROTOCOL_VERSION));
725        assert!(!ProtocolVersion::new(4, 20).supports(SESSION_ENV_FILE_PROTOCOL_VERSION));
726        assert!(PROTOCOL_VERSION.supports(SESSION_ENV_FILE_PROTOCOL_VERSION));
727    }
728
729    #[test]
730    fn environment_file_request_and_response_round_trip() -> serde_json::Result<()> {
731        for service in [None, Some("api".to_string())] {
732            let encoded = serde_json::to_value(Request::WriteEnvironmentFile {
733                service: service.clone(),
734            })?;
735            assert_matches!(
736                serde_json::from_value::<Request>(encoded)?,
737                Request::WriteEnvironmentFile { service: decoded } if decoded == service
738            );
739        }
740        assert!(Request::WriteEnvironmentFile { service: None }.is_retry_safe());
741        let encoded = serde_json::to_value(Request::GetSessionEnvironment)?;
742        assert_eq!(encoded, json!("GetSessionEnvironment"));
743        assert_matches!(
744            serde_json::from_value::<Request>(encoded)?,
745            Request::GetSessionEnvironment
746        );
747        assert!(Request::GetSessionEnvironment.is_retry_safe());
748
749        let encoded = serde_json::to_value(Response::EnvironmentFile {
750            path: "/run/micromux/0123456789abcdef.env.d/session.env".to_string(),
751            stale: false,
752        })?;
753        assert_eq!(
754            encoded,
755            json!({
756                "EnvironmentFile": {
757                    "path": "/run/micromux/0123456789abcdef.env.d/session.env",
758                    "stale": false
759                }
760            })
761        );
762        assert_matches!(
763            serde_json::from_value::<Response>(encoded)?,
764            Response::EnvironmentFile { path, stale: false } if path.ends_with("session.env")
765        );
766        Ok(())
767    }
768
769    /// A session answers terminal requests only from 3.18 on, and never across a major line.
770    #[test]
771    fn terminal_requests_require_protocol_3_18_on_the_same_major_line() {
772        assert!(ProtocolVersion::new(3, 18).supports(TERMINAL_PROTOCOL_VERSION));
773        assert!(!ProtocolVersion::new(3, 17).supports(TERMINAL_PROTOCOL_VERSION));
774        assert!(!ProtocolVersion::new(4, 18).supports(TERMINAL_PROTOCOL_VERSION));
775        assert!(PROTOCOL_VERSION.supports(TERMINAL_PROTOCOL_VERSION));
776    }
777
778    /// Input travels as base64, so control and non-UTF-8 bytes survive the JSON frame unchanged.
779    #[test]
780    fn send_input_round_trips_arbitrary_bytes_as_base64() -> serde_json::Result<()> {
781        let bytes = vec![0x1b, b'[', b'A', 0x00, 0xff, b'\r'];
782        let request = Request::SendInput {
783            service: "shell".to_string(),
784            data: InputBytes::from(bytes.clone()),
785            paste: true,
786        };
787
788        let encoded = serde_json::to_value(&request)?;
789        assert_eq!(
790            encoded,
791            json!({ "SendInput": { "service": "shell", "data": "G1tBAP8N", "paste": true } })
792        );
793        assert_matches!(
794            serde_json::from_value::<Request>(encoded)?,
795            Request::SendInput { service, data, paste: true }
796                if service == "shell" && data.as_bytes() == bytes.as_slice()
797        );
798
799        // `paste` is additive and defaults to key input.
800        assert_matches!(
801            serde_json::from_value::<Request>(
802                json!({ "SendInput": { "service": "shell", "data": "" } })
803            )?,
804            Request::SendInput { data, paste: false, .. } if data.as_bytes().is_empty()
805        );
806        assert!(
807            serde_json::from_value::<Request>(
808                json!({ "SendInput": { "service": "shell", "data": "not base64!" } })
809            )
810            .is_err()
811        );
812        Ok(())
813    }
814
815    /// Debug output reaches logs and "unexpected response" messages, so it must never carry
816    /// typed bytes, which may be a password.
817    #[test]
818    fn send_input_debug_output_names_only_the_length() {
819        let request = Request::SendInput {
820            service: "shell".to_string(),
821            data: InputBytes::from(b"hunter2".to_vec()),
822            paste: false,
823        };
824
825        let debug = format!("{request:?}");
826
827        assert!(debug.contains("7 bytes"), "{debug}");
828        assert!(!debug.contains("hunter2"), "{debug}");
829        assert!(!debug.contains("104"), "{debug}");
830    }
831
832    #[test]
833    fn resize_and_terminal_acknowledgement_round_trip() -> serde_json::Result<()> {
834        let encoded = serde_json::to_value(Request::ResizeTerminal {
835            cols: 120,
836            rows: 40,
837        })?;
838        assert_eq!(
839            encoded,
840            json!({ "ResizeTerminal": { "cols": 120, "rows": 40 } })
841        );
842        assert_matches!(
843            serde_json::from_value::<Request>(encoded)?,
844            Request::ResizeTerminal {
845                cols: 120,
846                rows: 40
847            }
848        );
849
850        let encoded = serde_json::to_value(Response::TerminalQueued)?;
851        assert_eq!(encoded, json!("TerminalQueued"));
852        assert_matches!(
853            serde_json::from_value::<Response>(encoded)?,
854            Response::TerminalQueued
855        );
856        Ok(())
857    }
858
859    #[test]
860    fn environment_request_and_response_round_trip() -> serde_json::Result<()> {
861        for service in [None, Some("api".to_string())] {
862            let encoded = serde_json::to_value(Request::GetEnvironment {
863                service: service.clone(),
864            })?;
865            assert_matches!(
866                serde_json::from_value::<Request>(encoded)?,
867                Request::GetEnvironment { service: decoded } if decoded == service
868            );
869        }
870        assert!(Request::GetEnvironment { service: None }.is_retry_safe());
871
872        let environment = ResolvedEnvironment {
873            variables: [
874                ("API_PORT".to_string(), "20001".to_string()),
875                ("DATABASE_URL".to_string(), "postgres://secret".to_string()),
876            ]
877            .into_iter()
878            .collect(),
879            stale: true,
880        };
881        let encoded = serde_json::to_value(Response::Environment(environment.clone()))?;
882        assert_eq!(
883            encoded,
884            json!({
885                "Environment": {
886                    "variables": {"API_PORT": "20001", "DATABASE_URL": "postgres://secret"},
887                    "stale": true
888                }
889            })
890        );
891        let Response::Environment(decoded) = serde_json::from_value::<Response>(encoded)? else {
892            return Err(serde_json::Error::io(std::io::Error::other(
893                "unexpected environment response variant",
894            )));
895        };
896        assert_eq!(decoded, environment);
897        Ok(())
898    }
899
900    /// Debug output reaches logs and "unexpected response" messages, so it must never carry a
901    /// value.
902    #[test]
903    fn environment_debug_output_names_variables_without_values() {
904        let response = Response::Environment(ResolvedEnvironment {
905            variables: [("DATABASE_URL".to_string(), "postgres://secret".to_string())]
906                .into_iter()
907                .collect(),
908            stale: false,
909        });
910
911        let debug = format!("{response:?}");
912
913        assert!(debug.contains("DATABASE_URL"), "{debug}");
914        assert!(!debug.contains("postgres://secret"), "{debug}");
915    }
916
917    #[test]
918    fn protocol_version_rejects_plain_integer_shape() {
919        let err = serde_json::from_value::<ProtocolVersion>(json!(5)).unwrap_err();
920
921        assert!(
922            err.to_string().contains("invalid type"),
923            "unexpected error: {err}"
924        );
925    }
926
927    #[test]
928    fn protocol_version_rejects_missing_minor() {
929        let err = serde_json::from_value::<ProtocolVersion>(json!({ "major": 5 })).unwrap_err();
930
931        assert!(
932            err.to_string().contains("missing field `minor`"),
933            "unexpected error: {err}"
934        );
935    }
936
937    #[test]
938    fn unknown_error_codes_degrade_without_deserialize_failure() {
939        let code = serde_json::from_str::<ErrorCode>("\"FutureError\"").unwrap();
940
941        assert_eq!(code, ErrorCode::Unknown);
942    }
943
944    #[test]
945    fn session_info_accepts_missing_additive_fields() {
946        let info = serde_json::from_value::<SessionInfo>(json!({
947            "protocol_version": { "major": 3, "minor": 2 },
948            "id": "abc",
949            "pid": 42,
950            "start_time": 99
951        }))
952        .unwrap();
953
954        assert_eq!(info.protocol_version, ProtocolVersion::new(3, 2));
955        assert_eq!(info.name, "");
956        assert!(info.services.is_empty());
957        assert!(!info.services_truncated);
958        assert_eq!(info.micromux_version, "");
959        assert!(info.capabilities.is_none());
960    }
961
962    #[test]
963    fn disk_log_read_health_accepts_missing_timeout_history() {
964        let health = serde_json::from_value::<DiskLogReadHealth>(json!({
965            "available": true,
966            "workers": 4,
967            "active": 1,
968            "queue_capacity": 4,
969            "queued": 2
970        }))
971        .unwrap();
972
973        assert!(health.initialized);
974        assert_eq!(health.abandoned, 0);
975        assert_eq!(health.timed_out_requests, 0);
976        assert_eq!(health.initialized, DiskLogReadHealth::default().initialized);
977    }
978
979    #[test]
980    fn dynamic_service_ack_round_trips_and_accepts_missing_additive_fields() {
981        let ack = DynamicServiceAck {
982            service: "debug".to_string(),
983            revision: 2,
984            observed_generation: 1,
985            expires_at_unix_ms: Some(1234),
986            command: vec!["true".to_string()],
987            working_dir: None,
988            ports: vec![3201],
989            env_keys: vec!["RUST_LOG".to_string()],
990            restart: micromux::RestartPolicy::Never,
991            healthcheck_configured: false,
992            already_retired: false,
993            idempotent_replay: true,
994        };
995        let encoded = serde_json::to_value(Response::DynamicService(ack.clone())).unwrap();
996        let decoded = serde_json::from_value::<Response>(encoded).unwrap();
997        let Response::DynamicService(decoded) = decoded else {
998            panic!("expected a dynamic-service response");
999        };
1000        assert_eq!(decoded.service, ack.service);
1001        assert_eq!(decoded.revision, ack.revision);
1002        assert!(decoded.idempotent_replay);
1003
1004        // The defaulted fields are additive: a minimal older payload still deserializes.
1005        let minimal = serde_json::from_value::<DynamicServiceAck>(json!({
1006            "service": "debug",
1007            "revision": 1,
1008            "observed_generation": 0,
1009            "command": ["true"],
1010            "restart": "Never",
1011            "healthcheck_configured": false
1012        }))
1013        .unwrap();
1014        assert_eq!(minimal.expires_at_unix_ms, None);
1015        assert_eq!(minimal.ports, [] as [u16; 0]);
1016        assert!(!minimal.already_retired);
1017    }
1018
1019    #[test]
1020    fn reconcile_request_and_receipt_round_trip() {
1021        let request = Request::ReconcileConfig { dry_run: true };
1022        let encoded = serde_json::to_value(&request).unwrap();
1023        assert_matches!(
1024            serde_json::from_value::<Request>(encoded).unwrap(),
1025            Request::ReconcileConfig { dry_run: true }
1026        );
1027
1028        let receipt = micromux::ReconcileReceipt {
1029            config_path: "/project/micromux.yaml".to_string(),
1030            dry_run: true,
1031            actions: vec![micromux::ReconcileAction {
1032                service: "worker".to_string(),
1033                action: micromux::ReconcileActionKind::Changed,
1034                detail: "changed service spec".to_string(),
1035            }],
1036        };
1037        let encoded = serde_json::to_value(Response::Reconcile(receipt.clone())).unwrap();
1038        let Response::Reconcile(decoded) = serde_json::from_value::<Response>(encoded).unwrap()
1039        else {
1040            panic!("expected a reconcile response");
1041        };
1042        assert_eq!(decoded, receipt);
1043    }
1044
1045    #[test]
1046    fn versioned_subscription_carries_the_client_protocol() {
1047        let request = Request::SubscribeWithVersion {
1048            protocol_version: PROTOCOL_VERSION,
1049        };
1050
1051        let encoded = serde_json::to_value(&request).unwrap();
1052
1053        assert_matches!(
1054            serde_json::from_value::<Request>(encoded).unwrap(),
1055            Request::SubscribeWithVersion { protocol_version }
1056                if protocol_version == PROTOCOL_VERSION
1057        );
1058    }
1059
1060    #[test]
1061    fn health_history_request_and_response_round_trip() -> serde_json::Result<()> {
1062        let request = Request::GetHealthHistory {
1063            service: "api".to_string(),
1064        };
1065        let encoded = serde_json::to_value(&request)?;
1066        assert_matches!(
1067            serde_json::from_value::<Request>(encoded)?,
1068            Request::GetHealthHistory { service } if service == "api"
1069        );
1070
1071        let response = Response::HealthHistory {
1072            attempts: vec![HealthAttempt {
1073                run_generation: 2,
1074                attempt: 3,
1075                command: "probe".to_string(),
1076                output: Vec::new(),
1077                result: None,
1078            }],
1079        };
1080        let encoded = serde_json::to_value(response)?;
1081        let Response::HealthHistory { attempts } = serde_json::from_value::<Response>(encoded)?
1082        else {
1083            return Err(serde_json::Error::io(std::io::Error::other(
1084                "unexpected health-history response variant",
1085            )));
1086        };
1087        assert_eq!(attempts.len(), 1);
1088        assert_eq!(attempts.first().map(|attempt| attempt.attempt), Some(3));
1089        Ok(())
1090    }
1091
1092    #[test]
1093    fn logs_response_accepts_missing_truncated_flag() {
1094        let response = serde_json::from_value::<Response>(json!({
1095            "Logs": {
1096                "lines": []
1097            }
1098        }))
1099        .unwrap();
1100
1101        match response {
1102            Response::Logs {
1103                lines,
1104                truncated,
1105                first_retained_seq,
1106            } => {
1107                assert!(lines.is_empty());
1108                assert!(!truncated);
1109                assert_eq!(first_retained_seq, None);
1110            }
1111            other => panic!("unexpected response: {other:?}"),
1112        }
1113    }
1114
1115    #[test]
1116    fn protocol_version_ignores_additive_fields() {
1117        let version = serde_json::from_value::<ProtocolVersion>(json!({
1118            "major": 3,
1119            "minor": 20,
1120            "future_capability": true
1121        }))
1122        .unwrap();
1123
1124        assert_eq!(version, PROTOCOL_VERSION);
1125    }
1126
1127    #[test]
1128    fn only_observations_are_safe_to_retry_after_a_lost_response() {
1129        assert!(Request::ListServices.is_retry_safe());
1130        assert!(
1131            Request::GetService {
1132                service: "api".to_string(),
1133            }
1134            .is_retry_safe()
1135        );
1136        assert!(Request::ReconcileConfig { dry_run: true }.is_retry_safe());
1137        assert!(!Request::RestartAll.is_retry_safe());
1138        assert!(!Request::ReconcileConfig { dry_run: false }.is_retry_safe());
1139        assert!(!Request::Shutdown.is_retry_safe());
1140        // A replayed keystroke would type twice.
1141        assert!(
1142            !Request::SendInput {
1143                service: "api".to_string(),
1144                data: InputBytes::from(b"y".to_vec()),
1145                paste: false,
1146            }
1147            .is_retry_safe()
1148        );
1149        assert!(!Request::ResizeTerminal { cols: 80, rows: 24 }.is_retry_safe());
1150    }
1151
1152    #[test]
1153    fn dynamic_request_round_trips_flat_spec_and_humantime_lease() -> serde_json::Result<()> {
1154        let value = json!({
1155            "StartDynamicService": {
1156                "params": {
1157                    "service": "debug",
1158                    "command": ["CMD-SHELL", "echo ready"],
1159                    "environment": {"MODE": "debug"},
1160                    "healthcheck": null,
1161                    "expires_after": "90s",
1162                    "idempotency_key": "request-1"
1163                }
1164            }
1165        });
1166        let request = serde_json::from_value::<Request>(value.clone())?;
1167        let Request::StartDynamicService { params } = &request else {
1168            return Err(serde_json::Error::io(std::io::Error::other(
1169                "unexpected request variant",
1170            )));
1171        };
1172        assert_eq!(
1173            params.expires_after,
1174            Some(micromux::Lease::After(std::time::Duration::from_secs(90)))
1175        );
1176        assert_eq!(params.spec.healthcheck, micromux::SpecField::Clear);
1177        let encoded = serde_json::to_value(&request)?;
1178        assert_eq!(
1179            encoded.pointer("/StartDynamicService/params/expires_after"),
1180            Some(&json!("1m 30s"))
1181        );
1182        assert_eq!(
1183            encoded.pointer("/StartDynamicService/params/extra_args"),
1184            Some(&json!([]))
1185        );
1186        let Request::StartDynamicService { params } = serde_json::from_value(encoded)? else {
1187            return Err(serde_json::Error::io(std::io::Error::other(
1188                "unexpected round-trip request variant",
1189            )));
1190        };
1191        assert_eq!(
1192            params.expires_after,
1193            Some(micromux::Lease::After(std::time::Duration::from_secs(90)))
1194        );
1195        Ok(())
1196    }
1197
1198    #[test]
1199    fn dynamic_request_round_trips_an_unbounded_or_omitted_lease() -> serde_json::Result<()> {
1200        let unbounded = json!({
1201            "StartDynamicService": {
1202                "params": {
1203                    "service": "debug",
1204                    "command": ["true"],
1205                    "expires_after": "none"
1206                }
1207            }
1208        });
1209        let request = serde_json::from_value::<Request>(unbounded)?;
1210        let Request::StartDynamicService { params } = request else {
1211            return Err(serde_json::Error::io(std::io::Error::other(
1212                "unexpected request variant",
1213            )));
1214        };
1215        assert_eq!(params.expires_after, Some(micromux::Lease::Unbounded));
1216
1217        let omitted = json!({
1218            "StartDynamicService": {
1219                "params": {
1220                    "service": "debug",
1221                    "command": ["true"]
1222                }
1223            }
1224        });
1225        let Request::StartDynamicService { params } = serde_json::from_value(omitted)? else {
1226            return Err(serde_json::Error::io(std::io::Error::other(
1227                "unexpected request variant",
1228            )));
1229        };
1230        assert_eq!(params.expires_after, None);
1231        Ok(())
1232    }
1233}