use micromux::{
DynamicServiceAck, DynamicServiceParams, HealthAttempt, Lease, LogLine, LogRunSummary,
ReconcileReceipt, ServiceCommandAck, ServiceEvent, ServiceID, ServiceSnapshot, SessionChange,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
pub const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 10);
pub(crate) const fn supports_versioned_subscriptions(version: ProtocolVersion) -> bool {
version.major() == PROTOCOL_VERSION.major() && version.minor() >= 7
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ProtocolVersion {
major: u16,
minor: u16,
}
impl ProtocolVersion {
#[must_use]
pub const fn new(major: u16, minor: u16) -> Self {
Self { major, minor }
}
#[must_use]
pub const fn major(self) -> u16 {
self.major
}
#[must_use]
pub const fn minor(self) -> u16 {
self.minor
}
#[must_use]
pub const fn is_compatible_with(self, peer: Self) -> bool {
self.major == peer.major
}
}
impl std::fmt::Display for ProtocolVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}.{}", self.major(), self.minor())
}
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub enum Request {
Describe,
ListServices,
GetService {
service: ServiceID,
},
GetLogs {
service: ServiceID,
run_generation: Option<u64>,
tail: Option<usize>,
},
FollowLogs {
service: ServiceID,
run_generation: Option<u64>,
after: Option<u64>,
},
ListLogRuns {
service: ServiceID,
},
GetHealth {
service: ServiceID,
},
GetHealthHistory {
service: ServiceID,
},
GetEvents {
service: ServiceID,
after: Option<u64>,
tail: Option<usize>,
},
Restart {
service: ServiceID,
},
RestartAll,
Enable {
service: ServiceID,
},
Disable {
service: ServiceID,
},
StartDynamicService {
params: DynamicServiceParams,
},
ReplaceDynamicService {
service: ServiceID,
expected_revision: u64,
params: DynamicServiceParams,
},
RenewDynamicService {
service: ServiceID,
expected_revision: u64,
expires_after: Option<Lease>,
},
StopDynamicService {
service: ServiceID,
},
ReconcileConfig {
dry_run: bool,
},
Shutdown,
Subscribe,
SubscribeWithVersion {
protocol_version: ProtocolVersion,
},
}
impl Request {
#[must_use]
pub const fn is_retry_safe(&self) -> bool {
matches!(
self,
Self::Describe
| Self::ListServices
| Self::GetService { .. }
| Self::GetLogs { .. }
| Self::FollowLogs { .. }
| Self::ListLogRuns { .. }
| Self::GetHealth { .. }
| Self::GetHealthHistory { .. }
| Self::GetEvents { .. }
| Self::ReconcileConfig { dry_run: true }
)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ServiceBrief {
pub id: ServiceID,
#[serde(default)]
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SessionInfo {
pub protocol_version: ProtocolVersion,
pub id: String,
pub pid: u32,
pub start_time: u64,
#[serde(default)]
pub name: String,
#[serde(default)]
pub working_dir: String,
#[serde(default)]
pub config_path: String,
#[serde(default)]
pub services: Vec<ServiceBrief>,
#[serde(default)]
pub services_truncated: bool,
#[serde(default)]
pub micromux_version: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub capabilities: Option<SessionCapabilities>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct SessionCapabilities {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dynamic_services: Option<DynamicServicesCaps>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub disk_log_reads: Option<DiskLogReadHealth>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
pub struct DiskLogReadHealth {
#[serde(default = "default_initialized_disk_log_pool")]
pub initialized: bool,
pub available: bool,
pub workers: usize,
pub active: usize,
pub queue_capacity: usize,
pub queued: usize,
#[serde(default)]
pub abandoned: usize,
#[serde(default)]
pub timed_out_requests: usize,
}
impl Default for DiskLogReadHealth {
fn default() -> Self {
Self {
initialized: default_initialized_disk_log_pool(),
available: false,
workers: 0,
active: 0,
queue_capacity: 0,
queued: 0,
abandoned: 0,
timed_out_requests: 0,
}
}
}
const fn default_initialized_disk_log_pool() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DynamicServicesCaps {
pub max_services: usize,
pub live_services: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_lifetime_secs: Option<u64>,
pub allowed_working_roots: Vec<String>,
}
impl SessionInfo {
#[must_use]
pub fn is_same_instance(&self, other: &Self) -> bool {
self.id == other.id && self.pid == other.pid && self.start_time == other.start_time
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum ErrorCode {
UnknownService,
UnknownRun,
NoSession,
Ambiguous,
Busy,
Timeout,
InvalidState,
ConfigReload,
PolicyDenied,
LimitExceeded,
RevisionMismatch,
InvalidSpec,
SchedulerStopped,
UnsupportedPlatform,
ProtocolVersionMismatch,
BadRequest,
Internal,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub enum Response {
Description(SessionInfo),
Services(Vec<ServiceSnapshot>),
Service(Box<ServiceSnapshot>),
Logs {
lines: Vec<LogLine>,
#[serde(default)]
truncated: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
first_retained_seq: Option<u64>,
},
LogRuns {
runs: Vec<LogRunSummary>,
},
Health(Option<HealthAttempt>),
HealthHistory {
attempts: Vec<HealthAttempt>,
},
Events {
events: Vec<ServiceEvent>,
truncated: bool,
},
Accepted {
services: Vec<ServiceCommandAck>,
},
DynamicService(DynamicServiceAck),
Reconcile(ReconcileReceipt),
Change(SessionChange),
ShuttingDown,
Error {
code: ErrorCode,
message: String,
},
}
impl Response {
#[must_use]
pub fn error(code: ErrorCode, message: impl Into<String>) -> Self {
Self::Error {
code,
message: message.into(),
}
}
}
#[cfg(test)]
mod tests {
use std::assert_matches;
use super::*;
use serde_json::json;
use similar_asserts::assert_eq;
fn session(id: &str, pid: u32, start_time: u64, name: &str) -> SessionInfo {
SessionInfo {
protocol_version: PROTOCOL_VERSION,
id: id.to_string(),
pid,
start_time,
name: name.to_string(),
working_dir: ".".to_string(),
config_path: "/project/micromux.yaml".to_string(),
services: Vec::new(),
services_truncated: false,
micromux_version: env!("CARGO_PKG_VERSION").to_string(),
capabilities: None,
}
}
#[test]
fn session_instance_identity_uses_stable_start_token() {
let first = session("aaa", 42, 100, "app");
let alias = session("aaa", 42, 100, "renamed");
let replacement = session("aaa", 42, 101, "app");
assert!(first.is_same_instance(&alias));
assert!(!first.is_same_instance(&replacement));
}
#[test]
fn protocol_version_uses_major_minor_shape_and_accepts_same_major() {
assert_eq!(
serde_json::to_value(PROTOCOL_VERSION).unwrap(),
json!({ "major": 3, "minor": 10 })
);
assert_eq!(
serde_json::from_value::<ProtocolVersion>(json!({ "major": 1, "minor": 0 })).unwrap(),
ProtocolVersion::new(1, 0)
);
assert!(PROTOCOL_VERSION.is_compatible_with(ProtocolVersion::new(3, 11)));
assert!(!PROTOCOL_VERSION.is_compatible_with(ProtocolVersion::new(2, 9)));
assert!(!supports_versioned_subscriptions(ProtocolVersion::new(
3, 6
)));
assert!(supports_versioned_subscriptions(ProtocolVersion::new(3, 7)));
}
#[test]
fn protocol_version_rejects_plain_integer_shape() {
let err = serde_json::from_value::<ProtocolVersion>(json!(5)).unwrap_err();
assert!(
err.to_string().contains("invalid type"),
"unexpected error: {err}"
);
}
#[test]
fn protocol_version_rejects_missing_minor() {
let err = serde_json::from_value::<ProtocolVersion>(json!({ "major": 5 })).unwrap_err();
assert!(
err.to_string().contains("missing field `minor`"),
"unexpected error: {err}"
);
}
#[test]
fn unknown_error_codes_degrade_without_deserialize_failure() {
let code = serde_json::from_str::<ErrorCode>("\"FutureError\"").unwrap();
assert_eq!(code, ErrorCode::Unknown);
}
#[test]
fn session_info_accepts_missing_additive_fields() {
let info = serde_json::from_value::<SessionInfo>(json!({
"protocol_version": { "major": 3, "minor": 2 },
"id": "abc",
"pid": 42,
"start_time": 99
}))
.unwrap();
assert_eq!(info.protocol_version, ProtocolVersion::new(3, 2));
assert_eq!(info.name, "");
assert!(info.services.is_empty());
assert!(!info.services_truncated);
assert_eq!(info.micromux_version, "");
assert!(info.capabilities.is_none());
}
#[test]
fn disk_log_read_health_accepts_missing_timeout_history() {
let health = serde_json::from_value::<DiskLogReadHealth>(json!({
"available": true,
"workers": 4,
"active": 1,
"queue_capacity": 4,
"queued": 2
}))
.unwrap();
assert!(health.initialized);
assert_eq!(health.abandoned, 0);
assert_eq!(health.timed_out_requests, 0);
assert_eq!(health.initialized, DiskLogReadHealth::default().initialized);
}
#[test]
fn dynamic_service_ack_round_trips_and_accepts_missing_additive_fields() {
let ack = DynamicServiceAck {
service: "debug".to_string(),
revision: 2,
observed_generation: 1,
expires_at_unix_ms: Some(1234),
command: vec!["true".to_string()],
working_dir: None,
ports: vec![3201],
env_keys: vec!["RUST_LOG".to_string()],
restart: micromux::RestartPolicy::Never,
healthcheck_configured: false,
already_retired: false,
idempotent_replay: true,
};
let encoded = serde_json::to_value(Response::DynamicService(ack.clone())).unwrap();
let decoded = serde_json::from_value::<Response>(encoded).unwrap();
let Response::DynamicService(decoded) = decoded else {
panic!("expected a dynamic-service response");
};
assert_eq!(decoded.service, ack.service);
assert_eq!(decoded.revision, ack.revision);
assert!(decoded.idempotent_replay);
let minimal = serde_json::from_value::<DynamicServiceAck>(json!({
"service": "debug",
"revision": 1,
"observed_generation": 0,
"command": ["true"],
"restart": "Never",
"healthcheck_configured": false
}))
.unwrap();
assert_eq!(minimal.expires_at_unix_ms, None);
assert!(minimal.ports.is_empty());
assert!(!minimal.already_retired);
}
#[test]
fn reconcile_request_and_receipt_round_trip() {
let request = Request::ReconcileConfig { dry_run: true };
let encoded = serde_json::to_value(&request).unwrap();
assert_matches!(
serde_json::from_value::<Request>(encoded).unwrap(),
Request::ReconcileConfig { dry_run: true }
);
let receipt = micromux::ReconcileReceipt {
config_path: "/project/micromux.yaml".to_string(),
dry_run: true,
actions: vec![micromux::ReconcileAction {
service: "worker".to_string(),
action: micromux::ReconcileActionKind::Changed,
detail: "changed service spec".to_string(),
}],
};
let encoded = serde_json::to_value(Response::Reconcile(receipt.clone())).unwrap();
let Response::Reconcile(decoded) = serde_json::from_value::<Response>(encoded).unwrap()
else {
panic!("expected a reconcile response");
};
assert_eq!(decoded, receipt);
}
#[test]
fn versioned_subscription_carries_the_client_protocol() {
let request = Request::SubscribeWithVersion {
protocol_version: PROTOCOL_VERSION,
};
let encoded = serde_json::to_value(&request).unwrap();
assert_matches!(
serde_json::from_value::<Request>(encoded).unwrap(),
Request::SubscribeWithVersion { protocol_version }
if protocol_version == PROTOCOL_VERSION
);
}
#[test]
fn health_history_request_and_response_round_trip() -> serde_json::Result<()> {
let request = Request::GetHealthHistory {
service: "api".to_string(),
};
let encoded = serde_json::to_value(&request)?;
assert_matches!(
serde_json::from_value::<Request>(encoded)?,
Request::GetHealthHistory { service } if service == "api"
);
let response = Response::HealthHistory {
attempts: vec![HealthAttempt {
run_generation: 2,
attempt: 3,
command: "probe".to_string(),
output: Vec::new(),
result: None,
}],
};
let encoded = serde_json::to_value(response)?;
let Response::HealthHistory { attempts } = serde_json::from_value::<Response>(encoded)?
else {
return Err(serde_json::Error::io(std::io::Error::other(
"unexpected health-history response variant",
)));
};
assert_eq!(attempts.len(), 1);
assert_eq!(attempts.first().map(|attempt| attempt.attempt), Some(3));
Ok(())
}
#[test]
fn logs_response_accepts_missing_truncated_flag() {
let response = serde_json::from_value::<Response>(json!({
"Logs": {
"lines": []
}
}))
.unwrap();
match response {
Response::Logs {
lines,
truncated,
first_retained_seq,
} => {
assert!(lines.is_empty());
assert!(!truncated);
assert_eq!(first_retained_seq, None);
}
other => panic!("unexpected response: {other:?}"),
}
}
#[test]
fn protocol_version_ignores_additive_fields() {
let version = serde_json::from_value::<ProtocolVersion>(json!({
"major": 3,
"minor": 10,
"future_capability": true
}))
.unwrap();
assert_eq!(version, PROTOCOL_VERSION);
}
#[test]
fn only_observations_are_safe_to_retry_after_a_lost_response() {
assert!(Request::ListServices.is_retry_safe());
assert!(
Request::GetService {
service: "api".to_string(),
}
.is_retry_safe()
);
assert!(Request::ReconcileConfig { dry_run: true }.is_retry_safe());
assert!(!Request::RestartAll.is_retry_safe());
assert!(!Request::ReconcileConfig { dry_run: false }.is_retry_safe());
assert!(!Request::Shutdown.is_retry_safe());
}
#[test]
fn dynamic_request_round_trips_flat_spec_and_humantime_lease() -> serde_json::Result<()> {
let value = json!({
"StartDynamicService": {
"params": {
"service": "debug",
"command": ["CMD-SHELL", "echo ready"],
"environment": {"MODE": "debug"},
"healthcheck": null,
"expires_after": "90s",
"idempotency_key": "request-1"
}
}
});
let request = serde_json::from_value::<Request>(value.clone())?;
let Request::StartDynamicService { params } = &request else {
return Err(serde_json::Error::io(std::io::Error::other(
"unexpected request variant",
)));
};
assert_eq!(
params.expires_after,
Some(micromux::Lease::After(std::time::Duration::from_secs(90)))
);
assert_eq!(params.spec.healthcheck, micromux::SpecField::Clear);
let encoded = serde_json::to_value(&request)?;
assert_eq!(
encoded.pointer("/StartDynamicService/params/expires_after"),
Some(&json!("1m 30s"))
);
assert_eq!(
encoded.pointer("/StartDynamicService/params/extra_args"),
Some(&json!([]))
);
let Request::StartDynamicService { params } = serde_json::from_value(encoded)? else {
return Err(serde_json::Error::io(std::io::Error::other(
"unexpected round-trip request variant",
)));
};
assert_eq!(
params.expires_after,
Some(micromux::Lease::After(std::time::Duration::from_secs(90)))
);
Ok(())
}
#[test]
fn dynamic_request_round_trips_an_unbounded_or_omitted_lease() -> serde_json::Result<()> {
let unbounded = json!({
"StartDynamicService": {
"params": {
"service": "debug",
"command": ["true"],
"expires_after": "none"
}
}
});
let request = serde_json::from_value::<Request>(unbounded)?;
let Request::StartDynamicService { params } = request else {
return Err(serde_json::Error::io(std::io::Error::other(
"unexpected request variant",
)));
};
assert_eq!(params.expires_after, Some(micromux::Lease::Unbounded));
let omitted = json!({
"StartDynamicService": {
"params": {
"service": "debug",
"command": ["true"]
}
}
});
let Request::StartDynamicService { params } = serde_json::from_value(omitted)? else {
return Err(serde_json::Error::io(std::io::Error::other(
"unexpected request variant",
)));
};
assert_eq!(params.expires_after, None);
Ok(())
}
}