use base64::Engine as _;
use micromux::{
DynamicServiceAck, DynamicServiceParams, HealthAttempt, Lease, LogLine, LogRunSummary,
ReconcileReceipt, ResolvedEnvironment, ServiceCommandAck, ServiceEvent, ServiceID,
ServiceSnapshot, SessionChange,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
pub const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 18);
pub const EVENTS_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 3);
pub const ENVIRONMENT_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 15);
pub const TERMINAL_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 18);
pub const MAX_REMOTE_PASTE_BYTES: usize = 512 * 1024;
const _: () = assert!(
MAX_REMOTE_PASTE_BYTES.div_ceil(3) * 4 + 64 * 1024 <= crate::MAX_FRAME_BYTES,
"a maximal remote paste must fit one control frame"
);
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
}
#[must_use]
pub const fn supports(self, revision: Self) -> bool {
self.major == revision.major && self.minor >= revision.minor
}
}
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,
},
GetEnvironment {
service: Option<ServiceID>,
},
ReconcileConfig {
dry_run: bool,
},
SendInput {
service: ServiceID,
data: InputBytes,
#[serde(default)]
paste: bool,
},
ResizeTerminal {
cols: u16,
rows: u16,
},
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::GetEnvironment { .. }
| Self::ReconcileConfig { dry_run: true }
)
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct InputBytes(Vec<u8>);
impl InputBytes {
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
#[must_use]
pub fn into_inner(self) -> Vec<u8> {
self.0
}
}
impl From<Vec<u8>> for InputBytes {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes)
}
}
impl std::fmt::Debug for InputBytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InputBytes({} bytes)", self.0.len())
}
}
impl Serialize for InputBytes {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&base64::engine::general_purpose::STANDARD.encode(&self.0))
}
}
impl<'de> Deserialize<'de> for InputBytes {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let encoded = String::deserialize(deserializer)?;
base64::engine::general_purpose::STANDARD
.decode(encoded)
.map(Self)
.map_err(serde::de::Error::custom)
}
}
impl JsonSchema for InputBytes {
fn schema_name() -> std::borrow::Cow<'static, str> {
"InputBytes".into()
}
fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "string",
"contentEncoding": "base64",
})
}
}
#[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 session: Option<Box<micromux::SessionSummary>>,
#[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),
Environment(ResolvedEnvironment),
Change(SessionChange),
TerminalQueued,
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 {
session: None,
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": 18 })
);
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, 18)));
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 events_require_protocol_3_3_on_the_same_major_line() {
assert!(ProtocolVersion::new(3, 3).supports(EVENTS_PROTOCOL_VERSION));
assert!(!ProtocolVersion::new(3, 2).supports(EVENTS_PROTOCOL_VERSION));
assert!(!ProtocolVersion::new(4, 3).supports(EVENTS_PROTOCOL_VERSION));
assert!(PROTOCOL_VERSION.supports(EVENTS_PROTOCOL_VERSION));
}
#[test]
fn environment_requires_protocol_3_15_on_the_same_major_line() {
assert!(ProtocolVersion::new(3, 15).supports(ENVIRONMENT_PROTOCOL_VERSION));
assert!(ProtocolVersion::new(3, 16).supports(ENVIRONMENT_PROTOCOL_VERSION));
assert!(!ProtocolVersion::new(3, 14).supports(ENVIRONMENT_PROTOCOL_VERSION));
assert!(!ProtocolVersion::new(4, 15).supports(ENVIRONMENT_PROTOCOL_VERSION));
assert!(PROTOCOL_VERSION.supports(ENVIRONMENT_PROTOCOL_VERSION));
}
#[test]
fn terminal_requests_require_protocol_3_18_on_the_same_major_line() {
assert!(ProtocolVersion::new(3, 18).supports(TERMINAL_PROTOCOL_VERSION));
assert!(!ProtocolVersion::new(3, 17).supports(TERMINAL_PROTOCOL_VERSION));
assert!(!ProtocolVersion::new(4, 18).supports(TERMINAL_PROTOCOL_VERSION));
assert!(PROTOCOL_VERSION.supports(TERMINAL_PROTOCOL_VERSION));
}
#[test]
fn send_input_round_trips_arbitrary_bytes_as_base64() -> serde_json::Result<()> {
let bytes = vec![0x1b, b'[', b'A', 0x00, 0xff, b'\r'];
let request = Request::SendInput {
service: "shell".to_string(),
data: InputBytes::from(bytes.clone()),
paste: true,
};
let encoded = serde_json::to_value(&request)?;
assert_eq!(
encoded,
json!({ "SendInput": { "service": "shell", "data": "G1tBAP8N", "paste": true } })
);
assert_matches!(
serde_json::from_value::<Request>(encoded)?,
Request::SendInput { service, data, paste: true }
if service == "shell" && data.as_bytes() == bytes.as_slice()
);
assert_matches!(
serde_json::from_value::<Request>(
json!({ "SendInput": { "service": "shell", "data": "" } })
)?,
Request::SendInput { data, paste: false, .. } if data.as_bytes().is_empty()
);
assert!(
serde_json::from_value::<Request>(
json!({ "SendInput": { "service": "shell", "data": "not base64!" } })
)
.is_err()
);
Ok(())
}
#[test]
fn send_input_debug_output_names_only_the_length() {
let request = Request::SendInput {
service: "shell".to_string(),
data: InputBytes::from(b"hunter2".to_vec()),
paste: false,
};
let debug = format!("{request:?}");
assert!(debug.contains("7 bytes"), "{debug}");
assert!(!debug.contains("hunter2"), "{debug}");
assert!(!debug.contains("104"), "{debug}");
}
#[test]
fn resize_and_terminal_acknowledgement_round_trip() -> serde_json::Result<()> {
let encoded = serde_json::to_value(Request::ResizeTerminal {
cols: 120,
rows: 40,
})?;
assert_eq!(
encoded,
json!({ "ResizeTerminal": { "cols": 120, "rows": 40 } })
);
assert_matches!(
serde_json::from_value::<Request>(encoded)?,
Request::ResizeTerminal {
cols: 120,
rows: 40
}
);
let encoded = serde_json::to_value(Response::TerminalQueued)?;
assert_eq!(encoded, json!("TerminalQueued"));
assert_matches!(
serde_json::from_value::<Response>(encoded)?,
Response::TerminalQueued
);
Ok(())
}
#[test]
fn environment_request_and_response_round_trip() -> serde_json::Result<()> {
for service in [None, Some("api".to_string())] {
let encoded = serde_json::to_value(Request::GetEnvironment {
service: service.clone(),
})?;
assert_matches!(
serde_json::from_value::<Request>(encoded)?,
Request::GetEnvironment { service: decoded } if decoded == service
);
}
assert!(Request::GetEnvironment { service: None }.is_retry_safe());
let environment = ResolvedEnvironment {
variables: [
("API_PORT".to_string(), "20001".to_string()),
("DATABASE_URL".to_string(), "postgres://secret".to_string()),
]
.into_iter()
.collect(),
stale: true,
};
let encoded = serde_json::to_value(Response::Environment(environment.clone()))?;
assert_eq!(
encoded,
json!({
"Environment": {
"variables": {"API_PORT": "20001", "DATABASE_URL": "postgres://secret"},
"stale": true
}
})
);
let Response::Environment(decoded) = serde_json::from_value::<Response>(encoded)? else {
return Err(serde_json::Error::io(std::io::Error::other(
"unexpected environment response variant",
)));
};
assert_eq!(decoded, environment);
Ok(())
}
#[test]
fn environment_debug_output_names_variables_without_values() {
let response = Response::Environment(ResolvedEnvironment {
variables: [("DATABASE_URL".to_string(), "postgres://secret".to_string())]
.into_iter()
.collect(),
stale: false,
});
let debug = format!("{response:?}");
assert!(debug.contains("DATABASE_URL"), "{debug}");
assert!(!debug.contains("postgres://secret"), "{debug}");
}
#[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_eq!(minimal.ports, [] as [u16; 0]);
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": 18,
"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());
assert!(
!Request::SendInput {
service: "api".to_string(),
data: InputBytes::from(b"y".to_vec()),
paste: false,
}
.is_retry_safe()
);
assert!(!Request::ResizeTerminal { cols: 80, rows: 24 }.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(())
}
}