1use 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
19pub const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 20);
24
25pub const EVENTS_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 3);
27
28pub const ENVIRONMENT_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 15);
30
31pub const SESSION_ENV_FILE_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 20);
37
38pub const TERMINAL_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 18);
41
42pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
59pub struct ProtocolVersion {
60 major: u16,
61 minor: u16,
62}
63
64impl ProtocolVersion {
65 #[must_use]
67 pub const fn new(major: u16, minor: u16) -> Self {
68 Self { major, minor }
69 }
70
71 #[must_use]
73 pub const fn major(self) -> u16 {
74 self.major
75 }
76
77 #[must_use]
79 pub const fn minor(self) -> u16 {
80 self.minor
81 }
82
83 #[must_use]
85 pub const fn is_compatible_with(self, peer: Self) -> bool {
86 self.major == peer.major
87 }
88
89 #[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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
106pub enum Request {
107 Describe,
109 ListServices,
114 GetService {
118 service: ServiceID,
120 },
121 GetLogs {
123 service: ServiceID,
125 run_generation: Option<u64>,
128 tail: Option<usize>,
130 },
131 FollowLogs {
133 service: ServiceID,
135 run_generation: Option<u64>,
138 after: Option<u64>,
141 },
142 ListLogRuns {
147 service: ServiceID,
149 },
150 GetHealth {
152 service: ServiceID,
154 },
155 GetHealthHistory {
157 service: ServiceID,
159 },
160 GetEvents {
164 service: ServiceID,
166 after: Option<u64>,
168 tail: Option<usize>,
170 },
171 Restart {
173 service: ServiceID,
175 },
176 RestartAll,
178 Enable {
180 service: ServiceID,
182 },
183 Disable {
185 service: ServiceID,
187 },
188 StartDynamicService {
190 params: DynamicServiceParams,
192 },
193 ReplaceDynamicService {
195 service: ServiceID,
197 expected_revision: u64,
199 params: DynamicServiceParams,
201 },
202 RenewDynamicService {
204 service: ServiceID,
206 expected_revision: u64,
208 expires_after: Option<Lease>,
210 },
211 StopDynamicService {
213 service: ServiceID,
215 },
216 GetEnvironment {
225 service: Option<ServiceID>,
227 },
228 GetSessionEnvironment,
234 WriteEnvironmentFile {
245 service: Option<ServiceID>,
247 },
248 ReconcileConfig {
252 dry_run: bool,
255 },
256 SendInput {
264 service: ServiceID,
266 data: InputBytes,
269 #[serde(default)]
271 paste: bool,
272 },
273 ResizeTerminal {
279 cols: u16,
281 rows: u16,
283 },
284 Shutdown,
288 Subscribe,
290 SubscribeWithVersion {
292 protocol_version: ProtocolVersion,
294 },
295}
296
297impl Request {
298 #[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#[derive(Clone, PartialEq, Eq)]
329pub struct InputBytes(Vec<u8>);
330
331impl InputBytes {
332 #[must_use]
334 pub fn as_bytes(&self) -> &[u8] {
335 &self.0
336 }
337
338 #[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#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
388pub struct ServiceBrief {
389 pub id: ServiceID,
391 #[serde(default)]
393 pub name: String,
394}
395
396#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
398pub struct SessionInfo {
399 pub protocol_version: ProtocolVersion,
401 pub id: String,
403 pub pid: u32,
405 pub start_time: u64,
407 #[serde(default)]
409 pub name: String,
410 #[serde(default)]
412 pub working_dir: String,
413 #[serde(default)]
415 pub config_path: String,
416 #[serde(default)]
418 pub services: Vec<ServiceBrief>,
419 #[serde(default)]
423 pub services_truncated: bool,
424 #[serde(default)]
426 pub micromux_version: String,
427 #[serde(default, skip_serializing_if = "Option::is_none")]
429 pub session: Option<Box<micromux::SessionSummary>>,
430 #[serde(default, skip_serializing_if = "Option::is_none")]
432 pub capabilities: Option<SessionCapabilities>,
433}
434
435#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
437pub struct SessionCapabilities {
438 #[serde(default, skip_serializing_if = "Option::is_none")]
440 pub dynamic_services: Option<DynamicServicesCaps>,
441 #[serde(default, skip_serializing_if = "Option::is_none")]
443 pub disk_log_reads: Option<DiskLogReadHealth>,
444}
445
446#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
448pub struct DiskLogReadHealth {
449 #[serde(default = "default_initialized_disk_log_pool")]
451 pub initialized: bool,
452 pub available: bool,
454 pub workers: usize,
456 pub active: usize,
458 pub queue_capacity: usize,
460 pub queued: usize,
462 #[serde(default)]
464 pub abandoned: usize,
465 #[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 true
488}
489
490#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
492pub struct DynamicServicesCaps {
493 pub max_services: usize,
495 pub live_services: usize,
497 #[serde(default, skip_serializing_if = "Option::is_none")]
499 pub max_lifetime_secs: Option<u64>,
500 pub allowed_working_roots: Vec<String>,
502}
503
504impl SessionInfo {
505 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
514pub enum ErrorCode {
515 UnknownService,
517 UnknownRun,
519 NoSession,
521 Ambiguous,
523 Busy,
525 Timeout,
527 InvalidState,
529 ConfigReload,
531 PolicyDenied,
533 LimitExceeded,
535 RevisionMismatch,
537 InvalidSpec,
539 SchedulerStopped,
541 UnsupportedPlatform,
543 ProtocolVersionMismatch,
545 BadRequest,
547 Internal,
549 #[serde(other)]
551 Unknown,
552}
553
554#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
556pub enum Response {
557 Description(SessionInfo),
559 Services(Vec<ServiceSnapshot>),
561 Service(Box<ServiceSnapshot>),
563 Logs {
565 lines: Vec<LogLine>,
567 #[serde(default)]
569 truncated: bool,
570 #[serde(default, skip_serializing_if = "Option::is_none")]
575 first_retained_seq: Option<u64>,
576 },
577 LogRuns {
579 runs: Vec<LogRunSummary>,
581 },
582 Health(Option<HealthAttempt>),
584 HealthHistory {
586 attempts: Vec<HealthAttempt>,
588 },
589 Events {
591 events: Vec<ServiceEvent>,
593 truncated: bool,
595 },
596 Accepted {
599 services: Vec<ServiceCommandAck>,
601 },
602 DynamicService(DynamicServiceAck),
604 Reconcile(ReconcileReceipt),
606 Environment(ResolvedEnvironment),
608 EnvironmentFile {
610 path: String,
612 stale: bool,
614 },
615 Change(SessionChange),
617 TerminalQueued,
624 ShuttingDown,
626 Error {
628 code: ErrorCode,
630 message: String,
632 },
633}
634
635impl Response {
636 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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 #[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 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 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}