micromux-control 0.1.2

Micromux is a local process supervisor with a terminal UI
Documentation
//! The micromux control plane: a per-session local control endpoint and its wire protocol.
//!
//! The session binds a Unix domain socket (Unix/macOS) keyed by a hash of its canonical config
//! path; clients — the `micromux ctl` CLI and the MCP proxy — connect, speak newline-delimited JSON
//! ([`Request`]/[`Response`]), and probe local endpoint paths without pruning stale sockets. The
//! core knows nothing about any of this; the server is driven by a
//! [`micromux::SessionModelReader`] (reads) and a [`micromux::ServiceControl`] (mutations), so it
//! can observe and command but never mutate the model directly.

mod client;
mod endpoint;
mod protocol;
mod select;
mod server;

use std::time::Duration;

#[cfg(unix)]
use futures::{SinkExt, StreamExt};
#[cfg(unix)]
use serde::Serialize;
#[cfg(unix)]
use serde::de::DeserializeOwned;
#[cfg(unix)]
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_util::codec::LinesCodecError;
#[cfg(unix)]
use tokio_util::codec::{Framed, LinesCodec};

pub use client::{
    Client, EndpointProbe, EndpointProbeResult, Subscription, answering_session_probes,
    probe_endpoint, probe_endpoints, probe_runtime_dir, probe_runtime_dirs,
    unique_answering_session_probes,
};
pub use endpoint::{
    CanonicalConfigPath, ControlEndpoint, RuntimeDirStatus, endpoint_for, endpoint_from_hash,
    endpoint_hash, runtime_dir, runtime_dir_statuses, transport_supported, usable_runtime_dirs,
};
pub use micromux::{DynamicServiceAck, ReconcileAction, ReconcileActionKind, ReconcileReceipt};
pub use protocol::{
    DiskLogReadHealth, DynamicServicesCaps, ErrorCode, PROTOCOL_VERSION, ProtocolVersion, Request,
    Response, ServiceBrief, SessionCapabilities, SessionInfo,
};
pub use select::{
    AmbiguousSelection, ProbeReport, ResolvedSession, RuntimeDirDetail, SelectError,
    SessionSelector, SocketProbeDetail, SocketProbeStatus, config_for_target, probe_detail,
    resolve_selector, resolve_selector_in_runtime_dirs, session_config_path_is_under,
    session_matches_config_path,
};
pub use server::{
    ControlServer, EndpointGuard, SessionIdentity, bind, bind_project, endpoint_owner_lock_held,
};

/// Maximum size of a single protocol frame. Oversized frames are rejected, not buffered, so a
/// broken peer cannot pin memory.
pub const MAX_FRAME_BYTES: usize = 1024 * 1024;

/// How long a client waits for a single response before giving up.
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);

/// How long discovery probes wait before classifying an endpoint as busy/unreachable.
///
/// This is intentionally shorter than [`REQUEST_TIMEOUT`]: discovery scans multiple endpoints and
/// a slow probe should not stall selection. Timed-out endpoints are reported, never pruned.
pub const PROBE_TIMEOUT: Duration = Duration::from_secs(2);

/// How long a request/response connection may sit idle before it is closed.
///
/// Version-aware subscriptions use a shorter heartbeat interval instead.
pub const IDLE_TIMEOUT: Duration = Duration::from_mins(5);

/// How often compatible subscription peers exchange a liveness notification while idle.
pub const SUBSCRIPTION_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(30);

/// How long a version-aware client waits without a subscription frame before reconnecting.
pub const SUBSCRIPTION_READ_TIMEOUT: Duration = Duration::from_secs(75);

/// Errors produced by the control plane.
#[derive(thiserror::Error, Debug)]
pub enum ControlError {
    /// An I/O error.
    #[error(transparent)]
    Io(#[from] std::io::Error),
    /// A JSON (de)serialization error.
    #[error("control protocol serialization error: {0}")]
    Serde(#[from] serde_json::Error),
    /// The control plane is not supported on this platform.
    #[error("the control plane is not supported on this platform")]
    Unsupported,
    /// The connection was closed before a response arrived.
    #[error("control connection closed")]
    Closed,
    /// A frame exceeded [`MAX_FRAME_BYTES`].
    #[error("control protocol frame exceeded the maximum size")]
    FrameTooLarge,
    /// A request timed out.
    #[error("control request timed out")]
    Timeout,
    /// The peer speaks an incompatible protocol version.
    #[error("control protocol version mismatch: peer={peer}, ours={ours}")]
    ProtocolMismatch {
        /// The peer's protocol version.
        peer: ProtocolVersion,
        /// Our protocol version.
        ours: ProtocolVersion,
    },
    /// The peer sent a response that did not match the request.
    #[error("unexpected control response: {0}")]
    Unexpected(String),
}

impl From<LinesCodecError> for ControlError {
    fn from(err: LinesCodecError) -> Self {
        match err {
            LinesCodecError::MaxLineLengthExceeded => Self::FrameTooLarge,
            LinesCodecError::Io(err) => Self::Io(err),
        }
    }
}

#[cfg(unix)]
type Framing<T> = Framed<T, LinesCodec>;

#[cfg(unix)]
fn framed<T: AsyncRead + AsyncWrite>(io: T) -> Framing<T> {
    Framed::new(io, LinesCodec::new_with_max_length(MAX_FRAME_BYTES))
}

#[cfg(unix)]
async fn write_message<T, M>(framing: &mut Framing<T>, message: &M) -> Result<(), ControlError>
where
    T: AsyncRead + AsyncWrite + Unpin,
    M: Serialize,
{
    let line = serde_json::to_string(message)?;
    if line.len() > MAX_FRAME_BYTES {
        return Err(ControlError::FrameTooLarge);
    }
    framing.send(line).await?;
    Ok(())
}

#[cfg(unix)]
async fn read_message<T, M>(framing: &mut Framing<T>) -> Result<Option<M>, ControlError>
where
    T: AsyncRead + AsyncWrite + Unpin,
    M: DeserializeOwned,
{
    match framing.next().await {
        Some(Ok(line)) => Ok(Some(serde_json::from_str(&line)?)),
        Some(Err(err)) => Err(err.into()),
        None => Ok(None),
    }
}

#[cfg(all(test, unix))]
mod tests {
    use std::assert_matches;

    use super::{ControlError, MAX_FRAME_BYTES, framed, write_message};

    #[tokio::test]
    async fn encode_rejects_a_frame_over_the_protocol_limit() {
        let (stream, _peer) = tokio::io::duplex(64);
        let mut conn = framed(stream);
        let oversized = "x".repeat(MAX_FRAME_BYTES);

        assert_matches!(
            write_message(&mut conn, &oversized).await,
            Err(ControlError::FrameTooLarge)
        );
    }
}