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