Skip to main content

micromux_control/
lib.rs

1//! The micromux control plane: a per-session local control endpoint and its wire protocol.
2//!
3//! The session binds a Unix domain socket (Unix/macOS) keyed by a hash of its canonical config
4//! path; clients — the `micromux ctl` CLI and the MCP proxy — connect, speak newline-delimited JSON
5//! ([`Request`]/[`Response`]), and probe local endpoint paths, removing only the stale sockets no
6//! session owns.
7//! The core knows nothing about any of this; the server is driven by a
8//! [`micromux::SessionModelReader`] (reads), a [`micromux::ServiceControl`] (mutations and the
9//! environment read), and optionally a [`micromux::TerminalControl`] (PTY input and resizes from
10//! attached TUIs), so it can observe and command but never mutate the model directly.
11
12mod client;
13mod endpoint;
14mod protocol;
15mod select;
16mod server;
17pub mod wait;
18
19use std::time::Duration;
20
21#[cfg(unix)]
22use futures::{SinkExt, StreamExt};
23#[cfg(unix)]
24use serde::Serialize;
25#[cfg(unix)]
26use serde::de::DeserializeOwned;
27#[cfg(unix)]
28use tokio::io::{AsyncRead, AsyncWrite};
29use tokio_util::codec::LinesCodecError;
30#[cfg(unix)]
31use tokio_util::codec::{Framed, LinesCodec};
32
33pub use client::{
34    Client, EndpointProbe, EndpointProbeResult, Subscription, answering_session_probes,
35    probe_endpoint, probe_endpoints, probe_runtime_dir, probe_runtime_dirs,
36    unique_answering_session_probes,
37};
38#[cfg(unix)]
39pub use endpoint::coordination_dir;
40pub use endpoint::{
41    CanonicalConfigPath, ControlEndpoint, RuntimeDirStatus, coordination_dir_in, endpoint_for,
42    endpoint_from_hash, endpoint_hash, runtime_dir, runtime_dir_in, runtime_dir_statuses,
43    transport_supported, usable_runtime_dirs,
44};
45pub use micromux::{
46    DynamicServiceAck, ReconcileAction, ReconcileActionKind, ReconcileReceipt, ResolvedEnvironment,
47};
48pub use protocol::{
49    DiskLogReadHealth, DynamicServicesCaps, ENVIRONMENT_PROTOCOL_VERSION, EVENTS_PROTOCOL_VERSION,
50    ErrorCode, InputBytes, MAX_REMOTE_PASTE_BYTES, PROTOCOL_VERSION, ProtocolVersion, Request,
51    Response, SESSION_ENV_FILE_PROTOCOL_VERSION, ServiceBrief, SessionCapabilities, SessionInfo,
52    TERMINAL_PROTOCOL_VERSION,
53};
54pub use select::{
55    AmbiguousSelection, LISTED_ABSENT_PROBES, ProbeReport, ResolvedSession, RuntimeDirDetail,
56    SelectError, SessionSelector, SocketProbeDetail, SocketProbeDetails, SocketProbeStatus,
57    config_for_target, probe_detail, resolve_selector, resolve_selector_in_runtime_dirs,
58    resolve_selector_with_statuses, session_config_path_is_under, session_matches_config_path,
59};
60pub use server::{
61    ClaimError, ControlServer, EndpointGuard, ProjectClaim, SESSION_ALREADY_STARTING,
62    SessionIdentity, UnclaimedProject, bind, bind_project, claim_project, endpoint_owner_lock_held,
63    hold_unclaimed_project,
64};
65#[cfg(unix)]
66pub use server::{claim_project_at, hold_unclaimed_project_at};
67
68/// Maximum size of a single protocol frame. Oversized frames are rejected, not buffered, so a
69/// broken peer cannot pin memory.
70pub const MAX_FRAME_BYTES: usize = 1024 * 1024;
71
72/// How long a client waits for a single response before giving up.
73pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
74
75/// How long discovery probes wait before classifying an endpoint as busy/unreachable.
76///
77/// This is intentionally shorter than [`REQUEST_TIMEOUT`]: discovery scans multiple endpoints and
78/// a slow probe should not stall selection. Timed-out endpoints are reported, never pruned.
79pub const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
80
81/// How long a request/response connection may sit idle before it is closed.
82///
83/// Version-aware subscriptions use a shorter heartbeat interval instead.
84pub const IDLE_TIMEOUT: Duration = Duration::from_mins(5);
85
86/// How often compatible subscription peers exchange a liveness notification while idle.
87pub const SUBSCRIPTION_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);
88
89/// How long a version-aware client waits without a subscription frame before reconnecting.
90pub const SUBSCRIPTION_READ_TIMEOUT: Duration = Duration::from_secs(75);
91
92/// Errors produced by the control plane.
93#[derive(thiserror::Error, Debug)]
94pub enum ControlError {
95    /// An I/O error.
96    #[error(transparent)]
97    Io(#[from] std::io::Error),
98    /// A JSON (de)serialization error.
99    #[error("control protocol serialization error: {0}")]
100    Serde(#[from] serde_json::Error),
101    /// The control plane is not supported on this platform.
102    #[error("the control plane is not supported on this platform")]
103    Unsupported,
104    /// The connection was closed before a response arrived.
105    #[error("control connection closed")]
106    Closed,
107    /// A frame exceeded [`MAX_FRAME_BYTES`].
108    #[error("control protocol frame exceeded the maximum size")]
109    FrameTooLarge,
110    /// A request timed out.
111    #[error("control request timed out")]
112    Timeout,
113    /// The peer speaks an incompatible protocol version.
114    #[error("control protocol version mismatch: peer={peer}, ours={ours}")]
115    ProtocolMismatch {
116        /// The peer's protocol version.
117        peer: ProtocolVersion,
118        /// Our protocol version.
119        ours: ProtocolVersion,
120    },
121    /// The peer sent a response that did not match the request.
122    #[error("unexpected control response: {0}")]
123    Unexpected(String),
124}
125
126impl From<LinesCodecError> for ControlError {
127    fn from(err: LinesCodecError) -> Self {
128        match err {
129            LinesCodecError::MaxLineLengthExceeded => Self::FrameTooLarge,
130            LinesCodecError::Io(err) => Self::Io(err),
131        }
132    }
133}
134
135#[cfg(unix)]
136type Framing<T> = Framed<T, LinesCodec>;
137
138#[cfg(unix)]
139fn framed<T: AsyncRead + AsyncWrite>(io: T) -> Framing<T> {
140    Framed::new(io, LinesCodec::new_with_max_length(MAX_FRAME_BYTES))
141}
142
143#[cfg(unix)]
144async fn write_message<T, M>(framing: &mut Framing<T>, message: &M) -> Result<(), ControlError>
145where
146    T: AsyncRead + AsyncWrite + Unpin,
147    M: Serialize,
148{
149    let line = serde_json::to_string(message)?;
150    if line.len() > MAX_FRAME_BYTES {
151        return Err(ControlError::FrameTooLarge);
152    }
153    framing.send(line).await?;
154    Ok(())
155}
156
157#[cfg(unix)]
158async fn read_message<T, M>(framing: &mut Framing<T>) -> Result<Option<M>, ControlError>
159where
160    T: AsyncRead + AsyncWrite + Unpin,
161    M: DeserializeOwned,
162{
163    match framing.next().await {
164        Some(Ok(line)) => Ok(Some(serde_json::from_str(&line)?)),
165        Some(Err(err)) => Err(err.into()),
166        None => Ok(None),
167    }
168}
169
170#[cfg(all(test, unix))]
171mod tests {
172    use std::assert_matches;
173
174    use super::{ControlError, MAX_FRAME_BYTES, framed, write_message};
175
176    #[tokio::test]
177    async fn encode_rejects_a_frame_over_the_protocol_limit() {
178        let (stream, _peer) = tokio::io::duplex(64);
179        let mut conn = framed(stream);
180        let oversized = "x".repeat(MAX_FRAME_BYTES);
181
182        assert_matches!(
183            write_message(&mut conn, &oversized).await,
184            Err(ControlError::FrameTooLarge)
185        );
186    }
187}