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 pub roles: Vec<ProviderRole>,
2034 pub control_ops: Vec<String>,
2035 #[serde(default, skip_serializing_if = "Option::is_none")]
2040 pub capabilities: Option<CapabilityDeclarations>,
2041 #[serde(default, skip_serializing_if = "Option::is_none")]
2044 pub self_signals: Option<Vec<SelfSignalDeclaration>>,
2045 #[serde(default, skip_serializing_if = "Option::is_none")]
2049 pub events: Option<Vec<EventDeclaration>>,
2050 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2053 pub operation_delivery: BTreeMap<String, OperationDelivery>,
2054 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2057 pub operation_payload: BTreeMap<String, OperationPayload>,
2058 #[serde(default, skip_serializing_if = "Option::is_none")]
2064 pub flow_operations: Option<Vec<String>>,
2065 #[serde(default, skip_serializing_if = "Option::is_none")]
2071 pub confirm_operations: Option<Vec<String>>,
2072 #[serde(default, skip_serializing_if = "Option::is_none")]
2075 pub rich_ui: Option<RichUiDescriptor>,
2076 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2079 pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2080 #[serde(default, skip_serializing_if = "is_false")]
2083 pub nonce_verified: bool,
2084}
2085
2086impl CatalogEntry {
2087 #[must_use]
2089 pub fn new(
2090 module_id: impl Into<String>,
2091 roles: Vec<ProviderRole>,
2092 control_ops: Vec<String>,
2093 ) -> Self {
2094 Self {
2095 module_id: module_id.into(),
2096 ready: default_true(),
2097 not_ready: None,
2098 module_version: None,
2099 roles,
2100 control_ops,
2101 capabilities: None,
2102 self_signals: None,
2103 events: None,
2104 operation_delivery: BTreeMap::new(),
2105 operation_payload: BTreeMap::new(),
2106 flow_operations: None,
2107 confirm_operations: None,
2108 rich_ui: None,
2109 role_declarations: BTreeMap::new(),
2110 nonce_verified: false,
2111 }
2112 }
2113
2114 #[must_use]
2116 pub fn with_operation_payload(
2117 mut self,
2118 operation_payload: BTreeMap<String, OperationPayload>,
2119 ) -> Self {
2120 self.operation_payload = operation_payload;
2121 self
2122 }
2123
2124 #[must_use]
2127 pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
2128 self.flow_operations = flow_operations;
2129 self
2130 }
2131
2132 #[must_use]
2135 pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
2136 self.confirm_operations = confirm_operations;
2137 self
2138 }
2139
2140 #[must_use]
2142 pub fn with_ready(mut self, ready: bool) -> Self {
2143 self.ready = ready;
2144 self
2145 }
2146
2147 #[must_use]
2149 pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
2150 self.not_ready = not_ready;
2151 self
2152 }
2153
2154 #[must_use]
2156 pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
2157 self.module_version = module_version;
2158 self
2159 }
2160
2161 #[must_use]
2163 pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
2164 self.capabilities = capabilities;
2165 self
2166 }
2167
2168 #[must_use]
2170 pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
2171 self.self_signals = self_signals;
2172 self
2173 }
2174
2175 #[must_use]
2177 pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
2178 self.events = events;
2179 self
2180 }
2181
2182 #[must_use]
2185 pub fn with_operation_delivery(
2186 mut self,
2187 operation_delivery: BTreeMap<String, OperationDelivery>,
2188 ) -> Self {
2189 self.operation_delivery = operation_delivery;
2190 self
2191 }
2192
2193 #[must_use]
2195 pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
2196 self.rich_ui = rich_ui;
2197 self
2198 }
2199
2200 #[must_use]
2202 pub fn with_role_declarations(
2203 mut self,
2204 role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
2205 ) -> Self {
2206 self.role_declarations = role_declarations;
2207 self
2208 }
2209
2210 #[must_use]
2213 pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
2214 self.nonce_verified = nonce_verified;
2215 self
2216 }
2217}
2218
2219fn is_false(value: &bool) -> bool {
2220 !value
2221}
2222
2223#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2225pub struct NotReadyReason {
2226 pub reason: String,
2231 #[serde(default, skip_serializing_if = "Option::is_none")]
2234 pub capability: Option<String>,
2235}
2236
2237impl NotReadyReason {
2238 pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
2239 pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
2240}
2241
2242#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2243pub struct CapabilityRequirementStatus {
2244 pub consumer: String,
2245 pub capability: String,
2246 pub need: String,
2247 pub verdict: String,
2248 pub episode_seq: u64,
2249 pub config_satisfiable: bool,
2250 pub runtime_available: bool,
2251 pub detail: String,
2252}
2253
2254#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2255pub struct SupervisorRescanResult {
2256 pub added: Vec<String>,
2257 pub removed: Vec<String>,
2258 pub changed_pending_reload: Vec<String>,
2259 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2272 pub enabled_changes: Vec<String>,
2273 pub unchanged: u32,
2274 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2282 pub preview: bool,
2283 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2301 pub restart_required: Vec<String>,
2302 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2306 pub capability_warnings: Vec<String>,
2307 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2314 pub module_actions: Vec<RescanModuleAction>,
2315 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2319 pub earlier_pending: Vec<String>,
2320 #[serde(default, skip_serializing_if = "Option::is_none")]
2323 pub expect: Option<RescanExpect>,
2324}
2325
2326#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
2342#[serde(rename_all = "snake_case")]
2343pub enum ModuleProtocol {
2344 #[default]
2348 Subc,
2349 None,
2358}
2359
2360#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2372#[non_exhaustive]
2373pub struct SupervisorEntry {
2374 #[serde(default, skip_serializing_if = "Option::is_none")]
2377 pub waiting_for_previous_pid: Option<u32>,
2378 pub module_id: String,
2379 pub state: String,
2380 #[serde(default, skip_serializing_if = "Option::is_none")]
2384 pub next_retry_at_ms: Option<u64>,
2385 pub enabled: bool,
2386 #[serde(default, skip_serializing_if = "Option::is_none")]
2389 pub configured_enabled: Option<bool>,
2390 pub live: bool,
2400 #[serde(default)]
2404 pub protocol: ModuleProtocol,
2405 #[serde(default, skip_serializing_if = "Option::is_none")]
2408 pub launch_nonce_env: Option<bool>,
2409 #[serde(default, skip_serializing_if = "Option::is_none")]
2415 pub launch_nonce_source: Option<String>,
2416 pub health: SupervisorHealthStatus,
2417 #[serde(default, skip_serializing_if = "Option::is_none")]
2420 pub pending_reload: Option<PendingReloadVerdict>,
2421 #[serde(default)]
2427 pub last_probe_ms: Option<u64>,
2428 #[serde(default, skip_serializing_if = "Option::is_none")]
2432 pub last_exit_code: Option<i32>,
2433 #[serde(default, skip_serializing_if = "Option::is_none")]
2437 pub last_exit_signal: Option<i32>,
2438 #[serde(default, skip_serializing_if = "Option::is_none")]
2442 pub last_exit_ms: Option<u64>,
2443 #[serde(default, skip_serializing_if = "Option::is_none")]
2446 pub last_exit_kind: Option<TerminalExitKind>,
2447 #[serde(default, skip_serializing_if = "Option::is_none")]
2464 pub restart_count: Option<u32>,
2465 #[serde(default, skip_serializing_if = "Option::is_none")]
2468 pub max_restarts: Option<u32>,
2469 #[serde(default, skip_serializing_if = "Option::is_none")]
2472 pub lifetime_restarts: Option<u32>,
2473 #[serde(default, skip_serializing_if = "Option::is_none")]
2477 pub spawn_generation: Option<u64>,
2478 #[serde(default, skip_serializing_if = "Option::is_none")]
2488 pub restart_window_secs: Option<u64>,
2489 #[serde(default, skip_serializing_if = "Option::is_none")]
2493 pub drain_timeout_ms: Option<u64>,
2494 #[serde(default, skip_serializing_if = "Option::is_none")]
2497 pub restart_backoff_ms: Option<u64>,
2498 #[serde(default, skip_serializing_if = "Option::is_none")]
2501 pub restart_max_backoff_ms: Option<u64>,
2502 #[serde(default, skip_serializing_if = "Option::is_none")]
2515 pub resources: Option<ChildResourceUsage>,
2516 #[serde(default, skip_serializing_if = "Option::is_none")]
2519 pub subtree: Option<SubtreeReading>,
2520}
2521
2522impl SupervisorEntry {
2523 #[must_use]
2525 pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
2526 self.next_retry_at_ms = next_retry_at_ms;
2527 self
2528 }
2529
2530 #[must_use]
2532 pub fn new(
2533 module_id: impl Into<String>,
2534 state: impl Into<String>,
2535 enabled: bool,
2536 live: bool,
2537 health: SupervisorHealthStatus,
2538 ) -> Self {
2539 Self {
2540 module_id: module_id.into(),
2541 state: state.into(),
2542 next_retry_at_ms: None,
2543 waiting_for_previous_pid: None,
2544 enabled,
2545 configured_enabled: None,
2546 live,
2547 protocol: ModuleProtocol::default(),
2548 launch_nonce_env: None,
2549 launch_nonce_source: None,
2550 health,
2551 pending_reload: None,
2552 last_probe_ms: None,
2553 last_exit_code: None,
2554 last_exit_signal: None,
2555 last_exit_ms: None,
2556 last_exit_kind: None,
2557 restart_count: None,
2558 max_restarts: None,
2559 lifetime_restarts: None,
2560 spawn_generation: None,
2561 restart_window_secs: None,
2562 drain_timeout_ms: None,
2563 restart_backoff_ms: None,
2564 restart_max_backoff_ms: None,
2565 resources: None,
2566 subtree: None,
2567 }
2568 }
2569
2570 #[must_use]
2572 pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
2573 self.protocol = protocol;
2574 self
2575 }
2576
2577 #[must_use]
2579 pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
2580 self.configured_enabled = configured_enabled;
2581 self
2582 }
2583
2584 #[must_use]
2586 pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
2587 self.launch_nonce_env = launch_nonce_env;
2588 self
2589 }
2590
2591 pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
2592 self.launch_nonce_source = source;
2593 self
2594 }
2595
2596 #[must_use]
2597 pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
2598 self.waiting_for_previous_pid = pid;
2599 self
2600 }
2601
2602 #[must_use]
2604 pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
2605 self.pending_reload = pending_reload;
2606 self
2607 }
2608
2609 #[must_use]
2611 pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
2612 self.last_probe_ms = last_probe_ms;
2613 self
2614 }
2615
2616 #[must_use]
2618 pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
2619 self.last_exit_code = last_exit_code;
2620 self
2621 }
2622
2623 #[must_use]
2625 pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
2626 self.last_exit_signal = last_exit_signal;
2627 self
2628 }
2629
2630 #[must_use]
2632 pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
2633 self.last_exit_ms = last_exit_ms;
2634 self
2635 }
2636
2637 #[must_use]
2639 pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
2640 self.last_exit_kind = last_exit_kind;
2641 self
2642 }
2643
2644 #[must_use]
2646 pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
2647 self.restart_count = restart_count;
2648 self
2649 }
2650
2651 #[must_use]
2653 pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
2654 self.max_restarts = max_restarts;
2655 self
2656 }
2657
2658 #[must_use]
2660 pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
2661 self.lifetime_restarts = lifetime_restarts;
2662 self
2663 }
2664
2665 #[must_use]
2667 pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
2668 self.spawn_generation = spawn_generation;
2669 self
2670 }
2671
2672 #[must_use]
2674 pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
2675 self.restart_window_secs = restart_window_secs;
2676 self
2677 }
2678
2679 #[must_use]
2681 pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
2682 self.drain_timeout_ms = drain_timeout_ms;
2683 self
2684 }
2685
2686 #[must_use]
2688 pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
2689 self.restart_backoff_ms = restart_backoff_ms;
2690 self
2691 }
2692
2693 #[must_use]
2695 pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
2696 self.restart_max_backoff_ms = restart_max_backoff_ms;
2697 self
2698 }
2699
2700 #[must_use]
2702 pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
2703 self.resources = resources;
2704 self
2705 }
2706
2707 #[must_use]
2709 pub fn with_subtree(mut self, subtree: Option<SubtreeReading>) -> Self {
2710 self.subtree = subtree;
2711 self
2712 }
2713}
2714
2715#[derive(Debug, Clone, PartialEq)]
2718pub enum ChildResourceUsage {
2719 Measured(ChildResourceReading),
2720 Unavailable {
2721 reason: ChildResourceUnavailableReason,
2722 },
2723 Unknown {
2726 tag: String,
2727 body: OrderedJsonObject,
2728 },
2729}
2730
2731#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2733pub struct ChildResourceReading {
2734 pub memory_bytes: u64,
2737 pub memory_kind: ChildMemoryKind,
2738 #[serde(default, skip_serializing_if = "Option::is_none")]
2741 pub swap_bytes: Option<u64>,
2742 pub cpu_user_ms: u64,
2746 pub cpu_system_ms: u64,
2749}
2750
2751open_string_enum! {
2752 ChildMemoryKind {
2754 PhysFootprint => "phys_footprint",
2758 ResidentSet => "resident_set",
2761 WindowsWorkingSet => "windows_working_set",
2764 }
2765}
2766
2767open_string_enum! {
2768 ChildResourceUnavailableReason {
2770 NotRunning => "not_running",
2772 UnsupportedPlatform => "unsupported_platform",
2774 Unreadable => "unreadable",
2777 ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
2780 }
2781}
2782
2783#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
2784#[serde(rename_all = "snake_case")]
2785pub enum SupervisorHealthStatus {
2786 Ok,
2787 Degraded,
2788 Failing,
2789 Unresponsive,
2790 Unknown,
2791}
2792
2793#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2794pub struct SupervisorHealthEntry {
2795 pub module_id: String,
2796 pub status: SupervisorHealthStatus,
2797 #[serde(default, skip_serializing_if = "Option::is_none")]
2803 pub detail: Option<String>,
2804 #[serde(default, skip_serializing_if = "Option::is_none")]
2809 pub metrics: Option<serde_json::Value>,
2810 pub consecutive_failures: u32,
2811 #[serde(default)]
2814 pub late_answer_count: u64,
2815 #[serde(default, skip_serializing_if = "Option::is_none")]
2817 pub last_late_answer_latency_ms: Option<u64>,
2818 #[serde(default)]
2823 pub last_action: Option<String>,
2824 #[serde(default)]
2827 pub last_action_ms: Option<u64>,
2828 #[serde(default, skip_serializing_if = "Option::is_none")]
2841 pub last_probe_ms: Option<u64>,
2842}
2843
2844#[cfg(test)]
2845mod tests {
2846 #[test]
2847 fn configured_enabled_omission_preserves_exact_old_list_bytes() {
2848 let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
2849 let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
2850 assert_eq!(decoded.configured_enabled, None);
2851 assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
2852 }
2853
2854 #[test]
2855 fn configured_enabled_values_round_trip_in_list() {
2856 for enabled in [false, true] {
2857 let entry = SupervisorEntry::new(
2858 "provider",
2859 "running",
2860 true,
2861 true,
2862 SupervisorHealthStatus::Unknown,
2863 )
2864 .with_configured_enabled(Some(enabled));
2865 let entry_json = serde_json::to_value(&entry).unwrap();
2866 assert_eq!(entry_json["configured_enabled"], enabled);
2867 assert_eq!(
2868 serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
2869 entry
2870 );
2871 }
2872 }
2873
2874 #[test]
2875 fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
2876 let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
2877 volume_serial_number: u64::MAX,
2878 file_id: [
2879 0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
2880 ],
2881 };
2882 let agreement = super::RunningImageAgreement::Match { evidence };
2883 let encoded = serde_json::to_string(&agreement).unwrap();
2884 assert!(encoded.contains("windows_spawn_file_id"));
2885 assert_eq!(
2886 serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
2887 agreement
2888 );
2889 }
2890
2891 #[test]
2892 fn unix_running_image_evidence_keeps_original_wire_bytes() {
2893 assert_eq!(
2894 serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
2895 device: 7,
2896 inode: 11
2897 })
2898 .unwrap(),
2899 "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
2900 );
2901 assert_eq!(
2902 serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
2903 digest: "abc".to_owned()
2904 })
2905 .unwrap(),
2906 "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
2907 );
2908 }
2909 use super::*;
2910 use subc_protocol::{BindIdentity, RouteTarget};
2911
2912 #[test]
2913 fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
2914 let entry = TerminalEntry {
2915 daemon_incarnation: Some("daemon-before-restart".into()),
2916 exit_code: Some(1),
2917 exit_signal: None,
2918 at_ms: 1_700_000_000_123,
2919 disposition: TerminalDisposition::Restarting,
2920 exit_kind: Some(TerminalExitKind::DeliberateSeverance),
2921 disposition_detail: None,
2922 };
2923 let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
2924 assert_eq!(
2925 serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
2926 ["exit_kind"],
2927 "deliberate_severance"
2928 );
2929
2930 #[derive(serde::Deserialize)]
2931 struct LegacyTerminalEntry {
2932 exit_code: Option<i32>,
2933 exit_signal: Option<i32>,
2934 at_ms: u64,
2935 disposition: TerminalDisposition,
2936 }
2937
2938 let decoded: LegacyTerminalEntry =
2939 serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
2940 assert_eq!(decoded.exit_code, Some(1));
2941 assert_eq!(decoded.exit_signal, None);
2942 assert_eq!(decoded.at_ms, 1_700_000_000_123);
2943 assert_eq!(decoded.disposition, TerminalDisposition::Restarting);
2944
2945 let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
2946 let future: TerminalEntry =
2947 serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
2948 assert_eq!(
2949 future.exit_kind,
2950 Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
2951 );
2952 }
2953
2954 #[test]
2955 fn terminal_incarnation_is_optional_for_older_daemons() {
2956 let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
2957 "at_ms": 123,
2958 "disposition": "stopped"
2959 }))
2960 .unwrap();
2961 let encoded = serde_json::to_value(&entry).unwrap();
2962 assert_eq!(
2963 (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
2964 (None, None)
2965 );
2966 }
2967
2968 #[test]
2969 fn route_poll_uses_kind_field() {
2970 let body = serde_json::to_value(ClientControlRequest::RoutePoll {
2971 route_channel: 7,
2972 route_epoch: 11,
2973 kind: PollKind::Status,
2974 })
2975 .unwrap();
2976
2977 assert_eq!(body["op"], "route.poll");
2978 assert_eq!(body["route_epoch"], 11);
2979 assert_eq!(body["kind"], "status");
2980 assert!(body.get("op").is_some());
2981 }
2982
2983 #[test]
2984 fn route_open_is_internally_tagged() {
2985 let request = ClientControlRequest::RouteOpen {
2986 target: RouteTarget::ToolProvider {
2987 module_id: "aft".to_string(),
2988 },
2989 identity: BindIdentity::new("/tmp/project", "opencode", "session-1"),
2990 consumer_identity: None,
2991 consumer_capabilities: None,
2992 role_versions: None,
2993 admission_facts: None,
2994 scope: None,
2995 };
2996
2997 let body = serde_json::to_value(request).unwrap();
2998 assert_eq!(body["op"], "route.open");
2999 assert_eq!(body["target"]["kind"], "tool_provider");
3000 assert!(body.get("consumer_identity").is_none());
3001 assert!(body.get("consumer_capabilities").is_none());
3002 assert!(body.get("role_versions").is_none());
3003 }
3004
3005 #[test]
3006 fn route_open_without_optional_fields_still_decodes() {
3007 let body = serde_json::json!({
3008 "op": "route.open",
3009 "target": { "kind": "tool_provider", "module_id": "aft" },
3010 "identity": {
3011 "project_root": "/tmp/project",
3012 "harness": "opencode",
3013 "session": "session-1"
3014 }
3015 });
3016
3017 let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
3018 let ClientControlRequest::RouteOpen {
3019 consumer_identity,
3020 consumer_capabilities,
3021 role_versions,
3022 admission_facts,
3023 ..
3024 } = decoded
3025 else {
3026 panic!("decoded wrong request variant");
3027 };
3028 assert_eq!(consumer_identity, None);
3029 assert_eq!(consumer_capabilities, None);
3030 assert_eq!(role_versions, None);
3031 assert_eq!(admission_facts, None);
3032 }
3033
3034 #[test]
3035 fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
3036 let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
3037 let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
3038 match decoded {
3039 ClientControlPush::RouteClosed {
3040 excluded_subscriptions,
3041 terminal,
3042 ..
3043 } => {
3044 assert_eq!(excluded_subscriptions, 0);
3045 assert_eq!(terminal, None);
3046 }
3047 other => panic!("unexpected push: {other:?}"),
3048 }
3049 assert!(!serde_json::to_string(&decoded)
3050 .unwrap()
3051 .contains("terminal"));
3052 }
3053
3054 #[test]
3055 fn old_route_closed_decoder_ignores_new_terminal_field() {
3056 #[derive(serde::Deserialize)]
3057 #[serde(tag = "op")]
3058 enum LegacyClientControlPush {
3059 #[serde(rename = "route.closed")]
3060 RouteClosed {
3061 module_id: String,
3062 reason: RouteCloseReason,
3063 drained: bool,
3064 abandoned: u32,
3065 },
3066 }
3067
3068 let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
3069 let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
3070 match decoded {
3071 LegacyClientControlPush::RouteClosed {
3072 module_id,
3073 reason,
3074 drained,
3075 abandoned,
3076 } => {
3077 assert_eq!(module_id, "aft-tools");
3078 assert_eq!(reason, RouteCloseReason::Crash);
3079 assert!(!drained);
3080 assert_eq!(abandoned, 0);
3081 }
3082 }
3083 }
3084
3085 #[test]
3086 fn supervisor_routes_is_a_control_plane_request() {
3087 let body = serde_json::json!({
3088 "op": "supervisor.routes",
3089 "module_id": "aft"
3090 });
3091
3092 let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
3093 assert_eq!(serde_json::to_value(request).unwrap(), body);
3094 }
3095
3096 #[test]
3097 fn diagnostic_string_enums_retain_unknown_wire_values() {
3098 let reason: RunningImageUnavailableReason =
3099 serde_json::from_str("\"future_reason\"").unwrap();
3100 let disposition: TerminalDisposition =
3101 serde_json::from_str("\"future_disposition\"").unwrap();
3102
3103 assert_eq!(
3104 reason,
3105 RunningImageUnavailableReason::Unknown("future_reason".to_string())
3106 );
3107 assert_eq!(
3108 disposition,
3109 TerminalDisposition::Unknown("future_disposition".to_string())
3110 );
3111 }
3112
3113 #[test]
3114 fn diagnostic_string_enums_preserve_existing_wire_names() {
3115 let names = [
3116 (RunningImageUnavailableReason::NotRunning, "not_running"),
3117 (
3118 RunningImageUnavailableReason::UnsupportedPlatform,
3119 "unsupported_platform",
3120 ),
3121 (
3122 RunningImageUnavailableReason::RunningExecutableUnreadable,
3123 "running_executable_unreadable",
3124 ),
3125 (
3126 RunningImageUnavailableReason::RunningExecutablePermissionDenied,
3127 "running_executable_permission_denied",
3128 ),
3129 (
3130 RunningImageUnavailableReason::ProcessHidden,
3131 "process_hidden",
3132 ),
3133 (
3134 RunningImageUnavailableReason::SpawnedPathUnreadable,
3135 "spawned_path_unreadable",
3136 ),
3137 (RunningImageUnavailableReason::HashFailed, "hash_failed"),
3138 (
3139 RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
3140 "process_identity_unconfirmed",
3141 ),
3142 ];
3143 for (value, expected) in names {
3144 let wire = serde_json::to_string(&value).unwrap();
3145 assert_eq!(wire, format!("\"{expected}\""));
3146 let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
3147 assert_eq!(decoded, value);
3148 }
3149
3150 for (value, expected) in [
3151 (TerminalDisposition::Stopped, "stopped"),
3152 (TerminalDisposition::Disabled, "disabled"),
3153 (TerminalDisposition::Failed, "failed"),
3154 (TerminalDisposition::Restarting, "restarting"),
3155 (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
3156 ] {
3157 let wire = serde_json::to_string(&value).unwrap();
3158 assert_eq!(wire, format!("\"{expected}\""));
3159 let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
3160 assert_eq!(decoded, value);
3161 }
3162 }
3163
3164 #[test]
3165 fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
3166 let entry = SupervisorEntry::new(
3167 "waiting-module",
3168 "starting",
3169 true,
3170 false,
3171 SupervisorHealthStatus::Unknown,
3172 );
3173 let old_wire = serde_json::to_value(&entry).unwrap();
3174 assert!(old_wire.get("waiting_for_previous_pid").is_none());
3175 let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
3176 assert_eq!(decoded.waiting_for_previous_pid, None);
3177 let entry = entry.with_waiting_for_previous_pid(Some(42));
3178 let wire = serde_json::to_value(&entry).unwrap();
3179 assert_eq!(wire["waiting_for_previous_pid"], 42);
3180 let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
3181 assert_eq!(decoded.waiting_for_previous_pid, Some(42));
3182 }
3183
3184 #[test]
3185 fn diagnostic_string_enums_reject_non_string_bodies() {
3186 assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
3187 assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
3188 }
3189
3190 #[test]
3191 fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
3192 let body = serde_json::json!({
3193 "op": "supervisor.provenance",
3194 "daemon": {
3195 "daemon_build": {},
3196 "daemon_observed": {
3197 "running_image": {
3198 "status": "unavailable",
3199 "reason": "not_running"
3200 }
3201 }
3202 },
3203 "modules": [
3204 {
3205 "module_id": "future",
3206 "module_declared": { "status": "unverifiable" },
3207 "daemon_observed": {
3208 "running_image": {
3209 "status": "unavailable",
3210 "reason": "future_reason"
3211 }
3212 }
3213 },
3214 {
3215 "module_id": "healthy-a",
3216 "module_declared": { "status": "unverifiable" },
3217 "daemon_observed": {
3218 "running_image": {
3219 "status": "match",
3220 "evidence": {
3221 "method": "linux_proc_sha256",
3222 "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
3223 }
3224 }
3225 }
3226 },
3227 {
3228 "module_id": "healthy-b",
3229 "module_declared": { "status": "unverifiable" },
3230 "daemon_observed": {
3231 "running_image": {
3232 "status": "unavailable",
3233 "reason": "unsupported_platform"
3234 }
3235 }
3236 }
3237 ]
3238 });
3239
3240 let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
3241 let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
3242 panic!("decoded wrong response variant");
3243 };
3244 assert_eq!(modules.len(), 3);
3245 assert_eq!(modules[0].module_id, "future");
3246 assert_eq!(
3247 modules[0].daemon_observed.running_image,
3248 RunningImageAgreement::Unavailable {
3249 reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
3250 }
3251 );
3252 assert_eq!(modules[1].module_id, "healthy-a");
3253 assert_eq!(modules[2].module_id, "healthy-b");
3254 }
3255
3256 #[test]
3257 fn tagged_unknown_values_retain_tag_and_body() {
3258 macro_rules! assert_unknown_round_trip {
3259 ($ty:ident, $field:literal, $value:expr) => {
3260 let value = $value;
3261 let wire = serde_json::to_string(&value).unwrap();
3262 let decoded: $ty = serde_json::from_str(&wire).unwrap();
3263 match decoded {
3264 $ty::Unknown { tag, body } => {
3265 assert_eq!(tag, value[$field].as_str().unwrap());
3266 assert_eq!(serde_json::to_value(&body).unwrap(), value);
3267 }
3268 _ => panic!("decoded known variant"),
3269 }
3270 };
3271 }
3272
3273 assert_unknown_round_trip!(
3274 ModuleDeclaredProvenance,
3275 "status",
3276 serde_json::json!({"status": "future", "build": {"version": 7}})
3277 );
3278 assert_unknown_round_trip!(
3279 RunningImageAgreement,
3280 "status",
3281 serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
3282 );
3283 assert_unknown_round_trip!(
3284 RunningImageEvidence,
3285 "method",
3286 serde_json::json!({"method": "future", "digest": "abc"})
3287 );
3288 assert_unknown_round_trip!(
3289 SupervisorRouteConsumer,
3290 "kind",
3291 serde_json::json!({"kind": "future", "module_id": "m"})
3292 );
3293 assert_unknown_round_trip!(
3294 StderrCaptureState,
3295 "state",
3296 serde_json::json!({"state": "future", "reason": "because"})
3297 );
3298 assert_unknown_round_trip!(
3299 StderrTailEntry,
3300 "kind",
3301 serde_json::json!({"kind": "future", "text": "line"})
3302 );
3303 assert_unknown_round_trip!(
3304 ChildResourceUsage,
3305 "status",
3306 serde_json::json!({"status": "future", "memory_bytes": 1})
3307 );
3308 }
3309
3310 #[test]
3311 fn child_resource_usage_round_trips_both_known_states() {
3312 let measured = ChildResourceUsage::Measured(ChildResourceReading {
3313 memory_bytes: 0,
3314 memory_kind: ChildMemoryKind::ResidentSet,
3315 swap_bytes: Some(0),
3316 cpu_user_ms: 0,
3317 cpu_system_ms: 0,
3318 });
3319 let wire = serde_json::to_value(&measured).unwrap();
3320 assert_eq!(
3321 wire,
3322 serde_json::json!({
3323 "status": "measured",
3324 "memory_bytes": 0,
3325 "memory_kind": "resident_set",
3326 "swap_bytes": 0,
3327 "cpu_user_ms": 0,
3328 "cpu_system_ms": 0
3329 })
3330 );
3331 assert_eq!(
3332 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3333 measured
3334 );
3335
3336 let unavailable = ChildResourceUsage::Unavailable {
3337 reason: ChildResourceUnavailableReason::NotRunning,
3338 };
3339 let wire = serde_json::to_value(&unavailable).unwrap();
3340 assert_eq!(
3341 wire,
3342 serde_json::json!({"status": "unavailable", "reason": "not_running"})
3343 );
3344 assert_eq!(
3345 serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
3346 unavailable
3347 );
3348 }
3349
3350 #[test]
3351 fn a_stderr_line_decodes_with_and_without_its_capture_time() {
3352 let stamped: StderrTailEntry = serde_json::from_str(
3356 r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
3357 )
3358 .unwrap();
3359 assert_eq!(
3360 stamped,
3361 StderrTailEntry::Line {
3362 text: "boom".to_string(),
3363 truncated: true,
3364 at_ms: Some(1_789_801_440_685),
3365 }
3366 );
3367 let unstamped: StderrTailEntry =
3368 serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
3369 assert_eq!(
3370 unstamped,
3371 StderrTailEntry::Line {
3372 text: "boom".to_string(),
3373 truncated: false,
3374 at_ms: None,
3375 }
3376 );
3377 assert_eq!(
3380 serde_json::to_string(&unstamped).unwrap(),
3381 r#"{"kind":"line","text":"boom"}"#
3382 );
3383 assert_eq!(
3384 serde_json::to_value(&stamped).unwrap()["at_ms"],
3385 serde_json::json!(1_789_801_440_685u64)
3386 );
3387 }
3388
3389 #[test]
3390 fn tagged_unknown_values_round_trip_the_original_json() {
3391 let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
3392 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3393 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3394 }
3395
3396 #[test]
3397 fn tagged_unknown_values_round_trip_trailing_tag() {
3398 let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
3399 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3400 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3401
3402 let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
3403 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3404 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3405 }
3406
3407 #[test]
3408 fn tagged_unknown_values_round_trip_middle_tag() {
3409 let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
3410 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3411 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3412
3413 let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
3414 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3415 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3416 }
3417
3418 #[test]
3419 fn tagged_unknown_values_round_trip_deep_payload() {
3420 let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
3421 let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
3422 assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);
3423
3424 let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
3425 let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
3426 assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
3427 }
3428
3429 #[test]
3430 fn tagged_unknown_values_reject_non_object_bodies() {
3431 for wire in ["42", r#""future""#, "[]"] {
3432 assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
3433 assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
3434 }
3435 }
3436
3437 #[test]
3438 fn duplicate_discriminators_reject_without_panicking() {
3439 assert_eq!(
3440 serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
3441 .unwrap(),
3442 ModuleDeclaredProvenance::Unverifiable
3443 );
3444 match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
3445 .unwrap()
3446 {
3447 ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
3448 _ => panic!("future discriminator decoded as a known variant"),
3449 }
3450
3451 let wires = [
3452 r#"{"status":"reported","status":"unverifiable"}"#,
3453 r#"{"status":"unverifiable","status":"reported"}"#,
3454 r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
3455 r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
3456 ];
3457
3458 for wire in wires {
3459 let result =
3460 std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
3461 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3462 assert!(
3463 result.unwrap().is_err(),
3464 "duplicate discriminator decoded: {wire}"
3465 );
3466 }
3467
3468 let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
3469 let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
3470 assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
3471 assert!(
3472 result.unwrap().is_err(),
3473 "duplicate discriminator decoded: {wire}"
3474 );
3475 }
3476
3477 #[test]
3478 fn nested_unknown_values_round_trip_without_normalizing_member_order() {
3479 let known_wire =
3480 r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
3481 let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
3482 assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);
3483
3484 for wire in [
3485 r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
3486 r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
3487 ] {
3488 let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
3489 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3490 }
3491
3492 for wire in [
3493 r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
3494 r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
3495 ] {
3496 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3497 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3498 }
3499
3500 let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
3501 let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
3502 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3503
3504 let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
3505 let decoded: StderrTail = serde_json::from_str(wire).unwrap();
3506 assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
3507 }
3508
3509 #[test]
3510 fn tagged_unknown_member_does_not_discard_known_siblings() {
3511 let body = serde_json::json!({
3512 "modules": [{
3513 "module_id": "target",
3514 "routes": [
3515 {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
3516 {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
3517 ]
3518 }]
3519 });
3520 let decoded: ClientControlResponse = serde_json::from_value(
3521 serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
3522 )
3523 .unwrap();
3524 let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
3525 panic!("decoded wrong response variant");
3526 };
3527 assert_eq!(modules[0].routes.len(), 2);
3528 assert_eq!(
3529 modules[0].routes[1].consumer,
3530 SupervisorRouteConsumer::Direct { connection_id: 7 }
3531 );
3532 }
3533}
3534
3535#[cfg(test)]
3536mod launch_nonce_redaction_tests {
3537 use super::*;
3538
3539 const NONCE: &str = "nonce-f00dfeed1234abcd";
3540
3541 fn identity() -> ConsumerIdentity {
3542 ConsumerIdentity {
3543 module_id: "wernicke".to_string(),
3544 launch_nonce: NONCE.to_string(),
3545 }
3546 }
3547
3548 #[test]
3549 fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
3550 let printed = format!("{:?}", identity());
3551 assert!(printed.contains("wernicke"), "{printed}");
3552 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3553 }
3554
3555 #[test]
3556 fn route_open_request_debug_never_prints_the_nonce() {
3557 let request = ClientControlRequest::RouteOpen {
3558 target: subc_protocol::RouteTarget::ToolProvider {
3559 module_id: "broca".to_string(),
3560 },
3561 identity: subc_protocol::BindIdentity::new(
3562 PathBuf::from("/tmp/project"),
3563 "test".to_string(),
3564 "session".to_string(),
3565 ),
3566 consumer_identity: Some(identity()),
3567 consumer_capabilities: None,
3568 role_versions: None,
3569 admission_facts: None,
3570 scope: None,
3571 };
3572 let printed = format!("{request:?}");
3573 assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
3574 }
3575}