1#![forbid(unsafe_code)]
9
10use std::{collections::BTreeMap, path::PathBuf};
11
12use serde::{
13 de::{Error as _, MapAccess, SeqAccess, Visitor},
14 ser::SerializeMap,
15 Deserialize, Deserializer, Serialize, Serializer,
16};
17use subc_protocol::{
18 manifest::{
19 CapabilityDeclarations, EventDeclaration, ManifestProvenance, OperationDelivery,
20 OperationPayload, ProviderRole, RichUiDescriptor, SelfSignalDeclaration,
21 },
22 scope::ScopeSelector,
23 session::HealthStatus,
24 BindIdentity, RouteTarget,
25};
26
27pub use subc_protocol::RouteCloseReason;
28
29mod activity;
30pub use activity::*;
31
32mod scope_served_by;
33pub use scope_served_by::*;
34
35macro_rules! open_string_enum {
36 (
37 $(#[$meta:meta])*
38 $name:ident {
39 $( $(#[$variant_meta:meta])* $variant:ident => $wire_name:literal ),+ $(,)?
40 }
41 ) => {
42 $(#[$meta])*
43 #[derive(Debug, Clone, PartialEq, Eq)]
44 pub enum $name {
45 $( $(#[$variant_meta])* $variant, )+
46 Unknown(String),
47 }
48
49 impl $name {
50 fn wire_name(&self) -> &str {
51 match self {
52 $( Self::$variant => $wire_name, )+
53 Self::Unknown(value) => value,
54 }
55 }
56 }
57
58 impl Serialize for $name {
59 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
60 where
61 S: serde::Serializer,
62 {
63 serializer.serialize_str(self.wire_name())
64 }
65 }
66
67 impl<'de> Deserialize<'de> for $name {
68 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
69 where
70 D: serde::Deserializer<'de>,
71 {
72 let value = String::deserialize(deserializer)?;
73 Ok(match value.as_str() {
74 $( $wire_name => Self::$variant, )+
75 _ => Self::Unknown(value),
76 })
77 }
78 }
79 };
80}
81
82mod rescan_checked;
83pub use rescan_checked::*;
84
85mod app_open;
86pub use app_open::*;
87
88mod connection_describe;
89pub use connection_describe::*;
90
91#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
93pub struct ConsumerIdentity {
94 pub module_id: String,
95 pub launch_nonce: String,
96}
97
98impl std::fmt::Debug for ConsumerIdentity {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 f.debug_struct("ConsumerIdentity")
105 .field("module_id", &self.module_id)
106 .field(
107 "launch_nonce",
108 &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
109 )
110 .finish()
111 }
112}
113
114pub mod ops {
125 pub const SERVER: &str = "server.";
126 pub const CATALOG: &str = "catalog.";
127 pub const ROUTE: &str = "route.";
128 pub const SUPERVISOR: &str = "supervisor.";
129 pub const CONFIG: &str = "config.";
130
131 pub const SERVER_DESCRIBE: &str = "server.describe";
132 pub const DAEMON_SHUTDOWN_INTENT: &str = "daemon.shutdown_intent";
133 pub const CATALOG_LIST: &str = "catalog.list";
134 pub const ROUTE_OPEN: &str = "route.open";
135 pub const ROUTE_POLL: &str = "route.poll";
136 pub const ROUTE_CLOSING: &str = "route.closing";
137 pub const ROUTE_CLOSED: &str = "route.closed";
138 pub const SUPERVISOR_LIST: &str = "supervisor.list";
139 pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
140 pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
141 pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
142 pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
143 pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
144 pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
145 pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
146 pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
147 pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
148 pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
149 pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
150 pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
151 pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
152 pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
153 pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
154 pub const ACTIVITY_RECORD: &str = "activity.record";
155 pub const ACTIVITY_QUERY: &str = "activity.query";
156 pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
157 pub const APP_OPEN: &str = "app.open";
158 pub const CONNECTION_DESCRIBE: &str = "connection.describe";
159}
160
161#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
163#[serde(tag = "op")]
164#[allow(clippy::large_enum_variant)]
167pub enum ClientControlRequest {
168 #[serde(rename = "daemon.shutdown_intent")]
171 DaemonShutdownIntent {
172 #[serde(default)]
173 intent: serde_json::Value,
174 },
175 #[serde(rename = "server.describe")]
176 ServerDescribe {},
177 #[serde(rename = "catalog.list")]
178 CatalogList {
179 #[serde(default)]
184 module_id: Option<String>,
185 },
186 #[serde(rename = "route.open")]
187 RouteOpen {
188 target: RouteTarget,
189 identity: BindIdentity,
190 #[serde(default, skip_serializing_if = "Option::is_none")]
199 consumer_identity: Option<ConsumerIdentity>,
200 #[serde(default, skip_serializing_if = "Option::is_none")]
208 consumer_capabilities: Option<Vec<String>>,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
220 role_versions: Option<BTreeMap<String, String>>,
221 #[serde(default, skip_serializing_if = "Option::is_none")]
223 admission_facts: Option<serde_json::Value>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
231 scope: Option<ScopeSelector>,
232 },
233 #[serde(rename = "route.poll")]
234 RoutePoll {
235 route_channel: u16,
236 route_epoch: u32,
237 kind: PollKind,
238 },
239 #[serde(rename = "supervisor.list")]
240 SupervisorList {},
241 #[serde(rename = "supervisor.spawn_snapshot")]
243 SupervisorSpawnSnapshot {},
244 #[serde(rename = "supervisor.spawn_subscribe")]
260 SupervisorSpawnSubscribe {
261 #[serde(default, skip_serializing_if = "Option::is_none")]
262 since: Option<SpawnCursor>,
263 },
264 #[serde(rename = "supervisor.restart")]
265 SupervisorRestart {
266 module_id: String,
267 #[serde(default, skip_serializing_if = "Option::is_none")]
277 drain_timeout_ms: Option<u64>,
278 },
279 #[serde(rename = "supervisor.swap")]
294 SupervisorSwap {
295 module_id: String,
296 #[serde(default, skip_serializing_if = "Option::is_none")]
299 ready_timeout_ms: Option<u64>,
300 },
301 #[serde(rename = "supervisor.reload")]
302 SupervisorReload { module_id: String },
303 #[serde(rename = "supervisor.rescan")]
304 SupervisorRescan {
305 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
325 preview: bool,
326 },
327 #[serde(rename = "supervisor.rescan_checked")]
351 SupervisorRescanChecked {
352 preview: bool,
353 #[serde(default, skip_serializing_if = "Option::is_none")]
354 candidate: Option<String>,
355 #[serde(default, skip_serializing_if = "Option::is_none")]
356 expect: Option<RescanExpect>,
357 },
358 #[serde(rename = "supervisor.release_reserved")]
362 SupervisorReleaseReserved { module_id: String },
363 #[serde(rename = "supervisor.set_enabled")]
364 SupervisorSetEnabled { module_id: String, enabled: bool },
365 #[serde(rename = "supervisor.health_probe")]
366 SupervisorHealthProbe { module_id: String },
367 #[serde(rename = "supervisor.health")]
368 SupervisorHealth {},
369 #[serde(rename = "supervisor.routes")]
382 SupervisorRoutes {
383 #[serde(default, skip_serializing_if = "Option::is_none")]
384 module_id: Option<String>,
385 },
386 #[serde(rename = "supervisor.provenance")]
389 SupervisorProvenance {
390 #[serde(default, skip_serializing_if = "Option::is_none")]
391 module_id: Option<String>,
392 },
393 #[serde(rename = "supervisor.stderr_tail")]
401 SupervisorStderrTail {
402 module_id: String,
403 #[serde(default, skip_serializing_if = "Option::is_none")]
404 max_lines: Option<u32>,
405 #[serde(default, skip_serializing_if = "Option::is_none")]
406 max_bytes: Option<u32>,
407 },
408 #[serde(rename = "supervisor.terminals")]
421 SupervisorTerminals { module_id: String },
422}
423
424#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
426#[serde(tag = "op")]
427pub enum ClientControlResponse {
428 #[serde(rename = "daemon.shutdown_intent")]
429 DaemonShutdownIntent { intent: String, expires_at_ms: u64 },
430 #[serde(rename = "server.describe")]
431 ServerDescribe {
432 protocol_ver: u8,
433 subc_ops: Vec<String>,
434 capabilities: Vec<String>,
435 connected_clients: u64,
436 #[serde(default, skip_serializing_if = "Option::is_none")]
437 counters: Option<serde_json::Value>,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
445 build_git_sha: Option<String>,
446 #[serde(default, skip_serializing_if = "Option::is_none")]
452 build_lock_digest: Option<String>,
453 #[serde(default, skip_serializing_if = "Vec::is_empty")]
457 capability_requirements: Vec<CapabilityRequirementStatus>,
458 #[serde(default, skip_serializing_if = "Option::is_none")]
463 machine_id: Option<String>,
464 #[serde(default, skip_serializing_if = "Option::is_none")]
473 config_path: Option<PathBuf>,
474 },
475 #[serde(rename = "catalog.list")]
476 CatalogList {
477 generation: u64,
478 modules: Vec<CatalogEntry>,
479 subc_ops: Vec<String>,
480 },
481 #[serde(rename = "route.open")]
482 RouteOpen {
483 route_channel: u16,
484 route_epoch: u32,
485 },
486 #[serde(rename = "route.poll")]
487 RoutePoll {
488 route_channel: u16,
489 route_epoch: u32,
490 status: Option<String>,
491 live: Option<bool>,
492 },
493 #[serde(rename = "supervisor.list")]
494 SupervisorList {
495 generation: u64,
496 modules: Vec<SupervisorEntry>,
497 },
498 #[serde(rename = "supervisor.spawn_snapshot")]
499 SupervisorSpawnSnapshot {
500 #[serde(flatten)]
501 snapshot: SpawnSnapshot,
502 },
503 #[serde(rename = "supervisor.ack")]
504 SupervisorAck { module_id: String, applied: bool },
505 #[serde(rename = "supervisor.rescan")]
506 SupervisorRescan {
507 #[serde(flatten)]
508 result: SupervisorRescanResult,
509 },
510 #[serde(rename = "supervisor.health_probe")]
511 SupervisorHealthProbe {
512 module_id: String,
513 status: HealthStatus,
514 #[serde(default, skip_serializing_if = "Option::is_none")]
515 detail: Option<String>,
516 #[serde(default, skip_serializing_if = "Option::is_none")]
517 metrics: Option<serde_json::Value>,
518 },
519 #[serde(rename = "supervisor.health")]
520 SupervisorHealth {
521 generation: u64,
522 modules: Vec<SupervisorHealthEntry>,
523 },
524 #[serde(rename = "supervisor.routes")]
525 SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
526 #[serde(rename = "supervisor.provenance")]
527 SupervisorProvenance {
528 daemon: SupervisorDaemonProvenance,
529 modules: Vec<SupervisorModuleProvenance>,
530 },
531 #[serde(rename = "supervisor.stderr_tail")]
532 SupervisorStderrTail {
533 module_id: String,
534 #[serde(flatten)]
535 tail: StderrTail,
536 },
537 #[serde(rename = "supervisor.terminals")]
538 SupervisorTerminals {
539 module_id: String,
540 #[serde(flatten)]
541 terminals: TerminalHistory,
542 },
543}
544
545#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
550#[serde(tag = "op")]
551pub enum ClientControlPush {
552 #[serde(rename = "route.closing")]
553 RouteClosing {
554 module_id: String,
555 #[serde(default)]
558 channels: Vec<u16>,
559 reason: RouteCloseReason,
560 },
561 #[serde(rename = "route.closed")]
562 RouteClosed {
563 module_id: String,
564 #[serde(default)]
567 channels: Vec<u16>,
568 reason: RouteCloseReason,
569 drained: bool,
571 abandoned: u32,
574 #[serde(default)]
576 excluded_subscriptions: u32,
577 #[serde(default, skip_serializing_if = "Option::is_none")]
583 terminal: Option<bool>,
584 },
585}
586
587#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
589pub struct SpawnCursor {
590 pub daemon_incarnation: String,
591 pub seq: u64,
592}
593
594#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
596pub struct LiveSpawn {
597 pub module_id: String,
598 pub spawn_generation: u64,
599 pub pid: u32,
600 pub spawned_at_ms: u64,
601}
602
603#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
605pub struct SpawnSnapshot {
606 pub cursor: SpawnCursor,
607 pub ring_bound: u64,
609 pub live: Vec<LiveSpawn>,
610}
611
612#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
614#[serde(rename_all = "snake_case")]
615pub enum SpawnEventKind {
616 Spawned,
617 Exited,
618}
619
620#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
626pub struct SpawnEvent {
627 pub cursor: SpawnCursor,
628 pub kind: SpawnEventKind,
629 pub module_id: String,
630 pub spawn_generation: u64,
631 pub pid: u32,
632 #[serde(default, skip_serializing_if = "Option::is_none")]
633 pub exit_code: Option<i32>,
634 #[serde(default, skip_serializing_if = "Option::is_none")]
635 pub exit_signal: Option<i32>,
636}
637
638#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
640pub struct StderrTail {
641 pub capture: StderrCaptureState,
642 pub entries: Vec<StderrTailEntry>,
643 #[serde(default, skip_serializing_if = "is_zero_u64")]
652 pub dropped_lines: u64,
653}
654
655#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
657pub struct SupervisorRouteModule {
658 pub module_id: String,
659 pub routes: Vec<SupervisorRoute>,
660}
661
662#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
664pub struct SupervisorRoute {
665 pub consumer: SupervisorRouteConsumer,
666 pub age_ms: u64,
668 pub draining: bool,
671 #[serde(default, skip_serializing_if = "Option::is_none")]
677 pub drain_reason: Option<RouteCloseReason>,
678}
679
680#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
682pub struct SupervisorModuleProvenance {
683 pub module_id: String,
684 pub module_declared: ModuleDeclaredProvenance,
685 pub daemon_observed: SupervisorObservedProcess,
686}
687
688#[derive(Debug, Clone, PartialEq)]
690pub enum ModuleDeclaredProvenance {
691 Reported {
692 build: ManifestProvenance,
693 },
694 Unverifiable,
695 Unknown {
698 tag: String,
699 body: OrderedJsonObject,
700 },
701}
702
703#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
708pub struct SupervisorObservedProcess {
709 #[serde(default, skip_serializing_if = "Option::is_none")]
715 pub launch_nonce_source: Option<String>,
716 #[serde(default, skip_serializing_if = "Option::is_none")]
717 pub pid: Option<u32>,
718 #[serde(default, skip_serializing_if = "Option::is_none")]
719 pub spawned_at_ms: Option<u64>,
720 #[serde(default, skip_serializing_if = "Option::is_none")]
721 pub spawned_from: Option<PathBuf>,
722 pub running_image: RunningImageAgreement,
723}
724
725#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
728pub struct PendingReloadVerdict {
729 pub path: ReloadPathAgreement,
730 pub image: RunningImageAgreement,
731 #[serde(default, skip_serializing_if = "Option::is_none")]
732 pub spec: Option<LaunchSpecAgreement>,
733}
734
735#[cfg(test)]
736mod launch_spec_wire_tests {
737 use super::*;
738
739 #[test]
740 fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
741 let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
742 let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
743 assert_eq!(parsed.spec, None);
744 assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
745 let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
746 let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
747 assert!(
748 matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
749 );
750 assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
751 let unavailable = LaunchSpecAgreement::Unavailable {
752 reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
753 };
754 let encoded = serde_json::to_string(&unavailable).unwrap();
755 assert_eq!(
756 encoded,
757 r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
758 );
759 assert_eq!(
760 serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
761 unavailable
762 );
763 }
764}
765
766#[derive(Debug, Clone, PartialEq)]
769pub enum LaunchSpecAgreement {
770 Match,
771 Mismatch,
772 Unavailable {
773 reason: LaunchSpecUnavailableReason,
774 },
775 Unknown {
776 tag: String,
777 body: OrderedJsonObject,
778 },
779}
780
781open_string_enum! {
782 LaunchSpecUnavailableReason {
783 NotRunning => "not_running",
784 SpawnedSpecUnavailable => "spawned_spec_unavailable",
785 }
786}
787
788#[derive(Debug, Clone, PartialEq)]
790pub enum ReloadPathAgreement {
791 Match,
792 Mismatch {
793 configured: PathBuf,
794 spawned_from: PathBuf,
795 },
796 Unavailable {
797 reason: ReloadPathUnavailableReason,
798 },
799 Unknown {
800 tag: String,
801 body: OrderedJsonObject,
802 },
803}
804
805open_string_enum! {
806 ReloadPathUnavailableReason {
808 NotRunning => "not_running",
809 SpawnedPathUnavailable => "spawned_path_unavailable",
810 }
811}
812
813#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
815pub struct SupervisorDaemonProvenance {
816 pub daemon_build: DaemonBuildProvenance,
817 pub daemon_observed: DaemonObservedProcess,
818}
819
820#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
822pub struct DaemonBuildProvenance {
823 #[serde(default, skip_serializing_if = "Option::is_none")]
824 pub build_git_sha: Option<String>,
825 #[serde(default, skip_serializing_if = "Option::is_none")]
826 pub build_lock_digest: Option<String>,
827}
828
829#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
831pub struct DaemonObservedProcess {
832 #[serde(default, skip_serializing_if = "Option::is_none")]
833 pub pid: Option<u32>,
834 #[serde(default, skip_serializing_if = "Option::is_none")]
839 pub started_at_ms: Option<u64>,
840 pub running_image: RunningImageAgreement,
841}
842
843#[derive(Debug, Clone, PartialEq)]
845pub enum RunningImageAgreement {
846 Match {
847 evidence: RunningImageEvidence,
848 },
849 Mismatch {
850 running: RunningImageEvidence,
851 disk: RunningImageEvidence,
852 },
853 Unavailable {
854 reason: RunningImageUnavailableReason,
855 },
856 Unknown {
859 tag: String,
860 body: OrderedJsonObject,
861 },
862}
863
864#[derive(Debug, Clone, PartialEq)]
866pub enum RunningImageEvidence {
867 LinuxProcSha256 {
868 digest: String,
869 },
870 MacosSpawnInode {
871 device: u64,
872 inode: u64,
873 },
874 WindowsSpawnFileId {
876 volume_serial_number: u64,
877 file_id: [u8; 16],
878 },
879 Unknown {
882 tag: String,
883 body: OrderedJsonObject,
884 },
885}
886
887open_string_enum! {
888 RunningImageUnavailableReason {
890 NotRunning => "not_running",
891 UnsupportedPlatform => "unsupported_platform",
892 RunningExecutableUnreadable => "running_executable_unreadable",
893 RunningExecutablePermissionDenied => "running_executable_permission_denied",
894 ProcessHidden => "process_hidden",
895 SpawnedPathUnreadable => "spawned_path_unreadable",
896 HashFailed => "hash_failed",
897 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
898 }
899}
900
901#[derive(Debug, Clone, PartialEq)]
907pub enum SupervisorRouteConsumer {
908 Reserved {
909 module_id: String,
910 },
911 Direct {
912 connection_id: u64,
913 },
914 Unknown {
917 tag: String,
918 body: OrderedJsonObject,
919 },
920}
921
922#[derive(Debug, Clone, PartialEq)]
929pub enum StderrCaptureState {
930 Captured,
933 Incomplete { reason: String },
935 NotCaptured { reason: String },
937 Unknown {
940 tag: String,
941 body: OrderedJsonObject,
942 },
943}
944
945#[derive(Debug, Clone, PartialEq)]
946pub enum StderrTailEntry {
947 Line {
948 text: String,
949 truncated: bool,
954 at_ms: Option<u64>,
958 },
959 ProcessStart,
964 Unknown {
967 tag: String,
968 body: OrderedJsonObject,
969 },
970}
971
972#[derive(Debug, Serialize, Deserialize)]
973#[serde(tag = "status", rename_all = "snake_case")]
974enum ModuleDeclaredProvenanceWire {
975 Reported { build: ManifestProvenance },
976 Unverifiable,
977}
978
979#[derive(Debug, Serialize, Deserialize)]
980#[serde(tag = "status", rename_all = "snake_case")]
981enum RunningImageAgreementWire {
982 Match {
983 evidence: RunningImageEvidence,
984 },
985 Mismatch {
986 running: RunningImageEvidence,
987 disk: RunningImageEvidence,
988 },
989 Unavailable {
990 reason: RunningImageUnavailableReason,
991 },
992}
993
994#[derive(Debug, Serialize, Deserialize)]
995#[serde(tag = "status", rename_all = "snake_case")]
996enum ReloadPathAgreementWire {
997 Match,
998 Mismatch {
999 configured: PathBuf,
1000 spawned_from: PathBuf,
1001 },
1002 Unavailable {
1003 reason: ReloadPathUnavailableReason,
1004 },
1005}
1006
1007#[derive(Debug, Serialize, Deserialize)]
1008#[serde(tag = "status", rename_all = "snake_case")]
1009enum LaunchSpecAgreementWire {
1010 Match,
1011 Mismatch,
1012 Unavailable { reason: LaunchSpecUnavailableReason },
1013}
1014
1015#[derive(Debug, Serialize, Deserialize)]
1016#[serde(tag = "method", rename_all = "snake_case")]
1017enum RunningImageEvidenceWire {
1018 LinuxProcSha256 {
1019 digest: String,
1020 },
1021 MacosSpawnInode {
1022 device: u64,
1023 inode: u64,
1024 },
1025 WindowsSpawnFileId {
1026 volume_serial_number: u64,
1027 file_id: [u8; 16],
1028 },
1029}
1030
1031#[derive(Debug, Serialize, Deserialize)]
1032#[serde(tag = "kind", rename_all = "snake_case")]
1033enum SupervisorRouteConsumerWire {
1034 Reserved { module_id: String },
1035 Direct { connection_id: u64 },
1036}
1037
1038#[derive(Debug, Serialize, Deserialize)]
1039#[serde(tag = "state", rename_all = "snake_case")]
1040enum StderrCaptureStateWire {
1041 Captured,
1042 Incomplete { reason: String },
1043 NotCaptured { reason: String },
1044}
1045
1046#[derive(Debug, Serialize, Deserialize)]
1047#[serde(tag = "status", rename_all = "snake_case")]
1048enum ChildResourceUsageWire {
1049 Measured(ChildResourceReading),
1050 Unavailable {
1051 reason: ChildResourceUnavailableReason,
1052 },
1053}
1054
1055#[derive(Debug, Serialize, Deserialize)]
1056#[serde(tag = "kind", rename_all = "snake_case")]
1057enum StderrTailEntryWire {
1058 Line {
1059 text: String,
1060 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1061 truncated: bool,
1062 #[serde(default, skip_serializing_if = "Option::is_none")]
1065 at_ms: Option<u64>,
1066 },
1067 ProcessStart,
1068}
1069
1070#[derive(Debug, Clone, PartialEq)]
1072pub enum OrderedJsonValue {
1073 Null,
1074 Bool(bool),
1075 Number(serde_json::Number),
1076 String(String),
1077 Array(Vec<Self>),
1078 Object(OrderedJsonObject),
1079}
1080
1081#[derive(Debug, Clone, PartialEq)]
1083pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);
1084
1085impl OrderedJsonObject {
1086 pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
1088 &self.0
1089 }
1090
1091 fn into_value(self) -> serde_json::Value {
1092 serde_json::Value::Object(
1093 self.0
1094 .into_iter()
1095 .map(|(key, value)| (key, value.into_value()))
1096 .collect(),
1097 )
1098 }
1099}
1100
1101impl OrderedJsonValue {
1102 fn into_value(self) -> serde_json::Value {
1103 match self {
1104 Self::Null => serde_json::Value::Null,
1105 Self::Bool(value) => serde_json::Value::Bool(value),
1106 Self::Number(value) => serde_json::Value::Number(value),
1107 Self::String(value) => serde_json::Value::String(value),
1108 Self::Array(values) => {
1109 serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
1110 }
1111 Self::Object(value) => value.into_value(),
1112 }
1113 }
1114}
1115
1116impl Serialize for OrderedJsonValue {
1117 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1118 where
1119 S: Serializer,
1120 {
1121 match self {
1122 Self::Null => serializer.serialize_unit(),
1123 Self::Bool(value) => serializer.serialize_bool(*value),
1124 Self::Number(value) => value.serialize(serializer),
1125 Self::String(value) => serializer.serialize_str(value),
1126 Self::Array(values) => values.serialize(serializer),
1127 Self::Object(value) => value.serialize(serializer),
1128 }
1129 }
1130}
1131
1132impl<'de> Deserialize<'de> for OrderedJsonValue {
1133 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1134 where
1135 D: Deserializer<'de>,
1136 {
1137 struct OrderedValueVisitor;
1138
1139 impl<'de> Visitor<'de> for OrderedValueVisitor {
1140 type Value = OrderedJsonValue;
1141
1142 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1143 formatter.write_str("a JSON value with ordered object members")
1144 }
1145
1146 fn visit_unit<E>(self) -> Result<Self::Value, E>
1147 where
1148 E: serde::de::Error,
1149 {
1150 Ok(OrderedJsonValue::Null)
1151 }
1152
1153 fn visit_none<E>(self) -> Result<Self::Value, E>
1154 where
1155 E: serde::de::Error,
1156 {
1157 Ok(OrderedJsonValue::Null)
1158 }
1159
1160 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1161 where
1162 D: Deserializer<'de>,
1163 {
1164 OrderedJsonValue::deserialize(deserializer)
1165 }
1166
1167 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1168 where
1169 E: serde::de::Error,
1170 {
1171 Ok(OrderedJsonValue::Bool(value))
1172 }
1173
1174 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1175 where
1176 E: serde::de::Error,
1177 {
1178 Ok(OrderedJsonValue::Number(value.into()))
1179 }
1180
1181 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1182 where
1183 E: serde::de::Error,
1184 {
1185 Ok(OrderedJsonValue::Number(value.into()))
1186 }
1187
1188 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1189 where
1190 E: serde::de::Error,
1191 {
1192 serde_json::Number::from_f64(value)
1193 .map(OrderedJsonValue::Number)
1194 .ok_or_else(|| E::custom("non-finite JSON number"))
1195 }
1196
1197 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1198 where
1199 E: serde::de::Error,
1200 {
1201 Ok(OrderedJsonValue::String(value.to_owned()))
1202 }
1203
1204 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1205 where
1206 E: serde::de::Error,
1207 {
1208 Ok(OrderedJsonValue::String(value))
1209 }
1210
1211 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1212 where
1213 A: SeqAccess<'de>,
1214 {
1215 let mut values = Vec::new();
1216 while let Some(value) = sequence.next_element()? {
1217 values.push(value);
1218 }
1219 Ok(OrderedJsonValue::Array(values))
1220 }
1221
1222 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1223 where
1224 A: MapAccess<'de>,
1225 {
1226 let mut entries = Vec::new();
1227 while let Some((key, value)) = map.next_entry()? {
1228 entries.push((key, value));
1229 }
1230 Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
1231 }
1232 }
1233
1234 deserializer.deserialize_any(OrderedValueVisitor)
1235 }
1236}
1237
1238impl Serialize for OrderedJsonObject {
1239 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1240 where
1241 S: Serializer,
1242 {
1243 let mut map = serializer.serialize_map(Some(self.0.len()))?;
1244 for (key, value) in &self.0 {
1245 map.serialize_entry(key, value)?;
1246 }
1247 map.end()
1248 }
1249}
1250
1251impl<'de> Deserialize<'de> for OrderedJsonObject {
1252 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1253 where
1254 D: Deserializer<'de>,
1255 {
1256 struct OrderedObjectVisitor;
1257
1258 impl<'de> Visitor<'de> for OrderedObjectVisitor {
1259 type Value = OrderedJsonObject;
1260
1261 fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1262 formatter.write_str("an object with ordered JSON members")
1263 }
1264
1265 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1266 where
1267 A: MapAccess<'de>,
1268 {
1269 let mut entries = Vec::new();
1270 while let Some((key, value)) = map.next_entry()? {
1271 entries.push((key, value));
1272 }
1273 Ok(OrderedJsonObject(entries))
1274 }
1275 }
1276
1277 deserializer.deserialize_map(OrderedObjectVisitor)
1278 }
1279}
1280
1281fn read_tagged<'de, D>(
1282 deserializer: D,
1283 field: &'static str,
1284) -> Result<(String, OrderedJsonObject), D::Error>
1285where
1286 D: Deserializer<'de>,
1287{
1288 let body = OrderedJsonObject::deserialize(deserializer)?;
1289 let mut tag = None;
1290 for (key, value) in body.as_entries() {
1291 if key != field {
1292 continue;
1293 }
1294 if tag.is_some() {
1295 return Err(D::Error::custom(format!(
1296 "tagged object has duplicate `{field}` field"
1297 )));
1298 }
1299 let OrderedJsonValue::String(value) = value else {
1300 return Err(D::Error::custom(format!(
1301 "tagged object has no string `{field}` field"
1302 )));
1303 };
1304 tag = Some(value);
1305 }
1306 let Some(tag) = tag else {
1307 return Err(D::Error::custom(format!(
1308 "tagged object has no string `{field}` field"
1309 )));
1310 };
1311 Ok((tag.to_string(), body))
1312}
1313
1314fn read_ordered_tagged(
1315 value: OrderedJsonValue,
1316 field: &'static str,
1317) -> Result<(String, OrderedJsonObject), String> {
1318 let OrderedJsonValue::Object(body) = value else {
1319 return Err(format!("expected tagged object with `{field}` field"));
1320 };
1321 let mut tag = None;
1322 for (key, value) in body.as_entries() {
1323 if key != field {
1324 continue;
1325 }
1326 if tag.is_some() {
1327 return Err(format!("tagged object has duplicate `{field}` field"));
1328 }
1329 let OrderedJsonValue::String(value) = value else {
1330 return Err(format!("tagged object has no string `{field}` field"));
1331 };
1332 tag = Some(value);
1333 }
1334 let Some(tag) = tag else {
1335 return Err(format!("tagged object has no string `{field}` field"));
1336 };
1337 Ok((tag.to_string(), body))
1338}
1339
1340fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
1341 body.as_entries()
1342 .iter()
1343 .find_map(|(key, value)| (key == field).then_some(value))
1344}
1345
1346fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
1347 match ordered_field(body, field) {
1348 Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
1349 Some(_) => Err(format!("tagged object field `{field}` is not a string")),
1350 None => Err(format!("tagged object has no `{field}` field")),
1351 }
1352}
1353
1354fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
1355 let (tag, body) = read_ordered_tagged(value, "method")?;
1356 match tag.as_str() {
1357 "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
1358 digest: ordered_string(&body, "digest")?,
1359 }),
1360 "macos_spawn_inode" => {
1361 let device = ordered_field(&body, "device")
1362 .and_then(|value| match value {
1363 OrderedJsonValue::Number(number) => number.as_u64(),
1364 _ => None,
1365 })
1366 .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
1367 let inode = ordered_field(&body, "inode")
1368 .and_then(|value| match value {
1369 OrderedJsonValue::Number(number) => number.as_u64(),
1370 _ => None,
1371 })
1372 .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
1373 Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
1374 }
1375 "windows_spawn_file_id" => {
1376 let wire: RunningImageEvidenceWire = serde_json::from_value(
1377 serde_json::to_value(&body).map_err(|error| error.to_string())?,
1378 )
1379 .map_err(|error| error.to_string())?;
1380 match wire {
1381 RunningImageEvidenceWire::WindowsSpawnFileId {
1382 volume_serial_number,
1383 file_id,
1384 } => Ok(RunningImageEvidence::WindowsSpawnFileId {
1385 volume_serial_number,
1386 file_id,
1387 }),
1388 _ => unreachable!(),
1389 }
1390 }
1391 _ => Ok(RunningImageEvidence::Unknown { tag, body }),
1392 }
1393}
1394
1395impl Serialize for ModuleDeclaredProvenance {
1396 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1397 where
1398 S: Serializer,
1399 {
1400 match self {
1401 Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
1402 build: build.clone(),
1403 }
1404 .serialize(serializer),
1405 Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
1406 Self::Unknown { body, .. } => body.serialize(serializer),
1407 }
1408 }
1409}
1410
1411impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
1412 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1413 where
1414 D: serde::Deserializer<'de>,
1415 {
1416 let (tag, value) = read_tagged(deserializer, "status")?;
1417 match tag.as_str() {
1418 "reported" => match serde_json::from_value(value.into_value())
1419 .map_err(D::Error::custom)?
1420 {
1421 ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
1422 ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
1423 },
1424 "unverifiable" => {
1425 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1426 ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
1427 ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
1428 }
1429 }
1430 _ => Ok(Self::Unknown { tag, body: value }),
1431 }
1432 }
1433}
1434
1435impl Serialize for RunningImageAgreement {
1436 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1437 where
1438 S: Serializer,
1439 {
1440 match self {
1441 Self::Match { evidence } => RunningImageAgreementWire::Match {
1442 evidence: evidence.clone(),
1443 }
1444 .serialize(serializer),
1445 Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
1446 running: running.clone(),
1447 disk: disk.clone(),
1448 }
1449 .serialize(serializer),
1450 Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
1451 reason: reason.clone(),
1452 }
1453 .serialize(serializer),
1454 Self::Unknown { body, .. } => body.serialize(serializer),
1455 }
1456 }
1457}
1458
1459impl Serialize for ReloadPathAgreement {
1460 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1461 where
1462 S: Serializer,
1463 {
1464 match self {
1465 Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
1466 Self::Mismatch {
1467 configured,
1468 spawned_from,
1469 } => ReloadPathAgreementWire::Mismatch {
1470 configured: configured.clone(),
1471 spawned_from: spawned_from.clone(),
1472 }
1473 .serialize(serializer),
1474 Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
1475 reason: reason.clone(),
1476 }
1477 .serialize(serializer),
1478 Self::Unknown { body, .. } => body.serialize(serializer),
1479 }
1480 }
1481}
1482
1483impl Serialize for LaunchSpecAgreement {
1484 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1485 where
1486 S: Serializer,
1487 {
1488 match self {
1489 Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
1490 Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
1491 Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
1492 reason: reason.clone(),
1493 }
1494 .serialize(serializer),
1495 Self::Unknown { body, .. } => body.serialize(serializer),
1496 }
1497 }
1498}
1499
1500impl<'de> Deserialize<'de> for LaunchSpecAgreement {
1501 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1502 where
1503 D: Deserializer<'de>,
1504 {
1505 let (tag, body) = read_tagged(deserializer, "status")?;
1506 match tag.as_str() {
1507 "match" => Ok(Self::Match),
1508 "mismatch" => Ok(Self::Mismatch),
1509 "unavailable" => match serde_json::from_value(body.into_value())
1510 .map_err(D::Error::custom)?
1511 {
1512 LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1513 _ => unreachable!(),
1514 },
1515 _ => Ok(Self::Unknown { tag, body }),
1516 }
1517 }
1518}
1519
1520impl<'de> Deserialize<'de> for ReloadPathAgreement {
1521 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1522 where
1523 D: Deserializer<'de>,
1524 {
1525 let (tag, body) = read_tagged(deserializer, "status")?;
1526 match tag.as_str() {
1527 "match" => Ok(Self::Match),
1528 "mismatch" => {
1529 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1530 ReloadPathAgreementWire::Mismatch {
1531 configured,
1532 spawned_from,
1533 } => Ok(Self::Mismatch {
1534 configured,
1535 spawned_from,
1536 }),
1537 _ => unreachable!(),
1538 }
1539 }
1540 "unavailable" => match serde_json::from_value(body.into_value())
1541 .map_err(D::Error::custom)?
1542 {
1543 ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
1544 _ => unreachable!(),
1545 },
1546 _ => Ok(Self::Unknown { tag, body }),
1547 }
1548 }
1549}
1550
1551impl<'de> Deserialize<'de> for RunningImageAgreement {
1552 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1553 where
1554 D: serde::Deserializer<'de>,
1555 {
1556 let (tag, value) = read_tagged(deserializer, "status")?;
1557 match tag.as_str() {
1558 "match" => Ok(Self::Match {
1559 evidence: decode_running_image_evidence(
1560 ordered_field(&value, "evidence")
1561 .cloned()
1562 .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
1563 )
1564 .map_err(D::Error::custom)?,
1565 }),
1566 "mismatch" => Ok(Self::Mismatch {
1567 running: decode_running_image_evidence(
1568 ordered_field(&value, "running")
1569 .cloned()
1570 .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
1571 )
1572 .map_err(D::Error::custom)?,
1573 disk: decode_running_image_evidence(
1574 ordered_field(&value, "disk")
1575 .cloned()
1576 .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
1577 )
1578 .map_err(D::Error::custom)?,
1579 }),
1580 "unavailable" => Ok(Self::Unavailable {
1581 reason: serde_json::from_value(
1582 ordered_field(&value, "reason")
1583 .cloned()
1584 .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
1585 .into_value(),
1586 )
1587 .map_err(D::Error::custom)?,
1588 }),
1589 _ => Ok(Self::Unknown { tag, body: value }),
1590 }
1591 }
1592}
1593
1594impl Serialize for ChildResourceUsage {
1595 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1596 where
1597 S: Serializer,
1598 {
1599 match self {
1600 Self::Measured(reading) => {
1601 ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
1602 }
1603 Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
1604 reason: reason.clone(),
1605 }
1606 .serialize(serializer),
1607 Self::Unknown { body, .. } => body.serialize(serializer),
1608 }
1609 }
1610}
1611
1612impl<'de> Deserialize<'de> for ChildResourceUsage {
1613 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1614 where
1615 D: Deserializer<'de>,
1616 {
1617 let (tag, body) = read_tagged(deserializer, "status")?;
1618 match tag.as_str() {
1619 "measured" | "unavailable" => {
1620 match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
1621 ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
1622 ChildResourceUsageWire::Unavailable { reason } => {
1623 Ok(Self::Unavailable { reason })
1624 }
1625 }
1626 }
1627 _ => Ok(Self::Unknown { tag, body }),
1628 }
1629 }
1630}
1631
1632impl Serialize for RunningImageEvidence {
1633 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1634 where
1635 S: Serializer,
1636 {
1637 match self {
1638 Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
1639 digest: digest.clone(),
1640 }
1641 .serialize(serializer),
1642 Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
1643 device: *device,
1644 inode: *inode,
1645 }
1646 .serialize(serializer),
1647 Self::WindowsSpawnFileId {
1648 volume_serial_number,
1649 file_id,
1650 } => RunningImageEvidenceWire::WindowsSpawnFileId {
1651 volume_serial_number: *volume_serial_number,
1652 file_id: *file_id,
1653 }
1654 .serialize(serializer),
1655 Self::Unknown { body, .. } => body.serialize(serializer),
1656 }
1657 }
1658}
1659
1660impl<'de> Deserialize<'de> for RunningImageEvidence {
1661 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1662 where
1663 D: serde::Deserializer<'de>,
1664 {
1665 let (tag, value) = read_tagged(deserializer, "method")?;
1666 match tag.as_str() {
1667 "linux_proc_sha256" => {
1668 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1669 RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
1670 Ok(Self::LinuxProcSha256 { digest })
1671 }
1672 _ => unreachable!(),
1673 }
1674 }
1675 "macos_spawn_inode" => {
1676 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1677 RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
1678 Ok(Self::MacosSpawnInode { device, inode })
1679 }
1680 _ => unreachable!(),
1681 }
1682 }
1683 "windows_spawn_file_id" => {
1684 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1685 RunningImageEvidenceWire::WindowsSpawnFileId {
1686 volume_serial_number,
1687 file_id,
1688 } => Ok(Self::WindowsSpawnFileId {
1689 volume_serial_number,
1690 file_id,
1691 }),
1692 _ => unreachable!(),
1693 }
1694 }
1695 _ => Ok(Self::Unknown { tag, body: value }),
1696 }
1697 }
1698}
1699
1700impl Serialize for SupervisorRouteConsumer {
1701 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1702 where
1703 S: Serializer,
1704 {
1705 match self {
1706 Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
1707 module_id: module_id.clone(),
1708 }
1709 .serialize(serializer),
1710 Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
1711 connection_id: *connection_id,
1712 }
1713 .serialize(serializer),
1714 Self::Unknown { body, .. } => body.serialize(serializer),
1715 }
1716 }
1717}
1718
1719impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
1720 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1721 where
1722 D: serde::Deserializer<'de>,
1723 {
1724 let (tag, value) = read_tagged(deserializer, "kind")?;
1725 match tag.as_str() {
1726 "reserved" => {
1727 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1728 SupervisorRouteConsumerWire::Reserved { module_id } => {
1729 Ok(Self::Reserved { module_id })
1730 }
1731 _ => unreachable!(),
1732 }
1733 }
1734 "direct" => {
1735 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1736 SupervisorRouteConsumerWire::Direct { connection_id } => {
1737 Ok(Self::Direct { connection_id })
1738 }
1739 _ => unreachable!(),
1740 }
1741 }
1742 _ => Ok(Self::Unknown { tag, body: value }),
1743 }
1744 }
1745}
1746
1747impl Serialize for StderrCaptureState {
1748 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1749 where
1750 S: Serializer,
1751 {
1752 match self {
1753 Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
1754 Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
1755 reason: reason.clone(),
1756 }
1757 .serialize(serializer),
1758 Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
1759 reason: reason.clone(),
1760 }
1761 .serialize(serializer),
1762 Self::Unknown { body, .. } => body.serialize(serializer),
1763 }
1764 }
1765}
1766
1767impl<'de> Deserialize<'de> for StderrCaptureState {
1768 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1769 where
1770 D: serde::Deserializer<'de>,
1771 {
1772 let (tag, value) = read_tagged(deserializer, "state")?;
1773 match tag.as_str() {
1774 "captured" => {
1775 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1776 StderrCaptureStateWire::Captured => Ok(Self::Captured),
1777 _ => unreachable!(),
1778 }
1779 }
1780 "incomplete" => match serde_json::from_value(value.into_value())
1781 .map_err(D::Error::custom)?
1782 {
1783 StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
1784 _ => unreachable!(),
1785 },
1786 "not_captured" => match serde_json::from_value(value.into_value())
1787 .map_err(D::Error::custom)?
1788 {
1789 StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
1790 _ => unreachable!(),
1791 },
1792 _ => Ok(Self::Unknown { tag, body: value }),
1793 }
1794 }
1795}
1796
1797impl Serialize for StderrTailEntry {
1798 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1799 where
1800 S: Serializer,
1801 {
1802 match self {
1803 Self::Line {
1804 text,
1805 truncated,
1806 at_ms,
1807 } => StderrTailEntryWire::Line {
1808 text: text.clone(),
1809 truncated: *truncated,
1810 at_ms: *at_ms,
1811 }
1812 .serialize(serializer),
1813 Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
1814 Self::Unknown { body, .. } => body.serialize(serializer),
1815 }
1816 }
1817}
1818
1819impl<'de> Deserialize<'de> for StderrTailEntry {
1820 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1821 where
1822 D: serde::Deserializer<'de>,
1823 {
1824 let (tag, value) = read_tagged(deserializer, "kind")?;
1825 match tag.as_str() {
1826 "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1827 StderrTailEntryWire::Line {
1828 text,
1829 truncated,
1830 at_ms,
1831 } => Ok(Self::Line {
1832 text,
1833 truncated,
1834 at_ms,
1835 }),
1836 _ => unreachable!(),
1837 },
1838 "process_start" => {
1839 match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
1840 StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
1841 _ => unreachable!(),
1842 }
1843 }
1844 _ => Ok(Self::Unknown { tag, body: value }),
1845 }
1846 }
1847}
1848
1849fn is_zero_u64(value: &u64) -> bool {
1850 *value == 0
1851}
1852
1853fn default_true() -> bool {
1854 true
1855}
1856
1857#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1859pub struct TerminalHistory {
1860 pub daemon_started_at_ms: u64,
1862 pub entries: Vec<TerminalEntry>,
1863 #[serde(default, skip_serializing_if = "is_zero_u64")]
1866 pub dropped: u64,
1867 #[serde(default, skip_serializing_if = "is_zero_u64")]
1870 pub journal_skipped_lines: u64,
1871 #[serde(default, skip_serializing_if = "is_zero_u64")]
1873 pub journal_read_errors: u64,
1874 #[serde(default, skip_serializing_if = "is_zero_u64")]
1876 pub journal_write_failures: u64,
1877}
1878
1879#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1881pub struct TerminalEntry {
1882 #[serde(default, skip_serializing_if = "Option::is_none")]
1885 pub daemon_incarnation: Option<String>,
1886 #[serde(default, skip_serializing_if = "Option::is_none")]
1887 pub exit_code: Option<i32>,
1888 #[serde(default, skip_serializing_if = "Option::is_none")]
1889 pub exit_signal: Option<i32>,
1890 pub at_ms: u64,
1891 pub disposition: TerminalDisposition,
1892 #[serde(default, skip_serializing_if = "Option::is_none")]
1896 pub exit_kind: Option<TerminalExitKind>,
1897 #[serde(default, skip_serializing_if = "Option::is_none")]
1904 pub disposition_detail: Option<String>,
1905}
1906
1907#[derive(Debug, Clone, PartialEq, Eq)]
1912pub enum TerminalExitKind {
1913 Clean,
1914 Crash,
1915 DeliberateSeverance,
1916 Unknown(String),
1917}
1918
1919impl TerminalExitKind {
1920 fn wire_name(&self) -> &str {
1921 match self {
1922 Self::Clean => "clean",
1923 Self::Crash => "crash",
1924 Self::DeliberateSeverance => "deliberate_severance",
1925 Self::Unknown(value) => value,
1926 }
1927 }
1928}
1929
1930impl Serialize for TerminalExitKind {
1931 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1932 where
1933 S: serde::Serializer,
1934 {
1935 serializer.serialize_str(self.wire_name())
1936 }
1937}
1938
1939impl<'de> Deserialize<'de> for TerminalExitKind {
1940 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1941 where
1942 D: serde::Deserializer<'de>,
1943 {
1944 let value = String::deserialize(deserializer)?;
1945 Ok(match value.as_str() {
1946 "clean" => Self::Clean,
1947 "crash" => Self::Crash,
1948 "deliberate_severance" => Self::DeliberateSeverance,
1949 _ => Self::Unknown(value),
1950 })
1951 }
1952}
1953
1954open_string_enum! {
1955 TerminalDisposition {
1957 Stopped => "stopped",
1958 Disabled => "disabled",
1959 Failed => "failed",
1960 Restarting => "restarting",
1961 DaemonShutdown => "daemon_shutdown",
1966 }
1967}
1968
1969#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1970#[serde(rename_all = "snake_case")]
1971pub enum PollKind {
1972 Status,
1973 Liveness,
1974}
1975
1976#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1988#[non_exhaustive]
1989pub struct CatalogEntry {
1990 pub module_id: String,
1991 #[serde(default = "default_true")]
2002 pub ready: bool,
2003 #[serde(default, skip_serializing_if = "Option::is_none")]
2007 pub not_ready: Option<NotReadyReason>,
2008 #[serde(default, skip_serializing_if = "Option::is_none")]
2029 pub module_version: Option<String>,
2030 pub roles: Vec<ProviderRole>,
2031 pub control_ops: Vec<String>,
2032 #[serde(default, skip_serializing_if = "Option::is_none")]
2037 pub capabilities: Option<CapabilityDeclarations>,
2038 #[serde(default, skip_serializing_if = "Option::is_none")]
2041 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2042 #[serde(default, skip_serializing_if = "Option::is_none")]
2046 pub events: Option<Vec<EventDeclaration>>,
2047 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2050 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2051 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2054 pub operation_payload: BTreeMap<String, OperationPayload>,
2055 #[serde(default, skip_serializing_if = "Option::is_none")]
2061 pub flow_operations: Option<Vec<String>>,
2062 #[serde(default, skip_serializing_if = "Option::is_none")]
2068 pub confirm_operations: Option<Vec<String>>,
2069 #[serde(default, skip_serializing_if = "Option::is_none")]
2072 pub rich_ui: Option<RichUiDescriptor>,
2073 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2076 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2077 #[serde(default, skip_serializing_if = "is_false")]
2080 pub nonce_verified: bool,
2081}
2082
2083impl CatalogEntry {
2084 #[must_use]
2086 pub fn new(
2087 module_id: impl Into<String>,
2088 roles: Vec<ProviderRole>,
2089 control_ops: Vec<String>,
2090 ) -> Self {
2091 Self {
2092 module_id: module_id.into(),
2093 ready: default_true(),
2094 not_ready: None,
2095 module_version: None,
2096 roles,
2097 control_ops,
2098 capabilities: None,
2099 self_signals: None,
2100 events: None,
2101 operation_delivery: BTreeMap::new(),
2102 operation_payload: BTreeMap::new(),
2103 flow_operations: None,
2104 confirm_operations: None,
2105 rich_ui: None,
2106 role_declarations: BTreeMap::new(),
2107 nonce_verified: false,
2108 }
2109 }
2110
2111 #[must_use]
2113 pub fn with_operation_payload(
2114 mut self,
2115 operation_payload: BTreeMap<String, OperationPayload>,
2116 ) -> Self {
2117 self.operation_payload = operation_payload;
2118 self
2119 }
2120
2121 #[must_use]
2124 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2125 self.flow_operations = flow_operations;
2126 self
2127 }
2128
2129 #[must_use]
2132 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2133 self.confirm_operations = confirm_operations;
2134 self
2135 }
2136
2137 #[must_use]
2139 pub fn with_ready(mut self, ready: bool) -> Self {
2140 self.ready = ready;
2141 self
2142 }
2143
2144 #[must_use]
2146 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2147 self.not_ready = not_ready;
2148 self
2149 }
2150
2151 #[must_use]
2153 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2154 self.module_version = module_version;
2155 self
2156 }
2157
2158 #[must_use]
2160 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2161 self.capabilities = capabilities;
2162 self
2163 }
2164
2165 #[must_use]
2167 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2168 self.self_signals = self_signals;
2169 self
2170 }
2171
2172 #[must_use]
2174 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2175 self.events = events;
2176 self
2177 }
2178
2179 #[must_use]
2182 pub fn with_operation_delivery(
2183 mut self,
2184 operation_delivery: BTreeMap<String, OperationDelivery>,
2185 ) -> Self {
2186 self.operation_delivery = operation_delivery;
2187 self
2188 }
2189
2190 #[must_use]
2192 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2193 self.rich_ui = rich_ui;
2194 self
2195 }
2196
2197 #[must_use]
2199 pub fn with_role_declarations(
2200 mut self,
2201 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2202 ) -> Self {
2203 self.role_declarations = role_declarations;
2204 self
2205 }
2206
2207 #[must_use]
2210 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2211 self.nonce_verified = nonce_verified;
2212 self
2213 }
2214}
2215
2216fn is_false(value: &bool) -> bool {
2217 !value
2218}
2219
2220#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2222pub struct NotReadyReason {
2223 pub reason: String,
2228 #[serde(default, skip_serializing_if = "Option::is_none")]
2231 pub capability: Option<String>,
2232}
2233
2234impl NotReadyReason {
2235 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2236 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2237}
2238
2239#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2240pub struct CapabilityRequirementStatus {
2241 pub consumer: String,
2242 pub capability: String,
2243 pub need: String,
2244 pub verdict: String,
2245 pub episode_seq: u64,
2246 pub config_satisfiable: bool,
2247 pub runtime_available: bool,
2248 pub detail: String,
2249}
2250
2251#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2252pub struct SupervisorRescanResult {
2253 pub added: Vec<String>,
2254 pub removed: Vec<String>,
2255 pub changed_pending_reload: Vec<String>,
2256 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2269 pub enabled_changes: Vec<String>,
2270 pub unchanged: u32,
2271 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2279 pub preview: bool,
2280 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2298 pub restart_required: Vec<String>,
2299 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2303 pub capability_warnings: Vec<String>,
2304 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2311 pub module_actions: Vec<RescanModuleAction>,
2312 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2316 pub earlier_pending: Vec<String>,
2317 #[serde(default, skip_serializing_if = "Option::is_none")]
2320 pub expect: Option<RescanExpect>,
2321}
2322
2323#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2339#[serde(rename_all = "snake_case")]
2340pub enum ModuleProtocol {
2341 #[default]
2345 Subc,
2346 None,
2355}
2356
2357#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2369#[non_exhaustive]
2370pub struct SupervisorEntry {
2371 #[serde(default, skip_serializing_if = "Option::is_none")]
2374 pub waiting_for_previous_pid: Option<u32>,
2375 pub module_id: String,
2376 pub state: String,
2377 #[serde(default, skip_serializing_if = "Option::is_none")]
2381 pub next_retry_at_ms: Option<u64>,
2382 pub enabled: bool,
2383 #[serde(default, skip_serializing_if = "Option::is_none")]
2386 pub configured_enabled: Option<bool>,
2387 pub live: bool,
2397 #[serde(default)]
2401 pub protocol: ModuleProtocol,
2402 #[serde(default, skip_serializing_if = "Option::is_none")]
2405 pub launch_nonce_env: Option<bool>,
2406 #[serde(default, skip_serializing_if = "Option::is_none")]
2412 pub launch_nonce_source: Option<String>,
2413 pub health: SupervisorHealthStatus,
2414 #[serde(default, skip_serializing_if = "Option::is_none")]
2417 pub pending_reload: Option<PendingReloadVerdict>,
2418 #[serde(default)]
2424 pub last_probe_ms: Option<u64>,
2425 #[serde(default, skip_serializing_if = "Option::is_none")]
2429 pub last_exit_code: Option<i32>,
2430 #[serde(default, skip_serializing_if = "Option::is_none")]
2434 pub last_exit_signal: Option<i32>,
2435 #[serde(default, skip_serializing_if = "Option::is_none")]
2439 pub last_exit_ms: Option<u64>,
2440 #[serde(default, skip_serializing_if = "Option::is_none")]
2443 pub last_exit_kind: Option<TerminalExitKind>,
2444 #[serde(default, skip_serializing_if = "Option::is_none")]
2461 pub restart_count: Option<u32>,
2462 #[serde(default, skip_serializing_if = "Option::is_none")]
2465 pub max_restarts: Option<u32>,
2466 #[serde(default, skip_serializing_if = "Option::is_none")]
2469 pub lifetime_restarts: Option<u32>,
2470 #[serde(default, skip_serializing_if = "Option::is_none")]
2474 pub spawn_generation: Option<u64>,
2475 #[serde(default, skip_serializing_if = "Option::is_none")]
2485 pub restart_window_secs: Option<u64>,
2486 #[serde(default, skip_serializing_if = "Option::is_none")]
2490 pub drain_timeout_ms: Option<u64>,
2491 #[serde(default, skip_serializing_if = "Option::is_none")]
2494 pub restart_backoff_ms: Option<u64>,
2495 #[serde(default, skip_serializing_if = "Option::is_none")]
2498 pub restart_max_backoff_ms: Option<u64>,
2499 #[serde(default, skip_serializing_if = "Option::is_none")]
2512 pub resources: Option<ChildResourceUsage>,
2513}
2514
2515impl SupervisorEntry {
2516 #[must_use]
2518 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
2519 self.next_retry_at_ms = next_retry_at_ms;
2520 self
2521 }
2522
2523 #[must_use]
2525 pub fn new(
2526 module_id: impl Into<String>,
2527 state: impl Into<String>,
2528 enabled: bool,
2529 live: bool,
2530 health: SupervisorHealthStatus,
2531 ) -> Self {
2532 Self {
2533 module_id: module_id.into(),
2534 state: state.into(),
2535 next_retry_at_ms: None,
2536 waiting_for_previous_pid: None,
2537 enabled,
2538 configured_enabled: None,
2539 live,
2540 protocol: ModuleProtocol::default(),
2541 launch_nonce_env: None,
2542 launch_nonce_source: None,
2543 health,
2544 pending_reload: None,
2545 last_probe_ms: None,
2546 last_exit_code: None,
2547 last_exit_signal: None,
2548 last_exit_ms: None,
2549 last_exit_kind: None,
2550 restart_count: None,
2551 max_restarts: None,
2552 lifetime_restarts: None,
2553 spawn_generation: None,
2554 restart_window_secs: None,
2555 drain_timeout_ms: None,
2556 restart_backoff_ms: None,
2557 restart_max_backoff_ms: None,
2558 resources: None,
2559 }
2560 }
2561
2562 #[must_use]
2564 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2565 self.protocol = protocol;
2566 self
2567 }
2568
2569 #[must_use]
2571 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
2572 self.configured_enabled = configured_enabled;
2573 self
2574 }
2575
2576 #[must_use]
2578 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2579 self.launch_nonce_env = launch_nonce_env;
2580 self
2581 }
2582
2583 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2584 self.launch_nonce_source = source;
2585 self
2586 }
2587
2588 #[must_use]
2589 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2590 self.waiting_for_previous_pid = pid;
2591 self
2592 }
2593
2594 #[must_use]
2596 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2597 self.pending_reload = pending_reload;
2598 self
2599 }
2600
2601 #[must_use]
2603 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2604 self.last_probe_ms = last_probe_ms;
2605 self
2606 }
2607
2608 #[must_use]
2610 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2611 self.last_exit_code = last_exit_code;
2612 self
2613 }
2614
2615 #[must_use]
2617 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2618 self.last_exit_signal = last_exit_signal;
2619 self
2620 }
2621
2622 #[must_use]
2624 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2625 self.last_exit_ms = last_exit_ms;
2626 self
2627 }
2628
2629 #[must_use]
2631 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2632 self.last_exit_kind = last_exit_kind;
2633 self
2634 }
2635
2636 #[must_use]
2638 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2639 self.restart_count = restart_count;
2640 self
2641 }
2642
2643 #[must_use]
2645 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2646 self.max_restarts = max_restarts;
2647 self
2648 }
2649
2650 #[must_use]
2652 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2653 self.lifetime_restarts = lifetime_restarts;
2654 self
2655 }
2656
2657 #[must_use]
2659 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2660 self.spawn_generation = spawn_generation;
2661 self
2662 }
2663
2664 #[must_use]
2666 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2667 self.restart_window_secs = restart_window_secs;
2668 self
2669 }
2670
2671 #[must_use]
2673 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2674 self.drain_timeout_ms = drain_timeout_ms;
2675 self
2676 }
2677
2678 #[must_use]
2680 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2681 self.restart_backoff_ms = restart_backoff_ms;
2682 self
2683 }
2684
2685 #[must_use]
2687 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2688 self.restart_max_backoff_ms = restart_max_backoff_ms;
2689 self
2690 }
2691
2692 #[must_use]
2694 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2695 self.resources = resources;
2696 self
2697 }
2698}
2699
2700#[derive(Debug, Clone, PartialEq)]
2703pub enum ChildResourceUsage {
2704 Measured(ChildResourceReading),
2705 Unavailable {
2706 reason: ChildResourceUnavailableReason,
2707 },
2708 Unknown {
2711 tag: String,
2712 body: OrderedJsonObject,
2713 },
2714}
2715
2716#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2718pub struct ChildResourceReading {
2719 pub memory_bytes: u64,
2722 pub memory_kind: ChildMemoryKind,
2723 #[serde(default, skip_serializing_if = "Option::is_none")]
2726 pub swap_bytes: Option<u64>,
2727 pub cpu_user_ms: u64,
2731 pub cpu_system_ms: u64,
2734}
2735
2736open_string_enum! {
2737 ChildMemoryKind {
2739 PhysFootprint => "phys_footprint",
2743 ResidentSet => "resident_set",
2746 WindowsWorkingSet => "windows_working_set",
2749 }
2750}
2751
2752open_string_enum! {
2753 ChildResourceUnavailableReason {
2755 NotRunning => "not_running",
2757 UnsupportedPlatform => "unsupported_platform",
2759 Unreadable => "unreadable",
2762 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2765 }
2766}
2767
2768#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2769#[serde(rename_all = "snake_case")]
2770pub enum SupervisorHealthStatus {
2771 Ok,
2772 Degraded,
2773 Failing,
2774 Unresponsive,
2775 Unknown,
2776}
2777
2778#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2779pub struct SupervisorHealthEntry {
2780 pub module_id: String,
2781 pub status: SupervisorHealthStatus,
2782 #[serde(default, skip_serializing_if = "Option::is_none")]
2788 pub detail: Option<String>,
2789 #[serde(default, skip_serializing_if = "Option::is_none")]
2794 pub metrics: Option<serde_json::Value>,
2795 pub consecutive_failures: u32,
2796 #[serde(default)]
2799 pub late_answer_count: u64,
2800 #[serde(default, skip_serializing_if = "Option::is_none")]
2802 pub last_late_answer_latency_ms: Option<u64>,
2803 #[serde(default)]
2808 pub last_action: Option<String>,
2809 #[serde(default)]
2812 pub last_action_ms: Option<u64>,
2813 #[serde(default, skip_serializing_if = "Option::is_none")]
2826 pub last_probe_ms: Option<u64>,
2827}
2828
2829#[cfg(test)]
2830mod tests {
2831 #[test]
2832 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
2833 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
2834 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
2835 assert_eq!(decoded.configured_enabled, None);
2836 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
2837 }
2838
2839 #[test]
2840 fn configured_enabled_values_round_trip_in_list() {
2841 for enabled in [false, true] {
2842 let entry = SupervisorEntry::new(
2843 "provider",
2844 "running",
2845 true,
2846 true,
2847 SupervisorHealthStatus::Unknown,
2848 )
2849 .with_configured_enabled(Some(enabled));
2850 let entry_json = serde_json::to_value(&entry).unwrap();
2851 assert_eq!(entry_json["configured_enabled"], enabled);
2852 assert_eq!(
2853 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
2854 entry
2855 );
2856 }
2857 }
2858
2859 #[test]
2860 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2861 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2862 volume_serial_number: u64::MAX,
2863 file_id: [
2864 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2865 ],
2866 };
2867 let agreement = super::RunningImageAgreement::Match { evidence };
2868 let encoded = serde_json::to_string(&agreement).unwrap();
2869 assert!(encoded.contains("windows_spawn_file_id"));
2870 assert_eq!(
2871 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
2872 agreement
2873 );
2874 }
2875
2876 #[test]
2877 fn unix_running_image_evidence_keeps_original_wire_bytes() {
2878 assert_eq!(
2879 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
2880 device: 7,
2881 inode: 11
2882 })
2883 .unwrap(),
2884 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
2885 );
2886 assert_eq!(
2887 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
2888 digest: "abc".to_owned()
2889 })
2890 .unwrap(),
2891 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
2892 );
2893 }
2894 use super::*;
2895 use subc_protocol::{BindIdentity, RouteTarget};
2896
2897 #[test]
2898 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
2899 let entry = TerminalEntry {
2900 daemon_incarnation: Some("daemon-before-restart".into()),
2901 exit_code: Some(1),
2902 exit_signal: None,
2903 at_ms: 1_700_000_000_123,
2904 disposition: TerminalDisposition::Restarting,
2905 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
2906 disposition_detail: None,
2907 };
2908 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
2909 assert_eq!(
2910 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
2911 ["exit_kind"],
2912 "deliberate_severance"
2913 );
2914
2915 #[derive(serde::Deserialize)]
2916 struct LegacyTerminalEntry {
2917 exit_code: Option<i32>,
2918 exit_signal: Option<i32>,
2919 at_ms: u64,
2920 disposition: TerminalDisposition,
2921 }
2922
2923 let decoded: LegacyTerminalEntry =
2924 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
2925 assert_eq!(decoded.exit_code, Some(1));
2926 assert_eq!(decoded.exit_signal, None);
2927 assert_eq!(decoded.at_ms, 1_700_000_000_123);
2928 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
2929
2930 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
2931 let future: TerminalEntry =
2932 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
2933 assert_eq!(
2934 future.exit_kind,
2935 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
2936 );
2937 }
2938
2939 #[test]
2940 fn terminal_incarnation_is_optional_for_older_daemons() {
2941 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
2942 "at_ms": 123,
2943 "disposition": "stopped"
2944 }))
2945 .unwrap();
2946 let encoded = serde_json::to_value(&entry).unwrap();
2947 assert_eq!(
2948 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
2949 (None, None)
2950 );
2951 }
2952
2953 #[test]
2954 fn route_poll_uses_kind_field() {
2955 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
2956 route_channel: 7,
2957 route_epoch: 11,
2958 kind: PollKind::Status,
2959 })
2960 .unwrap();
2961
2962 assert_eq!(body["op"], "route.poll");
2963 assert_eq!(body["route_epoch"], 11);
2964 assert_eq!(body["kind"], "status");
2965 assert!(body.get("op").is_some());
2966 }
2967
2968 #[test]
2969 fn route_open_is_internally_tagged() {
2970 let request = ClientControlRequest::RouteOpen {
2971 target: RouteTarget::ToolProvider {
2972 module_id: "aft".to_string(),
2973 },
2974 identity: BindIdentity::new("/tmp/project", "opencode", "session-1"),
2975 consumer_identity: None,
2976 consumer_capabilities: None,
2977 role_versions: None,
2978 admission_facts: None,
2979 scope: None,
2980 };
2981
2982 let body = serde_json::to_value(request).unwrap();
2983 assert_eq!(body["op"], "route.open");
2984 assert_eq!(body["target"]["kind"], "tool_provider");
2985 assert!(body.get("consumer_identity").is_none());
2986 assert!(body.get("consumer_capabilities").is_none());
2987 assert!(body.get("role_versions").is_none());
2988 }
2989
2990 #[test]
2991 fn route_open_without_optional_fields_still_decodes() {
2992 let body = serde_json::json!({
2993 "op": "route.open",
2994 "target": { "kind": "tool_provider", "module_id": "aft" },
2995 "identity": {
2996 "project_root": "/tmp/project",
2997 "harness": "opencode",
2998 "session": "session-1"
2999 }
3000 });
3001
3002 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3003 let ClientControlRequest::RouteOpen {
3004 consumer_identity,
3005 consumer_capabilities,
3006 role_versions,
3007 admission_facts,
3008 ..
3009 } = decoded
3010 else {
3011 panic!("decoded wrong request variant");
3012 };
3013 assert_eq!(consumer_identity, None);
3014 assert_eq!(consumer_capabilities, None);
3015 assert_eq!(role_versions, None);
3016 assert_eq!(admission_facts, None);
3017 }
3018
3019 #[test]
3020 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3021 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3022 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3023 match decoded {
3024 ClientControlPush::RouteClosed {
3025 excluded_subscriptions,
3026 terminal,
3027 ..
3028 } => {
3029 assert_eq!(excluded_subscriptions, 0);
3030 assert_eq!(terminal, None);
3031 }
3032 other => panic!("unexpected push: {other:?}"),
3033 }
3034 assert!(!serde_json::to_string(&decoded)
3035 .unwrap()
3036 .contains("terminal"));
3037 }
3038
3039 #[test]
3040 fn old_route_closed_decoder_ignores_new_terminal_field() {
3041 #[derive(serde::Deserialize)]
3042 #[serde(tag = "op")]
3043 enum LegacyClientControlPush {
3044 #[serde(rename = "route.closed")]
3045 RouteClosed {
3046 module_id: String,
3047 reason: RouteCloseReason,
3048 drained: bool,
3049 abandoned: u32,
3050 },
3051 }
3052
3053 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3054 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3055 match decoded {
3056 LegacyClientControlPush::RouteClosed {
3057 module_id,
3058 reason,
3059 drained,
3060 abandoned,
3061 } => {
3062 assert_eq!(module_id, "aft-tools");
3063 assert_eq!(reason, RouteCloseReason::Crash);
3064 assert!(!drained);
3065 assert_eq!(abandoned, 0);
3066 }
3067 }
3068 }
3069
3070 #[test]
3071 fn supervisor_routes_is_a_control_plane_request() {
3072 let body = serde_json::json!({
3073 "op": "supervisor.routes",
3074 "module_id": "aft"
3075 });
3076
3077 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3078 assert_eq!(serde_json::to_value(request).unwrap(), body);
3079 }
3080
3081 #[test]
3082 fn diagnostic_string_enums_retain_unknown_wire_values() {
3083 let reason: RunningImageUnavailableReason =
3084 serde_json::from_str("\"future_reason\"").unwrap();
3085 let disposition: TerminalDisposition =
3086 serde_json::from_str("\"future_disposition\"").unwrap();
3087
3088 assert_eq!(
3089 reason,
3090 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3091 );
3092 assert_eq!(
3093 disposition,
3094 TerminalDisposition::Unknown("future_disposition".to_string())
3095 );
3096 }
3097
3098 #[test]
3099 fn diagnostic_string_enums_preserve_existing_wire_names() {
3100 let names = [
3101 (RunningImageUnavailableReason::NotRunning, "not_running"),
3102 (
3103 RunningImageUnavailableReason::UnsupportedPlatform,
3104 "unsupported_platform",
3105 ),
3106 (
3107 RunningImageUnavailableReason::RunningExecutableUnreadable,
3108 "running_executable_unreadable",
3109 ),
3110 (
3111 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3112 "running_executable_permission_denied",
3113 ),
3114 (
3115 RunningImageUnavailableReason::ProcessHidden,
3116 "process_hidden",
3117 ),
3118 (
3119 RunningImageUnavailableReason::SpawnedPathUnreadable,
3120 "spawned_path_unreadable",
3121 ),
3122 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3123 (
3124 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3125 "process_identity_unconfirmed",
3126 ),
3127 ];
3128 for (value, expected) in names {
3129 let wire = serde_json::to_string(&value).unwrap();
3130 assert_eq!(wire, format!("\"{expected}\""));
3131 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3132 assert_eq!(decoded, value);
3133 }
3134
3135 for (value, expected) in [
3136 (TerminalDisposition::Stopped, "stopped"),
3137 (TerminalDisposition::Disabled, "disabled"),
3138 (TerminalDisposition::Failed, "failed"),
3139 (TerminalDisposition::Restarting, "restarting"),
3140 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3141 ] {
3142 let wire = serde_json::to_string(&value).unwrap();
3143 assert_eq!(wire, format!("\"{expected}\""));
3144 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3145 assert_eq!(decoded, value);
3146 }
3147 }
3148
3149 #[test]
3150 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3151 let entry = SupervisorEntry::new(
3152 "waiting-module",
3153 "starting",
3154 true,
3155 false,
3156 SupervisorHealthStatus::Unknown,
3157 );
3158 let old_wire = serde_json::to_value(&entry).unwrap();
3159 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3160 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3161 assert_eq!(decoded.waiting_for_previous_pid, None);
3162 let entry = entry.with_waiting_for_previous_pid(Some(42));
3163 let wire = serde_json::to_value(&entry).unwrap();
3164 assert_eq!(wire["waiting_for_previous_pid"], 42);
3165 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3166 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3167 }
3168
3169 #[test]
3170 fn diagnostic_string_enums_reject_non_string_bodies() {
3171 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3172 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3173 }
3174
3175 #[test]
3176 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3177 let body = serde_json::json!({
3178 "op": "supervisor.provenance",
3179 "daemon": {
3180 "daemon_build": {},
3181 "daemon_observed": {
3182 "running_image": {
3183 "status": "unavailable",
3184 "reason": "not_running"
3185 }
3186 }
3187 },
3188 "modules": [
3189 {
3190 "module_id": "future",
3191 "module_declared": { "status": "unverifiable" },
3192 "daemon_observed": {
3193 "running_image": {
3194 "status": "unavailable",
3195 "reason": "future_reason"
3196 }
3197 }
3198 },
3199 {
3200 "module_id": "healthy-a",
3201 "module_declared": { "status": "unverifiable" },
3202 "daemon_observed": {
3203 "running_image": {
3204 "status": "match",
3205 "evidence": {
3206 "method": "linux_proc_sha256",
3207 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3208 }
3209 }
3210 }
3211 },
3212 {
3213 "module_id": "healthy-b",
3214 "module_declared": { "status": "unverifiable" },
3215 "daemon_observed": {
3216 "running_image": {
3217 "status": "unavailable",
3218 "reason": "unsupported_platform"
3219 }
3220 }
3221 }
3222 ]
3223 });
3224
3225 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3226 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3227 panic!("decoded wrong response variant");
3228 };
3229 assert_eq!(modules.len(), 3);
3230 assert_eq!(modules[0].module_id, "future");
3231 assert_eq!(
3232 modules[0].daemon_observed.running_image,
3233 RunningImageAgreement::Unavailable {
3234 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3235 }
3236 );
3237 assert_eq!(modules[1].module_id, "healthy-a");
3238 assert_eq!(modules[2].module_id, "healthy-b");
3239 }
3240
3241 #[test]
3242 fn tagged_unknown_values_retain_tag_and_body() {
3243 macro_rules! assert_unknown_round_trip {
3244 ($ty:ident, $field:literal, $value:expr) => {
3245 let value = $value;
3246 let wire = serde_json::to_string(&value).unwrap();
3247 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3248 match decoded {
3249 $ty::Unknown { tag, body } => {
3250 assert_eq!(tag, value[$field].as_str().unwrap());
3251 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3252 }
3253 _ => panic!("decoded known variant"),
3254 }
3255 };
3256 }
3257
3258 assert_unknown_round_trip!(
3259 ModuleDeclaredProvenance,
3260 "status",
3261 serde_json::json!({"status": "future", "build": {"version": 7}})
3262 );
3263 assert_unknown_round_trip!(
3264 RunningImageAgreement,
3265 "status",
3266 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3267 );
3268 assert_unknown_round_trip!(
3269 RunningImageEvidence,
3270 "method",
3271 serde_json::json!({"method": "future", "digest": "abc"})
3272 );
3273 assert_unknown_round_trip!(
3274 SupervisorRouteConsumer,
3275 "kind",
3276 serde_json::json!({"kind": "future", "module_id": "m"})
3277 );
3278 assert_unknown_round_trip!(
3279 StderrCaptureState,
3280 "state",
3281 serde_json::json!({"state": "future", "reason": "because"})
3282 );
3283 assert_unknown_round_trip!(
3284 StderrTailEntry,
3285 "kind",
3286 serde_json::json!({"kind": "future", "text": "line"})
3287 );
3288 assert_unknown_round_trip!(
3289 ChildResourceUsage,
3290 "status",
3291 serde_json::json!({"status": "future", "memory_bytes": 1})
3292 );
3293 }
3294
3295 #[test]
3296 fn child_resource_usage_round_trips_both_known_states() {
3297 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3298 memory_bytes: 0,
3299 memory_kind: ChildMemoryKind::ResidentSet,
3300 swap_bytes: Some(0),
3301 cpu_user_ms: 0,
3302 cpu_system_ms: 0,
3303 });
3304 let wire = serde_json::to_value(&measured).unwrap();
3305 assert_eq!(
3306 wire,
3307 serde_json::json!({
3308 "status": "measured",
3309 "memory_bytes": 0,
3310 "memory_kind": "resident_set",
3311 "swap_bytes": 0,
3312 "cpu_user_ms": 0,
3313 "cpu_system_ms": 0
3314 })
3315 );
3316 assert_eq!(
3317 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3318 measured
3319 );
3320
3321 let unavailable = ChildResourceUsage::Unavailable {
3322 reason: ChildResourceUnavailableReason::NotRunning,
3323 };
3324 let wire = serde_json::to_value(&unavailable).unwrap();
3325 assert_eq!(
3326 wire,
3327 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3328 );
3329 assert_eq!(
3330 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3331 unavailable
3332 );
3333 }
3334
3335 #[test]
3336 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3337 let stamped: StderrTailEntry = serde_json::from_str(
3341 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3342 )
3343 .unwrap();
3344 assert_eq!(
3345 stamped,
3346 StderrTailEntry::Line {
3347 text: "boom".to_string(),
3348 truncated: true,
3349 at_ms: Some(1_789_801_440_685),
3350 }
3351 );
3352 let unstamped: StderrTailEntry =
3353 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3354 assert_eq!(
3355 unstamped,
3356 StderrTailEntry::Line {
3357 text: "boom".to_string(),
3358 truncated: false,
3359 at_ms: None,
3360 }
3361 );
3362 assert_eq!(
3365 serde_json::to_string(&unstamped).unwrap(),
3366 r#"{"kind":"line","text":"boom"}"#
3367 );
3368 assert_eq!(
3369 serde_json::to_value(&stamped).unwrap()["at_ms"],
3370 serde_json::json!(1_789_801_440_685u64)
3371 );
3372 }
3373
3374 #[test]
3375 fn tagged_unknown_values_round_trip_the_original_json() {
3376 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3377 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3378 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3379 }
3380
3381 #[test]
3382 fn tagged_unknown_values_round_trip_trailing_tag() {
3383 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3384 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3385 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3386
3387 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3388 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3389 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3390 }
3391
3392 #[test]
3393 fn tagged_unknown_values_round_trip_middle_tag() {
3394 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3395 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3396 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3397
3398 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3399 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3400 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3401 }
3402
3403 #[test]
3404 fn tagged_unknown_values_round_trip_deep_payload() {
3405 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3406 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3407 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3408
3409 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3410 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3411 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3412 }
3413
3414 #[test]
3415 fn tagged_unknown_values_reject_non_object_bodies() {
3416 for wire in ["42", r#""future""#, "[]"] {
3417 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3418 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3419 }
3420 }
3421
3422 #[test]
3423 fn duplicate_discriminators_reject_without_panicking() {
3424 assert_eq!(
3425 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3426 .unwrap(),
3427 ModuleDeclaredProvenance::Unverifiable
3428 );
3429 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3430 .unwrap()
3431 {
3432 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3433 _ => panic!("future discriminator decoded as a known variant"),
3434 }
3435
3436 let wires = [
3437 r#"{"status":"reported","status":"unverifiable"}"#,
3438 r#"{"status":"unverifiable","status":"reported"}"#,
3439 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3440 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3441 ];
3442
3443 for wire in wires {
3444 let result =
3445 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3446 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3447 assert!(
3448 result.unwrap().is_err(),
3449 "duplicate discriminator decoded: {wire}"
3450 );
3451 }
3452
3453 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3454 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3455 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3456 assert!(
3457 result.unwrap().is_err(),
3458 "duplicate discriminator decoded: {wire}"
3459 );
3460 }
3461
3462 #[test]
3463 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3464 let known_wire =
3465 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3466 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3467 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3468
3469 for wire in [
3470 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3471 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3472 ] {
3473 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3474 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3475 }
3476
3477 for wire in [
3478 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3479 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3480 ] {
3481 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3482 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3483 }
3484
3485 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3486 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3487 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3488
3489 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3490 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3491 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3492 }
3493
3494 #[test]
3495 fn tagged_unknown_member_does_not_discard_known_siblings() {
3496 let body = serde_json::json!({
3497 "modules": [{
3498 "module_id": "target",
3499 "routes": [
3500 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3501 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3502 ]
3503 }]
3504 });
3505 let decoded: ClientControlResponse = serde_json::from_value(
3506 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3507 )
3508 .unwrap();
3509 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3510 panic!("decoded wrong response variant");
3511 };
3512 assert_eq!(modules[0].routes.len(), 2);
3513 assert_eq!(
3514 modules[0].routes[1].consumer,
3515 SupervisorRouteConsumer::Direct { connection_id: 7 }
3516 );
3517 }
3518}
3519
3520#[cfg(test)]
3521mod launch_nonce_redaction_tests {
3522 use super::*;
3523
3524 const NONCE: &str = "nonce-f00dfeed1234abcd";
3525
3526 fn identity() -> ConsumerIdentity {
3527 ConsumerIdentity {
3528 module_id: "wernicke".to_string(),
3529 launch_nonce: NONCE.to_string(),
3530 }
3531 }
3532
3533 #[test]
3534 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3535 let printed = format!("{:?}", identity());
3536 assert!(printed.contains("wernicke"), "{printed}");
3537 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3538 }
3539
3540 #[test]
3541 fn route_open_request_debug_never_prints_the_nonce() {
3542 let request = ClientControlRequest::RouteOpen {
3543 target: subc_protocol::RouteTarget::ToolProvider {
3544 module_id: "broca".to_string(),
3545 },
3546 identity: subc_protocol::BindIdentity::new(
3547 PathBuf::from("/tmp/project"),
3548 "test".to_string(),
3549 "session".to_string(),
3550 ),
3551 consumer_identity: Some(identity()),
3552 consumer_capabilities: None,
3553 role_versions: None,
3554 admission_facts: None,
3555 scope: None,
3556 };
3557 let printed = format!("{request:?}");
3558 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3559 }
3560}